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
fa07355b3ec7c0b4dfc079da2300be7997900dca
Implement Container
ziyasal/loopback-sdk-net,ziyasal/loopback-sdk-net,ziyasal/loopback-sdk-net
src/LoopBack.Sdk.Xamarin/Loopback/Container.cs
src/LoopBack.Sdk.Xamarin/Loopback/Container.cs
using System; using System.Collections.Generic; using LoopBack.Sdk.Xamarin.Remooting; using PCLStorage; namespace LoopBack.Sdk.Xamarin.Loopback { public class Container : VirtualObject { public virtual string Name { set; get; } /// <summary> /// Upload a new file /// </summary> /// <param name="file">Content of the file.</param> /// <param name="onSuccess">The onSuccess to invoke when the execution finished with success</param> /// <param name="onError">The onSuccess to invoke when the execution finished with error</param> public virtual void Upload(IFile file, Action<File> onSuccess, Action<Exception> onError) { FileRepository.Upload(file, onSuccess, onError); } /// <summary> /// Upload a new file /// </summary> /// <param name="fileName">The file name, must be unique within the container.</param> /// <param name="content">Content of the file.</param> /// <param name="contentType">Content type (optional).</param> /// <param name="onSuccess">The onSuccess to invoke when the execution finished with success</param> /// <param name="onError">The onSuccess to invoke when the execution finished with error</param> public virtual void Upload(string fileName, byte[] content, string contentType, Action<File> onSuccess, Action<Exception> onError) { FileRepository.Upload(fileName, content, contentType, onSuccess, onError); } /// <summary> /// Create a new File object associated with this container. /// </summary> /// <param name="name">The name of the file.</param> /// <returns>The <see cref="File"/> object created</returns> public virtual File CreateFileObject(string name) { return FileRepository.CreateObject(new Dictionary<string, object> { { "name", name } }); } /// <summary> /// Get data of a File object. /// </summary> /// <param name="fileName">The name of the file.</param> /// <param name="onSuccess">The onSuccess to invoke when the execution finished with success</param> /// <param name="onError">The onSuccess to invoke when the execution finished with error</param> public virtual void GetFile(string fileName, Action<File> onSuccess, Action<Exception> onError) { FileRepository.Get(fileName, onSuccess, onError); } /// <summary> /// List all files in the container. /// </summary> /// <param name="onSuccess">The onSuccess to invoke when the execution finished with success</param> /// <param name="onError">The onSuccess to invoke when the execution finished with error</param> public virtual void GetAllFiles(Action<List<File>> onSuccess, Action<Exception> onError) { FileRepository.GetAll(onSuccess, onError); } public virtual FileRepository FileRepository { get { RestAdapter adapter = ((RestAdapter)Repository.Adapter); FileRepository repo = adapter.CreateRepository<FileRepository, File>(); repo.Container = this; return repo; } } } }
using System; using System.Collections.Generic; using LoopBack.Sdk.Xamarin.Remooting; using PCLStorage; namespace LoopBack.Sdk.Xamarin.Loopback { public class Container : VirtualObject { public virtual string Name { set; get; } public virtual void Upload(IFile file, Action<File> onSuccess, Action<Exception> onError) { FileRepository.Upload(file, onSuccess, onError); } public virtual void Upload(string fileName, byte[] content, string contentType, Action<File> onSuccess, Action<Exception> onError) { FileRepository.Upload(fileName, content, contentType, onSuccess, onError); } public virtual File CreateFileObject(string name) { return FileRepository.CreateObject(new Dictionary<string, object> { { "name", name } }); } public virtual void GetFile(string fileName, Action<File> onSuccess, Action<Exception> onError) { FileRepository.Get(fileName, onSuccess, onError); } public virtual void GetAllFiles(Action<List<File>> onSuccess, Action<Exception> onError) { FileRepository.GetAll(onSuccess, onError); } public virtual FileRepository FileRepository { get { RestAdapter adapter = ((RestAdapter)Repository.Adapter); FileRepository repo = adapter.CreateRepository<FileRepository, File>(); repo.Container = this; return repo; } } } }
mit
C#
e1865d8b62ee87a377a21ce314df9f912583a0bb
Remove use of Iesi-specific API.
fredericDelaporte/nhibernate-core,fredericDelaporte/nhibernate-core,ManufacturingIntelligence/nhibernate-core,nkreipke/nhibernate-core,livioc/nhibernate-core,RogerKratz/nhibernate-core,nhibernate/nhibernate-core,RogerKratz/nhibernate-core,hazzik/nhibernate-core,ngbrown/nhibernate-core,ngbrown/nhibernate-core,hazzik/nhibernate-core,nhibernate/nhibernate-core,alobakov/nhibernate-core,ManufacturingIntelligence/nhibernate-core,alobakov/nhibernate-core,lnu/nhibernate-core,hazzik/nhibernate-core,nkreipke/nhibernate-core,fredericDelaporte/nhibernate-core,ngbrown/nhibernate-core,RogerKratz/nhibernate-core,hazzik/nhibernate-core,lnu/nhibernate-core,nkreipke/nhibernate-core,RogerKratz/nhibernate-core,gliljas/nhibernate-core,nhibernate/nhibernate-core,gliljas/nhibernate-core,gliljas/nhibernate-core,livioc/nhibernate-core,livioc/nhibernate-core,lnu/nhibernate-core,alobakov/nhibernate-core,gliljas/nhibernate-core,fredericDelaporte/nhibernate-core,ManufacturingIntelligence/nhibernate-core,nhibernate/nhibernate-core
src/NHibernate.Test/DebugConnectionProvider.cs
src/NHibernate.Test/DebugConnectionProvider.cs
using System; using System.Collections; using System.Collections.Generic; using System.Data; using Iesi.Collections.Generic; using NHibernate.Connection; namespace NHibernate.Test { /// <summary> /// This connection provider keeps a list of all open connections, /// it is used when testing to check that tests clean up after themselves. /// </summary> public class DebugConnectionProvider : DriverConnectionProvider { private ISet<IDbConnection> connections = new HashedSet<IDbConnection>(); public override IDbConnection GetConnection() { try { IDbConnection connection = base.GetConnection(); connections.Add(connection); return connection; } catch (Exception e) { throw new HibernateException("Could not open connection to: " + ConnectionString, e); } } public override void CloseConnection(IDbConnection conn) { base.CloseConnection(conn); connections.Remove(conn); } public bool HasOpenConnections { get { // check to see if all connections that were at one point opened // have been closed through the CloseConnection // method if (connections.Count == 0) { // there are no connections, either none were opened or // all of the closings went through CloseConnection. return false; } else { // Disposing of an ISession does not call CloseConnection (should it???) // so a Diposed of ISession will leave an IDbConnection in the list but // the IDbConnection will be closed (atleast with MsSql it works this way). foreach (IDbConnection conn in connections) { if (conn.State != ConnectionState.Closed) { return true; } } // all of the connections have been Disposed and were closed that way // or they were Closed through the CloseConnection method. return false; } } } public void CloseAllConnections() { while (connections.Count != 0) { IEnumerator en = connections.GetEnumerator(); en.MoveNext(); CloseConnection(en.Current as IDbConnection); } } } }
using System; using System.Collections; using System.Collections.Generic; using System.Data; using Iesi.Collections.Generic; using NHibernate.Connection; namespace NHibernate.Test { /// <summary> /// This connection provider keeps a list of all open connections, /// it is used when testing to check that tests clean up after themselves. /// </summary> public class DebugConnectionProvider : DriverConnectionProvider { private ISet<IDbConnection> connections = new HashedSet<IDbConnection>(); public override IDbConnection GetConnection() { try { IDbConnection connection = base.GetConnection(); connections.Add(connection); return connection; } catch (Exception e) { throw new HibernateException("Could not open connection to: " + ConnectionString, e); } } public override void CloseConnection(IDbConnection conn) { base.CloseConnection(conn); connections.Remove(conn); } public bool HasOpenConnections { get { // check to see if all connections that were at one point opened // have been closed through the CloseConnection // method if (connections.IsEmpty) { // there are no connections, either none were opened or // all of the closings went through CloseConnection. return false; } else { // Disposing of an ISession does not call CloseConnection (should it???) // so a Diposed of ISession will leave an IDbConnection in the list but // the IDbConnection will be closed (atleast with MsSql it works this way). foreach (IDbConnection conn in connections) { if (conn.State != ConnectionState.Closed) { return true; } } // all of the connections have been Disposed and were closed that way // or they were Closed through the CloseConnection method. return false; } } } public void CloseAllConnections() { while (!connections.IsEmpty) { IEnumerator en = connections.GetEnumerator(); en.MoveNext(); CloseConnection(en.Current as IDbConnection); } } } }
lgpl-2.1
C#
be41da85f0cf12e5616316e7136a434fe34f2e8b
Add comments
AlexanderSher/RTVS,MikhailArkhipov/RTVS,karthiknadig/RTVS,MikhailArkhipov/RTVS,AlexanderSher/RTVS,karthiknadig/RTVS,AlexanderSher/RTVS,AlexanderSher/RTVS,AlexanderSher/RTVS,AlexanderSher/RTVS,karthiknadig/RTVS,karthiknadig/RTVS,MikhailArkhipov/RTVS,MikhailArkhipov/RTVS,karthiknadig/RTVS,MikhailArkhipov/RTVS,AlexanderSher/RTVS,karthiknadig/RTVS,MikhailArkhipov/RTVS,karthiknadig/RTVS,MikhailArkhipov/RTVS
src/Package/Impl/Plots/IPlotContentProvider.cs
src/Package/Impl/Plots/IPlotContentProvider.cs
using System; using System.Windows; namespace Microsoft.VisualStudio.R.Package.Plots { /// <summary> /// Plot content provider to load and consume plot content /// </summary> internal interface IPlotContentProvider { /// <summary> /// Event raised when UIElement is loaded, content presenter listens to this event /// </summary> event EventHandler<PlotChangedEventArgs> PlotChanged; /// <summary> /// Loads file on next idle time. Typically used /// in R plotting where several files may get produced /// in a fast succession. Eliminates multiple file loads. /// </summary> /// <param name="filePath"></param> void LoadFileOnIdle(string filePath); /// <summary> /// Load a file to create plot UIElement /// </summary> /// <param name="filePath">path to a file</param> void LoadFile(string filePath); /// <summary> /// Copy last loaded file to destination /// </summary> /// <param name="fileName">the destination filepath</param> void SaveFile(string fileName); } /// <summary> /// provide data ralated to PlotChanged event /// </summary> internal class PlotChangedEventArgs : EventArgs { /// <summary> /// new plot UIElement /// </summary> public UIElement NewPlotElement { get; set; } } }
using System; using System.Windows; namespace Microsoft.VisualStudio.R.Package.Plots { /// <summary> /// Plot content provider to load and consume plot content /// </summary> internal interface IPlotContentProvider { /// <summary> /// Event raised when UIElement is loaded, content presenter listens to this event /// </summary> event EventHandler<PlotChangedEventArgs> PlotChanged; void LoadFileOnIdle(string filePath); /// <summary> /// Load a file to create plot UIElement /// </summary> /// <param name="filePath">path to a file</param> void LoadFile(string filePath); /// <summary> /// Copy last loaded file to destination /// </summary> /// <param name="fileName">the destination filepath</param> void SaveFile(string fileName); } /// <summary> /// provide data ralated to PlotChanged event /// </summary> internal class PlotChangedEventArgs : EventArgs { /// <summary> /// new plot UIElement /// </summary> public UIElement NewPlotElement { get; set; } } }
mit
C#
62f7238796b339fa35ea4e0e383fbaf904edcd7d
Make CMethodId readonly
adamhathcock/sharpcompress,adamhathcock/sharpcompress,adamhathcock/sharpcompress
src/SharpCompress/Common/SevenZip/CMethodId.cs
src/SharpCompress/Common/SevenZip/CMethodId.cs
namespace SharpCompress.Common.SevenZip { internal readonly struct CMethodId { public const ulong K_COPY_ID = 0; public const ulong K_LZMA_ID = 0x030101; public const ulong K_LZMA2_ID = 0x21; public const ulong K_AES_ID = 0x06F10701; public static readonly CMethodId K_COPY = new CMethodId(K_COPY_ID); public static readonly CMethodId K_LZMA = new CMethodId(K_LZMA_ID); public static readonly CMethodId K_LZMA2 = new CMethodId(K_LZMA2_ID); public static readonly CMethodId K_AES = new CMethodId(K_AES_ID); public readonly ulong _id; public CMethodId(ulong id) { _id = id; } public override int GetHashCode() { return _id.GetHashCode(); } public override bool Equals(object obj) { return obj is CMethodId other && Equals(other); } public bool Equals(CMethodId other) { return _id == other._id; } public static bool operator ==(CMethodId left, CMethodId right) { return left._id == right._id; } public static bool operator !=(CMethodId left, CMethodId right) { return left._id != right._id; } public int GetLength() { int bytes = 0; for (ulong value = _id; value != 0; value >>= 8) { bytes++; } return bytes; } } }
namespace SharpCompress.Common.SevenZip { internal struct CMethodId { public const ulong K_COPY_ID = 0; public const ulong K_LZMA_ID = 0x030101; public const ulong K_LZMA2_ID = 0x21; public const ulong K_AES_ID = 0x06F10701; public static readonly CMethodId K_COPY = new CMethodId(K_COPY_ID); public static readonly CMethodId K_LZMA = new CMethodId(K_LZMA_ID); public static readonly CMethodId K_LZMA2 = new CMethodId(K_LZMA2_ID); public static readonly CMethodId K_AES = new CMethodId(K_AES_ID); public readonly ulong _id; public CMethodId(ulong id) { _id = id; } public override int GetHashCode() { return _id.GetHashCode(); } public override bool Equals(object obj) { return obj is CMethodId && (CMethodId)obj == this; } public bool Equals(CMethodId other) { return _id == other._id; } public static bool operator ==(CMethodId left, CMethodId right) { return left._id == right._id; } public static bool operator !=(CMethodId left, CMethodId right) { return left._id != right._id; } public int GetLength() { int bytes = 0; for (ulong value = _id; value != 0; value >>= 8) { bytes++; } return bytes; } } }
mit
C#
ceaae13575cb1ff8db556e1de3605ca77fe05b01
Make DoNotCloneAttribute public
JimBobSquarePants/Umbraco-CMS,dawoe/Umbraco-CMS,arknu/Umbraco-CMS,abryukhov/Umbraco-CMS,abryukhov/Umbraco-CMS,robertjf/Umbraco-CMS,bjarnef/Umbraco-CMS,leekelleher/Umbraco-CMS,mattbrailsford/Umbraco-CMS,marcemarc/Umbraco-CMS,JimBobSquarePants/Umbraco-CMS,JimBobSquarePants/Umbraco-CMS,marcemarc/Umbraco-CMS,umbraco/Umbraco-CMS,umbraco/Umbraco-CMS,KevinJump/Umbraco-CMS,robertjf/Umbraco-CMS,hfloyd/Umbraco-CMS,bjarnef/Umbraco-CMS,arknu/Umbraco-CMS,marcemarc/Umbraco-CMS,umbraco/Umbraco-CMS,dawoe/Umbraco-CMS,abjerner/Umbraco-CMS,KevinJump/Umbraco-CMS,KevinJump/Umbraco-CMS,NikRimington/Umbraco-CMS,dawoe/Umbraco-CMS,leekelleher/Umbraco-CMS,rasmuseeg/Umbraco-CMS,marcemarc/Umbraco-CMS,marcemarc/Umbraco-CMS,madsoulswe/Umbraco-CMS,bjarnef/Umbraco-CMS,tcmorris/Umbraco-CMS,umbraco/Umbraco-CMS,abryukhov/Umbraco-CMS,arknu/Umbraco-CMS,dawoe/Umbraco-CMS,abjerner/Umbraco-CMS,KevinJump/Umbraco-CMS,abryukhov/Umbraco-CMS,tcmorris/Umbraco-CMS,madsoulswe/Umbraco-CMS,tcmorris/Umbraco-CMS,abjerner/Umbraco-CMS,arknu/Umbraco-CMS,tcmorris/Umbraco-CMS,leekelleher/Umbraco-CMS,leekelleher/Umbraco-CMS,rasmuseeg/Umbraco-CMS,KevinJump/Umbraco-CMS,hfloyd/Umbraco-CMS,robertjf/Umbraco-CMS,robertjf/Umbraco-CMS,bjarnef/Umbraco-CMS,dawoe/Umbraco-CMS,mattbrailsford/Umbraco-CMS,madsoulswe/Umbraco-CMS,rasmuseeg/Umbraco-CMS,NikRimington/Umbraco-CMS,mattbrailsford/Umbraco-CMS,tcmorris/Umbraco-CMS,mattbrailsford/Umbraco-CMS,abjerner/Umbraco-CMS,leekelleher/Umbraco-CMS,NikRimington/Umbraco-CMS,JimBobSquarePants/Umbraco-CMS,tcmorris/Umbraco-CMS,hfloyd/Umbraco-CMS,JimBobSquarePants/Umbraco-CMS,hfloyd/Umbraco-CMS,robertjf/Umbraco-CMS,hfloyd/Umbraco-CMS
src/Umbraco.Core/Models/DoNotCloneAttribute.cs
src/Umbraco.Core/Models/DoNotCloneAttribute.cs
using System; namespace Umbraco.Core.Models { /// <summary> /// Used to attribute properties that have a setter and are a reference type /// that should be ignored for cloning when using the DeepCloneHelper /// </summary> /// <remarks> /// /// This attribute must be used: /// * when the property is backed by a field but the result of the property is the un-natural data stored in the field /// /// This attribute should not be used: /// * when the property is virtual /// * when the setter performs additional required logic other than just setting the underlying field /// /// </remarks> public class DoNotCloneAttribute : Attribute { } }
using System; namespace Umbraco.Core.Models { /// <summary> /// Used to attribute properties that have a setter and are a reference type /// that should be ignored for cloning when using the DeepCloneHelper /// </summary> /// <remarks> /// /// This attribute must be used: /// * when the property is backed by a field but the result of the property is the un-natural data stored in the field /// /// This attribute should not be used: /// * when the property is virtual /// * when the setter performs additional required logic other than just setting the underlying field /// /// </remarks> internal class DoNotCloneAttribute : Attribute { } }
mit
C#
a5c29c69cf2eb2bcceb6adf1fe0fe3ad58772525
Disable text tests for now
SteamDatabase/ValveResourceFormat
Tests/TextureTests.cs
Tests/TextureTests.cs
using System; using System.Drawing.Imaging; using System.IO; using NUnit.Framework; using ValveResourceFormat; using ValveResourceFormat.ResourceTypes; namespace Tests { public class TextureTests { [Test] [Ignore("Need a better way of testing images rather than comparing the files directly")] public void Test() { var path = Path.Combine(TestContext.CurrentContext.TestDirectory, "Files", "Textures"); var files = Directory.GetFiles(path, "*.vtex_c"); foreach (var file in files) { var resource = new Resource(); resource.Read(file); var bitmap = ((Texture)resource.Blocks[BlockType.DATA]).GenerateBitmap(); using (var ms = new MemoryStream()) { bitmap.Save(ms, ImageFormat.Png); using (var expected = new FileStream(Path.ChangeExtension(file, "png"), FileMode.Open, FileAccess.Read)) { FileAssert.AreEqual(expected, ms); } } } } } }
using System; using System.Drawing.Imaging; using System.IO; using NUnit.Framework; using ValveResourceFormat; using ValveResourceFormat.ResourceTypes; namespace Tests { public class TextureTests { [Test] public void Test() { var path = Path.Combine(TestContext.CurrentContext.TestDirectory, "Files", "Textures"); var files = Directory.GetFiles(path, "*.vtex_c"); foreach (var file in files) { var resource = new Resource(); resource.Read(file); var bitmap = ((Texture)resource.Blocks[BlockType.DATA]).GenerateBitmap(); using (var ms = new MemoryStream()) { bitmap.Save(ms, ImageFormat.Png); using (var expected = new FileStream(Path.ChangeExtension(file, "png"), FileMode.Open, FileAccess.Read)) { FileAssert.AreEqual(expected, ms); } } } } } }
mit
C#
6ff70a04d430983ab529ce40425a4a81eb37d9af
add support for per developer config files
sachatrauwaen/OpenApp,sachatrauwaen/OpenApp,sachatrauwaen/OpenApp,sachatrauwaen/OpenApp,sachatrauwaen/OpenApp,sachatrauwaen/OpenApp
src/Satrabel.OpenApp.Domain/Configuration/AppConfigurations.cs
src/Satrabel.OpenApp.Domain/Configuration/AppConfigurations.cs
using System; using System.Collections.Concurrent; using System.IO; using Abp.Extensions; using Abp.Reflection.Extensions; using Microsoft.Extensions.Configuration; namespace Satrabel.OpenApp.Configuration { public static class AppConfigurations { private static readonly ConcurrentDictionary<string, IConfigurationRoot> ConfigurationCache; static AppConfigurations() { ConfigurationCache = new ConcurrentDictionary<string, IConfigurationRoot>(); } public static IConfigurationRoot Get(string path, string environmentName = null, bool addUserSecrets = false) { var cacheKey = path + "#" + environmentName + "#" + addUserSecrets; return ConfigurationCache.GetOrAdd( cacheKey, _ => BuildConfiguration(path, environmentName, addUserSecrets) ); } /// <summary> /// based on http://www.michielpost.nl/PostDetail_2081.aspx /// </summary> /// <param name="path"></param> /// <param name="environmentName"></param> /// <param name="addUserSecrets"></param> /// <returns></returns> /// <remarks> /// Searches for /// - appsettings.json /// - appsettings.{environmentName}.json (Staging,Development, ...) //http://docs.asp.net/en/latest/fundamentals/environments.html /// - /Configuration/appsettings.{computerName}.json // in subfolder that can be excluded from .git /// - EnvironmentVariables() /// </remarks> private static IConfigurationRoot BuildConfiguration(string path, string environmentName = null, bool addUserSecrets = false) { var builder = new ConfigurationBuilder() .SetBasePath(path) .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true); if (!environmentName.IsNullOrWhiteSpace()) { builder = builder.AddJsonFile($"appsettings.{environmentName}.json", optional: true); } var computerName = Environment.GetEnvironmentVariable("COMPUTERNAME"); builder = builder.AddJsonFile(Path.Combine("Configuration", $"appsettings.{computerName}.json"), optional: true); builder = builder.AddEnvironmentVariables(); // https://docs.microsoft.com/en-us/aspnet/core/security/app-secrets?tabs=visual-studio if (addUserSecrets) { builder.AddUserSecrets(typeof(AppConfigurations).GetAssembly()); } return builder.Build(); } } }
using System.Collections.Concurrent; using Abp.Extensions; using Abp.Reflection.Extensions; using Microsoft.Extensions.Configuration; namespace Satrabel.OpenApp.Configuration { public static class AppConfigurations { private static readonly ConcurrentDictionary<string, IConfigurationRoot> ConfigurationCache; static AppConfigurations() { ConfigurationCache = new ConcurrentDictionary<string, IConfigurationRoot>(); } public static IConfigurationRoot Get(string path, string environmentName = null, bool addUserSecrets = false) { var cacheKey = path + "#" + environmentName + "#" + addUserSecrets; return ConfigurationCache.GetOrAdd( cacheKey, _ => BuildConfiguration(path, environmentName, addUserSecrets) ); } private static IConfigurationRoot BuildConfiguration(string path, string environmentName = null, bool addUserSecrets = false) { var builder = new ConfigurationBuilder() .SetBasePath(path) .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true); if (!environmentName.IsNullOrWhiteSpace()) { builder = builder.AddJsonFile($"appsettings.{environmentName}.json", optional: true); } builder = builder.AddEnvironmentVariables(); if (addUserSecrets) { builder.AddUserSecrets(typeof(AppConfigurations).GetAssembly()); } return builder.Build(); } } }
mit
C#
6440ec51d6f1010fb44bc4f5de4eab3811594d72
Fix for invalid syntax
thinkabouthub/NugetyCore
src/NugetyCore.AspNetCore/Extensions/Microsoft.Extensions.DependencyInjection.IMvcBuilder.cs
src/NugetyCore.AspNetCore/Extensions/Microsoft.Extensions.DependencyInjection.IMvcBuilder.cs
using System; using System.Collections.Generic; using Microsoft.Extensions.DependencyInjection; namespace Nugety { public static class IMvcBuilderExtensions { public static IMvcBuilder InitialiseModules(this IMvcBuilder builder, IEnumerable<IModuleInitializer> modules) { foreach (var m in modules) m.ConfigureServices(builder.Services, builder); return builder; } public static IMvcBuilder InitialiseModules(this IMvcBuilder builder, IEnumerable<ModuleInfo> modules) { foreach (var m in modules) { var initializer = m.Catalog.Load<IModuleInitializer>(m); initializer.ConfigureServices(builder.Services, builder); } return builder; } public static IMvcBuilder InitialiseModules(this IMvcBuilder builder, string fileNameFilterPattern, params string[] moduleName) { var modules = new NugetyCatalog() .Options.SetModuleFileNameFilter(fileNameFilterPattern) .FromDirectory() .GetModules<IModuleInitializer>(moduleName).Load(); builder.InitialiseModules(modules); return builder; } public static IMvcBuilder InitialiseModules(this IMvcBuilder builder, params string[] moduleName) { var modules = new NugetyCatalog() .FromDirectory() .GetModules<IModuleInitializer>(moduleName).Load(); builder.InitialiseModules(modules); return builder; } public static IMvcBuilder AddApplicationPartByType(this IMvcBuilder builder, params Type[] types) { builder.ConfigureApplicationPartManager(manager => { manager.ApplicationParts.Add(new TypesPart(types)); }); return builder; } } }
using System; using System.Collections.Generic; using Microsoft.Extensions.DependencyInjection; namespace Nugety { public static class IMvcBuilderExtensions { public static IMvcBuilder InitialiseModules(this IMvcBuilder builder, IEnumerable<IModuleInitializer> modules) { foreach (var m in modules) m.ConfigureServices(builder.Services, builder); return builder; } public static IMvcBuilder InitialiseModules(this IMvcBuilder builder, IEnumerable<ModuleInfo> modules) { foreach (var m in modules) { var initializer = m.Catalog.Load<IModuleInitializer>(m); initializer.ConfigureServices(builder.Services, builder); } return builder; } public static IMvcBuilder InitialiseModules(this IMvcBuilder builder, string fileNameFilterPattern, params string[] moduleName) { var modules = new NugetyCatalog() .Options.SetFileNameFilterPattern(fileNameFilterPattern) .FromDirectory() .GetModules<IModuleInitializer>(moduleName).Load(); builder.InitialiseModules(modules); return builder; } public static IMvcBuilder InitialiseModules(this IMvcBuilder builder, params string[] moduleName) { var modules = new NugetyCatalog() .FromDirectory() .GetModules<IModuleInitializer>(moduleName).Load(); builder.InitialiseModules(modules); return builder; } public static IMvcBuilder AddApplicationPartByType(this IMvcBuilder builder, params Type[] types) { builder.ConfigureApplicationPartManager(manager => { manager.ApplicationParts.Add(new TypesPart(types)); }); return builder; } } }
agpl-3.0
C#
34077a01266f39236e93a45f0c512b5372e94b16
Update WalletWasabi.Fluent/ViewModels/Dialog/IDialogHost.cs
nopara73/HiddenWallet,nopara73/HiddenWallet,nopara73/HiddenWallet,nopara73/HiddenWallet
WalletWasabi.Fluent/ViewModels/Dialog/IDialogHost.cs
WalletWasabi.Fluent/ViewModels/Dialog/IDialogHost.cs
using System; namespace WalletWasabi.Fluent.ViewModels.Dialog { /// <summary> /// Interface for ViewModels that can host a modal dialog. /// </summary> public interface IDialogHost { /// <summary> /// The currently active dialog. The modal dialog UI should close when this is null. /// </summary> DialogViewModelBase? CurrentDialog { get; set; } } }
#nullable enable using System; namespace WalletWasabi.Fluent.ViewModels.Dialog { /// <summary> /// Interface for ViewModels that can host a modal dialog. /// </summary> public interface IDialogHost { /// <summary> /// The currently active dialog. The modal dialog UI should close when this is null. /// </summary> DialogViewModelBase? CurrentDialog { get; set; } } }
mit
C#
0cab02e955cf76c8b78c4887af0dac274c4ca26d
insert seed data into demo db
christianacca/EntityFramework-MultiMigrate,christianacca/EntityFramework-MultiMigrate,christianacca/EntityFramework-MultiMigrate,christianacca/EntityFramework-MultiMigrate
sample/SegregatedMigrationSample/LibraryMigrations/Migrations/Configuration.cs
sample/SegregatedMigrationSample/LibraryMigrations/Migrations/Configuration.cs
using System.Data.Entity.Migrations; using CcAcca.BaseLibrary; using BaseLibraryConfiguration = CcAcca.BaseLibraryMigrations.Migrations.Configuration; namespace CcAcca.LibraryMigrations.Migrations { public sealed class Configuration : DbMigrationsConfiguration<LibraryDbContext> { public Configuration() { AutomaticMigrationsEnabled = false; } protected override void Seed(LibraryDbContext context) { // we need to create seed data for the BaseLibrary in our database // problem is CcAcca.LibraryMigrations.LibraryDbContext can't be used for that... // so instead we need to new up the BaseLibraryDbContext using the current connection to our db var baseLibraryDbContext = new BaseLibraryDbContext(context.Database.Connection, false); var statusLookup = new Lookup { Name = "Order Status" }; baseLibraryDbContext.Lookups.AddOrUpdate(x => x.Name, statusLookup); var inactiveItem = new LookupItem { Code = "P", Description = "Placed", LookupId = statusLookup.Id }; var activeItem = new LookupItem { Code = "D", Description = "Dispatched", LookupId = statusLookup.Id }; var items = new[] { inactiveItem, activeItem }; baseLibraryDbContext.LookupItems.AddOrUpdate(x => new { x.Code, x.LookupId }, items); baseLibraryDbContext.Addresses.AddRange(new[] { new Address {Line1 = "10 Somewhere", Line3 = "Chatham", Line4 = "Kent", Postcode = "xxx xxx"}, new Address {Line1 = "10 Somewhere else", Line3 = "Gravesend", Line4 = "Kent", Postcode = "yyy yyy"}, }); baseLibraryDbContext.SaveChanges(); } } }
using System.Data.Entity.Migrations; using CcAcca.BaseLibrary; using BaseLibraryConfiguration = CcAcca.BaseLibraryMigrations.Migrations.Configuration; namespace CcAcca.LibraryMigrations.Migrations { public sealed class Configuration : DbMigrationsConfiguration<LibraryDbContext> { public Configuration() { AutomaticMigrationsEnabled = false; } protected override void Seed(LibraryDbContext context) { // we need to create seed data for the BaseLibrary in our database // problem is CcAcca.LibraryMigrations.LibraryDbContext can't be used for that... // so instead we need to new up the BaseLibraryDbContext using the current connection to our db var baseLibraryDbContext = new BaseLibraryDbContext(context.Database.Connection, false); var statusLookup = new Lookup { Name = "Order Status" }; baseLibraryDbContext.Lookups.AddOrUpdate(x => x.Name, statusLookup); var inactiveItem = new LookupItem { Code = "P", Description = "Placed", LookupId = statusLookup.Id }; var activeItem = new LookupItem { Code = "D", Description = "Dispatched", LookupId = statusLookup.Id }; var items = new[] { inactiveItem, activeItem }; baseLibraryDbContext.LookupItems.AddOrUpdate(x => new { x.Code, x.LookupId }, items); baseLibraryDbContext.SaveChanges(); } } }
mit
C#
7f5a3398f3f24c5ca49e033af8757e97f4e39cef
Fix enum comparision in `LocalisableStringEqualityComparer`
smoogipooo/osu-framework,ZLima12/osu-framework,peppy/osu-framework,peppy/osu-framework,ppy/osu-framework,smoogipooo/osu-framework,ZLima12/osu-framework,ppy/osu-framework,ppy/osu-framework,peppy/osu-framework
osu.Framework/Localisation/LocalisableStringEqualityComparer.cs
osu.Framework/Localisation/LocalisableStringEqualityComparer.cs
// Copyright (c) ppy Pty Ltd <[email protected]>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using System; using System.Collections.Generic; namespace osu.Framework.Localisation { /// <summary> /// An equality comparer for the <see cref="LocalisableString"/> type. /// </summary> public class LocalisableStringEqualityComparer : IEqualityComparer<LocalisableString> { // ReSharper disable once InconsistentNaming (follows EqualityComparer<T>.Default) public static readonly LocalisableStringEqualityComparer Default = new LocalisableStringEqualityComparer(); public bool Equals(LocalisableString x, LocalisableString y) { var xData = x.Data; var yData = y.Data; if (ReferenceEquals(null, xData) != ReferenceEquals(null, yData)) return false; if (ReferenceEquals(null, xData)) return true; if (x.Casing != y.Casing) return false; if (xData.GetType() != yData.GetType()) return EqualityComparer<object>.Default.Equals(xData, yData); switch (xData) { case string strX: return strX.Equals((string)yData, StringComparison.Ordinal); case ILocalisableStringData dataX: return dataX.Equals((ILocalisableStringData)yData); } return false; } public int GetHashCode(LocalisableString obj) => HashCode.Combine(obj.Data?.GetType(), obj.Data); } }
// Copyright (c) ppy Pty Ltd <[email protected]>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using System; using System.Collections.Generic; namespace osu.Framework.Localisation { /// <summary> /// An equality comparer for the <see cref="LocalisableString"/> type. /// </summary> public class LocalisableStringEqualityComparer : IEqualityComparer<LocalisableString> { // ReSharper disable once InconsistentNaming (follows EqualityComparer<T>.Default) public static readonly LocalisableStringEqualityComparer Default = new LocalisableStringEqualityComparer(); public bool Equals(LocalisableString x, LocalisableString y) { var xData = x.Data; var yData = y.Data; if (ReferenceEquals(null, xData) != ReferenceEquals(null, yData)) return false; if (ReferenceEquals(null, xData)) return true; if (x.Casing == y.Casing) return true; if (xData.GetType() != yData.GetType()) return EqualityComparer<object>.Default.Equals(xData, yData); switch (xData) { case string strX: return strX.Equals((string)yData, StringComparison.Ordinal); case ILocalisableStringData dataX: return dataX.Equals((ILocalisableStringData)yData); } return false; } public int GetHashCode(LocalisableString obj) => HashCode.Combine(obj.Data?.GetType(), obj.Data); } }
mit
C#
0e9d860ec09beb750090e430c83d0f38b6048b0d
Ajuste na validação IE Alagoas
martinusso/docsbr.net
DocsBr/Validation/IE/IEAlagoasValidator.cs
DocsBr/Validation/IE/IEAlagoasValidator.cs
using System; using System.Linq; using DocsBr.Utils; namespace DocsBr.Validation.IE { public class IEAlagoasValidator : IIEValidator { private string inscEstadual; public IEAlagoasValidator(string inscEstadual) { this.inscEstadual = new OnlyNumbers(inscEstadual).ToString(); } public bool IsValid() { if (!IsCompanyTypeValid()) return false; return HasValidCheckDigits(); } private bool IsCompanyTypeValid() { /* * X – Tipo de empresa ( * 0-Normal, * 3-Produtor Rural, * 5-Substituta, * 7- Micro-Empresa Ambulante, * 8-Micro-Empresa) */ /* Desabilitado pois existe IEs válidas que não se enquadram nessa regra. string[] validTypes = {"0", "3", "5", "7", "8"}; string number = this.inscEstadual.Substring(2, 1); return validTypes.Contains(number); */ return true; } private bool HasValidCheckDigits() { string number = this.inscEstadual.Substring(0, this.inscEstadual.Length - 1); DigitoVerificador digitoVerificador = new DigitoVerificador(number) .Substituindo("0", 10, 11); return digitoVerificador.CalculaDigito() == this.inscEstadual.Substring(this.inscEstadual.Length - 1, 1); } } }
using System; using System.Linq; using DocsBr.Utils; namespace DocsBr.Validation.IE { public class IEAlagoasValidator : IIEValidator { private string inscEstadual; public IEAlagoasValidator(string inscEstadual) { this.inscEstadual = new OnlyNumbers(inscEstadual).ToString(); } public bool IsValid() { if (!IsCompanyTypeValid()) return false; return HasValidCheckDigits(); } private bool IsCompanyTypeValid() { /* * X – Tipo de empresa ( * 0-Normal, * 3-Produtor Rural, * 5-Substituta, * 7- Micro-Empresa Ambulante, * 8-Micro-Empresa) */ string[] validTypes = {"0", "3", "5", "7", "8"}; string number = this.inscEstadual.Substring(2, 1); return validTypes.Contains(number); } private bool HasValidCheckDigits() { string number = this.inscEstadual.Substring(0, this.inscEstadual.Length - 1); DigitoVerificador digitoVerificador = new DigitoVerificador(number) .Substituindo("0", 10, 11); return digitoVerificador.CalculaDigito() == this.inscEstadual.Substring(this.inscEstadual.Length - 1, 1); } } }
mit
C#
ae7f4f9a1a47dbb08e51a99fc6edbc0598334ba1
Support to map swagger UI to application root url
domaindrivendev/Swashbuckle.AspNetCore,domaindrivendev/Ahoy,domaindrivendev/Swashbuckle.AspNetCore,domaindrivendev/Ahoy,domaindrivendev/Swashbuckle.AspNetCore,domaindrivendev/Ahoy
src/Swashbuckle.AspNetCore.SwaggerUI/Application/SwaggerUIBuilderExtensions.cs
src/Swashbuckle.AspNetCore.SwaggerUI/Application/SwaggerUIBuilderExtensions.cs
using System; using Microsoft.AspNetCore.StaticFiles; using Swashbuckle.AspNetCore.SwaggerUI; namespace Microsoft.AspNetCore.Builder { public static class SwaggerUIBuilderExtensions { public static IApplicationBuilder UseSwaggerUI( this IApplicationBuilder app, Action<SwaggerUIOptions> setupAction) { var options = new SwaggerUIOptions(); setupAction?.Invoke(options); // Serve swagger-ui assets with the FileServer middleware, using a custom FileProvider // to inject parameters into "index.html" var fileServerOptions = new FileServerOptions { RequestPath = string.IsNullOrWhiteSpace(options.RoutePrefix) ? string.Empty : $"/{options.RoutePrefix}", FileProvider = new SwaggerUIFileProvider(options.IndexSettings.ToTemplateParameters()), EnableDefaultFiles = true, // serve index.html at /{options.RoutePrefix}/ }; fileServerOptions.StaticFileOptions.ContentTypeProvider = new FileExtensionContentTypeProvider(); app.UseFileServer(fileServerOptions); return app; } } }
using System; using Microsoft.AspNetCore.StaticFiles; using Swashbuckle.AspNetCore.SwaggerUI; namespace Microsoft.AspNetCore.Builder { public static class SwaggerUIBuilderExtensions { public static IApplicationBuilder UseSwaggerUI( this IApplicationBuilder app, Action<SwaggerUIOptions> setupAction) { var options = new SwaggerUIOptions(); setupAction?.Invoke(options); // Serve swagger-ui assets with the FileServer middleware, using a custom FileProvider // to inject parameters into "index.html" var fileServerOptions = new FileServerOptions { RequestPath = $"/{options.RoutePrefix}", FileProvider = new SwaggerUIFileProvider(options.IndexSettings.ToTemplateParameters()), EnableDefaultFiles = true, // serve index.html at /{options.RoutePrefix}/ }; fileServerOptions.StaticFileOptions.ContentTypeProvider = new FileExtensionContentTypeProvider(); app.UseFileServer(fileServerOptions); return app; } } }
mit
C#
ef33d70f96417a8bccb3814d6f9781fb94a72ac4
Use animation
sakapon/Tools-2016
IntelliRps/IntelliRpsLeap/MainViewModel.cs
IntelliRps/IntelliRpsLeap/MainViewModel.cs
using System; using System.Collections.Generic; using System.Linq; using System.Reactive.Linq; using System.Windows; using IntelliRps; using Reactive.Bindings; namespace IntelliRpsLeap { public class MainViewModel { public static readonly Func<RpsShape?, string> ToImagePath1 = s => s.HasValue ? $"Images/{s}-1.png" : null; public static readonly Func<RpsShape?, string> ToImagePath2 = s => s.HasValue ? $"Images/{s}-2.png" : null; public static readonly Func<bool, Visibility> ToVisible = b => b ? Visibility.Visible : Visibility.Hidden; public static readonly Func<bool, Visibility> ToHidden = b => b ? Visibility.Hidden : Visibility.Visible; public static readonly Func<MatchResult, string> ToMatchResultColor = r => r == MatchResult.Win ? "#FF009900" : r == MatchResult.Tie ? "#FFFFBB00" : "#FFCC0000"; public AppModel AppModel { get; } = new AppModel(); public ReactiveProperty<double> MatchesListWidth { get; } = new ReactiveProperty<double>(); public ReactiveProperty<double> MatchesListX { get; } = new ReactiveProperty<double>(); public MainViewModel() { MatchesListWidth .Where(width => width + MatchesListX.Value > 800) .Subscribe(_ => ScrollMatchesList()); } void ScrollMatchesList() { var renderingCount = NextRenderingCount(); var d = NextXDelta() / renderingCount; Observable.Timer(NextScrollDelay(), RenderingPeriod) .Take(renderingCount) .Subscribe(_ => MatchesListX.Value -= d); } static readonly TimeSpan RenderingPeriod = TimeSpan.FromSeconds(0.015); static readonly Random Random = new Random(); static double NextXDelta() => Random.Next(150, 250); static int NextRenderingCount() => Random.Next(20, 50); static TimeSpan NextScrollDelay() => TimeSpan.FromMilliseconds(Random.Next(100, 500)); } }
using System; using System.Collections.Generic; using System.Linq; using System.Reactive.Linq; using System.Windows; using IntelliRps; using Reactive.Bindings; namespace IntelliRpsLeap { public class MainViewModel { public static readonly Func<RpsShape?, string> ToImagePath1 = s => s.HasValue ? $"Images/{s}-1.png" : null; public static readonly Func<RpsShape?, string> ToImagePath2 = s => s.HasValue ? $"Images/{s}-2.png" : null; public static readonly Func<bool, Visibility> ToVisible = b => b ? Visibility.Visible : Visibility.Hidden; public static readonly Func<bool, Visibility> ToHidden = b => b ? Visibility.Hidden : Visibility.Visible; public static readonly Func<MatchResult, string> ToMatchResultColor = r => r == MatchResult.Win ? "#FF009900" : r == MatchResult.Tie ? "#FFFFBB00" : "#FFCC0000"; public AppModel AppModel { get; } = new AppModel(); public ReactiveProperty<double> MatchesListWidth { get; } = new ReactiveProperty<double>(); public ReactiveProperty<double> MatchesListX { get; } = new ReactiveProperty<double>(); public MainViewModel() { MatchesListWidth .Where(width => width + MatchesListX.Value > 900) .Subscribe(_ => MatchesListX.Value -= 200); } } }
mit
C#
404a6b231ddef2ec7b4b4f012feb1dd0965d571e
Fix .NET 461 failures
adamhathcock/sharpcompress,adamhathcock/sharpcompress,adamhathcock/sharpcompress
tests/SharpCompress.Test/Zip/ZipWriterTests.cs
tests/SharpCompress.Test/Zip/ZipWriterTests.cs
using System.Text; using SharpCompress.Common; using Xunit; namespace SharpCompress.Test.Zip { public class ZipWriterTests : WriterTests { public ZipWriterTests() : base(ArchiveType.Zip) { } [Fact] public void Zip_Deflate_Write() { Write(CompressionType.Deflate, "Zip.deflate.noEmptyDirs.zip", "Zip.deflate.noEmptyDirs.zip", Encoding.UTF8); } [Fact] public void Zip_BZip2_Write() { Write(CompressionType.BZip2, "Zip.bzip2.noEmptyDirs.zip", "Zip.bzip2.noEmptyDirs.zip", Encoding.UTF8); } [Fact] public void Zip_None_Write() { Write(CompressionType.None, "Zip.none.noEmptyDirs.zip", "Zip.none.noEmptyDirs.zip", Encoding.UTF8); } [Fact] public void Zip_LZMA_Write() { Write(CompressionType.LZMA, "Zip.lzma.noEmptyDirs.zip", "Zip.lzma.noEmptyDirs.zip", Encoding.UTF8); } [Fact] public void Zip_PPMd_Write() { Write(CompressionType.PPMd, "Zip.ppmd.noEmptyDirs.zip", "Zip.ppmd.noEmptyDirs.zip", Encoding.UTF8); } [Fact] public void Zip_Rar_Write() { Assert.Throws<InvalidFormatException>(() => Write(CompressionType.Rar, "Zip.ppmd.noEmptyDirs.zip", "Zip.ppmd.noEmptyDirs.zip")); } } }
using SharpCompress.Common; using Xunit; namespace SharpCompress.Test.Zip { public class ZipWriterTests : WriterTests { public ZipWriterTests() : base(ArchiveType.Zip) { } #if !NET461 // Failing on net461 [Fact] public void Zip_Deflate_Write() { Write(CompressionType.Deflate, "Zip.deflate.noEmptyDirs.zip", "Zip.deflate.noEmptyDirs.zip"); } // Failing on net461 [Fact] public void Zip_BZip2_Write() { Write(CompressionType.BZip2, "Zip.bzip2.noEmptyDirs.zip", "Zip.bzip2.noEmptyDirs.zip"); } // Failing on net461 [Fact] public void Zip_None_Write() { Write(CompressionType.None, "Zip.none.noEmptyDirs.zip", "Zip.none.noEmptyDirs.zip"); } // Failing on net461 [Fact] public void Zip_LZMA_Write() { Write(CompressionType.LZMA, "Zip.lzma.noEmptyDirs.zip", "Zip.lzma.noEmptyDirs.zip"); } // Failing on net461 [Fact] public void Zip_PPMd_Write() { Write(CompressionType.PPMd, "Zip.ppmd.noEmptyDirs.zip", "Zip.ppmd.noEmptyDirs.zip"); } #endif [Fact] public void Zip_Rar_Write() { Assert.Throws<InvalidFormatException>(() => Write(CompressionType.Rar, "Zip.ppmd.noEmptyDirs.zip", "Zip.ppmd.noEmptyDirs.zip")); } } }
mit
C#
09f9c480e4073cbbd1e7e5759a28c512e0ad1485
Add registration options for hover request
PowerShell/PowerShellEditorServices
src/PowerShellEditorServices.Protocol/LanguageServer/Hover.cs
src/PowerShellEditorServices.Protocol/LanguageServer/Hover.cs
// // Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. // using Microsoft.PowerShell.EditorServices.Protocol.MessageProtocol; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Microsoft.PowerShell.EditorServices.Protocol.LanguageServer { public class MarkedString { public string Language { get; set; } public string Value { get; set; } } public class Hover { public MarkedString[] Contents { get; set; } public Range? Range { get; set; } } public class HoverRequest { public static readonly RequestType<TextDocumentPositionParams, Hover, object, TextDocumentRegistrationOptions> Type = RequestType<TextDocumentPositionParams, Hover, object, TextDocumentRegistrationOptions>.Create("textDocument/hover"); } }
// // Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. // using Microsoft.PowerShell.EditorServices.Protocol.MessageProtocol; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Microsoft.PowerShell.EditorServices.Protocol.LanguageServer { public class MarkedString { public string Language { get; set; } public string Value { get; set; } } public class Hover { public MarkedString[] Contents { get; set; } public Range? Range { get; set; } } public class HoverRequest { public static readonly RequestType<TextDocumentPositionParams, Hover, object, object> Type = RequestType<TextDocumentPositionParams, Hover, object, object>.Create("textDocument/hover"); } }
mit
C#
c20f72fa080b1bb1393d15c5191e30130964db44
Fix VSTS build API url: "builds" should be "build" (#1303)
ericstj/buildtools,nguerrera/buildtools,chcosta/buildtools,alexperovich/buildtools,alexperovich/buildtools,dotnet/buildtools,mmitche/buildtools,crummel/dotnet_buildtools,MattGal/buildtools,MattGal/buildtools,tarekgh/buildtools,ericstj/buildtools,AlexGhiondea/buildtools,karajas/buildtools,dotnet/buildtools,AlexGhiondea/buildtools,nguerrera/buildtools,JeremyKuhne/buildtools,karajas/buildtools,MattGal/buildtools,ChadNedzlek/buildtools,alexperovich/buildtools,alexperovich/buildtools,ChadNedzlek/buildtools,weshaggard/buildtools,jthelin/dotnet-buildtools,mmitche/buildtools,dotnet/buildtools,stephentoub/buildtools,mmitche/buildtools,jthelin/dotnet-buildtools,crummel/dotnet_buildtools,nguerrera/buildtools,ChadNedzlek/buildtools,tarekgh/buildtools,ChadNedzlek/buildtools,dotnet/buildtools,jthelin/dotnet-buildtools,stephentoub/buildtools,chcosta/buildtools,joperezr/buildtools,joperezr/buildtools,JeremyKuhne/buildtools,joperezr/buildtools,tarekgh/buildtools,ericstj/buildtools,stephentoub/buildtools,JeremyKuhne/buildtools,alexperovich/buildtools,joperezr/buildtools,karajas/buildtools,crummel/dotnet_buildtools,joperezr/buildtools,weshaggard/buildtools,MattGal/buildtools,mmitche/buildtools,AlexGhiondea/buildtools,tarekgh/buildtools,mmitche/buildtools,ericstj/buildtools,AlexGhiondea/buildtools,nguerrera/buildtools,chcosta/buildtools,stephentoub/buildtools,weshaggard/buildtools,jthelin/dotnet-buildtools,tarekgh/buildtools,karajas/buildtools,crummel/dotnet_buildtools,weshaggard/buildtools,JeremyKuhne/buildtools,chcosta/buildtools,MattGal/buildtools
src/Microsoft.DotNet.Build.VstsBuildsApi/VstsBuildHttpClient.cs
src/Microsoft.DotNet.Build.VstsBuildsApi/VstsBuildHttpClient.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 Microsoft.DotNet.Build.VstsBuildsApi.Configuration; using Newtonsoft.Json.Linq; using System; namespace Microsoft.DotNet.Build.VstsBuildsApi { internal class VstsBuildHttpClient : VstsDefinitionHttpClient { private const string BuildApiType = "build"; public VstsBuildHttpClient(JObject definition, VstsApiEndpointConfig config) : base(new Uri(definition["project"]["url"].ToString()), config, BuildApiType) { } protected override bool IsMatching(JObject localDefinition, JObject retrievedDefinition) { return localDefinition["quality"].ToString() == "definition" && localDefinition["path"].ToString() == retrievedDefinition["path"].ToString(); } protected override string GetDefinitionProject(JObject definition) { return definition["project"]["name"].ToString(); } } }
// 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 Microsoft.DotNet.Build.VstsBuildsApi.Configuration; using Newtonsoft.Json.Linq; using System; namespace Microsoft.DotNet.Build.VstsBuildsApi { internal class VstsBuildHttpClient : VstsDefinitionHttpClient { private const string BuildApiType = "builds"; public VstsBuildHttpClient(JObject definition, VstsApiEndpointConfig config) : base(new Uri(definition["project"]["url"].ToString()), config, BuildApiType) { } protected override bool IsMatching(JObject localDefinition, JObject retrievedDefinition) { return localDefinition["quality"].ToString() == "definition" && localDefinition["path"].ToString() == retrievedDefinition["path"].ToString(); } protected override string GetDefinitionProject(JObject definition) { return definition["project"]["name"].ToString(); } } }
mit
C#
e6992e15dfe8ec53c29d482c73a61fcfaa1222d5
make sure we don't check for null twice
mruhul/Bolt.MayBe
src/Bolt.MayBe/MayBe.cs
src/Bolt.MayBe/MayBe.cs
namespace Bolt.Monad { public class MayBe<T> { public static readonly MayBe<T> None = new MayBe<T>(); private MayBe() { } public MayBe(T value) { Value = value; HasValue = value != null; } internal MayBe(T value, bool hasValue) { Value = value; HasValue = hasValue; } public T Value { get; private set; } public bool HasValue { get; private set; } public bool IsNone { get { return !HasValue; } } public T ValueOrDefault(T defaultValue) { return HasValue ? Value : defaultValue; } public static implicit operator MayBe<T>(T value) { return value == null ? None : new MayBe<T>(value, true); } public static implicit operator T(MayBe<T> maybe) { return maybe.Value; } } }
namespace Bolt.Monad { public class MayBe<T> { public static readonly MayBe<T> None = new MayBe<T>(); private MayBe() { } public MayBe(T value) { Value = value; HasValue = value != null; } public T Value { get; private set; } public bool HasValue { get; private set; } public bool IsNone { get { return !HasValue; } } public T ValueOrDefault(T defaultValue) { return HasValue ? Value : defaultValue; } public static implicit operator MayBe<T>(T value) { return value == null ? None : new MayBe<T>(value); } public static implicit operator T(MayBe<T> maybe) { return maybe.Value; } } }
apache-2.0
C#
2eda70542f4c063fe77f7026eba69153ea087aec
rename macro container to macro picker
NikRimington/Umbraco-CMS,marcemarc/Umbraco-CMS,WebCentrum/Umbraco-CMS,robertjf/Umbraco-CMS,arknu/Umbraco-CMS,PeteDuncanson/Umbraco-CMS,aadfPT/Umbraco-CMS,marcemarc/Umbraco-CMS,umbraco/Umbraco-CMS,kgiszewski/Umbraco-CMS,abryukhov/Umbraco-CMS,abjerner/Umbraco-CMS,dawoe/Umbraco-CMS,aadfPT/Umbraco-CMS,base33/Umbraco-CMS,hfloyd/Umbraco-CMS,bjarnef/Umbraco-CMS,madsoulswe/Umbraco-CMS,tcmorris/Umbraco-CMS,JeffreyPerplex/Umbraco-CMS,umbraco/Umbraco-CMS,abjerner/Umbraco-CMS,WebCentrum/Umbraco-CMS,kgiszewski/Umbraco-CMS,leekelleher/Umbraco-CMS,aaronpowell/Umbraco-CMS,dawoe/Umbraco-CMS,tcmorris/Umbraco-CMS,dawoe/Umbraco-CMS,KevinJump/Umbraco-CMS,base33/Umbraco-CMS,mattbrailsford/Umbraco-CMS,kgiszewski/Umbraco-CMS,marcemarc/Umbraco-CMS,lars-erik/Umbraco-CMS,madsoulswe/Umbraco-CMS,tcmorris/Umbraco-CMS,aaronpowell/Umbraco-CMS,leekelleher/Umbraco-CMS,JimBobSquarePants/Umbraco-CMS,umbraco/Umbraco-CMS,nul800sebastiaan/Umbraco-CMS,mattbrailsford/Umbraco-CMS,JimBobSquarePants/Umbraco-CMS,JeffreyPerplex/Umbraco-CMS,tompipe/Umbraco-CMS,tompipe/Umbraco-CMS,dawoe/Umbraco-CMS,lars-erik/Umbraco-CMS,hfloyd/Umbraco-CMS,abjerner/Umbraco-CMS,rasmuseeg/Umbraco-CMS,robertjf/Umbraco-CMS,robertjf/Umbraco-CMS,abryukhov/Umbraco-CMS,leekelleher/Umbraco-CMS,arknu/Umbraco-CMS,aaronpowell/Umbraco-CMS,JimBobSquarePants/Umbraco-CMS,hfloyd/Umbraco-CMS,arknu/Umbraco-CMS,base33/Umbraco-CMS,rasmuseeg/Umbraco-CMS,lars-erik/Umbraco-CMS,KevinJump/Umbraco-CMS,lars-erik/Umbraco-CMS,arknu/Umbraco-CMS,bjarnef/Umbraco-CMS,nul800sebastiaan/Umbraco-CMS,bjarnef/Umbraco-CMS,tcmorris/Umbraco-CMS,robertjf/Umbraco-CMS,umbraco/Umbraco-CMS,NikRimington/Umbraco-CMS,aadfPT/Umbraco-CMS,JimBobSquarePants/Umbraco-CMS,bjarnef/Umbraco-CMS,leekelleher/Umbraco-CMS,jchurchley/Umbraco-CMS,tcmorris/Umbraco-CMS,marcemarc/Umbraco-CMS,jchurchley/Umbraco-CMS,mattbrailsford/Umbraco-CMS,tompipe/Umbraco-CMS,KevinJump/Umbraco-CMS,abryukhov/Umbraco-CMS,abjerner/Umbraco-CMS,JeffreyPerplex/Umbraco-CMS,robertjf/Umbraco-CMS,leekelleher/Umbraco-CMS,lars-erik/Umbraco-CMS,PeteDuncanson/Umbraco-CMS,KevinJump/Umbraco-CMS,hfloyd/Umbraco-CMS,KevinJump/Umbraco-CMS,nul800sebastiaan/Umbraco-CMS,marcemarc/Umbraco-CMS,hfloyd/Umbraco-CMS,dawoe/Umbraco-CMS,madsoulswe/Umbraco-CMS,mattbrailsford/Umbraco-CMS,JimBobSquarePants/Umbraco-CMS,rasmuseeg/Umbraco-CMS,PeteDuncanson/Umbraco-CMS,WebCentrum/Umbraco-CMS,tcmorris/Umbraco-CMS,abryukhov/Umbraco-CMS,NikRimington/Umbraco-CMS,jchurchley/Umbraco-CMS
src/Umbraco.Web/PropertyEditors/MacroContainerPropertyEditor.cs
src/Umbraco.Web/PropertyEditors/MacroContainerPropertyEditor.cs
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Umbraco.Core; using Umbraco.Core.PropertyEditors; namespace Umbraco.Web.PropertyEditors { [PropertyEditor(Constants.PropertyEditors.MacroContainerAlias, "Macro Picker", "macrocontainer", ValueType = PropertyEditorValueTypes.Text, Group="rich content", Icon="icon-settings-alt")] public class MacroContainerPropertyEditor : PropertyEditor { /// <summary> /// Creates a pre value editor instance /// </summary> /// <returns></returns> protected override PreValueEditor CreatePreValueEditor() { return new MacroContainerPreValueEditor(); } protected override PropertyValueEditor CreateValueEditor() { //TODO: Need to add some validation to the ValueEditor to ensure that any media chosen actually exists! return base.CreateValueEditor(); } internal class MacroContainerPreValueEditor : PreValueEditor { [PreValueField("max", "Max items", "number", Description = "The maximum number of macros that are allowed in the container")] public int MaxItems { get; set; } [PreValueField("allowed", "Allowed items", "views/propertyeditors/macrocontainer/macrolist.prevalues.html", Description = "The macro types allowed, if none are selected all macros will be allowed")] public object AllowedItems { get; set; } } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Umbraco.Core; using Umbraco.Core.PropertyEditors; namespace Umbraco.Web.PropertyEditors { [PropertyEditor(Constants.PropertyEditors.MacroContainerAlias, "Macro container", "macrocontainer", ValueType = PropertyEditorValueTypes.Text, Group="rich content", Icon="icon-settings-alt")] public class MacroContainerPropertyEditor : PropertyEditor { /// <summary> /// Creates a pre value editor instance /// </summary> /// <returns></returns> protected override PreValueEditor CreatePreValueEditor() { return new MacroContainerPreValueEditor(); } protected override PropertyValueEditor CreateValueEditor() { //TODO: Need to add some validation to the ValueEditor to ensure that any media chosen actually exists! return base.CreateValueEditor(); } internal class MacroContainerPreValueEditor : PreValueEditor { [PreValueField("max", "Max items", "number", Description = "The maximum number of macros that are allowed in the container")] public int MaxItems { get; set; } [PreValueField("allowed", "Allowed items", "views/propertyeditors/macrocontainer/macrolist.prevalues.html", Description = "The macro types allowed, if none are selected all macros will be allowed")] public object AllowedItems { get; set; } } } }
mit
C#
0df08b681e6413160794528f89eede7bce3f5bb0
update version
SamuelDebruyn/MugenMvvmToolkit.DryIoc,SamuelDebruyn/MugenMvvmToolkit.DryIoc
build.cake
build.cake
const string version = "1.1.2"; const string defaultTarget = "Default"; const string solutionPath = "./MugenMvvmToolkit.DryIoc.sln"; const string projectPath = "./MugenMvvmToolkit.DryIoc/MugenMvvmToolkit.DryIoc.csproj"; const string testProjectPath = "./MugenMvvmToolkit.DryIoc.Tests/MugenMvvmToolkit.DryIoc.Tests.csproj"; const string configuration = "Release"; var target = Argument("target", defaultTarget); var packSettings = new DotNetCorePackSettings { Configuration = configuration, IncludeSymbols = true, ArgumentCustomization = args => args.Append("/p:PackageVersion=" + version) }; Task(defaultTarget) .Does(() => { DotNetCoreRestore(solutionPath); DotNetCoreBuild(solutionPath); DotNetCoreTest(testProjectPath); DotNetCorePack(projectPath, packSettings); }); RunTarget(target);
const string version = "1.1.1"; const string defaultTarget = "Default"; const string solutionPath = "./MugenMvvmToolkit.DryIoc.sln"; const string projectPath = "./MugenMvvmToolkit.DryIoc/MugenMvvmToolkit.DryIoc.csproj"; const string testProjectPath = "./MugenMvvmToolkit.DryIoc.Tests/MugenMvvmToolkit.DryIoc.Tests.csproj"; const string configuration = "Release"; var target = Argument("target", defaultTarget); var packSettings = new DotNetCorePackSettings { Configuration = configuration, IncludeSymbols = true, ArgumentCustomization = args => args.Append("/p:PackageVersion=" + version) }; Task(defaultTarget) .Does(() => { DotNetCoreRestore(solutionPath); DotNetCoreBuild(solutionPath); DotNetCoreTest(testProjectPath); DotNetCorePack(projectPath, packSettings); }); RunTarget(target);
mit
C#
4b20df12cd15c09ad002aa85dec6a4af83bbaa99
Build Script - cleanup and filling out vars
jonathanpeppers/Live.Forms.iOS,jonathanpeppers/Live.Forms.iOS
build.cake
build.cake
//#tool nuget:?package=NUnit.ConsoleRunner&version=3.4.0 string target = Argument("target", "Default"); string configuration = Argument("configuration", "Release"); // Define directories. var dirs = new[] { Directory("./Live.Forms/bin") + Directory(configuration), Directory("./Live.Forms.iOS/bin") + Directory(configuration), }; string sln = "./Live.Forms.iOS.sln"; Task("Clean") .Does(() => { foreach (var dir in dirs) CleanDirectory(dir); }); Task("Restore-NuGet-Packages") .IsDependentOn("Clean") .Does(() => { NuGetRestore(sln); }); Task("Build") .IsDependentOn("Restore-NuGet-Packages") .Does(() => { if(IsRunningOnWindows()) { // Use MSBuild MSBuild(sln, settings => settings .WithProperty("Platform", new[] { "iPhoneSimulator" }) .SetConfiguration(configuration)); } else { // Use XBuild XBuild(sln, settings => settings .WithProperty("Platform", new[] { "iPhoneSimulator" }) .SetConfiguration(configuration)); } }); Task("Default") .IsDependentOn("Build"); RunTarget(target);
//#tool nuget:?package=NUnit.ConsoleRunner&version=3.4.0 var target = Argument("target", "Default"); var configuration = Argument("configuration", "Release"); // Define directories. var buildDir = Directory("./src/Example/bin") + Directory(configuration); Task("Clean") .Does(() => { CleanDirectory(buildDir); }); Task("Restore-NuGet-Packages") .IsDependentOn("Clean") .Does(() => { NuGetRestore("./Live.Forms.iOS.sln"); }); Task("Build") .IsDependentOn("Restore-NuGet-Packages") .Does(() => { if(IsRunningOnWindows()) { // Use MSBuild MSBuild("./Live.Forms.iOS.sln", settings => settings.SetConfiguration(configuration)); } else { // Use XBuild XBuild("./Live.Forms.iOS.sln", settings => settings.SetConfiguration(configuration)); } }); Task("Default") .IsDependentOn("Build"); RunTarget(target);
mit
C#
aee8449502917d55023d094e82e0d04c5785a3bd
Copy Nupkg to artifacts folder
danielwertheim/mycouch,danielwertheim/mycouch
build.cake
build.cake
#load "./buildconfig.cake" var config = BuildConfig.Create(Context, BuildSystem); Information("SrcDir: " + config.SrcDir); Information("OutDir: " + config.OutDir); Information("SemVer: " + config.SemVer); Information("BuildProfile: " + config.BuildProfile); Information("IsTeamCityBuild: " + config.IsTeamCityBuild); Task("Default") .IsDependentOn("InitOutDir") .IsDependentOn("Build") .IsDependentOn("UnitTests"); Task("CI") .IsDependentOn("Default") .IsDependentOn("IntegrationTests") .IsDependentOn("Pack"); /********************************************/ Task("InitOutDir").Does(() => { EnsureDirectoryExists(config.OutDir); CleanDirectory(config.OutDir); }); Task("Build").Does(() => { foreach(var sln in GetFiles(config.SrcDir + "*.sln")) { DotNetBuild(sln, settings => settings.SetConfiguration(config.BuildProfile) .SetVerbosity(Verbosity.Minimal) .WithTarget("Rebuild") .WithProperty("TreatWarningsAsErrors", "true") .WithProperty("Version", config.SemVer) .WithProperty("AssemblyVersion", config.SemVer) .WithProperty("FileVersion", config.SemVer)); } }); Task("UnitTests").Does(() => { var settings = new DotNetCoreTestSettings { Configuration = config.BuildProfile, NoBuild = true }; foreach(var testProj in GetFiles(config.SrcDir + "tests/**/*.UnitTests.csproj")) { DotNetCoreTest(testProj.FullPath, settings); } }); Task("IntegrationTests").Does(() => { var settings = new DotNetCoreTestSettings { Configuration = config.BuildProfile, NoBuild = true }; foreach(var testProj in GetFiles(config.SrcDir + "tests/**/*.IntegrationTests.csproj")) { DotNetCoreTest(testProj.FullPath, settings); } }); Task("Pack").Does(() => { foreach(var sln in GetFiles(config.SrcDir + "projects/**/*.csproj")) { DotNetBuild(sln, settings => settings.SetConfiguration(config.BuildProfile) .SetVerbosity(Verbosity.Minimal) .WithTarget("Pack") .WithProperty("TreatWarningsAsErrors", "true") .WithProperty("Version", config.SemVer)); } CopyFiles( GetFiles(config.SrcDir + "projects/**/*.nupkg"), config.OutDir); }); RunTarget(config.Target);
#load "./buildconfig.cake" var config = BuildConfig.Create(Context, BuildSystem); Information("SrcDir: " + config.SrcDir); Information("OutDir: " + config.OutDir); Information("SemVer: " + config.SemVer); Information("BuildProfile: " + config.BuildProfile); Information("IsTeamCityBuild: " + config.IsTeamCityBuild); Task("Default") .IsDependentOn("InitOutDir") .IsDependentOn("Build") .IsDependentOn("UnitTests"); Task("CI") .IsDependentOn("Default") .IsDependentOn("IntegrationTests") .IsDependentOn("Pack"); /********************************************/ Task("InitOutDir").Does(() => { EnsureDirectoryExists(config.OutDir); CleanDirectory(config.OutDir); }); Task("Build").Does(() => { foreach(var sln in GetFiles(config.SrcDir + "*.sln")) { DotNetBuild(sln, settings => settings.SetConfiguration(config.BuildProfile) .SetVerbosity(Verbosity.Minimal) .WithTarget("Rebuild") .WithProperty("TreatWarningsAsErrors", "true") .WithProperty("Version", config.SemVer) .WithProperty("AssemblyVersion", config.SemVer) .WithProperty("FileVersion", config.SemVer)); } }); Task("UnitTests").Does(() => { var settings = new DotNetCoreTestSettings { Configuration = config.BuildProfile, NoBuild = true }; foreach(var testProj in GetFiles(config.SrcDir + "tests/**/*.UnitTests.csproj")) { DotNetCoreTest(testProj.FullPath, settings); } }); Task("IntegrationTests").Does(() => { var settings = new DotNetCoreTestSettings { Configuration = config.BuildProfile, NoBuild = true }; foreach(var testProj in GetFiles(config.SrcDir + "tests/**/*.IntegrationTests.csproj")) { DotNetCoreTest(testProj.FullPath, settings); } }); Task("Pack").Does(() => { foreach(var sln in GetFiles(config.SrcDir + "projects/**/*.csproj")) { DotNetBuild(sln, settings => settings.SetConfiguration(config.BuildProfile) .SetVerbosity(Verbosity.Minimal) .WithTarget("Pack") .WithProperty("TreatWarningsAsErrors", "true") .WithProperty("Version", config.SemVer)); } }); RunTarget(config.Target);
mit
C#
3f890d1767efb3b6db18edca8c24ae36f0a57ccc
exclude package restore for tests
IdentityModel/IdentityModelv2,IdentityModel/IdentityModelv2,IdentityModel/IdentityModel2,IdentityModel/IdentityModel,IdentityModel/IdentityModel,IdentityModel/IdentityModel2
build.cake
build.cake
var target = Argument("target", "Default"); var configuration = Argument<string>("configuration", "Release"); /////////////////////////////////////////////////////////////////////////////// // GLOBAL VARIABLES /////////////////////////////////////////////////////////////////////////////// var isLocalBuild = !AppVeyor.IsRunningOnAppVeyor; var packPath = Directory("./src/IdentityModel"); var sourcePath = Directory("./src"); var testsPath = Directory("test"); var buildArtifacts = Directory("./artifacts/packages"); Task("Build") .IsDependentOn("Clean") .IsDependentOn("Restore") .Does(() => { var projects = GetFiles("./**/project.json"); foreach(var project in projects) { var settings = new DotNetCoreBuildSettings { Configuration = configuration // Runtime = IsRunningOnWindows() ? null : "unix-x64" }; DotNetCoreBuild(project.GetDirectory().FullPath, settings); } }); Task("RunTests") .IsDependentOn("Restore") .IsDependentOn("Clean") .Does(() => { var projects = GetFiles("./test/**/project.json"); foreach(var project in projects) { var settings = new DotNetCoreTestSettings { Configuration = configuration }; DotNetCoreTest(project.GetDirectory().FullPath, settings); } }); Task("Pack") .IsDependentOn("Restore") .IsDependentOn("Clean") .Does(() => { var settings = new DotNetCorePackSettings { Configuration = configuration, OutputDirectory = buildArtifacts, }; // add build suffix for CI builds if(!isLocalBuild) { settings.VersionSuffix = "build" + AppVeyor.Environment.Build.Number.ToString().PadLeft(5,'0'); } DotNetCorePack(packPath, settings); }); Task("Clean") .Does(() => { CleanDirectories(new DirectoryPath[] { buildArtifacts }); }); Task("Restore") .Does(() => { var settings = new DotNetCoreRestoreSettings { Sources = new [] { "https://api.nuget.org/v3/index.json" } }; DotNetCoreRestore(sourcePath, settings); //DotNetCoreRestore(testsPath, settings); }); Task("Default") .IsDependentOn("Build") .IsDependentOn("RunTests") .IsDependentOn("Pack"); RunTarget(target);
var target = Argument("target", "Default"); var configuration = Argument<string>("configuration", "Release"); /////////////////////////////////////////////////////////////////////////////// // GLOBAL VARIABLES /////////////////////////////////////////////////////////////////////////////// var isLocalBuild = !AppVeyor.IsRunningOnAppVeyor; var packPath = Directory("./src/IdentityModel"); var sourcePath = Directory("./src"); var testsPath = Directory("test"); var buildArtifacts = Directory("./artifacts/packages"); Task("Build") .IsDependentOn("Clean") .IsDependentOn("Restore") .Does(() => { var projects = GetFiles("./**/project.json"); foreach(var project in projects) { var settings = new DotNetCoreBuildSettings { Configuration = configuration // Runtime = IsRunningOnWindows() ? null : "unix-x64" }; DotNetCoreBuild(project.GetDirectory().FullPath, settings); } }); Task("RunTests") .IsDependentOn("Restore") .IsDependentOn("Clean") .Does(() => { var projects = GetFiles("./test/**/project.json"); foreach(var project in projects) { var settings = new DotNetCoreTestSettings { Configuration = configuration }; DotNetCoreTest(project.GetDirectory().FullPath, settings); } }); Task("Pack") .IsDependentOn("Restore") .IsDependentOn("Clean") .Does(() => { var settings = new DotNetCorePackSettings { Configuration = configuration, OutputDirectory = buildArtifacts, }; // add build suffix for CI builds if(!isLocalBuild) { settings.VersionSuffix = "build" + AppVeyor.Environment.Build.Number.ToString().PadLeft(5,'0'); } DotNetCorePack(packPath, settings); }); Task("Clean") .Does(() => { CleanDirectories(new DirectoryPath[] { buildArtifacts }); }); Task("Restore") .Does(() => { var settings = new DotNetCoreRestoreSettings { Sources = new [] { "https://api.nuget.org/v3/index.json" } }; DotNetCoreRestore(sourcePath, settings); DotNetCoreRestore(testsPath, settings); }); Task("Default") .IsDependentOn("Build") .IsDependentOn("RunTests") .IsDependentOn("Pack"); RunTarget(target);
apache-2.0
C#
ea088deeeae31087dd0a9377fe5c6f8a34a0d8ed
Update DbContextExtensions.cs
refactorthis/GraphDiff
GraphDiff/GraphDiff/DbContextExtensions.cs
GraphDiff/GraphDiff/DbContextExtensions.cs
/* * This code is provided as is with no warranty. If you find a bug please report it on github. * If you would like to use the code please leave this comment at the top of the page * License MIT (c) Brent McKendrick 2012 */ using System; using System.Data.Entity; using System.Linq.Expressions; using RefactorThis.GraphDiff.Internal; using RefactorThis.GraphDiff.Internal.Graph; namespace RefactorThis.GraphDiff { public static class DbContextExtensions { /// <summary> /// Merges a graph of entities with the data store. /// </summary> /// <typeparam name="T">The type of the root entity</typeparam> /// <param name="context">The database context to attach / detach.</param> /// <param name="entity">The root entity.</param> /// <param name="mapping">The mapping configuration to define the bounds of the graph</param> /// <param name="allowDelete">NEED TEXTE!!!!</param> /// <returns>The attached entity graph</returns> public static T UpdateGraph<T>(this DbContext context, T entity, Expression<Func<IUpdateConfiguration<T>, object>> mapping = null, bool allowDelete = true) where T : class, new() { var root = mapping == null ? new GraphNode() : new ConfigurationVisitor<T>().GetNodes(mapping); root.AllowDelete = allowDelete; var graphDiffer = new GraphDiffer<T>(root); return graphDiffer.Merge(context, entity); } // TODO add IEnumerable<T> entities } }
/* * This code is provided as is with no warranty. If you find a bug please report it on github. * If you would like to use the code please leave this comment at the top of the page * License MIT (c) Brent McKendrick 2012 */ using System; using System.Data.Entity; using System.Linq.Expressions; using RefactorThis.GraphDiff.Internal; using RefactorThis.GraphDiff.Internal.Graph; namespace RefactorThis.GraphDiff { public static class DbContextExtensions { /// <summary> /// Merges a graph of entities with the data store. /// </summary> /// <typeparam name="T">The type of the root entity</typeparam> /// <param name="context">The database context to attach / detach.</param> /// <param name="entity">The root entity.</param> /// <param name="mapping">The mapping configuration to define the bounds of the graph</param> /// <param name="allowDelete">NEED TEXTE!!!!</param> /// <returns>The attached entity graph</returns> public static T UpdateGraph<T>(this DbContext context, T entity, Expression<Func<IUpdateConfiguration<T>, object>> mapping = null, bool allowDelete = true) where T : class, new() { var root = mapping == null ? new GraphNode() : new ConfigurationVisitor<T>().GetNodes(mapping); root.AllowDelete = allowDelete; var graphDiffer = new GraphDiffer<T>(root); return graphDiffer.Merge(context, entity); } // TODO add IEnumerable<T> entities } }
mit
C#
cb7252a97e46a6e21ead7ce5ff4b5d40db8d70d5
Fix tests, but not seeding Database anymore
kandanda/Client,kandanda/Client
Kandanda/Kandanda.Dal/KandandaDbContext.cs
Kandanda/Kandanda.Dal/KandandaDbContext.cs
using System.Data.Entity; using Kandanda.Dal.DataTransferObjects; namespace Kandanda.Dal { public class KandandaDbContext : DbContext { public KandandaDbContext() { // TODO fix SetInitializer for tests Database.SetInitializer(new DropCreateDatabaseAlways<KandandaDbContext>()); } public DbSet<Tournament> Tournaments { get; set; } public DbSet<Participant> Participants { get; set; } public DbSet<Match> Matches { get; set; } public DbSet<Place> Places { get; set; } public DbSet<Phase> Phases { get; set; } public DbSet<TournamentParticipant> TournamentParticipants { get; set; } } }
using System.Data.Entity; using Kandanda.Dal.DataTransferObjects; namespace Kandanda.Dal { public class KandandaDbContext : DbContext { public KandandaDbContext() { Database.SetInitializer(new SampleDataDbInitializer()); } public DbSet<Tournament> Tournaments { get; set; } public DbSet<Participant> Participants { get; set; } public DbSet<Match> Matches { get; set; } public DbSet<Place> Places { get; set; } public DbSet<Phase> Phases { get; set; } public DbSet<TournamentParticipant> TournamentParticipants { get; set; } } }
mit
C#
8807d64bd6c43b734740dfa1cd75216e3b1572c7
Debug output for package lookup via api
NuKeeperDotNet/NuKeeper,skolima/NuKeeper,AnthonySteele/NuKeeper,AnthonySteele/NuKeeper,NuKeeperDotNet/NuKeeper,skolima/NuKeeper,AnthonySteele/NuKeeper,AnthonySteele/NuKeeper,skolima/NuKeeper,NuKeeperDotNet/NuKeeper,skolima/NuKeeper,NuKeeperDotNet/NuKeeper
NuKeeper/NuGet/Api/PackageUpdatesLookup.cs
NuKeeper/NuGet/Api/PackageUpdatesLookup.cs
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using NuGet.Protocol.Core.Types; using NuKeeper.RepositoryInspection; namespace NuKeeper.NuGet.Api { public class PackageUpdatesLookup : IPackageUpdatesLookup { private readonly IApiPackageLookup _packageLookup; public PackageUpdatesLookup(IApiPackageLookup packageLookup) { _packageLookup = packageLookup; } public async Task<List<PackageUpdateSet>> FindUpdatesForPackages(List<PackageInProject> packages) { var latestVersions = await BuildLatestVersionsDictionary(packages); var results = new List<PackageUpdateSet>(); foreach (var packageId in latestVersions.Keys) { var latestVersion = latestVersions[packageId].Identity; var updatesForThisPackage = packages .Where(p => p.Id == packageId && p.Version < latestVersion.Version) .ToList(); if (updatesForThisPackage.Count > 0) { var updateSet = new PackageUpdateSet(latestVersion, updatesForThisPackage); results.Add(updateSet); } } return results; } private async Task<Dictionary<string, IPackageSearchMetadata>> BuildLatestVersionsDictionary(IEnumerable<PackageInProject> packages) { var result = new Dictionary<string, IPackageSearchMetadata>(); var packageIds = packages .Select(p => p.Id) .Distinct(); foreach (var packageId in packageIds) { var serverVersion = await _packageLookup.LookupLatest(packageId); if (serverVersion != null) { result.Add(packageId, serverVersion); Console.WriteLine($"Found latest version of {packageId}: {serverVersion.Identity?.Id} {serverVersion.Identity?.Version}"); } } return result; } } }
using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using NuGet.Protocol.Core.Types; using NuKeeper.RepositoryInspection; namespace NuKeeper.NuGet.Api { public class PackageUpdatesLookup : IPackageUpdatesLookup { private readonly IApiPackageLookup _packageLookup; public PackageUpdatesLookup(IApiPackageLookup packageLookup) { _packageLookup = packageLookup; } public async Task<List<PackageUpdateSet>> FindUpdatesForPackages(List<PackageInProject> packages) { var latestVersions = await BuildLatestVersionsDictionary(packages); var results = new List<PackageUpdateSet>(); foreach (var packageId in latestVersions.Keys) { var latestVersion = latestVersions[packageId].Identity; var updatesForThisPackage = packages .Where(p => p.Id == packageId && p.Version < latestVersion.Version) .ToList(); if (updatesForThisPackage.Count > 0) { var updateSet = new PackageUpdateSet(latestVersion, updatesForThisPackage); results.Add(updateSet); } } return results; } private async Task<Dictionary<string, IPackageSearchMetadata>> BuildLatestVersionsDictionary(IEnumerable<PackageInProject> packages) { var result = new Dictionary<string, IPackageSearchMetadata>(); var packageIds = packages .Select(p => p.Id) .Distinct(); foreach (var packageId in packageIds) { var serverVersion = await _packageLookup.LookupLatest(packageId); result.Add(packageId, serverVersion); } return result; } } }
apache-2.0
C#
17c68a649547b96886fdde66a9511bb9754a7de6
check fix
HackerDom/qctf-starter-2015,HackerDom/qctf-starter-2015,HackerDom/qctf-starter-2015,HackerDom/qctf-starter-2015
checksystem/src/chat/Check.ashx.cs
checksystem/src/chat/Check.ashx.cs
using System; using System.Linq; using System.Web; using main.auth; using main.db; namespace main.chat { public class Check : BaseHandler { protected override AjaxResult ProcessRequestInternal(HttpContext context) { var login = AuthModule.GetAuthLogin(); /*if(DateTime.UtcNow > Settings.BombTimerEnd) throw new HttpException(403, "Connection lost...");*/ var user = DbStorage.FindUserByLogin(login); if(user == null) throw new HttpException(403, "Access denied"); var revision = DbStorage.FindBroadcast(login); var flags = DbStorage.FindFlags(login); var timer = ElCapitan.HasBombTimer(flags) ? (user.EndTime != DateTime.MinValue ? user.EndTime : Settings.BombTimerEnd) : DateTime.MinValue; var answers = ElCapitan.GetBroadcastMsgs(ref revision); if(answers.Length == 0) return new AjaxResult {Messages = null, Files = null, Score = 0, Timer = timer}; var msgs = answers.Select(msg => new Msg {Text = msg, Time = DateTime.UtcNow, Type = MsgType.Answer}).ToArray(); DbStorage.AddDialog(login, null, msgs, null, null, revision); return new AjaxResult {Messages = msgs, Files = null, Score = 0, Timer = timer}; } } }
using System; using System.Linq; using System.Web; using main.auth; using main.db; namespace main.chat { public class Check : BaseHandler { protected override AjaxResult ProcessRequestInternal(HttpContext context) { var login = AuthModule.GetAuthLogin(); /*if(DateTime.UtcNow > Settings.BombTimerEnd) throw new HttpException(403, "Connection lost...");*/ var revision = DbStorage.FindBroadcast(login); var flags = DbStorage.FindFlags(login); var timer = ElCapitan.HasBombTimer(flags) ? Settings.BombTimerEnd : DateTime.MinValue; var answers = ElCapitan.GetBroadcastMsgs(ref revision); if(answers.Length == 0) return new AjaxResult {Messages = null, Files = null, Score = 0, Timer = timer}; var msgs = answers.Select(msg => new Msg {Text = msg, Time = DateTime.UtcNow, Type = MsgType.Answer}).ToArray(); DbStorage.AddDialog(login, null, msgs, null, null, revision); return new AjaxResult {Messages = msgs, Files = null, Score = 0, Timer = timer}; } } }
mit
C#
99e63ec2fa2c385de65b5569d82cda40e3ff2196
Use Helper to create instance from assembly
iahdevelop/nuPickers,JimBobSquarePants/nuPickers,LottePitcher/nuPickers,uComponents/nuPickers,abjerner/nuPickers,JimBobSquarePants/nuPickers,pgregorynz/nuPickers,iahdevelop/nuPickers,abjerner/nuPickers,pgregorynz/nuPickers,uComponents/nuPickers,pgregorynz/nuPickers,JimBobSquarePants/nuPickers,iahdevelop/nuPickers,abjerner/nuPickers,LottePitcher/nuPickers,uComponents/nuPickers,LottePitcher/nuPickers,pgregorynz/nuPickers
source/nuPickers/Shared/DotNetDataSource/DotNetDataSource.cs
source/nuPickers/Shared/DotNetDataSource/DotNetDataSource.cs
 namespace nuPickers.Shared.DotNetDataSource { using nuPickers.Shared.Editor; using System; using System.Reflection; using System.Collections.Generic; using System.Linq; public class DotNetDataSource { public string AssemblyName { get; set; } public string ClassName { get; set; } public IEnumerable<DotNetDataSourceProperty> Properties { get; set; } public IEnumerable<EditorDataItem> GetEditorDataItems() { List<EditorDataItem> editorDataItems = new List<EditorDataItem>(); object dotNetDataSource = Helper.GetAssembly(this.AssemblyName).CreateInstance(this.ClassName); foreach (PropertyInfo propertyInfo in dotNetDataSource.GetType().GetProperties().Where(x => this.Properties.Select(y => y.Name).Contains(x.Name))) { if (propertyInfo.PropertyType == typeof(string)) { propertyInfo.SetValue(dotNetDataSource, this.Properties.Where(x => x.Name == propertyInfo.Name).Single().Value); } else { // TODO: log unexpected property type } } return ((IDotNetDataSource)dotNetDataSource) .GetEditorDataItems() .Select(x => new EditorDataItem() { Key = x.Key, Label = x.Value }); } } }
 namespace nuPickers.Shared.DotNetDataSource { using nuPickers.Shared.Editor; using System; using System.Reflection; using System.Collections.Generic; using System.Linq; public class DotNetDataSource { public string AssemblyName { get; set; } public string ClassName { get; set; } public IEnumerable<DotNetDataSourceProperty> Properties { get; set; } public IEnumerable<EditorDataItem> GetEditorDataItems() { List<EditorDataItem> editorDataItems = new List<EditorDataItem>(); object dotNetDataSource = Activator.CreateInstance(this.AssemblyName, this.ClassName).Unwrap(); foreach (PropertyInfo propertyInfo in dotNetDataSource.GetType().GetProperties().Where(x => this.Properties.Select(y => y.Name).Contains(x.Name))) { if (propertyInfo.PropertyType == typeof(string)) { propertyInfo.SetValue(dotNetDataSource, this.Properties.Where(x => x.Name == propertyInfo.Name).Single().Value); } else { // TODO: log unexpected property type } } return ((IDotNetDataSource)dotNetDataSource) .GetEditorDataItems() .Select(x => new EditorDataItem() { Key = x.Key, Label = x.Value }); } } }
mit
C#
e583bf86a1c5afd34f9de2e41106259f79cdd063
Add date to status report
ndouthit/Certify,webprofusion/Certify,Prerequisite/Certify
src/Certify.Core.Models/Models/Shared/RenewalStatusReport.cs
src/Certify.Core.Models/Models/Shared/RenewalStatusReport.cs
using System; namespace Certify.Models.Shared { public class RenewalStatusReport { public string InstanceId { get; set; } public string MachineName { get; set; } public ManagedSite ManagedSite { get; set; } public string PrimaryContactEmail { get; set; } public string AppVersion { get; set; } public DateTime? DateReported { get; set; } } }
namespace Certify.Models.Shared { public class RenewalStatusReport { public string InstanceId { get; set; } public string MachineName { get; set; } public ManagedSite ManagedSite { get; set; } public string PrimaryContactEmail { get; set; } public string AppVersion { get; set; } } }
mit
C#
b0c9c865ef59b3475e9f4cfadaeac1d7b6fcf24c
Add comment on limitation of API assembly
nunit/nunit-console,nunit/nunit-console,nunit/nunit-console
src/NUnitEngine/nunit.engine.api/IRuntimeFrameworkService.cs
src/NUnitEngine/nunit.engine.api/IRuntimeFrameworkService.cs
// *********************************************************************** // Copyright (c) 2011 Charlie Poole, Rob Prouse // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // *********************************************************************** using System; using System.Collections.Generic; namespace NUnit.Engine { /// <summary> /// Implemented by a type that provides information about the /// current and other available runtimes. /// </summary> public interface IRuntimeFrameworkService { /// <summary> /// Returns true if the runtime framework represented by /// the string passed as an argument is available. /// </summary> /// <param name="framework">A string representing a framework, like 'net-4.0'</param> /// <returns>True if the framework is available, false if unavailable or nonexistent</returns> bool IsAvailable(string framework); /// <summary> /// Selects a target runtime framework for a TestPackage based on /// the settings in the package and the assemblies themselves. /// The package RuntimeFramework setting may be updated as a /// result and the selected runtime is returned. /// /// Note that if a package has subpackages, the subpackages may run on a different /// framework to the top-level package. In future, this method should /// probably not return a simple string, and instead require runners /// to inspect the test package structure, to find all desired frameworks. /// </summary> /// <param name="package">A TestPackage</param> /// <returns>The selected RuntimeFramework</returns> string SelectRuntimeFramework(TestPackage package); } }
// *********************************************************************** // Copyright (c) 2011 Charlie Poole, Rob Prouse // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // *********************************************************************** using System; using System.Collections.Generic; namespace NUnit.Engine { /// <summary> /// Implemented by a type that provides information about the /// current and other available runtimes. /// </summary> public interface IRuntimeFrameworkService { /// <summary> /// Returns true if the runtime framework represented by /// the string passed as an argument is available. /// </summary> /// <param name="framework">A string representing a framework, like 'net-4.0'</param> /// <returns>True if the framework is available, false if unavailable or nonexistent</returns> bool IsAvailable(string framework); /// <summary> /// Selects a target runtime framework for a TestPackage based on /// the settings in the package and the assemblies themselves. /// The package RuntimeFramework setting may be updated as a /// result and the selected runtime is returned. /// </summary> /// <param name="package">A TestPackage</param> /// <returns>The selected RuntimeFramework</returns> string SelectRuntimeFramework(TestPackage package); } }
mit
C#
b3270aedc8287d80690ef4b034784d5399fee002
Update BoxColliderFitChildren.cs
UnityCommunity/UnityLibrary
Assets/Scripts/Editor/ContextMenu/BoxColliderFitChildren.cs
Assets/Scripts/Editor/ContextMenu/BoxColliderFitChildren.cs
// Adjust Box Collider to fit child meshes inside // Usage: You have empty parent transform, with child meshes inside, add box collider to parent then use this // NOTE: Doesnt work if root transform is rotated using UnityEngine; using UnityEditor; namespace UnityLibrary { public class BoxColliderFitChildren : MonoBehaviour { [MenuItem("CONTEXT/BoxCollider/Fit to Children")] static void FixSize(MenuCommand command) { BoxCollider col = (BoxCollider)command.context; // record undo Undo.RecordObject(col.transform, "Fit Box Collider To Children"); // get child mesh bounds var b = GetRecursiveMeshBounds(col.gameObject); // set collider local center and size col.center = col.transform.root.InverseTransformVector(b.center) - col.transform.position; col.size = b.size; } public static Bounds GetRecursiveMeshBounds(GameObject go) { var r = go.GetComponentsInChildren<Renderer>(); if (r.Length > 0) { var b = r[0].bounds; for (int i = 1; i < r.Length; i++) { b.Encapsulate(r[i].bounds); } return b; } else // TODO no renderers { return new Bounds(Vector3.one, Vector3.one); } } } }
// Adjust Box Collider to fit child meshes inside // usage: You have empty parent transform, with child meshes inside, add box collider to parent then use this using UnityEngine; using UnityEditor; namespace UnityLibrary { public class BoxColliderFitChildren : MonoBehaviour { [MenuItem("CONTEXT/BoxCollider/Fit to Children")] static void FixSize(MenuCommand command) { BoxCollider col = (BoxCollider)command.context; // record undo Undo.RecordObject(col.transform, "Fit Box Collider To Children"); // get child mesh bounds var b = GetRecursiveMeshBounds(col.gameObject); // set collider local center and size col.center = col.transform.root.InverseTransformVector(b.center) - col.transform.position; col.size = b.size; } public static Bounds GetRecursiveMeshBounds(GameObject go) { var r = go.GetComponentsInChildren<Renderer>(); if (r.Length > 0) { var b = r[0].bounds; for (int i = 1; i < r.Length; i++) { b.Encapsulate(r[i].bounds); } return b; } else // TODO no renderers { return new Bounds(Vector3.one, Vector3.one); } } } }
mit
C#
f9f5f94206f41acfd26c499ad3518b3f9da64e2e
Add `HasPriorLearning` to draft response
SkillsFundingAgency/das-commitments,SkillsFundingAgency/das-commitments,SkillsFundingAgency/das-commitments
src/CommitmentsV2/SFA.DAS.CommitmentsV2.Api.Types/Responses/GetDraftApprenticeshipResponse.cs
src/CommitmentsV2/SFA.DAS.CommitmentsV2.Api.Types/Responses/GetDraftApprenticeshipResponse.cs
using System; using SFA.DAS.CommitmentsV2.Types; namespace SFA.DAS.CommitmentsV2.Api.Types.Responses { public sealed class GetDraftApprenticeshipResponse { public long Id { get; set; } public string FirstName { get; set; } public string LastName { get; set; } public string Email { get; set; } public string Uln { get; set; } public string CourseCode { get; set; } public DeliveryModel DeliveryModel { get; set; } public string TrainingCourseName { get; set; } public string TrainingCourseVersion { get; set; } public string TrainingCourseOption { get; set; } public bool TrainingCourseVersionConfirmed { get; set; } public string StandardUId { get; set; } public int? Cost { get; set; } public DateTime? StartDate { get; set; } public DateTime? EndDate { get; set; } public DateTime? DateOfBirth { get; set; } public string Reference { get; set; } public Guid? ReservationId { get; set; } public bool IsContinuation { get; set; } public DateTime? OriginalStartDate { get; set; } public bool HasStandardOptions { get; set; } public int? EmploymentPrice { get; set; } public DateTime? EmploymentEndDate { get; set; } public bool? HasPriorLearning { get; set; } } }
using System; using SFA.DAS.CommitmentsV2.Types; namespace SFA.DAS.CommitmentsV2.Api.Types.Responses { public sealed class GetDraftApprenticeshipResponse { public long Id { get; set; } public string FirstName { get; set; } public string LastName { get; set; } public string Email { get; set; } public string Uln { get; set; } public string CourseCode { get; set; } public DeliveryModel DeliveryModel { get; set; } public string TrainingCourseName { get; set; } public string TrainingCourseVersion { get; set; } public string TrainingCourseOption { get; set; } public bool TrainingCourseVersionConfirmed { get; set; } public string StandardUId { get; set; } public int? Cost { get; set; } public DateTime? StartDate { get; set; } public DateTime? EndDate { get; set; } public DateTime? DateOfBirth { get; set; } public string Reference { get; set; } public Guid? ReservationId { get; set; } public bool IsContinuation { get; set; } public DateTime? OriginalStartDate { get; set; } public bool HasStandardOptions { get; set; } public int? EmploymentPrice { get; set; } public DateTime? EmploymentEndDate { get; set; } } }
mit
C#
c646af56e2caa8dfb0a22a093b553cf0819ce6b2
use newtonsoft serializer
0xFireball/KQAnalytics3,0xFireball/KQAnalytics3,0xFireball/KQAnalytics3
KQAnalytics3/src/KQAnalytics3/Modules/DataQueryApiModule.cs
KQAnalytics3/src/KQAnalytics3/Modules/DataQueryApiModule.cs
using KQAnalytics3.Models.Data; using KQAnalytics3.Services.DataCollection; using Nancy; using Nancy.Security; using Newtonsoft.Json; using System.Collections.Generic; using System.Linq; using System.Text; namespace KQAnalytics3.Modules { public class DataQueryApiModule : NancyModule { public DataQueryApiModule() : base("/api") { // Require stateless auth this.RequiresAuthentication(); // Limit is the max number of log requests to return. Default 100 Get("/query/{limit}", async args => { var itemLimit = args.limit ?? 100; var data = await DataLoggerService.QueryRequests(itemLimit); var responseData = (string)JsonConvert.SerializeObject(data); return Response.AsText(responseData, "application/json"); }); } } }
using KQAnalytics3.Models.Data; using KQAnalytics3.Services.DataCollection; using Nancy; using Nancy.Security; using System.Collections.Generic; using System.Linq; namespace KQAnalytics3.Modules { public class DataQueryApiModule : NancyModule { public DataQueryApiModule() : base("/api") { // Require stateless auth this.RequiresAuthentication(); // Limit is the max number of log requests to return. Default 100 Get("/query/{limit}", async args => { var itemLimit = args.limit ?? 100; var data = (IEnumerable<LogRequest>)await DataLoggerService.QueryRequests(itemLimit); return Response.AsJson( data.ToArray() ); }); } } }
agpl-3.0
C#
9b484cc24a084abf99b8392ceaa99f168173bd70
Include index name in UpdateSettings test
UdiBen/elasticsearch-net,CSGOpenSource/elasticsearch-net,starckgates/elasticsearch-net,adam-mccoy/elasticsearch-net,UdiBen/elasticsearch-net,LeoYao/elasticsearch-net,CSGOpenSource/elasticsearch-net,ststeiger/elasticsearch-net,robertlyson/elasticsearch-net,tkirill/elasticsearch-net,UdiBen/elasticsearch-net,KodrAus/elasticsearch-net,Grastveit/NEST,abibell/elasticsearch-net,faisal00813/elasticsearch-net,robrich/elasticsearch-net,gayancc/elasticsearch-net,junlapong/elasticsearch-net,ststeiger/elasticsearch-net,wawrzyn/elasticsearch-net,amyzheng424/elasticsearch-net,DavidSSL/elasticsearch-net,SeanKilleen/elasticsearch-net,robrich/elasticsearch-net,junlapong/elasticsearch-net,Grastveit/NEST,mac2000/elasticsearch-net,abibell/elasticsearch-net,LeoYao/elasticsearch-net,jonyadamit/elasticsearch-net,RossLieberman/NEST,faisal00813/elasticsearch-net,CSGOpenSource/elasticsearch-net,mac2000/elasticsearch-net,elastic/elasticsearch-net,RossLieberman/NEST,joehmchan/elasticsearch-net,azubanov/elasticsearch-net,ststeiger/elasticsearch-net,starckgates/elasticsearch-net,KodrAus/elasticsearch-net,jonyadamit/elasticsearch-net,KodrAus/elasticsearch-net,jonyadamit/elasticsearch-net,robertlyson/elasticsearch-net,TheFireCookie/elasticsearch-net,gayancc/elasticsearch-net,geofeedia/elasticsearch-net,joehmchan/elasticsearch-net,RossLieberman/NEST,starckgates/elasticsearch-net,amyzheng424/elasticsearch-net,Grastveit/NEST,adam-mccoy/elasticsearch-net,joehmchan/elasticsearch-net,TheFireCookie/elasticsearch-net,tkirill/elasticsearch-net,cstlaurent/elasticsearch-net,LeoYao/elasticsearch-net,cstlaurent/elasticsearch-net,mac2000/elasticsearch-net,amyzheng424/elasticsearch-net,cstlaurent/elasticsearch-net,DavidSSL/elasticsearch-net,robertlyson/elasticsearch-net,SeanKilleen/elasticsearch-net,junlapong/elasticsearch-net,TheFireCookie/elasticsearch-net,SeanKilleen/elasticsearch-net,robrich/elasticsearch-net,abibell/elasticsearch-net,adam-mccoy/elasticsearch-net,DavidSSL/elasticsearch-net,wawrzyn/elasticsearch-net,geofeedia/elasticsearch-net,wawrzyn/elasticsearch-net,tkirill/elasticsearch-net,faisal00813/elasticsearch-net,azubanov/elasticsearch-net,geofeedia/elasticsearch-net,azubanov/elasticsearch-net,gayancc/elasticsearch-net,elastic/elasticsearch-net
src/Tests/Nest.Tests.Unit/ObjectInitializer/Update/UpdateSettingsRequestTests.cs
src/Tests/Nest.Tests.Unit/ObjectInitializer/Update/UpdateSettingsRequestTests.cs
using Elasticsearch.Net; using FluentAssertions; using NUnit.Framework; using System; using System.Collections.Generic; using System.Linq; using System.Reflection; using System.Text; using System.Threading.Tasks; namespace Nest.Tests.Unit.ObjectInitializer.Update { [TestFixture] public class UpdateSettingsRequestTests : BaseJsonTests { private readonly IElasticsearchResponse _status; public UpdateSettingsRequestTests() { var request = new UpdateSettingsRequest { Index = "my-index", NumberOfReplicas = 5, AutoExpandReplicas = false, BlocksReadOnly = true, BlocksRead = true, BlocksWrite = false, BlocksMetadata = true, RefreshInterval = "30s", IndexConcurrency = 5, Codec = "default", CodecBloomLoad = false, FailOnMergeFailure = false, TranslogFlushTreshHoldOps = "10s", TranslogFlushThresholdSize = "2048", TranslogFlushThresholdPeriod = "5s", TranslogDisableFlush = true, CacheFilterMaxSize = "-1", CacheFilterExpire = "-1", GatewaySnapshotInterval = "5s", RoutingAllocationInclude = new Dictionary<string, object> { { "tag", "value1,value2" } }, RoutingAllocationExclude = new Dictionary<string, object> { { "tag", "value3" } }, RoutingAllocationRequire = new Dictionary<string, object> { { "group4", "aaa" } }, RoutingAllocationEnable = RoutingAllocationEnableOption.NewPrimaries, RoutingAllocationDisableAllication = false, RoutingAllocationDisableNewAllocation = false, RoutingAllocationDisableReplicaAllocation = false, RoutingAllocationTotalShardsPerNode = 1, RecoveryInitialShards = "full", TtlDisablePurge = true, GcDeletes = true, TranslogFsType = "simple", CompoundFormat = true, CompoundOnFlush = true, WarmersEnabled = true }; var response = this._client.UpdateSettings(request); this._status = response.ConnectionStatus; } [Test] public void Url() { this._status.RequestUrl.Should().EndWith("/my-index/_settings"); this._status.RequestMethod.Should().Be("PUT"); } [Test] public void UpdateSettingsBody() { this.JsonEquals(this._status.Request, MethodInfo.GetCurrentMethod()); } } }
using Elasticsearch.Net; using FluentAssertions; using NUnit.Framework; using System; using System.Collections.Generic; using System.Linq; using System.Reflection; using System.Text; using System.Threading.Tasks; namespace Nest.Tests.Unit.ObjectInitializer.Update { [TestFixture] public class UpdateSettingsRequestTests : BaseJsonTests { private readonly IElasticsearchResponse _status; public UpdateSettingsRequestTests() { var request = new UpdateSettingsRequest { NumberOfReplicas = 5, AutoExpandReplicas = false, BlocksReadOnly = true, BlocksRead = true, BlocksWrite = false, BlocksMetadata = true, RefreshInterval = "30s", IndexConcurrency = 5, Codec = "default", CodecBloomLoad = false, FailOnMergeFailure = false, TranslogFlushTreshHoldOps = "10s", TranslogFlushThresholdSize = "2048", TranslogFlushThresholdPeriod = "5s", TranslogDisableFlush = true, CacheFilterMaxSize = "-1", CacheFilterExpire = "-1", GatewaySnapshotInterval = "5s", RoutingAllocationInclude = new Dictionary<string, object> { { "tag", "value1,value2" } }, RoutingAllocationExclude = new Dictionary<string, object> { { "tag", "value3" } }, RoutingAllocationRequire = new Dictionary<string, object> { { "group4", "aaa" } }, RoutingAllocationEnable = RoutingAllocationEnableOption.NewPrimaries, RoutingAllocationDisableAllication = false, RoutingAllocationDisableNewAllocation = false, RoutingAllocationDisableReplicaAllocation = false, RoutingAllocationTotalShardsPerNode = 1, RecoveryInitialShards = "full", TtlDisablePurge = true, GcDeletes = true, TranslogFsType = "simple", CompoundFormat = true, CompoundOnFlush = true, WarmersEnabled = true }; var response = this._client.UpdateSettings(request); this._status = response.ConnectionStatus; } [Test] public void Url() { this._status.RequestUrl.Should().EndWith("/_settings"); this._status.RequestMethod.Should().Be("PUT"); } [Test] public void UpdateSettingsBody() { this.JsonEquals(this._status.Request, MethodInfo.GetCurrentMethod()); } } }
apache-2.0
C#
0348c28ab2ce932902d88896f80d062f716f3674
Use inline initialization
pardeike/Harmony
Harmony/CodeInstruction.cs
Harmony/CodeInstruction.cs
using Harmony.ILCopying; using System.Collections.Generic; using System.Linq; using System.Reflection.Emit; namespace Harmony { public class CodeInstruction { public OpCode opcode; public object operand; public List<Label> labels = new List<Label>(); public List<ExceptionBlock> blocks = new List<ExceptionBlock>(); public CodeInstruction(OpCode opcode, object operand = null) { this.opcode = opcode; this.operand = operand; } // full copy (be careful with duplicate labels and exception blocks!) // for normal cases, use Clone() // public CodeInstruction(CodeInstruction instruction) { opcode = instruction.opcode; operand = instruction.operand; labels = instruction.labels.ToArray().ToList(); blocks = instruction.blocks.ToArray().ToList(); } // copy only opcode and operand // public CodeInstruction Clone() { return new CodeInstruction(this) { labels = new List<Label>(), blocks = new List<ExceptionBlock>() }; } // copy only operand, use new opcode // public CodeInstruction Clone(OpCode opcode) { var instruction = Clone(); instruction.opcode = opcode; return instruction; } // copy only opcode, use new operand // public CodeInstruction Clone(object operand) { var instruction = Clone(); instruction.operand = operand; return instruction; } public override string ToString() { var list = new List<string>(); foreach (var label in labels) list.Add("Label" + label.GetHashCode()); foreach (var block in blocks) list.Add("EX_" + block.blockType.ToString().Replace("Block", "")); var extras = list.Count > 0 ? " [" + string.Join(", ", list.ToArray()) + "]" : ""; var operandStr = Emitter.FormatArgument(operand); if (operandStr != "") operandStr = " " + operandStr; return opcode + operandStr + extras; } } }
using Harmony.ILCopying; using System.Collections.Generic; using System.Linq; using System.Reflection.Emit; namespace Harmony { public class CodeInstruction { public OpCode opcode; public object operand; public List<Label> labels = new List<Label>(); public List<ExceptionBlock> blocks = new List<ExceptionBlock>(); public CodeInstruction(OpCode opcode, object operand = null) { this.opcode = opcode; this.operand = operand; } // full copy (be careful with duplicate labels and exception blocks!) // for normal cases, use Clone() // public CodeInstruction(CodeInstruction instruction) { opcode = instruction.opcode; operand = instruction.operand; labels = instruction.labels.ToArray().ToList(); blocks = instruction.blocks.ToArray().ToList(); } // copy only opcode and operand // public CodeInstruction Clone() { var instruction = new CodeInstruction(this); instruction.labels = new List<Label>(); instruction.blocks = new List<ExceptionBlock>(); return instruction; } // copy only operand, use new opcode // public CodeInstruction Clone(OpCode opcode) { var instruction = Clone(); instruction.opcode = opcode; return instruction; } // copy only opcode, use new operand // public CodeInstruction Clone(object operand) { var instruction = Clone(); instruction.operand = operand; return instruction; } public override string ToString() { var list = new List<string>(); foreach (var label in labels) list.Add("Label" + label.GetHashCode()); foreach (var block in blocks) list.Add("EX_" + block.blockType.ToString().Replace("Block", "")); var extras = list.Count > 0 ? " [" + string.Join(", ", list.ToArray()) + "]" : ""; var operandStr = Emitter.FormatArgument(operand); if (operandStr != "") operandStr = " " + operandStr; return opcode + operandStr + extras; } } }
mit
C#
422fbf36a7495d5cbfbd30d01eec1377c3d6c291
Fix FortuneTeller for .NET4 not unregistering from eureka on app shutdown
SteelToeOSS/Samples,SteelToeOSS/Samples,SteelToeOSS/Samples,SteelToeOSS/Samples
Discovery/src/AspDotNet4/Fortune-Teller-Service4/Global.asax.cs
Discovery/src/AspDotNet4/Fortune-Teller-Service4/Global.asax.cs
using Autofac; using Autofac.Integration.WebApi; using FortuneTellerService4.Models; using Pivotal.Discovery.Client; using System; using System.Collections.Generic; using System.Linq; using System.Reflection; using System.Web; using System.Web.Http; using System.Web.Routing; namespace FortuneTellerService4 { public class WebApiApplication : System.Web.HttpApplication { private IDiscoveryClient _client; protected void Application_Start() { GlobalConfiguration.Configure(WebApiConfig.Register); var config = GlobalConfiguration.Configuration; // Build application configuration ServerConfig.RegisterConfig("development"); // Create IOC container builder var builder = new ContainerBuilder(); // Register your Web API controllers. builder.RegisterApiControllers(Assembly.GetExecutingAssembly()); // Register IDiscoveryClient, etc. builder.RegisterDiscoveryClient(ServerConfig.Configuration); // Initialize and Register FortuneContext builder.RegisterInstance(SampleData.InitializeFortunes()).SingleInstance(); // Register FortuneRepository builder.RegisterType<FortuneRepository>().As<IFortuneRepository>().SingleInstance(); var container = builder.Build(); config.DependencyResolver = new AutofacWebApiDependencyResolver(container); // Start the Discovery client background thread _client = container.Resolve<IDiscoveryClient>(); } protected void Application_End() { // Unregister current app with Service Discovery server _client.ShutdownAsync(); } } }
using Autofac; using Autofac.Integration.WebApi; using FortuneTellerService4.Models; using Pivotal.Discovery.Client; using System; using System.Collections.Generic; using System.Linq; using System.Reflection; using System.Web; using System.Web.Http; using System.Web.Routing; namespace FortuneTellerService4 { public class WebApiApplication : System.Web.HttpApplication { private IDiscoveryClient _client; protected void Application_Start() { GlobalConfiguration.Configure(WebApiConfig.Register); var config = GlobalConfiguration.Configuration; // Build application configuration ServerConfig.RegisterConfig("development"); // Create IOC container builder var builder = new ContainerBuilder(); // Register your Web API controllers. builder.RegisterApiControllers(Assembly.GetExecutingAssembly()); // Register IDiscoveryClient, etc. builder.RegisterDiscoveryClient(ServerConfig.Configuration); // Initialize and Register FortuneContext builder.RegisterInstance(SampleData.InitializeFortunes()).SingleInstance(); // Register FortuneRepository builder.RegisterType<FortuneRepository>().As<IFortuneRepository>().SingleInstance(); var container = builder.Build(); config.DependencyResolver = new AutofacWebApiDependencyResolver(container); // Start the Discovery client background thread _client = container.Resolve<IDiscoveryClient>(); } } }
apache-2.0
C#
14e4d1a2790310098796402fa9bdb2371feb250b
Improve layout
albinsunnanbo/html5-offline-poc,albinsunnanbo/html5-offline-poc,albinsunnanbo/html5-offline-poc
HTML5-offline-poc/src/HTML5-offline-poc/Views/Home/Index.cshtml
HTML5-offline-poc/src/HTML5-offline-poc/Views/Home/Index.cshtml
@{ ViewData["Title"] = "Home Page"; } <div class="row"> <div class="col-md-3"> <h2>Create items here</h2> <input type="text" id="txt-new-data" /> <button id="btn-add">Add</button> </div> <div class="col-md-3"> <h2>Items</h2> <ul id="offline-items"> @*<li>Content goes here</li>*@ </ul> </div> </div>
@{ ViewData["Title"] = "Home Page"; } <div class="row"> <div class="col-md-3"> <input type="text" id="txt-new-data" /> <button id="btn-add">Add</button> </div> <div class="col-md-3"> <h2>Items</h2> <ul id="offline-items"> @*<li>Content goes here</li>*@ </ul> </div> </div>
mit
C#
62b7b58d89bd95afe253565e5f2ee499617a0dd6
Add CR
nateforsyth/MSADevCampDay1
ConsoleApplicationGitDemo/ConsoleApplicationGitDemo/Program.cs
ConsoleApplicationGitDemo/ConsoleApplicationGitDemo/Program.cs
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ConsoleApplicationGitDemo { class Program { static void Main(string[] args) { Console.WriteLine("Hello world!"); Console.Read(); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ConsoleApplicationGitDemo { class Program { static void Main(string[] args) { Console.WriteLine("Hello world!"); } } }
mit
C#
3372cec70513765fe9065db13c3afb25f9c147a7
Add extra test for generic type for naming
Moq/moq
src/Stunts/Stunts.Tests/StuntNamingTests.cs
src/Stunts/Stunts.Tests/StuntNamingTests.cs
using System; using System.Collections.Generic; using Xunit; namespace Stunts.Tests { public class StuntNamingTests { [Theory] [InlineData("StuntFactoryIDisposableIServiceProvider" + StuntNaming.DefaultSuffix, typeof(StuntFactory), typeof(IServiceProvider), typeof(IDisposable))] [InlineData("IEnumerableOfIDisposableIServiceProvider" + StuntNaming.DefaultSuffix, typeof(IEnumerable<IDisposable>), typeof(IServiceProvider))] public void GetNameOrdersTypes(string expectedName, Type baseType, params Type[] implementedInterfaces) => Assert.Equal(expectedName, StuntNaming.GetName(baseType, implementedInterfaces)); [Theory] [InlineData(StuntNaming.DefaultNamespace + ".StuntFactoryIDisposableIServiceProvider" + StuntNaming.DefaultSuffix, typeof(StuntFactory), typeof(IServiceProvider), typeof(IDisposable))] [InlineData(StuntNaming.DefaultNamespace + ".IEnumerableOfIDisposableIServiceProvider" + StuntNaming.DefaultSuffix, typeof(IEnumerable<IDisposable>), typeof(IServiceProvider))] public void GetFullNameOrdersTypes(string expectedName, Type baseType, params Type[] implementedInterfaces) => Assert.Equal(expectedName, StuntNaming.GetFullName(baseType, implementedInterfaces)); } }
using System; using Xunit; namespace Stunts.Tests { public class StuntNamingTests { [Theory] [InlineData("StuntFactoryIDisposableIServiceProvider" + StuntNaming.DefaultSuffix, typeof(StuntFactory), typeof(IServiceProvider), typeof(IDisposable))] public void GetNameOrdersTypes(string expectedName, Type baseType, params Type[] implementedInterfaces) => Assert.Equal(expectedName, StuntNaming.GetName(baseType, implementedInterfaces)); [Theory] [InlineData(StuntNaming.DefaultNamespace + ".StuntFactoryIDisposableIServiceProvider" + StuntNaming.DefaultSuffix, typeof(StuntFactory), typeof(IServiceProvider), typeof(IDisposable))] public void GetFullNameOrdersTypes(string expectedName, Type baseType, params Type[] implementedInterfaces) => Assert.Equal(expectedName, StuntNaming.GetFullName(baseType, implementedInterfaces)); } }
apache-2.0
C#
4327d319a338fd7c39e9ad83614884c5174a8d4e
include context in event POST request
CoreAPM/DotNetAgent
CoreAPM.NET.CoreMiddleware/CoreAPMMiddleware.cs
CoreAPM.NET.CoreMiddleware/CoreAPMMiddleware.cs
using System; using System.Threading.Tasks; using CoreAPM.NET.Agent; using Microsoft.AspNetCore.Http; namespace CoreAPM.NET.CoreMiddleware { public class CoreAPMMiddleware { private readonly RequestDelegate _next; private readonly IAgent _agent; private readonly Func<ITimer> newTimer; public CoreAPMMiddleware(RequestDelegate next, IAgent agent, Func<ITimer> timerFac) { newTimer = timerFac; _next = next; _agent = agent; } public async Task Invoke(HttpContext httpContext) { var time = getRequestTime(httpContext); var e = new Event { ID = Guid.NewGuid(), Type = "ServerResponse", Source = httpContext.Request.Host.Value, Action = httpContext.Request.Path.Value, Result = httpContext.Response.StatusCode.ToString(), Context = httpContext.TraceIdentifier, Time = DateTime.Now, Length = await time }; _agent.Send(e); } private async Task<double> getRequestTime(HttpContext httpContext) { var timer = newTimer(); timer.Start(); await _next.Invoke(httpContext); timer.Stop(); return timer.CurrentTime; } } }
using System; using System.Threading.Tasks; using CoreAPM.NET.Agent; using Microsoft.AspNetCore.Http; namespace CoreAPM.NET.CoreMiddleware { public class CoreAPMMiddleware { private readonly RequestDelegate _next; private readonly IAgent _agent; private readonly Func<ITimer> newTimer; public CoreAPMMiddleware(RequestDelegate next, IAgent agent, Func<ITimer> timerFac) { newTimer = timerFac; _next = next; _agent = agent; } public async Task Invoke(HttpContext httpContext) { var time = getRequestTime(httpContext); var e = new Event { ID = Guid.NewGuid(), Type = "ServerResponse", Source = httpContext.Request.Host.Value, Action = httpContext.Request.Path.Value, Result = httpContext.Response.StatusCode.ToString(), Time = DateTime.Now, Length = await time }; _agent.Send(e); } private async Task<double> getRequestTime(HttpContext httpContext) { var timer = newTimer(); timer.Start(); await _next.Invoke(httpContext); timer.Stop(); return timer.CurrentTime; } } }
mit
C#
4a3ef400e64512db1e389b4556984b746899e507
Add Material.FromColor
florin-chelaru/urho,florin-chelaru/urho,florin-chelaru/urho,florin-chelaru/urho,florin-chelaru/urho,florin-chelaru/urho
Bindings/Portable/Material.cs
Bindings/Portable/Material.cs
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Urho { partial class Material { public static Material FromImage(string image) { var cache = Application.Current.ResourceCache; var material = new Material(); material.SetTexture(TextureUnit.Diffuse, cache.GetTexture2D(image)); material.SetTechnique(0, CoreAssets.Techniques.Diff, 0, 0); return material; } public static Material FromColor(Color color) { var material = new Material(); var cache = Application.Current.ResourceCache; material.SetTechnique(0, color.A == 1 ? CoreAssets.Techniques.NoTexture : CoreAssets.Techniques.NoTextureAlpha, 1, 1); material.SetShaderParameter("MatDiffColor", color); return material; } public static Material SkyboxFromImages( string imagePositiveX, string imageNegativeX, string imagePositiveY, string imageNegativeY, string imagePositiveZ, string imageNegativeZ) { var cache = Application.Current.ResourceCache; var material = new Material(); TextureCube cube = new TextureCube(); cube.SetData(CubeMapFace.PositiveX, cache.GetFile(imagePositiveX, false)); cube.SetData(CubeMapFace.NegativeX, cache.GetFile(imageNegativeX, false)); cube.SetData(CubeMapFace.PositiveY, cache.GetFile(imagePositiveY, false)); cube.SetData(CubeMapFace.NegativeY, cache.GetFile(imageNegativeY, false)); cube.SetData(CubeMapFace.PositiveZ, cache.GetFile(imagePositiveZ, false)); cube.SetData(CubeMapFace.NegativeZ, cache.GetFile(imageNegativeZ, false)); material.SetTexture(TextureUnit.Diffuse, cube); material.SetTechnique(0, CoreAssets.Techniques.DiffSkybox, 0, 0); material.CullMode = CullMode.None; return material; } public static Material SkyboxFromImage(string image) { return SkyboxFromImages(image, image, image, image, image, image); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Urho { partial class Material { public static Material FromImage(string image) { var cache = Application.Current.ResourceCache; var material = new Material(); material.SetTexture(TextureUnit.Diffuse, cache.GetTexture2D(image)); material.SetTechnique(0, CoreAssets.Techniques.Diff, 0, 0); return material; } public static Material SkyboxFromImages( string imagePositiveX, string imageNegativeX, string imagePositiveY, string imageNegativeY, string imagePositiveZ, string imageNegativeZ) { var cache = Application.Current.ResourceCache; var material = new Material(); TextureCube cube = new TextureCube(); cube.SetData(CubeMapFace.PositiveX, cache.GetFile(imagePositiveX, false)); cube.SetData(CubeMapFace.NegativeX, cache.GetFile(imageNegativeX, false)); cube.SetData(CubeMapFace.PositiveY, cache.GetFile(imagePositiveY, false)); cube.SetData(CubeMapFace.NegativeY, cache.GetFile(imageNegativeY, false)); cube.SetData(CubeMapFace.PositiveZ, cache.GetFile(imagePositiveZ, false)); cube.SetData(CubeMapFace.NegativeZ, cache.GetFile(imageNegativeZ, false)); material.SetTexture(TextureUnit.Diffuse, cube); material.SetTechnique(0, CoreAssets.Techniques.DiffSkybox, 0, 0); material.CullMode = CullMode.None; return material; } public static Material SkyboxFromImage(string image) { return SkyboxFromImages(image, image, image, image, image, image); } } }
mit
C#
c4497f45be9389912a44a173a84992d586c507c3
bump to v0.2.2
peters/assemblyinfo
src/assemblyinfo/Properties/AssemblyInfo.cs
src/assemblyinfo/Properties/AssemblyInfo.cs
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("assemblyinfo")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("assemblyinfo")] [assembly: AssemblyCopyright("Copyright © Peter Sunde 2013")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("d2587fde-ac26-43a1-bde3-920ae0fa540b")] // 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.2.2")] [assembly: AssemblyFileVersion("0.2.2")] [assembly: AssemblyInformationalVersion("0.2.2")] [assembly: InternalsVisibleTo("assemblyinfo.tests, PublicKey=00240000048000009400000006020000002400005253413100040000010001003f1fddfeafe99f552f4449650bd29ea429b00839864ebcd3313c9f15f095016cd22b37704d8fe005d978b8996877f6e73550131d78eb916f466d3dc80b9b2410f85287e1b6d3179d1621ddd2ed90624192f0979e35eadf2ee49158a496e4b278d5725b30e9d2679e07fe8f6cb528dc4460d472e0f44b663a75c4347924784cce")]
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("assemblyinfo")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("assemblyinfo")] [assembly: AssemblyCopyright("Copyright © Peter Sunde 2013")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("d2587fde-ac26-43a1-bde3-920ae0fa540b")] // 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.2.1")] [assembly: AssemblyFileVersion("0.2.1")] [assembly: AssemblyInformationalVersion("0.2.1")] [assembly: InternalsVisibleTo("assemblyinfo.tests, PublicKey=00240000048000009400000006020000002400005253413100040000010001003f1fddfeafe99f552f4449650bd29ea429b00839864ebcd3313c9f15f095016cd22b37704d8fe005d978b8996877f6e73550131d78eb916f466d3dc80b9b2410f85287e1b6d3179d1621ddd2ed90624192f0979e35eadf2ee49158a496e4b278d5725b30e9d2679e07fe8f6cb528dc4460d472e0f44b663a75c4347924784cce")]
mit
C#
c039528fd695d48f956c0a93bb2f9a10b0fb9753
Add Transaction APIs for executing IDeferable and IDeferable<T>.
SilkStack/Silk.Data.SQL.ORM
Silk.Data.SQL.ORM/Silk.Data/Transaction.cs
Silk.Data.SQL.ORM/Silk.Data/Transaction.cs
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace Silk.Data { public class Transaction { private readonly List<ITransactionController> _transactionControllers = new List<ITransactionController>(); private IEnumerable<ITransactionController> GetNewTransactionControllers(DeferredExecutor executor) { var result = new List<ITransactionController>(); foreach (var task in executor) { var controller = task.GetTransactionControllerImplementation(); var existingController = _transactionControllers.FirstOrDefault( q => q.AreEquivalentSharedControllers(controller) ); if (existingController == null) existingController = result.FirstOrDefault( q => q.AreEquivalentSharedControllers(controller) ); if (existingController != null) { task.SetSharedTransactionController(existingController); continue; } task.SetSharedTransactionController(controller); result.Add(controller); } return result; } public void Execute(IDeferable deferable) => Execute(new[] { deferable.Defer() }); public Task ExecuteAsync(IDeferable deferable) => ExecuteAsync(new[] { deferable.Defer() }); public T Execute<T>(IDeferable<T> deferable) { Execute(new[] { deferable.Defer(out var result) }); return result.Result; } public async Task<T> ExecuteAsync<T>(IDeferable<T> deferable) { await ExecuteAsync(new[] { deferable.Defer(out var result) }); return result.Result; } public void Execute(IEnumerable<IDeferred> deferredTasks) { var executor = deferredTasks.ToExecutor(); foreach (var controller in GetNewTransactionControllers(executor)) { controller.Begin(); _transactionControllers.Add(controller); } executor.Execute(); } public async Task ExecuteAsync(IEnumerable<IDeferred> deferredTasks) { var executor = deferredTasks.ToExecutor(); foreach (var controller in GetNewTransactionControllers(executor)) { await controller.BeginAsync(); _transactionControllers.Add(controller); } await executor.ExecuteAsync(); } public void Commit() { foreach (var controller in _transactionControllers) controller.Commit(); } public void Rollback() { var exceptionCollection = new List<Exception>(); foreach (var controller in _transactionControllers) { try { controller.Rollback(); } catch(Exception ex) { exceptionCollection.Add(ex); } } if (exceptionCollection.Count > 0) throw new AggregateException("One or more exceptions occurred while rolling back.", exceptionCollection); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace Silk.Data { public class Transaction { private readonly List<ITransactionController> _transactionControllers = new List<ITransactionController>(); private IEnumerable<ITransactionController> GetNewTransactionControllers(DeferredExecutor executor) { var result = new List<ITransactionController>(); foreach (var task in executor) { var controller = task.GetTransactionControllerImplementation(); var existingController = _transactionControllers.FirstOrDefault( q => q.AreEquivalentSharedControllers(controller) ); if (existingController == null) existingController = result.FirstOrDefault( q => q.AreEquivalentSharedControllers(controller) ); if (existingController != null) { task.SetSharedTransactionController(existingController); continue; } task.SetSharedTransactionController(controller); result.Add(controller); } return result; } public void Execute(IEnumerable<IDeferred> deferredTasks) { var executor = deferredTasks.ToExecutor(); foreach (var controller in GetNewTransactionControllers(executor)) { controller.Begin(); _transactionControllers.Add(controller); } executor.Execute(); } public async Task ExecuteAsync(IEnumerable<IDeferred> deferredTasks) { var executor = deferredTasks.ToExecutor(); foreach (var controller in GetNewTransactionControllers(executor)) { await controller.BeginAsync(); _transactionControllers.Add(controller); } await executor.ExecuteAsync(); } public void Commit() { foreach (var controller in _transactionControllers) controller.Commit(); } public void Rollback() { var exceptionCollection = new List<Exception>(); foreach (var controller in _transactionControllers) { try { controller.Rollback(); } catch(Exception ex) { exceptionCollection.Add(ex); } } if (exceptionCollection.Count > 0) throw new AggregateException("One or more exceptions occurred while rolling back.", exceptionCollection); } } }
mit
C#
d24da454b3e5d3e3f872363a94a18ab8b790e0ca
Fix ZoneMarker: replace DaemonEngineZone with DaemonZone
ulrichb/XmlDocInspections,ulrichb/XmlDocInspections,ulrichb/XmlDocInspections
Src/XmlDocInspections.Plugin/ZoneMarker.cs
Src/XmlDocInspections.Plugin/ZoneMarker.cs
using JetBrains.Application.BuildScript.Application.Zones; using JetBrains.ReSharper.Feature.Services.Daemon; using JetBrains.ReSharper.Psi.CSharp; namespace XmlDocInspections.Plugin { [ZoneMarker] public class ZoneMarker : IRequire<ILanguageCSharpZone>, IRequire<DaemonZone> { } }
using JetBrains.Application.BuildScript.Application.Zones; using JetBrains.ReSharper.Feature.Services.Daemon; using JetBrains.ReSharper.Psi.CSharp; namespace XmlDocInspections.Plugin { [ZoneMarker] public class ZoneMarker : IRequire<ILanguageCSharpZone>, IRequire<DaemonEngineZone> { } }
mit
C#
134d21bf28f895089e40b58fb9de9febfd929e93
change name every time tab is open
kaviteshsingh/tabcontrol_mvvm
TabbedLayout/ViewModels/TabOneViewModel.cs
TabbedLayout/ViewModels/TabOneViewModel.cs
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Windows.Input; using TabbedLayout.Commands; using TabbedLayout.Model; namespace TabbedLayout.ViewModels { class TabOneViewModel : WorkspaceViewModel { private Person _CurrentUser; public Person CurrentUser { get { return _CurrentUser; } set { _CurrentUser = value; OnPropertyChanged("CurrentUser"); } } private DelegateCommand _cmdSubmit; public DelegateCommand CmdSubmit { get { return _cmdSubmit ?? (_cmdSubmit = new DelegateCommand(SubmitHandler)); } } private void SubmitHandler() { Console.WriteLine(CurrentUser.ToString()); } public TabOneViewModel() { CurrentUser = new Person(); CurrentUser.Name = DateTime.Now.ToString(); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Windows.Input; using TabbedLayout.Commands; using TabbedLayout.Model; namespace TabbedLayout.ViewModels { class TabOneViewModel : WorkspaceViewModel { private Person _CurrentUser; public Person CurrentUser { get { return _CurrentUser; } set { _CurrentUser = value; OnPropertyChanged("CurrentUser"); } } private DelegateCommand _cmdSubmit; public DelegateCommand CmdSubmit { get { return _cmdSubmit ?? (_cmdSubmit = new DelegateCommand(SubmitHandler)); } } private void SubmitHandler() { Console.WriteLine(CurrentUser.ToString()); } public TabOneViewModel() { CurrentUser = new Person(); CurrentUser.Name = "Kavitesh"; } } }
mit
C#
62003b118f714e8876b29c39b774e1f63461ece4
build floor-plane
accu-rate/SumoVizUnity,accu-rate/SumoVizUnity
Assets/Scripts/sim/Floor.cs
Assets/Scripts/sim/Floor.cs
using UnityEngine; using System.Collections.Generic; using System; public class Floor { private List<Wall> walls = new List<Wall>(); private List<WunderZone> wunderZones = new List<WunderZone>(); private string floorId; private int level; internal float elevation; private float height; internal List<float> boundingPoints; internal Floor(string floorId) { this.floorId = floorId; } internal void addWunderZone(WunderZone wz) { wunderZones.Add(wz); } internal void addWall(Wall wall) { walls.Add(wall); } internal void printGeometryElements() { Debug.Log("Floor " + floorId); foreach(var wz in wunderZones) { Debug.Log(" WunderZone: " + wz.getId()); } foreach (var wall in walls) { Debug.Log(" Wall: " + wall.getId()); } } internal void setMetaData(int level, float height, float elevation, List<float> boundingPoints) { this.level = level; this.height = height; this.elevation = elevation; this.boundingPoints = boundingPoints; } internal void createObjects() { List<Vector2> plane = new List<Vector2>(); float minX = boundingPoints[0], minY = boundingPoints[1], maxX = boundingPoints[2], maxY = boundingPoints[3]; plane.Add(new Vector2(minX, minY)); plane.Add(new Vector2(minX, maxY)); plane.Add(new Vector2(maxX, maxY)); plane.Add(new Vector2(maxX, minY)); AreaGeometry.createOriginTarget(floorId + "_ground", plane, new Color(1.0f, 1.0f, 1.0f, 0.3f), elevation - 0.01f); foreach (WunderZone wz in wunderZones) { wz.createObject(); } foreach (Wall wall in walls) { wall.createObject(); } } }
using UnityEngine; using System.Collections.Generic; using System; public class Floor { private List<Wall> walls = new List<Wall>(); private List<WunderZone> wunderZones = new List<WunderZone>(); private string floorId; private int level; internal float elevation; private float height; internal List<float> boundingPoints; internal Floor(string floorId) { this.floorId = floorId; } internal void addWunderZone(WunderZone wz) { wunderZones.Add(wz); } internal void addWall(Wall wall) { walls.Add(wall); } internal void printGeometryElements() { Debug.Log("Floor " + floorId); foreach(var wz in wunderZones) { Debug.Log(" WunderZone: " + wz.getId()); } foreach (var wall in walls) { Debug.Log(" Wall: " + wall.getId()); } } internal void setMetaData(int level, float height, float elevation, List<float> boundingPoints) { this.level = level; this.height = height; this.elevation = elevation; this.boundingPoints = boundingPoints; } internal void createObjects() { foreach (WunderZone wz in wunderZones) { wz.createObject(); } foreach (Wall wall in walls) { wall.createObject(); } } }
mit
C#
20bd5158e4fbb81cd9f44be35d5e2719cca05993
Fix a typo
adrianbanks/BroadbandSpeedStats,adrianbanks/BroadbandSpeedStats,adrianbanks/BroadbandSpeedStats,adrianbanks/BroadbandSpeedStats
NetgearRouter.Tests/Devices/DeviceInformationExtractorTests.cs
NetgearRouter.Tests/Devices/DeviceInformationExtractorTests.cs
using System.Linq; using BroadbandStats.NetgearRouter.Devices; using NUnit.Framework; using Shouldly; namespace NetgearRouter.Tests.Devices { [TestFixture] public sealed class DeviceInformationExtractorTests { [TestCase(null)] [TestCase("")] [TestCase(" ")] [TestCase("gibberish")] public void ReturnsNullWhenGivenInvalidInput(string soapResponse) { var extractor = new DeviceInformationExtractor(); var deviceInformation = extractor.ExtractDeviceInformation(soapResponse); deviceInformation.ShouldBeNull(); } [TestCase("1@device1@")] [TestCase("2@device1@device2@")] public void ShouldExtractDeviceInformationCorrectly(string expectedDeviceInformation) { var soapResponse = string.Format(SoapBoilerPlate, expectedDeviceInformation); var extractor = new DeviceInformationExtractor(); var deviceInformation = extractor.ExtractDeviceInformation(soapResponse); deviceInformation.ShouldBe(expectedDeviceInformation); } private const string SoapBoilerPlate = @"<?xml version=""1.0"" encoding=""UTF-8""?> <soap-env:Envelope xmlns:soap-env=""http://schemas.xmlsoap.org/soap/envelope/"" soap-env:encodingStyle=""http://schemas.xmlsoap.org/soap/encoding/"" > <soap-env:Body> <m:GetAttachDeviceResponse xmlns:m=""urn:NETGEAT-ROUTER:service:DeviceInfo:1""> <NewAttachDevice>{0}</NewAttachDevice> </m:GetAttachDeviceResponse> <ResponseCode>000</ResponseCode> </soap-env:Body> </soap-env:Envelope>"; } }
using System.Linq; using BroadbandStats.NetgearRouter.Devices; using NUnit.Framework; using Shouldly; namespace NetgearRouter.Tests.Devices { [TestFixture] public sealed class DeviceInformationExtractorTests { [TestCase(null)] [TestCase("")] [TestCase(" ")] [TestCase("gibberish")] public void ReturnsNullWhenGivenInvalidInput(string soapResponse) { var extractor = new DeviceInformationExtractor(); var deviceInformation = extractor.ExtractDeviceInformation(soapResponse); deviceInformation.ShouldBeNull(); } [TestCase("1@device1@")] [TestCase("2@device1@device2@")] public void ShouldExtractDeviceInformationCorrectly(string expeectedDeviceInformation) { var soapResponse = string.Format(SoapBoilerPlate, expeectedDeviceInformation); var extractor = new DeviceInformationExtractor(); var deviceInformation = extractor.ExtractDeviceInformation(soapResponse); deviceInformation.ShouldBe(expeectedDeviceInformation); } private const string SoapBoilerPlate = @"<?xml version=""1.0"" encoding=""UTF-8""?> <soap-env:Envelope xmlns:soap-env=""http://schemas.xmlsoap.org/soap/envelope/"" soap-env:encodingStyle=""http://schemas.xmlsoap.org/soap/encoding/"" > <soap-env:Body> <m:GetAttachDeviceResponse xmlns:m=""urn:NETGEAT-ROUTER:service:DeviceInfo:1""> <NewAttachDevice>{0}</NewAttachDevice> </m:GetAttachDeviceResponse> <ResponseCode>000</ResponseCode> </soap-env:Body> </soap-env:Envelope>"; } }
mit
C#
c2ff7775d1806cba4cedcad7f576b048692f1b92
fix QueryTokenPartProxy
AlejandroCano/extensions,signumsoftware/extensions,signumsoftware/framework,AlejandroCano/extensions,signumsoftware/extensions,signumsoftware/framework
Signum.React.Extensions.Selenium/Search/QueryTokenPartProxy.cs
Signum.React.Extensions.Selenium/Search/QueryTokenPartProxy.cs
using OpenQA.Selenium; using Signum.Utilities; namespace Signum.React.Selenium { public class QueryTokenPartProxy { public IWebElement Element { get; private set; } public QueryTokenPartProxy(IWebElement element) { this.Element = element; } public void Select(string? key) { if (!this.Element.IsElementVisible(By.ClassName("rw-popup-container"))) { this.Element.FindElement(By.ClassName("rw-dropdown-list")).Click(); } var container = this.Element.WaitElementVisible(By.ClassName("rw-popup-container")); var selector = key.HasText() ? By.CssSelector("div > span[data-token='" + key + "']") : By.CssSelector("div > span:not([data-token])"); var elem = container.WaitElementVisible(selector); elem.ScrollTo(); elem.Click(); } } }
using OpenQA.Selenium; using Signum.Utilities; namespace Signum.React.Selenium { public class QueryTokenPartProxy { public IWebElement Element { get; private set; } public QueryTokenPartProxy(IWebElement element) { this.Element = element; } public void Select(string? key) { if (!this.Element.IsElementVisible(By.ClassName("rw-popup-container"))) { this.Element.FindElement(By.ClassName("rw-dropdown-list")).Click(); } var container = this.Element.WaitElementVisible(By.ClassName("rw-popup-container")); var selector = key.HasText() ? By.CssSelector("li > span[data-token='" + key + "']") : By.CssSelector("li > span:not([data-token])"); var elem = container.WaitElementVisible(selector); elem.ScrollTo(); elem.Click(); } } }
mit
C#
0890cf12d7b91b4c8a92f256346fbc0acf7bbb8a
Update RegionalCurrencyRedirectionOptions.cs
tiksn/TIKSN-Framework
TIKSN.Core/Globalization/RegionalCurrencyRedirectionOptions.cs
TIKSN.Core/Globalization/RegionalCurrencyRedirectionOptions.cs
using System.Collections.Generic; namespace TIKSN.Globalization { public class RegionalCurrencyRedirectionOptions { public RegionalCurrencyRedirectionOptions() => this.RegionalCurrencyRedirections = new Dictionary<string, string> { {"001", "en-US"}, {"150", "en-BE"}, {"029", "en-KN"}, {"419", "en-US"} }; public Dictionary<string, string> RegionalCurrencyRedirections { get; set; } } }
using System.Collections.Generic; namespace TIKSN.Globalization { public class RegionalCurrencyRedirectionOptions { public RegionalCurrencyRedirectionOptions() { RegionalCurrencyRedirections = new Dictionary<string, string> { { "001", "en-US"}, { "150", "en-BE"}, { "029", "en-KN"}, { "419", "en-US"} }; } public Dictionary<string, string> RegionalCurrencyRedirections { get; set; } } }
mit
C#
021bcb5e1134edc94c90e157ba73cc7747eaa6f9
Update MyDataRepository.cs
kelong/Data-Repository-with-Data-Caching-in-ASP.NET-MVC-4,CarmelSoftware/Data-Repository-with-Data-Caching-in-ASP.NET-MVC-4
Models/MyDataRepository.cs
Models/MyDataRepository.cs
// TODO: fix this class : class name : "RepositoryCaching" using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Runtime.Caching; namespace RepositoryWithCaching.Models { public class RepositoryCaching { public ObjectCache Cache { get { return MemoryCache.Default; } } public bool IsInMemory(string Key) { return Cache.Contains(Key); } public void Add(string Key, object Value, int Expiration) { Cache.Add(Key, Value, new CacheItemPolicy().AbsoluteExpiration = DateTime.Now + TimeSpan.FromMinutes(Expiration)); } public IQueryable<T> FetchData<T>(string Key) where T : class { return Cache[Key] as IQueryable<T>; } public void Remove(string Key) { Cache.Remove(Key); } } }
// TODO: fix this class : class name : "RepositoryCaching" using system; ////public class MyDataRepository { // TODO: check what happens when different users use Cache simultaneously public ObjectCache Cache { get { return MemoryCache.Default; } } public bool IsInMemory(string Key) { return Cache.Contains(Key); } public void Add(string Key, object Value, int Expiration) { Cache.Add(Key, Value, new CacheItemPolicy().AbsoluteExpiration = DateTime.Now + TimeSpan.FromMinutes(Expiration)); } public IQueryable<T> FetchData<T>(string Key) where T : class { return Cache[Key] as IQueryable<T>; } public void Remove(string Key) { Cache.Remove(Key); } } }
mit
C#
ff24d4b828d7b315777ddd059d25fd158f1e5696
Improve test.
TheSustainables/NDocRaptor
NDocRaptor.Test/Program.cs
NDocRaptor.Test/Program.cs
using System; using System.Diagnostics; using System.IO; namespace NDocRaptor { class Program { static void Main(string[] args) { var raptor = new DocRaptor("<your api key>", testMode: true); Action<DocRaptorResponse> test = response => { Console.WriteLine("Success: {0}", response.Success); Console.WriteLine("Error-phrase: {0}", response.ReasonPhrase); if (response.Success) { var tempFile = Path.GetTempFileName() + ".pdf"; var bytes = response.Response.Content.ReadAsByteArrayAsync().Result; File.WriteAllBytes(tempFile, bytes); Process.Start(tempFile); } }; var html = "<html><head><title></title></head><body><h1>Yeah</h1></body></html>"; test(raptor.CreatePdfDocumentAsync(html).Result); test(raptor.CreatePdfDocumentAsync(new Uri("https://html.spec.whatwg.org/multipage/")).Result); Console.ReadLine(); } } }
using System; using System.Diagnostics; using System.IO; namespace NDocRaptor { class Program { static void Main(string[] args) { var raptor = new DocRaptor("<your api key>", testMode: true); Action<DocRaptorResponse> test = response => { Console.WriteLine("Success: {0}", response.Success); Console.WriteLine("Error-phrase: {0}", response.ReasonPhrase); var tempFile = Path.GetTempFileName() + ".pdf"; var bytes = response.Response.Content.ReadAsByteArrayAsync().Result; File.WriteAllBytes(tempFile, bytes); Process.Start(tempFile); }; var html = "<html><head><title></title></head><body><h1>Yeah</h1></body></html>"; test(raptor.CreatePdfDocumentAsync(html).Result); test(raptor.CreatePdfDocumentAsync(new Uri("https://html.spec.whatwg.org/multipage/")).Result); Console.ReadLine(); } } }
mit
C#
95341555f1e95fed4626d1d95a380ce4bdfe2c26
Change Early Registration
OrchardCMS/Orchard-Harvest-Website,OrchardCMS/Orchard-Harvest-Website,OrchardCMS/Orchard-Harvest-Website,OrchardCMS/Orchard-Harvest-Website,OrchardCMS/Orchard-Harvest-Website,OrchardCMS/Orchard-Harvest-Website
src/Orchard.Web/Themes/OrchardHarvest.Theme2017/Views/Home-RegistrationBox.cshtml
src/Orchard.Web/Themes/OrchardHarvest.Theme2017/Views/Home-RegistrationBox.cshtml
<!-- box-action --> <section class="box-action"> <div class="container"> <div class="title"> <p class="lead">@T("Early Registration Ends Tuesday January 31")</p> </div> <div class="button"> <a href="https://orchardharvest.eventbrite.com" target="_blank">REGISTER TODAY</a> <span class="arrow_box_action"></span> </div> </div> </section> <!-- End box-action-->
<!-- box-action --> <section class="box-action"> <div class="container"> <div class="title"> <p class="lead">@T("Early Registration Ends Monday December 31")</p> </div> <div class="button"> <a href="https://www.eventbrite.com/e/orchard-harvest-2017-new-york-usa-tickets-29062296110" target="_blank">REGISTER TODAY</a> <span class="arrow_box_action"></span> </div> </div> </section> <!-- End box-action-->
bsd-3-clause
C#
a1fcd62c2d9441289c0668ff36b65c22570e8023
update slotname in redirect_uri
projectkudu/TryAppService,davidebbo/SimpleWAWS,fashaikh/SimpleWAWS,projectkudu/SimpleWAWS,projectkudu/TryAppService,projectkudu/SimpleWAWS,projectkudu/TryAppService,davidebbo/SimpleWAWS,projectkudu/SimpleWAWS,davidebbo/SimpleWAWS,davidebbo/SimpleWAWS,projectkudu/TryAppService,fashaikh/SimpleWAWS,projectkudu/SimpleWAWS,fashaikh/SimpleWAWS,fashaikh/SimpleWAWS
SimpleWAWS/Authentication/GoogleAuthProvider.cs
SimpleWAWS/Authentication/GoogleAuthProvider.cs
using System; using System.Collections.Generic; using System.Configuration; using System.Globalization; using System.Linq; using System.Net; using System.Text; using System.Web; namespace SimpleWAWS.Authentication { public class GoogleAuthProvider : BaseOpenIdConnectAuthProvider { public override string GetLoginUrl(HttpContextBase context) { var culture = CultureInfo.CurrentCulture.Name.ToLowerInvariant(); var builder = new StringBuilder(); builder.Append("https://accounts.google.com/o/oauth2/auth"); builder.Append("?response_type=id_token"); var slot = String.Empty; if (context.Request.QueryString["x-ms-routing-name"] != null) slot = $"?x-ms-routing-name={context.Request.QueryString["x-ms-routing-name"]}"; builder.AppendFormat("&redirect_uri={0}", WebUtility.UrlEncode(string.Format(CultureInfo.InvariantCulture, "https://{0}/Login{1}", context.Request.Headers["HOST"], slot))); builder.AppendFormat("&client_id={0}", AuthSettings.GoogleAppId); builder.AppendFormat("&scope={0}", "email"); if (context.IsFunctionsPortalRequest()) { builder.AppendFormat("&state={0}", WebUtility.UrlEncode(string.Format(CultureInfo.InvariantCulture, "{0}{1}", context.Request.Headers["Referer"], context.Request.Url.Query) )); } else builder.AppendFormat("&state={0}", WebUtility.UrlEncode(context.IsAjaxRequest()? string.Format(CultureInfo.InvariantCulture, "/{0}{1}", culture, context.Request.Url.Query) : context.Request.Url.PathAndQuery)); return builder.ToString(); } protected override string GetValidAudiance() { return AuthSettings.GoogleAppId; } public override string GetIssuerName(string altSecId) { return "Google"; } } }
using System; using System.Collections.Generic; using System.Configuration; using System.Globalization; using System.Linq; using System.Net; using System.Text; using System.Web; namespace SimpleWAWS.Authentication { public class GoogleAuthProvider : BaseOpenIdConnectAuthProvider { public override string GetLoginUrl(HttpContextBase context) { var culture = CultureInfo.CurrentCulture.Name.ToLowerInvariant(); var builder = new StringBuilder(); builder.Append("https://accounts.google.com/o/oauth2/auth"); builder.Append("?response_type=id_token"); builder.AppendFormat("&redirect_uri={0}", WebUtility.UrlEncode(string.Format(CultureInfo.InvariantCulture, "https://{0}/Login", context.Request.Headers["HOST"]))); builder.AppendFormat("&client_id={0}", AuthSettings.GoogleAppId); builder.AppendFormat("&scope={0}", "email"); if (context.IsFunctionsPortalRequest()) { var slot = String.Empty; if (context.Request.QueryString["x-ms-routing-name"] != null) slot = $"?x-ms-routing-name={context.Request.QueryString["x-ms-routing-name"]}"; builder.AppendFormat($"{slot}&state={0}", WebUtility.UrlEncode(string.Format(CultureInfo.InvariantCulture, "{0}{1}", context.Request.Headers["Referer"], context.Request.Url.Query) )); } else builder.AppendFormat("&state={0}", WebUtility.UrlEncode(context.IsAjaxRequest()? string.Format(CultureInfo.InvariantCulture, "/{0}{1}", culture, context.Request.Url.Query) : context.Request.Url.PathAndQuery)); return builder.ToString(); } protected override string GetValidAudiance() { return AuthSettings.GoogleAppId; } public override string GetIssuerName(string altSecId) { return "Google"; } } }
apache-2.0
C#
38a7b285ff324d959d26a0a2d391feb6029123e1
Disable broken test session thing.
wasabii/Cogito,wasabii/Cogito
Cogito.Core.Tests/Net/Http/HttpMessageEventSourceTests.cs
Cogito.Core.Tests/Net/Http/HttpMessageEventSourceTests.cs
using System; using System.Diagnostics.Eventing.Reader; using System.Net; using System.Net.Http; using Cogito.Net.Http; using Microsoft.Diagnostics.Tracing; using Microsoft.Diagnostics.Tracing.Session; using Microsoft.Practices.EnterpriseLibrary.SemanticLogging.Utility; using Microsoft.Samples.Eventing; using Microsoft.VisualStudio.TestTools.UnitTesting; namespace Cogito.Tests.Net.Http { [TestClass] public class HttpMessageEventSourceTests { [TestMethod] public void Test_EventSource() { EventSourceAnalyzer.InspectAll(HttpMessageEventSource.Current); } //[TestMethod] //public void Test_Request() //{ // using (var session = new TraceEventSession("MyRealTimeSession")) // { // session.Source.Dynamic.All += data => Console.WriteLine("GOT Event " + data); // session.EnableProvider(TraceEventProviders.GetEventSourceGuidFromName("Cogito-Net-Http-Messages")); // HttpMessageEventSource.Current.Request(new HttpRequestMessage(HttpMethod.Get, new Uri("http://www.tempuri.com")) // { // }); // session.Source.Process(); // } //} //[TestMethod] //public void Test_Response() //{ // HttpMessageEventSource.Current.Response(new HttpResponseMessage(HttpStatusCode.OK)); //} } }
using System; using System.Diagnostics.Eventing.Reader; using System.Net; using System.Net.Http; using Cogito.Net.Http; using Microsoft.Diagnostics.Tracing; using Microsoft.Diagnostics.Tracing.Session; using Microsoft.Practices.EnterpriseLibrary.SemanticLogging.Utility; using Microsoft.Samples.Eventing; using Microsoft.VisualStudio.TestTools.UnitTesting; namespace Cogito.Tests.Net.Http { [TestClass] public class HttpMessageEventSourceTests { [TestMethod] public void Test_EventSource() { EventSourceAnalyzer.InspectAll(HttpMessageEventSource.Current); } [TestMethod] public void Test_Request() { using (var session = new TraceEventSession("MyRealTimeSession")) { session.Source.Dynamic.All += data => Console.WriteLine("GOT Event " + data); session.EnableProvider(TraceEventProviders.GetEventSourceGuidFromName("Cogito-Net-Http-Messages")); HttpMessageEventSource.Current.Request(new HttpRequestMessage(HttpMethod.Get, new Uri("http://www.tempuri.com")) { }); session.Source.Process(); } } [TestMethod] public void Test_Response() { HttpMessageEventSource.Current.Response(new HttpResponseMessage(HttpStatusCode.OK)); } } }
mit
C#
ac09af742ba18a9b751fdf6fe9446af4dfc6697a
clean up created file after test run
OlegKleyman/Omego.Selenium
tests/integration/Omego.Selenium.Tests.Integration/Features/SeleniumExtensions.cs
tests/integration/Omego.Selenium.Tests.Integration/Features/SeleniumExtensions.cs
namespace Omego.Selenium.Tests.Integration.Features { using System; using System.Drawing.Imaging; using System.IO; using FluentAssertions; using Extensions; using OpenQA.Selenium; using OpenQA.Selenium.Firefox; using Xbehave; public class SeleniumExtensions { private IWebDriver driver; [Background] public void Background() { "Given I have an IWebDriver object"._(() => driver = new FirefoxDriver()) .Teardown(() => this.driver.Dispose()); "And it's full screen"._(() => this.driver.Manage().Window.Maximize()); } [Scenario] [Example(@".\screenshots", "screen.png")] [CLSCompliant(false)] public void TakeScreenShot(string directoryPath, string fileName) { var pathToFile = Path.Combine(directoryPath, fileName); "Given I used a web driver to go to a website"._( () => driver.Navigate().GoToUrl("http://www.thedailywtf.com")).Teardown(() => driver.Dispose()); $"When I call the SaveScreenShotAs in {pathToFile} extension method"._( () => driver.SaveScreenshotAs(1000, new ImageTarget(directoryPath, fileName, ImageFormat.Bmp))) .Teardown( () => { if (Directory.Exists(directoryPath)) { Directory.Delete(directoryPath, true); } }); "Then the screenshot should be saved"._( () => File.Exists(pathToFile).Should().BeTrue("The screenshot needs to exist")); } } }
namespace Omego.Selenium.Tests.Integration.Features { using System; using System.Drawing.Imaging; using System.IO; using FluentAssertions; using Extensions; using OpenQA.Selenium; using OpenQA.Selenium.Firefox; using Xbehave; public class SeleniumExtensions { private IWebDriver driver; [Background] public void Background() { "Given I have an IWebDriver object"._(() => driver = new FirefoxDriver()) .Teardown(() => this.driver.Dispose()); "And it's full screen"._(() => this.driver.Manage().Window.Maximize()); } [Scenario] [Example(@".\screenshots", "screen.png")] [CLSCompliant(false)] public void TakeScreenShot(string directoryPath, string fileName) { var pathToFile = Path.Combine(directoryPath, fileName); "Given I used a web driver to go to a website"._(() => driver.Navigate().GoToUrl("http://www.thedailywtf.com")) .Teardown(() => driver.Dispose()); $"When I call the SaveScreenShotAs in {pathToFile} extension method"._( () => driver.SaveScreenshotAs(1000, new ImageTarget(directoryPath, fileName, ImageFormat.Bmp))); "Then the screenshot should be saved"._( () => File.Exists(pathToFile).Should().BeTrue("The screenshot needs to exist")); } } }
unlicense
C#
8f47bbdae1ea5c0ec5a0cafb87f9f22c1ee58d7b
mark API calls as not implemented
SpectraLogic/tpfr_client
TpfrClient/TpfrClient.cs
TpfrClient/TpfrClient.cs
/* * ****************************************************************************** * Copyright 2014 - 2016 Spectra Logic Corporation. 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. A copy of the License is located at * * http://www.apache.org/licenses/LICENSE-2.0 * * or in the "license" file accompanying this file. * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR * CONDITIONS OF ANY KIND, either express or implied. See the License for the * specific language governing permissions and limitations under the License. * **************************************************************************** */ using System; using TpfrClient.Calls; using TpfrClient.Model; using TpfrClient.ResponseParsers; using TpfrClient.Runtime; namespace TpfrClient { public class TpfrClient : ITpfrClient { private readonly INetwork _network; public TpfrClient(string hostServerName, int hostServerPort) { _network = new Network(hostServerName, hostServerPort); } public TpfrClient(INetwork network) { _network = network; } public TpfrClient WithProxy(string proxy) { return !string.IsNullOrEmpty(proxy) ? WithProxy(new Uri(proxy)) : this; } private TpfrClient WithProxy(Uri proxy) { _network.WithProxy(proxy); return this; } public IndexStatus IndexFile(IndexFileRequest request) { return new IndexFileResponseParser().Parse(_network.Invoke(request)); } public IndexStatus FileStatus(FileStatusRequest request) { return new FileStatusResponseParser().Parse(_network.Invoke(request)); } [Obsolete("Not Implemented")] public OffsetsStatus QuestionTimecode(QuestionTimecodeRequest request) { throw new NotImplementedException(); return new QuestionTimecodeResponseParser().Parse(_network.Invoke(request)); } [Obsolete("Not Implemented")] public void ReWrap(ReWrapRequest request) { throw new NotImplementedException(); new ReWrapResponseParser().Parse(_network.Invoke(request)); } [Obsolete("Not Implemented")] public ReWrapStatus ReWrapStatus(ReWrapStatusRequest request) { throw new NotImplementedException(); return new ReWrapStatusResponseParser().Parse(_network.Invoke(request)); } } }
/* * ****************************************************************************** * Copyright 2014 - 2016 Spectra Logic Corporation. 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. A copy of the License is located at * * http://www.apache.org/licenses/LICENSE-2.0 * * or in the "license" file accompanying this file. * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR * CONDITIONS OF ANY KIND, either express or implied. See the License for the * specific language governing permissions and limitations under the License. * **************************************************************************** */ using System; using TpfrClient.Calls; using TpfrClient.Model; using TpfrClient.ResponseParsers; using TpfrClient.Runtime; namespace TpfrClient { public class TpfrClient : ITpfrClient { private readonly INetwork _network; public TpfrClient(string hostServerName, int hostServerPort) { _network = new Network(hostServerName, hostServerPort); } public TpfrClient(INetwork network) { _network = network; } public TpfrClient WithProxy(string proxy) { return !string.IsNullOrEmpty(proxy) ? WithProxy(new Uri(proxy)) : this; } private TpfrClient WithProxy(Uri proxy) { _network.WithProxy(proxy); return this; } public IndexStatus IndexFile(IndexFileRequest request) { return new IndexFileResponseParser().Parse(_network.Invoke(request)); } public IndexStatus FileStatus(FileStatusRequest request) { return new FileStatusResponseParser().Parse(_network.Invoke(request)); } public OffsetsStatus QuestionTimecode(QuestionTimecodeRequest request) { return new QuestionTimecodeResponseParser().Parse(_network.Invoke(request)); } public void ReWrap(ReWrapRequest request) { new ReWrapResponseParser().Parse(_network.Invoke(request)); } public ReWrapStatus ReWrapStatus(ReWrapStatusRequest request) { return new ReWrapStatusResponseParser().Parse(_network.Invoke(request)); } } }
apache-2.0
C#
b42f54addb51ea9ed3ab8154be5eb2bd849eaa14
Add comments for F.Add
farity/farity
Farity/Add.cs
Farity/Add.cs
using System; namespace Farity { public static partial class F { /// <summary> /// Adds two numeric values. /// </summary> /// <typeparam name="T">The data type of the operands in the add operation.</typeparam> /// <param name="a">The addendum.</param> /// <param name="b">The additive.</param> /// <returns>The result of adding the two values.</returns> public static T Add<T>(T a, T b) where T : struct, IComparable, IComparable<T>, IConvertible, IEquatable<T>, IFormattable => Operator<T>.Add(a, b); } }
using System; namespace Farity { public static partial class F { public static T Add<T>(T a, T b) where T : struct, IComparable, IComparable<T>, IConvertible, IEquatable<T>, IFormattable => Operator<T>.Add(a, b); } }
mit
C#
84be861145219c20282a2d642b6af67bcd09e4a3
Update Gate.cs
irtezasyed007/CSC523-Game-Project
Gates/Gate.cs
Gates/Gate.cs
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace CSC_523_Game { abstract class Gate { public Variable[] vars; public Gate(Variable[] vars) { this.vars = vars; } public abstract bool gateOperation(); public abstract bool getResult(); } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace CSC_523_Game { abstract class Gate { public Variable[] vars; public Gate(Variable [] vars) { this.vars = vars; } public abstract bool getResult(); } }
mit
C#
bd2611224623a707a84420b0613beaa54bcbd7d6
Fix bug about declined by user not shown
joinrpg/joinrpg-net,leotsarev/joinrpg-net,kirillkos/joinrpg-net,joinrpg/joinrpg-net,joinrpg/joinrpg-net,joinrpg/joinrpg-net,leotsarev/joinrpg-net,leotsarev/joinrpg-net,leotsarev/joinrpg-net,kirillkos/joinrpg-net
JoinRpg.Dal.Impl/Repositories/ClaimPredicates.cs
JoinRpg.Dal.Impl/Repositories/ClaimPredicates.cs
using System; using System.Linq.Expressions; using JoinRpg.Data.Interfaces; using JoinRpg.DataModel; namespace JoinRpg.Dal.Impl.Repositories { internal static class ClaimPredicates { public static Expression<Func<Claim, bool>> GetClaimStatusPredicate(ClaimStatusSpec status) { switch (status) { case ClaimStatusSpec.Any: return claim => true; case ClaimStatusSpec.Active: return c => c.ClaimStatus != Claim.Status.DeclinedByMaster && c.ClaimStatus != Claim.Status.DeclinedByUser && c.ClaimStatus != Claim.Status.OnHold; case ClaimStatusSpec.InActive: return c => c.ClaimStatus == Claim.Status.DeclinedByMaster || c.ClaimStatus == Claim.Status.DeclinedByUser || c.ClaimStatus == Claim.Status.OnHold; case ClaimStatusSpec.Discussion: return c => c.ClaimStatus == Claim.Status.AddedByMaster || c.ClaimStatus == Claim.Status.AddedByUser || c.ClaimStatus == Claim.Status.Discussed; case ClaimStatusSpec.OnHold: return c => c.ClaimStatus == Claim.Status.OnHold; case ClaimStatusSpec.Approved: return c => c.ClaimStatus == Claim.Status.Approved || c.ClaimStatus == Claim.Status.CheckedIn; case ClaimStatusSpec.ReadyForCheckIn: return c => c.ClaimStatus == Claim.Status.Approved && c.CheckInDate == null; case ClaimStatusSpec.CheckedIn: return c => c.ClaimStatus == Claim.Status.CheckedIn; default: throw new ArgumentOutOfRangeException(nameof(status), status, null); } } } }
using System; using System.Linq.Expressions; using JoinRpg.Data.Interfaces; using JoinRpg.DataModel; namespace JoinRpg.Dal.Impl.Repositories { internal static class ClaimPredicates { public static Expression<Func<Claim, bool>> GetClaimStatusPredicate(ClaimStatusSpec status) { switch (status) { case ClaimStatusSpec.Any: return claim => true; case ClaimStatusSpec.Active: return c => c.ClaimStatus != Claim.Status.DeclinedByMaster && c.ClaimStatus != Claim.Status.DeclinedByUser && c.ClaimStatus != Claim.Status.OnHold; case ClaimStatusSpec.InActive: return c => c.ClaimStatus == Claim.Status.DeclinedByMaster || c.ClaimStatus == Claim.Status.DeclinedByUser && c.ClaimStatus == Claim.Status.OnHold; case ClaimStatusSpec.Discussion: return c => c.ClaimStatus == Claim.Status.AddedByMaster || c.ClaimStatus == Claim.Status.AddedByUser || c.ClaimStatus == Claim.Status.Discussed; case ClaimStatusSpec.OnHold: return c => c.ClaimStatus == Claim.Status.OnHold; case ClaimStatusSpec.Approved: return c => c.ClaimStatus == Claim.Status.Approved || c.ClaimStatus == Claim.Status.CheckedIn; case ClaimStatusSpec.ReadyForCheckIn: return c => c.ClaimStatus == Claim.Status.Approved && c.CheckInDate == null; case ClaimStatusSpec.CheckedIn: return c => c.ClaimStatus == Claim.Status.CheckedIn; default: throw new ArgumentOutOfRangeException(nameof(status), status, null); } } } }
mit
C#
f4f3588047606c5210beec97b06436d3c7e765ac
Fix bug - command parameter is always null.
ashokgelal/Puppy
Puppy/MenuService/MenuItem.cs
Puppy/MenuService/MenuItem.cs
#region Using using System.Collections.Generic; using System.Windows.Input; using PuppyFramework.Services; #endregion namespace PuppyFramework.MenuService { public class MenuItem : MenuItemBase { #region Fields private ObservableSortedList<MenuItemBase> _children; private string _title; #endregion #region Properties public object CommandParameter { get; set; } public CommandBinding CommandBinding { get; set; } public ObservableSortedList<MenuItemBase> Children { get { return _children; } private set { SetProperty(ref _children, value); } } public string Title { get { return _title; } protected set { SetProperty(ref _title, value); } } #endregion #region Constructors public MenuItem(string title, double weight) : base(weight) { Title = title; Children = new ObservableSortedList<MenuItemBase>(); HiddenFlag = false; } #endregion #region Methods public void AddChild(MenuItemBase child, IComparer<MenuItemBase> menuItemComparer = null) { Children.Add(child); if (menuItemComparer != null) { Children.Sort(menuItemComparer); } } public bool RemoveChild(MenuItemBase child) { return Children.Remove(child); } #endregion } }
#region Using using System.Collections.Generic; using System.Windows.Input; using PuppyFramework.Services; #endregion namespace PuppyFramework.MenuService { public class MenuItem : MenuItemBase { #region Fields private ObservableSortedList<MenuItemBase> _children; private string _title; #endregion #region Properties public object CommandParamter { get; set; } public CommandBinding CommandBinding { get; set; } public ObservableSortedList<MenuItemBase> Children { get { return _children; } private set { SetProperty(ref _children, value); } } public string Title { get { return _title; } protected set { SetProperty(ref _title, value); } } #endregion #region Constructors public MenuItem(string title, double weight) : base(weight) { Title = title; Children = new ObservableSortedList<MenuItemBase>(); HiddenFlag = false; } #endregion #region Methods public void AddChild(MenuItemBase child, IComparer<MenuItemBase> menuItemComparer = null) { Children.Add(child); if (menuItemComparer != null) { Children.Sort(menuItemComparer); } } public bool RemoveChild(MenuItemBase child) { return Children.Remove(child); } #endregion } }
mit
C#
2acb1014236b03273799a37a596dcf8e26df6df0
Convert value for TextBoxCell to string, even it is not a string instance
l8s/Eto,l8s/Eto,bbqchickenrobot/Eto-1,bbqchickenrobot/Eto-1,PowerOfCode/Eto,PowerOfCode/Eto,PowerOfCode/Eto,bbqchickenrobot/Eto-1,l8s/Eto
Source/Eto.Platform.Mac/Forms/Cells/TextBoxCellHandler.cs
Source/Eto.Platform.Mac/Forms/Cells/TextBoxCellHandler.cs
using System; using MonoMac.AppKit; using Eto.Forms; using MonoMac.Foundation; using MonoMac.ObjCRuntime; using Eto.Drawing; namespace Eto.Platform.Mac.Forms.Controls { public class TextBoxCellHandler : CellHandler<NSTextFieldCell, TextBoxCell>, ITextBoxCell { public class EtoCell : NSTextFieldCell, IMacControl { public object Handler { get; set; } public EtoCell () { } public EtoCell (IntPtr handle) : base(handle) { } [Export("copyWithZone:")] NSObject CopyWithZone (IntPtr zone) { var ptr = Messaging.IntPtr_objc_msgSendSuper_IntPtr (SuperHandle, MacCommon.selCopyWithZone.Handle, zone); return new EtoCell (ptr) { Handler = this.Handler }; } } public TextBoxCellHandler () { Control = new EtoCell { Handler = this, UsesSingleLineMode = true }; } public override void SetBackgroundColor (NSCell cell, Color color) { var c = cell as EtoCell; c.BackgroundColor = Generator.ConvertNS (color); c.DrawsBackground = color != Colors.Transparent; } public override Color GetBackgroundColor (NSCell cell) { var c = cell as EtoCell; return Generator.Convert (c.BackgroundColor); } public override void SetForegroundColor (NSCell cell, Color color) { var c = cell as EtoCell; c.TextColor = Generator.ConvertNS (color); } public override Color GetForegroundColor (NSCell cell) { var c = cell as EtoCell; return Generator.Convert (c.TextColor); } public override NSObject GetObjectValue (object dataItem) { if (Widget.Binding != null) { var val = Widget.Binding.GetValue (dataItem); return val != null ? new NSString(Convert.ToString (val)) : null; } else return null; } public override void SetObjectValue (object dataItem, NSObject val) { if (Widget.Binding != null) { var str = val as NSString; if (str != null) Widget.Binding.SetValue (dataItem, (string)str); else Widget.Binding.SetValue (dataItem, null); } } public override float GetPreferredSize (object value, System.Drawing.SizeF cellSize, NSCell cell) { var font = cell.Font ?? NSFont.SystemFontOfSize (NSFont.SystemFontSize); var str = new NSString (Convert.ToString (value)); var attrs = NSDictionary.FromObjectAndKey (font, NSAttributedString.FontAttributeName); return str.StringSize (attrs).Width + 4; // for border } } }
using System; using MonoMac.AppKit; using Eto.Forms; using MonoMac.Foundation; using MonoMac.ObjCRuntime; using Eto.Drawing; namespace Eto.Platform.Mac.Forms.Controls { public class TextBoxCellHandler : CellHandler<NSTextFieldCell, TextBoxCell>, ITextBoxCell { public class EtoCell : NSTextFieldCell, IMacControl { public object Handler { get; set; } public EtoCell () { } public EtoCell (IntPtr handle) : base(handle) { } [Export("copyWithZone:")] NSObject CopyWithZone (IntPtr zone) { var ptr = Messaging.IntPtr_objc_msgSendSuper_IntPtr (SuperHandle, MacCommon.selCopyWithZone.Handle, zone); return new EtoCell (ptr) { Handler = this.Handler }; } } public TextBoxCellHandler () { Control = new EtoCell { Handler = this, UsesSingleLineMode = true }; } public override void SetBackgroundColor (NSCell cell, Color color) { var c = cell as EtoCell; c.BackgroundColor = Generator.ConvertNS (color); c.DrawsBackground = color != Colors.Transparent; } public override Color GetBackgroundColor (NSCell cell) { var c = cell as EtoCell; return Generator.Convert (c.BackgroundColor); } public override void SetForegroundColor (NSCell cell, Color color) { var c = cell as EtoCell; c.TextColor = Generator.ConvertNS (color); } public override Color GetForegroundColor (NSCell cell) { var c = cell as EtoCell; return Generator.Convert (c.TextColor); } public override NSObject GetObjectValue (object dataItem) { if (Widget.Binding != null) { var val = Widget.Binding.GetValue (dataItem); return val is string ? new NSString((string)val) : null; } else return new NSString (); } public override void SetObjectValue (object dataItem, NSObject val) { if (Widget.Binding != null) { var str = val as NSString; if (str != null) Widget.Binding.SetValue (dataItem, (string)str); else Widget.Binding.SetValue (dataItem, null); } } public override float GetPreferredSize (object value, System.Drawing.SizeF cellSize, NSCell cell) { var font = cell.Font ?? NSFont.SystemFontOfSize (NSFont.SystemFontSize); var str = new NSString (Convert.ToString (value)); var attrs = NSDictionary.FromObjectAndKey (font, NSAttributedString.FontAttributeName); return str.StringSize (attrs).Width + 4; // for border } } }
bsd-3-clause
C#
62c34e14902026f609b66411cfdc2cf1e6d9a45f
Move ship with code.
MoreOnCode/MonoGameBookCode
Vol6-CodeCamps/Ch03-SpaceGame/SpaceGame/SpaceGame/Game.cs
Vol6-CodeCamps/Ch03-SpaceGame/SpaceGame/SpaceGame/Game.cs
using System; using System.Collections.Generic; using System.IO; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Graphics; using Microsoft.Xna.Framework.Input; using Microsoft.Xna.Framework.Media; using Microsoft.Xna.Framework.Input.Touch; namespace SpaceGame { public class SpaceGame : Microsoft.Xna.Framework.Game { // Resources for drawing. private GraphicsDeviceManager graphics; private SpriteBatch spriteBatch; // reference our spaceship protected Texture2D texShip; // NEW: our ship's location protected Vector2 locShipStart = Vector2.One * 100.0f; protected Vector2 locShipDelta = Vector2.Zero; public SpaceGame() { graphics = new GraphicsDeviceManager(this); Content.RootDirectory = "Content"; if(PlatformHelper.CurrentPlatform == Platforms.WindowsPhone) { TargetElapsedTime = TimeSpan.FromTicks(333333); } graphics.IsFullScreen = PlatformHelper.IsMobile; this.IsMouseVisible = PlatformHelper.IsDesktop; graphics.PreferredBackBufferWidth = 800; graphics.PreferredBackBufferHeight = 480; graphics.SupportedOrientations = DisplayOrientation.LandscapeLeft | DisplayOrientation.LandscapeRight; GamePadEx.KeyboardPlayerIndex = PlayerIndex.One; } protected override void LoadContent() { // Create a new SpriteBatch, which can be used to draw textures. spriteBatch = new SpriteBatch(GraphicsDevice); // load our spaceship image texShip = Content.Load<Texture2D> ("playerShip1_red"); } protected override void Update(GameTime gameTime) { var gamepad1 = GamePadEx.GetState (PlayerIndex.One); if (gamepad1.IsButtonDown (Buttons.Back)) { this.Exit (); } else { // NEW: move the ship var dX = (float)Math.Sin(gameTime.TotalGameTime.TotalSeconds); locShipDelta.X = 75.0f * dX; } base.Update(gameTime); } protected override void Draw(GameTime gameTime) { graphics.GraphicsDevice.Clear (Color.CornflowerBlue); spriteBatch.Begin (); // NEW: draw our spaceship image at current location spriteBatch.Draw ( texShip, locShipStart + locShipDelta, Color.White); spriteBatch.End (); base.Draw (gameTime); } } }
using System; using System.Collections.Generic; using System.IO; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Graphics; using Microsoft.Xna.Framework.Input; using Microsoft.Xna.Framework.Media; using Microsoft.Xna.Framework.Input.Touch; namespace SpaceGame { public class SpaceGame : Microsoft.Xna.Framework.Game { // Resources for drawing. private GraphicsDeviceManager graphics; private SpriteBatch spriteBatch; // NEW: reference our spaceship protected Texture2D texShip; public SpaceGame() { graphics = new GraphicsDeviceManager(this); Content.RootDirectory = "Content"; if(PlatformHelper.CurrentPlatform == Platforms.WindowsPhone) { TargetElapsedTime = TimeSpan.FromTicks(333333); } graphics.IsFullScreen = PlatformHelper.IsMobile; this.IsMouseVisible = PlatformHelper.IsDesktop; graphics.PreferredBackBufferWidth = 800; graphics.PreferredBackBufferHeight = 480; graphics.SupportedOrientations = DisplayOrientation.LandscapeLeft | DisplayOrientation.LandscapeRight; GamePadEx.KeyboardPlayerIndex = PlayerIndex.One; } protected override void LoadContent() { // Create a new SpriteBatch, which can be used to draw textures. spriteBatch = new SpriteBatch(GraphicsDevice); // NEW: load our spaceship image texShip = Content.Load<Texture2D> ("playerShip1_red"); } protected override void Update(GameTime gameTime) { var gamepad1 = GamePadEx.GetState (PlayerIndex.One); if (gamepad1.IsButtonDown (Buttons.Back)) { this.Exit (); } else { // TODO: update game objects here } base.Update(gameTime); } protected override void Draw(GameTime gameTime) { graphics.GraphicsDevice.Clear (Color.CornflowerBlue); spriteBatch.Begin (); // NEW: draw our spaceship image spriteBatch.Draw (texShip, Vector2.One * 100.0f, Color.White); spriteBatch.End (); base.Draw (gameTime); } } }
mit
C#
9f3094ffbe51d28713329c3c29a18f7250675e12
Initialize animated object path
bartlomiejwolk/AnimationPathAnimator
PathData.cs
PathData.cs
using UnityEngine; using System.Collections; namespace ATP.AnimationPathTools { public class PathData : ScriptableObject { [SerializeField] private AnimationPath animatedObjectPath; [SerializeField] private AnimationPath rotationPath; [SerializeField] private AnimationCurve easeCurve; [SerializeField] private AnimationCurve tiltingCurve; private void OnEnable() { InstantiateReferenceTypes(); AssignDefaultValues(); } private void AssignDefaultValues() { InitializeAnimatedObjectPath(); } private void InitializeAnimatedObjectPath() { var firstNodePos = new Vector3(0, 0, 0); animatedObjectPath.CreateNewNode(0, firstNodePos); var lastNodePos = new Vector3(1, 0, 1); animatedObjectPath.CreateNewNode(1, lastNodePos); } private void InstantiateReferenceTypes() { animatedObjectPath = ScriptableObject.CreateInstance<AnimationPath>(); rotationPath = ScriptableObject.CreateInstance<AnimationPath>(); easeCurve = new AnimationCurve(); tiltingCurve = new AnimationCurve(); } } }
using UnityEngine; using System.Collections; namespace ATP.AnimationPathTools { public class PathData : ScriptableObject { [SerializeField] private AnimationPath animatedObjectPath; [SerializeField] private AnimationPath rotationPath; [SerializeField] private AnimationCurve easeCurve; [SerializeField] private AnimationCurve tiltingCurve; private void OnEnable() { animatedObjectPath = ScriptableObject.CreateInstance<AnimationPath>(); rotationPath = ScriptableObject.CreateInstance<AnimationPath>(); easeCurve = new AnimationCurve(); tiltingCurve = new AnimationCurve(); } } }
mit
C#
567a7b6d48c3c0ebead0a6635c6b36da50ba34c9
Fix AddSmtpSender extension methods to property add service
lukencode/FluentEmail,lukencode/FluentEmail
src/Senders/FluentEmail.Smtp/FluentEmailSmtpBuilderExtensions.cs
src/Senders/FluentEmail.Smtp/FluentEmailSmtpBuilderExtensions.cs
using FluentEmail.Core.Interfaces; using FluentEmail.Smtp; using Microsoft.Extensions.DependencyInjection.Extensions; using System; using System.Net; using System.Net.Mail; namespace Microsoft.Extensions.DependencyInjection { public static class FluentEmailSmtpBuilderExtensions { public static FluentEmailServicesBuilder AddSmtpSender(this FluentEmailServicesBuilder builder, SmtpClient smtpClient) { builder.Services.TryAdd(ServiceDescriptor.Singleton<ISender>(x => new SmtpSender(smtpClient))); return builder; } public static FluentEmailServicesBuilder AddSmtpSender(this FluentEmailServicesBuilder builder, string host, int port) => AddSmtpSender(builder, () => new SmtpClient(host, port)); public static FluentEmailServicesBuilder AddSmtpSender(this FluentEmailServicesBuilder builder, string host, int port, string username, string password) => AddSmtpSender(builder, () => new SmtpClient(host, port) { EnableSsl = true, Credentials = new NetworkCredential (username, password) }); public static FluentEmailServicesBuilder AddSmtpSender(this FluentEmailServicesBuilder builder, Func<SmtpClient> clientFactory) { builder.Services.TryAdd(ServiceDescriptor.Scoped<ISender>(x => new SmtpSender(clientFactory))); return builder; } } }
using FluentEmail.Core.Interfaces; using FluentEmail.Smtp; using Microsoft.Extensions.DependencyInjection.Extensions; using System; using System.Net; using System.Net.Mail; namespace Microsoft.Extensions.DependencyInjection { public static class FluentEmailSmtpBuilderExtensions { public static FluentEmailServicesBuilder AddSmtpSender(this FluentEmailServicesBuilder builder, SmtpClient smtpClient) { builder.Services.TryAdd(ServiceDescriptor.Scoped<ISender>(x => new SmtpSender(smtpClient))); return builder; } public static FluentEmailServicesBuilder AddSmtpSender(this FluentEmailServicesBuilder builder, string host, int port) => AddSmtpSender(builder, new SmtpClient(host, port)); public static FluentEmailServicesBuilder AddSmtpSender(this FluentEmailServicesBuilder builder, string host, int port, string username, string password) => AddSmtpSender(builder, new SmtpClient(host, port) { EnableSsl = true, Credentials = new NetworkCredential (username, password) }); public static FluentEmailServicesBuilder AddSmtpSender(this FluentEmailServicesBuilder builder, Func<SmtpClient> clientFactory) { builder.Services.TryAdd(ServiceDescriptor.Scoped<ISender>(x => new SmtpSender(clientFactory))); return builder; } } }
mit
C#
2b5b64e35233ca2c8177a371b86067cfce06b0c8
Correct minify abstraction
ssg/Eksi.Tasks,ssg/Eksi.Tasks
MinifyTask.cs
MinifyTask.cs
/* * Eksi.Tasks library - collection of NAnt tasks * Copyright (c) 2010 Ekşi Teknoloji Ltd. (http://www.eksiteknoloji.com) * Licensed under MIT License, read license.txt for details */ using System; using System.IO; using NAnt.Core; using NAnt.Core.Attributes; using NAnt.Core.Types; namespace Eksi.Tasks { /// <summary> /// This is the base task to derive all "minimizers" from. /// </summary> public abstract class MinifyTask : Task { [TaskAttribute("suffix", Required = false)] public string Suffix { get; set; } [TaskAttribute("todir", Required = false)] public string DestPath { get; set; } [BuildElement("fileset", Required = true)] public FileSet Files { get; set; } protected override void ExecuteTask() { string suffix = Suffix; string destPath = DestPath; foreach (var fileName in Files.FileNames) { string outputFileName = Path.GetFileNameWithoutExtension(fileName) + (suffix ?? String.Empty) + Path.GetExtension(fileName); string outputPath = destPath ?? Path.GetDirectoryName(fileName); if (!Directory.Exists(outputPath)) { Directory.CreateDirectory(outputPath); } outputFileName = Path.Combine(outputPath, outputFileName); Minify(fileName, outputFileName); } } protected abstract void Minify(string inputFileName, string outputFileName); } }
/* * Eksi.Tasks library - collection of NAnt tasks * Copyright (c) 2010 Ekşi Teknoloji Ltd. (http://www.eksiteknoloji.com) * Licensed under MIT License, read license.txt for details */ using System; using System.IO; using NAnt.Core; using NAnt.Core.Attributes; using NAnt.Core.Types; namespace Eksi.Tasks { /// <summary> /// This is the base task to derive all "minimizers" from. /// </summary> public class MinifyTask : Task { [TaskAttribute("suffix", Required = false)] public string Suffix { get; set; } [TaskAttribute("todir", Required = false)] public string DestPath { get; set; } [BuildElement("fileset", Required = true)] public FileSet Files { get; set; } protected override void ExecuteTask() { string suffix = Suffix; string destPath = DestPath; foreach (var fileName in Files.FileNames) { string outputFileName = Path.GetFileNameWithoutExtension(fileName) + (suffix ?? String.Empty) + Path.GetExtension(fileName); string outputPath = destPath ?? Path.GetDirectoryName(fileName); if (!Directory.Exists(outputPath)) { Directory.CreateDirectory(outputPath); } outputFileName = Path.Combine(outputPath, outputFileName); Minify(fileName, outputFileName); } } protected virtual void Minify(string inputFileName, string outputFileName) { throw new NotImplementedException("Forgot to override Minify"); } } }
mit
C#
7bab361a63a3b45f3a52cd9045da3deb83aae3f5
Add convenience ctor
praeclarum/Ooui,praeclarum/Ooui,praeclarum/Ooui
Ooui/Label.cs
Ooui/Label.cs
using System; namespace Ooui { public class Label : Element { public Element For { get => GetAttribute<Element> ("for", null); set => SetAttributeProperty ("for", value); } public Label () : base ("label") { } public Label (string text) : this () { Text = text; } } }
using System; namespace Ooui { public class Label : Element { public Element For { get => GetAttribute<Element> ("for", null); set => SetAttributeProperty ("for", value); } public Label () : base ("label") { } } }
mit
C#
8f0eb99f9207de002a9a2229d0dac650eae16c97
Implement AppHarborClient#GetApplication
appharbor/appharbor-cli
src/AppHarbor/AppHarborClient.cs
src/AppHarbor/AppHarborClient.cs
using System; using System.Collections.Generic; using AppHarbor.Model; namespace AppHarbor { public class AppHarborClient : IAppHarborClient { private readonly AuthInfo _authInfo; public AppHarborClient(string AccessToken) { _authInfo = new AuthInfo { AccessToken = AccessToken }; } public CreateResult<string> CreateApplication(string name, string regionIdentifier = null) { var appHarborApi = GetAppHarborApi(); return appHarborApi.CreateApplication(name, regionIdentifier); } public Application GetApplication(string id) { var appHarborApi = GetAppHarborApi(); return appHarborApi.GetApplication(id); } public IEnumerable<Application> GetApplications() { var appHarborApi = GetAppHarborApi(); return appHarborApi.GetApplications(); } public User GetUser() { var appHarborApi = GetAppHarborApi(); return appHarborApi.GetUser(); } private AppHarborApi GetAppHarborApi() { try { return new AppHarborApi(_authInfo); } catch (ArgumentNullException) { throw new CommandException("You're not logged in. Log in with \"appharbor login\""); } } } }
using System; using System.Collections.Generic; using AppHarbor.Model; namespace AppHarbor { public class AppHarborClient : IAppHarborClient { private readonly AuthInfo _authInfo; public AppHarborClient(string AccessToken) { _authInfo = new AuthInfo { AccessToken = AccessToken }; } public CreateResult<string> CreateApplication(string name, string regionIdentifier = null) { var appHarborApi = GetAppHarborApi(); return appHarborApi.CreateApplication(name, regionIdentifier); } public Application GetApplication(string id) { throw new NotImplementedException(); } public IEnumerable<Application> GetApplications() { var appHarborApi = GetAppHarborApi(); return appHarborApi.GetApplications(); } public User GetUser() { var appHarborApi = GetAppHarborApi(); return appHarborApi.GetUser(); } private AppHarborApi GetAppHarborApi() { try { return new AppHarborApi(_authInfo); } catch (ArgumentNullException) { throw new CommandException("You're not logged in. Log in with \"appharbor login\""); } } } }
mit
C#
1996407aeac2e23936b1287f1edfe6629480b22f
Update Bind.cs
charleypeng/XamIoc
XamIoc/Bind.cs
XamIoc/Bind.cs
using System; using System.Collections.Generic; using System.Text; namespace XamIoc { public static partial class Core { /// <summary> /// Bind Interface to Class /// </summary> /// <typeparam name="TSource">Interface</typeparam> /// <typeparam name="TDestination">Class</typeparam> public static void Bind<TSource, TDestination>() { InversionDict[typeof(TSource)] = typeof(TDestination); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace XamIoc { public static partial class Core { /// <summary> /// Bind Interface to Class /// </summary> /// <typeparam name="TSource">Interface</typeparam> /// <typeparam name="TDestination">Class</typeparam> public static void Bind<TSource, TDestination>() { InversionDict[typeof(TSource)] = typeof(TDestination); } } }
mit
C#
b0c959b5bf4c825ac6fd4b0c1794fe98017d1d54
Update the value type too
VolatileMindsLLC/ntreg-sharp
ValueKey.cs
ValueKey.cs
using System; using System.IO; using System.Collections.Generic; namespace ntregsharp { public class ValueKey { public ValueKey (BinaryReader hive) { this.AbsoluteOffset = hive.BaseStream.Position; byte[] buf = hive.ReadBytes (2); if (buf [0] != 0x76 && buf [1] != 0x6b) throw new NotSupportedException ("Bad vk header"); buf = hive.ReadBytes (2); this.NameLength = BitConverter.ToInt16 (buf, 0); this.DataLength = BitConverter.ToInt32 (hive.ReadBytes (4), 0); //dataoffset, unless data is stored here byte[] databuf = hive.ReadBytes (4); this.ValueType = hive.ReadInt32 (); hive.BaseStream.Position += 4; buf = hive.ReadBytes (this.NameLength); this.Name = (this.NameLength == 0) ? "Default" : System.Text.Encoding.UTF8.GetString (buf); if (this.DataLength < 5) { this.DataOffset = this.AbsoluteOffset + 8; this.Data = databuf; } else { hive.BaseStream.Position = 0x1000 + BitConverter.ToInt32 (databuf, 0) + 0x04; this.DataOffset = hive.BaseStream.Position; this.Data = hive.ReadBytes (this.DataLength); if (this.ValueType == 1) this.String = System.Text.Encoding.Unicode.GetString (this.Data); } } public void EditName (FileStream hive, string newName) { byte[] name = System.Text.Encoding.UTF8.GetBytes (System.Text.Encoding.UTF8.GetString (System.Text.Encoding.ASCII.GetBytes (newName))); if (name.Length > this.NameLength) throw new Exception ("New name cannot be longer than old name currently."); hive.Position = this.AbsoluteOffset + 20; int k = this.NameLength - name.Length; hive.Write (name, 0, name.Length); for (int i = 0; i < k; i++) hive.WriteByte (0x00); } public void EditData (FileStream hive, byte[] data, int valueType) { if (data.Length > this.DataLength) throw new Exception ("New data cannot be longer than old data currently."); byte[] bytes = BitConverter.GetBytes (valueType); hive.Position = this.AbsoluteOffset + 12; hive.Write (bytes, 0, bytes.Length); hive.Position = this.DataOffset; int k = this.DataLength - data.Length; hive.Write (data, 0, data.Length); for (int i = 0; i < k; i++) hive.WriteByte (0x00); } public long AbsoluteOffset { get; set; } public short NameLength { get; set; } public int DataLength { get; set; } public long DataOffset { get; set; } public int ValueType { get; set; } public string Name { get; set; } public byte[] Data { get; set; } public string String { get; set; } } }
using System; using System.IO; using System.Collections.Generic; namespace ntregsharp { public class ValueKey { public ValueKey (BinaryReader hive) { this.AbsoluteOffset = hive.BaseStream.Position; byte[] buf = hive.ReadBytes (2); if (buf [0] != 0x76 && buf [1] != 0x6b) throw new NotSupportedException ("Bad vk header"); buf = hive.ReadBytes (2); this.NameLength = BitConverter.ToInt16 (buf, 0); this.DataLength = BitConverter.ToInt32 (hive.ReadBytes (4), 0); //dataoffset, unless data is stored here byte[] databuf = hive.ReadBytes (4); this.ValueType = hive.ReadInt32 (); hive.BaseStream.Position += 4; buf = hive.ReadBytes (this.NameLength); this.Name = (this.NameLength == 0) ? "Default" : System.Text.Encoding.UTF8.GetString (buf); if (this.DataLength < 5) { this.DataOffset = this.AbsoluteOffset + 8; this.Data = databuf; } else { hive.BaseStream.Position = 0x1000 + BitConverter.ToInt32 (databuf, 0) + 0x04; this.DataOffset = hive.BaseStream.Position; this.Data = hive.ReadBytes (this.DataLength); if (this.ValueType == 1) this.String = System.Text.Encoding.Unicode.GetString (this.Data); } } public void EditName (FileStream hive, string newName) { byte[] name = System.Text.Encoding.UTF8.GetBytes (System.Text.Encoding.UTF8.GetString (System.Text.Encoding.ASCII.GetBytes (newName))); if (name.Length > this.NameLength) throw new Exception ("New name cannot be longer than old name currently."); hive.Position = this.AbsoluteOffset + 20; int k = this.NameLength - name.Length; hive.Write (name, 0, name.Length); for (int i = 0; i < k; i++) hive.WriteByte (0x00); } public void EditData (FileStream hive, byte[] data, int valueType) { if (data.Length > this.DataLength) throw new Exception ("New data cannot be longer than old data currently."); hive.Position = this.DataOffset; int k = this.DataLength - data.Length; hive.Write (data, 0, data.Length); for (int i = 0; i < k; i++) hive.WriteByte (0x00); } public long AbsoluteOffset { get; set; } public short NameLength { get; set; } public int DataLength { get; set; } public long DataOffset { get; set; } public int ValueType { get; set; } public string Name { get; set; } public byte[] Data { get; set; } public string String { get; set; } } }
mit
C#
1ce0947729f8f8fa0829cad2b8d18c305d97125b
Bump version
jkonecki/Streamstone,james-andrewsmith/Streamstone,attilah/Streamstone
Source/Streamstone.Version.cs
Source/Streamstone.Version.cs
using System; using System.Linq; using System.Reflection; [assembly: AssemblyVersion("0.4.9.0")] [assembly: AssemblyFileVersion("0.4.9.0")]
using System; using System.Linq; using System.Reflection; [assembly: AssemblyVersion("0.4.4.0")] [assembly: AssemblyFileVersion("0.4.4.0")]
apache-2.0
C#
5a251d070a8b7355bd469769239ae502a0b6a47e
Fix MediatR examples exception handlers
jbogard/MediatR
samples/MediatR.Examples/ExceptionHandler/ExceptionsHandlers.cs
samples/MediatR.Examples/ExceptionHandler/ExceptionsHandlers.cs
using MediatR.Pipeline; using System; using System.IO; using System.Threading; using System.Threading.Tasks; namespace MediatR.Examples.ExceptionHandler; public class CommonExceptionHandler : AsyncRequestExceptionHandler<PingResource, Pong> { private readonly TextWriter _writer; public CommonExceptionHandler(TextWriter writer) => _writer = writer; protected override async Task Handle(PingResource request, Exception exception, RequestExceptionHandlerState<Pong> state, CancellationToken cancellationToken) { // Exception type name required because it is checked later in messages await _writer.WriteLineAsync($"Handling {exception.GetType().FullName}"); // Exception handler type name required because it is checked later in messages await _writer.WriteLineAsync($"---- Exception Handler: '{typeof(CommonExceptionHandler).FullName}'").ConfigureAwait(false); state.SetHandled(new Pong()); } } public class ConnectionExceptionHandler : IRequestExceptionHandler<PingResource, Pong, ConnectionException> { private readonly TextWriter _writer; public ConnectionExceptionHandler(TextWriter writer) => _writer = writer; public async Task Handle(PingResource request, ConnectionException exception, RequestExceptionHandlerState<Pong> state, CancellationToken cancellationToken) { // Exception type name required because it is checked later in messages await _writer.WriteLineAsync($"Handling {exception.GetType().FullName}"); // Exception handler type name required because it is checked later in messages await _writer.WriteLineAsync($"---- Exception Handler: '{typeof(ConnectionExceptionHandler).FullName}'").ConfigureAwait(false); state.SetHandled(new Pong()); } } public class AccessDeniedExceptionHandler : IRequestExceptionHandler<PingResource, Pong, ForbiddenException> { private readonly TextWriter _writer; public AccessDeniedExceptionHandler(TextWriter writer) => _writer = writer; public async Task Handle(PingResource request, ForbiddenException exception, RequestExceptionHandlerState<Pong> state, CancellationToken cancellationToken) { // Exception type name required because it is checked later in messages await _writer.WriteLineAsync($"Handling {exception.GetType().FullName}"); // Exception handler type name required because it is checked later in messages await _writer.WriteLineAsync($"---- Exception Handler: '{typeof(AccessDeniedExceptionHandler).FullName}'").ConfigureAwait(false); state.SetHandled(new Pong()); } } public class ServerExceptionHandler : IRequestExceptionHandler<PingNewResource, Pong, ServerException> { private readonly TextWriter _writer; public ServerExceptionHandler(TextWriter writer) => _writer = writer; public virtual async Task Handle(PingNewResource request, ServerException exception, RequestExceptionHandlerState<Pong> state, CancellationToken cancellationToken) { // Exception type name required because it is checked later in messages await _writer.WriteLineAsync($"Handling {exception.GetType().FullName}"); // Exception handler type name required because it is checked later in messages await _writer.WriteLineAsync($"---- Exception Handler: '{typeof(ServerExceptionHandler).FullName}'").ConfigureAwait(false); state.SetHandled(new Pong()); } }
using MediatR.Pipeline; using System; using System.IO; using System.Threading; using System.Threading.Tasks; namespace MediatR.Examples.ExceptionHandler; public class CommonExceptionHandler : AsyncRequestExceptionHandler<PingResource, Pong> { private readonly TextWriter _writer; public CommonExceptionHandler(TextWriter writer) => _writer = writer; protected override async Task Handle(PingResource request, Exception exception, RequestExceptionHandlerState<Pong> state, CancellationToken cancellationToken) { await _writer.WriteLineAsync($"---- Exception Handler: '{typeof(CommonExceptionHandler).FullName}'").ConfigureAwait(false); state.SetHandled(new Pong()); } } public class ConnectionExceptionHandler : IRequestExceptionHandler<PingResource, Pong, ConnectionException> { private readonly TextWriter _writer; public ConnectionExceptionHandler(TextWriter writer) => _writer = writer; public async Task Handle(PingResource request, ConnectionException exception, RequestExceptionHandlerState<Pong> state, CancellationToken cancellationToken) { await _writer.WriteLineAsync($"---- Exception Handler: '{typeof(ConnectionExceptionHandler).FullName}'").ConfigureAwait(false); state.SetHandled(new Pong()); } } public class AccessDeniedExceptionHandler : IRequestExceptionHandler<PingResource, Pong, ForbiddenException> { private readonly TextWriter _writer; public AccessDeniedExceptionHandler(TextWriter writer) => _writer = writer; public async Task Handle(PingResource request, ForbiddenException exception, RequestExceptionHandlerState<Pong> state, CancellationToken cancellationToken) { await _writer.WriteLineAsync($"---- Exception Handler: '{typeof(AccessDeniedExceptionHandler).FullName}'").ConfigureAwait(false); state.SetHandled(new Pong()); } } public class ServerExceptionHandler : IRequestExceptionHandler<PingNewResource, Pong, ServerException> { private readonly TextWriter _writer; public ServerExceptionHandler(TextWriter writer) => _writer = writer; public virtual async Task Handle(PingNewResource request, ServerException exception, RequestExceptionHandlerState<Pong> state, CancellationToken cancellationToken) { await _writer.WriteLineAsync($"---- Exception Handler: '{typeof(ServerExceptionHandler).FullName}'").ConfigureAwait(false); state.SetHandled(new Pong()); } }
apache-2.0
C#
c8cdbf250387171d88d7f6cb0ebefa4519b3d72f
Patch from Dru Sellers, better error message on exception in getting values in Int32Type
RogerKratz/nhibernate-core,ngbrown/nhibernate-core,nkreipke/nhibernate-core,alobakov/nhibernate-core,nkreipke/nhibernate-core,livioc/nhibernate-core,gliljas/nhibernate-core,fredericDelaporte/nhibernate-core,hazzik/nhibernate-core,ManufacturingIntelligence/nhibernate-core,nhibernate/nhibernate-core,ManufacturingIntelligence/nhibernate-core,ManufacturingIntelligence/nhibernate-core,hazzik/nhibernate-core,lnu/nhibernate-core,nhibernate/nhibernate-core,RogerKratz/nhibernate-core,livioc/nhibernate-core,gliljas/nhibernate-core,ngbrown/nhibernate-core,nhibernate/nhibernate-core,livioc/nhibernate-core,alobakov/nhibernate-core,alobakov/nhibernate-core,gliljas/nhibernate-core,fredericDelaporte/nhibernate-core,RogerKratz/nhibernate-core,gliljas/nhibernate-core,lnu/nhibernate-core,nkreipke/nhibernate-core,lnu/nhibernate-core,ngbrown/nhibernate-core,RogerKratz/nhibernate-core,hazzik/nhibernate-core,nhibernate/nhibernate-core,fredericDelaporte/nhibernate-core,fredericDelaporte/nhibernate-core,hazzik/nhibernate-core
src/NHibernate/Type/Int32Type.cs
src/NHibernate/Type/Int32Type.cs
using System; using System.Collections; using System.Data; using NHibernate.Engine; using NHibernate.SqlTypes; namespace NHibernate.Type { /// <summary> /// Maps a <see cref="System.Int32"/> Property /// to a <see cref="DbType.Int32"/> column. /// </summary> [Serializable] public class Int32Type : ValueTypeType, IDiscriminatorType, IVersionType { /// <summary></summary> internal Int32Type() : base(SqlTypeFactory.Int32) { } /// <summary> /// /// </summary> /// <param name="rs"></param> /// <param name="index"></param> /// <returns></returns> public override object Get(IDataReader rs, int index) { try { return Convert.ToInt32(rs[index]); } catch(Exception ex) { throw new FormatException(string.Format("Input string '{0}' was not in the correct format.", rs[index]), ex); } } /// <summary> /// /// </summary> /// <param name="rs"></param> /// <param name="name"></param> /// <returns></returns> public override object Get(IDataReader rs, string name) { try { return Convert.ToInt32(rs[name]); } catch(Exception ex) { throw new FormatException(string.Format("Input string '{0}' was not in the correct format.", rs[name]), ex); } } /// <summary></summary> public override System.Type ReturnedClass { get { return typeof(Int32); } } /// <summary> /// /// </summary> /// <param name="cmd"></param> /// <param name="value"></param> /// <param name="index"></param> public override void Set(IDbCommand cmd, object value, int index) { IDataParameter parm = cmd.Parameters[index] as IDataParameter; parm.Value = value; } /// <summary></summary> public override string Name { get { return "Int32"; } } /// <summary> /// /// </summary> /// <param name="value"></param> /// <returns></returns> public override string ObjectToSQLString(object value) { return value.ToString(); } /// <summary> /// /// </summary> /// <param name="xml"></param> /// <returns></returns> public object StringToObject(string xml) { return FromString(xml); } public override object FromStringValue(string xml) { return int.Parse(xml); } #region IVersionType Members public virtual object Next(object current, ISessionImplementor session) { return ((int) current) + 1; } public virtual object Seed(ISessionImplementor session) { return 1; } public IComparer Comparator { get { return Comparer.DefaultInvariant; } } #endregion } }
using System; using System.Collections; using System.Data; using NHibernate.Engine; using NHibernate.SqlTypes; namespace NHibernate.Type { /// <summary> /// Maps a <see cref="System.Int32"/> Property /// to a <see cref="DbType.Int32"/> column. /// </summary> [Serializable] public class Int32Type : ValueTypeType, IDiscriminatorType, IVersionType { /// <summary></summary> internal Int32Type() : base(SqlTypeFactory.Int32) { } /// <summary> /// /// </summary> /// <param name="rs"></param> /// <param name="index"></param> /// <returns></returns> public override object Get(IDataReader rs, int index) { return Convert.ToInt32(rs[index]); } /// <summary> /// /// </summary> /// <param name="rs"></param> /// <param name="name"></param> /// <returns></returns> public override object Get(IDataReader rs, string name) { return Convert.ToInt32(rs[name]); } /// <summary></summary> public override System.Type ReturnedClass { get { return typeof(Int32); } } /// <summary> /// /// </summary> /// <param name="cmd"></param> /// <param name="value"></param> /// <param name="index"></param> public override void Set(IDbCommand cmd, object value, int index) { IDataParameter parm = cmd.Parameters[index] as IDataParameter; parm.Value = value; } /// <summary></summary> public override string Name { get { return "Int32"; } } /// <summary> /// /// </summary> /// <param name="value"></param> /// <returns></returns> public override string ObjectToSQLString(object value) { return value.ToString(); } /// <summary> /// /// </summary> /// <param name="xml"></param> /// <returns></returns> public object StringToObject(string xml) { return FromString(xml); } public override object FromStringValue(string xml) { return int.Parse(xml); } #region IVersionType Members public virtual object Next(object current, ISessionImplementor session) { return ((int) current) + 1; } public virtual object Seed(ISessionImplementor session) { return 1; } public IComparer Comparator { get { return Comparer.DefaultInvariant; } } #endregion } }
lgpl-2.1
C#
1318f0a472072c0a47a6ea7895cc6398543bb575
Include suggestions in GitHub output
laedit/vika
src/NVika/BuildServers/GitHub.cs
src/NVika/BuildServers/GitHub.cs
using System; using System.ComponentModel.Composition; using System.Text; using NVika.Abstractions; using NVika.Parsers; namespace NVika.BuildServers { internal sealed class GitHub : BuildServerBase { private readonly IEnvironment _environment; [ImportingConstructor] internal GitHub(IEnvironment environment) { _environment = environment; } public override string Name => nameof(GitHub); public override bool CanApplyToCurrentContext() => !string.IsNullOrEmpty(_environment.GetEnvironmentVariable("GITHUB_ACTIONS")); public override void WriteMessage(Issue issue) { var outputString = new StringBuilder(); switch (issue.Severity) { case IssueSeverity.Error: outputString.Append("::error "); break; case IssueSeverity.Warning: outputString.Append("::warning "); break; case IssueSeverity.Suggestion: outputString.Append("::notice "); break; } var details = issue.Message; if (issue.FilePath != null) { var absolutePath = issue.FilePath.Replace('\\', '/'); var relativePath = issue.Project != null ? issue.FilePath.Replace($"{issue.Project.Replace('\\', '/')}/", string.Empty) : absolutePath; outputString.Append($"file={absolutePath},"); details = $"{issue.Message} in {relativePath} on line {issue.Line}"; } if (issue.Offset != null) outputString.Append($"col={issue.Offset.Start},"); outputString.Append($"line={issue.Line}::{details}"); Console.WriteLine(outputString.ToString()); } } }
using System; using System.ComponentModel.Composition; using System.Text; using NVika.Abstractions; using NVika.Parsers; namespace NVika.BuildServers { internal sealed class GitHub : BuildServerBase { private readonly IEnvironment _environment; [ImportingConstructor] internal GitHub(IEnvironment environment) { _environment = environment; } public override string Name => nameof(GitHub); public override bool CanApplyToCurrentContext() => !string.IsNullOrEmpty(_environment.GetEnvironmentVariable("GITHUB_ACTIONS")); public override void WriteMessage(Issue issue) { var outputString = new StringBuilder(); switch (issue.Severity) { case IssueSeverity.Error: outputString.Append("::error "); break; case IssueSeverity.Warning: outputString.Append("::warning"); break; } var details = issue.Message; if (issue.FilePath != null) { var absolutePath = issue.FilePath.Replace('\\', '/'); var relativePath = issue.Project != null ? issue.FilePath.Replace($"{issue.Project.Replace('\\', '/')}/", string.Empty) : absolutePath; outputString.Append($"file={absolutePath},"); details = $"{issue.Message} in {relativePath} on line {issue.Line}"; } if (issue.Offset != null) outputString.Append($"col={issue.Offset.Start},"); outputString.Append($"line={issue.Line}::{details}"); Console.WriteLine(outputString.ToString()); } } }
apache-2.0
C#
61078e5a95682b4d5442664efcdd1c82b6f18202
revert last commit. oops
bordoley/RxApp
RxApp.Android/Interfaces.cs
RxApp.Android/Interfaces.cs
using ReactiveUI; using System; using System.ComponentModel; namespace RxApp { public interface IRxApplication : IService, IAndroidApplication { INavigationStack NavigationStack { get; } void OnActivityCreated(IRxActivity activity); } public interface IRxActivity : IActivity, IViewFor, INotifyPropertyChanged { } public interface IRxActivity<TViewModel> : IRxActivity, IViewFor<TViewModel> where TViewModel: class { } }
using ReactiveUI; using System; using System.ComponentModel; namespace RxApp { public interface IRxApplication : IService, IAndroidApplication { INavigationStack NavigationStack { get; } void OnActivityCreated(IRxActivity activity); } public interface IRxActivity : IActivity, IViewFor, INotifyPropertyChanged { } public interface IRxActivity<TViewModel> : IRxActivity, IViewFor<TViewModel>, INotifyPropertyChanged where TViewModel: class { } }
apache-2.0
C#
a290437286e1c55e34efea34bc5b0327271c71a1
Fix skin changed events triggering after disposal
smoogipoo/osu,smoogipooo/osu,EVAST9919/osu,smoogipoo/osu,ppy/osu,UselessToucan/osu,peppy/osu,ZLima12/osu,EVAST9919/osu,smoogipoo/osu,ppy/osu,UselessToucan/osu,2yangk23/osu,peppy/osu-new,ZLima12/osu,peppy/osu,UselessToucan/osu,peppy/osu,NeoAdonis/osu,johnneijzen/osu,johnneijzen/osu,ppy/osu,NeoAdonis/osu,2yangk23/osu,NeoAdonis/osu
osu.Game/Skinning/SkinReloadableDrawable.cs
osu.Game/Skinning/SkinReloadableDrawable.cs
// Copyright (c) ppy Pty Ltd <[email protected]>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using System; using osu.Framework.Allocation; using osu.Framework.Graphics.Containers; namespace osu.Game.Skinning { /// <summary> /// A drawable which has a callback when the skin changes. /// </summary> public abstract class SkinReloadableDrawable : CompositeDrawable { private readonly Func<ISkinSource, bool> allowFallback; private ISkinSource skin; /// <summary> /// Whether fallback to default skin should be allowed if the custom skin is missing this resource. /// </summary> private bool allowDefaultFallback => allowFallback == null || allowFallback.Invoke(skin); /// <summary> /// Create a new <see cref="SkinReloadableDrawable"/> /// </summary> /// <param name="allowFallback">A conditional to decide whether to allow fallback to the default implementation if a skinned element is not present.</param> protected SkinReloadableDrawable(Func<ISkinSource, bool> allowFallback = null) { this.allowFallback = allowFallback; } [BackgroundDependencyLoader] private void load(ISkinSource source) { skin = source; skin.SourceChanged += onChange; } private void onChange() => // schedule required to avoid calls after disposed. Schedule(() => SkinChanged(skin, allowDefaultFallback)); protected override void LoadAsyncComplete() { base.LoadAsyncComplete(); SkinChanged(skin, allowDefaultFallback); } /// <summary> /// Called when a change is made to the skin. /// </summary> /// <param name="skin">The new skin.</param> /// <param name="allowFallback">Whether fallback to default skin should be allowed if the custom skin is missing this resource.</param> protected virtual void SkinChanged(ISkinSource skin, bool allowFallback) { } protected override void Dispose(bool isDisposing) { base.Dispose(isDisposing); if (skin != null) skin.SourceChanged -= onChange; } } }
// Copyright (c) ppy Pty Ltd <[email protected]>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using System; using osu.Framework.Allocation; using osu.Framework.Graphics.Containers; namespace osu.Game.Skinning { /// <summary> /// A drawable which has a callback when the skin changes. /// </summary> public abstract class SkinReloadableDrawable : CompositeDrawable { private readonly Func<ISkinSource, bool> allowFallback; private ISkinSource skin; /// <summary> /// Whether fallback to default skin should be allowed if the custom skin is missing this resource. /// </summary> private bool allowDefaultFallback => allowFallback == null || allowFallback.Invoke(skin); /// <summary> /// Create a new <see cref="SkinReloadableDrawable"/> /// </summary> /// <param name="allowFallback">A conditional to decide whether to allow fallback to the default implementation if a skinned element is not present.</param> protected SkinReloadableDrawable(Func<ISkinSource, bool> allowFallback = null) { this.allowFallback = allowFallback; } [BackgroundDependencyLoader] private void load(ISkinSource source) { skin = source; skin.SourceChanged += onChange; } private void onChange() => SkinChanged(skin, allowDefaultFallback); protected override void LoadAsyncComplete() { base.LoadAsyncComplete(); onChange(); } /// <summary> /// Called when a change is made to the skin. /// </summary> /// <param name="skin">The new skin.</param> /// <param name="allowFallback">Whether fallback to default skin should be allowed if the custom skin is missing this resource.</param> protected virtual void SkinChanged(ISkinSource skin, bool allowFallback) { } protected override void Dispose(bool isDisposing) { base.Dispose(isDisposing); if (skin != null) skin.SourceChanged -= onChange; } } }
mit
C#
ea3cf0587c40ba130188f5856c9824fdafada028
Revert "replace old parameter names with new key parameter names"
tropo/tropo-webapi-csharp,tropo/tropo-webapi-csharp
TropoOutboundSMS/Program.cs
TropoOutboundSMS/Program.cs
using System; using System.Collections.Generic; using System.Web; using System.Xml; using TropoCSharp.Structs; using TropoCSharp.Tropo; namespace OutboundTest { /// <summary> /// A simple console appplication used to launch a Tropo Session and send an outbound SMS. /// Note - use in conjnction withe the OutboundSMS.aspx example in the TropoSamples project. /// For further information, see http://blog.tropo.com/2011/04/14/sending-outbound-sms-with-c/ /// </summary> class Program { static void Main(string[] args) { // The voice and messaging tokens provisioned when your Tropo application is set up. string voiceToken = "your-voice-token-here"; string messagingToken = "your-messaging-token-here"; // A collection to hold the parameters we want to send to the Tropo Session API. IDictionary<string, string> parameters = new Dictionary<String, String>(); // Enter a phone number to send a call or SMS message to here. parameters.Add("sendToNumber", "15551112222"); // Enter a phone number to use as the caller ID. parameters.Add("sendFromNumber", "15551113333"); // Select the channel you want to use via the Channel struct. string channel = Channel.Text; parameters.Add("channel", channel); string network = Network.SMS; parameters.Add("network", network); // Message is sent as a query string parameter, make sure it is properly encoded. parameters.Add("msg", HttpUtility.UrlEncode("This is a test message from C#.")); // Instantiate a new instance of the Tropo object. Tropo tropo = new Tropo(); // Create an XML doc to hold the response from the Tropo Session API. XmlDocument doc = new XmlDocument(); // Set the token to use. string token = channel == Channel.Text ? messagingToken : voiceToken; // Load the XML document with the return value of the CreateSession() method call. doc.Load(tropo.CreateSession(token, parameters)); // Display the results in the console. Console.WriteLine("Result: " + doc.SelectSingleNode("session/success").InnerText.ToUpper()); Console.WriteLine("Token: " + doc.SelectSingleNode("session/token").InnerText); Console.Read(); } } }
using System; using System.Collections.Generic; using System.Web; using System.Xml; using TropoCSharp.Structs; using TropoCSharp.Tropo; namespace OutboundTest { /// <summary> /// A simple console appplication used to launch a Tropo Session and send an outbound SMS. /// Note - use in conjnction withe the OutboundSMS.aspx example in the TropoSamples project. /// For further information, see http://blog.tropo.com/2011/04/14/sending-outbound-sms-with-c/ /// </summary> class Program { static void Main(string[] args) { // The voice and messaging tokens provisioned when your Tropo application is set up. string voiceToken = "your-voice-token-here"; string messagingToken = "your-messaging-token-here"; // A collection to hold the parameters we want to send to the Tropo Session API. IDictionary<string, string> parameters = new Dictionary<String, String>(); // Enter a phone number to send a call or SMS message to here. parameters.Add("numberToDial", "15551112222"); // Enter a phone number to use as the caller ID. parameters.Add("sendFromNumber", "15551113333"); // Select the channel you want to use via the Channel struct. string channel = Channel.Text; parameters.Add("channel", channel); string network = Network.SMS; parameters.Add("network", network); // Message is sent as a query string parameter, make sure it is properly encoded. parameters.Add("textMessageBody", HttpUtility.UrlEncode("This is a test message from C#.")); // Instantiate a new instance of the Tropo object. Tropo tropo = new Tropo(); // Create an XML doc to hold the response from the Tropo Session API. XmlDocument doc = new XmlDocument(); // Set the token to use. string token = channel == Channel.Text ? messagingToken : voiceToken; // Load the XML document with the return value of the CreateSession() method call. doc.Load(tropo.CreateSession(token, parameters)); // Display the results in the console. Console.WriteLine("Result: " + doc.SelectSingleNode("session/success").InnerText.ToUpper()); Console.WriteLine("Token: " + doc.SelectSingleNode("session/token").InnerText); Console.Read(); } } }
mit
C#
2fb3c3bcf6182a0de653d7747862ea7dd467f5fd
Fix x-container-experiment-seed failure in .NET Framework branches
ashmind/SharpLab,ashmind/SharpLab,ashmind/SharpLab,ashmind/SharpLab,ashmind/SharpLab,ashmind/SharpLab
source/NetFramework/Server/MirrorSharp/SetOptionsFromClient.cs
source/NetFramework/Server/MirrorSharp/SetOptionsFromClient.cs
using System.Collections.Generic; using System.Linq; using JetBrains.Annotations; using MirrorSharp.Advanced; using SharpLab.Server.Common; namespace SharpLab.Server.MirrorSharp { [UsedImplicitly(ImplicitUseKindFlags.InstantiatedNoFixedConstructorSignature)] public class SetOptionsFromClient : ISetOptionsFromClientExtension { private const string Optimize = "x-optimize"; private const string Target = "x-target"; private const string ContainerExperimentSeed = "x-container-experiment-seed"; private readonly IDictionary<string, ILanguageAdapter> _languages; public SetOptionsFromClient(IReadOnlyList<ILanguageAdapter> languages) { _languages = languages.ToDictionary(l => l.LanguageName); } public bool TrySetOption(IWorkSession session, string name, string value) { switch (name) { case Optimize: _languages[session.LanguageName].SetOptimize(session, value); return true; case Target: session.SetTargetName(value); _languages[session.LanguageName].SetOptionsForTarget(session, value); return true; case ContainerExperimentSeed: // not supported in .NET Framework return true; default: return false; } } } }
using System.Collections.Generic; using System.Linq; using JetBrains.Annotations; using MirrorSharp.Advanced; using SharpLab.Server.Common; namespace SharpLab.Server.MirrorSharp { [UsedImplicitly(ImplicitUseKindFlags.InstantiatedNoFixedConstructorSignature)] public class SetOptionsFromClient : ISetOptionsFromClientExtension { private const string Optimize = "x-optimize"; private const string Target = "x-target"; private readonly IDictionary<string, ILanguageAdapter> _languages; public SetOptionsFromClient(IReadOnlyList<ILanguageAdapter> languages) { _languages = languages.ToDictionary(l => l.LanguageName); } public bool TrySetOption(IWorkSession session, string name, string value) { switch (name) { case Optimize: _languages[session.LanguageName].SetOptimize(session, value); return true; case Target: session.SetTargetName(value); _languages[session.LanguageName].SetOptionsForTarget(session, value); return true; default: return false; } } } }
bsd-2-clause
C#
850ac51233dba57771e4b797457a09e2b0066547
Debug scenario disable bugsnag
File-New-Project/EarTrumpet
EarTrumpet/Services/ErrorReportingService.cs
EarTrumpet/Services/ErrorReportingService.cs
using Bugsnag; using Bugsnag.Clients; using EarTrumpet.Extensions; using System; using System.Diagnostics; using Windows.ApplicationModel; namespace EarTrumpet.Services { class ErrorReportingService { internal static void Initialize() { #if VSDEBUG return; #else try { WPFClient.Config.AppVersion = App.Current.HasIdentity() ? Package.Current.Id.Version.ToVersionString() : "DevInternal"; WPFClient.Start(); WPFClient.Config.BeforeNotify(OnBeforeNotify); } catch(Exception ex) { Trace.WriteLine(ex); } #endif } private static bool OnBeforeNotify(Event error) { error.Metadata.AddToTab("Device", "machineName", "<redacted>"); error.Metadata.AddToTab("Device", "hostname", "<redacted>"); return true; } } }
using Bugsnag; using Bugsnag.Clients; using EarTrumpet.Extensions; using System; using System.Diagnostics; using System.IO; using Windows.ApplicationModel; namespace EarTrumpet.Services { class ErrorReportingService { internal static void Initialize() { WPFClient.Config.AppVersion = App.Current.HasIdentity() ? Package.Current.Id.Version.ToVersionString() : "DevInternal"; WPFClient.Start(); WPFClient.Config.BeforeNotify(OnBeforeNotify); } private static bool OnBeforeNotify(Event error) { error.Metadata.AddToTab("Device", "machineName", "<redacted>"); error.Metadata.AddToTab("Device", "hostname", "<redacted>"); return true; } } }
mit
C#
1437540efbbc8dac9b14223e1f1bd8e7332a54f7
Remove 'Positions Vacant' sticky note
croquet-australia/croquet-australia.com.au,croquet-australia/website-application,croquet-australia/croquet-australia.com.au,croquet-australia/croquet-australia.com.au,croquet-australia/croquet-australia-website,croquet-australia/website-application,croquet-australia/croquet-australia-website,croquet-australia/croquet-australia-website,croquet-australia/website-application,croquet-australia/croquet-australia-website,croquet-australia/croquet-australia.com.au,croquet-australia/website-application
source/CroquetAustralia.Website/Layouts/Shared/Sidebar.cshtml
source/CroquetAustralia.Website/Layouts/Shared/Sidebar.cshtml
<div class="sticky-notes"> <div class="sticky-note"> <i class="pin"></i> <div class="content green"> <h1> GC Handicapping System </h1> <p> New <a href="/disciplines/golf-croquet/resources">GC Handicapping System</a> comes into effect 3 April, 2017 </p> </div> </div> </div>
<div class="sticky-notes"> <div class="sticky-note"> <i class="pin"></i> <div class="content green"> <h1> GC Handicapping System </h1> <p> New <a href="/disciplines/golf-croquet/resources">GC Handicapping System</a> comes into effect 3 April, 2017 </p> </div> </div> <div class="sticky-note"> <i class="pin"></i> <div class="content green"> <h1> Positions Vacant </h1> <p> ACA would like your help! <a href="/position-vacant">Positions Vacant</a> </p> </div> </div> </div>
mit
C#
71a234db9b8d01a78cf0da1f7cd758de3f18b84d
Update MarginMultiplierConverter to support Thickness input
jkoritzinsky/Avalonia,AvaloniaUI/Avalonia,SuperJMN/Avalonia,wieslawsoltes/Perspex,AvaloniaUI/Avalonia,SuperJMN/Avalonia,AvaloniaUI/Avalonia,SuperJMN/Avalonia,jkoritzinsky/Avalonia,Perspex/Perspex,Perspex/Perspex,jkoritzinsky/Avalonia,jkoritzinsky/Perspex,SuperJMN/Avalonia,SuperJMN/Avalonia,jkoritzinsky/Avalonia,wieslawsoltes/Perspex,AvaloniaUI/Avalonia,wieslawsoltes/Perspex,jkoritzinsky/Avalonia,AvaloniaUI/Avalonia,wieslawsoltes/Perspex,AvaloniaUI/Avalonia,wieslawsoltes/Perspex,jkoritzinsky/Avalonia,AvaloniaUI/Avalonia,grokys/Perspex,grokys/Perspex,akrisiun/Perspex,wieslawsoltes/Perspex,SuperJMN/Avalonia,wieslawsoltes/Perspex,jkoritzinsky/Avalonia,SuperJMN/Avalonia
src/Avalonia.Controls/Converters/MarginMultiplierConverter.cs
src/Avalonia.Controls/Converters/MarginMultiplierConverter.cs
using System; using System.Globalization; using Avalonia.Data.Converters; namespace Avalonia.Controls.Converters { public class MarginMultiplierConverter : IValueConverter { public double Indent { get; set; } public bool Left { get; set; } = false; public bool Top { get; set; } = false; public bool Right { get; set; } = false; public bool Bottom { get; set; } = false; public object Convert(object value, Type targetType, object parameter, CultureInfo culture) { if (value is int scalarDepth) { return new Thickness( Left ? Indent * scalarDepth : 0, Top ? Indent * scalarDepth : 0, Right ? Indent * scalarDepth : 0, Bottom ? Indent * scalarDepth : 0); } else if (value is Thickness thinknessDepth) { return new Thickness( Left ? Indent * thinknessDepth.Left : 0, Top ? Indent * thinknessDepth.Top : 0, Right ? Indent * thinknessDepth.Right : 0, Bottom ? Indent * thinknessDepth.Bottom : 0); } return new Thickness(0); } public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) { throw new System.NotImplementedException(); } } }
using System; using System.Globalization; using Avalonia.Data.Converters; namespace Avalonia.Controls.Converters { public class MarginMultiplierConverter : IValueConverter { public double Indent { get; set; } public bool Left { get; set; } = false; public bool Top { get; set; } = false; public bool Right { get; set; } = false; public bool Bottom { get; set; } = false; public object Convert(object value, Type targetType, object parameter, CultureInfo culture) { if (!(value is int depth)) return new Thickness(0); return new Thickness(Left ? Indent * depth : 0, Top ? Indent * depth : 0, Right ? Indent * depth : 0, Bottom ? Indent * depth : 0); } public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) { throw new System.NotImplementedException(); } } }
mit
C#
f6f978e19cfa2870b986647ecc2aba02efdef26a
Clear "file" setting so Source doesn't start with the last-used card image.
nealterrell/NetrunnerOBS
Prototype/NetrunnerCardImageSourceFactory.cs
Prototype/NetrunnerCardImageSourceFactory.cs
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using CLROBS; using System.Windows; namespace NetrunnerOBS { /// <summary> /// Factory registered with the OBS API so OBS can create our source object /// when needed. /// </summary> public class NetrunnerCardImageSourceFactory : AbstractImageSourceFactory { // Kind of hacky: a singleton CardWindow connects to all sources. static CardWindow mConfiguration; static List<NetrunnerCardImageSource> mSources = new List<NetrunnerCardImageSource>(); public NetrunnerCardImageSourceFactory() { ClassName = "CardImageSourceClass"; DisplayName = "Netrunner Card"; } public override ImageSource Create(XElement data) { // Clear the file data, so the stream always starts with a blank card. data.SetString("file", ""); var source = new NetrunnerCardImageSource(data); mSources.Add(source); return source; } public override bool ShowConfiguration(XElement data) { try { if (mConfiguration == null) { mConfiguration = new CardWindow(data); mConfiguration.CardChanged += mConfiguration_CardChanged; } mConfiguration.Show(); } catch (Exception e) { MessageBox.Show(e.ToString()); } return true; } void mConfiguration_CardChanged(object sender, CardChangedEventArgs e) { foreach (var source in mSources) source.UpdateSettings(); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using CLROBS; using System.Windows; namespace NetrunnerOBS { /// <summary> /// Factory registered with the OBS API so OBS can create our source object /// when needed. /// </summary> public class NetrunnerCardImageSourceFactory : AbstractImageSourceFactory { // Kind of hacky: a singleton CardWindow connects to all sources. static CardWindow mConfiguration; static List<NetrunnerCardImageSource> mSources = new List<NetrunnerCardImageSource>(); public NetrunnerCardImageSourceFactory() { ClassName = "CardImageSourceClass"; DisplayName = "Netrunner Card"; } public override ImageSource Create(XElement data) { var source = new NetrunnerCardImageSource(data); mSources.Add(source); return source; } public override bool ShowConfiguration(XElement data) { try { if (mConfiguration == null) { mConfiguration = new CardWindow(data); mConfiguration.CardChanged += mConfiguration_CardChanged; } mConfiguration.Show(); } catch (Exception e) { MessageBox.Show(e.ToString()); } return true; } void mConfiguration_CardChanged(object sender, CardChangedEventArgs e) { foreach (var source in mSources) source.UpdateSettings(); } } }
mit
C#
86f9e8533d364b1042711c9c91f73bfa7b8566b8
Fix showing digits - show '1' instead of 'D1'
terrajobst/git-istage,terrajobst/git-istage
src/git-istage/ConsoleCommand.cs
src/git-istage/ConsoleCommand.cs
using System; namespace GitIStage { internal sealed class ConsoleCommand { private readonly Action _handler; private readonly ConsoleKey _key; public readonly string Description; private readonly ConsoleModifiers _modifiers; public ConsoleCommand(Action handler, ConsoleKey key, string description) { _handler = handler; _key = key; Description = description; _modifiers = 0; } public ConsoleCommand(Action handler, ConsoleKey key, ConsoleModifiers modifiers, string description) { _handler = handler; _key = key; _modifiers = modifiers; Description = description; } public void Execute() { _handler(); } public bool MatchesKey(ConsoleKeyInfo keyInfo) { return _key == keyInfo.Key && _modifiers == keyInfo.Modifiers; } public string GetCommandShortcut() { string key = _key.ToString().Replace("Arrow", ""); if (key.StartsWith("D") && key.Length == 2) key = key.Replace("D", ""); if (_modifiers != 0) return $"{_modifiers.ToString().Replace("Control", "Ctrl")} + {key.ToString()}"; else return key.ToString(); } } }
using System; namespace GitIStage { internal sealed class ConsoleCommand { private readonly Action _handler; private readonly ConsoleKey _key; public readonly string Description; private readonly ConsoleModifiers _modifiers; public ConsoleCommand(Action handler, ConsoleKey key, string description) { _handler = handler; _key = key; Description = description; _modifiers = 0; } public ConsoleCommand(Action handler, ConsoleKey key, ConsoleModifiers modifiers, string description) { _handler = handler; _key = key; _modifiers = modifiers; Description = description; } public void Execute() { _handler(); } public bool MatchesKey(ConsoleKeyInfo keyInfo) { return _key == keyInfo.Key && _modifiers == keyInfo.Modifiers; } public string GetCommandShortcut() { string key = _key.ToString().Replace("Arrow", ""); if (_modifiers != 0) { return $"{_modifiers.ToString().Replace("Control", "Ctrl")} + {key.ToString()}"; } else return key.ToString(); } } }
mit
C#
bdae9bcb0b085d30cd318d9723d429e11cf42434
Create Pool Tests work. removed obsolete tests
srottem/indy-sdk,srottem/indy-sdk,Artemkaaas/indy-sdk,Artemkaaas/indy-sdk,Artemkaaas/indy-sdk,srottem/indy-sdk,peacekeeper/indy-sdk,peacekeeper/indy-sdk,peacekeeper/indy-sdk,Artemkaaas/indy-sdk,anastasia-tarasova/indy-sdk,srottem/indy-sdk,anastasia-tarasova/indy-sdk,srottem/indy-sdk,anastasia-tarasova/indy-sdk,Artemkaaas/indy-sdk,peacekeeper/indy-sdk,peacekeeper/indy-sdk,Artemkaaas/indy-sdk,srottem/indy-sdk,Artemkaaas/indy-sdk,peacekeeper/indy-sdk,Artemkaaas/indy-sdk,srottem/indy-sdk,anastasia-tarasova/indy-sdk,srottem/indy-sdk,srottem/indy-sdk,srottem/indy-sdk,anastasia-tarasova/indy-sdk,Artemkaaas/indy-sdk,peacekeeper/indy-sdk,Artemkaaas/indy-sdk,srottem/indy-sdk,anastasia-tarasova/indy-sdk,anastasia-tarasova/indy-sdk,srottem/indy-sdk,peacekeeper/indy-sdk,Artemkaaas/indy-sdk,peacekeeper/indy-sdk,peacekeeper/indy-sdk,anastasia-tarasova/indy-sdk,Artemkaaas/indy-sdk,Artemkaaas/indy-sdk,peacekeeper/indy-sdk,anastasia-tarasova/indy-sdk,anastasia-tarasova/indy-sdk,peacekeeper/indy-sdk,anastasia-tarasova/indy-sdk,peacekeeper/indy-sdk,anastasia-tarasova/indy-sdk,anastasia-tarasova/indy-sdk,srottem/indy-sdk
wrappers/dotnet/indy-sdk-dotnet-test/PoolTests/CreatePoolTest.cs
wrappers/dotnet/indy-sdk-dotnet-test/PoolTests/CreatePoolTest.cs
using Hyperledger.Indy.PoolApi; using Microsoft.VisualStudio.TestTools.UnitTesting; using System.IO; using System.Threading.Tasks; namespace Hyperledger.Indy.Test.PoolTests { [TestClass] public class CreatePoolTest : IndyIntegrationTestBase { [TestMethod] public async Task TestCreatePoolWorksForNullConfig() { string poolConfigName = "testCreatePoolWorks"; var file = File.Create(string.Format("{0}.txn", poolConfigName)); PoolUtils.WriteTransactions(file, 1); await Pool.CreatePoolLedgerConfigAsync(poolConfigName, null); } [TestMethod] public async Task TestCreatePoolWorksForConfigJSON() { var genesisTxnFile = PoolUtils.CreateGenesisTxnFile("genesis.txn"); var path = Path.GetFullPath(genesisTxnFile.Name).Replace('\\', '/'); var configJson = string.Format("{{\"genesis_txn\":\"{0}\"}}", path); await Pool.CreatePoolLedgerConfigAsync("testCreatePoolWorks", configJson); } [TestMethod] public async Task TestCreatePoolWorksForTwice() { var genesisTxnFile = PoolUtils.CreateGenesisTxnFile("genesis.txn"); var path = Path.GetFullPath(genesisTxnFile.Name).Replace('\\', '/'); var configJson = string.Format("{{\"genesis_txn\":\"{0}\"}}", path); await Pool.CreatePoolLedgerConfigAsync("pool1", configJson); var ex = await Assert.ThrowsExceptionAsync<PoolLedgerConfigExistsException>(() => Pool.CreatePoolLedgerConfigAsync("pool1", configJson) );; } } }
using Hyperledger.Indy.PoolApi; using Microsoft.VisualStudio.TestTools.UnitTesting; using System.IO; using System.Threading.Tasks; namespace Hyperledger.Indy.Test.PoolTests { [TestClass] public class CreatePoolTest : IndyIntegrationTestBase { [TestMethod] public async Task TestCreatePoolWorksForNullConfig() { var file = File.Create("testCreatePoolWorks.txn"); PoolUtils.WriteTransactions(file, 1); await Pool.CreatePoolLedgerConfigAsync("testCreatePoolWorks", null); } [TestMethod] public async Task TestCreatePoolWorksForConfigJSON() { var genesisTxnFile = PoolUtils.CreateGenesisTxnFile("genesis.txn"); var path = Path.GetFullPath(genesisTxnFile.Name).Replace('\\', '/'); var configJson = string.Format("{{\"genesis_txn\":\"{0}\"}}", path); await Pool.CreatePoolLedgerConfigAsync("testCreatePoolWorks", configJson); } [TestMethod] public async Task TestCreatePoolWorksForTwice() { var genesisTxnFile = PoolUtils.CreateGenesisTxnFile("genesis.txn"); var path = Path.GetFullPath(genesisTxnFile.Name).Replace('\\', '/'); var configJson = string.Format("{{\"genesis_txn\":\"{0}\"}}", path); await Pool.CreatePoolLedgerConfigAsync("pool1", configJson); var ex = await Assert.ThrowsExceptionAsync<PoolLedgerConfigExistsException>(() => Pool.CreatePoolLedgerConfigAsync("pool1", configJson) );; } } }
apache-2.0
C#
8fd89a4d460ae15d0dab2c40d4a92245e8b01769
Remove unused import
ulrichb/ImplicitNullability,ulrichb/ImplicitNullability,ulrichb/ImplicitNullability
Src/ImplicitNullability.Plugin/ZoneMarker.cs
Src/ImplicitNullability.Plugin/ZoneMarker.cs
using JetBrains.Application.BuildScript.Application.Zones; using JetBrains.ReSharper.Feature.Services.Daemon; using JetBrains.ReSharper.Psi; using JetBrains.ReSharper.Psi.CSharp; namespace ImplicitNullability.Plugin { [ZoneDefinition] [ZoneDefinitionConfigurableFeature(AssemblyConsts.Title, AssemblyConsts.Description, IsInProductSection: false)] public interface IImplicitNullabilityZone : IPsiLanguageZone, IRequire<ILanguageCSharpZone>, IRequire<DaemonZone> { } [ZoneMarker] public class ZoneMarker : IRequire<IImplicitNullabilityZone> { } }
using JetBrains.Application.BuildScript.Application.Zones; using JetBrains.ReSharper.Feature.Services.Daemon; using JetBrains.ReSharper.Psi; using JetBrains.ReSharper.Psi.Asp; using JetBrains.ReSharper.Psi.CSharp; namespace ImplicitNullability.Plugin { [ZoneDefinition] [ZoneDefinitionConfigurableFeature(AssemblyConsts.Title, AssemblyConsts.Description, IsInProductSection: false)] public interface IImplicitNullabilityZone : IPsiLanguageZone, IRequire<ILanguageCSharpZone>, IRequire<DaemonZone> { } [ZoneMarker] public class ZoneMarker : IRequire<IImplicitNullabilityZone> { } }
mit
C#
0abec4390b30fdda97dc496594f9b1f9c9b20e17
Fix casing of interop directories (dotnet/corert#6982)
shimingsg/corefx,ViktorHofer/corefx,ptoonen/corefx,shimingsg/corefx,ptoonen/corefx,wtgodbe/corefx,ViktorHofer/corefx,ViktorHofer/corefx,ericstj/corefx,BrennanConroy/corefx,BrennanConroy/corefx,ericstj/corefx,ptoonen/corefx,ViktorHofer/corefx,wtgodbe/corefx,shimingsg/corefx,ptoonen/corefx,ericstj/corefx,shimingsg/corefx,ericstj/corefx,ericstj/corefx,ptoonen/corefx,ptoonen/corefx,ViktorHofer/corefx,ViktorHofer/corefx,ptoonen/corefx,shimingsg/corefx,shimingsg/corefx,ViktorHofer/corefx,wtgodbe/corefx,wtgodbe/corefx,BrennanConroy/corefx,wtgodbe/corefx,ericstj/corefx,wtgodbe/corefx,ericstj/corefx,shimingsg/corefx,wtgodbe/corefx
src/Common/src/CoreLib/Interop/Windows/Kernel32/Interop.GetCurrentProcess_IntPtr.cs
src/Common/src/CoreLib/Interop/Windows/Kernel32/Interop.GetCurrentProcess_IntPtr.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.Runtime.InteropServices; internal partial class Interop { internal partial class Kernel32 { [DllImport(Libraries.Kernel32)] internal static extern IntPtr GetCurrentProcess(); } }
// 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.Runtime.InteropServices; internal partial class Interop { internal partial class Kernel32 { [DllImport(Libraries.Kernel32, SetLastError = true)] internal static extern IntPtr GetCurrentProcess(); } }
mit
C#
6b78045ff1b35b0d406d43494feda064d97a43ed
fix codefactor empty line complaint
peppy/osu,peppy/osu,smoogipooo/osu,peppy/osu-new,ppy/osu,ppy/osu,NeoAdonis/osu,UselessToucan/osu,peppy/osu,smoogipoo/osu,smoogipoo/osu,UselessToucan/osu,NeoAdonis/osu,UselessToucan/osu,NeoAdonis/osu,ppy/osu,smoogipoo/osu
osu.Game/Rulesets/UI/Scrolling/ScrollingPlayfield.cs
osu.Game/Rulesets/UI/Scrolling/ScrollingPlayfield.cs
// Copyright (c) ppy Pty Ltd <[email protected]>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using osu.Framework.Allocation; using osu.Framework.Bindables; using osu.Game.Rulesets.Objects.Drawables; using osu.Game.Skinning; using osuTK; namespace osu.Game.Rulesets.UI.Scrolling { /// <summary> /// A type of <see cref="Playfield"/> specialized towards scrolling <see cref="DrawableHitObject"/>s. /// </summary> public abstract class ScrollingPlayfield : Playfield { protected readonly IBindable<ScrollingDirection> Direction = new Bindable<ScrollingDirection>(); [Resolved] protected IScrollingInfo ScrollingInfo { get; private set; } protected ISkinSource CurrentSkin { get; private set; } [BackgroundDependencyLoader] private void load(ISkinSource skin) { Direction.BindTo(ScrollingInfo.Direction); CurrentSkin = skin; skin.SourceChanged += OnSkinChanged; OnSkinChanged(); } protected virtual void OnSkinChanged() { } /// <summary> /// Given a position in screen space, return the time within this column. /// </summary> public virtual double TimeAtScreenSpacePosition(Vector2 screenSpacePosition) => ((ScrollingHitObjectContainer)HitObjectContainer).TimeAtScreenSpacePosition(screenSpacePosition); /// <summary> /// Given a time, return the screen space position within this column. /// </summary> public virtual Vector2 ScreenSpacePositionAtTime(double time) => ((ScrollingHitObjectContainer)HitObjectContainer).ScreenSpacePositionAtTime(time); protected sealed override HitObjectContainer CreateHitObjectContainer() => new ScrollingHitObjectContainer(); } }
// Copyright (c) ppy Pty Ltd <[email protected]>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using osu.Framework.Allocation; using osu.Framework.Bindables; using osu.Game.Rulesets.Objects.Drawables; using osu.Game.Skinning; using osuTK; namespace osu.Game.Rulesets.UI.Scrolling { /// <summary> /// A type of <see cref="Playfield"/> specialized towards scrolling <see cref="DrawableHitObject"/>s. /// </summary> public abstract class ScrollingPlayfield : Playfield { protected readonly IBindable<ScrollingDirection> Direction = new Bindable<ScrollingDirection>(); [Resolved] protected IScrollingInfo ScrollingInfo { get; private set; } protected ISkinSource CurrentSkin { get; private set; } [BackgroundDependencyLoader] private void load(ISkinSource skin) { Direction.BindTo(ScrollingInfo.Direction); CurrentSkin = skin; skin.SourceChanged += OnSkinChanged; OnSkinChanged(); } protected virtual void OnSkinChanged() { } /// <summary> /// Given a position in screen space, return the time within this column. /// </summary> public virtual double TimeAtScreenSpacePosition(Vector2 screenSpacePosition) => ((ScrollingHitObjectContainer)HitObjectContainer).TimeAtScreenSpacePosition(screenSpacePosition); /// <summary> /// Given a time, return the screen space position within this column. /// </summary> public virtual Vector2 ScreenSpacePositionAtTime(double time) => ((ScrollingHitObjectContainer)HitObjectContainer).ScreenSpacePositionAtTime(time); protected sealed override HitObjectContainer CreateHitObjectContainer() => new ScrollingHitObjectContainer(); } }
mit
C#
b5c40bca9624a1b3baf7eb9b299a61d34c48680b
Add comment
60071jimmy/UartOscilloscope,60071jimmy/UartOscilloscope
QueueDataGraphic/QueueDataGraphic/CSharpFiles/QueueDataGraphic.cs
QueueDataGraphic/QueueDataGraphic/CSharpFiles/QueueDataGraphic.cs
/******************************************************************** * Develop by Jimmy Hu * * This program is licensed under the Apache License 2.0. * * QueueDataGraphic.cs * * 本檔案用於佇列資料繪圖功能 * ******************************************************************** */ using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace QueueDataGraphic.CSharpFiles { // namespace start, 進入命名空間 class QueueDataGraphic // QueueDataGraphic class, QueueDataGraphic類別 { // QueueDataGraphic class start, 進入QueueDataGraphic類別 List<DataQueue> DataQueueList; // DataQueueList object, DataQueueList物件 /// <summary> /// QueueDataGraphic constructor, QueueDataGraphic建構子 /// </summary> public QueueDataGraphic() // QueueDataGraphic constructor, QueueDataGraphic建構子 { // QueueDataGraphic constructor start, 進入QueueDataGraphic建構子 } // QueueDataGraphic constructor end, 結束QueueDataGraphic建構子 } // QueueDataGraphic class end, 結束QueueDataGraphic類別 } // namespace end, 結束命名空間
/******************************************************************** * Develop by Jimmy Hu * * This program is licensed under the Apache License 2.0. * * QueueDataGraphic.cs * * 本檔案用於佇列資料繪圖功能 * ******************************************************************** */ using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace QueueDataGraphic.CSharpFiles { // namespace start, 進入命名空間 class QueueDataGraphic // QueueDataGraphic class, QueueDataGraphic類別 { // QueueDataGraphic class start, 進入QueueDataGraphic類別 List<DataQueue> DataQueueList; // DataQueueList object, DataQueueList物件 /// <summary> /// QueueDataGraphic constructor, QueueDataGraphic建構子 /// </summary> public QueueDataGraphic() { } } // QueueDataGraphic class end, 結束QueueDataGraphic類別 } // namespace end, 結束命名空間
apache-2.0
C#
0e4ebfe8357437c88ce5b744b09d5b1c87974f8c
Change so that the constructor is public for the AccountRepository so it can be registered
SkillsFundingAgency/das-employerapprenticeshipsservice,SkillsFundingAgency/das-employerapprenticeshipsservice,SkillsFundingAgency/das-employerapprenticeshipsservice
src/SFA.DAS.EmployerApprenticeshipsService.Infrastructure/Data/AccountRepository.cs
src/SFA.DAS.EmployerApprenticeshipsService.Infrastructure/Data/AccountRepository.cs
using System; using System.Data; using System.Threading.Tasks; using Dapper; using SFA.DAS.EmployerApprenticeshipsService.Domain.Configuration; using SFA.DAS.EmployerApprenticeshipsService.Domain.Data; namespace SFA.DAS.EmployerApprenticeshipsService.Infrastructure.Data { public class AccountRepository : BaseRepository, IAccountRepository { private readonly EmployerApprenticeshipsServiceConfiguration _configuration; public override string ConnectionString { get; set; } public AccountRepository(EmployerApprenticeshipsServiceConfiguration configuration) { _configuration = configuration; } public async Task<int> CreateAccount(string userRef, string employerNumber, string employerName, string employerRef) { ConnectionString = _configuration.Employer.DatabaseConnectionString; return await WithConnection(async c => { var parameters = new DynamicParameters(); parameters.Add("@userRef", new Guid(userRef), DbType.Guid); parameters.Add("@employerNumber", employerNumber, DbType.String); parameters.Add("@employerName", employerName, DbType.String); parameters.Add("@employerRef", employerRef, DbType.String); parameters.Add("@accountId", null, DbType.Int32, ParameterDirection.Output, 4); await c.ExecuteAsync( sql: "[dbo].[CreateAccount]", param: parameters, commandType: CommandType.StoredProcedure); return parameters.Get<int>("@accountId"); }); } } }
using System; using System.Data; using System.Threading.Tasks; using Dapper; using SFA.DAS.EmployerApprenticeshipsService.Domain.Configuration; using SFA.DAS.EmployerApprenticeshipsService.Domain.Data; namespace SFA.DAS.EmployerApprenticeshipsService.Infrastructure.Data { public class AccountRepository : BaseRepository, IAccountRepository { private readonly EmployerApprenticeshipsServiceConfiguration _configuration; public override string ConnectionString { get; set; } protected AccountRepository(EmployerApprenticeshipsServiceConfiguration configuration) { _configuration = configuration; } public async Task<int> CreateAccount(string userRef, string employerNumber, string employerName, string employerRef) { ConnectionString = _configuration.Employer.DatabaseConnectionString; return await WithConnection(async c => { var parameters = new DynamicParameters(); parameters.Add("@userRef", new Guid(userRef), DbType.Guid); parameters.Add("@employerNumber", employerNumber, DbType.String); parameters.Add("@employerName", employerName, DbType.String); parameters.Add("@employerRef", employerRef, DbType.String); parameters.Add("@accountId", null, DbType.Int32, ParameterDirection.Output, 4); await c.ExecuteAsync( sql: "[dbo].[CreateAccount]", param: parameters, commandType: CommandType.StoredProcedure); return parameters.Get<int>("@accountId"); }); } } }
mit
C#
000c6782ee02038ae743974769024a83f147d13b
comment tests.
tonyredondo/TWCore2,tonyredondo/TWCore2,tonyredondo/TWCore2,tonyredondo/TWCore2
tools/TWCore.Diagnostics.Api/DiagnosticMessagingServiceAsync.cs
tools/TWCore.Diagnostics.Api/DiagnosticMessagingServiceAsync.cs
/* Copyright 2015-2018 Daniel Adrian Redondo Suarez Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ using System; using System.Threading.Tasks; using TWCore.Diagnostics.Api.MessageHandlers.RavenDb; using TWCore.Diagnostics.Api.Models; using TWCore.Serialization; using TWCore.Services; // ReSharper disable UnusedMember.Global namespace TWCore.Diagnostics.Api { public class DiagnosticMessagingServiceAsync : BusinessMessagesServiceAsync<DiagnosticMessagingBusinessAsync> { protected override void OnInit(string[] args) { EnableMessagesTrace = false; SerializerManager.SupressFileExtensionWarning = true; base.OnInit(args); //var data = DbHandlers.Instance.Query.GetEnvironmentsAndApps().WaitAndResults(); //var data2 = DbHandlers.Instance.Query.GetEnvironmentsAndApps().WaitAndResults(); //var data3 = DbHandlers.Instance.Query.GetEnvironmentsAndApps().WaitAndResults(); //var status = ((RavenDbQueryHandler) DbHandlers.Instance.Query).GetCurrentStatus("DEV", null, null); // Task.Delay(6000).ContinueWith(async _ => // { // while (true) // { // Core.Trace.Write("Hola Mundo"); // await Task.Delay(6000).ConfigureAwait(false); // } // }); /* var logs = DbHandlers.Instance.Query.GetLogsAsync("Processing message", null, DateTime.MinValue, DateTime.Now).WaitAndResults(); var logs2 = DbHandlers.Instance.Query.GetLogsAsync("Processing message", null, DateTime.MinValue, DateTime.Now).WaitAndResults(); var logs3 = DbHandlers.Instance.Query.GetLogsAsync("Processing message", null, DateTime.MinValue, DateTime.Now).WaitAndResults(); Task.Delay(2000).ContinueWith(async _ => { while (true) { Core.Log.ErrorGroup(new Exception("Test de Error"), Guid.NewGuid().ToString(), "Reporte de error."); await Task.Delay(2000).ConfigureAwait(false); } }); */ } } }
/* Copyright 2015-2018 Daniel Adrian Redondo Suarez Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ using System; using System.Threading.Tasks; using TWCore.Diagnostics.Api.MessageHandlers.RavenDb; using TWCore.Diagnostics.Api.Models; using TWCore.Serialization; using TWCore.Services; // ReSharper disable UnusedMember.Global namespace TWCore.Diagnostics.Api { public class DiagnosticMessagingServiceAsync : BusinessMessagesServiceAsync<DiagnosticMessagingBusinessAsync> { protected override void OnInit(string[] args) { EnableMessagesTrace = false; SerializerManager.SupressFileExtensionWarning = true; base.OnInit(args); var data = DbHandlers.Instance.Query.GetEnvironmentsAndApps().WaitAndResults(); var data2 = DbHandlers.Instance.Query.GetEnvironmentsAndApps().WaitAndResults(); var data3 = DbHandlers.Instance.Query.GetEnvironmentsAndApps().WaitAndResults(); var status = ((RavenDbQueryHandler) DbHandlers.Instance.Query).GetCurrentStatus("DEV", null, null); Task.Delay(6000).ContinueWith(async _ => { while (true) { Core.Trace.Write("Hola Mundo"); await Task.Delay(6000).ConfigureAwait(false); } }); /* var logs = DbHandlers.Instance.Query.GetLogsAsync("Processing message", null, DateTime.MinValue, DateTime.Now).WaitAndResults(); var logs2 = DbHandlers.Instance.Query.GetLogsAsync("Processing message", null, DateTime.MinValue, DateTime.Now).WaitAndResults(); var logs3 = DbHandlers.Instance.Query.GetLogsAsync("Processing message", null, DateTime.MinValue, DateTime.Now).WaitAndResults(); Task.Delay(2000).ContinueWith(async _ => { while (true) { Core.Log.ErrorGroup(new Exception("Test de Error"), Guid.NewGuid().ToString(), "Reporte de error."); await Task.Delay(2000).ConfigureAwait(false); } }); */ } } }
apache-2.0
C#
437890cb178cde33c72c8439a8f17106db411aae
Fix build
holance/helix-toolkit,chrkon/helix-toolkit,JeremyAnsel/helix-toolkit,helix-toolkit/helix-toolkit
Source/HelixToolkit.SharpDX.Shared/Model/ContextSharedResource.cs
Source/HelixToolkit.SharpDX.Shared/Model/ContextSharedResource.cs
/* The MIT License (MIT) Copyright (c) 2018 Helix Toolkit contributors */ using System; using SharpDX.Direct3D11; #if NETFX_CORE namespace HelixToolkit.UWP.Model #else namespace HelixToolkit.Wpf.SharpDX.Model #endif { using Utilities; public sealed class ContextSharedResource : IDisposable { public ShaderResourceViewProxy ShadowView { set; get; } public ShaderResourceViewProxy EnvironementMap { set;get; } public ShaderResourceViewProxy SSAOMap { set;get; } public int EnvironmentMapMipLevels { set;get; } #region IDisposable Support private bool disposedValue = false; // To detect redundant calls private void Dispose(bool disposing) { if (!disposedValue) { if (disposing) { ShadowView = null; EnvironementMap = null; SSAOMap = null; // TODO: dispose managed state (managed objects). } // TODO: free unmanaged resources (unmanaged objects) and override a finalizer below. // TODO: set large fields to null. disposedValue = true; } } // TODO: override a finalizer only if Dispose(bool disposing) above has code to free unmanaged resources. // ~ContextSharedResource() { // // Do not change this code. Put cleanup code in Dispose(bool disposing) above. // Dispose(false); // } // This code added to correctly implement the disposable pattern. public void Dispose() { // Do not change this code. Put cleanup code in Dispose(bool disposing) above. Dispose(true); // TODO: uncomment the following line if the finalizer is overridden above. // GC.SuppressFinalize(this); } #endregion } }
/* The MIT License (MIT) Copyright (c) 2018 Helix Toolkit contributors */ using System; using SharpDX.Direct3D11; #if NETFX_CORE namespace HelixToolkit.UWP.Model #else namespace HelixToolkit.Wpf.SharpDX.Model #endif { using Utilities; public sealed class ContextSharedResource : IDisposable { public ShaderResourceViewProxy ShadowView { set; get; } public ShaderResourceViewProxy EnvironementMap { set;get; } public ShaderResourceViewProxy SSAOMap { set;get; } public int EnvironmentMapMipLevels { set;get; } #region IDisposable Support private bool disposedValue = false; // To detect redundant calls protected virtual void Dispose(bool disposing) { if (!disposedValue) { if (disposing) { ShadowView = null; // TODO: dispose managed state (managed objects). } // TODO: free unmanaged resources (unmanaged objects) and override a finalizer below. // TODO: set large fields to null. disposedValue = true; } } // TODO: override a finalizer only if Dispose(bool disposing) above has code to free unmanaged resources. // ~ContextSharedResource() { // // Do not change this code. Put cleanup code in Dispose(bool disposing) above. // Dispose(false); // } // This code added to correctly implement the disposable pattern. public void Dispose() { // Do not change this code. Put cleanup code in Dispose(bool disposing) above. Dispose(true); // TODO: uncomment the following line if the finalizer is overridden above. // GC.SuppressFinalize(this); } #endregion } }
mit
C#
1f1a939759c86dfdda8de16feea7323411292788
Update to variable name
ChilliConnect/Samples,ChilliConnect/Samples,ChilliConnect/Samples
UnitySamples/TicTacToeRealtime/Assets/Scripts/PhotonController.cs
UnitySamples/TicTacToeRealtime/Assets/Scripts/PhotonController.cs
using System; using System.Collections; using System.Collections.Generic; using System.IO; using UnityEngine; using ChilliConnect; public class PhotonController : MonoBehaviour { private string m_photonApplicationId = "PHOTON_APPLICATION_ID"; private ChilliConnectSdk m_chilliConnect; /// Make instance of ChilliConnectId. /// /// @param chilliConnect /// Instance of the chilliConnect SDK /// public void Initialise(ChilliConnectSdk chilliConnect) { m_chilliConnect = chilliConnect; } /// Gets a new access token for use with connecting to Photon Multiplayer /// Token lasts for 5 minutes /// public void LoadPhotonInstance() { UnityEngine.Debug.Log ("Photon Multiplayer - Starting Photon Access Token Generation"); m_chilliConnect.Multiplayer.GeneratePhotonAccessToken(m_photonApplicationId, (request, response) => OnPhotonAccessTokenRetrieved(response), (request, createError) => Debug.LogError(createError.ErrorDescription)); } /// Handler for successful PhotonAccessToken retrieval, will connect to Photon Services /// private void OnPhotonAccessTokenRetrieved(GeneratePhotonAccessTokenResponse photonAccessTokenResponse) { UnityEngine.Debug.Log ("Photon Multiplayer - Retrieved Initial Access Token: " + photonAccessTokenResponse.PhotonAccessToken); PhotonNetwork.AuthValues = new AuthenticationValues(); PhotonNetwork.AuthValues.AuthType = CustomAuthenticationType.Custom; PhotonNetwork.AuthValues.AddAuthParameter("PhotonAccessToken", photonAccessTokenResponse.PhotonAccessToken); PhotonNetwork.ConnectUsingSettings("1.0"); } void OnConnectedToMaster () { UnityEngine.Debug.Log ("Photon Multiplayer - Connected: " + PhotonNetwork.connected); PhotonNetwork.JoinRandomRoom(); } void OnPhotonRandomJoinFailed(object[] codeAndMsg) { Debug.Log("Photon Multiplayer - No Rooms Available, Creating New Room"); PhotonNetwork.CreateRoom(null, new RoomOptions() { MaxPlayers = 2, PlayerTtl = 20000 }, null); } }
using System; using System.Collections; using System.Collections.Generic; using System.IO; using UnityEngine; using ChilliConnect; public class PhotonController : MonoBehaviour { private string m_photonApplicationId = "PHOTON_APPLICATION_ID"; private ChilliConnectSdk m_chilliConnect; /// Make instance of ChilliConnectId. /// /// @param chilliConnect /// Instance of the chilliConnect SDK /// public void Initialise(ChilliConnectSdk chilliConnect) { m_chilliConnect = chilliConnect; } /// Gets a new access token for use with connecting to Photon Multiplayer /// Token lasts for 5 minutes /// public void LoadPhotonInstance() { UnityEngine.Debug.Log ("Photon Multiplayer - Starting Photon Access Token Generation"); m_chilliConnect.Multiplayer.GeneratePhotonAccessToken(m_photonApplicationId, (request, response) => OnPhotonAccessTokenRetrieved(response), (request, createError) => Debug.LogError(createError.ErrorDescription)); } /// Handler for successful PhotonAccessToken retrieval, will connect to Photon Services /// private void OnPhotonAccessTokenRetrieved(GeneratePhotonAccessTokenResponse photonAccessToken) { UnityEngine.Debug.Log ("Photon Multiplayer - Retrieved Initial Access Token: " + photonAccessToken.PhotonAccessToken); PhotonNetwork.AuthValues = new AuthenticationValues(); PhotonNetwork.AuthValues.AuthType = CustomAuthenticationType.Custom; PhotonNetwork.AuthValues.AddAuthParameter("PhotonAccessToken", photonAccessToken.PhotonAccessToken); PhotonNetwork.ConnectUsingSettings("1.0"); } void OnConnectedToMaster () { UnityEngine.Debug.Log ("Photon Multiplayer - Connected: " + PhotonNetwork.connected); PhotonNetwork.JoinRandomRoom(); } void OnPhotonRandomJoinFailed(object[] codeAndMsg) { Debug.Log("Photon Multiplayer - No Rooms Available, Creating New Room"); PhotonNetwork.CreateRoom(null, new RoomOptions() { MaxPlayers = 2, PlayerTtl = 20000 }, null); } }
mit
C#
d3d2eda105d88042793af5f3d7a1b3a5b71605e4
Add CustomAttributeCollection Find()/FindAll() methods
picrap/dnlib,yck1509/dnlib,ilkerhalil/dnlib,jorik041/dnlib,modulexcite/dnlib,kiootic/dnlib,0xd4d/dnlib,Arthur2e5/dnlib,ZixiangBoy/dnlib
src/DotNet/CustomAttributeCollection.cs
src/DotNet/CustomAttributeCollection.cs
using System.Collections.Generic; namespace dot10.DotNet { /// <summary> /// Stores <see cref="CustomAttribute"/>s /// </summary> public class CustomAttributeCollection : LazyList<CustomAttribute> { /// <summary> /// Default constructor /// </summary> internal CustomAttributeCollection() { } /// <summary> /// Constructor /// </summary> /// <param name="length">Initial length of the list</param> /// <param name="context">Context passed to <paramref name="readOriginalValue"/></param> /// <param name="readOriginalValue">Delegate instance that returns original values</param> internal CustomAttributeCollection(int length, object context, MFunc<object, uint, CustomAttribute> readOriginalValue) : base(length, context, readOriginalValue) { } /// <summary> /// Finds a custom attribute /// </summary> /// <param name="fullName">Full name of custom attribute type</param> /// <returns>A <see cref="CustomAttribute"/> or <c>null</c> if it wasn't found</returns> public CustomAttribute Find(string fullName) { foreach (var ca in this) { if (ca != null && ca.TypeFullName == fullName) return ca; } return null; } /// <summary> /// Finds all custom attributes of a certain type /// </summary> /// <param name="fullName">Full name of custom attribute type</param> /// <returns>All <see cref="CustomAttribute"/>s of the requested type</returns> public IEnumerable<CustomAttribute> FindAll(string fullName) { foreach (var ca in this) { if (ca != null && ca.TypeFullName == fullName) yield return ca; } } } }
using System.Collections.Generic; namespace dot10.DotNet { /// <summary> /// Stores <see cref="CustomAttribute"/>s /// </summary> public class CustomAttributeCollection : LazyList<CustomAttribute> { /// <summary> /// Default constructor /// </summary> internal CustomAttributeCollection() { } /// <summary> /// Constructor /// </summary> /// <param name="length">Initial length of the list</param> /// <param name="context">Context passed to <paramref name="readOriginalValue"/></param> /// <param name="readOriginalValue">Delegate instance that returns original values</param> internal CustomAttributeCollection(int length, object context, MFunc<object, uint, CustomAttribute> readOriginalValue) : base(length, context, readOriginalValue) { } } }
mit
C#
9900971df3916bd2db71ab1a0ffb5cf0640bbcb4
Fix NH-1838 (Guid support in MySql dialect)
nkreipke/nhibernate-core,alobakov/nhibernate-core,ngbrown/nhibernate-core,ngbrown/nhibernate-core,gliljas/nhibernate-core,RogerKratz/nhibernate-core,gliljas/nhibernate-core,hazzik/nhibernate-core,fredericDelaporte/nhibernate-core,ngbrown/nhibernate-core,nhibernate/nhibernate-core,nkreipke/nhibernate-core,lnu/nhibernate-core,hazzik/nhibernate-core,livioc/nhibernate-core,hazzik/nhibernate-core,nhibernate/nhibernate-core,alobakov/nhibernate-core,RogerKratz/nhibernate-core,ManufacturingIntelligence/nhibernate-core,ManufacturingIntelligence/nhibernate-core,nhibernate/nhibernate-core,alobakov/nhibernate-core,fredericDelaporte/nhibernate-core,nkreipke/nhibernate-core,hazzik/nhibernate-core,lnu/nhibernate-core,livioc/nhibernate-core,livioc/nhibernate-core,gliljas/nhibernate-core,fredericDelaporte/nhibernate-core,nhibernate/nhibernate-core,fredericDelaporte/nhibernate-core,gliljas/nhibernate-core,RogerKratz/nhibernate-core,ManufacturingIntelligence/nhibernate-core,lnu/nhibernate-core,RogerKratz/nhibernate-core
src/NHibernate/Dialect/MySQL5Dialect.cs
src/NHibernate/Dialect/MySQL5Dialect.cs
using System.Data; using NHibernate.SqlCommand; namespace NHibernate.Dialect { public class MySQL5Dialect : MySQLDialect { public MySQL5Dialect() { RegisterColumnType(DbType.Decimal, "DECIMAL(19,5)"); RegisterColumnType(DbType.Decimal, 19, "DECIMAL($p, $s)"); RegisterColumnType(DbType.Guid, "BINARY(16)"); } //Reference 5.x //Numeric: //http://dev.mysql.com/doc/refman/5.0/en/numeric-type-overview.html //Date and time: //http://dev.mysql.com/doc/refman/5.0/en/date-and-time-type-overview.html //String: //http://dev.mysql.com/doc/refman/5.0/en/string-type-overview.html //default: //http://dev.mysql.com/doc/refman/5.0/en/data-type-defaults.html public override bool SupportsVariableLimit { get { //note: why false? return false; } } public override bool SupportsSubSelects { get { //subquery in mysql? yes! From 4.1! //http://dev.mysql.com/doc/refman/5.1/en/subqueries.html return true; } } public override SqlString GetLimitString(SqlString querySqlString, int offset, int limit) { var pagingBuilder = new SqlStringBuilder(); pagingBuilder.Add(querySqlString); pagingBuilder.Add(" limit "); if (offset > 0) { pagingBuilder.Add(offset.ToString()); pagingBuilder.Add(", "); } pagingBuilder.Add(limit.ToString()); return pagingBuilder.ToSqlString(); } public override string SelectGUIDString { get { return "select uuid()"; } } public override SqlString AppendIdentitySelectToInsert (NHibernate.SqlCommand.SqlString insertString) { return insertString.Append(";" + IdentitySelectString); } public override bool SupportsInsertSelectIdentity { get { return true; } } } }
using System.Data; using NHibernate.SqlCommand; namespace NHibernate.Dialect { public class MySQL5Dialect : MySQLDialect { public MySQL5Dialect() { RegisterColumnType(DbType.Decimal, "DECIMAL(19,5)"); RegisterColumnType(DbType.Decimal, 19, "DECIMAL($p, $s)"); } //Reference 5.x //Numeric: //http://dev.mysql.com/doc/refman/5.0/en/numeric-type-overview.html //Date and time: //http://dev.mysql.com/doc/refman/5.0/en/date-and-time-type-overview.html //String: //http://dev.mysql.com/doc/refman/5.0/en/string-type-overview.html //default: //http://dev.mysql.com/doc/refman/5.0/en/data-type-defaults.html public override bool SupportsVariableLimit { get { //note: why false? return false; } } public override bool SupportsSubSelects { get { //subquery in mysql? yes! From 4.1! //http://dev.mysql.com/doc/refman/5.1/en/subqueries.html return true; } } public override SqlString GetLimitString(SqlString querySqlString, int offset, int limit) { var pagingBuilder = new SqlStringBuilder(); pagingBuilder.Add(querySqlString); pagingBuilder.Add(" limit "); if (offset > 0) { pagingBuilder.Add(offset.ToString()); pagingBuilder.Add(", "); } pagingBuilder.Add(limit.ToString()); return pagingBuilder.ToSqlString(); } public override string SelectGUIDString { get { return "select uuid()"; } } public override SqlString AppendIdentitySelectToInsert (NHibernate.SqlCommand.SqlString insertString) { return insertString.Append(";" + IdentitySelectString); } public override bool SupportsInsertSelectIdentity { get { return true; } } } }
lgpl-2.1
C#
4332d05963b4fc7fcf06a683ff6a9c5178a4e8c7
Handle other kinds of deserialization exceptions
auth0/auth0.net,auth0/auth0.net
src/Auth0.Core/ApiError.cs
src/Auth0.Core/ApiError.cs
using Auth0.Core.Serialization; using Newtonsoft.Json; using System; using System.Net.Http; using System.Threading.Tasks; namespace Auth0.Core { /// <summary> /// Error information captured from a failed API request. /// </summary> [JsonConverter(typeof(ApiErrorConverter))] public class ApiError { /// <summary> /// Description of the failing HTTP Status Code. /// </summary> [JsonProperty("error")] public string Error { get; set; } /// <summary> /// Error code returned by the API. /// </summary> [JsonProperty("errorCode")] public string ErrorCode { get; set; } /// <summary> /// Description of the error. /// </summary> [JsonProperty("message")] public string Message { get; set; } /// <summary> /// Parse a <see cref="HttpResponseMessage"/> into an <see cref="ApiError"/> asynchronously. /// </summary> /// <param name="response"><see cref="HttpResponseMessage"/> to parse.</param> /// <returns><see cref="Task"/> representing the operation and associated <see cref="ApiError"/> on /// successful completion.</returns> public static async Task<ApiError> Parse(HttpResponseMessage response) { if (response == null || response.Content == null) return null; var content = await response.Content.ReadAsStringAsync().ConfigureAwait(false); if (String.IsNullOrEmpty(content)) return null; try { return JsonConvert.DeserializeObject<ApiError>(content); } catch (JsonException) { return new ApiError { Error = content, Message = content }; } } } }
using Auth0.Core.Serialization; using Newtonsoft.Json; using System; using System.Net.Http; using System.Threading.Tasks; namespace Auth0.Core { /// <summary> /// Error information captured from a failed API request. /// </summary> [JsonConverter(typeof(ApiErrorConverter))] public class ApiError { /// <summary> /// Description of the failing HTTP Status Code. /// </summary> [JsonProperty("error")] public string Error { get; set; } /// <summary> /// Error code returned by the API. /// </summary> [JsonProperty("errorCode")] public string ErrorCode { get; set; } /// <summary> /// Description of the error. /// </summary> [JsonProperty("message")] public string Message { get; set; } /// <summary> /// Parse a <see cref="HttpResponseMessage"/> into an <see cref="ApiError"/> asynchronously. /// </summary> /// <param name="response"><see cref="HttpResponseMessage"/> to parse.</param> /// <returns><see cref="Task"/> representing the operation and associated <see cref="ApiError"/> on /// successful completion.</returns> public static async Task<ApiError> Parse(HttpResponseMessage response) { if (response == null || response.Content == null) return null; var content = await response.Content.ReadAsStringAsync().ConfigureAwait(false); if (String.IsNullOrEmpty(content)) return null; try { return JsonConvert.DeserializeObject<ApiError>(content); } catch (JsonSerializationException) { return new ApiError { Error = content, Message = content }; } } } }
mit
C#
1b0c490c1e7d7b9c4edc0cd921f4bdb679f9d497
Add MergeWith method to the Entity to enable accumulating information
AlexGhiondea/SmugMug.NET
src/SmugMugShared/Descriptors/Entity.cs
src/SmugMugShared/Descriptors/Entity.cs
// Copyright (c) Alex Ghiondea. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System.Collections.Generic; using System.Linq; namespace SmugMug.Shared.Descriptors { public class Entity { public string Name { get; set; } public List<Property> Properties { get; set; } public List<Method> Methods { get; set; } public Entity() { Methods = new List<Method>(); Properties = new List<Property>(); } public void MergeWith(Entity other) { foreach (var meth in other.Methods) { if (Methods.FirstOrDefault(m => m.Uri == meth.Uri) == null) { Methods.Add(meth); } } foreach (var prop in other.Properties) { if (Properties.FirstOrDefault(p => p.Name == prop.Name) == null) { Properties.Add(prop); } } } } }
// Copyright (c) Alex Ghiondea. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System.Collections.Generic; namespace SmugMug.Shared.Descriptors { public class Entity { public string Name { get; set; } public List<Property> Properties { get; set; } public List<Method> Methods { get; set; } public Entity() { Methods = new List<Method>(); Properties = new List<Property>(); } } }
mit
C#
65c8ed5fb44d8e8af74ede61476710e772833204
add time utils.
ivanchanfy/FyUtils
FyUtils/TimeUtils.cs
FyUtils/TimeUtils.cs
using System; namespace FyUtils { public class TimeUtils { public static long CurrentTimestamp { get { return GetTimestampFromDateTime(DateTime.UtcNow); } } public static DateTime GetDateTimeFromTimestamp(long timestamp) { return new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc).AddSeconds(timestamp); } public static long GetTimestampFromDateTime(DateTime dateTime) { return Convert.ToInt64((dateTime - new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc)).TotalSeconds); } public static string GetStringFromTimestamp(long timestamp) { return GetStringFromDateTime(GetDateTimeFromTimestamp(timestamp)); } public static string GetStringFromTimestamp(long timestamp, string format) { return GetStringFromDateTime(GetDateTimeFromTimestamp(timestamp), format); } public static string GetStringFromDateTime(DateTime dateTime) { return GetStringFromDateTime(dateTime, "yyyy-MM-dd"); } public static string GetStringFromDateTime(DateTime dateTime, string format) { return dateTime.ToString(format); } public static bool IsToday(long timestamp) { return IsSameDay(CurrentTimestamp, timestamp); } public static bool IsToday(DateTime dateTime) { return IsSameDay(DateTime.UtcNow, dateTime); } public static bool IsSameDay(long timestamp1, long timestamp2) { DateTime dateTime1 = GetDateTimeFromTimestamp(timestamp1); DateTime dateTime2 = GetDateTimeFromTimestamp(timestamp2); return IsSameDay(dateTime1, dateTime2); } public static bool IsSameDay(DateTime dateTime1, DateTime dateTime2) { return (dateTime1.DayOfYear == dateTime2.DayOfYear && dateTime1.Year == dateTime2.Year); } public static bool IsLeapYear(long timestamp) { return IsLeapYear(GetDateTimeFromTimestamp(timestamp)); } public static bool IsLeapYear(DateTime dateTime) { return (dateTime.Year % 4 == 0 && dateTime.Year % 100 != 0) || dateTime.Year % 400 == 0; } } }
using System; namespace FyUtils { public class TimeUtils { } }
apache-2.0
C#
09dc6afd7a058bd0559576ea7e722119d499b1c0
Test coverage for projection of the results of queries using EF.Functions and date functions
agileobjects/AgileMapper
AgileMapper.UnitTests.Orms.EfCore2/WhenProjectingToFlatTypes.cs
AgileMapper.UnitTests.Orms.EfCore2/WhenProjectingToFlatTypes.cs
namespace AgileObjects.AgileMapper.UnitTests.Orms.EfCore2 { using System; using System.Linq; using System.Threading.Tasks; using Infrastructure; using Microsoft.EntityFrameworkCore; using TestClasses; using Xunit; public class WhenProjectingToFlatTypes : WhenProjectingToFlatTypes<EfCore2TestDbContext> { public WhenProjectingToFlatTypes(InMemoryEfCore2TestContext context) : base(context) { } [Fact] public Task ShouldProjectUsingEfFunctionsLike() { return RunTest(async context => { var person1 = new Person { Name = "Person One" }; var person2 = new Person { Name = "Person Two" }; var person3 = new Person { Name = "Person Three" }; await context.Persons.AddRangeAsync(person1, person2, person3); await context.SaveChangesAsync(); var personVms = await context .Persons .Where(pvm => EF.Functions.Like(pvm.Name, "%Tw%")) .Project().To<PersonViewModel>() .OrderBy(pvm => pvm.Id) .ToListAsync(); var personVm = personVms.ShouldHaveSingleItem(); personVm.Id.ShouldBe(person2.PersonId); personVm.Name.ShouldBe("Person Two"); personVm.AddressId.ShouldBeNull(); }); } [Fact] public Task ShouldProjectUsingDatePart() { return RunTest(async context => { var dateTime1 = new PublicDateTime { Value = DateTime.Today.AddMonths(-1) }; var dateTime2 = new PublicDateTime { Value = DateTime.Today }; var dateTime3 = new PublicDateTime { Value = DateTime.Today.AddMonths(+1) }; await context.DateTimeItems.AddRangeAsync(dateTime1, dateTime2, dateTime3); await context.SaveChangesAsync(); var dateTimeDtos = await context .DateTimeItems .Where(d => d.Value.Month == DateTime.Today.Month) .Project().To<PublicDateTimeDto>() .OrderBy(pvm => pvm.Id) .ToListAsync(); var dateTimeDto = dateTimeDtos.ShouldHaveSingleItem(); dateTimeDto.Id.ShouldBe(dateTime2.Id); dateTimeDto.Value.ShouldBe(DateTime.Today); }); } [Fact] public Task ShouldProjectUsingDateDiff() { return RunTest(async context => { var dateTime1 = new PublicDateTime { Value = DateTime.Today.AddMonths(-1) }; var dateTime2 = new PublicDateTime { Value = DateTime.Today }; var dateTime3 = new PublicDateTime { Value = DateTime.Today.AddMonths(+1) }; await context.DateTimeItems.AddRangeAsync(dateTime1, dateTime2, dateTime3); await context.SaveChangesAsync(); var dateTimeDtos = await context .DateTimeItems .Where(d => (d.Value - DateTime.Today).TotalDays > 15) .Project().To<PublicDateTimeDto>() .OrderBy(pvm => pvm.Id) .ToListAsync(); var dateTimeDto = dateTimeDtos.ShouldHaveSingleItem(); dateTimeDto.Id.ShouldBe(dateTime3.Id); dateTimeDto.Value.ShouldBe(dateTime3.Value); }); } } }
namespace AgileObjects.AgileMapper.UnitTests.Orms.EfCore2 { using Infrastructure; public class WhenProjectingToFlatTypes : WhenProjectingToFlatTypes<EfCore2TestDbContext> { public WhenProjectingToFlatTypes(InMemoryEfCore2TestContext context) : base(context) { } } }
mit
C#
ceefea50ff4d0e407aa5f5088cfe905e05c4dc8f
add new 'Ignore Clipping Planes' option to alembic camera component
unity3d-jp/AlembicImporter,unity3d-jp/AlembicImporter,unity3d-jp/AlembicImporter
AlembicImporter/Assets/AlembicImporter/Scripts/AlembicCamera.cs
AlembicImporter/Assets/AlembicImporter/Scripts/AlembicCamera.cs
using System; using System.Collections; using System.Collections.Generic; using System.Runtime.InteropServices; using System.Runtime.CompilerServices; using System.Reflection; using UnityEngine; #if UNITY_EDITOR using UnityEditor; #endif [ExecuteInEditMode] public class AlembicCamera : AlembicElement { public AbcAPI.aiAspectRatioModeOverride m_aspectRatioMode = AbcAPI.aiAspectRatioModeOverride.InheritStreamSetting; public bool m_ignoreClippingPlanes = false; Camera m_camera; AbcAPI.aiCameraData m_abcData; bool m_lastIgnoreClippingPlanes = false; public override void AbcSetup(AlembicStream abcStream, AbcAPI.aiObject abcObj, AbcAPI.aiSchema abcSchema) { base.AbcSetup(abcStream, abcObj, abcSchema); m_camera = GetOrAddComponent<Camera>(); } public override void AbcGetConfig(ref AbcAPI.aiConfig config) { if (m_aspectRatioMode != AbcAPI.aiAspectRatioModeOverride.InheritStreamSetting) { config.aspectRatio = AbcAPI.GetAspectRatio((AbcAPI.aiAspectRatioMode) m_aspectRatioMode); } } public override void AbcSampleUpdated(AbcAPI.aiSample sample, bool topologyChanged) { AbcAPI.aiCameraGetData(sample, ref m_abcData); AbcDirty(); } public override void AbcUpdate() { if (AbcIsDirty() || m_lastIgnoreClippingPlanes != m_ignoreClippingPlanes) { m_trans.forward = -m_trans.parent.forward; m_camera.fieldOfView = m_abcData.fieldOfView; if (!m_ignoreClippingPlanes) { m_camera.nearClipPlane = m_abcData.nearClippingPlane; m_camera.farClipPlane = m_abcData.farClippingPlane; } // no use for focusDistance and focalLength yet (could be usefull for DoF component) AbcClean(); m_lastIgnoreClippingPlanes = m_ignoreClippingPlanes; } } }
using System; using System.Collections; using System.Collections.Generic; using System.Runtime.InteropServices; using System.Runtime.CompilerServices; using System.Reflection; using UnityEngine; #if UNITY_EDITOR using UnityEditor; #endif [ExecuteInEditMode] public class AlembicCamera : AlembicElement { public AbcAPI.aiAspectRatioModeOverride m_aspectRatioMode = AbcAPI.aiAspectRatioModeOverride.InheritStreamSetting; Camera m_camera; AbcAPI.aiCameraData m_abcData; public override void AbcSetup(AlembicStream abcStream, AbcAPI.aiObject abcObj, AbcAPI.aiSchema abcSchema) { base.AbcSetup(abcStream, abcObj, abcSchema); m_camera = GetOrAddComponent<Camera>(); } public override void AbcGetConfig(ref AbcAPI.aiConfig config) { if (m_aspectRatioMode != AbcAPI.aiAspectRatioModeOverride.InheritStreamSetting) { config.aspectRatio = AbcAPI.GetAspectRatio((AbcAPI.aiAspectRatioMode) m_aspectRatioMode); } } public override void AbcSampleUpdated(AbcAPI.aiSample sample, bool topologyChanged) { AbcAPI.aiCameraGetData(sample, ref m_abcData); AbcDirty(); } public override void AbcUpdate() { if (AbcIsDirty()) { m_trans.forward = -m_trans.parent.forward; m_camera.fieldOfView = m_abcData.fieldOfView; m_camera.nearClipPlane = m_abcData.nearClippingPlane; m_camera.farClipPlane = m_abcData.farClippingPlane; // no use for focusDistance and focalLength yet (could be usefull for DoF component) AbcClean(); } } }
mit
C#
89ddeadfdfe2975af151a746a2a625d99426d304
Add content type extension
modulexcite/lokad-cqrs
Framework/Lokad.Cqrs.Http/Feature.Http/Handlers/EmbeddedResourceHttpRequestHandler.cs
Framework/Lokad.Cqrs.Http/Feature.Http/Handlers/EmbeddedResourceHttpRequestHandler.cs
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Reflection; namespace Lokad.Cqrs.Feature.Http.Handlers { public sealed class EmbeddedResourceHttpRequestHandler : IHttpRequestHandler { readonly Assembly _resourceAssembly; readonly Dictionary<string,string> _set = new Dictionary<string, string>(StringComparer.InvariantCultureIgnoreCase); public EmbeddedResourceHttpRequestHandler(Assembly resourceAssembly, string ns) { _resourceAssembly = resourceAssembly; if (!string.IsNullOrEmpty(ns) && !ns.EndsWith(".")) { ns = ns + "."; } var filter = _resourceAssembly .GetManifestResourceNames() .Where(n => n.StartsWith(ns)); foreach (var f in filter) { _set.Add("/" + f.Remove(0, ns.Length), f); } } public bool WillHandle(IHttpContext context) { return _set.ContainsKey(context.GetRequestUrl()); } public void Handle(IHttpContext context) { var requestUrl = context.GetRequestUrl(); var resource = _set[requestUrl]; using (var r = _resourceAssembly.GetManifestResourceStream(resource)) { r.CopyTo(context.Response.OutputStream); } GuessContentType(resource).IfValue(s => context.Response.ContentType = s); } static Optional<string> GuessContentType(string fileName) { if (string.IsNullOrEmpty(fileName)) return Optional<string>.Empty; var path = Path.GetExtension(fileName).ToLowerInvariant(); switch (path) { default: return Optional<string>.Empty; } } public static IHttpRequestHandler ServeFilesFromScope(object instance) { var callingAssembly = Assembly.GetCallingAssembly(); return new EmbeddedResourceHttpRequestHandler(callingAssembly, instance.GetType().Namespace); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Reflection; namespace Lokad.Cqrs.Feature.Http.Handlers { public sealed class EmbeddedResourceHttpRequestHandler : IHttpRequestHandler { readonly Assembly _resourceAssembly; readonly Dictionary<string,string> _set = new Dictionary<string, string>(StringComparer.InvariantCultureIgnoreCase); public EmbeddedResourceHttpRequestHandler(Assembly resourceAssembly, string ns) { _resourceAssembly = resourceAssembly; if (!string.IsNullOrEmpty(ns) && !ns.EndsWith(".")) { ns = ns + "."; } var filter = _resourceAssembly .GetManifestResourceNames() .Where(n => n.StartsWith(ns)); foreach (var f in filter) { _set.Add("/" + f.Remove(0, ns.Length), f); } } public bool WillHandle(IHttpContext context) { return _set.ContainsKey(context.GetRequestUrl()); } public void Handle(IHttpContext context) { var resource = _set[context.GetRequestUrl()]; using (var r = _resourceAssembly.GetManifestResourceStream(resource)) { r.CopyTo(context.Response.OutputStream); } } public static IHttpRequestHandler ServeFilesFromScope(object instance) { var callingAssembly = Assembly.GetCallingAssembly(); return new EmbeddedResourceHttpRequestHandler(callingAssembly, instance.GetType().Namespace); } } }
bsd-3-clause
C#
092b4870ef0b1a9fc4d42c5fc913aef9b4b9245a
Update latest version download link
vedi/unity3d-levelup,vedi/unity3d-levelup,vedi/unity3d-levelup,vedi/unity3d-levelup,vedi/unity3d-levelup
Soomla/Assets/Plugins/Soomla/Levelup/Config/LevelUpSettings.cs
Soomla/Assets/Plugins/Soomla/Levelup/Config/LevelUpSettings.cs
/// Copyright (C) 2012-2014 Soomla Inc. /// /// Licensed under the Apache License, Version 2.0 (the "License"); /// you may not use this file except in compliance with the License. /// You may obtain a copy of the License at /// /// http://www.apache.org/licenses/LICENSE-2.0 /// /// Unless required by applicable law or agreed to in writing, software /// distributed under the License is distributed on an "AS IS" BASIS, /// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. /// See the License for the specific language governing permissions and /// limitations under the License. using UnityEngine; using System.IO; using System; using System.Collections.Generic; using System.Linq; #if UNITY_EDITOR using UnityEditor; #endif namespace Soomla.Levelup { #if UNITY_EDITOR [InitializeOnLoad] #endif /// <summary> /// This class holds the levelup's configurations. /// </summary> public class LevelUpSettings : ISoomlaSettings { #if UNITY_EDITOR static LevelUpSettings instance = new LevelUpSettings(); static string currentModuleVersion = "1.1.0"; static LevelUpSettings() { SoomlaEditorScript.addSettings(instance); SoomlaEditorScript.addFileList("LevelUp", "Assets/Soomla/levelup_file_list", new string[] {}); } // BuildTargetGroup[] supportedPlatforms = { BuildTargetGroup.Android, BuildTargetGroup.iPhone, // BuildTargetGroup.WebPlayer, BuildTargetGroup.Standalone}; GUIContent levelUpVersion = new GUIContent("LevelUp Version [?]", "The SOOMLA LevelUp version. "); private LevelUpSettings() { } public void OnEnable() { // Generating AndroidManifest.xml // ManifestTools.GenerateManifest(); } public void OnModuleGUI() { // AndroidGUI(); // EditorGUILayout.Space(); // IOSGUI(); } public void OnInfoGUI() { SoomlaEditorScript.RemoveSoomlaModuleButton(levelUpVersion, currentModuleVersion, "LevelUp"); SoomlaEditorScript.LatestVersionField ("unity3d-levelup", currentModuleVersion, "New version available!", "http://library.soom.la/fetch/unity3d-levelup-only/latest?cf=unity"); EditorGUILayout.Space(); } public void OnSoomlaGUI() { } #endif /** LevelUp Specific Variables **/ } }
/// Copyright (C) 2012-2014 Soomla Inc. /// /// Licensed under the Apache License, Version 2.0 (the "License"); /// you may not use this file except in compliance with the License. /// You may obtain a copy of the License at /// /// http://www.apache.org/licenses/LICENSE-2.0 /// /// Unless required by applicable law or agreed to in writing, software /// distributed under the License is distributed on an "AS IS" BASIS, /// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. /// See the License for the specific language governing permissions and /// limitations under the License. using UnityEngine; using System.IO; using System; using System.Collections.Generic; using System.Linq; #if UNITY_EDITOR using UnityEditor; #endif namespace Soomla.Levelup { #if UNITY_EDITOR [InitializeOnLoad] #endif /// <summary> /// This class holds the levelup's configurations. /// </summary> public class LevelUpSettings : ISoomlaSettings { #if UNITY_EDITOR static LevelUpSettings instance = new LevelUpSettings(); static string currentModuleVersion = "1.1.0"; static LevelUpSettings() { SoomlaEditorScript.addSettings(instance); SoomlaEditorScript.addFileList("LevelUp", "Assets/Soomla/levelup_file_list", new string[] {}); } // BuildTargetGroup[] supportedPlatforms = { BuildTargetGroup.Android, BuildTargetGroup.iPhone, // BuildTargetGroup.WebPlayer, BuildTargetGroup.Standalone}; GUIContent levelUpVersion = new GUIContent("LevelUp Version [?]", "The SOOMLA LevelUp version. "); private LevelUpSettings() { } public void OnEnable() { // Generating AndroidManifest.xml // ManifestTools.GenerateManifest(); } public void OnModuleGUI() { // AndroidGUI(); // EditorGUILayout.Space(); // IOSGUI(); } public void OnInfoGUI() { SoomlaEditorScript.RemoveSoomlaModuleButton(levelUpVersion, currentModuleVersion, "LevelUp"); SoomlaEditorScript.LatestVersionField ("unity3d-levelup", currentModuleVersion, "New LevelUp version available!", "http://library.soom.la/fetch/unity3d-levelup/latest?cf=unity"); EditorGUILayout.Space(); } public void OnSoomlaGUI() { } #endif /** LevelUp Specific Variables **/ } }
apache-2.0
C#