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 |
|---|---|---|---|---|---|---|---|---|
bf552e554fdbec5d5fc17a1f49645b9e2d913d16
|
Bump version to 0.6.7
|
ar3cka/Journalist
|
src/SolutionInfo.cs
|
src/SolutionInfo.cs
|
// <auto-generated/>
using System.Reflection;
[assembly: AssemblyProductAttribute("Journalist")]
[assembly: AssemblyVersionAttribute("0.6.7")]
[assembly: AssemblyInformationalVersionAttribute("0.6.7")]
[assembly: AssemblyFileVersionAttribute("0.6.7")]
[assembly: AssemblyCompanyAttribute("Anton Mednonogov")]
namespace System {
internal static class AssemblyVersionInformation {
internal const string Version = "0.6.7";
}
}
|
// <auto-generated/>
using System.Reflection;
[assembly: AssemblyProductAttribute("Journalist")]
[assembly: AssemblyVersionAttribute("0.6.6")]
[assembly: AssemblyInformationalVersionAttribute("0.6.6")]
[assembly: AssemblyFileVersionAttribute("0.6.6")]
[assembly: AssemblyCompanyAttribute("Anton Mednonogov")]
namespace System {
internal static class AssemblyVersionInformation {
internal const string Version = "0.6.6";
}
}
|
apache-2.0
|
C#
|
6231e7841d22205888ca68911f9ecbad69ff676c
|
Add missing override for the AppDelegate.Window property. Fix bug #11914
|
a9upam/monotouch-samples,davidrynn/monotouch-samples,YOTOV-LIMITED/monotouch-samples,haithemaraissia/monotouch-samples,iFreedive/monotouch-samples,a9upam/monotouch-samples,robinlaide/monotouch-samples,sakthivelnagarajan/monotouch-samples,xamarin/monotouch-samples,nelzomal/monotouch-samples,YOTOV-LIMITED/monotouch-samples,peteryule/monotouch-samples,albertoms/monotouch-samples,nelzomal/monotouch-samples,kingyond/monotouch-samples,kingyond/monotouch-samples,labdogg1003/monotouch-samples,iFreedive/monotouch-samples,davidrynn/monotouch-samples,a9upam/monotouch-samples,andypaul/monotouch-samples,sakthivelnagarajan/monotouch-samples,robinlaide/monotouch-samples,markradacz/monotouch-samples,W3SS/monotouch-samples,YOTOV-LIMITED/monotouch-samples,peteryule/monotouch-samples,andypaul/monotouch-samples,nelzomal/monotouch-samples,xamarin/monotouch-samples,hongnguyenpro/monotouch-samples,labdogg1003/monotouch-samples,haithemaraissia/monotouch-samples,nervevau2/monotouch-samples,hongnguyenpro/monotouch-samples,nelzomal/monotouch-samples,albertoms/monotouch-samples,markradacz/monotouch-samples,labdogg1003/monotouch-samples,davidrynn/monotouch-samples,W3SS/monotouch-samples,peteryule/monotouch-samples,nervevau2/monotouch-samples,nervevau2/monotouch-samples,peteryule/monotouch-samples,markradacz/monotouch-samples,davidrynn/monotouch-samples,haithemaraissia/monotouch-samples,hongnguyenpro/monotouch-samples,kingyond/monotouch-samples,robinlaide/monotouch-samples,sakthivelnagarajan/monotouch-samples,nervevau2/monotouch-samples,sakthivelnagarajan/monotouch-samples,hongnguyenpro/monotouch-samples,albertoms/monotouch-samples,YOTOV-LIMITED/monotouch-samples,labdogg1003/monotouch-samples,haithemaraissia/monotouch-samples,W3SS/monotouch-samples,robinlaide/monotouch-samples,andypaul/monotouch-samples,andypaul/monotouch-samples,a9upam/monotouch-samples,xamarin/monotouch-samples,iFreedive/monotouch-samples
|
WorldCities/WorldCities/AppDelegate.cs
|
WorldCities/WorldCities/AppDelegate.cs
|
//
// AppDelegate.cs
//
// Author:
// Mike Krüger <mkrueger@xamarin.com>
//
// Copyright (c) 2011 Xamarin Inc. (http://xamarin.com)
//
// 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.Collections.Generic;
using System.Linq;
using MonoTouch.Foundation;
using MonoTouch.UIKit;
namespace WorldCities
{
// The UIApplicationDelegate for the application. This class is responsible for launching the
// User Interface of the application, as well as listening (and optionally responding) to
// application events from iOS.
[Register ("AppDelegate")]
public partial class AppDelegate : UIApplicationDelegate
{
// class-level declarations
[Export("window")]
public override UIWindow Window {
get;
set;
}
// This method is invoked when the application is about to move from active to inactive state.
// OpenGL applications should use this method to pause.
public override void OnResignActivation (UIApplication application)
{
}
// This method should be used to release shared resources and it should store the application state.
// If your application supports background exection this method is called instead of WillTerminate
// when the user quits.
public override void DidEnterBackground (UIApplication application)
{
}
/// This method is called as part of the transiton from background to active state.
public override void WillEnterForeground (UIApplication application)
{
}
/// This method is called when the application is about to terminate. Save data, if needed.
public override void WillTerminate (UIApplication application)
{
}
}
}
|
//
// AppDelegate.cs
//
// Author:
// Mike Krüger <mkrueger@xamarin.com>
//
// Copyright (c) 2011 Xamarin Inc. (http://xamarin.com)
//
// 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.Collections.Generic;
using System.Linq;
using MonoTouch.Foundation;
using MonoTouch.UIKit;
namespace WorldCities
{
// The UIApplicationDelegate for the application. This class is responsible for launching the
// User Interface of the application, as well as listening (and optionally responding) to
// application events from iOS.
[Register ("AppDelegate")]
public partial class AppDelegate : UIApplicationDelegate
{
// class-level declarations
[Export("window")]
public UIWindow Window {
get;
set;
}
// This method is invoked when the application is about to move from active to inactive state.
// OpenGL applications should use this method to pause.
public override void OnResignActivation (UIApplication application)
{
}
// This method should be used to release shared resources and it should store the application state.
// If your application supports background exection this method is called instead of WillTerminate
// when the user quits.
public override void DidEnterBackground (UIApplication application)
{
}
/// This method is called as part of the transiton from background to active state.
public override void WillEnterForeground (UIApplication application)
{
}
/// This method is called when the application is about to terminate. Save data, if needed.
public override void WillTerminate (UIApplication application)
{
}
}
}
|
mit
|
C#
|
721cc7c02b64c285223390ca038a1f0d6f0120eb
|
Disable lobby music for headless
|
fomalsd/unitystation,fomalsd/unitystation,Necromunger/unitystation,krille90/unitystation,fomalsd/unitystation,Necromunger/unitystation,krille90/unitystation,Necromunger/unitystation,fomalsd/unitystation,Necromunger/unitystation,fomalsd/unitystation,krille90/unitystation,Necromunger/unitystation,fomalsd/unitystation,Necromunger/unitystation,fomalsd/unitystation
|
UnityProject/Assets/Scripts/UI/Lobby/SongTracker.cs
|
UnityProject/Assets/Scripts/UI/Lobby/SongTracker.cs
|
using Mirror;
using UnityEngine;
using UnityEngine.UI;
/// <summary>
/// Class used to display the information of the song being played in the lobby screen.
/// </summary>
public class SongTracker : MonoBehaviour
{
[SerializeField] private Text trackName;
[SerializeField] private Text artist;
private float timeBetweenSongs = 2f;
private float currentWaitTime = 0f;
/// <summary>
/// If true the SongTracker will continue to play tracks one after
/// another in a random order
/// </summary>
public bool PlayingRandomPlayList { get; private set; }
void Awake()
{
ToggleUI(false);
}
void Update()
{
if (!PlayingRandomPlayList || CustomNetworkManager.isHeadless) return;
if (!SoundManager.isLobbyMusicPlaying())
{
currentWaitTime += Time.deltaTime;
if (currentWaitTime >= timeBetweenSongs)
{
currentWaitTime = 0f;
PlayRandomTrack();
}
}
}
public void StartPlayingRandomPlaylist()
{
PlayingRandomPlayList = true;
PlayRandomTrack();
ToggleUI(true);
}
public void Stop()
{
PlayingRandomPlayList = false;
ToggleUI(false);
SoundManager.StopMusic();
}
void ToggleUI(bool isActive)
{
trackName.gameObject.SetActive(isActive);
artist.gameObject.SetActive(isActive);
}
void PlayRandomTrack()
{
var songInfo = SoundManager.PlayRandomTrack();
trackName.text = songInfo[0];
// If the name of the artist is included, add it as well
if (songInfo.Length == 2)
{
artist.text = songInfo[1];
}
else
{
artist.text = "";
}
}
}
|
using UnityEngine;
using UnityEngine.UI;
/// <summary>
/// Class used to display the information of the song being played in the lobby screen.
/// </summary>
public class SongTracker : MonoBehaviour
{
[SerializeField] private Text trackName;
[SerializeField] private Text artist;
private float timeBetweenSongs = 2f;
private float currentWaitTime = 0f;
/// <summary>
/// If true the SongTracker will continue to play tracks one after
/// another in a random order
/// </summary>
public bool PlayingRandomPlayList { get; private set; }
void Awake()
{
ToggleUI(false);
}
void Update()
{
if (!PlayingRandomPlayList) return;
if (!SoundManager.isLobbyMusicPlaying())
{
currentWaitTime += Time.deltaTime;
if (currentWaitTime >= timeBetweenSongs)
{
currentWaitTime = 0f;
PlayRandomTrack();
}
}
}
public void StartPlayingRandomPlaylist()
{
PlayingRandomPlayList = true;
PlayRandomTrack();
ToggleUI(true);
}
public void Stop()
{
PlayingRandomPlayList = false;
ToggleUI(false);
SoundManager.StopMusic();
}
void ToggleUI(bool isActive)
{
trackName.gameObject.SetActive(isActive);
artist.gameObject.SetActive(isActive);
}
void PlayRandomTrack()
{
var songInfo = SoundManager.PlayRandomTrack();
trackName.text = songInfo[0];
// If the name of the artist is included, add it as well
if (songInfo.Length == 2)
{
artist.text = songInfo[1];
}
else
{
artist.text = "";
}
}
}
|
agpl-3.0
|
C#
|
994826b575b8ffbd2095798a92950f15ac34c5f1
|
Add XML documentation for `HostConfig`
|
ppy/osu-framework,smoogipooo/osu-framework,ppy/osu-framework,peppy/osu-framework,ppy/osu-framework,peppy/osu-framework,smoogipooo/osu-framework,peppy/osu-framework
|
osu.Framework/HostConfig.cs
|
osu.Framework/HostConfig.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
{
/// <summary>
/// Various configuration properties for a <see cref="Host"/>.
/// </summary>
public struct HostConfig
{
/// <summary>
/// Name of the game or application.
/// </summary>
public string GameName { get; set; }
/// <summary>
/// Whether to bind the IPC port.
/// </summary>
public bool BindIPC { get; set; }
/// <summary>
/// Whether this is a portable installation.
/// </summary>
public bool PortableInstallation { get; set; }
/// <summary>
/// Whether to bypass the compositor.
/// </summary>
/// <remarks>
/// On Linux, the compositor re-buffers the application to apply various window effects,
/// increasing latency in the process. Thus it is a good idea for games to bypass it,
/// though normal applications would generally benefit from letting the window effects untouched. <br/>
/// If the SDL_VIDEO_X11_NET_WM_BYPASS_COMPOSITOR environment variable is set, this property will have no effect.
/// </remarks>
public bool BypassCompositor { get; set; }
public static HostConfig GameConfig(string gameName, bool bindIPC = false, bool portableInstallation = false)
{
return new HostConfig
{
GameName = gameName,
BindIPC = bindIPC,
PortableInstallation = portableInstallation,
BypassCompositor = true,
};
}
public static HostConfig ApplicationConfig(string gameName, bool bindIPC = false, bool portableInstallation = false)
{
return new HostConfig
{
GameName = gameName,
BindIPC = bindIPC,
PortableInstallation = portableInstallation,
BypassCompositor = false,
};
}
}
}
|
// 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
{
public struct HostConfig
{
public string GameName { get; set; }
public bool BindIPC { get; set; }
public bool PortableInstallation { get; set; }
public bool BypassCompositor { get; set; }
public static HostConfig GameConfig(string gameName, bool bindIPC = false, bool portableInstallation = false)
{
return new HostConfig
{
GameName = gameName,
BindIPC = bindIPC,
PortableInstallation = portableInstallation,
BypassCompositor = true,
};
}
public static HostConfig ApplicationConfig(string gameName, bool bindIPC = false, bool portableInstallation = false)
{
return new HostConfig
{
GameName = gameName,
BindIPC = bindIPC,
PortableInstallation = portableInstallation,
BypassCompositor = false,
};
}
}
}
|
mit
|
C#
|
2d6f6b5a12cac06a0479274ff726460e5399c91a
|
Clean up using statements
|
frackleton/ApplicationInsights-SDK-Labs,Microsoft/ApplicationInsights-SDK-Labs
|
WCF/Shared.Tests/Integration/OperationContextExtensionsTests.cs
|
WCF/Shared.Tests/Integration/OperationContextExtensionsTests.cs
|
using Microsoft.VisualStudio.TestTools.UnitTesting;
using System;
using System.ServiceModel;
namespace Microsoft.ApplicationInsights.Wcf.Tests.Integration
{
[TestClass]
public class OperationContextExtensionsTests
{
[TestMethod]
public void WhenOperationContextIsNullReturnsNull()
{
var result = OperationContextExtensions.GetRequestTelemetry(null);
Assert.IsNull(result);
}
[TestMethod]
[TestCategory("Integration")]
public void WhenOperationContextIsClientContextReturnsNull()
{
using ( var host = new HostingContext<ContextCheckService, IContextCheckService>() )
{
host.Open();
var client = host.GetChannel();
using ( var scope = new OperationContextScope((IContextChannel)client) )
{
Assert.IsNull(OperationContext.Current.GetRequestTelemetry());
}
}
}
[TestMethod]
[TestCategory("Integration")]
public void WhenOperationContextIsServiceContextReturnsRequest()
{
using ( var host = new HostingContext<ContextCheckService, IContextCheckService>() )
{
host.Open();
var client = host.GetChannel();
using ( var scope = new OperationContextScope((IContextChannel)client) )
{
Assert.IsTrue(client.CanGetRequestTelemetry());
}
}
}
[ServiceContract]
public interface IContextCheckService
{
[OperationContract]
bool CanGetRequestTelemetry();
}
[ServiceTelemetry]
class ContextCheckService : IContextCheckService
{
public bool CanGetRequestTelemetry()
{
return OperationContext.Current.GetRequestTelemetry() != null;
}
}
}
}
|
using Microsoft.VisualStudio.TestTools.UnitTesting;
using System;
using System.Collections.Generic;
using System.ServiceModel;
using System.Text;
namespace Microsoft.ApplicationInsights.Wcf.Tests.Integration
{
[TestClass]
public class OperationContextExtensionsTests
{
[TestMethod]
public void WhenOperationContextIsNullReturnsNull()
{
var result = OperationContextExtensions.GetRequestTelemetry(null);
Assert.IsNull(result);
}
[TestMethod]
[TestCategory("Integration")]
public void WhenOperationContextIsClientContextReturnsNull()
{
using ( var host = new HostingContext<ContextCheckService, IContextCheckService>() )
{
host.Open();
var client = host.GetChannel();
using ( var scope = new OperationContextScope((IContextChannel)client) )
{
Assert.IsNull(OperationContext.Current.GetRequestTelemetry());
}
}
}
[TestMethod]
[TestCategory("Integration")]
public void WhenOperationContextIsServiceContextReturnsRequest()
{
using ( var host = new HostingContext<ContextCheckService, IContextCheckService>() )
{
host.Open();
var client = host.GetChannel();
using ( var scope = new OperationContextScope((IContextChannel)client) )
{
Assert.IsTrue(client.CanGetRequestTelemetry());
}
}
}
[ServiceContract]
public interface IContextCheckService
{
[OperationContract]
bool CanGetRequestTelemetry();
}
[ServiceTelemetry]
class ContextCheckService : IContextCheckService
{
public bool CanGetRequestTelemetry()
{
return OperationContext.Current.GetRequestTelemetry() != null;
}
}
}
}
|
mit
|
C#
|
f439237bd79c6a49b4c216eb4cb6394e722c7ed8
|
Set a more sane default for TimingControlPoint's BeatLength
|
peppy/osu-new,UselessToucan/osu,Frontear/osuKyzer,naoey/osu,UselessToucan/osu,DrabWeb/osu,smoogipoo/osu,peppy/osu,DrabWeb/osu,ppy/osu,ppy/osu,smoogipoo/osu,EVAST9919/osu,ZLima12/osu,Drezi126/osu,ppy/osu,2yangk23/osu,2yangk23/osu,naoey/osu,NeoAdonis/osu,peppy/osu,NeoAdonis/osu,DrabWeb/osu,peppy/osu,Damnae/osu,smoogipooo/osu,osu-RP/osu-RP,johnneijzen/osu,ZLima12/osu,EVAST9919/osu,Nabile-Rahmani/osu,johnneijzen/osu,UselessToucan/osu,NeoAdonis/osu,naoey/osu,smoogipoo/osu
|
osu.Game/Beatmaps/ControlPoints/TimingControlPoint.cs
|
osu.Game/Beatmaps/ControlPoints/TimingControlPoint.cs
|
// Copyright (c) 2007-2017 ppy Pty Ltd <contact@ppy.sh>.
// Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu/master/LICENCE
using osu.Game.Beatmaps.Timing;
namespace osu.Game.Beatmaps.ControlPoints
{
public class TimingControlPoint : ControlPoint
{
/// <summary>
/// The time signature at this control point.
/// </summary>
public TimeSignatures TimeSignature = TimeSignatures.SimpleQuadruple;
/// <summary>
/// The beat length at this control point.
/// </summary>
public double BeatLength = 1000;
}
}
|
// Copyright (c) 2007-2017 ppy Pty Ltd <contact@ppy.sh>.
// Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu/master/LICENCE
using osu.Game.Beatmaps.Timing;
namespace osu.Game.Beatmaps.ControlPoints
{
public class TimingControlPoint : ControlPoint
{
/// <summary>
/// The time signature at this control point.
/// </summary>
public TimeSignatures TimeSignature = TimeSignatures.SimpleQuadruple;
/// <summary>
/// The beat length at this control point.
/// </summary>
public double BeatLength = 500;
}
}
|
mit
|
C#
|
5ab47f39b160cdd8670ac734426229482821138e
|
Update Program.cs (#32010)
|
aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore
|
src/Identity/samples/IdentitySample.Mvc/Program.cs
|
src/Identity/samples/IdentitySample.Mvc/Program.cs
|
using System.IO;
using Microsoft.AspNetCore.Hosting;
namespace IdentitySample
{
public static class Program
{
public static void Main(string[] args)
{
var host = CreateHostBuilder(args).Build();
host.Run();
}
public static IWebHostBuilder CreateHostBuilder(string[] args) =>
new WebHostBuilder()
.UseKestrel()
.UseContentRoot(Directory.GetCurrentDirectory())
.UseIISIntegration()
.UseStartup<Startup>();
}
}
|
using System.IO;
using Microsoft.AspNetCore.Hosting;
namespace IdentitySample
{
public static class Program
{
public static void Main(string[] args)
{
var host = new WebHostBuilder()
.UseKestrel()
.UseContentRoot(Directory.GetCurrentDirectory())
.UseIISIntegration()
.UseStartup<Startup>()
.Build();
host.Run();
}
}
}
|
apache-2.0
|
C#
|
67b4bb15767bf32bafd303c06505b4bb135a816a
|
add log message when homepage is disabled
|
MienDev/IdentityServer4,MienDev/IdentityServer4,IdentityServer/IdentityServer4,MienDev/IdentityServer4,IdentityServer/IdentityServer4,IdentityServer/IdentityServer4,IdentityServer/IdentityServer4,MienDev/IdentityServer4
|
host/Quickstart/Home/HomeController.cs
|
host/Quickstart/Home/HomeController.cs
|
// Copyright (c) Brock Allen & Dominick Baier. All rights reserved.
// Licensed under the Apache License, Version 2.0. See LICENSE in the project root for license information.
using IdentityServer4.Services;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using System.Threading.Tasks;
namespace IdentityServer4.Quickstart.UI
{
[SecurityHeaders]
[AllowAnonymous]
public class HomeController : Controller
{
private readonly IIdentityServerInteractionService _interaction;
private readonly IHostingEnvironment _environment;
private readonly ILogger _logger;
public HomeController(IIdentityServerInteractionService interaction, IHostingEnvironment environment, ILogger<HomeController> logger)
{
_interaction = interaction;
_environment = environment;
_logger = logger;
}
public IActionResult Index()
{
if (_environment.IsDevelopment())
{
// only show in development
return View();
}
_logger.LogInformation("Homepage is disabled in production. Returning 404.");
return NotFound();
}
/// <summary>
/// Shows the error page
/// </summary>
public async Task<IActionResult> Error(string errorId)
{
var vm = new ErrorViewModel();
// retrieve error details from identityserver
var message = await _interaction.GetErrorContextAsync(errorId);
if (message != null)
{
vm.Error = message;
if (!_environment.IsDevelopment())
{
// only show in development
message.ErrorDescription = null;
}
}
return View("Error", vm);
}
}
}
|
// Copyright (c) Brock Allen & Dominick Baier. All rights reserved.
// Licensed under the Apache License, Version 2.0. See LICENSE in the project root for license information.
using IdentityServer4.Services;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc;
using System.Threading.Tasks;
namespace IdentityServer4.Quickstart.UI
{
[SecurityHeaders]
[AllowAnonymous]
public class HomeController : Controller
{
private readonly IIdentityServerInteractionService _interaction;
private readonly IHostingEnvironment _environment;
public HomeController(IIdentityServerInteractionService interaction, IHostingEnvironment environment)
{
_interaction = interaction;
_environment = environment;
}
public IActionResult Index()
{
if (_environment.IsDevelopment())
{
// only show in development
return View();
}
return NotFound();
}
/// <summary>
/// Shows the error page
/// </summary>
public async Task<IActionResult> Error(string errorId)
{
var vm = new ErrorViewModel();
// retrieve error details from identityserver
var message = await _interaction.GetErrorContextAsync(errorId);
if (message != null)
{
vm.Error = message;
if (!_environment.IsDevelopment())
{
// only show in development
message.ErrorDescription = null;
}
}
return View("Error", vm);
}
}
}
|
apache-2.0
|
C#
|
99f04e682aaa13e7a7b95a238b51671369161344
|
comment out Asserts about test_file
|
castleproject/Castle.Transactions,castleproject/Castle.Transactions,castleproject/Castle.Transactions
|
src/Castle.Transactions.IO.Tests/AsDependentTransaction.cs
|
src/Castle.Transactions.IO.Tests/AsDependentTransaction.cs
|
namespace Castle.Transactions.IO.Tests
{
using System.IO;
using Castle.IO.Extensions;
using Castle.Transactions.Activities;
using NUnit.Framework;
[TestFixture]
public class AsDependentTransaction : TxFTestFixtureBase
{
private string test_file;
private ITransactionManager subject;
[SetUp]
public void given_manager()
{
test_file = ".".Combine("test.txt");
subject = new TransactionManager(new CallContextActivityManager());
}
[Test]
public void Then_DependentTransaction_CanBeCommitted()
{
// verify process state
Assert.That(subject.CurrentTransaction.HasValue, Is.False);
Assert.That(System.Transactions.Transaction.Current, Is.Null);
// actual test code
using (var stdTx = subject.CreateTransaction(new DefaultTransactionOptions()).Value.Transaction)
{
Assert.That(subject.CurrentTransaction.HasValue, Is.True);
Assert.That(subject.CurrentTransaction.Value, Is.EqualTo(stdTx));
using (var innerTransaction = subject.CreateFileTransaction().Value)
{
Assert.That(subject.CurrentTransaction.Value, Is.EqualTo(innerTransaction),
"Now that we have created a dependent transaction, it's the current tx in the resource manager.");
// this is supposed to be registered in an IoC container
//var fa = (IFileAdapter)innerTransaction;
//fa.WriteAllText(test_file, "Hello world");
innerTransaction.Complete();
}
}
//Assert.That(File.Exists(test_file));
//Assert.That(File.ReadAllText(test_file), Is.EqualTo("Hello world"));
}
[Test]
public void CompletedState()
{
using (IFileTransaction tx = subject.CreateFileTransaction().Value)
{
Assert.That(tx.State, Is.EqualTo(TransactionState.Active));
tx.Complete();
Assert.That(tx.State, Is.EqualTo(TransactionState.CommittedOrCompleted));
}
}
[TearDown]
public void tear_down()
{
subject.Dispose();
}
}
}
|
namespace Castle.Transactions.IO.Tests
{
using System.IO;
using Castle.IO.Extensions;
using Castle.Transactions.Activities;
using NUnit.Framework;
[TestFixture]
public class AsDependentTransaction : TxFTestFixtureBase
{
private string test_file;
private ITransactionManager subject;
[SetUp]
public void given_manager()
{
test_file = ".".Combine("test.txt");
subject = new TransactionManager(new CallContextActivityManager());
}
[Test]
public void Then_DependentTransaction_CanBeCommitted()
{
// verify process state
Assert.That(subject.CurrentTransaction.HasValue, Is.False);
Assert.That(System.Transactions.Transaction.Current, Is.Null);
// actual test code
using (var stdTx = subject.CreateTransaction(new DefaultTransactionOptions()).Value.Transaction)
{
Assert.That(subject.CurrentTransaction.HasValue, Is.True);
Assert.That(subject.CurrentTransaction.Value, Is.EqualTo(stdTx));
using (var innerTransaction = subject.CreateFileTransaction().Value)
{
Assert.That(subject.CurrentTransaction.Value, Is.EqualTo(innerTransaction),
"Now that we have created a dependent transaction, it's the current tx in the resource manager.");
// this is supposed to be registered in an IoC container
//var fa = (IFileAdapter)innerTransaction;
//fa.WriteAllText(test_file, "Hello world");
innerTransaction.Complete();
}
}
Assert.That(File.Exists(test_file));
Assert.That(File.ReadAllText(test_file), Is.EqualTo("Hello world"));
}
[Test]
public void CompletedState()
{
using (IFileTransaction tx = subject.CreateFileTransaction().Value)
{
Assert.That(tx.State, Is.EqualTo(TransactionState.Active));
tx.Complete();
Assert.That(tx.State, Is.EqualTo(TransactionState.CommittedOrCompleted));
}
}
[TearDown]
public void tear_down()
{
subject.Dispose();
}
}
}
|
apache-2.0
|
C#
|
ad03a37ae3c7df4b7b24653e28d5537f2af07340
|
Update program version and copyright info
|
Psimage/KWADTool
|
KWADTool/Properties/AssemblyInfo.cs
|
KWADTool/Properties/AssemblyInfo.cs
|
using System.Reflection;
using System.Runtime.InteropServices;
using CommandLine;
// 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("KWADTool")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("KWADTool")]
[assembly: AssemblyCopyright("Copyright (C) 2017 Yaroslav Bugaev\n")]
[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("d2f49d46-d494-4844-a8f4-dc9d55ff35b9")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
[assembly: AssemblyInformationalVersion("1.2.0")]
// from CommandLineParser.Text
[assembly: AssemblyLicense(
"This is free software. You may redistribute copies of it under the terms of",
"the MIT License <http://opensource.org/licenses/MIT>.\n")]
[assembly: AssemblyUsage(
"Usage: KWADTool -i <kwadFile> [-e (anims|textures|blobs|all)] [-o <outputDir>]")]
|
using System.Reflection;
using System.Runtime.InteropServices;
using CommandLine;
// 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("KWADTool")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("KWADTool")]
[assembly: AssemblyCopyright("Copyright (C) 2016 Yaroslav Bugaev\n")]
[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("d2f49d46-d494-4844-a8f4-dc9d55ff35b9")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
[assembly: AssemblyInformationalVersion("1.1.0")]
// from CommandLineParser.Text
[assembly: AssemblyLicense(
"This is free software. You may redistribute copies of it under the terms of",
"the MIT License <http://opensource.org/licenses/MIT>.\n")]
[assembly: AssemblyUsage(
"Usage: KWADTool -i <kwadFile> [-e (anims|textures|blobs|all)] [-o <outputDir>]")]
|
mit
|
C#
|
332910f7ec638d551334e0a4a7a5364688458f29
|
use cute api
|
kingyond/monotouch-samples,nervevau2/monotouch-samples,W3SS/monotouch-samples,sakthivelnagarajan/monotouch-samples,robinlaide/monotouch-samples,sakthivelnagarajan/monotouch-samples,YOTOV-LIMITED/monotouch-samples,kingyond/monotouch-samples,sakthivelnagarajan/monotouch-samples,andypaul/monotouch-samples,haithemaraissia/monotouch-samples,peteryule/monotouch-samples,peteryule/monotouch-samples,albertoms/monotouch-samples,xamarin/monotouch-samples,iFreedive/monotouch-samples,labdogg1003/monotouch-samples,nelzomal/monotouch-samples,andypaul/monotouch-samples,YOTOV-LIMITED/monotouch-samples,hongnguyenpro/monotouch-samples,iFreedive/monotouch-samples,a9upam/monotouch-samples,davidrynn/monotouch-samples,labdogg1003/monotouch-samples,xamarin/monotouch-samples,markradacz/monotouch-samples,hongnguyenpro/monotouch-samples,kingyond/monotouch-samples,W3SS/monotouch-samples,labdogg1003/monotouch-samples,haithemaraissia/monotouch-samples,albertoms/monotouch-samples,sakthivelnagarajan/monotouch-samples,peteryule/monotouch-samples,nelzomal/monotouch-samples,labdogg1003/monotouch-samples,nervevau2/monotouch-samples,davidrynn/monotouch-samples,hongnguyenpro/monotouch-samples,davidrynn/monotouch-samples,robinlaide/monotouch-samples,markradacz/monotouch-samples,iFreedive/monotouch-samples,hongnguyenpro/monotouch-samples,a9upam/monotouch-samples,albertoms/monotouch-samples,nervevau2/monotouch-samples,YOTOV-LIMITED/monotouch-samples,YOTOV-LIMITED/monotouch-samples,W3SS/monotouch-samples,nelzomal/monotouch-samples,nervevau2/monotouch-samples,a9upam/monotouch-samples,a9upam/monotouch-samples,davidrynn/monotouch-samples,robinlaide/monotouch-samples,xamarin/monotouch-samples,peteryule/monotouch-samples,robinlaide/monotouch-samples,andypaul/monotouch-samples,haithemaraissia/monotouch-samples,andypaul/monotouch-samples,nelzomal/monotouch-samples,haithemaraissia/monotouch-samples,markradacz/monotouch-samples
|
ios8/Lister/ListerKit/ListDocument.cs
|
ios8/Lister/ListerKit/ListDocument.cs
|
using System;
using UIKit;
using Foundation;
using Common;
namespace ListerKit
{
public class ListDocument : UIDocument
{
public event EventHandler DocumentDeleted;
public List List { get; set; }
public ListDocument (NSUrl url)
: base(url)
{
List = new List ();
}
public override bool LoadFromContents (NSObject contents, string typeName, out NSError outError)
{
outError = null;
List deserializedList = (List)NSKeyedUnarchiver.UnarchiveObject ((NSData)contents);
if (deserializedList!= null) {
List = deserializedList;
return true;
}
outError = new NSError (NSError.CocoaErrorDomain, (int)NSCocoaError.FileReadCorruptFile, new NSDictionary (
NSError.LocalizedDescriptionKey, "Could not read file",
NSError.LocalizedFailureReasonErrorKey, "File was in an invalid format"
));
return false;
}
public override NSObject ContentsForType (string typeName, out NSError outError)
{
outError = null;
NSData serializedList = NSKeyedArchiver.ArchivedDataWithRootObject (List);
if (serializedList != null)
return serializedList;
outError = new NSError (NSError.CocoaErrorDomain, (int)NSCocoaError.FileReadUnknown, new NSDictionary (
NSError.LocalizedDescriptionKey, "Could not save file",
NSError.LocalizedFailureReasonErrorKey, "An unexpected error occured"
));
return null;
}
public override void AccommodatePresentedItemDeletion (Action<NSError> completionHandler)
{
var handler = DocumentDeleted;
if (handler != null)
handler (this, EventArgs.Empty);
}
}
}
|
using System;
using UIKit;
using Foundation;
using Common;
namespace ListerKit
{
public class ListDocument : UIDocument
{
public event EventHandler DocumentDeleted;
public List List { get; set; }
public ListDocument (NSUrl url)
: base(url)
{
List = new List ();
}
public override bool LoadFromContents (NSObject contents, string typeName, out NSError outError)
{
outError = null;
List deserializedList = (List)NSKeyedUnarchiver.UnarchiveObject ((NSData)contents);
if (deserializedList!= null) {
List = deserializedList;
return true;
}
outError = new NSError (NSError.CocoaErrorDomain, (int)NSCocoaError.FileReadCorruptFile, NSDictionary.FromObjectsAndKeys (
new NSObject[] {
(NSString)"Could not read file",
(NSString)"File was in an invalid format"
},
new NSObject[] {
NSError.LocalizedDescriptionKey,
NSError.LocalizedFailureReasonErrorKey
}
));
return false;
}
public override NSObject ContentsForType (string typeName, out NSError outError)
{
outError = null;
NSData serializedList = NSKeyedArchiver.ArchivedDataWithRootObject (List);
if (serializedList != null)
return serializedList;
outError = new NSError (NSError.CocoaErrorDomain, (int)NSCocoaError.FileReadUnknown, NSDictionary.FromObjectsAndKeys (
new NSObject[] {
(NSString)"Could not save file",
(NSString)"An unexpected error occured"
},
new NSObject[] {
NSError.LocalizedDescriptionKey,
NSError.LocalizedFailureReasonErrorKey
}
));
return null;
}
public override void AccommodatePresentedItemDeletion (Action<NSError> completionHandler)
{
var handler = DocumentDeleted;
if (handler != null)
handler (this, EventArgs.Empty);
}
}
}
|
mit
|
C#
|
17f6976099d7d3c5bd98caaa1348ae2557129e86
|
Add Help
|
jamesweb-ms/CachelessDnsClient
|
CDC/Program.cs
|
CDC/Program.cs
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using CachelessDnsClient;
namespace CDC
{
class Program
{
static Client client = new Client();
static void Main(string[] args)
{
if (args.Length < 0 || args.Length > 2)
{
Help();
return;
}
if (args.Length == 1)
{
QueryHost(args[0]);
return;
}
switch (args[0].ToLowerInvariant())
{
case "/exists":
QueryHost(args[1]);
break;
case "/replica":
QueryHostReplica(args[1]);
break;
default:
Help();
break;
}
}
static void QueryHostReplica(string name)
{
string result = "not replicated";
if (client.HostEntryReplicated(name).Result)
{
result = "replicated";
}
Console.WriteLine("Hostname '{0}' {1}", name, result);
}
static void QueryHost(string name)
{
string result = "not found";
if (client.HostEntryExists(name).Result)
{
result = "found";
}
Console.WriteLine("Hostname '{0}' {1}", name, result);
}
static void Help()
{
Console.WriteLine("Usage:");
Console.WriteLine(" cdc host # Looks up host name");
Console.WriteLine(" cdc /exists host # Looks up host name");
Console.WriteLine(" cdc /replica host # Looks up host name on all SOA Name servers");
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using CachelessDnsClient;
namespace CDC
{
class Program
{
static Client client = new Client();
static void Main(string[] args)
{
if (args.Length < 0 || args.Length > 2)
{
Help();
return;
}
if (args.Length == 1)
{
QueryHost(args[0]);
return;
}
switch (args[0].ToLowerInvariant())
{
case "/exists":
QueryHost(args[1]);
break;
case "/replica":
QueryHostReplica(args[1]);
break;
default:
Help();
break;
}
}
static void QueryHostReplica(string name)
{
string result = "not replicated";
if (client.HostEntryReplicated(name).Result)
{
result = "replicated";
}
Console.WriteLine("Hostname '{0}' {1}", name, result);
}
static void QueryHost(string name)
{
string result = "not found";
if (client.HostEntryExists(name).Result)
{
result = "found";
}
Console.WriteLine("Hostname '{0}' {1}", name, result);
}
static void Help()
{
}
}
}
|
apache-2.0
|
C#
|
bf3b5cca1c6b016ec2d6bb3a8c32e279db68d94b
|
Fix bug in test - SwapRedBlue swaps the whole pixel, not the bytes, so count == w*h
|
mono/SkiaSharp,mono/SkiaSharp,mono/SkiaSharp,mono/SkiaSharp,mono/SkiaSharp,mono/SkiaSharp,mono/SkiaSharp
|
tests/Tests/SKPixmapTest.cs
|
tests/Tests/SKPixmapTest.cs
|
using System;
using System.Runtime.InteropServices;
using Xunit;
namespace SkiaSharp.Tests
{
public class SKPixmapTest : SKTest
{
[SkippableFact]
public void ReadPixelSucceeds()
{
var info = new SKImageInfo(10, 10);
var ptr1 = Marshal.AllocCoTaskMem(info.BytesSize);
var pix1 = new SKPixmap(info, ptr1);
var ptr2 = Marshal.AllocCoTaskMem(info.BytesSize);
var result = pix1.ReadPixels(info, ptr2, info.RowBytes);
Assert.True(result);
}
[SkippableFact]
public void WithMethodsDoNotModifySource()
{
var info = new SKImageInfo(100, 30, SKColorType.Rgb565, SKAlphaType.Unpremul);
var pixmap = new SKPixmap(info, (IntPtr)123);
Assert.Equal(SKColorType.Rgb565, pixmap.ColorType);
Assert.Equal((IntPtr)123, pixmap.GetPixels());
var copy = pixmap.WithColorType(SKColorType.Index8);
Assert.Equal(SKColorType.Rgb565, pixmap.ColorType);
Assert.Equal((IntPtr)123, pixmap.GetPixels());
Assert.Equal(SKColorType.Index8, copy.ColorType);
Assert.Equal((IntPtr)123, copy.GetPixels());
}
[SkippableFact]
public void ReadPixelCopiesData()
{
var info = new SKImageInfo(10, 10);
using (var bmp1 = new SKBitmap(info))
using (var pix1 = bmp1.PeekPixels())
using (var bmp2 = new SKBitmap(info))
using (var pix2 = bmp2.PeekPixels())
{
bmp1.Erase(SKColors.Blue);
bmp1.Erase(SKColors.Green);
Assert.NotEqual(Marshal.ReadInt64(pix1.GetPixels()), Marshal.ReadInt64(pix2.GetPixels()));
var result = pix1.ReadPixels(pix2);
Assert.True(result);
Assert.Equal(Marshal.ReadInt64(pix1.GetPixels()), Marshal.ReadInt64(pix2.GetPixels()));
}
}
[SkippableFact]
public void SwizzleSwapsRedAndBlue()
{
var info = new SKImageInfo(10, 10);
using (var bmp = new SKBitmap(info))
{
bmp.Erase(SKColors.Red);
Assert.Equal(SKColors.Red, bmp.Pixels[0]);
SKSwizzle.SwapRedBlue(bmp.GetPixels(out var length), info.Width * info.Height);
Assert.Equal(SKColors.Blue, bmp.Pixels[0]);
}
}
}
}
|
using System;
using System.Runtime.InteropServices;
using Xunit;
namespace SkiaSharp.Tests
{
public class SKPixmapTest : SKTest
{
[SkippableFact]
public void ReadPixelSucceeds()
{
var info = new SKImageInfo(10, 10);
var ptr1 = Marshal.AllocCoTaskMem(info.BytesSize);
var pix1 = new SKPixmap(info, ptr1);
var ptr2 = Marshal.AllocCoTaskMem(info.BytesSize);
var result = pix1.ReadPixels(info, ptr2, info.RowBytes);
Assert.True(result);
}
[SkippableFact]
public void WithMethodsDoNotModifySource()
{
var info = new SKImageInfo(100, 30, SKColorType.Rgb565, SKAlphaType.Unpremul);
var pixmap = new SKPixmap(info, (IntPtr)123);
Assert.Equal(SKColorType.Rgb565, pixmap.ColorType);
Assert.Equal((IntPtr)123, pixmap.GetPixels());
var copy = pixmap.WithColorType(SKColorType.Index8);
Assert.Equal(SKColorType.Rgb565, pixmap.ColorType);
Assert.Equal((IntPtr)123, pixmap.GetPixels());
Assert.Equal(SKColorType.Index8, copy.ColorType);
Assert.Equal((IntPtr)123, copy.GetPixels());
}
[SkippableFact]
public void ReadPixelCopiesData()
{
var info = new SKImageInfo(10, 10);
using (var bmp1 = new SKBitmap(info))
using (var pix1 = bmp1.PeekPixels())
using (var bmp2 = new SKBitmap(info))
using (var pix2 = bmp2.PeekPixels())
{
bmp1.Erase(SKColors.Blue);
bmp1.Erase(SKColors.Green);
Assert.NotEqual(Marshal.ReadInt64(pix1.GetPixels()), Marshal.ReadInt64(pix2.GetPixels()));
var result = pix1.ReadPixels(pix2);
Assert.True(result);
Assert.Equal(Marshal.ReadInt64(pix1.GetPixels()), Marshal.ReadInt64(pix2.GetPixels()));
}
}
[SkippableFact]
public void SwizzleSwapsRedAndBlue()
{
var info = new SKImageInfo(10, 10);
using (var bmp = new SKBitmap(info))
{
bmp.Erase(SKColors.Red);
Assert.Equal(SKColors.Red, bmp.Pixels[0]);
SKSwizzle.SwapRedBlue(bmp.GetPixels(out var length), (int)length);
Assert.Equal(SKColors.Blue, bmp.Pixels[0]);
}
}
}
}
|
mit
|
C#
|
3452a625895bf0ec67dfa16fa087e33a9da13d89
|
Fix a minor async delayer issue
|
tgstation/tgstation-server,tgstation/tgstation-server-tools,tgstation/tgstation-server
|
tests/Tgstation.Server.Host.Tests/Core/TestAsyncDelayer.cs
|
tests/Tgstation.Server.Host.Tests/Core/TestAsyncDelayer.cs
|
using Microsoft.VisualStudio.TestTools.UnitTesting;
using System;
using System.Threading;
using System.Threading.Tasks;
namespace Tgstation.Server.Host.Core.Tests
{
[TestClass]
public sealed class TestAsyncDelayer
{
[TestMethod]
public async Task TestDelay()
{
var delayer = new AsyncDelayer();
var startDelay = delayer.Delay(TimeSpan.FromSeconds(1), default);
var checkDelay = Task.Delay(TimeSpan.FromSeconds(1) - TimeSpan.FromMilliseconds(100), default);
await startDelay.ConfigureAwait(false);
Assert.IsTrue(checkDelay.IsCompleted);
}
[TestMethod]
public async Task TestCancel()
{
var delayer = new AsyncDelayer();
using var cts = new CancellationTokenSource();
cts.Cancel();
await Assert.ThrowsExceptionAsync<TaskCanceledException>(() => delayer.Delay(TimeSpan.FromSeconds(1), cts.Token)).ConfigureAwait(false);
}
}
}
|
using Microsoft.VisualStudio.TestTools.UnitTesting;
using System;
using System.Threading;
using System.Threading.Tasks;
namespace Tgstation.Server.Host.Core.Tests
{
[TestClass]
public sealed class TestAsyncDelayer
{
[TestMethod]
public async Task TestDelay()
{
var delayer = new AsyncDelayer();
var startDelay = delayer.Delay(TimeSpan.FromSeconds(1), default);
var checkDelay = Task.Delay(TimeSpan.FromSeconds(1) - TimeSpan.FromMilliseconds(10), default);
await startDelay.ConfigureAwait(false);
Assert.IsTrue(checkDelay.IsCompleted);
}
[TestMethod]
public async Task TestCancel()
{
var delayer = new AsyncDelayer();
using (var cts = new CancellationTokenSource())
{
cts.Cancel();
await Assert.ThrowsExceptionAsync<TaskCanceledException>(() => delayer.Delay(TimeSpan.FromSeconds(1), cts.Token)).ConfigureAwait(false);
}
}
}
}
|
agpl-3.0
|
C#
|
cfcd65f6f1e242bb75215c897dd80c5fe1b6e52d
|
prepare for v2.0.7
|
longshine/Mina.NET
|
Mina.NET/Properties/AssemblyInfo.cs
|
Mina.NET/Properties/AssemblyInfo.cs
|
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// 有关程序集的常规信息通过以下
// 特性集控制。更改这些特性值可修改
// 与程序集关联的信息。
[assembly: AssemblyTitle("Mina.NET")]
[assembly: AssemblyDescription("Async socket library for high performance and high scalability network applications.")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("Mina.NET")]
[assembly: AssemblyCopyright("Copyright © Longshine 2013-2014")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
[assembly: System.CLSCompliant(true)]
// 将 ComVisible 设置为 false 使此程序集中的类型
// 对 COM 组件不可见。如果需要从 COM 访问此程序集中的类型,
// 则将该类型上的 ComVisible 特性设置为 true。
[assembly: ComVisible(false)]
// 如果此项目向 COM 公开,则下列 GUID 用于类型库的 ID
[assembly: Guid("2070ccbf-2ee3-476e-9715-54e97a5e26c7")]
// 程序集的版本信息由下面四个值组成:
//
// 主版本
// 次版本
// 内部版本号
// 修订号
//
// 可以指定所有这些值,也可以使用“内部版本号”和“修订号”的默认值,
// 方法是按如下所示使用“*”:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("2.0.7")]
[assembly: AssemblyFileVersion("2.0.7")]
|
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// 有关程序集的常规信息通过以下
// 特性集控制。更改这些特性值可修改
// 与程序集关联的信息。
[assembly: AssemblyTitle("Mina.NET")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("Mina.NET")]
[assembly: AssemblyCopyright("Copyright © Longshine 2013")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
[assembly: System.CLSCompliant(true)]
// 将 ComVisible 设置为 false 使此程序集中的类型
// 对 COM 组件不可见。如果需要从 COM 访问此程序集中的类型,
// 则将该类型上的 ComVisible 特性设置为 true。
[assembly: ComVisible(false)]
// 如果此项目向 COM 公开,则下列 GUID 用于类型库的 ID
[assembly: Guid("2070ccbf-2ee3-476e-9715-54e97a5e26c7")]
// 程序集的版本信息由下面四个值组成:
//
// 主版本
// 次版本
// 内部版本号
// 修订号
//
// 可以指定所有这些值,也可以使用“内部版本号”和“修订号”的默认值,
// 方法是按如下所示使用“*”:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("0.1.1")]
[assembly: AssemblyFileVersion("0.1")]
|
apache-2.0
|
C#
|
6f4d16d086513f48c52f647babfa5f28ba8a9f0c
|
update copyright
|
thepunctuatedhorizon/BrickCoinAlpha.0.0.1,bitcoinbrisbane/NBitcoin,stratisproject/NStratis,NicolasDorier/NBitcoin,dangershony/NStratis,you21979/NBitcoin,lontivero/NBitcoin,MetacoSA/NBitcoin,HermanSchoenfeld/NBitcoin,MetacoSA/NBitcoin
|
NBitcoin/Properties/AssemblyInfo.cs
|
NBitcoin/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("NBitcoin")]
[assembly: AssemblyDescription("Implementation of bitcoin protocol")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("AO-IS")]
[assembly: AssemblyProduct("NBitcoin")]
[assembly: AssemblyCopyright("Copyright © AO-IS 2014")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
[assembly:InternalsVisibleTo("NBitcoin.Tests")]
// 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("cdc7304e-259b-4a89-9b20-46811ef91006")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.4.18")]
[assembly: AssemblyFileVersion("1.0.0.0")]
|
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("NBitcoin")]
[assembly: AssemblyDescription("Implementation of bitcoin protocol")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("AO-IS")]
[assembly: AssemblyProduct("NBitcoin")]
[assembly: AssemblyCopyright("Copyright © Microsoft 2014")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
[assembly:InternalsVisibleTo("NBitcoin.Tests")]
// 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("cdc7304e-259b-4a89-9b20-46811ef91006")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.4.18")]
[assembly: AssemblyFileVersion("1.0.0.0")]
|
mit
|
C#
|
89fd05280626698612d740f2a5a39df20fb0c058
|
Fix Windows 8 IOCP issue with server
|
ermau/Tempest.Social
|
Desktop/Tempest.Social.Server/Program.cs
|
Desktop/Tempest.Social.Server/Program.cs
|
using System;
using System.IO;
using System.Net;
using System.Text;
using System.Threading;
using Tempest.Providers.Network;
namespace Tempest.Social.Server
{
class Program
{
private static readonly PublicKeyIdentityProvider IdentityProvider = new PublicKeyIdentityProvider();
static void Main (string[] args)
{
Console.WriteLine ("Getting server key...");
IAsymmetricKey key = GetKey ("server.key");
Console.WriteLine ("Got it.");
var provider = new NetworkConnectionProvider (
new[] { SocialProtocol.Instance },
new IPEndPoint (IPAddress.Any, SocialProtocol.DefaultPort),
10000,
() => new RSACrypto(),
key);
SocialServer server = new SocialServer (new MemoryWatchListProvider(), IdentityProvider);
server.ConnectionMade += OnConnectionMade;
server.AddConnectionProvider (provider);
server.Start();
Console.WriteLine ("Server ready.");
while (true)
Thread.Sleep (1000);
}
private static void OnConnectionMade (object sender, ConnectionMadeEventArgs e)
{
Console.WriteLine ("Connection made");
}
private static IAsymmetricKey GetKey (string path)
{
IAsymmetricKey key = null;
if (!File.Exists (path))
{
RSACrypto crypto = new RSACrypto();
key = crypto.ExportKey (true);
using (FileStream stream = File.Create (path))
key.Serialize (null, new StreamValueWriter (stream));
}
if (key == null)
{
using (FileStream stream = File.OpenRead (path))
key = new RSAAsymmetricKey (null, new StreamValueReader (stream));
}
return key;
}
}
}
|
using System;
using System.IO;
using System.Net;
using System.Text;
using Tempest.Providers.Network;
namespace Tempest.Social.Server
{
class Program
{
private static readonly PublicKeyIdentityProvider IdentityProvider = new PublicKeyIdentityProvider();
static void Main (string[] args)
{
Console.WriteLine ("Getting server key...");
IAsymmetricKey key = GetKey ("server.key");
Console.WriteLine ("Got it.");
var provider = new NetworkConnectionProvider (
new[] { SocialProtocol.Instance },
new IPEndPoint (IPAddress.Any, SocialProtocol.DefaultPort),
10000,
() => new RSACrypto(),
key);
SocialServer server = new SocialServer (new MemoryWatchListProvider(), IdentityProvider);
server.ConnectionMade += OnConnectionMade;
server.AddConnectionProvider (provider);
server.Start();
Console.WriteLine ("Server ready.");
while (Console.ReadLine() != "exit") ;
}
private static void OnConnectionMade (object sender, ConnectionMadeEventArgs e)
{
Console.WriteLine ("Connection made");
}
private static IAsymmetricKey GetKey (string path)
{
IAsymmetricKey key = null;
if (!File.Exists (path))
{
RSACrypto crypto = new RSACrypto();
key = crypto.ExportKey (true);
using (FileStream stream = File.Create (path))
key.Serialize (null, new StreamValueWriter (stream));
}
if (key == null)
{
using (FileStream stream = File.OpenRead (path))
key = new RSAAsymmetricKey (null, new StreamValueReader (stream));
}
return key;
}
}
}
|
mit
|
C#
|
45f588ad72438e30c1ffd6037f8ae10864c1291a
|
Bump to v2.7.0.0
|
Silv3rPRO/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.7.0.0")]
[assembly: AssemblyFileVersion("2.7.0.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.6.2.0")]
[assembly: AssemblyFileVersion("2.6.2.0")]
[assembly: NeutralResourcesLanguage("en")]
|
mit
|
C#
|
c46a92c97cccf2f75b3af161562439044829ecf4
|
Make GrowthPushAndroid methods static
|
SIROK-archive/growthpush-unity,SIROK/growthpush-unity,SIROK/growthpush-unity,SIROK/growthpush-unity,SIROK-archive/growthpush-unity,SIROK-archive/growthpush-unity
|
source/Assets/Plugins/GrowthPush/GrowthPushAndroid.cs
|
source/Assets/Plugins/GrowthPush/GrowthPushAndroid.cs
|
using UnityEngine;
using System.Collections;
using System;
public class GrowthPushAndroid
{
private static GrowthPushAndroid instance = new GrowthPushAndroid();
#if UNITY_ANDROID && !UNITY_EDITOR
private static AndroidJavaObject growthPush;
#endif
private GrowthPushAndroid() {
if (growthPush != null)
return;
#if UNITY_ANDROID && !UNITY_EDITOR
using(AndroidJavaClass gpclass = new AndroidJavaClass( "com.growthpush.GrowthPush" )) {
growthPush = gpclass.CallStatic<AndroidJavaObject>("getInstance");
}
#endif
}
public static Initialize(int applicationId, string secret, GrowthPush.Environment environment, bool debug) {
instance.Initialize(applicationId, secret, environment, debug);
}
public static Register(string senderId) {
instance.Register(applicationId, secret, environment, debug);
}
public void TrackEvent(string name, string val) {
instance.TrackEvent(name, val);
}
public void SetTag(string name, string val) {
instance.SetTag(name, val);
}
public void SetDeviceTags() {
instance.SetDeviceTags();
}
public void Initialize(int applicationId, string secret, GrowthPush.Environment environment, bool debug) {
if (growthPush == null)
return;
#if UNITY_ANDROID && !UNITY_EDITOR
AndroidJavaClass environmentClass = new AndroidJavaClass("com.growthpush.model.Environment");
AndroidJavaObject environmentObject = environmentClass.GetStatic<AndroidJavaObject>(environment == GrowthPush.Environment.Production ? "production" : "development");
AndroidJavaClass unityPlayer = new AndroidJavaClass("com.unity3d.player.UnityPlayer");
AndroidJavaObject activity = unityPlayer.GetStatic<AndroidJavaObject>("currentActivity");
growthPush.Call<AndroidJavaObject>("initialize", activity, applicationId, secret, environmentObject, debug);
#endif
}
public void Register(string senderId) {
if (growthPush == null)
return;
#if UNITY_ANDROID && !UNITY_EDITOR
growthPush.Call<AndroidJavaObject>("register", senderId);
#endif
}
public void TrackEvent(string name, string val) {
if (growthPush == null)
return;
#if UNITY_ANDROID && !UNITY_EDITOR
growthPush.Call("trackEvent", name, val);
#endif
}
public void SetTag(string name, string val) {
if (growthPush == null)
return;
#if UNITY_ANDROID && !UNITY_EDITOR
growthPush.Call("setTag", name, val);
#endif
}
public void SetDeviceTags() {
if (growthPush == null)
return;
#if UNITY_ANDROID && !UNITY_EDITOR
growthPush.Call("setDeviceTags");
#endif
}
// TODO Refactor callback flow
public void callTrackGrowthPushMessage() {
#if UNITY_ANDROID && !UNITY_EDITOR
using(AndroidJavaObject java = new AndroidJavaClass("com.growthpush.ExternalFramework")) {
java.CallStatic("setFramework", "unity");
java.CallStatic("callTrackGrowthPushMessage");
}
#endif
}
}
|
using UnityEngine;
using System.Collections;
using System;
public class GrowthPushAndroid
{
private static GrowthPushAndroid instance = new GrowthPushAndroid ();
#if UNITY_ANDROID && !UNITY_EDITOR
private static AndroidJavaObject growthPush;
#endif
public GrowthPushAndroid ()
{
#if UNITY_ANDROID && !UNITY_EDITOR
if (growthPush == null) {
using(AndroidJavaClass gpclass = new AndroidJavaClass( "com.growthpush.GrowthPush" ))
{
growthPush = gpclass.CallStatic<AndroidJavaObject>("getInstance");
}
}
#endif
}
public static GrowthPushAndroid GetInstance ()
{
return instance;
}
public GrowthPushAndroid Initialize (int applicationId, string secret, GrowthPush.Environment environment, bool debug)
{
#if UNITY_ANDROID && !UNITY_EDITOR
if(growthPush != null)
{
AndroidJavaClass environmentClass = new AndroidJavaClass("com.growthpush.model.Environment");
AndroidJavaObject environmentObject = environmentClass.GetStatic<AndroidJavaObject>(environment == GrowthPush.Environment.Production ? "production" : "development");
AndroidJavaClass unityPlayer = new AndroidJavaClass("com.unity3d.player.UnityPlayer");
AndroidJavaObject activity = unityPlayer.GetStatic<AndroidJavaObject>("currentActivity");
growthPush.Call<AndroidJavaObject>("initialize", activity, applicationId, secret, environmentObject, debug);
}
#endif
return this;
}
public GrowthPushAndroid Register (string senderId)
{
#if UNITY_ANDROID && !UNITY_EDITOR
if( growthPush != null )
growthPush.Call<AndroidJavaObject>("register", senderId);
#endif
return this;
}
public void TrackEvent (string name)
{
TrackEvent (name, "");
}
public void TrackEvent (string name, string val)
{
#if UNITY_ANDROID && !UNITY_EDITOR
if( growthPush != null )
growthPush.Call("trackEvent", name, val);
#endif
}
public void SetTag (string name)
{
SetTag (name, "");
}
public void SetTag (string name, string val)
{
#if UNITY_ANDROID && !UNITY_EDITOR
if( growthPush != null )
growthPush.Call("setTag", name, val);
#endif
}
public void SetDeviceTags ()
{
#if UNITY_ANDROID && !UNITY_EDITOR
if( growthPush != null )
growthPush.Call("setDeviceTags");
#endif
}
public void callTrackGrowthPushMessage ()
{
#if UNITY_ANDROID && !UNITY_EDITOR
using(AndroidJavaObject java = new AndroidJavaClass("com.growthpush.ExternalFramework"))
{
java.CallStatic("setFramework", "unity");
java.CallStatic("callTrackGrowthPushMessage");
}
#endif
}
}
|
apache-2.0
|
C#
|
b496ee90df96f682203ee4a59b8d05ac17bfcc66
|
add commented required changes for index.cshtml
|
AlejandroCano/extensions,signumsoftware/framework,signumsoftware/framework,signumsoftware/extensions,MehdyKarimpour/extensions,MehdyKarimpour/extensions,signumsoftware/extensions,AlejandroCano/extensions
|
Signum.Engine.Extensions/Dynamic/DynamicCSSOverrideLogic.cs
|
Signum.Engine.Extensions/Dynamic/DynamicCSSOverrideLogic.cs
|
using Signum.Engine;
using Signum.Engine.DynamicQuery;
using Signum.Engine.Maps;
using Signum.Engine.Operations;
using Signum.Entities;
using Signum.Entities.Basics;
using Signum.Entities.Dynamic;
using Signum.Utilities;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
namespace Signum.Engine.Dynamic
{
public static class DynamicCSSOverrideLogic
{
public static ResetLazy<List<DynamicCSSOverrideEntity>> Cached;
public static void Start(SchemaBuilder sb)
{
if (sb.NotDefined(MethodBase.GetCurrentMethod()))
{
sb.Include<DynamicCSSOverrideEntity>()
.WithSave(DynamicCSSOverrideOperation.Save)
.WithDelete(DynamicCSSOverrideOperation.Delete)
.WithQuery(() => e => new
{
Entity = e,
e.Id,
e.Name,
Script = e.Script.Etc(100),
});
Cached = sb.GlobalLazy(() =>
Database.Query<DynamicCSSOverrideEntity>().Where(a => !a.Mixin<DisabledMixin>().IsDisabled).ToList(),
new InvalidateWith(typeof(DynamicCSSOverrideEntity)));
}
}
}
}
// In order to work this module, you should apply below mentioned changes to your index.cshtml file
/*
@using Signum.Utilities;
@using Signum.Engine.Dynamic; <====*
@using Newtonsoft.Json.Linq;
@{
string json = File.ReadAllText(Path.Combine(Server.MapPath("~/dist/"), "webpack-assets.json"));
var main = (string)JObject.Parse(json).Property("main").Value["js"];
string jsonDll = File.ReadAllText(Path.Combine(Server.MapPath("~/dist/"), "webpack-assets.dll.json"));
var vendor = (string)JObject.Parse(jsonDll).Property("vendor").Value["js"];
var cssOverride = String.Join("\r\n", DynamicCSSOverrideLogic.Cached.Value.Select(a => a.Script)); <====*
}
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>@ViewBag.Title</title>
</head>
<body>
<style type="text/css">@cssOverride</style> <====*
<div id="reactDiv"></div>
<script>
var __baseUrl = "@Url.Content("~/")";
</script>
<script language="javascript" src="@Url.Content("~/dist/es6-promise.auto.min.js")"></script>
<script language="javascript" src="@Url.Content("~/dist/fetch.js")"></script>
<script language="javascript" src="@Url.Content("~/dist/" + vendor)"></script>
<script language="javascript" src="@Url.Content("~/dist/" + main)"></script>
</body>
</html>
*/
|
using Signum.Engine;
using Signum.Engine.DynamicQuery;
using Signum.Engine.Maps;
using Signum.Engine.Operations;
using Signum.Entities;
using Signum.Entities.Basics;
using Signum.Entities.Dynamic;
using Signum.Utilities;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
namespace Signum.Engine.Dynamic
{
public static class DynamicCSSOverrideLogic
{
public static ResetLazy<List<DynamicCSSOverrideEntity>> Cached;
public static void Start(SchemaBuilder sb)
{
if (sb.NotDefined(MethodBase.GetCurrentMethod()))
{
sb.Include<DynamicCSSOverrideEntity>()
.WithSave(DynamicCSSOverrideOperation.Save)
.WithDelete(DynamicCSSOverrideOperation.Delete)
.WithQuery(() => e => new
{
Entity = e,
e.Id,
e.Name,
Script = e.Script.Etc(100),
});
Cached = sb.GlobalLazy(() =>
Database.Query<DynamicCSSOverrideEntity>().Where(a => !a.Mixin<DisabledMixin>().IsDisabled).ToList(),
new InvalidateWith(typeof(DynamicCSSOverrideEntity)));
}
}
}
}
|
mit
|
C#
|
7a0288b6ff7fa4d7460a43d4b2f06a5668f50d2a
|
Fix missing return
|
Smartling/api-sdk-net
|
Smartling.API/Authentication/OAuthAuthenticationStrategy.cs
|
Smartling.API/Authentication/OAuthAuthenticationStrategy.cs
|
using System;
namespace Smartling.Api.Authentication
{
public class OAuthAuthenticationStrategy : IAuthenticationStrategy
{
private DateTime LastSuccessfullUpdate = DateTime.MinValue;
private AuthResponse LastResponse;
private readonly AuthApiClient client;
public OAuthAuthenticationStrategy(string userIdentifier, string userSecret)
{
client = new AuthApiClient(userIdentifier, userSecret);
}
public OAuthAuthenticationStrategy(AuthApiClient client)
{
this.client = client;
}
public string GetToken()
{
if (LastResponse != null && DateTime.UtcNow < LastSuccessfullUpdate.AddSeconds(LastResponse.data.expiresIn))
{
return LastResponse.data.accessToken;
}
if (LastResponse != null && DateTime.UtcNow < LastSuccessfullUpdate.AddSeconds(LastResponse.data.refreshExpiresIn))
{
try
{
LastResponse = client.Refresh(LastResponse.data.refreshToken);
}
catch
{
// If RefreshToken has failed for any reason - authenticate again
return GetToken(true);
}
}
else
{
LastResponse = client.Authenticate();
}
LastSuccessfullUpdate = DateTime.UtcNow;
return LastResponse.data.accessToken;
}
public string GetToken(bool forceAuthentication)
{
LastResponse = client.Authenticate();
LastSuccessfullUpdate = DateTime.UtcNow;
return LastResponse.data.accessToken;
}
}
}
|
using System;
namespace Smartling.Api.Authentication
{
public class OAuthAuthenticationStrategy : IAuthenticationStrategy
{
private DateTime LastSuccessfullUpdate = DateTime.MinValue;
private AuthResponse LastResponse;
private readonly AuthApiClient client;
public OAuthAuthenticationStrategy(string userIdentifier, string userSecret)
{
client = new AuthApiClient(userIdentifier, userSecret);
}
public OAuthAuthenticationStrategy(AuthApiClient client)
{
this.client = client;
}
public string GetToken()
{
if (LastResponse != null && DateTime.UtcNow < LastSuccessfullUpdate.AddSeconds(LastResponse.data.expiresIn))
{
return LastResponse.data.accessToken;
}
if (LastResponse != null && DateTime.UtcNow < LastSuccessfullUpdate.AddSeconds(LastResponse.data.refreshExpiresIn))
{
try
{
LastResponse = client.Refresh(LastResponse.data.refreshToken);
}
catch
{
// If RefreshToken has failed for any reason - authenticate again
GetToken(true);
}
}
else
{
LastResponse = client.Authenticate();
}
LastSuccessfullUpdate = DateTime.UtcNow;
return LastResponse.data.accessToken;
}
public string GetToken(bool forceAuthentication)
{
LastResponse = client.Authenticate();
LastSuccessfullUpdate = DateTime.UtcNow;
return LastResponse.data.accessToken;
}
}
}
|
apache-2.0
|
C#
|
81f50b8fbc1d9955935521fc0abdbb436a467953
|
Update minimum date for commitids.
|
CamTechConsultants/CvsntGitImporter
|
Program.cs
|
Program.cs
|
/*
* John Hall <john.hall@xjtag.com>
* Copyright (c) Midas Yellow Ltd. All rights reserved.
*/
using System;
using System.Collections.Generic;
using System.Linq;
namespace CvsGitConverter
{
class Program
{
static readonly DateTime StartDate = new DateTime(2003, 2, 1);
static void Main(string[] args)
{
if (args.Length != 1)
throw new ArgumentException("Need a cvs.log file");
var parser = new CvsLogParser(args[0], startDate: StartDate);
var builder = new CommitBuilder(parser);
var commits = builder.GetCommits().SplitMultiBranchCommits().ToList();
Verify(commits);
// build lookup of all files
var allFiles = new Dictionary<string, FileInfo>();
foreach (var f in parser.Files)
allFiles.Add(f.Name, f);
var tagResolver = new TagResolver(commits, allFiles);
tagResolver.Resolve();
if (tagResolver.Errors.Any())
{
Console.Error.WriteLine("Errors resolving tags:");
foreach (var error in tagResolver.Errors)
Console.Error.WriteLine(" {0}", error);
}
}
private static void Verify(IEnumerable<Commit> commits)
{
foreach (var commit in commits)
{
if (!commit.Verify())
{
Console.Error.WriteLine("Verification failed: {0} {1}", commit.CommitId, commit.Time);
foreach (var revision in commit)
Console.Error.WriteLine(" {0} r{1}", revision.File, revision.Revision);
bool first = true;
foreach (var error in commit.Errors)
{
if (first)
first = false;
else
Console.Error.WriteLine("----------------------------------------");
Console.Error.WriteLine(error);
}
Console.Error.WriteLine("========================================");
}
}
}
}
}
|
/*
* John Hall <john.hall@xjtag.com>
* Copyright (c) Midas Yellow Ltd. All rights reserved.
*/
using System;
using System.Collections.Generic;
using System.Linq;
namespace CvsGitConverter
{
class Program
{
static readonly DateTime StartDate = new DateTime(2003, 1, 1);
static void Main(string[] args)
{
if (args.Length != 1)
throw new ArgumentException("Need a cvs.log file");
var parser = new CvsLogParser(args[0], startDate: StartDate);
var builder = new CommitBuilder(parser);
var commits = builder.GetCommits().SplitMultiBranchCommits().ToList();
Verify(commits);
// build lookup of all files
var allFiles = new Dictionary<string, FileInfo>();
foreach (var f in parser.Files)
allFiles.Add(f.Name, f);
var tagResolver = new TagResolver(commits, allFiles);
tagResolver.Resolve();
if (tagResolver.Errors.Any())
{
Console.Error.WriteLine("Errors resolving tags:");
foreach (var error in tagResolver.Errors)
Console.Error.WriteLine(" {0}", error);
}
}
private static void Verify(IEnumerable<Commit> commits)
{
foreach (var commit in commits)
{
if (!commit.Verify())
{
Console.Error.WriteLine("Verification failed: {0} {1}", commit.CommitId, commit.Time);
foreach (var revision in commit)
Console.Error.WriteLine(" {0} r{1}", revision.File, revision.Revision);
bool first = true;
foreach (var error in commit.Errors)
{
if (first)
first = false;
else
Console.Error.WriteLine("----------------------------------------");
Console.Error.WriteLine(error);
}
Console.Error.WriteLine("========================================");
}
}
}
}
}
|
mit
|
C#
|
b031c3bf304a306060c955543592bd7919c5c6da
|
Update ComBytes.cs
|
halex2005/diadocsdk-csharp,diadoc/diadocsdk-csharp,halex2005/diadocsdk-csharp,diadoc/diadocsdk-csharp
|
src/Com/ComBytes.cs
|
src/Com/ComBytes.cs
|
using System.IO;
using System.Runtime.InteropServices;
using System.Text;
namespace Diadoc.Api.Com
{
[ComVisible(true)]
[Guid("AC96A3DD-E099-44CC-ABD5-11C303307159")]
public interface IComBytes
{
byte[] Bytes { get; set; }
void ReadFromFile(string path);
void SaveToFile(string path);
void ReadFromText(string text, string codePage);
}
[ComVisible(true)]
[ProgId("Diadoc.Api.ComBytes")]
[Guid("97D998E3-E603-4450-A027-EA774091BE72")]
[ClassInterface(ClassInterfaceType.None)]
[ComDefaultInterface(typeof(IComBytes))]
public class ComBytes : SafeComObject, IComBytes
{
public byte[] Bytes { get; set; }
public void ReadFromFile(string path)
{
Bytes = File.ReadAllBytes(path);
}
public void ReadFromText(string text, string codePage)
{
if (System.String.IsNullOrEmpty(codePage)) codePage="utf-8";
Encoding encoding = Encoding.GetEncoding(codePage);
Bytes = encoding.GetBytes(text);
}
public void SaveToFile(string path)
{
if (Bytes != null)
{
File.WriteAllBytes(path, Bytes);
}
}
}
}
|
using System.IO;
using System.Runtime.InteropServices;
using System.Text;
namespace Diadoc.Api.Com
{
[ComVisible(true)]
[Guid("AC96A3DD-E099-44CC-ABD5-11C303307159")]
public interface IComBytes
{
byte[] Bytes { get; set; }
void ReadFromFile(string path);
void SaveToFile(string path);
void ReadFromText(string text);
}
[ComVisible(true)]
[ProgId("Diadoc.Api.ComBytes")]
[Guid("97D998E3-E603-4450-A027-EA774091BE72")]
[ClassInterface(ClassInterfaceType.None)]
[ComDefaultInterface(typeof(IComBytes))]
public class ComBytes : SafeComObject, IComBytes
{
public byte[] Bytes { get; set; }
public void ReadFromFile(string path)
{
Bytes = File.ReadAllBytes(path);
}
public void ReadFromText(string text)
{
Bytes = Encoding.UTF8.GetBytes(text);
}
public void SaveToFile(string path)
{
if (Bytes != null)
{
File.WriteAllBytes(path, Bytes);
}
}
}
}
|
mit
|
C#
|
e8667f7405981439286918b04e125c6e623274f4
|
bump version
|
Selz/PexelsNet
|
PexelsNet/Properties/AssemblyInfo.cs
|
PexelsNet/Properties/AssemblyInfo.cs
|
using System;
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("PexelsNet")]
[assembly: AssemblyDescription("PexelsNet is a .NET class library that provides an easy-to-use interface for the https://www.pexels.com/ web api")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Mathieu Kempe")]
[assembly: AssemblyProduct("PexelsNet")]
[assembly: AssemblyCopyright("Copyright © 2020")]
[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("55f9f5af-565e-4b4a-ba73-e3d7438a5f11")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("3.1.0.0")]
[assembly: AssemblyFileVersion("3.1.0.0")]
|
using System;
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("PexelsNet")]
[assembly: AssemblyDescription("PexelsNet is a .NET class library that provides an easy-to-use interface for the https://www.pexels.com/ web api")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Mathieu Kempe")]
[assembly: AssemblyProduct("PexelsNet")]
[assembly: AssemblyCopyright("Copyright © 2020")]
[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("55f9f5af-565e-4b4a-ba73-e3d7438a5f11")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("2.4.0.0")]
[assembly: AssemblyFileVersion("2.4.0.0")]
|
mit
|
C#
|
fa6b5eaa619085c6acef48c3b2776022476bfb5c
|
Set version to 1.1.2.0
|
da2x/EdgeDeflector
|
EdgeDeflector/Properties/AssemblyInfo.cs
|
EdgeDeflector/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("EdgeDeflector")]
[assembly: AssemblyDescription("Rewrites microsoft-edge URI addresses into standard http URI addresses.")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("EdgeDeflector")]
[assembly: AssemblyCopyright("Copyright © 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("64e191bc-e8ce-4190-939e-c77a75aa0e28")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Maintenance Number
// Build Number
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.1.2.0")]
[assembly: AssemblyFileVersion("1.1.2.0")]
|
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("EdgeDeflector")]
[assembly: AssemblyDescription("Rewrites microsoft-edge URI addresses into standard http URI addresses.")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("EdgeDeflector")]
[assembly: AssemblyCopyright("Copyright © 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("64e191bc-e8ce-4190-939e-c77a75aa0e28")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Maintenance Number
// Build Number
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.1.1.0")]
[assembly: AssemblyFileVersion("1.1.1.0")]
|
mit
|
C#
|
5128e3bfc9b83672e3097f31fd1129abd0810098
|
Add notes about ConsoleLogger (#1531)
|
EasyNetQ/EasyNetQ
|
Source/EasyNetQ/Logging/ConsoleLogger.cs
|
Source/EasyNetQ/Logging/ConsoleLogger.cs
|
using System;
namespace EasyNetQ.Logging;
/// <summary>
/// Simple built-in implementation to log messages into console. It is assumed for use for debugging
/// purposes and shouldn't be used in the production environment.
/// </summary>
public sealed class ConsoleLogger<TCategoryName> : ILogger<TCategoryName>
{
/// <inheritdoc />
public bool Log(
LogLevel logLevel,
Func<string>? messageFunc,
Exception? exception = null,
params object?[] formatParameters
)
{
if (messageFunc == null) return true;
var consoleColor = logLevel switch
{
LogLevel.Trace => ConsoleColor.DarkGray,
LogLevel.Debug => ConsoleColor.Gray,
LogLevel.Info => ConsoleColor.White,
LogLevel.Warn => ConsoleColor.Magenta,
LogLevel.Error => ConsoleColor.Yellow,
LogLevel.Fatal => ConsoleColor.Red,
_ => throw new ArgumentOutOfRangeException(nameof(logLevel), logLevel, null)
};
// no cache here so performance hit (+one more below building output string)
var message = MessageFormatter.FormatStructuredMessage(messageFunc(), formatParameters, out _);
if (exception != null) message += " -> " + exception;
ConcurrentColoredConsole.WriteLine(consoleColor, $"[{DateTime.UtcNow:HH:mm:ss} {logLevel}] {message}");
return true;
}
}
|
using System;
namespace EasyNetQ.Logging;
/// <inheritdoc />
public sealed class ConsoleLogger<TCategoryName> : ILogger<TCategoryName>
{
/// <inheritdoc />
public bool Log(
LogLevel logLevel,
Func<string>? messageFunc,
Exception? exception = null,
params object?[] formatParameters
)
{
if (messageFunc == null) return true;
var consoleColor = logLevel switch
{
LogLevel.Trace => ConsoleColor.DarkGray,
LogLevel.Debug => ConsoleColor.Gray,
LogLevel.Info => ConsoleColor.White,
LogLevel.Warn => ConsoleColor.Magenta,
LogLevel.Error => ConsoleColor.Yellow,
LogLevel.Fatal => ConsoleColor.Red,
_ => throw new ArgumentOutOfRangeException(nameof(logLevel), logLevel, null)
};
var message = MessageFormatter.FormatStructuredMessage(messageFunc(), formatParameters, out _);
if (exception != null) message += " -> " + exception;
ConcurrentColoredConsole.WriteLine(consoleColor, $"[{DateTime.UtcNow:HH:mm:ss} {logLevel}] {message}");
return true;
}
}
|
mit
|
C#
|
c8408bdd61049ed02bcf6306a2651cc19daac3ce
|
Add stub method for Getting volunteers by date
|
mjmilan/crisischeckin,andrewhart098/crisischeckin,coridrew/crisischeckin,mheggeseth/crisischeckin,brunck/crisischeckin,mjmilan/crisischeckin,jsucupira/crisischeckin,jplwood/crisischeckin,pooran/crisischeckin,MobileRez/crisischeckin,RyanBetker/crisischeckinUpdates,pottereric/crisischeckin,andrewhart098/crisischeckin,HTBox/crisischeckin,lloydfaulkner/crisischeckin,djjlewis/crisischeckin,pooran/crisischeckin,HTBox/crisischeckin,RyanBetker/crisischeckin,brunck/crisischeckin,RyanBetker/crisischeckinUpdates,mjmilan/crisischeckin,jplwood/crisischeckin,mheggeseth/crisischeckin,MobileRez/crisischeckin,coridrew/crisischeckin,HTBox/crisischeckin,andrewhart098/crisischeckin,djjlewis/crisischeckin,RyanBetker/crisischeckin,brunck/crisischeckin,jsucupira/crisischeckin,lloydfaulkner/crisischeckin,pottereric/crisischeckin
|
crisischeckin/Services/AdminService.cs
|
crisischeckin/Services/AdminService.cs
|
using Models;
using Services.Interfaces;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Services
{
public class AdminService : IAdmin
{
private readonly IDataService dataService;
public AdminService(IDataService service)
{
if (service == null)
throw new ArgumentNullException("service", "Service Interface must not be null");
this.dataService = service;
}
public IEnumerable<Person> GetVolunteers(Disaster disaster)
{
if (disaster == null)
throw new ArgumentNullException("disaster", "disaster cannot be null");
var storedDisaster = dataService.Disasters.SingleOrDefault(d => d.Id == disaster.Id);
if (storedDisaster == null)
throw new ArgumentException("Disaster was not found", "disaster");
var commitments = from c in dataService.Commitments
where c.DisasterId == disaster.Id
select c;
var people = from c in commitments
join p in dataService.Persons on c.PersonId equals p.Id
select p;
return people;
}
public IEnumerable<Person> GetVolunteersForDate(Disaster disaster, DateTime date)
{
if (disaster == null)
throw new ArgumentNullException("disaster", "disaster cannot be null");
var storedDisaster = dataService.Disasters.SingleOrDefault(d => d.Id == disaster.Id);
if (storedDisaster == null)
throw new ArgumentException("Disaster was not found", "disaster");
var commitments = from c in dataService.Commitments
where c.DisasterId == disaster.Id
select c;
var people = from c in commitments
join p in dataService.Persons on c.PersonId equals p.Id
select p;
return people;
}
}
}
|
using Models;
using Services.Interfaces;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Services
{
public class AdminService : IAdmin
{
private readonly IDataService dataService;
public AdminService(IDataService service)
{
if (service == null)
throw new ArgumentNullException("service", "Service Interface must not be null");
this.dataService = service;
}
public IEnumerable<Person> GetVolunteers(Disaster disaster)
{
if (disaster == null)
throw new ArgumentNullException("disaster", "disaster cannot be null");
var storedDisaster = dataService.Disasters.SingleOrDefault(d => d.Id == disaster.Id);
if (storedDisaster == null)
throw new ArgumentException("Disaster was not found", "disaster");
var commitments = from c in dataService.Commitments
where c.DisasterId == disaster.Id
select c;
var people = from c in commitments
join p in dataService.Persons on c.PersonId equals p.Id
select p;
return people;
}
}
}
|
apache-2.0
|
C#
|
54f22349295303bef7bdad16de21ad47fade7d38
|
Update AssemblyInfo.cs
|
mksmbrtsh/gpstalk
|
gpstalk_PDA/Properties/AssemblyInfo.cs
|
gpstalk_PDA/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("gpstalk_PDA")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("gpstalk_PDA")]
[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("f30976ed-fd3c-4a5c-a87b-0bb8d083fad8")]
// 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.0.*")]
|
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("gpstalk_PDA")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("gpstalk_PDA")]
[assembly: AssemblyCopyright("Copyright © gosniias 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("f30976ed-fd3c-4a5c-a87b-0bb8d083fad8")]
// 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.0.*")]
|
bsd-3-clause
|
C#
|
8a84219dabb8411d99c57ffa7167f2bced4105a8
|
Add an explanatory note to Mailchimp admin
|
planetClaire/Orchard-LETS,planetClaire/Orchard-LETS,planetClaire/Orchard-LETS,planetClaire/Orchard-LETS,planetClaire/Orchard-LETS
|
src/Orchard.Web/Modules/LETS/Views/MemberAdmin/Mailchimp.cshtml
|
src/Orchard.Web/Modules/LETS/Views/MemberAdmin/Mailchimp.cshtml
|
@using LETS.Models
@model LETS.ViewModels.MailchimpSyncViewModel
<h2>@T("Mailchimp")</h2>
<p>Members are added to the mailchimp mailing list when they are approved AND they have verified their email address.</p>
<p><strong>Important: </strong>Members are not automatically unsubscribed if they are disabled or deleted. Remove them on the Mailchimp website. </p>
<h3>@T("Approved & verified members missing from Mailchimp list")</h3>
@if (Model == null || Model.MissingListMembers.Count().Equals(0))
{
<p>@T("Nothing to show")</p>
}
else
{
<table class="items">
@foreach (var member in Model.MissingListMembers)
{
<tr>
<td>@member.Name</td>
<td>@member.Email</td>
<td><a href="@Url.Action("SubscribeToMailchimp", "MemberAdmin", new {area = "LETS", id = member.Id})" title="@T("Subscribe")">@T("Subscribe")</a></td>
</tr>
}
</table>
}
<h3>@T("Emails on list missing from approved & verified members")</h3>
@if (Model == null || Model.MissingOrchardMembers.Count().Equals(0))
{
<p>@T("Nothing to show")</p>
}
else
{
<table class="items">
@foreach (var member in Model.MissingOrchardMembers)
{
<tr>
<td>@member.Email</td>
</tr>
}
</table>
}
|
@using LETS.Models
@model LETS.ViewModels.MailchimpSyncViewModel
<h2>@T("Mailchimp")</h2>
<h3>@T("Approved & verified members missing from Mailchimp list")</h3>
@if (Model == null || Model.MissingListMembers.Count().Equals(0))
{
<p>@T("Nothing to show")</p>
}
else
{
<table class="items">
@foreach (var member in Model.MissingListMembers)
{
<tr>
<td>@member.Name</td>
<td>@member.Email</td>
<td><a href="@Url.Action("SubscribeToMailchimp", "MemberAdmin", new {area = "LETS", id = member.Id})" title="@T("Subscribe")">@T("Subscribe")</a></td>
</tr>
}
</table>
}
<h3>@T("Emails on list missing from approved & verified members")</h3>
@if (Model == null || Model.MissingOrchardMembers.Count().Equals(0))
{
<p>@T("Nothing to show")</p>
}
else
{
<table class="items">
@foreach (var member in Model.MissingOrchardMembers)
{
<tr>
<td>@member.Email</td>
</tr>
}
</table>
}
|
bsd-3-clause
|
C#
|
5cf3f822ab48d92d0dd27ce59d61179646b4be7f
|
Make ShellSettings fields readonly (#11850)
|
stevetayloruk/Orchard2,stevetayloruk/Orchard2,stevetayloruk/Orchard2,stevetayloruk/Orchard2,stevetayloruk/Orchard2
|
src/OrchardCore/OrchardCore.Abstractions/Shell/ShellSettings.cs
|
src/OrchardCore/OrchardCore.Abstractions/Shell/ShellSettings.cs
|
using System;
using System.Threading.Tasks;
using Microsoft.Extensions.Configuration;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using OrchardCore.Environment.Shell.Configuration;
using OrchardCore.Environment.Shell.Models;
namespace OrchardCore.Environment.Shell
{
/// <summary>
/// Represents the minimalistic set of fields stored for each tenant. This model
/// is obtained from the 'IShellSettingsManager', which by default reads this
/// from the 'App_Data/tenants.json' file.
/// </summary>
public class ShellSettings
{
private readonly ShellConfiguration _settings;
private readonly ShellConfiguration _configuration;
public ShellSettings()
{
_settings = new ShellConfiguration();
_configuration = new ShellConfiguration();
}
public ShellSettings(ShellConfiguration settings, ShellConfiguration configuration)
{
_settings = settings;
_configuration = configuration;
}
public ShellSettings(ShellSettings settings)
{
_settings = new ShellConfiguration(settings._settings);
_configuration = new ShellConfiguration(settings.Name, settings._configuration);
Name = settings.Name;
}
public string Name { get; set; }
public string VersionId
{
get => _settings["VersionId"];
set => _settings["VersionId"] = value;
}
public string RequestUrlHost
{
get => _settings["RequestUrlHost"];
set => _settings["RequestUrlHost"] = value;
}
public string RequestUrlPrefix
{
get => _settings["RequestUrlPrefix"]?.Trim(' ', '/');
set => _settings["RequestUrlPrefix"] = value;
}
[JsonConverter(typeof(StringEnumConverter))]
public TenantState State
{
get => _settings.GetValue<TenantState>("State");
set => _settings["State"] = value.ToString();
}
[JsonIgnore]
public IShellConfiguration ShellConfiguration => _configuration;
[JsonIgnore]
public string this[string key]
{
get => _configuration[key];
set => _configuration[key] = value;
}
public Task EnsureConfigurationAsync() => _configuration.EnsureConfigurationAsync();
public bool IsDefaultShell()
=> String.Equals(Name, ShellHelper.DefaultShellName, StringComparison.OrdinalIgnoreCase);
}
}
|
using System;
using System.Threading.Tasks;
using Microsoft.Extensions.Configuration;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using OrchardCore.Environment.Shell.Configuration;
using OrchardCore.Environment.Shell.Models;
namespace OrchardCore.Environment.Shell
{
/// <summary>
/// Represents the minimalistic set of fields stored for each tenant. This model
/// is obtained from the 'IShellSettingsManager', which by default reads this
/// from the 'App_Data/tenants.json' file.
/// </summary>
public class ShellSettings
{
private ShellConfiguration _settings;
private ShellConfiguration _configuration;
public ShellSettings()
{
_settings = new ShellConfiguration();
_configuration = new ShellConfiguration();
}
public ShellSettings(ShellConfiguration settings, ShellConfiguration configuration)
{
_settings = settings;
_configuration = configuration;
}
public ShellSettings(ShellSettings settings)
{
_settings = new ShellConfiguration(settings._settings);
_configuration = new ShellConfiguration(settings.Name, settings._configuration);
Name = settings.Name;
}
public string Name { get; set; }
public string VersionId
{
get => _settings["VersionId"];
set => _settings["VersionId"] = value;
}
public string RequestUrlHost
{
get => _settings["RequestUrlHost"];
set => _settings["RequestUrlHost"] = value;
}
public string RequestUrlPrefix
{
get => _settings["RequestUrlPrefix"]?.Trim(' ', '/');
set => _settings["RequestUrlPrefix"] = value;
}
[JsonConverter(typeof(StringEnumConverter))]
public TenantState State
{
get => _settings.GetValue<TenantState>("State");
set => _settings["State"] = value.ToString();
}
[JsonIgnore]
public IShellConfiguration ShellConfiguration => _configuration;
[JsonIgnore]
public string this[string key]
{
get => _configuration[key];
set => _configuration[key] = value;
}
public Task EnsureConfigurationAsync() => _configuration.EnsureConfigurationAsync();
public bool IsDefaultShell()
=> String.Equals(Name, ShellHelper.DefaultShellName, StringComparison.OrdinalIgnoreCase);
}
}
|
bsd-3-clause
|
C#
|
587c689d4b0e59212366e73fb42130ba3627f23d
|
remove whitespaces
|
Barrelrolla/MonsterClicker
|
MonsterClicker/MonsterClicker/StartUp.cs
|
MonsterClicker/MonsterClicker/StartUp.cs
|
namespace MonsterClicker
{
using System;
using System.Windows.Forms;
static class StartUp
{
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new Form1());
}
}
}
|
namespace MonsterClicker
{
using System;
using System.Windows.Forms;
static class StartUp
{
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new Form1());
}
}
}
|
mit
|
C#
|
f79ad8110e670a9a5998a2a6dc72d4f07fb2170a
|
Fix FakeScraper by implementing the new API.
|
faint32/snowflake-1,SnowflakePowered/snowflake,RonnChyran/snowflake,RonnChyran/snowflake,SnowflakePowered/snowflake,RonnChyran/snowflake,faint32/snowflake-1,faint32/snowflake-1,SnowflakePowered/snowflake
|
Snowflake.Tests/Fakes/FakeScraper.cs
|
Snowflake.Tests/Fakes/FakeScraper.cs
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Snowflake.Tests.Fakes
{
internal class FakeScraper : Snowflake.Scraper.IScraper
{
public Utility.BiDictionary<string, string> ScraperMap
{
get { throw new NotImplementedException(); }
}
public IList<Scraper.IGameScrapeResult> GetSearchResults(string searchQuery)
{
throw new NotImplementedException();
}
public IList<Scraper.IGameScrapeResult> GetSearchResults(string searchQuery, string platformId)
{
throw new NotImplementedException();
}
public Tuple<IDictionary<string, string>, Scraper.IGameImagesResult> GetGameDetails(string id)
{
throw new NotImplementedException();
}
public string PluginName
{
get { throw new NotImplementedException(); }
}
public string PluginDataPath
{
get { throw new NotImplementedException(); }
}
public IList<string> SupportedPlatforms
{
get { throw new NotImplementedException(); }
}
public System.Reflection.Assembly PluginAssembly
{
get { throw new NotImplementedException(); }
}
public IDictionary<string, dynamic> PluginInfo
{
get { throw new NotImplementedException(); }
}
public Service.ICoreService CoreInstance
{
get { throw new NotImplementedException(); }
}
public System.IO.Stream GetResource(string resourceName)
{
throw new NotImplementedException();
}
public string GetStringResource(string resourceName)
{
throw new NotImplementedException();
}
public Plugin.IPluginConfiguration PluginConfiguration
{
get { throw new NotImplementedException(); }
}
public IList<Scraper.IGameScrapeResult> GetSearchResults(IDictionary<string, string> identifiedMetadata, string platformId)
{
throw new NotImplementedException();
}
public IList<Scraper.IGameScrapeResult> GetSearchResults(IDictionary<string, string> identifiedMetadata, string searchQuery, string platformId)
{
throw new NotImplementedException();
}
public IList<Scraper.IGameScrapeResult> SortBestResults(IDictionary<string, string> identifiedMetadata, IList<Scraper.IGameScrapeResult> searchResults)
{
throw new NotImplementedException();
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Snowflake.Tests.Fakes
{
internal class FakeScraper : Snowflake.Scraper.IScraper
{
public Utility.BiDictionary<string, string> ScraperMap
{
get { throw new NotImplementedException(); }
}
public IList<Scraper.IGameScrapeResult> GetSearchResults(string searchQuery)
{
throw new NotImplementedException();
}
public IList<Scraper.IGameScrapeResult> GetSearchResults(string searchQuery, string platformId)
{
throw new NotImplementedException();
}
public Tuple<IDictionary<string, string>, Scraper.IGameImagesResult> GetGameDetails(string id)
{
throw new NotImplementedException();
}
public string PluginName
{
get { throw new NotImplementedException(); }
}
public string PluginDataPath
{
get { throw new NotImplementedException(); }
}
public IList<string> SupportedPlatforms
{
get { throw new NotImplementedException(); }
}
public System.Reflection.Assembly PluginAssembly
{
get { throw new NotImplementedException(); }
}
public IDictionary<string, dynamic> PluginInfo
{
get { throw new NotImplementedException(); }
}
public Service.ICoreService CoreInstance
{
get { throw new NotImplementedException(); }
}
public System.IO.Stream GetResource(string resourceName)
{
throw new NotImplementedException();
}
public string GetStringResource(string resourceName)
{
throw new NotImplementedException();
}
public Plugin.IPluginConfiguration PluginConfiguration
{
get { throw new NotImplementedException(); }
}
}
}
|
mpl-2.0
|
C#
|
307c8829be41e1f85f5ebb62be34c30625520a32
|
Update nullable annotations in TodoComments folder
|
KevinRansom/roslyn,shyamnamboodiripad/roslyn,bartdesmet/roslyn,stephentoub/roslyn,tannergooding/roslyn,gafter/roslyn,mgoertz-msft/roslyn,dotnet/roslyn,genlu/roslyn,sharwell/roslyn,AlekseyTs/roslyn,ErikSchierboom/roslyn,wvdd007/roslyn,heejaechang/roslyn,brettfo/roslyn,mavasani/roslyn,weltkante/roslyn,aelij/roslyn,CyrusNajmabadi/roslyn,physhi/roslyn,heejaechang/roslyn,jmarolf/roslyn,KirillOsenkov/roslyn,panopticoncentral/roslyn,aelij/roslyn,tmat/roslyn,jasonmalinowski/roslyn,CyrusNajmabadi/roslyn,diryboy/roslyn,CyrusNajmabadi/roslyn,mgoertz-msft/roslyn,diryboy/roslyn,mavasani/roslyn,physhi/roslyn,jasonmalinowski/roslyn,tannergooding/roslyn,KevinRansom/roslyn,ErikSchierboom/roslyn,eriawan/roslyn,wvdd007/roslyn,gafter/roslyn,eriawan/roslyn,aelij/roslyn,bartdesmet/roslyn,stephentoub/roslyn,jmarolf/roslyn,gafter/roslyn,jmarolf/roslyn,AmadeusW/roslyn,shyamnamboodiripad/roslyn,dotnet/roslyn,mgoertz-msft/roslyn,weltkante/roslyn,brettfo/roslyn,panopticoncentral/roslyn,KevinRansom/roslyn,AlekseyTs/roslyn,brettfo/roslyn,panopticoncentral/roslyn,KirillOsenkov/roslyn,shyamnamboodiripad/roslyn,mavasani/roslyn,eriawan/roslyn,tannergooding/roslyn,ErikSchierboom/roslyn,weltkante/roslyn,diryboy/roslyn,physhi/roslyn,sharwell/roslyn,wvdd007/roslyn,jasonmalinowski/roslyn,heejaechang/roslyn,KirillOsenkov/roslyn,genlu/roslyn,AlekseyTs/roslyn,tmat/roslyn,AmadeusW/roslyn,bartdesmet/roslyn,genlu/roslyn,sharwell/roslyn,tmat/roslyn,dotnet/roslyn,AmadeusW/roslyn,stephentoub/roslyn
|
src/Workspaces/Core/Portable/TodoComments/TodoCommentOptions.cs
|
src/Workspaces/Core/Portable/TodoComments/TodoCommentOptions.cs
|
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable enable
using System;
using System.Collections.Immutable;
using System.Composition;
using Microsoft.CodeAnalysis.Host.Mef;
using Microsoft.CodeAnalysis.Options;
using Microsoft.CodeAnalysis.Options.Providers;
namespace Microsoft.CodeAnalysis.Editor.Implementation.TodoComments
{
internal static class TodoCommentOptions
{
public static readonly Option<string> TokenList = new Option<string>(nameof(TodoCommentOptions), nameof(TokenList), defaultValue: "HACK:1|TODO:1|UNDONE:1|UnresolvedMergeConflict:0");
}
[ExportOptionProvider, Shared]
internal class TodoCommentOptionsProvider : IOptionProvider
{
[ImportingConstructor]
[Obsolete(MefConstruction.ImportingConstructorMessage, error: true)]
public TodoCommentOptionsProvider()
{
}
public ImmutableArray<IOption> Options { get; } = ImmutableArray.Create<IOption>(
TodoCommentOptions.TokenList);
}
}
|
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Immutable;
using System.Composition;
using Microsoft.CodeAnalysis.Host.Mef;
using Microsoft.CodeAnalysis.Options;
using Microsoft.CodeAnalysis.Options.Providers;
namespace Microsoft.CodeAnalysis.Editor.Implementation.TodoComments
{
internal static class TodoCommentOptions
{
public static readonly Option<string> TokenList = new Option<string>(nameof(TodoCommentOptions), nameof(TokenList), defaultValue: "HACK:1|TODO:1|UNDONE:1|UnresolvedMergeConflict:0");
}
[ExportOptionProvider, Shared]
internal class TodoCommentOptionsProvider : IOptionProvider
{
[ImportingConstructor]
[Obsolete(MefConstruction.ImportingConstructorMessage, error: true)]
public TodoCommentOptionsProvider()
{
}
public ImmutableArray<IOption> Options { get; } = ImmutableArray.Create<IOption>(
TodoCommentOptions.TokenList);
}
}
|
mit
|
C#
|
72aa8a0680db865afd566bd12b92b7a3b140415c
|
Replace params in git.repo.path
|
ComputerWorkware/TeamCityApi
|
src/TeamCityApi/Domain/VcsCommit.cs
|
src/TeamCityApi/Domain/VcsCommit.cs
|
using System.Linq;
namespace TeamCityApi.Domain
{
public enum GitAuthenticationType
{
Ssh = 1,
Http = 2
}
public class VcsCommit
{
public string CommitSha { get; set; }
public string RepositoryLocation { get; set; }
public string RepositoryNameWithNamespace { get; set; }
public string BranchName { get; set; }
public GitAuthenticationType AuthenticationType { get; set; }
public string VcsRootId { get; set; }
/// <summary>
/// Encapsulate Repo location, Branch and Commit.
/// Since VcsRoot contains parameter placeholders, build parameters needed to generate end values
/// </summary>
/// <param name="vcsRoot"></param>
/// <param name="parameters"></param>
/// <param name="commitHash"></param>
public VcsCommit(VcsRoot vcsRoot, PropertyList parameters, string commitHash)
{
CommitSha = commitHash;
AuthenticationType = GitAuthenticationType.Http;
VcsRootId = vcsRoot.VcsRootId;
Property property = vcsRoot.Properties.Property.FirstOrDefault(x => x.Name == "url");
if (property != null)
{
RepositoryLocation = parameters.ReplaceInString(property.Value);
}
property = parameters.FirstOrDefault(x => x.Name == "git.repo.path");
if (property != null)
{
RepositoryNameWithNamespace = parameters.ReplaceInString(property.Value);
}
property = vcsRoot.Properties.Property.FirstOrDefault(x => x.Name == "authMethod");
if (property != null)
{
AuthenticationType = property.Value == "PASSWORD" ? GitAuthenticationType.Http : GitAuthenticationType.Ssh;
}
property = vcsRoot.Properties.Property.FirstOrDefault(x => x.Name == "branch");
if (property != null)
{
BranchName = parameters.ReplaceInString(property.Value);
}
}
}
}
|
using System.Linq;
namespace TeamCityApi.Domain
{
public enum GitAuthenticationType
{
Ssh = 1,
Http = 2
}
public class VcsCommit
{
public string CommitSha { get; set; }
public string RepositoryLocation { get; set; }
public string RepositoryNameWithNamespace { get; set; }
public string BranchName { get; set; }
public GitAuthenticationType AuthenticationType { get; set; }
public string VcsRootId { get; set; }
/// <summary>
/// Encapsulate Repo location, Branch and Commit.
/// Since VcsRoot contains parameter placeholders, build parameters needed to generate end values
/// </summary>
/// <param name="vcsRoot"></param>
/// <param name="parameters"></param>
/// <param name="commitHash"></param>
public VcsCommit(VcsRoot vcsRoot, PropertyList parameters, string commitHash)
{
CommitSha = commitHash;
AuthenticationType = GitAuthenticationType.Http;
VcsRootId = vcsRoot.VcsRootId;
Property property = vcsRoot.Properties.Property.FirstOrDefault(x => x.Name == "url");
if (property != null)
{
RepositoryLocation = parameters.ReplaceInString(property.Value);
}
property = parameters.FirstOrDefault(x => x.Name == "git.repo.path");
if (property != null)
{
RepositoryNameWithNamespace = property.Value;
}
property = vcsRoot.Properties.Property.FirstOrDefault(x => x.Name == "authMethod");
if (property != null)
{
AuthenticationType = property.Value == "PASSWORD" ? GitAuthenticationType.Http : GitAuthenticationType.Ssh;
}
property = vcsRoot.Properties.Property.FirstOrDefault(x => x.Name == "branch");
if (property != null)
{
BranchName = parameters.ReplaceInString(property.Value);
}
}
}
}
|
mit
|
C#
|
cbfed54c5a7cbfc7d2c94322894abcf3df52f16d
|
update IdGenerator
|
WeihanLi/WeihanLi.Common,WeihanLi/WeihanLi.Common,WeihanLi/WeihanLi.Common
|
src/WeihanLi.Common/IIdGenerator.cs
|
src/WeihanLi.Common/IIdGenerator.cs
|
using System;
using WeihanLi.Common.Helpers;
namespace WeihanLi.Common
{
/// <summary>
/// IdGenerator
/// </summary>
public interface IIdGenerator
{
/// <summary>
/// Generate a new id
/// </summary>
/// <returns>new id</returns>
string NewId();
}
/// <summary>
/// IdGenerator based on Guid
/// </summary>
public sealed class GuidIdGenerator : IIdGenerator
{
public GuidIdGenerator()
{
}
public static readonly GuidIdGenerator Instance = new GuidIdGenerator();
public string NewId() => Guid.NewGuid().ToString("N");
}
public sealed class SequentialGuidIdGenerator : IIdGenerator
{
public string NewId() => SequentialGuidGenerator.Create(SequentialGuidType.SequentialAsString).ToString("N");
}
/// <summary>
/// IdGenerator based on ObjectId
/// </summary>
public sealed class ObjectIdGenerator : IIdGenerator
{
public string NewId() => ObjectId.GenerateNewStringId();
}
/// <summary>
/// Snowflake IdGenerator
/// WARNING: NotImplemented, do not use
/// </summary>
public sealed class SnowflakeIdGenerator : IIdGenerator
{
public string NewId()
{
throw new NotImplementedException();
}
}
}
|
using System;
using WeihanLi.Common.Helpers;
namespace WeihanLi.Common
{
/// <summary>
/// IdGenerator
/// </summary>
public interface IIdGenerator
{
/// <summary>
/// Generate a new id
/// </summary>
/// <returns>new id</returns>
string NewId();
}
/// <summary>
/// IdGenerator based on Guid
/// </summary>
public sealed class GuidIdGenerator : IIdGenerator
{
public GuidIdGenerator()
{
}
public static readonly GuidIdGenerator Instance = new GuidIdGenerator();
public string NewId() => Guid.NewGuid().ToString("N");
}
public sealed class SequentialGuidIdGenerator : IIdGenerator
{
public SequentialGuidIdGenerator()
{
}
public static readonly SequentialGuidIdGenerator Instance = new SequentialGuidIdGenerator();
public string NewId() => SequentialGuidGenerator.Create(SequentialGuidType.SequentialAsString).ToString("N");
}
/// <summary>
/// IdGenerator based on ObjectId
/// </summary>
public sealed class ObjectIdGenerator : IIdGenerator
{
public ObjectIdGenerator()
{
}
public static readonly ObjectIdGenerator Instance = new ObjectIdGenerator();
public string NewId() => ObjectId.GenerateNewStringId();
}
/// <summary>
/// Snowflake IdGenerator
/// WARNING: NotImplemented, do not use
/// </summary>
public sealed class SnowflakeIdGenerator : IIdGenerator
{
public string NewId()
{
throw new NotImplementedException();
}
}
}
|
mit
|
C#
|
1f9ef835e03c9fa2a6d72b908ec09836c44286e2
|
Use minute instead of month in logger timestamp
|
2gis/Winium.Desktop,zebraxxl/Winium.Desktop
|
src/Winium.Desktop.Driver/Logger.cs
|
src/Winium.Desktop.Driver/Logger.cs
|
namespace Winium.Desktop.Driver
{
#region using
using System.ComponentModel;
using NLog;
using NLog.Targets;
#endregion
internal static class Logger
{
#region Constants
private const string LayoutFormat = "${date:format=HH\\:mm\\:ss} [${level:uppercase=true}] ${message}";
#endregion
#region Static Fields
private static readonly NLog.Logger Log = LogManager.GetLogger("outerdriver");
#endregion
#region Public Methods and Operators
public static void Debug([Localizable(false)] string message, params object[] args)
{
Log.Debug(message, args);
}
public static void Error([Localizable(false)] string message, params object[] args)
{
Log.Error(message, args);
}
public static void Fatal([Localizable(false)] string message, params object[] args)
{
Log.Fatal(message, args);
}
public static void Info([Localizable(false)] string message, params object[] args)
{
Log.Info(message, args);
}
public static void TargetConsole(bool verbose)
{
var target = new ConsoleTarget { Layout = LayoutFormat };
NLog.Config.SimpleConfigurator.ConfigureForTargetLogging(target, verbose ? LogLevel.Debug : LogLevel.Fatal);
LogManager.ReconfigExistingLoggers();
}
public static void TargetFile(string fileName, bool verbose)
{
var target = new FileTarget { Layout = LayoutFormat, FileName = fileName };
NLog.Config.SimpleConfigurator.ConfigureForTargetLogging(target, verbose ? LogLevel.Debug : LogLevel.Info);
LogManager.ReconfigExistingLoggers();
}
public static void Trace([Localizable(false)] string message, params object[] args)
{
Log.Trace(message, args);
}
public static void Warn([Localizable(false)] string message, params object[] args)
{
Log.Warn(message, args);
}
#endregion
}
}
|
namespace Winium.Desktop.Driver
{
#region using
using System.ComponentModel;
using NLog;
using NLog.Targets;
#endregion
internal static class Logger
{
#region Constants
private const string LayoutFormat = "${date:format=HH\\:MM\\:ss} [${level:uppercase=true}] ${message}";
#endregion
#region Static Fields
private static readonly NLog.Logger Log = LogManager.GetLogger("outerdriver");
#endregion
#region Public Methods and Operators
public static void Debug([Localizable(false)] string message, params object[] args)
{
Log.Debug(message, args);
}
public static void Error([Localizable(false)] string message, params object[] args)
{
Log.Error(message, args);
}
public static void Fatal([Localizable(false)] string message, params object[] args)
{
Log.Fatal(message, args);
}
public static void Info([Localizable(false)] string message, params object[] args)
{
Log.Info(message, args);
}
public static void TargetConsole(bool verbose)
{
var target = new ConsoleTarget { Layout = LayoutFormat };
NLog.Config.SimpleConfigurator.ConfigureForTargetLogging(target, verbose ? LogLevel.Debug : LogLevel.Fatal);
LogManager.ReconfigExistingLoggers();
}
public static void TargetFile(string fileName, bool verbose)
{
var target = new FileTarget { Layout = LayoutFormat, FileName = fileName };
NLog.Config.SimpleConfigurator.ConfigureForTargetLogging(target, verbose ? LogLevel.Debug : LogLevel.Info);
LogManager.ReconfigExistingLoggers();
}
public static void Trace([Localizable(false)] string message, params object[] args)
{
Log.Trace(message, args);
}
public static void Warn([Localizable(false)] string message, params object[] args)
{
Log.Warn(message, args);
}
#endregion
}
}
|
mpl-2.0
|
C#
|
5065f6213e23904e1e0a2962a00b60a086dcdf60
|
Update Demo
|
sunkaixuan/SqlSugar
|
Src/Asp.Net/SqlServerTest/Program.cs
|
Src/Asp.Net/SqlServerTest/Program.cs
|
using OrmTest.PerformanceTesting;
using OrmTest.UnitTest;
using System;
namespace OrmTest
{
class Program
{
static void Main(string[] args)
{
//OldTestMain.Init();
//Demo
Demo0_SqlSugarClient.Init();
Demo1_Queryable.Init();
Demo2_Updateable.Init();
Democ_GobalFilter.Init();
DemoD_DbFirst.Init();
DemoE_CodeFirst.Init();
Demo5_SqlQueryable.Init();
Demo6_Queue.Init();
//Unit test
NewUnitTest.Init();
Console.WriteLine("all successfully.");
Console.ReadKey();
}
}
}
|
using OrmTest.PerformanceTesting;
using OrmTest.UnitTest;
using System;
namespace OrmTest
{
class Program
{
static void Main(string[] args)
{
//OldTestMain.Init();
//Demo
//Demo0_SqlSugarClient.Init();
//Demo1_Queryable.Init();
//Demo2_Updateable.Init();
//Democ_GobalFilter.Init();
//DemoD_DbFirst.Init();
//DemoE_CodeFirst.Init();
//Demo5_SqlQueryable.Init();
//Demo6_Queue.Init();
//Unit test
NewUnitTest.Init();
Console.WriteLine("all successfully.");
Console.ReadKey();
}
}
}
|
apache-2.0
|
C#
|
3a4d0a4a50c3ae6731a41e046fee2533fc51165e
|
Bump v1.0.17.2264
|
karronoli/tiny-sato
|
TinySato/Properties/AssemblyInfo.cs
|
TinySato/Properties/AssemblyInfo.cs
|
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// アセンブリに関する一般情報は以下の属性セットをとおして制御されます。
// アセンブリに関連付けられている情報を変更するには、
// これらの属性値を変更してください。
[assembly: AssemblyTitle("TinySato")]
[assembly: AssemblyDescription("You can construct and send SBPL packet to Sato printer. Sato printer is needed to be recognized by windows driver.")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("TinySato")]
[assembly: AssemblyCopyright("Copyright 2016 karronoli")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// ComVisible を false に設定すると、その型はこのアセンブリ内で COM コンポーネントから
// 参照不可能になります。COM からこのアセンブリ内の型にアクセスする場合は、
// その型の ComVisible 属性を true に設定してください。
[assembly: ComVisible(false)]
// このプロジェクトが COM に公開される場合、次の GUID が typelib の ID になります
[assembly: Guid("f56213db-fa1f-42da-b930-b642a56ee840")]
// アセンブリのバージョン情報は次の 4 つの値で構成されています:
//
// メジャー バージョン
// マイナー バージョン
// ビルド番号
// Revision
//
// すべての値を指定するか、下のように '*' を使ってビルドおよびリビジョン番号を
// 既定値にすることができます:
[assembly: AssemblyVersion("1.0.17.22647")]
[assembly: AssemblyFileVersion("1.0.17")]
|
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// アセンブリに関する一般情報は以下の属性セットをとおして制御されます。
// アセンブリに関連付けられている情報を変更するには、
// これらの属性値を変更してください。
[assembly: AssemblyTitle("TinySato")]
[assembly: AssemblyDescription("You can construct and send SBPL packet to Sato printer. Sato printer is needed to be recognized by windows driver.")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("TinySato")]
[assembly: AssemblyCopyright("Copyright 2016 karronoli")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// ComVisible を false に設定すると、その型はこのアセンブリ内で COM コンポーネントから
// 参照不可能になります。COM からこのアセンブリ内の型にアクセスする場合は、
// その型の ComVisible 属性を true に設定してください。
[assembly: ComVisible(false)]
// このプロジェクトが COM に公開される場合、次の GUID が typelib の ID になります
[assembly: Guid("f56213db-fa1f-42da-b930-b642a56ee840")]
// アセンブリのバージョン情報は次の 4 つの値で構成されています:
//
// メジャー バージョン
// マイナー バージョン
// ビルド番号
// Revision
//
// すべての値を指定するか、下のように '*' を使ってビルドおよびリビジョン番号を
// 既定値にすることができます:
[assembly: AssemblyVersion("1.0.17.*")]
[assembly: AssemblyFileVersion("1.0.17")]
|
apache-2.0
|
C#
|
70ad02d80ee76c9edb064eb5c77a7d125c93eb2a
|
Bump version to 1.4.0.0
|
priaonehaha/prontocms,priaonehaha/prontocms,xingh/prontocms,xingh/prontocms,xingh/prontocms,xingh/prontocms,priaonehaha/prontocms,xingh/prontocms,xingh/prontocms,priaonehaha/prontocms,priaonehaha/prontocms
|
Source/Pronto/Properties/AssemblyInfo.cs
|
Source/Pronto/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("Pronto")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("Pronto")]
[assembly: AssemblyCopyright("Copyright © Andrew Davey 2009")]
[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("1AF2C5AF-12AC-47d6-9300-774D35320570")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.4.0.0")]
[assembly: AssemblyFileVersion("1.4.0.0")]
|
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("Pronto")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("Pronto")]
[assembly: AssemblyCopyright("Copyright © Andrew Davey 2009")]
[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("1AF2C5AF-12AC-47d6-9300-774D35320570")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.3.0.0")]
[assembly: AssemblyFileVersion("1.3.0.0")]
|
mit
|
C#
|
c2a6374190dd236cf3c639957a7a6025e66b9f75
|
Package Update #CHANGE: Pushed AdamsLair.WinForms 1.1.3
|
AdamsLair/winforms
|
WinForms/Properties/AssemblyInfo.cs
|
WinForms/Properties/AssemblyInfo.cs
|
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// Allgemeine Informationen über eine Assembly werden über die folgenden
// Attribute gesteuert. Ändern Sie diese Attributwerte, um die Informationen zu ändern,
// die mit einer Assembly verknüpft sind.
[assembly: AssemblyTitle("AdamsLair.WinForms")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("AdamsLair.WinForms")]
[assembly: AssemblyCopyright("")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Durch Festlegen von ComVisible auf "false" werden die Typen in dieser Assembly unsichtbar
// für COM-Komponenten. Wenn Sie auf einen Typ in dieser Assembly von
// COM zugreifen müssen, legen Sie das ComVisible-Attribut für diesen Typ auf "true" fest.
[assembly: ComVisible(false)]
// Die folgende GUID bestimmt die ID der Typbibliothek, wenn dieses Projekt für COM verfügbar gemacht wird
[assembly: Guid("735ee5dc-8c18-4a06-8e64-2f172ddd01cc")]
// Versionsinformationen für eine Assembly bestehen aus den folgenden vier Werten:
//
// Hauptversion
// Nebenversion
// Buildnummer
// Revision
//
// Sie können alle Werte angeben oder die standardmäßigen Build- und Revisionsnummern
// übernehmen, indem Sie "*" eingeben:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.1.3")]
|
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// Allgemeine Informationen über eine Assembly werden über die folgenden
// Attribute gesteuert. Ändern Sie diese Attributwerte, um die Informationen zu ändern,
// die mit einer Assembly verknüpft sind.
[assembly: AssemblyTitle("AdamsLair.WinForms")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("AdamsLair.WinForms")]
[assembly: AssemblyCopyright("")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Durch Festlegen von ComVisible auf "false" werden die Typen in dieser Assembly unsichtbar
// für COM-Komponenten. Wenn Sie auf einen Typ in dieser Assembly von
// COM zugreifen müssen, legen Sie das ComVisible-Attribut für diesen Typ auf "true" fest.
[assembly: ComVisible(false)]
// Die folgende GUID bestimmt die ID der Typbibliothek, wenn dieses Projekt für COM verfügbar gemacht wird
[assembly: Guid("735ee5dc-8c18-4a06-8e64-2f172ddd01cc")]
// Versionsinformationen für eine Assembly bestehen aus den folgenden vier Werten:
//
// Hauptversion
// Nebenversion
// Buildnummer
// Revision
//
// Sie können alle Werte angeben oder die standardmäßigen Build- und Revisionsnummern
// übernehmen, indem Sie "*" eingeben:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.1.2")]
|
mit
|
C#
|
aad2e5906025920c15b35c76b05a91518cdfd070
|
Fix for incorrect expectation of guid string
|
InishTech/Sp.Api
|
Sp.Portal.Acceptance/LandingPageFacts.cs
|
Sp.Portal.Acceptance/LandingPageFacts.cs
|
namespace Sp.Portal.Acceptance
{
using System.Net;
using HtmlAgilityPack;
using RestSharp;
using Sp.Portal.Acceptance.Wrappers;
using Xunit;
using Xunit.Extensions;
public static class LandingPageFacts
{
[Theory, PortalData]
public static void LandingPageShouldReturnHtml( SpPortalApi portalApi)
{
var request = new RestRequest( string.Empty );
request.AddHeader( "Accept", "text/html" );
var response = portalApi.Execute( request );
Assert.Equal( HttpStatusCode.OK, response.StatusCode );
Assert.True( response.ContentType.StartsWith( "text/html" ) );
}
[Theory, PortalData]
public static void LandingPageShouldContainSignedCustomerId( SpPortalApi portalApi )
{
var request = new RestRequest( string.Empty );
request.AddHeader( "Accept", "text/html" );
var response = portalApi.Execute( request );
Assert.Equal( HttpStatusCode.OK, response.StatusCode );
Assert.True( response.ContentType.StartsWith( "text/html" ) );
HtmlDocument doc = new HtmlDocument();
doc.LoadHtml( response.Content );
var node = doc.DocumentNode.SelectSingleNode( "//span[@data-claimid='customerid']" );
Assert.NotNull( node );
Assert.Contains( "bff714f1-3c88-40e7-9e78-a73c041ac8eb", node.InnerText );
}
[Theory, PortalData]
public static void SignoffShouldRedirectBackToSts( SpPortalApi portalApi )
{
LandingPageShouldReturnHtml( portalApi );
var result = portalApi.SignOff();
Assert.Equal( HttpStatusCode.OK, result.StatusCode );
Assert.Contains( "Sp.Auth.Web", result.ResponseUri.AbsolutePath );
}
}
}
|
namespace Sp.Portal.Acceptance
{
using System.Net;
using HtmlAgilityPack;
using RestSharp;
using Sp.Portal.Acceptance.Wrappers;
using Xunit;
using Xunit.Extensions;
public static class LandingPageFacts
{
[Theory, PortalData]
public static void LandingPageShouldReturnHtml( SpPortalApi portalApi)
{
var request = new RestRequest( string.Empty );
request.AddHeader( "Accept", "text/html" );
var response = portalApi.Execute( request );
Assert.Equal( HttpStatusCode.OK, response.StatusCode );
Assert.True( response.ContentType.StartsWith( "text/html" ) );
}
[Theory, PortalData]
public static void LandingPageShouldContainSignedCustomerId( SpPortalApi portalApi )
{
var request = new RestRequest( string.Empty );
request.AddHeader( "Accept", "text/html" );
var response = portalApi.Execute( request );
Assert.Equal( HttpStatusCode.OK, response.StatusCode );
Assert.True( response.ContentType.StartsWith( "text/html" ) );
HtmlDocument doc = new HtmlDocument();
doc.LoadHtml( response.Content );
var node = doc.DocumentNode.SelectSingleNode( "//span[@data-claimid='customerid']" );
Assert.NotNull( node );
Assert.Contains( "BFF714F1-3C88-40E7-9E78-A73C041AC8EB", node.InnerText );
}
[Theory, PortalData]
public static void SignoffShouldRedirectBackToSts( SpPortalApi portalApi )
{
LandingPageShouldReturnHtml( portalApi );
var result = portalApi.SignOff();
Assert.Equal( HttpStatusCode.OK, result.StatusCode );
Assert.Contains( "Sp.Auth.Web", result.ResponseUri.AbsolutePath );
}
}
}
|
bsd-3-clause
|
C#
|
27c7409407ff80d84aaeaa45c083ff2d23f13417
|
Update ValuesController.cs
|
bigfont/webapi-cors
|
CORS/Controllers/ValuesController.cs
|
CORS/Controllers/ValuesController.cs
|
using System.Collections.Generic;
using System.Web.Http;
using System.Web.Http.Cors;
namespace CORS.Controllers
{
public class ValuesController : ApiController
{
// GET api/values
public IEnumerable<string> Get()
{
return new string[] { "This is a CORS request.", "That works from any origin." };
}
// GET api/values/another
[HttpGet]
[EnableCors(origins:"http://www.bigfont.ca", headers:"*", methods: "*")]
public IEnumerable<string> Another()
{
return new string[] { "This is a CORS request.", "It works only from www.bigfont.ca." };
}
}
}
|
using System.Collections.Generic;
using System.Web.Http;
using System.Web.Http.Cors;
namespace CORS.Controllers
{
public class ValuesController : ApiController
{
// GET api/values
public IEnumerable<string> Get()
{
return new string[] { "This is a CORS request.", "That works from any origin." };
}
// GET api/values/another
[HttpGet]
[EnableCors(origins:"http://www.bigfont.ca", headers:"*", methods: "*")]
public IEnumerable<string> Another()
{
return new string[] { "This is a CORS request.", "It works only from www.bigfont.ca." };
}
public class EstimateQuery
{
public string username { get; set; }
}
public IHttpActionResult GetTitleEstimate([FromUri] EstimateQuery query)
{
// All the values in "query" are null or zero
// Do some stuff with query if there were anything to do
if(query != null && query.username != null)
{
return Ok(query.username);
}
else
{
return Ok("Add a username!");
}
}
}
}
|
mit
|
C#
|
49c26f1ce5ae668a57adac9f63c2b66c8a5df289
|
fix await usage in library code
|
AerisG222/NDCRaw
|
src/NDCRaw/DCRaw.cs
|
src/NDCRaw/DCRaw.cs
|
using System;
using System.ComponentModel;
using System.IO;
using System.Diagnostics;
using System.Threading.Tasks;
using Medallion.Shell;
namespace NDCRaw
{
public class DCRaw
{
public DCRawOptions Options { get; private set; }
public DCRaw(DCRawOptions options)
{
Options = options;
}
public DCRawResult Convert(string srcPath)
{
return ConvertAsync(srcPath).Result;
}
public Task<DCRawResult> ConvertAsync(string srcPath)
{
if(!File.Exists(srcPath))
{
throw new FileNotFoundException("Please make sure the raw image exists.", srcPath);
}
return RunProcessAsync(srcPath);
}
async Task<DCRawResult> RunProcessAsync(string fileName)
{
var ext = Options.Format == Format.Ppm ? ".ppm" : ".tiff";
var output = fileName.Replace(Path.GetExtension(fileName), ext);
try
{
var cmd = Command.Run(Options.DCRawPath, Options.GetArguments(fileName));
await cmd.Task.ConfigureAwait(false);
return new DCRawResult {
ExitCode = cmd.Result.ExitCode,
StandardOutput = cmd.StandardOutput.ReadToEnd(),
StandardError = cmd.StandardError.ReadToEnd(),
OutputFilename = output
};
}
catch (Win32Exception ex)
{
throw new Exception("Error when trying to start the dcraw process. Please make sure dcraw is installed, and its path is properly specified in the options.", ex);
}
}
}
}
|
using System;
using System.ComponentModel;
using System.IO;
using System.Diagnostics;
using System.Threading.Tasks;
using Medallion.Shell;
namespace NDCRaw
{
public class DCRaw
{
public DCRawOptions Options { get; private set; }
public DCRaw(DCRawOptions options)
{
Options = options;
}
public DCRawResult Convert(string srcPath)
{
return ConvertAsync(srcPath).Result;
}
public Task<DCRawResult> ConvertAsync(string srcPath)
{
if(!File.Exists(srcPath))
{
throw new FileNotFoundException("Please make sure the raw image exists.", srcPath);
}
return RunProcessAsync(srcPath);
}
async Task<DCRawResult> RunProcessAsync(string fileName)
{
var ext = Options.Format == Format.Ppm ? ".ppm" : ".tiff";
var output = fileName.Replace(Path.GetExtension(fileName), ext);
try
{
var cmd = Command.Run(Options.DCRawPath, Options.GetArguments(fileName));
await cmd.Task;
return new DCRawResult {
ExitCode = cmd.Result.ExitCode,
StandardOutput = cmd.StandardOutput.ReadToEnd(),
StandardError = cmd.StandardError.ReadToEnd(),
OutputFilename = output
};
}
catch (Win32Exception ex)
{
throw new Exception("Error when trying to start the dcraw process. Please make sure dcraw is installed, and its path is properly specified in the options.", ex);
}
}
}
}
|
mit
|
C#
|
8bc5f884ecd52435eb6153cec8110d17598ce6a7
|
Fix local environmental issue.
|
joj/cecil,saynomoo/cecil,sailro/cecil,fnajera-rac-de/cecil,xen2/cecil,jbevain/cecil,kzu/cecil,gluck/cecil,mono/cecil,ttRevan/cecil,SiliconStudio/Mono.Cecil,cgourlay/cecil,furesoft/cecil
|
Test/Mono.Cecil.Tests/BaseTestFixture.cs
|
Test/Mono.Cecil.Tests/BaseTestFixture.cs
|
using System;
using System.IO;
using System.Reflection;
using NUnit.Framework;
using Mono.Cecil.PE;
namespace Mono.Cecil.Tests {
public abstract class BaseTestFixture {
public static string GetResourcePath (string name, Assembly assembly)
{
return Path.Combine (FindResourcesDirectory (assembly), name);
}
public static string GetAssemblyResourcePath (string name, Assembly assembly)
{
return GetResourcePath (Path.Combine ("assemblies", name), assembly);
}
public static string GetCSharpResourcePath (string name, Assembly assembly)
{
return GetResourcePath (Path.Combine ("cs", name), assembly);
}
public static string GetILResourcePath (string name, Assembly assembly)
{
return GetResourcePath (Path.Combine ("il", name), assembly);
}
public static ModuleDefinition GetResourceModule (string name)
{
return ModuleDefinition.ReadModule (GetAssemblyResourcePath (name, typeof (BaseTestFixture).Assembly));
}
public static ModuleDefinition GetResourceModule (string name, ReadingMode mode)
{
return ModuleDefinition.ReadModule (GetAssemblyResourcePath (name, typeof (BaseTestFixture).Assembly), new ReaderParameters (mode));
}
internal static Image GetResourceImage (string name)
{
using (var fs = new FileStream (GetAssemblyResourcePath (name, typeof (BaseTestFixture).Assembly), FileMode.Open, FileAccess.Read))
return ImageReader.ReadImageFrom (fs);
}
public static ModuleDefinition GetCurrentModule ()
{
return ModuleDefinition.ReadModule (typeof (BaseTestFixture).Module.FullyQualifiedName);
}
public static string FindResourcesDirectory (Assembly assembly)
{
var path = Path.GetDirectoryName (new Uri (assembly.CodeBase).LocalPath);
while (!Directory.Exists (Path.Combine (path, "Resources"))) {
var old = path;
path = Path.GetDirectoryName (path);
Assert.AreNotEqual (old, path);
}
return Path.Combine (path, "Resources");
}
}
}
|
using System;
using System.IO;
using System.Reflection;
using NUnit.Framework;
using Mono.Cecil.PE;
namespace Mono.Cecil.Tests {
public abstract class BaseTestFixture {
public static string GetResourcePath (string name, Assembly assembly)
{
return Path.Combine (FindResourcesDirectory (assembly), name);
}
public static string GetAssemblyResourcePath (string name, Assembly assembly)
{
return GetResourcePath (Path.Combine ("assemblies", name), assembly);
}
public static string GetCSharpResourcePath (string name, Assembly assembly)
{
return GetResourcePath (Path.Combine ("cs", name), assembly);
}
public static string GetILResourcePath (string name, Assembly assembly)
{
return GetResourcePath (Path.Combine ("il", name), assembly);
}
public static ModuleDefinition GetResourceModule (string name)
{
return ModuleDefinition.ReadModule (GetAssemblyResourcePath (name, typeof (BaseTestFixture).Assembly));
}
public static ModuleDefinition GetResourceModule (string name, ReadingMode mode)
{
return ModuleDefinition.ReadModule (GetAssemblyResourcePath (name, typeof (BaseTestFixture).Assembly), new ReaderParameters (mode));
}
internal static Image GetResourceImage (string name)
{
using (var fs = new FileStream (GetAssemblyResourcePath (name, typeof (BaseTestFixture).Assembly), FileMode.Open, FileAccess.Read))
return ImageReader.ReadImageFrom (fs);
}
public static ModuleDefinition GetCurrentModule ()
{
return ModuleDefinition.ReadModule (typeof (BaseTestFixture).Module.FullyQualifiedName);
}
public static string FindResourcesDirectory (Assembly assembly)
{
var path = Path.GetDirectoryName (new Uri (assembly.CodeBase).AbsolutePath);
while (!Directory.Exists (Path.Combine (path, "Resources"))) {
var old = path;
path = Path.GetDirectoryName (path);
Assert.AreNotEqual (old, path);
}
return Path.Combine (path, "Resources");
}
}
}
|
mit
|
C#
|
ebebb15b43c31d77f5f97f04d32b996973ce7223
|
enable tests to fix TeamCity error
|
ralbu/TeamCityAzure
|
MobileService/Source/Tests/Services/UserServiceTest.cs
|
MobileService/Source/Tests/Services/UserServiceTest.cs
|
using Common;
using UserManagement.Controllers;
using UserManagement.Services;
using Xunit;
namespace Tests.Services
{
public class UserServiceTest
{
private readonly IUserService _userService = new UserService();
public UserServiceTest()
{
_userService.AddUser(new User
{
Id = 1,
Name = "user name 1"
});
}
[Fact]
public void GetUsers_ShouldReturnUsers()
{
Assert.True(_userService.GetUsers().Count > 0);
}
[Fact]
public void AddUser_ShouldAddUser()
{
var totalUsers = _userService.GetUsers().Count;
_userService.AddUser(new User
{
Id = 2,
Name = "user name 2"
});
Assert.Equal(totalUsers + 1, _userService.GetUsers().Count);
}
[Fact]
public void GetUserById_ShouldReturnUser()
{
_userService.AddUser(new User
{
Id = 3,
Name = "my user"
});
var user = _userService.GetUserById(3);
Assert.Equal("my user", user.Name);
}
}
}
|
using Common;
using UserManagement.Controllers;
using UserManagement.Services;
//using Xunit;
namespace Tests.Services
{
public class UserServiceTest
{
/*
private readonly IUserService _userService = new UserService();
public UserServiceTest()
{
_userService.AddUser(new User
{
Id = 1,
Name = "user name 1"
});
}
[Fact]
public void GetUsers_ShouldReturnUsers()
{
Assert.True(_userService.GetUsers().Count > 0);
}
[Fact]
public void AddUser_ShouldAddUser()
{
var totalUsers = _userService.GetUsers().Count;
_userService.AddUser(new User
{
Id = 2,
Name = "user name 2"
});
Assert.Equal(totalUsers + 1, _userService.GetUsers().Count);
}
[Fact]
public void GetUserById_ShouldReturnUser()
{
_userService.AddUser(new User
{
Id = 3,
Name = "my user"
});
var user = _userService.GetUserById(3);
Assert.Equal("my user", user.Name);
} */
}
}
|
mit
|
C#
|
1b86f262404e8eac62e703821b8250021afe870e
|
add namesspace, usings
|
Pondidum/AutoMapper.RestExtensions
|
AutoMapper.RestExtensions.cs
|
AutoMapper.RestExtensions.cs
|
using System;
using System.Collections.Generic;
namespace AutoMapper.Rest
{
public static class Extensions
{
public static IMappingExpression<TSource, TDestination> Link<TSource, TDestination>(this IMappingExpression<TSource, TDestination> mapping, string key, Func<TSource, string> createLink)
where TDestination : IRestLinked
{
return mapping.AfterMap((u, r) => r.Links[key] = createLink(u));
}
}
public interface IRestLinked
{
Dictionary<string, string> Links { get; set; }
}
}
|
public static class Extensions
{
public static IMappingExpression<TSource, TDestination> Link<TSource, TDestination>(this IMappingExpression<TSource, TDestination> mapping, string key, Func<TSource, string> createLink)
where TDestination : IRestLinked
{
return mapping.AfterMap((u, r) => r.Links[key] = createLink(u));
}
}
public interface IRestLinked
{
Dictionary<string, string> Links { get; set; }
}
|
lgpl-2.1
|
C#
|
2c16e03fe3ea414febceaff81c7be2fec1701972
|
update to v2
|
Fody/MethodTimer
|
CommonAssemblyInfo.cs
|
CommonAssemblyInfo.cs
|
using System.Reflection;
[assembly: AssemblyTitle("MethodTimer")]
[assembly: AssemblyProduct("MethodTimer")]
[assembly: AssemblyVersion("2.0.0")]
|
using System.Reflection;
[assembly: AssemblyTitle("MethodTimer")]
[assembly: AssemblyProduct("MethodTimer")]
[assembly: AssemblyVersion("1.19.1")]
[assembly: AssemblyFileVersion("1.19.1")]
|
mit
|
C#
|
6e27b1e393a301cca47d2c2fb7378a2953e17aa5
|
add missing return statement
|
DasAllFolks/SharpGraphs
|
Graph/Graph.cs
|
Graph/Graph.cs
|
using System;
namespace Graph
{
public class Vertex
{
private bool hasLabel;
private string label;
public Vertex ()
{
}
// XXXX: Remind self how to link to private field?
public bool HasLabel
{
get;
set;
}
public string Label
{
get
{
if (!this.hasLabel)
{
throw NoLabelFoundException("This vertex is unlabeled.");
}
return this.label;
}
set;
}
public class NoLabelFoundException : Exception
{
}
}
public class Edge
{
public Edge ()
{
}
}
public class Graph
{
public Graph ()
{
}
public void AddVertex ()
{
}
public void AddVertex (int label)
{
}
public void AddVertex (string label)
{
}
}
|
using System;
namespace Graph
{
public class Vertex
{
private bool hasLabel;
private string label;
public Vertex ()
{
}
// XXXX: Remind self how to link to private field?
public bool HasLabel
{
get;
set;
}
public string Label
{
get
{
if (!this.hasLabel)
{
throw NoLabelFoundException("This vertex is unlabeled.");
}
}
set;
}
public class NoLabelFoundException : Exception
{
}
}
public class Edge
{
public Edge ()
{
}
}
public class Graph
{
public Graph ()
{
}
public void AddVertex ()
{
}
public void AddVertex (int label)
{
}
public void AddVertex (string label)
{
}
}
|
apache-2.0
|
C#
|
dc051a8b7992ebf6f7a7b8f08da6b16ea8b97ee8
|
add gameplay leaderboard config
|
peppy/osu,ppy/osu,peppy/osu,peppy/osu,ppy/osu,ppy/osu
|
osu.Game/Overlays/Settings/Sections/Gameplay/HUDSettings.cs
|
osu.Game/Overlays/Settings/Sections/Gameplay/HUDSettings.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.Framework.Allocation;
using osu.Framework.Graphics;
using osu.Framework.Localisation;
using osu.Game.Configuration;
using osu.Game.Localisation;
namespace osu.Game.Overlays.Settings.Sections.Gameplay
{
public class HUDSettings : SettingsSubsection
{
protected override LocalisableString Header => GameplaySettingsStrings.HUDHeader;
[BackgroundDependencyLoader]
private void load(OsuConfigManager config)
{
Children = new Drawable[]
{
new SettingsEnumDropdown<HUDVisibilityMode>
{
LabelText = GameplaySettingsStrings.HUDVisibilityMode,
Current = config.GetBindable<HUDVisibilityMode>(OsuSetting.HUDVisibilityMode)
},
new SettingsCheckbox
{
ClassicDefault = false,
LabelText = GameplaySettingsStrings.ShowHealthDisplayWhenCantFail,
Current = config.GetBindable<bool>(OsuSetting.ShowHealthDisplayWhenCantFail),
Keywords = new[] { "hp", "bar" }
},
new SettingsCheckbox
{
LabelText = GameplaySettingsStrings.AlwaysShowKeyOverlay,
Current = config.GetBindable<bool>(OsuSetting.KeyOverlay),
Keywords = new[] { "counter" },
},
new SettingsCheckbox
{
LabelText = GameplaySettingsStrings.AlwaysShowGameplayLeaderboard,
Current = config.GetBindable<bool>(OsuSetting.GameplayLeaderboard),
Keywords = new[] { "leaderboard", "score" },
},
};
}
}
}
|
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
#nullable disable
using osu.Framework.Allocation;
using osu.Framework.Graphics;
using osu.Framework.Localisation;
using osu.Game.Configuration;
using osu.Game.Localisation;
namespace osu.Game.Overlays.Settings.Sections.Gameplay
{
public class HUDSettings : SettingsSubsection
{
protected override LocalisableString Header => GameplaySettingsStrings.HUDHeader;
[BackgroundDependencyLoader]
private void load(OsuConfigManager config)
{
Children = new Drawable[]
{
new SettingsEnumDropdown<HUDVisibilityMode>
{
LabelText = GameplaySettingsStrings.HUDVisibilityMode,
Current = config.GetBindable<HUDVisibilityMode>(OsuSetting.HUDVisibilityMode)
},
new SettingsCheckbox
{
ClassicDefault = false,
LabelText = GameplaySettingsStrings.ShowHealthDisplayWhenCantFail,
Current = config.GetBindable<bool>(OsuSetting.ShowHealthDisplayWhenCantFail),
Keywords = new[] { "hp", "bar" }
},
new SettingsCheckbox
{
LabelText = GameplaySettingsStrings.AlwaysShowKeyOverlay,
Current = config.GetBindable<bool>(OsuSetting.KeyOverlay),
Keywords = new[] { "counter" },
},
};
}
}
}
|
mit
|
C#
|
862eb38d33368b390235e8071013905249b5e527
|
add gui to main class
|
AlexanderDzhoganov/NoMoreGrind
|
NoMoreGrind.cs
|
NoMoreGrind.cs
|
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using UnityEngine;
using Upgradeables;
using System.Reflection;
namespace NoMoreGrind
{
[KSPAddon(KSPAddon.Startup.SpaceCentre, true)]
public class NoMoreGrind : MonoBehaviour
{
public void Awake()
{
print("NoMoreGrind: Initialized");
}
public void Start()
{
List<FieldInfo> fields = new List<FieldInfo>
(
typeof(UpgradeableFacility).GetFields
(
BindingFlags.NonPublic | BindingFlags.Instance
)
);
var levelField =
new List<FieldInfo>(
fields.Where<FieldInfo>(
f => f.FieldType.Equals(typeof(UpgradeableObject.UpgradeLevel)))).First();
foreach (UpgradeableFacility facility in GameObject.FindObjectsOfType<UpgradeableFacility>())
{
UpgradeableObject.UpgradeLevel level = (UpgradeableObject.UpgradeLevel)levelField.GetValue(facility);
level.levelCost *= 0.1f;
}
}
public void LoadState(ConfigNode configNode)
{
gui.LoadConfig(configNode);
}
public void SaveState(ConfigNode configNode)
{
gui.SaveConfig(configNode);
}
void OnGUI()
{
gui.OnGUI();
}
private GUI gui = new GUI();
public void OnDestroy()
{
print("NoMoreGrind: Deinitialized");
}
}
}
|
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using UnityEngine;
using Upgradeables;
using System.Reflection;
namespace NoMoreGrind
{
[KSPAddon(KSPAddon.Startup.SpaceCentre, true)]
public class NoMoreGrind : MonoBehaviour
{
public void Awake()
{
print("NoMoreGrind: Initialized");
}
public void Start()
{
List<FieldInfo> fields = new List<FieldInfo>
(
typeof(UpgradeableFacility).GetFields
(
BindingFlags.NonPublic | BindingFlags.Instance
)
);
var levelField =
new List<FieldInfo>(
fields.Where<FieldInfo>(
f => f.FieldType.Equals(typeof(UpgradeableObject.UpgradeLevel)))).First();
foreach (UpgradeableFacility facility in GameObject.FindObjectsOfType<UpgradeableFacility>())
{
UpgradeableObject.UpgradeLevel level = (UpgradeableObject.UpgradeLevel)levelField.GetValue(facility);
level.levelCost *= 0.1f;
}
}
public void OnDestroy()
{
print("NoMoreGrind: Deinitialized");
}
}
}
|
mit
|
C#
|
2d7d4038d71f435fe1908662e176662cdf5c2f90
|
添加注释。
|
yaukeywang/2DPlatformer-SLua,lingkeyang/2DPlatformer-SLua,lingkeyang/2DPlatformer-SLua
|
Assets/Game/Scripts/Editor/CustomExportTypeToLua.cs
|
Assets/Game/Scripts/Editor/CustomExportTypeToLua.cs
|
/**
* The custom export lua type class, this is editor class.
*
* @filename CustomExportTypeToLua.cs
* @copyright Copyright (c) 2015 Yaukey/yaukeywang/WangYaoqi (yaukeywang@gmail.com) all rights reserved.
* @license The MIT License (MIT)
* @author Yaukey
* @date 2016-03-16
*/
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using SLua;
// The custom export lua type class.
public class CustomExportTypeToLua : ICustomExportPost
{
/**
* Add custom class type to export.
*
* @param LuaCodeGen.ExportGenericDelegate cAdd - The type adder delegate.
* @return void.
*/
public static void OnAddCustomClass(LuaCodeGen.ExportGenericDelegate cAdd)
{
// add your custom class here
// add( type, typename)
// type is what you want to export
// typename used for simplify generic type name or rename, like List<int> named to "ListInt", if not a generic type keep typename as null or rename as new type name.
//cAdd(typeof(string), "String");
cAdd(typeof(GUIElement), null);
cAdd(typeof(GUIText), null);
cAdd(typeof(GUITexture), null);
}
/**
* Add custom assembly type to export.
*
* @param ref List<string> cList - The name list of custom assembly to load.
* @return void.
*/
public static void OnAddCustomAssembly(ref List<string> cList)
{
// add your custom assembly here
// you can build a dll for 3rd library like ngui titled assembly name "NGUI", put it in Assets folder
// add its name into list, slua will generate all exported interface automatically for you.
//cList.Add("NGUI");
}
}
|
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using SLua;
public class CustomExportTypeToLua : ICustomExportPost
{
public static void OnAddCustomClass(LuaCodeGen.ExportGenericDelegate cAdd)
{
// add your custom class here
// add( type, typename)
// type is what you want to export
// typename used for simplify generic type name or rename, like List<int> named to "ListInt", if not a generic type keep typename as null or rename as new type name.
//cAdd(typeof(string), "String");
cAdd(typeof(GUIElement), null);
cAdd(typeof(GUIText), null);
cAdd(typeof(GUITexture), null);
}
public static void OnAddCustomAssembly(ref List<string> cList)
{
// add your custom assembly here
// you can build a dll for 3rd library like ngui titled assembly name "NGUI", put it in Assets folder
// add its name into list, slua will generate all exported interface automatically for you
//cList.Add("NGUI");
}
}
|
mit
|
C#
|
400b1885f23581068133ea37e27d948078e9e5ac
|
test running Spec class fails after last change on name
|
mattflo/NSpec,mattflo/NSpec,BennieCopeland/NSpec,mattflo/NSpec,nspec/NSpec,BennieCopeland/NSpec,nspec/NSpec,mattflo/NSpec
|
NSpecSpecs/describe_RunningSpecs/Exceptions/when_method_level_context_contains_exception.cs
|
NSpecSpecs/describe_RunningSpecs/Exceptions/when_method_level_context_contains_exception.cs
|
using NSpec;
using NSpecSpecs.WhenRunningSpecs;
using NUnit.Framework;
namespace NSpecSpecs.describe_RunningSpecs.Exceptions
{
[TestFixture]
[Category("RunningSpecs")]
public class when_method_level_context_contains_exception : when_running_specs
{
public class SpecClass : nspec
{
public void method_level_context()
{
DoSomethingThatThrows();
before = () => { };
it["should pass"] = () => { };
}
void DoSomethingThatThrows()
{
throw new KnownException("Bare code threw exception");
}
}
[SetUp]
public void setup()
{
Run(typeof(SpecClass));
}
[Test]
public void example_named_after_context_should_fail_with_same_exception()
{
var example = TheExample("Method context body throws an exception of type KnownException");
example.Exception.GetType().should_be(typeof(KnownException));
}
}
}
|
using NSpec;
using NSpecSpecs.WhenRunningSpecs;
using NUnit.Framework;
namespace NSpecSpecs.describe_RunningSpecs.Exceptions
{
[TestFixture]
[Category("RunningSpecs")]
public class when_method_level_context_contains_exception : when_running_specs
{
public class SpecClass : nspec
{
public void method_level_context()
{
DoSomethingThatThrows();
before = () => { };
it["should pass"] = () => { };
}
void DoSomethingThatThrows()
{
throw new KnownException("Bare code threw exception");
}
}
[SetUp]
public void setup()
{
Run(typeof(SpecClass));
}
[Test]
public void example_named_after_context_should_fail_with_same_exception()
{
var example = TheExample("method_level_context throws an exception of type KnownException");
example.Exception.GetType().should_be(typeof(KnownException));
}
}
}
|
mit
|
C#
|
4f8f376a72697b69319f7c9231a3a0ccf15d82d3
|
Change error text.
|
LykkeCity/CompetitionPlatform,LykkeCity/CompetitionPlatform,LykkeCity/CompetitionPlatform
|
src/CompetitionPlatform/Views/Shared/ProjectNotFound.cshtml
|
src/CompetitionPlatform/Views/Shared/ProjectNotFound.cshtml
|
@{
ViewData["Title"] = "Project Not Found";
}
<br />
<br />
<div class="container">
<h1 class="text-danger">Error.</h1>
<h2 class="text-danger">Project not found.</h2>
<p>
Project with this id was not found.
</p>
</div>
|
@{
ViewData["Title"] = "Access Denied";
}
<br />
<br />
<div class="container">
<h1 class="text-danger">Error.</h1>
<h2 class="text-danger">Project not found.</h2>
<p>
Project with this id was not found.
</p>
</div>
|
mit
|
C#
|
05802f073af6b0b715620609c9729ab612b9ad99
|
Fix EF sql column type unit
|
massimodipaolo/bom-core
|
src/modules/Data.EF/AppDbContext.cs
|
src/modules/Data.EF/AppDbContext.cs
|
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Reflection;
using System.Threading.Tasks;
namespace core.Extensions.Data
{
public class AppDbContext : DbContext
{
static AppDbContext()
{
}
public AppDbContext(DbContextOptions<AppDbContext> options) : base(options) { }
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
var tKeys = new KeyValuePair<Type, int>[] {
new KeyValuePair<Type,int>(typeof(IEntity<int>),11),
new KeyValuePair<Type,int>(typeof(IEntity<long>),20),
new KeyValuePair<Type, int>(typeof(IEntity<Guid>),36),
new KeyValuePair<Type, int>(typeof(IEntity<string>),255)
};
foreach (KeyValuePair<Type, int> tKey in tKeys)
{
foreach (Type type in Base.Util.GetAllTypesOf(tKey.Key)/*.Where(_ => _ != typeof(Entity<Guid>))*/)
{
try
{
modelBuilder.Entity(type)
.ToTable(type.Name)
.Property("Id").HasColumnName("Id")
.IsUnicode(false)
.HasMaxLength(tKey.Value)
//.HasColumnType(tKey.Value)
.HasDefaultValue()
;
}
catch { }
}
}
}
}
}
|
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Reflection;
using System.Threading.Tasks;
namespace core.Extensions.Data
{
public class AppDbContext : DbContext
{
static AppDbContext()
{
}
public AppDbContext(DbContextOptions<AppDbContext> options) : base(options) { }
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
var tKeys = new KeyValuePair<Type, string>[] {
new KeyValuePair<Type,string>(typeof(IEntity<int>),"int"),
new KeyValuePair<Type,string>(typeof(IEntity<long>),"bigint"),
new KeyValuePair<Type, string>(typeof(IEntity<Guid>),"uniqueidentifier"),
new KeyValuePair<Type, string>(typeof(IEntity<string>),"varchar")
};
foreach (KeyValuePair<Type, string> tKey in tKeys)
{
foreach (Type type in Base.Util.GetAllTypesOf(tKey.Key)/*.Where(_ => _ != typeof(Entity<Guid>))*/)
{
try
{
modelBuilder.Entity(type)
.ToTable(type.Name)
.Property("Id").HasColumnName("Id")
.HasColumnType(tKey.Value)
.HasDefaultValue()
;
}
catch { }
}
}
}
}
}
|
mit
|
C#
|
ee12f0f2bf20dbb471d0c0b870c866c3fcfd5a3b
|
Fix SSPG button
|
sergeyshushlyapin/Sitecore-Instance-Manager,Brad-Christie/Sitecore-Instance-Manager,Sitecore/Sitecore-Instance-Manager
|
src/SIM.Tool.Windows/MainWindowComponents/OpenSSPGButton.cs
|
src/SIM.Tool.Windows/MainWindowComponents/OpenSSPGButton.cs
|
namespace SIM.Tool.Windows.MainWindowComponents
{
using System.Windows;
using SIM.Instances;
using SIM.Tool.Base.Plugins;
using JetBrains.Annotations;
using SIM.Core;
[UsedImplicitly]
public class OpenSSPGButton : IMainWindowButton
{
#region Public methods
public bool IsEnabled(Window mainWindow, Instance instance)
{
return true;
}
public void OnClick(Window mainWindow, Instance instance)
{
CoreApp.RunApp("iexplore", "http://dl.sitecore.net/updater/sspg/SSPG.application");
}
#endregion
}
}
|
namespace SIM.Tool.Windows.MainWindowComponents
{
using System.Windows;
using SIM.Instances;
using SIM.Tool.Base.Plugins;
using JetBrains.Annotations;
using SIM.Core;
[UsedImplicitly]
public class OpenSspgButton : IMainWindowButton
{
#region Public methods
public bool IsEnabled(Window mainWindow, Instance instance)
{
return true;
}
public void OnClick(Window mainWindow, Instance instance)
{
CoreApp.RunApp("iexplore", "http://dl.sitecore.net/updater/sspg/SSPG.application");
}
#endregion
}
}
|
mit
|
C#
|
16268d05889f3c8a8b0883fc3ed98ce214793913
|
Remove unused broker parameter
|
bjartebore/azure-activedirectory-library-for-dotnet,AzureAD/microsoft-authentication-library-for-dotnet,AzureAD/microsoft-authentication-library-for-dotnet,yamamoWorks/azure-activedirectory-library-for-dotnet,AzureAD/azure-activedirectory-library-for-dotnet,AzureAD/microsoft-authentication-library-for-dotnet,AzureAD/microsoft-authentication-library-for-dotnet
|
src/ADAL.PCL.Mac/PlatformParameters.cs
|
src/ADAL.PCL.Mac/PlatformParameters.cs
|
//------------------------------------------------------------------------------
//
// Copyright (c) Microsoft Corporation.
// All rights reserved.
//
// This code is licensed under the MIT License.
//
// 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 AppKit;
namespace Microsoft.IdentityModel.Clients.ActiveDirectory
{
/// <summary>
/// Additional parameters used in acquiring user's authorization
/// </summary>
public class PlatformParameters : IPlatformParameters
{
private PlatformParameters()
{
}
/// <summary>
/// Additional parameters used in acquiring user's authorization
/// </summary>
/// <param name="callerViewController">UIViewController instance</param>
public PlatformParameters(NSWindow callerWindow):this()
{
this.CallerWindow = callerWindow;
}
/// <summary>
/// Caller NSWindow
/// </summary>
public NSWindow CallerWindow { get; private set; }
/// <summary>
/// Shows the prompt in a modal dialog.
/// </summary>
public bool UseModalDialog { get; set; }
}
}
|
//------------------------------------------------------------------------------
//
// Copyright (c) Microsoft Corporation.
// All rights reserved.
//
// This code is licensed under the MIT License.
//
// 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 AppKit;
namespace Microsoft.IdentityModel.Clients.ActiveDirectory
{
/// <summary>
/// Additional parameters used in acquiring user's authorization
/// </summary>
public class PlatformParameters : IPlatformParameters
{
private PlatformParameters()
{
}
/// <summary>
/// Additional parameters used in acquiring user's authorization
/// </summary>
/// <param name="callerViewController">UIViewController instance</param>
public PlatformParameters(NSWindow callerWindow):this()
{
this.CallerWindow = callerWindow;
}
/// <summary>
/// Additional parameters used in acquiring user's authorization
/// </summary>
/// <param name="callerViewController">UIViewController instance</param>
/// <param name="useBroker">skips calling to broker if broker is present. false, by default</param>
public PlatformParameters(NSWindow callerWindow, bool useBroker):this(callerWindow)
{
UseBroker = useBroker;
}
/// <summary>
/// Caller NSWindow
/// </summary>
public NSWindow CallerWindow { get; private set; }
/// <summary>
/// Skips calling to broker if broker is present. false, by default
/// </summary>
public bool UseBroker { get; set; }
/// <summary>
/// Shows the prompt in a modal dialog.
/// </summary>
public bool UseModalDialog { get; set; }
}
}
|
mit
|
C#
|
eb40b6e1b77b085c92061bd0d1fdda62cc1edec5
|
Remove unnecessary using
|
RubenLaube-Pohto/asp.net-project
|
Program.cs
|
Program.cs
|
using Microsoft.AspNetCore.Hosting;
namespace ChatApp
{
public class Program
{
public static void Main(string[] args)
{
var host = new WebHostBuilder()
.UseKestrel()
.UseStartup<Startup>() // <Startup> tells to look for Startup class in Startup.cs
.UseContentRoot(System.IO.Directory.GetCurrentDirectory())
.Build();
host.Run();
}
}
}
|
using System;
using Microsoft.AspNetCore.Hosting;
namespace ChatApp
{
public class Program
{
public static void Main(string[] args)
{
var host = new WebHostBuilder()
.UseKestrel()
.UseStartup<Startup>() // <Startup> tells to look for Startup class in Startup.cs
.UseContentRoot(System.IO.Directory.GetCurrentDirectory())
.Build();
host.Run();
}
}
}
|
mit
|
C#
|
1036270ea6363e9d1c39aa278924c8c7c72dd994
|
Move TestEnvironmentSetUpFixture into project root namespace
|
ulrichb/ReSharperExtensionsShared
|
Src/ReSharperExtensionsShared.Tests/ZoneMarkerAndSetUpFixture.cs
|
Src/ReSharperExtensionsShared.Tests/ZoneMarkerAndSetUpFixture.cs
|
using JetBrains.Application.BuildScript.Application.Zones;
using JetBrains.ReSharper.Psi.CSharp;
using JetBrains.ReSharper.TestFramework;
using JetBrains.TestFramework;
using JetBrains.TestFramework.Application.Zones;
using NUnit.Framework;
[assembly: RequiresSTA]
namespace ReSharperExtensionsShared.Tests
{
[ZoneDefinition]
public interface ITestEnvironmentZone : ITestsZone, IRequire<PsiFeatureTestZone>
{
}
[ZoneMarker]
public class ZoneMarker : IRequire<ILanguageCSharpZone>, IRequire<ITestEnvironmentZone>
{
}
[SetUpFixture]
public class TestEnvironmentSetUpFixture : ExtensionTestEnvironmentAssembly<ITestEnvironmentZone>
{
}
}
|
using JetBrains.Application.BuildScript.Application.Zones;
using JetBrains.ReSharper.Psi.CSharp;
using JetBrains.ReSharper.TestFramework;
using JetBrains.TestFramework;
using JetBrains.TestFramework.Application.Zones;
using NUnit.Framework;
using ReSharperExtensionsShared.Tests;
[assembly: RequiresSTA]
namespace ReSharperExtensionsShared.Tests
{
[ZoneDefinition]
public interface ITestEnvironmentZone : ITestsZone, IRequire<PsiFeatureTestZone>
{
}
[ZoneMarker]
public class ZoneMarker : IRequire<ILanguageCSharpZone>, IRequire<ITestEnvironmentZone>
{
}
}
// ReSharper disable once CheckNamespace
[SetUpFixture]
public class TestEnvironmentSetUpFixture : ExtensionTestEnvironmentAssembly<ITestEnvironmentZone>
{
}
|
mit
|
C#
|
12dd85de9fd06291b6c8dc73a169abde703e362e
|
Update XRSDKWindowsMixedRealityUtilitiesProvider.cs
|
DDReaper/MixedRealityToolkit-Unity,killerantz/HoloToolkit-Unity,killerantz/HoloToolkit-Unity,killerantz/HoloToolkit-Unity,killerantz/HoloToolkit-Unity
|
Assets/MRTK/Providers/WindowsMixedReality/XRSDK/XRSDKWindowsMixedRealityUtilitiesProvider.cs
|
Assets/MRTK/Providers/WindowsMixedReality/XRSDK/XRSDKWindowsMixedRealityUtilitiesProvider.cs
|
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
using Microsoft.MixedReality.Toolkit.WindowsMixedReality;
using System;
#if WMR_ENABLED
using UnityEngine.XR.WindowsMR;
#endif // WMR_ENABLED
namespace Microsoft.MixedReality.Toolkit.XRSDK.WindowsMixedReality
{
/// <summary>
/// An implementation of <see cref="Toolkit.WindowsMixedReality.IWindowsMixedRealityUtilitiesProvider"/> for Unity's XR SDK pipeline.
/// </summary>
public class XRSDKWindowsMixedRealityUtilitiesProvider : IWindowsMixedRealityUtilitiesProvider
{
/// <inheritdoc />
IntPtr IWindowsMixedRealityUtilitiesProvider.ISpatialCoordinateSystemPtr =>
#if WMR_ENABLED
WindowsMREnvironment.OriginSpatialCoordinateSystem;
#else
IntPtr.Zero;
#endif
/// <inheritdoc />
IntPtr IWindowsMixedRealityUtilitiesProvider.IHolographicFramePtr =>
#if WMR_ENABLED
WindowsMREnvironment.CurrentHolographicRenderFrame;
#else
IntPtr.Zero;
#endif
}
}
|
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
using Microsoft.MixedReality.Toolkit.WindowsMixedReality;
using System;
#if WMR_ENABLED
using UnityEngine.XR.WindowsMR;
#endif // WMR_ENABLED
namespace Microsoft.MixedReality.Toolkit.XRSDK.WindowsMixedReality
{
/// <summary>
/// An implementation of <see cref="Toolkit.WindowsMixedReality.IWindowsMixedRealityUtilitiesProvider"/> for Unity's XR SDK pipeline.
/// </summary>
public class XRSDKWindowsMixedRealityUtilitiesProvider : IWindowsMixedRealityUtilitiesProvider
{
/// <inheritdoc />
IntPtr IWindowsMixedRealityUtilitiesProvider.ISpatialCoordinateSystemPtr =>
#if WMR_ENABLED
WindowsMREnvironment.OriginSpatialCoordinateSystem;
#else
IntPtr.Zero;
#endif
/// <summary>
/// Currently unable to access HolographicFrame in XR SDK. Always returns IntPtr.Zero.
/// </summary>
IntPtr IWindowsMixedRealityUtilitiesProvider.IHolographicFramePtr => IntPtr.Zero;
}
}
|
mit
|
C#
|
a01db9f9815823a6f5519a824836467df07cd5be
|
check if cache works
|
Soluto/tweek,Soluto/tweek,Soluto/tweek,Soluto/tweek,Soluto/tweek,Soluto/tweek
|
core/Engine/Engine/Rules/Creation/RulesLoader.cs
|
core/Engine/Engine/Rules/Creation/RulesLoader.cs
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Engine.Core.Rules;
using Engine.Drivers.Rules;
using static Engine.Core.Utils.TraceHelpers;
using LanguageExt.Trans.Linq;
using LanguageExt;
//check chache
namespace Engine.Rules.Creation
{
public delegate IRuleParser GetRuleParser(string format);
public static class RulesLoader
{
public static async Task<Func<IReadOnlyDictionary<string, IRule>>> Factory(IRulesDriver driver, GetRuleParser parserResolver)
{
var instance = Parse(await driver.GetAllRules(), parserResolver);
driver.OnRulesChange += (newRules) =>
{
using (TraceTime("loading new rules"))
{
instance = Parse(newRules, parserResolver);
}
};
return () => instance;
}
public static IReadOnlyDictionary<string,IRule> Parse(IDictionary<string, RuleDefinition> rules, GetRuleParser parserResolver)
{
return rules.ToDictionary(x=>x.Key.ToLower(), x=>
parserResolver(x.Value.Format).Parse(x.Value.Payload));
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Engine.Core.Rules;
using Engine.Drivers.Rules;
using static Engine.Core.Utils.TraceHelpers;
using LanguageExt.Trans.Linq;
using LanguageExt;
namespace Engine.Rules.Creation
{
public delegate IRuleParser GetRuleParser(string format);
public static class RulesLoader
{
public static async Task<Func<IReadOnlyDictionary<string, IRule>>> Factory(IRulesDriver driver, GetRuleParser parserResolver)
{
var instance = Parse(await driver.GetAllRules(), parserResolver);
driver.OnRulesChange += (newRules) =>
{
using (TraceTime("loading new rules"))
{
instance = Parse(newRules, parserResolver);
}
};
return () => instance;
}
public static IReadOnlyDictionary<string,IRule> Parse(IDictionary<string, RuleDefinition> rules, GetRuleParser parserResolver)
{
return rules.ToDictionary(x=>x.Key.ToLower(), x=>
parserResolver(x.Value.Format).Parse(x.Value.Payload));
}
}
}
|
mit
|
C#
|
bb5f37164760088a3b30b617e9f252f5a5f4eeed
|
Add test for INPUT union
|
AArnott/pinvoke,vbfox/pinvoke,jmelosegui/pinvoke
|
src/User32.Tests/User32Facts.cs
|
src/User32.Tests/User32Facts.cs
|
// Copyright (c) to owners found in https://github.com/AArnott/pinvoke/blob/master/COPYRIGHT.md. All rights reserved.
// Licensed under the MIT license. See LICENSE.txt file in the project root for full license information.
using System;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices;
using System.Threading;
using PInvoke;
using Xunit;
using static PInvoke.User32;
public partial class User32Facts
{
[Fact]
public void MessageBeep_Asterisk()
{
Assert.True(MessageBeep(MessageBeepType.MB_ICONASTERISK));
}
[Fact]
public void INPUT_Union()
{
INPUT i = default(INPUT);
i.type = InputType.INPUT_HARDWARE;
// Assert that the first field (type) has its own memory space.
Assert.Equal(0u, i.hi.uMsg);
Assert.Equal(0, (int)i.ki.wScan);
Assert.Equal(0, i.mi.dx);
// Assert that these three fields (hi, ki, mi) share memory space.
i.hi.uMsg = 1;
Assert.Equal(1, (int)i.ki.wVk);
Assert.Equal(1, i.mi.dx);
}
}
|
// Copyright (c) to owners found in https://github.com/AArnott/pinvoke/blob/master/COPYRIGHT.md. All rights reserved.
// Licensed under the MIT license. See LICENSE.txt file in the project root for full license information.
using System;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices;
using System.Threading;
using PInvoke;
using Xunit;
using static PInvoke.User32;
public partial class User32Facts
{
[Fact]
public void MessageBeep_Asterisk()
{
Assert.True(MessageBeep(MessageBeepType.MB_ICONASTERISK));
}
}
|
mit
|
C#
|
eb472e8507f34be83f629abca053e01118d9e2c8
|
Add comments to ControllerCodeHelper.MonoclePainting
|
AngelDE98/FEZMod,AngelDE98/FEZMod
|
FEZ.Speedrun.mm/FezGame/Speedrun/BOT/ControllerCodeHelper.cs
|
FEZ.Speedrun.mm/FezGame/Speedrun/BOT/ControllerCodeHelper.cs
|
using System;
using FezGame.Structure;
using Microsoft.Xna.Framework;
using FezEngine;
using FezGame.Components;
using FezEngine.Structure.Input;
using FezGame.Mod;
using FezEngine.Structure;
using FezEngine.Services;
using FezEngine.Tools;
using System.Collections.Generic;
namespace FezGame.Speedrun.BOT {
public static class ControllerCodeHelper {
public static KeySequence MonoclePainting = new KeySequence()
/*l r*///l: left; r: right; 0: not pressed; 1: pressed; 2: released;
/*0 1*/.Add(CodeInput.SpinRight)
/*0 2*/.AddFrame()
/*0 1*/.AddFrame(CodeInput.SpinRight)
/*1 2*/.AddFrame(CodeInput.SpinLeft)
/*2 1*/.AddFrame(CodeInput.SpinRight)
/*1 2*/.AddFrame(CodeInput.SpinLeft)
/*2 0*/.AddFrame()
/*1 0*/.AddFrame(CodeInput.SpinLeft)
/*2 0*/.AddFrame()
/*1 0*/.AddFrame(CodeInput.SpinLeft)
/*2 1*/.AddFrame(CodeInput.SpinRight);
/*0 2*/
/*0 0*/
}
}
|
using System;
using FezGame.Structure;
using Microsoft.Xna.Framework;
using FezEngine;
using FezGame.Components;
using FezEngine.Structure.Input;
using FezGame.Mod;
using FezEngine.Structure;
using FezEngine.Services;
using FezEngine.Tools;
using System.Collections.Generic;
namespace FezGame.Speedrun.BOT {
public static class ControllerCodeHelper {
public static KeySequence MonoclePainting = new KeySequence()
.Add(CodeInput.SpinRight)
.AddFrame()
.AddFrame(CodeInput.SpinRight)
.AddFrame(CodeInput.SpinLeft)
.AddFrame(CodeInput.SpinRight)
.AddFrame(CodeInput.SpinLeft)
.AddFrame()
.AddFrame(CodeInput.SpinLeft)
.AddFrame()
.AddFrame(CodeInput.SpinLeft)
.AddFrame(CodeInput.SpinRight);
}
}
|
mit
|
C#
|
486ec49933effdfb55e093b234cdcba48e1e5442
|
Update LazyCacheServiceCollectionExtensions.cs (#62)
|
alastairtree/LazyCache,alastairtree/LazyCache
|
LazyCache.AspNetCore/LazyCacheServiceCollectionExtensions.cs
|
LazyCache.AspNetCore/LazyCacheServiceCollectionExtensions.cs
|
using System;
using LazyCache;
using LazyCache.Providers;
using Microsoft.Extensions.Caching.Memory;
using Microsoft.Extensions.DependencyInjection.Extensions;
// ReSharper disable once CheckNamespace - MS guidelines say put DI registration in this NS
namespace Microsoft.Extensions.DependencyInjection
{
// See https://github.com/aspnet/Caching/blob/dev/src/Microsoft.Extensions.Caching.Memory/MemoryCacheServiceCollectionExtensions.cs
public static class LazyCacheServiceCollectionExtensions
{
public static IServiceCollection AddLazyCache(this IServiceCollection services)
{
if (services == null) throw new ArgumentNullException(nameof(services));
services.AddOptions();
services.TryAdd(ServiceDescriptor.Singleton<IMemoryCache, MemoryCache>());
services.TryAdd(ServiceDescriptor.Singleton<ICacheProvider, MemoryCacheProvider>());
services.TryAdd(ServiceDescriptor.Singleton<IAppCache, CachingService>());
return services;
}
public static IServiceCollection AddLazyCache(this IServiceCollection services,
Func<IServiceProvider, CachingService> implementationFactory)
{
if (services == null) throw new ArgumentNullException(nameof(services));
if (implementationFactory == null) throw new ArgumentNullException(nameof(implementationFactory));
services.AddOptions();
services.TryAdd(ServiceDescriptor.Singleton<IMemoryCache, MemoryCache>());
services.TryAdd(ServiceDescriptor.Singleton<ICacheProvider, MemoryCacheProvider>());
services.TryAdd(ServiceDescriptor.Singleton<IAppCache>(implementationFactory));
return services;
}
}
}
|
using System;
using LazyCache;
using LazyCache.Providers;
using Microsoft.Extensions.Caching.Memory;
using Microsoft.Extensions.DependencyInjection.Extensions;
// ReSharper disable once CheckNamespace - MS guidelines say put DI registration in this NS
namespace Microsoft.Extensions.DependencyInjection
{
// See https://github.com/aspnet/Caching/blob/dev/src/Microsoft.Extensions.Caching.Memory/MemoryCacheServiceCollectionExtensions.cs
public static class LazyCacheServiceCollectionExtensions
{
public static IServiceCollection AddLazyCache(this IServiceCollection services)
{
if (services == null) throw new ArgumentNullException(nameof(services));
services.AddOptions();
services.TryAdd(ServiceDescriptor.Singleton<IMemoryCache, MemoryCache>());
services.TryAdd(ServiceDescriptor.Singleton<ICacheProvider, MemoryCacheProvider>());
services.TryAdd(ServiceDescriptor.Singleton<IAppCache, CachingService>());
return services;
}
public static IServiceCollection AddLazyCache(this IServiceCollection services,
Func<IServiceProvider, CachingService> implmentationFactory)
{
if (services == null) throw new ArgumentNullException(nameof(services));
if (implmentationFactory == null) throw new ArgumentNullException(nameof(implmentationFactory));
services.AddOptions();
services.TryAdd(ServiceDescriptor.Singleton<IMemoryCache, MemoryCache>());
services.TryAdd(ServiceDescriptor.Singleton<ICacheProvider, MemoryCacheProvider>());
services.TryAdd(ServiceDescriptor.Singleton<IAppCache>(implmentationFactory));
return services;
}
}
}
|
mit
|
C#
|
1522ff94b3ab7ada60accef0d62c9940d0b9ac41
|
move to version 1.4.2
|
ChrisMissal/Formo,Moulde/Formo,noelbundick/Formo,madhon/Formo
|
src/Formo/Properties/AssemblyInfo.cs
|
src/Formo/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("Formo")]
[assembly: AssemblyDescription("Formo lets you use your configuration file as a dynamic object.")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("Formo")]
[assembly: AssemblyCopyright("Copyright © Chris Missal 2013")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("e132cc76-3768-45f7-84c6-75d907225721")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.4.2.*")]
[assembly: AssemblyFileVersion("1.4.2.*")]
|
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("Formo")]
[assembly: AssemblyDescription("Formo lets you use your configuration file as a dynamic object.")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("Formo")]
[assembly: AssemblyCopyright("Copyright © Chris Missal 2013")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("e132cc76-3768-45f7-84c6-75d907225721")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.4.1.*")]
[assembly: AssemblyFileVersion("1.4.1.*")]
|
mit
|
C#
|
140a08e1ecdff16f60bf54d8d8d8a730a4ae4792
|
Add comment to ProxyAuthorizationException constructor
|
justcoding121/Titanium-Web-Proxy,titanium007/Titanium,titanium007/Titanium-Web-Proxy
|
Titanium.Web.Proxy/Exceptions/ProxyAuthorizationException.cs
|
Titanium.Web.Proxy/Exceptions/ProxyAuthorizationException.cs
|
using System;
using System.Collections.Generic;
using Titanium.Web.Proxy.Models;
namespace Titanium.Web.Proxy.Exceptions
{
/// <summary>
/// Proxy authorization exception
/// </summary>
public class ProxyAuthorizationException : ProxyException
{
/// <summary>
/// Instantiate new instance
/// </summary>
/// <param name="message">Exception message</param>
/// <param name="innerException">Inner exception associated to upstream proxy authorization</param>
/// <param name="headers">Http's headers associated</param>
public ProxyAuthorizationException(string message, Exception innerException, IEnumerable<HttpHeader> headers) : base(message, innerException)
{
Headers = headers;
}
/// <summary>
/// Headers associated with the authorization exception
/// </summary>
public IEnumerable<HttpHeader> Headers { get; }
}
}
|
using System;
using System.Collections.Generic;
using Titanium.Web.Proxy.Models;
namespace Titanium.Web.Proxy.Exceptions
{
/// <summary>
/// Proxy authorization exception
/// </summary>
public class ProxyAuthorizationException : ProxyException
{
public ProxyAuthorizationException(string message, Exception innerException, IEnumerable<HttpHeader> headers) : base(message, innerException)
{
Headers = headers;
}
/// <summary>
/// Headers associated with the authorization exception
/// </summary>
public IEnumerable<HttpHeader> Headers { get; }
}
}
|
mit
|
C#
|
c97c6565a94e1728abf4cee5de9a768f8b043a0f
|
Fix typo in CalculatesAverageGrade() test
|
charlesroper/CSharp-Fundamentals
|
Grades.Tests/UnitTest1.cs
|
Grades.Tests/UnitTest1.cs
|
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace Grades.Tests
{
[TestClass]
public class GradeBookTests
{
private GradeStatistics _stats;
public GradeBookTests()
{
var book = new GradeBook();
book.AddGrade(90f);
book.AddGrade(100f);
book.AddGrade(50f);
_stats = book.ComputeStatistics();
}
[TestMethod]
public void CalculatesHighestGrade()
{
Assert.AreEqual(100f, _stats.HighestGrade);
}
[TestMethod]
public void CalculatesLowestGrade()
{
Assert.AreEqual(100f, _stats.HighestGrade);
}
[TestMethod]
public void CalculatesAverageGrade()
{
Assert.AreEqual(100f, _stats.HighestGrade);
}
}
}
|
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace Grades.Tests
{
[TestClass]
public class GradeBookTests
{
private GradeStatistics _stats;
public GradeBookTests()
{
var book = new GradeBook();
book.AddGrade(90f);
book.AddGrade(100f);
book.AddGrade(50f);
_stats = book.ComputeStatistics();
}
[TestMethod]
public void CalculatesHighestGrade()
{
Assert.AreEqual(100f, _stats.HighestGrade);
}
[TestMethod]
public void CalculatesLowestGrade()
{
Assert.AreEqual(100f, _stats.HighestGrade);
}
[TestMethod]
public void CalculatesAveragaGrade()
{
Assert.AreEqual(100f, _stats.HighestGrade);
}
}
}
|
mit
|
C#
|
2350f757b1466c0377aa149a404efb4cab6b6fd3
|
Add yet another word
|
ArcticEcho/Hatman
|
Hatman/Commands/Should.cs
|
Hatman/Commands/Should.cs
|
using System.Text.RegularExpressions;
using ChatExchangeDotNet;
namespace Hatman.Commands
{
class Should : ICommand
{
private readonly Regex ptn = new Regex(@"(?i)^((sh|[cw])ould|can|are|did|were|will|is|has|does|do).*\?", Extensions.RegOpts);
private readonly string[] phrases = new[]
{
"No.",
"Yes.",
"Yup.",
"Nope.",
"Indubitably",
"Never. Ever. *EVER*.",
"I'll tell ya, only if I get my coffee.",
"Nah.",
"Ask The Skeet.",
"... do I look like I know everything?",
"Ask me no questions, and I shall tell no lies.",
"Sure, when it rains imaginary internet points.",
"Yeah.",
"Ofc.",
"NOOOOOOOOOOOOOOOO",
"Sure..."
};
public Regex CommandPattern
{
get
{
return ptn;
}
}
public string Description
{
get
{
return "Decides whether or not something should happen.";
}
}
public string Usage
{
get
{
return "(sh|[wc])ould|will|did and many words alike";
}
}
public void ProcessMessage(Message msg, ref Room rm)
{
rm.PostReplyFast(msg, phrases.PickRandom());
}
}
}
|
using System.Text.RegularExpressions;
using ChatExchangeDotNet;
namespace Hatman.Commands
{
class Should : ICommand
{
private readonly Regex ptn = new Regex(@"(?i)^((sh|[cw])ould|can|are|did|will|is|has|does|do).*\?", Extensions.RegOpts);
private readonly string[] phrases = new[]
{
"No.",
"Yes.",
"Yup.",
"Nope.",
"Indubitably",
"Never. Ever. *EVER*.",
"I'll tell ya, only if I get my coffee.",
"Nah.",
"Ask The Skeet.",
"... do I look like I know everything?",
"Ask me no questions, and I shall tell no lies.",
"Sure, when it rains imaginary internet points.",
"Yeah.",
"Ofc.",
"NOOOOOOOOOOOOOOOO",
"Sure..."
};
public Regex CommandPattern
{
get
{
return ptn;
}
}
public string Description
{
get
{
return "Decides whether or not something should happen.";
}
}
public string Usage
{
get
{
return "(sh|[wc])ould|will|did and many words alike";
}
}
public void ProcessMessage(Message msg, ref Room rm)
{
rm.PostReplyFast(msg, phrases.PickRandom());
}
}
}
|
isc
|
C#
|
d60a68de94a178187ff294484ab460fe7011e6c2
|
Revert "Add NeedsCpp to LinkWithAttribute"
|
jorik041/maccore,mono/maccore,cwensley/maccore
|
src/ObjCRuntime/LinkWithAttribute.cs
|
src/ObjCRuntime/LinkWithAttribute.cs
|
//
// Authors: Jeffrey Stedfast
//
// Copyright 2011 Xamarin Inc.
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
using System;
using System.IO;
namespace MonoMac.ObjCRuntime {
[Flags]
public enum LinkTarget {
Simulator = 1,
ArmV6 = 2,
ArmV7 = 4,
Thumb = 8,
}
[AttributeUsage(AttributeTargets.Assembly, AllowMultiple=true)]
public class LinkWithAttribute : Attribute {
public LinkWithAttribute (string libraryName, LinkTarget target, string linkerFlags)
{
LibraryName = libraryName;
LinkerFlags = linkerFlags;
LinkTarget = target;
}
public LinkWithAttribute (string libraryName, LinkTarget target)
{
LibraryName = libraryName;
LinkTarget = target;
}
public LinkWithAttribute (string libraryName)
{
LibraryName = libraryName;
}
public bool ForceLoad {
get; set;
}
public string LibraryName {
get; private set;
}
public string LinkerFlags {
get; set;
}
public LinkTarget LinkTarget {
get; set;
}
}
}
|
//
// Authors: Jeffrey Stedfast
//
// Copyright 2011 Xamarin Inc.
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
using System;
using System.IO;
namespace MonoMac.ObjCRuntime {
[Flags]
public enum LinkTarget {
Simulator = 1,
ArmV6 = 2,
ArmV7 = 4,
Thumb = 8,
}
[AttributeUsage(AttributeTargets.Assembly, AllowMultiple=true)]
public class LinkWithAttribute : Attribute {
public LinkWithAttribute (string libraryName, LinkTarget target, string linkerFlags)
{
LibraryName = libraryName;
LinkerFlags = linkerFlags;
LinkTarget = target;
}
public LinkWithAttribute (string libraryName, LinkTarget target)
{
LibraryName = libraryName;
LinkTarget = target;
}
public LinkWithAttribute (string libraryName)
{
LibraryName = libraryName;
}
public bool ForceLoad {
get; set;
}
public string LibraryName {
get; private set;
}
public string LinkerFlags {
get; set;
}
public LinkTarget LinkTarget {
get; set;
}
public bool NeedsCpp {
get; set;
}
}
}
|
apache-2.0
|
C#
|
9094307172feac4a3e6090fc3ad9ce5a237306a6
|
Update FastStack.cs
|
erebuswolf/LockstepFramework,SnpM/Lockstep-Framework,yanyiyun/LockstepFramework
|
Core/Utility/Fast/FastStack.cs
|
Core/Utility/Fast/FastStack.cs
|
using System.Collections;
using System;
namespace Lockstep {
public class FastStack<T>
{
private const int DefaultCapacity = 8;
public T[] innerArray;
public int Count = 0;
public int Capacity;
public FastStack (int StartCapacity)
{
Capacity = StartCapacity;
Initialize ();
}
public FastStack ()
{
Capacity = DefaultCapacity;
Initialize ();
}
private void Initialize ()
{
#if UNITY_EDITOR
if (Capacity <= 0)
{
UnityEngine.Debug.LogError ("Initializing list with capacity less than or equal to zero isn't supported");
}
#endif
innerArray = new T[Capacity];
}
public void Add (T item)
{
EnsureCapacity ();
innerArray [Count++] = item;
}
public T Pop ()
{
return (innerArray[--Count]);
}
public T Peek ()
{
return innerArray[Count - 1];
}
private void EnsureCapacity ()
{
if (Count == Capacity) {
Capacity *= 2;
T[] newItems = new T[Capacity];
Array.Copy (innerArray, 0, newItems, 0, Count);
innerArray = newItems;
}
}
public T this [int index] {
get {
return innerArray [index];
}
set {
innerArray [index] = value;
}
}
public void Clear ()
{
innerArray = new T[Capacity];
}
/// <summary>
/// Marks elements for overwriting. Note: After using FastClear(), this list will still keep any references to objects it previously had.
/// </summary>
public void FastClear ()
{
Count = 0;
}
public override string ToString ()
{
if (Count <= 0)
return base.ToString ();
string output = string.Empty;
for (int i = 0; i < Count - 1; i++)
output += innerArray [i] + ", ";
return base.ToString () + ": " + output + innerArray [Count - 1];
}
}
}
|
using System.Collections;
using System;
namespace Lockstep {
public class FastStack<T>
{
private const int DefaultCapacity = 8;
public T[] innerArray;
public int Count = 0;
public int Capacity;
public FastStack (int StartCapacity)
{
Capacity = StartCapacity;
Initialize ();
}
public FastStack ()
{
Capacity = DefaultCapacity;
Initialize ();
}
private void Initialize ()
{
#if UNITY_EDITOR
if (Capacity <= 0)
{
UnityEngine.Debug.LogError ("Initializing list with capacity less than or equal to zero isn't supported");
}
#endif
innerArray = new T[Capacity];
}
public void Add (T item)
{
EnsureCapacity ();
innerArray [Count++] = item;
}
public T Pop ()
{
return (innerArray[--Count]);
}
public T Peek ()
{
return innerArray[Count - 1];
}
private void EnsureCapacity ()
{
if (Count == Capacity) {
Capacity *= 2;
T[] newItems = new T[Capacity];
Array.Copy (innerArray, 0, newItems, 0, Count);
innerArray = newItems;
}
}
public T this [int index] {
get {
return innerArray [index];
}
set {
innerArray [index] = value;
}
}
public void Clear ()
{
innerArray = new T[Capacity];
}
/// <summary>
/// Marks elements for overwriting. Note: After using FastClear(), this list will still keep any references to objects it previously had.
/// </summary>
public void FastClear ()
{
Count = 0;
}
public override string ToString ()
{
string output = string.Empty;
for (int i = 0; i < Count - 1; i++)
output += innerArray [i] + ", ";
return output + innerArray [Count - 1];
}
}
}
|
mit
|
C#
|
fcb2ce2670cbc7e49bbea6c8787c4ae648d038ae
|
Update NotesRepository.cs
|
CarmelSoftware/MVCDataRepositoryXML
|
Models/NotesRepository.cs
|
Models/NotesRepository.cs
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Xml.Linq;
namespace IoCDependencyInjection.Models
{
|
////// TODO
|
mit
|
C#
|
0a628ff5ba496ed1ffa144c133c3d1e7137b01c4
|
update view
|
MachUpskillingFY17/JabbR-Core,MachUpskillingFY17/JabbR-Core,MachUpskillingFY17/JabbR-Core
|
src/JabbR-Core/Views/Account/_changeusername.cshtml
|
src/JabbR-Core/Views/Account/_changeusername.cshtml
|
@using JabbR_Core
@using JabbR_Core.ViewModels
@model ChangeUsernameViewModel
@*<form class="form-horizontal" action="@Url.Content("~/account/changeusername")#changeUsername" method="POST">*@
<form asp-controller="Account" asp-action="ChangeUsername" method="post" class="form-horizontal">
@Html.ValidationSummary()
<div class="control-group">
<label class="control-label" for="username">@LanguageResources.Account_UserName</label>
<div class="controls">
<input asp-for="username" class="form-control" format=@LanguageResources.Account_UserName placeholder="New Username" />
</div>
</div>
<div class="control-group">
<label class="control-label" for="confirmUsername">@LanguageResources.Account_UserNameConfirm</label>
<div class="controls">
<input asp-for="confirmUsername" class="form-control" format=@LanguageResources.Account_UserName placeholder="Confirm New Username" />
</div>
</div>
<div class="control-group">
<label class="control-label" for="password">@LanguageResources.Account_Pass</label>
<div class="controls">
<input asp-for="password" class="form-control" format=@LanguageResources.Account_Pass placeholder="Password" />
</div>
</div>
<div class="control-group">
<div class="controls">
<input type="submit" class="btn" value="@LanguageResources.Account_ChangeUserName" />
</div>
</div>
@Html.AntiForgeryToken()
</form>
|
@using JabbR_Core
@using JabbR_Core.ViewModels
@model ChangeUsernameViewModel
@*<form class="form-horizontal" action="@Url.Content("~/account/changeusername")#changeUsername" method="POST">*@
<form asp-controller="Account" asp-action="ChangeUsername" method="post" class="form-horizontal">
@Html.ValidationSummary()
<div class="control-group">
<label class="control-label" for="username">@LanguageResources.Account_UserName</label>
<div class="controls">
<input asp-for="username" class="form-control" format=@LanguageResources.Account_UserName placeholder="Username" />
@Html.ValidationMessageFor(x => x.username)
</div>
</div>
<div class="control-group">
<label class="control-label" for="confirmUsername">@LanguageResources.Account_UserNameConfirm</label>
<div class="controls">
<input asp-for="confirmUsername" class="form-control" format=@LanguageResources.Account_UserName placeholder="Confirm Username" />
@Html.ValidationMessageFor(x => x.confirmUsername)
</div>
</div>
<div class="control-group">
<label class="control-label" for="password">@LanguageResources.Account_Pass</label>
<div class="controls">
<input asp-for="password" class="form-control" format=@LanguageResources.Account_Pass placeholder="Password" />
</div>
</div>
<div class="control-group">
<div class="controls">
<input type="submit" class="btn" value="@LanguageResources.Account_ChangeUserName" />
</div>
</div>
@Html.AntiForgeryToken()
</form>
|
mit
|
C#
|
0e2e5e96d18c4c0da5d679291cb1e9aa36dec281
|
replace embed translate to Resources.GetString
|
effekseer/Effekseer,effekseer/Effekseer,effekseer/Effekseer,effekseer/Effekseer,effekseer/Effekseer,effekseer/Effekseer,effekseer/Effekseer
|
Dev/Editor/Effekseer/Define.cs
|
Dev/Editor/Effekseer/Define.cs
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Effekseer
{
public class ErrorUtils
{
public static void ThrowFileNotfound()
{
throw new Exception(Resources.GetString("MismatchResourceError"));
}
public static void ShowErrorByNodeLayerLimit()
{
var mb = new GUI.Dialog.MessageBox();
mb.Show("Error", String.Format(Resources.GetString("LayerLimitError"), Constant.NodeLayerLimit));
}
}
/// <summary>
/// Attribute for unique name
/// </summary>
[AttributeUsage(
AttributeTargets.Class | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Method,
AllowMultiple = false,
Inherited = false)]
public class UniqueNameAttribute : Attribute
{
public UniqueNameAttribute()
{
value = string.Empty;
}
public string value
{
get;
set;
}
/// <summary>
/// Get unique name from attribute
/// </summary>
/// <param name="attributes"></param>
/// <returns></returns>
public static string GetUniqueName(object[] attributes)
{
if (attributes != null && attributes.Length > 0)
{
foreach (var attribute in attributes)
{
if (!(attribute is UniqueNameAttribute)) continue;
return ((UniqueNameAttribute)attribute).value;
}
}
return string.Empty;
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Effekseer
{
public class ErrorUtils
{
public static void ThrowFileNotfound()
{
if (Core.Option.GuiLanguage.Value == Language.Japanese)
{
throw new Exception("リソースファイルを更新してください。Script/setup.pyを呼ぶか、cmakeを使用し、ResourceDataをリビルドしてください。");
}
else
{
throw new Exception("Please update resource files!. call Script/setup.py or use cmake and rebuild ResourceData.");
}
}
public static void ShowErrorByNodeLayerLimit()
{
var mb = new GUI.Dialog.MessageBox();
if (Core.Option.GuiLanguage.Value == Language.Japanese)
{
mb.Show("Error", "ノードツリーはルートを含めて" + Constant.NodeLayerLimit + "レイヤーまでに制限されています。");
}
else
{
mb.Show("Error", "The node tree is limited to " + Constant.NodeLayerLimit + " layers, including the root.");
}
}
}
/// <summary>
/// Attribute for unique name
/// </summary>
[AttributeUsage(
AttributeTargets.Class | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Method,
AllowMultiple = false,
Inherited = false)]
public class UniqueNameAttribute : Attribute
{
public UniqueNameAttribute()
{
value = string.Empty;
}
public string value
{
get;
set;
}
/// <summary>
/// Get unique name from attribute
/// </summary>
/// <param name="attributes"></param>
/// <returns></returns>
public static string GetUniqueName(object[] attributes)
{
if (attributes != null && attributes.Length > 0)
{
foreach (var attribute in attributes)
{
if (!(attribute is UniqueNameAttribute)) continue;
return ((UniqueNameAttribute)attribute).value;
}
}
return string.Empty;
}
}
}
|
mit
|
C#
|
9ad54736ed967ea25cae6609d90980b364461dbe
|
Fix visibility of Address.Create (#2979)
|
bokobza/StratisBitcoinFullNode,mikedennis/StratisBitcoinFullNode,stratisproject/StratisBitcoinFullNode,Neurosploit/StratisBitcoinFullNode,stratisproject/StratisBitcoinFullNode,quantumagi/StratisBitcoinFullNode,fassadlr/StratisBitcoinFullNode,Neurosploit/StratisBitcoinFullNode,mikedennis/StratisBitcoinFullNode,fassadlr/StratisBitcoinFullNode,Aprogiena/StratisBitcoinFullNode,bokobza/StratisBitcoinFullNode,mikedennis/StratisBitcoinFullNode,mikedennis/StratisBitcoinFullNode,bokobza/StratisBitcoinFullNode,Aprogiena/StratisBitcoinFullNode,bokobza/StratisBitcoinFullNode,Aprogiena/StratisBitcoinFullNode,Neurosploit/StratisBitcoinFullNode,quantumagi/StratisBitcoinFullNode
|
src/Stratis.SmartContracts.CLR/AddressExtensions.cs
|
src/Stratis.SmartContracts.CLR/AddressExtensions.cs
|
using System;
using NBitcoin;
using Extensions = Stratis.SmartContracts.Core.Extensions;
namespace Stratis.SmartContracts.CLR
{
public static class AddressExtensions
{
public static uint160 ToUint160(this Address address)
{
return new uint160(address.ToBytes());
}
public static uint160 ToUint160(this string base58Address, Network network)
{
return new uint160(new BitcoinPubKeyAddress(base58Address, network).Hash.ToBytes());
}
public static Address ToAddress(this uint160 address)
{
return CreateAddress(address.ToBytes());
}
public static Address ToAddress(this string address, Network network)
{
return CreateAddress(address.ToUint160(network).ToBytes());
}
public static Address ToAddress(this byte[] bytes)
{
if (bytes.Length != Address.Width)
throw new ArgumentOutOfRangeException(nameof(bytes), "Address must be 20 bytes wide");
return CreateAddress(bytes);
}
public static Address HexToAddress(this string hexString)
{
// uint160 only parses a big-endian hex string
var result = Extensions.HexStringToBytes(hexString);
return CreateAddress(result);
}
public static string ToBase58Address(this uint160 address, Network network)
{
return new BitcoinPubKeyAddress(new KeyId(address), network).ToString();
}
private static Address CreateAddress(byte[] bytes)
{
var pn0 = BitConverter.ToUInt32(bytes, 0);
var pn1 = BitConverter.ToUInt32(bytes, 4);
var pn2 = BitConverter.ToUInt32(bytes, 8);
var pn3 = BitConverter.ToUInt32(bytes, 12);
var pn4 = BitConverter.ToUInt32(bytes, 16);
return new Address(pn0, pn1, pn2, pn3, pn4);
}
}
}
|
using System;
using NBitcoin;
using Extensions = Stratis.SmartContracts.Core.Extensions;
namespace Stratis.SmartContracts.CLR
{
public static class AddressExtensions
{
public static uint160 ToUint160(this Address address)
{
return new uint160(address.ToBytes());
}
public static uint160 ToUint160(this string base58Address, Network network)
{
return new uint160(new BitcoinPubKeyAddress(base58Address, network).Hash.ToBytes());
}
public static Address ToAddress(this uint160 address)
{
return Address.Create(address.ToBytes());
}
public static Address ToAddress(this string address, Network network)
{
return Address.Create(address.ToUint160(network).ToBytes());
}
public static Address ToAddress(this byte[] bytes)
{
if (bytes.Length != Address.Width)
throw new ArgumentOutOfRangeException(nameof(bytes), "Address must be 20 bytes wide");
return Address.Create(bytes);
}
public static Address HexToAddress(this string hexString)
{
// uint160 only parses a big-endian hex string
var result = Extensions.HexStringToBytes(hexString);
return Address.Create(result);
}
public static string ToBase58Address(this uint160 address, Network network)
{
return new BitcoinPubKeyAddress(new KeyId(address), network).ToString();
}
}
}
|
mit
|
C#
|
a23e6051911a119c7e4aa9dc863807cc8e8d027a
|
fix console color
|
amiralles/contest,amiralles/contest
|
src/Contest.Core/Printer.cs
|
src/Contest.Core/Printer.cs
|
namespace Contest.Core {
using System;
using System.Collections.Generic;
using System.Diagnostics;
class Printer{
static ConsoleColor White = ConsoleColor.White;
static ConsoleColor Red = ConsoleColor.Red;
static ConsoleColor Green = ConsoleColor.Green;
static ConsoleColor Yellow = ConsoleColor.Yellow;
// void PrintResults(int casesCount, long elapsedMilliseconds)
public readonly static Action<int, long, int, int, int, int, string> PrintResults =
(casesCount, elapsedms, assertsCount, passCount, failCount, ignoreCount, cherry) => {
Print("".PadRight(40, '='), White);
Print("STATS", White);
if(!string.IsNullOrEmpty(cherry)){
Print("".PadRight(40, '='), White);
Print("Cherry Picking => {0}".Interpol(cherry), White);
}
Print("".PadRight(40, '='), White);
Print("Test : {0}".Interpol(casesCount), White);
Print("Asserts : {0}".Interpol(assertsCount), White);
Print("Elapsed : {0} ms".Interpol(elapsedms), White);
Print("Passing : {0}".Interpol(passCount), Green);
Print("Failing : {0}".Interpol(failCount), Red);
Print("Ignored : {0}".Interpol(ignoreCount), Yellow);
Print("".PadRight(40, '='), White);
};
public readonly static Action<string> PrintFixName = name => {
Print("".PadRight(40, '='), ConsoleColor.Cyan);
Print(name, ConsoleColor.Cyan);
Print("".PadRight(40, '='), ConsoleColor.Cyan);
};
public readonly static Action<string, ConsoleColor> Print = (msg, color) => {
var fcolor = Console.ForegroundColor;
try {
Console.ForegroundColor = color;
Console.WriteLine(msg);
}
finally {
Console.ForegroundColor = fcolor;
}
};
}
}
|
namespace Contest.Core {
using System;
using System.Collections.Generic;
using System.Diagnostics;
class Printer{
static ConsoleColor White = ConsoleColor.White;
static ConsoleColor Red = Red;
static ConsoleColor Green = Green;
static ConsoleColor Yellow = Yellow;
// void PrintResults(int casesCount, long elapsedMilliseconds)
public readonly static Action<int, long, int, int, int, int, string> PrintResults =
(casesCount, elapsedms, assertsCount, passCount, failCount, ignoreCount, cherry) => {
Print("".PadRight(40, '='), White);
Print("STATS", White);
if(!string.IsNullOrEmpty(cherry)){
Print("".PadRight(40, '='), White);
Print("Cherry Picking => {0}".Interpol(cherry), White);
}
Print("".PadRight(40, '='), White);
Print("Test : {0}".Interpol(casesCount), White);
Print("Asserts : {0}".Interpol(assertsCount), White);
Print("Elapsed : {0} ms".Interpol(elapsedms), White);
Print("Passing : {0}".Interpol(passCount), Green);
Print("Failing : {0}".Interpol(failCount), Red);
Print("Ignored : {0}".Interpol(ignoreCount), Yellow);
Print("".PadRight(40, '='), White);
};
public readonly static Action<string> PrintFixName = name => {
Print("".PadRight(40, '='), ConsoleColor.Cyan);
Print(name, ConsoleColor.Cyan);
Print("".PadRight(40, '='), ConsoleColor.Cyan);
};
public readonly static Action<string, ConsoleColor> Print = (msg, color) => {
var fcolor = Console.ForegroundColor;
try {
Console.ForegroundColor = color;
Console.WriteLine(msg);
}
finally {
Console.ForegroundColor = fcolor;
}
};
}
}
|
mit
|
C#
|
a4a4cc53b5b320bcdc4f74449a8b9dcf9027318d
|
Build failure test
|
mikeobrien/WcfRestContrib,mikeobrien/WcfRestContrib,mikeobrien/WcfRestContrib
|
src/WcfRestContrib.Tests/EncodedUrlBehaviorTests.cs
|
src/WcfRestContrib.Tests/EncodedUrlBehaviorTests.cs
|
using System;
using System.Net;
using System.ServiceModel;
using System.ServiceModel.Web;
using NUnit.Framework;
using Should;
namespace WcfRestContrib.Tests
{
[TestFixture]
public class EncodedUrlBehaviorTests
{
[ServiceContract]
public class Service
{
[WebGet(UriTemplate = "/{*value}")]
[OperationContract]
public string Method(string value)
{
return value;
}
}
[Test]
public void should()
{
throw new Exception();
}
[Test]
public void Should_Accept_Url_With_Encoded_Forwardslash()
{
using (var host = new Host<Service>("http://localhost:48645/"))
{
var response = host.Get("this%2fthat@someplace.com");
response.StatusCode.ShouldEqual(HttpStatusCode.OK);
response.Content.ShouldContain("this/that@someplace.com");
}
}
[Test]
public void Should_Accept_Url_With_Encoded_Backslash()
{
using (var host = new Host<Service>("http://localhost:48645/"))
{
var response = host.Get("this%5cthat@someplace.com");
response.StatusCode.ShouldEqual(HttpStatusCode.OK);
response.Content.ShouldContain(@"this/that@someplace.com");
}
}
}
}
|
using System.Net;
using System.ServiceModel;
using System.ServiceModel.Web;
using NUnit.Framework;
using Should;
namespace WcfRestContrib.Tests
{
[TestFixture]
public class EncodedUrlBehaviorTests
{
[ServiceContract]
public class Service
{
[WebGet(UriTemplate = "/{*value}")]
[OperationContract]
public string Method(string value)
{
return value;
}
}
[Test]
public void Should_Accept_Url_With_Encoded_Forwardslash()
{
using (var host = new Host<Service>("http://localhost:48645/"))
{
var response = host.Get("this%2fthat@someplace.com");
response.StatusCode.ShouldEqual(HttpStatusCode.OK);
response.Content.ShouldContain("this/that@someplace.com");
}
}
[Test]
public void Should_Accept_Url_With_Encoded_Backslash()
{
using (var host = new Host<Service>("http://localhost:48645/"))
{
var response = host.Get("this%5cthat@someplace.com");
response.StatusCode.ShouldEqual(HttpStatusCode.OK);
response.Content.ShouldContain(@"this/that@someplace.com");
}
}
}
}
|
mit
|
C#
|
9cafec3af687003697982f92cc22bac5442b1829
|
Scrub test key
|
hewittj/chargify-dot-net,kfrancis/chargify-dot-net,hewittj/chargify-dot-net,kfrancis/chargify-dot-net,hewittj/chargify-dot-net,kfrancis/chargify-dot-net
|
Source/ChargifyDotNetTests/Base/ChargifyTestBase.cs
|
Source/ChargifyDotNetTests/Base/ChargifyTestBase.cs
|
using System;
using ChargifyNET;
using System.Net;
#if NUNIT
using NUnit.Framework;
#else
using TestFixture = Microsoft.VisualStudio.TestTools.UnitTesting.TestClassAttribute;
using Test = Microsoft.VisualStudio.TestTools.UnitTesting.TestMethodAttribute;
using TestFixtureSetUp = Microsoft.VisualStudio.TestTools.UnitTesting.TestInitializeAttribute;
using SetUp = Microsoft.VisualStudio.TestTools.UnitTesting.TestInitializeAttribute;
using Microsoft.VisualStudio.TestTools.UnitTesting;
#endif
namespace ChargifyDotNetTests.Base
{
public class ChargifyTestBase
{
/// <summary>
/// Gets or sets the test context which provides
/// information about and functionality for the current test run.
///</summary>
public TestContext TestContext { get; set; }
public ChargifyConnect Chargify => _chargify ?? (_chargify = new ChargifyConnect
{
apiKey = "",
Password = "X",
URL = "https://subdomain.chargify.com/",
SharedKey = "123456789",
UseJSON = false,
ProtocolType = SecurityProtocolType.Tls12
});
private ChargifyConnect _chargify;
/// <summary>
/// Method that allows me to use Faker methods in place rather than writing a bunch of specific "GetRandom.." methods.
/// </summary>
/// <param name="oldValue">The value that the result cannot be</param>
/// <param name="generateValue">The method (that returns string) that will be used to generate the random value</param>
/// <returns>A new random string value that isn't the same as the existing/old value</returns>
public string GetNewRandomValue(string oldValue, Func<string> generateValue)
{
string retVal;
do
{
retVal = generateValue();
}
while (retVal == oldValue);
return retVal;
}
internal void SetJson(bool useJson)
{
if (Chargify != null) {
_chargify.UseJSON = useJson;
}
}
}
}
|
using System;
using ChargifyNET;
using System.Net;
#if NUNIT
using NUnit.Framework;
#else
using TestFixture = Microsoft.VisualStudio.TestTools.UnitTesting.TestClassAttribute;
using Test = Microsoft.VisualStudio.TestTools.UnitTesting.TestMethodAttribute;
using TestFixtureSetUp = Microsoft.VisualStudio.TestTools.UnitTesting.TestInitializeAttribute;
using SetUp = Microsoft.VisualStudio.TestTools.UnitTesting.TestInitializeAttribute;
using Microsoft.VisualStudio.TestTools.UnitTesting;
#endif
namespace ChargifyDotNetTests.Base
{
public class ChargifyTestBase
{
/// <summary>
/// Gets or sets the test context which provides
/// information about and functionality for the current test run.
///</summary>
public TestContext TestContext { get; set; }
public ChargifyConnect Chargify => _chargify ?? (_chargify = new ChargifyConnect
{
apiKey = "WQyfCM9jaEV59ktDVGnev859bOlT1afmBvOaBlU",
Password = "X",
URL = "https://css-test.chargify.com/",
SharedKey = "123456789",
UseJSON = false,
ProtocolType = SecurityProtocolType.Tls12
});
private ChargifyConnect _chargify;
/// <summary>
/// Method that allows me to use Faker methods in place rather than writing a bunch of specific "GetRandom.." methods.
/// </summary>
/// <param name="oldValue">The value that the result cannot be</param>
/// <param name="generateValue">The method (that returns string) that will be used to generate the random value</param>
/// <returns>A new random string value that isn't the same as the existing/old value</returns>
public string GetNewRandomValue(string oldValue, Func<string> generateValue)
{
string retVal;
do
{
retVal = generateValue();
}
while (retVal == oldValue);
return retVal;
}
internal void SetJson(bool useJson)
{
if (Chargify != null) {
_chargify.UseJSON = useJson;
}
}
}
}
|
mit
|
C#
|
04157e3a3d7c60fa95a91db736e6c07679e9aa3d
|
Update UDP
|
Pliner/EasyGelf
|
Source/EasyGelf.Core/Transports/Udp/UdpTransport.cs
|
Source/EasyGelf.Core/Transports/Udp/UdpTransport.cs
|
using System;
using System.Net.Sockets;
using EasyGelf.Core.Encoders;
namespace EasyGelf.Core.Transports.Udp
{
public sealed class UdpTransport : ITransport, IDisposable
{
private readonly UdpTransportConfiguration configuration;
private readonly ITransportEncoder encoder;
private readonly IGelfMessageSerializer messageSerializer;
private readonly UdpClient udpClient;
private bool disposed;
public UdpTransport(
UdpTransportConfiguration configuration,
ITransportEncoder encoder,
IGelfMessageSerializer messageSerializer)
{
this.configuration = configuration;
this.encoder = encoder;
this.messageSerializer = messageSerializer;
this.udpClient = new UdpClient();
}
public void Send(GelfMessage message)
{
var serialzed = messageSerializer.Serialize(message);
var encoded = encoder.Encode(serialzed);
foreach (var bytes in encoded)
{
udpClient.Send(bytes, bytes.Length, configuration.GetHost());
}
}
public void Close()
{
Dispose();
}
public void Dispose()
{
if (!disposed)
{
udpClient.Dispose();
disposed = true;
}
}
}
}
|
using System.Net.Sockets;
using EasyGelf.Core.Encoders;
namespace EasyGelf.Core.Transports.Udp
{
public sealed class UdpTransport : ITransport
{
private readonly UdpTransportConfiguration configuration;
private readonly ITransportEncoder encoder;
private readonly IGelfMessageSerializer messageSerializer;
public UdpTransport(UdpTransportConfiguration configuration, ITransportEncoder encoder, IGelfMessageSerializer messageSerializer)
{
this.configuration = configuration;
this.encoder = encoder;
this.messageSerializer = messageSerializer;
}
public void Send(GelfMessage message)
{
using (var udpClient = new UdpClient())
foreach (var bytes in encoder.Encode(messageSerializer.Serialize(message)))
udpClient.Send(bytes, bytes.Length, configuration.GetHost());
}
public void Close()
{
}
}
}
|
mit
|
C#
|
e2c80f09dacc27e16a83f2cf5b0dbed82b75ae26
|
Remove unnecesary directive
|
peppy/osu,ppy/osu,peppy/osu,ppy/osu,peppy/osu,ppy/osu
|
osu.Game.Tests/Visual/Gameplay/TestSceneSkinnableComboCounter.cs
|
osu.Game.Tests/Visual/Gameplay/TestSceneSkinnableComboCounter.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 NUnit.Framework;
using osu.Framework.Allocation;
using osu.Framework.Graphics;
using osu.Framework.Testing;
using osu.Game.Rulesets.Osu;
using osu.Game.Rulesets.Scoring;
using osu.Game.Screens.Play.HUD.ComboCounters;
using osu.Game.Skinning;
namespace osu.Game.Tests.Visual.Gameplay
{
public class TestSceneSkinnableComboCounter : SkinnableHUDComponentTestScene
{
[Cached]
private ScoreProcessor scoreProcessor = new ScoreProcessor(new OsuRuleset());
protected override Drawable CreateDefaultImplementation() => new DefaultComboCounter();
protected override Drawable CreateLegacyImplementation() => new LegacyComboCounter();
[Test]
public void TestComboCounterIncrementing()
{
AddRepeatStep("increase combo", () => scoreProcessor.Combo.Value++, 10);
AddStep("reset combo", () => scoreProcessor.Combo.Value = 0);
}
[Test]
public void TestLegacyComboCounterHiddenByRulesetImplementation()
{
AddToggleStep("toggle legacy hidden by ruleset", visible =>
{
foreach (var legacyCounter in this.ChildrenOfType<LegacyComboCounter>())
legacyCounter.HiddenByRulesetImplementation = visible;
});
AddRepeatStep("increase combo", () => scoreProcessor.Combo.Value++, 10);
}
}
}
|
// 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 NUnit.Framework;
using osu.Framework.Allocation;
using osu.Framework.Graphics;
using osu.Framework.Testing;
using osu.Game.Rulesets.Osu;
using osu.Game.Rulesets.Scoring;
using osu.Game.Screens.Play.HUD;
using osu.Game.Screens.Play.HUD.ComboCounters;
using osu.Game.Skinning;
namespace osu.Game.Tests.Visual.Gameplay
{
public class TestSceneSkinnableComboCounter : SkinnableHUDComponentTestScene
{
[Cached]
private ScoreProcessor scoreProcessor = new ScoreProcessor(new OsuRuleset());
protected override Drawable CreateDefaultImplementation() => new DefaultComboCounter();
protected override Drawable CreateLegacyImplementation() => new LegacyComboCounter();
[Test]
public void TestComboCounterIncrementing()
{
AddRepeatStep("increase combo", () => scoreProcessor.Combo.Value++, 10);
AddStep("reset combo", () => scoreProcessor.Combo.Value = 0);
}
[Test]
public void TestLegacyComboCounterHiddenByRulesetImplementation()
{
AddToggleStep("toggle legacy hidden by ruleset", visible =>
{
foreach (var legacyCounter in this.ChildrenOfType<LegacyComboCounter>())
legacyCounter.HiddenByRulesetImplementation = visible;
});
AddRepeatStep("increase combo", () => scoreProcessor.Combo.Value++, 10);
}
}
}
|
mit
|
C#
|
b6b8098b989383b0402e2efe48476048f9b05f3f
|
Add an arbitrary offset to prevent div-by-0
|
2yangk23/osu,ppy/osu,NeoAdonis/osu,smoogipooo/osu,EVAST9919/osu,NeoAdonis/osu,peppy/osu,EVAST9919/osu,peppy/osu-new,smoogipoo/osu,ppy/osu,peppy/osu,johnneijzen/osu,UselessToucan/osu,UselessToucan/osu,ppy/osu,2yangk23/osu,UselessToucan/osu,peppy/osu,smoogipoo/osu,smoogipoo/osu,NeoAdonis/osu,johnneijzen/osu
|
osu.Game/Screens/Edit/Compose/Components/CircularBeatSnapGrid.cs
|
osu.Game/Screens/Edit/Compose/Components/CircularBeatSnapGrid.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 System;
using osu.Framework.Graphics;
using osu.Framework.Graphics.UserInterface;
using osu.Game.Rulesets.Objects;
using osuTK;
namespace osu.Game.Screens.Edit.Compose.Components
{
public abstract class CircularBeatSnapGrid : BeatSnapGrid
{
protected CircularBeatSnapGrid(HitObject hitObject, Vector2 centrePosition)
: base(hitObject, centrePosition)
{
}
protected override void CreateContent(Vector2 centrePosition)
{
float dx = Math.Max(centrePosition.X, DrawWidth - centrePosition.X);
float dy = Math.Max(centrePosition.Y, DrawHeight - centrePosition.Y);
float maxDistance = new Vector2(dx, dy).Length;
int requiredCircles = (int)(maxDistance / DistanceSpacing);
for (int i = 0; i < requiredCircles; i++)
{
float radius = (i + 1) * DistanceSpacing * 2;
AddInternal(new CircularProgress
{
Origin = Anchor.Centre,
Position = centrePosition,
Current = { Value = 1 },
Size = new Vector2(radius),
InnerRadius = 4 * 1f / radius,
Colour = GetColourForBeatIndex(i)
});
}
}
public override Vector2 GetSnapPosition(Vector2 position)
{
Vector2 direction = position - CentrePosition;
if (direction == Vector2.Zero)
direction = new Vector2(0.001f, 0.001f);
float distance = direction.Length;
float radius = DistanceSpacing;
int radialCount = Math.Max(1, (int)Math.Round(distance / radius));
Vector2 normalisedDirection = direction * new Vector2(1f / distance);
return CentrePosition + normalisedDirection * radialCount * radius;
}
}
}
|
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using System;
using osu.Framework.Graphics;
using osu.Framework.Graphics.UserInterface;
using osu.Game.Rulesets.Objects;
using osuTK;
namespace osu.Game.Screens.Edit.Compose.Components
{
public abstract class CircularBeatSnapGrid : BeatSnapGrid
{
protected CircularBeatSnapGrid(HitObject hitObject, Vector2 centrePosition)
: base(hitObject, centrePosition)
{
}
protected override void CreateContent(Vector2 centrePosition)
{
float dx = Math.Max(centrePosition.X, DrawWidth - centrePosition.X);
float dy = Math.Max(centrePosition.Y, DrawHeight - centrePosition.Y);
float maxDistance = new Vector2(dx, dy).Length;
int requiredCircles = (int)(maxDistance / DistanceSpacing);
for (int i = 0; i < requiredCircles; i++)
{
float radius = (i + 1) * DistanceSpacing * 2;
AddInternal(new CircularProgress
{
Origin = Anchor.Centre,
Position = centrePosition,
Current = { Value = 1 },
Size = new Vector2(radius),
InnerRadius = 4 * 1f / radius,
Colour = GetColourForBeatIndex(i)
});
}
}
public override Vector2 GetSnapPosition(Vector2 position)
{
Vector2 direction = position - CentrePosition;
float distance = direction.Length;
float radius = DistanceSpacing;
int radialCount = Math.Max(1, (int)Math.Round(distance / radius));
Vector2 normalisedDirection = direction * new Vector2(1f / distance);
return CentrePosition + normalisedDirection * radialCount * radius;
}
}
}
|
mit
|
C#
|
9c569347c7b2cab10e0034e74e88e52329e763df
|
Update EnumerableExtensions.cs
|
keith-hall/Extensions,keith-hall/Extensions
|
src/EnumerableExtensions.cs
|
src/EnumerableExtensions.cs
|
using System;
using System.Collections.Generic;
using System.Linq;
namespace HallLibrary.Extensions
{
/// <summary>
/// Contains static methods for working with <see cref="IEnumerable" />s.
/// </summary>
public static class EnumerableExtensions
{
/// <summary>
/// Randomise the order of the elements in the <paramref name="source"/> enumerable.
/// </summary>
/// <typeparam name="T">The type of the elements in the <paramref name="source"/> enumerable.</typeparam>
/// <param name="source">The enumerable containing the elements to shuffle.</param>
/// <returns>An enumerable containing the same elements but in a random order.</returns>
public static IEnumerable<T> Shuffle<T>(this IEnumerable<T> source)
{
return Shuffle(source, new Random());
}
/// <summary>
/// Randomise the order of the elements in the <paramref name="source"/> enumerable, using the specified <paramref name="random"/> seed.
/// </summary>
/// <typeparam name="T">The type of the elements in the <paramref name="source"/> enumerable.</typeparam>
/// <param name="source">The enumerable containing the elements to shuffle.</param>
/// <param name="random">The random seed to use.</param>
/// <returns>An enumerable containing the same elements but in a random order.</returns>
public static IEnumerable<T> Shuffle<T>(this IEnumerable<T> source, Random random)
{ // http://stackoverflow.com/questions/1287567/is-using-random-and-orderby-a-good-shuffle-algorithm
var elements = source.ToArray();
for (var i = elements.Length - 1; i >= 0; i--)
{
// Swap element "i" with a random earlier element it (or itself)
// ... except we don't really need to swap it fully, as we can
// return it immediately, and afterwards it's irrelevant.
var swapIndex = random.Next(i + 1); // Random.Next maxValue is an exclusive upper-bound, which is why we add 1
yield return elements[swapIndex];
elements[swapIndex] = elements[i];
}
}
/// <summary>
/// Returns <c>true</c> if the number of elements in the <paramref name="enumerable"/> exceeds the specified <paramref name="count"/>, without enumerating through every element.
/// </summary>
/// <typeparam name="T">The type of elements in the enumerable.</typeparam>
/// <param name="enumerable">The enumerable sequence to check.</param>
/// <param name="count">The count to exceed.</param>
/// <returns>Returns <c>true</c> if the number of elements in the <paramref name="enumerable"/> exceeds the specified <paramref name="count"/>.</returns>
public static bool CountExceeds<T>(this IEnumerable<T> enumerable, int count)
{
return enumerable.Take(count + 1).Count() > count;
}
/// <summary>
/// Converts the current <paramref name="value"/> to an enumerable, containing the <paramref name="value"/> as it's sole element.
/// </summary>
/// <typeparam name="T">The type of the element.</typeparam>
/// <param name="value">The value that the new enumerable will contain.</param>
/// <returns>Returns an enumerable containing a single element.</returns>
public static IEnumerable<T> AsSingleEnumerable<T>(this T value)
{
//x return Enumerable.Repeat(value, 1);
return new[] { value };
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
namespace HallLibrary.Extensions
{
public static class EnumerableExtensions
{
/// <summary>
/// Randomise the order of the elements in the <paramref name="source"/> enumerable.
/// </summary>
/// <typeparam name="T">The type of the elements in the <paramref name="source"/> enumerable.</typeparam>
/// <param name="source">The enumerable containing the elements to shuffle.</param>
/// <returns>An enumerable containing the same elements but in a random order.</returns>
public static IEnumerable<T> Shuffle<T>(this IEnumerable<T> source)
{
return Shuffle(source, new Random());
}
/// <summary>
/// Randomise the order of the elements in the <paramref name="source"/> enumerable, using the specified <paramref name="random"/> seed.
/// </summary>
/// <typeparam name="T">The type of the elements in the <paramref name="source"/> enumerable.</typeparam>
/// <param name="source">The enumerable containing the elements to shuffle.</param>
/// <param name="random">The random seed to use.</param>
/// <returns>An enumerable containing the same elements but in a random order.</returns>
public static IEnumerable<T> Shuffle<T>(this IEnumerable<T> source, Random random)
{ // http://stackoverflow.com/questions/1287567/is-using-random-and-orderby-a-good-shuffle-algorithm
var elements = source.ToArray();
for (var i = elements.Length - 1; i >= 0; i--)
{
// Swap element "i" with a random earlier element it (or itself)
// ... except we don't really need to swap it fully, as we can
// return it immediately, and afterwards it's irrelevant.
var swapIndex = random.Next(i + 1); // Random.Next maxValue is an exclusive upper-bound, which is why we add 1
yield return elements[swapIndex];
elements[swapIndex] = elements[i];
}
}
/// <summary>
/// Returns <c>true</c> if the number of elements in the <paramref name="enumerable"/> exceeds the specified <paramref name="count"/>, without enumerating through every element.
/// </summary>
/// <typeparam name="T">The type of elements in the enumerable.</typeparam>
/// <param name="enumerable">The enumerable sequence to check.</param>
/// <param name="count">The count to exceed.</param>
/// <returns>Returns <c>true</c> if the number of elements in the <paramref name="enumerable"/> exceeds the specified <paramref name="count"/>.</returns>
public static bool CountExceeds<T>(this IEnumerable<T> enumerable, int count)
{
return enumerable.Take(count + 1).Count() > count;
}
/// <summary>
/// Converts the current <paramref name="value"/> to an enumerable, containing the <paramref name="value"/> as it's sole element.
/// </summary>
/// <typeparam name="T">The type of the element.</typeparam>
/// <param name="value">The value that the new enumerable will contain.</param>
/// <returns>Returns an enumerable containing a single element.</returns>
public static IEnumerable<T> AsSingleEnumerable<T>(this T value)
{
//x return Enumerable.Repeat(value, 1);
return new[] { value };
}
}
}
|
apache-2.0
|
C#
|
ee900036cdc5b1c1920f6db38c38f00b66b3ed6a
|
Fix missing }
|
SteamDatabase/ValveResourceFormat
|
ValveResourceFormat/Block.cs
|
ValveResourceFormat/Block.cs
|
using System;
using System.IO;
namespace ValveResourceFormat
{
/// <summary>
/// Represents a block within the resource file.
/// </summary>
public abstract class Block
{
/// <summary>
/// Offset to the data.
/// </summary>
public uint Offset { get; set; }
/// <summary>
/// Data size.
/// </summary>
public uint Size { get; set; }
public abstract BlockType GetChar();
public abstract void Read(BinaryReader reader);
public abstract override string ToString();
/// <summary>
/// Returns a class for given block type.
/// </summary>
/// <param name="input">Block type.</param>
/// <param name="resourceType">Resource type (for DATA block only).</param>
/// <returns>
/// Constructed block type object.
/// </returns>
public static Block ConstructFromType(string input, ResourceType resourceType)
{
switch (input)
{
case "DATA":
return ConstructResourceType(resourceType);
case "REDI":
return new Blocks.ResourceEditInfo();
case "RERL":
return new Blocks.ResourceExtRefList();
case "NTRO":
return new Blocks.ResourceIntrospectionManifest();
case "VBIB":
return new Blocks.VBIB();
}
throw new ArgumentException(string.Format("Unrecognized block type '{0}'", input));
}
public static Blocks.ResourceData ConstructResourceType(ResourceType resourceType)
{
switch (resourceType)
{
case ResourceType.Panorama:
return new ResourceTypes.Panorama();
}
return new Blocks.ResourceData();
}
}
}
|
using System;
using System.IO;
namespace ValveResourceFormat
{
/// <summary>
/// Represents a block within the resource file.
/// </summary>
public abstract class Block
{
/// <summary>
/// Offset to the data.
/// </summary>
public uint Offset { get; set; }
/// <summary>
/// Data size.
/// </summary>
public uint Size { get; set; }
public abstract BlockType GetChar();
public abstract void Read(BinaryReader reader);
public abstract override string ToString();
/// <summary>
/// Returns a class for given block type.
/// </summary>
/// <param name="input">Block type.</param>
/// <param name="resourceType">Resource type (for DATA block only).</param>
/// <returns>
/// Constructed block type object.
/// </returns>
public static Block ConstructFromType(string input, ResourceType resourceType)
{
switch (input)
{
case "DATA":
return ConstructResourceType(resourceType);
case "REDI":
return new Blocks.ResourceEditInfo();
case "RERL":
return new Blocks.ResourceExtRefList();
case "NTRO":
return new Blocks.ResourceIntrospectionManifest();
case "VBIB":
return new Blocks.VBIB();
}
throw new ArgumentException(string.Format("Unrecognized block type '{0}'", input));
}
public static Blocks.ResourceData ConstructResourceType(ResourceType resourceType)
{
switch (resourceType)
{
case ResourceType.Panorama:
return new ResourceTypes.Panorama();
return new Blocks.ResourceData();
}
}
}
|
mit
|
C#
|
a2e64067a93baa89155a4a98468cade0b0bd0881
|
Implement ISlaveDataStore implicitly
|
NModbus/NModbus
|
NModbus/Data/SlaveDataStore.cs
|
NModbus/Data/SlaveDataStore.cs
|
namespace NModbus.Data
{
public class SlaveDataStore : ISlaveDataStore
{
public IPointSource<ushort> HoldingRegisters { get; } = new PointSource<ushort>();
public IPointSource<ushort> InputRegisters { get; } = new PointSource<ushort>();
public IPointSource<bool> CoilDiscretes { get; } = new PointSource<bool>();
public IPointSource<bool> CoilInputs { get; } = new PointSource<bool>();
}
}
|
namespace NModbus.Data
{
public class SlaveDataStore : ISlaveDataStore
{
private readonly IPointSource<ushort> _holdingRegisters = new PointSource<ushort>();
private readonly IPointSource<ushort> _inputRegisters = new PointSource<ushort>();
private readonly IPointSource<bool> _coilDiscretes = new PointSource<bool>();
private readonly IPointSource<bool> _coilInputs = new PointSource<bool>();
IPointSource<ushort> ISlaveDataStore.HoldingRegisters => _holdingRegisters;
IPointSource<ushort> ISlaveDataStore.InputRegisters => _inputRegisters;
IPointSource<bool> ISlaveDataStore.CoilDiscretes => _coilDiscretes;
IPointSource<bool> ISlaveDataStore.CoilInputs => _coilInputs;
}
}
|
mit
|
C#
|
373c67668c63686a8ac0be1665d8a520b0b5b9ad
|
Hide Cursor
|
ludimation/Winter,ludimation/Winter,ludimation/Winter
|
Winter/Assets/Scripts/GUIBehavior.cs
|
Winter/Assets/Scripts/GUIBehavior.cs
|
using UnityEngine;
using System.Collections;
public class GUIBehavior : MonoBehaviour {
public Texture barTexture;
public wolf wolfData;
public int boxWidth = 34;
public int boxHeight = 30;
void OnGUI () {
Screen.showCursor = false;
//Print the bar
GUI.Box (new Rect(Screen.width - barTexture.width - 18,10,barTexture.width + 8, barTexture.height + 8),barTexture);
//Print the box
GUI.Box (new Rect(Screen.width - barTexture.width / 2 - 14 - boxWidth / 2 , 8f + .97f * barTexture.height * (100f - wolfData.GetTemp()) / 100f,boxWidth,boxHeight), "");
}
void Update () {
if(Input.GetKey ("t")) {
Application.LoadLevel("Win");
print ("STUFF");
}
else if (Input.GetKey ("g")) {
Application.LoadLevel("Lose");
print ("LOSE");
}
}
}
|
using UnityEngine;
using System.Collections;
public class GUIBehavior : MonoBehaviour {
public Texture barTexture;
public wolf wolfData;
public int boxWidth = 34;
public int boxHeight = 30;
void OnGUI () {
//Print the bar
GUI.Box (new Rect(Screen.width - barTexture.width - 18,10,barTexture.width + 8, barTexture.height + 8),barTexture);
//Print the box
GUI.Box (new Rect(Screen.width - barTexture.width / 2 - 14 - boxWidth / 2 , 8f + .97f * barTexture.height * (100f - wolfData.GetTemp()) / 100f,boxWidth,boxHeight), "");
}
void Update () {
if(Input.GetKey ("t")) {
Application.LoadLevel("Win");
print ("STUFF");
}
else if (Input.GetKey ("g")) {
Application.LoadLevel("Lose");
print ("LOSE");
}
}
}
|
mit
|
C#
|
a8315461eb4239c5c5b2831fd643cc6d23919cdc
|
Add an [Obsolete] default .ctor to NSTimer for binary compatibility (will fail at compile time). Fix bug #6987
|
jorik041/maccore,mono/maccore,cwensley/maccore
|
src/Foundation/NSTimer.cs
|
src/Foundation/NSTimer.cs
|
using System;
using System.Reflection;
using System.Collections;
using System.Runtime.InteropServices;
using MonoMac.ObjCRuntime;
namespace MonoMac.Foundation {
public partial class NSTimer {
public static NSTimer CreateRepeatingScheduledTimer (TimeSpan when, NSAction action)
{
return CreateScheduledTimer (when.TotalSeconds, new NSActionDispatcher (action), NSActionDispatcher.Selector, null, true);
}
public static NSTimer CreateRepeatingScheduledTimer (double seconds, NSAction action)
{
return CreateScheduledTimer (seconds, new NSActionDispatcher (action), NSActionDispatcher.Selector, null, true);
}
public static NSTimer CreateScheduledTimer (TimeSpan when, NSAction action)
{
return CreateScheduledTimer (when.TotalSeconds, new NSActionDispatcher (action), NSActionDispatcher.Selector, null, false);
}
public static NSTimer CreateScheduledTimer (double seconds, NSAction action)
{
return CreateScheduledTimer (seconds, new NSActionDispatcher (action), NSActionDispatcher.Selector, null, false);
}
public static NSTimer CreateRepeatingTimer (TimeSpan when, NSAction action)
{
return CreateTimer (when.TotalSeconds, new NSActionDispatcher (action), NSActionDispatcher.Selector, null, true);
}
public static NSTimer CreateRepeatingTimer (double seconds, NSAction action)
{
return CreateTimer (seconds, new NSActionDispatcher (action), NSActionDispatcher.Selector, null, true);
}
public static NSTimer CreateTimer (TimeSpan when, NSAction action)
{
return CreateTimer (when.TotalSeconds, new NSActionDispatcher (action), NSActionDispatcher.Selector, null, false);
}
public static NSTimer CreateTimer (double seconds, NSAction action)
{
return CreateTimer (seconds, new NSActionDispatcher (action), NSActionDispatcher.Selector, null, false);
}
public NSTimer (NSDate date, TimeSpan when, NSAction action, System.Boolean repeats)
: this (date, when.TotalSeconds, new NSActionDispatcher (action), NSActionDispatcher.Selector, null, repeats)
{
}
[Obsolete ("This instance of NSTimer would be unusable. Symbol kept for binary compatibility", true)]
public NSTimer ()
{
}
}
}
|
using System;
using System.Reflection;
using System.Collections;
using System.Runtime.InteropServices;
using MonoMac.ObjCRuntime;
namespace MonoMac.Foundation {
public partial class NSTimer {
public static NSTimer CreateRepeatingScheduledTimer (TimeSpan when, NSAction action)
{
return CreateScheduledTimer (when.TotalSeconds, new NSActionDispatcher (action), NSActionDispatcher.Selector, null, true);
}
public static NSTimer CreateRepeatingScheduledTimer (double seconds, NSAction action)
{
return CreateScheduledTimer (seconds, new NSActionDispatcher (action), NSActionDispatcher.Selector, null, true);
}
public static NSTimer CreateScheduledTimer (TimeSpan when, NSAction action)
{
return CreateScheduledTimer (when.TotalSeconds, new NSActionDispatcher (action), NSActionDispatcher.Selector, null, false);
}
public static NSTimer CreateScheduledTimer (double seconds, NSAction action)
{
return CreateScheduledTimer (seconds, new NSActionDispatcher (action), NSActionDispatcher.Selector, null, false);
}
public static NSTimer CreateRepeatingTimer (TimeSpan when, NSAction action)
{
return CreateTimer (when.TotalSeconds, new NSActionDispatcher (action), NSActionDispatcher.Selector, null, true);
}
public static NSTimer CreateRepeatingTimer (double seconds, NSAction action)
{
return CreateTimer (seconds, new NSActionDispatcher (action), NSActionDispatcher.Selector, null, true);
}
public static NSTimer CreateTimer (TimeSpan when, NSAction action)
{
return CreateTimer (when.TotalSeconds, new NSActionDispatcher (action), NSActionDispatcher.Selector, null, false);
}
public static NSTimer CreateTimer (double seconds, NSAction action)
{
return CreateTimer (seconds, new NSActionDispatcher (action), NSActionDispatcher.Selector, null, false);
}
public NSTimer (NSDate date, TimeSpan when, NSAction action, System.Boolean repeats)
: this (date, when.TotalSeconds, new NSActionDispatcher (action), NSActionDispatcher.Selector, null, repeats)
{
}
}
}
|
apache-2.0
|
C#
|
49c19abf2be3280ce19747e882a713449123069e
|
Support for Title on Windows.
|
toroso/ruibarbo
|
ruibarbo.core/Wpf/Base/WpfWindowBase.cs
|
ruibarbo.core/Wpf/Base/WpfWindowBase.cs
|
using ruibarbo.core.ElementFactory;
using ruibarbo.core.Wpf.Invoker;
namespace ruibarbo.core.Wpf.Base
{
public class WpfWindowBase<TNativeElement> : WpfFrameworkElementBase<TNativeElement>
where TNativeElement : System.Windows.Window
{
public WpfWindowBase(ISearchSourceElement searchParent, TNativeElement frameworkElement)
: base(searchParent, frameworkElement)
{
}
public void MakeSureWindowIsTopmost()
{
OnUiThread.Invoke(this, frameworkElement => frameworkElement.Activate());
}
public string Title
{
get { return OnUiThread.Get(this, frameworkElement => frameworkElement.Title); }
}
}
}
|
using ruibarbo.core.ElementFactory;
using ruibarbo.core.Wpf.Invoker;
namespace ruibarbo.core.Wpf.Base
{
public class WpfWindowBase<TNativeElement> : WpfFrameworkElementBase<TNativeElement>
where TNativeElement : System.Windows.Window
{
public WpfWindowBase(ISearchSourceElement searchParent, TNativeElement frameworkElement)
: base(searchParent, frameworkElement)
{
}
public void MakeSureWindowIsTopmost()
{
OnUiThread.Invoke(this, fe => fe.Activate());
}
}
}
|
apache-2.0
|
C#
|
ad64d0330c872813b350a73b3d9f2ba72bbcd5ef
|
Fix nuke command exception, add autocomplete (#11828)
|
space-wizards/space-station-14,space-wizards/space-station-14,space-wizards/space-station-14,space-wizards/space-station-14,space-wizards/space-station-14,space-wizards/space-station-14
|
Content.Server/Nuke/Commands/SendNukeCodesCommand.cs
|
Content.Server/Nuke/Commands/SendNukeCodesCommand.cs
|
using System.Linq;
using Content.Server.Administration;
using Content.Server.Station.Systems;
using Content.Shared.Administration;
using JetBrains.Annotations;
using Robust.Shared.Console;
namespace Content.Server.Nuke.Commands
{
[UsedImplicitly]
[AdminCommand(AdminFlags.Fun)]
public sealed class SendNukeCodesCommand : IConsoleCommand
{
public string Command => "nukecodes";
public string Description => "Send nuke codes to a station's communication consoles";
public string Help => "nukecodes [station EntityUid]";
[Dependency] private readonly IEntityManager _entityManager = default!;
public SendNukeCodesCommand()
{
IoCManager.InjectDependencies(this);
}
public void Execute(IConsoleShell shell, string argStr, string[] args)
{
if (args.Length != 1)
{
shell.WriteError(Loc.GetString("shell-need-exactly-one-argument"));
return;
}
if (!EntityUid.TryParse(args[0], out var uid))
{
shell.WriteError(Loc.GetString("shell-entity-uid-must-be-number"));
return;
}
_entityManager.System<NukeCodePaperSystem>().SendNukeCodes(uid);
}
public CompletionResult GetCompletion(IConsoleShell shell, string[] args)
{
if (args.Length != 1)
{
return CompletionResult.Empty;
}
var stations = _entityManager
.System<StationSystem>()
.Stations
.Select(station =>
{
var meta = _entityManager.GetComponent<MetaDataComponent>(station);
return new CompletionOption(station.ToString(), meta.EntityName);
});
return CompletionResult.FromHintOptions(stations, null);
}
}
}
|
using Content.Server.Administration;
using Content.Shared.Administration;
using JetBrains.Annotations;
using Robust.Shared.Console;
namespace Content.Server.Nuke.Commands
{
[UsedImplicitly]
[AdminCommand(AdminFlags.Fun)]
public sealed class SendNukeCodesCommand : IConsoleCommand
{
public string Command => "nukecodes";
public string Description => "Send nuke codes to a station's communication consoles";
public string Help => "nukecodes [station EntityUid]";
public void Execute(IConsoleShell shell, string argStr, string[] args)
{
if (args.Length != 1)
{
shell.WriteError("shell-need-exactly-one-argument");
}
if (!EntityUid.TryParse(args[0], out var uid))
{
shell.WriteError(Loc.GetString("shell-entity-uid-must-be-number"));
}
IoCManager.Resolve<EntityManager>().System<NukeCodePaperSystem>().SendNukeCodes(uid);
}
}
}
|
mit
|
C#
|
66adaed39d5046eda675c05ace2a6f8e9a81ea77
|
Tweak the latest news view.
|
bigfont/orchard-cms-modules-and-themes,bigfont/orchard-cms-modules-and-themes,bigfont/orchard-cms-modules-and-themes,bigfont/orchard-cms-modules-and-themes,bigfont/orchard-cms-modules-and-themes
|
Orchard.Source.1.8.1/src/Orchard.Web/Themes/LccNetwork.Bootstrap/Views/ProjectionPageStaff.cshtml
|
Orchard.Source.1.8.1/src/Orchard.Web/Themes/LccNetwork.Bootstrap/Views/ProjectionPageStaff.cshtml
|
@using System.Dynamic;
@using System.Linq;
@using Orchard.ContentManagement;
@using Orchard.Utility.Extensions;
@functions
{
dynamic GetMainPartFromContentItem(ContentItem item)
{
// get the ContentPart that has the same name as the item's ContentType
// so that we can access the item fields.
var contentType = item.TypeDefinition.Name;
var parts = item.Parts as List<ContentPart>;
return parts.First(p => p.PartDefinition.Name.Equals(contentType));
}
dynamic GetTermPartFromTaxonomyField(dynamic field, int index = 0)
{
// get the termPart at index in the taxonomy field
return field !=null &&
field.Terms != null &&
field.Terms.Count > index ?
field.Terms[index] : null;
}
}
@{
var contentItems = (Model.ContentItems as IEnumerable<ContentItem>);
var cssClass = contentItems.First().TypeDefinition.Name.HtmlClassify();
<ul>
@foreach (ContentItem item in contentItems)
{
var itemDisplayUrl = Url.ItemDisplayUrl(item);
// get the mainPart, so we can access the item's fields
dynamic mainPart = GetMainPartFromContentItem(item);
var firstName = mainPart.FirstName.Value;
var lastName = mainPart.LastName.Value;
var position = mainPart.Position.Value;
var email = mainPart.Email.Value;
var lccTermPart = GetTermPartFromTaxonomyField(mainPart.Lcc);
var associatedLcc = lccTermPart != null ? lccTermPart.Name : string.Empty;
<li>
<p>@firstName @lastName @position @email @associatedLcc</p>
</li>
}
</ul>
}
|
@using System.Dynamic;
@using System.Linq;
@using Orchard.ContentManagement;
@using Orchard.Utility.Extensions;
@functions
{
dynamic GetMainPartFromContentItem(ContentItem item)
{
// get the ContentPart that has the same name as the item's ContentType
// so that we can access the item fields.
var contentType = item.TypeDefinition.Name;
var parts = item.Parts as List<ContentPart>;
return parts.First(p => p.PartDefinition.Name.Equals(contentType));
}
}
@{
var contentItems = (Model.ContentItems as IEnumerable<ContentItem>);
var cssClass = contentItems.First().TypeDefinition.Name.HtmlClassify();
<ul>
@foreach (ContentItem item in contentItems)
{
var itemDisplayUrl = Url.ItemDisplayUrl(item);
// get the mainPart, so we can access the item's fields
dynamic mainPart = GetMainPartFromContentItem(item);
var firstName = mainPart.FirstName.Value;
var lastName = mainPart.LastName.Value;
var position = mainPart.Position.Value;
var email = mainPart.Email.Value;
//var associatedLcc = mainPart.
<li>
<p>@firstName @lastName @position</p>
</li>
}
</ul>
}
|
bsd-3-clause
|
C#
|
6f91938aa853722119ac390c639aa989edc93b1f
|
Fix last binary page
|
mbdavid/LiteDB
|
LiteDB/Engine/FileCollection/BinaryFileCollection.cs
|
LiteDB/Engine/FileCollection/BinaryFileCollection.cs
|
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace LiteDB.Engine
{
/// <summary>
/// Represent an external file with binary data content. File will be break in chunks
/// </summary>
public class BinaryFileCollection : IFileCollection
{
private readonly string _filename;
private readonly int _bufferSize;
public BinaryFileCollection(string filename, int bufferSize = 8000)
{
_filename = filename;
_bufferSize = bufferSize;
}
public string Name => Path.GetFileName(_filename);
public IEnumerable<BsonDocument> Input()
{
var buffer = new byte[_bufferSize];
var bytesRead = 0;
var chunk = 0;
using (var fs = new FileStream(_filename, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
{
while((bytesRead = fs.Read(buffer, 0, _bufferSize)) > 0)
{
var data = new byte[bytesRead];
Buffer.BlockCopy(buffer, 0, data, 0, bytesRead);
yield return new BsonDocument
{
["chunk"] = chunk++,
["length"] = bytesRead,
["data"] = data
};
}
}
}
public int Output(IEnumerable<BsonValue> source)
{
var index = 0;
using (var fs = new FileStream(_filename, FileMode.CreateNew))
{
foreach(var value in source)
{
var buffer = value.AsBinary;
fs.Write(buffer, 0, buffer.Length);
index++;
}
fs.Flush();
}
return index;
}
}
}
|
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace LiteDB.Engine
{
/// <summary>
/// Represent an external file with binary data content. File will be break in chunks
/// </summary>
public class BinaryFileCollection : IFileCollection
{
private readonly string _filename;
private readonly int _bufferSize;
public BinaryFileCollection(string filename, int bufferSize = 8000)
{
_filename = filename;
_bufferSize = bufferSize;
}
public string Name => Path.GetFileName(_filename);
public IEnumerable<BsonDocument> Input()
{
var buffer = new byte[_bufferSize];
var bytesRead = 0;
var chunk = 0;
using (var fs = new FileStream(_filename, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
{
while((bytesRead = fs.Read(buffer, 0, _bufferSize)) > 0)
{
yield return new BsonDocument
{
["chunk"] = chunk++,
["length"] = bytesRead,
["data"] = buffer
};
buffer = new byte[_bufferSize];
}
}
}
public int Output(IEnumerable<BsonValue> source)
{
var index = 0;
using (var fs = new FileStream(_filename, FileMode.CreateNew))
{
foreach(var value in source)
{
var buffer = value.AsBinary;
fs.Write(buffer, 0, buffer.Length);
index++;
}
fs.Flush();
}
return index;
}
}
}
|
mit
|
C#
|
ee25f4c0b85fe30f4fb8325ed4b74b1d4d4a74e0
|
Fix attempting to filter by project filtered by context instead
|
hartez/TodotxtTouch.WindowsPhone
|
TodotxtTouch.WindowsPhone/Tasks/TaskFilterFactory.cs
|
TodotxtTouch.WindowsPhone/Tasks/TaskFilterFactory.cs
|
using System;
using System.Collections.Generic;
using System.Linq;
using EZLibrary;
using TodotxtTouch.WindowsPhone.ViewModel;
namespace TodotxtTouch.WindowsPhone.Tasks
{
public class TaskFilterFactory
{
private const char Delimiter = ',';
public static TaskFilter CreateTaskFilterFromString(string filter)
{
if (filter.StartsWith("context:"))
{
string target = filter.Replace("context:", String.Empty);
return new ContextTaskFilter(
task => task.Contexts.Contains(target),
target);
}
if (filter.StartsWith("project:"))
{
string target = filter.Replace("project: ", "+");
return new ProjectTaskFilter(
task => task.Projects.Contains(target),
target);
}
return null;
}
public static List<TaskFilter> ParseFilterString(string filter)
{
string[] filters = filter.Split(Delimiter);
return filters.Where(f => !String.IsNullOrEmpty(f)).Select(CreateTaskFilterFromString).ToList();
}
public static string CreateFilterString(List<TaskFilter> filters)
{
return filters.ToDelimitedList(t => t.ToString(), Delimiter.ToString());
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using EZLibrary;
using TodotxtTouch.WindowsPhone.ViewModel;
namespace TodotxtTouch.WindowsPhone.Tasks
{
public class TaskFilterFactory
{
private const char Delimiter = ',';
public static TaskFilter CreateTaskFilterFromString(string filter)
{
if (filter.StartsWith("context:"))
{
string target = filter.Replace("context:", String.Empty);
return new ContextTaskFilter(
task => task.Contexts.Contains(target),
target);
}
if (filter.StartsWith("project:"))
{
string target = filter.Replace("project: ", "+");
return new ContextTaskFilter(
task => task.Projects.Contains(target),
target);
}
return null;
}
public static List<TaskFilter> ParseFilterString(string filter)
{
string[] filters = filter.Split(Delimiter);
return filters.Where(f => !String.IsNullOrEmpty(f)).Select(CreateTaskFilterFromString).ToList();
}
public static string CreateFilterString(List<TaskFilter> filters)
{
return filters.ToDelimitedList(t => t.ToString(), Delimiter.ToString());
}
}
}
|
mit
|
C#
|
62dbd059367204ea4bcebf4e72ac38b5a5277762
|
Rewrite VerifyPhoneNumber form markup
|
peterblazejewicz/aspnet-5-bootstrap-4,peterblazejewicz/aspnet-5-bootstrap-4
|
WebApplication/Views/Manage/VerifyPhoneNumber.cshtml
|
WebApplication/Views/Manage/VerifyPhoneNumber.cshtml
|
@model VerifyPhoneNumberViewModel
@{
ViewData["Title"] = "Verify Phone Number";
}
<h2>@ViewData["Title"].</h2>
<form asp-controller="Manage" asp-action="VerifyPhoneNumber" asp-route-returnurl="@ViewData["ReturnUrl"]" method="post" role="form">
<input asp-for="PhoneNumber" type="hidden" />
<h4>Add a phone number.</h4>
<h5>@ViewData["Status"]</h5>
<hr />
<div asp-validation-summary="ValidationSummary.All" class="text-danger"></div>
<fieldset>
<div class="form-group row">
<label asp-for="Code" class="col-md-2 control-label"></label>
<div class="col-md-10">
<input asp-for="Code" class="form-control" />
<span asp-validation-for="Code" class="text-danger"></span>
</div>
</div>
<div class="form-group row">
<div class="col-md-offset-2 col-md-10">
<button type="submit" class="btn btn-primary">Submit</button>
</div>
</div>
</fieldset>
</form>
@section Scripts {
@{ await Html.RenderPartialAsync("_ValidationScriptsPartial"); }
}
|
@model VerifyPhoneNumberViewModel
@{
ViewData["Title"] = "Verify Phone Number";
}
<h2>@ViewData["Title"].</h2>
<form asp-controller="Manage" asp-action="VerifyPhoneNumber" asp-route-returnurl="@ViewData["ReturnUrl"]" method="post" role="form">
<input asp-for="PhoneNumber" type="hidden" />
<h4>Add a phone number.</h4>
<h5>@ViewData["Status"]</h5>
<hr />
<div asp-validation-summary="ValidationSummary.All" class="text-danger"></div>
<div class="form-group">
<label asp-for="Code" class="col-md-2 control-label"></label>
<div class="col-md-10">
<input asp-for="Code" class="form-control" />
<span asp-validation-for="Code" class="text-danger"></span>
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<button type="submit" class="btn btn-default">Submit</button>
</div>
</div>
</form>
@section Scripts {
@{ await Html.RenderPartialAsync("_ValidationScriptsPartial"); }
}
|
mit
|
C#
|
2a8c5aa5c5d0cdbb7e981ab438315a578430da98
|
Fix potential test failure due to not waiting long enough on track start
|
peppy/osu-framework,EVAST9919/osu-framework,EVAST9919/osu-framework,EVAST9919/osu-framework,peppy/osu-framework,ZLima12/osu-framework,ppy/osu-framework,ppy/osu-framework,EVAST9919/osu-framework,ppy/osu-framework,ZLima12/osu-framework,smoogipooo/osu-framework,smoogipooo/osu-framework,peppy/osu-framework
|
osu.Framework.Tests/Audio/DevicelessAudioTest.cs
|
osu.Framework.Tests/Audio/DevicelessAudioTest.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 NUnit.Framework;
namespace osu.Framework.Tests.Audio
{
[TestFixture]
public class DevicelessAudioTest : AudioThreadTest
{
public override void SetUp()
{
base.SetUp();
// lose all devices
Manager.SimulateDeviceLoss();
}
[Test]
public void TestPlayTrackWithoutDevices()
{
var track = Manager.Tracks.Get("Tracks.sample-track.mp3");
// start track
track.Restart();
WaitForOrAssert(() => track.IsRunning, "Track started", 1000);
CheckTrackIsProgressing(track);
// stop track
track.Stop();
WaitForOrAssert(() => !track.IsRunning, "Track did not stop", 1000);
Assert.IsFalse(track.IsRunning);
// seek track
track.Seek(0);
Assert.IsFalse(track.IsRunning);
WaitForOrAssert(() => track.CurrentTime == 0, "Track did not seek correctly", 1000);
}
}
}
|
// 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 NUnit.Framework;
namespace osu.Framework.Tests.Audio
{
[TestFixture]
public class DevicelessAudioTest : AudioThreadTest
{
public override void SetUp()
{
base.SetUp();
// lose all devices
Manager.SimulateDeviceLoss();
}
[Test]
public void TestPlayTrackWithoutDevices()
{
var track = Manager.Tracks.Get("Tracks.sample-track.mp3");
// start track
track.Restart();
Assert.IsTrue(track.IsRunning);
CheckTrackIsProgressing(track);
// stop track
track.Stop();
WaitForOrAssert(() => !track.IsRunning, "Track did not stop", 1000);
Assert.IsFalse(track.IsRunning);
// seek track
track.Seek(0);
Assert.IsFalse(track.IsRunning);
WaitForOrAssert(() => track.CurrentTime == 0, "Track did not seek correctly", 1000);
}
}
}
|
mit
|
C#
|
0fb86e505ddeabf4964ee4f087a8bf9b3575191a
|
添加多租户OAuth演示 #1550
|
JeffreySu/WeiXinMPSDK,jiehanlin/WeiXinMPSDK,lishewen/WeiXinMPSDK,jiehanlin/WeiXinMPSDK,mc7246/WeiXinMPSDK,mc7246/WeiXinMPSDK,lishewen/WeiXinMPSDK,JeffreySu/WeiXinMPSDK,JeffreySu/WeiXinMPSDK,lishewen/WeiXinMPSDK,mc7246/WeiXinMPSDK,jiehanlin/WeiXinMPSDK
|
Samples/Senparc.Weixin.MP.Sample.vs2017/Senparc.Weixin.MP.CoreSample/Filters/CustomOAuthAttribute.cs
|
Samples/Senparc.Weixin.MP.Sample.vs2017/Senparc.Weixin.MP.CoreSample/Filters/CustomOAuthAttribute.cs
|
using System.Linq;
using System.Web;
using Microsoft.AspNetCore.Http;
using Senparc.CO2NET;
using Senparc.CO2NET.Trace;
using Senparc.Weixin.MP.MvcExtension;
namespace Senparc.Weixin.MP.CoreSample.Filters
{
/// <summary>
/// OAuth自动验证,可以加在Action或整个Controller上
/// </summary>
public class CustomOAuthAttribute : SenparcOAuthAttribute
{
public CustomOAuthAttribute(string appId, string oauthCallbackUrl)
: base(appId, oauthCallbackUrl)
{
//如果是多租户,appId 可以传入 null,并且忽略下一行,使用 IsLogined() 方法中的动态赋值语句
base._appId = base._appId ?? Config.SenparcWeixinSetting.TenPayV3_AppId;//填写公众号AppId(适用于公众号、微信支付、JsApi等)
}
public override bool IsLogined(HttpContext httpContext)
{
//如果是多租户,也可以这样写,通过 URL 参数来区分:
//base._appId = httpContext.Request.Query["appId"].FirstOrDefault();//appId也可以是数据库存储的Id,避免暴露真实的AppId
return httpContext != null && httpContext.Session.GetString("OpenId") != null;
//也可以使用其他方法如Session验证用户登录
//return httpContext != null && httpContext.User.Identity.IsAuthenticated;
}
}
}
|
using System.Linq;
using System.Web;
using Microsoft.AspNetCore.Http;
using Senparc.CO2NET;
using Senparc.CO2NET.Trace;
using Senparc.Weixin.MP.MvcExtension;
namespace Senparc.Weixin.MP.CoreSample.Filters
{
/// <summary>
/// OAuth自动验证,可以加在Action或整个Controller上
/// </summary>
public class CustomOAuthAttribute : SenparcOAuthAttribute
{
public CustomOAuthAttribute(string appId, string oauthCallbackUrl)
: base(appId, oauthCallbackUrl)
{
base._appId = base._appId ?? Config.SenparcWeixinSetting.TenPayV3_AppId;
//如果是多租户,也可以这样写,通过 URL 参数来区分:
var httpContextAccessor = SenparcDI.GetService<IHttpContextAccessor>();
base._appId = httpContextAccessor.HttpContext.Request.Query["appId"].FirstOrDefault();//appId也可以是数据库存储的Id,避免暴露真实的AppId
//SenparcTrace.SendCustomLog("SenparcOAuthAttribute3 测试00", httpContextAccessor.HttpContext.Request.ToJson(true));
SenparcTrace.SendCustomLog("SenparcOAuthAttribute3 测试00", httpContextAccessor.HttpContext.Request.AbsoluteUri());
SenparcTrace.SendCustomLog("SenparcOAuthAttribute3 测试11", httpContextAccessor.HttpContext.Request.Query["appId"].FirstOrDefault());
SenparcTrace.SendCustomLog("SenparcOAuthAttribute3 测试22", httpContextAccessor.HttpContext.Request.Query["oauthCallbackUrl"].FirstOrDefault());
SenparcTrace.SendCustomLog("SenparcOAuthAttribute3 测试33", httpContextAccessor.HttpContext.Request.Query["productId"].FirstOrDefault());
SenparcTrace.SendCustomLog("SenparcOAuthAttribute3 测试44", httpContextAccessor.HttpContext.Request.Query["hc"].FirstOrDefault());
}
public override bool IsLogined(HttpContext httpContext)
{
var httpContextAccessor = SenparcDI.GetService<IHttpContextAccessor>();
//SenparcTrace.SendCustomLog("SenparcOAuthAttribute4 测试00", httpContextAccessor.HttpContext.Request.ToJson(true));
SenparcTrace.SendCustomLog("SenparcOAuthAttribute4 测试00", httpContextAccessor.HttpContext.Request.AbsoluteUri());
SenparcTrace.SendCustomLog("SenparcOAuthAttribute4 测试11", httpContextAccessor.HttpContext.Request.Query["appId"].FirstOrDefault());
SenparcTrace.SendCustomLog("SenparcOAuthAttribute4 测试22", httpContextAccessor.HttpContext.Request.Query["oauthCallbackUrl"].FirstOrDefault());
SenparcTrace.SendCustomLog("SenparcOAuthAttribute4 测试33", httpContextAccessor.HttpContext.Request.Query["productId"].FirstOrDefault());
SenparcTrace.SendCustomLog("SenparcOAuthAttribute4 测试44", httpContextAccessor.HttpContext.Request.Query["hc"].FirstOrDefault());
return httpContext != null && httpContext.Session.GetString("OpenId") != null;
//也可以使用其他方法如Session验证用户登录
//return httpContext != null && httpContext.User.Identity.IsAuthenticated;
}
}
}
|
apache-2.0
|
C#
|
3a3b2146f4fc5bc870f42f732a5228b0452bd450
|
bump version
|
GeertvanHorrik/Fody,distantcam/Fody,ColinDabritzViewpoint/Fody,Fody/Fody,ichengzi/Fody,jasonholloway/Fody,huoxudong125/Fody,furesoft/Fody,PKRoma/Fody
|
CommonAssemblyInfo.cs
|
CommonAssemblyInfo.cs
|
using System.Reflection;
[assembly: AssemblyTitle("Fody")]
[assembly: AssemblyProduct("Fody")]
[assembly: AssemblyVersion("1.17.4")]
[assembly: AssemblyFileVersion("1.17.4")]
|
using System.Reflection;
[assembly: AssemblyTitle("Fody")]
[assembly: AssemblyProduct("Fody")]
[assembly: AssemblyVersion("1.17.1")]
[assembly: AssemblyFileVersion("1.17.1")]
|
mit
|
C#
|
d94165757e10c9a6d43ecc4df41177b97c2e4605
|
fix Variable serialization
|
cbovar/ConvNetSharp
|
src/ConvNetSharp.Flow/Ops/Variable.cs
|
src/ConvNetSharp.Flow/Ops/Variable.cs
|
using System;
using System.Collections.Generic;
using System.Diagnostics;
using ConvNetSharp.Volume;
namespace ConvNetSharp.Flow.Ops
{
[DebuggerDisplay("{Name}")]
public class Variable<T> : Op<T>, IPersistable<T> where T : struct, IEquatable<T>, IFormattable
{
public Variable(Volume<T> v, string name, bool isLearnable = false)
{
this.Name = name;
this.Result = v;
this.IsLearnable = isLearnable;
}
public Variable(Dictionary<string, object> data)
{
this.Name = (string)data["Name"];
this.IsLearnable = (string)data["IsLearnable"] == "True";
}
public override string Representation => this.Name;
public string Name { get; set; }
public bool IsLearnable { get; }
public void SetValue(Volume<T> value)
{
this.Result = value;
SetDirty();
}
protected override void Dispose(bool disposing)
{
if (disposing)
{
this.Result?.Dispose();
}
base.Dispose(disposing);
}
public override Dictionary<string, object> GetData()
{
var data = base.GetData();
data["Name"] = this.Name;
data["IsLearnable"] = this.IsLearnable;
return data;
}
public override string ToString()
{
return this.Name;
}
}
}
|
using System;
using System.Collections.Generic;
using System.Diagnostics;
using ConvNetSharp.Volume;
namespace ConvNetSharp.Flow.Ops
{
[DebuggerDisplay("{Name}")]
public class Variable<T> : Op<T>, IPersistable<T>, IValueOp<T> where T : struct, IEquatable<T>, IFormattable
{
public Variable(Volume<T> v, string name)
{
this.Name = name;
this.Result = v;
}
public Variable(Dictionary<string, object> data)
{
this.Name = (string) data["Name"];
}
public override string Representation => this.Name;
public string Name { get; set; }
public void SetValue(Volume<T> value)
{
this.Result = value;
SetDirty();
}
public override void Differentiate()
{
}
protected override void Dispose(bool disposing)
{
if (disposing)
{
this.Result?.Dispose();
}
base.Dispose(disposing);
}
public override Volume<T> Evaluate(Session<T> session)
{
return this.Result;
}
public override Dictionary<string, object> GetData()
{
var data = base.GetData();
data["Name"] = this.Name;
return data;
}
public override string ToString()
{
return this.Name;
}
}
}
|
mit
|
C#
|
6cb5fad8e1ca9bf5c90e088c4fe6977a85697626
|
Update Markdown output to match linter now used in NUnit docs
|
rprouse/GetChanges
|
GetChanges/Program.cs
|
GetChanges/Program.cs
|
using Nito.AsyncEx;
using Octokit;
using System;
using System.Collections.Generic;
using System.Linq;
namespace Alteridem.GetChanges
{
class Program
{
static int Main(string[] args)
{
var options = new Options();
if (!CommandLine.Parser.Default.ParseArguments(args, options))
{
return -1;
}
AsyncContext.Run(() => MainAsync(options));
//Console.WriteLine("*** Press ENTER to Exit ***");
//Console.ReadLine();
return 0;
}
static async void MainAsync(Options options)
{
var github = new GitHubApi(options.Organization, options.Repository);
var milestones = await github.GetOpenMilestones();
foreach (var milestone in milestones.Where(m => m.DueOn != null && m.DueOn.Value.Subtract(DateTimeOffset.Now).TotalDays < 30))
{
var milestoneIssues = await github.GetClosedIssuesForMilestone(milestone);
DisplayIssuesForMilestone(options, milestone.Title, milestoneIssues);
}
}
static void DisplayIssuesForMilestone(Options options, string milestone, IEnumerable<Issue> issues)
{
Console.WriteLine("## {0}", milestone);
Console.WriteLine();
foreach (var issue in issues)
{
if(options.LinkIssues)
Console.WriteLine($"* [{issue.Number:####}](https://github.com/{options.Organization}/{options.Repository}/issues/{issue.Number}) {issue.Title}");
else
Console.WriteLine($"* {issue.Number:####} {issue.Title}");
}
Console.WriteLine();
}
}
}
|
using Nito.AsyncEx;
using Octokit;
using System;
using System.Collections.Generic;
using System.Linq;
namespace Alteridem.GetChanges
{
class Program
{
static int Main(string[] args)
{
var options = new Options();
if (!CommandLine.Parser.Default.ParseArguments(args, options))
{
return -1;
}
AsyncContext.Run(() => MainAsync(options));
//Console.WriteLine("*** Press ENTER to Exit ***");
//Console.ReadLine();
return 0;
}
static async void MainAsync(Options options)
{
var github = new GitHubApi(options.Organization, options.Repository);
var milestones = await github.GetOpenMilestones();
foreach (var milestone in milestones.Where(m => m.DueOn != null && m.DueOn.Value.Subtract(DateTimeOffset.Now).TotalDays < 30))
{
var milestoneIssues = await github.GetClosedIssuesForMilestone(milestone);
DisplayIssuesForMilestone(options, milestone.Title, milestoneIssues);
}
}
static void DisplayIssuesForMilestone(Options options, string milestone, IEnumerable<Issue> issues)
{
Console.WriteLine("## {0}", milestone);
Console.WriteLine();
foreach (var issue in issues)
{
if(options.LinkIssues)
Console.WriteLine($" * [{issue.Number:####}](https://github.com/{options.Organization}/{options.Repository}/issues/{issue.Number}) {issue.Title}");
else
Console.WriteLine($" * {issue.Number:####} {issue.Title}");
}
Console.WriteLine();
}
}
}
|
mit
|
C#
|
22c7f28b77adad58852edef9b33d6ba9c3a7de32
|
Add comment and cleanup to the Program class in snippets.
|
ivanpointer/NuLog,ivanpointer/NuLog,ivanpointer/NuLog,ivanpointer/NuLog,ivanpointer/NuLog
|
Take2/NuLogSnippets/Program.cs
|
Take2/NuLogSnippets/Program.cs
|
/* © 2017 Ivan Pointer
MIT License: https://github.com/ivanpointer/NuLog/blob/master/LICENSE
Source on GitHub: https://github.com/ivanpointer/NuLog */
namespace NuLogSnippets
{
internal class Program
{
private static void Main(string[] args)
{
// Nothing to do. Code is here for documentation purposes.
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace NuLogSnippets
{
class Program
{
static void Main(string[] args)
{
}
}
}
|
mit
|
C#
|
22cad15845fc07d07e50153c2ccfaf65972d49f3
|
handle action not found
|
barld/project5_6,barld/project5_6,barld/project5_6
|
MVC/RequestHandler.cs
|
MVC/RequestHandler.cs
|
using MVC.View;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
namespace MVC
{
internal class RequestHandler
{
private readonly ControllerFactory controllerFartory;
private readonly HttpListenerContext HttpContext;
internal RequestHandler(ControllerFactory cFactory, HttpListenerContext context)
{
controllerFartory = cFactory;
HttpContext = context;
}
internal ViewObject HandelToView()
{
var deCodedRawUrl = WebUtility.UrlDecode(HttpContext.Request.RawUrl);
var urlParts = deCodedRawUrl
.Split('?', '#')
.First().Split('/')
.Where(s => !String.IsNullOrWhiteSpace(s))
.Select(s => s.ToLower())
.ToList();
using (var controller = controllerFartory.GetByRawUrl(urlParts[0]))
{
var controllerType = controller.GetType();
MethodInfo method;
if(urlParts.Count > 1)
{
method = controllerType.GetMethods()
.FirstOrDefault(mi => mi.Name.ToLower() == $"get{urlParts[1]}");
}
else
{
method = controllerType.GetMethods()
.FirstOrDefault(mi => mi.Name.ToLower() == "get");
}
var result = method?.Invoke(controller, new object[] { });
if (result != null && result is ViewObject)
return (result as ViewObject);
else if(method == null)
return new NotFoundView("action not found");
else
return new RawObjectView(result);
}
}
}
}
|
using MVC.View;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
namespace MVC
{
internal class RequestHandler
{
private readonly ControllerFactory controllerFartory;
private readonly HttpListenerContext HttpContext;
internal RequestHandler(ControllerFactory cFactory, HttpListenerContext context)
{
controllerFartory = cFactory;
HttpContext = context;
}
internal ViewObject HandelToView()
{
var deCodedRawUrl = WebUtility.UrlDecode(HttpContext.Request.RawUrl);
var UrlParts = deCodedRawUrl
.Split('?', '#')
.First().Split('/')
.Where(s => !String.IsNullOrWhiteSpace(s))
.Select(s => s.ToLower())
.ToList();
using (var controller = controllerFartory.GetByRawUrl(UrlParts[0]))
{
var controllerType = controller.GetType();
MethodInfo method;
if(UrlParts.Count > 1)
{
method = controllerType.GetMethods()
.FirstOrDefault(mi => mi.Name.ToLower() == $"get{UrlParts[1]}");
}
else
{
method = controllerType.GetMethods()
.FirstOrDefault(mi => mi.Name.ToLower() == "get");
}
var result = method?.Invoke(controller, new object[] { });
if (result != null && result is ViewObject)
return (result as ViewObject);
else
return new RawObjectView(result);
}
}
}
}
|
mit
|
C#
|
3e3d3de89eea1fb32194dd70e46595d0b270efe4
|
Set CreateTime & UpdateTime nullable.
|
OShop/OShop.PayPal,OShop/OShop.PayPal
|
Models/Api/Payment.cs
|
Models/Api/Payment.cs
|
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using System;
using System.Collections.Generic;
namespace OShop.PayPal.Models.Api {
public class Payment {
[JsonProperty("intent", Required = Required.Always)]
[JsonConverter(typeof(StringEnumConverter))]
public PaymentIntent Intent { get; set; }
[JsonProperty("payer", Required = Required.Always)]
public Payer Payer { get; set; }
[JsonProperty("transactions", Required = Required.Always)]
public List<Transaction> Transactions { get; set; }
[JsonProperty("redirect_urls", NullValueHandling = NullValueHandling.Ignore)]
public RedirectUrls RedirectUrls { get; set; }
[JsonProperty("id", NullValueHandling = NullValueHandling.Ignore)]
public string Id { get; set; }
[JsonProperty("create_time", NullValueHandling = NullValueHandling.Ignore)]
public DateTime? CreateTime { get; set; }
[JsonProperty("state", NullValueHandling = NullValueHandling.Ignore)]
[JsonConverter(typeof(StringEnumConverter))]
public PaymentState State { get; set; }
[JsonProperty("update_time", NullValueHandling = NullValueHandling.Ignore)]
public DateTime? UpdateTime { get; set; }
[JsonProperty("experience_profile_id", NullValueHandling = NullValueHandling.Ignore)]
public string ExperienceProfileId { get; set; }
[JsonProperty("links", NullValueHandling = NullValueHandling.Ignore)]
public List<Link> Links { get; set; }
}
public enum PaymentIntent {
[JsonProperty("sale")]
Sale,
[JsonProperty("authorize")]
Authorize,
[JsonProperty("order")]
Order
}
public enum PaymentState {
[JsonProperty("created")]
Created,
[JsonProperty("approved")]
Approved,
[JsonProperty("failed")]
Failed,
[JsonProperty("pending")]
Pending,
[JsonProperty("canceled")]
Canceled,
[JsonProperty("expired")]
Expired,
[JsonProperty("in_progress")]
InProgress
}
}
|
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using System;
using System.Collections.Generic;
namespace OShop.PayPal.Models.Api {
public class Payment {
[JsonProperty("intent", Required = Required.Always)]
[JsonConverter(typeof(StringEnumConverter))]
public PaymentIntent Intent { get; set; }
[JsonProperty("payer", Required = Required.Always)]
public Payer Payer { get; set; }
[JsonProperty("transactions", Required = Required.Always)]
public List<Transaction> Transactions { get; set; }
[JsonProperty("redirect_urls", NullValueHandling = NullValueHandling.Ignore)]
public RedirectUrls RedirectUrls { get; set; }
[JsonProperty("id", NullValueHandling = NullValueHandling.Ignore)]
public string Id { get; set; }
[JsonProperty("create_time", NullValueHandling = NullValueHandling.Ignore)]
public DateTime CreateTime { get; set; }
[JsonProperty("state", NullValueHandling = NullValueHandling.Ignore)]
[JsonConverter(typeof(StringEnumConverter))]
public PaymentState State { get; set; }
[JsonProperty("update_time", NullValueHandling = NullValueHandling.Ignore)]
public DateTime UpdateTime { get; set; }
[JsonProperty("experience_profile_id", NullValueHandling = NullValueHandling.Ignore)]
public string ExperienceProfileId { get; set; }
[JsonProperty("links", NullValueHandling = NullValueHandling.Ignore)]
public List<Link> Links { get; set; }
}
public enum PaymentIntent {
[JsonProperty("sale")]
Sale,
[JsonProperty("authorize")]
Authorize,
[JsonProperty("order")]
Order
}
public enum PaymentState {
[JsonProperty("created")]
Created,
[JsonProperty("approved")]
Approved,
[JsonProperty("failed")]
Failed,
[JsonProperty("pending")]
Pending,
[JsonProperty("canceled")]
Canceled,
[JsonProperty("expired")]
Expired,
[JsonProperty("in_progress")]
InProgress
}
}
|
mit
|
C#
|
f95222bcfb09b77df86809c70f9aed93a1e3de6e
|
Set version to 1.0.0
|
TheOtherTimDuncan/TOTD-Mailer
|
SharedAssemblyInfo.cs
|
SharedAssemblyInfo.cs
|
using System.Reflection;
// 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: AssemblyConfiguration("")]
[assembly: AssemblyCompany("The Other Tim Duncan")]
[assembly: AssemblyProduct("TOTD Mailer")]
[assembly: AssemblyCopyright("Copyright © 2016")]
[assembly: AssemblyTrademark("")]
// 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.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
|
using System.Reflection;
// 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: AssemblyConfiguration("")]
[assembly: AssemblyCompany("The Other Tim Duncan")]
[assembly: AssemblyProduct("TOTD Mailer")]
[assembly: AssemblyCopyright("Copyright © 2016")]
[assembly: AssemblyTrademark("")]
// 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.0.0.0")]
[assembly: AssemblyFileVersion("2.0.0.0")]
|
mit
|
C#
|
61f1b63c19f5f260493136d536aa880ebc76570b
|
Bump version number
|
mjanthony/Huxley,jpsingleton/Huxley,Newsworthy/Huxley,Newsworthy/Huxley,mjanthony/Huxley,jpsingleton/Huxley
|
src/Huxley/Properties/AssemblyInfo.cs
|
src/Huxley/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("Huxley")]
[assembly: AssemblyDescription("A restful JSON proxy for the UK National Rail Live Departure Board SOAP API (Darwin)")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("James Singleton (unop.uk)")]
[assembly: AssemblyProduct("Huxley")]
[assembly: AssemblyCopyright("Copyright © 2015")]
[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("73cde2fa-1069-4e90-b2ce-f97c866b296e")]
// 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.2.0.0")]
[assembly: AssemblyFileVersion("1.2.0.0")]
|
using System.Reflection;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("Huxley")]
[assembly: AssemblyDescription("A restful JSON proxy for the UK National Rail Live Departure Board SOAP API (Darwin)")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("James Singleton (unop.uk)")]
[assembly: AssemblyProduct("Huxley")]
[assembly: AssemblyCopyright("Copyright © 2015")]
[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("73cde2fa-1069-4e90-b2ce-f97c866b296e")]
// 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.1.0.0")]
[assembly: AssemblyFileVersion("1.1.0.0")]
|
agpl-3.0
|
C#
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.