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 |
|---|---|---|---|---|---|---|---|---|
02aeca29ba327cf4933916d1cc9855addeb9ab6b
|
Fix FileLoggingConfiguration comments
|
tgstation/tgstation-server,Cyberboss/tgstation-server,tgstation/tgstation-server,Cyberboss/tgstation-server,tgstation/tgstation-server-tools
|
src/Tgstation.Server.Host/Configuration/FileLoggingConfiguration.cs
|
src/Tgstation.Server.Host/Configuration/FileLoggingConfiguration.cs
|
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
namespace Tgstation.Server.Host.Configuration
{
/// <summary>
/// File logging configuration options
/// </summary>
sealed class FileLoggingConfiguration
{
/// <summary>
/// The key for the <see cref="Microsoft.Extensions.Configuration.IConfigurationSection"/> the <see cref="FileLoggingConfiguration"/> resides in
/// </summary>
public const string Section = "FileLogging";
/// <summary>
/// Default value for <see cref="LogLevel"/>
/// </summary>
const LogLevel DefaultLogLevel = LogLevel.Debug;
/// <summary>
/// Default value for <see cref="MicrosoftLogLevel"/>
/// </summary>
const LogLevel DefaultMicrosoftLogLevel = LogLevel.Warning;
/// <summary>
/// Where log files are stored
/// </summary>
public string Directory { get; set; }
/// <summary>
/// If file logging is disabled
/// </summary>
public bool Disable { get; set; }
/// <summary>
/// The minimum <see cref="Microsoft.Extensions.Logging.LogLevel"/> to display in logs
/// </summary>
[JsonConverter(typeof(StringEnumConverter))]
public LogLevel LogLevel { get; set; } = DefaultLogLevel;
/// <summary>
/// The minimum <see cref="Microsoft.Extensions.Logging.LogLevel"/> to display in logs for Microsoft library sources
/// </summary>
[JsonConverter(typeof(StringEnumConverter))]
public LogLevel MicrosoftLogLevel { get; set; } = DefaultMicrosoftLogLevel;
}
}
|
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
namespace Tgstation.Server.Host.Configuration
{
/// <summary>
/// File logging configuration options
/// </summary>
sealed class FileLoggingConfiguration
{
/// <summary>
/// The key for the <see cref="Microsoft.Extensions.Configuration.IConfigurationSection"/> the <see cref="FileLoggingConfiguration"/> resides in
/// </summary>
public const string Section = "FileLogging";
/// <summary>
/// Default value for <see cref="LogLevel"/>
/// </summary>
const LogLevel DefaultLogLevel = LogLevel.Debug;
/// <summary>
/// Default value for <see cref="MicrosoftLogLevel"/>
/// </summary>
const LogLevel DefaultMicrosoftLogLevel = LogLevel.Warning;
/// <summary>
/// Where log files are stored
/// </summary>
public string Directory { get; set; }
/// <summary>
/// If file logging is disabled
/// </summary>
public bool Disable { get; set; }
/// <summary>
/// The <see cref="string"/>ified minimum <see cref="Microsoft.Extensions.Logging.LogLevel"/> to display in logs
/// </summary>
[JsonConverter(typeof(StringEnumConverter))]
public LogLevel LogLevel { get; set; } = DefaultLogLevel;
/// <summary>
/// The <see cref="string"/>ified minimum <see cref="Microsoft.Extensions.Logging.LogLevel"/> to display in logs for Microsoft library sources
/// </summary>
[JsonConverter(typeof(StringEnumConverter))]
public LogLevel MicrosoftLogLevel { get; set; } = DefaultMicrosoftLogLevel;
}
}
|
agpl-3.0
|
C#
|
826ebf3bb61544c3a438024fb0471950b1026a4b
|
fix bug when reading authors
|
StephenClearyApps/DotNetApis,StephenClearyApps/DotNetApis,StephenClearyApps/DotNetApis,StephenClearyApps/DotNetApis
|
service/DotNetApis.Nuget/NugetPackage.InternalMetadata.cs
|
service/DotNetApis.Nuget/NugetPackage.InternalMetadata.cs
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Sockets;
using NuGet.Packaging;
using NuGet.Packaging.Core;
namespace DotNetApis.Nuget
{
partial class NugetPackage
{
/// <summary>
/// Package metadata contained within the package itself.
/// </summary>
public sealed class InternalMetadata
{
internal InternalMetadata(IPackageCoreReader package)
{
NuspecReader = new NuspecReader(package.GetNuspec());
PackageId = package.GetIdentity().Id;
Version = NugetVersion.FromNuGetVersion(package.GetIdentity().Version);
}
private static string NullIfEmpty(string data) => data == "" ? null : data;
/// <summary>
/// Gets the .nuspec reader for this package.
/// </summary>
public NuspecReader NuspecReader { get; }
public string PackageId { get; }
public NugetVersion Version { get; }
public string Title => NullIfEmpty(NuspecReader.GetTitle());
public string Summary => NullIfEmpty(NuspecReader.GetSummary()) ?? NullIfEmpty(NuspecReader.GetDescription());
public string Description => NullIfEmpty(NuspecReader.GetDescription()) ?? NullIfEmpty(NuspecReader.GetSummary());
private static readonly char[] Comma = { ',' };
public IReadOnlyList<string> Authors
{
get
{
var authors = NuspecReader.GetAuthors().Split(Comma, StringSplitOptions.RemoveEmptyEntries);
if (authors.Length != 0)
return authors.Select(x => x.Trim()).ToList();
return NuspecReader.GetMetadata().Where(x => string.Equals(x.Key, "author", StringComparison.InvariantCultureIgnoreCase)).Select(x => x.Value).ToList();
}
}
public string IconUrl => NullIfEmpty(NuspecReader.GetIconUrl());
public string ProjectUrl => NullIfEmpty(NuspecReader.GetProjectUrl());
/// <summary>
/// Returns an identifying string for this package, in the form "Id ver".
/// </summary>
public override string ToString() => PackageId + " " + Version;
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using NuGet.Packaging;
using NuGet.Packaging.Core;
namespace DotNetApis.Nuget
{
partial class NugetPackage
{
/// <summary>
/// Package metadata contained within the package itself.
/// </summary>
public sealed class InternalMetadata
{
private readonly List<KeyValuePair<string, string>> _metadata;
internal InternalMetadata(IPackageCoreReader package)
{
NuspecReader = new NuspecReader(package.GetNuspec());
_metadata = NuspecReader.GetMetadata().ToList();
PackageId = package.GetIdentity().Id;
Version = NugetVersion.FromNuGetVersion(package.GetIdentity().Version);
}
private string ReadMetadata(string key) => _metadata.FirstOrDefault(x => string.Equals(x.Key, key, StringComparison.InvariantCultureIgnoreCase)).Value;
private IReadOnlyList<string> ReadMultiMetadata(string key) =>
_metadata.Where(x => string.Equals(x.Key, key, StringComparison.InvariantCultureIgnoreCase)).Select(x => x.Value).ToList();
/// <summary>
/// Gets the .nuspec reader for this package.
/// </summary>
public NuspecReader NuspecReader { get; }
public string PackageId { get; }
public NugetVersion Version { get; }
public string Title => ReadMetadata("title");
public string Summary => ReadMetadata("summary") ?? ReadMetadata("description");
public string Description => ReadMetadata("description") ?? ReadMetadata("summary");
public IReadOnlyList<string> Authors => ReadMultiMetadata("author");
public string IconUrl => ReadMetadata("iconurl");
public string ProjectUrl => ReadMetadata("projecturl");
/// <summary>
/// Returns an identifying string for this package, in the form "Id ver".
/// </summary>
public override string ToString() => PackageId + " " + Version;
}
}
}
|
mit
|
C#
|
263cbbbeeae8e30de7c4ea1b8d83652363e65d81
|
delete StringLengthValidator from ResetPasswordRequestEntity
|
signumsoftware/framework,signumsoftware/extensions,signumsoftware/extensions,AlejandroCano/extensions,signumsoftware/framework,AlejandroCano/extensions
|
Signum.Entities.Extensions/Authorization/ResetPasswordRequest.cs
|
Signum.Entities.Extensions/Authorization/ResetPasswordRequest.cs
|
using System;
namespace Signum.Entities.Authorization
{
[Serializable, EntityKind(EntityKind.System, EntityData.Transactional)]
public class ResetPasswordRequestEntity : Entity
{
[UniqueIndex(AvoidAttachToUniqueIndexes = true)]
public string Code { get; set; }
public UserEntity User { get; set; }
public DateTime RequestDate { get; set; }
public bool Lapsed { get; set; }
}
[AutoInit]
public static class ResetPasswordRequestOperation
{
public static readonly ExecuteSymbol<ResetPasswordRequestEntity> Execute;
}
}
|
using System;
namespace Signum.Entities.Authorization
{
[Serializable, EntityKind(EntityKind.System, EntityData.Transactional)]
public class ResetPasswordRequestEntity : Entity
{
[UniqueIndex(AvoidAttachToUniqueIndexes = true)]
[StringLengthValidator(AllowNulls = false, Max = 32)]
public string Code { get; set; }
public UserEntity User { get; set; }
public DateTime RequestDate { get; set; }
public bool Lapsed { get; set; }
}
[AutoInit]
public static class ResetPasswordRequestOperation
{
public static readonly ExecuteSymbol<ResetPasswordRequestEntity> Execute;
}
}
|
mit
|
C#
|
7910e4c04c9f576739c862cdb23a9a2692ad8370
|
Fix wrong namespace beeing used in TitanTest
|
Marc3842h/Titan,Marc3842h/Titan,Marc3842h/Titan
|
TitanTest/ShareCodeDecoderTest.cs
|
TitanTest/ShareCodeDecoderTest.cs
|
using Titan.MatchID.Sharecode;
using Xunit;
namespace TitanTest
{
public class ShareCodeDecoderTest
{
[Fact]
public void TestDecoder()
{
if(ShareCode.Decode("CSGO-727c4-5oCG3-PurVX-sJkdn-LsXfE").MatchID == 3208347562318757960)
{
Assert.True(true, "The decoded Match ID is 3208347562318757960");
}
else
{
Assert.True(false);
}
}
}
}
|
using Titan.Sharecode;
using Xunit;
namespace TitanTest
{
public class ShareCodeDecoderTest
{
[Fact]
public void TestDecoder()
{
if(ShareCode.Decode("CSGO-727c4-5oCG3-PurVX-sJkdn-LsXfE").MatchID == 3208347562318757960)
{
Assert.True(true, "The decoded Match ID is 3208347562318757960");
}
else
{
Assert.True(false);
}
}
}
}
|
mit
|
C#
|
6fd2db5dd6465d1dd5979b3c0cb7bfbe3107d205
|
Fix missed analysis warning
|
natsnudasoft/AdiePlayground
|
test/unit/AdiePlayground.CommonTests/SystemDateTimeProviderTests.cs
|
test/unit/AdiePlayground.CommonTests/SystemDateTimeProviderTests.cs
|
// <copyright file="SystemDateTimeProviderTests.cs" company="natsnudasoft">
// Copyright (c) Adrian John Dunstan. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// </copyright>
namespace AdiePlayground.CommonTests
{
using Common;
using NUnit.Framework;
/// <summary>
/// Tests the <see cref="SystemDateTimeProvider"/> class.
/// </summary>
[TestFixture]
public sealed class SystemDateTimeProviderTests
{
/// <summary>
/// Tests the Now method.
/// </summary>
[System.Diagnostics.CodeAnalysis.SuppressMessage(
"Microsoft.Performance",
"CA1804:RemoveUnusedLocals",
MessageId = "dateTime",
Justification = "We need to assign the property to test for exception.")]
[Test]
public void Now_DoesNotThrow()
{
var dateTimeProvider = new SystemDateTimeProvider();
Assert.DoesNotThrow(() => { var dateTime = dateTimeProvider.Now; });
}
}
}
|
// <copyright file="SystemDateTimeProviderTests.cs" company="natsnudasoft">
// Copyright (c) Adrian John Dunstan. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// </copyright>
namespace AdiePlayground.CommonTests
{
using Common;
using NUnit.Framework;
/// <summary>
/// Tests the <see cref="SystemDateTimeProvider"/> class.
/// </summary>
[TestFixture]
public sealed class SystemDateTimeProviderTests
{
/// <summary>
/// Tests the Now method.
/// </summary>
[Test]
public void Now_DoesNotThrow()
{
var dateTimeProvider = new SystemDateTimeProvider();
Assert.DoesNotThrow(() => { var dateTime = dateTimeProvider.Now; });
}
}
}
|
apache-2.0
|
C#
|
07964ed5cac1a77a57b4dce839b51a150f3153a2
|
Fix for setting worldCamera to null even when user chose UIRaycastCamera
|
HattMarris1/HoloToolkit-Unity
|
Assets/HoloToolkit/Utilities/Scripts/Editor/CanvasEditorExtension.cs
|
Assets/HoloToolkit/Utilities/Scripts/Editor/CanvasEditorExtension.cs
|
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See LICENSE in the project root for license information.
using HoloToolkit.Unity.InputModule;
using UnityEditor;
using UnityEngine;
namespace HoloToolkit.Unity
{
/// <summary>
/// Helper class to assign the UIRaycastCamera when creating a new canvas object and assigning the world space render mode.
/// </summary>
[CustomEditor(typeof(Canvas))]
public class CanvasEditorExtension : Editor
{
private const string DialogText = "Hi there, we noticed that you've changed this canvas to use WorldSpace.\n\n" +
"In order for the InputManager to work properly with uGUI raycasting we'd like to update this canvas' " +
"WorldCamera to use the FocusManager's UIRaycastCamera.\n";
private Canvas canvas;
private bool userPermission;
private void OnEnable()
{
canvas = (Canvas)target;
}
public override void OnInspectorGUI()
{
EditorGUI.BeginChangeCheck();
base.OnInspectorGUI();
// We will only ask if we have a focus manager in our scene.
if (EditorGUI.EndChangeCheck() && FocusManager.Instance)
{
FocusManager.AssertIsInitialized();
// We only need to ask if the worldCamera is not already the UIRaycastCamera
if (canvas.worldCamera != FocusManager.Instance.UIRaycastCamera)
{
if (canvas.isRootCanvas && canvas.renderMode == RenderMode.WorldSpace)
{
userPermission = EditorUtility.DisplayDialog("Attention!", DialogText, "OK", "Cancel");
if (userPermission)
{
canvas.worldCamera = FocusManager.Instance.UIRaycastCamera;
}
}
if (canvas.renderMode != RenderMode.WorldSpace || !userPermission)
{
// Sets it back to MainCamera default
canvas.worldCamera = null;
}
}
}
}
}
}
|
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See LICENSE in the project root for license information.
using HoloToolkit.Unity.InputModule;
using UnityEditor;
using UnityEngine;
namespace HoloToolkit.Unity
{
/// <summary>
/// Helper class to assign the UIRaycastCamera when creating a new canvas object and assigning the world space render mode.
/// </summary>
[CustomEditor(typeof(Canvas))]
public class CanvasEditorExtension : Editor
{
private const string DialogText = "Hi there, we noticed that you've changed this canvas to use WorldSpace.\n\n" +
"In order for the InputManager to work properly with uGUI raycasting we'd like to update this canvas' " +
"WorldCamera to use the FocusManager's UIRaycastCamera.\n";
private Canvas canvas;
private bool userPermission;
private void OnEnable()
{
canvas = (Canvas)target;
}
public override void OnInspectorGUI()
{
EditorGUI.BeginChangeCheck();
base.OnInspectorGUI();
// We will only ask if we have a focus manager in our scene.
if (EditorGUI.EndChangeCheck() && FocusManager.Instance)
{
FocusManager.AssertIsInitialized();
if (canvas.isRootCanvas && canvas.renderMode == RenderMode.WorldSpace && canvas.worldCamera != FocusManager.Instance.UIRaycastCamera)
{
userPermission = EditorUtility.DisplayDialog("Attention!", DialogText, "OK", "Cancel");
if (userPermission)
{
canvas.worldCamera = FocusManager.Instance.UIRaycastCamera;
}
}
if (canvas.renderMode != RenderMode.WorldSpace || !userPermission)
{
// Sets it back to MainCamera default
canvas.worldCamera = null;
}
}
}
}
}
|
mit
|
C#
|
3920839746074c01f65cc437427e658ba03105f6
|
Update XML comments of `PageSnapshotsConfiguration`
|
atata-framework/atata,atata-framework/atata
|
src/Atata/Context/PageSnapshots/PageSnapshotsConfiguration.cs
|
src/Atata/Context/PageSnapshots/PageSnapshotsConfiguration.cs
|
using System;
namespace Atata
{
/// <summary>
/// Represents the configuration of page snapshots functionality.
/// </summary>
public sealed class PageSnapshotsConfiguration : ICloneable
{
/// <summary>
/// Gets or sets the strategy for a page snapshot taking.
/// The default value is an instance of <see cref="CdpOrPageSourcePageSnapshotStrategy"/>.
/// </summary>
public IPageSnapshotStrategy Strategy { get; set; } = CdpOrPageSourcePageSnapshotStrategy.Instance;
/// <summary>
/// Gets or sets the page snapshot file name template.
/// The file name is relative to Artifacts path.
/// The default value is <c>"{snapshot-number:D2} - {snapshot-pageobjectname} {snapshot-pageobjecttypename}{snapshot-title: - *}"</c>.
/// </summary>
public string FileNameTemplate { get; set; } =
"{snapshot-number:D2} - {snapshot-pageobjectname} {snapshot-pageobjecttypename}{snapshot-title: - *}";
/// <inheritdoc cref="Clone"/>
object ICloneable.Clone() => Clone();
/// <summary>
/// Creates a new object that is a copy of the current instance.
/// </summary>
/// <returns>
/// A new object that is a copy of this instance.
/// </returns>
internal PageSnapshotsConfiguration Clone()
{
PageSnapshotsConfiguration clone = (PageSnapshotsConfiguration)MemberwiseClone();
if (Strategy is ICloneable cloneablePageSnapshotStrategy)
clone.Strategy = (IPageSnapshotStrategy)cloneablePageSnapshotStrategy.Clone();
return clone;
}
}
}
|
using System;
namespace Atata
{
/// <summary>
/// Represents the configuration of page snapshots functionality.
/// </summary>
public sealed class PageSnapshotsConfiguration : ICloneable
{
/// <summary>
/// Gets or sets the strategy for a page snapshot taking.
/// The default value is an instance of <see cref="CdpOrPageSourcePageSnapshotStrategy"/>.
/// </summary>
public IPageSnapshotStrategy Strategy { get; set; } = CdpOrPageSourcePageSnapshotStrategy.Instance;
/// <summary>
/// Gets or sets the page snapshot file name template.
/// The file name is relative to Artifacts path.
/// The default value is <c>"{snapshot-number:D2} - {snapshot-pageobjectname} {snapshot-pageobjecttypename}{snapshot-title: - *}"</c>.
/// </summary>
public string FileNameTemplate { get; set; } =
"{snapshot-number:D2} - {snapshot-pageobjectname} {snapshot-pageobjecttypename}{snapshot-title: - *}";
object ICloneable.Clone() => Clone();
internal PageSnapshotsConfiguration Clone()
{
PageSnapshotsConfiguration clone = (PageSnapshotsConfiguration)MemberwiseClone();
if (Strategy is ICloneable cloneablePageSnapshotStrategy)
clone.Strategy = (IPageSnapshotStrategy)cloneablePageSnapshotStrategy.Clone();
return clone;
}
}
}
|
apache-2.0
|
C#
|
4dc99f2846e92e89d332c7c509776a6ca9226445
|
Handle "null" data values from Lassie API
|
eurofurence/ef-app_backend-dotnet-core,eurofurence/ef-app_backend-dotnet-core
|
src/Eurofurence.App.Server.Services/Lassie/LassieApiClient.cs
|
src/Eurofurence.App.Server.Services/Lassie/LassieApiClient.cs
|
using Eurofurence.App.Server.Services.Abstractions.Lassie;
using Newtonsoft.Json;
using System.Collections.Generic;
using System.Net.Http;
using System.Threading.Tasks;
namespace Eurofurence.App.Server.Services.Lassie
{
public class LassieApiClient : ILassieApiClient
{
private class DataResponseWrapper<T>
{
public T[] Data { get; set; }
}
private LassieConfiguration _configuration;
public LassieApiClient(LassieConfiguration configuration)
{
_configuration = configuration;
}
public async Task<LostAndFoundResponse[]> QueryLostAndFoundDbAsync(string command = "lostandfound")
{
var outgoingQuery = new List<KeyValuePair<string, string>>()
{
new KeyValuePair<string, string>("apikey", _configuration.ApiKey),
new KeyValuePair<string, string>("request", "lostandfounddb"),
new KeyValuePair<string, string>("command", command)
};
using (var client = new HttpClient())
{
var response = await client.PostAsync(_configuration.BaseApiUrl, new FormUrlEncodedContent(outgoingQuery));
var content = await response.Content.ReadAsStringAsync();
var dataResponse = JsonConvert.DeserializeObject<DataResponseWrapper<LostAndFoundResponse>>(content,
new JsonSerializerSettings() { DateTimeZoneHandling = DateTimeZoneHandling.Local });
return dataResponse.Data ?? new LostAndFoundResponse[0];
}
}
}
}
|
using Eurofurence.App.Server.Services.Abstractions.Lassie;
using Newtonsoft.Json;
using System.Collections.Generic;
using System.Net.Http;
using System.Threading.Tasks;
namespace Eurofurence.App.Server.Services.Lassie
{
public class LassieApiClient : ILassieApiClient
{
private class DataResponseWrapper<T>
{
public T[] Data { get; set; }
}
private LassieConfiguration _configuration;
public LassieApiClient(LassieConfiguration configuration)
{
_configuration = configuration;
}
public async Task<LostAndFoundResponse[]> QueryLostAndFoundDbAsync(string command = "lostandfound")
{
var outgoingQuery = new List<KeyValuePair<string, string>>()
{
new KeyValuePair<string, string>("apikey", _configuration.ApiKey),
new KeyValuePair<string, string>("request", "lostandfounddb"),
new KeyValuePair<string, string>("command", command)
};
using (var client = new HttpClient())
{
var response = await client.PostAsync(_configuration.BaseApiUrl, new FormUrlEncodedContent(outgoingQuery));
var content = await response.Content.ReadAsStringAsync();
var dataResponse = JsonConvert.DeserializeObject<DataResponseWrapper<LostAndFoundResponse>>(content,
new JsonSerializerSettings() { DateTimeZoneHandling = DateTimeZoneHandling.Local });
return dataResponse.Data;
}
}
}
}
|
mit
|
C#
|
bc046cfac56a8f5d89ab3af95a064bf72c3d00d3
|
Fix tag slug
|
yonglehou/Orchard,geertdoornbos/Orchard,OrchardCMS/Orchard-Harvest-Website,li0803/Orchard,jtkech/Orchard,hannan-azam/Orchard,jerryshi2007/Orchard,kgacova/Orchard,omidnasri/Orchard,MpDzik/Orchard,sfmskywalker/Orchard-Off-The-Grid-Sample-Code,patricmutwiri/Orchard,SouleDesigns/SouleDesigns.Orchard,omidnasri/Orchard,armanforghani/Orchard,jaraco/orchard,Anton-Am/Orchard,mvarblow/Orchard,spraiin/Orchard,luchaoshuai/Orchard,escofieldnaxos/Orchard,ehe888/Orchard,TaiAivaras/Orchard,brownjordaninternational/OrchardCMS,bedegaming-aleksej/Orchard,qt1/Orchard,infofromca/Orchard,marcoaoteixeira/Orchard,vard0/orchard.tan,LaserSrl/Orchard,Sylapse/Orchard.HttpAuthSample,KeithRaven/Orchard,KeithRaven/Orchard,gcsuk/Orchard,AndreVolksdorf/Orchard,SeyDutch/Airbrush,alejandroaldana/Orchard,oxwanawxo/Orchard,AndreVolksdorf/Orchard,jaraco/orchard,abhishekluv/Orchard,sfmskywalker/Orchard,sebastienros/msc,infofromca/Orchard,jtkech/Orchard,johnnyqian/Orchard,sebastienros/msc,harmony7/Orchard,Codinlab/Orchard,bigfont/orchard-cms-modules-and-themes,Inner89/Orchard,Codinlab/Orchard,jimasp/Orchard,asabbott/chicagodevnet-website,qt1/orchard4ibn,Dolphinsimon/Orchard,geertdoornbos/Orchard,patricmutwiri/Orchard,vairam-svs/Orchard,princeppy/JPYSites-Orchard-Azure-Live-SourceCode,dmitry-urenev/extended-orchard-cms-v10.1,aaronamm/Orchard,sfmskywalker/Orchard,KeithRaven/Orchard,jtkech/Orchard,Lombiq/Orchard,enspiral-dev-academy/Orchard,alejandroaldana/Orchard,stormleoxia/Orchard,enspiral-dev-academy/Orchard,DonnotRain/Orchard,fassetar/Orchard,qt1/orchard4ibn,bedegaming-aleksej/Orchard,stormleoxia/Orchard,jersiovic/Orchard,openbizgit/Orchard,mvarblow/Orchard,AEdmunds/beautiful-springtime,huoxudong125/Orchard,omidnasri/Orchard,jagraz/Orchard,Anton-Am/Orchard,hbulzy/Orchard,smartnet-developers/Orchard,yonglehou/Orchard,brownjordaninternational/OrchardCMS,salarvand/Portal,gcsuk/Orchard,KeithRaven/Orchard,gcsuk/Orchard,salarvand/orchard,huoxudong125/Orchard,dcinzona/Orchard-Harvest-Website,NIKASoftwareDevs/Orchard,AdvantageCS/Orchard,ehe888/Orchard,cryogen/orchard,jtkech/Orchard,johnnyqian/Orchard,cryogen/orchard,xiaobudian/Orchard,enspiral-dev-academy/Orchard,salarvand/orchard,Praggie/Orchard,sfmskywalker/Orchard-Off-The-Grid-Sample-Code,MpDzik/Orchard,jimasp/Orchard,jerryshi2007/Orchard,sfmskywalker/Orchard-Off-The-Grid-Sample-Code,fortunearterial/Orchard,escofieldnaxos/Orchard,geertdoornbos/Orchard,IDeliverable/Orchard,phillipsj/Orchard,hhland/Orchard,phillipsj/Orchard,TalaveraTechnologySolutions/Orchard,luchaoshuai/Orchard,Inner89/Orchard,Cphusion/Orchard,vard0/orchard.tan,austinsc/Orchard,cooclsee/Orchard,Inner89/Orchard,jchenga/Orchard,Lombiq/Orchard,yersans/Orchard,TalaveraTechnologySolutions/Orchard,spraiin/Orchard,kouweizhong/Orchard,angelapper/Orchard,NIKASoftwareDevs/Orchard,xkproject/Orchard,Lombiq/Orchard,smartnet-developers/Orchard,Inner89/Orchard,abhishekluv/Orchard,dburriss/Orchard,Fogolan/OrchardForWork,TalaveraTechnologySolutions/Orchard,IDeliverable/Orchard,xiaobudian/Orchard,arminkarimi/Orchard,m2cms/Orchard,smartnet-developers/Orchard,brownjordaninternational/OrchardCMS,salarvand/Portal,Codinlab/Orchard,Morgma/valleyviewknolls,vard0/orchard.tan,hhland/Orchard,neTp9c/Orchard,princeppy/JPYSites-Orchard-Azure-Live-SourceCode,AndreVolksdorf/Orchard,AdvantageCS/Orchard,xkproject/Orchard,LaserSrl/Orchard,dozoft/Orchard,Lombiq/Orchard,OrchardCMS/Orchard,omidnasri/Orchard,AEdmunds/beautiful-springtime,AEdmunds/beautiful-springtime,sfmskywalker/Orchard-Off-The-Grid-Sample-Code,smartnet-developers/Orchard,asabbott/chicagodevnet-website,emretiryaki/Orchard,jersiovic/Orchard,xkproject/Orchard,hbulzy/Orchard,princeppy/JPYSites-Orchard-Azure-Live-SourceCode,IDeliverable/Orchard,fassetar/Orchard,gcsuk/Orchard,huoxudong125/Orchard,TalaveraTechnologySolutions/Orchard,jersiovic/Orchard,emretiryaki/Orchard,Serlead/Orchard,jerryshi2007/Orchard,ehe888/Orchard,SzymonSel/Orchard,jersiovic/Orchard,Praggie/Orchard,Serlead/Orchard,jerryshi2007/Orchard,omidnasri/Orchard,MpDzik/Orchard,omidnasri/Orchard,stormleoxia/Orchard,xiaobudian/Orchard,Anton-Am/Orchard,Cphusion/Orchard,stormleoxia/Orchard,grapto/Orchard.CloudBust,qt1/Orchard,armanforghani/Orchard,MpDzik/Orchard,OrchardCMS/Orchard,armanforghani/Orchard,huoxudong125/Orchard,MpDzik/Orchard,Cphusion/Orchard,Fogolan/OrchardForWork,li0803/Orchard,phillipsj/Orchard,princeppy/JPYSites-Orchard-Azure-Live-SourceCode,vairam-svs/Orchard,Ermesx/Orchard,marcoaoteixeira/Orchard,TaiAivaras/Orchard,Praggie/Orchard,sfmskywalker/Orchard,AndreVolksdorf/Orchard,luchaoshuai/Orchard,dozoft/Orchard,ericschultz/outercurve-orchard,infofromca/Orchard,aaronamm/Orchard,andyshao/Orchard,dcinzona/Orchard,hannan-azam/Orchard,jerryshi2007/Orchard,armanforghani/Orchard,jagraz/Orchard,mvarblow/Orchard,abhishekluv/Orchard,harmony7/Orchard,harmony7/Orchard,abhishekluv/Orchard,li0803/Orchard,yersans/Orchard,tobydodds/folklife,OrchardCMS/Orchard-Harvest-Website,TalaveraTechnologySolutions/Orchard,princeppy/JPYSites-Orchard-Azure-Live-SourceCode,bedegaming-aleksej/Orchard,phillipsj/Orchard,fassetar/Orchard,kouweizhong/Orchard,openbizgit/Orchard,angelapper/Orchard,bigfont/orchard-continuous-integration-demo,AEdmunds/beautiful-springtime,spraiin/Orchard,angelapper/Orchard,phillipsj/Orchard,dozoft/Orchard,mvarblow/Orchard,aaronamm/Orchard,TalaveraTechnologySolutions/Orchard,salarvand/orchard,Praggie/Orchard,TaiAivaras/Orchard,salarvand/Portal,MpDzik/Orchard,emretiryaki/Orchard,tobydodds/folklife,Anton-Am/Orchard,Fogolan/OrchardForWork,Ermesx/Orchard,infofromca/Orchard,sfmskywalker/Orchard,m2cms/Orchard,rtpHarry/Orchard,SzymonSel/Orchard,OrchardCMS/Orchard,bigfont/orchard-cms-modules-and-themes,Anton-Am/Orchard,fortunearterial/Orchard,grapto/Orchard.CloudBust,xkproject/Orchard,oxwanawxo/Orchard,geertdoornbos/Orchard,asabbott/chicagodevnet-website,xiaobudian/Orchard,Sylapse/Orchard.HttpAuthSample,MetSystem/Orchard,enspiral-dev-academy/Orchard,marcoaoteixeira/Orchard,grapto/Orchard.CloudBust,patricmutwiri/Orchard,Sylapse/Orchard.HttpAuthSample,bigfont/orchard-cms-modules-and-themes,dcinzona/Orchard-Harvest-Website,jimasp/Orchard,planetClaire/Orchard-LETS,fassetar/Orchard,planetClaire/Orchard-LETS,dcinzona/Orchard,SouleDesigns/SouleDesigns.Orchard,RoyalVeterinaryCollege/Orchard,SeyDutch/Airbrush,SzymonSel/Orchard,dmitry-urenev/extended-orchard-cms-v10.1,MetSystem/Orchard,caoxk/orchard,m2cms/Orchard,planetClaire/Orchard-LETS,jchenga/Orchard,RoyalVeterinaryCollege/Orchard,aaronamm/Orchard,qt1/orchard4ibn,omidnasri/Orchard,vairam-svs/Orchard,mgrowan/Orchard,luchaoshuai/Orchard,fortunearterial/Orchard,Inner89/Orchard,hhland/Orchard,jchenga/Orchard,fortunearterial/Orchard,caoxk/orchard,aaronamm/Orchard,patricmutwiri/Orchard,tobydodds/folklife,armanforghani/Orchard,austinsc/Orchard,sebastienros/msc,JRKelso/Orchard,dburriss/Orchard,spraiin/Orchard,planetClaire/Orchard-LETS,oxwanawxo/Orchard,DonnotRain/Orchard,Morgma/valleyviewknolls,yersans/Orchard,tobydodds/folklife,LaserSrl/Orchard,OrchardCMS/Orchard-Harvest-Website,austinsc/Orchard,qt1/Orchard,ehe888/Orchard,SouleDesigns/SouleDesigns.Orchard,jaraco/orchard,sebastienros/msc,stormleoxia/Orchard,jagraz/Orchard,JRKelso/Orchard,mvarblow/Orchard,harmony7/Orchard,dcinzona/Orchard-Harvest-Website,ericschultz/outercurve-orchard,rtpHarry/Orchard,jchenga/Orchard,kouweizhong/Orchard,IDeliverable/Orchard,hbulzy/Orchard,kgacova/Orchard,cryogen/orchard,DonnotRain/Orchard,KeithRaven/Orchard,kgacova/Orchard,SzymonSel/Orchard,openbizgit/Orchard,Praggie/Orchard,austinsc/Orchard,caoxk/orchard,dcinzona/Orchard,OrchardCMS/Orchard-Harvest-Website,m2cms/Orchard,dcinzona/Orchard,dozoft/Orchard,kouweizhong/Orchard,bedegaming-aleksej/Orchard,arminkarimi/Orchard,jaraco/orchard,qt1/orchard4ibn,Morgma/valleyviewknolls,planetClaire/Orchard-LETS,NIKASoftwareDevs/Orchard,hannan-azam/Orchard,yonglehou/Orchard,xiaobudian/Orchard,jchenga/Orchard,li0803/Orchard,harmony7/Orchard,sfmskywalker/Orchard,Fogolan/OrchardForWork,Cphusion/Orchard,cooclsee/Orchard,openbizgit/Orchard,OrchardCMS/Orchard-Harvest-Website,yersans/Orchard,grapto/Orchard.CloudBust,jtkech/Orchard,rtpHarry/Orchard,sfmskywalker/Orchard,neTp9c/Orchard,dburriss/Orchard,AdvantageCS/Orchard,salarvand/orchard,cooclsee/Orchard,Fogolan/OrchardForWork,salarvand/orchard,SzymonSel/Orchard,qt1/Orchard,SeyDutch/Airbrush,NIKASoftwareDevs/Orchard,LaserSrl/Orchard,mgrowan/Orchard,SouleDesigns/SouleDesigns.Orchard,hbulzy/Orchard,jersiovic/Orchard,omidnasri/Orchard,vard0/orchard.tan,andyshao/Orchard,patricmutwiri/Orchard,qt1/orchard4ibn,dmitry-urenev/extended-orchard-cms-v10.1,spraiin/Orchard,bigfont/orchard-continuous-integration-demo,dcinzona/Orchard-Harvest-Website,neTp9c/Orchard,grapto/Orchard.CloudBust,NIKASoftwareDevs/Orchard,hannan-azam/Orchard,Cphusion/Orchard,Serlead/Orchard,ericschultz/outercurve-orchard,hhland/Orchard,andyshao/Orchard,dcinzona/Orchard-Harvest-Website,bigfont/orchard-continuous-integration-demo,m2cms/Orchard,jagraz/Orchard,sfmskywalker/Orchard,cooclsee/Orchard,emretiryaki/Orchard,AdvantageCS/Orchard,abhishekluv/Orchard,johnnyqian/Orchard,xkproject/Orchard,abhishekluv/Orchard,austinsc/Orchard,hbulzy/Orchard,JRKelso/Orchard,jimasp/Orchard,dmitry-urenev/extended-orchard-cms-v10.1,vairam-svs/Orchard,dcinzona/Orchard,Morgma/valleyviewknolls,andyshao/Orchard,TalaveraTechnologySolutions/Orchard,sebastienros/msc,mgrowan/Orchard,johnnyqian/Orchard,AdvantageCS/Orchard,caoxk/orchard,emretiryaki/Orchard,vairam-svs/Orchard,bigfont/orchard-continuous-integration-demo,Lombiq/Orchard,ehe888/Orchard,Sylapse/Orchard.HttpAuthSample,OrchardCMS/Orchard,angelapper/Orchard,neTp9c/Orchard,arminkarimi/Orchard,dmitry-urenev/extended-orchard-cms-v10.1,escofieldnaxos/Orchard,alejandroaldana/Orchard,Ermesx/Orchard,yonglehou/Orchard,jimasp/Orchard,gcsuk/Orchard,li0803/Orchard,tobydodds/folklife,brownjordaninternational/OrchardCMS,Morgma/valleyviewknolls,MetSystem/Orchard,ericschultz/outercurve-orchard,MetSystem/Orchard,grapto/Orchard.CloudBust,brownjordaninternational/OrchardCMS,hannan-azam/Orchard,kouweizhong/Orchard,Dolphinsimon/Orchard,Sylapse/Orchard.HttpAuthSample,omidnasri/Orchard,alejandroaldana/Orchard,bigfont/orchard-cms-modules-and-themes,dcinzona/Orchard-Harvest-Website,bedegaming-aleksej/Orchard,geertdoornbos/Orchard,johnnyqian/Orchard,JRKelso/Orchard,infofromca/Orchard,marcoaoteixeira/Orchard,TaiAivaras/Orchard,DonnotRain/Orchard,smartnet-developers/Orchard,cryogen/orchard,RoyalVeterinaryCollege/Orchard,Ermesx/Orchard,Ermesx/Orchard,kgacova/Orchard,cooclsee/Orchard,enspiral-dev-academy/Orchard,dburriss/Orchard,mgrowan/Orchard,oxwanawxo/Orchard,yersans/Orchard,TalaveraTechnologySolutions/Orchard,RoyalVeterinaryCollege/Orchard,OrchardCMS/Orchard,alejandroaldana/Orchard,rtpHarry/Orchard,rtpHarry/Orchard,sfmskywalker/Orchard,qt1/Orchard,andyshao/Orchard,TaiAivaras/Orchard,SeyDutch/Airbrush,hhland/Orchard,asabbott/chicagodevnet-website,huoxudong125/Orchard,openbizgit/Orchard,fortunearterial/Orchard,angelapper/Orchard,tobydodds/folklife,dburriss/Orchard,escofieldnaxos/Orchard,OrchardCMS/Orchard-Harvest-Website,SeyDutch/Airbrush,Serlead/Orchard,marcoaoteixeira/Orchard,oxwanawxo/Orchard,Codinlab/Orchard,vard0/orchard.tan,Serlead/Orchard,escofieldnaxos/Orchard,yonglehou/Orchard,bigfont/orchard-cms-modules-and-themes,kgacova/Orchard,luchaoshuai/Orchard,Dolphinsimon/Orchard,Dolphinsimon/Orchard,sfmskywalker/Orchard-Off-The-Grid-Sample-Code,Dolphinsimon/Orchard,dozoft/Orchard,LaserSrl/Orchard,RoyalVeterinaryCollege/Orchard,MetSystem/Orchard,JRKelso/Orchard,mgrowan/Orchard,fassetar/Orchard,Codinlab/Orchard,neTp9c/Orchard,AndreVolksdorf/Orchard,qt1/orchard4ibn,arminkarimi/Orchard,vard0/orchard.tan,IDeliverable/Orchard,SouleDesigns/SouleDesigns.Orchard,jagraz/Orchard,arminkarimi/Orchard,DonnotRain/Orchard,salarvand/Portal,salarvand/Portal
|
src/Orchard.Web/Modules/Orchard.Tags/Providers/TagPatterns.cs
|
src/Orchard.Web/Modules/Orchard.Tags/Providers/TagPatterns.cs
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Orchard.Tags.Services;
using Orchard.Localization;
using Orchard.Tags.Models;
using System.Web.Routing;
namespace Orchard.Tags.Providers {
public class TagPatterns {
private readonly ITagService _tagService;
public TagPatterns(
ITagService tagService
) {
_tagService = tagService;
T = NullLocalizer.Instance;
}
public Localizer T { get; set; }
public void Describe(dynamic describe) {
describe.For<TagRecord>("Tags", T("Tags"), T("Tags url patterns"), (Func<TagRecord, string>)GetId, (Func<string, TagRecord>)GetTag)
.Pattern("Tags", T("View all tags"), T("A list of all tags are displayed on this page"), (Func<TagRecord, RouteValueDictionary>)GetTagsRouteValues)
.Pattern("View", T("View tagged content"), T("Tagged content will be listed on this Url for each tag"), (Func<TagRecord, RouteValueDictionary>)GetRouteValues);
}
protected RouteValueDictionary GetRouteValues(TagRecord tag) {
return new RouteValueDictionary(new{
area = "Orchard.Tags",
controller = "Home",
action = "Search",
tagName = tag.TagName
});
}
protected RouteValueDictionary GetTagsRouteValues(TagRecord tag) {
return new RouteValueDictionary(new {
area = "Orchard.Tags",
controller = "Home",
action = "Index"
});
}
protected string GetId(TagRecord tag) {
return tag.Id.ToString();
}
protected TagRecord GetTag(string id) {
return _tagService.GetTag(Convert.ToInt32(id));
}
public void Suggest(dynamic suggest) {
suggest.For("Tags")
.Suggest("View", "tags/tag-name", "{Tag.Name.Slug}", T("Slugified tag name"))
.Suggest("Tags", "tags", "tags", T("Plain /tags url"));
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Orchard.Tags.Services;
using Orchard.Localization;
using Orchard.Tags.Models;
using System.Web.Routing;
namespace Orchard.Tags.Providers {
public class TagPatterns {
private readonly ITagService _tagService;
public TagPatterns(
ITagService tagService
) {
_tagService = tagService;
T = NullLocalizer.Instance;
}
public Localizer T { get; set; }
public void Describe(dynamic describe) {
describe.For<TagRecord>("Tags", T("Tags"), T("Tags url patterns"), (Func<TagRecord, string>)GetId, (Func<string, TagRecord>)GetTag)
.Pattern("Tags", T("View all tags"), T("A list of all tags are displayed on this page"), (Func<TagRecord, RouteValueDictionary>)GetTagsRouteValues)
.Pattern("View", T("View tagged content"), T("Tagged content will be listed on this Url for each tag"), (Func<TagRecord, RouteValueDictionary>)GetRouteValues);
}
protected RouteValueDictionary GetRouteValues(TagRecord tag) {
return new RouteValueDictionary(new{
area = "Orchard.Tags",
controller = "Home",
action = "Search",
tagName = tag.TagName
});
}
protected RouteValueDictionary GetTagsRouteValues(TagRecord tag) {
return new RouteValueDictionary(new {
area = "Orchard.Tags",
controller = "Home",
action = "Index"
});
}
protected string GetId(TagRecord tag) {
return tag.Id.ToString();
}
protected TagRecord GetTag(string id) {
return _tagService.GetTag(Convert.ToInt32(id));
}
public void Suggest(dynamic suggest) {
suggest.For("Tags")
.Suggest("View", "tags/tag-name", "{Tag.Slug}", T("Slugified tag name"))
.Suggest("Tags", "tags", "tags", T("Plain /tags url"));
}
}
}
|
bsd-3-clause
|
C#
|
a54c9f01c41362b89477bb4fea27f178602ee9c9
|
remove accidental commit
|
agileharbor/shipStationAccess
|
src/ShipStationAccess/V2/Models/Command/ShipStationCommand.cs
|
src/ShipStationAccess/V2/Models/Command/ShipStationCommand.cs
|
namespace ShipStationAccess.V2.Models.Command
{
internal sealed class ShipStationCommand
{
public static readonly ShipStationCommand Unknown = new ShipStationCommand( string.Empty );
public static readonly ShipStationCommand GetOrders = new ShipStationCommand( "/Orders/List" );
public static readonly ShipStationCommand GetTags = new ShipStationCommand( "/Accounts/ListTags" );
public static readonly ShipStationCommand CreateUpdateOrder = new ShipStationCommand( "/Orders/CreateOrder" );
public static readonly ShipStationCommand UpdateOrderItemsWarehouseLocation = new ShipStationCommand( "/Orders/UpdateWarehouseLocation" );
public static readonly ShipStationCommand GetStores = new ShipStationCommand( "/Stores" );
public static readonly ShipStationCommand GetShippingLabel = new ShipStationCommand( "/Orders/CreateLabelForOrder" );
private ShipStationCommand( string command )
{
this.Command = command;
}
public string Command{ get; private set; }
}
}
|
namespace ShipStationAccess.V2.Models.Command
{
internal sealed class ShipStationCommand
{
public static readonly ShipStationCommand Unknown = new ShipStationCommand( string.Empty );
public static readonly ShipStationCommand GetOrders = new ShipStationCommand( "/Orders/List" );
public static readonly ShipStationCommand GetTags = new ShipStationCommand( "/Accounts/ListTags" );
public static readonly ShipStationCommand GetLabel = new ShipStationCommand( "/Accounts/ListTags" );
public static readonly ShipStationCommand CreateUpdateOrder = new ShipStationCommand( "/Orders/CreateOrder" );
public static readonly ShipStationCommand UpdateOrderItemsWarehouseLocation = new ShipStationCommand( "/Orders/UpdateWarehouseLocation" );
public static readonly ShipStationCommand GetStores = new ShipStationCommand( "/Stores" );
public static readonly ShipStationCommand GetShippingLabel = new ShipStationCommand( "/Orders/CreateLabelForOrder" );
private ShipStationCommand( string command )
{
this.Command = command;
}
public string Command{ get; private set; }
}
}
|
bsd-3-clause
|
C#
|
93f7e2fbcf5adcfb9febb5a27671b9afc0f08a37
|
Update OpeningMicrosoftExcel2007XlsxFiles.cs
|
aspose-cells/Aspose.Cells-for-.NET,maria-shahid-aspose/Aspose.Cells-for-.NET,asposecells/Aspose_Cells_NET,aspose-cells/Aspose.Cells-for-.NET,asposecells/Aspose_Cells_NET,maria-shahid-aspose/Aspose.Cells-for-.NET,asposecells/Aspose_Cells_NET,maria-shahid-aspose/Aspose.Cells-for-.NET,aspose-cells/Aspose.Cells-for-.NET,asposecells/Aspose_Cells_NET,aspose-cells/Aspose.Cells-for-.NET,maria-shahid-aspose/Aspose.Cells-for-.NET
|
Examples/CSharp/Files/Handling/OpeningMicrosoftExcel2007XlsxFiles.cs
|
Examples/CSharp/Files/Handling/OpeningMicrosoftExcel2007XlsxFiles.cs
|
using System.IO;
using Aspose.Cells;
using System;
namespace Aspose.Cells.Examples.Files.Handling
{
public class OpeningMicrosoftExcel2007XlsxFiles
{
public static void Main(string[] args)
{
//ExStart:1
// The path to the documents directory.
string dataDir = Aspose.Cells.Examples.Utils.GetDataDir(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
// Opening Microsoft Excel 2007 Xlsx Files
//Instantiate LoadOptions specified by the LoadFormat.
LoadOptions loadOptions2 = new LoadOptions(LoadFormat.Xlsx);
//Create a Workbook object and opening the file from its path
Workbook wbExcel2007 = new Workbook(dataDir + "Book_Excel2007.xlsx", loadOptions2);
Console.WriteLine("Microsoft Excel 2007 workbook opened successfully!");
//ExEnd:1
}
}
}
|
using System.IO;
using Aspose.Cells;
using System;
namespace Aspose.Cells.Examples.Files.Handling
{
public class OpeningMicrosoftExcel2007XlsxFiles
{
public static void Main(string[] args)
{
//Exstart:1
// The path to the documents directory.
string dataDir = Aspose.Cells.Examples.Utils.GetDataDir(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
// Opening Microsoft Excel 2007 Xlsx Files
//Instantiate LoadOptions specified by the LoadFormat.
LoadOptions loadOptions2 = new LoadOptions(LoadFormat.Xlsx);
//Create a Workbook object and opening the file from its path
Workbook wbExcel2007 = new Workbook(dataDir + "Book_Excel2007.xlsx", loadOptions2);
Console.WriteLine("Microsoft Excel 2007 workbook opened successfully!");
//ExEnd:1
}
}
}
|
mit
|
C#
|
9bb72ff7e2fcd63995ebcf0c50d94af6fbd8733a
|
Fix find usages of property event handlers
|
JetBrains/resharper-unity,JetBrains/resharper-unity,JetBrains/resharper-unity
|
resharper/resharper-unity/src/Yaml/Psi/Search/UnityYamlUsageSearchFactory.cs
|
resharper/resharper-unity/src/Yaml/Psi/Search/UnityYamlUsageSearchFactory.cs
|
using System.Collections.Generic;
using System.Linq;
using JetBrains.ProjectModel;
using JetBrains.ReSharper.Plugins.Unity.Yaml.Psi.Caches;
using JetBrains.ReSharper.Plugins.Yaml.Psi;
using JetBrains.ReSharper.Plugins.Yaml.Psi.Search;
using JetBrains.ReSharper.Psi;
using JetBrains.ReSharper.Psi.ExtensionsAPI;
using JetBrains.Util.dataStructures;
namespace JetBrains.ReSharper.Plugins.Unity.Yaml.Psi.Search
{
// Note that there isn't a default searcher factory for YAML because it has no declared elements to search for. This
// searcher factory is looking for C# declared elements - class or method, etc.
[PsiSharedComponent]
public class UnityYamlUsageSearchFactory : DomainSpecificSearcherFactoryBase
{
public override bool IsCompatibleWithLanguage(PsiLanguageType languageType)
{
return languageType.Is<YamlLanguage>();
}
public override IDomainSpecificSearcher CreateReferenceSearcher(IDeclaredElementsSet elements,
bool findCandidates)
{
// We're interested in classes for usages of MonoScript references, and methods for UnityEvent usages
if (elements.All(e => e is IClass || e is IMethod || e is IProperty))
return new YamlReferenceSearcher(this, elements, findCandidates);
return null;
}
// Used to filter files before searching for reference. Method references require the element short name while
// class references use the class's file's asset guid. If the file doesn't contain one of these words, it won't
// be searched
public override IEnumerable<string> GetAllPossibleWordsInFile(IDeclaredElement element)
{
var metaFileGuidCache = element.GetSolution().GetComponent<MetaFileGuidCache>();
var words = new FrugalLocalList<string>();
words.Add(element.ShortName);
foreach (var sourceFile in element.GetSourceFiles())
{
var guid = metaFileGuidCache.GetAssetGuid(sourceFile);
if (guid != null)
words.Add(guid);
}
return words.ToList();
}
}
}
|
using System.Collections.Generic;
using System.Linq;
using JetBrains.ProjectModel;
using JetBrains.ReSharper.Plugins.Unity.Yaml.Psi.Caches;
using JetBrains.ReSharper.Plugins.Yaml.Psi;
using JetBrains.ReSharper.Plugins.Yaml.Psi.Search;
using JetBrains.ReSharper.Psi;
using JetBrains.ReSharper.Psi.ExtensionsAPI;
using JetBrains.Util.dataStructures;
namespace JetBrains.ReSharper.Plugins.Unity.Yaml.Psi.Search
{
// Note that there isn't a default searcher factory for YAML because it has no declared elements to search for. This
// searcher factory is looking for C# declared elements - class or method, etc.
[PsiSharedComponent]
public class UnityYamlUsageSearchFactory : DomainSpecificSearcherFactoryBase
{
public override bool IsCompatibleWithLanguage(PsiLanguageType languageType)
{
return languageType.Is<YamlLanguage>();
}
public override IDomainSpecificSearcher CreateReferenceSearcher(IDeclaredElementsSet elements,
bool findCandidates)
{
// We're interested in classes for usages of MonoScript references, and methods for UnityEvent usages
if (elements.All(e => e is IClass || e is IMethod))
return new YamlReferenceSearcher(this, elements, findCandidates);
return null;
}
// Used to filter files before searching for reference. Method references require the element short name while
// class references use the class's file's asset guid. If the file doesn't contain one of these words, it won't
// be searched
public override IEnumerable<string> GetAllPossibleWordsInFile(IDeclaredElement element)
{
var metaFileGuidCache = element.GetSolution().GetComponent<MetaFileGuidCache>();
var words = new FrugalLocalList<string>();
words.Add(element.ShortName);
foreach (var sourceFile in element.GetSourceFiles())
{
var guid = metaFileGuidCache.GetAssetGuid(sourceFile);
if (guid != null)
words.Add(guid);
}
return words.ToList();
}
}
}
|
apache-2.0
|
C#
|
a20cdbb0dc44d651c0e216de73cdd7929a1bdc72
|
Add methods to IScriptBuilder
|
Ackara/Daterpillar
|
src/Daterpillar.Core/TextTransformation/IScriptBuilder.cs
|
src/Daterpillar.Core/TextTransformation/IScriptBuilder.cs
|
namespace Gigobyte.Daterpillar.TextTransformation
{
public interface IScriptBuilder
{
void Append(string text);
void AppendLine(string text);
void Create(Table table);
void Create(Index index);
void Create(ForeignKey foreignKey);
void Drop(Table table);
void Drop(Index index);
void Drop(ForeignKey foreignKey);
void AlterTable(Table tableA, Table tableB);
byte[] GetContentAsBytes();
string GetContentAsString();
}
}
|
namespace Gigobyte.Daterpillar.TextTransformation
{
public interface IScriptBuilder
{
void Create(Table table);
void Create(Index index);
void Drop(Table table);
void Drop(Index index);
void AlterTable(Table tableA, Table tableB);
}
}
|
mit
|
C#
|
63c96d5a83560e864d62585aa27e9443bd968236
|
Fix tail note not properly capping result
|
UselessToucan/osu,ppy/osu,peppy/osu,smoogipooo/osu,peppy/osu-new,EVAST9919/osu,smoogipoo/osu,ppy/osu,smoogipoo/osu,peppy/osu,johnneijzen/osu,2yangk23/osu,2yangk23/osu,EVAST9919/osu,UselessToucan/osu,peppy/osu,johnneijzen/osu,NeoAdonis/osu,smoogipoo/osu,ppy/osu,NeoAdonis/osu,UselessToucan/osu,NeoAdonis/osu
|
osu.Game.Rulesets.Mania/Objects/Drawables/DrawableHoldNoteTail.cs
|
osu.Game.Rulesets.Mania/Objects/Drawables/DrawableHoldNoteTail.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.Diagnostics;
using osu.Game.Rulesets.Scoring;
namespace osu.Game.Rulesets.Mania.Objects.Drawables
{
/// <summary>
/// The tail of a <see cref="DrawableHoldNote"/>.
/// </summary>
public class DrawableHoldNoteTail : DrawableNote
{
/// <summary>
/// Lenience of release hit windows. This is to make cases where the hold note release
/// is timed alongside presses of other hit objects less awkward.
/// Todo: This shouldn't exist for non-LegacyBeatmapDecoder beatmaps
/// </summary>
private const double release_window_lenience = 1.5;
private readonly DrawableHoldNote holdNote;
public DrawableHoldNoteTail(DrawableHoldNote holdNote)
: base(holdNote.HitObject.Tail)
{
this.holdNote = holdNote;
}
public void UpdateResult() => base.UpdateResult(true);
protected override void CheckForResult(bool userTriggered, double timeOffset)
{
Debug.Assert(HitObject.HitWindows != null);
// Factor in the release lenience
timeOffset /= release_window_lenience;
if (!userTriggered)
{
if (!HitObject.HitWindows.CanBeHit(timeOffset))
ApplyResult(r => r.Type = HitResult.Miss);
return;
}
var result = HitObject.HitWindows.ResultFor(timeOffset);
if (result == HitResult.None)
return;
ApplyResult(r =>
{
// If the head wasn't hit or the hold note was broken, cap the max score to Meh.
if (result > HitResult.Meh && (!holdNote.Head.IsHit || holdNote.HasBroken))
result = HitResult.Meh;
r.Type = result;
});
}
public override bool OnPressed(ManiaAction action) => false; // Handled by the hold note
public override bool OnReleased(ManiaAction action) => false; // Handled by the hold note
}
}
|
// 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.Diagnostics;
using osu.Game.Rulesets.Scoring;
namespace osu.Game.Rulesets.Mania.Objects.Drawables
{
/// <summary>
/// The tail of a <see cref="DrawableHoldNote"/>.
/// </summary>
public class DrawableHoldNoteTail : DrawableNote
{
/// <summary>
/// Lenience of release hit windows. This is to make cases where the hold note release
/// is timed alongside presses of other hit objects less awkward.
/// Todo: This shouldn't exist for non-LegacyBeatmapDecoder beatmaps
/// </summary>
private const double release_window_lenience = 1.5;
private readonly DrawableHoldNote holdNote;
public DrawableHoldNoteTail(DrawableHoldNote holdNote)
: base(holdNote.HitObject.Tail)
{
this.holdNote = holdNote;
}
public void UpdateResult() => base.UpdateResult(true);
protected override void CheckForResult(bool userTriggered, double timeOffset)
{
Debug.Assert(HitObject.HitWindows != null);
// Factor in the release lenience
timeOffset /= release_window_lenience;
if (!userTriggered)
{
if (!HitObject.HitWindows.CanBeHit(timeOffset))
ApplyResult(r => r.Type = HitResult.Miss);
return;
}
var result = HitObject.HitWindows.ResultFor(timeOffset);
if (result == HitResult.None)
return;
ApplyResult(r =>
{
if (holdNote.HasBroken && (result == HitResult.Perfect || result == HitResult.Perfect))
result = HitResult.Good;
r.Type = result;
});
}
public override bool OnPressed(ManiaAction action) => false; // Handled by the hold note
public override bool OnReleased(ManiaAction action) => false; // Handled by the hold note
}
}
|
mit
|
C#
|
13ed52a990cc4f1b53b3a1f1b37694859b5427cf
|
Fix weird license misindent
|
ppy/osu,NeoAdonis/osu,smoogipoo/osu,NeoAdonis/osu,peppy/osu,UselessToucan/osu,smoogipoo/osu,peppy/osu,peppy/osu,ppy/osu,smoogipoo/osu,ppy/osu,UselessToucan/osu,smoogipooo/osu,peppy/osu-new,NeoAdonis/osu,UselessToucan/osu
|
osu.Game.Tests/Rulesets/TestSceneRulesetSkinProvidingContainer.cs
|
osu.Game.Tests/Rulesets/TestSceneRulesetSkinProvidingContainer.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 NUnit.Framework;
using osu.Framework.Allocation;
using osu.Framework.Audio.Sample;
using osu.Framework.Bindables;
using osu.Framework.Graphics;
using osu.Framework.Graphics.OpenGL.Textures;
using osu.Framework.Graphics.Textures;
using osu.Game.Audio;
using osu.Game.Rulesets;
using osu.Game.Skinning;
using osu.Game.Tests.Testing;
using osu.Game.Tests.Visual;
namespace osu.Game.Tests.Rulesets
{
public class TestSceneRulesetSkinProvidingContainer : OsuTestScene
{
[Resolved]
private SkinManager skins { get; set; }
private SkinRequester requester;
protected override Ruleset CreateRuleset() => new TestSceneRulesetDependencies.TestRuleset();
[Test]
public void TestEarlyAddedSkinRequester()
{
Texture textureOnLoad = null;
AddStep("set skin", () => skins.CurrentSkinInfo.Value = DefaultLegacySkin.Info);
AddStep("setup provider", () =>
{
var rulesetSkinProvider = new RulesetSkinProvidingContainer(Ruleset.Value.CreateInstance(), Beatmap.Value.Beatmap, Beatmap.Value.Skin);
rulesetSkinProvider.Add(requester = new SkinRequester());
requester.OnLoadAsync += () => textureOnLoad = requester.GetTexture("hitcircle");
Child = rulesetSkinProvider;
});
AddAssert("requester got correct initial texture", () => textureOnLoad != null);
}
private class SkinRequester : Drawable, ISkin
{
private ISkinSource skin;
public event Action OnLoadAsync;
[BackgroundDependencyLoader]
private void load(ISkinSource skin)
{
this.skin = skin;
OnLoadAsync?.Invoke();
}
public Drawable GetDrawableComponent(ISkinComponent component) => skin.GetDrawableComponent(component);
public Texture GetTexture(string componentName, WrapMode wrapModeS = default, WrapMode wrapModeT = default) => skin.GetTexture(componentName);
public ISample GetSample(ISampleInfo sampleInfo) => skin.GetSample(sampleInfo);
public IBindable<TValue> GetConfig<TLookup, TValue>(TLookup lookup) => skin.GetConfig<TLookup, TValue>(lookup);
}
}
}
|
// 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 NUnit.Framework;
using osu.Framework.Allocation;
using osu.Framework.Audio.Sample;
using osu.Framework.Bindables;
using osu.Framework.Graphics;
using osu.Framework.Graphics.OpenGL.Textures;
using osu.Framework.Graphics.Textures;
using osu.Game.Audio;
using osu.Game.Rulesets;
using osu.Game.Skinning;
using osu.Game.Tests.Testing;
using osu.Game.Tests.Visual;
namespace osu.Game.Tests.Rulesets
{
public class TestSceneRulesetSkinProvidingContainer : OsuTestScene
{
[Resolved]
private SkinManager skins { get; set; }
private SkinRequester requester;
protected override Ruleset CreateRuleset() => new TestSceneRulesetDependencies.TestRuleset();
[Test]
public void TestEarlyAddedSkinRequester()
{
Texture textureOnLoad = null;
AddStep("set skin", () => skins.CurrentSkinInfo.Value = DefaultLegacySkin.Info);
AddStep("setup provider", () =>
{
var rulesetSkinProvider = new RulesetSkinProvidingContainer(Ruleset.Value.CreateInstance(), Beatmap.Value.Beatmap, Beatmap.Value.Skin);
rulesetSkinProvider.Add(requester = new SkinRequester());
requester.OnLoadAsync += () => textureOnLoad = requester.GetTexture("hitcircle");
Child = rulesetSkinProvider;
});
AddAssert("requester got correct initial texture", () => textureOnLoad != null);
}
private class SkinRequester : Drawable, ISkin
{
private ISkinSource skin;
public event Action OnLoadAsync;
[BackgroundDependencyLoader]
private void load(ISkinSource skin)
{
this.skin = skin;
OnLoadAsync?.Invoke();
}
public Drawable GetDrawableComponent(ISkinComponent component) => skin.GetDrawableComponent(component);
public Texture GetTexture(string componentName, WrapMode wrapModeS = default, WrapMode wrapModeT = default) => skin.GetTexture(componentName);
public ISample GetSample(ISampleInfo sampleInfo) => skin.GetSample(sampleInfo);
public IBindable<TValue> GetConfig<TLookup, TValue>(TLookup lookup) => skin.GetConfig<TLookup, TValue>(lookup);
}
}
}
|
mit
|
C#
|
93b616af6fb208715016869c28ada5a953d70471
|
Add unit tests for enum access token grant type read and write.
|
henrikfroehling/TraktApiSharp
|
Source/Tests/TraktApiSharp.Tests/Enums/TraktAccessTokenGrantTypeTests.cs
|
Source/Tests/TraktApiSharp.Tests/Enums/TraktAccessTokenGrantTypeTests.cs
|
namespace TraktApiSharp.Tests.Enums
{
using FluentAssertions;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Newtonsoft.Json;
using TraktApiSharp.Enums;
[TestClass]
public class TraktAccessTokenGrantTypeTests
{
class TestObject
{
[JsonConverter(typeof(TraktAccessTokenGrantTypeConverter))]
public TraktAccessTokenGrantType Value { get; set; }
}
[TestMethod]
public void TestTraktAccessTokenGrantTypeHasMembers()
{
typeof(TraktAccessTokenGrantType).GetEnumNames().Should().HaveCount(3)
.And.Contain("AuthorizationCode", "RefreshToken", "Unspecified");
}
[TestMethod]
public void TestTraktAccessTokenGrantTypeGetAsString()
{
TraktAccessTokenGrantType.AuthorizationCode.AsString().Should().Be("authorization_code");
TraktAccessTokenGrantType.RefreshToken.AsString().Should().Be("refresh_token");
TraktAccessTokenGrantType.Unspecified.AsString().Should().NotBeNull().And.BeEmpty();
}
[TestMethod]
public void TestTraktAccessTokenGrantTypeWriteAndReadJson_AuthorizationCode()
{
var obj = new TestObject { Value = TraktAccessTokenGrantType.AuthorizationCode };
var objWritten = JsonConvert.SerializeObject(obj);
objWritten.Should().NotBeNullOrEmpty();
var objRead = JsonConvert.DeserializeObject<TestObject>(objWritten);
objRead.Should().NotBeNull();
objRead.Value.Should().Be(TraktAccessTokenGrantType.AuthorizationCode);
}
[TestMethod]
public void TestTraktAccessTokenGrantTypeWriteAndReadJson_RefreshToken()
{
var obj = new TestObject { Value = TraktAccessTokenGrantType.RefreshToken };
var objWritten = JsonConvert.SerializeObject(obj);
objWritten.Should().NotBeNullOrEmpty();
var objRead = JsonConvert.DeserializeObject<TestObject>(objWritten);
objRead.Should().NotBeNull();
objRead.Value.Should().Be(TraktAccessTokenGrantType.RefreshToken);
}
[TestMethod]
public void TestTraktAccessTokenGrantTypeWriteAndReadJson_Unspecified()
{
var obj = new TestObject { Value = TraktAccessTokenGrantType.Unspecified };
var objWritten = JsonConvert.SerializeObject(obj);
objWritten.Should().NotBeNullOrEmpty();
var objRead = JsonConvert.DeserializeObject<TestObject>(objWritten);
objRead.Should().NotBeNull();
objRead.Value.Should().Be(TraktAccessTokenGrantType.Unspecified);
}
}
}
|
namespace TraktApiSharp.Tests.Enums
{
using FluentAssertions;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using TraktApiSharp.Enums;
[TestClass]
public class TraktAccessTokenGrantTypeTests
{
[TestMethod]
public void TestTraktAccessTokenGrantTypeHasMembers()
{
typeof(TraktAccessTokenGrantType).GetEnumNames().Should().HaveCount(3)
.And.Contain("AuthorizationCode", "RefreshToken", "Unspecified");
}
[TestMethod]
public void TestTraktAccessTokenGrantTypeGetAsString()
{
TraktAccessTokenGrantType.AuthorizationCode.AsString().Should().Be("authorization_code");
TraktAccessTokenGrantType.RefreshToken.AsString().Should().Be("refresh_token");
TraktAccessTokenGrantType.Unspecified.AsString().Should().NotBeNull().And.BeEmpty();
}
}
}
|
mit
|
C#
|
d8bdfe034b3810c96431d3bee27ec4dac3f35ac4
|
Refactor NonTrivialConstantVisitor.
|
Code-Sharp/GraphClimber
|
src/GraphClimber/ExpressionCompiler/NonTrivialConstantVisitor.cs
|
src/GraphClimber/ExpressionCompiler/NonTrivialConstantVisitor.cs
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using GraphClimber.ExpressionCompiler.Extensions;
namespace GraphClimber.ExpressionCompiler
{
public class NonTrivialConstantVisitor : ExpressionVisitor
{
private static readonly MethodInfo _getMethodInfo = typeof (NonTrivialConstantVisitor).GetMethod("Get", BindingFlags.Static | BindingFlags.Public);
private static readonly IList<object> _objects = new List<object>();
private static readonly object _syncRoot = new object();
public static readonly ExpressionVisitor Empty = new NonTrivialConstantVisitor();
private NonTrivialConstantVisitor()
{
}
public static object Get(int number)
{
return _objects[number];
}
public static int Add(object value)
{
lock (_syncRoot)
{
int objectNumber = _objects.Count;
_objects.Add(value);
return objectNumber;
}
}
protected override Expression VisitConstant(ConstantExpression node)
{
if (node.Type.IsPrimitive || node.Type == typeof(string))
{
return base.VisitConstant(node);
}
// RuntimeType is internal, using Type instead.
if (node.Type.FullName == "System.RuntimeType")
{
return Expression.Constant(node.Value, typeof (Type));
}
int objectNumber = Add(node.Value);
return Expression.Call(_getMethodInfo, objectNumber.Constant()).Convert(node.Type);
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using GraphClimber.ExpressionCompiler.Extensions;
namespace GraphClimber.ExpressionCompiler
{
public class NonTrivialConstantVisitor : ExpressionVisitor
{
private static readonly MethodInfo _getMethodInfo = typeof (NonTrivialConstantVisitor).GetMethod("Get", BindingFlags.Static | BindingFlags.Public);
private static readonly IList<object> _objects = new List<object>();
private static readonly object _syncRoot = new object();
public static readonly ExpressionVisitor Empty = new NonTrivialConstantVisitor();
private NonTrivialConstantVisitor()
{
}
public static object Get(int number)
{
return _objects[number];
}
public static int Add<T>(T value)
{
lock (_syncRoot)
{
int objectNumber = _objects.Count;
_objects.Add(value);
return objectNumber;
}
}
protected override Expression VisitConstant(ConstantExpression node)
{
if (node.Type.IsPrimitive || node.Type == typeof(string))
{
return base.VisitConstant(node);
}
if (node.Type.FullName == "System.RuntimeType")
{
return Expression.Constant(node.Value, typeof (Type));
}
int objectNumber = Add(node.Value);
return Expression.Call(_getMethodInfo, objectNumber.Constant()).Convert(node.Type);
}
}
}
|
bsd-2-clause
|
C#
|
075d64221a131249b1c90f49e622cebd8434b662
|
clear the pool after the test
|
lnu/nhibernate-core,RogerKratz/nhibernate-core,alobakov/nhibernate-core,livioc/nhibernate-core,fredericDelaporte/nhibernate-core,ManufacturingIntelligence/nhibernate-core,lnu/nhibernate-core,nhibernate/nhibernate-core,livioc/nhibernate-core,hazzik/nhibernate-core,nkreipke/nhibernate-core,ngbrown/nhibernate-core,RogerKratz/nhibernate-core,ManufacturingIntelligence/nhibernate-core,nkreipke/nhibernate-core,ManufacturingIntelligence/nhibernate-core,ngbrown/nhibernate-core,RogerKratz/nhibernate-core,gliljas/nhibernate-core,gliljas/nhibernate-core,nkreipke/nhibernate-core,RogerKratz/nhibernate-core,hazzik/nhibernate-core,hazzik/nhibernate-core,nhibernate/nhibernate-core,alobakov/nhibernate-core,hazzik/nhibernate-core,fredericDelaporte/nhibernate-core,alobakov/nhibernate-core,fredericDelaporte/nhibernate-core,livioc/nhibernate-core,fredericDelaporte/nhibernate-core,ngbrown/nhibernate-core,lnu/nhibernate-core,nhibernate/nhibernate-core,gliljas/nhibernate-core,nhibernate/nhibernate-core,gliljas/nhibernate-core
|
src/NHibernate.Test/NHSpecificTest/NH1908ThreadSafety/Fixture.cs
|
src/NHibernate.Test/NHSpecificTest/NH1908ThreadSafety/Fixture.cs
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using NHibernate.Util;
using NUnit.Framework;
namespace NHibernate.Test.NHSpecificTest.NH1908ThreadSafety
{
[TestFixture]
public class Fixture : BugTestCase
{
protected override bool AppliesTo(Dialect.Dialect dialect)
{
return !(dialect is Dialect.Oracle8iDialect);
// Oracle sometimes causes: ORA-12520: TNS:listener could not find available handler for requested type of server
// Following links bizarrely suggest it's an Oracle limitation under load:
// http://www.orafaq.com/forum/t/60019/2/ & http://www.ispirer.com/wiki/sqlways/troubleshooting-guide/oracle/import/tns_listener
}
protected override void OnTearDown()
{
base.OnTearDown();
if (!(Dialect is Dialect.FirebirdDialect))
return;
// Firebird will pool each connection created during the test and will not drop the created tables
// which will result in other tests failing when they try to create tables with same name
// By clearing the connection pool the tables will get dropped. This is done by the following code.
var fbConnectionType = ReflectHelper.TypeFromAssembly("FirebirdSql.Data.FirebirdClient.FbConnection", "FirebirdSql.Data.FirebirdClient", false);
var clearPool = fbConnectionType.GetMethod("ClearPool");
var sillyConnection = sessions.ConnectionProvider.GetConnection();
clearPool.Invoke(null, new object[] { sillyConnection });
sessions.ConnectionProvider.CloseConnection(sillyConnection);
}
[Test]
public void UsingFiltersIsThreadSafe()
{
var errors = new List<Exception>();
var threads = new List<Thread>();
for (int i = 0; i < 50; i++)
{
var thread = new Thread(() =>
{
try
{
ScenarioRunningWithMultiThreading();
}
catch (Exception ex)
{
lock (errors)
errors.Add(ex);
}
});
thread.Start();
threads.Add(thread);
}
foreach (var thread in threads)
{
thread.Join();
}
Console.WriteLine("Detected {0} errors in threads. Displaying the first three (if any):", errors.Count);
foreach (var exception in errors.Take(3))
Console.WriteLine(exception);
Assert.AreEqual(0, errors.Count, "number of threads with exceptions");
}
private void ScenarioRunningWithMultiThreading()
{
using (var session = sessions.OpenSession())
{
session
.EnableFilter("CurrentOnly")
.SetParameter("date", DateTime.Now);
session.CreateQuery(
@"
select u
from Order u
left join fetch u.ActiveOrderLines
where
u.Email = :email
")
.SetString("email", "stupid@bugs.com")
.UniqueResult<Order>();
}
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using NUnit.Framework;
namespace NHibernate.Test.NHSpecificTest.NH1908ThreadSafety
{
[TestFixture]
public class Fixture : BugTestCase
{
protected override bool AppliesTo(Dialect.Dialect dialect)
{
return !(dialect is Dialect.Oracle8iDialect);
// Oracle sometimes causes: ORA-12520: TNS:listener could not find available handler for requested type of server
// Following links bizarrely suggest it's an Oracle limitation under load:
// http://www.orafaq.com/forum/t/60019/2/ & http://www.ispirer.com/wiki/sqlways/troubleshooting-guide/oracle/import/tns_listener
}
[Test]
public void UsingFiltersIsThreadSafe()
{
var errors = new List<Exception>();
var threads = new List<Thread>();
for (int i = 0; i < 50; i++)
{
var thread = new Thread(() =>
{
try
{
ScenarioRunningWithMultiThreading();
}
catch (Exception ex)
{
lock (errors)
errors.Add(ex);
}
});
thread.Start();
threads.Add(thread);
}
foreach (var thread in threads)
{
thread.Join();
}
Console.WriteLine("Detected {0} errors in threads. Displaying the first three (if any):", errors.Count);
foreach (var exception in errors.Take(3))
Console.WriteLine(exception);
Assert.AreEqual(0, errors.Count, "number of threads with exceptions");
}
private void ScenarioRunningWithMultiThreading()
{
using (var session = sessions.OpenSession())
{
session
.EnableFilter("CurrentOnly")
.SetParameter("date", DateTime.Now);
session.CreateQuery(
@"
select u
from Order u
left join fetch u.ActiveOrderLines
where
u.Email = :email
")
.SetString("email", "stupid@bugs.com")
.UniqueResult<Order>();
}
}
}
}
|
lgpl-2.1
|
C#
|
9e68c92d1917f0d7d01bd14f84e6b32ccb55da58
|
Add confirm & return_url properties to SetupIntentCreateOptions
|
stripe/stripe-dotnet
|
src/Stripe.net/Services/SetupIntents/SetupIntentCreateOptions.cs
|
src/Stripe.net/Services/SetupIntents/SetupIntentCreateOptions.cs
|
namespace Stripe
{
using System.Collections.Generic;
using Newtonsoft.Json;
public class SetupIntentCreateOptions : BaseOptions
{
[JsonProperty("confirm")]
public bool? Confirm { get; set; }
[JsonProperty("customer")]
public string CustomerId { get; set; }
[JsonProperty("description")]
public string Description { get; set; }
[JsonProperty("metadata")]
public Dictionary<string, string> Metadata { get; set; }
[JsonProperty("on_behalf_of")]
public string OnBehalfOf { get; set; }
[JsonProperty("payment_method")]
public string PaymentMethodId { get; set; }
[JsonProperty("payment_method_types")]
public List<string> PaymentMethodTypes { get; set; }
[JsonProperty("return_url")]
public string ReturnUrl { get; set; }
[JsonProperty("usage")]
public string Usage { get; set; }
}
}
|
namespace Stripe
{
using System.Collections.Generic;
using Newtonsoft.Json;
public class SetupIntentCreateOptions : BaseOptions
{
[JsonProperty("customer")]
public string CustomerId { get; set; }
[JsonProperty("description")]
public string Description { get; set; }
[JsonProperty("metadata")]
public Dictionary<string, string> Metadata { get; set; }
[JsonProperty("on_behalf_of")]
public string OnBehalfOf { get; set; }
[JsonProperty("payment_method")]
public string PaymentMethodId { get; set; }
[JsonProperty("payment_method_types")]
public List<string> PaymentMethodTypes { get; set; }
[JsonProperty("usage")]
public string Usage { get; set; }
}
}
|
apache-2.0
|
C#
|
1aca60e9c71a6a0f85984a65977374a5db4cfa96
|
sort properties
|
arknu/Umbraco-CMS,marcemarc/Umbraco-CMS,NikRimington/Umbraco-CMS,marcemarc/Umbraco-CMS,arknu/Umbraco-CMS,tcmorris/Umbraco-CMS,abryukhov/Umbraco-CMS,umbraco/Umbraco-CMS,NikRimington/Umbraco-CMS,umbraco/Umbraco-CMS,tcmorris/Umbraco-CMS,tcmorris/Umbraco-CMS,bjarnef/Umbraco-CMS,robertjf/Umbraco-CMS,JimBobSquarePants/Umbraco-CMS,mattbrailsford/Umbraco-CMS,robertjf/Umbraco-CMS,bjarnef/Umbraco-CMS,abryukhov/Umbraco-CMS,abjerner/Umbraco-CMS,robertjf/Umbraco-CMS,JimBobSquarePants/Umbraco-CMS,leekelleher/Umbraco-CMS,tcmorris/Umbraco-CMS,dawoe/Umbraco-CMS,leekelleher/Umbraco-CMS,hfloyd/Umbraco-CMS,abjerner/Umbraco-CMS,madsoulswe/Umbraco-CMS,marcemarc/Umbraco-CMS,umbraco/Umbraco-CMS,KevinJump/Umbraco-CMS,umbraco/Umbraco-CMS,marcemarc/Umbraco-CMS,NikRimington/Umbraco-CMS,arknu/Umbraco-CMS,JimBobSquarePants/Umbraco-CMS,bjarnef/Umbraco-CMS,dawoe/Umbraco-CMS,KevinJump/Umbraco-CMS,arknu/Umbraco-CMS,robertjf/Umbraco-CMS,marcemarc/Umbraco-CMS,leekelleher/Umbraco-CMS,bjarnef/Umbraco-CMS,abryukhov/Umbraco-CMS,abryukhov/Umbraco-CMS,abjerner/Umbraco-CMS,dawoe/Umbraco-CMS,leekelleher/Umbraco-CMS,robertjf/Umbraco-CMS,hfloyd/Umbraco-CMS,tcmorris/Umbraco-CMS,hfloyd/Umbraco-CMS,mattbrailsford/Umbraco-CMS,KevinJump/Umbraco-CMS,JimBobSquarePants/Umbraco-CMS,leekelleher/Umbraco-CMS,madsoulswe/Umbraco-CMS,hfloyd/Umbraco-CMS,mattbrailsford/Umbraco-CMS,madsoulswe/Umbraco-CMS,dawoe/Umbraco-CMS,KevinJump/Umbraco-CMS,hfloyd/Umbraco-CMS,dawoe/Umbraco-CMS,KevinJump/Umbraco-CMS,abjerner/Umbraco-CMS,mattbrailsford/Umbraco-CMS,JimBobSquarePants/Umbraco-CMS,tcmorris/Umbraco-CMS
|
src/Umbraco.Web/PropertyEditors/BlockListConfiguration.cs
|
src/Umbraco.Web/PropertyEditors/BlockListConfiguration.cs
|
using Newtonsoft.Json;
using System;
using Umbraco.Core.PropertyEditors;
namespace Umbraco.Web.PropertyEditors
{
/// <summary>
/// The configuration object for the Block List editor
/// </summary>
public class BlockListConfiguration
{
[ConfigurationField("blocks", "Available Blocks", "views/propertyeditors/blocklist/prevalue/blocklist.blockconfiguration.html", Description = "Define the available blocks.")]
public BlockConfiguration[] Blocks { get; set; }
public class BlockConfiguration
{
[JsonProperty("backgroundColor")]
public string BackgroundColor { get; set; }
[JsonProperty("iconColor")]
public string IconColor { get; set; }
[JsonProperty("thumbnail")]
public string Thumbnail { get; set; }
[JsonProperty("contentTypeKey")]
public Guid Key { get; set; }
[JsonProperty("settingsElementTypeKey")]
public string SettingsElementTypeKey { get; set; }
[JsonProperty("view")]
public string View { get; set; }
[JsonProperty("stylesheet")]
public string Stylesheet { get; set; }
[JsonProperty("label")]
public string Label { get; set; }
[JsonProperty("editorSize")]
public string EditorSize { get; set; }
}
[ConfigurationField("validationLimit", "Amount", "numberrange", Description = "Set a required range of blocks")]
public NumberRange ValidationLimit { get; set; } = new NumberRange();
public class NumberRange
{
[JsonProperty("min")]
public int? Min { get; set; }
[JsonProperty("max")]
public int? Max { get; set; }
}
[ConfigurationField("useInlineEditingAsDefault", "Inline editing mode", "boolean", Description = "Use the inline editor as the default block view.")]
public bool UseInlineEditingAsDefault { get; set; }
[ConfigurationField("maxPropertyWidth", "Property editor width", "textstring", Description = "optional css overwrite, example: 800px or 100%")]
public string MaxPropertyWidth { get; set; }
}
}
|
using Newtonsoft.Json;
using System;
using Umbraco.Core.PropertyEditors;
namespace Umbraco.Web.PropertyEditors
{
/// <summary>
/// The configuration object for the Block List editor
/// </summary>
public class BlockListConfiguration
{
[ConfigurationField("blocks", "Available Blocks", "views/propertyeditors/blocklist/prevalue/blocklist.blockconfiguration.html", Description = "Define the available blocks.")]
public BlockConfiguration[] Blocks { get; set; }
[ConfigurationField("validationLimit", "Amount", "numberrange", Description = "Set a required range of blocks")]
public NumberRange ValidationLimit { get; set; } = new NumberRange();
public class NumberRange
{
[JsonProperty("min")]
public int? Min { get; set; }
[JsonProperty("max")]
public int? Max { get; set; }
}
public class BlockConfiguration
{
[JsonProperty("backgroundColor")]
public string BackgroundColor { get; set; }
[JsonProperty("iconColor")]
public string IconColor { get; set; }
[JsonProperty("thumbnail")]
public string Thumbnail { get; set; }
[JsonProperty("contentTypeKey")]
public Guid Key { get; set; }
[JsonProperty("settingsElementTypeKey")]
public string SettingsElementTypeKey { get; set; }
[JsonProperty("view")]
public string View { get; set; }
[JsonProperty("stylesheet")]
public string Stylesheet { get; set; }
[JsonProperty("label")]
public string Label { get; set; }
[JsonProperty("editorSize")]
public string EditorSize { get; set; }
}
[ConfigurationField("useInlineEditingAsDefault", "Inline editing mode", "boolean", Description = "Use the inline editor as the default block view.")]
public bool UseInlineEditingAsDefault { get; set; }
[ConfigurationField("maxPropertyWidth", "Property editor width", "textstring", Description = "optional css overwrite, example: 800px or 100%")]
public string MaxPropertyWidth { get; set; }
}
}
|
mit
|
C#
|
8f4bea432e0e32739faa073b5b10860339dd05df
|
Add more complex array test to hello app
|
gregmac/NServiceMVC,gregmac/NServiceMVC,gregmac/NServiceMVC,ManuelRin/NServiceMVC,ManuelRin/NServiceMVC
|
src/NServiceMVC.Examples.HelloWorld/Controllers/ArraySampleController.cs
|
src/NServiceMVC.Examples.HelloWorld/Controllers/ArraySampleController.cs
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using AttributeRouting;
namespace NServiceMVC.Examples.HelloWorld.Controllers
{
public class ArraySampleController : ServiceController
{
//
// GET: /ArraySample/
[GET("arraysample/string/list")]
public List<string> StringList()
{
return new List<string>() { "one", "two", "three" };
}
[GET("arraysample/string/enumerable")]
public IEnumerable<string> StringEnumerable()
{
return new List<string>() { "one", "two", "three" };
}
[GET("arraysample/string/array")]
public string[] StringArray()
{
return new string[] { "one", "two", "three" };
}
[GET("arraysample/hello/{name}")]
public List<Models.HelloResponse> HelloList(string name)
{
return new List<Models.HelloResponse>() {
new Models.HelloResponse() { GreetingType = "Hello", Name = name },
new Models.HelloResponse() { GreetingType = "Bonjour", Name = name },
new Models.HelloResponse() { GreetingType = "¡Hola", Name = name },
new Models.HelloResponse() { GreetingType = "こんにちは", Name = name },
new Models.HelloResponse() { GreetingType = "שלום", Name = name },
new Models.HelloResponse() { GreetingType = "привет", Name = name },
new Models.HelloResponse() { GreetingType = "Hallå", Name = name },
};
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using AttributeRouting;
namespace NServiceMVC.Examples.HelloWorld.Controllers
{
public class ArraySampleController : ServiceController
{
//
// GET: /ArraySample/
[GET("arraysample/string/list")]
public List<string> StringList()
{
return new List<string>() { "one", "two", "three" };
}
[GET("arraysample/string/enumerable")]
public IEnumerable<string> StringEnumerable()
{
return new List<string>() { "one", "two", "three" };
}
[GET("arraysample/string/array")]
public string[] StringArray()
{
return new string[] { "one", "two", "three" };
}
}
}
|
mit
|
C#
|
1eefe32c8c0797b6351b6ac78a9903c9851001d9
|
Remove ClientId option from RestConfig
|
Aux/NTwitch,Aux/NTwitch
|
src/NTwitch.Rest/TwitchRestClientConfig.cs
|
src/NTwitch.Rest/TwitchRestClientConfig.cs
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace NTwitch.Rest
{
public class TwitchRestClientConfig
{
public string BaseUrl { get; set; } = "https://api.twitch.tv/kraken/";
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace Twitch.Rest
{
public class TwitchRestClientConfig
{
public string BaseUrl { get; set; } = "https://api.twitch.tv/kraken/";
public uint ClientId { get; set; }
}
}
|
mit
|
C#
|
4b145d3da8f3647c8d5114c8e50f40c1ddd2da0e
|
Fix issue when no UserDetails created yet and get current user info is requested.
|
enarod/enarod-web-api,enarod/enarod-web-api,enarod/enarod-web-api
|
Infopulse.EDemocracy.Data/Repositories/UserDetailRepository.cs
|
Infopulse.EDemocracy.Data/Repositories/UserDetailRepository.cs
|
using System;
using System.Collections.Generic;
using Infopulse.EDemocracy.Data.Interfaces;
using Infopulse.EDemocracy.Model;
using System.Data;
using System.Data.Entity;
using System.Data.SqlClient;
using System.Linq;
using System.Runtime.CompilerServices;
namespace Infopulse.EDemocracy.Data.Repositories
{
public class UserDetailRepository : BaseRepository, IUserDetailRepository
{
public int GetUserId(string userEmail)
{
using (var db = new EDEntities())
{
var userID = db.Database.SqlQuery<int>(
"sp_User_GetIdByEmail @UserEmail",
new SqlParameter()
{
ParameterName = "UserEmail",
DbType = DbType.String,
Value = userEmail,
Direction = ParameterDirection.Input
});
return userID.SingleOrDefault();
}
}
public UserDetail Update(UserDetail user)
{
using (var db = new EDEntities())
{
var userDetailFromDb = db.UserDetails.SingleOrDefault(ud => ud.UserID == user.UserID);
if (userDetailFromDb == null && user.User != null && !string.IsNullOrWhiteSpace(user.User.Email))
{
userDetailFromDb = db.UserDetails.SingleOrDefault(ud => ud.User.Email == user.User.Email);
}
if (userDetailFromDb == null)
{
user.CreatedBy = this.UnknownAppUser;
user.CreatedDate = DateTime.UtcNow;
user.User = null;
db.UserDetails.Add(user);
}
else
{
user.ID = userDetailFromDb.ID;
var entry = db.Entry(userDetailFromDb);
entry.CurrentValues.SetValues(user);
entry.Property(u => u.CreatedBy).IsModified = false;
entry.Property(u => u.CreatedDate).IsModified = false;
}
db.SaveChanges();
return db.UserDetails.SingleOrDefault(ud => ud.ID == user.ID);
}
}
//public IEnumerable<UserDetail> Get()
//{
// using (var db = new EDEntities())
// {
// var usersInfo = db.UserDetails
//.Include("User")
//.ToList();
// return usersInfo;
// }
//}
public UserDetail Get(int userID)
{
using (var db = new EDEntities())
{
var userInfo = db.UserDetails
.Include("User")
.SingleOrDefault(u => u.UserID == userID);
return userInfo;
}
}
}
}
|
using System;
using System.Collections.Generic;
using Infopulse.EDemocracy.Data.Interfaces;
using Infopulse.EDemocracy.Model;
using System.Data;
using System.Data.Entity;
using System.Data.SqlClient;
using System.Linq;
using System.Runtime.CompilerServices;
namespace Infopulse.EDemocracy.Data.Repositories
{
public class UserDetailRepository : BaseRepository, IUserDetailRepository
{
public int GetUserId(string userEmail)
{
using (var db = new EDEntities())
{
var userID = db.Database.SqlQuery<int>(
"sp_User_GetIdByEmail @UserEmail",
new SqlParameter()
{
ParameterName = "UserEmail",
DbType = DbType.String,
Value = userEmail,
Direction = ParameterDirection.Input
});
return userID.SingleOrDefault();
}
}
public UserDetail Update(UserDetail user)
{
using (var db = new EDEntities())
{
var userDetailFromDb = db.UserDetails.SingleOrDefault(ud => ud.UserID == user.UserID);
if (userDetailFromDb == null && user.User != null && !string.IsNullOrWhiteSpace(user.User.Email))
{
userDetailFromDb = db.UserDetails.SingleOrDefault(ud => ud.User.Email == user.User.Email);
}
if (userDetailFromDb == null)
{
user.CreatedBy = this.UnknownAppUser;
user.CreatedDate = DateTime.UtcNow;
db.UserDetails.Add(user);
}
else
{
user.ID = userDetailFromDb.ID;
var entry = db.Entry(userDetailFromDb);
entry.CurrentValues.SetValues(user);
entry.Property(u => u.CreatedBy).IsModified = false;
entry.Property(u => u.CreatedDate).IsModified = false;
}
db.SaveChanges();
return db.UserDetails.SingleOrDefault(ud => ud.ID == user.ID);
}
}
//public IEnumerable<UserDetail> Get()
//{
// using (var db = new EDEntities())
// {
// var usersInfo = db.UserDetails
//.Include("User")
//.ToList();
// return usersInfo;
// }
//}
public UserDetail Get(int userID)
{
using (var db = new EDEntities())
{
var userInfo = db.UserDetails
.Include("User")
.SingleOrDefault(u => u.UserID == userID);
return userInfo;
}
}
}
}
|
cc0-1.0
|
C#
|
c3951a5d06f560101eec5cafe751844951d1fa39
|
add debug information
|
dinazil/blogsamples,dinazil/blogsamples,dinazil/blogsamples
|
run_time_code_generation/RpcClientGenerator/ClientGenerator.cs
|
run_time_code_generation/RpcClientGenerator/ClientGenerator.cs
|
using System;
using System.CodeDom.Compiler;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Diagnostics;
namespace RpcClientGenerator
{
public static class ClientGenerator
{
public static T GenerateRpcClient<T>(IRpcClient client) where T : class
{
string code = GenerateInterfaceWrapperCode<T>();
var provider = CodeDomProvider.CreateProvider("CSharp");
var parameters = new CompilerParameters()
{
IncludeDebugInformation = true,
//TODO: need a more general way to find the
TempFiles = new TempFileCollection(Path.GetTempPath(), true)
};
parameters.ReferencedAssemblies.Add (typeof(T).Assembly.Location);
var result = provider.CompileAssemblyFromSource (parameters, code);
if (result.Errors.HasErrors)
{
throw new Exception ("Could not compile auto-generated code");
}
var smartClientType = result.CompiledAssembly.GetType ("SmartClient");
return (T)Activator.CreateInstance (smartClientType, new object[] { client }, null);
}
private static string GeneratePrefixCode<T>()
{
string interfaceName = typeof(T).FullName;
var code = GetFormattingString("prefix");
return code.Replace ("{interfaceName}", interfaceName);
}
private static string GenerateMethodCode(MethodInfo method)
{
string returnType = method.ReturnType.FullName;
string methodName = method.Name;
string parameterType = method.GetParameters ().Single ().ParameterType.FullName;
var remoteNameAttribute = (RemoteProcedureNameAttribute)Attribute.GetCustomAttribute (method, typeof(RemoteProcedureNameAttribute));
string remoteMethodName = remoteNameAttribute == null ? method.Name : remoteNameAttribute.Name;
var code = GetFormattingString("method");
code = code.Replace ("{returnType}", returnType);
code = code.Replace ("{methodName}", methodName);
code = code.Replace ("{remoteMethodName}", remoteMethodName);
return code.Replace ("{parameterType}", parameterType);
}
private static string GenerateSuffixCode()
{
return GetFormattingString("suffix");
}
private static string GenerateInterfaceWrapperCode<T>()
{
string start = GeneratePrefixCode<T> ();
string end = GenerateSuffixCode ();
var methodInfos = typeof(T).GetMethods (BindingFlags.Public | BindingFlags.Instance);
string methods = string.Join(Environment.NewLine, methodInfos.Select(GenerateMethodCode));
return $"{start}{Environment.NewLine}{methods}{Environment.NewLine}{end}";
}
private static string GetFormattingString(string resource)
{
var assembly = Assembly.GetExecutingAssembly();
var resourceName = "RpcClientGenerator.Resources." + resource + ".txt";
using (Stream stream = assembly.GetManifestResourceStream(resourceName))
{
using (StreamReader reader = new StreamReader(stream))
{
return reader.ReadToEnd();
}
}
}
}
}
|
using System;
using System.CodeDom.Compiler;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Diagnostics;
namespace RpcClientGenerator
{
public static class ClientGenerator
{
public static T GenerateRpcClient<T> (IRpcClient client) where T : class
{
string code = GenerateInterfaceWrapperCode<T> ();
var provider = CodeDomProvider.CreateProvider("CSharp");
var parameters = new CompilerParameters ();
parameters.ReferencedAssemblies.Add (typeof(T).Assembly.Location);
var result = provider.CompileAssemblyFromSource (parameters, code);
if (result.Errors.HasErrors)
{
throw new Exception ("Could not compile auto-generated code");
}
var smartClientType = result.CompiledAssembly.GetType ("SmartClient");
return (T)Activator.CreateInstance (smartClientType, new object[] { client }, null);
}
private static string GeneratePrefixCode<T>()
{
string interfaceName = typeof(T).FullName;
var code = GetFormattingString("prefix");
return code.Replace ("{interfaceName}", interfaceName);
}
private static string GenerateMethodCode(MethodInfo method)
{
string returnType = method.ReturnType.FullName;
string methodName = method.Name;
string parameterType = method.GetParameters ().Single ().ParameterType.FullName;
var remoteNameAttribute = (RemoteProcedureNameAttribute)Attribute.GetCustomAttribute (method, typeof(RemoteProcedureNameAttribute));
string remoteMethodName = remoteNameAttribute == null ? method.Name : remoteNameAttribute.Name;
var code = GetFormattingString("method");
code = code.Replace ("{returnType}", returnType);
code = code.Replace ("{methodName}", methodName);
code = code.Replace ("{remoteMethodName}", remoteMethodName);
return code.Replace ("{parameterType}", parameterType);
}
private static string GenerateSuffixCode()
{
return GetFormattingString("suffix");
}
private static string GenerateInterfaceWrapperCode<T>()
{
string start = GeneratePrefixCode<T> ();
string end = GenerateSuffixCode ();
var methodInfos = typeof(T).GetMethods (BindingFlags.Public | BindingFlags.Instance);
string methods = string.Join(Environment.NewLine, methodInfos.Select(GenerateMethodCode));
return $"{start}{Environment.NewLine}{methods}{Environment.NewLine}{end}";
}
private static string GetFormattingString(string resource)
{
var assembly = Assembly.GetExecutingAssembly();
var resourceName = "RpcClientGenerator.Resources." + resource + ".txt";
using (Stream stream = assembly.GetManifestResourceStream(resourceName))
{
using (StreamReader reader = new StreamReader(stream))
{
return reader.ReadToEnd();
}
}
}
}
}
|
mit
|
C#
|
eb67a487e411d1a65d6896358fe2222c7f7ada48
|
use a simple test framework
|
carterjones/beaengine-cs,carterjones/beaengine-cs
|
Tests/Program.cs
|
Tests/Program.cs
|
// This is free and unencumbered software released into the public domain.
namespace Tests
{
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using BeaEngineCS;
/// <summary>
/// Tests various functionality of the distorm3cs interface.
/// </summary>
internal class Program
{
/// <summary>
/// Runs the collection of tests of the BeaEngineCS interface.
/// </summary>
/// <param name="args">Command line arguments passed to the program.</param>
public static void Main(string[] args)
{
bool result = true;
bool tmpResult = false;
result &= tmpResult = Program.VersionTest();
Console.WriteLine("VersionTest(): " + (tmpResult ? "Passed" : "Failed"));
result &= tmpResult = Program.RevisionTest();
Console.WriteLine("RevisionTest(): " + (tmpResult ? "Passed" : "Failed"));
result &= tmpResult = Program.DisasmTest();
Console.WriteLine("DisasmTest(): " + (tmpResult ? "Passed" : "Failed"));
Console.WriteLine("--------------------------------------------");
Console.WriteLine("End result: " + (result ? "All passed" : "Not all passed"));
Console.WriteLine();
Console.WriteLine("Press any key to continue.");
Console.ReadKey();
}
/// <summary>
/// Tests the BeaEngineCS.BeaEngineVersion() function.
/// </summary>
/// <returns>Returns true if the test passed.</returns>
private static bool VersionTest()
{
return BeaEngine.Version.Equals("4.1");
}
/// <summary>
/// Tests the BeaEngineCS.BeaEngineRevision() function.
/// </summary>
/// <returns>Returns true if the test passed.</returns>
private static bool RevisionTest()
{
return BeaEngine.Revision.Equals("172");
}
/// <summary>
/// Tests the BeaEngineCS.Disasm() function.
/// </summary>
/// <returns>Returns true if the test passed.</returns>
private static bool DisasmTest()
{
int dataSize = 0x100;
IntPtr data = Marshal.AllocHGlobal(dataSize);
for (int i = 0; i < dataSize; ++i)
{
Marshal.WriteByte(IntPtr.Add(data, i), 0);
}
BeaEngine._Disasm inst = new BeaEngine._Disasm();
inst.EIP = (UIntPtr)data.ToInt64();
int len = BeaEngine.Disasm(ref inst);
if (len == BeaEngine.UnknownOpcode)
{
Console.Error.WriteLine("Unknown opcode.");
return false;
}
else if (len == BeaEngine.OutOfRange)
{
Console.Error.WriteLine("Out of range.");
return false;
}
else
{
return inst.CompleteInstr.Equals("add byte ptr [eax], al");
}
}
}
}
|
// This is free and unencumbered software released into the public domain.
namespace Tests
{
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Runtime.InteropServices;
using BeaEngineCS;
class Program
{
static void Main(string[] args)
{
int dataSize = 0x1000;
IntPtr data = Marshal.AllocHGlobal(dataSize);
for (int i = 0; i < dataSize; ++i)
{
Marshal.WriteByte(IntPtr.Add(data, i), 0);
}
BeaEngine._Disasm inst = new BeaEngine._Disasm();
inst.EIP = (UIntPtr)data.ToInt64();
int len = BeaEngine.Disasm(ref inst);
if (len == BeaEngine.UnknownOpcode)
{
Console.Error.WriteLine("Unknown opcode.");
}
else if (len == BeaEngine.OutOfRange)
{
Console.Error.WriteLine("Out of range.");
}
else
{
Console.WriteLine(inst.CompleteInstr);
}
}
}
}
|
bsd-2-clause
|
C#
|
bfddb3d8a351c4d9c1195e9023b246e0fd604e8d
|
Fix FPS and update FPS display
|
litsungyi/Camus
|
Utilities/FPS.cs
|
Utilities/FPS.cs
|
using System.Collections.Generic;
using UnityEngine;
namespace Camus.Utilities
{
public class FPS : MonoBehaviour
{
private static readonly int MaxCount = 100;
[SerializeField] private float frames = 0f;
private Queue<float> deltas = new Queue<float>();
private void Update()
{
var delta = Time.deltaTime;
deltas.Enqueue(delta);
if (deltas.Count > MaxCount)
{
deltas.Dequeue();
}
var total = 0f;
foreach (var item in deltas)
{
total += item;
}
var average = deltas.Count == 0 ? 0 : total / deltas.Count;
frames = average <= 0 ? 0 : 1f / average;
}
#if UNITY_EDITOR
private void OnGUI()
{
var style = new GUIStyle(GUI.skin.label);
style.normal.textColor = GetColor();
style.fontSize = 16;
style.alignment = TextAnchor.MiddleRight;
var rect = new Rect(new Vector2(Screen.width - 110, 10), new Vector2(100, 20));
UnityEditor.EditorGUI.LabelField(rect, string.Format("FPS: {0:00.0}", frames), style);
}
private Color GetColor()
{
if (frames >= 60f)
{
return Color.green;
}
else if (frames >= 30f)
{
return Color.blue;
}
else if (frames >= 10f)
{
return Color.yellow;
}
else
{
return Color.red;
}
}
#endif
}
}
|
using System.Collections.Generic;
using UnityEngine;
namespace Camus.Utilities
{
public class FPS : MonoBehaviour
{
private static readonly int MaxCount = 100;
[SerializeField] private int count = 0;
[SerializeField] private float frames = 0f;
private Queue<float> deltas = new Queue<float>();
private void Update()
{
var delta = Time.deltaTime;
++count;
deltas.Enqueue(delta);
if (deltas.Count > MaxCount)
{
deltas.Dequeue();
count = MaxCount;
}
var total = 0f;
foreach (var item in deltas)
{
total += item;
}
var average = count == -1 ? 0 : total / count;
frames = average <= 0 ? 0 : 1f / average;
}
#if UNITY_EDITOR
private void OnGUI()
{
UnityEditor.EditorGUILayout.LabelField(string.Format("FPS: {0:00.0}", frames));
}
#endif
}
}
|
mit
|
C#
|
f175badf0919cf79b01c9ae8373df986f326b778
|
Address review comments
|
dotnet/roslyn,bartdesmet/roslyn,sharwell/roslyn,jasonmalinowski/roslyn,KevinRansom/roslyn,shyamnamboodiripad/roslyn,jasonmalinowski/roslyn,eriawan/roslyn,eriawan/roslyn,diryboy/roslyn,bartdesmet/roslyn,mavasani/roslyn,weltkante/roslyn,CyrusNajmabadi/roslyn,shyamnamboodiripad/roslyn,jasonmalinowski/roslyn,KevinRansom/roslyn,diryboy/roslyn,eriawan/roslyn,mavasani/roslyn,sharwell/roslyn,dotnet/roslyn,shyamnamboodiripad/roslyn,weltkante/roslyn,diryboy/roslyn,weltkante/roslyn,sharwell/roslyn,CyrusNajmabadi/roslyn,mavasani/roslyn,KevinRansom/roslyn,dotnet/roslyn,CyrusNajmabadi/roslyn,bartdesmet/roslyn
|
src/Workspaces/Remote/ServiceHub/Host/RemoteAnalyzerAssemblyLoaderService.cs
|
src/Workspaces/Remote/ServiceHub/Host/RemoteAnalyzerAssemblyLoaderService.cs
|
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Composition;
using System.Diagnostics;
using System.IO;
using System.Reflection;
using Microsoft.CodeAnalysis.Host;
using Microsoft.CodeAnalysis.Host.Mef;
namespace Microsoft.CodeAnalysis.Remote.Diagnostics
{
/// <summary>
/// Customizes the path where to store shadow-copies of analyzer assemblies.
/// </summary>
[ExportWorkspaceService(typeof(IAnalyzerAssemblyLoaderProvider), WorkspaceKind.RemoteWorkspace), Shared]
internal sealed class RemoteAnalyzerAssemblyLoaderService : IAnalyzerAssemblyLoaderProvider
{
private readonly RemoteAnalyzerAssemblyLoader _loader;
private readonly ShadowCopyAnalyzerAssemblyLoader _shadowCopyLoader;
[ImportingConstructor]
[Obsolete(MefConstruction.ImportingConstructorMessage, error: true)]
public RemoteAnalyzerAssemblyLoaderService()
{
var baseDirectory = Path.GetDirectoryName(Path.GetFullPath(typeof(RemoteAnalyzerAssemblyLoader).GetTypeInfo().Assembly.Location));
Debug.Assert(baseDirectory != null);
_loader = new(baseDirectory);
_shadowCopyLoader = new(Path.Combine(Path.GetTempPath(), "VS", "AnalyzerAssemblyLoader"));
}
public IAnalyzerAssemblyLoader GetLoader(in AnalyzerAssemblyLoaderOptions options)
=> options.ShadowCopy ? _shadowCopyLoader : _loader;
// For analyzers shipped in Roslyn, different set of assemblies might be used when running
// in-proc and OOP e.g. in-proc (VS) running on desktop clr and OOP running on ServiceHub .Net6
// host. We need to make sure to use the ones from the same location as the remote.
private class RemoteAnalyzerAssemblyLoader : DefaultAnalyzerAssemblyLoader
{
private readonly string _baseDirectory;
protected override Assembly LoadImpl(string fullPath)
=> base.LoadImpl(FixPath(fullPath));
public RemoteAnalyzerAssemblyLoader(string baseDirectory)
{
_baseDirectory = baseDirectory;
}
private string FixPath(string fullPath)
{
var fixedPath = Path.GetFullPath(Path.Combine(_baseDirectory, Path.GetFileName(fullPath)));
return File.Exists(fixedPath) ? fixedPath : fullPath;
}
}
}
}
|
// 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.Composition;
using System.IO;
using System.Reflection;
using Microsoft.CodeAnalysis.Host;
using Microsoft.CodeAnalysis.Host.Mef;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.Remote.Diagnostics
{
/// <summary>
/// Customizes the path where to store shadow-copies of analyzer assemblies.
/// </summary>
[ExportWorkspaceService(typeof(IAnalyzerAssemblyLoaderProvider), WorkspaceKind.RemoteWorkspace), Shared]
internal sealed class RemoteAnalyzerAssemblyLoaderService : IAnalyzerAssemblyLoaderProvider
{
private readonly RemoteAnalyzerAssemblyLoader _loader;
private readonly ShadowCopyAnalyzerAssemblyLoader _shadowCopyLoader;
[ImportingConstructor]
[Obsolete(MefConstruction.ImportingConstructorMessage, error: true)]
public RemoteAnalyzerAssemblyLoaderService()
{
_loader = new(Path.GetDirectoryName(Path.GetFullPath(typeof(RemoteAnalyzerAssemblyLoader).GetTypeInfo().Assembly.Location)));
_shadowCopyLoader = new(Path.Combine(Path.GetTempPath(), "VS", "AnalyzerAssemblyLoader"));
}
public IAnalyzerAssemblyLoader GetLoader(in AnalyzerAssemblyLoaderOptions options)
=> options.ShadowCopy ? _shadowCopyLoader : _loader;
// For analyzers shipped in Roslyn, different set of assemblies might be used when running
// in-proc and OOP e.g. in-proc (VS) running on desktop clr and OOP running on ServiceHub .Net6
// host. We need to make sure to use the right one for OOP.
private class RemoteAnalyzerAssemblyLoader : DefaultAnalyzerAssemblyLoader
{
private readonly string? _baseDirectory;
protected override Assembly LoadImpl(string fullPath)
=> base.LoadImpl(FixPath(fullPath));
public RemoteAnalyzerAssemblyLoader(string? baseDirectory)
{
_baseDirectory = baseDirectory;
}
private string FixPath(string fullPath)
{
if (_baseDirectory == null)
{
return fullPath;
}
var assemblyName = Path.GetFileName(fullPath);
var fixedPath = Path.GetFullPath(Path.Combine(_baseDirectory, assemblyName));
if (!PathUtilities.PathsEqual(fixedPath, Path.GetFullPath(fullPath)) && File.Exists(fixedPath))
{
return fixedPath;
}
return fullPath;
}
}
}
}
|
mit
|
C#
|
a9cf0a9baae6fc677e6e34ae29690db3e059230a
|
Tidy up test class
|
JoeMighty/shouldly
|
src/Shouldly.Tests/ShouldThrow/FuncOfTaskWhichThrowsDirectlyScenario.cs
|
src/Shouldly.Tests/ShouldThrow/FuncOfTaskWhichThrowsDirectlyScenario.cs
|
using System;
using System.Threading.Tasks;
using Xunit;
namespace Shouldly.Tests.ShouldThrow
{
public class FuncOfTaskWhichThrowsDirectlyScenario
{
[Fact]
public void ShouldPass()
{
// ReSharper disable once RedundantDelegateCreation
var task = new Func<Task>(() => { throw new InvalidOperationException(); });
task.ShouldThrow<InvalidOperationException>();
}
[Fact]
public void ShouldPass_ExceptionTypePassedIn()
{
// ReSharper disable once RedundantDelegateCreation
var task = new Func<Task>(() => { throw new InvalidOperationException(); });
task.ShouldThrow(typeof(InvalidOperationException));
}
[Fact]
public void ShouldPassTimeoutException()
{
var task = new Func<Task>(() => { throw new TimeoutException(); });
task.ShouldThrow<TimeoutException>();
}
[Fact]
public void ShouldPassTimeoutException_ExceptionTypePassedIn()
{
var task = new Func<Task>(() => { throw new TimeoutException(); });
task.ShouldThrow(typeof(TimeoutException));
}
[Fact]
public void ShouldPassTimeoutExceptionAsync()
{
var task = new Func<Task>(async () => { throw new TimeoutException(); });
task.ShouldThrow<TimeoutException>();
}
[Fact]
public void ShouldPassTimeoutExceptionAsync_ExceptionTypePassedIn()
{
var task = new Func<Task>(async () => { throw new TimeoutException(); });
task.ShouldThrow(typeof(TimeoutException));
}
}
}
|
using System;
using System.Threading.Tasks;
using Xunit;
namespace Shouldly.Tests.ShouldThrow
{
public class FuncOfTaskWhichThrowsDirectlyScenario
{
[Fact]
public void ShouldPass()
{
// ReSharper disable once RedundantDelegateCreation
var task = new Func<Task>(() => { throw new InvalidOperationException(); });
task.ShouldThrow<InvalidOperationException>();
}
[Fact]
public void ShouldPass_ExceptionTypePassedIn()
{
// ReSharper disable once RedundantDelegateCreation
var task = new Func<Task>(() => { throw new InvalidOperationException(); });
task.ShouldThrow(typeof(InvalidOperationException));
}
[Fact]
public void ShouldPassTimeoutException()
{
var task = new Func<Task>(() => { throw new TimeoutException(); });
task.ShouldThrow<TimeoutException>();
}
[Fact]
public void ShouldPassTimeoutException_ExceptionTypePassedIn()
{
var task = new Func<Task>(() => { throw new TimeoutException(); });
task.ShouldThrow(typeof(TimeoutException));
}
[Fact]
public void ShouldPassTimeoutExceptionAsync()
{
var task = new Func<Task>(async () => { throw new TimeoutException(); });
task.ShouldThrow<TimeoutException>();
}
[Fact]
public void ShouldPassTimeoutExceptionAsync_ExceptionTypePassedIn()
{
var task = new Func<Task>(async () => { throw new TimeoutException(); });
task.ShouldThrow(typeof(TimeoutException));
}
}
}
|
bsd-3-clause
|
C#
|
633c9fa529b55f8013097eaec774aca964ea3b6d
|
Change bulk op.
|
danielwertheim/mycouch,danielwertheim/mycouch
|
src/Tests/MyCouch.IntegrationTests/TestFixtures/ViewsFixture.cs
|
src/Tests/MyCouch.IntegrationTests/TestFixtures/ViewsFixture.cs
|
using System;
using System.Linq;
using MyCouch.Commands;
using MyCouch.Querying;
using MyCouch.Testing;
using MyCouch.Testing.Model;
namespace MyCouch.IntegrationTests.TestFixtures
{
public class ViewsFixture : IDisposable
{
private IClient _client;
public Artist[] Artists { get; protected set; }
public ViewsFixture()
{
Artists = ClientTestData.Artists.CreateArtists(10);
_client = IntegrationTestsRuntime.CreateClient();
var bulk = new BulkCommand();
bulk.Include(Artists.Select(i => _client.Entities.Serializer.Serialize(i)).ToArray());
var bulkResponse = _client.Documents.BulkAsync(bulk).Result;
foreach (var row in bulkResponse.Rows)
{
var artist = Artists.Single(i => i.ArtistId == row.Id);
_client.Entities.Reflector.RevMember.SetValueTo(artist, row.Rev);
}
_client.Documents.PostAsync(ClientTestData.Views.Artists).Wait();
var touchView1 = new ViewQuery(ClientTestData.Views.ArtistsAlbumsViewId).Configure(q => q.Stale(Stale.UpdateAfter));
var touchView2 = new ViewQuery(ClientTestData.Views.ArtistsNameNoValueViewId).Configure(q => q.Stale(Stale.UpdateAfter));
_client.Views.RunQueryAsync(touchView1).Wait();
_client.Views.RunQueryAsync(touchView2).Wait();
}
public virtual void Dispose()
{
_client.ClearAllDocuments();
_client.Dispose();
_client = null;
}
}
}
|
using System;
using System.Linq;
using MyCouch.Commands;
using MyCouch.Querying;
using MyCouch.Testing;
using MyCouch.Testing.Model;
namespace MyCouch.IntegrationTests.TestFixtures
{
public class ViewsFixture : IDisposable
{
private IClient _client;
public Artist[] Artists { get; protected set; }
public ViewsFixture()
{
Artists = ClientTestData.Artists.CreateArtists(10);
_client = IntegrationTestsRuntime.CreateClient();
var bulk = new BulkCommand();
bulk.Include(Artists.Select(i => _client.Entities.Serializer.Serialize(i)).ToArray());
var bulkResponse = _client.Documents.BulkAsync(bulk);
foreach (var row in bulkResponse.Result.Rows)
{
var artist = Artists.Single(i => i.ArtistId == row.Id);
_client.Entities.Reflector.RevMember.SetValueTo(artist, row.Rev);
}
_client.Documents.PostAsync(ClientTestData.Views.Artists).Wait();
var touchView1 = new ViewQuery(ClientTestData.Views.ArtistsAlbumsViewId).Configure(q => q.Stale(Stale.UpdateAfter));
var touchView2 = new ViewQuery(ClientTestData.Views.ArtistsNameNoValueViewId).Configure(q => q.Stale(Stale.UpdateAfter));
_client.Views.RunQueryAsync(touchView1).Wait();
_client.Views.RunQueryAsync(touchView2).Wait();
}
public virtual void Dispose()
{
_client.ClearAllDocuments();
_client.Dispose();
_client = null;
}
}
}
|
mit
|
C#
|
e6ba2f9195dd10f9c1cdce5864dd7129512ee817
|
Fix a bench
|
alexandrnikitin/MakingIntParseFaster.NET
|
MakingIntParseFaster/IntParseBenchmarks.cs
|
MakingIntParseFaster/IntParseBenchmarks.cs
|
using BenchmarkDotNet.Attributes;
namespace MakingIntParseFaster
{
[Config(typeof(Config))]
public class IntParseBenchmarks
{
[Benchmark]
public int OneDigit()
{
return int.Parse("1");
}
[Benchmark]
public int MaxValue()
{
return int.Parse("2147483647");
}
[Benchmark]
public int Sign()
{
return int.Parse("-2147483648");
}
[Benchmark]
public int Whitespaces()
{
return int.Parse(" -2147483648 ");
}
[Benchmark]
public int FasterOneDigit()
{
return FasterInt.Parse("1");
}
[Benchmark]
public int FasterMaxValue()
{
return FasterInt.Parse("2147483647");
}
[Benchmark]
public int FasterSign()
{
return FasterInt.Parse("-2147483648");
}
[Benchmark]
public int FasterWhitespaces()
{
return FasterInt.Parse(" -2147483648 ");
}
}
}
|
using BenchmarkDotNet.Attributes;
namespace MakingIntParseFaster
{
[Config(typeof(Config))]
public class IntParseBenchmarks
{
[Benchmark]
public int OneDigit()
{
return int.Parse("1");
}
[Benchmark]
public int MaxValue()
{
return int.Parse("2147483647");
}
[Benchmark]
public int Sign()
{
return int.Parse("-2147483648");
}
[Benchmark]
public int Whitespaces()
{
return int.Parse(" -2147483648 ");
}
[Benchmark]
public int FasterOneDigit()
{
return FasterInt.Parse("1");
}
[Benchmark]
public int FasterMaxValue()
{
return FasterInt.Parse("2147483647");
}
[Benchmark]
public int FasterSign()
{
return FasterInt.Parse("-2147483648");
}
[Benchmark]
public int FasterWhitespaces()
{
return int.Parse(" -2147483648 ");
}
}
}
|
mit
|
C#
|
84693beca8b31be50bb6e568452a88d643cef580
|
Test fixed
|
pushrbx/squidex,Squidex/squidex,pushrbx/squidex,pushrbx/squidex,pushrbx/squidex,Squidex/squidex,pushrbx/squidex,Squidex/squidex,Squidex/squidex,Squidex/squidex
|
tests/Squidex.Domain.Apps.Core.Tests/Apps/RoleExtensionTests.cs
|
tests/Squidex.Domain.Apps.Core.Tests/Apps/RoleExtensionTests.cs
|
// ==========================================================================
// RoleExtensionTests.cs
// Squidex Headless CMS
// ==========================================================================
// Copyright (c) Squidex Group
// All rights reserved.
// ==========================================================================
using System;
using Xunit;
namespace Squidex.Domain.Apps.Core.Apps
{
public class RoleExtensionTests
{
[Fact]
public void Should_convert_from_client_permission_to_app_permission()
{
Assert.Equal(AppPermission.Developer, AppClientPermission.Developer.ToAppPermission());
Assert.Equal(AppPermission.Editor, AppClientPermission.Editor.ToAppPermission());
Assert.Equal(AppPermission.Reader, AppClientPermission.Reader.ToAppPermission());
}
[Fact]
public void Should_throw_when_converting_from_invalid_client_permission()
{
Assert.Throws<ArgumentException>(() => ((AppClientPermission)10).ToAppPermission());
}
[Fact]
public void Should_convert_from_contributor_permission_to_app_permission()
{
Assert.Equal(AppPermission.Developer, AppContributorPermission.Developer.ToAppPermission());
Assert.Equal(AppPermission.Editor, AppContributorPermission.Editor.ToAppPermission());
Assert.Equal(AppPermission.Owner, AppContributorPermission.Owner.ToAppPermission());
}
[Fact]
public void Should_throw_when_converting_from_invalid_contributor_permission()
{
Assert.Throws<ArgumentException>(() => ((AppContributorPermission)10).ToAppPermission());
}
}
}
|
// ==========================================================================
// RoleExtensionTests.cs
// Squidex Headless CMS
// ==========================================================================
// Copyright (c) Squidex Group
// All rights reserved.
// ==========================================================================
using System;
using Xunit;
namespace Squidex.Domain.Apps.Core.Apps
{
public class RoleExtensionTests
{
[Fact]
public void Should_convert_from_client_permission_to_app_permission()
{
Assert.Equal(AppPermission.Developer, AppClientPermission.Developer.ToAppPermission());
Assert.Equal(AppPermission.Editor, AppClientPermission.Editor.ToAppPermission());
Assert.Equal(AppPermission.Reader, AppClientPermission.Reader.ToAppPermission());
}
[Fact]
public void Should_throw_when_converting_from_invalid_client_permission()
{
Assert.Throws<ArgumentException>(() => ((AppClientPermission)10).ToAppPermission());
}
[Fact]
public void Should_convert_from_contributor_permission_to_app_permission()
{
Assert.Equal(AppPermission.Developer, AppContributorPermission.Developer.ToAppPermission());
Assert.Equal(AppPermission.Editor, AppContributorPermission.Editor.ToAppPermission());
Assert.Equal(AppPermission.Owner, AppContributorPermission.Owner.ToAppPermission());
}
[Fact]
public void Should_throw_when_converting_from_invalid_contributor_permission()
{
Assert.Throws<ArgumentException>(() => ((AppContributorPermission) 10).ToAppPermission());
}
}
}
|
mit
|
C#
|
a782904b23ba42cf19a84a83e5e5d9c2560d48e1
|
Make the MVC content verification test explicitly pass the framework
|
mlorbetske/templating,mlorbetske/templating,seancpeters/templating,seancpeters/templating,seancpeters/templating,seancpeters/templating
|
test/Microsoft.TemplateEngine.Cli.UnitTests/PrecedenceSelectionTests.cs
|
test/Microsoft.TemplateEngine.Cli.UnitTests/PrecedenceSelectionTests.cs
|
using Xunit;
namespace Microsoft.TemplateEngine.Cli.UnitTests
{
public class PrecedenceSelectionTests : EndToEndTestBase
{
[Theory(DisplayName = nameof(VerifyTemplateContent))]
[InlineData("mvc -f netcoreapp2.0", "MvcNoAuthTest.json", "MvcFramework20Test.json")]
[InlineData("mvc -au individual -f netcoreapp2.0", "MvcIndAuthTest.json", "MvcFramework20Test.json")]
[InlineData("mvc -f netcoreapp1.0", "MvcNoAuthTest.json", "MvcFramework10Test.json")]
[InlineData("mvc -au individual -f netcoreapp1.0", "MvcIndAuthTest.json", "MvcFramework10Test.json")]
[InlineData("mvc -f netcoreapp1.1", "MvcNoAuthTest.json", "MvcFramework11Test.json")]
[InlineData("mvc -au individual -f netcoreapp1.1", "MvcIndAuthTest.json", "MvcFramework11Test.json")]
[InlineData("mvc -f netcoreapp2.0", "MvcNoAuthTest.json", "MvcFramework20Test.json")]
[InlineData("mvc -au individual -f netcoreapp2.0", "MvcIndAuthTest.json", "MvcFramework20Test.json")]
public void VerifyTemplateContent(string args, params string[] scripts)
{
Run(args, scripts);
}
}
}
|
using Xunit;
namespace Microsoft.TemplateEngine.Cli.UnitTests
{
public class PrecedenceSelectionTests : EndToEndTestBase
{
[Theory(DisplayName = nameof(VerifyTemplateContent))]
[InlineData("mvc", "MvcNoAuthTest.json", "MvcFramework20Test.json")]
[InlineData("mvc -au individual", "MvcIndAuthTest.json", "MvcFramework20Test.json")]
[InlineData("mvc -f netcoreapp1.0", "MvcNoAuthTest.json", "MvcFramework10Test.json")]
[InlineData("mvc -au individual -f netcoreapp1.0", "MvcIndAuthTest.json", "MvcFramework10Test.json")]
[InlineData("mvc -f netcoreapp1.1", "MvcNoAuthTest.json", "MvcFramework11Test.json")]
[InlineData("mvc -au individual -f netcoreapp1.1", "MvcIndAuthTest.json", "MvcFramework11Test.json")]
[InlineData("mvc -f netcoreapp2.0", "MvcNoAuthTest.json", "MvcFramework20Test.json")]
[InlineData("mvc -au individual -f netcoreapp2.0", "MvcIndAuthTest.json", "MvcFramework20Test.json")]
public void VerifyTemplateContent(string args, params string[] scripts)
{
Run(args, scripts);
}
}
}
|
mit
|
C#
|
aa382780d58c53ef5a0ede492f9b668eeaa3b9e7
|
Remove more unused commented code
|
Microsoft/nodejstools,Microsoft/nodejstools,Microsoft/nodejstools,Microsoft/nodejstools,Microsoft/nodejstools
|
Nodejs/Product/ProjectWizard/NodejsPackageParametersExtension.cs
|
Nodejs/Product/ProjectWizard/NodejsPackageParametersExtension.cs
|
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text.RegularExpressions;
using EnvDTE;
using Microsoft.VisualStudio.Shell.Interop;
using Microsoft.VisualStudio.TemplateWizard;
namespace Microsoft.NodejsTools.ProjectWizard
{
internal class NodejsPackageParametersExtension : IWizard
{
public void RunStarted(object automationObject, Dictionary<string, string> replacementsDictionary, WizardRunKind runKind, object[] customParams)
{
var projectName = replacementsDictionary["$projectname$"];
replacementsDictionary.Add("$npmsafeprojectname$", NormalizeNpmPackageName(projectName));
}
public void ProjectFinishedGenerating(EnvDTE.Project project)
{
return;
}
public void ProjectItemFinishedGenerating(ProjectItem projectItem)
{
return;
}
public bool ShouldAddProjectItem(string filePath)
{
return true;
}
public void BeforeOpeningFile(ProjectItem projectItem)
{
return;
}
public void RunFinished()
{
return;
}
private const int NpmPackageNameMaxLength = 214;
/// <summary>
/// Normalize a project name to be a valid Npm package name: https://docs.npmjs.com/files/package.json#name
/// </summary>
/// <param name="projectName">Name of a VS project.</param>
private static string NormalizeNpmPackageName(string projectName)
{
// Remove all leading url-invalid, underscore, and period characters
var npmProjectNameTransform = Regex.Replace(projectName, "^[^a-zA-Z0-9-~]*", string.Empty);
// Replace all invalid characters with a dash
npmProjectNameTransform = Regex.Replace(npmProjectNameTransform, "[^a-zA-Z0-9-_~.]", "-");
// Insert hyphens between camelcased sections.
npmProjectNameTransform = Regex.Replace(npmProjectNameTransform, "([a-z0-9])([A-Z])", "$1-$2").ToLowerInvariant();
return npmProjectNameTransform.Substring(0, Math.Min(npmProjectNameTransform.Length, NpmPackageNameMaxLength));
}
}
}
|
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text.RegularExpressions;
using EnvDTE;
using Microsoft.VisualStudio.Shell.Interop;
using Microsoft.VisualStudio.TemplateWizard;
namespace Microsoft.NodejsTools.ProjectWizard
{
internal class NodejsPackageParametersExtension : IWizard
{
//private const string tsSdkSetupPackageIdPrefix = "Microsoft.VisualStudio.Component.TypeScript.";
public void RunStarted(object automationObject, Dictionary<string, string> replacementsDictionary, WizardRunKind runKind, object[] customParams)
{
var projectName = replacementsDictionary["$projectname$"];
replacementsDictionary.Add("$npmsafeprojectname$", NormalizeNpmPackageName(projectName));
}
public void ProjectFinishedGenerating(EnvDTE.Project project)
{
return;
}
public void ProjectItemFinishedGenerating(ProjectItem projectItem)
{
return;
}
public bool ShouldAddProjectItem(string filePath)
{
return true;
}
public void BeforeOpeningFile(ProjectItem projectItem)
{
return;
}
public void RunFinished()
{
return;
}
private const int NpmPackageNameMaxLength = 214;
/// <summary>
/// Normalize a project name to be a valid Npm package name: https://docs.npmjs.com/files/package.json#name
/// </summary>
/// <param name="projectName">Name of a VS project.</param>
private static string NormalizeNpmPackageName(string projectName)
{
// Remove all leading url-invalid, underscore, and period characters
var npmProjectNameTransform = Regex.Replace(projectName, "^[^a-zA-Z0-9-~]*", string.Empty);
// Replace all invalid characters with a dash
npmProjectNameTransform = Regex.Replace(npmProjectNameTransform, "[^a-zA-Z0-9-_~.]", "-");
// Insert hyphens between camelcased sections.
npmProjectNameTransform = Regex.Replace(npmProjectNameTransform, "([a-z0-9])([A-Z])", "$1-$2").ToLowerInvariant();
return npmProjectNameTransform.Substring(0, Math.Min(npmProjectNameTransform.Length, NpmPackageNameMaxLength));
}
}
}
|
apache-2.0
|
C#
|
a9be48e0d3d8c2664e12d45a9dcefcbda9748401
|
Mark unused property obsolete
|
hildabarbara/PnP,markcandelora/PnP,PaoloPia/PnP,bstenberg64/PnP,selossej/PnP,zrahui/PnP,PaoloPia/PnP,durayakar/PnP,brennaman/PnP,Anil-Lakhagoudar/PnP,narval32/Shp,jlsfernandez/PnP,perolof/PnP,biste5/PnP,sjuppuh/PnP,edrohler/PnP,rgueldenpfennig/PnP,sandhyagaddipati/PnPSamples,pdfshareforms/PnP,r0ddney/PnP,spdavid/PnP,rbarten/PnP,8v060htwyc/PnP,OfficeDev/PnP,vman/PnP,patrick-rodgers/PnP,OfficeDev/PnP,dalehhirt/PnP,timothydonato/PnP,narval32/Shp,OneBitSoftware/PnP,worksofwisdom/PnP,vnathalye/PnP,MaurizioPz/PnP,OneBitSoftware/PnP,mauricionr/PnP,darei-fr/PnP,OzMakka/PnP,lamills1/PnP,bstenberg64/PnP,spdavid/PnP,lamills1/PnP,ebbypeter/PnP,werocool/PnP,OfficeDev/PnP,vman/PnP,PaoloPia/PnP,hildabarbara/PnP,JBeerens/PnP,sndkr/PnP,joaopcoliveira/PnP,svarukala/PnP,nishantpunetha/PnP,NexploreDev/PnP-PowerShell,briankinsella/PnP,joaopcoliveira/PnP,gavinbarron/PnP,OzMakka/PnP,JBeerens/PnP,MaurizioPz/PnP,valt83/PnP,OzMakka/PnP,jlsfernandez/PnP,yagoto/PnP,NexploreDev/PnP-PowerShell,Rick-Kirkham/PnP,werocool/PnP,NavaneethaDev/PnP,svarukala/PnP,ebbypeter/PnP,patrick-rodgers/PnP,NavaneethaDev/PnP,gautekramvik/PnP,timschoch/PnP,timothydonato/PnP,nishantpunetha/PnP,jeroenvanlieshout/PnP,rbarten/PnP,JBeerens/PnP,Claire-Hindhaugh/PnP,vnathalye/PnP,SteenMolberg/PnP,brennaman/PnP,andreasblueher/PnP,Chowdarysandhya/PnPTest,tomvr2610/PnP,RickVanRousselt/PnP,yagoto/PnP,weshackett/PnP,GSoft-SharePoint/PnP,IDTimlin/PnP,dalehhirt/PnP,rroman81/PnP,mauricionr/PnP,comblox/PnP,chrisobriensp/PnP,RickVanRousselt/PnP,tomvr2610/PnP,erwinvanhunen/PnP,durayakar/PnP,rgueldenpfennig/PnP,patrick-rodgers/PnP,aammiitt2/PnP,JilleFloridor/PnP,8v060htwyc/PnP,MaurizioPz/PnP,rroman81/PnP,baldswede/PnP,Anil-Lakhagoudar/PnP,srirams007/PnP,sndkr/PnP,svarukala/PnP,erwinvanhunen/PnP,biste5/PnP,lamills1/PnP,SimonDoy/PnP,gautekramvik/PnP,r0ddney/PnP,darei-fr/PnP,IvanTheBearable/PnP,comblox/PnP,darei-fr/PnP,BartSnyckers/PnP,GSoft-SharePoint/PnP,dalehhirt/PnP,worksofwisdom/PnP,timothydonato/PnP,sandhyagaddipati/PnPSamples,bstenberg64/PnP,afsandeberg/PnP,gavinbarron/PnP,afsandeberg/PnP,briankinsella/PnP,OneBitSoftware/PnP,rgueldenpfennig/PnP,valt83/PnP,PieterVeenstra/PnP,rroman81/PnP,andreasblueher/PnP,NexploreDev/PnP-PowerShell,yagoto/PnP,valt83/PnP,russgove/PnP,machadosantos/PnP,comblox/PnP,russgove/PnP,aammiitt2/PnP,NavaneethaDev/PnP,erwinvanhunen/PnP,sjuppuh/PnP,yagoto/PnP,edrohler/PnP,perolof/PnP,worksofwisdom/PnP,PieterVeenstra/PnP,mauricionr/PnP,JilleFloridor/PnP,SuryaArup/PnP,hildabarbara/PnP,baldswede/PnP,ebbypeter/PnP,OneBitSoftware/PnP,sjuppuh/PnP,rbarten/PnP,IDTimlin/PnP,machadosantos/PnP,jeroenvanlieshout/PnP,sndkr/PnP,sandhyagaddipati/PnPSamples,vnathalye/PnP,edrohler/PnP,narval32/Shp,pdfshareforms/PnP,jlsfernandez/PnP,perolof/PnP,werocool/PnP,machadosantos/PnP,aammiitt2/PnP,rahulsuryawanshi/PnP,gavinbarron/PnP,srirams007/PnP,pascalberger/PnP,PieterVeenstra/PnP,vman/PnP,GSoft-SharePoint/PnP,BartSnyckers/PnP,weshackett/PnP,rahulsuryawanshi/PnP,Rick-Kirkham/PnP,nishantpunetha/PnP,zrahui/PnP,timschoch/PnP,SuryaArup/PnP,8v060htwyc/PnP,Chowdarysandhya/PnPTest,pascalberger/PnP,Claire-Hindhaugh/PnP,selossej/PnP,Rick-Kirkham/PnP,IvanTheBearable/PnP,SteenMolberg/PnP,SimonDoy/PnP,pdfshareforms/PnP,PaoloPia/PnP,SteenMolberg/PnP,JilleFloridor/PnP,zrahui/PnP,BartSnyckers/PnP,selossej/PnP,8v060htwyc/PnP,markcandelora/PnP,bhoeijmakers/PnP,srirams007/PnP,durayakar/PnP,andreasblueher/PnP,jeroenvanlieshout/PnP,r0ddney/PnP,briankinsella/PnP,weshackett/PnP,baldswede/PnP,joaopcoliveira/PnP,RickVanRousselt/PnP,chrisobriensp/PnP,brennaman/PnP,Chowdarysandhya/PnPTest,spdavid/PnP,SimonDoy/PnP,bhoeijmakers/PnP,russgove/PnP,biste5/PnP,SuryaArup/PnP,timschoch/PnP,Claire-Hindhaugh/PnP,gautekramvik/PnP,markcandelora/PnP,tomvr2610/PnP,afsandeberg/PnP,chrisobriensp/PnP,OfficeDev/PnP,Anil-Lakhagoudar/PnP,bhoeijmakers/PnP,pascalberger/PnP,IDTimlin/PnP,IvanTheBearable/PnP,rahulsuryawanshi/PnP
|
Solutions/PowerShell.Commands/HelpAttributes/CmdletHelpAttribute.cs
|
Solutions/PowerShell.Commands/HelpAttributes/CmdletHelpAttribute.cs
|
using System;
namespace OfficeDevPnP.PowerShell.CmdletHelpAttributes
{
[AttributeUsage(AttributeTargets.Class,
AllowMultiple = false)]
public sealed class CmdletHelpAttribute : Attribute
{
readonly string description;
[Obsolete("Is not used. Use DetailedDescription instead.")]
public string Details { get; set; }
public string DetailedDescription { get; set; }
public string Copyright { get; set; }
public string Version { get; set; }
public string Category { get; set; }
public CmdletHelpAttribute(string description)
{
this.description = description;
}
public string Description
{
get
{
return description;
}
}
}
}
|
using System;
namespace OfficeDevPnP.PowerShell.CmdletHelpAttributes
{
[AttributeUsage(AttributeTargets.Class,
AllowMultiple = false)]
public sealed class CmdletHelpAttribute : Attribute
{
readonly string description;
public string Details { get; set; }
public string DetailedDescription { get; set; }
public string Copyright { get; set; }
public string Version { get; set; }
public string Category { get; set; }
public CmdletHelpAttribute(string description)
{
this.description = description;
}
public string Description
{
get
{
return description;
}
}
}
}
|
mit
|
C#
|
9965652c47a319023204b39665a088d8fc46fcab
|
Switch Deconstruct Request reach check to not use player transform position.
|
Necromunger/unitystation,Necromunger/unitystation,Necromunger/unitystation,krille90/unitystation,Necromunger/unitystation,krille90/unitystation,fomalsd/unitystation,fomalsd/unitystation,Necromunger/unitystation,fomalsd/unitystation,fomalsd/unitystation,krille90/unitystation,Necromunger/unitystation,fomalsd/unitystation,fomalsd/unitystation,fomalsd/unitystation
|
UnityProject/Assets/Scripts/Construction/Managers/Deconstruction.cs
|
UnityProject/Assets/Scripts/Construction/Managers/Deconstruction.cs
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Deconstruction : MonoBehaviour
{
public GameObject wallGirderPrefab;
public GameObject metalPrefab;
//Server only:
public void TryTileDeconstruct(TileChangeManager tileChangeManager, TileType tileType, Vector3 cellPos, Vector3 worldPos)
{
var cellPosInt = Vector3Int.RoundToInt(cellPos);
switch (tileType)
{
case TileType.Wall:
DoWallDeconstruction(cellPosInt, tileChangeManager, worldPos);
tileChangeManager.gameObject.GetComponent<SubsystemManager>().UpdateAt(cellPosInt);
break;
}
}
//Server only
public void ProcessDeconstructRequest(GameObject player, GameObject matrixRoot, TileType tileType,
Vector3 cellPos, Vector3 worldCellPos)
{
if (player.Player().Script.IsInReach(worldCellPos, true) == false)
{
//Not in range on the server, do not process any further:
return;
}
//Process Wall deconstruct request:
if (tileType == TileType.Wall)
{
//Set up the action to be invoked when progress bar finishes:
var progressFinishAction = new FinishProgressAction(
finishReason =>
{
if (finishReason == FinishProgressAction.FinishReason.COMPLETED)
{
CraftingManager.Deconstruction.TryTileDeconstruct(
matrixRoot.GetComponent<TileChangeManager>(), tileType, cellPos, worldCellPos);
}
}
);
//Start the progress bar:
UIManager.ProgressBar.StartProgress(Vector3Int.RoundToInt(worldCellPos),
10f, progressFinishAction, player, "Weld", 0.8f);
SoundManager.PlayNetworkedAtPos("Weld", worldCellPos, Random.Range(0.9f, 1.1f));
}
}
//does the deconstruction when deconstruction progress finishes
private void DoTileDeconstruction()
{
}
private void DoWallDeconstruction(Vector3Int cellPos, TileChangeManager tcm, Vector3 worldPos)
{
tcm.RemoveTile(cellPos, LayerType.Walls);
SoundManager.PlayNetworkedAtPos("Deconstruct", worldPos, 1f);
PoolManager.PoolNetworkInstantiate(metalPrefab, worldPos, tcm.transform);
PoolManager.PoolNetworkInstantiate(wallGirderPrefab, worldPos, tcm.transform);
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Deconstruction : MonoBehaviour
{
public GameObject wallGirderPrefab;
public GameObject metalPrefab;
//Server only:
public void TryTileDeconstruct(TileChangeManager tileChangeManager, TileType tileType, Vector3 cellPos, Vector3 worldPos)
{
var cellPosInt = Vector3Int.RoundToInt(cellPos);
switch (tileType)
{
case TileType.Wall:
DoWallDeconstruction(cellPosInt, tileChangeManager, worldPos);
tileChangeManager.gameObject.GetComponent<SubsystemManager>().UpdateAt(cellPosInt);
break;
}
}
//Server only
public void ProcessDeconstructRequest(GameObject player, GameObject matrixRoot, TileType tileType,
Vector3 cellPos, Vector3 worldCellPos)
{
if (PlayerScript.IsInReach(player.transform.position, worldCellPos) == false)
{
//Not in range on the server, do not process any further:
return;
}
//Process Wall deconstruct request:
if (tileType == TileType.Wall)
{
//Set up the action to be invoked when progress bar finishes:
var progressFinishAction = new FinishProgressAction(
finishReason =>
{
if (finishReason == FinishProgressAction.FinishReason.COMPLETED)
{
CraftingManager.Deconstruction.TryTileDeconstruct(
matrixRoot.GetComponent<TileChangeManager>(), tileType, cellPos, worldCellPos);
}
}
);
//Start the progress bar:
UIManager.ProgressBar.StartProgress(Vector3Int.RoundToInt(worldCellPos),
10f, progressFinishAction, player, "Weld", 0.8f);
SoundManager.PlayNetworkedAtPos("Weld", worldCellPos, Random.Range(0.9f, 1.1f));
}
}
//does the deconstruction when deconstruction progress finishes
private void DoTileDeconstruction()
{
}
private void DoWallDeconstruction(Vector3Int cellPos, TileChangeManager tcm, Vector3 worldPos)
{
tcm.RemoveTile(cellPos, LayerType.Walls);
SoundManager.PlayNetworkedAtPos("Deconstruct", worldPos, 1f);
PoolManager.PoolNetworkInstantiate(metalPrefab, worldPos, tcm.transform);
PoolManager.PoolNetworkInstantiate(wallGirderPrefab, worldPos, tcm.transform);
}
}
|
agpl-3.0
|
C#
|
413f984f1b07cd9129f73be5338c5fdfeccfe52b
|
Make stopping of a recording async so we dont block the next song
|
haefele/SpotifyRecorder
|
SpotifyRecorder/Tests/SpotifyRecorder.Tests.Console/Program.cs
|
SpotifyRecorder/Tests/SpotifyRecorder.Tests.Console/Program.cs
|
using System;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using SpotifyRecorder.Core.Abstractions.Entities;
using SpotifyRecorder.Core.Abstractions.Extensions;
using SpotifyRecorder.Core.Abstractions.Services;
using SpotifyRecorder.Core.Implementations.Services;
namespace SpotifyRecorder.Tests.Console
{
class Program
{
static void Main(string[] args)
{
var recordingService = new AudioRecordingService();
var spotifyService = new SpotifyService();
IAudioRecorder currentRecorder = null;
AudioOutputDevice stereoMix = new AudioOutputDeviceService().GetOutputDevices().FirstOrDefault(f => f.Name.Contains("Stereo"));
spotifyService.GetSong().Subscribe(song =>
{
if (currentRecorder != null)
{
System.Console.WriteLine($"Song {currentRecorder.Song.Title} finished.");
StopRecording(currentRecorder);
}
if (song != null)
{
System.Console.WriteLine($"Recording song {song.Title}");
currentRecorder = recordingService.StartRecording(stereoMix, song);
}
else
{
System.Console.WriteLine("Currently no song is playing.");
currentRecorder = null;
}
});
System.Console.ReadLine();
}
private static void StopRecording(IAudioRecorder recorder)
{
Task.Run(() =>
{
var recorded = recorder.StopRecording();
ID3TagService service = new ID3TagService();
var tags = service.GetTags(recorded);
tags.Artists = new[] { recorded.Song.Artist };
tags.Title = recorded.Song.Title;
service.UpdateTags(tags, recorded);
string fileName = $"{recorded.Song.Artist} - {recorded.Song.Title}.mp3".ToValidFileName();
File.WriteAllBytes(Path.Combine(".", fileName), recorded.Data);
});
}
}
}
|
using System;
using System.IO;
using System.Linq;
using NAudio.Wave;
using SpotifyRecorder.Core.Abstractions.Entities;
using SpotifyRecorder.Core.Abstractions.Extensions;
using SpotifyRecorder.Core.Abstractions.Services;
using SpotifyRecorder.Core.Implementations.Services;
namespace SpotifyRecorder.Tests.Console
{
class Program
{
static void Main(string[] args)
{
var recordingService = new AudioRecordingService();
var spotifyService = new SpotifyService();
IAudioRecorder currentRecorder = null;
AudioOutputDevice stereoMix = new AudioOutputDeviceService().GetOutputDevices().FirstOrDefault(f => f.Name.Contains("Stereo"));
spotifyService.GetSong().Subscribe(song =>
{
if (currentRecorder != null)
{
System.Console.WriteLine($"Song {currentRecorder.Song.Title} finished.");
var recorded = currentRecorder.StopRecording();
ID3TagService service = new ID3TagService();
var tags = service.GetTags(recorded);
tags.Artists = new[] {recorded.Song.Artist};
tags.Title = recorded.Song.Title;
service.UpdateTags(tags, recorded);
string fileName = $"{recorded.Song.Artist} - {recorded.Song.Title}.mp3".ToValidFileName();
File.WriteAllBytes(Path.Combine(".", fileName), recorded.Data);
}
if (song != null)
{
System.Console.WriteLine($"Recording song {song.Title}");
currentRecorder = recordingService.StartRecording(stereoMix, song);
}
else
{
System.Console.WriteLine("Currently no song is playing.");
currentRecorder = null;
}
});
System.Console.ReadLine();
}
}
}
|
mit
|
C#
|
8ab05fe158f54462a75b39ffe2e974b3034bc6bb
|
Mark IFunctionPointerTypeSymbol as deriving from ITypeSymbol
|
tannergooding/roslyn,jasonmalinowski/roslyn,eriawan/roslyn,bartdesmet/roslyn,genlu/roslyn,heejaechang/roslyn,gafter/roslyn,CyrusNajmabadi/roslyn,tannergooding/roslyn,KevinRansom/roslyn,eriawan/roslyn,ErikSchierboom/roslyn,davkean/roslyn,wvdd007/roslyn,stephentoub/roslyn,mavasani/roslyn,genlu/roslyn,jmarolf/roslyn,panopticoncentral/roslyn,sharwell/roslyn,aelij/roslyn,tmat/roslyn,tmat/roslyn,genlu/roslyn,bartdesmet/roslyn,weltkante/roslyn,shyamnamboodiripad/roslyn,shyamnamboodiripad/roslyn,mgoertz-msft/roslyn,mgoertz-msft/roslyn,aelij/roslyn,KirillOsenkov/roslyn,gafter/roslyn,bartdesmet/roslyn,stephentoub/roslyn,ErikSchierboom/roslyn,tannergooding/roslyn,eriawan/roslyn,wvdd007/roslyn,AmadeusW/roslyn,sharwell/roslyn,brettfo/roslyn,CyrusNajmabadi/roslyn,heejaechang/roslyn,shyamnamboodiripad/roslyn,panopticoncentral/roslyn,brettfo/roslyn,tmat/roslyn,jasonmalinowski/roslyn,jmarolf/roslyn,davkean/roslyn,brettfo/roslyn,ErikSchierboom/roslyn,mavasani/roslyn,AlekseyTs/roslyn,AlekseyTs/roslyn,gafter/roslyn,diryboy/roslyn,dotnet/roslyn,davkean/roslyn,stephentoub/roslyn,physhi/roslyn,AlekseyTs/roslyn,heejaechang/roslyn,diryboy/roslyn,diryboy/roslyn,panopticoncentral/roslyn,weltkante/roslyn,KevinRansom/roslyn,wvdd007/roslyn,physhi/roslyn,sharwell/roslyn,jasonmalinowski/roslyn,aelij/roslyn,mgoertz-msft/roslyn,AmadeusW/roslyn,dotnet/roslyn,mavasani/roslyn,physhi/roslyn,KevinRansom/roslyn,AmadeusW/roslyn,jmarolf/roslyn,CyrusNajmabadi/roslyn,dotnet/roslyn,KirillOsenkov/roslyn,weltkante/roslyn,KirillOsenkov/roslyn
|
src/Compilers/Core/Portable/Symbols/IFunctionPointerTypeSymbol.cs
|
src/Compilers/Core/Portable/Symbols/IFunctionPointerTypeSymbol.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
namespace Microsoft.CodeAnalysis
{
// PROTOTYPE(func-ptr): Document
// https://github.com/dotnet/roslyn/issues/39865: Expose calling convention on either this or IMethodSymbol in general
public interface IFunctionPointerTypeSymbol : ITypeSymbol
{
public IMethodSymbol Signature { get; }
}
}
|
// 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
namespace Microsoft.CodeAnalysis
{
// PROTOTYPE(func-ptr): Document
// https://github.com/dotnet/roslyn/issues/39865: Expose calling convention on either this or IMethodSymbol in general
public interface IFunctionPointerTypeSymbol : ISymbol
{
public IMethodSymbol Signature { get; }
}
}
|
mit
|
C#
|
28f6a5ce8e2ee72eb1620b81644f6470cacb5a2d
|
Fix bug where property names were always named the p1 name.
|
Microsoft/ApplicationInsights-SDK-Labs,frackleton/ApplicationInsights-SDK-Labs
|
AggregateMetrics/AggregateMetrics/MetricTelemetryExtensions.cs
|
AggregateMetrics/AggregateMetrics/MetricTelemetryExtensions.cs
|
namespace Microsoft.ApplicationInsights.Extensibility.AggregateMetrics
{
using System.Globalization;
using Microsoft.ApplicationInsights.DataContracts;
using Microsoft.ApplicationInsights.Extensibility.Implementation;
internal static class MetricTelemetryExtensions
{
internal static void AddProperties(this MetricTelemetry metricTelemetry, MetricsBag metricsBag, string p1Name, string p2Name, string p3Name)
{
if (metricsBag.Property1 != null)
{
metricTelemetry.Properties[p1Name] = metricsBag.Property1;
}
if (metricsBag.Property2 != null)
{
metricTelemetry.Properties[p2Name] = metricsBag.Property2;
}
if (metricsBag.Property3 != null)
{
metricTelemetry.Properties[p3Name] = metricsBag.Property3;
}
}
internal static MetricTelemetry CreateDerivedMetric(this MetricTelemetry metricTelemetry, string nameSuffix, double value)
{
var derivedTelemetry = new MetricTelemetry(string.Format(CultureInfo.InvariantCulture, "{0}_{1}", metricTelemetry.Name, nameSuffix), value)
{
Timestamp = metricTelemetry.Timestamp
};
derivedTelemetry.Context.GetInternalContext().SdkVersion = metricTelemetry.Context.GetInternalContext().SdkVersion;
return derivedTelemetry;
}
}
}
|
namespace Microsoft.ApplicationInsights.Extensibility.AggregateMetrics
{
using System.Globalization;
using Microsoft.ApplicationInsights.DataContracts;
using Microsoft.ApplicationInsights.Extensibility.Implementation;
internal static class MetricTelemetryExtensions
{
internal static void AddProperties(this MetricTelemetry metricTelemetry, MetricsBag metricsBag, string p1Name, string p2Name, string p3Name)
{
if (metricsBag.Property1 != null)
{
metricTelemetry.Properties[p1Name] = metricsBag.Property1;
}
if (metricsBag.Property2 != null)
{
metricTelemetry.Properties[p1Name] = metricsBag.Property2;
}
if (metricsBag.Property3 != null)
{
metricTelemetry.Properties[p1Name] = metricsBag.Property3;
}
}
internal static MetricTelemetry CreateDerivedMetric(this MetricTelemetry metricTelemetry, string nameSuffix, double value)
{
var derivedTelemetry = new MetricTelemetry(string.Format(CultureInfo.InvariantCulture, "{0}_{1}", metricTelemetry.Name, nameSuffix), value)
{
Timestamp = metricTelemetry.Timestamp
};
derivedTelemetry.Context.GetInternalContext().SdkVersion = metricTelemetry.Context.GetInternalContext().SdkVersion;
return derivedTelemetry;
}
}
}
|
mit
|
C#
|
30a24256709b719c4b4be1fa7fd8f5e51496759f
|
Fix access violation on Windows
|
mrward/monodevelop-powershell-addin
|
src/MonoDevelop.PowerShell/MonoDevelop.PowerShell/PowerShellOutputPad.cs
|
src/MonoDevelop.PowerShell/MonoDevelop.PowerShell/PowerShellOutputPad.cs
|
//
// PowerShellOutputPad.cs
//
// Author:
// Matt Ward <matt.ward@xamarin.com>
//
// Copyright (c) 2016 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 Gtk;
using MonoDevelop.Components;
using MonoDevelop.Components.Docking;
using MonoDevelop.Core;
using MonoDevelop.Ide.Gui;
using MonoDevelop.Ide.Gui.Components;
namespace MonoDevelop.PowerShell
{
class PowerShellOutputPad : PadContent
{
static PowerShellOutputPad instance;
static readonly LogView logView = new LogView ();
public PowerShellOutputPad ()
{
instance = this;
}
public static PowerShellOutputPad Instance {
get { return instance; }
}
protected override void Initialize (IPadWindow window)
{
DockItemToolbar toolbar = window.GetToolbar (DockPositionType.Right);
var clearButton = new Button (new ImageView (Ide.Gui.Stock.Broom, IconSize.Menu));
clearButton.Clicked += ButtonClearClick;
clearButton.TooltipText = GettextCatalog.GetString ("Clear");
toolbar.Add (clearButton);
toolbar.ShowAll ();
logView.ShowAll ();
}
public override Control Control {
get { return logView; }
}
public static LogView LogView {
get { return logView; }
}
void ButtonClearClick (object sender, EventArgs e)
{
logView.Clear ();
}
public static void WriteText (string message)
{
Runtime.RunInMainThread (() => {
logView.WriteText (message + Environment.NewLine);
});
}
public static void WriteError (string message)
{
Runtime.RunInMainThread (() => {
logView.WriteError (message + Environment.NewLine);
});
}
}
}
|
//
// PowerShellOutputPad.cs
//
// Author:
// Matt Ward <matt.ward@xamarin.com>
//
// Copyright (c) 2016 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 Gtk;
using MonoDevelop.Components;
using MonoDevelop.Components.Docking;
using MonoDevelop.Core;
using MonoDevelop.Ide.Gui;
using MonoDevelop.Ide.Gui.Components;
namespace MonoDevelop.PowerShell
{
class PowerShellOutputPad : PadContent
{
static PowerShellOutputPad instance;
static readonly LogView logView = new LogView ();
public PowerShellOutputPad ()
{
instance = this;
}
public static PowerShellOutputPad Instance {
get { return instance; }
}
protected override void Initialize (IPadWindow window)
{
DockItemToolbar toolbar = window.GetToolbar (DockPositionType.Right);
var clearButton = new Button (new ImageView (Ide.Gui.Stock.Broom, IconSize.Menu));
clearButton.Clicked += ButtonClearClick;
clearButton.TooltipText = GettextCatalog.GetString ("Clear");
toolbar.Add (clearButton);
toolbar.ShowAll ();
logView.ShowAll ();
}
public override Control Control {
get { return logView; }
}
public static LogView LogView {
get { return logView; }
}
void ButtonClearClick (object sender, EventArgs e)
{
logView.Clear ();
}
public static void WriteText (string message)
{
logView.WriteText (message + Environment.NewLine);
}
public static void WriteError (string message)
{
logView.WriteError (message + Environment.NewLine);
}
}
}
|
mit
|
C#
|
71d167bc7342360c6b0c9ed255df95efdbad816a
|
Disable failing test
|
BrennanConroy/corefx,Chrisboh/corefx,rjxby/corefx,fgreinacher/corefx,zhenlan/corefx,twsouthwick/corefx,mokchhya/corefx,dhoehna/corefx,PatrickMcDonald/corefx,CherryCxldn/corefx,gabrielPeart/corefx,krytarowski/corefx,CloudLens/corefx,alexandrnikitin/corefx,jeremymeng/corefx,shmao/corefx,andyhebear/corefx,ericstj/corefx,YoupHulsebos/corefx,gregg-miskelly/corefx,lggomez/corefx,shimingsg/corefx,seanshpark/corefx,rahku/corefx,ptoonen/corefx,nchikanov/corefx,erpframework/corefx,richlander/corefx,Alcaro/corefx,pallavit/corefx,jmhardison/corefx,Petermarcu/corefx,the-dwyer/corefx,MaggieTsang/corefx,tstringer/corefx,Priya91/corefx-1,huanjie/corefx,akivafr123/corefx,vijaykota/corefx,YoupHulsebos/corefx,adamralph/corefx,KrisLee/corefx,ViktorHofer/corefx,claudelee/corefx,krytarowski/corefx,thiagodin/corefx,shiftkey-tester/corefx,stephenmichaelf/corefx,marksmeltzer/corefx,zmaruo/corefx,erpframework/corefx,elijah6/corefx,viniciustaveira/corefx,MaggieTsang/corefx,Yanjing123/corefx,CloudLens/corefx,rubo/corefx,destinyclown/corefx,690486439/corefx,lggomez/corefx,dtrebbien/corefx,nbarbettini/corefx,stone-li/corefx,rajansingh10/corefx,manu-silicon/corefx,JosephTremoulet/corefx,JosephTremoulet/corefx,cydhaselton/corefx,ptoonen/corefx,weltkante/corefx,shrutigarg/corefx,manu-silicon/corefx,scott156/corefx,the-dwyer/corefx,rjxby/corefx,benjamin-bader/corefx,cartermp/corefx,Priya91/corefx-1,cartermp/corefx,cartermp/corefx,alphonsekurian/corefx,Frank125/corefx,tijoytom/corefx,cartermp/corefx,akivafr123/corefx,wtgodbe/corefx,Petermarcu/corefx,rahku/corefx,elijah6/corefx,mmitche/corefx,chenxizhang/corefx,seanshpark/corefx,ellismg/corefx,ptoonen/corefx,marksmeltzer/corefx,MaggieTsang/corefx,stormleoxia/corefx,tijoytom/corefx,Jiayili1/corefx,ravimeda/corefx,mokchhya/corefx,dkorolev/corefx,lggomez/corefx,arronei/corefx,ellismg/corefx,vidhya-bv/corefx-sorting,seanshpark/corefx,ViktorHofer/corefx,erpframework/corefx,zmaruo/corefx,gregg-miskelly/corefx,seanshpark/corefx,stone-li/corefx,DnlHarvey/corefx,oceanho/corefx,dtrebbien/corefx,mafiya69/corefx,mafiya69/corefx,khdang/corefx,wtgodbe/corefx,vrassouli/corefx,benpye/corefx,janhenke/corefx,vrassouli/corefx,Yanjing123/corefx,richlander/corefx,jcme/corefx,vijaykota/corefx,bitcrazed/corefx,nelsonsar/corefx,alexperovich/corefx,mmitche/corefx,shimingsg/corefx,jlin177/corefx,stephenmichaelf/corefx,Petermarcu/corefx,ellismg/corefx,690486439/corefx,mafiya69/corefx,weltkante/corefx,shimingsg/corefx,alphonsekurian/corefx,jhendrixMSFT/corefx,zhenlan/corefx,uhaciogullari/corefx,rahku/corefx,vs-team/corefx,Jiayili1/corefx,mellinoe/corefx,larsbj1988/corefx,SGuyGe/corefx,stone-li/corefx,twsouthwick/corefx,janhenke/corefx,alphonsekurian/corefx,krytarowski/corefx,claudelee/corefx,popolan1986/corefx,chaitrakeshav/corefx,the-dwyer/corefx,nchikanov/corefx,brett25/corefx,nchikanov/corefx,gabrielPeart/corefx,shimingsg/corefx,dsplaisted/corefx,josguil/corefx,anjumrizwi/corefx,alexperovich/corefx,gkhanna79/corefx,misterzik/corefx,ptoonen/corefx,shimingsg/corefx,Winsto/corefx,cydhaselton/corefx,billwert/corefx,matthubin/corefx,alexperovich/corefx,jlin177/corefx,shana/corefx,pallavit/corefx,Alcaro/corefx,ericstj/corefx,YoupHulsebos/corefx,vs-team/corefx,shmao/corefx,Ermiar/corefx,khdang/corefx,shana/corefx,andyhebear/corefx,brett25/corefx,akivafr123/corefx,parjong/corefx,shrutigarg/corefx,parjong/corefx,thiagodin/corefx,cydhaselton/corefx,Yanjing123/corefx,kkurni/corefx,YoupHulsebos/corefx,tijoytom/corefx,Priya91/corefx-1,SGuyGe/corefx,comdiv/corefx,fffej/corefx,CloudLens/corefx,alphonsekurian/corefx,jlin177/corefx,mazong1123/corefx,n1ghtmare/corefx,jcme/corefx,jlin177/corefx,Chrisboh/corefx,jmhardison/corefx,lggomez/corefx,krk/corefx,alexandrnikitin/corefx,adamralph/corefx,zhenlan/corefx,khdang/corefx,tstringer/corefx,pallavit/corefx,bpschoch/corefx,mmitche/corefx,shahid-pk/corefx,dsplaisted/corefx,shimingsg/corefx,tijoytom/corefx,heXelium/corefx,SGuyGe/corefx,dotnet-bot/corefx,krk/corefx,brett25/corefx,jeremymeng/corefx,YoupHulsebos/corefx,jmhardison/corefx,billwert/corefx,EverlessDrop41/corefx,rjxby/corefx,billwert/corefx,stephenmichaelf/corefx,zhangwenquan/corefx,BrennanConroy/corefx,mafiya69/corefx,gkhanna79/corefx,lydonchandra/corefx,scott156/corefx,mmitche/corefx,jlin177/corefx,heXelium/corefx,josguil/corefx,ellismg/corefx,Ermiar/corefx,ptoonen/corefx,rjxby/corefx,stephenmichaelf/corefx,dotnet-bot/corefx,benjamin-bader/corefx,jhendrixMSFT/corefx,Yanjing123/corefx,stephenmichaelf/corefx,xuweixuwei/corefx,kyulee1/corefx,s0ne0me/corefx,mazong1123/corefx,mmitche/corefx,axelheer/corefx,nbarbettini/corefx,alexperovich/corefx,axelheer/corefx,jcme/corefx,janhenke/corefx,rahku/corefx,pgavlin/corefx,krytarowski/corefx,the-dwyer/corefx,mellinoe/corefx,anjumrizwi/corefx,spoiledsport/corefx,stone-li/corefx,billwert/corefx,mokchhya/corefx,parjong/corefx,Petermarcu/corefx,Priya91/corefx-1,matthubin/corefx,vidhya-bv/corefx-sorting,s0ne0me/corefx,DnlHarvey/corefx,zhangwenquan/corefx,yizhang82/corefx,rajansingh10/corefx,pgavlin/corefx,vijaykota/corefx,shrutigarg/corefx,ericstj/corefx,jmhardison/corefx,Chrisboh/corefx,nbarbettini/corefx,comdiv/corefx,dhoehna/corefx,shimingsg/corefx,janhenke/corefx,tstringer/corefx,nelsonsar/corefx,parjong/corefx,shmao/corefx,mazong1123/corefx,thiagodin/corefx,dotnet-bot/corefx,fgreinacher/corefx,nchikanov/corefx,erpframework/corefx,richlander/corefx,bitcrazed/corefx,larsbj1988/corefx,arronei/corefx,marksmeltzer/corefx,uhaciogullari/corefx,benjamin-bader/corefx,gkhanna79/corefx,dkorolev/corefx,nbarbettini/corefx,bpschoch/corefx,690486439/corefx,vs-team/corefx,YoupHulsebos/corefx,misterzik/corefx,pgavlin/corefx,bpschoch/corefx,cydhaselton/corefx,Jiayili1/corefx,cartermp/corefx,anjumrizwi/corefx,ViktorHofer/corefx,lggomez/corefx,mellinoe/corefx,krytarowski/corefx,DnlHarvey/corefx,ericstj/corefx,heXelium/corefx,Frank125/corefx,matthubin/corefx,pallavit/corefx,ptoonen/corefx,marksmeltzer/corefx,Winsto/corefx,cnbin/corefx,chenxizhang/corefx,MaggieTsang/corefx,andyhebear/corefx,JosephTremoulet/corefx,billwert/corefx,manu-silicon/corefx,kkurni/corefx,Petermarcu/corefx,ravimeda/corefx,chenkennt/corefx,ravimeda/corefx,weltkante/corefx,DnlHarvey/corefx,yizhang82/corefx,stone-li/corefx,krk/corefx,tijoytom/corefx,larsbj1988/corefx,manu-silicon/corefx,larsbj1988/corefx,VPashkov/corefx,axelheer/corefx,lggomez/corefx,seanshpark/corefx,cartermp/corefx,gkhanna79/corefx,iamjasonp/corefx,anjumrizwi/corefx,parjong/corefx,alexandrnikitin/corefx,ravimeda/corefx,huanjie/corefx,nbarbettini/corefx,lydonchandra/corefx,Jiayili1/corefx,josguil/corefx,elijah6/corefx,Priya91/corefx-1,cnbin/corefx,fffej/corefx,fernando-rodriguez/corefx,rjxby/corefx,690486439/corefx,andyhebear/corefx,tstringer/corefx,gregg-miskelly/corefx,spoiledsport/corefx,cydhaselton/corefx,scott156/corefx,Jiayili1/corefx,huanjie/corefx,n1ghtmare/corefx,yizhang82/corefx,PatrickMcDonald/corefx,alphonsekurian/corefx,n1ghtmare/corefx,zmaruo/corefx,elijah6/corefx,n1ghtmare/corefx,tijoytom/corefx,shana/corefx,jeremymeng/corefx,adamralph/corefx,axelheer/corefx,chenkennt/corefx,vidhya-bv/corefx-sorting,alexperovich/corefx,mafiya69/corefx,mellinoe/corefx,SGuyGe/corefx,PatrickMcDonald/corefx,yizhang82/corefx,comdiv/corefx,iamjasonp/corefx,dotnet-bot/corefx,kkurni/corefx,chaitrakeshav/corefx,parjong/corefx,chenxizhang/corefx,rahku/corefx,Yanjing123/corefx,shmao/corefx,nchikanov/corefx,stephenmichaelf/corefx,shmao/corefx,mellinoe/corefx,shiftkey-tester/corefx,benpye/corefx,VPashkov/corefx,shmao/corefx,lggomez/corefx,oceanho/corefx,bitcrazed/corefx,yizhang82/corefx,rubo/corefx,alphonsekurian/corefx,janhenke/corefx,elijah6/corefx,EverlessDrop41/corefx,stormleoxia/corefx,alphonsekurian/corefx,chaitrakeshav/corefx,Ermiar/corefx,DnlHarvey/corefx,gkhanna79/corefx,brett25/corefx,richlander/corefx,mellinoe/corefx,lydonchandra/corefx,JosephTremoulet/corefx,CherryCxldn/corefx,josguil/corefx,jeremymeng/corefx,kkurni/corefx,manu-silicon/corefx,billwert/corefx,wtgodbe/corefx,dhoehna/corefx,benpye/corefx,shahid-pk/corefx,s0ne0me/corefx,ellismg/corefx,mazong1123/corefx,gkhanna79/corefx,Chrisboh/corefx,Ermiar/corefx,krk/corefx,mazong1123/corefx,rajansingh10/corefx,mazong1123/corefx,shrutigarg/corefx,kyulee1/corefx,Jiayili1/corefx,wtgodbe/corefx,the-dwyer/corefx,CherryCxldn/corefx,twsouthwick/corefx,twsouthwick/corefx,iamjasonp/corefx,gabrielPeart/corefx,zmaruo/corefx,jhendrixMSFT/corefx,parjong/corefx,arronei/corefx,cydhaselton/corefx,mmitche/corefx,dkorolev/corefx,uhaciogullari/corefx,thiagodin/corefx,chenkennt/corefx,iamjasonp/corefx,mmitche/corefx,richlander/corefx,PatrickMcDonald/corefx,MaggieTsang/corefx,Petermarcu/corefx,Frank125/corefx,yizhang82/corefx,JosephTremoulet/corefx,khdang/corefx,shahid-pk/corefx,jcme/corefx,popolan1986/corefx,xuweixuwei/corefx,gkhanna79/corefx,PatrickMcDonald/corefx,xuweixuwei/corefx,CherryCxldn/corefx,elijah6/corefx,jhendrixMSFT/corefx,gabrielPeart/corefx,alexandrnikitin/corefx,vidhya-bv/corefx-sorting,zhenlan/corefx,weltkante/corefx,weltkante/corefx,billwert/corefx,jhendrixMSFT/corefx,twsouthwick/corefx,uhaciogullari/corefx,DnlHarvey/corefx,dhoehna/corefx,bpschoch/corefx,bitcrazed/corefx,chaitrakeshav/corefx,zhangwenquan/corefx,claudelee/corefx,destinyclown/corefx,ericstj/corefx,mazong1123/corefx,alexperovich/corefx,BrennanConroy/corefx,cnbin/corefx,nchikanov/corefx,KrisLee/corefx,shmao/corefx,ellismg/corefx,rajansingh10/corefx,bitcrazed/corefx,shana/corefx,jcme/corefx,benpye/corefx,comdiv/corefx,kyulee1/corefx,dhoehna/corefx,Alcaro/corefx,khdang/corefx,YoupHulsebos/corefx,ViktorHofer/corefx,ericstj/corefx,nbarbettini/corefx,josguil/corefx,wtgodbe/corefx,nelsonsar/corefx,krytarowski/corefx,stephenmichaelf/corefx,seanshpark/corefx,pallavit/corefx,krk/corefx,Ermiar/corefx,shiftkey-tester/corefx,dotnet-bot/corefx,jlin177/corefx,vrassouli/corefx,vrassouli/corefx,dtrebbien/corefx,Frank125/corefx,viniciustaveira/corefx,spoiledsport/corefx,khdang/corefx,yizhang82/corefx,fernando-rodriguez/corefx,Ermiar/corefx,shiftkey-tester/corefx,dsplaisted/corefx,tijoytom/corefx,twsouthwick/corefx,marksmeltzer/corefx,axelheer/corefx,rubo/corefx,KrisLee/corefx,shahid-pk/corefx,ericstj/corefx,the-dwyer/corefx,josguil/corefx,richlander/corefx,zhenlan/corefx,wtgodbe/corefx,ViktorHofer/corefx,s0ne0me/corefx,richlander/corefx,elijah6/corefx,kkurni/corefx,pgavlin/corefx,stone-li/corefx,weltkante/corefx,marksmeltzer/corefx,dotnet-bot/corefx,zhenlan/corefx,Alcaro/corefx,JosephTremoulet/corefx,benpye/corefx,janhenke/corefx,benjamin-bader/corefx,marksmeltzer/corefx,fernando-rodriguez/corefx,rubo/corefx,jlin177/corefx,akivafr123/corefx,CloudLens/corefx,Petermarcu/corefx,popolan1986/corefx,zhangwenquan/corefx,ravimeda/corefx,mokchhya/corefx,ViktorHofer/corefx,twsouthwick/corefx,alexandrnikitin/corefx,lydonchandra/corefx,the-dwyer/corefx,oceanho/corefx,rubo/corefx,Chrisboh/corefx,mafiya69/corefx,Priya91/corefx-1,destinyclown/corefx,fgreinacher/corefx,dhoehna/corefx,shahid-pk/corefx,dkorolev/corefx,690486439/corefx,EverlessDrop41/corefx,ViktorHofer/corefx,ptoonen/corefx,pallavit/corefx,dhoehna/corefx,vidhya-bv/corefx-sorting,iamjasonp/corefx,iamjasonp/corefx,VPashkov/corefx,zhenlan/corefx,wtgodbe/corefx,stormleoxia/corefx,jhendrixMSFT/corefx,krk/corefx,fgreinacher/corefx,axelheer/corefx,tstringer/corefx,mokchhya/corefx,benpye/corefx,jcme/corefx,shahid-pk/corefx,tstringer/corefx,SGuyGe/corefx,benjamin-bader/corefx,VPashkov/corefx,nchikanov/corefx,rjxby/corefx,misterzik/corefx,heXelium/corefx,vs-team/corefx,krk/corefx,manu-silicon/corefx,n1ghtmare/corefx,jhendrixMSFT/corefx,matthubin/corefx,weltkante/corefx,Jiayili1/corefx,Winsto/corefx,ravimeda/corefx,kkurni/corefx,cnbin/corefx,kyulee1/corefx,JosephTremoulet/corefx,stormleoxia/corefx,rjxby/corefx,Ermiar/corefx,ravimeda/corefx,KrisLee/corefx,viniciustaveira/corefx,krytarowski/corefx,claudelee/corefx,gregg-miskelly/corefx,Chrisboh/corefx,rahku/corefx,fffej/corefx,fffej/corefx,rahku/corefx,seanshpark/corefx,SGuyGe/corefx,nelsonsar/corefx,mokchhya/corefx,dotnet-bot/corefx,MaggieTsang/corefx,cydhaselton/corefx,iamjasonp/corefx,oceanho/corefx,viniciustaveira/corefx,benjamin-bader/corefx,dtrebbien/corefx,nbarbettini/corefx,MaggieTsang/corefx,DnlHarvey/corefx,manu-silicon/corefx,huanjie/corefx,alexperovich/corefx,scott156/corefx,akivafr123/corefx,jeremymeng/corefx,stone-li/corefx
|
src/System.IO.FileSystem/tests/FileStream/ctor_str_fm_fa_fs_buffer_fo.cs
|
src/System.IO.FileSystem/tests/FileStream/ctor_str_fm_fa_fs_buffer_fo.cs
|
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System;
using System.IO;
using Xunit;
namespace System.IO.FileSystem.Tests
{
public class FileStream_ctor_str_fm_fa_fs_buffer_fo : FileStream_ctor_str_fm_fa_fs_buffer
{
protected sealed override FileStream CreateFileStream(string path, FileMode mode, FileAccess access, FileShare share, int bufferSize)
{
return CreateFileStream(path, mode, access, share, bufferSize, FileOptions.None);
}
protected virtual FileStream CreateFileStream(string path, FileMode mode, FileAccess access, FileShare share, int bufferSize, FileOptions options)
{
return new FileStream(path, mode, access, share, bufferSize, options);
}
[Fact]
public void InvalidFileOptionsThrow()
{
Assert.Throws<ArgumentOutOfRangeException>("options", () => CreateFileStream(GetTestFilePath(), FileMode.Create, FileAccess.ReadWrite, FileShare.Read, c_DefaultBufferSize, ~FileOptions.None));
}
[Fact]
[ActiveIssue(1434)]
public void ValidFileOptions()
{
foreach(FileOptions option in Enum.GetValues(typeof(FileOptions)))
{
using (CreateFileStream(GetTestFilePath(), FileMode.Create, FileAccess.ReadWrite, FileShare.Read, c_DefaultBufferSize, option))
{ }
}
// FILE_FLAG_NO_BUFFERRING is also supported
using (CreateFileStream(GetTestFilePath(), FileMode.Create, FileAccess.ReadWrite, FileShare.Read, c_DefaultBufferSize, (FileOptions)0x20000000))
{ }
}
}
}
|
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System;
using System.IO;
using Xunit;
namespace System.IO.FileSystem.Tests
{
public class FileStream_ctor_str_fm_fa_fs_buffer_fo : FileStream_ctor_str_fm_fa_fs_buffer
{
protected sealed override FileStream CreateFileStream(string path, FileMode mode, FileAccess access, FileShare share, int bufferSize)
{
return CreateFileStream(path, mode, access, share, bufferSize, FileOptions.None);
}
protected virtual FileStream CreateFileStream(string path, FileMode mode, FileAccess access, FileShare share, int bufferSize, FileOptions options)
{
return new FileStream(path, mode, access, share, bufferSize, options);
}
[Fact]
public void InvalidFileOptionsThrow()
{
Assert.Throws<ArgumentOutOfRangeException>("options", () => CreateFileStream(GetTestFilePath(), FileMode.Create, FileAccess.ReadWrite, FileShare.Read, c_DefaultBufferSize, ~FileOptions.None));
}
[Fact]
public void ValidFileOptions()
{
foreach(FileOptions option in Enum.GetValues(typeof(FileOptions)))
{
using (CreateFileStream(GetTestFilePath(), FileMode.Create, FileAccess.ReadWrite, FileShare.Read, c_DefaultBufferSize, option))
{ }
}
// FILE_FLAG_NO_BUFFERRING is also supported
using (CreateFileStream(GetTestFilePath(), FileMode.Create, FileAccess.ReadWrite, FileShare.Read, c_DefaultBufferSize, (FileOptions)0x20000000))
{ }
}
}
}
|
mit
|
C#
|
0e98a1a7291669f4d9dd42ac9a373487fbd15781
|
fix up the casing rather than surpress
|
jhancock93/autorest,selvasingh/azure-sdk-for-java,Azure/azure-sdk-for-java,haocs/autorest,matt-gibbs/AutoRest,begoldsm/autorest,jkonecki/autorest,anudeepsharma/autorest,jianghaolu/AutoRest,jianghaolu/AutoRest,begoldsm/autorest,sharadagarwal/autorest,yonglehou/autorest,fhoring/autorest,begoldsm/autorest,jianghaolu/AutoRest,vishrutshah/autorest,colemickens/autorest,garimakhulbe/autorest,vishrutshah/autorest,yugangw-msft/autorest,garimakhulbe/autorest,tonytang-microsoft-com/autorest,devigned/autorest,jkonecki/autorest,xingwu1/autorest,lmazuel/autorest,vulcansteel/autorest,AzCiS/autorest,tbombach/autorest,BretJohnson/autorest,yugangw-msft/autorest,veronicagg/autorest,stankovski/AutoRest,xingwu1/autorest,matthchr/autorest,matthchr/autorest,annatisch/autorest,devigned/autorest,jhendrixMSFT/autorest,brodyberg/autorest,brodyberg/autorest,dsgouda/autorest,jhancock93/autorest,balajikris/autorest,devigned/autorest,begoldsm/autorest,devigned/autorest,lmazuel/autorest,annatisch/autorest,matthchr/autorest,John-Hart/autorest,yaqiyang/autorest,jhancock93/autorest,tbombach/autorest,begoldsm/autorest,haocs/autorest,navalev/azure-sdk-for-java,BretJohnson/autorest,xingwu1/autorest,tbombach/autorest,Azure/autorest,yugangw-msft/autorest,lmazuel/autorest,yonglehou/autorest,dsgouda/autorest,AzCiS/autorest,haocs/autorest,vishrutshah/autorest,navalev/azure-sdk-for-java,AzCiS/autorest,sergey-shandar/autorest,garimakhulbe/autorest,matt-gibbs/AutoRest,tbombach/autorest,jhancock93/autorest,AzCiS/autorest,matt-gibbs/AutoRest,stankovski/AutoRest,jhendrixMSFT/autorest,csmengwan/autorest,haocs/autorest,balajikris/autorest,anudeepsharma/autorest,veronicagg/autorest,dsgouda/autorest,stankovski/AutoRest,dsgouda/autorest,sergey-shandar/autorest,tbombach/autorest,anudeepsharma/autorest,tbombach/autorest,begoldsm/autorest,amarzavery/AutoRest,stankovski/AutoRest,hovsepm/AutoRest,brodyberg/autorest,yaqiyang/autorest,xingwu1/autorest,jianghaolu/AutoRest,jhancock93/autorest,fhoring/autorest,dsgouda/autorest,navalev/azure-sdk-for-java,yaqiyang/autorest,devigned/autorest,haocs/autorest,Azure/autorest,tbombach/autorest,veronicagg/autorest,BurtBiel/autorest,selvasingh/azure-sdk-for-java,balajikris/autorest,jhancock93/autorest,csmengwan/autorest,tonytang-microsoft-com/autorest,matthchr/autorest,annatisch/autorest,xingwu1/autorest,garimakhulbe/autorest,hovsepm/AutoRest,anudeepsharma/autorest,navalev/azure-sdk-for-java,jianghaolu/AutoRest,yonglehou/autorest,jkonecki/autorest,lmazuel/autorest,stankovski/AutoRest,haocs/autorest,ljhljh235/AutoRest,vasanthangel4/autorest,vasanthangel4/autorest,annatisch/autorest,John-Hart/autorest,dsgouda/autorest,lmazuel/autorest,hovsepm/AutoRest,vishrutshah/autorest,BretJohnson/autorest,garimakhulbe/autorest,amarzavery/AutoRest,hovsepm/AutoRest,annatisch/autorest,ljhljh235/AutoRest,vulcansteel/autorest,ljhljh235/AutoRest,brodyberg/autorest,fhoring/autorest,devigned/autorest,csmengwan/autorest,haocs/autorest,vasanthangel4/autorest,csmengwan/autorest,csmengwan/autorest,dsgouda/autorest,yaqiyang/autorest,colemickens/autorest,tonytang-microsoft-com/autorest,veronicagg/autorest,vulcansteel/autorest,BurtBiel/autorest,fearthecowboy/autorest,csmengwan/autorest,matt-gibbs/AutoRest,Azure/azure-sdk-for-java,ljhljh235/AutoRest,amarzavery/AutoRest,brjohnstmsft/autorest,tonytang-microsoft-com/autorest,colemickens/autorest,fhoring/autorest,vasanthangel4/autorest,lmazuel/autorest,yaqiyang/autorest,anudeepsharma/autorest,ljhljh235/AutoRest,lmazuel/autorest,sharadagarwal/autorest,brodyberg/autorest,vishrutshah/autorest,navalev/azure-sdk-for-java,sergey-shandar/autorest,sergey-shandar/autorest,matthchr/autorest,tonytang-microsoft-com/autorest,sharadagarwal/autorest,hovsepm/AutoRest,BurtBiel/autorest,annatisch/autorest,veronicagg/autorest,hovsepm/AutoRest,Azure/azure-sdk-for-java,BurtBiel/autorest,veronicagg/autorest,stankovski/AutoRest,AzCiS/autorest,ljhljh235/AutoRest,colemickens/autorest,fhoring/autorest,John-Hart/autorest,csmengwan/autorest,hovsepm/AutoRest,jianghaolu/AutoRest,matthchr/autorest,Azure/azure-sdk-for-java,begoldsm/autorest,matt-gibbs/AutoRest,jhendrixMSFT/autorest,vulcansteel/autorest,Azure/autorest,csmengwan/autorest,fhoring/autorest,yugangw-msft/autorest,vulcansteel/autorest,anudeepsharma/autorest,Azure/autorest,dsgouda/autorest,devigned/autorest,anudeepsharma/autorest,lmazuel/autorest,haocs/autorest,fhoring/autorest,sergey-shandar/autorest,garimakhulbe/autorest,veronicagg/autorest,jianghaolu/AutoRest,hovsepm/AutoRest,yonglehou/autorest,sharadagarwal/autorest,anudeepsharma/autorest,haocs/autorest,vishrutshah/autorest,stankovski/AutoRest,sergey-shandar/autorest,fhoring/autorest,AzCiS/autorest,matthchr/autorest,yugangw-msft/autorest,balajikris/autorest,sergey-shandar/autorest,colemickens/autorest,yonglehou/autorest,balajikris/autorest,vishrutshah/autorest,matthchr/autorest,annatisch/autorest,BurtBiel/autorest,vishrutshah/autorest,BurtBiel/autorest,BurtBiel/autorest,John-Hart/autorest,John-Hart/autorest,balajikris/autorest,garimakhulbe/autorest,olydis/autorest,BretJohnson/autorest,jhancock93/autorest,jkonecki/autorest,yaqiyang/autorest,xingwu1/autorest,xingwu1/autorest,veronicagg/autorest,yaqiyang/autorest,ljhljh235/AutoRest,markcowl/autorest,annatisch/autorest,dsgouda/autorest,amarzavery/AutoRest,vishrutshah/autorest,selvasingh/azure-sdk-for-java,brodyberg/autorest,BurtBiel/autorest,vasanthangel4/autorest,jhendrixMSFT/autorest,matthchr/autorest,amarzavery/AutoRest,yugangw-msft/autorest,tbombach/autorest,yugangw-msft/autorest,John-Hart/autorest,matt-gibbs/AutoRest,amarzavery/AutoRest,jianghaolu/AutoRest,begoldsm/autorest,tbombach/autorest,lmazuel/autorest,balajikris/autorest,AzCiS/autorest,John-Hart/autorest,jkonecki/autorest,fearthecowboy/autorest,sharadagarwal/autorest,vulcansteel/autorest,brodyberg/autorest,sharadagarwal/autorest,brjohnstmsft/autorest,yugangw-msft/autorest,AzCiS/autorest,xingwu1/autorest,amarzavery/AutoRest,jianghaolu/AutoRest,anudeepsharma/autorest,veronicagg/autorest,sharadagarwal/autorest,ljhljh235/AutoRest,Azure/azure-sdk-for-java,fhoring/autorest,vulcansteel/autorest,brodyberg/autorest,stankovski/AutoRest,balajikris/autorest,yaqiyang/autorest,balajikris/autorest,John-Hart/autorest,olydis/autorest,devigned/autorest,sharadagarwal/autorest,amarzavery/AutoRest,garimakhulbe/autorest,amarzavery/AutoRest,jhancock93/autorest,sergey-shandar/autorest,jhancock93/autorest,hovsepm/AutoRest,devigned/autorest,garimakhulbe/autorest,annatisch/autorest,yugangw-msft/autorest,begoldsm/autorest,sergey-shandar/autorest,BretJohnson/autorest
|
Microsoft.Rest/ClientRuntime/BasicAuthenticationCredentials.cs
|
Microsoft.Rest/ClientRuntime/BasicAuthenticationCredentials.cs
|
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for license information.
using System;
using System.Globalization;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace Microsoft.Rest
{
/// <summary>
/// Basic Auth credentials for use with a REST Service Client.
/// </summary>
public class BasicAuthenticationCredentials : ServiceClientCredentials
{
/// <summary>
/// Basic auth UserName.
/// </summary>
public string UserName { get; set; }
/// <summary>
/// Basic auth password.
/// </summary>
public string Password { get; set; }
/// <summary>
/// Add the Basic Authentication Header to each outgoing request
/// </summary>
/// <param name="request">The outgoing request</param>
/// <param name="cancellationToken">A token to cancel the operation</param>
/// <returns></returns>
public override Task ProcessHttpRequestAsync(HttpRequestMessage request,
CancellationToken cancellationToken)
{
if (request == null)
{
throw new ArgumentNullException("request");
}
// Add username and password to "Basic" header of each request.
request.Headers.Authorization = new AuthenticationHeaderValue("Basic",
Convert.ToBase64String(Encoding.UTF8.GetBytes(string.Format(
CultureInfo.InvariantCulture,
"{0}:{1}",
UserName,
Password).ToCharArray())));
return PlatformTaskEx.FromResult(null);
}
}
}
|
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for license information.
using System;
using System.Globalization;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace Microsoft.Rest
{
/// <summary>
/// Basic Auth credentials for use with a REST Service Client.
/// </summary>
public class BasicAuthenticationCredentials : ServiceClientCredentials
{
/// <summary>
/// Basic auth username.
/// </summary>
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming",
"CA1702:CompoundWordsShouldBeCasedCorrectly", MessageId = "Username")]
public string Username { get; set; }
/// <summary>
/// Basic auth password.
/// </summary>
public string Password { get; set; }
/// <summary>
/// Add the Basic Authentication Header to each outgoing request
/// </summary>
/// <param name="request">The outgoing request</param>
/// <param name="cancellationToken">A token to cancel the operation</param>
/// <returns></returns>
public override Task ProcessHttpRequestAsync(HttpRequestMessage request,
CancellationToken cancellationToken)
{
if (request == null)
{
throw new ArgumentNullException("request");
}
// Add username and password to "Basic" header of each request.
request.Headers.Authorization = new AuthenticationHeaderValue("Basic",
Convert.ToBase64String(Encoding.UTF8.GetBytes(string.Format(
CultureInfo.InvariantCulture,
"{0}:{1}",
Username,
Password).ToCharArray())));
return PlatformTaskEx.FromResult(null);
}
}
}
|
mit
|
C#
|
416d7d59f02823e032202fd959dfb40c7532fd3b
|
Fix negative hue
|
treehopper-electronics/treehopper-sdk,treehopper-electronics/treehopper-sdk,treehopper-electronics/treehopper-sdk,treehopper-electronics/treehopper-sdk,treehopper-electronics/treehopper-sdk,treehopper-electronics/treehopper-sdk
|
NET/Libraries/Treehopper.Libraries/Utilities/ColorConverter.cs
|
NET/Libraries/Treehopper.Libraries/Utilities/ColorConverter.cs
|
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Text;
namespace Treehopper.Libraries.Utilities
{
static class ColorConverter
{
/// <summary>
/// Construct a color from HSL values
/// </summary>
/// <param name="hue">The hue, in degrees (0-360 mod)</param>
/// <param name="saturation">The saturation percentage, from 0 to 100</param>
/// <param name="luminance">The luminance percentage, from 0 to 100</param>
/// <returns></returns>
public static Color FromHsl(float hue, float saturation, float luminance)
{
var h = Math.Max((hue % 360) / 360.0f, 0);
var s = saturation / 100.0f;
var l = luminance / 100.0f;
float r, g, b;
if (s == 0)
{
r = g = b = l; // achromatic
}
else
{
var q = l < 0.5 ? l * (1 + s) : l + s - l * s;
var p = 2 * l - q;
r = hue2rgb(p, q, h + 1f / 3f);
g = hue2rgb(p, q, h);
b = hue2rgb(p, q, h - 1f / 3f);
}
return Color.FromArgb((int)Math.Round(r * 255), (int)Math.Round(g * 255), (int)Math.Round(b * 255));
}
private static float hue2rgb(float p, float q, float t)
{
if (t < 0) t += 1;
if (t > 1) t -= 1;
if (t < 1d / 6) return p + (q - p) * 6f * t;
if (t < 1d / 2) return q;
if (t < 2d / 3) return p + (q - p) * (2f / 3f - t) * 6f;
return p;
}
}
}
|
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Text;
namespace Treehopper.Libraries.Utilities
{
static class ColorConverter
{
/// <summary>
/// Construct a color from HSL values
/// </summary>
/// <param name="hue">The hue, in degrees (0-360 mod)</param>
/// <param name="saturation">The saturation percentage, from 0 to 100</param>
/// <param name="luminance">The luminance percentage, from 0 to 100</param>
/// <returns></returns>
public static Color FromHsl(float hue, float saturation, float luminance)
{
var h = hue % 360 / 360.0f;
var s = saturation / 100.0f;
var l = luminance / 100.0f;
float r, g, b;
if (s == 0)
{
r = g = b = l; // achromatic
}
else
{
var q = l < 0.5 ? l * (1 + s) : l + s - l * s;
var p = 2 * l - q;
r = hue2rgb(p, q, h + 1f / 3f);
g = hue2rgb(p, q, h);
b = hue2rgb(p, q, h - 1f / 3f);
}
return Color.FromArgb((int)Math.Round(r * 255), (int)Math.Round(g * 255), (int)Math.Round(b * 255));
}
private static float hue2rgb(float p, float q, float t)
{
if (t < 0) t += 1;
if (t > 1) t -= 1;
if (t < 1d / 6) return p + (q - p) * 6f * t;
if (t < 1d / 2) return q;
if (t < 2d / 3) return p + (q - p) * (2f / 3f - t) * 6f;
return p;
}
}
}
|
mit
|
C#
|
a197791e7f7fb2ef3f9bff37b46845910e7bc881
|
use PropertyName of JsonPropertyAttribute to map attributes.
|
eoin55/HoneyBear.HalClient
|
Src/HoneyBear.HalClient/Models/ResourceConverterExtenstions.cs
|
Src/HoneyBear.HalClient/Models/ResourceConverterExtenstions.cs
|
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using Newtonsoft.Json.Linq;
namespace HoneyBear.HalClient.Models
{
/// <summary>
/// Contains a set of IResource extensions.
/// </summary>
public static class ResourceConverterExtenstions
{
internal static T Data<T>(this IResource source)
where T : class, new()
{
var data = new T();
var dataType = typeof(T);
foreach (var property in dataType.GetProperties())
{
var propertyName = property.Name;
var jsonPropertyAttribute = property.GetCustomAttributes(false).OfType<Newtonsoft.Json.JsonPropertyAttribute>().FirstOrDefault();
if (jsonPropertyAttribute != null && !string.IsNullOrEmpty(jsonPropertyAttribute.PropertyName))
{
propertyName = jsonPropertyAttribute.PropertyName;
}
var pair = source.FirstOrDefault(p => p.Key.Equals(propertyName, StringComparison.InvariantCultureIgnoreCase));
if (pair.Key == null)
continue;
var propertyType = property.PropertyType;
object value;
var complex = pair.Value as JObject;
var array = pair.Value as JArray;
if (complex != null)
value = complex.ToObject(propertyType);
else if (array != null)
value = array.ToObject(propertyType);
else if (pair.Value != null)
value = TypeDescriptor.GetConverter(propertyType).ConvertFromInvariantString(pair.Value.ToString());
else
value = null;
property.SetValue(data, value, null);
}
return data;
}
/// <summary>
/// Deserialises a list of resources into a given type.
/// </summary>
/// <param name="source">The list of resources.</param>
/// <typeparam name="T">The type to deserialise the resources into.</typeparam>
/// <returns>A list of deserialised POCOs.</returns>
public static IEnumerable<T> Data<T>(this IEnumerable<IResource<T>> source)
where T : class, new()
=> source.Select(s => s.Data);
}
}
|
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using Newtonsoft.Json.Linq;
namespace HoneyBear.HalClient.Models
{
/// <summary>
/// Contains a set of IResource extensions.
/// </summary>
public static class ResourceConverterExtenstions
{
internal static T Data<T>(this IResource source)
where T : class, new()
{
var data = new T();
var dataType = typeof(T);
foreach (var property in dataType.GetProperties())
{
var pair = source.FirstOrDefault(p => p.Key.Equals(property.Name, StringComparison.InvariantCultureIgnoreCase));
if (pair.Key == null)
continue;
var propertyType = dataType.GetProperty(property.Name).PropertyType;
object value;
var complex = pair.Value as JObject;
var array = pair.Value as JArray;
if (complex != null)
value = complex.ToObject(propertyType);
else if (array != null)
value = array.ToObject(propertyType);
else if (pair.Value != null)
value = TypeDescriptor.GetConverter(propertyType).ConvertFromInvariantString(pair.Value.ToString());
else
value = null;
property.SetValue(data, value, null);
}
return data;
}
/// <summary>
/// Deserialises a list of resources into a given type.
/// </summary>
/// <param name="source">The list of resources.</param>
/// <typeparam name="T">The type to deserialise the resources into.</typeparam>
/// <returns>A list of deserialised POCOs.</returns>
public static IEnumerable<T> Data<T>(this IEnumerable<IResource<T>> source)
where T : class, new()
=> source.Select(s => s.Data);
}
}
|
mit
|
C#
|
195d7a1190241e2b02169b946835a1aad821f191
|
Return a text/plain response for 500 errors
|
BrightstarDB/BrightstarDB,BrightstarDB/BrightstarDB,BrightstarDB/BrightstarDB,BrightstarDB/BrightstarDB
|
src/core/BrightstarDB.Server.Modules/CorsPipelinesExtension.cs
|
src/core/BrightstarDB.Server.Modules/CorsPipelinesExtension.cs
|
using System;
using System.Linq;
using BrightstarDB.Client;
using BrightstarDB.Dto;
using BrightstarDB.Server.Modules.Configuration;
using Nancy;
using Nancy.Bootstrapper;
using Nancy.Responses;
using Nancy.Responses.Negotiation;
namespace BrightstarDB.Server.Modules
{
public static class CorsPipelinesExtension
{
public static void EnableCors(this IPipelines pipelines, CorsConfiguration corsConfiguration)
{
pipelines.AfterRequest.AddItemToEndOfPipeline(ctx =>
{
UpdateResponseHeaders(ctx.Request, ctx.Response, corsConfiguration);
});
pipelines.OnError.AddItemToEndOfPipeline((ctx, exception) =>
{
if (exception == null)
{
// Nothing to serialize, just return default 500 response
return HttpStatusCode.InternalServerError;
}
Response response;
if (ctx.Request.Headers.Accept.Any(x => x.Item1.ToLowerInvariant().Contains("application/json")))
{
// Return the exception detail as JSON
response = new JsonResponse(new ExceptionDetailObject(exception),
new DefaultJsonSerializer()) {StatusCode = HttpStatusCode.InternalServerError};
}
else
{
// Return the exception message as text/plain
response = new TextResponse(HttpStatusCode.InternalServerError, exception.Message);
}
UpdateResponseHeaders(ctx.Request, response, corsConfiguration);
return response;
});
}
private static void UpdateResponseHeaders(Request request, Response response, CorsConfiguration corsConfiguration)
{
if (!request.Headers.Keys.Contains("Origin")) return;
response.WithHeader("Access-Control-Allow-Origin", corsConfiguration.AllowOrigin);
if (request.Method.Equals("OPTIONS"))
{
response
.WithHeader("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, PATCH, OPTIONS")
.WithHeader("Access-Control-Allow-Headers", "Accept, Origin, Content-type");
}
}
}
}
|
using System;
using System.Linq;
using BrightstarDB.Client;
using BrightstarDB.Dto;
using BrightstarDB.Server.Modules.Configuration;
using Nancy;
using Nancy.Bootstrapper;
using Nancy.Responses;
using Nancy.Responses.Negotiation;
namespace BrightstarDB.Server.Modules
{
public static class CorsPipelinesExtension
{
public static void EnableCors(this IPipelines pipelines, CorsConfiguration corsConfiguration)
{
pipelines.AfterRequest.AddItemToEndOfPipeline(ctx =>
{
UpdateResponseHeaders(ctx.Request, ctx.Response, corsConfiguration);
});
pipelines.OnError.AddItemToEndOfPipeline((ctx, exception) =>
{
if (exception != null)
{
if (ctx.Request.Headers.Accept.Any(x => x.Item1.ToLowerInvariant().Contains("application/json")))
{
// Return the exception detail as JSON
var jsonResponse = new JsonResponse(new ExceptionDetailObject(exception),
new DefaultJsonSerializer()) {StatusCode = HttpStatusCode.InternalServerError};
UpdateResponseHeaders(ctx.Request, jsonResponse, corsConfiguration);
return jsonResponse;
}
}
return HttpStatusCode.InternalServerError;
});
}
private static void UpdateResponseHeaders(Request request, Response response, CorsConfiguration corsConfiguration)
{
if (!request.Headers.Keys.Contains("Origin")) return;
response.WithHeader("Access-Control-Allow-Origin", corsConfiguration.AllowOrigin);
if (request.Method.Equals("OPTIONS"))
{
response
.WithHeader("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, PATCH, OPTIONS")
.WithHeader("Access-Control-Allow-Headers", "Accept, Origin, Content-type");
}
}
}
}
|
mit
|
C#
|
25268b1027975b629b4ebf20f1c026cc40af8543
|
Add LOGIN command tests.
|
jan-schubert/MailMessaging
|
Source/MailMessaging.Plain.IntegrationTest.Shared/_MailMessenger/Login.cs
|
Source/MailMessaging.Plain.IntegrationTest.Shared/_MailMessenger/Login.cs
|
using FluentAssertions;
using MailMessaging.Plain.Contracts;
using MailMessaging.Plain.Contracts.Commands;
using MailMessaging.Plain.Core;
using MailMessaging.Plain.Core.Commands;
using NUnit.Framework;
#if WinRT
using MailMessaging.Plain.WinRT;
#elif NET
using MailMessaging.Plain.Net;
#endif
namespace MailMessaging.Plain.IntegrationTest._MailMessenger
{
[TestFixture]
public class Login : TestBase
{
[Test]
public void ShouldConnectServer()
{
var account = new Account("127.0.0.1", 51234, false);
var tcpClient = new TcpClient();
var messenger = new MailMessenger(account, tcpClient);
messenger.Connect().Result.Should().Be(ConnectResult.Connected);
var response = messenger.Send(new LoginCommand(_tagService, "validUserName", "validPassword")).Result;
response.Result.Should().Be(ResponseResult.OK);
response.Message.Should().Be("A0001 OK LOGIN completed\r\n");
}
[TestCase("invalidUserName", "invalidPassword")]
[TestCase("validUserName", "invalidPassword")]
[TestCase("invalidUserName", "validPassword")]
public void ShouldReceiveNoResponseIfLoginDataAreInvalid(string userName, string invalidpassword)
{
var account = new Account("127.0.0.1", 51234, false);
var tcpClient = new TcpClient();
var messenger = new MailMessenger(account, tcpClient);
messenger.Connect().Result.Should().Be(ConnectResult.Connected);
var response = messenger.Send(new LoginCommand(_tagService, userName, invalidpassword)).Result;
response.Result.Should().Be(ResponseResult.NO);
response.Message.Should().Be("A0001 NO authentication failed\r\n");
}
}
}
|
using FluentAssertions;
using MailMessaging.Plain.Contracts;
using MailMessaging.Plain.Contracts.Commands;
using MailMessaging.Plain.Core;
using MailMessaging.Plain.Core.Commands;
using NUnit.Framework;
#if WinRT
using MailMessaging.Plain.WinRT;
#elif NET
using MailMessaging.Plain.Net;
#endif
namespace MailMessaging.Plain.IntegrationTest._MailMessenger
{
[TestFixture]
public class Login : TestBase
{
[Test]
public void ShouldConnectServer()
{
var account = new Account("127.0.0.1", 51234, false);
var tcpClient = new TcpClient();
var messenger = new MailMessenger(account, tcpClient);
messenger.Connect().Result.Should().Be(ConnectResult.Connected);
var response = messenger.Send(new LoginCommand(_tagService, "validUserName", "validPassword")).Result;
response.Result.Should().Be(ResponseResult.OK);
response.Message.Should().Be("A0001 OK LOGIN completed\r\n");
}
[Test]
public void ShouldConnectServerIfLoginDataAreInvalid()
{
var account = new Account("127.0.0.1", 51234, false);
var tcpClient = new TcpClient();
var messenger = new MailMessenger(account, tcpClient);
messenger.Connect().Result.Should().Be(ConnectResult.Connected);
var response = messenger.Send(new LoginCommand(_tagService, "invalidUserName", "invalidPassword")).Result;
response.Result.Should().Be(ResponseResult.NO);
response.Message.Should().Be("A0001 NO authentication failed\r\n");
}
}
}
|
apache-2.0
|
C#
|
6575b878f38a409fe59f7ff4e07d5bddf5365aa0
|
use _ instead of variable
|
nopara73/HiddenWallet,nopara73/HiddenWallet,nopara73/HiddenWallet,nopara73/HiddenWallet
|
WalletWasabi.Fluent/ViewModels/AddWallet/ConfirmRecoveryWordsViewModel.cs
|
WalletWasabi.Fluent/ViewModels/AddWallet/ConfirmRecoveryWordsViewModel.cs
|
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Reactive.Linq;
using System.Windows.Input;
using DynamicData;
using DynamicData.Binding;
using ReactiveUI;
using WalletWasabi.Blockchain.Keys;
using WalletWasabi.Wallets;
namespace WalletWasabi.Fluent.ViewModels.AddWallet
{
public class ConfirmRecoveryWordsViewModel : RoutableViewModel
{
private readonly ReadOnlyObservableCollection<RecoveryWordViewModel> _confirmationWords;
public ConfirmRecoveryWordsViewModel(NavigationStateViewModel navigationState, List<RecoveryWordViewModel> mnemonicWords, KeyManager keyManager, WalletManager walletManager)
: base(navigationState, NavigationTarget.DialogScreen)
{
var confirmationWordsSourceList = new SourceList<RecoveryWordViewModel>();
var finishCommandCanExecute =
confirmationWordsSourceList
.Connect()
.ObserveOn(RxApp.MainThreadScheduler)
.WhenValueChanged(x => x.IsConfirmed)
.Select(_ => confirmationWordsSourceList.Items.All(x => x.IsConfirmed));
NextCommand = ReactiveCommand.Create(
() =>
{
walletManager.AddWallet(keyManager);
ClearNavigation(NavigationTarget.DialogScreen);
},
finishCommandCanExecute);
CancelCommand = ReactiveCommand.Create(() => ClearNavigation(NavigationTarget.DialogScreen));
confirmationWordsSourceList
.Connect()
.ObserveOn(RxApp.MainThreadScheduler)
.OnItemAdded(x => x.Reset())
.Sort(SortExpressionComparer<RecoveryWordViewModel>.Ascending(x => x.Index))
.Bind(out _confirmationWords)
.Subscribe();
// Select 4 random words to confirm.
confirmationWordsSourceList.AddRange(mnemonicWords.OrderBy(x => new Random().NextDouble()).Take(4));
}
public ReadOnlyObservableCollection<RecoveryWordViewModel> ConfirmationWords => _confirmationWords;
public ICommand NextCommand { get; }
}
}
|
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Reactive.Linq;
using System.Windows.Input;
using DynamicData;
using DynamicData.Binding;
using ReactiveUI;
using WalletWasabi.Blockchain.Keys;
using WalletWasabi.Wallets;
namespace WalletWasabi.Fluent.ViewModels.AddWallet
{
public class ConfirmRecoveryWordsViewModel : RoutableViewModel
{
private readonly ReadOnlyObservableCollection<RecoveryWordViewModel> _confirmationWords;
public ConfirmRecoveryWordsViewModel(NavigationStateViewModel navigationState, List<RecoveryWordViewModel> mnemonicWords, KeyManager keyManager, WalletManager walletManager)
: base(navigationState, NavigationTarget.DialogScreen)
{
var confirmationWordsSourceList = new SourceList<RecoveryWordViewModel>();
var finishCommandCanExecute =
confirmationWordsSourceList
.Connect()
.ObserveOn(RxApp.MainThreadScheduler)
.WhenValueChanged(x => x.IsConfirmed)
.Select(x => confirmationWordsSourceList.Items.All(x => x.IsConfirmed));
NextCommand = ReactiveCommand.Create(
() =>
{
walletManager.AddWallet(keyManager);
ClearNavigation(NavigationTarget.DialogScreen);
},
finishCommandCanExecute);
CancelCommand = ReactiveCommand.Create(() => ClearNavigation(NavigationTarget.DialogScreen));
confirmationWordsSourceList
.Connect()
.ObserveOn(RxApp.MainThreadScheduler)
.OnItemAdded(x => x.Reset())
.Sort(SortExpressionComparer<RecoveryWordViewModel>.Ascending(x => x.Index))
.Bind(out _confirmationWords)
.Subscribe();
// Select 4 random words to confirm.
confirmationWordsSourceList.AddRange(mnemonicWords.OrderBy(x => new Random().NextDouble()).Take(4));
}
public ReadOnlyObservableCollection<RecoveryWordViewModel> ConfirmationWords => _confirmationWords;
public ICommand NextCommand { get; }
}
}
|
mit
|
C#
|
0096a21f6099571dc0b50e5bf60887b383d6d9a2
|
Format suggestions
|
nopara73/HiddenWallet,nopara73/HiddenWallet,nopara73/HiddenWallet,nopara73/HiddenWallet
|
WalletWasabi.Gui/Controls/TransactionDetails/Models/AddressAmountTuple.cs
|
WalletWasabi.Gui/Controls/TransactionDetails/Models/AddressAmountTuple.cs
|
using NBitcoin;
using System;
namespace WalletWasabi.Gui.Controls.TransactionDetails.Models
{
public readonly struct AddressAmountTuple : IEquatable<AddressAmountTuple>
{
public AddressAmountTuple(string address = default, Money amount = default, bool isEmpty = true)
{
Address = address;
Amount = amount;
IsEmpty = isEmpty;
}
public string Address { get; }
public Money Amount { get; }
private bool IsEmpty { get; }
public static bool operator ==(AddressAmountTuple x, AddressAmountTuple y) => x.Equals(y);
public static bool operator !=(AddressAmountTuple x, AddressAmountTuple y) => !(x == y);
public bool Equals(AddressAmountTuple other) =>
(IsEmpty, Amount, Address) == (other.IsEmpty, other.Amount, other.Address);
public override bool Equals(object other) =>
((AddressAmountTuple)other).Equals(this) == true;
public override int GetHashCode() =>
HashCode.Combine(IsEmpty, Amount, Address);
}
}
|
using NBitcoin;
using System;
namespace WalletWasabi.Gui.Controls.TransactionDetails.Models
{
public readonly struct AddressAmountTuple : IEquatable<AddressAmountTuple>
{
public AddressAmountTuple(string address = default(string), Money amount = default(Money), bool isEmpty = true)
{
Address = address;
Amount = amount;
IsEmpty = isEmpty;
}
public string Address { get; }
public Money Amount { get; }
private bool IsEmpty { get; }
public static bool operator ==(AddressAmountTuple x, AddressAmountTuple y) => x.Equals(y);
public static bool operator !=(AddressAmountTuple x, AddressAmountTuple y) => !(x == y);
public bool Equals(AddressAmountTuple other) =>
(IsEmpty, Amount, Address) == (other.IsEmpty, other.Amount, other.Address);
public override bool Equals(object other) =>
((AddressAmountTuple)other).Equals(this) == true;
public override int GetHashCode() =>
HashCode.Combine(IsEmpty, Amount, Address);
}
}
|
mit
|
C#
|
426958667df5750f4229065653c9d24e129921ea
|
add tests
|
NakedObjectsGroup/NakedObjectsFramework,NakedObjectsGroup/NakedObjectsFramework,NakedObjectsGroup/NakedObjectsFramework,NakedObjectsGroup/NakedObjectsFramework
|
Test/NakedObjects.Rest.Test.EndToEnd/ServiceActionInvokeDelete.cs
|
Test/NakedObjects.Rest.Test.EndToEnd/ServiceActionInvokeDelete.cs
|
// Copyright © Naked Objects Group Ltd ( http://www.nakedobjects.net).
// All Rights Reserved. This code released under the terms of the
// Microsoft Public License (MS-PL) ( http://opensource.org/licenses/ms-pl.html)
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace RestfulObjects.Test.EndToEnd {
[TestClass]
public class ServiceActionInvokeDelete : AbstractActionInvokeDelete {
protected override string BaseUrl {
get { return Urls.Services + Urls.WithActionService + Urls.Actions; }
}
protected override string FilePrefix {
get { return "Service-Action-Invoke-Delete-"; }
}
[TestMethod]
public void AttemptInvokePostActionWithDelete() {
DoAttemptInvokePostActionWithDelete();
}
[TestMethod]
public void AttemptInvokePutActionWithDelete() {
DoAttemptInvokePutActionWithDelete();
}
[TestMethod]
public void AttemptInvokeGetActionWithDelete() {
DoAttemptInvokeGetActionWithDelete();
}
}
}
|
// Copyright © Naked Objects Group Ltd ( http://www.nakedobjects.net).
// All Rights Reserved. This code released under the terms of the
// Microsoft Public License (MS-PL) ( http://opensource.org/licenses/ms-pl.html)
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace RestfulObjects.Test.EndToEnd {
[TestClass, Ignore]
public class ServiceActionInvokeDelete : AbstractActionInvokeDelete {
protected override string BaseUrl {
get { return Urls.Services + Urls.WithActionService + Urls.Actions; }
}
protected override string FilePrefix {
get { return "Service-Action-Invoke-Delete-"; }
}
[TestMethod]
public void AttemptInvokePostActionWithDelete() {
DoAttemptInvokePostActionWithDelete();
}
[TestMethod]
public void AttemptInvokePutActionWithDelete() {
DoAttemptInvokePutActionWithDelete();
}
[TestMethod]
public void AttemptInvokeGetActionWithDelete() {
DoAttemptInvokeGetActionWithDelete();
}
}
}
|
apache-2.0
|
C#
|
672c8e9e10cc6a9e8eaa02f3c5f34a0e544f596c
|
update comments
|
AsterNET/AsterNET,skrusty/AsterNET
|
Asterisk.2013/Asterisk.NET/Manager/Action/BlindTransferAction.cs
|
Asterisk.2013/Asterisk.NET/Manager/Action/BlindTransferAction.cs
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace AsterNET.Manager.Action
{
/// <summary>
/// Redirect all channels currently bridged to the specified channel to the specified destination.<br />
/// See <see target="_blank" href="https://wiki.asterisk.org/wiki/display/AST/Asterisk+16+ManagerAction_BlindTransfer">https://wiki.asterisk.org/wiki/display/AST/Asterisk+16+ManagerAction_BlindTransfer</see>
/// </summary>
class BlindTransferAction : ManagerAction
{
/// <summary>
/// Creates a new empty <see cref="BlindTransferAction"/>.
/// </summary>
public BlindTransferAction()
{
}
/// <summary>
/// Creates a new <see cref="BlindTransferAction"/>.
/// </summary>
/// <param name="channel"></param>
/// <param name="context"></param>
/// <param name="extension"></param>
public BlindTransferAction(string channel, string context, string extension)
{
Channel = channel;
Context = context;
Exten = extension;
}
/// <summary>
/// Get the name of this action, i.e. "BlindTransfer".
/// </summary>
public override string Action
{
get { return "BlindTransfer"; }
}
/// <summary>
/// Gets or sets the channel.
/// </summary>
public string Channel { get; set; }
/// <summary>
/// Gets or sets the context.
/// </summary>
public string Context { get; set; }
/// <summary>
/// Gets or sets the extension.
/// </summary>
public string Exten { get; set; }
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace AsterNET.Manager.Action
{
/// <summary>
/// Redirect all channels currently bridged to the specified channel to the specified destination.
///
/// See <see target="_blank" href="https://wiki.asterisk.org/wiki/display/AST/Asterisk+16+ManagerAction_BlindTransfer">https://wiki.asterisk.org/wiki/display/AST/Asterisk+16+ManagerAction_BlindTransfer</see>
/// </summary>
class BlindTransferAction : ManagerAction
{
/// <summary>
/// Creates a new empty <see cref="BlindTransferAction"/>.
/// </summary>
public BlindTransferAction()
{
}
/// <summary>
/// Creates a new <see cref="BlindTransferAction"/>.
/// </summary>
/// <param name="channel"></param>
/// <param name="context"></param>
/// <param name="extension"></param>
public BlindTransferAction(string channel, string context, string extension)
{
Channel = channel;
Context = context;
Exten = extension;
}
/// <summary>
/// Get the name of this action, i.e. "BlindTransfer".
/// </summary>
public override string Action
{
get { return "BlindTransfer"; }
}
/// <summary>
/// Gets or sets the channel.
/// </summary>
public string Channel { get; set; }
/// <summary>
/// Gets or sets the context.
/// </summary>
public string Context { get; set; }
/// <summary>
/// Gets or sets the exten.
/// </summary>
public string Exten { get; set; }
}
}
|
mit
|
C#
|
2a1cf85c39eab095bc0d78ea5223e366927834fc
|
add null tag validation
|
SoftwareFans/AstroPhotoGallery,SoftwareFans/AstroPhotoGallery,SoftwareFans/AstroPhotoGallery
|
AstroPhotoGallery/AstroPhotoGallery/Controllers/TagController.cs
|
AstroPhotoGallery/AstroPhotoGallery/Controllers/TagController.cs
|
using AstroPhotoGallery.Extensions;
using AstroPhotoGallery.Models;
using PagedList;
using System.Data.Entity;
using System.Linq;
using System.Web.Mvc;
namespace AstroPhotoGallery.Controllers
{
public class TagController : Controller
{
//
// GET: Tag/ListPicsWithTag/id
public ActionResult ListPicsWithTag(int? id, int? page)
{
if (id == null)
{
this.AddNotification("No tag ID provided.", NotificationType.ERROR);
return RedirectToAction("Index", "Home");
}
using (var db = new GalleryDbContext())
{
var requestedTag = db.Tags
.Include(t => t.Pictures.Select(p => p.Tags))
.Include(t => t.Pictures.Select(p => p.PicUploader))
.FirstOrDefault(t => t.Id == id);
if (requestedTag == null)
{
this.AddNotification("Such a tag does not exist.", NotificationType.ERROR);
return RedirectToAction("Index", "Home");
}
//Get pictures from db
var pictures = db.Tags
.Include(t => t.Pictures.Select(p => p.Tags))
.Include(t => t.Pictures.Select(p => p.PicUploader))
.FirstOrDefault(t => t.Id == id)
.Pictures
.OrderByDescending(p => p.Id)
.ToList();
//Return the view
int pageSize = 8;
int pageNumber = (page ?? 1);
return View(pictures.ToPagedList(pageNumber, pageSize));
}
}
}
}
|
using AstroPhotoGallery.Extensions;
using AstroPhotoGallery.Models;
using PagedList;
using System.Data.Entity;
using System.Linq;
using System.Web.Mvc;
namespace AstroPhotoGallery.Controllers
{
public class TagController : Controller
{
//
// GET: Tag/ListPicsWithTag/id
public ActionResult ListPicsWithTag(int? id, int? page)
{
if (id == null)
{
this.AddNotification("No tag ID provided.", NotificationType.ERROR);
return RedirectToAction("Index", "Home");
}
using (var db = new GalleryDbContext())
{
//Get pictures from db
var pictures = db.Tags
.Include(t => t.Pictures.Select(p => p.Tags))
.Include(t => t.Pictures.Select(p => p.PicUploader))
.FirstOrDefault(t => t.Id == id)
.Pictures
.OrderByDescending(p => p.Id)
.ToList();
//Return the view
int pageSize = 8;
int pageNumber = (page ?? 1);
return View(pictures.ToPagedList(pageNumber, pageSize));
}
}
}
}
|
mit
|
C#
|
1d63786674916e476aecfa163a3f7ee9ff97f217
|
Update CommentsDisqus.cshtml
|
Shazwazza/Articulate,readingdancer/Articulate,readingdancer/Articulate,Shazwazza/Articulate,readingdancer/Articulate,Shazwazza/Articulate
|
src/Articulate.Web/App_Plugins/Articulate/Themes/VAPOR/Views/Partials/CommentsDisqus.cshtml
|
src/Articulate.Web/App_Plugins/Articulate/Themes/VAPOR/Views/Partials/CommentsDisqus.cshtml
|
@model Articulate.Models.PostModel
@if (Model.DisqusShortName.IsNullOrWhiteSpace())
{
<p>
<em>
To enable comments sign up for a <a href="http://disqus.com" target="_blank">Disqus</a> account and
enter your Disqus shortname in the Articulate node settings.
</em>
</p>
}
else
{
<div id="disqus_thread">
<script type="text/javascript">
/** ENTER DISQUS SHORTNAME HERE **/
var disqus_shortname = '@Model.DisqusShortName';
/** DO NOT MODIFY BELOW THIS LINE **/
var disqus_identifier = '@Model.GetKey()';
var disqus_url = '@Model.UrlWithDomain()';
(function () {
var dsq = document.createElement('script'); dsq.type = 'text/javascript'; dsq.async = true;
dsq.src = '//' + disqus_shortname + '.disqus.com/embed.js';
(document.getElementsByTagName('head')[0] || document.getElementsByTagName('body')[0]).appendChild(dsq);
})();
</script>
<noscript>
Please enable JavaScript to view the <a href="http://disqus.com/?ref_noscript">comments powered by Disqus.</a>
</noscript>
<a href="http://disqus.com" class="dsq-brlink">
comments powered by <span class="logo-disqus">Disqus</span>
</a>
</div>
}
|
@model Articulate.Models.PostModel
@if (Model.DisqusShortName.IsNullOrWhiteSpace())
{
<p>
<em>
To enable comments sign up for a <a href="http://disqus.com" target="_blank">Disqus</a> account and
enter your Disqus shortname in the Articulate node settings.
</em>
</p>
}
else
{
<div id="disqus_thread">
<script type="text/javascript">
/** ENTER DISQUS SHORTNAME HERE **/
var disqus_shortname = '@Model.DisqusShortName';
/** DO NOT MODIFY BELOW THIS LINE **/
var disqus_identifier = '@Model.Id';
var disqus_url = '@Model.UrlWithDomain()';
(function () {
var dsq = document.createElement('script'); dsq.type = 'text/javascript'; dsq.async = true;
dsq.src = '//' + disqus_shortname + '.disqus.com/embed.js';
(document.getElementsByTagName('head')[0] || document.getElementsByTagName('body')[0]).appendChild(dsq);
})();
</script>
<noscript>
Please enable JavaScript to view the <a href="http://disqus.com/?ref_noscript">comments powered by Disqus.</a>
</noscript>
<a href="http://disqus.com" class="dsq-brlink">
comments powered by <span class="logo-disqus">Disqus</span>
</a>
</div>
}
|
mit
|
C#
|
2aab8b9e228f3bb4ed835fc2a6016a3d6b1a75a3
|
add decomposed and disassembled instruction lists
|
carterjones/nouzuru,carterjones/nouzuru
|
Nouzuru/Page.cs
|
Nouzuru/Page.cs
|
namespace Nouzuru
{
using System;
using System.Collections.Generic;
using Bunseki;
using Distorm3cs;
/// <summary>
/// Represents a memory page.
/// </summary>
public class Page
{
/// <summary>
/// Gets or sets the base address of the memory page.
/// </summary>
public IntPtr Address { get; set; }
/// <summary>
/// Gets or sets the data stored within the memory page.
/// </summary>
public byte[] Data { get; set; }
/// <summary>
/// Gets or sets the instructions found within the memory page.
/// </summary>
public List<Instruction> Instructions { get; set; }
/// <summary>
/// Gets or sets the disassembled instructions found within the memory page.
/// </summary>
public List<string> InstructionsDisassembled { get; set; }
/// <summary>
/// Gets or sets the decomposed instructions found within the memory page.
/// </summary>
public Distorm.DInst[] InstructionsDecomposed { get; set; }
/// <summary>
/// Gets the size of the memory page.
/// </summary>
public uint Size
{
get { return (uint)this.Data.Length; }
}
public bool Disassemble(Distorm.DecodeType decodeType)
{
if (this.Data.Length == 0)
{
return false;
}
if (this.InstructionsDisassembled.Count != 0)
{
this.InstructionsDisassembled = Distorm.Disassemble(this.Data, (ulong)Address.ToInt64(), decodeType);
if (this.InstructionsDisassembled.Count == 0)
{
return false;
}
}
if (this.InstructionsDecomposed.Length != 0)
{
this.InstructionsDecomposed = Distorm.Decompose(this.Data, (ulong)Address.ToInt64(), decodeType);
if (this.InstructionsDecomposed.Length == 0)
{
return false;
}
}
return true;
}
}
}
|
namespace Nouzuru
{
using System;
using System.Collections.Generic;
using Bunseki;
using Distorm3cs;
/// <summary>
/// Represents a memory page.
/// </summary>
public class Page
{
/// <summary>
/// Gets or sets the base address of the memory page.
/// </summary>
public IntPtr Address { get; set; }
/// <summary>
/// Gets or sets the data stored within the memory page.
/// </summary>
public byte[] Data { get; set; }
/// <summary>
/// Gets or sets the instructions found within the memory page.
/// </summary>
public List<Instruction> Instructions { get; set; }
/// <summary>
/// Gets the size of the memory page.
/// </summary>
public uint Size
{
get { return (uint)this.Data.Length; }
}
public bool Disassemble(Distorm.DecodeType decodeType)
{
if (this.Data.Length == 0)
{
return false;
}
if (this.InstructionsDisassembled.Count != 0)
{
this.InstructionsDisassembled = Distorm.Disassemble(this.Data, (ulong)Address.ToInt64(), decodeType);
if (this.InstructionsDisassembled.Count == 0)
{
return false;
}
}
if (this.InstructionsDecomposed.Length != 0)
{
this.InstructionsDecomposed = Distorm.Decompose(this.Data, (ulong)Address.ToInt64(), decodeType);
if (this.InstructionsDecomposed.Length == 0)
{
return false;
}
}
return true;
}
}
}
|
bsd-2-clause
|
C#
|
1d0613967b84476391b7c4dfe480555223f6b43c
|
Update assembly metadata
|
ridercz/AutoACME
|
Altairis.AutoACME.Configuration/Properties/AssemblyInfo.cs
|
Altairis.AutoACME.Configuration/Properties/AssemblyInfo.cs
|
using System.Reflection;
[assembly: AssemblyTitle("Altairis AutoACME Configuration")]
[assembly: AssemblyDescription("Configuration store for ACME certificate management")]
[assembly: AssemblyCompany("Alairis, s. r. o.")]
[assembly: AssemblyProduct("Altairis AutoACME")]
[assembly: AssemblyCopyright("Copyright © Altairis, 2017")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
|
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("Altairis.AutoACME.Configuration")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("Altairis.AutoACME.Configuration")]
[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("bd224f53-b4c4-466e-9ab0-d5d6da9927f0")]
// 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")]
|
mit
|
C#
|
9a83ebb0ccd185ee331390b570069443370c7e3e
|
Increase version of assembly
|
rjasica/sign
|
sign/Properties/AssemblyInfo.cs
|
sign/Properties/AssemblyInfo.cs
|
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using CommandLine;
[assembly: AssemblyTitle("sign")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("sign")]
[assembly: AssemblyCopyright("Copyright © Rafał Jasica 2014")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
[assembly: ComVisible(false)]
[assembly: Guid("82af63f5-2fba-4c28-9997-9bb244bd7863")]
[assembly: AssemblyVersion("1.1.4.0")]
[assembly: AssemblyFileVersion("1.1.4.0")]
[assembly: AssemblyInformationalVersionAttribute("1.1.4")]
[assembly: AssemblyLicense(
"This is free software. You may redistribute copies of it under the terms of",
"the MIT License <http://www.opensource.org/licenses/mit-license.php>.")]
|
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using CommandLine;
[assembly: AssemblyTitle("sign")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("sign")]
[assembly: AssemblyCopyright("Copyright © Rafał Jasica 2014")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
[assembly: ComVisible(false)]
[assembly: Guid("82af63f5-2fba-4c28-9997-9bb244bd7863")]
[assembly: AssemblyVersion("1.1.2.0")]
[assembly: AssemblyFileVersion("1.1.2.0")]
[assembly: AssemblyInformationalVersionAttribute("1.1.2")]
[assembly: AssemblyLicense(
"This is free software. You may redistribute copies of it under the terms of",
"the MIT License <http://www.opensource.org/licenses/mit-license.php>.")]
|
mit
|
C#
|
c0c39b60d625ac775cd677a710939cd76dd8c551
|
Fix surface tester.
|
eylvisaker/AgateLib
|
AgateLib.Tests/Tests.WinForms/DisplayTests/SurfaceTester/SurfaceTester.cs
|
AgateLib.Tests/Tests.WinForms/DisplayTests/SurfaceTester/SurfaceTester.cs
|
// The contents of this file are public domain.
// You may use them as you wish.
//
using System;
using System.Collections.Generic;
using System.Threading;
using System.Windows.Forms;
using AgateLib;
using AgateLib.Platform.WinForms.ApplicationModels;
namespace AgateLib.Testing.DisplayTests.SurfaceTester
{
class SurfaceTester : IDiscreteAgateTest
{
public string Name { get { return "Surface Tester"; } }
public string Category { get { return "Display"; } }
public void Main(string[] args)
{
using (var model = new PassiveModel(args))
{
model.Parameters.AssetLocations.Path = "Assets";
model.Run(() =>
{
frmSurfaceTester form = new frmSurfaceTester();
form.Show();
int frame = 0;
while (form.Visible)
{
form.UpdateDisplay();
frame++;
}
});
}
}
}
}
|
// The contents of this file are public domain.
// You may use them as you wish.
//
using System;
using System.Collections.Generic;
using System.Threading;
using System.Windows.Forms;
using AgateLib;
using AgateLib.Platform.WinForms.ApplicationModels;
namespace AgateLib.Testing.DisplayTests.SurfaceTester
{
class SurfaceTester : IDiscreteAgateTest
{
public string Name { get { return "Surface Tester"; } }
public string Category { get { return "Display"; } }
public void Main(string[] args)
{
using (var model = new PassiveModel(args))
{
model.Run(() =>
{
frmSurfaceTester form = new frmSurfaceTester();
form.Show();
int frame = 0;
while (form.Visible)
{
form.UpdateDisplay();
frame++;
}
});
}
}
}
}
|
mit
|
C#
|
5a6c1baf7463e85cb4c2e8344a518aeda94de600
|
Add unit test to save and VALIDATE file in given non-en-US culture.
|
jongleur1983/ClosedXML,JavierJJJ/ClosedXML,ClosedXML/ClosedXML,igitur/ClosedXML,b0bi79/ClosedXML,clinchergt/ClosedXML
|
ClosedXML_Tests/Excel/Saving/SavingTests.cs
|
ClosedXML_Tests/Excel/Saving/SavingTests.cs
|
using ClosedXML.Excel;
using NUnit.Framework;
using System.Globalization;
using System.IO;
using System.Threading;
namespace ClosedXML_Tests.Excel.Saving
{
[TestFixture]
public class SavingTests
{
[Test]
public void CanSuccessfullySaveFileMultipleTimes()
{
using (var wb = new XLWorkbook())
{
var sheet = wb.Worksheets.Add("TestSheet");
var memoryStream = new MemoryStream();
wb.SaveAs(memoryStream, true);
for (int i = 1; i <= 3; i++)
{
sheet.Cell(i, 1).Value = "test" + i;
wb.SaveAs(memoryStream, true);
}
memoryStream.Close();
memoryStream.Dispose();
}
}
[Test]
public void CanSaveAndValidateFileInAnotherCulture()
{
string[] cultures = new string[] { "it", "de-AT" };
foreach (var culture in cultures)
{
Thread.CurrentThread.CurrentCulture = CultureInfo.GetCultureInfo(culture);
using (var wb = new XLWorkbook())
{
var memoryStream = new MemoryStream();
var ws = wb.Worksheets.Add("Sheet1");
wb.SaveAs(memoryStream, true);
}
}
}
}
}
|
using ClosedXML.Excel;
using NUnit.Framework;
using System.IO;
namespace ClosedXML_Tests.Excel.Saving
{
[TestFixture]
public class SavingTests
{
[Test]
public void CanSuccessfullySaveFileMultipleTimes()
{
using (var wb = new XLWorkbook())
{
var sheet = wb.Worksheets.Add("TestSheet");
var memoryStream = new MemoryStream();
wb.SaveAs(memoryStream, true);
for (int i = 1; i <= 3; i++)
{
sheet.Cell(i, 1).Value = "test" + i;
wb.SaveAs(memoryStream, true);
}
memoryStream.Close();
memoryStream.Dispose();
}
}
}
}
|
mit
|
C#
|
a7ae7c580f9a8e85ecee3194de752fc7584f2893
|
Change JSON URL: InternetExplorer -> MicrosoftEdge
|
mayuki/PlatformStatusTracker,mayuki/PlatformStatusTracker,mayuki/PlatformStatusTracker
|
PlatformStatusTracker/PlatformStatusTracker.Core/Model/DataUpdateAgent.cs
|
PlatformStatusTracker/PlatformStatusTracker.Core/Model/DataUpdateAgent.cs
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using PlatformStatusTracker.Core.Enum;
using PlatformStatusTracker.Core.Repository;
namespace PlatformStatusTracker.Core.Model
{
public class DataUpdateAgent
{
private IStatusDataRepository _statusDataRepository;
public DataUpdateAgent(IStatusDataRepository repository)
{
_statusDataRepository = repository;
}
public async Task UpdateAllAsync()
{
await Task.WhenAll(UpdateChromiumAsync(), UpdateModernIeAsync(), UpdateWebKitJavaScriptCoreAsync(), UpdateWebKitWebCoreAsync());
}
public async Task UpdateChromiumAsync()
{
var httpClient = new HttpClient();
var data = await httpClient.GetStringAsync("http://www.chromestatus.com/features.json");
await _statusDataRepository.InsertAsync(StatusDataType.Chromium, DateTime.UtcNow.Date, data);
}
public async Task UpdateModernIeAsync()
{
var httpClient = new HttpClient();
var data = await httpClient.GetStringAsync("https://raw.githubusercontent.com/MicrosoftEdge/Status/production/app/static/ie-status.json");
await _statusDataRepository.InsertAsync(StatusDataType.InternetExplorer, DateTime.UtcNow.Date, data);
}
public async Task UpdateWebKitWebCoreAsync()
{
var httpClient = new HttpClient();
var data = await httpClient.GetStringAsync("http://svn.webkit.org/repository/webkit/trunk/Source/WebCore/features.json");
await _statusDataRepository.InsertAsync(StatusDataType.WebKitWebCore, DateTime.UtcNow.Date, data);
}
public async Task UpdateWebKitJavaScriptCoreAsync()
{
var httpClient = new HttpClient();
var data = await httpClient.GetStringAsync("http://svn.webkit.org/repository/webkit/trunk/Source/JavaScriptCore/features.json");
await _statusDataRepository.InsertAsync(StatusDataType.WebKitJavaScriptCore, DateTime.UtcNow.Date, data);
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using PlatformStatusTracker.Core.Enum;
using PlatformStatusTracker.Core.Repository;
namespace PlatformStatusTracker.Core.Model
{
public class DataUpdateAgent
{
private IStatusDataRepository _statusDataRepository;
public DataUpdateAgent(IStatusDataRepository repository)
{
_statusDataRepository = repository;
}
public async Task UpdateAllAsync()
{
await Task.WhenAll(UpdateChromiumAsync(), UpdateModernIeAsync(), UpdateWebKitJavaScriptCoreAsync(), UpdateWebKitWebCoreAsync());
}
public async Task UpdateChromiumAsync()
{
var httpClient = new HttpClient();
var data = await httpClient.GetStringAsync("http://www.chromestatus.com/features.json");
await _statusDataRepository.InsertAsync(StatusDataType.Chromium, DateTime.UtcNow.Date, data);
}
public async Task UpdateModernIeAsync()
{
var httpClient = new HttpClient();
var data = await httpClient.GetStringAsync("https://raw.githubusercontent.com/InternetExplorer/Status.IE/production/app/static/ie-status.json");
await _statusDataRepository.InsertAsync(StatusDataType.InternetExplorer, DateTime.UtcNow.Date, data);
}
public async Task UpdateWebKitWebCoreAsync()
{
var httpClient = new HttpClient();
var data = await httpClient.GetStringAsync("http://svn.webkit.org/repository/webkit/trunk/Source/WebCore/features.json");
await _statusDataRepository.InsertAsync(StatusDataType.WebKitWebCore, DateTime.UtcNow.Date, data);
}
public async Task UpdateWebKitJavaScriptCoreAsync()
{
var httpClient = new HttpClient();
var data = await httpClient.GetStringAsync("http://svn.webkit.org/repository/webkit/trunk/Source/JavaScriptCore/features.json");
await _statusDataRepository.InsertAsync(StatusDataType.WebKitJavaScriptCore, DateTime.UtcNow.Date, data);
}
}
}
|
mit
|
C#
|
7abf54e3cde07357545514fe0c93ee4f1a4a5a01
|
Remove unused CompletedTask member
|
DotNetAnalyzers/StyleCopAnalyzers
|
StyleCop.Analyzers/StyleCop.Analyzers/AnalyzerConstants.cs
|
StyleCop.Analyzers/StyleCop.Analyzers/AnalyzerConstants.cs
|
namespace StyleCop.Analyzers
{
using System.Threading.Tasks;
using Microsoft.CodeAnalysis;
internal static class AnalyzerConstants
{
static AnalyzerConstants()
{
#if DEBUG
// In DEBUG builds, the tests are enabled to simplify development and testing.
DisabledNoTests = true;
#else
DisabledNoTests = false;
#endif
}
/// <summary>
/// Gets a reference value which can be passed to
/// <see cref="DiagnosticDescriptor(string, string, string, string, DiagnosticSeverity, bool, string, string, string[])"/>
/// to disable a diagnostic which is currently untested.
/// </summary>
/// <value>
/// A reference value which can be passed to
/// <see cref="DiagnosticDescriptor(string, string, string, string, DiagnosticSeverity, bool, string, string, string[])"/>
/// to disable a diagnostic which is currently untested.
/// </value>
internal static bool DisabledNoTests { get; }
/// <summary>
/// Gets a reference value which can be passed to
/// <see cref="DiagnosticDescriptor(string, string, string, string, DiagnosticSeverity, bool, string, string, string[])"/>
/// to indicate that the diagnostic should be enabled by default.
/// </summary>
/// <value>
/// A reference value which can be passed to
/// <see cref="DiagnosticDescriptor(string, string, string, string, DiagnosticSeverity, bool, string, string, string[])"/>
/// to indicate that the diagnostic should be enabled by default.
/// </value>
internal static bool EnabledByDefault => true;
}
}
|
namespace StyleCop.Analyzers
{
using System.Threading.Tasks;
using Microsoft.CodeAnalysis;
internal static class AnalyzerConstants
{
static AnalyzerConstants()
{
#if DEBUG
// In DEBUG builds, the tests are enabled to simplify development and testing.
DisabledNoTests = true;
#else
DisabledNoTests = false;
#endif
}
/// <summary>
/// Gets a reference value which can be passed to
/// <see cref="DiagnosticDescriptor(string, string, string, string, DiagnosticSeverity, bool, string, string, string[])"/>
/// to disable a diagnostic which is currently untested.
/// </summary>
/// <value>
/// A reference value which can be passed to
/// <see cref="DiagnosticDescriptor(string, string, string, string, DiagnosticSeverity, bool, string, string, string[])"/>
/// to disable a diagnostic which is currently untested.
/// </value>
internal static bool DisabledNoTests { get; }
/// <summary>
/// Gets a reference value which can be passed to
/// <see cref="DiagnosticDescriptor(string, string, string, string, DiagnosticSeverity, bool, string, string, string[])"/>
/// to indicate that the diagnostic should be enabled by default.
/// </summary>
/// <value>
/// A reference value which can be passed to
/// <see cref="DiagnosticDescriptor(string, string, string, string, DiagnosticSeverity, bool, string, string, string[])"/>
/// to indicate that the diagnostic should be enabled by default.
/// </value>
internal static bool EnabledByDefault => true;
internal static Task CompletedTask { get; } = Task.FromResult(false);
}
}
|
mit
|
C#
|
86aa3b1cf425756873d1b25b3283415b3363c4cb
|
Fix font not loading in initial dialogue
|
Barleytree/NitoriWare,NitorInc/NitoriWare,Barleytree/NitoriWare,NitorInc/NitoriWare
|
Assets/Microgames/DatingSim/Scripts/DatingSimDialogueController.cs
|
Assets/Microgames/DatingSim/Scripts/DatingSimDialogueController.cs
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using TMPro;
public class DatingSimDialogueController : MonoBehaviour
{
public float introTextDelay;
[Tooltip("If set to >0 will slow down or speed up text advance to complete it in this time")]
public float introTextForceCompletionTime;
private TMP_Text textComp;
private AdvancingText textPlayer;
private float defaultTextSpeed;
void Start()
{
textComp = GetComponent<TMP_Text>();
textPlayer = GetComponent<AdvancingText>();
defaultTextSpeed = textPlayer.getAdvanceSpeed();
SetDialogue(DatingSimHelper.getSelectedCharacter().getLocalizedIntroDialogue());
textPlayer.enabled = false;
Invoke("EnableTextPlayer", introTextDelay);
}
void OnFontLocalized()
{
if (introTextForceCompletionTime > 0f)
{
float newSpeed = textPlayer.getTotalVisibleChars() / introTextForceCompletionTime;
textPlayer.setAdvanceSpeed(newSpeed);
}
}
void EnableTextPlayer()
{
textPlayer.enabled = true;
}
public void resetDialogueSpeed()
{
textPlayer.setAdvanceSpeed(defaultTextSpeed);
}
public void SetDialogue(string str)
{
textComp.text = str;
textComp.maxVisibleCharacters = 0;
textPlayer.resetAdvance();
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using TMPro;
public class DatingSimDialogueController : MonoBehaviour
{
public float introTextDelay;
[Tooltip("If set to >0 will slow down or speed up text advance to complete it in this time")]
public float introTextForceCompletionTime;
private TMP_Text textComp;
private AdvancingText textPlayer;
private float defaultTextSpeed;
void Start()
{
textComp = GetComponent<TMP_Text>();
textPlayer = GetComponent<AdvancingText>();
defaultTextSpeed = textPlayer.getAdvanceSpeed();
SetDialogue(DatingSimHelper.getSelectedCharacter().getLocalizedIntroDialogue());
if (introTextForceCompletionTime > 0f)
{
float newSpeed = textPlayer.getTotalVisibleChars() / introTextForceCompletionTime;
textPlayer.setAdvanceSpeed(newSpeed);
}
textPlayer.enabled = false;
Invoke("EnableTextPlayer", introTextDelay);
}
void EnableTextPlayer()
{
textPlayer.enabled = true;
}
public void resetDialogueSpeed()
{
textPlayer.setAdvanceSpeed(defaultTextSpeed);
}
public void SetDialogue(string str)
{
textComp.text = str;
textComp.maxVisibleCharacters = 0;
textPlayer.resetAdvance();
}
}
|
mit
|
C#
|
77b725ea8991748fd400675f35f83d9d7bcfeb1b
|
add a little something more +semver:patch
|
loqu8/GrooveApi
|
src/GrooveApi/GrooveClass1.cs
|
src/GrooveApi/GrooveClass1.cs
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace GrooveApi
{
class GrooveClass1
{
public GrooveClass1()
{
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace GrooveApi
{
class GrooveClass1
{
}
}
|
apache-2.0
|
C#
|
41c9cbb64332f1d0b965eea028e461160294c8fe
|
Add ReSharper to known words
|
nuke-build/nuke,nuke-build/nuke,nuke-build/nuke,nuke-build/nuke
|
source/Nuke.Common/Constants.cs
|
source/Nuke.Common/Constants.cs
|
// Copyright 2019 Maintainers of NUKE.
// Distributed under the MIT License.
// https://github.com/nuke-build/nuke/blob/master/LICENSE
using System;
using System.IO;
using System.Linq;
using JetBrains.Annotations;
using Nuke.Common.IO;
namespace Nuke.Common
{
internal static class Constants
{
internal static readonly string[] KnownWords =
{
"GitHub",
"GitVersion",
"MSBuild",
"NuGet",
"ReSharper"
};
internal const string ConfigurationFileName = ".nuke";
internal const string TargetsSeparator = "+";
internal const string InvokedTargetsParameterName = "Target";
internal const string SkippedTargetsParameterName = "Skip";
public const string VisualStudioDebugParameterName = "visual-studio-debug";
internal const string CompletionParameterName = "shell-completion";
[CanBeNull]
internal static AbsolutePath TryGetRootDirectoryFrom(string startDirectory)
{
return (AbsolutePath) FileSystemTasks.FindParentDirectory(
startDirectory,
predicate: x => x.GetFiles(ConfigurationFileName).Any());
}
internal static AbsolutePath GetTemporaryDirectory(AbsolutePath rootDirectory)
{
return rootDirectory / ".tmp";
}
internal static AbsolutePath GetCompletionFile(AbsolutePath rootDirectory)
{
var completionFileName = CompletionParameterName + ".yml";
return File.Exists(rootDirectory / completionFileName)
? rootDirectory / completionFileName
: GetTemporaryDirectory(rootDirectory) / completionFileName;
}
internal static AbsolutePath GetBuildAttemptFile(AbsolutePath rootDirectory)
{
return GetTemporaryDirectory(rootDirectory) / "build-attempt.log";
}
public static AbsolutePath GetVisualStudioDebugFile(AbsolutePath rootDirectory)
{
return GetTemporaryDirectory(rootDirectory) / $"{VisualStudioDebugParameterName}.log";
}
internal static AbsolutePath GetMissingPackageFile(AbsolutePath rootDirectory)
{
return GetTemporaryDirectory(rootDirectory) / "missing-package.log";
}
}
}
|
// Copyright 2019 Maintainers of NUKE.
// Distributed under the MIT License.
// https://github.com/nuke-build/nuke/blob/master/LICENSE
using System;
using System.IO;
using System.Linq;
using JetBrains.Annotations;
using Nuke.Common.IO;
namespace Nuke.Common
{
internal static class Constants
{
internal static readonly string[] KnownWords = { "GitHub", "NuGet", "MSBuild", "GitVersion" };
internal const string ConfigurationFileName = ".nuke";
internal const string TargetsSeparator = "+";
internal const string InvokedTargetsParameterName = "Target";
internal const string SkippedTargetsParameterName = "Skip";
public const string VisualStudioDebugParameterName = "visual-studio-debug";
internal const string CompletionParameterName = "shell-completion";
[CanBeNull]
internal static AbsolutePath TryGetRootDirectoryFrom(string startDirectory)
{
return (AbsolutePath) FileSystemTasks.FindParentDirectory(
startDirectory,
predicate: x => x.GetFiles(ConfigurationFileName).Any());
}
internal static AbsolutePath GetTemporaryDirectory(AbsolutePath rootDirectory)
{
return rootDirectory / ".tmp";
}
internal static AbsolutePath GetCompletionFile(AbsolutePath rootDirectory)
{
var completionFileName = CompletionParameterName + ".yml";
return File.Exists(rootDirectory / completionFileName)
? rootDirectory / completionFileName
: GetTemporaryDirectory(rootDirectory) / completionFileName;
}
internal static AbsolutePath GetBuildAttemptFile(AbsolutePath rootDirectory)
{
return GetTemporaryDirectory(rootDirectory) / "build-attempt.log";
}
public static AbsolutePath GetVisualStudioDebugFile(AbsolutePath rootDirectory)
{
return GetTemporaryDirectory(rootDirectory) / $"{VisualStudioDebugParameterName}.log";
}
internal static AbsolutePath GetMissingPackageFile(AbsolutePath rootDirectory)
{
return GetTemporaryDirectory(rootDirectory) / "missing-package.log";
}
}
}
|
mit
|
C#
|
6658c5aaa5cec9550e4c1b5538b7ee5a8ad014f2
|
Update MessagePackDeserializer.cs
|
tiksn/TIKSN-Framework
|
TIKSN.Core/Serialization/MessagePack/MessagePackDeserializer.cs
|
TIKSN.Core/Serialization/MessagePack/MessagePackDeserializer.cs
|
using System.IO;
using MsgPack.Serialization;
namespace TIKSN.Serialization.MessagePack
{
public class MessagePackDeserializer : DeserializerBase<byte[]>
{
private readonly SerializationContext _serializationContext;
public MessagePackDeserializer(SerializationContext serializationContext) =>
this._serializationContext = serializationContext;
protected override T DeserializeInternal<T>(byte[] serial)
{
var serializer = this._serializationContext.GetSerializer<T>();
using (var stream = new MemoryStream(serial))
{
return serializer.Unpack(stream);
}
}
}
}
|
using MsgPack.Serialization;
using System.IO;
namespace TIKSN.Serialization.MessagePack
{
public class MessagePackDeserializer : DeserializerBase<byte[]>
{
private readonly SerializationContext _serializationContext;
public MessagePackDeserializer(SerializationContext serializationContext)
{
_serializationContext = serializationContext;
}
protected override T DeserializeInternal<T>(byte[] serial)
{
var serializer = _serializationContext.GetSerializer<T>();
using (var stream = new MemoryStream(serial))
{
return serializer.Unpack(stream);
}
}
}
}
|
mit
|
C#
|
0ba9b3985256a4316f18b390bbb73ef883563cf4
|
Increase token timeout to 5 minutes
|
EricSten-MSFT/kudu,EricSten-MSFT/kudu,projectkudu/kudu,EricSten-MSFT/kudu,shibayan/kudu,projectkudu/kudu,shibayan/kudu,shibayan/kudu,projectkudu/kudu,projectkudu/kudu,EricSten-MSFT/kudu,EricSten-MSFT/kudu,shibayan/kudu,projectkudu/kudu,shibayan/kudu
|
Kudu.Core/Infrastructure/SecurityUtility.cs
|
Kudu.Core/Infrastructure/SecurityUtility.cs
|
using Microsoft.AspNetCore.DataProtection;
using Microsoft.Azure.Web.DataProtection;
using System;
using System.Security.Cryptography;
namespace Kudu.Core.Infrastructure
{
public static class SecurityUtility
{
private const string DefaultProtectorPurpose = "function-secrets";
private static string GenerateSecretString()
{
using (var rng = RandomNumberGenerator.Create())
{
byte[] data = new byte[40];
rng.GetBytes(data);
string secret = Convert.ToBase64String(data);
// Replace pluses as they are problematic as URL values
return secret.Replace('+', 'a');
}
}
public static Tuple<string, string>[] GenerateSecretStringsKeyPair(int number)
{
var unencryptedToEncryptedKeyPair = new Tuple<string, string>[number];
var protector = DataProtectionProvider.CreateAzureDataProtector().CreateProtector(DefaultProtectorPurpose);
for (int i = 0; i < number; i++)
{
string unencryptedKey = GenerateSecretString();
unencryptedToEncryptedKeyPair[i] = new Tuple<string, string>(unencryptedKey, protector.Protect(unencryptedKey));
}
return unencryptedToEncryptedKeyPair;
}
public static string DecryptSecretString(string content)
{
try
{
var protector = DataProtectionProvider.CreateAzureDataProtector().CreateProtector(DefaultProtectorPurpose);
return protector.Unprotect(content);
}
catch (CryptographicException ex)
{
throw new FormatException($"unable to decrypt {content}, the key is either invalid or malformed", ex);
}
}
public static string GenerateFunctionToken()
{
string siteName = ServerConfiguration.GetApplicationName();
string issuer = $"https://{siteName}.scm.azurewebsites.net";
string audience = $"https://{siteName}.azurewebsites.net/azurefunctions";
return JwtGenerator.GenerateToken(issuer, audience, expires: DateTime.UtcNow.AddMinutes(5));
}
}
}
|
using Microsoft.AspNetCore.DataProtection;
using Microsoft.Azure.Web.DataProtection;
using System;
using System.Security.Cryptography;
namespace Kudu.Core.Infrastructure
{
public static class SecurityUtility
{
private const string DefaultProtectorPurpose = "function-secrets";
private static string GenerateSecretString()
{
using (var rng = RandomNumberGenerator.Create())
{
byte[] data = new byte[40];
rng.GetBytes(data);
string secret = Convert.ToBase64String(data);
// Replace pluses as they are problematic as URL values
return secret.Replace('+', 'a');
}
}
public static Tuple<string, string>[] GenerateSecretStringsKeyPair(int number)
{
var unencryptedToEncryptedKeyPair = new Tuple<string, string>[number];
var protector = DataProtectionProvider.CreateAzureDataProtector().CreateProtector(DefaultProtectorPurpose);
for (int i = 0; i < number; i++)
{
string unencryptedKey = GenerateSecretString();
unencryptedToEncryptedKeyPair[i] = new Tuple<string, string>(unencryptedKey, protector.Protect(unencryptedKey));
}
return unencryptedToEncryptedKeyPair;
}
public static string DecryptSecretString(string content)
{
try
{
var protector = DataProtectionProvider.CreateAzureDataProtector().CreateProtector(DefaultProtectorPurpose);
return protector.Unprotect(content);
}
catch (CryptographicException ex)
{
throw new FormatException($"unable to decrypt {content}, the key is either invalid or malformed", ex);
}
}
public static string GenerateFunctionToken()
{
string siteName = ServerConfiguration.GetApplicationName();
string issuer = $"https://{siteName}.scm.azurewebsites.net";
string audience = $"https://{siteName}.azurewebsites.net/azurefunctions";
return JwtGenerator.GenerateToken(issuer, audience, expires: DateTime.UtcNow.AddMinutes(2));
}
}
}
|
apache-2.0
|
C#
|
920b590ae60a8f818ede5e966774860aa2fd8529
|
fix null value when creating dictionary from object
|
mikebridge/Liquid.NET,mikebridge/Liquid.NET,mikebridge/Liquid.NET
|
Liquid.NET/src/Constants/DictionaryValue.cs
|
Liquid.NET/src/Constants/DictionaryValue.cs
|
using System;
using System.Collections.Generic;
using System.Linq;
using Liquid.NET.Utils;
namespace Liquid.NET.Constants
{
// TODO: determine whether the keys should be case insensitive or not.
public class DictionaryValue : ExpressionConstant
{
private readonly IDictionary<String, Option<IExpressionConstant>> _value;
public DictionaryValue(IDictionary<String, Option<IExpressionConstant>> dictionary)
{
_value = dictionary;
}
public DictionaryValue(IDictionary<String, IExpressionConstant> dictionary)
{
_value = dictionary.ToDictionary(kv => kv.Key, v => v.Value == null? Option<IExpressionConstant>.None() : v.Value.ToOption());
}
public override object Value
{
get { return _value; }
}
public IDictionary<String, Option<IExpressionConstant>> DictValue { get { return _value; } }
// TODO: not sure what this should do
public override bool IsTrue
{
get { return _value != null; }
//get { return _value.Keys.Any(); }
}
public override string LiquidTypeName
{
get { return "hash"; }
}
public Option<IExpressionConstant> ValueAt(String key)
{
//Console.WriteLine("VALUE AT " + key);
// TODO: Fix this.
var result = _value.ContainsKey(key) ? _value[key] : new None<IExpressionConstant>(); // new Undefined(key);
//var result = _value.ContainsKey(key) ? _value[key] : FilterFactory.CreateUndefinedForType(typeof(StringValue))
//Console.WriteLine("IS " + result);
return result;
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using Liquid.NET.Utils;
namespace Liquid.NET.Constants
{
// TODO: determine whether the keys should be case insensitive or not.
public class DictionaryValue : ExpressionConstant
{
private readonly IDictionary<String, Option<IExpressionConstant>> _value;
public DictionaryValue(IDictionary<String, Option<IExpressionConstant>> dictionary)
{
_value = dictionary;
}
public DictionaryValue(IDictionary<String, IExpressionConstant> dictionary)
{
_value = dictionary.ToDictionary(kv => kv.Key, v => v.Value.ToOption());
}
public override object Value
{
get { return _value; }
}
public IDictionary<String, Option<IExpressionConstant>> DictValue { get { return _value; } }
// TODO: not sure what this should do
public override bool IsTrue
{
get { return _value != null; }
//get { return _value.Keys.Any(); }
}
public override string LiquidTypeName
{
get { return "hash"; }
}
public Option<IExpressionConstant> ValueAt(String key)
{
//Console.WriteLine("VALUE AT " + key);
// TODO: Fix this.
var result = _value.ContainsKey(key) ? _value[key] : new None<IExpressionConstant>(); // new Undefined(key);
//var result = _value.ContainsKey(key) ? _value[key] : FilterFactory.CreateUndefinedForType(typeof(StringValue))
//Console.WriteLine("IS " + result);
return result;
}
}
}
|
mit
|
C#
|
cfc9aa183370420ca5c7f14a70c64c42f41155b6
|
Resolve #286 - Fix usage of type property
|
csf-dev/ZPT-Sharp,csf-dev/ZPT-Sharp
|
ZptSharp.Impl/Rendering/ZptDocumentRendererForFilePathFactory.cs
|
ZptSharp.Impl/Rendering/ZptDocumentRendererForFilePathFactory.cs
|
using System;
using ZptSharp.Dom;
using Microsoft.Extensions.DependencyInjection;
namespace ZptSharp.Rendering
{
/// <summary>
/// Implementation of <see cref="IGetsZptDocumentRendererForFilePath"/> which uses a file path to
/// get a suitable implementation of <see cref="IRendersZptDocument"/>.
/// </summary>
public class ZptDocumentRendererForFilePathFactory : IGetsZptDocumentRendererForFilePath
{
readonly IServiceProvider serviceProvider;
IGetsDocumentReaderWriterForFile ReaderWriterFactory
=> serviceProvider.GetRequiredService<IGetsDocumentReaderWriterForFile>();
IGetsZptDocumentRenderer RendererFactory
=> serviceProvider.GetRequiredService<IGetsZptDocumentRenderer>();
/// <summary>
/// Gets the document renderer.
/// </summary>
/// <returns>The document renderer.</returns>
/// <param name="filePath">The path to a file which would be rendered by the renderer.</param>
public IRendersZptDocument GetDocumentRenderer(string filePath)
{
var readerWriterType = GetDocumentReaderWriterType(filePath);
return RendererFactory.GetDocumentRenderer(readerWriterType);
}
System.Type GetDocumentReaderWriterType(string filePath)
{
var readerWriter = ReaderWriterFactory.GetDocumentProvider(filePath);
if (readerWriter != null) return readerWriter.ResolvableType;
var message = String.Format(Resources.ExceptionMessage.CannotGetReaderWriterForFile,
filePath,
nameof(Hosting.EnvironmentRegistry));
throw new NoMatchingReaderWriterException(message);
}
/// <summary>
/// Initializes a new instance of the <see cref="ZptDocumentRendererForFilePathFactory"/> class.
/// </summary>
/// <param name="serviceProvider">Service provider.</param>
public ZptDocumentRendererForFilePathFactory(IServiceProvider serviceProvider)
{
this.serviceProvider = serviceProvider ?? throw new ArgumentNullException(nameof(serviceProvider));
}
}
}
|
using System;
using ZptSharp.Dom;
using Microsoft.Extensions.DependencyInjection;
namespace ZptSharp.Rendering
{
/// <summary>
/// Implementation of <see cref="IGetsZptDocumentRendererForFilePath"/> which uses a file path to
/// get a suitable implementation of <see cref="IRendersZptDocument"/>.
/// </summary>
public class ZptDocumentRendererForFilePathFactory : IGetsZptDocumentRendererForFilePath
{
readonly IServiceProvider serviceProvider;
IGetsDocumentReaderWriterForFile ReaderWriterFactory
=> serviceProvider.GetRequiredService<IGetsDocumentReaderWriterForFile>();
IGetsZptDocumentRenderer RendererFactory
=> serviceProvider.GetRequiredService<IGetsZptDocumentRenderer>();
/// <summary>
/// Gets the document renderer.
/// </summary>
/// <returns>The document renderer.</returns>
/// <param name="filePath">The path to a file which would be rendered by the renderer.</param>
public IRendersZptDocument GetDocumentRenderer(string filePath)
{
var readerWriterType = GetDocumentReaderWriterType(filePath);
return RendererFactory.GetDocumentRenderer(readerWriterType);
}
System.Type GetDocumentReaderWriterType(string filePath)
{
var readerWriter = ReaderWriterFactory.GetDocumentProvider(filePath);
if (readerWriter != null) return readerWriter.GetType();
var message = String.Format(Resources.ExceptionMessage.CannotGetReaderWriterForFile,
filePath,
nameof(Hosting.EnvironmentRegistry));
throw new NoMatchingReaderWriterException(message);
}
/// <summary>
/// Initializes a new instance of the <see cref="ZptDocumentRendererForFilePathFactory"/> class.
/// </summary>
/// <param name="serviceProvider">Service provider.</param>
public ZptDocumentRendererForFilePathFactory(IServiceProvider serviceProvider)
{
this.serviceProvider = serviceProvider ?? throw new ArgumentNullException(nameof(serviceProvider));
}
}
}
|
mit
|
C#
|
d807b5001e3be3aac743482139ebb61dfdd8797b
|
Remove the need to be Master to save/update file
|
DragonEyes7/ConcoursUBI17,DragonEyes7/ConcoursUBI17
|
Proto/Assets/Scripts/Time/TimeController.cs
|
Proto/Assets/Scripts/Time/TimeController.cs
|
using UnityEngine;
public class TimeController : MonoBehaviour
{
public MultipleDelegate Tick = new MultipleDelegate();
public MultipleDelegate End = new MultipleDelegate();
[SerializeField] private string _filePath;
[SerializeField] private int _penalizePlayerOnWrongTarget = 20;
int _Time, _maxTime = 30, _totalTime, _penalities = 0;
float _Timer;
bool _IsPlaying = false;
public int time
{
get { return _Time; }
set { _Time = value; }
}
public int maxTime
{
get { return _maxTime; }
}
public bool isPlaying
{
get { return _IsPlaying; }
set { _IsPlaying = value; }
}
void FixedUpdate()
{
_Timer += Time.deltaTime;
if (_Timer >= 1f && _IsPlaying) DoTick();
}
public void DoTick()
{
_Timer = 0;
_Time++;
_totalTime++;
Tick.Execute(_Time);
if (_Time == _maxTime)
{
//Game has ended stop countdown and show the players they f*cked up
FindObjectOfType<GameManager>().Defeat();
End.Execute(_Time);
End.Empty();
}
}
public void SaveTime()
{
var leaderboard = new Leaderboard(_filePath);
leaderboard.AddScore(new Score(PhotonNetwork.room.Name, _totalTime, _penalities));
leaderboard.Save();
}
public void WrongTargetIntercepted()
{
++_penalities;
_totalTime += _penalizePlayerOnWrongTarget;
}
public void SetMaxTime(int maxTime)
{
_maxTime = maxTime;
}
}
|
using UnityEngine;
public class TimeController : MonoBehaviour
{
public MultipleDelegate Tick = new MultipleDelegate();
public MultipleDelegate End = new MultipleDelegate();
[SerializeField] private string _filePath;
[SerializeField] private int _penalizePlayerOnWrongTarget = 20;
int _Time, _maxTime = 30, _totalTime, _penalities = 0;
float _Timer;
bool _IsPlaying = false;
public int time
{
get { return _Time; }
set { _Time = value; }
}
public int maxTime
{
get { return _maxTime; }
}
public bool isPlaying
{
get { return _IsPlaying; }
set { _IsPlaying = value; }
}
void FixedUpdate()
{
_Timer += Time.deltaTime;
if (_Timer >= 1f && _IsPlaying) DoTick();
}
public void DoTick()
{
_Timer = 0;
_Time++;
_totalTime++;
Tick.Execute(_Time);
if (_Time == _maxTime)
{
//Game has ended stop countdown and show the players they f*cked up
FindObjectOfType<GameManager>().Defeat();
End.Execute(_Time);
End.Empty();
}
}
public void SaveTime()
{
if (PhotonNetwork.isMasterClient)
{
var leaderboard = new Leaderboard(_filePath);
leaderboard.AddScore(new Score(PhotonNetwork.room.Name, _totalTime, _penalities));
leaderboard.Save();
}
}
public void WrongTargetIntercepted()
{
++_penalities;
_totalTime += _penalizePlayerOnWrongTarget;
}
public void SetMaxTime(int maxTime)
{
_maxTime = maxTime;
}
}
|
mit
|
C#
|
84fa6e0abf1c015e1a657a5aee89e52fcc067600
|
Convert to new Visual Studio project types
|
SimControl/SimControl.Reactive
|
SimControl.Reactive/StateMachineObserver.cs
|
SimControl.Reactive/StateMachineObserver.cs
|
// Copyright (c) SimControl e.U. - Wilhelm Medetz. See LICENSE.txt in the project root for more information.
#if false
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics.CodeAnalysis;
// TODO: CR
namespace SimControl.Reactive
{
//public class ObservedState: INotifyPropertyChanged
//{
// public string Name { get; internal set; }
// public string Type { get; internal set; }
// public bool IsActive { get; internal set; }
// public IEnumerable<ObservedState> Children { get; internal set; }
// public event PropertyChangedEventHandler PropertyChanged;
//}
//interface IStateMachineObserver: INotifyPropertyChanged
//{
// ExecutionStateValue ExecutionState { get; }
// IDictionary<string, ObservedState> States { get; }
//}
//public class StateMachineObserver: IStateMachineObserver
//{
// public ExecutionStateValue ExecutionState
// {
// get { throw new NotImplementedException(); }
// }
// public IDictionary<string, ObservedState> States
// {
// get { throw new NotImplementedException(); }
// }
// public event PropertyChangedEventHandler PropertyChanged;
//}
}
#endif
|
// Copyright (c) SimControl e.U. - Wilhelm Medetz. See LICENSE.txt in the project root for more information.
#if false
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics.CodeAnalysis;
// TODO: CR
namespace SimControl.Reactive
{
//public class ObservedState: INotifyPropertyChanged
//{
// public string Name { get; internal set; }
// public string Type { get; internal set; }
// public bool IsActive { get; internal set; }
// public IEnumerable<ObservedState> Children { get; internal set; }
// public event PropertyChangedEventHandler PropertyChanged;
//}
//interface IStateMachineObserver: INotifyPropertyChanged
//{
// ExecutionStateValue ExecutionState { get; }
// IDictionary<string, ObservedState> States { get; }
//}
//public class StateMachineObserver: IStateMachineObserver
//{
// public ExecutionStateValue ExecutionState
// {
// get { throw new NotImplementedException(); }
// }
// public IDictionary<string, ObservedState> States
// {
// get { throw new NotImplementedException(); }
// }
// public event PropertyChangedEventHandler PropertyChanged;
//}
}
#endif
|
mit
|
C#
|
adec97fb92f6bf890fe5d06157537358c936c702
|
change configuration service-collection-extenstions, AddPoco changed to accept key-setting
|
SorenZ/Alamut.DotNet
|
src/Alamut.Utilities.AspNet/Configuration/ServiceCollectionExtensions.cs
|
src/Alamut.Utilities.AspNet/Configuration/ServiceCollectionExtensions.cs
|
using System;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
// https://www.strathweb.com/2016/09/strongly-typed-configuration-in-asp-net-core-without-ioptionst/
namespace Alamut.Utilities.AspNet.Configuration
{
public static class ServiceCollectionExtensions
{
/// <summary>
/// bind a configuration section to provided class and inject to the service collection with Singleton life time
/// </summary>
/// <typeparam name="TConfig">type of the configuration section</typeparam>
/// <param name="services">current service collection</param>
/// <param name="configuration">the configuration instance </param>
/// <param name="key">the key of the configuration section to bind, use nameof(TConfig) if not provided</param>
/// <returns></returns>
public static TConfig AddPoco<TConfig>(this IServiceCollection services,
IConfiguration configuration,
string key = null) where TConfig : class, new()
{
if (services == null) throw new ArgumentNullException(nameof(services));
if (configuration == null) throw new ArgumentNullException(nameof(configuration));
var config = new TConfig();
configuration.Bind(key ?? typeof(TConfig).Name, config);
services.AddSingleton(config);
return config;
}
}
}
|
using System;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
// https://www.strathweb.com/2016/09/strongly-typed-configuration-in-asp-net-core-without-ioptionst/
namespace Alamut.Utilities.AspNet.Configuration
{
public static class ServiceCollectionExtensions
{
public static TConfig ConfigurePoco<TConfig>(this IServiceCollection services, IConfiguration configuration) where TConfig : class, new()
{
if (services == null) throw new ArgumentNullException(nameof(services));
if (configuration == null) throw new ArgumentNullException(nameof(configuration));
var config = new TConfig();
configuration.Bind(config);
services.AddSingleton(config);
return config;
}
}
}
|
mit
|
C#
|
dbaa8a377e9848be18a2b1a1a2406efe5d076c0c
|
Fix formatting in LINQ statement
|
jskeet/gcloud-dotnet,jskeet/google-cloud-dotnet,googleapis/google-cloud-dotnet,jskeet/google-cloud-dotnet,jskeet/google-cloud-dotnet,googleapis/google-cloud-dotnet,jskeet/google-cloud-dotnet,jskeet/google-cloud-dotnet,googleapis/google-cloud-dotnet
|
apis/Google.Cloud.Storage.V1/Google.Cloud.Storage.V1.Tests/Conformance/ConformanceTestData.cs
|
apis/Google.Cloud.Storage.V1/Google.Cloud.Storage.V1.Tests/Conformance/ConformanceTestData.cs
|
// Copyright 2019 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
using Google.Apis.Auth.OAuth2;
using Google.Cloud.ClientTesting;
using Google.Protobuf.Collections;
using System;
using System.Collections.ObjectModel;
using System.IO;
using System.Linq;
using Xunit;
namespace Google.Cloud.Storage.V1.Tests.Conformance
{
// Note: we may want to move some of this logic into ClientTesting over time.
internal static class ConformanceTestData
{
internal static ServiceAccountCredential TestCredential { get; } =
(ServiceAccountCredential) GoogleCredential.FromFile(Path.Combine(DataPath, "test_service_account.not-a-test.json")).UnderlyingCredential;
internal static ReadOnlyCollection<TestFile> TestFiles { get; } =
Directory.GetFiles(DataPath, "*.json")
.Where(path => !Path.GetFileName(path).Contains("not-a-test"))
.Select(path => TestFile.Parser.ParseJson(File.ReadAllText(path)))
.ToList()
.AsReadOnly();
private static string DataPath => Path.Combine(TestEnvironment.FindConformanceTestsDirectory(), "storage", "v1");
internal static TheoryData<T> GetTheoryData<T>(Func<TestFile, RepeatedField<T>> testExtractor)
{
var ret = new TheoryData<T>();
foreach (var file in TestFiles)
{
foreach (var test in testExtractor(file))
{
ret.Add(test);
}
}
return ret;
}
}
}
|
// Copyright 2019 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
using Google.Apis.Auth.OAuth2;
using Google.Cloud.ClientTesting;
using Google.Protobuf.Collections;
using System;
using System.Collections.ObjectModel;
using System.IO;
using System.Linq;
using Xunit;
namespace Google.Cloud.Storage.V1.Tests.Conformance
{
// Note: we may want to move some of this logic into ClientTesting over time.
internal static class ConformanceTestData
{
internal static ServiceAccountCredential TestCredential { get; } =
(ServiceAccountCredential) GoogleCredential.FromFile(Path.Combine(DataPath, "test_service_account.not-a-test.json")).UnderlyingCredential;
internal static ReadOnlyCollection<TestFile> TestFiles { get; } =
Directory.GetFiles(DataPath, "*.json")
.Where(path => !Path.GetFileName(path)
.Contains("not-a-test"))
.Select(path => TestFile.Parser.ParseJson(File.ReadAllText(path)))
.ToList()
.AsReadOnly();
private static string DataPath => Path.Combine(TestEnvironment.FindConformanceTestsDirectory(), "storage", "v1");
internal static TheoryData<T> GetTheoryData<T>(Func<TestFile, RepeatedField<T>> testExtractor)
{
var ret = new TheoryData<T>();
foreach (var file in TestFiles)
{
foreach (var test in testExtractor(file))
{
ret.Add(test);
}
}
return ret;
}
}
}
|
apache-2.0
|
C#
|
cbc20b8def0b576d5b605b934962e4a5edacbded
|
Fix bug with html escaping in view sermons.
|
razsilev/Sv_Naum,razsilev/Sv_Naum,razsilev/Sv_Naum
|
Source/SvNaum.Web/Views/Home/Sermons.cshtml
|
Source/SvNaum.Web/Views/Home/Sermons.cshtml
|
@model IEnumerable<SvNaum.Models.Sermon>
@{
ViewBag.Title = "Проповеди";
}
@*<h2>Проповеди!</h2>*@
<br />
@if (this.User.Identity.IsAuthenticated)
{
@Html.ActionLink("Create Sermon", "SermonAdd", "Admin")
<br />
<br />
}
@if (Model != null && Model.Count() > 0)
{
foreach (var item in Model)
{
<div>
@*@Html.LabelFor(m => item.Theme)*@
@*@Html.DisplayFor(m => item.Theme)*@
<h2>
@Html.DisplayFor(m => item.Title)
</h2>
<p>
@Html.Raw(item.Text)
</p>
<br />
<div class="avtor">
@Html.DisplayFor(m => item.Author)
</div>
<br />
@Html.DisplayFor(m => item.Date.ToLocalTime().GetDateTimeFormats()[1])
<br />
<div id="facebookButton" class="fb-share-button" data-href="https://developers.facebook.com/docs/plugins/" data-layout="button">
</div>
@if (this.User.Identity.IsAuthenticated)
{
<div>
@Html.ActionLink("Edit", "SermonEdit", "Admin", new { id = item.Id }, null)
@Html.ActionLink("Delete", "SermonDelete", "Admin", new { id = item.Id }, null)
</div>
}
</div>
}
}
else
{
<h3>There is no sermons!</h3>
}
|
@model IEnumerable<SvNaum.Models.Sermon>
@{
ViewBag.Title = "Проповеди";
}
@*<h2>Проповеди!</h2>*@
<br />
@if (this.User.Identity.IsAuthenticated)
{
@Html.ActionLink("Create Sermon", "SermonAdd", "Admin")
<br />
<br />
}
@if (Model != null && Model.Count() > 0)
{
foreach (var item in Model)
{
<div>
@*@Html.LabelFor(m => item.Theme)*@
@*@Html.DisplayFor(m => item.Theme)*@
<br />
@*@Html.LabelFor(m => item.Title)*@
<h2>
@Html.DisplayFor(m => item.Title)
</h2>
<br />
@*@Html.LabelFor(m => item.Text)*@
<p>
@Html.DisplayFor(m => item.Text)
</p>
<br />
@*@Html.LabelFor(m => item.Author)*@
<div class="avtor">
@Html.DisplayFor(m => item.Author)
</div>
<br />
@*@Html.LabelFor(m => item.Date)*@
@Html.DisplayFor(m => item.Date.ToLocalTime().GetDateTimeFormats()[1])
<br />
<div id="facebookButton" class="fb-share-button" data-href="https://developers.facebook.com/docs/plugins/" data-layout="button">
</div>
@if (this.User.Identity.IsAuthenticated)
{
@Html.ActionLink("Delete", "SermonDelete", "Admin", new { id = item.Id }, null)
<br />
@Html.ActionLink("Edit", "SermonEdit", "Admin", new { id = item.Id }, null)
}
</div>
}
}
else
{
<h3>There is no sermons!</h3>
}
|
mit
|
C#
|
662ee7382c1a32bf8e39205a41d52b339de8eea7
|
Add ActiveButton property to TabPanel
|
chylex/TweetDuck,chylex/TweetDuck,chylex/TweetDuck,chylex/TweetDuck
|
Core/Controls/TabPanel.cs
|
Core/Controls/TabPanel.cs
|
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using System.Windows.Forms;
namespace TweetDck.Core.Controls{
sealed partial class TabPanel : UserControl{
public IEnumerable<TabButton> Buttons{
get{
return panelButtons.Controls.Cast<TabButton>();
}
}
public TabButton ActiveButton { get; private set; }
// ReSharper disable once ConvertToAutoPropertyWithPrivateSetter
public Panel Content{
get{
return panelContent;
}
}
private int btnWidth;
public TabPanel(){
InitializeComponent();
}
public void SetupTabPanel(int buttonWidth){
this.btnWidth = buttonWidth;
}
public TabButton AddButton(string title, Action callback){
TabButton button = new TabButton();
button.SetupButton((btnWidth-1)*panelButtons.Controls.Count,btnWidth,title,callback);
button.Click += (sender, args) => SelectTab((TabButton)sender);
panelButtons.Controls.Add(button);
return button;
}
public void SelectTab(TabButton button){
if (ActiveButton != null){
ActiveButton.BackColor = SystemColors.Control;
}
button.BackColor = Color.White;
button.Callback();
ActiveButton = button;
}
public void ReplaceContent(Control newControl){
newControl.Dock = DockStyle.Fill;
Content.SuspendLayout();
Content.Controls.Clear();
Content.Controls.Add(newControl);
Content.ResumeLayout(true);
}
}
}
|
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using System.Windows.Forms;
namespace TweetDck.Core.Controls{
sealed partial class TabPanel : UserControl{
public IEnumerable<TabButton> Buttons{
get{
return panelButtons.Controls.Cast<TabButton>();
}
}
// ReSharper disable once ConvertToAutoPropertyWithPrivateSetter
public Panel Content{
get{
return panelContent;
}
}
private int btnWidth;
public TabPanel(){
InitializeComponent();
}
public void SetupTabPanel(int buttonWidth){
this.btnWidth = buttonWidth;
}
public TabButton AddButton(string title, Action callback){
TabButton button = new TabButton();
button.SetupButton((btnWidth-1)*panelButtons.Controls.Count,btnWidth,title,callback);
button.Click += (sender, args) => SelectTab((TabButton)sender);
panelButtons.Controls.Add(button);
return button;
}
public void SelectTab(TabButton button){
foreach(TabButton btn in Buttons){
btn.BackColor = SystemColors.Control;
}
button.BackColor = Color.White;
button.Callback();
}
public void ReplaceContent(Control newControl){
newControl.Dock = DockStyle.Fill;
Content.SuspendLayout();
Content.Controls.Clear();
Content.Controls.Add(newControl);
Content.ResumeLayout(true);
}
}
}
|
mit
|
C#
|
0eba9031fd3de60964c7165fe6b766bb7cae7d6e
|
Remove dead code
|
cbcrc/LinkIt
|
HeterogeneousDataSources/LoadLinkExpressions/INestedLoadLinkExpression.cs
|
HeterogeneousDataSources/LoadLinkExpressions/INestedLoadLinkExpression.cs
|
using System;
namespace HeterogeneousDataSources.LoadLinkExpressions
{
public interface INestedLoadLinkExpression : ILoadLinkExpression
{
Type ChildLinkedSourceType { get; }
}
}
|
using System;
namespace HeterogeneousDataSources.LoadLinkExpressions
{
public interface INestedLoadLinkExpression : ILoadLinkExpression
{
Type ChildLinkedSourceType { get; }
Type ChildLinkedSourceModelType { get; }
}
}
|
mit
|
C#
|
9cab86aed6df0cd31b56421d0e584aa26480e841
|
Fix NRE when value is not set
|
mycroes/SupportManager,mycroes/SupportManager,mycroes/SupportManager
|
SupportManager.Web/Infrastructure/Tags/DefaultAspNetMvcHtmlConventions.cs
|
SupportManager.Web/Infrastructure/Tags/DefaultAspNetMvcHtmlConventions.cs
|
using System;
using System.ComponentModel.DataAnnotations;
using HtmlTags;
using HtmlTags.Conventions;
namespace SupportManager.Web.Infrastructure.Tags
{
public class DefaultAspNetMvcHtmlConventions : HtmlConventionRegistry
{
public DefaultAspNetMvcHtmlConventions()
{
Editors.Always.AddClass("form-control");
Editors.IfPropertyIs<DateTimeOffset>().ModifyWith(m => m.CurrentTag.Attr("type", "datetime-local").Value(m.Value<DateTimeOffset?>()?.ToLocalTime().DateTime.ToString("O")));
Editors.IfPropertyIs<DateTime?>().ModifyWith(m => m.CurrentTag
.AddPattern("9{1,2}/9{1,2}/9999")
.AddPlaceholder("MM/DD/YYYY")
.AddClass("datepicker")
.Value(m.Value<DateTime?>() != null ? m.Value<DateTime>().ToShortDateString() : string.Empty));
Editors.If(er => er.Accessor.Name.EndsWith("id", StringComparison.OrdinalIgnoreCase)).BuildBy(a => new HiddenTag().Value(a.StringValue()));
Editors.IfPropertyIs<byte[]>().BuildBy(a => new HiddenTag().Value(Convert.ToBase64String(a.Value<byte[]>())));
Editors.BuilderPolicy<UserPhoneNumberSelectElementBuilder>();
Editors.BuilderPolicy<TeamSelectElementBuilder>();
Labels.Always.AddClass("control-label");
Labels.Always.AddClass("col-md-2");
Labels.ModifyForAttribute<DisplayAttribute>((t, a) => t.Text(a.Name));
DisplayLabels.Always.BuildBy<DefaultDisplayLabelBuilder>();
DisplayLabels.ModifyForAttribute<DisplayAttribute>((t, a) => t.Text(a.Name));
Displays.IfPropertyIs<DateTime>().ModifyWith(m => m.CurrentTag.Text(m.Value<DateTime>().ToShortDateString()));
Displays.IfPropertyIs<DateTime?>().ModifyWith(m => m.CurrentTag.Text(m.Value<DateTime?>() == null ? null : m.Value<DateTime?>().Value.ToShortDateString()));
Displays.IfPropertyIs<decimal>().ModifyWith(m => m.CurrentTag.Text(m.Value<decimal>().ToString("C")));
Displays.IfPropertyIs<bool>().BuildBy<BoolDisplayBuilder>();
}
public ElementCategoryExpression DisplayLabels
{
get { return new ElementCategoryExpression(Library.TagLibrary.Category("DisplayLabels").Profile(TagConstants.Default)); }
}
}
}
|
using System;
using System.ComponentModel.DataAnnotations;
using HtmlTags;
using HtmlTags.Conventions;
namespace SupportManager.Web.Infrastructure.Tags
{
public class DefaultAspNetMvcHtmlConventions : HtmlConventionRegistry
{
public DefaultAspNetMvcHtmlConventions()
{
Editors.Always.AddClass("form-control");
Editors.IfPropertyIs<DateTimeOffset>().ModifyWith(m => m.CurrentTag.Attr("type", "datetime-local").Value(m.Value<DateTimeOffset>().ToLocalTime().DateTime.ToString("O")));
Editors.IfPropertyIs<DateTime?>().ModifyWith(m => m.CurrentTag
.AddPattern("9{1,2}/9{1,2}/9999")
.AddPlaceholder("MM/DD/YYYY")
.AddClass("datepicker")
.Value(m.Value<DateTime?>() != null ? m.Value<DateTime>().ToShortDateString() : string.Empty));
Editors.If(er => er.Accessor.Name.EndsWith("id", StringComparison.OrdinalIgnoreCase)).BuildBy(a => new HiddenTag().Value(a.StringValue()));
Editors.IfPropertyIs<byte[]>().BuildBy(a => new HiddenTag().Value(Convert.ToBase64String(a.Value<byte[]>())));
Editors.BuilderPolicy<UserPhoneNumberSelectElementBuilder>();
Editors.BuilderPolicy<TeamSelectElementBuilder>();
Labels.Always.AddClass("control-label");
Labels.Always.AddClass("col-md-2");
Labels.ModifyForAttribute<DisplayAttribute>((t, a) => t.Text(a.Name));
DisplayLabels.Always.BuildBy<DefaultDisplayLabelBuilder>();
DisplayLabels.ModifyForAttribute<DisplayAttribute>((t, a) => t.Text(a.Name));
Displays.IfPropertyIs<DateTime>().ModifyWith(m => m.CurrentTag.Text(m.Value<DateTime>().ToShortDateString()));
Displays.IfPropertyIs<DateTime?>().ModifyWith(m => m.CurrentTag.Text(m.Value<DateTime?>() == null ? null : m.Value<DateTime?>().Value.ToShortDateString()));
Displays.IfPropertyIs<decimal>().ModifyWith(m => m.CurrentTag.Text(m.Value<decimal>().ToString("C")));
Displays.IfPropertyIs<bool>().BuildBy<BoolDisplayBuilder>();
}
public ElementCategoryExpression DisplayLabels
{
get { return new ElementCategoryExpression(Library.TagLibrary.Category("DisplayLabels").Profile(TagConstants.Default)); }
}
}
}
|
mit
|
C#
|
18d658f7e15cdf06c4edc2ac6e1b03414dd8c5c9
|
Add window.prompt support to JavaScriptDialogHandler
|
chylex/TweetDuck,chylex/TweetDuck,chylex/TweetDuck,chylex/TweetDuck
|
Core/Handling/JavaScriptDialogHandler.cs
|
Core/Handling/JavaScriptDialogHandler.cs
|
using CefSharp;
using CefSharp.WinForms;
using System.Drawing;
using System.Windows.Forms;
using TweetDck.Core.Controls;
using TweetDck.Core.Other;
namespace TweetDck.Core.Handling {
class JavaScriptDialogHandler : IJsDialogHandler{
bool IJsDialogHandler.OnJSDialog(IWebBrowser browserControl, IBrowser browser, string originUrl, CefJsDialogType dialogType, string messageText, string defaultPromptText, IJsDialogCallback callback, ref bool suppressMessage){
((ChromiumWebBrowser)browserControl).InvokeSafe(() => {
FormMessage form = new FormMessage(Program.BrandName, messageText, MessageBoxIcon.None);
TextBox input = null;
if (dialogType == CefJsDialogType.Alert){
form.AddButton("OK");
}
else if (dialogType == CefJsDialogType.Confirm){
form.AddButton("No", DialogResult.No);
form.AddButton("Yes");
}
else if (dialogType == CefJsDialogType.Prompt){
form.AddButton("Cancel", DialogResult.Cancel);
form.AddButton("OK");
input = new TextBox{
Anchor = AnchorStyles.Left | AnchorStyles.Right | AnchorStyles.Bottom,
Location = new Point(27, form.ActionPanelY-46),
Size = new Size(form.ClientSize.Width-54, 20)
};
form.Controls.Add(input);
form.Height += input.Size.Height+input.Margin.Vertical;
}
bool success = form.ShowDialog() == DialogResult.OK;
if (input == null){
callback.Continue(success);
}
else{
callback.Continue(success, input.Text);
input.Dispose();
}
form.Dispose();
});
return true;
}
bool IJsDialogHandler.OnJSBeforeUnload(IWebBrowser browserControl, IBrowser browser, string message, bool isReload, IJsDialogCallback callback){
return false;
}
void IJsDialogHandler.OnResetDialogState(IWebBrowser browserControl, IBrowser browser){}
void IJsDialogHandler.OnDialogClosed(IWebBrowser browserControl, IBrowser browser){}
}
}
|
using CefSharp;
using CefSharp.WinForms;
using System.Windows.Forms;
using TweetDck.Core.Controls;
using TweetDck.Core.Other;
namespace TweetDck.Core.Handling {
class JavaScriptDialogHandler : IJsDialogHandler{
bool IJsDialogHandler.OnJSDialog(IWebBrowser browserControl, IBrowser browser, string originUrl, CefJsDialogType dialogType, string messageText, string defaultPromptText, IJsDialogCallback callback, ref bool suppressMessage){
if (dialogType != CefJsDialogType.Alert && dialogType != CefJsDialogType.Confirm){
return false;
}
((ChromiumWebBrowser)browserControl).InvokeSafe(() => {
FormMessage form = new FormMessage(Program.BrandName, messageText, MessageBoxIcon.None);
if (dialogType == CefJsDialogType.Alert){
form.AddButton("OK");
}
else if (dialogType == CefJsDialogType.Confirm){
form.AddButton("No", DialogResult.No);
form.AddButton("Yes");
}
else{
return;
}
callback.Continue(form.ShowDialog() == DialogResult.OK);
form.Dispose();
});
return true;
}
bool IJsDialogHandler.OnJSBeforeUnload(IWebBrowser browserControl, IBrowser browser, string message, bool isReload, IJsDialogCallback callback){
return false;
}
void IJsDialogHandler.OnResetDialogState(IWebBrowser browserControl, IBrowser browser){}
void IJsDialogHandler.OnDialogClosed(IWebBrowser browserControl, IBrowser browser){}
}
}
|
mit
|
C#
|
256657c8c7944dc751393ff25104bda2b959e3f3
|
Update version number.
|
ollyau/FSActiveFires
|
FSActiveFires/Properties/AssemblyInfo.cs
|
FSActiveFires/Properties/AssemblyInfo.cs
|
using System.Reflection;
using System.Resources;
using System.Runtime.CompilerServices;
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("FSActiveFires")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("FSActiveFires")]
[assembly: AssemblyCopyright("Copyright © Orion Lyau 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)]
//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("0.1.1.0")]
[assembly: AssemblyFileVersion("0.1.1.0")]
|
using System.Reflection;
using System.Resources;
using System.Runtime.CompilerServices;
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("FSActiveFires")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("FSActiveFires")]
[assembly: AssemblyCopyright("Copyright © Orion Lyau 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)]
//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("0.1.0.1")]
[assembly: AssemblyFileVersion("0.1.0.1")]
|
mit
|
C#
|
df36b1066f9f9fbbd5e0eea8a51863d5c8bd3f6a
|
Add ResetDefinesTo
|
DarrenTsung/DTCommandPalette
|
DefaultCommands/Editor/ScriptingDefines/ScriptingDefinesManager.cs
|
DefaultCommands/Editor/ScriptingDefines/ScriptingDefinesManager.cs
|
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using UnityEditor;
using UnityEngine;
namespace DTCommandPalette.ScriptingDefines {
public static class ScriptingDefinesManager {
public static BuildTargetGroup CurrentTargetGroup {
get { return EditorUserBuildSettings.selectedBuildTargetGroup; }
}
public static string[] GetCurrentDefines() {
return GetDefinesFor(CurrentTargetGroup);
}
public static void ResetDefinesTo(string[] previousDefines) {
SetScriptingDefines(CurrentTargetGroup, previousDefines);
}
public static string[] GetDefinesFor(BuildTargetGroup targetGroup) {
string scriptingDefinesString = PlayerSettings.GetScriptingDefineSymbolsForGroup(targetGroup);
return scriptingDefinesString.Split(';');
}
public static bool RemoveDefine(string symbol) {
return RemoveDefine(CurrentTargetGroup, symbol);
}
public static bool RemoveDefine(BuildTargetGroup targetGroup, string symbol) {
string[] scriptingDefines = GetDefinesFor(targetGroup);
if (!scriptingDefines.Contains(symbol)) {
return false;
}
scriptingDefines = scriptingDefines.Where(s => s != symbol).ToArray();
SetScriptingDefines(targetGroup, scriptingDefines);
return true;
}
public static bool AddDefineIfNotFound(string symbol) {
return AddDefineIfNotFound(CurrentTargetGroup, symbol);
}
public static bool AddDefineIfNotFound(BuildTargetGroup targetGroup, string symbol) {
string[] scriptingDefines = GetDefinesFor(targetGroup);
if (scriptingDefines.Contains(symbol)) {
return false;
}
scriptingDefines = scriptingDefines.ConcatSingle(symbol).ToArray();
SetScriptingDefines(targetGroup, scriptingDefines);
return true;
}
// PRAGMA MARK - Internal
private static void SetScriptingDefines(BuildTargetGroup targetGroup, string[] scriptingDefines) {
string newScriptingDefines = string.Join(";", scriptingDefines);
PlayerSettings.SetScriptingDefineSymbolsForGroup(targetGroup, newScriptingDefines);
AssetDatabase.SaveAssets();
}
}
}
|
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using UnityEditor;
using UnityEngine;
namespace DTCommandPalette.ScriptingDefines {
public static class ScriptingDefinesManager {
public static BuildTargetGroup CurrentTargetGroup {
get { return EditorUserBuildSettings.selectedBuildTargetGroup; }
}
public static string[] GetCurrentDefines() {
return GetDefinesFor(CurrentTargetGroup);
}
public static string[] GetDefinesFor(BuildTargetGroup targetGroup) {
string scriptingDefinesString = PlayerSettings.GetScriptingDefineSymbolsForGroup(targetGroup);
return scriptingDefinesString.Split(';');
}
public static bool RemoveDefine(string symbol) {
return RemoveDefine(CurrentTargetGroup, symbol);
}
public static bool RemoveDefine(BuildTargetGroup targetGroup, string symbol) {
string[] scriptingDefines = GetDefinesFor(targetGroup);
if (!scriptingDefines.Contains(symbol)) {
return false;
}
scriptingDefines = scriptingDefines.Where(s => s != symbol).ToArray();
SetScriptingDefines(targetGroup, scriptingDefines);
return true;
}
public static bool AddDefineIfNotFound(string symbol) {
return AddDefineIfNotFound(CurrentTargetGroup, symbol);
}
public static bool AddDefineIfNotFound(BuildTargetGroup targetGroup, string symbol) {
string[] scriptingDefines = GetDefinesFor(targetGroup);
if (scriptingDefines.Contains(symbol)) {
return false;
}
scriptingDefines = scriptingDefines.ConcatSingle(symbol).ToArray();
SetScriptingDefines(targetGroup, scriptingDefines);
return true;
}
// PRAGMA MARK - Internal
private static void SetScriptingDefines(BuildTargetGroup targetGroup, string[] scriptingDefines) {
string newScriptingDefines = string.Join(";", scriptingDefines);
PlayerSettings.SetScriptingDefineSymbolsForGroup(targetGroup, newScriptingDefines);
AssetDatabase.SaveAssets();
}
}
}
|
mit
|
C#
|
bf9c29e587f1dcfe8fa4d3b77ea9ac7fd83c9777
|
Update Run.cs
|
win120a/ACClassRoomUtil,win120a/ACClassRoomUtil
|
LoginPasswordUtil/C-Sharp-Version/Run.cs
|
LoginPasswordUtil/C-Sharp-Version/Run.cs
|
/*
Copyright (C) 2011-2014 AC Inc. (Andy Cheung)
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
/*
-> ACLoginPasswordUtil.exe
This is my first draft of this (C# version), it may not pass the build.
*/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using ACLoginPasswordUtil;
using System.Diagnostics;
namespace ACLoginPasswordUtil
{
class Run
{
int decrypt(String[] originalArgs)
{
int first = Int32.Parse(originalArgs[0]);
int second = Int32.Parse(originalArgs[1]);
int result = first + second;
return result;
}
public static void Main(String[] a)
{
String sysPath = Environment.GetEnvironmentVariable("SystemRoot");
Run thisInstance = new Run();
Resources resClass = new Resources();
int pswInt = thisInstance.decrypt(a);
if (pswInt > 1 && !(pswInt > 5)) // The value check.
{
StringBuilder sBuilder = new StringBuilder();
sBuilder.Append(sysPath);
sBuilder.Append("\\System32\\");
sBuilder.Append(resClass.baseCmd);
sBuilder.Append(resClass.netCmd);
String cmdText = sBuilder.ToString();
sBuilder.Clear();
sBuilder.Append(resClass.armv7a);
sBuilder.Append(pswInt);
String pswText = sBuilder.ToString();
sBuilder.Clear();
sBuilder.Append(cmdText);
sBuilder.Append(pswText);
Process.Start(sBuilder.ToString());
}
}
}
}
|
/*
Copyright (C) 2011-2014 AC Inc. (Andy Cheung)
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
/*
This is my first draft of this (C# version), it may not pass the build.
*/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using ACLoginPasswordUtil;
using System.Diagnostics;
namespace ACLoginPasswordUtil
{
class Run
{
int decrypt(String[] originalArgs)
{
int first = Int32.Parse(originalArgs[0]);
int second = Int32.Parse(originalArgs[1]);
int result = first + second;
return result;
}
public static void Main(String[] a)
{
String sysPath = Environment.GetEnvironmentVariable("SystemRoot");
Run thisInstance = new Run();
Resources resClass = new Resources();
int pswInt = thisInstance.decrypt(a);
if (pswInt > 1 && !(pswInt > 5)) // The value check.
{
StringBuilder sBuilder = new StringBuilder();
sBuilder.Append(sysPath);
sBuilder.Append("\\System32\\");
sBuilder.Append(resClass.baseCmd);
sBuilder.Append(resClass.netCmd);
String cmdText = sBuilder.ToString();
sBuilder.Clear();
sBuilder.Append(resClass.armv7a);
sBuilder.Append(pswInt);
String pswText = sBuilder.ToString();
sBuilder.Clear();
sBuilder.Append(cmdText);
sBuilder.Append(pswText);
Process.Start(sBuilder.ToString());
}
}
}
}
|
apache-2.0
|
C#
|
43a255c649985f43a7bd719dd96a3ac836080b01
|
update naming in session query
|
0xFireball/KQAnalytics3,0xFireball/KQAnalytics3,0xFireball/KQAnalytics3
|
KQAnalytics3/src/KQAnalytics3/Services/DataCollection/SessionStorageService.cs
|
KQAnalytics3/src/KQAnalytics3/Services/DataCollection/SessionStorageService.cs
|
using KQAnalytics3.Models.Data;
using KQAnalytics3.Services.Database;
using System.Threading.Tasks;
namespace KQAnalytics3.Services.DataCollection
{
public class SessionStorageService
{
public static string SessionUserCookieStorageKey => "kq_session";
public static async Task<UserSession> GetSessionFromIdentifierAsync(string identifier)
{
UserSession ret = null;
var db = DatabaseAccessService.OpenOrCreateDefault();
// Get stored sessions collection
var storedSessions = db.GetCollection<UserSession>(DatabaseAccessService.LoggedRequestDataKey);
ret = storedSessions.FindOne(x => x.SessionId == identifier);
return ret;
}
public static async Task SaveSessionAsync(UserSession session)
{
var db = DatabaseAccessService.OpenOrCreateDefault();
// Get logged requests collection
var loggedRequests = db.GetCollection<UserSession>(DatabaseAccessService.LoggedRequestDataKey);
// Use ACID transaction
using (var trans = db.BeginTrans())
{
// Insert new session into database
loggedRequests.Insert(session);
trans.Commit();
}
// Index requests by identifier
loggedRequests.EnsureIndex(x => x.SessionId);
}
}
}
|
using KQAnalytics3.Models.Data;
using KQAnalytics3.Services.Database;
using System.Threading.Tasks;
namespace KQAnalytics3.Services.DataCollection
{
public class SessionStorageService
{
public static string SessionUserCookieStorageKey => "kq_session";
public static async Task<UserSession> GetSessionFromIdentifierAsync(string identifier)
{
UserSession ret = null;
var db = DatabaseAccessService.OpenOrCreateDefault();
// Get logged requests collection
var loggedRequests = db.GetCollection<UserSession>(DatabaseAccessService.LoggedRequestDataKey);
// Log by descending timestamp
ret = loggedRequests.FindOne(x => x.SessionId == identifier);
return ret;
}
public static async Task SaveSessionAsync(UserSession session)
{
var db = DatabaseAccessService.OpenOrCreateDefault();
// Get logged requests collection
var loggedRequests = db.GetCollection<UserSession>(DatabaseAccessService.LoggedRequestDataKey);
// Use ACID transaction
using (var trans = db.BeginTrans())
{
// Insert new session into database
loggedRequests.Insert(session);
trans.Commit();
}
// Index requests by identifier
loggedRequests.EnsureIndex(x => x.SessionId);
}
}
}
|
agpl-3.0
|
C#
|
6a35dd9f113f254b7f818a478085e88fa3289856
|
Update ServiceCollectionExtensions.cs
|
autofac/Autofac.Extensions.DependencyInjection
|
src/Autofac.Extensions.DependencyInjection/ServiceCollectionExtensions.cs
|
src/Autofac.Extensions.DependencyInjection/ServiceCollectionExtensions.cs
|
// This software is part of the Autofac IoC container
// Copyright © 2017 Autofac Contributors
// http://autofac.org
//
// 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 Microsoft.Extensions.DependencyInjection;
namespace Autofac.Extensions.DependencyInjection
{
/// <summary>
/// Extension methods on <see cref="IServiceCollection"/> to register the <see cref="IServiceProviderFactory{TContainerBuilder}"/>.
/// </summary>
public static class ServiceCollectionExtensions
{
/// <summary>
/// Adds the <see cref="AutofacServiceProviderFactory"/> to the service collection.
/// </summary>
/// <param name="services">The service collection to add the factory to.</param>
/// <param name="configurationAction">Action on a <see cref="ContainerBuilder"/> that adds component registrations to the container.</param>
/// <returns>The service collection.</returns>
public static IServiceCollection AddAutofac(this IServiceCollection services, Action<ContainerBuilder> configurationAction = null)
{
return services.AddSingleton<IServiceProviderFactory<ContainerBuilder>>(new AutofacServiceProviderFactory(configurationAction));
}
}
}
|
// This software is part of the Autofac IoC container
// Copyright © 2017 Autofac Contributors
// http://autofac.org
//
// 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 Microsoft.Extensions.DependencyInjection;
namespace Autofac.Extensions.DependencyInjection
{
/// <summary>
/// Extension methods on <see cref="IServiceCollection"/> to register the <see cref="IServiceProviderFactory{TContainerBuilder}"/>.
/// </summary>
public static class ServiceCollectionExtensions
{
/// <summary>
/// Adds the <see cref="AutofacServiceProviderFactory"/> to the service collection.
/// </summary>
/// <param name="services">The service collection to add the factory to.</param>
/// <param name="configurationAction">Action on a <see cref="ContainerBuilder"/> that adds component registrations to the conatiner.</param>
/// <returns>The service collection.</returns>
public static IServiceCollection AddAutofac(this IServiceCollection services, Action<ContainerBuilder> configurationAction = null)
{
return services.AddSingleton<IServiceProviderFactory<ContainerBuilder>>(new AutofacServiceProviderFactory(configurationAction));
}
}
}
|
mit
|
C#
|
842964664dd155c28686410e5f8bcedd2920744c
|
Fix OutFormatter
|
visualeyes/halcyon
|
src/Halcyon.Mvc/HAL/Json/JsonHalOutputFormatter.cs
|
src/Halcyon.Mvc/HAL/Json/JsonHalOutputFormatter.cs
|
using Halcyon.HAL;
using Microsoft.AspNet.Mvc.Formatters;
using Microsoft.Net.Http.Headers;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace Halcyon.Web.HAL.Json {
public class JsonHalOutputFormatter : IOutputFormatter {
public const string HalJsonType = "application/hal+json";
private readonly IEnumerable<string> halJsonMediaTypes;
private readonly JsonOutputFormatter jsonFormatter;
public JsonHalOutputFormatter(JsonOutputFormatter jsonFormatter, IEnumerable<string> halJsonMediaTypes = null) {
if (halJsonMediaTypes == null) halJsonMediaTypes = new string[] { HalJsonType };
this.jsonFormatter = jsonFormatter;
this.halJsonMediaTypes = halJsonMediaTypes;
}
public bool CanWriteResult(OutputFormatterCanWriteContext context) {
return context.ObjectType == typeof(HALResponse);
}
public async Task WriteAsync(OutputFormatterWriteContext context) {
string mediaType = context.ContentType.MediaType;
object value = null;
var halResponse = ((HALResponse)context.Object);
// If it is a HAL response but set to application/json - convert to a plain response
var serializer = Newtonsoft.Json.JsonSerializer.Create(jsonFormatter.SerializerSettings);
if (!halResponse.Config.ForceHAL && !halJsonMediaTypes.Contains(mediaType)) {
value = halResponse.ToPlainResponse(serializer);
} else {
value = halResponse.ToJObject(serializer);
}
var jsonContext = new OutputFormatterWriteContext(context.HttpContext, context.WriterFactory, value.GetType(), value);
await jsonFormatter.WriteAsync(jsonContext);
}
}
}
|
using Halcyon.HAL;
using Microsoft.AspNet.Mvc.Formatters;
using Microsoft.Net.Http.Headers;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace Halcyon.Web.HAL.Json {
public class JsonHalOutputFormatter : IOutputFormatter {
public const string HalJsonType = "application/hal+json";
private readonly IEnumerable<string> halJsonMediaTypes;
private readonly JsonOutputFormatter jsonFormatter;
public JsonHalOutputFormatter(JsonOutputFormatter jsonFormatter, IEnumerable<string> halJsonMediaTypes = null) {
if (halJsonMediaTypes == null) halJsonMediaTypes = new string[] { HalJsonType };
this.jsonFormatter = jsonFormatter;
this.halJsonMediaTypes = halJsonMediaTypes;
}
public bool CanWriteResult(OutputFormatterCanWriteContext context) {
return context.ObjectType == typeof(HALResponse);
}
public async Task WriteAsync(OutputFormatterWriteContext context) {
string mediaType = context.ContentType.MediaType;
object value = null;
var halResponse = ((HALResponse)context.Object);
// If it is a HAL response but set to application/json - convert to a plain response
var serializer = Newtonsoft.Json.JsonSerializer.Create(jsonFormatter.SerializerSettings);
if (!halResponse.Config.ForceHAL && halJsonMediaTypes.Contains(mediaType)) {
value = halResponse.ToPlainResponse(serializer);
} else {
value = halResponse.ToJObject(serializer);
}
var jsonContext = new OutputFormatterWriteContext(context.HttpContext, context.WriterFactory, value.GetType(), value);
await jsonFormatter.WriteAsync(jsonContext);
}
}
}
|
mit
|
C#
|
73c6f86fb506d25e36aa7337c6f3dcb5255e97b4
|
remove comment, found implementation in owin
|
Malkiat-Singh/aspnet-identity-mongo,iiwaasnet/aspnet-identity-mongo,Malkiat-Singh/aspnet-identity-mongo,s4lvo/aspnet-identity-mongo,winterdouglas/aspnet-identity-mongo,abbasmhd/aspnet-identity-mongo,abbasmhd/aspnet-identity-mongo,Dedice/aspnet-identity-mongo,FelschR/AspNetCore.Identity.DocumentDB,iiwaasnet/aspnet-identity-mongo,s4lvo/aspnet-identity-mongo,FelschR/aspnetcore-identity-documentdb,g0t4/aspnet-identity-mongo,Dedice/aspnet-identity-mongo
|
src/IntegrationTests/UserConfirmationStoreTests.cs
|
src/IntegrationTests/UserConfirmationStoreTests.cs
|
namespace IntegrationTests
{
using AspNet.Identity.MongoDB;
using Microsoft.AspNet.Identity;
using NUnit.Framework;
[TestFixture]
public class UserConfirmationStoreTests : UserIntegrationTestsBase
{
[Test]
public void Create_NewUser_IsNotConfirmed()
{
var manager = GetUserManager();
var user = new IdentityUser {UserName = "bob"};
manager.Create(user);
var isConfirmed = manager.IsConfirmed(user.Id);
Expect(isConfirmed, Is.False);
}
[Test]
public void SetConfirmed_IsConfirmed()
{
var manager = GetUserManager();
var user = new IdentityUser {UserName = "bob"};
manager.Create(user);
manager.SetConfirmed(user.Id, true);
var isConfirmed = manager.IsConfirmed(user.Id);
Expect(isConfirmed);
}
[Test]
public void SetUnConfirmed_AlreadyConfirmed_IsNotConfirmed()
{
var manager = GetUserManager();
var user = new IdentityUser {UserName = "bob"};
manager.Create(user);
manager.SetConfirmed(user.Id, true);
manager.SetConfirmed(user.Id, false);
var isConfirmed = manager.IsConfirmed(user.Id);
Expect(isConfirmed, Is.False);
}
}
}
|
namespace IntegrationTests
{
using AspNet.Identity.MongoDB;
using Microsoft.AspNet.Identity;
using NUnit.Framework;
[TestFixture]
public class UserConfirmationStoreTests : UserIntegrationTestsBase
{
[Test]
public void Create_NewUser_IsNotConfirmed()
{
var manager = GetUserManager();
var user = new IdentityUser {UserName = "bob"};
manager.Create(user);
var isConfirmed = manager.IsConfirmed(user.Id);
Expect(isConfirmed, Is.False);
}
[Test]
public void SetConfirmed_IsConfirmed()
{
var manager = GetUserManager();
var user = new IdentityUser {UserName = "bob"};
manager.Create(user);
manager.SetConfirmed(user.Id, true);
var isConfirmed = manager.IsConfirmed(user.Id);
Expect(isConfirmed);
}
[Test]
public void SetUnConfirmed_AlreadyConfirmed_IsNotConfirmed()
{
var manager = GetUserManager();
var user = new IdentityUser {UserName = "bob"};
manager.Create(user);
manager.SetConfirmed(user.Id, true);
manager.SetConfirmed(user.Id, false);
var isConfirmed = manager.IsConfirmed(user.Id);
Expect(isConfirmed, Is.False);
}
// todo look into ITokenProvider (and potentially mongo persistence?)
}
}
|
mit
|
C#
|
82b524c0da961daaca41a420df8302f5791a93f8
|
Fix #181 that directory could be removed by user when wox running.
|
kdar/Wox,JohnTheGr8/Wox,derekforeman/Wox,EmuxEvans/Wox,Megasware128/Wox,Launchify/Launchify,jondaniels/Wox,mika76/Wox,sanbinabu/Wox,AlexCaranha/Wox,shangvven/Wox,yozora-hitagi/Saber,derekforeman/Wox,18098924759/Wox,apprentice3d/Wox,danisein/Wox,vebin/Wox,zlphoenix/Wox,mika76/Wox,AlexCaranha/Wox,gnowxilef/Wox,dstiert/Wox,danisein/Wox,renzhn/Wox,jondaniels/Wox,kdar/Wox,18098924759/Wox,gnowxilef/Wox,derekforeman/Wox,mika76/Wox,Launchify/Launchify,apprentice3d/Wox,kdar/Wox,dstiert/Wox,medoni/Wox,AlexCaranha/Wox,kayone/Wox,dstiert/Wox,JohnTheGr8/Wox,zlphoenix/Wox,18098924759/Wox,sanbinabu/Wox,sanbinabu/Wox,shangvven/Wox,yozora-hitagi/Saber,vebin/Wox,EmuxEvans/Wox,shangvven/Wox,apprentice3d/Wox,kayone/Wox,renzhn/Wox,gnowxilef/Wox,Megasware128/Wox,medoni/Wox,kayone/Wox,EmuxEvans/Wox,vebin/Wox
|
Wox.Plugin.SystemPlugins/Program/ProgramSources/FileSystemProgramSource.cs
|
Wox.Plugin.SystemPlugins/Program/ProgramSources/FileSystemProgramSource.cs
|
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using Wox.Infrastructure.Storage.UserSettings;
namespace Wox.Plugin.SystemPlugins.Program.ProgramSources
{
public class FileSystemProgramSource : AbstractProgramSource
{
private string baseDirectory;
public FileSystemProgramSource(string baseDirectory)
{
this.baseDirectory = baseDirectory;
}
public FileSystemProgramSource(ProgramSource source):this(source.Location)
{
this.BonusPoints = source.BonusPoints;
}
public override List<Program> LoadPrograms()
{
List<Program> list = new List<Program>();
if (Directory.Exists(baseDirectory))
{
GetAppFromDirectory(baseDirectory, list);
FileChangeWatcher.AddWatch(baseDirectory);
}
return list;
}
private void GetAppFromDirectory(string path, List<Program> list)
{
try
{
foreach (string file in Directory.GetFiles(path))
{
if (UserSettingStorage.Instance.ProgramSuffixes.Split(';').Any(o => file.EndsWith("." + o)))
{
Program p = CreateEntry(file);
list.Add(p);
}
}
foreach (var subDirectory in Directory.GetDirectories(path))
{
GetAppFromDirectory(subDirectory, list);
}
}
catch (UnauthorizedAccessException e)
{
Debug.WriteLine(string.Format("Can't access to directory {0}", path), "WoxDebug");
}
catch (DirectoryNotFoundException e)
{
//no-operation
}
}
public override string ToString()
{
return typeof(FileSystemProgramSource).Name + ":" + this.baseDirectory;
}
}
}
|
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using Wox.Infrastructure.Storage.UserSettings;
namespace Wox.Plugin.SystemPlugins.Program.ProgramSources
{
public class FileSystemProgramSource : AbstractProgramSource
{
private string baseDirectory;
public FileSystemProgramSource(string baseDirectory)
{
this.baseDirectory = baseDirectory;
}
public FileSystemProgramSource(ProgramSource source):this(source.Location)
{
this.BonusPoints = source.BonusPoints;
}
public override List<Program> LoadPrograms()
{
List<Program> list = new List<Program>();
if (Directory.Exists(baseDirectory))
{
GetAppFromDirectory(baseDirectory, list);
FileChangeWatcher.AddWatch(baseDirectory);
}
return list;
}
private void GetAppFromDirectory(string path, List<Program> list)
{
try
{
foreach (string file in Directory.GetFiles(path))
{
if (UserSettingStorage.Instance.ProgramSuffixes.Split(';').Any(o => file.EndsWith("." + o)))
{
Program p = CreateEntry(file);
list.Add(p);
}
}
foreach (var subDirectory in Directory.GetDirectories(path))
{
GetAppFromDirectory(subDirectory, list);
}
}
catch (UnauthorizedAccessException e)
{
Debug.WriteLine(string.Format("Can't access to directory {0}",path),"WoxDebug");
}
}
public override string ToString()
{
return typeof(FileSystemProgramSource).Name + ":" + this.baseDirectory;
}
}
}
|
mit
|
C#
|
049975b5a46bce96baee5132d12157a01d2a7653
|
Use kebaberize shorthand
|
smoogipoo/osu,NeoAdonis/osu,ppy/osu,smoogipoo/osu,EVAST9919/osu,UselessToucan/osu,peppy/osu,UselessToucan/osu,UselessToucan/osu,2yangk23/osu,NeoAdonis/osu,ppy/osu,2yangk23/osu,NeoAdonis/osu,peppy/osu-new,peppy/osu,johnneijzen/osu,EVAST9919/osu,johnneijzen/osu,ppy/osu,smoogipoo/osu,smoogipooo/osu,peppy/osu
|
osu.Game.Rulesets.Catch/Skinning/CatchLegacySkinTransformer.cs
|
osu.Game.Rulesets.Catch/Skinning/CatchLegacySkinTransformer.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 Humanizer;
using osu.Framework.Audio.Sample;
using osu.Framework.Bindables;
using osu.Framework.Graphics;
using osu.Framework.Graphics.Textures;
using osu.Game.Audio;
using osu.Game.Skinning;
using osuTK;
namespace osu.Game.Rulesets.Catch.Skinning
{
public class CatchLegacySkinTransformer : ISkin
{
private readonly ISkin source;
public CatchLegacySkinTransformer(ISkinSource source)
{
this.source = source;
}
public Drawable GetDrawableComponent(ISkinComponent component)
{
if (!(component is CatchSkinComponent catchSkinComponent))
return null;
switch (catchSkinComponent.Component)
{
case CatchSkinComponents.FruitApple:
case CatchSkinComponents.FruitBananas:
case CatchSkinComponents.FruitOrange:
case CatchSkinComponents.FruitGrapes:
case CatchSkinComponents.FruitPear:
var lookupName = catchSkinComponent.Component.ToString().Kebaberize();
if (GetTexture(lookupName) != null)
return new LegacyFruitPiece(lookupName);
break;
case CatchSkinComponents.Droplet:
if (GetTexture("fruit-drop") != null)
return new LegacyFruitPiece("fruit-drop") { Scale = new Vector2(0.8f) };
break;
}
return null;
}
public Texture GetTexture(string componentName) => source.GetTexture(componentName);
public SampleChannel GetSample(ISampleInfo sample) => source.GetSample(sample);
public IBindable<TValue> GetConfig<TLookup, TValue>(TLookup lookup) => source.GetConfig<TLookup, TValue>(lookup);
}
}
|
// 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 Humanizer;
using osu.Framework.Audio.Sample;
using osu.Framework.Bindables;
using osu.Framework.Graphics;
using osu.Framework.Graphics.Textures;
using osu.Game.Audio;
using osu.Game.Skinning;
using osuTK;
namespace osu.Game.Rulesets.Catch.Skinning
{
public class CatchLegacySkinTransformer : ISkin
{
private readonly ISkin source;
public CatchLegacySkinTransformer(ISkinSource source)
{
this.source = source;
}
public Drawable GetDrawableComponent(ISkinComponent component)
{
if (!(component is CatchSkinComponent catchSkinComponent))
return null;
switch (catchSkinComponent.Component)
{
case CatchSkinComponents.FruitApple:
case CatchSkinComponents.FruitBananas:
case CatchSkinComponents.FruitOrange:
case CatchSkinComponents.FruitGrapes:
case CatchSkinComponents.FruitPear:
var lookupName = catchSkinComponent.Component.ToString().Underscore().Hyphenate();
if (GetTexture(lookupName) != null)
return new LegacyFruitPiece(lookupName);
break;
case CatchSkinComponents.Droplet:
if (GetTexture("fruit-drop") != null)
return new LegacyFruitPiece("fruit-drop") { Scale = new Vector2(0.8f) };
break;
}
return null;
}
public Texture GetTexture(string componentName) => source.GetTexture(componentName);
public SampleChannel GetSample(ISampleInfo sample) => source.GetSample(sample);
public IBindable<TValue> GetConfig<TLookup, TValue>(TLookup lookup) => source.GetConfig<TLookup, TValue>(lookup);
}
}
|
mit
|
C#
|
f0e91ba43188c7cc3f7a0e660c13477551082f71
|
Fix overlined playlist test scene not working
|
smoogipoo/osu,ppy/osu,peppy/osu,NeoAdonis/osu,UselessToucan/osu,ppy/osu,peppy/osu,NeoAdonis/osu,UselessToucan/osu,smoogipooo/osu,UselessToucan/osu,peppy/osu,NeoAdonis/osu,smoogipoo/osu,smoogipoo/osu,peppy/osu-new,ppy/osu
|
osu.Game.Tests/Visual/Multiplayer/TestSceneOverlinedPlaylist.cs
|
osu.Game.Tests/Visual/Multiplayer/TestSceneOverlinedPlaylist.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;
using osu.Framework.Graphics;
using osu.Game.Online.Multiplayer;
using osu.Game.Rulesets.Osu;
using osu.Game.Screens.Multi;
using osu.Game.Tests.Beatmaps;
using osuTK;
namespace osu.Game.Tests.Visual.Multiplayer
{
public class TestSceneOverlinedPlaylist : MultiplayerTestScene
{
protected override bool UseOnlineAPI => true;
public TestSceneOverlinedPlaylist()
{
Add(new DrawableRoomPlaylist(false, false)
{
Anchor = Anchor.Centre,
Origin = Anchor.Centre,
Size = new Vector2(500),
Items = { BindTarget = Room.Playlist }
});
}
[SetUp]
public new void Setup() => Schedule(() =>
{
Room.RoomID.Value = 7;
for (int i = 0; i < 10; i++)
{
Room.Playlist.Add(new PlaylistItem
{
ID = i,
Beatmap = { Value = new TestBeatmap(new OsuRuleset().RulesetInfo).BeatmapInfo },
Ruleset = { Value = new OsuRuleset().RulesetInfo }
});
}
});
}
}
|
// 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;
using osu.Framework.Graphics;
using osu.Game.Online.Multiplayer;
using osu.Game.Rulesets.Osu;
using osu.Game.Screens.Multi;
using osu.Game.Tests.Beatmaps;
using osuTK;
namespace osu.Game.Tests.Visual.Multiplayer
{
public class TestSceneOverlinedPlaylist : MultiplayerTestScene
{
protected override bool UseOnlineAPI => true;
public TestSceneOverlinedPlaylist()
{
Add(new DrawableRoomPlaylist(false, false)
{
Anchor = Anchor.Centre,
Origin = Anchor.Centre,
Size = new Vector2(500),
});
}
[SetUp]
public new void Setup() => Schedule(() =>
{
Room.RoomID.Value = 7;
for (int i = 0; i < 10; i++)
{
Room.Playlist.Add(new PlaylistItem
{
ID = i,
Beatmap = { Value = new TestBeatmap(new OsuRuleset().RulesetInfo).BeatmapInfo },
Ruleset = { Value = new OsuRuleset().RulesetInfo }
});
}
});
}
}
|
mit
|
C#
|
e67fc30a1477000c6aaec9ade210afb6353101a8
|
Cut off getter / setter prefix only if it exists
|
danielpalme/ReportGenerator,danielpalme/ReportGenerator,danielpalme/ReportGenerator,danielpalme/ReportGenerator,danielpalme/ReportGenerator,danielpalme/ReportGenerator,danielpalme/ReportGenerator
|
ReportGenerator/Parser/Preprocessing/CodeAnalysis/PropertyElement.cs
|
ReportGenerator/Parser/Preprocessing/CodeAnalysis/PropertyElement.cs
|
using System;
using ICSharpCode.NRefactory.CSharp;
using ICSharpCode.NRefactory.PatternMatching;
namespace Palmmedia.ReportGenerator.Parser.Preprocessing.CodeAnalysis
{
/// <summary>
/// Represents a property in a source file.
/// </summary>
internal class PropertyElement : SourceElement
{
private const string GetterPrefix = "get_";
private const string SetterPrefix = "set_";
/// <summary>
/// The name of the property.
/// </summary>
private readonly string name;
/// <summary>
/// Initializes a new instance of the <see cref="PropertyElement"/> class.
/// </summary>
/// <param name="classname">The classname.</param>
/// <param name="name">The name of the property.</param>
internal PropertyElement(string classname, string name)
: base(classname)
{
if (name == null)
{
throw new ArgumentNullException(nameof(name));
}
this.name = name;
//Cut off prefix only if property starts with standard getter ("get_") / setter prefix ("set_")
if (this.name.StartsWith(GetterPrefix, StringComparison.Ordinal))
{
this.name = name.Substring(GetterPrefix.Length);
}
else if (this.name.StartsWith(SetterPrefix, StringComparison.Ordinal))
{
this.name = name.Substring(SetterPrefix.Length);
}
}
/// <summary>
/// Determines whether the given <see cref="ICSharpCode.NRefactory.PatternMatching.INode"/> matches the <see cref="SourceElement"/>.
/// </summary>
/// <param name="node">The node.</param>
/// <returns>
/// A <see cref="SourceElementPosition"/> or <c>null</c> if <see cref="SourceElement"/> does not match the <see cref="ICSharpCode.NRefactory.PatternMatching.INode"/>.
/// </returns>
internal override SourceElementPosition GetSourceElementPosition(INode node)
{
PropertyDeclaration propertyDeclaration = node as PropertyDeclaration;
if (propertyDeclaration != null && propertyDeclaration.Name.Equals(this.name))
{
return new SourceElementPosition(
propertyDeclaration.StartLocation.Line,
propertyDeclaration.EndLocation.Line);
}
return null;
}
}
}
|
using System;
using ICSharpCode.NRefactory.CSharp;
using ICSharpCode.NRefactory.PatternMatching;
namespace Palmmedia.ReportGenerator.Parser.Preprocessing.CodeAnalysis
{
/// <summary>
/// Represents a property in a source file.
/// </summary>
internal class PropertyElement : SourceElement
{
/// <summary>
/// The name of the property.
/// </summary>
private readonly string name;
/// <summary>
/// Initializes a new instance of the <see cref="PropertyElement"/> class.
/// </summary>
/// <param name="classname">The classname.</param>
/// <param name="name">The name of the property.</param>
internal PropertyElement(string classname, string name)
: base(classname)
{
if (name == null)
{
throw new ArgumentNullException(nameof(name));
}
this.name = name.Substring(4);
}
/// <summary>
/// Determines whether the given <see cref="ICSharpCode.NRefactory.PatternMatching.INode"/> matches the <see cref="SourceElement"/>.
/// </summary>
/// <param name="node">The node.</param>
/// <returns>
/// A <see cref="SourceElementPosition"/> or <c>null</c> if <see cref="SourceElement"/> does not match the <see cref="ICSharpCode.NRefactory.PatternMatching.INode"/>.
/// </returns>
internal override SourceElementPosition GetSourceElementPosition(INode node)
{
PropertyDeclaration propertyDeclaration = node as PropertyDeclaration;
if (propertyDeclaration != null && propertyDeclaration.Name.Equals(this.name))
{
return new SourceElementPosition(
propertyDeclaration.StartLocation.Line,
propertyDeclaration.EndLocation.Line);
}
return null;
}
}
}
|
apache-2.0
|
C#
|
690a8f4ae26df2070f520362536aabbb1e65963e
|
Change version 1.0
|
DataGenSoftware/DataGen.Extensions
|
DataGen.Extensions/DataGen.Extensions.Shared/Common/AssemblyInfo.Common.cs
|
DataGen.Extensions/DataGen.Extensions.Shared/Common/AssemblyInfo.Common.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("DataGen.Extensions")]
[assembly: AssemblyDescription(".NET types extensions")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("DataGen.Extensions")]
[assembly: AssemblyCopyright("Copyright © Karol Habczyk")]
[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)]
// 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.*")]
[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("DataGen.Extensions")]
[assembly: AssemblyDescription(".NET types extensions")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("DataGen.Extensions")]
[assembly: AssemblyCopyright("Copyright © Karol Habczyk")]
[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)]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("0.8.*")]
[assembly: AssemblyFileVersion("0.8.0.0")]
|
mit
|
C#
|
a9d2b1594ba165c7791ee3216e2872dfbc946a3c
|
remove redundant copy paste
|
WojcikMike/docs.particular.net
|
samples/ravendb/evolving-sagadata/Version_5/UpgradeToV3/RavenExtensions.cs
|
samples/ravendb/evolving-sagadata/Version_5/UpgradeToV3/RavenExtensions.cs
|
using System.Collections.Generic;
using System.Linq;
using Raven.Abstractions.Commands;
using Raven.Abstractions.Data;
using Raven.Client;
using Raven.Client.Document;
#region RavenExtensions
public static class RavenExtensions
{
public static void BatchDelete(this DocumentStore store, IEnumerable<string> keysToDelete)
{
// Process groups in batches of 1000 to avoid a possible timeout
foreach (var batch in keysToDelete.Batch(1000))
{
DeleteCommandData[] deleteCommands = batch
.Select(key => new DeleteCommandData
{
Key = key
})
.ToArray();
store.DatabaseCommands.Batch(deleteCommands);
}
}
static IEnumerable<IEnumerable<T>> Batch<T>(this IEnumerable<T> items, int maxItems)
{
return items.Select((item, index) => new
{
item,
index
})
.GroupBy(x => x.index/maxItems)
.Select(g => g.Select(x => x.item));
}
public static IEnumerable<StreamResult<T>> Stream<T>(this IDocumentStore store, string prefix)
{
using (IDocumentSession session = store.OpenSession())
using (IEnumerator<StreamResult<T>> enumerator = session.Advanced.Stream<T>(prefix))
{
while (enumerator.MoveNext())
{
yield return enumerator.Current;
}
}
}
public static string GetDocumentPrefix<T>(this DocumentStore store)
{
return store.Conventions.FindTypeTagName(typeof(T)) + "/";
}
}
#endregion
|
using System.Collections.Generic;
using System.Linq;
using Raven.Abstractions.Commands;
using Raven.Abstractions.Data;
using Raven.Client;
using Raven.Client.Document;
#region RavenExtensions
public static class RavenExtensions
{
public static void BatchDelete(this DocumentStore store, IEnumerable<string> keysToDelete)
{
// Process groups in batches of 1000 to avoid a possible timeout
foreach (var batch in keysToDelete.Batch(1000))
{
DeleteCommandData[] deleteCommands = batch
.Select(key => new DeleteCommandData
{
Key = key
})
.ToArray();
store.DatabaseCommands.Batch(deleteCommands);
}
}
static IEnumerable<IEnumerable<T>> Batch<T>(this IEnumerable<T> items, int maxItems)
{
return items.Select((item, index) => new
{
item,
index
})
.GroupBy(x => x.index/maxItems)
.Select(g => g.Select(x => x.item));
}
public static IEnumerable<StreamResult<T>> Stream<T>(this IDocumentStore store, string prefix)
{
using (IDocumentSession session = store.OpenSession())
using (IEnumerator<StreamResult<T>> enumerator = session.Advanced.Stream<T>(prefix))
using (BulkInsertOperation bulkInsert = store.BulkInsert())
{
while (enumerator.MoveNext())
{
yield return enumerator.Current;
}
}
}
public static string GetDocumentPrefix<T>(this DocumentStore store)
{
return store.Conventions.FindTypeTagName(typeof(T)) + "/";
}
}
#endregion
|
apache-2.0
|
C#
|
1a7ecef8d52f2c253851a83603ffeef7e61ed378
|
Fix missed rename
|
autofac/Autofac.Extensions.DependencyInjection
|
test/Autofac.Extensions.DependencyInjection.Test/HostBuilderExtensionsTests.cs
|
test/Autofac.Extensions.DependencyInjection.Test/HostBuilderExtensionsTests.cs
|
using Microsoft.Extensions.Hosting;
using Xunit;
namespace Autofac.Extensions.DependencyInjection.Test
{
public sealed class HostBuilderExtensionsTests
{
[Fact]
public void UseAutofacAutofacServiceProviderResolveable()
{
var host = Host.CreateDefaultBuilder(null)
.UseAutofac()
.Build();
Assert.IsAssignableFrom<AutofacServiceProvider>(host.Services);
}
[Fact]
public void UseAutofacChildScopeFactoryWithDelegateAutofacServiceProviderResolveable()
{
var host = Host.CreateDefaultBuilder(null)
.UseAutofacChildLifetimeScopeFactory(GetRootLifetimeScope)
.Build();
Assert.IsAssignableFrom<AutofacServiceProvider>(host.Services);
}
[Fact]
public void UseAutofacChildScopeFactoryWithInstanceAutofacServiceProviderResolveable()
{
var rootLifetimeScope = GetRootLifetimeScope();
var host = Host.CreateDefaultBuilder(null)
.UseAutofacChildLifetimeScopeFactory(rootLifetimeScope)
.Build();
Assert.IsAssignableFrom<AutofacServiceProvider>(host.Services);
}
private static ILifetimeScope GetRootLifetimeScope() => new ContainerBuilder().Build();
}
}
|
using Microsoft.Extensions.Hosting;
using Xunit;
namespace Autofac.Extensions.DependencyInjection.Test
{
public sealed class HostBuilderExtensionsTests
{
[Fact]
public void UseAutofacAutofacServiceProviderResolveable()
{
var host = Host.CreateDefaultBuilder(null)
.UseAutofac()
.Build();
Assert.IsAssignableFrom<AutofacServiceProvider>(host.Services);
}
[Fact]
public void UseAutofacChildScopeFactoryWithDelegateAutofacServiceProviderResolveable()
{
var host = Host.CreateDefaultBuilder(null)
.UseAutofacChildScopeFactory(GetRootLifetimeScope)
.Build();
Assert.IsAssignableFrom<AutofacServiceProvider>(host.Services);
}
[Fact]
public void UseAutofacChildScopeFactoryWithInstanceAutofacServiceProviderResolveable()
{
var rootLifetimeScope = GetRootLifetimeScope();
var host = Host.CreateDefaultBuilder(null)
.UseAutofacChildScopeFactory(rootLifetimeScope)
.Build();
Assert.IsAssignableFrom<AutofacServiceProvider>(host.Services);
}
private static ILifetimeScope GetRootLifetimeScope() => new ContainerBuilder().Build();
}
}
|
mit
|
C#
|
1da9b8500cd076321b2e413d5c99359e6be2e134
|
Optimize HttpClientInstrumentationOptions.EventFilter (#1170)
|
open-telemetry/opentelemetry-dotnet,open-telemetry/opentelemetry-dotnet,open-telemetry/opentelemetry-dotnet
|
src/OpenTelemetry.Instrumentation.Http/HttpClientInstrumentationOptions.cs
|
src/OpenTelemetry.Instrumentation.Http/HttpClientInstrumentationOptions.cs
|
// <copyright file="HttpClientInstrumentationOptions.cs" company="OpenTelemetry Authors">
// Copyright The OpenTelemetry Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// </copyright>
using System;
using System.Net.Http;
using System.Runtime.CompilerServices;
using OpenTelemetry.Context.Propagation;
using OpenTelemetry.Trace;
namespace OpenTelemetry.Instrumentation.Http
{
/// <summary>
/// Options for HttpClient instrumentation.
/// </summary>
public class HttpClientInstrumentationOptions
{
/// <summary>
/// Gets or sets a value indicating whether or not the HTTP version should be added as the <see cref="SemanticConventions.AttributeHttpFlavor"/> tag. Default value: False.
/// </summary>
public bool SetHttpFlavor { get; set; }
/// <summary>
/// Gets or sets <see cref="ITextFormat"/> for context propagation. Default value: <see cref="CompositePropagator"/> with <see cref="TraceContextFormat"/> & <see cref="BaggageFormat"/>.
/// </summary>
public ITextFormat TextFormat { get; set; } = new CompositePropagator(new ITextFormat[]
{
new TraceContextFormat(),
new BaggageFormat(),
});
/// <summary>
/// Gets or sets an optional callback method for filtering <see cref="HttpRequestMessage"/> requests that are sent through the instrumentation.
/// </summary>
public Func<HttpRequestMessage, bool> FilterFunc { get; set; }
[MethodImpl(MethodImplOptions.AggressiveInlining)]
internal bool EventFilter(string activityName, object arg1)
{
return
this.FilterFunc == null ||
!TryParseHttpRequestMessage(activityName, arg1, out HttpRequestMessage requestMessage) ||
this.FilterFunc(requestMessage);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private static bool TryParseHttpRequestMessage(string activityName, object arg1, out HttpRequestMessage requestMessage)
{
return (requestMessage = arg1 as HttpRequestMessage) != null && activityName == "System.Net.Http.HttpRequestOut";
}
}
}
|
// <copyright file="HttpClientInstrumentationOptions.cs" company="OpenTelemetry Authors">
// Copyright The OpenTelemetry Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// </copyright>
using System;
using System.Net.Http;
using OpenTelemetry.Context.Propagation;
using OpenTelemetry.Trace;
namespace OpenTelemetry.Instrumentation.Http
{
/// <summary>
/// Options for HttpClient instrumentation.
/// </summary>
public class HttpClientInstrumentationOptions
{
/// <summary>
/// Gets or sets a value indicating whether or not the HTTP version should be added as the <see cref="SemanticConventions.AttributeHttpFlavor"/> tag. Default value: False.
/// </summary>
public bool SetHttpFlavor { get; set; }
/// <summary>
/// Gets or sets <see cref="ITextFormat"/> for context propagation. Default value: <see cref="CompositePropagator"/> with <see cref="TraceContextFormat"/> & <see cref="BaggageFormat"/>.
/// </summary>
public ITextFormat TextFormat { get; set; } = new CompositePropagator(new ITextFormat[]
{
new TraceContextFormat(),
new BaggageFormat(),
});
/// <summary>
/// Gets or sets an optional callback method for filtering <see cref="HttpRequestMessage"/> requests that are sent through the instrumentation.
/// </summary>
public Func<HttpRequestMessage, bool> FilterFunc { get; set; }
internal bool EventFilter(string activityName, object arg1)
{
if (TryParseHttpRequestMessage(activityName, arg1, out HttpRequestMessage requestMessage))
{
return this.FilterFunc?.Invoke(requestMessage) ?? true;
}
return true;
}
private static bool TryParseHttpRequestMessage(string activityName, object arg1, out HttpRequestMessage requestMessage)
{
return (requestMessage = arg1 as HttpRequestMessage) != null && activityName == "System.Net.Http.HttpRequestOut";
}
}
}
|
apache-2.0
|
C#
|
e96050c085ec036da47b547cd150dcdfc9474306
|
Remove unnecessary using directive.
|
msgpack/msgpack-cli,msgpack/msgpack-cli
|
src/MsgPack/IAsyncUnpackable.cs
|
src/MsgPack/IAsyncUnpackable.cs
|
#region -- License Terms --
//
// MessagePack for CLI
//
// Copyright (C) 2015 FUJIWARA, Yusuke
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
#endregion -- License Terms --
#if FEATURE_TAP
using System;
using System.Threading;
using System.Threading.Tasks;
namespace MsgPack
{
/// <summary>
/// An interface which is implemented by the objects which know how to unpack themselves using specified <see cref="Unpacker"/> asynchronously.
/// </summary>
/// <remarks>
/// <include file='remarks.xml' path='doc/para[@name="MsgPack.Serialization.customPackingUnpacking"]'/>
/// </remarks>
public interface IAsyncUnpackable
{
/// <summary>
/// Unpacks this object contents from the specified <see cref="Unpacker"/> asynchronously.
/// </summary>
/// <param name="unpacker">The <see cref="Unpacker"/> that this object will read from.</param>
/// <param name="cancellationToken">The token to monitor for cancellation requests. The default value is <see cref="CancellationToken.None"/>.</param>
/// <returns>A <see cref="Task"/> that represents the asynchronous operation.</returns>
/// <exception cref="ArgumentNullException">
/// <paramref name="unpacker"/> is <c>null</c>.
/// </exception>
/// <exception cref="System.Runtime.Serialization.SerializationException">
/// Failed to deserialize this object.
/// </exception>
/// <include file='remarks.xml' path='doc/remarks[@name="MsgPack.Serialization.customUnpacking"]'/>
Task UnpackFromMessageAsync( Unpacker unpacker, CancellationToken cancellationToken );
}
}
#endif // FEATURE_TAP
|
#region -- License Terms --
//
// MessagePack for CLI
//
// Copyright (C) 2015 FUJIWARA, Yusuke
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
#endregion -- License Terms --
#if FEATURE_TAP
using System;
using System.Runtime.Serialization;
using System.Threading;
using System.Threading.Tasks;
namespace MsgPack
{
/// <summary>
/// An interface which is implemented by the objects which know how to unpack themselves using specified <see cref="Unpacker"/> asynchronously.
/// </summary>
/// <remarks>
/// <include file='remarks.xml' path='doc/para[@name="MsgPack.Serialization.customPackingUnpacking"]'/>
/// </remarks>
public interface IAsyncUnpackable
{
/// <summary>
/// Unpacks this object contents from the specified <see cref="Unpacker"/> asynchronously.
/// </summary>
/// <param name="unpacker">The <see cref="Unpacker"/> that this object will read from.</param>
/// <param name="cancellationToken">The token to monitor for cancellation requests. The default value is <see cref="CancellationToken.None"/>.</param>
/// <returns>A <see cref="Task"/> that represents the asynchronous operation.</returns>
/// <exception cref="ArgumentNullException">
/// <paramref name="unpacker"/> is <c>null</c>.
/// </exception>
/// <exception cref="System.Runtime.Serialization.SerializationException">
/// Failed to deserialize this object.
/// </exception>
/// <include file='remarks.xml' path='doc/remarks[@name="MsgPack.Serialization.customUnpacking"]'/>
Task UnpackFromMessageAsync( Unpacker unpacker, CancellationToken cancellationToken );
}
}
#endif // FEATURE_TAP
|
apache-2.0
|
C#
|
647c0bae9bd0712f9590e877be3ff87ef1e40c8d
|
Test automated build
|
AlexStefan/template-app
|
Internationalization/Internationalization.Core/ViewModels/MainViewModel.cs
|
Internationalization/Internationalization.Core/ViewModels/MainViewModel.cs
|
using MvvmCross.Localization;
using MvvmCross.Plugin.JsonLocalization;
using MvvmCross.ViewModels;
namespace Internationalization.Core.ViewModels
{
public class MainViewModel : MvxViewModel
{
private readonly IMvxTextProviderBuilder builder;
public MainViewModel(IMvxTextProviderBuilder builder)
{
this.builder = builder;
}
public string DynamicText
{
get
{
return TextSource.GetText("DynamicValue");//builder.TextProvider.GetText("DynamicValue");
}
}
public IMvxLanguageBinder TextSource
{
get { return new MvxLanguageBinder(Constants.GeneralNamespace, "strings"); }
}
}
}
|
using MvvmCross.Localization;
using MvvmCross.Plugin.JsonLocalization;
using MvvmCross.ViewModels;
namespace Internationalization.Core.ViewModels
{
public class MainViewModel : MvxViewModel
{
private readonly IMvxTextProviderBuilder builder;
public MainViewModel(IMvxTextProviderBuilder builder)
{
this.builder = builder;
}
public string DynamicText
{
get
{
return TextSource.GetText("DynamicValue");
}
}
public IMvxLanguageBinder TextSource
{
get { return new MvxLanguageBinder(Constants.GeneralNamespace, "strings"); }
}
}
}
|
mit
|
C#
|
e8da78cd41fffb23453567dc3c391f78101a095e
|
Update relative point animation
|
AvaloniaUI/Avalonia,jkoritzinsky/Avalonia,jkoritzinsky/Avalonia,AvaloniaUI/Avalonia,wieslawsoltes/Perspex,SuperJMN/Avalonia,SuperJMN/Avalonia,jkoritzinsky/Avalonia,wieslawsoltes/Perspex,AvaloniaUI/Avalonia,jkoritzinsky/Avalonia,wieslawsoltes/Perspex,SuperJMN/Avalonia,wieslawsoltes/Perspex,jkoritzinsky/Avalonia,jkoritzinsky/Avalonia,jkoritzinsky/Perspex,SuperJMN/Avalonia,AvaloniaUI/Avalonia,SuperJMN/Avalonia,AvaloniaUI/Avalonia,grokys/Perspex,wieslawsoltes/Perspex,SuperJMN/Avalonia,SuperJMN/Avalonia,AvaloniaUI/Avalonia,grokys/Perspex,wieslawsoltes/Perspex,Perspex/Perspex,wieslawsoltes/Perspex,Perspex/Perspex,AvaloniaUI/Avalonia,jkoritzinsky/Avalonia
|
src/Avalonia.Visuals/Animation/Animators/RelativePointAnimator.cs
|
src/Avalonia.Visuals/Animation/Animators/RelativePointAnimator.cs
|
namespace Avalonia.Animation.Animators
{
/// <summary>
/// Animator that handles <see cref="RelativePoint"/> properties.
/// </summary>
public class RelativePointAnimator : Animator<RelativePoint>
{
private static readonly PointAnimator s_pointAnimator = new PointAnimator();
public override RelativePoint Interpolate(double progress, RelativePoint oldValue, RelativePoint newValue)
{
if (oldValue.Unit != newValue.Unit)
{
return progress >= 0.5 ? newValue : oldValue;
}
return new RelativePoint(s_pointAnimator.Interpolate(progress, oldValue.Point, newValue.Point), oldValue.Unit);
}
}
}
|
namespace Avalonia.Animation.Animators
{
/// <summary>
/// Animator that handles <see cref="RelativePoint"/> properties.
/// </summary>
public class RelativePointAnimator : Animator<RelativePoint>
{
private static readonly PointAnimator s_pointAnimator = new PointAnimator();
public override RelativePoint Interpolate(double progress, RelativePoint oldValue, RelativePoint newValue)
{
if (oldValue.Unit != newValue.Unit)
{
return progress >= 1 ? newValue : oldValue;
}
return new RelativePoint(s_pointAnimator.Interpolate(progress, oldValue.Point, newValue.Point), oldValue.Unit);
}
}
}
|
mit
|
C#
|
2f286b09cc1cc887974b9eb2b8435cf22826bc32
|
Update AgreementTemplateExtensions.cs
|
SkillsFundingAgency/das-employerapprenticeshipsservice,SkillsFundingAgency/das-employerapprenticeshipsservice,SkillsFundingAgency/das-employerapprenticeshipsservice
|
src/SFA.DAS.EmployerAccounts.Web/Extensions/AgreementTemplateExtensions.cs
|
src/SFA.DAS.EmployerAccounts.Web/Extensions/AgreementTemplateExtensions.cs
|
using SFA.DAS.EmployerAccounts.Web.ViewModels;
using System.Collections.Generic;
using System.Linq;
namespace SFA.DAS.EmployerAccounts.Web.Extensions
{
public static class AgreementTemplateExtensions
{
public static readonly int[] VariationsOfv3Agreement = {3, 4, 5, 6};
public static string InsetText(this AgreementTemplateViewModel agreementTemplate, ICollection<OrganisationAgreementViewModel> organisationAgreementViewModel)
{
switch (agreementTemplate.VersionNumber)
{
case 1:
return string.Empty;
case 2:
return "This is a variation of the agreement that we published 1 May 2017. We updated it to add clause 7 (transfer of funding).";
case 3:
return "This is a new agreement.";
case 4:
return HasSignedVariationOfv3Agreement(organisationAgreementViewModel) ? "This is a variation to the agreement we published 9 January 2020. You only need to accept it if you want to access incentive payments for hiring a new apprentice." : "This is a new agreement.";
case var _ when agreementTemplate.VersionNumber >= 5:
return HasSignedVariationOfv3Agreement(organisationAgreementViewModel) ? "This is a variation to the agreement we published 9 January 2020." : "This is a new agreement.";
default:
return string.Empty;
}
}
private static bool HasSignedVariationOfv3Agreement(ICollection<OrganisationAgreementViewModel> organisationAgreementViewModel)
{
return organisationAgreementViewModel
.Any(agreement => !string.IsNullOrEmpty(agreement.SignedDateText) && VariationsOfv3Agreement.Contains(agreement.Template.VersionNumber));
}
}
}
|
using SFA.DAS.EmployerAccounts.Web.ViewModels;
using System.Collections.Generic;
using System.Linq;
namespace SFA.DAS.EmployerAccounts.Web.Extensions
{
public static class AgreementTemplateExtensions
{
public static readonly int[] VariationsOfv3Agreement = {3, 4, 5, 6};
public static string InsetText(this AgreementTemplateViewModel agreementTemplate, ICollection<OrganisationAgreementViewModel> organisationAgreementViewModel)
{
switch (agreementTemplate.VersionNumber)
{
case 1:
return string.Empty;
case 2:
return "This is a variation of the agreement that we published 1 May 2017. We updated it to add clause 7 (transfer of funding).";
case 3:
return "This is a new agreement.";
case 4:
return HasSignedVariationOfv3Agreement(organisationAgreementViewModel) ? "This is a variation to the agreement we published 9 January 2020. You only need to accept it if you want to access incentive payments for hiring a new apprentice." : "This is a new agreement.";
case var ver when ver >= 5:
return HasSignedVariationOfv3Agreement(organisationAgreementViewModel) ? "This is a variation to the agreement we published 9 January 2020." : "This is a new agreement.";
default:
return string.Empty;
}
}
private static bool HasSignedVariationOfv3Agreement(ICollection<OrganisationAgreementViewModel> organisationAgreementViewModel)
{
return organisationAgreementViewModel
.Any(agreement => !string.IsNullOrEmpty(agreement.SignedDateText) && VariationsOfv3Agreement.Contains(agreement.Template.VersionNumber));
}
}
}
|
mit
|
C#
|
9b91cba2445135027f8c293ab502e51a0697d88f
|
Update CompositionRootSetupBaseTests.cs
|
tiksn/TIKSN-Framework
|
TIKSN.UnitTests.Shared/DependencyInjection/CompositionRootSetupBaseTests.cs
|
TIKSN.UnitTests.Shared/DependencyInjection/CompositionRootSetupBaseTests.cs
|
using Microsoft.Extensions.DependencyInjection;
using Xunit;
using Xunit.Abstractions;
namespace TIKSN.DependencyInjection.Tests
{
public class CompositionRootSetupBaseTests
{
private readonly TestCompositionRootSetup _compositionRoot;
public CompositionRootSetupBaseTests(ITestOutputHelper testOutputHelper) => this._compositionRoot = new TestCompositionRootSetup(testOutputHelper, configureOptions: (s, c) => s.Configure<TestOptions>(c));
[Fact]
public void OptionsValidationForNonParameterLessPropertyType() => this._compositionRoot.CreateServiceProvider();
}
}
|
using Microsoft.Extensions.DependencyInjection;
using Xunit;
using Xunit.Abstractions;
namespace TIKSN.DependencyInjection.Tests
{
public class CompositionRootSetupBaseTests
{
private readonly TestCompositionRootSetup _compositionRoot;
public CompositionRootSetupBaseTests(ITestOutputHelper testOutputHelper)
{
_compositionRoot = new TestCompositionRootSetup(testOutputHelper, configureOptions: (s, c) => s.Configure<TestOptions>(c));
}
[Fact]
public void OptionsValidationForNonParameterLessPropertyType()
{
_compositionRoot.CreateServiceProvider();
}
}
}
|
mit
|
C#
|
6c0cb07c7e7dcd20b85b03ce7a29a88872e04b60
|
Fix table header
|
Mimalef/repop
|
src/PersonnelListEquips.aspx.cs
|
src/PersonnelListEquips.aspx.cs
|
using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
public partial class PersonnelListEquip : BasePage
{
protected void Page_Load(object sender, EventArgs e)
{
string sql = @"
SELECT
id AS 'کد',
type AS 'نوع',
brand AS 'برند',
model AS 'مدل',
status AS 'وضعیت',
customer AS 'کد مشتری'
FROM
equipments";
sql = string.Format(sql);
fillTable(sql, ref TableEquip);
}
}
|
using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
public partial class PersonnelListEquip : BasePage
{
protected void Page_Load(object sender, EventArgs e)
{
string sql = @"
SELECT
id,
type,
brand,
model,
status,
customer
FROM
equipments";
sql = string.Format(sql);
fillTable(sql, ref TableEquip);
}
}
|
mit
|
C#
|
0e6b2be124cbf59f4fede3c06e89ceae4c596e84
|
add CurrentiOSLanguage
|
NDark/ndinfrastructure,NDark/ndinfrastructure
|
Unity/F_PlatformRegion/PlatformRegion.cs
|
Unity/F_PlatformRegion/PlatformRegion.cs
|
/**
MIT License
Copyright (c) 2017 - 2021 NDark
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.
*/
/**
* https://wenrongdev.com/unity53-native-system-language/
*/
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public static class PlatformRegion
{
public static string CheckUnityApplicationSystemLanguage()
{
string ret = string.Empty;
SystemLanguage unitySystemLangauge = Application.systemLanguage;
ret = unitySystemLangauge.ToString();
Debug.Log("CheckApplicationSystemLanguage() ret=" + ret);
return ret ;
}
#if UNITY_ANDROID
public static string CurrentAndroidLanguage()
{
string result = "";
using (AndroidJavaClass cls = new AndroidJavaClass("java.util.Locale"))
{
if (cls != null)
{
using (AndroidJavaObject locale = cls.CallStatic<AndroidJavaObject>("getDefault"))
{
if (locale != null)
{
result = locale.Call<string>("getLanguage") + "_" + locale.Call<string>("getDefault");
Debug.Log("CurrentAndroidLanguage() Android lang: " + result);
}
else
{
Debug.LogError("CurrentAndroidLanguage() locale null");
}
}
}
else
{
Debug.LogError("CurrentAndroidLanguage() cls null");
}
}
Debug.LogWarning("CurrentAndroidLanguage() result" + result);
return result;
}
#endif
#if UNITY_IPHONE
[DllImport("__Internal")]
private static extern string CurIOSLang();
public static string CurrentiOSLanguage()
{
string ret = CurIOSLang();
Debug.LogWarning("CurrentAndroidLanguage() result" + result);
return ret;
}
#endif
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public static class PlatformRegion
{
public static string GetDeviceLanguage()
{
string ret = string.Empty;
SystemLanguage unitySystemLangauge = Application.systemLanguage;
if (unitySystemLangauge == SystemLanguage.ChineseSimplified)
{
ret = VTacticConst.CONST_Languages_TraditionalChinese;
}
else if (unitySystemLangauge == SystemLanguage.Chinese)
{
ret = VTacticConst.CONST_Languages_TraditionalChinese;
}
else if (unitySystemLangauge == SystemLanguage.German)
{
ret = VTacticConst.CONST_Languages_German;
}
else if (unitySystemLangauge == SystemLanguage.Spanish)
{
ret = VTacticConst.CONST_Languages_Spanish;
}
if (Application.platform == RuntimePlatform.IPhonePlayer)
{
#if UNITY_IPHONE
ret = CurIOSLang();
#endif
}
else if (Application.platform == RuntimePlatform.Android)
{
#if UNITY_ANDROID
ret = CurrentAndroidLanguage();
#endif
}
else if (Application.platform == RuntimePlatform.WindowsEditor
|| Application.platform == RuntimePlatform.OSXEditor)
{
ret = CheckUnityApplicationSystemLanguage();
}
else
{
Debug.LogWarning("unknown platform=" + Application.platform );
}
Debug.Log("CheckApplicationSystemLanguage() ret=" + ret);
return ret;
}
public static string CheckUnityApplicationSystemLanguage()
{
string ret = string.Empty;
SystemLanguage unitySystemLangauge = Application.systemLanguage;
if (unitySystemLangauge == SystemLanguage.ChineseSimplified)
{
ret = VTacticConst.CONST_Languages_TraditionalChinese;
}
else if (unitySystemLangauge == SystemLanguage.Chinese)
{
ret = VTacticConst.CONST_Languages_TraditionalChinese;
}
else if (unitySystemLangauge == SystemLanguage.German)
{
ret = VTacticConst.CONST_Languages_German;
}
else if (unitySystemLangauge == SystemLanguage.Spanish)
{
ret = VTacticConst.CONST_Languages_Spanish;
}
else // malay { }
{
Debug.Log("CheckApplicationSystemLanguage() Application.systemLanguage=" + Application.systemLanguage.ToString() );
}
Debug.Log("CheckApplicationSystemLanguage() ret=" + ret);
return ret;
}
#if UNITY_ANDROID
private static string CurrentAndroidLanguage()
{
string result = "";
using (AndroidJavaClass cls = new AndroidJavaClass("java.util.Locale"))
{
if (cls != null)
{
using (AndroidJavaObject locale = cls.CallStatic("getDefault"))
{
if (locale != null)
{
result = locale.Call("getLanguage") + "_" + locale.Call("getDefault");
Debug.Log("Android lang: " + result);
}
else
{
Debug.Log("locale null");
}
}
}
else
{
Debug.Log("cls null");
}
}
return result;
}
#endif
#if UNITY_IPHONE
[DllImport("__Internal")]
private static extern string CurIOSLang();
#endif
}
|
mit
|
C#
|
89b8977f7daf4c0f44dc6540e814a4d693c87041
|
Fix not setting custom scheme response status text correctly
|
chylex/TweetDuck,chylex/TweetDuck,chylex/TweetDuck,chylex/TweetDuck
|
Browser/Adapters/CefSchemeResourceVisitor.cs
|
Browser/Adapters/CefSchemeResourceVisitor.cs
|
using System;
using System.IO;
using System.Net;
using CefSharp;
using TweetLib.Browser.Interfaces;
using TweetLib.Browser.Request;
namespace TweetDuck.Browser.Adapters {
internal sealed class CefSchemeResourceVisitor : ISchemeResourceVisitor<IResourceHandler> {
public static CefSchemeResourceVisitor Instance { get; } = new CefSchemeResourceVisitor();
private static readonly SchemeResource.Status FileIsEmpty = new SchemeResource.Status(HttpStatusCode.NoContent, "File is empty.");
private CefSchemeResourceVisitor() {}
public IResourceHandler Status(SchemeResource.Status status) {
var handler = CreateHandler(Array.Empty<byte>());
handler.StatusCode = (int) status.Code;
handler.StatusText = status.Message;
return handler;
}
public IResourceHandler File(SchemeResource.File file) {
byte[] contents = file.Contents;
if (contents.Length == 0) {
return Status(FileIsEmpty); // FromByteArray crashes CEF internals with no contents
}
var handler = CreateHandler(contents);
handler.MimeType = Cef.GetMimeType(file.Extension);
return handler;
}
private static ResourceHandler CreateHandler(byte[] bytes) {
return ResourceHandler.FromStream(new MemoryStream(bytes), autoDisposeStream: true);
}
}
}
|
using System.IO;
using System.Net;
using System.Text;
using CefSharp;
using TweetLib.Browser.Interfaces;
using TweetLib.Browser.Request;
namespace TweetDuck.Browser.Adapters {
internal sealed class CefSchemeResourceVisitor : ISchemeResourceVisitor<IResourceHandler> {
public static CefSchemeResourceVisitor Instance { get; } = new CefSchemeResourceVisitor();
private static readonly SchemeResource.Status FileIsEmpty = new SchemeResource.Status(HttpStatusCode.NoContent, "File is empty.");
private CefSchemeResourceVisitor() {}
public IResourceHandler Status(SchemeResource.Status status) {
var handler = CreateHandler(Encoding.UTF8.GetBytes(status.Message));
handler.StatusCode = (int) status.Code;
return handler;
}
public IResourceHandler File(SchemeResource.File file) {
byte[] contents = file.Contents;
if (contents.Length == 0) {
return Status(FileIsEmpty); // FromByteArray crashes CEF internals with no contents
}
var handler = CreateHandler(contents);
handler.MimeType = Cef.GetMimeType(file.Extension);
return handler;
}
private static ResourceHandler CreateHandler(byte[] bytes) {
var handler = ResourceHandler.FromStream(new MemoryStream(bytes), autoDisposeStream: true);
handler.Headers.Set("Access-Control-Allow-Origin", "*");
return handler;
}
}
}
|
mit
|
C#
|
a2d95cb8f78d38a1ffccbf4b200bfee74b6b0a20
|
Fix for Deserialization of complex objects
|
wallaceiam/CQRS.Light,wallaceiam/CQRS.Light,wallaceiam/CQRS.Light,wallaceiam/DDD.Light
|
CQRS.Light.Core/JsonSerializationStrategy.cs
|
CQRS.Light.Core/JsonSerializationStrategy.cs
|
using System;
using CQRS.Light.Contracts;
using Newtonsoft.Json;
using Newtonsoft.Json.Serialization;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
namespace CQRS.Light.Core
{
public class JsonSerializationStrategy : ISerializationStrategy
{
private readonly JsonSerializerSettings deserializeSettings = new JsonSerializerSettings() { ContractResolver = new JsonSerializationContractResolver() };
public string Serialize(object @object)
{
return JsonConvert.SerializeObject(@object);
}
public object Deserialize(string serializedObject, Type objectType)
{
return JsonConvert.DeserializeObject(serializedObject, objectType, deserializeSettings);
}
}
internal class JsonSerializationContractResolver : Newtonsoft.Json.Serialization.DefaultContractResolver
{
protected override IList<JsonProperty> CreateProperties(Type type, MemberSerialization memberSerialization)
{
var props = type.GetProperties(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance)
.Select(p => base.CreateProperty(p, memberSerialization))
.Union(type.GetFields(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance)
.Select(f => base.CreateProperty(f, memberSerialization)))
.ToList();
props.ForEach(p => { p.Writable = true; p.Readable = true; });
return props;
}
}
}
|
using System;
using CQRS.Light.Contracts;
using Newtonsoft.Json;
namespace CQRS.Light.Core
{
public class JsonSerializationStrategy : ISerializationStrategy
{
public string Serialize(object @object)
{
return JsonConvert.SerializeObject(@object);
}
public object Deserialize(string serializedObject, Type objectType)
{
return JsonConvert.DeserializeObject(serializedObject, objectType);
}
}
}
|
mit
|
C#
|
3b3f813a3b2b91518bd68c5a1fece8c4318a50f6
|
Remove all Console.Write calls from InvariantRunner
|
sharper-library/Sharper.C.Testing
|
Sharper.C.Testing/Testing/InvariantRunner.cs
|
Sharper.C.Testing/Testing/InvariantRunner.cs
|
using System;
using System.Collections.Generic;
using Microsoft.FSharp.Core;
using Microsoft.FSharp.Collections;
using FsCheck;
namespace Sharper.C.Testing
{
public struct InvariantRunner
: IRunner
{
private readonly List<InvariantResult> results;
private InvariantRunner(List<InvariantResult> results)
{ this.results = results;
}
public static InvariantRunner Mk()
=> new InvariantRunner(new List<InvariantResult>());
public IEnumerable<InvariantResult> Results
=> results;
public void OnArguments
( int ntest
, FSharpList<object> args
, FSharpFunc<int, FSharpFunc<FSharpList<object>, string>> every
)
=> every.Invoke(ntest).Invoke(args);
public void OnFinished(string name, TestResult result)
=> results.Add(InvariantResult.Mk(name, result));
public void OnShrink
( FSharpList<object> args
, FSharpFunc<FSharpList<object>, string> everyShrink
)
=> everyShrink.Invoke(args);
public void OnStartFixture(Type t)
=> Runner.onStartFixtureToString(t);
}
}
|
using System;
using System.Collections.Generic;
using Microsoft.FSharp.Core;
using Microsoft.FSharp.Collections;
using FsCheck;
namespace Sharper.C.Testing
{
public struct InvariantRunner
: IRunner
{
private readonly List<InvariantResult> results;
private InvariantRunner(List<InvariantResult> results)
{ this.results = results;
}
public static InvariantRunner Mk()
=> new InvariantRunner(new List<InvariantResult>());
public IEnumerable<InvariantResult> Results
=> results;
public void OnArguments
( int ntest
, FSharpList<object> args
, FSharpFunc<int, FSharpFunc<FSharpList<object>, string>> every
)
=> Console.Write(every.Invoke(ntest).Invoke(args));
public void OnFinished(string name, TestResult result)
=> results.Add(InvariantResult.Mk(name, result));
public void OnShrink
( FSharpList<object> args
, FSharpFunc<FSharpList<object>, string> everyShrink
)
=> Console.Write(everyShrink.Invoke(args));
public void OnStartFixture(Type t)
=> Console.Write(Runner.onStartFixtureToString(t));
}
}
|
mit
|
C#
|
17556b5e4647c32c460ba9c31ccef5222c607eb4
|
Change unsupported mutating methods to explicit interface implementations
|
fluentassertions/fluentassertions,jnyrup/fluentassertions,jnyrup/fluentassertions,fluentassertions/fluentassertions
|
Src/FluentAssertions/Common/ReadOnlyNonGenericCollectionWrapper.cs
|
Src/FluentAssertions/Common/ReadOnlyNonGenericCollectionWrapper.cs
|
using System;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using System.Linq;
namespace FluentAssertions.Common;
internal static class ReadOnlyNonGenericCollectionWrapper
{
public static ReadOnlyNonGenericCollectionWrapper<DataTableCollection, DataTable> Create(DataTableCollection collection)
{
return
(collection != null)
? new ReadOnlyNonGenericCollectionWrapper<DataTableCollection, DataTable>(collection)
: null;
}
public static ReadOnlyNonGenericCollectionWrapper<DataColumnCollection, DataColumn> Create(DataColumnCollection collection)
{
return
(collection != null)
? new ReadOnlyNonGenericCollectionWrapper<DataColumnCollection, DataColumn>(collection)
: null;
}
public static ReadOnlyNonGenericCollectionWrapper<DataRowCollection, DataRow> Create(DataRowCollection collection)
{
return
(collection != null)
? new ReadOnlyNonGenericCollectionWrapper<DataRowCollection, DataRow>(collection)
: null;
}
}
internal class ReadOnlyNonGenericCollectionWrapper<TCollection, TItem> : ICollection<TItem>, ICollectionWrapper<TCollection>
where TCollection : ICollection
{
public TCollection UnderlyingCollection { get; }
public ReadOnlyNonGenericCollectionWrapper(TCollection collection)
{
Guard.ThrowIfArgumentIsNull(collection, nameof(collection));
UnderlyingCollection = collection;
}
public int Count => UnderlyingCollection.Count;
bool ICollection<TItem>.IsReadOnly => true;
public IEnumerator<TItem> GetEnumerator() => UnderlyingCollection.Cast<TItem>().GetEnumerator();
IEnumerator IEnumerable.GetEnumerator() => UnderlyingCollection.GetEnumerator();
public bool Contains(TItem item) => UnderlyingCollection.Cast<TItem>().Contains(item);
public void CopyTo(TItem[] array, int arrayIndex) => UnderlyingCollection.CopyTo(array, arrayIndex);
void ICollection<TItem>.Add(TItem item) => throw new NotSupportedException();
void ICollection<TItem>.Clear() => throw new NotSupportedException();
bool ICollection<TItem>.Remove(TItem item) => throw new NotSupportedException();
}
|
using System;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using System.Linq;
namespace FluentAssertions.Common;
internal static class ReadOnlyNonGenericCollectionWrapper
{
public static ReadOnlyNonGenericCollectionWrapper<DataTableCollection, DataTable> Create(DataTableCollection collection)
{
return
(collection != null)
? new ReadOnlyNonGenericCollectionWrapper<DataTableCollection, DataTable>(collection)
: null;
}
public static ReadOnlyNonGenericCollectionWrapper<DataColumnCollection, DataColumn> Create(DataColumnCollection collection)
{
return
(collection != null)
? new ReadOnlyNonGenericCollectionWrapper<DataColumnCollection, DataColumn>(collection)
: null;
}
public static ReadOnlyNonGenericCollectionWrapper<DataRowCollection, DataRow> Create(DataRowCollection collection)
{
return
(collection != null)
? new ReadOnlyNonGenericCollectionWrapper<DataRowCollection, DataRow>(collection)
: null;
}
}
internal class ReadOnlyNonGenericCollectionWrapper<TCollection, TItem> : ICollection<TItem>, ICollectionWrapper<TCollection>
where TCollection : ICollection
{
public TCollection UnderlyingCollection { get; }
public ReadOnlyNonGenericCollectionWrapper(TCollection collection)
{
Guard.ThrowIfArgumentIsNull(collection, nameof(collection));
UnderlyingCollection = collection;
}
public int Count => UnderlyingCollection.Count;
public bool IsReadOnly => true;
public IEnumerator<TItem> GetEnumerator() => UnderlyingCollection.Cast<TItem>().GetEnumerator();
IEnumerator IEnumerable.GetEnumerator() => UnderlyingCollection.GetEnumerator();
public bool Contains(TItem item) => UnderlyingCollection.Cast<TItem>().Contains(item);
public void CopyTo(TItem[] array, int arrayIndex) => UnderlyingCollection.CopyTo(array, arrayIndex);
/*
Mutation is not supported, but these methods must be implemented to satisfy ICollection<T>:
* Add
* Clear
* Remove
*/
public void Add(TItem item) => throw new NotSupportedException();
public void Clear() => throw new NotSupportedException();
public bool Remove(TItem item) => throw new NotSupportedException();
}
|
apache-2.0
|
C#
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.