content
stringlengths 5
1.04M
| avg_line_length
float64 1.75
12.9k
| max_line_length
int64 2
244k
| alphanum_fraction
float64 0
0.98
| licenses
list | repository_name
stringlengths 7
92
| path
stringlengths 3
249
| size
int64 5
1.04M
| lang
stringclasses 2
values |
|---|---|---|---|---|---|---|---|---|
using Lyrico.Common;
using Lyrico.Helpers;
using Lyrico.Models;
using Lyrico.Models.Spotify;
using Lyrico.Services.Interfaces;
using Lyrico.Utils;
using Lyrico.Views;
using Prism.Commands;
using Prism.Navigation;
using Prism.Services;
using System;
using System.Collections.Generic;
using System.Security;
using System.Threading.Tasks;
namespace Lyrico.ViewModels
{
public class SpotifyLoginPageViewModel : BindableBase, INavigatedAware, IDisposable
{
private INavigationService _navigationService { get; }
private IWebAuthService _webAuthService { get; }
private ISpotifyService _spotifyService { get; }
public SpotifyLoginPageViewModel(INavigationService ns, IWebAuthService was, ISpotifyService ss)
{
_navigationService = ns;
_webAuthService = was;
_spotifyService = ss;
OpenAuthenticationPageCommand = new DelegateCommand(async () => await OpenAuthenticationPage());
}
public void OnNavigatedFrom(INavigationParameters parameters)
{
}
public void OnNavigatedTo(INavigationParameters parameters)
{
}
public void Dispose()
{
}
public DelegateCommand OpenAuthenticationPageCommand { get; }
public async Task OpenAuthenticationPage()
{
AuthRequest request = new AuthRequest(Constants.RedirectUri, Secrets.SpotifyClientId, ResponseType.Code)
{
Scope = new List<string> { Scopes.UserReadCurrentlyPlaying, Scopes.UserReadPlaybackState },
State = Guid.NewGuid().ToString("N"),
};
Uri uri = request.ToUri();
var result = await _webAuthService.LaunchUriAsync(uri.OriginalString);
Console.WriteLine("Request State: " + request.State + " | Result State: " + result.Properties["state"]);
if (!result.Properties["state"].StartsWith(request.State)) // Spotify sometimes appends #_=_ to the sent State parameter. Investigation as to why this is happening is needed. Might change to Json parsing using custom class.
throw new SecurityException("Antiforgery token validation failed");
var swapResult = await _spotifyService.RequestToken(result.Properties["code"]);
if (swapResult == null)
{
await _navigationService.NavigateAsync("MainPage?auth=fail");
}
else
{
TokenUtil.SetAccessToken(swapResult);
await _navigationService.NavigateAsync("MainPage?auth=success");
}
}
}
}
| 34.842105
| 235
| 0.655967
|
[
"MIT"
] |
mikan9/lyrico
|
Lyrico/Lyrico/ViewModels/SpotifyLoginPageViewModel.cs
| 2,650
|
C#
|
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Runtime.InteropServices;
using System.Threading;
using Umbraco.Cms.Core.Configuration;
using Umbraco.Cms.Core.Models;
using Umbraco.Extensions;
namespace Umbraco.Cms.Core.Services
{
public class UserDataService : IUserDataService
{
private readonly IUmbracoVersion _version;
private readonly ILocalizationService _localizationService;
public UserDataService(IUmbracoVersion version, ILocalizationService localizationService)
{
_version = version;
_localizationService = localizationService;
}
public IEnumerable<UserData> GetUserData() =>
new List<UserData>
{
new("Server OS", RuntimeInformation.OSDescription),
new("Server Framework", RuntimeInformation.FrameworkDescription),
new("Default Language", _localizationService.GetDefaultLanguageIsoCode()),
new("Umbraco Version", _version.SemanticVersion.ToSemanticStringWithoutBuild()),
new("Current Culture", Thread.CurrentThread.CurrentCulture.ToString()),
new("Current UI Culture", Thread.CurrentThread.CurrentUICulture.ToString()),
new("Current Webserver", GetCurrentWebServer())
};
private string GetCurrentWebServer() => IsRunningInProcessIIS() ? "IIS" : "Kestrel";
public bool IsRunningInProcessIIS()
{
if (!RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
{
return false;
}
string processName = Path.GetFileNameWithoutExtension(Process.GetCurrentProcess().ProcessName);
return (processName.Contains("w3wp") || processName.Contains("iisexpress"));
}
}
}
| 37.734694
| 107
| 0.665765
|
[
"MIT"
] |
Ambertvu/Umbraco-CMS
|
src/Umbraco.Core/Services/UserDataService.cs
| 1,851
|
C#
|
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
// Runtime Version:4.0.30319.34209
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
namespace PackOpeningTracker.Properties {
[global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Editors.SettingsDesigner.SettingsSingleFileGenerator", "10.0.0.0")]
internal sealed partial class Settings : global::System.Configuration.ApplicationSettingsBase {
private static Settings defaultInstance = ((Settings)(global::System.Configuration.ApplicationSettingsBase.Synchronized(new Settings())));
public static Settings Default {
get {
return defaultInstance;
}
}
}
}
| 39.740741
| 151
| 0.584343
|
[
"MIT"
] |
Gabriel-Em/Hearthstone-Pack-Opening-Tracker-Obsolete-
|
PackOpeningTracker/PackOpeningTracker/Properties/Settings.Designer.cs
| 1,075
|
C#
|
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Xml.Linq;
using Moq;
using Palmmedia.ReportGenerator.Core.Parser;
using Palmmedia.ReportGenerator.Core.Parser.Analysis;
using Palmmedia.ReportGenerator.Core.Parser.FileReading;
using Palmmedia.ReportGenerator.Core.Parser.Filtering;
using Palmmedia.ReportGenerator.Core.Parser.Preprocessing;
using Xunit;
namespace Palmmedia.ReportGenerator.Core.Test.Parser
{
/// <summary>
/// This is a test class for OpenCoverParser and is intended
/// to contain all OpenCoverParser Unit Tests
/// </summary>
[Collection("FileManager")]
public class OpenCoverParserTest
{
private static readonly string FilePath1 = Path.Combine(FileManager.GetCSharpReportDirectory(), "OpenCover.xml");
private static readonly string FilePath2 = Path.Combine(FileManager.GetCSharpReportDirectory(), "OpenCoverWithTrackedMethods.xml");
private ParserResult parserResultWithoutPreprocessing;
private ParserResult parserResultWithPreprocessing;
private ParserResult parserResultWithTrackedMethods;
public OpenCoverParserTest()
{
var filterMock = new Mock<IFilter>();
filterMock.Setup(f => f.IsElementIncludedInReport(It.IsAny<string>())).Returns(true);
this.parserResultWithoutPreprocessing = new OpenCoverParser(filterMock.Object, filterMock.Object, filterMock.Object).Parse(XDocument.Load(FilePath1));
var report = XDocument.Load(FilePath1);
new OpenCoverReportPreprocessor().Execute(report);
this.parserResultWithPreprocessing = new OpenCoverParser(filterMock.Object, filterMock.Object, filterMock.Object).Parse(report);
report = XDocument.Load(FilePath2);
new OpenCoverReportPreprocessor().Execute(report);
this.parserResultWithTrackedMethods = new OpenCoverParser(filterMock.Object, filterMock.Object, filterMock.Object).Parse(report);
}
/// <summary>
/// A test for SupportsBranchCoverage
/// </summary>
[Fact]
public void SupportsBranchCoverage()
{
Assert.True(this.parserResultWithoutPreprocessing.SupportsBranchCoverage);
Assert.True(this.parserResultWithPreprocessing.SupportsBranchCoverage);
Assert.True(this.parserResultWithTrackedMethods.SupportsBranchCoverage);
}
/// <summary>
/// A test for NumberOfLineVisits
/// </summary>
[Fact]
public void NumberOfLineVisitsTest_WithoutPreprocessing()
{
var fileAnalysis = GetFileAnalysis(this.parserResultWithoutPreprocessing.Assemblies, "Test.TestClass", "C:\\temp\\TestClass.cs");
Assert.Equal(1, fileAnalysis.Lines.Single(l => l.LineNumber == 9).LineVisits);
Assert.Equal(1, fileAnalysis.Lines.Single(l => l.LineNumber == 10).LineVisits);
Assert.Equal(1, fileAnalysis.Lines.Single(l => l.LineNumber == 11).LineVisits);
Assert.Equal(1, fileAnalysis.Lines.Single(l => l.LineNumber == 12).LineVisits);
Assert.Equal(1, fileAnalysis.Lines.Single(l => l.LineNumber == 19).LineVisits);
Assert.Equal(0, fileAnalysis.Lines.Single(l => l.LineNumber == 23).LineVisits);
Assert.Equal(0, fileAnalysis.Lines.Single(l => l.LineNumber == 31).LineVisits);
fileAnalysis = GetFileAnalysis(this.parserResultWithoutPreprocessing.Assemblies, "Test.TestClass2", "C:\\temp\\TestClass2.cs");
Assert.Equal(3, fileAnalysis.Lines.Single(l => l.LineNumber == 13).LineVisits);
Assert.Equal(0, fileAnalysis.Lines.Single(l => l.LineNumber == 15).LineVisits);
Assert.Equal(0, fileAnalysis.Lines.Single(l => l.LineNumber == 19).LineVisits);
Assert.Equal(2, fileAnalysis.Lines.Single(l => l.LineNumber == 25).LineVisits);
Assert.Equal(1, fileAnalysis.Lines.Single(l => l.LineNumber == 31).LineVisits);
Assert.Equal(0, fileAnalysis.Lines.Single(l => l.LineNumber == 37).LineVisits);
Assert.Equal(4, fileAnalysis.Lines.Single(l => l.LineNumber == 54).LineVisits);
Assert.Equal(0, fileAnalysis.Lines.Single(l => l.LineNumber == 81).LineVisits);
Assert.False(fileAnalysis.Lines.Single(l => l.LineNumber == 44).CoveredBranches.HasValue, "No covered branches");
Assert.False(fileAnalysis.Lines.Single(l => l.LineNumber == 44).TotalBranches.HasValue, "No total branches");
Assert.Equal(1, fileAnalysis.Lines.Single(l => l.LineNumber == 54).CoveredBranches.Value);
Assert.Equal(2, fileAnalysis.Lines.Single(l => l.LineNumber == 54).TotalBranches.Value);
fileAnalysis = GetFileAnalysis(this.parserResultWithoutPreprocessing.Assemblies, "Test.PartialClass", "C:\\temp\\PartialClass.cs");
Assert.Equal(1, fileAnalysis.Lines.Single(l => l.LineNumber == 9).LineVisits);
Assert.Equal(0, fileAnalysis.Lines.Single(l => l.LineNumber == 14).LineVisits);
fileAnalysis = GetFileAnalysis(this.parserResultWithoutPreprocessing.Assemblies, "Test.PartialClass", "C:\\temp\\PartialClass2.cs");
Assert.Equal(1, fileAnalysis.Lines.Single(l => l.LineNumber == 9).LineVisits);
Assert.Equal(0, fileAnalysis.Lines.Single(l => l.LineNumber == 14).LineVisits);
fileAnalysis = GetFileAnalysis(this.parserResultWithoutPreprocessing.Assemblies, "Test.ClassWithExcludes", "C:\\temp\\ClassWithExcludes.cs");
Assert.Equal(-1, fileAnalysis.Lines.Single(l => l.LineNumber == 9).LineVisits);
Assert.Equal(-1, fileAnalysis.Lines.Single(l => l.LineNumber == 19).LineVisits);
}
/// <summary>
/// A test for NumberOfLineVisits
/// </summary>
[Fact]
public void NumberOfLineVisitsTest_WithPreprocessing()
{
var fileAnalysis = GetFileAnalysis(this.parserResultWithPreprocessing.Assemblies, "Test.TestClass", "C:\\temp\\TestClass.cs");
Assert.Equal(1, fileAnalysis.Lines.Single(l => l.LineNumber == 9).LineVisits);
Assert.Equal(1, fileAnalysis.Lines.Single(l => l.LineNumber == 10).LineVisits);
Assert.Equal(1, fileAnalysis.Lines.Single(l => l.LineNumber == 11).LineVisits);
Assert.Equal(1, fileAnalysis.Lines.Single(l => l.LineNumber == 12).LineVisits);
Assert.Equal(1, fileAnalysis.Lines.Single(l => l.LineNumber == 19).LineVisits);
Assert.Equal(0, fileAnalysis.Lines.Single(l => l.LineNumber == 23).LineVisits);
Assert.Equal(0, fileAnalysis.Lines.Single(l => l.LineNumber == 31).LineVisits);
fileAnalysis = GetFileAnalysis(this.parserResultWithPreprocessing.Assemblies, "Test.TestClass2", "C:\\temp\\TestClass2.cs");
Assert.Equal(3, fileAnalysis.Lines.Single(l => l.LineNumber == 13).LineVisits);
Assert.Equal(0, fileAnalysis.Lines.Single(l => l.LineNumber == 15).LineVisits);
Assert.Equal(0, fileAnalysis.Lines.Single(l => l.LineNumber == 19).LineVisits);
Assert.Equal(2, fileAnalysis.Lines.Single(l => l.LineNumber == 25).LineVisits);
Assert.Equal(1, fileAnalysis.Lines.Single(l => l.LineNumber == 31).LineVisits);
Assert.Equal(0, fileAnalysis.Lines.Single(l => l.LineNumber == 37).LineVisits);
Assert.Equal(4, fileAnalysis.Lines.Single(l => l.LineNumber == 54).LineVisits);
Assert.Equal(0, fileAnalysis.Lines.Single(l => l.LineNumber == 81).LineVisits);
Assert.False(fileAnalysis.Lines.Single(l => l.LineNumber == 44).CoveredBranches.HasValue);
Assert.False(fileAnalysis.Lines.Single(l => l.LineNumber == 44).TotalBranches.HasValue);
Assert.Equal(1, fileAnalysis.Lines.Single(l => l.LineNumber == 54).CoveredBranches.Value);
Assert.Equal(2, fileAnalysis.Lines.Single(l => l.LineNumber == 54).TotalBranches.Value);
fileAnalysis = GetFileAnalysis(this.parserResultWithPreprocessing.Assemblies, "Test.PartialClass", "C:\\temp\\PartialClass.cs");
Assert.Equal(1, fileAnalysis.Lines.Single(l => l.LineNumber == 9).LineVisits);
Assert.Equal(0, fileAnalysis.Lines.Single(l => l.LineNumber == 14).LineVisits);
fileAnalysis = GetFileAnalysis(this.parserResultWithPreprocessing.Assemblies, "Test.PartialClass", "C:\\temp\\PartialClass2.cs");
Assert.Equal(1, fileAnalysis.Lines.Single(l => l.LineNumber == 9).LineVisits);
Assert.Equal(0, fileAnalysis.Lines.Single(l => l.LineNumber == 14).LineVisits);
fileAnalysis = GetFileAnalysis(this.parserResultWithPreprocessing.Assemblies, "Test.ClassWithExcludes", "C:\\temp\\ClassWithExcludes.cs");
Assert.Equal(-1, fileAnalysis.Lines.Single(l => l.LineNumber == 9).LineVisits);
Assert.Equal(-1, fileAnalysis.Lines.Single(l => l.LineNumber == 19).LineVisits);
}
/// <summary>
/// A test for NumberOfLineVisits
/// </summary>
[Fact]
public void NumberOfLineVisitsTest_WithTrackedMethods()
{
var fileAnalysis = GetFileAnalysis(this.parserResultWithTrackedMethods.Assemblies, "Test.PartialClass", "C:\\temp\\PartialClass.cs");
var line = fileAnalysis.Lines.Single(l => l.LineNumber == 9);
Assert.Equal(2, line.LineVisits);
Assert.Equal(2, line.LineCoverageByTestMethod.Count);
Assert.Equal(1, line.LineCoverageByTestMethod.First().Value.LineVisits);
Assert.Equal(1, line.LineCoverageByTestMethod.ElementAt(1).Value.LineVisits);
}
/// <summary>
/// A test for LineVisitStatus
/// </summary>
[Fact]
public void LineVisitStatusTest_WithTrackedMethods()
{
var fileAnalysis = GetFileAnalysis(this.parserResultWithTrackedMethods.Assemblies, "Test.TestClass", "C:\\temp\\TestClass.cs");
var line = fileAnalysis.Lines.Single(l => l.LineNumber == 1);
Assert.Equal(LineVisitStatus.NotCoverable, line.LineVisitStatus);
Assert.Equal(2, line.LineCoverageByTestMethod.Count);
Assert.Equal(LineVisitStatus.NotCoverable, line.LineCoverageByTestMethod.First().Value.LineVisitStatus);
Assert.Equal(LineVisitStatus.NotCoverable, line.LineCoverageByTestMethod.ElementAt(1).Value.LineVisitStatus);
line = fileAnalysis.Lines.Single(l => l.LineNumber == 15);
Assert.Equal(LineVisitStatus.Covered, line.LineVisitStatus);
Assert.Equal(2, line.LineCoverageByTestMethod.Count);
Assert.Equal(LineVisitStatus.Covered, line.LineCoverageByTestMethod.First().Value.LineVisitStatus);
Assert.Equal(LineVisitStatus.Covered, line.LineCoverageByTestMethod.ElementAt(1).Value.LineVisitStatus);
line = fileAnalysis.Lines.Single(l => l.LineNumber == 17);
Assert.Equal(LineVisitStatus.PartiallyCovered, line.LineVisitStatus);
Assert.Equal(2, line.LineCoverageByTestMethod.Count);
Assert.Equal(LineVisitStatus.PartiallyCovered, line.LineCoverageByTestMethod.First().Value.LineVisitStatus);
Assert.Equal(LineVisitStatus.PartiallyCovered, line.LineCoverageByTestMethod.ElementAt(1).Value.LineVisitStatus);
line = fileAnalysis.Lines.Single(l => l.LineNumber == 22);
Assert.Equal(LineVisitStatus.NotCovered, line.LineVisitStatus);
Assert.Equal(2, line.LineCoverageByTestMethod.Count);
Assert.Equal(LineVisitStatus.NotCovered, line.LineCoverageByTestMethod.First().Value.LineVisitStatus);
Assert.Equal(LineVisitStatus.NotCovered, line.LineCoverageByTestMethod.ElementAt(1).Value.LineVisitStatus);
}
/// <summary>
/// A test for NumberOfFiles
/// </summary>
[Fact]
public void NumberOfFilesTest()
{
Assert.Equal(15, this.parserResultWithoutPreprocessing.Assemblies.SelectMany(a => a.Classes).SelectMany(a => a.Files).Distinct().Count());
}
/// <summary>
/// A test for FilesOfClass
/// </summary>
[Fact]
public void FilesOfClassTest()
{
Assert.Single(this.parserResultWithoutPreprocessing.Assemblies.Single(a => a.Name == "Test").Classes.Single(c => c.Name == "Test.TestClass").Files);
Assert.Equal(2, this.parserResultWithoutPreprocessing.Assemblies.Single(a => a.Name == "Test").Classes.Single(c => c.Name == "Test.PartialClass").Files.Count());
}
/// <summary>
/// A test for ClassesInAssembly
/// </summary>
[Fact]
public void ClassesInAssemblyTest()
{
Assert.Equal(17, this.parserResultWithoutPreprocessing.Assemblies.SelectMany(a => a.Classes).Count());
}
/// <summary>
/// A test for Assemblies
/// </summary>
[Fact]
public void AssembliesTest()
{
Assert.Single(this.parserResultWithoutPreprocessing.Assemblies);
}
/// <summary>
/// A test for GetCoverageQuotaOfClass.
/// </summary>
[Fact]
public void GetCoverableLinesOfClassTest()
{
Assert.Equal(4, this.parserResultWithoutPreprocessing.Assemblies.Single(a => a.Name == "Test").Classes.Single(c => c.Name == "Test.AbstractClass").CoverableLines);
}
/// <summary>
/// A test for GetCoverageQuotaOfClass.
/// </summary>
[Fact]
public void GetCoverageQuotaOfClassTest()
{
Assert.Equal(66.6m, this.parserResultWithoutPreprocessing.Assemblies.Single(a => a.Name == "Test").Classes.Single(c => c.Name == "Test.PartialClassWithAutoProperties").CoverageQuota);
}
/// <summary>
/// A test for MethodMetrics
/// </summary>
[Fact]
public void MethodMetricsTest()
{
var metrics = this.parserResultWithoutPreprocessing.Assemblies.Single(a => a.Name == "Test").Classes.Single(c => c.Name == "Test.TestClass").Files.Single(f => f.Path == "C:\\temp\\TestClass.cs").MethodMetrics;
Assert.Equal(2, metrics.Count());
Assert.Equal("System.Void Test.TestClass::SampleFunction()", metrics.First().FullName);
Assert.Equal(5, metrics.First().Metrics.Count());
Assert.Equal("Cyclomatic complexity", metrics.First().Metrics.ElementAt(0).Name);
Assert.Equal(3, metrics.First().Metrics.ElementAt(0).Value);
Assert.Equal("NPath complexity", metrics.First().Metrics.ElementAt(1).Name);
Assert.Equal(2, metrics.First().Metrics.ElementAt(1).Value);
Assert.Equal("Sequence coverage", metrics.First().Metrics.ElementAt(2).Name);
Assert.Equal(75M, metrics.First().Metrics.ElementAt(2).Value);
Assert.Equal("Branch coverage", metrics.First().Metrics.ElementAt(3).Name);
Assert.Equal(66.67M, metrics.First().Metrics.ElementAt(3).Value);
Assert.Equal("Crap Score", metrics.First().Metrics.ElementAt(4).Name);
Assert.Equal(3.14M, metrics.First().Metrics.ElementAt(4).Value);
metrics = this.parserResultWithoutPreprocessing.Assemblies.Single(a => a.Name == "Test").Classes.Single(c => c.Name == "Test.AsyncClass").Files.Single(f => f.Path == "C:\\temp\\AsyncClass.cs").MethodMetrics;
Assert.Single(metrics);
Assert.Equal("SendAsync()", metrics.First().FullName);
}
/// <summary>
/// A test for CodeElements
/// </summary>
[Fact]
public void CodeElementsTest()
{
var codeElements = GetFile(this.parserResultWithPreprocessing.Assemblies, "Test.TestClass", "C:\\temp\\TestClass.cs").CodeElements;
Assert.Equal(2, codeElements.Count());
codeElements = GetFile(this.parserResultWithPreprocessing.Assemblies, "Test.PartialClass", "C:\\temp\\PartialClass.cs").CodeElements;
Assert.Equal(4, codeElements.Count());
codeElements = GetFile(this.parserResultWithPreprocessing.Assemblies, "Test.TestClass2", "C:\\temp\\TestClass2.cs").CodeElements;
Assert.Equal(10, codeElements.Count());
codeElements = GetFile(this.parserResultWithPreprocessing.Assemblies, "Test.AsyncClass", "C:\\temp\\AsyncClass.cs").CodeElements;
Assert.Single(codeElements);
Assert.Equal("SendAsync()", codeElements.First().Name);
}
private static CodeFile GetFile(IEnumerable<Assembly> assemblies, string className, string fileName) => assemblies
.Single(a => a.Name == "Test").Classes
.Single(c => c.Name == className).Files
.Single(f => f.Path == fileName);
private static FileAnalysis GetFileAnalysis(IEnumerable<Assembly> assemblies, string className, string fileName) => assemblies
.Single(a => a.Name == "Test").Classes
.Single(c => c.Name == className).Files
.Single(f => f.Path == fileName)
.AnalyzeFile(new CachingFileReader(new LocalFileReader(), 0));
}
}
| 54.40694
| 221
| 0.65739
|
[
"Apache-2.0"
] |
Meir017/ReportGenerator
|
src/ReportGenerator.Core.Test/Parser/OpenCoverParserTest.cs
| 17,247
|
C#
|
using System;
using System.Collections.Generic;
using System.Text;
using EnumsNET;
using EnumsNET.NonGeneric;
using Snowflake.Configuration.Attributes;
namespace Snowflake.Configuration.Serialization
{
public sealed class EnumConfigurationNode
: AbstractConfigurationNode<Enum>
{
internal EnumConfigurationNode(string key, Enum value, Type enumType) : base(key, value)
{
this.EnumType = enumType;
this.Value = NonGenericEnums.GetMember(enumType, value)
.Attributes.Get<SelectionOptionAttribute>().SerializeAs;
}
public new string Value { get; }
public Type EnumType { get; }
}
}
| 29.608696
| 96
| 0.687225
|
[
"MPL-2.0"
] |
fossabot/snowflake-1
|
src/Snowflake.Framework/Configuration/Serialization/NodeTypes/EnumConfigurationNode.cs
| 683
|
C#
|
using System;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Identity.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Logging;
using MultiTenancyServer.EntityFramework;
using MultiTenancyServer.Options;
using MultiTenancyServer.Samples.AspNetIdentityAndEFCore.Models;
namespace MultiTenancyServer.Samples.AspNetIdentityAndEFCore.Data
{
public class ApplicationDbContext : IdentityDbContext<ApplicationUser>, ITenantDbContext<ApplicationTenant, string>
{
private static TenancyModelState<string> _tenancyModelState;
private readonly ITenancyContext<ApplicationTenant> _tenancyContext;
private readonly ILogger _logger;
public ApplicationDbContext(
DbContextOptions<ApplicationDbContext> options,
ITenancyContext<ApplicationTenant> tenancyContext,
ILogger<ApplicationDbContext> logger)
: base(options)
{
// The request scoped tenancy context.
// Should not access the tenancyContext.Tenant property in the constructor yet,
// as the request pipeline has not finished running yet and it will likely be null.
// Use the private property wrapper above to access it later on demand.
_tenancyContext = tenancyContext;
_logger = logger ?? throw new ArgumentNullException(nameof(logger));
}
// MultiTenancyServer implementation.
public DbSet<ApplicationTenant> Tenants { get; set; }
protected override void OnModelCreating(ModelBuilder builder)
{
base.OnModelCreating(builder);
// Customize the ASP.NET Identity model and override the defaults if needed.
// For example, you can rename the ASP.NET Identity table names and more.
// Add your customizations after calling base.OnModelCreating(builder);
// MultiTenancyServer configuration.
var tenantStoreOptions = new TenantStoreOptions();
builder.ConfigureTenantContext<ApplicationTenant, string>(tenantStoreOptions);
// Add multi-tenancy support to model.
var tenantReferenceOptions = new TenantReferenceOptions();
builder.HasTenancy<string>(tenantReferenceOptions, out _tenancyModelState);
// Configure custom properties on ApplicationTenant.
builder.Entity<ApplicationTenant>(b =>
{
b.Property(t => t.DisplayName).HasMaxLength(256);
});
// Configure properties on User (ASP.NET Core Identity).
builder.Entity<ApplicationUser>(b =>
{
// Add multi-tenancy support to entity.
b.HasTenancy(() => _tenancyContext.Tenant.Id, _tenancyModelState, hasIndex: false);
// Remove unique index on NormalizedUserName.
b.HasIndex(u => u.NormalizedUserName).HasName("UserNameIndex").IsUnique(false);
// Add unique index on TenantId and NormalizedUserName.
b.HasIndex(tenantReferenceOptions.ReferenceName, nameof(ApplicationUser.NormalizedUserName))
.HasName("TenantUserNameIndex").IsUnique();
});
// Configure properties on Role (ASP.NET Core Identity).
builder.Entity<IdentityRole>(b =>
{
// Add multi-tenancy support to entity.
b.HasTenancy(() => _tenancyContext.Tenant.Id, _tenancyModelState, hasIndex: false);
// Remove unique index on NormalizedUserName.
b.HasIndex(r => r.NormalizedName).HasName("RoleNameIndex").IsUnique(false);
// Add unique index on TenantId and NormalizedUserName.
b.HasIndex(tenantReferenceOptions.ReferenceName, nameof(IdentityRole.NormalizedName))
.HasName("TenantRoleNameIndex").IsUnique();
});
}
public override int SaveChanges(bool acceptAllChangesOnSuccess)
{
// Ensure multi-tenancy for all tenantable entities.
this.EnsureTenancy(_tenancyContext?.Tenant?.Id, _tenancyModelState, _logger);
return base.SaveChanges(acceptAllChangesOnSuccess);
}
public override Task<int> SaveChangesAsync(bool acceptAllChangesOnSuccess, CancellationToken cancellationToken = default)
{
// Ensure multi-tenancy for all tenantable entities.
this.EnsureTenancy(_tenancyContext?.Tenant?.Id, _tenancyModelState, _logger);
return base.SaveChangesAsync(acceptAllChangesOnSuccess, cancellationToken);
}
}
}
| 48.112245
| 129
| 0.670201
|
[
"Apache-2.0"
] |
MultiTenancyServer/MultiTenancyServer
|
samples/AspNetIdentityAndEFCore/Data/ApplicationDbContext.cs
| 4,717
|
C#
|
using BackendlessAPI;
using BackendlessAPI.Async;
using BackendlessAPI.File;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.IO;
using System.Threading.Tasks;
using Xamarin.Forms;
using Plugin.Media;
using Plugin.Media.Abstractions;
namespace SampleFileManager
{
[DesignTimeVisible( false )]
public partial class MainPage : ContentPage
{
Image img = new Image
{
MinimumWidthRequest = 300,
MinimumHeightRequest = 200,
WidthRequest = 300,
HeightRequest = 200
};
public MainPage()
{
InitializerAPI.InitializeAPI();
InitializeComponent();
try
{
}
catch( Exception e )
{
DisplayAlert( "Error", e.Message, "Ok" );
}
}
public async void TakePhotoAndUploadIt( Object sender, EventArgs ea )
{
try
{
if( CrossMedia.Current.IsPickPhotoSupported && CrossMedia.Current.IsCameraAvailable )
{
MediaFile photo = await CrossMedia.Current.TakePhotoAsync( new StoreCameraMediaOptions
{
SaveToAlbum = true,
Directory = "Sample",
Name = $"{DateTime.Now.ToString( "dd.MM.yyyy_hh.mm.ss" )}.jpg"
} ).ConfigureAwait( false );
if( photo == null )
return;
img.Source = ImageSource.FromFile( photo.Path );
AsyncCallback<BackendlessFile> callback = new AsyncCallback<BackendlessFile>(
async result =>
{
await Device.InvokeOnMainThreadAsync( () =>
{
layoutForImage.Children.Add( img );
Content = mainLayout;
} );
},
async fault =>
{
await Device.InvokeOnMainThreadAsync( async () =>
{
await DisplayAlert( "Error", fault.Message, "Ok" );
} );
} );
FileStream fs = new FileStream( photo.Path, FileMode.Open, FileAccess.Read );
Backendless.Files.Upload( fs, "fileservice_sample", callback );
}
}
catch( Exception e )
{
await Device.InvokeOnMainThreadAsync( async () =>
{
await DisplayAlert( "Error", e.Message, "Ok" );
} );
}
}
public async void BrowseUploaded( Object sender, EventArgs ea )
{
try
{
await Task.Run( async () =>
{
List<BackendlessAPI.File.FileInfo> listJpgImages = (List<BackendlessAPI.File.FileInfo>) Backendless.Files.Listing( "/fileservice_sample", "*.jpg", false );
foreach( var entry in listJpgImages )
{
Image stackImage = new Image
{
MinimumWidthRequest = 300,
MinimumHeightRequest = 200,
WidthRequest = 300,
HeightRequest = 200
};
stackImage.Source = ImageSource.FromUri( new Uri( entry.PublicURL ) );
await Device.InvokeOnMainThreadAsync( () =>
{
allPhotos.Children.Add( stackImage );
} );
}
await Device.InvokeOnMainThreadAsync( () =>
{
Content = mainLayout;
} );
} );
}
catch( Exception e )
{
await Device.InvokeOnMainThreadAsync( async () =>
{
await DisplayAlert( "Error", e.Message, "Ok" );
} );
}
}
}
}
| 27.095238
| 165
| 0.55126
|
[
"Apache-2.0"
] |
Delta-BWH/LifeBoat
|
codegen/features/xsls/backendless-codegen-xsls/net/backendless-codegen/Xamarin/SFM/SampleFileManager/SampleFileManager/MainPage.xaml.cs
| 3,416
|
C#
|
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Xml;
using Abp.Extensions;
using Abp.IO.Extensions;
using Abp.Xml.Extensions;
namespace Abp.Timing.Timezone
{
/// <summary>
/// 多时区帮助类
/// </summary>
public static class TimezoneHelper
{
static readonly Dictionary<string, string> TimeZoneMappings = new Dictionary<string, string>();
static readonly object SyncObj = new object();
/// <summary>
/// Maps given windows timezone id to IANA timezone id
/// </summary>
/// <param name="windowsTimezoneId"></param>
/// <returns></returns>
/// <exception cref="Exception"></exception>
public static string WindowsToIana(string windowsTimezoneId)
{
if (windowsTimezoneId.Equals("UTC", StringComparison.OrdinalIgnoreCase))
{
return "Etc/UTC";
}
GetTimezoneMappings();
if (TimeZoneMappings.ContainsKey(windowsTimezoneId))
{
return TimeZoneMappings[windowsTimezoneId];
}
throw new Exception(string.Format("Unable to map {0} to iana timezone.", windowsTimezoneId));
}
public static DateTime? Convert(DateTime? date, string fromTimeZoneId, string toTimeZoneId)
{
if (!date.HasValue)
{
return null;
}
var sourceTimeZone = TimeZoneInfo.FindSystemTimeZoneById(fromTimeZoneId);
var destinationTimeZone = TimeZoneInfo.FindSystemTimeZoneById(toTimeZoneId);
return TimeZoneInfo.ConvertTime(date.Value, sourceTimeZone, destinationTimeZone);
}
public static DateTime? ConvertFromUtc(DateTime? date, string toTimeZoneId)
{
return Convert(date, "UTC", toTimeZoneId);
}
private static void GetTimezoneMappings()
{
lock (SyncObj)
{
if (TimeZoneMappings.Count > 0)
{
return;
}
}
var assembly = Assembly.GetExecutingAssembly();
var resourceNames = assembly.GetManifestResourceNames();
var resourceName = resourceNames.First(r => r.Contains("WindowsZones.xml"));
using (Stream stream = assembly.GetManifestResourceStream(resourceName))
{
var bytes = stream.GetAllBytes();
var xmlString = Encoding.UTF8.GetString(bytes, 3, bytes.Length - 3); //Skipping byte order mark
var xmlDocument = new XmlDocument();
xmlDocument.LoadXml(xmlString);
var defaultMappingNodes = xmlDocument.SelectNodes("//supplementalData/windowsZones/mapTimezones/mapZone[@territory='001']");
AddMappingsToDictionary(TimeZoneMappings, defaultMappingNodes);
}
}
private static void AddMappingsToDictionary(Dictionary<string, string> timeZoneMappings, XmlNodeList defaultMappingNodes)
{
lock (SyncObj)
{
if (TimeZoneMappings.Count > 0)
{
return;
}
foreach (XmlNode defaultMappingNode in defaultMappingNodes)
{
var windowsTimezoneId = defaultMappingNode.GetAttributeValueOrNull("other");
var ianaTimezoneId = defaultMappingNode.GetAttributeValueOrNull("type");
if (windowsTimezoneId.IsNullOrEmpty() || ianaTimezoneId.IsNullOrEmpty())
{
continue;
}
timeZoneMappings.Add(windowsTimezoneId, ianaTimezoneId);
}
}
}
}
}
| 34.491071
| 140
| 0.581672
|
[
"MIT"
] |
maoyuan121/abpclone
|
src/Abp/Timing/Timezone/TimezoneHelper.cs
| 3,877
|
C#
|
using System;
using System.Runtime.InteropServices;
using System.Drawing;
using System.Collections.Generic;
using System.Text;
using System.IO;
using System.Windows.Forms;
using System.Linq;
namespace BotFramework
{
/// <summary>
/// C# dll imports
/// </summary>
public static class DllImport
{
/// <summary>
/// Set User agent for whole process of accessing internet
/// </summary>
/// <param name="dwOption">Use URLMON_OPTION_USERAGENT</param>
/// <param name="pBuffer"></param>
/// <param name="dwBufferLength"></param>
/// <param name="dwReserved"></param>
/// <returns></returns>
[DllImport("urlmon.dll", CharSet = CharSet.Ansi)]
public static extern int UrlMkSetSessionOption( int dwOption, string pBuffer, int dwBufferLength, int dwReserved);
/// <summary>
/// Set user agent
/// </summary>
public const int URLMON_OPTION_USERAGENT = 0x10000001;
/// <summary>
/// Set other IntPtr's parent to new IntPtr
/// </summary>
/// <param name="hwndChild"></param>
/// <param name="hwndNewParent"></param>
/// <returns></returns>
[DllImport("user32.dll")]
public static extern IntPtr SetParent(IntPtr hwndChild, IntPtr hwndNewParent);
/// <summary>
/// Move specific window to new location
/// </summary>
/// <param name="hwnd"></param>
/// <param name="x"></param>
/// <param name="y"></param>
/// <param name="nWidth"></param>
/// <param name="nHeight"></param>
/// <param name="bRepaint"></param>
/// <returns></returns>
[DllImport("user32.dll", SetLastError = true)]
public static extern bool MoveWindow(IntPtr hwnd, int x, int y, int nWidth, int nHeight, bool bRepaint);
/// <summary>
/// Return IntPtr of specific window, using class name and window text
/// </summary>
/// <param name="className"></param>
/// <param name="WindowText"></param>
/// <returns></returns>
[DllImport("user32.dll")]
public static extern IntPtr FindWindow(string className, string WindowText);
private delegate bool EnumWindowProc(IntPtr hwnd, IntPtr lParam);
/// <summary>
/// Return IntPtr of specific window, using class name and window text, with parent handler
/// </summary>
/// <param name="parentHandle"></param>
/// <param name="childAfter"></param>
/// <param name="lclassName"></param>
/// <param name="windowTitle"></param>
/// <returns></returns>
[DllImport("user32.dll", CharSet = CharSet.Unicode)]
public static extern IntPtr FindWindowEx(IntPtr parentHandle, IntPtr childAfter, string lclassName, string windowTitle);
/// <summary>
/// Set the window state with show or hide
/// </summary>
/// <param name="hWnd"></param>
/// <param name="nCmdShow"></param>
/// <returns></returns>
[DllImport("user32.dll")]
public static extern bool ShowWindow(IntPtr hWnd, int nCmdShow);
[DllImport("user32")]
[return: MarshalAs(UnmanagedType.Bool)]
private static extern bool EnumChildWindows(IntPtr window, EnumWindowProc callback, IntPtr lParam);
/// <summary>
/// Get all the child handle IntPtr of a program
/// </summary>
/// <param name="mainHandle"></param>
/// <returns></returns>
public static List<IntPtr> GetAllChildHandles(IntPtr mainHandle)
{
List<IntPtr> childHandles = new List<IntPtr>();
GCHandle gcChildhandlesList = GCHandle.Alloc(childHandles);
IntPtr pointerChildHandlesList = GCHandle.ToIntPtr(gcChildhandlesList);
try
{
EnumWindowProc childProc = new EnumWindowProc(EnumWindow);
EnumChildWindows(mainHandle, childProc, pointerChildHandlesList);
}
finally
{
gcChildhandlesList.Free();
}
return childHandles;
}
/// <summary>
/// Register Hotkey for some UI or button
/// </summary>
/// <param name="hWnd"></param>
/// <param name="id"></param>
/// <param name="fsModifiers"></param>
/// <param name="key"></param>
/// <returns></returns>
[DllImport("user32.dll", PreserveSig = false)]
public static extern bool RegisterHotKey(IntPtr hWnd,int id,uint fsModifiers,Keys key);
/// <summary>
/// Unregister the hotkey from UI or button
/// </summary>
/// <param name="hWnd"></param>
/// <param name="id"></param>
/// <returns></returns>
[DllImport("user32.dll")]
public static extern bool UnregisterHotKey(IntPtr hWnd, int id);
/// <summary>
/// Send Message to Program
/// </summary>
/// <param name="hWnd"></param>
/// <param name="Msg"></param>
/// <param name="wParam"></param>
/// <param name="lParam"></param>
/// <returns></returns>
[DllImport("user32.dll", EntryPoint = "SendMessage", CharSet = CharSet.Auto)]
public static extern bool SendMessage(IntPtr hWnd, uint Msg, int wParam, StringBuilder lParam);
/// <summary>
/// Send Message to Program
/// </summary>
/// <param name="hWnd"></param>
/// <param name="Msg"></param>
/// <param name="wparam"></param>
/// <param name="lparam"></param>
/// <returns></returns>
[DllImport("user32.dll", SetLastError = true)]
public static extern IntPtr SendMessage(int hWnd, int Msg, int wparam, int lparam);
const int WM_GETTEXT = 0x000D;
const int WM_GETTEXTLENGTH = 0x000E;
/// <summary>
/// Get control's Text
/// </summary>
/// <param name="hWnd"></param>
/// <returns></returns>
public static string GetControlText(IntPtr hWnd)
{
// Get the size of the string required to hold the window title (including trailing null.)
Int32 titleSize = SendMessage((int)hWnd, WM_GETTEXTLENGTH, 0, 0).ToInt32();
// If titleSize is 0, there is no title so return an empty string (or null)
if (titleSize == 0)
return String.Empty;
StringBuilder title = new StringBuilder(titleSize + 1);
SendMessage(hWnd, (int)WM_GETTEXT, title.Capacity, title);
return title.ToString();
}
private static bool EnumWindow(IntPtr hWnd, IntPtr lParam)
{
GCHandle gcChildhandlesList = GCHandle.FromIntPtr(lParam);
if (gcChildhandlesList == null || gcChildhandlesList.Target == null)
{
return false;
}
List<IntPtr> childHandles = gcChildhandlesList.Target as List<IntPtr>;
childHandles.Add(hWnd);
return true;
}
/// <summary>
/// Set program location
/// </summary>
/// <param name="hWnd"></param>
/// <param name="hWndInsertAfter"></param>
/// <param name="X"></param>
/// <param name="Y"></param>
/// <param name="cx"></param>
/// <param name="cy"></param>
/// <param name="uFlags">Reference <see cref="SWP_NOSIZE"/> <see cref="SWP_NOZORDER"/></param>
/// <returns></returns>
[DllImport("user32.dll", SetLastError = true)]
public static extern bool SetWindowPos(IntPtr hWnd, IntPtr hWndInsertAfter, int X, int Y, int cx, int cy, uint uFlags);
/// <summary>
/// uflags of <see cref="SetWindowPos"/>
/// </summary>
public const uint SWP_NOSIZE = 0x0001, SWP_NOZORDER = 0x0004;
/// <summary>
/// Get Window's Rectangle
/// </summary>
/// <param name="hWnd"></param>
/// <param name="rect"></param>
/// <returns></returns>
[DllImport("user32.dll")]
public static extern IntPtr GetWindowRect(IntPtr hWnd, ref Rectangle rect);
/// <summary>
/// Set window to foreground
/// </summary>
/// <param name="hWnd"></param>
/// <returns></returns>
[DllImport("USER32.DLL")]
public static extern bool SetForegroundWindow(IntPtr hWnd);
/// <summary>
/// Get Parent's hWnd
/// </summary>
/// <param name="hWnd"></param>
/// <returns></returns>
[DllImport("user32.dll", ExactSpelling = true, CharSet = CharSet.Auto)]
public static extern IntPtr GetParent(IntPtr hWnd);
/// <summary>
/// Get all child window handles
/// </summary>
/// <param name="hParent"></param>
/// <param name="Class"></param>
/// <param name="name"></param>
/// <param name="maxCount"></param>
/// <returns></returns>
public static List<IntPtr> GetAllChildrenWindowHandles(IntPtr hParent, string Class, string name, int maxCount)
{
List<IntPtr> result = new List<IntPtr>();
int ct = 0;
IntPtr prevChild = IntPtr.Zero;
IntPtr currChild = IntPtr.Zero;
while (true && ct < maxCount)
{
currChild = FindWindowEx(hParent, prevChild, Class, name);
if (currChild == IntPtr.Zero) break;
result.Add(currChild);
prevChild = currChild;
++ct;
}
return result;
}
/// <summary>
/// Send Message to window
/// </summary>
/// <param name="hWnd"></param>
/// <param name="Msg"></param>
/// <param name="wParam"></param>
/// <param name="lParam"></param>
/// <returns></returns>
[DllImport("user32.dll")]
public static extern int SendMessage(IntPtr hWnd, int Msg, int wParam, int lParam);
/// <summary>
/// Used for borderless window to release mouse click
/// </summary>
/// <returns></returns>
[DllImport("user32.dll")]
public static extern bool ReleaseCapture();
/// <summary>
/// Get this process
/// </summary>
/// <returns></returns>
[DllImport("kernel32.dll")]
public static extern IntPtr GetCurrentProcess();
/// <summary>
///
/// </summary>
/// <param name="moduleName"></param>
/// <returns></returns>
[DllImport("kernel32.dll")]
public static extern IntPtr GetModuleHandle(string moduleName);
/// <summary>
///
/// </summary>
/// <param name="hModule"></param>
/// <param name="procName"></param>
/// <returns></returns>
[DllImport("kernel32")]
public static extern IntPtr GetProcAddress(IntPtr hModule, string procName);
/// <summary>
///
/// </summary>
/// <param name="hProcess"></param>
/// <param name="wow64Process"></param>
/// <returns></returns>
[DllImport("kernel32.dll")]
public static extern bool IsWow64Process(IntPtr hProcess, out bool wow64Process);
/// <summary>
///
/// </summary>
public const int WM_NCLBUTTONDOWN = 0xA1;
/// <summary>
///
/// </summary>
public const int HT_CAPTION = 0x2;
/// <summary>
///
/// </summary>
/// <param name="hWnd"></param>
/// <returns></returns>
[DllImport("user32.dll")]
[return: MarshalAs(UnmanagedType.Bool)]
public static extern bool IsWindow(IntPtr hWnd);
/// <summary>
///
/// </summary>
/// <param name="control"></param>
/// <param name="type"></param>
/// <returns></returns>
public static IEnumerable<Control> GetAll(Control control, Type type = null)
{
var controls = control.Controls.Cast<Control>();
//check the all value, if true then get all the controls
//otherwise get the controls of the specified type
if (type == null)
return controls.SelectMany(ctrl => GetAll(ctrl, type)).Concat(controls);
else
return controls.SelectMany(ctrl => GetAll(ctrl, type)).Concat(controls).Where(c => c.GetType() == type);
}
[StructLayout(LayoutKind.Sequential)]
private struct LASTINPUTINFO
{
public uint cbSize;
public uint dwTime;
}
[DllImport("user32.dll")]
static extern bool GetLastInputInfo(ref LASTINPUTINFO plii);
/// <summary>
///
/// </summary>
/// <returns></returns>
public static TimeSpan GetInactiveTime()
{
LASTINPUTINFO info = new LASTINPUTINFO();
info.cbSize = (uint)Marshal.SizeOf(info);
if (GetLastInputInfo(ref info))
return TimeSpan.FromMilliseconds(Environment.TickCount - info.dwTime);
else
return TimeSpan.FromMilliseconds(0);
}
/// <summary>
///
/// </summary>
/// <param name="dwFlags"></param>
/// <param name="dx"></param>
/// <param name="dy"></param>
/// <param name="cButtons"></param>
/// <param name="dwExtraInfo"></param>
[DllImport("user32.dll", CharSet = CharSet.Auto, CallingConvention = CallingConvention.StdCall)]
public static extern void mouse_event(uint dwFlags, int dx, int dy, uint cButtons, uint dwExtraInfo);
/// <summary>
///
/// </summary>
/// <param name="hWnd"></param>
/// <param name="bRevert"></param>
/// <returns></returns>
[DllImport("user32")]
public static extern IntPtr GetSystemMenu(IntPtr hWnd, bool bRevert);
/// <summary>
///
/// </summary>
/// <param name="hMenu"></param>
/// <param name="itemId"></param>
/// <param name="uEnable"></param>
/// <returns></returns>
[DllImport("user32")]
public static extern bool EnableMenuItem(IntPtr hMenu, uint itemId, uint uEnable);
/// <summary>
///
/// </summary>
//Mouse actions
public const int MOUSEEVENTF_LEFTDOWN = 0x02;
/// <summary>
///
/// </summary>
public const int MOUSEEVENTF_LEFTUP = 0x04;
/// <summary>
///
/// </summary>
public const int MOUSEEVENTF_RIGHTDOWN = 0x08;
/// <summary>
///
/// </summary>
public const int MOUSEEVENTF_RIGHTUP = 0x10;
/// <summary>
///
/// </summary>
public const int MOUSEEVENTF_MOVE = 0x0001;
/// <summary>
///
/// </summary>
/// <param name="hWnd"></param>
/// <param name="hdcBlt"></param>
/// <param name="nFlags"></param>
/// <returns></returns>
[DllImport("user32.dll")]
public static extern bool PrintWindow(IntPtr hWnd, IntPtr hdcBlt, int nFlags);
}
}
| 37.70516
| 128
| 0.544376
|
[
"MIT"
] |
PoH98/Bot
|
ImageProcessor/DllImport.cs
| 15,348
|
C#
|
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Logging;
namespace JobPortal
{
public class Program
{
public static void Main(string[] args)
{
CreateWebHostBuilder(args).Build().Run();
}
public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
WebHost.CreateDefaultBuilder(args)
.UseStartup<Startup>();
//.ConfigureLogging(logging =>
//{
// // clear default logging providers
// logging.ClearProviders();
// // add built-in providers manually, as needed
// logging.AddConsole();
// logging.AddDebug();
//});
}
}
| 28.088235
| 76
| 0.584293
|
[
"MIT"
] |
manjurulhoque/asp-core-simple-job-portal
|
Program.cs
| 957
|
C#
|
using UnityEngine;
using System.Collections;
public class GravityChange : MonoBehaviour {
float gravityMagnitude;
// Use this for initialization
void Start () {
gravityMagnitude = Physics.gravity.magnitude;
}
// Update is called once per frame
void Update () {
if (Input.GetKeyDown("right")) {
SwitchGravity(Vector3.right);
}
}
void SwitchGravity(Vector3 gravityDirection) {
Physics.gravity = gravityDirection * gravityMagnitude;
//Rotate the player so that gravity direction is down
GameManager.S.playerMovement.gameObject.GetComponentInChildren<PlayerAim>().Rotate(-gravityDirection);
}
}
| 23.923077
| 104
| 0.754019
|
[
"MIT"
] |
joshviss/ObeseSquirrels
|
ForDaManShawn/Assets/__Scripts/GravityChange.cs
| 624
|
C#
|
using System;
using NetRuntimeSystem = System;
using System.Runtime.InteropServices;
using System.Runtime.CompilerServices;
using System.ComponentModel;
using System.Reflection;
using System.Collections.Generic;
using NetOffice;
namespace NetOffice.OWC10Api
{
///<summary>
/// DispatchInterface PivotFilterAxis
/// SupportByVersion OWC10, 1
///</summary>
[SupportByVersionAttribute("OWC10", 1)]
[EntityTypeAttribute(EntityType.IsDispatchInterface)]
public class PivotFilterAxis : PivotAxis
{
#pragma warning disable
#region Type Information
private static Type _type;
[EditorBrowsable(EditorBrowsableState.Never), Browsable(false)]
public static Type LateBindingApiWrapperType
{
get
{
if (null == _type)
_type = typeof(PivotFilterAxis);
return _type;
}
}
#endregion
#region Construction
///<param name="factory">current used factory core</param>
///<param name="parentObject">object there has created the proxy</param>
///<param name="comProxy">inner wrapped COM proxy</param>
public PivotFilterAxis(Core factory, COMObject parentObject, object comProxy) : base(factory, parentObject, comProxy)
{
}
///<param name="parentObject">object there has created the proxy</param>
///<param name="comProxy">inner wrapped COM proxy</param>
[EditorBrowsable(EditorBrowsableState.Never), Browsable(false)]
public PivotFilterAxis(COMObject parentObject, object comProxy) : base(parentObject, comProxy)
{
}
///<param name="factory">current used factory core</param>
///<param name="parentObject">object there has created the proxy</param>
///<param name="comProxy">inner wrapped COM proxy</param>
///<param name="comProxyType">Type of inner wrapped COM proxy"</param>
[EditorBrowsable(EditorBrowsableState.Never), Browsable(false)]
public PivotFilterAxis(Core factory, COMObject parentObject, object comProxy, NetRuntimeSystem.Type comProxyType) : base(factory, parentObject, comProxy, comProxyType)
{
}
///<param name="parentObject">object there has created the proxy</param>
///<param name="comProxy">inner wrapped COM proxy</param>
///<param name="comProxyType">Type of inner wrapped COM proxy"</param>
[EditorBrowsable(EditorBrowsableState.Never), Browsable(false)]
public PivotFilterAxis(COMObject parentObject, object comProxy, NetRuntimeSystem.Type comProxyType) : base(parentObject, comProxy, comProxyType)
{
}
///<param name="replacedObject">object to replaced. replacedObject are not usable after this action</param>
[EditorBrowsable(EditorBrowsableState.Never), Browsable(false)]
public PivotFilterAxis(COMObject replacedObject) : base(replacedObject)
{
}
[EditorBrowsable(EditorBrowsableState.Never), Browsable(false)]
public PivotFilterAxis() : base()
{
}
/// <param name="progId">registered ProgID</param>
[EditorBrowsable(EditorBrowsableState.Never), Browsable(false)]
public PivotFilterAxis(string progId) : base(progId)
{
}
#endregion
#region Properties
#endregion
#region Methods
#endregion
#pragma warning restore
}
}
| 32.534653
| 169
| 0.703287
|
[
"MIT"
] |
Engineerumair/NetOffice
|
Source/OWC10/DispatchInterfaces/PivotFilterAxis.cs
| 3,286
|
C#
|
using System;
using System.Collections.Generic;
using System.Runtime.InteropServices;
using System.Text;
namespace OpenCvSharp.Util
{
internal static class StringHelper
{
public static unsafe string PtrToStringAnsi(sbyte* p)
{
#if DOTNET_FRAMEWORK
return new string(p);
#else
// memo: https://github.com/dotnet/standard/blob/master/netstandard/ref/mscorlib.cs#L2970
return Marshal.PtrToStringAnsi(new IntPtr(p));
#endif
}
public static unsafe string PtrToStringAnsi(IntPtr p)
{
#if DOTNET_FRAMEWORK
return new string((sbyte*)p);
#else
// memo: https://github.com/dotnet/standard/blob/master/netstandard/ref/mscorlib.cs#L2970
return Marshal.PtrToStringAnsi(p);
#endif
}
}
}
| 26.064516
| 101
| 0.660891
|
[
"BSD-3-Clause"
] |
CollegiumXR/OpenCvSharp-Xamarin.Droid
|
src/OpenCvSharp/Util/StringHelper.cs
| 810
|
C#
|
using System.Collections.Generic;
using JetBlack.MessageBus.FeedBus.Distributor.Interactors;
using JetBlack.MessageBus.FeedBus.Messages;
namespace JetBlack.MessageBus.FeedBus.Distributor.Publishers
{
public class StalePublisherEventArgs : InteractorEventArgs
{
public StalePublisherEventArgs(IInteractor interactor, IList<FeedTopic> feedsAndTopics)
: base(interactor)
{
FeedsAndTopics = feedsAndTopics;
}
public IList<FeedTopic> FeedsAndTopics { get; }
public override string ToString()
{
return $"{base.ToString()}, FeedsAndTopics=[{string.Join(",", FeedsAndTopics)}]";
}
}
}
| 30.782609
| 97
| 0.661017
|
[
"Apache-2.0"
] |
rob-blackbourn/scratch-dotnet
|
JetBlack.MessageBus/JetBlack.MessageBus.FeedBus.Distributor/Publishers/StalePublisherEventArgs.cs
| 710
|
C#
|
using System;
using System.Collections.Generic;
using ISAAR.MSolve.FEM.Entities;
namespace ISAAR.MSolve.FEM.Embedding
{
public class EmbeddedNode
{
private readonly Node node;
private readonly Element embeddedInElement;
private readonly IList<double> coordinates = new List<double>();
private readonly IList<DOFType> dependentDOFs;
public Node Node { get { return node; } }
public Element EmbeddedInElement { get { return embeddedInElement; } }
public IList<DOFType> DependentDOFs { get { return dependentDOFs; } }
public IList<double> Coordinates { get { return coordinates; } }
public EmbeddedNode(Node node, Element hostElement, IList<DOFType> dependentDOFs)
{
this.node = node;
this.embeddedInElement = hostElement;
this.dependentDOFs = dependentDOFs;
}
public override bool Equals(object obj)
{
EmbeddedNode e = obj as EmbeddedNode;
if (e == null) return false;
return (e.Node == this.node && e.EmbeddedInElement == embeddedInElement);
}
public override string ToString()
{
if (node == null) return "(Null inside node)";
string hostElementID = embeddedInElement == null ? "(N/A)" : embeddedInElement.ID.ToString();
string coordinateString = String.Empty;
foreach (var c in coordinates)
coordinateString += c.ToString() + " ";
var header = String.Format("{0} (host: {4}): ({1}, {2}, {3}) [{5}]", node.ID, node.X, node.Y, node.Z, hostElementID, coordinateString);
string constraintsDescripton = string.Empty;
foreach (var c in node.Constraints)
{
string con = string.Empty;
switch (c)
{
case DOFType.Pore:
con = "Pore";
break;
case DOFType.RotX:
con = "rX";
break;
case DOFType.RotY:
con = "rY";
break;
case DOFType.RotZ:
con = "rZ";
break;
case DOFType.Unknown:
con = "?";
break;
case DOFType.X:
con = "X";
break;
case DOFType.Y:
con = "Y";
break;
case DOFType.Z:
con = "Z";
break;
}
constraintsDescripton += c.ToString() + ", ";
}
constraintsDescripton = constraintsDescripton.Length > 1 ? constraintsDescripton.Substring(0, constraintsDescripton.Length - 2) : constraintsDescripton;
return String.Format("{0} - Con ({1})", header, constraintsDescripton);
}
}
}
| 37.120482
| 164
| 0.493022
|
[
"Apache-2.0"
] |
GoatOfRafin/MSolve
|
ISAAR.MSolve.FEM/Embedding/EmbeddedNode.cs
| 3,083
|
C#
|
using CommonServiceLocator;
using GalaSoft.MvvmLight.Ioc;
namespace Demo.CustomOpenFileDialog
{
/// <summary>
/// This class contains static references to all the view models in the
/// application and provides an entry point for the bindings.
/// </summary>
public class ViewModelLocator
{
public ViewModelLocator()
{
ServiceLocator.SetLocatorProvider(() => SimpleIoc.Default);
SimpleIoc.Default.Register<MainWindowViewModel>();
}
public MainWindowViewModel MainWindow => ServiceLocator.Current.GetInstance<MainWindowViewModel>();
}
}
| 28.318182
| 107
| 0.685393
|
[
"Apache-2.0"
] |
FantasticFiasco/mvvm-dialogs
|
samples/net-framework/Demo.CustomOpenFileDialog/ViewModelLocator.cs
| 623
|
C#
|
using System;
using My2C2P.Org.BouncyCastle.Asn1;
using My2C2P.Org.BouncyCastle.Asn1.CryptoPro;
using My2C2P.Org.BouncyCastle.Asn1.Oiw;
using My2C2P.Org.BouncyCastle.Asn1.Pkcs;
using My2C2P.Org.BouncyCastle.Asn1.Sec;
using My2C2P.Org.BouncyCastle.Asn1.X509;
using My2C2P.Org.BouncyCastle.Asn1.X9;
using My2C2P.Org.BouncyCastle.Crypto;
using My2C2P.Org.BouncyCastle.Crypto.Parameters;
using My2C2P.Org.BouncyCastle.Math;
using My2C2P.Org.BouncyCastle.Security;
using My2C2P.Org.BouncyCastle.Utilities;
namespace My2C2P.Org.BouncyCastle.Pkcs
{
public sealed class PrivateKeyInfoFactory
{
private PrivateKeyInfoFactory()
{
}
public static PrivateKeyInfo CreatePrivateKeyInfo(
AsymmetricKeyParameter key)
{
if (key == null)
throw new ArgumentNullException("key");
if (!key.IsPrivate)
throw new ArgumentException("Public key passed - private key expected", "key");
if (key is ElGamalPrivateKeyParameters)
{
ElGamalPrivateKeyParameters _key = (ElGamalPrivateKeyParameters)key;
return new PrivateKeyInfo(
new AlgorithmIdentifier(
OiwObjectIdentifiers.ElGamalAlgorithm,
new ElGamalParameter(
_key.Parameters.P,
_key.Parameters.G).ToAsn1Object()),
new DerInteger(_key.X));
}
if (key is DsaPrivateKeyParameters)
{
DsaPrivateKeyParameters _key = (DsaPrivateKeyParameters)key;
return new PrivateKeyInfo(
new AlgorithmIdentifier(
X9ObjectIdentifiers.IdDsa,
new DsaParameter(
_key.Parameters.P,
_key.Parameters.Q,
_key.Parameters.G).ToAsn1Object()),
new DerInteger(_key.X));
}
if (key is DHPrivateKeyParameters)
{
DHPrivateKeyParameters _key = (DHPrivateKeyParameters)key;
DHParameter p = new DHParameter(
_key.Parameters.P, _key.Parameters.G, _key.Parameters.L);
return new PrivateKeyInfo(
new AlgorithmIdentifier(_key.AlgorithmOid, p.ToAsn1Object()),
new DerInteger(_key.X));
}
if (key is RsaKeyParameters)
{
AlgorithmIdentifier algID = new AlgorithmIdentifier(
PkcsObjectIdentifiers.RsaEncryption, DerNull.Instance);
RsaPrivateKeyStructure keyStruct;
if (key is RsaPrivateCrtKeyParameters)
{
RsaPrivateCrtKeyParameters _key = (RsaPrivateCrtKeyParameters)key;
keyStruct = new RsaPrivateKeyStructure(
_key.Modulus,
_key.PublicExponent,
_key.Exponent,
_key.P,
_key.Q,
_key.DP,
_key.DQ,
_key.QInv);
}
else
{
RsaKeyParameters _key = (RsaKeyParameters) key;
keyStruct = new RsaPrivateKeyStructure(
_key.Modulus,
BigInteger.Zero,
_key.Exponent,
BigInteger.Zero,
BigInteger.Zero,
BigInteger.Zero,
BigInteger.Zero,
BigInteger.Zero);
}
return new PrivateKeyInfo(algID, keyStruct.ToAsn1Object());
}
if (key is ECPrivateKeyParameters)
{
ECPrivateKeyParameters priv = (ECPrivateKeyParameters)key;
ECDomainParameters dp = priv.Parameters;
int orderBitLength = dp.N.BitLength;
AlgorithmIdentifier algID;
ECPrivateKeyStructure ec;
if (priv.AlgorithmName == "ECGOST3410")
{
if (priv.PublicKeyParamSet == null)
throw Platform.CreateNotImplementedException("Not a CryptoPro parameter set");
Gost3410PublicKeyAlgParameters gostParams = new Gost3410PublicKeyAlgParameters(
priv.PublicKeyParamSet, CryptoProObjectIdentifiers.GostR3411x94CryptoProParamSet);
algID = new AlgorithmIdentifier(CryptoProObjectIdentifiers.GostR3410x2001, gostParams);
// TODO Do we need to pass any parameters here?
ec = new ECPrivateKeyStructure(orderBitLength, priv.D);
}
else
{
X962Parameters x962;
if (priv.PublicKeyParamSet == null)
{
X9ECParameters ecP = new X9ECParameters(dp.Curve, dp.G, dp.N, dp.H, dp.GetSeed());
x962 = new X962Parameters(ecP);
}
else
{
x962 = new X962Parameters(priv.PublicKeyParamSet);
}
// TODO Possible to pass the publicKey bitstring here?
ec = new ECPrivateKeyStructure(orderBitLength, priv.D, x962);
algID = new AlgorithmIdentifier(X9ObjectIdentifiers.IdECPublicKey, x962);
}
return new PrivateKeyInfo(algID, ec);
}
if (key is Gost3410PrivateKeyParameters)
{
Gost3410PrivateKeyParameters _key = (Gost3410PrivateKeyParameters)key;
if (_key.PublicKeyParamSet == null)
throw Platform.CreateNotImplementedException("Not a CryptoPro parameter set");
byte[] keyEnc = _key.X.ToByteArrayUnsigned();
byte[] keyBytes = new byte[keyEnc.Length];
for (int i = 0; i != keyBytes.Length; i++)
{
keyBytes[i] = keyEnc[keyEnc.Length - 1 - i]; // must be little endian
}
Gost3410PublicKeyAlgParameters algParams = new Gost3410PublicKeyAlgParameters(
_key.PublicKeyParamSet, CryptoProObjectIdentifiers.GostR3411x94CryptoProParamSet, null);
AlgorithmIdentifier algID = new AlgorithmIdentifier(
CryptoProObjectIdentifiers.GostR3410x94,
algParams.ToAsn1Object());
return new PrivateKeyInfo(algID, new DerOctetString(keyBytes));
}
throw new ArgumentException("Class provided is not convertible: " + Platform.GetTypeName(key));
}
public static PrivateKeyInfo CreatePrivateKeyInfo(
char[] passPhrase,
EncryptedPrivateKeyInfo encInfo)
{
return CreatePrivateKeyInfo(passPhrase, false, encInfo);
}
public static PrivateKeyInfo CreatePrivateKeyInfo(
char[] passPhrase,
bool wrongPkcs12Zero,
EncryptedPrivateKeyInfo encInfo)
{
AlgorithmIdentifier algID = encInfo.EncryptionAlgorithm;
IBufferedCipher cipher = PbeUtilities.CreateEngine(algID) as IBufferedCipher;
if (cipher == null)
throw new Exception("Unknown encryption algorithm: " + algID.Algorithm);
ICipherParameters cipherParameters = PbeUtilities.GenerateCipherParameters(
algID, passPhrase, wrongPkcs12Zero);
cipher.Init(false, cipherParameters);
byte[] keyBytes = cipher.DoFinal(encInfo.GetEncryptedData());
return PrivateKeyInfo.GetInstance(keyBytes);
}
}
}
| 38.524272
| 108
| 0.550781
|
[
"MIT"
] |
2C2P/My2C2PPKCS7
|
My2C2PPKCS7/pkcs/PrivateKeyInfoFactory.cs
| 7,936
|
C#
|
/*
* Copyright (C) 2016-2018. Filament Games, LLC. All rights reserved.
* Author: Alex Beauchesne
* Date: 21 Nov 2016
*
* File: Routine.cs
* Purpose: A safe handle pointing at an executing Routine Fiber.
* Helps prevent memory leaks and dangling references.
*/
using BeauRoutine.Internal;
using System;
using System.Collections;
using UnityEngine;
namespace BeauRoutine
{
/// <summary>
/// Custom coroutines.
/// </summary>
public partial struct Routine : IEquatable<Routine>, IDisposable
{
private uint m_Value;
/// <summary>
/// Generates the Routine handle with the given ID.
/// </summary>
private Routine(uint inValue)
{
m_Value = inValue;
}
/// <summary>
/// Default Routine. Points to no routine.
/// </summary>
static public Routine Null
{
get { return s_Null; }
}
static private Routine s_Null = default(Routine);
#region Status
/// <summary>
/// Returns an IEnumerator that waits for the routine to finish.
/// </summary>
public IEnumerator Wait()
{
Manager m = Manager.Get();
if (m != null)
{
Fiber fiber = m.Fibers[this];
if (fiber != null)
return fiber.Wait();
}
return null;
}
/// <summary>
/// Returns if the routine exists.
/// </summary>
public bool Exists()
{
Manager m = Manager.Get();
if (m != null)
{
return m_Value > 0 && m.Fibers[this] != null;
}
return false;
}
#endregion
#region Flow Control
/// <summary>
/// Pauses the routine.
/// </summary>
public Routine Pause()
{
Manager m = Manager.Get();
if (m != null)
{
Fiber fiber = m.Fibers[this];
if (fiber != null)
fiber.Pause();
}
return this;
}
/// <summary>
/// Resumes the routine.
/// </summary>
public Routine Resume()
{
Manager m = Manager.Get();
if (m != null)
{
Fiber fiber = m.Fibers[this];
if (fiber != null)
fiber.Resume();
}
return this;
}
/// <summary>
/// Returns if the routine is paused.
/// </summary>
public bool GetPaused()
{
Manager m = Manager.Get();
if (m != null)
{
Fiber fiber = m.Fibers[this];
if (fiber != null)
return fiber.GetPaused();
}
return false;
}
/// <summary>
/// Stops the routine and clears the pointer.
/// </summary>
public Routine Stop()
{
Manager m = Manager.Get();
if (m != null && m_Value != 0)
{
Fiber fiber = m.Fibers[this];
if (fiber != null)
fiber.Stop();
m_Value = 0;
}
return this;
}
/// <summary>
/// Delays the routine by the given number of seconds.
/// </summary>
public Routine DelayBy(float inSeconds)
{
Manager m = Manager.Get();
if (m != null)
{
Fiber fiber = m.Fibers[this];
if (fiber != null)
fiber.AddDelay(inSeconds);
}
return this;
}
/// <summary>
/// Returns the time scaling on the routine.
/// </summary>
public float GetTimeScale()
{
Manager m = Manager.Get();
if (m != null)
{
Fiber fiber = m.Fibers[this];
return fiber == null ? 1.0f : fiber.TimeScale;
}
return 1.0f;
}
/// <summary>
/// Sets the time scaling on the routine.
/// </summary>
public Routine SetTimeScale(float inValue)
{
Manager m = Manager.Get();
if (m != null)
{
Fiber fiber = m.Fibers[this];
if (fiber != null)
fiber.TimeScale = inValue;
}
return this;
}
/// <summary>
/// Disables per-object time scaling
/// for this routine.
/// </summary>
public Routine DisableObjectTimeScale()
{
Manager m = Manager.Get();
if (m != null)
{
Fiber fiber = m.Fibers[this];
if (fiber != null)
fiber.IgnoreObjectTimeScale();
}
return this;
}
/// <summary>
/// Re-enables per-object time scaling
/// for this routine.
/// </summary>
public Routine EnableObjectTimeScale()
{
Manager m = Manager.Get();
if (m != null)
{
Fiber fiber = m.Fibers[this];
if (fiber != null)
fiber.UseObjectTimeScale();
}
return this;
}
/// <summary>
/// The Routine will execute even while the object is disabled.
/// </summary>
public Routine ExecuteWhileDisabled()
{
Manager m = Manager.Get();
if (m != null)
{
Fiber fiber = m.Fibers[this];
if (fiber != null)
fiber.IgnoreObjectActive();
}
return this;
}
/// <summary>
/// The Routine will execute only while the object is enabled.
/// This is default behavior.
/// </summary>
public Routine ExecuteWhileEnabled()
{
Manager m = Manager.Get();
if (m != null)
{
Fiber fiber = m.Fibers[this];
if (fiber != null)
fiber.UseObjectActive();
}
return this;
}
/// <summary>
/// Returns the optional name
/// for this routine.
/// </summary>
public string GetName()
{
Manager m = Manager.Get();
if (m != null)
{
Fiber fiber = m.Fibers[this];
if (fiber != null)
return fiber.Name;
}
return null;
}
/// <summary>
/// Sets the optional name
/// for this routine.
/// </summary>
public Routine SetName(string inName)
{
Manager m = Manager.Get();
if (m != null)
{
Fiber fiber = m.Fibers[this];
if (fiber != null)
fiber.Name = inName;
}
return this;
}
/// <summary>
/// Returns the execution priority
/// for this routine.
/// </summary>
public int GetPriority()
{
Manager m = Manager.Get();
if (m != null)
{
Fiber fiber = m.Fibers[this];
if (fiber != null)
return fiber.Priority;
}
return 0;
}
/// <summary>
/// Sets the execution priority for this routine.
/// Routines with a greater priority are executed
/// first.
/// </summary>
public Routine SetPriority(int inPriority)
{
Manager m = Manager.Get();
if (m != null)
{
Fiber fiber = m.Fibers[this];
if (fiber != null)
fiber.SetPriority(inPriority);
}
return this;
}
/// <summary>
/// Gets the update timing for the routine.
/// </summary>
public RoutinePhase GetPhase()
{
Manager m = Manager.Get();
if (m != null)
{
Fiber fiber = m.Fibers[this];
if (fiber != null)
return fiber.GetPhase();
return m.DefaultPhase;
}
return RoutinePhase.LateUpdate;
}
/// <summary>
/// Sets the update timing for the routine.
/// Note that if this update is currently running,
/// this routine will not execute until the next update.
/// </summary>
public Routine SetPhase(RoutinePhase inUpdate)
{
Manager m = Manager.Get();
if (m != null)
{
Fiber fiber = m.Fibers[this];
if (fiber != null)
fiber.SetPhase(inUpdate);
}
return this;
}
/// <summary>
/// Attempts to manually update the given routine.
/// </summary>
public bool TryManuallyUpdate()
{
return TryManuallyUpdate(Time.deltaTime);
}
/// <summary>
/// Attempts to manually update the given routine
/// by the given delta time.
/// </summary>
public bool TryManuallyUpdate(float inDeltaTime)
{
Manager m = Manager.Get();
if (m != null)
{
Fiber fiber = m.Fibers[this];
if (fiber != null)
{
return m.ManualUpdate(fiber, inDeltaTime);
}
}
return false;
}
#endregion
#region Replace
/// <summary>
/// Stops the current routine and runs another routine.
/// </summary>
public Routine Replace(IEnumerator inNewRoutine)
{
Manager m = Manager.Get();
if (m != null)
{
Fiber fiber = m.Fibers[this];
if (fiber != null)
fiber.Stop();
m_Value = m.RunFiber(null, inNewRoutine).m_Value;
}
return this;
}
/// <summary>
/// Stops the current routine and runs another routine.
/// </summary>
public Routine Replace(MonoBehaviour inHost, IEnumerator inNewRoutine)
{
Manager m = Manager.Get();
if (m != null)
{
Fiber fiber = m.Fibers[this];
if (fiber != null)
fiber.Stop();
m_Value = m.RunFiber(inHost, inNewRoutine).m_Value;
}
return this;
}
/// <summary>
/// Stops the current routine and points to the given routine.
/// </summary>
public Routine Replace(Routine inRoutine)
{
Manager m = Manager.Get();
if (m != null)
{
Fiber fiber = m.Fibers[this];
if (fiber != null)
fiber.Stop();
m_Value = inRoutine.m_Value;
}
return this;
}
#endregion
#region Callbacks
/// <summary>
/// Registers a function to be called when the
/// routine completes successfully.
/// </summary>
public Routine OnComplete(Action inCallback)
{
Manager m = Manager.Get();
if (m != null)
{
Fiber fiber = m.Fibers[this];
if (fiber != null)
fiber.OnComplete(inCallback);
}
return this;
}
/// <summary>
/// Registers a function to be called when the
/// routine exits prematurely.
/// </summary>
public Routine OnStop(Action inCallback)
{
Manager m = Manager.Get();
if (m != null)
{
Fiber fiber = m.Fibers[this];
if (fiber != null)
fiber.OnStop(inCallback);
}
return this;
}
/// <summary>
/// Registers a function to be called if the
/// routine encounters an exception.
/// </summary>
public Routine OnException(ExceptionHandler inCallback)
{
Manager m = Manager.Get();
if (m != null)
{
Fiber fiber = m.Fibers[this];
if (fiber != null)
fiber.OnException(inCallback);
}
return this;
}
#endregion
#region Overrides
public void Dispose()
{
Stop();
}
public bool Equals(Routine other)
{
return m_Value == other.m_Value;
}
public override bool Equals(object obj)
{
if (obj is Routine)
return Equals((Routine)obj);
return false;
}
public override int GetHashCode()
{
return (int)m_Value;
}
static public implicit operator bool(Routine inHandle)
{
return inHandle.Exists();
}
static public explicit operator uint(Routine inHandle)
{
return inHandle.m_Value;
}
static public explicit operator Routine(uint inValue)
{
return new Routine(inValue);
}
static public bool operator==(Routine first, Routine second)
{
return first.m_Value == second.m_Value;
}
static public bool operator !=(Routine first, Routine second)
{
return first.m_Value != second.m_Value;
}
#endregion
}
}
| 26.467803
| 78
| 0.438855
|
[
"MIT"
] |
SHiLLySiT/BeauRoutine
|
Assets/BeauRoutine/Routine/Routine.cs
| 13,977
|
C#
|
#region
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using WinterLeaf.Engine;
using WinterLeaf.Engine.Classes;
using WinterLeaf.Engine.Containers;
using WinterLeaf.Engine.Enums;
using System.ComponentModel;
using System.Threading;
using WinterLeaf.Engine.Classes.Interopt;
using WinterLeaf.Engine.Classes.Decorations;
using WinterLeaf.Engine.Classes.Extensions;
using WinterLeaf.Engine.Classes.Helpers;
using Winterleaf.Demo.Full.Dedicated.Models.Base;
#endregion
namespace Winterleaf.Demo.Full.Dedicated.Models.User.Extendable
{
/// <summary>
///
/// </summary>
[TypeConverter(typeof(TypeConverterGeneric<CustomMaterial>))]
public partial class CustomMaterial: CustomMaterial_Base
{
#region ProxyObjects Operator Overrides
/// <summary>
///
/// </summary>
/// <param name="ts"></param>
/// <param name="simobjectid"></param>
/// <returns></returns>
public static bool operator ==(CustomMaterial ts, string simobjectid)
{
return object.ReferenceEquals(ts, null) ? object.ReferenceEquals(simobjectid, null) : ts.Equals(simobjectid);
}
/// <summary>
///
/// </summary>
/// <returns></returns>
public override int GetHashCode()
{
return base.GetHashCode();
}
/// <summary>
///
/// </summary>
/// <param name="obj"></param>
/// <returns></returns>
public override bool Equals(object obj)
{
return (this._ID ==(string)myReflections.ChangeType( obj,typeof(string)));
}
/// <summary>
///
/// </summary>
/// <param name="ts"></param>
/// <param name="simobjectid"></param>
/// <returns></returns>
public static bool operator !=(CustomMaterial ts, string simobjectid)
{
if (object.ReferenceEquals(ts, null))
return !object.ReferenceEquals(simobjectid, null);
return !ts.Equals(simobjectid);
}
/// <summary>
///
/// </summary>
/// <param name="ts"></param>
/// <returns></returns>
public static implicit operator string( CustomMaterial ts)
{
return ReferenceEquals(ts, null) ? "0" : ts._ID;
}
/// <summary>
///
/// </summary>
/// <param name="ts"></param>
/// <returns></returns>
public static implicit operator CustomMaterial(string ts)
{
uint simobjectid = resolveobject(ts);
return (CustomMaterial) Omni.self.getSimObject(simobjectid,typeof(CustomMaterial));
}
/// <summary>
///
/// </summary>
/// <param name="ts"></param>
/// <returns></returns>
public static implicit operator int( CustomMaterial ts)
{
return (int)ts._iID;
}
/// <summary>
///
/// </summary>
/// <param name="simobjectid"></param>
/// <returns></returns>
public static implicit operator CustomMaterial(int simobjectid)
{
return (CustomMaterial) Omni.self.getSimObject((uint)simobjectid,typeof(CustomMaterial));
}
/// <summary>
///
/// </summary>
/// <param name="ts"></param>
/// <returns></returns>
public static implicit operator uint( CustomMaterial ts)
{
return ts._iID;
}
/// <summary>
///
/// </summary>
/// <returns></returns>
public static implicit operator CustomMaterial(uint simobjectid)
{
return (CustomMaterial) Omni.self.getSimObject(simobjectid,typeof(CustomMaterial));
}
#endregion
}}
| 29.985294
| 122
| 0.530652
|
[
"MIT",
"Unlicense"
] |
RichardRanft/OmniEngine.Net
|
Templates/C#-Full-Ded/WinterLeaf.Demo.Full.Dedicated/Models.User/Extendable/CustomMaterial.cs
| 3,943
|
C#
|
// <copyright file="Cauchy.cs" company="Math.NET">
// Math.NET Numerics, part of the Math.NET Project
// http://numerics.mathdotnet.com
// http://github.com/mathnet/mathnet-numerics
//
// Copyright (c) 2009-2013 Math.NET
//
// 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.
// </copyright>
using System;
using System.Collections.Generic;
using MathNet.Numerics.Properties;
using MathNet.Numerics.Random;
using MathNet.Numerics.Threading;
namespace MathNet.Numerics.Distributions
{
/// <summary>
/// Continuous Univariate Cauchy distribution.
/// The Cauchy distribution is a symmetric continuous probability distribution. For details about this distribution, see
/// <a href="http://en.wikipedia.org/wiki/Cauchy_distribution">Wikipedia - Cauchy distribution</a>.
/// </summary>
public class Cauchy : IContinuousDistribution
{
System.Random _random;
readonly double _location;
readonly double _scale;
/// <summary>
/// Initializes a new instance of the <see cref="Cauchy"/> class with the location parameter set to 0 and the scale parameter set to 1
/// </summary>
public Cauchy() : this(0, 1)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="Cauchy"/> class.
/// </summary>
/// <param name="location">The location (x0) of the distribution.</param>
/// <param name="scale">The scale (γ) of the distribution. Range: γ > 0.</param>
public Cauchy(double location, double scale)
{
if (!IsValidParameterSet(location, scale))
{
throw new ArgumentException(Resources.InvalidDistributionParameters);
}
_random = SystemRandomSource.Default;
_location = location;
_scale = scale;
}
/// <summary>
/// Initializes a new instance of the <see cref="Cauchy"/> class.
/// </summary>
/// <param name="location">The location (x0) of the distribution.</param>
/// <param name="scale">The scale (γ) of the distribution. Range: γ > 0.</param>
/// <param name="randomSource">The random number generator which is used to draw random samples.</param>
public Cauchy(double location, double scale, System.Random randomSource)
{
if (!IsValidParameterSet(location, scale))
{
throw new ArgumentException(Resources.InvalidDistributionParameters);
}
_random = randomSource ?? SystemRandomSource.Default;
_location = location;
_scale = scale;
}
/// <summary>
/// A string representation of the distribution.
/// </summary>
/// <returns>a string representation of the distribution.</returns>
public override string ToString()
{
return "Cauchy(x0 = " + _location + ", γ = " + _scale + ")";
}
/// <summary>
/// Tests whether the provided values are valid parameters for this distribution.
/// </summary>
/// <param name="location">The location (x0) of the distribution.</param>
/// <param name="scale">The scale (γ) of the distribution. Range: γ > 0.</param>
public static bool IsValidParameterSet(double location, double scale)
{
return scale > 0.0 && !double.IsNaN(location);
}
/// <summary>
/// Gets the location (x0) of the distribution.
/// </summary>
public double Location => _location;
/// <summary>
/// Gets the scale (γ) of the distribution. Range: γ > 0.
/// </summary>
public double Scale => _scale;
/// <summary>
/// Gets or sets the random number generator which is used to draw random samples.
/// </summary>
public System.Random RandomSource
{
get => _random;
set => _random = value ?? SystemRandomSource.Default;
}
/// <summary>
/// Gets the mean of the distribution.
/// </summary>
public double Mean => throw new NotSupportedException();
/// <summary>
/// Gets the variance of the distribution.
/// </summary>
public double Variance => throw new NotSupportedException();
/// <summary>
/// Gets the standard deviation of the distribution.
/// </summary>
public double StdDev => throw new NotSupportedException();
/// <summary>
/// Gets the entropy of the distribution.
/// </summary>
public double Entropy => Math.Log(4.0*Constants.Pi*_scale);
/// <summary>
/// Gets the skewness of the distribution.
/// </summary>
public double Skewness => throw new NotSupportedException();
/// <summary>
/// Gets the mode of the distribution.
/// </summary>
public double Mode => _location;
/// <summary>
/// Gets the median of the distribution.
/// </summary>
public double Median => _location;
/// <summary>
/// Gets the minimum of the distribution.
/// </summary>
public double Minimum => double.NegativeInfinity;
/// <summary>
/// Gets the maximum of the distribution.
/// </summary>
public double Maximum => double.PositiveInfinity;
/// <summary>
/// Computes the probability density of the distribution (PDF) at x, i.e. ∂P(X ≤ x)/∂x.
/// </summary>
/// <param name="x">The location at which to compute the density.</param>
/// <returns>the density at <paramref name="x"/>.</returns>
/// <seealso cref="PDF"/>
public double Density(double x)
{
return 1.0/(Constants.Pi*_scale*(1.0 + (((x - _location)/_scale)*((x - _location)/_scale))));
}
/// <summary>
/// Computes the log probability density of the distribution (lnPDF) at x, i.e. ln(∂P(X ≤ x)/∂x).
/// </summary>
/// <param name="x">The location at which to compute the log density.</param>
/// <returns>the log density at <paramref name="x"/>.</returns>
/// <seealso cref="PDFLn"/>
public double DensityLn(double x)
{
return -Math.Log(Constants.Pi*_scale*(1.0 + (((x - _location)/_scale)*((x - _location)/_scale))));
}
/// <summary>
/// Computes the cumulative distribution (CDF) of the distribution at x, i.e. P(X ≤ x).
/// </summary>
/// <param name="x">The location at which to compute the cumulative distribution function.</param>
/// <returns>the cumulative distribution at location <paramref name="x"/>.</returns>
/// <seealso cref="CDF"/>
public double CumulativeDistribution(double x)
{
return ((1.0/Constants.Pi)*Math.Atan((x - _location)/_scale)) + 0.5;
}
/// <summary>
/// Computes the inverse of the cumulative distribution function (InvCDF) for the distribution
/// at the given probability. This is also known as the quantile or percent point function.
/// </summary>
/// <param name="p">The location at which to compute the inverse cumulative density.</param>
/// <returns>the inverse cumulative density at <paramref name="p"/>.</returns>
/// <seealso cref="InvCDF"/>
public double InverseCumulativeDistribution(double p)
{
return p <= 0.0 ? double.NegativeInfinity : p >= 1.0 ? double.PositiveInfinity
: _location + _scale*Math.Tan((p - 0.5)*Constants.Pi);
}
/// <summary>
/// Draws a random sample from the distribution.
/// </summary>
/// <returns>A random number from this distribution.</returns>
public double Sample()
{
return SampleUnchecked(_random, _location, _scale);
}
/// <summary>
/// Fills an array with samples generated from the distribution.
/// </summary>
public void Samples(double[] values)
{
SamplesUnchecked(_random, values, _location, _scale);
}
/// <summary>
/// Generates a sequence of samples from the Cauchy distribution.
/// </summary>
/// <returns>a sequence of samples from the distribution.</returns>
public IEnumerable<double> Samples()
{
return SamplesUnchecked(_random, _location, _scale);
}
static double SampleUnchecked(System.Random rnd, double location, double scale)
{
return location + scale*Math.Tan(Constants.Pi*(rnd.NextDouble() - 0.5));
}
static void SamplesUnchecked(System.Random rnd, double[] values, double location, double scale)
{
rnd.NextDoubles(values);
CommonParallel.For(0, values.Length, 4096, (a, b) =>
{
for (int i = a; i < b; i++)
{
values[i] = location + scale*Math.Tan(Constants.Pi*(values[i] - 0.5));
}
});
}
static IEnumerable<double> SamplesUnchecked(System.Random rnd, double location, double scale)
{
while (true)
{
yield return location + scale*Math.Tan(Constants.Pi*(rnd.NextDouble() - 0.5));
}
}
/// <summary>
/// Computes the probability density of the distribution (PDF) at x, i.e. ∂P(X ≤ x)/∂x.
/// </summary>
/// <param name="location">The location (x0) of the distribution.</param>
/// <param name="scale">The scale (γ) of the distribution. Range: γ > 0.</param>
/// <param name="x">The location at which to compute the density.</param>
/// <returns>the density at <paramref name="x"/>.</returns>
/// <seealso cref="Density"/>
public static double PDF(double location, double scale, double x)
{
if (scale <= 0.0)
{
throw new ArgumentException(Resources.InvalidDistributionParameters);
}
return 1.0/(Constants.Pi*scale*(1.0 + (((x - location)/scale)*((x - location)/scale))));
}
/// <summary>
/// Computes the log probability density of the distribution (lnPDF) at x, i.e. ln(∂P(X ≤ x)/∂x).
/// </summary>
/// <param name="location">The location (x0) of the distribution.</param>
/// <param name="scale">The scale (γ) of the distribution. Range: γ > 0.</param>
/// <param name="x">The location at which to compute the density.</param>
/// <returns>the log density at <paramref name="x"/>.</returns>
/// <seealso cref="DensityLn"/>
public static double PDFLn(double location, double scale, double x)
{
if (scale <= 0.0)
{
throw new ArgumentException(Resources.InvalidDistributionParameters);
}
return -Math.Log(Constants.Pi*scale*(1.0 + (((x - location)/scale)*((x - location)/scale))));
}
/// <summary>
/// Computes the cumulative distribution (CDF) of the distribution at x, i.e. P(X ≤ x).
/// </summary>
/// <param name="x">The location at which to compute the cumulative distribution function.</param>
/// <param name="location">The location (x0) of the distribution.</param>
/// <param name="scale">The scale (γ) of the distribution. Range: γ > 0.</param>
/// <returns>the cumulative distribution at location <paramref name="x"/>.</returns>
/// <seealso cref="CumulativeDistribution"/>
public static double CDF(double location, double scale, double x)
{
if (scale <= 0.0)
{
throw new ArgumentException(Resources.InvalidDistributionParameters);
}
return Math.Atan((x - location)/scale)/Constants.Pi + 0.5;
}
/// <summary>
/// Computes the inverse of the cumulative distribution function (InvCDF) for the distribution
/// at the given probability. This is also known as the quantile or percent point function.
/// </summary>
/// <param name="p">The location at which to compute the inverse cumulative density.</param>
/// <param name="location">The location (x0) of the distribution.</param>
/// <param name="scale">The scale (γ) of the distribution. Range: γ > 0.</param>
/// <returns>the inverse cumulative density at <paramref name="p"/>.</returns>
/// <seealso cref="InverseCumulativeDistribution"/>
public static double InvCDF(double location, double scale, double p)
{
if (scale <= 0.0)
{
throw new ArgumentException(Resources.InvalidDistributionParameters);
}
return p <= 0.0 ? double.NegativeInfinity : p >= 1.0 ? double.PositiveInfinity
: location + scale*Math.Tan((p - 0.5)*Constants.Pi);
}
/// <summary>
/// Generates a sample from the distribution.
/// </summary>
/// <param name="rnd">The random number generator to use.</param>
/// <param name="location">The location (x0) of the distribution.</param>
/// <param name="scale">The scale (γ) of the distribution. Range: γ > 0.</param>
/// <returns>a sample from the distribution.</returns>
public static double Sample(System.Random rnd, double location, double scale)
{
if (scale <= 0.0)
{
throw new ArgumentException(Resources.InvalidDistributionParameters);
}
return SampleUnchecked(rnd, location, scale);
}
/// <summary>
/// Generates a sequence of samples from the distribution.
/// </summary>
/// <param name="rnd">The random number generator to use.</param>
/// <param name="location">The location (x0) of the distribution.</param>
/// <param name="scale">The scale (γ) of the distribution. Range: γ > 0.</param>
/// <returns>a sequence of samples from the distribution.</returns>
public static IEnumerable<double> Samples(System.Random rnd, double location, double scale)
{
if (scale <= 0.0)
{
throw new ArgumentException(Resources.InvalidDistributionParameters);
}
return SamplesUnchecked(rnd, location, scale);
}
/// <summary>
/// Fills an array with samples generated from the distribution.
/// </summary>
/// <param name="rnd">The random number generator to use.</param>
/// <param name="values">The array to fill with the samples.</param>
/// <param name="location">The location (x0) of the distribution.</param>
/// <param name="scale">The scale (γ) of the distribution. Range: γ > 0.</param>
/// <returns>a sequence of samples from the distribution.</returns>
public static void Samples(System.Random rnd, double[] values, double location, double scale)
{
if (scale <= 0.0)
{
throw new ArgumentException(Resources.InvalidDistributionParameters);
}
SamplesUnchecked(rnd, values, location, scale);
}
/// <summary>
/// Generates a sample from the distribution.
/// </summary>
/// <param name="location">The location (x0) of the distribution.</param>
/// <param name="scale">The scale (γ) of the distribution. Range: γ > 0.</param>
/// <returns>a sample from the distribution.</returns>
public static double Sample(double location, double scale)
{
if (scale <= 0.0)
{
throw new ArgumentException(Resources.InvalidDistributionParameters);
}
return SampleUnchecked(SystemRandomSource.Default, location, scale);
}
/// <summary>
/// Generates a sequence of samples from the distribution.
/// </summary>
/// <param name="location">The location (x0) of the distribution.</param>
/// <param name="scale">The scale (γ) of the distribution. Range: γ > 0.</param>
/// <returns>a sequence of samples from the distribution.</returns>
public static IEnumerable<double> Samples(double location, double scale)
{
if (scale <= 0.0)
{
throw new ArgumentException(Resources.InvalidDistributionParameters);
}
return SamplesUnchecked(SystemRandomSource.Default, location, scale);
}
/// <summary>
/// Fills an array with samples generated from the distribution.
/// </summary>
/// <param name="values">The array to fill with the samples.</param>
/// <param name="location">The location (x0) of the distribution.</param>
/// <param name="scale">The scale (γ) of the distribution. Range: γ > 0.</param>
/// <returns>a sequence of samples from the distribution.</returns>
public static void Samples(double[] values, double location, double scale)
{
if (scale <= 0.0)
{
throw new ArgumentException(Resources.InvalidDistributionParameters);
}
SamplesUnchecked(SystemRandomSource.Default, values, location, scale);
}
}
}
| 41.441964
| 142
| 0.588764
|
[
"MIT"
] |
ChristopherSchubert/com.appalachia.dotnet.mdabros.sharp-learning
|
src/Numerics/Distributions/Cauchy.cs
| 18,625
|
C#
|
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using MassTransit;
using System;
using Cesxhin.AnimeSaturn.Application.Generic;
using NLog;
using Cesxhin.AnimeSaturn.Application.CronJob;
using Quartz;
using Cesxhin.AnimeSaturn.Application.CheckManager.Interfaces;
using Cesxhin.AnimeSaturn.Application.CheckManager;
namespace Cesxhin.AnimeSaturn.UpdateService
{
public class Program
{
public static void Main(string[] args)
{
CreateHostBuilder(args).Build().Run();
}
public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.ConfigureServices((hostContext, services) =>
{
//rabbit
services.AddMassTransit(
x =>
{
x.UsingRabbitMq((context, cfg) =>
{
cfg.Host(
Environment.GetEnvironmentVariable("ADDRESS_RABBIT") ?? "localhost",
"/",
credentials =>
{
credentials.Username(Environment.GetEnvironmentVariable("USERNAME_RABBIT") ?? "guest");
credentials.Password(Environment.GetEnvironmentVariable("PASSWORD_RABBIT") ?? "guest");
});
});
});
//setup nlog
var level = Environment.GetEnvironmentVariable("LOG_LEVEL").ToLower() ?? "info";
LogLevel logLevel = NLogManager.GetLevel(level);
NLogManager.Configure(logLevel);
//select service between anime or manga
var serviceSelect = Environment.GetEnvironmentVariable("SELECT_SERVICE") ?? "anime";
//cronjob for check health
services.AddQuartz(q =>
{
q.UseMicrosoftDependencyInjectionJobFactory();
q.ScheduleJob<HealthJob>(trigger => trigger
.StartNow()
.WithDailyTimeIntervalSchedule(x => x.WithIntervalInSeconds(60)), job => job.WithIdentity("update-"+ serviceSelect));
q.ScheduleJob<SpaceDiskJob>(trigger => trigger
.StartNow()
.WithDailyTimeIntervalSchedule(x => x.WithIntervalInSeconds(60)));
});
services.AddQuartzHostedService(q => q.WaitForJobsToComplete = true);
if(serviceSelect.ToLower().Contains("anime"))
services.AddTransient<IUpdate, UpdateAnime>();
else
services.AddTransient<IUpdate, UpdateManga>();
services.AddHostedService<Worker>();
});
}
}
| 41.712329
| 145
| 0.5133
|
[
"MIT"
] |
GamingBunker/AnimePlex
|
src/Cesxhin.AnimeSaturn/Cesxhin.AnimeSaturn.UpdateService/Program.cs
| 3,045
|
C#
|
/* _BEGIN_TEMPLATE_
{
"id": "BT_018",
"name": [
"幽光鱼竿",
"Underlight Angling Rod"
],
"text": [
"在你的英雄攻击后,随机将一张鱼人牌置入你的手牌。",
"After your Hero attacks, add a random Murloc to your hand."
],
"CardClass": "PALADIN",
"type": "WEAPON",
"cost": 3,
"rarity": "EPIC",
"set": "BLACK_TEMPLE",
"collectible": true,
"dbfId": 56443
}
_END_TEMPLATE_ */
namespace HREngine.Bots
{
class Sim_BT_018 : SimTemplate
{
}
}
| 16.142857
| 64
| 0.588496
|
[
"MIT"
] |
chi-rei-den/Silverfish
|
cards/BLACK_TEMPLE/BT/Sim_BT_018.cs
| 508
|
C#
|
using FBLASocialApp.DataService;
using System;
using Xamarin.Forms;
using Xamarin.Forms.Internals;
using Xamarin.Forms.Xaml;
namespace FBLASocialApp.Views.Social
{
/// <summary>
/// Page to show the suggestion page details.
/// </summary>
[Preserve(AllMembers = true)]
[XamlCompilation(XamlCompilationOptions.Compile)]
public partial class SuggestionPage
{
/// <summary>
/// Initializes a new instance of the <see cref="SuggestionPage" /> class.
/// </summary>
public SuggestionPage()
{
InitializeComponent();
this.BindingContext = SuggestionDataService.Instance.SuggestionViewModel;
}
/// <summary>
/// Invoked when view size is changed.
/// </summary>
/// <param name="width">The Width</param>
/// <param name="height">The Height</param>
protected override void OnSizeAllocated(double width, double height)
{
base.OnSizeAllocated(width, height);
if (width > height)
{
if (Search.IsVisible)
{
Search.WidthRequest = width;
}
}
}
/// <summary>
/// Invoked when search button is clicked.
/// </summary>
/// <param name="sender">The Sender</param>
/// <param name="e">Event Args</param>
private void SearchButton_Clicked(object sender, EventArgs e)
{
this.Search.IsVisible = true;
this.Title.IsVisible = false;
this.SearchButton.IsVisible = false;
if (this.TitleView != null)
{
double opacity;
// Animating Width of the search box, from 0 to full width when it added to the view.
var expandAnimation = new Animation(
property =>
{
Search.WidthRequest = property;
opacity = property / TitleView.Width;
Search.Opacity = opacity;
}, 0, TitleView.Width, Easing.Linear);
expandAnimation.Commit(Search, "Expand", 16, 250, Easing.Linear, (p, q) => this.SearchExpandAnimationCompleted());
}
}
/// <summary>
/// Invoked when back to title button is clicked.
/// </summary>
/// <param name="sender">The Sender</param>
/// <param name="e">Event Args</param>
private void BackToTitle_Clicked(object sender, EventArgs e)
{
this.SearchButton.IsVisible = true;
if (this.TitleView != null)
{
double opacity;
// Animating Width of the search box, from full width to 0 before it removed from view.
var shrinkAnimation = new Animation(property =>
{
Search.WidthRequest = property;
opacity = property / TitleView.Width;
Search.Opacity = opacity;
},
TitleView.Width, 0, Easing.Linear);
shrinkAnimation.Commit(Search, "Shrink", 16, 250, Easing.Linear, (p, q) => this.SearchBoxAnimationCompleted());
}
SearchEntry.Text = string.Empty;
}
/// <summary>
/// Invokes when search box Animation completed.
/// </summary>
private void SearchBoxAnimationCompleted()
{
this.Search.IsVisible = false;
this.Title.IsVisible = true;
}
/// <summary>
/// Invokes when search expand Animation completed.
/// </summary>
private void SearchExpandAnimationCompleted()
{
this.SearchEntry.Focus();
}
}
}
| 34.725664
| 131
| 0.517584
|
[
"MIT"
] |
eahs/FBLA-SocialApp
|
Source/FBLASocialApp/FBLASocialApp/FBLASocialApp/Views/Social/SuggestionPage.xaml.cs
| 3,926
|
C#
|
using System;
using System.Collections.Generic;
using System.Text;
namespace akarnokd.reactive_extensions
{
/// <summary>
/// Signals an exception immediately.
/// </summary>
internal sealed class CompletableError : ICompletableSource
{
readonly Exception error;
public CompletableError(Exception error)
{
this.error = error;
}
public void Subscribe(ICompletableObserver observer)
{
observer.Error(error);
}
}
}
| 20.8
| 63
| 0.623077
|
[
"Apache-2.0"
] |
akarnokd/reactive-extensions
|
reactive-extensions/completable/CompletableError.cs
| 522
|
C#
|
namespace Intelligob.Escritorio.Vistas.Interfaces
{
public interface IVista
{
object DataContext
{
get;
set;
}
}
}
| 13.615385
| 49
| 0.502825
|
[
"CC0-1.0"
] |
jmbarberan/gobman
|
Intelligob/Vistas/Interfaces/IVista.cs
| 179
|
C#
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Codeless.Ecma {
public class WeakKeyedItem : IEquatable<WeakKeyedItem> {
private readonly WeakReference reference;
private readonly int hashCode;
protected WeakKeyedItem() {
reference = new WeakReference(this);
hashCode = base.GetHashCode();
}
internal WeakKeyedItem(object target) {
Guard.ArgumentNotNull(target, "target");
reference = new WeakReference(target);
hashCode = target.GetHashCode();
}
protected internal bool IsTargetAlive {
get { return reference.IsAlive; }
}
protected internal object Target {
get { return reference.Target; }
}
public bool Equals(WeakKeyedItem other) {
if (other == null || !reference.IsAlive || !other.reference.IsAlive) {
return false;
}
return reference.Target.Equals(other.reference.Target);
}
public override int GetHashCode() {
return hashCode;
}
}
}
| 24.5
| 76
| 0.670554
|
[
"MIT"
] |
misonou/codeless-ecma
|
src/Codeless.Ecma/WeakKeyedItem.cs
| 1,031
|
C#
|
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
// Runtime Version:4.0.30319.42000
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
namespace Faker.Resources.Names {
using System;
/// <summary>
/// A strongly-typed resource class, for looking up localized strings, etc.
/// </summary>
// This class was auto-generated by the StronglyTypedResourceBuilder
// class via a tool like ResGen or Visual Studio.
// To add or remove a member, edit your .ResX file then rerun ResGen
// with the /str option, or rebuild your VS project.
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "15.0.0.0")]
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
internal class EnglishNames {
private static global::System.Resources.ResourceManager resourceMan;
private static global::System.Globalization.CultureInfo resourceCulture;
[global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
internal EnglishNames() {
}
/// <summary>
/// Returns the cached ResourceManager instance used by this class.
/// </summary>
[global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
internal static global::System.Resources.ResourceManager ResourceManager {
get {
if (object.ReferenceEquals(resourceMan, null)) {
global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("Faker.Resources.Names.EnglishNames", typeof(EnglishNames).Assembly);
resourceMan = temp;
}
return resourceMan;
}
}
/// <summary>
/// Overrides the current thread's CurrentUICulture property for all
/// resource lookups using this strongly typed resource class.
/// </summary>
[global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
internal static global::System.Globalization.CultureInfo Culture {
get {
return resourceCulture;
}
set {
resourceCulture = value;
}
}
/// <summary>
/// Looks up a localized string similar to Aaliyah; Aaron; Abagail; Abbey; Abbie; Abbigail; Abby; Abdiel; Abdul; Abdullah; Abe; Abel; Abelardo; Abigail; Abigale; Abigayle; Abner; Abraham; Ada; Adah; Adalberto; Adaline; Adam; Adan; Addie; Addison; Adela; Adelbert; Adele; Adelia; Adeline; Adell; Adella; Adelle; Aditya; Adolf; Adolfo; Adolph; Adolphus; Adonis; Adrain; Adrian; Adriana; Adrianna; Adriel; Adrien; Adrienne; Afton; Aglae; Agnes; Agustin; Agustina; Ahmad; Ahmed; Aida; Aidan; Aiden; Aileen; Aimee; Aisha; Aiyana; Akeem; Al; Alaina; Alan; Alana [rest of string was truncated]";.
/// </summary>
internal static string FirstName {
get {
return ResourceManager.GetString("FirstName", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Abbott; Abernathy; Abshire; Adams; Altenwerth; Anderson; Ankunding; Armstrong; Auer; Aufderhar; Bahringer; Bailey; Balistreri; Barrows; Bartell; Bartoletti; Barton; Bashirian; Batz; Bauch; Baumbach; Bayer; Beahan; Beatty; Bechtelar; Becker; Bednar; Beer; Beier; Berge; Bergnaum; Bergstrom; Bernhard; Bernier; Bins; Blanda; Blick; Block; Bode; Boehm; Bogan; Bogisich; Borer; Bosco; Botsford; Boyer; Boyle; Bradtke; Brakus; Braun; Breitenberg; Brekke; Brown; Bruen; Buckridge; Carroll; Carter; Cartwright; Casper; [rest of string was truncated]";.
/// </summary>
internal static string LastName {
get {
return ResourceManager.GetString("LastName", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Mr.;Mrs.;Ms.;Miss;Dr..
/// </summary>
internal static string Prefix {
get {
return ResourceManager.GetString("Prefix", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Jr.;Sr.;I;II;III;IV;V;MD;DDS;PhD;DVM.
/// </summary>
internal static string Suffix {
get {
return ResourceManager.GetString("Suffix", resourceCulture);
}
}
}
}
| 50.35
| 604
| 0.61569
|
[
"MIT"
] |
arsalanvaloojerdi/faker-cs
|
src/Faker/Resources/Names/EnglishNames.Designer.cs
| 5,037
|
C#
|
using System.Collections;
using Characters;
using NUnit.Framework;
using UnityEngine;
using UnityEngine.TestTools;
namespace Tests {
public class PlayerTest {
[UnityTest]
public IEnumerator InitalizePlayer() {
GameObject player = MonoBehaviour.Instantiate(Resources.Load<GameObject>("Prefabs/Player/Player"));
yield return new WaitForEndOfFrame();
Assert.NotNull(player.GetComponent<ICharacter>());
Assert.NotNull(player.GetComponent<IPhysicsCharacter>());
Assert.NotNull(player.GetComponent<IPhysicsCharacter>().getRigidbody());
Assert.NotNull(player.GetComponent<IPhysicsCharacter>().getStats());
Assert.NotNull(player.GetComponent<IPhysicsCharacter>().getMovement());
Assert.NotNull(player.GetComponent<IPhysicsCharacter>().getHealthComponent());
Object.Destroy(player);
}
}
}
| 37.52
| 111
| 0.676972
|
[
"BSD-3-Clause"
] |
Mu-L/Erbium
|
Erbium/Assets/Tests/PlayerTest.cs
| 940
|
C#
|
//
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT license. See LICENSE.txt file in the project root for full license information.
//
namespace Lomo.Commerce.DataModels
{
using System.Xml.Serialization;
/// <summary>
/// Represents the card brands supported by the Commerce service.
/// </summary>
public enum CardBrand
{
/// <summary>
/// Indicates the card is of an unknown brand.
/// </summary>
[XmlEnum("0")]
Unknown = 0,
/// <summary>
/// Indicates the card is an American Express card.
/// </summary>
[XmlEnum("3")]
AmericanExpress = 3,
/// <summary>
/// Indicates the card is a Visa card.
/// </summary>
[XmlEnum("4")]
Visa = 4,
/// <summary>
/// Indicates the card is a MasterCard.
/// </summary>
[XmlEnum("5")]
MasterCard = 5
}
}
| 25.526316
| 105
| 0.547423
|
[
"MIT"
] |
BOONRewardsInc/rewards
|
Commerce/DataModels/Cards/CardBrand.cs
| 970
|
C#
|
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// アセンブリに関する一般情報は以下の属性セットをとおして制御されます。
// アセンブリに関連付けられている情報を変更するには、
// これらの属性値を変更してください。
[assembly: AssemblyTitle("HelloWorld")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("HelloWorld")]
[assembly: AssemblyCopyright("Copyright © 2015")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// ComVisible を false に設定すると、その型はこのアセンブリ内で COM コンポーネントから
// 参照不可能になります。COM からこのアセンブリ内の型にアクセスする場合は、
// その型の ComVisible 属性を true に設定してください。
[assembly: ComVisible(false)]
// このプロジェクトが COM に公開される場合、次の GUID が typelib の ID になります
[assembly: Guid("07c9fa6c-acb2-43ac-90e1-23008b6708aa")]
// アセンブリのバージョン情報は次の 4 つの値で構成されています:
//
// メジャー バージョン
// マイナー バージョン
// ビルド番号
// Revision
//
// すべての値を指定するか、下のように '*' を使ってビルドおよびリビジョン番号を
// 既定値にすることができます:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| 29.108108
| 57
| 0.743733
|
[
"MIT"
] |
malaybaku/QiMessagingDotNet
|
QiMessaging/HelloWorld/Properties/AssemblyInfo.cs
| 1,646
|
C#
|
/*
* Copyright (c) Contributors, http://aurora-sim.org/
* See CONTRIBUTORS.TXT for a full list of copyright holders.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the Aurora-Sim Project nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using Aurora.Framework;
using OpenSim.Region.Framework.Interfaces;
namespace Aurora.ScriptEngine.AuroraDotNetEngine.MiniModule
{
internal class LOParcel : MarshalByRefObject, IParcel
{
private readonly int m_parcelID;
private readonly IScene m_scene;
public LOParcel(IScene m_scene, int m_parcelID)
{
this.m_scene = m_scene;
this.m_parcelID = m_parcelID;
}
#region IParcel Members
public string Name
{
get { return GetLO().LandData.Name; }
set { GetLO().LandData.Name = value; }
}
public string Description
{
get { return GetLO().LandData.Description; }
set { GetLO().LandData.Description = value; }
}
public ISocialEntity Owner
{
get { throw new NotImplementedException(); }
set { throw new NotImplementedException(); }
}
#endregion
private ILandObject GetLO()
{
IParcelManagementModule parcelManagement = m_scene.RequestModuleInterface<IParcelManagementModule>();
if (parcelManagement != null)
{
return parcelManagement.GetLandObject(m_parcelID);
}
return null;
}
}
}
| 39.168831
| 114
| 0.659814
|
[
"BSD-3-Clause"
] |
BillyWarrhol/Aurora-Sim
|
Aurora/AuroraDotNetEngine/CompilerTools/Minimodule/LOParcel.cs
| 3,016
|
C#
|
using Hotel.Business.Interfaces;
using Hotel.Domain.Models;
using Hotel.Domain.ValueObjects;
using Hotel.Repository.Interfaces;
namespace Hotel.Business.Business
{
/// <summary>
/// Classe responsável por aplicar as regras de negócio do Hotel.
/// </summary>
public class HotelBusiness : IHotelBusiness
{
private readonly IRepository<RoomEntity> _roomRepository;
public HotelBusiness(IRepository<RoomEntity> roomRepository)
{
_roomRepository = roomRepository;
}
/// <summary>
/// Obtem as informações do Hotel. No caso, as informações dos quartos cadastrados no mesmo.
/// </summary>
/// <returns></returns>
public HotelEntity GetInfoHotel()
{
var infoHotel = new HotelEntity
{
QuantityRoom = _roomRepository.GetAll().Count,
QuantityRoomBlock = _roomRepository.Find(x => x.Status == RoomStatus.Lock).Count,
QuantityRoomBusy = _roomRepository.Find(x => x.Status == RoomStatus.Busy).Count
};
return infoHotel;
}
}
}
| 31.611111
| 100
| 0.622144
|
[
"MIT"
] |
mateusggeracino/Hotel
|
source/Hotel.Business/Business/HotelBusiness.cs
| 1,146
|
C#
|
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("SpeedUnits")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("SpeedUnits")]
[assembly: AssemblyCopyright("Copyright © 2017")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("72b9167f-9ba2-4e4b-820a-f4c8e59b66bb")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| 37.648649
| 84
| 0.744436
|
[
"MIT"
] |
akaraatanasov/SoftUni
|
Technologies Fundamentals/Programming Fundamentals/Data Types - Exercises/SpeedUnits/Properties/AssemblyInfo.cs
| 1,396
|
C#
|
// 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.
#if WINFORMS_NAMESPACE
namespace System.Windows.Forms.Internal
#elif DRAWING_NAMESPACE
namespace System.Drawing.Internal
#else
namespace System.Experimental.Gdi
#endif
{
/// <devdoc>
/// Specifies the map-mode of a device context.
/// </devdoc>
#if WINFORMS_PUBLIC_GRAPHICS_LIBRARY
public
#else
internal
#endif
enum DeviceContextMapMode
{
Text = 1, // MM_TEXT
LoMetric = 2,
HiMetric = 3,
LoEnglish = 4,
HiEnglish = 5,
Twips = 6,
Isotropic = 7,
Anisotropic = 8
/*
Mapping Mode Logical Unit x-axis y-axis
MM_TEXT Pixel Right Down
MM_LOMETRIC 0.1 mm Right Up
MM_HIMETRIC 0.01 mm Right Up
MM_LOENGLISH 0.01 in. Right Up
MM_HIENGLISH 0.001 in. Right Up
MM_TWIPS 1/1440 in. Right Up
MM_ISOTROPIC Arbitrary (x = y) Selectable Selectable
MM_ANISOTROPIC Arbitrary (x !=y) Selectable Selectable
*/
}
}
| 31.673913
| 71
| 0.524365
|
[
"MIT"
] |
0xflotus/winforms
|
src/System.Windows.Forms/src/misc/GDI/DeviceContextMapMode.cs
| 1,457
|
C#
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using CSharpGL;
namespace c12d03_RaycastLine
{
partial class CubeNode
{
private const string vertexCode = @"
#version 150
in vec3 inPosition;
uniform mat4 mvpMat;
void main() {
gl_Position = mvpMat * vec4(inPosition, 1.0);
}
";
private const string fragmentCode = @"
#version 150
uniform vec4 color = vec4(1, 1, 1, 1); // default: red color.
uniform bool halfTransparent = true;
out vec4 outColor;
void main() {
if (halfTransparent) {
if (int(gl_FragCoord.x + gl_FragCoord.y) % 2 == 1) discard;
}
outColor = color;
}
";
}
}
| 16.047619
| 67
| 0.658754
|
[
"MIT"
] |
AugusZhan/CSharpGL
|
OpenGLviaCSharp/c12d03_RaycastLine/CubeNode.shaders.cs
| 676
|
C#
|
// ------------------------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License in the project root for license information.
// ------------------------------------------------------------------------------
// **NOTE** This file was generated by a tool and any changes will be overwritten.
// Template Source: Templates\CSharp\Requests\EntityRequestBuilder.cs.tt
namespace Microsoft.Graph
{
using System;
using System.Collections.Generic;
using System.IO;
/// <summary>
/// The type MacOSCustomConfigurationRequestBuilder.
/// </summary>
public partial class MacOSCustomConfigurationRequestBuilder : DeviceConfigurationRequestBuilder, IMacOSCustomConfigurationRequestBuilder
{
/// <summary>
/// Constructs a new MacOSCustomConfigurationRequestBuilder.
/// </summary>
/// <param name="requestUrl">The URL for the built request.</param>
/// <param name="client">The <see cref="IBaseClient"/> for handling requests.</param>
public MacOSCustomConfigurationRequestBuilder(
string requestUrl,
IBaseClient client)
: base(requestUrl, client)
{
}
/// <summary>
/// Builds the request.
/// </summary>
/// <returns>The built request.</returns>
public new IMacOSCustomConfigurationRequest Request()
{
return this.Request(null);
}
/// <summary>
/// Builds the request.
/// </summary>
/// <param name="options">The query and header options for the request.</param>
/// <returns>The built request.</returns>
public new IMacOSCustomConfigurationRequest Request(IEnumerable<Option> options)
{
return new MacOSCustomConfigurationRequest(this.RequestUrl, this.Client, options);
}
}
}
| 36.444444
| 153
| 0.591463
|
[
"MIT"
] |
AzureMentor/msgraph-sdk-dotnet
|
src/Microsoft.Graph/Requests/Generated/MacOSCustomConfigurationRequestBuilder.cs
| 1,968
|
C#
|
// Copyright (C) 2015-2022 The Neo Project.
//
// The neo is free software distributed under the MIT software license,
// see the accompanying file LICENSE in the main directory of the
// project or http://www.opensource.org/licenses/mit-license.php
// for more details.
//
// Redistribution and use in source and binary forms with or without
// modifications are permitted.
using System;
using System.Buffers.Binary;
using System.Numerics;
using System.Runtime.CompilerServices;
using System.Security.Cryptography;
namespace Neo.Cryptography
{
/// <summary>
/// Computes the 128 bits murmur hash for the input data.
/// </summary>
public sealed class Murmur128 : HashAlgorithm
{
private const ulong c1 = 0x87c37b91114253d5;
private const ulong c2 = 0x4cf5ad432745937f;
private const int r1 = 31;
private const int r2 = 33;
private const uint m = 5;
private const uint n1 = 0x52dce729;
private const uint n2 = 0x38495ab5;
private readonly uint seed;
private int length;
public override int HashSize => 128;
private ulong H1 { get; set; }
private ulong H2 { get; set; }
/// <summary>
/// Initializes a new instance of the <see cref="Murmur128"/> class with the specified seed.
/// </summary>
/// <param name="seed">The seed to be used.</param>
public Murmur128(uint seed)
{
this.seed = seed;
Initialize();
}
protected override void HashCore(byte[] array, int ibStart, int cbSize)
{
HashCore(array.AsSpan(ibStart, cbSize));
}
protected override void HashCore(ReadOnlySpan<byte> source)
{
int cbSize = source.Length;
length += cbSize;
int remainder = cbSize & 15;
int alignedLength = cbSize - remainder;
for (int i = 0; i < alignedLength; i += 16)
{
ulong k1 = BinaryPrimitives.ReadUInt64LittleEndian(source[i..]);
k1 *= c1;
k1 = BitOperations.RotateLeft(k1, r1);
k1 *= c2;
H1 ^= k1;
H1 = BitOperations.RotateLeft(H1, 27);
H1 += H2;
H1 = H1 * m + n1;
ulong k2 = BinaryPrimitives.ReadUInt64LittleEndian(source[(i + 8)..]);
k2 *= c2;
k2 = BitOperations.RotateLeft(k2, r2);
k2 *= c1;
H2 ^= k2;
H2 = BitOperations.RotateLeft(H2, 31);
H2 += H1;
H2 = H2 * m + n2;
}
if (remainder > 0)
{
ulong remainingBytesL = 0, remainingBytesH = 0;
switch (remainder)
{
case 15: remainingBytesH ^= (ulong)source[alignedLength + 14] << 48; goto case 14;
case 14: remainingBytesH ^= (ulong)source[alignedLength + 13] << 40; goto case 13;
case 13: remainingBytesH ^= (ulong)source[alignedLength + 12] << 32; goto case 12;
case 12: remainingBytesH ^= (ulong)source[alignedLength + 11] << 24; goto case 11;
case 11: remainingBytesH ^= (ulong)source[alignedLength + 10] << 16; goto case 10;
case 10: remainingBytesH ^= (ulong)source[alignedLength + 9] << 8; goto case 9;
case 9: remainingBytesH ^= (ulong)source[alignedLength + 8] << 0; goto case 8;
case 8: remainingBytesL ^= (ulong)source[alignedLength + 7] << 56; goto case 7;
case 7: remainingBytesL ^= (ulong)source[alignedLength + 6] << 48; goto case 6;
case 6: remainingBytesL ^= (ulong)source[alignedLength + 5] << 40; goto case 5;
case 5: remainingBytesL ^= (ulong)source[alignedLength + 4] << 32; goto case 4;
case 4: remainingBytesL ^= (ulong)source[alignedLength + 3] << 24; goto case 3;
case 3: remainingBytesL ^= (ulong)source[alignedLength + 2] << 16; goto case 2;
case 2: remainingBytesL ^= (ulong)source[alignedLength + 1] << 8; goto case 1;
case 1: remainingBytesL ^= (ulong)source[alignedLength] << 0; break;
}
H2 ^= BitOperations.RotateLeft(remainingBytesH * c2, r2) * c1;
H1 ^= BitOperations.RotateLeft(remainingBytesL * c1, r1) * c2;
}
}
protected override byte[] HashFinal()
{
byte[] buffer = GC.AllocateUninitializedArray<byte>(sizeof(ulong) * 2);
TryHashFinal(buffer, out _);
return buffer;
}
protected override bool TryHashFinal(Span<byte> destination, out int bytesWritten)
{
ulong len = (ulong)length;
H1 ^= len; H2 ^= len;
H1 += H2;
H2 += H1;
H1 = FMix(H1);
H2 = FMix(H2);
H1 += H2;
H2 += H1;
if (BinaryPrimitives.TryWriteUInt64LittleEndian(destination, H1))
BinaryPrimitives.TryWriteUInt64LittleEndian(destination[sizeof(ulong)..], H2);
bytesWritten = Math.Min(destination.Length, sizeof(ulong) * 2);
return bytesWritten == sizeof(ulong) * 2;
}
public override void Initialize()
{
H1 = H2 = seed;
length = 0;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private static ulong FMix(ulong h)
{
h = (h ^ (h >> 33)) * 0xff51afd7ed558ccd;
h = (h ^ (h >> 33)) * 0xc4ceb9fe1a85ec53;
return (h ^ (h >> 33));
}
}
}
| 37.705882
| 102
| 0.540475
|
[
"MIT"
] |
awatin/neo
|
src/neo/Cryptography/Murmur128.cs
| 5,769
|
C#
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace CreateCookies.Model
{
class Recipe
{
private double quantity;
private Ingredient ingredient;
private Product product;
public Recipe(double quantity, Ingredient ingredient, Product product)
{
}
public double Quantity
{
get
{
return quantity;
}
set
{
quantity = value;
}
}
internal Ingredient Ingredient
{
get
{
return ingredient;
}
set
{
ingredient = value;
}
}
internal Product Product
{
get
{
return product;
}
set
{
product = value;
}
}
}
}
| 17.033333
| 77
| 0.423679
|
[
"MIT"
] |
spikk/effective-adventure
|
CreateCookiesSolution/CreateCookies/Model/Recipe.cs
| 1,024
|
C#
|
using System;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Identity.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore;
using MyCompany.Domain.Entities;
namespace MyCompany.Domain {
public class AppDbContext : IdentityDbContext<IdentityUser> {
public AppDbContext(DbContextOptions<AppDbContext> options) : base(options) {
Database.EnsureCreated();
}
//созданеи объектов доменных моделей
public DbSet<TextField> TextFields { get; set; }
public DbSet<ServiceItem> ServiceItems { get; set; }
protected override void OnModelCreating(ModelBuilder modelBuilder) {
base.OnModelCreating(modelBuilder);
modelBuilder.Entity<IdentityRole>().HasData(new IdentityRole {
Id = "44546e06-8719-4ad8-b88a-f271ae9d6eab",
Name = "admin",
NormalizedName = "ADMIN"
});
modelBuilder.Entity<IdentityUser>().HasData(new IdentityUser {
Id = "3b62472e-4f66-49fa-a20f-e7685b9565d8",
UserName = "admin",
NormalizedUserName = "ADMIN",
Email = "my@email.com",
NormalizedEmail = "MY@EMAIL.COM",
EmailConfirmed = true,
PasswordHash = new PasswordHasher<IdentityUser>().HashPassword(null, "superpassword"),
SecurityStamp = string.Empty
});
modelBuilder.Entity<IdentityUserRole<string>>().HasData(new IdentityUserRole<string> {
RoleId = "44546e06-8719-4ad8-b88a-f271ae9d6eab",
UserId = "3b62472e-4f66-49fa-a20f-e7685b9565d8"
});
modelBuilder.Entity<TextField>().HasData(new TextField {
Id = new Guid("63dc8fa6-07ae-4391-8916-e057f71239ce"),
CodeWord = "PageIndex",
Title = "Главная"
});
modelBuilder.Entity<TextField>().HasData(new TextField {
Id = new Guid("70bf165a-700a-4156-91c0-e83fce0a277f"),
CodeWord = "PageServices",
Title = "Наши услуги"
});
modelBuilder.Entity<TextField>().HasData(new TextField {
Id = new Guid("4aa76a4c-c59d-409a-84c1-06e6487a137a"),
CodeWord = "PageContacts",
Title = "Контакты"
});
}
}
}
| 38.1
| 98
| 0.615923
|
[
"Unlicense"
] |
michailnk/forSites
|
sites/MyCompany/Domain/AppDbContext.cs
| 2,344
|
C#
|
// Fill out your copyright notice in the Description page of Project Settings.
using UnrealBuildTool;
using System.Collections.Generic;
public class MomotarouZEROEditorTarget : TargetRules
{
public MomotarouZEROEditorTarget(TargetInfo Target)
{
Type = TargetType.Editor;
}
//
// TargetRules interface.
//
public override void SetupBinaries(
TargetInfo Target,
ref List<UEBuildBinaryConfiguration> OutBuildBinaryConfigurations,
ref List<string> OutExtraModuleNames
)
{
OutExtraModuleNames.AddRange( new string[] { "MomotarouZERO" } );
}
}
| 21.653846
| 78
| 0.772647
|
[
"MIT"
] |
ryutokizaki/MomotaroZeroCpp
|
Source/MomotarouZEROEditor.Target.cs
| 563
|
C#
|
using UnityEngine;
using System.Collections;
#if UNITY_EDITOR_WIN || UNITY_STANDALONE_WIN
public abstract class OVRComposition {
public abstract OVRManager.CompositionMethod CompositionMethod();
public abstract void Update(Camera mainCamera);
public abstract void Cleanup();
public virtual void RecenterPose() { }
protected bool usingLastAttachedNodePose = false;
protected OVRPose lastAttachedNodePose = new OVRPose(); // Sometimes the attach node pose is not readable (lose tracking, low battery, etc.) Use the last pose instead when it happens
internal OVRPose ComputeCameraWorldSpacePose(OVRPlugin.CameraExtrinsics extrinsics)
{
OVRPose worldSpacePose = new OVRPose();
OVRPose trackingSpacePose = new OVRPose();
OVRPose cameraTrackingSpacePose = extrinsics.RelativePose.ToOVRPose();
trackingSpacePose = cameraTrackingSpacePose;
if (extrinsics.AttachedToNode != OVRPlugin.Node.None && OVRPlugin.GetNodePresent(extrinsics.AttachedToNode))
{
if (usingLastAttachedNodePose)
{
Debug.Log("The camera attached node get tracked");
usingLastAttachedNodePose = false;
}
OVRPose attachedNodePose = OVRPlugin.GetNodePose(extrinsics.AttachedToNode, OVRPlugin.Step.Render).ToOVRPose();
lastAttachedNodePose = attachedNodePose;
trackingSpacePose = attachedNodePose * trackingSpacePose;
}
else
{
if (extrinsics.AttachedToNode != OVRPlugin.Node.None)
{
if (!usingLastAttachedNodePose)
{
Debug.LogWarning("The camera attached node could not be tracked, using the last pose");
usingLastAttachedNodePose = true;
}
trackingSpacePose = lastAttachedNodePose * trackingSpacePose;
}
}
worldSpacePose = OVRExtensions.ToWorldSpacePose(trackingSpacePose);
return worldSpacePose;
}
}
#endif
| 31.280702
| 194
| 0.767807
|
[
"MIT"
] |
AIRobolab-unilu/vr-teleop
|
Assets/Oculus/VR/Scripts/Composition/OVRComposition.cs
| 1,783
|
C#
|
// This file may be edited manually or auto-generated using IfcKit at www.buildingsmart-tech.org.
// IFC content is copyright (C) 1996-2018 BuildingSMART International Ltd.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Runtime.InteropServices;
using System.Runtime.Serialization;
using System.Xml.Serialization;
using BuildingSmart.IFC.IfcMeasureResource;
using BuildingSmart.IFC.IfcUtilityResource;
namespace BuildingSmart.IFC.IfcKernel
{
public partial class IfcGroup : IfcObject
{
[InverseProperty("RelatingGroup")]
[Description("Reference to the relationship <em>IfcRelAssignsToGroup</em> that assigns the one to many group members to the <em>IfcGroup</em> object. <blockquote class=\"change-ifc2x4\">IFC4 CHANGE The cardinality has been changed from 1..1 to 0..? in order to allow the exchange of a group concept without having already group members assigned. It now also allows the use of many instances of <em>IfcRelAssignsToGroup</em> to assign the group members. The change has been done with upward compatibility for file based exchange.</blockquote>")]
public ISet<IfcRelAssignsToGroup> IsGroupedBy { get; protected set; }
public IfcGroup(IfcGloballyUniqueId __GlobalId, IfcOwnerHistory __OwnerHistory, IfcLabel? __Name, IfcText? __Description, IfcLabel? __ObjectType)
: base(__GlobalId, __OwnerHistory, __Name, __Description, __ObjectType)
{
this.IsGroupedBy = new HashSet<IfcRelAssignsToGroup>();
}
}
}
| 45.685714
| 553
| 0.797373
|
[
"Unlicense",
"MIT"
] |
BuildingSMART/IfcDoc
|
IfcKit/schemas/IfcKernel/IfcGroup.cs
| 1,599
|
C#
|
namespace ATA_GUI
{
partial class UpdateForm
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(UpdateForm));
this.progressBar1 = new System.Windows.Forms.ProgressBar();
this.labelLog = new System.Windows.Forms.Label();
this.labelWarning = new System.Windows.Forms.Label();
this.SuspendLayout();
//
// progressBar1
//
this.progressBar1.Location = new System.Drawing.Point(43, 35);
this.progressBar1.Name = "progressBar1";
this.progressBar1.Size = new System.Drawing.Size(249, 23);
this.progressBar1.TabIndex = 0;
//
// labelLog
//
this.labelLog.AutoSize = true;
this.labelLog.Location = new System.Drawing.Point(40, 77);
this.labelLog.Name = "labelLog";
this.labelLog.Size = new System.Drawing.Size(0, 13);
this.labelLog.TabIndex = 1;
//
// labelWarning
//
this.labelWarning.AutoSize = true;
this.labelWarning.Location = new System.Drawing.Point(40, 101);
this.labelWarning.Name = "labelWarning";
this.labelWarning.Size = new System.Drawing.Size(0, 13);
this.labelWarning.TabIndex = 41;
//
// UpdateForm
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(336, 125);
this.Controls.Add(this.labelWarning);
this.Controls.Add(this.labelLog);
this.Controls.Add(this.progressBar1);
this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.None;
this.Icon = ((System.Drawing.Icon)(resources.GetObject("$this.Icon")));
this.Name = "UpdateForm";
this.StartPosition = System.Windows.Forms.FormStartPosition.CenterParent;
this.Text = "UpdateForm";
this.Shown += new System.EventHandler(this.UpdateForm_Shown);
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
private System.Windows.Forms.ProgressBar progressBar1;
private System.Windows.Forms.Label labelLog;
private System.Windows.Forms.Label labelWarning;
}
}
| 39.186047
| 142
| 0.581602
|
[
"Apache-2.0"
] |
MassimilianoSartore/ATA-GUI
|
ATA-GUI/Forms/UpdateForm.Designer.cs
| 3,372
|
C#
|
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Text;
namespace IndoorLocationViewer
{
public class PillarMessage
{
[JsonProperty("st")]
public string StationMac { get; set; }
[JsonProperty("t")]
public string T { get; set; }
[JsonProperty("e")]
public List<PillarMessageEntry> Entries { get; set; } = new List<PillarMessageEntry>();
}
public class PillarMessageEntry
{
[JsonProperty("m")]
public string Mac { get; set; }
[JsonProperty("r")]
public string RSSI { get; set; }
}
}
| 21.551724
| 95
| 0.6048
|
[
"Apache-2.0"
] |
dsmithson/indoorTrackerUI
|
src/PillarMessage.cs
| 627
|
C#
|
using UnityEngine;
using System.Collections;
using System;
using System.Collections.Generic;
public class EllipticalPathCS1 : MonoBehaviour
{
public GameObject Parent;
public float radiusA = 5;
public float radiusB = 10;
public float eccentricity = 0.0f;
public float speed = 1.0f;
public float InclinationAngle = 10.0f;
public bool ShowOrbit = false;
public float angle;
public bool Circ = false;
public int Hitpoints = 20;
public bool Alive = true;
public GameObject Debris;
// Use this for initialization
void Start()
{
if (ShowOrbit)
{
createOrbitLine(ConvertScales(0.0f, 360.0f, angle, 0.0f, Mathf.PI * 2));
}
}
public void GenDebris()
{
EllipticalPathCS1 GOEs = gameObject.GetComponent<EllipticalPathCS1>();
GameObject DebrisInstance = Instantiate(Debris, gameObject.transform.position, gameObject.transform.rotation) as GameObject;
DebrisInstance.GetComponent<EllipticalPathCS1>().Parent = GameObject.Find("Sol");
DebrisInstance.name = gameObject.name + "_debris";
DebrisInstance.GetComponent<EllipticalPathCS1>().radiusA = GOEs.radiusA;
DebrisInstance.GetComponent<EllipticalPathCS1>().radiusB = GOEs.radiusB;
DebrisInstance.GetComponent<EllipticalPathCS1>().speed = GOEs.speed - 10;
DebrisInstance.GetComponent<EllipticalPathCS1>().eccentricity = GOEs.eccentricity;
DebrisInstance.GetComponent<EllipticalPathCS1>().InclinationAngle = GOEs.InclinationAngle;
DebrisInstance.GetComponent<EllipticalPathCS1>().ShowOrbit = false;
DebrisInstance.GetComponent<EllipticalPathCS1>().angle = GOEs.angle;
DebrisInstance.transform.localScale = new Vector3(1, 1, 1);
DebrisInstance.transform.localRotation = Quaternion.Euler(0.0f, UnityEngine.Random.Range(0, 360), 90.0f);
}
// Update is called once per frame
void Update()
{
if (Hitpoints <= 0 && Alive)
{
Debug.Log(gameObject.name + "has been destroyed, all life has been exterminated...etc...etc...//points should be taken away here or somthing.");
Alive = false;
}
angle += speed * Time.deltaTime;
transform.position = CalculateEllipse(ConvertScales(0.0f, 360.0f, angle, 0.0f, Mathf.PI * 2));
float A;
if (angle > 360.0f)
{
A = angle % 360.0f;
}
else
{
A = angle;
}
if (Circ && (A >= 0 && A <= 5 || A <= 360 && A >= 355))
{
StartCoroutine(CirculariseEllipse(angle, 1f));
}
}
void LateUpdate()
{
if (ShowOrbit)
{
createOrbitLine(ConvertScales(0.0f, 360.0f, angle, 0.0f, Mathf.PI * 2));
}
}
public void createOrbitLine(float PosAngle)
{
LineRenderer TM = (LineRenderer)transform.GetComponent(typeof(LineRenderer));
TM.SetVertexCount(361);
TM.SetColors(Color.red, Color.red);
List<Vector3> Rs = new List<Vector3>();
for (int i = 0; i <= 360; i++)
{
Vector3 CalcedEcc;
float InclinationInRadians = ConvertScales(0.0f, 360.0f, InclinationAngle, 0.0f, Mathf.PI * 2);
float Irads = ConvertScales(0.0f, 360.0f, i, 0.0f, Mathf.PI * 2);
float x = 0 + radiusA * Mathf.Cos(Irads) * Mathf.Cos(InclinationInRadians) - radiusB * Mathf.Sin(Irads) * Mathf.Sin(InclinationInRadians);
float y = 0 + radiusA * Mathf.Cos(Irads) * Mathf.Sin(InclinationInRadians) + radiusB * Mathf.Sin(Irads) * Mathf.Cos(InclinationInRadians);
CalcedEcc = CalculateEccentricityOffset(eccentricity, InclinationAngle);
TM.SetPosition(i, Parent.transform.position + new Vector3(x, 0, y) - CalcedEcc);
}
}
//public Vector3 CalculatePosition(float angle)
//{
// // Calculates position with parametric form, explanation:
// // http://en.wikipedia.org/wiki/Ellipse#Parametric_form_in_canonical_position
// float x = radiusA * Mathf.Cos(angle);
// float y = radiusB * Mathf.Sin(angle);
// return Parent.transform.position + new Vector3(x, 0, y) - new Vector3(eccentricity, 0, 0);
//}
public Vector3 CalculateEllipse(float PosAngle)
{
Vector3 CalcedEcc;
float InclinationInRadians = ConvertScales(0.0f, 360.0f, InclinationAngle, 0.0f, Mathf.PI * 2);
float x = 0 + radiusA * Mathf.Cos(PosAngle) * Mathf.Cos(InclinationInRadians) - radiusB * Mathf.Sin(PosAngle) * Mathf.Sin(InclinationInRadians);
float y = 0 + radiusA * Mathf.Cos(PosAngle) * Mathf.Sin(InclinationInRadians) + radiusB * Mathf.Sin(PosAngle) * Mathf.Cos(InclinationInRadians);
CalcedEcc = CalculateEccentricityOffset(eccentricity, InclinationAngle);
return Parent.transform.position + new Vector3(x, 0, y) - CalcedEcc;
}
IEnumerator CirculariseEllipse(float PosAngle, float duration)
{
float NewRadius = radiusA - eccentricity;
Debug.Log(NewRadius);
float Rahold = radiusA;
float Rbhold = radiusB;
float Ecchold = eccentricity;
float speedhold = speed;
float elapsedTime = 0.0f;
while (elapsedTime < duration)
{
elapsedTime += Time.deltaTime;
float t = elapsedTime / duration;
radiusA = Mathf.Lerp(Rahold, NewRadius, t);
radiusB = Mathf.Lerp(Rbhold, NewRadius, t);
eccentricity = Mathf.Lerp(Ecchold, 0, t);
speed = Mathf.Lerp(speedhold, speedhold / 2, t);
yield return null;
}
eccentricity = 0;
radiusA = NewRadius;
speed = speedhold / 2;
Circ = false;
}
//public void CirculariseEllipse(float PosAngle)
//{
//}
public float ConvertScales(float scaleAstart, float scaleAend, float ScaleAValueGiven, float scaleBstart, float scaleBend)
{
float ScaleBvalueToFind = 0.0f;
float Numerator = (ScaleAValueGiven - scaleAstart) * (scaleBstart - scaleBend);
float denom = scaleAend - scaleAstart;
ScaleBvalueToFind = Mathf.Abs(Numerator / denom);
return ScaleBvalueToFind;
}
public Vector3 CalculateEccentricityOffset(float Hypot, float angle)
{
int Multi = 1;
if (angle > 180)
{
angle -= 180;
Multi = -1;
}
double CosAngD = Math.Cos((angle * Math.PI / 180));
float CosAng = (float)CosAngD;
float SideB = CosAng * Hypot;
float SideA = Mathf.Sqrt((Hypot * Hypot) - (SideB * SideB));
// Debug.Log("IncAngle: " + angle + "; Ecc: " + eccentricity + "; CosAngD: " + CosAngD + " CosAng: " + CosAng + "; sides: " + SideA + " " + SideB + " --- " + SideB + Multi);
return new Vector3(SideB * Multi, 0, SideA * Multi);
}
}
//if (A >= 0 && A <= 20 || A <= 360 && A >= 340)
//{
// if (radiusA > radiusB)
// {
// radiusA -= 0.1f;
// }
// if (eccentricity > 0)
// {
// eccentricity -= 0.1f;
// }
//}
| 36.26
| 181
| 0.601213
|
[
"MIT"
] |
Blindbuffalo/SpaceDefenceTests
|
Assets/Scripts/EllipticalPathCS1.cs
| 7,254
|
C#
|
using CollectIt.Database.Abstractions.Account.Interfaces;
using CollectIt.Database.Entities.Account.Restrictions;
using CollectIt.Database.Entities.Resources;
namespace CollectIt.Database.Infrastructure.Account;
public class RestrictionVerifier : IRestrictionVerifier
{
private readonly Restriction? _restriction;
public RestrictionVerifier(Restriction? restriction)
{
_restriction = restriction;
}
public bool IsSatisfiedBy(Resource resource)
{
return _restriction?.IsSatisfiedBy(resource) ?? true;
}
}
| 27.75
| 61
| 0.767568
|
[
"Apache-2.0"
] |
SamboTrener/collect-it
|
src/CollectIt.Database/CollectIt.Database.Infrastructure/Account/RestrictionVerifier.cs
| 555
|
C#
|
using System;
using System.Collections.Generic;
namespace BizHawk.Client.Common
{
public static class PlatformFrameRates
{
// these are political numbers, designed to be in accord with tasvideos.org tradition. they're not necessarily mathematical factualities (although they may be in some cases)
// it would be nice if we could turn this into a rational expression natively, and also, to write some comments about the derivation and ideal values (since this seems to be where they're all collected)
// are we collecting them anywhere else? for avi-writing code perhaps?
// just some constants, according to specs
private static readonly double PALCarrier = (15625 * 283.75) + 25; // 4.43361875 MHz
private static readonly double NTSCCarrier = 4500000 * 227.5 / 286; // 3.579545454... MHz
private static readonly double PALNCarrier = (15625 * 229.25) + 25; // 3.58205625 MHz
private static readonly Dictionary<string, double> Rates = new Dictionary<string, double>
{
["NES"] = 60.098813897440515532, // discussion here: http://forums.nesdev.com/viewtopic.php?t=492 ; a rational expression would be (19687500 / 11) / ((341*262-0.529780.5)/3) -> (118125000 / 1965513) -> 60.098813897440515529533511098629 (so our chosen number is very close)
["NES_PAL"] = 50.006977968268290849,
["FDS"] = 60.098813897440515532,
["FDS_PAL"] = 50.006977968268290849,
["SNES"] = 21477272.0 / (4 * 341 * 262), // 60.098475521
["SNES_PAL"] = 21281370.0 / (4 * 341 * 312), // 50.0069789082
["SGB"] = 21477272.0 / (4 * 341 * 262), // 60.098475521
["SGB_PAL"] = 21281370.0 / (4 * 341 * 312), // 50.0069789082
["PCE"] = (7159090.90909090 / 455 / 263), // 59.8261054535
["PCECD"] = (7159090.90909090 / 455 / 263), // 59.8261054535
["SMS"] = (3579545 / 262.0 / 228.0), // 59.9227434043
["SMS_PAL"] = (3546893 / 313.0 / 228.0), // 49.7014320946
["GG"] = (3579545 / 262.0 / 228.0), // 59.9227434043
["GG_PAL"] = (3546893 / 313.0 / 228.0), // 49.7014320946
["SG"] = (3579545 / 262.0 / 228.0), // 59.9227434043
["SG_PAL"] = (3546893 / 313.0 / 228.0), // 49.7014320946
["NGP"] = (6144000.0 / (515 * 198)), // 60.2530155928
["VB"] = (20000000.0 / (259 * 384 * 4)), // 50.2734877735
["Lynx"] = 16000000.0 / (16 * 105 * 159), // 59.89817310572028
["WSWAN"] = (3072000.0 / (159 * 256)), // 75.4716981132
["GB"] = 262144.0 / 4389.0, // 59.7275005696
["GBC"] = 262144.0 / 4389.0, // 59.7275005696
// RetroEdit: I don't like how this is cycles per second instead of FPS.
// It probably should be moved to a separate place.
["GB_Clock"] = 2097152.0,
["GBA"] = 262144.0 / 4389.0, // 59.7275005696
["GEN"] = 53693175 / (3420.0 * 262),
["GEN_PAL"] = 53203424 / (3420.0 * 313),
// while the number of scanlines per frame is software controlled and variable, we
// enforce exactly 262 (NTSC) 312 (PAL) per reference time frame
["A26"] = 315000000.0 / 88.0 / 262.0 / 228.0, // 59.922751013550531429197560173856
// this pal clock ref is exact
["A26_PAL"] = 3546895.0 / 312.0 / 228.0, // 49.860759671614934772829509671615
["A78"] = 59.9227510135505,
["Coleco"] = 59.9227510135505,
// according to http://problemkaputt.de/psx-spx.htm
//["PSX"] = 44100.0 * 768 * 11 / 7 / 263 / 3413, // 59.292862562
//["PSX_PAL"] = 44100.0 * 768 * 11 / 7 / 314 / 3406, // 49.7645593576
// according to https://github.com/TASVideos/mednafen/blob/740d63996fc7cebffd39ee253a29ee434965db21/src/psx/gpu.cpp
["PSX"] = 502813668.0 / 8388608, //59.940060138702392578125
["PSX_PAL"] = 419432765.0 / 8388608, //50.00028192996978759765625
["C64_PAL"] = PALCarrier * 2 / 9 / 312 / 63,
["C64_NTSC"] = NTSCCarrier * 2 / 7 / 263 / 65,
["C64_NTSC_OLD"] = NTSCCarrier * 2 / 7 / 262 / 64,
["C64_DREAN"] = PALNCarrier * 2 / 7 / 312 / 65,
["INTV"] = 59.92,
["ZXSpectrum_PAL"] = 50.080128205,
["AmstradCPC_PAL"] = 50.08012820512821,
};
public static double GetFrameRate(string systemId, bool pal)
{
var key = systemId + (pal ? "_PAL" : "");
return Rates.ContainsKey(key) ? Rates[key] : 60.0;
}
}
}
| 50.409639
| 276
| 0.63217
|
[
"MIT"
] |
davidackroyd99/BizHawk
|
src/BizHawk.Client.Common/movie/PlatformFrameRates.cs
| 4,186
|
C#
|
using System.Collections.Generic;
namespace Bve5_Parsing.MapGrammar
{
/// <summary>
/// マップ構文の構文解析結果を格納するクラス
/// </summary>
public class MapData
{
/// <summary>
/// マップファイルのバージョン
/// </summary>
public string Version { get; set; }
/// <summary>
/// マップファイルのエンコーディング
/// </summary>
public string Encoding { get; set; }
/// <summary>
/// ストラクチャリストのファイルパス
/// </summary>
public string StructureListPath { get; set; }
/// <summary>
/// 停車場リストのファイルパス
/// </summary>
public string StationListPath { get; set; }
/// <summary>
/// 信号リストのファイルパス
/// </summary>
public string SignalListPath { get; set; }
/// <summary>
/// 音リストのファイルパス
/// </summary>
public string SoundListPath { get; set; }
/// <summary>
/// 固定音源リストのファイルパス
/// </summary>
public string Sound3DListPath { get; set; }
/// <summary>
/// 構文
/// </summary>
public List<SyntaxData> Statements { get; set; }
public MapData()
{
Statements = new List<SyntaxData>();
}
/// <summary>
/// 文字列から対応するリストファイルのパスを設定する
/// </summary>
/// <param name="elementName">LoadListFileNodeのelementName</param>
/// <param name="path">設定するファイルパス</param>
public void SetListPathToString(string elementName, string path)
{
switch (elementName)
{
case "structure":
StructureListPath = path;
break;
case "station":
StationListPath = path;
break;
case "signal":
SignalListPath = path;
break;
case "sound":
SoundListPath = path;
break;
case "sound3d":
Sound3DListPath = path;
break;
}
}
}
/// <summary>
/// 構文情報を管理するクラス
/// </summary>
public class SyntaxData
{
public double Distance { get; set; }
public string[] MapElement { get; set; }
public string Key { get; set; }
public string Function { get; set; }
public Dictionary<string, object> Arguments { get; set; }
public SyntaxData()
{
Arguments = new Dictionary<string, object>();
}
}
}
| 25.71
| 74
| 0.473746
|
[
"MIT"
] |
s520/Bve5_Parsing
|
Bve5_Parsing/MapGrammar/MapData.cs
| 2,901
|
C#
|
// MIT License
//
// Copyright(c) 2021 ICARUS Consulting GmbH
//
// 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.Collections;
using Xunit;
namespace Yaapii.Atoms.Enumerable.Tests
{
public class ManyOfArrayListTests
{
[Fact]
public void BuildsFromStrings()
{
var arr = new ArrayList() { "A", "B", "C" };
Assert.True(
new ItemAt<object>(
new ManyOfArrayList(arr)
).Value().ToString() == "A");
}
}
}
| 37.071429
| 81
| 0.693642
|
[
"MIT"
] |
icarus-consulting/Yaapii.Atoms
|
tests/Yaapii.Atoms.Tests/Enumerable/ManyOfArrayListTests.cs
| 1,557
|
C#
|
using System;
using System.Collections.Generic;
using System.Text.RegularExpressions;
using Microsoft.Xrm.Sdk;
using Microsoft.Xrm.Sdk.Metadata;
namespace FieldCreator.TyCorcoran
{
public class AttrBase
{
public AttrBase (Attribute attribute)
{
_attribute = attribute;
}
private Attribute _attribute;
private const string _regexSanitizedSchemaName = "[^a-zA-Z0-9_]";
public bool AttrAuditEnabled => _attribute.AuditEnabled.ToLower() == "true" ? true : false;
public string AttrEntitySchemaName => Regex.Replace(_attribute.EntitySchemaName.ToLower(), _regexSanitizedSchemaName, string.Empty);
public string AttrSolution => _attribute.SolutionUniqueName;
public string AttrDescription => _attribute.Description;
public string AttrSchemaName => Regex.Replace(_attribute.FieldSchemaName, _regexSanitizedSchemaName, string.Empty);
public string AttrFieldLabel => _attribute.FieldLabel;
public AttributeRequiredLevel AttrRequiredLevel
{
get
{
var reqlevel = new AttributeRequiredLevel();
switch (_attribute.RequiredLevel)
{
case "None":
reqlevel = AttributeRequiredLevel.None;
return reqlevel;
case "System Required":
reqlevel = AttributeRequiredLevel.ApplicationRequired;
return reqlevel;
case "Recommended":
reqlevel = AttributeRequiredLevel.Recommended;
return reqlevel;
default:
reqlevel = 0;
return reqlevel;
}
}
}
public OptionSetMetadata GenerateOptionSetMetadata()
{
var osMetaDataCollection = CreateOptionMetaDataCollection();
return new OptionSetMetadata(osMetaDataCollection)
{
IsGlobal = false,
OptionSetType = (_attribute.FieldType == "FieldCreator.TyCorcoran.AttrOptionSet") ? OptionSetType.Picklist : default
};
}
public OptionMetadataCollection CreateOptionMetaDataCollection()
{
string optionSetValueString = _attribute.OptionSetValues;
var optionSetMetadataCollection = new List<OptionMetadata>();
if (!string.IsNullOrWhiteSpace(optionSetValueString))
{
var optionSetStringList = new List<string>(optionSetValueString.Split('|'));
foreach (var option in optionSetStringList)
{
var osMeta = new OptionMetadata(new Label(option, 1033), null);
optionSetMetadataCollection.Add(osMeta);
}
};
var optionMetaCollection = new OptionMetadataCollection(optionSetMetadataCollection);
return optionMetaCollection;
}
public static OptionMetadataCollection CreateOptionMetaDataCollection(Attribute attribute)
{
string optionSetValueString = attribute.OptionSetValues;
var optionSetMetadataCollection = new List<OptionMetadata>();
if (!string.IsNullOrWhiteSpace(optionSetValueString))
{
var optionSetStringList = new List<string>(optionSetValueString.Split('|'));
foreach (var option in optionSetStringList)
{
var osMeta = new OptionMetadata(new Label(option, 1033), null);
optionSetMetadataCollection.Add(osMeta);
}
};
var optionMetaCollection = new OptionMetadataCollection(optionSetMetadataCollection);
return optionMetaCollection;
}
}
}
| 44.045455
| 140
| 0.602683
|
[
"MIT"
] |
tcorcor1/FieldCreator.TyCorcoran
|
FieldCreator/AttributeTypes/AttrBase.cs
| 3,878
|
C#
|
/*
* Kubernetes
*
* No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen)
*
* OpenAPI spec version: v1.7.10
*
* Generated by: https://github.com/swagger-api/swagger-codegen.git
*/
using System;
using System.Linq;
using System.IO;
using System.Text;
using System.Text.RegularExpressions;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Runtime.Serialization;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using System.ComponentModel.DataAnnotations;
using SwaggerDateConverter = Kubernetes.DotNet.Client.SwaggerDateConverter;
namespace Kubernetes.DotNet.Model
{
/// <summary>
/// Role is a namespaced, logical grouping of PolicyRules that can be referenced as a unit by a RoleBinding.
/// </summary>
[DataContract]
public partial class V1beta1Role : IEquatable<V1beta1Role>, IValidatableObject
{
/// <summary>
/// Initializes a new instance of the <see cref="V1beta1Role" /> class.
/// </summary>
[JsonConstructorAttribute]
protected V1beta1Role() { }
/// <summary>
/// Initializes a new instance of the <see cref="V1beta1Role" /> class.
/// </summary>
/// <param name="ApiVersion">APIVersion defines the versioned schema of this representation of an object. Servers should convert recognized schemas to the latest internal value, and may reject unrecognized values. More info: https://git.k8s.io/community/contributors/devel/api-conventions.md#resources.</param>
/// <param name="Kind">Kind is a string value representing the REST resource this object represents. Servers may infer this from the endpoint the client submits requests to. Cannot be updated. In CamelCase. More info: https://git.k8s.io/community/contributors/devel/api-conventions.md#types-kinds.</param>
/// <param name="Metadata">Standard object's metadata..</param>
/// <param name="Rules">Rules holds all the PolicyRules for this Role (required).</param>
public V1beta1Role(string ApiVersion = default(string), string Kind = default(string), V1ObjectMeta Metadata = default(V1ObjectMeta), List<V1beta1PolicyRule> Rules = default(List<V1beta1PolicyRule>))
{
// to ensure "Rules" is required (not null)
if (Rules == null)
{
throw new InvalidDataException("Rules is a required property for V1beta1Role and cannot be null");
}
else
{
this.Rules = Rules;
}
this.ApiVersion = ApiVersion;
this.Kind = Kind;
this.Metadata = Metadata;
}
/// <summary>
/// APIVersion defines the versioned schema of this representation of an object. Servers should convert recognized schemas to the latest internal value, and may reject unrecognized values. More info: https://git.k8s.io/community/contributors/devel/api-conventions.md#resources
/// </summary>
/// <value>APIVersion defines the versioned schema of this representation of an object. Servers should convert recognized schemas to the latest internal value, and may reject unrecognized values. More info: https://git.k8s.io/community/contributors/devel/api-conventions.md#resources</value>
[DataMember(Name="apiVersion", EmitDefaultValue=false)]
public string ApiVersion { get; set; }
/// <summary>
/// Kind is a string value representing the REST resource this object represents. Servers may infer this from the endpoint the client submits requests to. Cannot be updated. In CamelCase. More info: https://git.k8s.io/community/contributors/devel/api-conventions.md#types-kinds
/// </summary>
/// <value>Kind is a string value representing the REST resource this object represents. Servers may infer this from the endpoint the client submits requests to. Cannot be updated. In CamelCase. More info: https://git.k8s.io/community/contributors/devel/api-conventions.md#types-kinds</value>
[DataMember(Name="kind", EmitDefaultValue=false)]
public string Kind { get; set; }
/// <summary>
/// Standard object's metadata.
/// </summary>
/// <value>Standard object's metadata.</value>
[DataMember(Name="metadata", EmitDefaultValue=false)]
public V1ObjectMeta Metadata { get; set; }
/// <summary>
/// Rules holds all the PolicyRules for this Role
/// </summary>
/// <value>Rules holds all the PolicyRules for this Role</value>
[DataMember(Name="rules", EmitDefaultValue=false)]
public List<V1beta1PolicyRule> Rules { get; set; }
/// <summary>
/// Returns the string presentation of the object
/// </summary>
/// <returns>String presentation of the object</returns>
public override string ToString()
{
var sb = new StringBuilder();
sb.Append("class V1beta1Role {\n");
sb.Append(" ApiVersion: ").Append(ApiVersion).Append("\n");
sb.Append(" Kind: ").Append(Kind).Append("\n");
sb.Append(" Metadata: ").Append(Metadata).Append("\n");
sb.Append(" Rules: ").Append(Rules).Append("\n");
sb.Append("}\n");
return sb.ToString();
}
/// <summary>
/// Returns the JSON string presentation of the object
/// </summary>
/// <returns>JSON string presentation of the object</returns>
public string ToJson()
{
return JsonConvert.SerializeObject(this, Formatting.Indented);
}
/// <summary>
/// Returns true if objects are equal
/// </summary>
/// <param name="obj">Object to be compared</param>
/// <returns>Boolean</returns>
public override bool Equals(object obj)
{
// credit: http://stackoverflow.com/a/10454552/677735
return this.Equals(obj as V1beta1Role);
}
/// <summary>
/// Returns true if V1beta1Role instances are equal
/// </summary>
/// <param name="other">Instance of V1beta1Role to be compared</param>
/// <returns>Boolean</returns>
public bool Equals(V1beta1Role other)
{
// credit: http://stackoverflow.com/a/10454552/677735
if (other == null)
return false;
return
(
this.ApiVersion == other.ApiVersion ||
this.ApiVersion != null &&
this.ApiVersion.Equals(other.ApiVersion)
) &&
(
this.Kind == other.Kind ||
this.Kind != null &&
this.Kind.Equals(other.Kind)
) &&
(
this.Metadata == other.Metadata ||
this.Metadata != null &&
this.Metadata.Equals(other.Metadata)
) &&
(
this.Rules == other.Rules ||
this.Rules != null &&
this.Rules.SequenceEqual(other.Rules)
);
}
/// <summary>
/// Gets the hash code
/// </summary>
/// <returns>Hash code</returns>
public override int GetHashCode()
{
// credit: http://stackoverflow.com/a/263416/677735
unchecked // Overflow is fine, just wrap
{
int hash = 41;
// Suitable nullity checks etc, of course :)
if (this.ApiVersion != null)
hash = hash * 59 + this.ApiVersion.GetHashCode();
if (this.Kind != null)
hash = hash * 59 + this.Kind.GetHashCode();
if (this.Metadata != null)
hash = hash * 59 + this.Metadata.GetHashCode();
if (this.Rules != null)
hash = hash * 59 + this.Rules.GetHashCode();
return hash;
}
}
/// <summary>
/// To validate all properties of the instance
/// </summary>
/// <param name="validationContext">Validation context</param>
/// <returns>Validation Result</returns>
IEnumerable<System.ComponentModel.DataAnnotations.ValidationResult> IValidatableObject.Validate(ValidationContext validationContext)
{
yield break;
}
}
}
| 44.360825
| 318
| 0.598652
|
[
"MIT"
] |
masroorhasan/Kubernetes.DotNet
|
src/Kubernetes.DotNet/Model/V1beta1Role.cs
| 8,606
|
C#
|
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
// <auto-generated/>
#nullable disable
using System.Collections.Generic;
using Azure.Core;
using Azure.ResourceManager.Models;
namespace Azure.ResourceManager.KeyVault.Models
{
/// <summary> A private link resource. </summary>
public partial class PrivateLinkResource : KeyVaultResource
{
/// <summary> Initializes a new instance of PrivateLinkResource. </summary>
public PrivateLinkResource()
{
RequiredMembers = new ChangeTrackingList<string>();
RequiredZoneNames = new ChangeTrackingList<string>();
}
/// <summary> Initializes a new instance of PrivateLinkResource. </summary>
/// <param name="id"> The id. </param>
/// <param name="name"> The name. </param>
/// <param name="type"> The type. </param>
/// <param name="systemData"> The systemData. </param>
/// <param name="location"> Azure location of the key vault resource. </param>
/// <param name="tags"> Tags assigned to the key vault resource. </param>
/// <param name="groupId"> Group identifier of private link resource. </param>
/// <param name="requiredMembers"> Required member names of private link resource. </param>
/// <param name="requiredZoneNames"> Required DNS zone names of the the private link resource. </param>
internal PrivateLinkResource(ResourceIdentifier id, string name, ResourceType type, SystemData systemData, string location, IReadOnlyDictionary<string, string> tags, string groupId, IReadOnlyList<string> requiredMembers, IList<string> requiredZoneNames) : base(id, name, type, systemData, location, tags)
{
GroupId = groupId;
RequiredMembers = requiredMembers;
RequiredZoneNames = requiredZoneNames;
}
/// <summary> Group identifier of private link resource. </summary>
public string GroupId { get; }
/// <summary> Required member names of private link resource. </summary>
public IReadOnlyList<string> RequiredMembers { get; }
/// <summary> Required DNS zone names of the the private link resource. </summary>
public IList<string> RequiredZoneNames { get; }
}
}
| 47.204082
| 312
| 0.669693
|
[
"MIT"
] |
AntonioVT/azure-sdk-for-net
|
sdk/keyvault/Azure.ResourceManager.KeyVault/src/Generated/Models/PrivateLinkResource.cs
| 2,313
|
C#
|
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
using System.Collections.Generic;
using Aliyun.Acs.Core;
using Aliyun.Acs.Core.Http;
using Aliyun.Acs.Core.Transform;
using Aliyun.Acs.Core.Utils;
using Aliyun.Acs.live.Transform;
using Aliyun.Acs.live.Transform.V20161101;
namespace Aliyun.Acs.live.Model.V20161101
{
public class DeleteLiveDomainRequest : RpcAcsRequest<DeleteLiveDomainResponse>
{
public DeleteLiveDomainRequest()
: base("live", "2016-11-01", "DeleteLiveDomain", "live", "openAPI")
{
}
private string securityToken;
private string ownerAccount;
private string domainName;
private long? ownerId;
public string SecurityToken
{
get
{
return securityToken;
}
set
{
securityToken = value;
DictionaryUtil.Add(QueryParameters, "SecurityToken", value);
}
}
public string OwnerAccount
{
get
{
return ownerAccount;
}
set
{
ownerAccount = value;
DictionaryUtil.Add(QueryParameters, "OwnerAccount", value);
}
}
public string DomainName
{
get
{
return domainName;
}
set
{
domainName = value;
DictionaryUtil.Add(QueryParameters, "DomainName", value);
}
}
public long? OwnerId
{
get
{
return ownerId;
}
set
{
ownerId = value;
DictionaryUtil.Add(QueryParameters, "OwnerId", value.ToString());
}
}
public override DeleteLiveDomainResponse GetResponse(UnmarshallerContext unmarshallerContext)
{
return DeleteLiveDomainResponseUnmarshaller.Unmarshall(unmarshallerContext);
}
}
}
| 23.76699
| 101
| 0.676471
|
[
"Apache-2.0"
] |
xueandfeng/aliyun-openapi-net-sdk
|
aliyun-net-sdk-live/Live/Model/V20161101/DeleteLiveDomainRequest.cs
| 2,448
|
C#
|
using System;
using System.Collections.Generic;
using System.Linq;
using MSearch.Extensions;
using MSearch.Common;
using Newtonsoft.Json;
namespace MSearch.GA
{
public class GeneticAlgorithm<IndividualType> : IMetaHeuristic<IndividualType>
{
public Configuration<IndividualType> Config { get; set; }
private IndividualType _bestIndividual { get; set; }
private double _bestFitness { get; set; }
private int _iterationCount { get; set; }
//private Func<IndividualType> _initFunc { get; set; }
private Func<IndividualType, IndividualType, IndividualType> _crossOverFunc { get; set; }
public List<KeyValue<IndividualType, double>> Population { get; set; }
private List<double> _iterationFitnessSequence = new List<double>();
public GeneticAlgorithm()
{
}
public GeneticAlgorithm(Func<IndividualType, IndividualType, IndividualType> crossOverFunction)
{
this._crossOverFunc = crossOverFunction;
}
public void create(Configuration<IndividualType> config)
{
this.Config = config;
this.Population = new List<KeyValue<IndividualType, double>>();
if (config.populationSize <= 2) throw new Exception("Population Size must be more than 2");
if (_crossOverFunc == null) throw new Exception("Please provide a Cross Over Function");
for (int i = 0; i < config.populationSize; i++)
{
this.Population.Add(new KeyValue<IndividualType, double>());
}
if (config.movement == Search.Direction.Optimization)
{
_bestFitness = double.MaxValue;
}
else if (config.movement == Search.Direction.Divergence)
{
_bestFitness = double.MinValue;
}
for (int index = 0; index <= Population.Count - 1; index++)
{
Population[index].key = config.initializeSolutionFunction();
Population[index].value = config.objectiveFunction.Invoke(Population[index].key);
}
}
public List<double> getIterationSequence()
{
return _iterationFitnessSequence;
}
public double getBestFitness()
{
return this._bestFitness;
}
public IndividualType fullIteration()
{
for (int count = 1; count <= Config.noOfIterations; count++)
{
_iterationCount = count;
IndividualType _bestIndividual = singleIteration();
_iterationFitnessSequence.Add(_bestFitness);
}
Console.WriteLine("End of Iterations");
return _bestIndividual;
}
public IndividualType singleIteration()
{
var individuals = Config.selectionFunction.Invoke(Population.Select((individual) => individual.key), Population.Select((individual) => individual.value), 2);
IndividualType individualA = individuals.ElementAt(0);
IndividualType individualB = individuals.ElementAt(1);
double fitnessA = Config.objectiveFunction.Invoke(individualA);
double fitnessB = Config.objectiveFunction.Invoke(individualB);
int indexA = Population.Select((individual) => individual.value).ToList().IndexOf(fitnessA);
int indexB = Population.Select((individual) => individual.value).ToList().IndexOf(fitnessB);
//cross-over
IndividualType newIndividual = this._crossOverFunc(Config.cloneFunction.Invoke(individualA), Config.cloneFunction.Invoke(individualB));
double newFitness = Config.objectiveFunction.Invoke(newIndividual);
if ((Config.hardObjectiveFunction != null &&
((Config.enforceHardObjective && Config.hardObjectiveFunction(newIndividual)) || (!Config.enforceHardObjective))) ||
Config.hardObjectiveFunction == null)
{
if ((Config.movement == Search.Direction.Optimization && newFitness < _bestFitness) ||
(Config.movement == Search.Direction.Divergence && newFitness > _bestFitness))
{
_bestIndividual = newIndividual;
_bestFitness = newFitness;
}
if ((Config.movement == Search.Direction.Optimization && newFitness < fitnessA) ||
(Config.movement == Search.Direction.Divergence && newFitness > fitnessA))
{
individualA = newIndividual;
Population[indexA].key = individualA;
Population[indexA].value = newFitness;
fitnessA = newFitness;
}
else if ((Config.movement == Search.Direction.Optimization && newFitness < fitnessB) ||
(Config.movement == Search.Direction.Divergence && newFitness > fitnessB))
{
individualB = newIndividual;
Population[indexA].key = individualB;
Population[indexA].value = newFitness;
fitnessB = newFitness;
}
}
//mutation
line1:
IndividualType individualAClone = Config.mutationFunction.Invoke(Config.cloneFunction.Invoke(individualA));
IndividualType individualBClone = Config.mutationFunction.Invoke(Config.cloneFunction.Invoke(individualB));
double fitnessAClone = Config.objectiveFunction.Invoke(individualAClone);
double fitnessBClone = Config.objectiveFunction.Invoke(individualBClone);
if (Config.hardObjectiveFunction != null &&
((Config.enforceHardObjective &&
!Config.hardObjectiveFunction(individualAClone) || !Config.hardObjectiveFunction(individualBClone))))
{
goto line1;
}
if ((Config.movement == Search.Direction.Optimization && fitnessAClone < _bestFitness) ||
(Config.movement == Search.Direction.Divergence && fitnessAClone > _bestFitness))
{
_bestIndividual = individualAClone;
_bestFitness = fitnessAClone;
}
else if ((Config.movement == Search.Direction.Optimization && fitnessBClone < _bestFitness) ||
(Config.movement == Search.Direction.Divergence && fitnessBClone > _bestFitness))
{
_bestIndividual = individualBClone;
_bestFitness = fitnessBClone;
}
if ((Config.movement == Search.Direction.Optimization && fitnessAClone < fitnessA) ||
(Config.movement == Search.Direction.Divergence && fitnessAClone > fitnessA))
{
Population[indexA].key = individualAClone;
Population[indexA].value = fitnessAClone;
}
else if ((Config.movement == Search.Direction.Optimization && fitnessAClone < fitnessB) ||
(Config.movement == Search.Direction.Divergence && fitnessAClone > fitnessB))
{
Population[indexB].key = individualAClone;
Population[indexB].value = fitnessAClone;
}
else if ((Config.movement == Search.Direction.Optimization && fitnessBClone < fitnessA) ||
(Config.movement == Search.Direction.Divergence && fitnessBClone > fitnessA))
{
Population[indexA].key = individualBClone;
Population[indexA].value = fitnessBClone;
}
else if ((Config.movement == Search.Direction.Optimization && fitnessBClone < fitnessB) ||
(Config.movement == Search.Direction.Divergence && fitnessBClone > fitnessB))
{
Population[indexB].key = individualBClone;
Population[indexB].value = fitnessBClone;
}
if (Config.writeToConsole && ((_iterationCount % Config.consoleWriteInterval) == 0) || (_iterationCount - 1 == 0))
{
if (Config.consoleWriteFunction == null) Console.WriteLine(_iterationCount + "\t" + Newtonsoft.Json.JsonConvert.SerializeObject(_iterationCount) + " = " + _bestFitness);
else Config.consoleWriteFunction(_bestIndividual, _bestFitness, _iterationCount);
}
return _bestIndividual;
}
}
}
| 45.764706
| 185
| 0.595817
|
[
"MIT"
] |
mykeels/MSearch
|
MSearch/GA/GeneticAlgorithm.cs
| 8,560
|
C#
|
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for license information.
// Code generated by Microsoft (R) AutoRest Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is regenerated.
namespace Microsoft.Azure.PowerShell.Cmdlets.VMware.Models.Api10
{
using Microsoft.Azure.PowerShell.Cmdlets.VMware.Runtime.PowerShell;
/// <summary>
/// Common error response for all Azure Resource Manager APIs to return error details for failed operations. (This also follows
/// the OData error response format.)
/// </summary>
[System.ComponentModel.TypeConverter(typeof(ErrorResponseTypeConverter))]
public partial class ErrorResponse
{
/// <summary>
/// <c>AfterDeserializeDictionary</c> will be called after the deserialization has finished, allowing customization of the
/// object before it is returned. Implement this method in a partial class to enable this behavior
/// </summary>
/// <param name="content">The global::System.Collections.IDictionary content that should be used.</param>
partial void AfterDeserializeDictionary(global::System.Collections.IDictionary content);
/// <summary>
/// <c>AfterDeserializePSObject</c> will be called after the deserialization has finished, allowing customization of the object
/// before it is returned. Implement this method in a partial class to enable this behavior
/// </summary>
/// <param name="content">The global::System.Management.Automation.PSObject content that should be used.</param>
partial void AfterDeserializePSObject(global::System.Management.Automation.PSObject content);
/// <summary>
/// <c>BeforeDeserializeDictionary</c> will be called before the deserialization has commenced, allowing complete customization
/// of the object before it is deserialized.
/// If you wish to disable the default deserialization entirely, return <c>true</c> in the <see "returnNow" /> output parameter.
/// Implement this method in a partial class to enable this behavior.
/// </summary>
/// <param name="content">The global::System.Collections.IDictionary content that should be used.</param>
/// <param name="returnNow">Determines if the rest of the serialization should be processed, or if the method should return
/// instantly.</param>
partial void BeforeDeserializeDictionary(global::System.Collections.IDictionary content, ref bool returnNow);
/// <summary>
/// <c>BeforeDeserializePSObject</c> will be called before the deserialization has commenced, allowing complete customization
/// of the object before it is deserialized.
/// If you wish to disable the default deserialization entirely, return <c>true</c> in the <see "returnNow" /> output parameter.
/// Implement this method in a partial class to enable this behavior.
/// </summary>
/// <param name="content">The global::System.Management.Automation.PSObject content that should be used.</param>
/// <param name="returnNow">Determines if the rest of the serialization should be processed, or if the method should return
/// instantly.</param>
partial void BeforeDeserializePSObject(global::System.Management.Automation.PSObject content, ref bool returnNow);
/// <summary>
/// Deserializes a <see cref="global::System.Collections.IDictionary" /> into an instance of <see cref="Microsoft.Azure.PowerShell.Cmdlets.VMware.Models.Api10.ErrorResponse"
/// />.
/// </summary>
/// <param name="content">The global::System.Collections.IDictionary content that should be used.</param>
/// <returns>
/// an instance of <see cref="Microsoft.Azure.PowerShell.Cmdlets.VMware.Models.Api10.IErrorResponse" />.
/// </returns>
public static Microsoft.Azure.PowerShell.Cmdlets.VMware.Models.Api10.IErrorResponse DeserializeFromDictionary(global::System.Collections.IDictionary content)
{
return new ErrorResponse(content);
}
/// <summary>
/// Deserializes a <see cref="global::System.Management.Automation.PSObject" /> into an instance of <see cref="Microsoft.Azure.PowerShell.Cmdlets.VMware.Models.Api10.ErrorResponse"
/// />.
/// </summary>
/// <param name="content">The global::System.Management.Automation.PSObject content that should be used.</param>
/// <returns>
/// an instance of <see cref="Microsoft.Azure.PowerShell.Cmdlets.VMware.Models.Api10.IErrorResponse" />.
/// </returns>
public static Microsoft.Azure.PowerShell.Cmdlets.VMware.Models.Api10.IErrorResponse DeserializeFromPSObject(global::System.Management.Automation.PSObject content)
{
return new ErrorResponse(content);
}
/// <summary>
/// Deserializes a <see cref="global::System.Collections.IDictionary" /> into a new instance of <see cref="Microsoft.Azure.PowerShell.Cmdlets.VMware.Models.Api10.ErrorResponse"
/// />.
/// </summary>
/// <param name="content">The global::System.Collections.IDictionary content that should be used.</param>
internal ErrorResponse(global::System.Collections.IDictionary content)
{
bool returnNow = false;
BeforeDeserializeDictionary(content, ref returnNow);
if (returnNow)
{
return;
}
// actually deserialize
((Microsoft.Azure.PowerShell.Cmdlets.VMware.Models.Api10.IErrorResponseInternal)this).Code = (string) content.GetValueForProperty("Code",((Microsoft.Azure.PowerShell.Cmdlets.VMware.Models.Api10.IErrorResponseInternal)this).Code, global::System.Convert.ToString);
((Microsoft.Azure.PowerShell.Cmdlets.VMware.Models.Api10.IErrorResponseInternal)this).Message = (string) content.GetValueForProperty("Message",((Microsoft.Azure.PowerShell.Cmdlets.VMware.Models.Api10.IErrorResponseInternal)this).Message, global::System.Convert.ToString);
((Microsoft.Azure.PowerShell.Cmdlets.VMware.Models.Api10.IErrorResponseInternal)this).Target = (string) content.GetValueForProperty("Target",((Microsoft.Azure.PowerShell.Cmdlets.VMware.Models.Api10.IErrorResponseInternal)this).Target, global::System.Convert.ToString);
((Microsoft.Azure.PowerShell.Cmdlets.VMware.Models.Api10.IErrorResponseInternal)this).Detail = (Microsoft.Azure.PowerShell.Cmdlets.VMware.Models.Api10.IErrorResponse[]) content.GetValueForProperty("Detail",((Microsoft.Azure.PowerShell.Cmdlets.VMware.Models.Api10.IErrorResponseInternal)this).Detail, __y => TypeConverterExtensions.SelectToArray<Microsoft.Azure.PowerShell.Cmdlets.VMware.Models.Api10.IErrorResponse>(__y, Microsoft.Azure.PowerShell.Cmdlets.VMware.Models.Api10.ErrorResponseTypeConverter.ConvertFrom));
((Microsoft.Azure.PowerShell.Cmdlets.VMware.Models.Api10.IErrorResponseInternal)this).AdditionalInfo = (Microsoft.Azure.PowerShell.Cmdlets.VMware.Models.Api10.IErrorAdditionalInfo[]) content.GetValueForProperty("AdditionalInfo",((Microsoft.Azure.PowerShell.Cmdlets.VMware.Models.Api10.IErrorResponseInternal)this).AdditionalInfo, __y => TypeConverterExtensions.SelectToArray<Microsoft.Azure.PowerShell.Cmdlets.VMware.Models.Api10.IErrorAdditionalInfo>(__y, Microsoft.Azure.PowerShell.Cmdlets.VMware.Models.Api10.ErrorAdditionalInfoTypeConverter.ConvertFrom));
AfterDeserializeDictionary(content);
}
/// <summary>
/// Deserializes a <see cref="global::System.Management.Automation.PSObject" /> into a new instance of <see cref="Microsoft.Azure.PowerShell.Cmdlets.VMware.Models.Api10.ErrorResponse"
/// />.
/// </summary>
/// <param name="content">The global::System.Management.Automation.PSObject content that should be used.</param>
internal ErrorResponse(global::System.Management.Automation.PSObject content)
{
bool returnNow = false;
BeforeDeserializePSObject(content, ref returnNow);
if (returnNow)
{
return;
}
// actually deserialize
((Microsoft.Azure.PowerShell.Cmdlets.VMware.Models.Api10.IErrorResponseInternal)this).Code = (string) content.GetValueForProperty("Code",((Microsoft.Azure.PowerShell.Cmdlets.VMware.Models.Api10.IErrorResponseInternal)this).Code, global::System.Convert.ToString);
((Microsoft.Azure.PowerShell.Cmdlets.VMware.Models.Api10.IErrorResponseInternal)this).Message = (string) content.GetValueForProperty("Message",((Microsoft.Azure.PowerShell.Cmdlets.VMware.Models.Api10.IErrorResponseInternal)this).Message, global::System.Convert.ToString);
((Microsoft.Azure.PowerShell.Cmdlets.VMware.Models.Api10.IErrorResponseInternal)this).Target = (string) content.GetValueForProperty("Target",((Microsoft.Azure.PowerShell.Cmdlets.VMware.Models.Api10.IErrorResponseInternal)this).Target, global::System.Convert.ToString);
((Microsoft.Azure.PowerShell.Cmdlets.VMware.Models.Api10.IErrorResponseInternal)this).Detail = (Microsoft.Azure.PowerShell.Cmdlets.VMware.Models.Api10.IErrorResponse[]) content.GetValueForProperty("Detail",((Microsoft.Azure.PowerShell.Cmdlets.VMware.Models.Api10.IErrorResponseInternal)this).Detail, __y => TypeConverterExtensions.SelectToArray<Microsoft.Azure.PowerShell.Cmdlets.VMware.Models.Api10.IErrorResponse>(__y, Microsoft.Azure.PowerShell.Cmdlets.VMware.Models.Api10.ErrorResponseTypeConverter.ConvertFrom));
((Microsoft.Azure.PowerShell.Cmdlets.VMware.Models.Api10.IErrorResponseInternal)this).AdditionalInfo = (Microsoft.Azure.PowerShell.Cmdlets.VMware.Models.Api10.IErrorAdditionalInfo[]) content.GetValueForProperty("AdditionalInfo",((Microsoft.Azure.PowerShell.Cmdlets.VMware.Models.Api10.IErrorResponseInternal)this).AdditionalInfo, __y => TypeConverterExtensions.SelectToArray<Microsoft.Azure.PowerShell.Cmdlets.VMware.Models.Api10.IErrorAdditionalInfo>(__y, Microsoft.Azure.PowerShell.Cmdlets.VMware.Models.Api10.ErrorAdditionalInfoTypeConverter.ConvertFrom));
AfterDeserializePSObject(content);
}
/// <summary>
/// Creates a new instance of <see cref="ErrorResponse" />, deserializing the content from a json string.
/// </summary>
/// <param name="jsonText">a string containing a JSON serialized instance of this model.</param>
/// <returns>an instance of the <see cref="className" /> model class.</returns>
public static Microsoft.Azure.PowerShell.Cmdlets.VMware.Models.Api10.IErrorResponse FromJsonString(string jsonText) => FromJson(Microsoft.Azure.PowerShell.Cmdlets.VMware.Runtime.Json.JsonNode.Parse(jsonText));
/// <summary>Serializes this instance to a json string.</summary>
/// <returns>a <see cref="System.String" /> containing this model serialized to JSON text.</returns>
public string ToJsonString() => ToJson(null, Microsoft.Azure.PowerShell.Cmdlets.VMware.Runtime.SerializationMode.IncludeAll)?.ToString();
}
/// Common error response for all Azure Resource Manager APIs to return error details for failed operations. (This also follows
/// the OData error response format.)
[System.ComponentModel.TypeConverter(typeof(ErrorResponseTypeConverter))]
public partial interface IErrorResponse
{
}
}
| 79.155405
| 572
| 0.720273
|
[
"MIT"
] |
Amrinder-Singh29/azure-powershell
|
src/VMware/generated/api/Models/Api10/ErrorResponse.PowerShell.cs
| 11,568
|
C#
|
/*
THE COMPUTER CODE CONTAINED HEREIN IS THE SOLE PROPERTY OF REVIVAL
PRODUCTIONS, LLC ("REVIVAL"). REVIVAL, IN DISTRIBUTING THE CODE TO
END-USERS, AND SUBJECT TO ALL OF THE TERMS AND CONDITIONS HEREIN, GRANTS A
ROYALTY-FREE, PERPETUAL LICENSE TO SUCH END-USERS FOR USE BY SUCH END-USERS
IN USING, DISPLAYING, AND CREATING DERIVATIVE WORKS THEREOF, SO LONG AS
SUCH USE, DISPLAY OR CREATION IS FOR NON-COMMERCIAL, ROYALTY OR REVENUE
FREE PURPOSES. IN NO EVENT SHALL THE END-USER USE THE COMPUTER CODE
CONTAINED HEREIN FOR REVENUE-BEARING PURPOSES. THE END-USER UNDERSTANDS
AND AGREES TO THE TERMS HEREIN AND ACCEPTS THE SAME BY USE OF THIS FILE.
COPYRIGHT 2015-2020 REVIVAL PRODUCTIONS, LLC. ALL RIGHTS RESERVED.
*/
using System;
using System.Collections.Generic;
using System.Windows.Forms;
using System.IO;
using OpenTK;
using Newtonsoft.Json.Linq;
using Newtonsoft.Json;
using System.Diagnostics;
// EDITOR - Utility functions
// Mostly used for consolidating or redirecting editor commands to the specific steps
// Fairly random collection, so moving groups of functions to new files/etc is fine
namespace OverloadLevelEditor
{
public partial class Editor : EditorDockContent
{
public int m_decal_active = 0;
public Vector3 m_src_side_pos = Vector3.Zero;
public Matrix4 m_src_side_rotation = Matrix4.Identity;
public int m_src_seg_count = 0;
public Vector3 m_dest_side_pos = Vector3.Zero;
public Matrix4 m_dest_side_rotation = Matrix4.Identity;
public void CopyMarkedSegments(bool silent = false)
{
Vector3 src_side_normal;
if (m_level.GetSelectedSide() != null) {
m_level.GetSelectedSidePosAndNormal(out m_src_side_pos, out src_side_normal);
} else {
m_src_side_pos = Vector3.Zero;
src_side_normal = Vector3.UnitX;
}
m_src_side_rotation = ComputeRotationFromNormal(src_side_normal);
m_src_seg_count = m_lvl_buffer.CopyMarkedSegments(m_level);
if (!silent) {
AddOutputText("Copied " + m_src_seg_count.ToString() + " marked segments");
}
}
public bool PasteBufferSegments(bool aligned, bool paste_entites, bool refresh = true)
{
if (m_src_seg_count > 0) {
if (refresh) {
SaveStateForUndo("Paste copied segments");
}
if (aligned) {
Vector3 dest_side_normal;
m_level.GetSelectedSidePosAndNormal(out m_dest_side_pos, out dest_side_normal);
m_dest_side_rotation = ComputeRotationFromNormal(-dest_side_normal).Inverted();
}
m_level.PasteSegments(m_lvl_buffer, aligned);
if (paste_entites) {
m_level.PasteEntities(m_lvl_buffer, aligned);
} else {
//If not pasting entities, must go through and clear Door value on pasted sides
m_level.ClearDoorReferences(m_lvl_buffer);
}
if (refresh) {
AddOutputText("Pasted buffer segments (" + (aligned ? "at side" : "at origin") + ")" + (paste_entites ? " with entities" : ""));
RefreshGeometry();
}
return true;
} else {
AddOutputText("Buffer has 0 segments");
return false;
}
}
public void PasteMirror(Axis axis)
{
SaveStateForUndo("Paste copied segments (mirror)");
if (PasteBufferSegments(false, false)) {
m_level.FlipMarkedSegments(axis, Vector3.Zero);
AddOutputText("Pasted buffer segments (mirrored)");
RefreshGeometry();
}
}
public Matrix4 ComputeRotationFromNormal(Vector3 normal)
{
// Rotate to align to the normal
if (Math.Abs(normal.Y) < (0.99f)) {
return Matrix4.LookAt(Vector3.Zero, normal, Vector3.UnitY);
} else {
return Matrix4.LookAt(Vector3.Zero, normal, Vector3.UnitX);
}
}
// Rotate and offset the position based on the src and dest side
public Vector3 AlignPasteVert(Vector3 v)
{
// Remove src side position
v -= m_src_side_pos;
// Rotate to align to src normal
v = Vector3.Transform(v, m_src_side_rotation);
// Rotate to align to dest normal
v = Vector3.Transform(v, m_dest_side_rotation);
// Add the dest side position
v += m_dest_side_pos;
return v;
}
public void MaybeFlipMarkedSegments(Axis axis)
{
if (!m_level.MarkedSegmentsAreIsolated()) {
AddOutputText("Marked segments must be isolated to flip them");
} else if (m_level.GetSelectedSide() == null) {
AddOutputText("Must have selected segment/side to flip marked segments");
} else {
SaveStateForUndo("Flip marked segments");
m_level.FlipMarkedSegments(axis, m_level.GetSelectedSidePos());
AddOutputText("Flipped the marked segments");
RefreshMarkedSegmentGMeshes();
RefreshGeometry();
}
}
public void MaybeRotateMarkedSegments(Axis axis, float rot, bool origin)
{
if (!m_level.MarkedSegmentsAreIsolated()) {
AddOutputText("Marked segments must be isolated to rotate them");
} else if (m_level.GetSelectedSide() == null) {
AddOutputText("Must have selected segment/side to rotate marked segments");
} else {
SaveStateForUndo("Rotate marked segments");
m_level.RotateMarkedSegments(axis, rot, (origin ? Vector3.Zero : m_level.GetSelectedSidePos()));
RefreshMarkedSegmentGMeshes();
RefreshGeometry();
}
}
public void IsolateMarkedSegments()
{
SaveStateForUndo("Isolate marked segments");
CopyMarkedSegments(true);
m_level.DeleteMarked(true);
PasteBufferSegments(false, false);
AddOutputText("Isolated the marked segments");
RefreshGeometry();
}
// TODO: Maybe make this a setting?
public const float JOIN_RANGE = 3f;
public void JoinSelectedSideToMarked()
{
if (!m_level.SelectedSegmentAlive()) {
AddOutputText("Must have a selected side for this operation");
return;
}
if (m_level.num_marked_sides == 1) {
if (!m_level.SelectedSideMarked()) {
SaveStateForUndo("Join sides");
// Move the selected side's verts to match the marked one's
Side selected = m_level.GetSelectedSide();
Side marked = m_level.FindFirstMarkedSide();
if (marked == null) {
Utility.DebugPopup("Could not find a marked side", "ERROR");
return;
}
m_level.JoinSides(selected, marked);
AddOutputText("Joined the selected side to the marked side");
RefreshGeometry();
} else {
AddOutputText("Can't join a side to itself");
}
} else {
SaveStateForUndo("Join sides nearby");
if (m_level.MaybeJoinSelectedSideToNearest(JOIN_RANGE)) {
AddOutputText("Joined the selected side to a nearby side");
RefreshGeometry();
} else {
AddOutputText("Could not find a side to join to.");
}
}
}
public void JoinMarkedSides()
{
if (m_level.num_marked_sides > 1) {
SaveStateForUndo("Join marked sides");
int count = m_level.JoinMarkedSides();
AddOutputText("Joined " + count + " pairs of marked sides");
RefreshGeometry();
} else {
AddOutputText("Must mark 2 or more adjacent sides");
}
}
//Returns true if at least two verts on check_side are in front of base_side, and none are behind
public bool SideInFrontOfSide(Side base_side, Side check_side)
{
Vector3 center = base_side.FindCenter();
Vector3 normal = -base_side.FindNormal();
int zero_count = 0;
for (int i = 0; i < Side.NUM_VERTS; i++) {
float dot = Vector3.Dot(m_level.vertex[check_side.vert[i]].position - center, normal);
if (dot < 0f) {
return false;
} else if (dot < 0.0001) {
zero_count++;
}
}
return (zero_count <= 2);
}
public void ConnectSelectedSideToMarkedWithSegment()
{
Side selected = m_level.GetSelectedSide();
if (selected == null) {
MessageBox.Show("Must have a selected side for this operation.");
return;
}
if (m_level.num_marked_sides == 0) {
MessageBox.Show("Must have a marked side for this operation.");
return;
}
if (m_level.num_marked_sides > 1) {
MessageBox.Show("Must have only one marked side for this operation.");
return;
}
Side marked = m_level.FindFirstMarkedSide();
if ((selected.segment.neighbor[selected.num] != -1) || (marked.segment.neighbor[marked.num] != -1)) {
MessageBox.Show("Selected and Marked sides must not have connections for this operaion.");
return;
}
//Check for any points on one face behind the other
if (!SideInFrontOfSide(selected, marked) || !SideInFrontOfSide(marked, selected)) {
MessageBox.Show("Selected and Marked sides must face each other for this operation.");
return;
}
SaveStateForUndo("Connect with segment");
//Insert the segment
int new_segnum = m_level.InsertSegmentBetween(selected, marked);
// Select the new segment (depending on the option)
if (m_insert_advance) {
m_level.selected_segment = new_segnum;
}
//Done
RefreshGeometry();
}
//Rotate the marked segments around the center point of the selected side
public void RotateAtSelectedSide(bool backwards)
{
Side selected_side = m_level.GetSelectedSide();
if (selected_side == null) {
MessageBox.Show("Must have a selected side for this operation.");
return;
}
if (!m_level.MarkedSegmentsAreIsolated()) {
MessageBox.Show("Marked segments must be isolated to rotate them");
return;
}
Segment selected_seg = selected_side.segment;
System.Diagnostics.Debug.Assert(selected_seg != null);
SaveStateForUndo("Rotate at Selected Side");
float angle = (float)m_rotate_angle / 180f * (float)Math.PI;
m_level.RotateMarkedSegments(selected_side.FindNormal(), backwards ? -angle : angle, selected_side.FindCenter());
RefreshGeometry();
}
public void MarkCoplanarSides()
{
if (m_level.selected_segment > -1 && m_level.selected_side > -1) {
SaveStateForUndo("Mark coplanar sides", false);
SetEditModeSilent(EditMode.SIDE);
m_level.UnTagAllSides();
m_level.TagSelectedSide();
m_level.TagCoplanarConnectedSides(m_level.segment[m_level.selected_segment].side[m_level.selected_side], ((float)m_coplanar_tol) * Utility.RAD_90 / 90f, true);
m_level.MarkTaggedSides();
AddOutputText("Marked coplanar sides");
RefreshGeometry();
}
}
public void MarkCoTextureSides()
{
if (m_level.selected_segment > -1 && m_level.selected_side > -1) {
SaveStateForUndo("Mark coplanar sides", false);
SetEditModeSilent(EditMode.SIDE);
m_level.UnTagAllSides();
m_level.TagSelectedSide();
m_level.TagCoTextureConnectedSides(m_level.segment[m_level.selected_segment].side[m_level.selected_side], true);
m_level.MarkTaggedSides();
AddOutputText("Marked coplanar sides");
RefreshGeometry();
}
}
public void MarkConnectedTextureSides()
{
if (m_level.selected_segment > -1 && m_level.selected_side > -1) {
SaveStateForUndo("Mark same-textured connected sides", false);
SetEditModeSilent(EditMode.SIDE);
m_level.UnTagAllSides();
m_level.TagSelectedSide();
m_level.TagCoplanarConnectedSides(m_level.segment[m_level.selected_segment].side[m_level.selected_side], ((float)m_coplanar_tol) * Utility.RAD_90 / 90f, true);
m_level.MarkTaggedSides();
AddOutputText("Marked coplanar sides");
RefreshGeometry();
}
}
public void MarkWallSides()
{
if (m_level.selected_segment > -1 && m_level.selected_side > -1) {
SaveStateForUndo("Mark wall sides", false);
SetEditModeSilent(EditMode.SIDE);
m_level.UnTagAllSides();
m_level.TagSelectedSide();
m_level.TagConnectedWallSides(m_level.segment[m_level.selected_segment].side[m_level.selected_side], 0.4f);
m_level.MarkTaggedSides();
AddOutputText("Marked wall sides");
RefreshGeometry();
}
}
public void MarkWallSidesStraight()
{
if (m_level.selected_segment > -1 && m_level.selected_side > -1) {
SaveStateForUndo("Mark wall sides straight", false);
SetEditModeSilent(EditMode.SIDE);
m_level.UnTagAllSides();
m_level.TagSelectedSide();
m_level.TagConnectedWallSidesStraight(m_level.segment[m_level.selected_segment].side[m_level.selected_side], 0.4f);
m_level.MarkTaggedSides();
AddOutputText("Marked wall sides on same XY plane");
RefreshGeometry();
}
}
public void FitFrameLevel(bool all, GLView view)
{
List<Vector3> pos_list = pos_list = m_level.AllVertexPositions();
if (all) {
gl_panel.FitFrame(pos_list);
} else {
view.FitFrame(pos_list);
}
}
public void FitFrameMarkedSelected(bool all, GLView view, bool dont_change_zoom = false)
{
List<Vector3> pos_list = m_level.AllMarkedVertexPositions(true);
if (all) {
gl_panel.FitFrame(pos_list, dont_change_zoom);
} else {
view.FitFrame(pos_list, dont_change_zoom);
}
}
public const float UV_SHIFT = 0.25f;
public const float UV_SHIFT_MINOR = UV_SHIFT / 8f;
public void MoveMarkedSideTextures(Vector2 dir, bool minor)
{
SaveStateForUndo("Move textures");
m_level.UVMoveMarkedSide(dir * (minor ? UV_SHIFT_MINOR : UV_SHIFT));
RefreshGeometry();
}
public const float UV_ROT = Utility.RAD_45;
public const float UV_ROT_MINOR = UV_ROT / 8f;
public void RotateMarkedSideTextures(float angle, bool minor)
{
SaveStateForUndo("Rotate textures");
m_level.UVRotateMarkedSide(angle * (minor ? UV_ROT_MINOR : UV_ROT));
RefreshGeometry();
}
public Axis AxisFromViewType(ViewType vt)
{
switch (vt) {
case ViewType.FRONT:
return Axis.Z;
case ViewType.RIGHT:
return Axis.X;
default:
case ViewType.TOP:
return Axis.Y;
}
}
public void SetActiveDecal(int idx)
{
m_decal_active = idx;
GeometryDecalsPane.UpdateDecalLabels();
}
public void CycleDecalAlignment(bool reverse)
{
Decal d = m_level.GetSelectedDecal(m_decal_active);
if (d != null) {
SaveStateForUndo("Decal cycle alignment");
d.CycleAlign(reverse);
GeometryDecalsPane.UpdateDecalLabels();
RefreshSelectedGMeshes();
RefreshGeometry();
}
}
public void CycleDecalMirror()
{
Decal d = m_level.GetSelectedDecal(m_decal_active);
if (d != null) {
SaveStateForUndo("Decal cycle mirror");
d.CycleMirror();
GeometryDecalsPane.UpdateDecalLabels();
RefreshSelectedGMeshes();
RefreshGeometry();
}
}
public void CycleDecalClip(int idx, bool reverse)
{
Decal d = m_level.GetSelectedDecal(m_decal_active);
if (d != null) {
SaveStateForUndo("Decal cycle clip");
d.CycleClip(idx, reverse);
GeometryDecalsPane.UpdateDecalLabels();
RefreshSelectedGMeshes();
RefreshGeometry();
}
}
public void SetDecalPresetClip(DecalClip dc1, DecalClip dc2, DecalClip dc3, DecalClip dc4)
{
Decal d = m_level.GetSelectedDecal(m_decal_active);
if (d != null) {
SaveStateForUndo("Decal set all 4 preset");
d.Set4Clips(dc1, dc2, dc3, dc4);
GeometryDecalsPane.UpdateDecalLabels();
RefreshSelectedGMeshes();
RefreshGeometry();
}
}
public void ResetDecalSettings()
{
Decal d = m_level.GetSelectedDecal(m_decal_active);
if (d != null) {
SaveStateForUndo("Decal reset repeat/rotation/offset settings");
d.ResetSettings();
GeometryDecalsPane.UpdateDecalLabels();
RefreshSelectedGMeshes();
RefreshGeometry();
}
}
public void ChangeDecalRepeat(int u, int v)
{
Decal d = m_level.GetSelectedDecal(m_decal_active);
if (d != null) {
SaveStateForUndo("Decal change repeat");
d.ChangeRepeat(u, v);
GeometryDecalsPane.UpdateDecalLabels();
RefreshSelectedGMeshes();
RefreshGeometry();
}
}
public void ChangeDecalOffset(int u, int v)
{
Decal d = m_level.GetSelectedDecal(m_decal_active);
if (d != null) {
SaveStateForUndo("Decal change offset");
d.ChangeOffset(u, v);
GeometryDecalsPane.UpdateDecalLabels();
RefreshSelectedGMeshes();
RefreshGeometry();
}
}
public void ChangeDecalRotation(int inc)
{
Decal d = m_level.GetSelectedDecal(m_decal_active);
if (d != null) {
SaveStateForUndo("Decal rotation");
d.ChangeRotation(inc);
GeometryDecalsPane.UpdateDecalLabels();
RefreshSelectedGMeshes();
RefreshGeometry();
}
}
public void ChangeSideDeformationHeight(int increment)
{
Side s = m_level.GetSelectedSide();
if (s != null) {
s.deformation_height = Utility.SnapValue(Utility.Clamp(s.deformation_height + increment * 0.05f, 0f, 2f), 0.05f);
TexturingPane.UpdateTextureLabels();
}
}
public void ChangeSplitPlaneOrder(int increment)
{
Side s = m_level.GetSelectedSide();
if (s != null) {
s.chunk_plane_order += increment;
if (s.chunk_plane_order < -1) {
s.chunk_plane_order = -1;
}
//if (false) {
// // DEBUG FUNCTION: Set the same split on all marked sides to make chunks segment-sized
// List<Side> side_list = m_level.GetMarkedSides(false);
// foreach (Side s1 in side_list) {
// if (s1.ConnectedSide() != null && s1.ConnectedSide().chunk_plane_order == -1) {
// s1.chunk_plane_order = s.chunk_plane_order;
// }
// }
//}
RefreshGeometry();
TexturingPane.UpdateTextureLabels();
}
}
public void CyclePathfinding(int increment)
{
Segment seg = m_level.GetSelectedSegment();
if (seg != null) {
seg.m_pathfinding = (PathfindingType)(((int)seg.m_pathfinding + (int)PathfindingType.NUM + increment) % (int)PathfindingType.NUM);
RefreshGeometry();
TexturingPane.UpdateTextureLabels();
}
}
public void CycleExitSegment(int increment)
{
Segment seg = m_level.GetSelectedSegment();
if (seg != null) {
seg.m_exit_segment_type = (ExitSegmentType)(((int)seg.m_exit_segment_type + (int)ExitSegmentType.NUM + increment) % (int)ExitSegmentType.NUM);
RefreshGeometry();
TexturingPane.UpdateTextureLabels();
}
}
public void ToggleDark()
{
Segment seg = m_level.GetSelectedSegment();
if (seg != null) {
seg.m_dark = !seg.m_dark;
RefreshGeometry();
TexturingPane.UpdateTextureLabels();
}
}
public void CopySideDeformationHeightToMarked()
{
Side s = m_level.GetSelectedSide();
if (s != null) {
List<Side> s_list = m_level.GetMarkedSides();
for (int i = 0; i < s_list.Count; i++) {
s_list[i].deformation_height = s.deformation_height;
}
}
}
public void SetSplitPlaneOrder(int order)
{
Side s = m_level.GetSelectedSide();
if (s != null) {
s.chunk_plane_order = order;
RefreshGeometry();
}
}
public void CopyDecalPropertiesToMarked(int idx)
{
Decal d = m_level.GetSelectedDecal(idx);
if (d != null) {
SaveStateForUndo("Decal copy properties");
m_level.CopyDecalPropertiesToMarked(d, idx);
RefreshMarkedSideGMeshes();
RefreshGeometry();
}
}
public void ToggleMarkedDecalHidden(int idx)
{
//first determine if any are hidden
bool any_hidden = false;
foreach (Decal d in m_level.GetMarkedAppliedDecals(idx)) {
if (d.hidden) {
any_hidden = true;
break;
}
}
//Now hide or unhide based on whether any were hidden
foreach (Decal d in m_level.GetMarkedAppliedDecals(idx)) {
d.hidden = !any_hidden;
}
GeometryDecalsPane.UpdateDecalLabels();
RefreshMarkedSideGMeshes();
RefreshGeometry();
}
public void ToggleDecalHidden(int idx)
{
Decal d = m_level.GetSelectedDecal(idx);
if (d != null) {
SaveStateForUndo("Decal hidden toggle");
d.hidden = !d.hidden;
GeometryDecalsPane.UpdateDecalLabels();
RefreshSelectedGMeshes();
RefreshGeometry();
}
}
public void SnapMarkedElementsToGrid()
{
SaveStateForUndo("Snap marked elements to grid");
m_level.SnapMarkedToGrid();
}
public void RotatedMarkedEntities(Axis axis, float dir, bool minor)
{
SaveStateForUndo("Rotate marked entites");
m_level.RotateMarkedEntities(axis, dir * Utility.RAD_45 * (minor ? 0.25f : 1f));
}
public void ScaleMarkedElements(GLView view, bool up, bool minor)
{
SaveStateForUndo("Scale marked elements");
float amt = 1f;
if (up) {
amt = (minor ? 1.1f : 2f);
} else {
amt = (minor ? 1f / 1.1f : 0.5f);
}
m_level.ScaleMarked(view, m_scale_mode, amt);
RefreshGeometry();
}
public ScaleMode m_scale_mode = ScaleMode.VIEW_XY;
public void ScaleMarkedElementsRaw(GLView view, float amtx = 1f, float amty = 1f)
{
if (m_scale_mode == ScaleMode.FREE_XY) {
m_level.ScaleMarked(view, ScaleMode.VIEW_X, amtx);
m_level.ScaleMarked(view, ScaleMode.VIEW_X, amty);
} else {
m_level.ScaleMarked(view, m_scale_mode, amtx);
}
RefreshGeometry();
}
public void RotatedMarkedElements(GLView view, float amt, bool minor)
{
SaveStateForUndo("Rotate marked elements");
m_level.RotateMarked(view, Utility.RAD_45 * amt * (minor ? 0.125f : 1f));
RefreshGeometry();
}
public void RotateMarkedElementsRaw(GLView view, float amt)
{
m_level.RotateMarked(view, amt);
RefreshGeometry();
}
public void MoveMarkedElements(GLView view, Vector3 dir, bool minor)
{
SaveStateForUndo("Move marked elements");
m_level.MoveMarked(view, dir, m_grid_snap * (minor ? 0.25f : 1f));
}
public void InsertMarkedSides()
{
SaveStateForUndo("Insert segment(s)");
if (m_level.InsertMarkedSides()) {
RefreshTaggedSegmentGMeshes();
RefreshGeometry();
AddOutputText("Inserted segments on marked sides");
}
}
public void InsertSelectedSide(bool regular)
{
SaveStateForUndo("Insert segment");
if (m_level.InsertSegmentSelectedSide(regular) != -1) {
RefreshTaggedSegmentGMeshes();
RefreshGeometry();
AddOutputText("Inserted new segment");
}
}
public void DeleteMarked()
{
SaveStateForUndo("Delete marked");
m_level.DeleteMarked();
m_level.CompactLevelSegments();
RefreshLevelGmesh();
RefreshGeometry();
}
public void ClearAllMarked()
{
SaveStateForUndo("Clear all marked", false);
m_level.ClearAllMarked();
RefreshGeometry();
}
public void ToggleMarkAll()
{
SaveStateForUndo("Toggle mark all", false);
m_level.ToggleMarkAll();
RefreshGeometry();
}
public void ToggleMarkSelected()
{
SaveStateForUndo("Toggle mark selected", false);
m_level.ToggleMarkSelected();
RefreshGeometry();
}
public void SetMarkedRobotsStation(bool station)
{
SaveStateForUndo("Marked robots set to station: " + station, false);
m_level.SetMarkedRobotsStation(station);
EntityEditPane.UpdateEntityLabels();
RefreshGeometry();
}
public void SetMarkedRobotsNGP(bool ngp)
{
SaveStateForUndo("Marked robots set to New Game Plus: " + ngp, false);
m_level.SetMarkedRobotsNGP(ngp);
EntityEditPane.UpdateEntityLabels();
RefreshGeometry();
}
public void SelectAdjacentSegment()
{
SaveStateForUndo("Select adjacent segment", false);
m_level.SelectAdjacentSegment();
RefreshGeometry();
}
public void SelectOppositeSegment()
{
SaveStateForUndo("Select opposite segment", false);
m_level.SelectOppositeSegment();
RefreshGeometry();
}
public void CycleSelectedSegment(bool prev)
{
SaveStateForUndo("Cycle selected segment", false);
m_level.CycleSelectedSegment(prev);
RefreshGeometry();
}
public void CycleSelectedSide(bool prev)
{
SaveStateForUndo("Cycle selected side", false);
m_level.CycleSelectedSide(prev);
RefreshGeometry();
}
public void CycleSelectedEntity(bool prev)
{
SaveStateForUndo("Cycle selected entity", false);
m_level.CycleSelectedEntity(prev);
RefreshGeometry();
}
public void SetSelectedEntitySubType(int index)
{
SaveStateForUndo("Change entity subtype");
m_level.SetSelectedEntitySubType(index);
EntityEditPane.UpdateEntityLabels();
RefreshGeometry();
}
//Returns entity number
private int DoCreateEntity(int segnum, Vector3 pos, Vector3 dir)
{
SaveStateForUndo("Place new entity");
//Get type & subtype
EntityType type = (EntityType)EntityEditPane.comboBox_entity_type.SelectedIndex;
if (type == EntityType.ITEM) {
dir = Vector3.UnitZ;
}
Entity selected_entity = m_level.GetSelectedEntity();
int subtype = ((selected_entity != null) && (selected_entity.Type == type)) ? selected_entity.SubType : 0;
//Create the entity
int entity_num = m_level.CreateEntity(segnum, pos, dir, type, subtype);
//Leave just this new entity marked
m_level.MarkAllEntities(false);
m_level.entity[entity_num].marked = true;
//Update the windows
RefreshGeometry();
//Done
return entity_num;
}
public void CreateEntityInSegment()
{
DoCreateEntity(m_level.selected_segment, m_level.GetSelectedSegmentPos(), -m_level.GetSelectedSideNormal());
}
public void CreateEntityOnSide()
{
Debug.Assert((m_level.GetSelectedSide().Door == -1) || ((EntityType)EntityEditPane.comboBox_entity_type.SelectedIndex != EntityType.DOOR));
int entity_num = DoCreateEntity(m_level.selected_segment, m_level.GetSelectedSidePos(), m_level.GetSelectedSideNormal());
//If placing a door, point the side to the door & set the split plane (if not already split)
if (m_level.entity[entity_num].Type == EntityType.DOOR) {
m_level.GetSelectedSide().Door = entity_num;
if (m_level.GetSelectedSide().chunk_plane_order == -1) {
m_level.GetSelectedSide().chunk_plane_order = 0;
}
}
RefreshGeometry();
}
public void EntityResetRotation()
{
SaveStateForUndo("Reset entity rotation");
m_level.EntityResetRotation();
this.Refresh();
}
public int EntityMarkedResetRotation()
{
SaveStateForUndo("Reset entity rotation");
int num = m_level.EntityMarkedResetRotation();
this.Refresh();
return num;
}
public void EntityFaceSelectedSide()
{
SaveStateForUndo("Entity face selected side");
m_level.EntityFaceSelectedSide();
this.Refresh();
}
public int EntityMarkedFaceSelectedSide()
{
SaveStateForUndo("Entity face selected side");
int num = m_level.EntityMarkedFaceSelectedSide();
this.Refresh();
return num;
}
public void EntityCycleTeam()
{
SaveStateForUndo("Entity face selected side");
m_level.EntityCycleTeam();
EntityEditPane.UpdateEntityLabels();
}
public int DuplicateMarkedEntities()
{
SaveStateForUndo("Duplicate marked entities");
int num = m_level.DuplicateMarkedEntities();
RefreshGeometry();
return num;
}
public void EntityMoveToSide()
{
Debug.Assert((m_level.GetSelectedSide().Door == -1) || (m_level.GetSelectedEntity().Type != EntityType.DOOR) || (m_level.GetSelectedSide().Door == m_level.GetSelectedEntity().num));
SaveStateForUndo("Entity move to selected side");
m_level.EntityMoveToSide();
EntityEditPane.UpdateEntityLabels();
this.Refresh();
}
public void EntityAlignToSide()
{
SaveStateForUndo("Entity align to selected side");
m_level.EntityAlignToSide();
this.Refresh();
}
public void EntityMoveToSegment()
{
SaveStateForUndo("Entity move to selected segment");
m_level.EntityMoveToSegment();
EntityEditPane.UpdateEntityLabels();
this.Refresh();
}
public void ApplyTexture(string s, int idx)
{
SaveStateForUndo("Apply texture to side(s)");
m_level.ApplyTexture(s, idx);
RefreshGeometry();
}
public void MarkSidesWithTexture(string s)
{
SaveStateForUndo("Mark sides with texture");
m_level.MarkSidesWithTexture(s);
RefreshGeometry();
}
public string GetSelectedSideTexture()
{
return m_level.GetSelectedSideTexture();
}
public void MarkSidesWithCavePreset(int idx, bool same_height = false)
{
SaveStateForUndo("Mark sides with cave preset");
m_level.MarkSidesWithCavePreset(idx, same_height);
RefreshGeometry();
}
public int GetSelectedSideCavePreset()
{
return m_level.GetSelectedSideCavePreset();
}
public void SetSideCavePreset(int idx)
{
SaveStateForUndo("Set cave preset");
m_level.SetSideCavePreset(idx);
RefreshGeometry();
}
public void ApplyDecal(DMesh dm, int idx)
{
SaveStateForUndo("Apply decal to side(s)");
List<Side> side_list = m_level.GetMarkedSides();
//Apply to selected if no marked
if (side_list.Count == 0) {
Side side = m_level.GetSelectedSide();
if (side != null) {
m_level.ApplyDecal(side, dm, idx);
RefreshSelectedGMeshes();
}
} else {
//Apply to all marked
foreach (Side side in side_list) {
m_level.ApplyDecal(side, dm, idx);
}
RefreshMarkedSideGMeshes();
}
RefreshGeometry();
}
public Guid m_entity_prev_guid = Guid.Empty;
public void ELLFeedback(object sender, EntityLinkLabelArgs e)
{
Entity entity = m_level.GetSelectedEntity();
if (entity != null) {
switch (e.Button) {
case MouseButtons.Left:
if (e.Shift) {
entity.ClearLink(e.Index);
m_entity_prev_guid = Guid.Empty;
} else {
List<Entity> e_list = m_level.GetMarkedEntities();
if (e_list.Count > 0) {
entity.AssignLink(e.Index, e_list[0].guid);
e_list[0].marked = false;
m_entity_prev_guid = Guid.Empty;
}
}
break;
case MouseButtons.Right:
case MouseButtons.Middle:
Guid guid = entity.GetLinkGUID(e.Index);
Entity linked_e = m_level.FindEntityWithGUID(guid);
if (linked_e != null) {
if (e.Button == MouseButtons.Right) {
linked_e.marked = true;
} else {
m_level.selected_entity = linked_e.num;
}
}
break;
}
}
RefreshGeometry();
}
public string EntityGUIDString(Guid guid)
{
if (guid == Guid.Empty) {
return " - ";
}
Entity e = m_level.FindEntityWithGUID(guid);
if (e != null) {
return string.Format("{0} - {1}", e.Type, guid.ToPrettyString());
}
return "<missing>";
}
public void UpdateCountLabels()
{
var level = m_level;
label_count_total.Text = "Total: " + level.num_segments.ToString() + "/" + level.num_sides.ToString() + "/" + level.num_vertices.ToString();
label_count_marked.Text = "Marked: " + level.num_marked_segments.ToString() + "/" + level.num_marked_sides.ToString() + "/" + level.num_marked_vertices.ToString();
label_count_selected.Text = "Selected: " + (level.selected_segment < 0 ? "--" : level.selected_segment.ToString()) + "/" +
(level.selected_side < 0 ? "--" : level.selected_side.ToString()) + "/" +
(level.selected_vertex < 0 ? "--" : level.selected_vertex.ToString());
}
public void AddOutputText(string s)
{
OutputPane.AddText(s);
}
bool NewOrLoadLevelHelper(Func<Tuple<Level, string>> acquire_level)
{
try {
var level_path_tuple = acquire_level();
if (level_path_tuple == null || level_path_tuple.Item1 == null) {
return false;
}
this.m_level = level_path_tuple.Item1;
string path_to_file = level_path_tuple.Item2;
Shell.CurrentLevelFilePath = path_to_file;
m_level.GetTextureSet(false); //This will set to a valid set if the default is invalid
gl_panel.DeleteGMesh();
EntityListPane.Populate();
LevelGlobalPane.UpdateLabels();
LevelCustomInfoPane.Populate();
if (string.IsNullOrWhiteSpace(path_to_file)) {
this.Text = "<New Level>";
AddOutputText("Created new level");
} else {
this.Text = Path.GetFileName(path_to_file);
AddOutputText(string.Format("Loaded level: {0}", path_to_file));
AddRecentFile(path_to_file);
}
return true;
}
catch (Exception ex) {
MessageBox.Show(string.Format("Error initializing level: {0}", ex.Message), "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
return false;
}
}
public void NewLevel()
{
NewOrLoadLevelHelper(() => new Tuple<Level, string>(new Level(this), null));
}
public bool LoadLevel(string path_to_file)
{
return NewOrLoadLevelHelper(() => {
var fileData = System.IO.File.ReadAllText(path_to_file);
var root = JObject.Parse(fileData);
var newLevel = new Level(this);
newLevel.Deserialize(root);
newLevel.dirty = false;
//Look for entites without segment & entites in segments that are not alive
string bad_segnums = "";
foreach (Entity entity in newLevel.EnumerateAliveEntities()) {
if ((entity.m_segnum == -1) || (!newLevel.segment[entity.m_segnum].Alive)) {
entity.m_segnum = newLevel.FindSegmentForPoint(entity.position);
if (entity.m_segnum == -1) {
bad_segnums += entity.num + " ";
}
}
}
if (bad_segnums != "") {
AddOutputText("These entities are not in a segment " + bad_segnums);
}
// Compact the segment array down to remove dead segment slots
newLevel.CompactLevelSegments();
return new Tuple<Level, string>(newLevel, path_to_file);
});
}
public bool SaveLevel(string path_to_file, bool silent = false)
{
try {
// Compact the segment array down to remove dead segment slots
this.m_level.CompactLevelSegments();
var root = new JObject();
this.m_level.Serialize(root);
var fileData = root.ToString(Formatting.Indented);
System.IO.File.WriteAllText(path_to_file, fileData);
if (!silent) {
Shell.CurrentLevelFilePath = path_to_file;
this.Text = Path.GetFileName(path_to_file);
AddOutputText(string.Format("Saved level: {0}", path_to_file));
AddRecentFile(path_to_file);
m_level.dirty = false;
}
return true;
}
catch (Exception ex) {
if (!silent) {
MessageBox.Show(string.Format("Failed to save level: {0}", ex.Message));
}
return false;
}
}
public bool ExportLevel(string inputLevelPath, string outputPath, OverloadLevelExport.LevelType exportLevelType)
{
try {
try {
UnityEngine.Debug.LogCallback = (int level, string msg) => {
string tag = "INFO";
switch (level) {
case 1:
tag = "WARN";
break;
case 2:
tag = "ERROR";
break;
}
AddOutputText(string.Format("{0}: {1}", tag, msg));
};
using (var serializer = new OverloadLevelConvertSerializer(outputPath, true)) {
// Serializer header
OverloadLevelConverter.WriteSerializationLevelHeader(serializer, (uint)exportLevelType);
using (OverloadLevelExport.SceneBroker sceneBroker = new OverloadLevelExport.SceneBroker(serializer, exportLevelType)) {
serializer.Context = sceneBroker;
OverloadLevelExport.SceneBroker.ActiveSceneBrokerInstance = sceneBroker;
try {
OverloadLevelConverter.ConvertLevel(inputLevelPath, Path.GetFileNameWithoutExtension(outputPath), this.m_filepath_root, sceneBroker);
// Last packet is the 'Done' packet
var doneCmd = new OverloadLevelExport.CmdDone();
doneCmd.Serialize(serializer);
} finally {
serializer.Context = null;
OverloadLevelExport.SceneBroker.ActiveSceneBrokerInstance = null;
}
}
}
} finally {
UnityEngine.Debug.LogCallback = null;
GC.Collect();
}
return true;
} catch (Exception ex) {
MessageBox.Show(string.Format("Failed to export level: {0}", ex.Message));
return false;
}
}
public void ExportSimpleMission(string output_path, string output_name, string level_name)
{
if (output_name != null && output_name != "" && output_path != null && output_path != "") {
output_name = Path.Combine(output_path, output_name);
if (File.Exists(output_name)) {
AddOutputText("The mission file already exists: " + output_name);
return;
}
TextWriter w = new StreamWriter(output_name);
w.WriteLine("# Default Mission File for custom mission (" + level_name + ")");
w.WriteLine("display_name: # MISSION NAME");
string visible_name = level_name.Replace('_', ' ').ToUpper();
w.WriteLine(" EN: " + visible_name);
w.WriteLine(" ES: " + visible_name);
w.WriteLine(" FR: " + visible_name);
w.WriteLine(" DE: " + visible_name);
w.WriteLine(" RU: " + visible_name);
w.WriteLine("levels:");
w.WriteLine(" - name: # LEVEL NAME");
w.WriteLine(" EN: " + visible_name);
w.WriteLine(" ES: " + visible_name);
w.WriteLine(" FR: " + visible_name);
w.WriteLine(" DE: " + visible_name);
w.WriteLine(" RU: " + visible_name);
w.WriteLine(" scene: " + level_name);
w.WriteLine(" music: outer_01");
w.WriteLine(" # BRIEFING? weapons: [impulse]");
w.WriteLine(" # BRIEFING? missiles: [falcon, missile_pod]");
w.WriteLine(" # BRIEFING? robots: [grunta, gruntb, recoila]");
w.WriteLine(" upgrade_points: 0");
w.WriteLine(" super_upgrade_points: 0");
w.WriteLine(" ammo: 0");
w.WriteLine(" loadout:");
w.WriteLine(" impulse: 0 # Number is [unlock level]");
w.WriteLine(" falcon: [0, 10] # Numbers are [unlock level, ammo]");
w.WriteLine("# ADDITIONAL LEVELS GO HERE");
w.Close();
AddOutputText("Created a default mission file for: " + level_name);
} else {
AddOutputText("Could not find the directory or filename to create a mission file");
}
}
public void GenerateCMData(string output_path, string output_name, string level_name)
{
if (output_name != null && output_name != "" && output_path != null && output_path != "") {
output_name = Path.Combine(output_path, output_name);
if (File.Exists(output_name)) {
AddOutputText("The CM data file already exists: " + output_name);
return;
}
TextWriter w = new StreamWriter(output_name);
w.WriteLine("CHALLENGE_DATA");
w.WriteLine("// Challenge mode data for custom level (" + level_name + ")");
w.WriteLine("");
w.WriteLine("$desc_english CUSTOM LEVEL DESCRIPTION");
w.WriteLine("$desc_spanish CUSTOM LEVEL DESCRIPTION");
w.WriteLine("$desc_french CUSTOM LEVEL DESCRIPTION");
w.WriteLine("$desc_german CUSTOM LEVEL DESCRIPTION");
w.WriteLine("$desc_russian CUSTOM LEVEL DESCRIPTION");
w.WriteLine("");
w.WriteLine("$music; outer_01 // outer_01 - 05, titan_06 - 10, inner_11 - 12, alien_13 - 16, outer/titan/alien_boss");
w.WriteLine("// More or less bots (additive) in countdown/infinite for this level (0 is default, can go higher than 1 for very large levels)");
w.WriteLine("$robot_count_booster_infinite; 0.0");
w.WriteLine("$robot_count_booster_countdown; 0.0");
w.WriteLine("");
w.WriteLine("$group1_robots; 2 // Up to 5 groups allowed, with any number of robots per group");
w.WriteLine("$robot; hulkb; 0.25; 0.1 // First number is the relative frequency a certain robot type will spawn (overall, not at any given time)");
w.WriteLine("$robot; hulka; 0.25; 0.1 // Second number is a modifier on how hard robot is considered for the level (higher = harder, 0 = default)");
w.WriteLine("$robot; vipera; 0.25; 0.1 // Some robot types have additonal restrictions in code that cannot be altered (max count at once, for instance)");
w.WriteLine("");
w.WriteLine("$group2_robots; 2");
w.WriteLine("$robot; cannonb; 0.5; 0");
w.WriteLine("$robot; recoilb; 0.6; 0");
w.WriteLine("$robot; gruntb; 0.5; 0");
w.WriteLine("$robot; droneb; 0.3; 0");
w.WriteLine("");
w.WriteLine("$group3_robots; 2");
w.WriteLine("$robot; bladesa; 0.3; 0");
w.WriteLine("$robot; detonatora; 0.3; 0");
w.WriteLine("$robot; clawbota; 0.3; 0");
w.WriteLine("");
w.WriteLine("$super_robots; 3 // Number of super robot types and their appearance rate");
w.WriteLine("$super_robot; hulka; 0.8");
w.WriteLine("$super_robot; cannonb; 1.0");
w.WriteLine("$super_robot; recoila; 1.0");
w.WriteLine("$super_robot; gruntb; 1.0");
w.WriteLine("$super_robot; cannona; 1.0");
w.WriteLine("$super_robot; grunta; 1.0");
w.WriteLine("");
w.WriteLine("$robot_variant; recoila; 0.5 // Chance a certain robot type will be a variant (during a playthrough). Only 7 bots have variants");
w.WriteLine("$robot_variant; recoilb; 0.5");
w.WriteLine("$robot_variant; hulka; 0.5");
w.WriteLine("$robot_variant; dronea; 0.5");
w.WriteLine("$robot_variant; droneb; 0.5");
w.WriteLine("$robot_variant; grunta; 0.5");
w.WriteLine("$robot_variant; gruntb; 0.5");
w.WriteLine("");
w.WriteLine("CHALLENGE_DATA_END");
w.Close();
AddOutputText("Created default CM data file for: " + level_name);
} else {
AddOutputText("Could not find the directory or filename to create a CM data file");
}
}
public DMesh GetDMeshByName(string name)
{
foreach (DMesh dmesh in decal_list.m_dmesh) {
if (dmesh.name == name) {
return dmesh;
}
}
return null;
}
public void AddRecentFile(string filename)
{
if (MaybeRecentFilesSwap(filename)) {
// Already swapped inside MaybeRecentFilesSwap
} else {
for (int i = NumRecentFiles - 1; i > 0; i--) {
SetRecentFile(i, GetRecentFile(i - 1));
}
SetRecentFile(0, filename);
}
Shell.UpdateRecentFileMenu();
}
public bool MaybeRecentFilesSwap(string filename)
{
for (int i = 0; i < NumRecentFiles; i++) {
if (GetRecentFile(i) != filename) {
continue;
}
// Swap with the first item if it's in the list
string s = GetRecentFile(0);
SetRecentFile(0, filename);
SetRecentFile(i, s);
return true;
}
return false;
}
//Returns the number of errors found
public int CheckLevelValidity(bool mark_bad_segements = false)
{
int error_count = 0;
if (mark_bad_segements) {
ClearAllMarked();
}
//Check for the right number of verts in segment sides (not sure exactly what error this is checking for -Matt)
foreach (Segment seg in m_level.EnumerateAliveSegments()) {
int old_error_count = error_count;
List<int> seg_verts = new List<int>();
int sv_count = 0;
for (int j = 0; j < Segment.NUM_SIDES; j++) {
for (int k = 0; k < Side.NUM_VERTS; k++) {
if (!seg_verts.Contains(seg.side[j].vert[k])) {
seg_verts.Add(seg.side[j].vert[k]);
sv_count += 1;
}
if (seg.side[j].FindAdjacentSideSameSegment(k) == null) {
AddOutputText("Could not find the adjacent side for a segment " + seg.num + " side " + j);
error_count++;
}
}
}
if (sv_count != 8) {
AddOutputText("A segment had the wrong number of verts within the sides (" + sv_count + "), segment #: " + seg.num);
error_count++;
}
//Check for two verts in a segment that are very close together
bool overlapping = false;
for (int h = 0; h < Segment.NUM_VERTS; h++) {
for (int g = h + 1; g < Segment.NUM_VERTS; g++) {
Vector3 diff = (m_level.vertex[seg.vert[h]].position - m_level.vertex[seg.vert[g]].position);
if (diff.LengthSquared < 0.0001f) {
overlapping = true;
}
}
}
if (overlapping) {
AddOutputText("Two verts are overlapping in segment #: " + seg.num);
error_count++;
}
//Check for degenerate faces
if (SegmentDegenerateFacesNear(seg)) {
error_count++;
}
//Check for reciprocal connections
for (int sidenum = 0; sidenum < 6; sidenum++) {
int neighbor = seg.neighbor[sidenum];
if (neighbor > -1) {
try {
m_level.segment[neighbor].FindConnectingSide(seg.num);
}
catch {
AddOutputText("Segment " + seg.num + " side " + sidenum + " connects to segment " + neighbor + " but that segment doesn't connect back.");
error_count++;
}
}
}
//Mark this segment if errors found
if (mark_bad_segements && (error_count != old_error_count)) {
seg.marked = true;
}
}
//Check for missing decals
foreach (Segment segment in m_level.EnumerateAliveSegments()) {
foreach (Side side in segment.side) {
foreach (Decal decal in side.decal) {
if (!string.IsNullOrEmpty(decal.mesh_name) && !decal.hidden) {
if (side.level.editor.GetDMeshByName(decal.mesh_name) == null) {
AddOutputText("Segment " + segment.num + " Side " + side.num + " specifies invalid decal '" + decal.mesh_name + "'.");
error_count++;
if (mark_bad_segements) {
segment.marked = side.marked = true;
}
}
}
}
}
}
//Clear tag for all doors
foreach (Entity door in m_level.EnumerateAliveEntities(EntityType.DOOR)) {
door.tag = false;
}
//Make sure segment -> door connections are right
foreach (Segment segment in m_level.EnumerateAliveSegments()) {
int old_error_count = error_count;
foreach (Side side in segment.side) {
//Check doors
if (side.Door != -1) {
Entity door = m_level.entity[side.Door];
//Make sure the entity pointed to is a valid door
if (!door.alive) {
AddOutputText("Segment " + segment.num + " Side " + side.num + " specifies entity " + door.num + " as a door, but that entity is not alive.");
error_count++;
} else if (door.Type != EntityType.DOOR) {
AddOutputText("Segment " + segment.num + " Side " + side.num + " specifies entity " + door.num + " as a door, but it not.");
if (mark_bad_segements) {
door.marked = true;
}
error_count++;
} else {
//Flag this door as having been found
door.tag = true;
//Make sure door and segment point at each other
if (door.m_segnum != segment.num) {
AddOutputText("Segment " + segment.num + " Side " + side.num + " contains door " + door.num + " but door says it's in segment " + door.m_segnum);
if (mark_bad_segements) {
door.marked = true;
}
error_count++;
}
//Make sure the door is properly located
//AddOutputText("Door distance from center: " + (door.position - side.FindCenter()).Length);
if ((door.position - side.FindCenter()).Length > 0.1f) { //Need to check this constant
AddOutputText("Door (entity " + door.num + ") is not at center of side (segment = " + segment.num + ", side = " + side.num + ").");
if (mark_bad_segements) {
door.marked = true;
}
error_count++;
}
//Make sure there's a connection on the other side of this door
if (segment.neighbor[side.num] == -1) {
AddOutputText("Door (entity " + door.num + " in segment " + segment.num + ") does not connect to another segment.");
error_count++;
}
//Make sure the side has a separation plane
if (side.chunk_plane_order == -1) {
AddOutputText("Segment " + segment.num + " side " + side.num + " contains a door but has its sort order set to OFF.");
error_count++;
}
}
}
}
//Mark segment if errors found
if (mark_bad_segements && (error_count != old_error_count)) {
segment.marked = true;
}
}
//Make sure we found a segment side for each door
foreach (Entity door in m_level.EnumerateAliveEntities(EntityType.DOOR)) {
if (!door.tag) {
AddOutputText("Door " + door.num + ": There is no segment/side that owns this door. The door says it belongs to segment " + door.m_segnum + ".");
if (mark_bad_segements) {
door.marked = true;
}
error_count++;
}
}
//Make sure each entity (except scripts & doors) is in the segment it thinks it's in
foreach (Entity entity in m_level.EnumerateAliveEntities()) {
if ((entity.Type != EntityType.SCRIPT) && (entity.Type != EntityType.DOOR)) {
if (!entity.InSegment()) {
if (entity.m_segnum == -1) {
AddOutputText("Entity " + entity.num + " is marked as being in segment -1");
} else {
AddOutputText("Entity " + entity.num + " thinks it's in segment " + entity.m_segnum + " but it is not.");
}
if (mark_bad_segements) {
entity.marked = true;
}
error_count++;
}
}
}
//Update display if we've marked bad segments
if (mark_bad_segements && (error_count > 0)) {
RefreshGeometry();
}
AddOutputText("Done testing validity");
return error_count;
}
public void RemoveInvalidDoorReferences()
{
int count = 0;
foreach (Segment segment in m_level.EnumerateAliveSegments()) {
foreach (Side side in segment.side) {
if (side.Door != -1) {
Entity door = m_level.entity[side.Door];
//Make sure the entity pointed to is a valid door
if (!door.alive) {
count++;
side.Door = -1;
} else if (door.Type != EntityType.DOOR) {
count++;
side.Door = -1;
}
}
}
}
AddOutputText("Removed " + count + " invalid door references");
}
public void MakeAllDoorsBeSplitPlanes(int order = 5)
{
foreach (Segment segment in m_level.EnumerateAliveSegments()) {
foreach (Side side in segment.side) {
if (side.Door != -1) {
if (side.chunk_plane_order == -1) {
side.chunk_plane_order = 5;
}
}
}
}
}
public void ClearSplitPlanes()
{
foreach (Segment segment in m_level.EnumerateAliveSegments()) {
foreach (Side side in segment.side) {
side.chunk_plane_order = -1;
}
}
}
//Find all segments that are too small for a robot to pass through, and mark it as no pathfinding
public void FindImpassibleSegments()
{
string impassible_segments = "";
foreach (Segment segment in m_level.EnumerateAliveSegments()) {
Vector3 segment_center = segment.FindCenter();
bool impassible = false;
//Check for a solid wall too close to the center
foreach (Side side in segment.side) {
Vector3 side_center = side.FindCenter();
if (!side.HasNeighbor) { //If side is solid, check that it's not too close to the segment center
if (Vector3.Subtract(segment_center, side_center).LengthSquared < 0.64f) {
impassible = true;
}
}
//else { //If side is open, check that the opening is big enough
// for (int edge_num = 0; edge_num < 4; edge_num++) {
// Side adjacent_side = side.FindAdjacentSideOtherSegment(edge_num);
// if (!adjacent_side.HasNeighbor) {
// Vector3 edge_center = side.FindEdgeCenter(edge_num);
// if (Vector3.Subtract(side_center, edge_center).LengthSquared < 0.64f) {
// impassible = true;
// break; //break out of edge loop
// }
// }
// }
//}
if (impassible) {
segment.m_pathfinding = PathfindingType.None;
impassible_segments += segment.num + ",";
break; //break of out of side loop
}
}
}
if (impassible_segments == "") {
AddOutputText("No impassible segments found.");
} else {
AddOutputText("Marked segments as impassible: " + impassible_segments.Substring(0, impassible_segments.Length - 1));
}
}
// Mark all impassible segments (GB or No PF)
public void MarkImpassibleSegments()
{
bool impassible;
m_level.ClearAllMarked();
SetEditModeSilent(EditMode.SEGMENT);
foreach (Segment segment in m_level.EnumerateAliveSegments()) {
impassible = ((segment.m_pathfinding == PathfindingType.None) || (segment.m_pathfinding == PathfindingType.GB));
if (impassible) {
segment.marked = true;
}
}
RefreshGeometry();
}
public void AllRobotsDropPowerups()
{
int count_switch = 0;
int count_total = 0;
foreach (Entity entity in m_level.EnumerateAliveEntities()) {
if (entity.Type == EntityType.ENEMY) {
if (((Overload.EntityPropsRobot)entity.entity_props).replace_default_drop) {
((Overload.EntityPropsRobot)entity.entity_props).replace_default_drop = false;
count_switch += 1;
}
count_total += 1;
}
}
AddOutputText("Switched this many robots to drop powerups: " + count_switch + " out of " + count_total);
RefreshGeometry();
}
public void CopyEntityStatsClipboard()
{
string output_text = "";
output_text += "--Enemies--\n";
int[] count_normal = new int[(int)Overload.EnemyType.NUM];
int[] count_variant = new int[(int)Overload.EnemyType.NUM];
int[] count_super = new int[(int)Overload.EnemyType.NUM];
int count_ngp = 0;
int count_station = 0;
int count_dropped = 0;
foreach (Entity entity in m_level.EnumerateAliveEntities()) {
if (entity.Type == EntityType.ENEMY) {
if (((Overload.EntityPropsRobot)entity.entity_props).super) {
count_super[entity.SubType] += 1;
} else if (((Overload.EntityPropsRobot)entity.entity_props).variant) {
count_variant[entity.SubType] += 1;
} else {
count_normal[entity.SubType] += 1;
}
if (((Overload.EntityPropsRobot)entity.entity_props).bonus_drop1 == Overload.ItemPrefab.entity_item_log_entry) {
count_dropped += 1;
}
if (((Overload.EntityPropsRobot)entity.entity_props).ng_plus) {
count_ngp += 1;
}
if (((Overload.EntityPropsRobot)entity.entity_props).station) {
count_station += 1;
}
}
}
for (int i = 0; i < count_normal.Length; i++) {
if (count_normal[i] > 0) {
output_text += " " + ((Overload.EnemyType)i).ToString() + " NORMAL\t" + count_normal[i] + "\n";
}
if (count_variant[i] > 0) {
output_text += " " + ((Overload.EnemyType)i).ToString() + " VARIANT\t" + count_variant[i] + "\n";
}
if (count_super[i] > 0) {
output_text += " " + ((Overload.EnemyType)i).ToString() + " SUPER\t" + count_super[i] + "\n";
}
}
output_text += " DROPPED LOG ENTRY\t" + count_dropped + "\n";
output_text += " STATION BOTS\t" + count_station + "\n";
output_text += " NG+ BOTS\t" + count_ngp + "\n";
output_text += "\n";
output_text += "--Items--\n";
int[] count_items = new int[(int)ItemSubType.NUM];
int[] count_super_items = new int[(int)ItemSubType.NUM];
int count_secrets = 0;
foreach (Entity entity in m_level.EnumerateAliveEntities()) {
if (entity.Type == EntityType.ITEM) {
if (((Overload.EntityPropsItem)entity.entity_props).secret) {
count_secrets += 1;
}
if (((Overload.EntityPropsItem)entity.entity_props).super) {
count_super_items[entity.SubType] += 1;
} else {
count_items[entity.SubType] += 1;
}
}
}
for (int i = 0; i < count_items.Length; i++) {
if (count_items[i] > 0) {
output_text += " " + ((ItemSubType)i).ToString() + "\t" + count_items[i] + "\n";
}
}
for (int i = 0; i < count_items.Length; i++) {
if (count_super_items[i] > 0) {
output_text += " " + ((ItemSubType)i).ToString() + " SUPER\t" + count_super_items[i] + "\n";
}
}
output_text += " SECRET ITEMS\t" + count_secrets + "\n";
output_text += "\n";
output_text += "--Props--\n";
int[] count_props = new int[(int)PropSubType.NUM];
foreach (Entity entity in m_level.EnumerateAliveEntities()) {
if (entity.Type == EntityType.PROP) {
count_props[entity.SubType] += 1;
}
}
for (int i = 0; i < count_props.Length; i++) {
if (count_props[i] > 0) {
output_text += " " + ((PropSubType)i).ToString() + "\t" + count_props[i] + "\n";
}
}
output_text += "\n";
output_text += "--Scripts--\n";
int[] count_scripts = new int[(int)ScriptSubType.NUM];
foreach (Entity entity in m_level.EnumerateAliveEntities()) {
if (entity.Type == EntityType.SCRIPT) {
count_scripts[entity.SubType] += 1;
}
}
for (int i = 0; i < count_scripts.Length; i++) {
if (count_scripts[i] > 0) {
output_text += " " + ((ScriptSubType)i).ToString() + "\t" + count_scripts[i] + "\n";
}
}
output_text += "\n";
output_text += "--Matcens--\n";
int count_matcens = 0;
int count_shielded = 0;
foreach (Entity entity in m_level.EnumerateAliveEntities()) {
if (entity.Type == EntityType.SPECIAL) {
Overload.EntityPropsSpecial eps = (Overload.EntityPropsSpecial)entity.entity_props;
if (entity.SubType == (int)SpecialSubType.MATCEN) {
count_matcens += 1;
if (eps.Invulnerable) {
count_shielded += 1;
}
}
}
}
output_text += " TOTAL MATCENS\t" + count_matcens + "\n";
output_text += " TOTAL SHIELDED\t" + count_shielded + "\n";
Clipboard.SetText(output_text);
}
public void CopyTextureStatsToClipboard()
{
string output_text = "";
// Keep a list and count of all textures in the level
List<string> tex_names = new List<string>();
List<int> tex_count = new List<int>();
// sides first
foreach (Segment seg in m_level.EnumerateAliveSegments()) {
for (int i = 0; i < 6; i++) {
if (!seg.side[i].HasNeighbor) {
AddToListPair(tex_names, tex_count, seg.side[i].tex_name);
}
}
}
int decal_start = tex_names.Count;
// decals second
foreach (Segment seg in m_level.EnumerateAliveSegments()) {
for (int i = 0; i < 6; i++) {
if (!seg.side[i].decal[0].hidden && seg.side[i].decal[0].dmesh != null) {
for (int j = 0; j < seg.side[i].decal[0].dmesh.tex_name.Count; j++) {
bool used = false;
for (int k = 0; k < seg.side[i].decal[0].dmesh.triangle.Count; k++) {
if (seg.side[i].decal[0].dmesh.triangle[k].tex_index == j) {
used = true;
break;
}
}
if (used) {
AddToListPair(tex_names, tex_count, Utility.GetPathlessFilename(seg.side[i].decal[0].dmesh.tex_name[j]));
}
}
}
if (!seg.side[i].decal[1].hidden && seg.side[i].decal[1].dmesh != null) {
for (int j = 0; j < seg.side[i].decal[1].dmesh.tex_name.Count; j++) {
bool used = false;
for (int k = 0; k < seg.side[i].decal[1].dmesh.triangle.Count; k++) {
if (seg.side[i].decal[1].dmesh.triangle[k].tex_index == j) {
used = true;
break;
}
}
if (used) {
AddToListPair(tex_names, tex_count, Utility.GetPathlessFilename(seg.side[i].decal[1].dmesh.tex_name[j]));
}
}
}
}
}
for (int i = 0; i < tex_names.Count; i++) {
if (i == 0) {
output_text += "--LEVEL TEXTURES--\n";
} else if (i == decal_start) {
output_text += "\n";
output_text += "--DECAL-SPECIFIC TEXTURES--\n";
}
output_text += tex_names[i] + "\t" + tex_count[i].ToString() + "\n";
}
output_text += "\n";
output_text += "--DECALS--\n";
List<string> decal_names = new List<string>();
List<int> decal_count = new List<int>();
foreach (Segment seg in m_level.EnumerateAliveSegments()) {
for (int i = 0; i < 6; i++) {
if (!seg.side[i].decal[0].hidden && seg.side[i].decal[0].dmesh != null) {
AddToListPair(decal_names, decal_count, (seg.side[i].decal[0].dmesh.name));
}
if (!seg.side[i].decal[1].hidden && seg.side[i].decal[1].dmesh != null) {
AddToListPair(decal_names, decal_count, (seg.side[i].decal[1].dmesh.name));
}
}
}
for (int i = 0; i < decal_names.Count; i++) {
output_text += decal_names[i] + "\t" + decal_count[i].ToString() + "\n";
}
Clipboard.SetText(output_text);
}
public void AddToListPair(List<string> name_list, List<int> count_list, string name)
{
if (name_list.Contains(name)) {
int idx = name_list.IndexOf(name);
count_list[idx] += 1;
} else {
name_list.Add(name);
count_list.Add(1);
}
}
//void DegenTest(Vector3 norm1,Vector3 norm2, float threshold, int segnum, ref bool degenerate)
//{
// if (Math.Abs(Vector3.Dot(norm1, norm2)) > threshold) {
// degenerate = true;
// AddOutputText("Segment " + segnum + " is degenerate, threshold = " + Vector3.Dot(norm1, norm2));
// }
//}
// Check for degenerate segment due to:
// - Given a triangle and the four vertices on the opposite side, two verticies lie on opposite sides of the triangle's plane
// - Two sides are very close together.
// - Adjacent sides have nearly identical normals. Specifically: If sides A and B are adjacent and either triangle in A has a nearly identical normal to either triangle in B.
// Print errors and return true if any of the above occur.
public bool SegmentDegenerateFacesNear(Segment segdata)
{
Vector3 a, b, c;
float[] distances = new float[4];
float distance_sum = 0.0f;
int other_side_index;
//// First, check for nearly identical normals on adjacent sides.
//bool degenerate = false;
//for (int sidenum = 0; sidenum < 6; sidenum++) {
// for (int side2 = 0; side2 < 6; side2++) {
// if (sidenum == side2)
// continue;
// if (sidenum == Utility.OppositeSide(side2))
// continue;
// Vector3 norm1, norm2, norm3, norm4;
// Vector3 edge1, edge2, edge3;
// edge1 = (m_level.vertex[segdata.vert[Segment.SegmentSideVerts[sidenum, 1]]].position - m_level.vertex[segdata.vert[Segment.SegmentSideVerts[sidenum, 0]]].position).Normalized();
// edge2 = (m_level.vertex[segdata.vert[Segment.SegmentSideVerts[sidenum, 2]]].position - m_level.vertex[segdata.vert[Segment.SegmentSideVerts[sidenum, 0]]].position).Normalized();
// edge3 = (m_level.vertex[segdata.vert[Segment.SegmentSideVerts[sidenum, 3]]].position - m_level.vertex[segdata.vert[Segment.SegmentSideVerts[sidenum, 0]]].position).Normalized();
// norm1 = Vector3.Cross(edge1, edge2).Normalized();
// norm2 = Vector3.Cross(edge2, edge3).Normalized();
// edge1 = (m_level.vertex[segdata.vert[Segment.SegmentSideVerts[side2, 1]]].position - m_level.vertex[segdata.vert[Segment.SegmentSideVerts[side2, 0]]].position).Normalized();
// edge2 = (m_level.vertex[segdata.vert[Segment.SegmentSideVerts[side2, 2]]].position - m_level.vertex[segdata.vert[Segment.SegmentSideVerts[side2, 0]]].position).Normalized();
// edge3 = (m_level.vertex[segdata.vert[Segment.SegmentSideVerts[side2, 3]]].position - m_level.vertex[segdata.vert[Segment.SegmentSideVerts[side2, 0]]].position).Normalized();
// norm3 = Vector3.Cross(edge1, edge2).Normalized();
// norm4 = Vector3.Cross(edge2, edge3).Normalized();
// float threshold = 0.995f;
// //DegenTest(norm1, norm3, threshold, segdata.num, ref degenerate);
// //DegenTest(norm1, norm4, threshold, segdata.num, ref degenerate);
// //DegenTest(norm2, norm3, threshold, segdata.num, ref degenerate);
// //DegenTest(norm2, norm4, threshold, segdata.num, ref degenerate);
// if (Math.Abs(Vector3.Dot(norm1, norm3)) > threshold) degenerate = true;
// if (Math.Abs(Vector3.Dot(norm1, norm4)) > threshold) degenerate = true;
// if (Math.Abs(Vector3.Dot(norm2, norm3)) > threshold) degenerate = true;
// if (Math.Abs(Vector3.Dot(norm2, norm4)) > threshold) degenerate = true;
// if (degenerate) {
// AddOutputText("Segment " + segdata.num + " is degenerate because adjacent sides " + sidenum + " & " + side2 +" are nearly coplanar.");
// return true;
// }
// }
//}
for (int sidenum = 0; sidenum < 6; sidenum++) {
int degen_count = 0;
for (int trinum = 0; trinum < 2; trinum++) {
a = m_level.vertex[segdata.vert[Segment.SegmentSideVerts[sidenum, 0]]].position;
if (trinum == 0) {
b = m_level.vertex[segdata.vert[Segment.SegmentSideVerts[sidenum, 1]]].position;
c = m_level.vertex[segdata.vert[Segment.SegmentSideVerts[sidenum, 2]]].position;
} else {
b = m_level.vertex[segdata.vert[Segment.SegmentSideVerts[sidenum, 2]]].position;
c = m_level.vertex[segdata.vert[Segment.SegmentSideVerts[sidenum, 3]]].position;
}
Vector3 ab = b - a;
Vector3 ac = c - a;
Vector3 normal = Vector3.Cross(ab, ac).Normalized();
other_side_index = Utility.OppositeSide(sidenum);
for (int j = 0; j < 4; j++) { // Check all vertices on opposite side
distances[j] = Vector3.Dot(m_level.vertex[segdata.vert[Segment.SegmentSideVerts[other_side_index, j]]].position - a, normal);
}
distance_sum = Math.Abs(distances[0]);
// Have all distances. If one is negative and any are positive, or vice versa, we have a degneracy.
if (distances[0] < 0.0f) {
for (int k = 1; k < 4; k++) {
distance_sum += Math.Abs(distances[k]);
if (distances[k] > 0.0f) {
degen_count++;
}
}
} else {
for (int k = 1; k < 4; k++) {
distance_sum += Math.Abs(distances[k]);
if (distances[k] < 0.0f) {
degen_count++;
}
}
}
}
if (degen_count == 2) { // Requiring both triangles to partition vertices on opposite side. Requiring only one flagged too many not so bad segments.
AddOutputText("Segment " + segdata.num + " is degenerate. Side #" + Utility.OppositeSide(sidenum) + " has vertices on both sides of side #" + sidenum + ". Distances = " + distances[0] + " " + distances[1] + " " + distances[2] + " " + distances[3]);
return true;
}
if (distance_sum < 0.2f) {
AddOutputText("Segment " + segdata.num + " is degenerate. Sides " + Utility.OppositeSide(sidenum) + " and " + sidenum + " are very, very close together");
return true;
}
}
return false;
}
public static string CleanupName(string s)
{
//Must convert to lower case before converting to title case, because ToTitleCase() won't change all-caps words on the assumption they're acronyms
var text_info = System.Threading.Thread.CurrentThread.CurrentCulture.TextInfo;
return (s == null) ? "" : text_info.ToTitleCase(text_info.ToLower(s.Replace('_', ' ')));
}
public void Split2Way()
{
m_level.SplitSegment2Way(m_level.selected_segment, m_level.selected_side);
RefreshGeometry(true);
}
public void Split5Way()
{
m_level.SplitSegment5Way(m_level.selected_segment, m_level.selected_side);
RefreshGeometry(true);
}
public void Split7Way()
{
m_level.SplitSegment7Way(m_level.selected_segment);
RefreshGeometry(true);
}
public void AverageMarkedSideVertsY()
{
m_level.AverageMarkedSideVertsY();
RefreshGeometry(true);
}
public void HideMarkedSegments()
{
m_level.HideMarkedSegments();
if (m_level.selected_segment > -1) {
if (m_level.segment[m_level.selected_segment].m_hidden) {
m_level.selected_segment = -1;
}
}
RefreshAllGMeshes();
RefreshGeometry(true);
}
public void HideUnmarkedSegments()
{
m_level.HideUnmarkedSegments();
if (m_level.selected_segment > -1) {
if (m_level.segment[m_level.selected_segment].m_hidden) {
m_level.selected_segment = -1;
}
}
RefreshAllGMeshes();
RefreshGeometry(true);
}
public void UnhideHiddenSegments()
{
m_level.UnhideHiddenSegments();
RefreshAllGMeshes();
RefreshGeometry(true);
}
}
}
| 30.997195
| 255
| 0.659367
|
[
"MIT"
] |
SiriusTR/OverloadLevelEditor
|
OverloadLevelEditor/Main/EditorUtility.cs
| 66,305
|
C#
|
//namespace CSharpGL
//{
// /// <summary>
// ///
// /// </summary>
// public enum TransformFeedbackTarget : uint
// {
// /// <summary>
// ///
// /// </summary>
// TransformFeedback = GL.GL_TRANSFORM_FEEDBACK,
// }
//}
| 20.307692
| 55
| 0.462121
|
[
"MIT"
] |
AugusZhan/CSharpGL
|
CSharpGL/GLAPI/GL.Enumerations/NotUsedYet/TransformFeedbackTarget.cs
| 266
|
C#
|
/*
Copyright (c) 2019-2021 Integrative Software LLC
Created: 12/2019
Author: Pablo Carbonell
*/
using Microsoft.AspNetCore.Http;
using System;
using System.Collections.Generic;
using Xunit;
namespace Integrative.Lara.Tests.Middleware
{
public class EventParametersTesting
{
private readonly Guid _id = Guid.Parse("{2F97BE9D-1CC3-4EBD-BC93-EF748B774F1D}");
[Fact]
public void RoundTripMinimum()
{
var x = new EventParameters
{
DocumentId = _id,
ElementId = "abc",
EventName = "click",
EventNumber = 1,
};
var json = LaraUI.JSON.Stringify(x);
var result = LaraUI.JSON.Parse<EventParameters>(json);
Assert.Equal(x.DocumentId, result.DocumentId);
Assert.Equal(x.ElementId, result.ElementId);
Assert.Equal(x.EventName, result.EventName);
Assert.Equal(x.EventNumber, result.EventNumber);
}
[Fact]
public void RoundTripEmptyFiles()
{
var x = new SocketEventParameters
{
DocumentId = _id,
SocketFiles = new FormFileCollection()
};
var json = LaraUI.JSON.Stringify(x);
var result = LaraUI.JSON.Parse<SocketEventParameters>(json);
Assert.NotNull(result.SocketFiles);
Assert.Empty(result.SocketFiles);
}
[Fact]
public void RoundTripFile()
{
var x = new FormFile
{
Content = "hello",
ContentDisposition = "a",
ContentType = "b",
FileName = "c",
Name = "d"
};
var json = LaraUI.JSON.Stringify(x);
var result = LaraUI.JSON.Parse<FormFile>(json);
Assert.Equal(x.Content, result.Content);
Assert.Equal(x.ContentDisposition, result.ContentDisposition);
Assert.Equal(x.ContentType, result.ContentType);
Assert.Equal(x.FileName, result.FileName);
Assert.Equal(x.Length, result.Length);
Assert.Equal(x.Name, result.Name);
}
[Fact]
public void SerializeBytes()
{
var bytes = BuildBytes();
var x = new FormFile
{
Content = Convert.ToBase64String(bytes)
};
var json = LaraUI.JSON.Stringify(x);
var result = LaraUI.JSON.Parse<FormFile>(json);
var output = Convert.FromBase64String(result.Content);
Assert.Equal(256, bytes.Length);
for (var index = 0; index < 256; index++)
{
Assert.Equal(index, output[index]);
}
}
private static byte[] BuildBytes()
{
var bytes = new byte[256];
for (var index = 0; index <= 255; index++)
{
bytes[index] = (byte)index;
}
return bytes;
}
[Fact]
public void FileCollectionIterates()
{
var f1 = new FormFile();
var f2 = new FormFile();
var list = new FormFileCollection
{
InnerList = new List<FormFile>()
};
list.InnerList.Add(f1);
list.InnerList.Add(f2);
var other = new List<FormFile>();
foreach (FormFile? f in list)
{
Assert.NotNull(f);
other.Add(f!);
}
Assert.Equal(2, other.Count);
Assert.Same(f1, other[0]);
Assert.Same(f2, other[1]);
}
[Fact]
public void NullCollectionEmpty()
{
var x = new FormFileCollection();
var size = x.Count;
Assert.Equal(0, size);
x.InnerList = new List<FormFile>();
size = x.Count;
Assert.Equal(0, size);
}
[Fact]
public void FindFileByName()
{
var f1 = new FormFile();
var f2 = new FormFile
{
Name = "lala"
};
var x = new FormFileCollection
{
InnerList = new List<FormFile>
{
f1,
f2
}
};
var found = x.GetFile("lala");
Assert.Same(f2, found);
}
[Fact]
public void GetFileReadonlyList()
{
var f1 = new FormFile();
var x = new FormFileCollection
{
InnerList = new List<FormFile>
{
f1
}
};
var list = x as IReadOnlyList<IFormFile>;
var found = list[0];
Assert.Same(f1, found);
}
[Fact]
public void GetFilesByName()
{
var f1 = new FormFile
{
Name = "a"
};
var f2 = new FormFile
{
Name = "b"
};
var f3 = new FormFile
{
Name = "a"
};
var x = new FormFileCollection
{
InnerList = new List<FormFile>
{
f1, f2, f3
}
};
var found = x.GetFiles("a");
Assert.Equal(2, found.Count);
Assert.Same(f1, found[0]);
Assert.Same(f3, found[1]);
}
[Fact]
public void EnumrableInterface()
{
var x = new FormFileCollection();
var y = (IEnumerable<IFormFile>) x;
using var enumerator = y.GetEnumerator();
Assert.False(enumerator.MoveNext());
}
}
}
| 28.587379
| 89
| 0.46035
|
[
"Apache-2.0"
] |
integrativesoft/lara
|
src/Tests/Middleware/EventParametersTesting.cs
| 5,891
|
C#
|
namespace Imager.Interface {
public class ScalerInformation {
private readonly string _displayName;
private readonly string _description;
private readonly byte _scaleFactorX;
private readonly byte _scaleFactorY;
public ScalerInformation(string displayName, string description, byte scaleFactorX, byte scaleFactorY) {
this._description = description;
this._scaleFactorX = scaleFactorX;
this._scaleFactorY = scaleFactorY;
this._displayName = displayName;
}
public string Description {
get { return this._description; }
}
public byte ScaleFactorX {
get { return this._scaleFactorX; }
}
public byte ScaleFactorY {
get { return this._scaleFactorY; }
}
public string DisplayName {
get { return this._displayName; }
}
}
}
| 25.90625
| 108
| 0.693607
|
[
"MIT"
] |
SkyImmerse/TFCTools
|
TibiaUCStudio/Imager/Interface/ScalerInformation.cs
| 831
|
C#
|
#region WatiN Copyright (C) 2006-2011 Jeroen van Menen
//Copyright 2006-2011 Jeroen van Menen
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#endregion Copyright
namespace WatiN.Core.Interfaces
{
/// <summary>
/// Implement this interface if you create your own Logger class.
/// For example <c>Logger.LogWriter = new MyLogWriter</c>.
/// </summary>
public interface ILogWriter
{
bool HandlesLogAction { get; }
bool HandlesLogDebug { get; }
void LogAction(string message);
void LogDebug(string message);
}
}
| 33
| 78
| 0.700643
|
[
"Apache-2.0"
] |
Bruno-N-Fernandes/WatiN
|
src/Core/Interfaces/ILogWriter.cs
| 1,089
|
C#
|
namespace Conflux.Graphql.Wrappers
{
public interface IIgnore
{
}
}
| 10.25
| 35
| 0.646341
|
[
"Apache-2.0"
] |
Panther59/Conflux
|
Conflux/Graphql/Wrappers/IIGnore.cs
| 84
|
C#
|
using System;
using System.Collections.Generic;
/// <summary>
/// Summary description for Class1
/// </summary>
///
[Serializable()]
public class Gene
{
private List<double> data;
private double fitness = 0.0;
private const double mutateChance = 0.05;
private const double mutationRate = 0.5;
private const double upperBound = 1.0;
private const double lowerBound = 0.0;
public void outputData()
{
int i = 1;
foreach (double value in data) {
LogWriter.writeData("\t" + i.ToString() + ": " + value + Environment.NewLine);
i++;
}
LogWriter.writeData("\tFitness: " + fitness + Environment.NewLine);
}
public Gene(int size, Random rand)
{
data = new List<double>(size);
for (int i = 0; i < size; i++) {
data.Add(rand.NextDouble() * upperBound);
}
}
public Gene(List<double> data)
{
this.data = data;
}
public int getLength()
{
return data.Capacity;
}
public double get(int index)
{
return data[index];
}
public void set(int index, double value)
{
data[index] = value;
}
/// THIS SHIT BELOW MIGHT BREAK BY WRITING OVER ARRAY BOUNDS
public List<double> getLeft(double percent)
{
if (percent > 1.0 || percent < 0.0)
throw new System.Exception();
int index = (int)(data.Capacity * percent);
if (index == 0)
throw new SystemException();
return data.GetRange(0, index);
}
public List<double> getRight(double percent)
{
if (percent > 1.0 || percent < 0.0)
throw new System.Exception();
int index = (int)(data.Capacity * (1.0 - percent));
if (index == 0)
throw new SystemException();
return data.GetRange(index, data.Capacity - index);
}
public double getFitness()
{
return fitness;
}
public void setFitness(double value) {
fitness = value;
}
public void adjustFitness(int winnings)
{
if (winnings > 0)
fitness += winFunction(winnings);
else
fitness -= lossFunction(winnings);
}
private double winFunction(int winnings)
{
return winnings ^ 2;
}
private double lossFunction(int winnings)
{
return winnings^2;
}
public void mutate(Random rand)
{
for (int i = 0; i < data.Capacity; i++)
{
if (rand.NextDouble() < mutateChance)
{
data[i] *= (rand.Next(0, 2) == 0 ? mutationRate : -mutationRate);
if (data[i] > upperBound)
data[i] = upperBound;
else if(data[i] < lowerBound)
data[i] = lowerBound;
}
}
}
}
| 19.811475
| 90
| 0.635499
|
[
"MIT"
] |
FireCube-/HarvesterBot
|
TexasHoldEm/Gene.cs
| 2,419
|
C#
|
// Copyright 2004-2009 Castle Project - http://www.castleproject.org/
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
namespace Telerik.JustMock.Core.Castle.Core.Internal
{
internal class NoOpUpgradeableLock : IUpgradeableLockHolder
{
public static readonly IUpgradeableLockHolder Lock = new NoOpUpgradeableLock();
public void Dispose()
{
}
public bool LockAcquired
{
get { return true; }
}
public ILockHolder Upgrade()
{
return NoOpLock.Lock;
}
public ILockHolder Upgrade(bool waitForLock)
{
return NoOpLock.Lock;
}
}
}
| 26.243902
| 81
| 0.732342
|
[
"Apache-2.0"
] |
tailsu/JustMockLite
|
Telerik.JustMock/Core/DynamicProxy/Castle.Core/Internal/NoOpUpgradeableLock.cs
| 1,078
|
C#
|
using System.Collections.Generic;
using System.Linq;
using SqlParser.Ast;
namespace SqlParser.Symbols
{
public class SymbolTable
{
private readonly SymbolTable _parent;
private readonly Dictionary<string, SymbolInfo> _symbols;
public SymbolTable(IEnumerable<SymbolInfo> environmentalSymbols)
{
_symbols = new Dictionary<string, SymbolInfo>();
foreach (var sym in (environmentalSymbols ?? Enumerable.Empty<SymbolInfo>()))
{
if (string.IsNullOrEmpty(sym.OriginalName))
continue;
if (sym.OriginKind == SymbolOriginKind.Unknown)
sym.OriginKind = SymbolOriginKind.Environmental;
_symbols.Add(sym.OriginalName, sym);
}
}
public SymbolTable(SymbolTable parent)
{
_parent = parent;
_symbols = new Dictionary<string, SymbolInfo>();
}
public SymbolInfo GetInfo(string symbol)
{
if (_symbols.ContainsKey(symbol))
return _symbols[symbol];
return _parent?.GetInfo(symbol);
}
public SymbolInfo GetInfoOrThrow(string symbol, Location l)
{
var info = GetInfo(symbol);
if (info == null)
throw SymbolNotDefinedException.Create(symbol, l);
return info;
}
public bool ContainsSymbol(string symbol)
{
if (_symbols.ContainsKey(symbol))
return true;
return _parent?.ContainsSymbol(symbol) ?? false;
}
public void AddSymbol(string symbol, SymbolInfo info)
{
if (ContainsSymbol(symbol))
throw SymbolAlreadyDefinedException.Create(symbol, info.DefinedAt);
_symbols.Add(symbol, info);
}
public ISqlNode ResolveIdentifier(ISqlNode n)
{
if (n is SqlIdentifierNode id)
return GetInfo(id.Name)?.Translate(n) ?? n;
if (n is SqlObjectIdentifierNode oid)
return GetInfo(oid.ToString())?.Translate(n) ?? n;
if (n is SqlQualifiedIdentifierNode qid)
return GetInfo(qid.ToString())?.Translate(n) ?? n;
if (n is SqlVariableNode v)
return GetInfo(v.Name)?.Translate(n) ?? GetInfo(v.GetBareName())?.Translate(n) ?? n;
return n;
}
}
}
| 32.733333
| 100
| 0.569043
|
[
"Apache-2.0"
] |
Whiteknight/SqlParser
|
Src/SqlParser/Symbols/SymbolTable.cs
| 2,457
|
C#
|
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Moq;
using TOTD.Mvc;
using TOTD.Utility.StringHelpers;
namespace TOTD.Test
{
public class BaseHtmlTest
{
public ViewContext GetViewContext()
{
ViewContext result = new ViewContext();
result.RouteData.Values[RouteValueKeys.Controller] = "test";
result.RouteData.Values[RouteValueKeys.Action] = "action";
result.Writer = new StringWriter();
result.HttpContext = GetHttpContext();
result.RequestContext = new RequestContext(GetHttpContext(), result.RouteData);
return result;
}
public RouteCollection GetRouteCollection()
{
RouteCollection result = new RouteCollection();
result.Add(new Route("{controller}/{action}/{id}", null)
{
Defaults = new RouteValueDictionary(new
{
id = "defaultid"
})
});
return result;
}
public HtmlHelper GetHtmlHelper()
{
return new HtmlHelper(GetViewContext(), GetViewDataContainer(new ViewDataDictionary()), GetRouteCollection());
}
public HtmlHelper<TModel> GetHtmlHelper<TModel>(ViewDataDictionary<TModel> viewData)
{
ViewContext viewContext = GetViewContext();
viewContext.ViewData = viewData;
IViewDataContainer container = GetViewDataContainer(viewData);
return new HtmlHelper<TModel>(viewContext, container, GetRouteCollection());
}
public static IViewDataContainer GetViewDataContainer(ViewDataDictionary viewData)
{
Mock<IViewDataContainer> mockContainer = new Mock<IViewDataContainer>();
mockContainer.Setup(c => c.ViewData).Returns(viewData);
return mockContainer.Object;
}
public HttpContextBase GetHttpContext()
{
Mock<HttpContextBase> mockHttpContext = new Mock<HttpContextBase>();
Uri uri = new Uri("http://localhost");
mockHttpContext.Setup(o => o.Request.Url).Returns(uri);
mockHttpContext.Setup(o => o.Request.PathInfo).Returns(String.Empty);
mockHttpContext.Setup(o => o.Session).Returns((HttpSessionStateBase)null);
mockHttpContext.Setup(o => o.Response.ApplyAppPathModifier(It.IsAny<string>())).Returns<string>(r => r);
mockHttpContext.Setup(o => o.Items).Returns(new Hashtable());
return mockHttpContext.Object;
}
}
}
| 33.783133
| 122
| 0.632311
|
[
"MIT"
] |
TheOtherTimDuncan/TOTD
|
TODT.Test/BaseHtmlTest.cs
| 2,806
|
C#
|
using RESTworld.Business.Models.Abstractions;
using System.Collections.Generic;
namespace RESTworld.Business.Models
{
/// <inheritdoc/>
public record ReadOnlyPagedCollection<T>(IReadOnlyCollection<T> Items, long? TotalCount)
: IReadOnlyPagedCollection<T>
{
}
}
| 26.909091
| 93
| 0.712838
|
[
"Unlicense"
] |
wertzui/RESTworld
|
src/RESTworld/RESTworld.Business/Models/ReadOnlyPagedCollection.cs
| 298
|
C#
|
// 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
// ReSharper disable once CheckNamespace
namespace DotNetNuke.Services.Tokens
{
using System;
using System.Web.UI;
using DotNetNuke.Entities.Users;
using DotNetNuke.Framework.JavaScriptLibraries;
using DotNetNuke.Web.Client;
using DotNetNuke.Web.Client.ClientResourceManagement;
using Newtonsoft.Json;
public class JavaScriptDto
{
[JsonProperty("jsname")]
public string JsName { get; set; }
[JsonProperty("path")]
public string Path { get; set; }
[JsonProperty("priority")]
public int Priority { get; set; }
[JsonProperty("provider")]
public string Provider { get; set; }
[JsonProperty("specific")]
public string Specific { get; set; }
[JsonProperty("version")]
public string Version { get; set; }
}
public class JavaScriptPropertyAccess : JsonPropertyAccess<JavaScriptDto>
{
private readonly Page _page;
/// <summary>
/// Initializes a new instance of the <see cref="JavaScriptPropertyAccess"/> class.
/// </summary>
/// <param name="page"></param>
public JavaScriptPropertyAccess(Page page)
{
this._page = page;
}
/// <inheritdoc/>
protected override string ProcessToken(JavaScriptDto model, UserInfo accessingUser, Scope accessLevel)
{
if (string.IsNullOrEmpty(model.JsName))
{
if (string.IsNullOrEmpty(model.Path))
{
throw new ArgumentException("If the jsname property is not specified then the JavaScript token must specify a path or property.");
}
if (model.Priority == 0)
{
model.Priority = (int)FileOrder.Js.DefaultPriority;
}
if (string.IsNullOrEmpty(model.Provider))
{
ClientResourceManager.RegisterScript(this._page, model.Path, model.Priority);
}
else
{
ClientResourceManager.RegisterScript(this._page, model.Path, model.Priority, model.Provider);
}
}
else if (!string.IsNullOrEmpty(model.Path))
{
if (model.Priority == 0)
{
model.Priority = (int)FileOrder.Js.DefaultPriority;
}
if (string.IsNullOrEmpty(model.Provider))
{
ClientResourceManager.RegisterScript(this._page, model.Path, model.Priority, string.Empty, model.JsName, model.Version);
}
else
{
ClientResourceManager.RegisterScript(this._page, model.Path, model.Priority, model.Provider, model.JsName, model.Version);
}
}
else
{
Version version = null;
SpecificVersion specific = SpecificVersion.Latest;
if (!string.IsNullOrEmpty(model.Version))
{
version = new Version(model.Version);
if (!string.IsNullOrEmpty(model.Specific))
{
switch (model.Specific)
{
case "Exact":
specific = SpecificVersion.Exact;
break;
case "LatestMajor":
specific = SpecificVersion.LatestMajor;
break;
case "LatestMinor":
specific = SpecificVersion.LatestMinor;
break;
default:
specific = SpecificVersion.Latest;
break;
}
}
}
JavaScript.RequestRegistration(model.JsName, version, specific);
}
return string.Empty;
}
}
}
| 34.563492
| 150
| 0.50907
|
[
"MIT"
] |
Mariusz11711/DNN
|
DNN Platform/Library/Services/Tokens/PropertyAccess/JavaScriptPropertyAccess.cs
| 4,357
|
C#
|
using System;
using System.Diagnostics.CodeAnalysis;
using System.Traits;
using System.Traits.Concepts;
namespace Numbersome {
public static partial class ArithmeticExtensions {
/// <summary>
/// Multiplies the <paramref name="values"/>.
/// </summary>
/// <typeparam name="TEnumerator">The type of the enumerator of the <paramref name="values"/>.</typeparam>
/// <param name="values">The values to sum.</param>
/// <returns>The sum of the <paramref name="values"/>.</returns>
public static Double Product<TEnumerator>([AllowNull] this ISequence<nint, TEnumerator> values) where TEnumerator : notnull, ICount, ICurrent<nint>, IMoveNext, IReset {
if (values is null || values.Count == 0) {
return Double.NaN;
}
Double i = 1;
if (values is not null) {
foreach (nint value in values) {
i *= value;
}
}
return i;
}
/// <summary>
/// Multiplies the <paramref name="values"/>.
/// </summary>
/// <typeparam name="TEnumerator">The type of the enumerator of the <paramref name="values"/>.</typeparam>
/// <param name="values">The values to sum.</param>
/// <returns>The sum of the <paramref name="values"/>.</returns>
[CLSCompliant(false)]
public static Double Product<TEnumerator>([AllowNull] this ISequence<nuint, TEnumerator> values) where TEnumerator : notnull, ICount, ICurrent<nuint>, IMoveNext, IReset {
if (values is null || values.Count == 0) {
return Double.NaN;
}
Double i = 1;
if (values is not null) {
foreach (nuint value in values) {
i *= value;
}
}
return i;
}
/// <summary>
/// Multiplies the <paramref name="values"/>.
/// </summary>
/// <typeparam name="TEnumerator">The type of the enumerator of the <paramref name="values"/>.</typeparam>
/// <param name="values">The values to sum.</param>
/// <returns>The sum of the <paramref name="values"/>.</returns>
[CLSCompliant(false)]
public static Single Product<TEnumerator>([AllowNull] this ISequence<SByte, TEnumerator> values) where TEnumerator : notnull, ICount, ICurrent<SByte>, IMoveNext, IReset {
if (values is null || values.Count == 0) {
return Single.NaN;
}
Single i = 1;
if (values is not null) {
foreach (SByte value in values) {
i *= value;
}
}
return i;
}
/// <summary>
/// Multiplies the <paramref name="values"/>.
/// </summary>
/// <typeparam name="TEnumerator">The type of the enumerator of the <paramref name="values"/>.</typeparam>
/// <param name="values">The values to sum.</param>
/// <returns>The sum of the <paramref name="values"/>.</returns>
public static Single Product<TEnumerator>([AllowNull] this ISequence<Byte, TEnumerator> values) where TEnumerator : notnull, ICount, ICurrent<Byte>, IMoveNext, IReset {
if (values is null || values.Count == 0) {
return Single.NaN;
}
Single i = 1;
if (values is not null) {
foreach (Byte value in values) {
i *= value;
}
}
return i;
}
/// <summary>
/// Multiplies the <paramref name="values"/>.
/// </summary>
/// <typeparam name="TEnumerator">The type of the enumerator of the <paramref name="values"/>.</typeparam>
/// <param name="values">The values to sum.</param>
/// <returns>The sum of the <paramref name="values"/>.</returns>
public static Single Product<TEnumerator>([AllowNull] this ISequence<Int16, TEnumerator> values) where TEnumerator : notnull, ICount, ICurrent<Int16>, IMoveNext, IReset {
if (values is null || values.Count == 0) {
return Single.NaN;
}
Single i = 1;
if (values is not null) {
foreach (Int16 value in values) {
i *= value;
}
}
return i;
}
/// <summary>
/// Multiplies the <paramref name="values"/>.
/// </summary>
/// <typeparam name="TEnumerator">The type of the enumerator of the <paramref name="values"/>.</typeparam>
/// <param name="values">The values to sum.</param>
/// <returns>The sum of the <paramref name="values"/>.</returns>
[CLSCompliant(false)]
public static Single Product<TEnumerator>([AllowNull] this ISequence<UInt16, TEnumerator> values) where TEnumerator : notnull, ICount, ICurrent<UInt16>, IMoveNext, IReset {
if (values is null || values.Count == 0) {
return Single.NaN;
}
Single i = 1;
if (values is not null) {
foreach (UInt16 value in values) {
i *= value;
}
}
return i;
}
/// <summary>
/// Multiplies the <paramref name="values"/>.
/// </summary>
/// <typeparam name="TEnumerator">The type of the enumerator of the <paramref name="values"/>.</typeparam>
/// <param name="values">The values to sum.</param>
/// <returns>The sum of the <paramref name="values"/>.</returns>
public static Double Product<TEnumerator>([AllowNull] this ISequence<Int32, TEnumerator> values) where TEnumerator : notnull, ICount, ICurrent<Int32>, IMoveNext, IReset {
if (values is null || values.Count == 0) {
return Double.NaN;
}
Double i = 1;
if (values is not null) {
foreach (Int32 value in values) {
i *= value;
}
}
return i;
}
/// <summary>
/// Multiplies the <paramref name="values"/>.
/// </summary>
/// <typeparam name="TEnumerator">The type of the enumerator of the <paramref name="values"/>.</typeparam>
/// <param name="values">The values to sum.</param>
/// <returns>The sum of the <paramref name="values"/>.</returns>
[CLSCompliant(false)]
public static Double Product<TEnumerator>([AllowNull] this ISequence<UInt32, TEnumerator> values) where TEnumerator : notnull, ICount, ICurrent<UInt32>, IMoveNext, IReset {
if (values is null || values.Count == 0) {
return Double.NaN;
}
Double i = 1;
if (values is not null) {
foreach (UInt32 value in values) {
i *= value;
}
}
return i;
}
/// <summary>
/// Multiplies the <paramref name="values"/>.
/// </summary>
/// <typeparam name="TEnumerator">The type of the enumerator of the <paramref name="values"/>.</typeparam>
/// <param name="values">The values to sum.</param>
/// <returns>The sum of the <paramref name="values"/>.</returns>
public static Double Product<TEnumerator>([AllowNull] this ISequence<Int64, TEnumerator> values) where TEnumerator : notnull, ICount, ICurrent<Int64>, IMoveNext, IReset {
if (values is null || values.Count == 0) {
return Double.NaN;
}
Double i = 1;
if (values is not null) {
foreach (Int64 value in values) {
i *= value;
}
}
return i;
}
/// <summary>
/// Multiplies the <paramref name="values"/>.
/// </summary>
/// <typeparam name="TEnumerator">The type of the enumerator of the <paramref name="values"/>.</typeparam>
/// <param name="values">The values to sum.</param>
/// <returns>The sum of the <paramref name="values"/>.</returns>
[CLSCompliant(false)]
public static Double Product<TEnumerator>([AllowNull] this ISequence<UInt64, TEnumerator> values) where TEnumerator : notnull, ICount, ICurrent<UInt64>, IMoveNext, IReset {
if (values is null || values.Count == 0) {
return Double.NaN;
}
Double i = 1;
if (values is not null) {
foreach (UInt64 value in values) {
i *= value;
}
}
return i;
}
/// <summary>
/// Multiplies the <paramref name="values"/>.
/// </summary>
/// <typeparam name="TEnumerator">The type of the enumerator of the <paramref name="values"/>.</typeparam>
/// <param name="values">The values to sum.</param>
/// <returns>The sum of the <paramref name="values"/>.</returns>
public static Single Product<TEnumerator>([AllowNull] this ISequence<Single, TEnumerator> values) where TEnumerator : notnull, ICount, ICurrent<Single>, IMoveNext, IReset {
if (values is null || values.Count == 0) {
return Single.NaN;
}
Single i = 1;
if (values is not null) {
foreach (Single value in values) {
i *= value;
}
}
return i;
}
/// <summary>
/// Multiplies the <paramref name="values"/>.
/// </summary>
/// <typeparam name="TEnumerator">The type of the enumerator of the <paramref name="values"/>.</typeparam>
/// <param name="values">The values to sum.</param>
/// <returns>The sum of the <paramref name="values"/>.</returns>
public static Double Product<TEnumerator>([AllowNull] this ISequence<Double, TEnumerator> values) where TEnumerator : notnull, ICount, ICurrent<Double>, IMoveNext, IReset {
if (values is null || values.Count == 0) {
return Double.NaN;
}
Double i = 1;
if (values is not null) {
foreach (Double value in values) {
i *= value;
}
}
return i;
}
}
}
| 35.413223
| 174
| 0.645974
|
[
"BSD-3-Clause"
] |
Entomy/LibLangly
|
Numbersome.Arithmetic/Product.cs
| 8,572
|
C#
|
using MsgPack.Serialization;
using System;
namespace ManahostManager.Utils.Formatters
{
public class MsgPackDatetimeSerializer : MessagePackSerializer<DateTime>
{
public MsgPackDatetimeSerializer(SerializationContext ctx) : base(ctx)
{
}
protected override void PackToCore(MsgPack.Packer packer, DateTime objectTree)
{
packer.Pack(objectTree.Ticks);
}
protected override DateTime UnpackFromCore(MsgPack.Unpacker unpacker)
{
return new DateTime((long)unpacker.LastReadData);
}
}
}
| 26.863636
| 86
| 0.671743
|
[
"MIT"
] |
charla-n/ManahostManager
|
ManahostManager/Utils/Formatters/MsgPackDatetimeSerializer.cs
| 593
|
C#
|
// *** WARNING: this file was generated by the Pulumi Terraform Bridge (tfgen) Tool. ***
// *** Do not edit by hand unless you're certain you know what you are doing! ***
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Threading.Tasks;
using Pulumi.Serialization;
namespace Pulumi.Gcp.Compute
{
/// <summary>
/// Manages a Target Pool within GCE. This is a collection of instances used as
/// target of a network load balancer (Forwarding Rule). For more information see
/// [the official
/// documentation](https://cloud.google.com/compute/docs/load-balancing/network/target-pools)
/// and [API](https://cloud.google.com/compute/docs/reference/latest/targetPools).
/// </summary>
public partial class TargetPool : Pulumi.CustomResource
{
/// <summary>
/// URL to the backup target pool. Must also set
/// failover\_ratio.
/// </summary>
[Output("backupPool")]
public Output<string?> BackupPool { get; private set; } = null!;
/// <summary>
/// Textual description field.
/// </summary>
[Output("description")]
public Output<string?> Description { get; private set; } = null!;
/// <summary>
/// Ratio (0 to 1) of failed nodes before using the
/// backup pool (which must also be set).
/// </summary>
[Output("failoverRatio")]
public Output<double?> FailoverRatio { get; private set; } = null!;
/// <summary>
/// List of zero or one health check name or self_link. Only
/// legacy `gcp.compute.HttpHealthCheck` is supported.
/// </summary>
[Output("healthChecks")]
public Output<string?> HealthChecks { get; private set; } = null!;
/// <summary>
/// List of instances in the pool. They can be given as
/// URLs, or in the form of "zone/name". Note that the instances need not exist
/// at the time of target pool creation, so there is no need to use the
/// interpolation to create a dependency on the instances from the
/// target pool.
/// </summary>
[Output("instances")]
public Output<ImmutableArray<string>> Instances { get; private set; } = null!;
/// <summary>
/// A unique name for the resource, required by GCE. Changing
/// this forces a new resource to be created.
/// </summary>
[Output("name")]
public Output<string> Name { get; private set; } = null!;
/// <summary>
/// The ID of the project in which the resource belongs. If it
/// is not provided, the provider project is used.
/// </summary>
[Output("project")]
public Output<string> Project { get; private set; } = null!;
/// <summary>
/// Where the target pool resides. Defaults to project
/// region.
/// </summary>
[Output("region")]
public Output<string> Region { get; private set; } = null!;
/// <summary>
/// The URI of the created resource.
/// </summary>
[Output("selfLink")]
public Output<string> SelfLink { get; private set; } = null!;
/// <summary>
/// How to distribute load. Options are "NONE" (no
/// affinity). "CLIENT\_IP" (hash of the source/dest addresses / ports), and
/// "CLIENT\_IP\_PROTO" also includes the protocol (default "NONE").
/// </summary>
[Output("sessionAffinity")]
public Output<string?> SessionAffinity { get; private set; } = null!;
/// <summary>
/// Create a TargetPool resource with the given unique name, arguments, and options.
/// </summary>
///
/// <param name="name">The unique name of the resource</param>
/// <param name="args">The arguments used to populate this resource's properties</param>
/// <param name="options">A bag of options that control this resource's behavior</param>
public TargetPool(string name, TargetPoolArgs? args = null, CustomResourceOptions? options = null)
: base("gcp:compute/targetPool:TargetPool", name, args ?? new TargetPoolArgs(), MakeResourceOptions(options, ""))
{
}
private TargetPool(string name, Input<string> id, TargetPoolState? state = null, CustomResourceOptions? options = null)
: base("gcp:compute/targetPool:TargetPool", name, state, MakeResourceOptions(options, id))
{
}
private static CustomResourceOptions MakeResourceOptions(CustomResourceOptions? options, Input<string>? id)
{
var defaultOptions = new CustomResourceOptions
{
Version = Utilities.Version,
};
var merged = CustomResourceOptions.Merge(defaultOptions, options);
// Override the ID if one was specified for consistency with other language SDKs.
merged.Id = id ?? merged.Id;
return merged;
}
/// <summary>
/// Get an existing TargetPool resource's state with the given name, ID, and optional extra
/// properties used to qualify the lookup.
/// </summary>
///
/// <param name="name">The unique name of the resulting resource.</param>
/// <param name="id">The unique provider ID of the resource to lookup.</param>
/// <param name="state">Any extra arguments used during the lookup.</param>
/// <param name="options">A bag of options that control this resource's behavior</param>
public static TargetPool Get(string name, Input<string> id, TargetPoolState? state = null, CustomResourceOptions? options = null)
{
return new TargetPool(name, id, state, options);
}
}
public sealed class TargetPoolArgs : Pulumi.ResourceArgs
{
/// <summary>
/// URL to the backup target pool. Must also set
/// failover\_ratio.
/// </summary>
[Input("backupPool")]
public Input<string>? BackupPool { get; set; }
/// <summary>
/// Textual description field.
/// </summary>
[Input("description")]
public Input<string>? Description { get; set; }
/// <summary>
/// Ratio (0 to 1) of failed nodes before using the
/// backup pool (which must also be set).
/// </summary>
[Input("failoverRatio")]
public Input<double>? FailoverRatio { get; set; }
/// <summary>
/// List of zero or one health check name or self_link. Only
/// legacy `gcp.compute.HttpHealthCheck` is supported.
/// </summary>
[Input("healthChecks")]
public Input<string>? HealthChecks { get; set; }
[Input("instances")]
private InputList<string>? _instances;
/// <summary>
/// List of instances in the pool. They can be given as
/// URLs, or in the form of "zone/name". Note that the instances need not exist
/// at the time of target pool creation, so there is no need to use the
/// interpolation to create a dependency on the instances from the
/// target pool.
/// </summary>
public InputList<string> Instances
{
get => _instances ?? (_instances = new InputList<string>());
set => _instances = value;
}
/// <summary>
/// A unique name for the resource, required by GCE. Changing
/// this forces a new resource to be created.
/// </summary>
[Input("name")]
public Input<string>? Name { get; set; }
/// <summary>
/// The ID of the project in which the resource belongs. If it
/// is not provided, the provider project is used.
/// </summary>
[Input("project")]
public Input<string>? Project { get; set; }
/// <summary>
/// Where the target pool resides. Defaults to project
/// region.
/// </summary>
[Input("region")]
public Input<string>? Region { get; set; }
/// <summary>
/// How to distribute load. Options are "NONE" (no
/// affinity). "CLIENT\_IP" (hash of the source/dest addresses / ports), and
/// "CLIENT\_IP\_PROTO" also includes the protocol (default "NONE").
/// </summary>
[Input("sessionAffinity")]
public Input<string>? SessionAffinity { get; set; }
public TargetPoolArgs()
{
}
}
public sealed class TargetPoolState : Pulumi.ResourceArgs
{
/// <summary>
/// URL to the backup target pool. Must also set
/// failover\_ratio.
/// </summary>
[Input("backupPool")]
public Input<string>? BackupPool { get; set; }
/// <summary>
/// Textual description field.
/// </summary>
[Input("description")]
public Input<string>? Description { get; set; }
/// <summary>
/// Ratio (0 to 1) of failed nodes before using the
/// backup pool (which must also be set).
/// </summary>
[Input("failoverRatio")]
public Input<double>? FailoverRatio { get; set; }
/// <summary>
/// List of zero or one health check name or self_link. Only
/// legacy `gcp.compute.HttpHealthCheck` is supported.
/// </summary>
[Input("healthChecks")]
public Input<string>? HealthChecks { get; set; }
[Input("instances")]
private InputList<string>? _instances;
/// <summary>
/// List of instances in the pool. They can be given as
/// URLs, or in the form of "zone/name". Note that the instances need not exist
/// at the time of target pool creation, so there is no need to use the
/// interpolation to create a dependency on the instances from the
/// target pool.
/// </summary>
public InputList<string> Instances
{
get => _instances ?? (_instances = new InputList<string>());
set => _instances = value;
}
/// <summary>
/// A unique name for the resource, required by GCE. Changing
/// this forces a new resource to be created.
/// </summary>
[Input("name")]
public Input<string>? Name { get; set; }
/// <summary>
/// The ID of the project in which the resource belongs. If it
/// is not provided, the provider project is used.
/// </summary>
[Input("project")]
public Input<string>? Project { get; set; }
/// <summary>
/// Where the target pool resides. Defaults to project
/// region.
/// </summary>
[Input("region")]
public Input<string>? Region { get; set; }
/// <summary>
/// The URI of the created resource.
/// </summary>
[Input("selfLink")]
public Input<string>? SelfLink { get; set; }
/// <summary>
/// How to distribute load. Options are "NONE" (no
/// affinity). "CLIENT\_IP" (hash of the source/dest addresses / ports), and
/// "CLIENT\_IP\_PROTO" also includes the protocol (default "NONE").
/// </summary>
[Input("sessionAffinity")]
public Input<string>? SessionAffinity { get; set; }
public TargetPoolState()
{
}
}
}
| 38.106312
| 137
| 0.576548
|
[
"ECL-2.0",
"Apache-2.0"
] |
dimpu47/pulumi-gcp
|
sdk/dotnet/Compute/TargetPool.cs
| 11,470
|
C#
|
namespace Dicres.RepositoryService.DataAccess.Contracts.Entities
{
public interface IBaseWithIdEntity : IBaseEntity
{
int Id { get; set; }
}
}
| 20.5
| 65
| 0.689024
|
[
"MIT"
] |
jorgediegocrespo/Coworking.Api
|
Coworking.Api/Dicres.RepositoryService.DataAccess.Contracts/Entitites/IBaseWithIdEntity.cs
| 166
|
C#
|
using System;
#if !NO_UNITY
using UnityEngine;
#endif
namespace Gaia.FullSerializer
{
/// <summary>
/// Extend this interface on your type to receive notifications about serialization/deserialization events. If you don't
/// have access to the type itself, then you can write an fsObjectProcessor instead.
/// </summary>
public interface fsISerializationCallbacks {
/// <summary>
/// Called before serialization.
/// </summary>
void OnBeforeSerialize(Type storageType);
/// <summary>
/// Called after serialization.
/// </summary>
/// <param name="storageType">The field/property type that is storing the instance.</param>
/// <param name="data">The data that was serialized.</param>
void OnAfterSerialize(Type storageType, ref fsData data);
/// <summary>
/// Called before deserialization.
/// </summary>
/// <param name="storageType">The field/property type that is storing the instance.</param>
/// <param name="data">The data that will be used for deserialization.</param>
void OnBeforeDeserialize(Type storageType, ref fsData data);
/// <summary>
/// Called after deserialization.
/// </summary>
/// <param name="storageType">The field/property type that is storing the instance.</param>
/// <param name="instance">The type of the instance.</param>
void OnAfterDeserialize(Type storageType);
}
}
namespace Gaia.FullSerializer.Internal
{
public class fsSerializationCallbackProcessor : fsObjectProcessor {
public override bool CanProcess(Type type) {
return typeof(fsISerializationCallbacks).IsAssignableFrom(type);
}
public override void OnBeforeSerialize(Type storageType, object instance) {
((fsISerializationCallbacks)instance).OnBeforeSerialize(storageType);
}
public override void OnAfterSerialize(Type storageType, object instance, ref fsData data) {
((fsISerializationCallbacks)instance).OnAfterSerialize(storageType, ref data);
}
public override void OnBeforeDeserializeAfterInstanceCreation(Type storageType, object instance, ref fsData data) {
if (instance is fsISerializationCallbacks == false) {
throw new InvalidCastException("Please ensure the converter for " + storageType + " actually returns an instance of it, not an instance of " + instance.GetType());
}
((fsISerializationCallbacks)instance).OnBeforeDeserialize(storageType, ref data);
}
public override void OnAfterDeserialize(Type storageType, object instance) {
((fsISerializationCallbacks)instance).OnAfterDeserialize(storageType);
}
}
#if !NO_UNITY
public class fsSerializationCallbackReceiverProcessor : fsObjectProcessor {
public override bool CanProcess(Type type) {
return typeof(ISerializationCallbackReceiver).IsAssignableFrom(type);
}
public override void OnBeforeSerialize(Type storageType, object instance) {
((ISerializationCallbackReceiver)instance).OnBeforeSerialize();
}
public override void OnAfterDeserialize(Type storageType, object instance) {
((ISerializationCallbackReceiver)instance).OnAfterDeserialize();
}
}
#endif
}
| 40.141176
| 179
| 0.676143
|
[
"MIT"
] |
naivetang/ET_FGUI
|
Unity/Assets/Resources/Gaia/Scripts/JsonSerialiser/fsISerializationCallbacks.cs
| 3,412
|
C#
|
// *** WARNING: this file was generated by the Pulumi Terraform Bridge (tfgen) Tool. ***
// *** Do not edit by hand unless you're certain you know what you are doing! ***
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Threading.Tasks;
using Pulumi.Serialization;
namespace Pulumi.Yandex.Outputs
{
[OutputType]
public sealed class MdbClickhouseClusterCloudStorage
{
/// <summary>
/// Whether to use Yandex Object Storage for storing ClickHouse data. Can be either `true` or `false`.
/// </summary>
public readonly bool Enabled;
[OutputConstructor]
private MdbClickhouseClusterCloudStorage(bool enabled)
{
Enabled = enabled;
}
}
}
| 27.678571
| 110
| 0.672258
|
[
"ECL-2.0",
"Apache-2.0"
] |
pulumi/pulumi-yandex
|
sdk/dotnet/Outputs/MdbClickhouseClusterCloudStorage.cs
| 775
|
C#
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using SBP_Data.Models;
using FluentNHibernate.Mapping;
namespace SBP_Data.Mappings
{
class LikMapiranje : ClassMap<Lik>
{
public LikMapiranje()
{
Table("LIK");
Id(x => x.Id, "LIK_ID").GeneratedBy.TriggerIdentity();
Map(x => x.HP).Column("HP");
Map(x => x.XP).Column("XP");
Map(x => x.Zlato).Column("ZLATO");
Map(x => x.StepenZamora).Column("STEPEN_ZAMORA");
References(x => x.Rasa).Column("RASA_FK").LazyLoad();//.Cascade.All();
References(x => x.Igrac).Column("IGRAC_FK").LazyLoad();
}
}
}
| 27.481481
| 82
| 0.58221
|
[
"MIT"
] |
Etheraex/SBP
|
SBP_Projekat/SBP_Data/Mappings/LikMapiranje.cs
| 744
|
C#
|
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("AnimalType")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Microsoft")]
[assembly: AssemblyProduct("AnimalType")]
[assembly: AssemblyCopyright("Copyright © Microsoft 2016")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("432a93f9-8dc6-4a45-b46e-2adac712a395")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| 38.135135
| 84
| 0.747697
|
[
"MIT"
] |
AquaRush/SoftwareUniversity
|
Programming-Basics-October-2016/Complex-Conditional-Statements/AnimalType/Properties/AssemblyInfo.cs
| 1,414
|
C#
|
using System.Collections.Generic;
using STRINGS;
using TUNING;
using UnityEngine;
public class PropGravitasShelfConfig : IEntityConfig
{
public string[] GetDlcIds()
{
return DlcManager.AVAILABLE_EXPANSION1_ONLY;
}
public GameObject CreatePrefab()
{
GameObject obj = EntityTemplates.CreatePlacedEntity("PropGravitasShelf", STRINGS.BUILDINGS.PREFABS.PROPGRAVITASSHELF.NAME, STRINGS.BUILDINGS.PREFABS.PROPGRAVITASSHELF.DESC, 50f, decor: TUNING.BUILDINGS.DECOR.BONUS.TIER0, noise: NOISE_POLLUTION.NOISY.TIER0, anim: Assets.GetAnim("gravitas_shelf_kanim"), initialAnim: "off", sceneLayer: Grid.SceneLayer.Building, width: 2, height: 1, element: SimHashes.Creature, additionalTags: new List<Tag> { GameTags.Gravitas });
PrimaryElement component = obj.GetComponent<PrimaryElement>();
component.SetElement(SimHashes.Granite);
component.Temperature = 294.15f;
obj.AddOrGet<Demolishable>();
return obj;
}
public void OnPrefabInit(GameObject inst)
{
inst.GetComponent<OccupyArea>().objectLayers = new ObjectLayer[1] { ObjectLayer.Building };
}
public void OnSpawn(GameObject inst)
{
}
}
| 34.625
| 466
| 0.783394
|
[
"MIT"
] |
undancer/oni-data
|
Managed/main/PropGravitasShelfConfig.cs
| 1,108
|
C#
|
using System;
using System.Collections.Generic;
using System.Linq;
namespace Luger.Configuration.CommandLine.Specifications
{
public static class CommandLineSpecificationExtensions
{
/// <summary>
/// Add flag.
/// </summary>
public static CommandLineSpecification AddFlagWithValue(
this CommandLineSpecification receiver,
string name,
string longName,
char shortName = default,
string value = "True")
=> receiver.Add(new FlagWithValueSpecification(new(name), new(longName), new(shortName), value));
/// <summary>
/// Add flag with value argument.
/// </summary>
public static CommandLineSpecification AddFlagWithArgument(
this CommandLineSpecification receiver,
string name,
string longName,
char shortName = default)
=> receiver.Add(new FlagWithArgumentSpecification(new(name), new(longName), new(shortName)));
/// <summary>
/// Flags enum of standard flags.
/// </summary>
[Flags]
public enum StandardFlagsFlags
{
DryRun = 1,
Help = 2,
Quiet = 4,
Verbose = 8
}
private static readonly Dictionary<StandardFlagsFlags, FlagSpecification> StandardFlags = new()
{
[StandardFlagsFlags.DryRun] = new FlagWithValueSpecification(new("DryRun"), new("dry-run"), new('n')),
[StandardFlagsFlags.Help] = new FlagWithValueSpecification(new("Help"), new("help"), new('h')),
[StandardFlagsFlags.Quiet] = new FlagWithValueSpecification(new("Quiet"), new("quiet"), new('q')),
[StandardFlagsFlags.Verbose] = new FlagWithValueSpecification(new("Verbose"), new("verbose"), new('v'))
};
/// <summary>
/// Add standard flags.
/// </summary>
/// <param name="standardFlags">Flags to add.</param>
public static CommandLineSpecification AddStandardFlags(
this CommandLineSpecification receiver,
StandardFlagsFlags standardFlags
= StandardFlagsFlags.DryRun
| StandardFlagsFlags.Help
| StandardFlagsFlags.Quiet
| StandardFlagsFlags.Verbose)
=> Enum.GetValues<StandardFlagsFlags>()
.Where(f => standardFlags.HasFlag(f))
.Aggregate(
seed: receiver,
func: (caf, sf) => caf.Add(StandardFlags[sf]));
/// <summary>
/// Add verb.
/// </summary>
public static CommandLineSpecification AddVerb(
this CommandLineSpecification receiver,
string name,
Func<CommandLineSpecification, CommandLineSpecification> commandLineSpecificationBuilder,
StringComparison verbNameComparison = StringComparison.OrdinalIgnoreCase,
StringComparison childNameComparison = StringComparison.OrdinalIgnoreCase)
{
var commandLineSpecification = commandLineSpecificationBuilder(new CommandLineSpecification(childNameComparison));
var verbSpecification = new VerbSpecification(new(name), commandLineSpecification, verbNameComparison);
return receiver.Add(verbSpecification);
}
/// <summary>
/// Add argument.
/// </summary>
public static CommandLineSpecification AddArgument(this CommandLineSpecification receiver, string name)
=> receiver.Add(new ArgumentSpecification(new(name)));
/// <summary>
/// Add multi-argument.
/// </summary>
public static CommandLineSpecification AddMultiArgument(this CommandLineSpecification receiver, string name)
=> receiver.Add(new MultiArgumentSpecification(new(name)));
}
}
| 38.50495
| 126
| 0.616868
|
[
"MIT"
] |
chamalulu/Luger
|
src/Config.CommandLine/Specifications/CommandLineSpecificationExtensions.cs
| 3,889
|
C#
|
// Copyright 2013 The Noda Time Authors. All rights reserved.
// Use of this source code is governed by the Apache License 2.0,
// as found in the LICENSE.txt file.
using NodaTime.Annotations;
using NodaTime.TimeZones.IO;
using NodaTime.Utility;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
namespace NodaTime.TimeZones.Cldr
{
/// <summary>
/// Represents a single <c><mapZone></c> element in the CLDR Windows zone mapping file.
/// </summary>
/// <remarks>
/// <para>
/// Equality is defined in a component-wise fashion. When comparing two values for equality, the <see cref="TzdbIds"/> properties
/// must return the same IDs in the same order for the values to be considered equal.
/// </para>
/// </remarks>
/// <threadsafety>This type is immutable reference type. See the thread safety section of the user guide for more information.</threadsafety>
[Immutable]
public sealed class MapZone : IEquatable<MapZone?>
{
/// <summary>
/// Identifier used for the primary territory of each Windows time zone. A zone mapping with
/// this territory will always have a single entry. The value of this constant is "001".
/// </summary>
public const string PrimaryTerritory = "001";
/// <summary>
/// Identifier used for the "fixed offset" territory. A zone mapping with
/// this territory will always have a single entry. The value of this constant is "ZZ".
/// </summary>
public const string FixedOffsetTerritory = "ZZ";
/// <summary>
/// Gets the Windows system time zone identifier for this mapping, such as "Central Standard Time".
/// </summary>
/// <remarks>
/// <para>
/// Most Windows system time zone identifiers use the name for the "standard" part of the zone as
/// the overall identifier. Don't be fooled: just because a time zone includes "standard" in its identifier
/// doesn't mean that it doesn't observe daylight saving time.
/// </para>
/// </remarks>
/// <value>The Windows system time zone identifier for this mapping, such as "Central Standard Time".</value>
public string WindowsId { get; }
/// <summary>
/// Gets the territory code for this mapping.
/// </summary>
/// <remarks>
/// This is typically either "001" to indicate that it's the primary territory for this ID, or
/// "ZZ" to indicate a fixed-offset ID, or a different two-character capitalized code
/// which indicates the geographical territory.
/// </remarks>
/// <value>The territory code for this mapping.</value>
public string Territory { get; }
/// <summary>
/// Gets a read-only non-empty collection of TZDB zone identifiers for this mapping, such as
/// "America/Chicago" and "America/Matamoros" (both of which are TZDB zones associated with the "Central Standard Time"
/// Windows system time zone).
/// </summary>
/// <remarks>
/// For the primary and fixed-offset territory IDs ("001" and "ZZ") this always
/// contains exactly one time zone ID. The IDs returned are not necessarily canonical in TZDB.
/// </remarks>
/// <value>A read-only non-empty collection of TZDB zone identifiers for this mapping.</value>
public IList<string> TzdbIds { get; }
/// <summary>
/// Creates a new mapping entry.
/// </summary>
/// <remarks>
/// This constructor is only public for the sake of testability.
/// </remarks>
/// <param name="windowsId">Windows system time zone identifier. Must not be null.</param>
/// <param name="territory">Territory code. Must not be null.</param>
/// <param name="tzdbIds">List of territory codes. Must not be null, and must not
/// contains null values.</param>
public MapZone(string windowsId, string territory, IList<string> tzdbIds)
: this(Preconditions.CheckNotNull(windowsId, nameof(windowsId)),
Preconditions.CheckNotNull(territory, nameof(territory)),
new ReadOnlyCollection<string>(new List<string>(Preconditions.CheckNotNull(tzdbIds, nameof(tzdbIds)))))
{
}
/// <summary>
/// Private constructor to avoid unnecessary list copying (and validation) when deserializing.
/// </summary>
private MapZone(string windowsId, string territory, ReadOnlyCollection<string> tzdbIds)
{
this.WindowsId = windowsId;
this.Territory = territory;
this.TzdbIds = tzdbIds;
}
/// <summary>
/// Reads a mapping from a reader.
/// </summary>
internal static MapZone Read(IDateTimeZoneReader reader)
{
string windowsId = reader.ReadString();
string territory = reader.ReadString();
int count = reader.ReadCount();
string[] tzdbIds = new string[count];
for (int i = 0; i < count; i++)
{
tzdbIds[i] = reader.ReadString();
}
return new MapZone(windowsId, territory, new ReadOnlyCollection<string>(tzdbIds));
}
/// <summary>
/// Writes this mapping to a writer.
/// </summary>
/// <param name="writer"></param>
internal void Write(IDateTimeZoneWriter writer)
{
writer.WriteString(WindowsId);
writer.WriteString(Territory);
writer.WriteCount(TzdbIds.Count);
foreach (string id in TzdbIds)
{
writer.WriteString(id);
}
}
/// <summary>
/// Compares two <see cref="MapZone"/> values for equality.
/// See the type documentation for a description of equality semantics.
/// </summary>
/// <param name="other">The value to compare this map zone with.</param>
/// <returns>True if the given value is another map zone equal to this one; false otherwise.</returns>
public bool Equals(MapZone? other) =>
other != null &&
WindowsId == other.WindowsId &&
Territory == other.Territory &&
TzdbIds.SequenceEqual(other.TzdbIds);
/// <summary>
/// Returns a hash code for this map zone.
/// See the type documentation for a description of equality semantics.
/// </summary>
/// <returns>A hash code for this map zone.</returns>
public override int GetHashCode()
{
var hash = HashCodeHelper.Initialize().Hash(WindowsId).Hash(Territory);
foreach (var id in TzdbIds)
{
hash = hash.Hash(id);
}
return hash.Value;
}
/// <summary>
/// Compares two <see cref="MapZone"/> values for equality.
/// See the type documentation for a description of equality semantics.
/// </summary>
/// <param name="obj">The value to compare this map zone with.</param>
/// <returns>True if the given value is another map zone equal to this one; false otherwise.</returns>
public override bool Equals(object? obj) => Equals(obj as MapZone);
/// <summary>
/// Returns a <see cref="System.String" /> that represents this instance.
/// </summary>
/// <returns>
/// The value of the current instance, for diagnostic purposes.
/// </returns>
public override string ToString()
=> $"Windows ID: {WindowsId}; Territory: {Territory}; TzdbIds: {string.Join(" ", TzdbIds)}";
}
}
| 43.853933
| 145
| 0.604151
|
[
"Apache-2.0"
] |
0xced/nodatime
|
src/NodaTime/TimeZones/Cldr/MapZone.cs
| 7,808
|
C#
|
namespace Merchello.Web.Search
{
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using Core;
using Core.Models;
using Core.Persistence.Querying;
using Core.Services;
using Examine;
using global::Examine;
using global::Examine.Providers;
using Merchello.Core.Chains;
using Merchello.Core.ValueConverters;
using Merchello.Examine.Providers;
using Merchello.Web.Caching;
using Merchello.Web.DataModifiers;
using Merchello.Web.DataModifiers.Product;
using Merchello.Web.Models;
using Merchello.Web.Models.ContentEditing.Content;
using Merchello.Web.Models.VirtualContent;
using Models.ContentEditing;
using Models.Querying;
using Umbraco.Core.Cache;
using Umbraco.Core.Events;
using Umbraco.Core.Persistence;
/// <summary>
/// Represents a CachedProductQuery
/// </summary>
internal class CachedProductQuery : CachedQueryableCollectionQueryBase<IProduct, ProductDisplay>, ICachedProductQuery
{
/// <summary>
/// The product service.
/// </summary>
private readonly ProductService _productService;
/// <summary>
/// A value indicating whether or not this is being used for back office editors.
/// </summary>
private readonly DetachedValuesConversionType _conversionType;
/// <summary>
/// The <see cref="ProductContentFactory"/>.
/// </summary>
private readonly Lazy<ProductContentFactory> _productContentFactory;
/// <summary>
/// The <see cref="VirtualProductContentCache"/>.
/// </summary>
private VirtualProductContentCache _cache;
/// <summary>
/// The data modifier.
/// </summary>
private Lazy<IDataModifierChain<IProductVariantDataModifierData>> _dataModifier;
/// <summary>
/// Initializes a new instance of the <see cref="CachedProductQuery"/> class.
/// </summary>
public CachedProductQuery()
: this(MerchelloContext.Current, true)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="CachedProductQuery"/> class.
/// </summary>
/// <param name="merchelloContext">
/// The <see cref="IMerchelloContext"/>.
/// </param>
/// <param name="enableDataModifiers">
/// A value indicating whether or not data modifiers are enabled.
/// </param>
public CachedProductQuery(IMerchelloContext merchelloContext, bool enableDataModifiers)
: this(merchelloContext, enableDataModifiers, DetachedValuesConversionType.Db)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="CachedProductQuery"/> class.
/// </summary>
/// <param name="merchelloContext">
/// The <see cref="IMerchelloContext"/>.
/// </param>
/// <param name="indexProvider">
/// The index provider.
/// </param>
/// <param name="searchProvider">
/// The search provider.
/// </param>
/// <param name="enableDataModifiers">
/// A value indicating whether or not data modifiers are enabled.
/// </param>
public CachedProductQuery(IMerchelloContext merchelloContext, BaseIndexProvider indexProvider, BaseSearchProvider searchProvider, bool enableDataModifiers)
: this(merchelloContext, indexProvider, searchProvider, enableDataModifiers, DetachedValuesConversionType.Db)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="CachedProductQuery"/> class.
/// </summary>
/// <param name="merchelloContext">
/// The <see cref="IMerchelloContext"/>.
/// </param>
/// <param name="enableDataModifiers">
/// The enable data modifiers.
/// </param>
/// <param name="conversionType">
/// The detached value conversion type.
/// </param>
internal CachedProductQuery(IMerchelloContext merchelloContext, bool enableDataModifiers, DetachedValuesConversionType conversionType)
: this(
merchelloContext,
ExamineManager.Instance.IndexProviderCollection["MerchelloProductIndexer"],
ExamineManager.Instance.SearchProviderCollection["MerchelloProductSearcher"],
enableDataModifiers,
conversionType)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="CachedProductQuery"/> class.
/// </summary>
/// <param name="merchelloContext">
/// The <see cref="IMerchelloContext"/>.
/// </param>
/// <param name="indexProvider">
/// The index provider.
/// </param>
/// <param name="searchProvider">
/// The search provider.
/// </param>
/// <param name="enableDataModifiers">
/// The enable data modifiers.
/// </param>
/// <param name="conversionType">
/// The is for back office editors.
/// </param>
internal CachedProductQuery(IMerchelloContext merchelloContext, BaseIndexProvider indexProvider, BaseSearchProvider searchProvider, bool enableDataModifiers, DetachedValuesConversionType conversionType)
: base(merchelloContext.Cache, merchelloContext.Services.ProductService, indexProvider, searchProvider, enableDataModifiers)
{
_productService = (ProductService)merchelloContext.Services.ProductService;
this._conversionType = conversionType;
_productContentFactory = new Lazy<ProductContentFactory>(() => new ProductContentFactory());
_cache = new VirtualProductContentCache(merchelloContext.Cache, this.GetProductContent, enableDataModifiers);
this.Initialize();
}
internal event TypedEventHandler<CachedProductQuery, bool> DataModifierChanged;
/// <summary>
/// Gets or sets a value indicating whether enable data modifiers.
/// </summary>
internal override bool EnableDataModifiers
{
get
{
return base.EnableDataModifiers;
}
set
{
base.EnableDataModifiers = value;
if (DataModifierChanged != null)
{
DataModifierChanged.Invoke(this, value);
}
}
}
/// <summary>
/// Gets the key field in index.
/// </summary>
protected override string KeyFieldInIndex
{
get { return "productKey"; }
}
/// <summary>
/// Gets <see cref="IProductContent"/> by it's key
/// </summary>
/// <param name="key">
/// The key.
/// </param>
/// <returns>
/// The <see cref="IProductContent"/>.
/// </returns>
public IProductContent TypedProductContent(Guid key)
{
return _cache.GetByKey(key);
}
/// <summary>
/// Gets the typed content by it's sku.
/// </summary>
/// <param name="sku">
/// The sku.
/// </param>
/// <returns>
/// The <see cref="IProductContent"/>.
/// </returns>
public IProductContent TypedProductContentBySku(string sku)
{
return _cache.GetBySku(sku, GetProductContentBySku);
}
/// <summary>
/// Gets the typed content by it's slug.
/// </summary>
/// <param name="slug">
/// The slug.
/// </param>
/// <returns>
/// The <see cref="IProductContent"/>.
/// </returns>
public IProductContent TypedProductContentBySlug(string slug)
{
return _cache.GetBySlug(slug, GetProductContentBySlug);
}
/// <summary>
/// Gets the typed <see cref="IProductContent"/> for a collection.
/// </summary>
/// <param name="collectionKey">
/// The collection key.
/// </param>
/// <returns>
/// The <see cref="IEnumerable{IProductContent}"/>.
/// </returns>
public IEnumerable<IProductContent> TypedProductContentFromCollection(Guid collectionKey)
{
return TypedProductContentFromCollection(collectionKey, 1, long.MaxValue);
}
/// <summary>
/// The typed product content from collection.
/// </summary>
/// <param name="collectionKey">
/// The collection key.
/// </param>
/// <param name="page">
/// The page.
/// </param>
/// <param name="itemsPerPage">
/// The items per page.
/// </param>
/// <param name="sortBy">
/// The sort by.
/// </param>
/// <param name="sortDirection">
/// The sort direction.
/// </param>
/// <returns>
/// The <see cref="IEnumerable{IProductContent}"/>.
/// </returns>
public IEnumerable<IProductContent> TypedProductContentFromCollection(
Guid collectionKey,
long page,
long itemsPerPage,
string sortBy = "",
SortDirection sortDirection = SortDirection.Ascending,
bool includeUnavailable = false)
{
return TypedProductContentPageFromCollection(collectionKey, page, itemsPerPage, sortBy, sortDirection, includeUnavailable).Items;
}
/// <summary>
/// Gets a <see cref="PagedCollection{IProductContent}"/>.
/// </summary>
/// <param name="collectionKey">
/// The collection key.
/// </param>
/// <param name="page">
/// The page.
/// </param>
/// <param name="itemsPerPage">
/// The items per page.
/// </param>
/// <param name="sortBy">
/// The sort by.
/// </param>
/// <param name="sortDirection">
/// The sort direction.
/// </param>
/// <returns>
/// The <see cref="PagedCollection"/>.
/// </returns>
public PagedCollection<IProductContent> TypedProductContentPageFromCollection(
Guid collectionKey,
long page,
long itemsPerPage,
string sortBy = "",
SortDirection sortDirection = SortDirection.Ascending,
bool includeUnavailable = false)
{
var pagedKeys = GetCollectionPagedKeys(collectionKey, page, itemsPerPage, sortBy, sortDirection, includeUnavailable);
return _cache.GetPagedCollectionByCacheKey(pagedKeys, sortBy);
}
/// <summary>
/// Search returning an <see cref="IProductContent"/> collection.
/// </summary>
/// <param name="page">
/// The page.
/// </param>
/// <param name="itemsPerPage">
/// The items per page.
/// </param>
/// <param name="sortBy">
/// The sort by.
/// </param>
/// <param name="sortDirection">
/// The sort direction.
/// </param>
/// <returns>
/// The <see cref="IEnumerable{IProductContent}"/>.
/// </returns>
public IEnumerable<IProductContent> TypedProductContentSearch(long page, long itemsPerPage, string sortBy = "name", SortDirection sortDirection = SortDirection.Descending, bool includeUnavailable = false)
{
return TypedProductContentSearchPaged(page, itemsPerPage, sortBy, sortDirection, includeUnavailable).Items;
}
/// <summary>
/// Search returning an <see cref="IProductContent"/> collection.
/// </summary>
/// <param name="term">
/// The term.
/// </param>
/// <param name="page">
/// The page.
/// </param>
/// <param name="itemsPerPage">
/// The items per page.
/// </param>
/// <param name="sortBy">
/// The sort by.
/// </param>
/// <param name="sortDirection">
/// The sort direction.
/// </param>
/// <returns>
/// The <see cref="IEnumerable{IProductContent}"/>.
/// </returns>
public IEnumerable<IProductContent> TypedProductContentSearch(
string term,
long page,
long itemsPerPage,
string sortBy = "name",
SortDirection sortDirection = SortDirection.Ascending,
bool includeUnavailable = false)
{
return TypedProductContentSearchPaged(term, page, itemsPerPage, sortBy, sortDirection, includeUnavailable).Items;
}
/// <summary>
/// Search returning an <see cref="IProductContent"/> paged collection.
/// </summary>
/// <param name="page">
/// The page.
/// </param>
/// <param name="itemsPerPage">
/// The items per page.
/// </param>
/// <param name="sortBy">
/// The sort by.
/// </param>
/// <param name="sortDirection">
/// The sort direction.
/// </param>
/// <returns>
/// The <see cref="PagedCollection"/>.
/// </returns>
public PagedCollection<IProductContent> TypedProductContentSearchPaged(
long page,
long itemsPerPage,
string sortBy = "name",
SortDirection sortDirection = SortDirection.Descending,
bool includeUnavailable = false)
{
var cacheKey = PagedKeyCache.GetPagedQueryCacheKey<ICachedProductQuery>("Search", page, itemsPerPage, sortBy, sortDirection, includeUnavailable);
var pagedKeys = PagedKeyCache.GetPageByCacheKey(cacheKey);
if (pagedKeys != null) return _cache.MapPagedCollection(pagedKeys, sortBy);
return
_cache.GetPagedCollectionByCacheKey(
PagedKeyCache.CachePage(cacheKey, _productService.GetPagedKeys(page, itemsPerPage, sortBy, sortDirection, includeUnavailable)),
sortBy);
}
/// <summary>
/// Search returning an <see cref="IProductContent"/> paged collection.
/// </summary>
/// <param name="term">
/// The term.
/// </param>
/// <param name="page">
/// The page.
/// </param>
/// <param name="itemsPerPage">
/// The items per page.
/// </param>
/// <param name="sortBy">
/// The sort by.
/// </param>
/// <param name="sortDirection">
/// The sort direction.
/// </param>
/// <returns>
/// The <see cref="PagedCollection"/>.
/// </returns>
public PagedCollection<IProductContent> TypedProductContentSearchPaged(
string term,
long page,
long itemsPerPage,
string sortBy = "name",
SortDirection sortDirection = SortDirection.Descending,
bool includeUnavailable = false)
{
var cacheKey = PagedKeyCache.GetPagedQueryCacheKey<ICachedProductQuery>("Search", page, itemsPerPage, sortBy, sortDirection, includeUnavailable, new Dictionary<string, string> { { "term", term } });
var pagedKeys = PagedKeyCache.GetPageByCacheKey(cacheKey);
return
_cache.GetPagedCollectionByCacheKey(
pagedKeys ?? _productService.GetPagedKeys(term, page, itemsPerPage, sortBy, sortDirection, includeUnavailable),
sortBy);
}
/// <inheritdoc />
public PagedCollection<IProductContent> TypedProductContentByPriceRange(
decimal min,
decimal max,
long page,
long itemsPerPage,
string sortBy = "price",
SortDirection sortDirection = SortDirection.Descending,
bool includeUnavailable = false)
{
var cacheKey = PagedKeyCache.GetPagedQueryCacheKey<ICachedProductQuery>(
"GetProductsInPriceRange",
page,
itemsPerPage,
sortBy,
sortDirection,
includeUnavailable,
new Dictionary<string, string>
{
{ "min", min.ToString(CultureInfo.InvariantCulture) },
{ "max", max.ToString(CultureInfo.InvariantCulture) }
});
var pagedKeys = PagedKeyCache.GetPageByCacheKey(cacheKey);
return
_cache.GetPagedCollectionByCacheKey(
pagedKeys ?? _productService.GetProductsKeysInPriceRange(min, max, page, itemsPerPage, sortBy, sortDirection, includeUnavailable),
sortBy);
}
///// <inheritdoc />
//public PagedCollection<IProductContent> TypedProductContentByPriceRange(
// string searchTerm,
// decimal min,
// decimal max,
// long page,
// long itemsPerPage,
// string sortBy = "price",
// SortDirection sortDirection = SortDirection.Descending)
//{
// throw new NotImplementedException();
//}
/// <summary>
/// Gets a <see cref="PagedCollection{IProductContent}"/> that exists in every collection referenced.
/// </summary>
/// <param name="collectionKeys">
/// The collection of collection keys.
/// </param>
/// <param name="page">
/// The page.
/// </param>
/// <param name="itemsPerPage">
/// The items per page.
/// </param>
/// <param name="sortBy">
/// The sort by.
/// </param>
/// <param name="sortDirection">
/// The sort direction.
/// </param>
/// <returns>
/// The <see cref="PagedCollection"/>.
/// </returns>
public PagedCollection<IProductContent> TypedProductContentPageThatExistInAllCollections(
IEnumerable<Guid> collectionKeys,
long page,
long itemsPerPage,
string sortBy = "",
SortDirection sortDirection = SortDirection.Ascending,
bool includeUnavailable = false)
{
var keys = collectionKeys as Guid[] ?? collectionKeys.ToArray();
if (!keys.Any()) return PagedCollection<IProductContent>.Empty();
var pagedKeys = ((ProductService)Service).GetKeysThatExistInAllCollections(keys, page, itemsPerPage, sortBy, sortDirection, includeUnavailable);
return _cache.MapPagedCollection(pagedKeys, sortBy);
}
/// <summary>
/// Gets a <see cref="PagedCollection{IProductContent}"/> that exists in every collection referenced.
/// </summary>
/// <param name="collectionKeys">
/// The collection of collection keys.
/// </param>
/// <param name="searchTerm">
/// The search Term.
/// </param>
/// <param name="page">
/// The page.
/// </param>
/// <param name="itemsPerPage">
/// The items per page.
/// </param>
/// <param name="sortBy">
/// The sort by.
/// </param>
/// <param name="sortDirection">
/// The sort direction.
/// </param>
/// <returns>
/// The <see cref="PagedCollection"/>.
/// </returns>
public PagedCollection<IProductContent> TypedProductContentPageThatExistInAllCollections(
IEnumerable<Guid> collectionKeys,
string searchTerm,
long page,
long itemsPerPage,
string sortBy = "",
SortDirection sortDirection = SortDirection.Ascending,
bool includeUnavailable = false)
{
var keys = collectionKeys as Guid[] ?? collectionKeys.ToArray();
if (!keys.Any()) return PagedCollection<IProductContent>.Empty();
var pagedKeys = ((ProductService)Service).GetKeysThatExistInAllCollections(keys, searchTerm, page, itemsPerPage, sortBy, sortDirection, includeUnavailable);
return _cache.MapPagedCollection(pagedKeys, sortBy);
}
/// <inheritdoc/>
public PagedCollection<IProductContent> TypedProductContentPageThatExistInAllCollections(
IEnumerable<Guid> collectionKeys,
decimal min,
decimal max,
long page,
long itemsPerPage,
string sortBy = "",
SortDirection sortDirection = SortDirection.Ascending,
bool includeUnavailable = false)
{
var keys = collectionKeys as Guid[] ?? collectionKeys.ToArray();
if (!keys.Any()) return PagedCollection<IProductContent>.Empty();
var pagedKeys = ((ProductService)Service).GetKeysThatExistInAllCollections(keys, min, max, page, itemsPerPage, sortBy, sortDirection, includeUnavailable);
return _cache.MapPagedCollection(pagedKeys, sortBy);
}
/// <inheritdoc/>
public PagedCollection<IProductContent> TypedProductContentPageThatExistInAllCollections(
IEnumerable<Guid> collectionKeys,
string searchTerm,
decimal min,
decimal max,
long page,
long itemsPerPage,
string sortBy = "",
SortDirection sortDirection = SortDirection.Ascending,
bool includeUnavailable = false)
{
var keys = collectionKeys as Guid[] ?? collectionKeys.ToArray();
if (!keys.Any()) return PagedCollection<IProductContent>.Empty();
var pagedKeys = ((ProductService)Service).GetKeysThatExistInAllCollections(keys, searchTerm, min, max, page, itemsPerPage, sortBy, sortDirection, includeUnavailable);
return _cache.MapPagedCollection(pagedKeys, sortBy);
}
/// <summary>
/// Gets a <see cref="PagedCollection{IProductContent}"/> that does not exists in any of the collections referenced..
/// </summary>
/// <param name="collectionKeys">
/// The collection keys.
/// </param>
/// <param name="page">
/// The page.
/// </param>
/// <param name="itemsPerPage">
/// The items per page.
/// </param>
/// <param name="sortBy">
/// The sort by.
/// </param>
/// <param name="sortDirection">
/// The sort direction.
/// </param>
/// <returns>
/// The <see cref="PagedCollection"/>.
/// </returns>
public PagedCollection<IProductContent> TypedProductContentPageThatNotInAnyCollections(
IEnumerable<Guid> collectionKeys,
long page,
long itemsPerPage,
string sortBy = "",
SortDirection sortDirection = SortDirection.Ascending,
bool includeUnavailable = false)
{
var keys = collectionKeys as Guid[] ?? collectionKeys.ToArray();
if (!keys.Any()) return PagedCollection<IProductContent>.Empty();
var pagedKeys = ((ProductService)Service).GetKeysNotInAnyCollections(keys, page, itemsPerPage, sortBy, sortDirection, includeUnavailable);
return _cache.MapPagedCollection(pagedKeys, sortBy);
}
/// <summary>
/// Gets a <see cref="PagedCollection{IProductContent}"/> that does not exists in any of the collections referenced..
/// </summary>
/// <param name="collectionKeys">
/// The collection keys.
/// </param>
/// <param name="searchTerm">
/// The search Term.
/// </param>
/// <param name="page">
/// The page.
/// </param>
/// <param name="itemsPerPage">
/// The items per page.
/// </param>
/// <param name="sortBy">
/// The sort by.
/// </param>
/// <param name="sortDirection">
/// The sort direction.
/// </param>
/// <returns>
/// The <see cref="PagedCollection"/>.
/// </returns>
public PagedCollection<IProductContent> TypedProductContentPageThatNotInAnyCollections(
IEnumerable<Guid> collectionKeys,
string searchTerm,
long page,
long itemsPerPage,
string sortBy = "",
SortDirection sortDirection = SortDirection.Ascending,
bool includeUnavailable = false)
{
var keys = collectionKeys as Guid[] ?? collectionKeys.ToArray();
if (!keys.Any()) return PagedCollection<IProductContent>.Empty();
var pagedKeys = ((ProductService)Service).GetKeysNotInAnyCollections(keys, searchTerm, page, itemsPerPage, sortBy, sortDirection, includeUnavailable);
return _cache.MapPagedCollection(pagedKeys, sortBy);
}
/// <inheritdoc/>
public PagedCollection<IProductContent> TypedProductContentPageThatNotInAnyCollections(
IEnumerable<Guid> collectionKeys,
decimal min,
decimal max,
long page,
long itemsPerPage,
string sortBy = "",
SortDirection sortDirection = SortDirection.Ascending,
bool includeUnavailable = false)
{
var keys = collectionKeys as Guid[] ?? collectionKeys.ToArray();
if (!keys.Any()) return PagedCollection<IProductContent>.Empty();
var pagedKeys = ((ProductService)Service).GetKeysNotInAnyCollections(keys, min, max, page, itemsPerPage, sortBy, sortDirection, includeUnavailable);
return _cache.MapPagedCollection(pagedKeys, sortBy);
}
/// <inheritdoc/>
public PagedCollection<IProductContent> TypedProductContentPageThatNotInAnyCollections(
IEnumerable<Guid> collectionKeys,
string searchTerm,
decimal min,
decimal max,
long page,
long itemsPerPage,
string sortBy = "",
SortDirection sortDirection = SortDirection.Ascending,
bool includeUnavailable = false)
{
var keys = collectionKeys as Guid[] ?? collectionKeys.ToArray();
if (!keys.Any()) return PagedCollection<IProductContent>.Empty();
var pagedKeys = ((ProductService)Service).GetKeysNotInAnyCollections(keys, searchTerm, min, max, page, itemsPerPage, sortBy, sortDirection, includeUnavailable);
return _cache.MapPagedCollection(pagedKeys, sortBy);
}
/// <summary>
/// Gets a <see cref="PagedCollection{IProductContent}"/> that exists in any of the collections passed.
/// </summary>
/// <param name="collectionKeys">
/// The collection keys.
/// </param>
/// <param name="page">
/// The page.
/// </param>
/// <param name="itemsPerPage">
/// The items per page.
/// </param>
/// <param name="sortBy">
/// The sort by.
/// </param>
/// <param name="sortDirection">
/// The sort direction.
/// </param>
/// <returns>
/// The <see cref="PagedCollection"/>.
/// </returns>
public PagedCollection<IProductContent> TypedProductContentPageThatExistsInAnyCollections(
IEnumerable<Guid> collectionKeys,
long page,
long itemsPerPage,
string sortBy = "",
SortDirection sortDirection = SortDirection.Ascending,
bool includeUnavailable = false)
{
var keys = collectionKeys as Guid[] ?? collectionKeys.ToArray();
if (!keys.Any()) return PagedCollection<IProductContent>.Empty();
var pagedKeys = ((ProductService)Service).GetKeysThatExistInAnyCollections(keys, page, itemsPerPage, sortBy, sortDirection, includeUnavailable);
return _cache.MapPagedCollection(pagedKeys, sortBy);
}
/// <summary>
/// Gets a <see cref="PagedCollection{IProductContent}"/> that exists in any of the collections passed.
/// </summary>
/// <param name="collectionKeys">
/// The collection keys.
/// </param>
/// <param name="searchTerm">
/// The search Term.
/// </param>
/// <param name="page">
/// The page.
/// </param>
/// <param name="itemsPerPage">
/// The items per page.
/// </param>
/// <param name="sortBy">
/// The sort by.
/// </param>
/// <param name="sortDirection">
/// The sort direction.
/// </param>
/// <returns>
/// The <see cref="PagedCollection"/>.
/// </returns>
public PagedCollection<IProductContent> TypedProductContentPageThatExistsInAnyCollections(
IEnumerable<Guid> collectionKeys,
string searchTerm,
long page,
long itemsPerPage,
string sortBy = "",
SortDirection sortDirection = SortDirection.Ascending,
bool includeUnavailable = false)
{
var keys = collectionKeys as Guid[] ?? collectionKeys.ToArray();
if (!keys.Any()) return PagedCollection<IProductContent>.Empty();
var pagedKeys = ((ProductService)Service).GetKeysThatExistInAnyCollections(keys, searchTerm, page, itemsPerPage, sortBy, sortDirection, includeUnavailable);
return _cache.MapPagedCollection(pagedKeys, sortBy);
}
/// <inheritdoc/>
public PagedCollection<IProductContent> TypedProductContentPageThatExistsInAnyCollections(
IEnumerable<Guid> collectionKeys,
decimal min,
decimal max,
long page,
long itemsPerPage,
string sortBy = "",
SortDirection sortDirection = SortDirection.Ascending,
bool includeUnavailable = false)
{
var keys = collectionKeys as Guid[] ?? collectionKeys.ToArray();
if (!keys.Any()) return PagedCollection<IProductContent>.Empty();
var pagedKeys = ((ProductService)Service).GetKeysThatExistInAnyCollections(keys, min, max, page, itemsPerPage, sortBy, sortDirection, includeUnavailable);
return _cache.MapPagedCollection(pagedKeys, sortBy);
}
/// <inheritdoc/>
public PagedCollection<IProductContent> TypedProductContentPageThatExistsInAnyCollections(
IEnumerable<Guid> collectionKeys,
string searchTerm,
decimal min,
decimal max,
long page,
long itemsPerPage,
string sortBy = "",
SortDirection sortDirection = SortDirection.Ascending,
bool includeUnavailable = false)
{
var keys = collectionKeys as Guid[] ?? collectionKeys.ToArray();
if (!keys.Any()) return PagedCollection<IProductContent>.Empty();
var pagedKeys = ((ProductService)Service).GetKeysThatExistInAnyCollections(keys, searchTerm, min, max, page, itemsPerPage, sortBy, sortDirection, includeUnavailable);
return _cache.MapPagedCollection(pagedKeys, sortBy);
}
/// <summary>
/// Gets a <see cref="ProductDisplay"/> by it's unique key
/// </summary>
/// <param name="key">
/// The key.
/// </param>
/// <returns>
/// The <see cref="ProductDisplay"/>.
/// </returns>
public override ProductDisplay GetByKey(Guid key)
{
//// modify data is handled in GetDisplayObject!
return GetDisplayObject(key);
}
/// <summary>
/// Gets a <see cref="ProductDisplay"/> by it's SKU.
/// </summary>
/// <param name="sku">
/// The SKU.
/// </param>
/// <returns>
/// The <see cref="ProductDisplay"/>.
/// </returns>
public ProductDisplay GetBySku(string sku)
{
var criteria = SearchProvider.CreateSearchCriteria();
criteria.Field("sku", sku).And().Field("master", "True");
var displays = SearchProvider.Search(criteria).Select(PerformMapSearchResultToDisplayObject);
var display = displays.FirstOrDefault(x => x.Sku.Equals(sku, StringComparison.InvariantCultureIgnoreCase));
if (display != null) return this.ModifyData(display);
var entity = _productService.GetBySku(sku);
if (entity == null) return null;
ReindexEntity(entity);
return this.ModifyData(entity.ToProductDisplay(this._conversionType));
}
/// <summary>
/// Gets a product by it's slug.
/// </summary>
/// <param name="slug">
/// The slug.
/// </param>
/// <returns>
/// The <see cref="ProductDisplay"/>.
/// </returns>
public ProductDisplay GetBySlug(string slug)
{
var criteria = SearchProvider.CreateSearchCriteria();
criteria.Field("slugs", slug).And().Field("master", "True");
var displays = SearchProvider.Search(criteria).Select(PerformMapSearchResultToDisplayObject).ToArray();
var display = displays.FirstOrDefault(x => x.DetachedContents.Any(y => y.Slug.Equals(slug, StringComparison.InvariantCultureIgnoreCase)));
// Don't modify the data here as it would have been modified in the PerformMapSearchResultToDisplayObject
if (display != null) return display;
var key = _productService.GetKeyForSlug(slug);
return Guid.Empty.Equals(key) ? null : this.GetByKey(key);
}
/// <summary>
/// Gets a <see cref="ProductVariantDisplay"/> by it's key
/// </summary>
/// <param name="key">
/// The key.
/// </param>
/// <returns>
/// The <see cref="ProductVariantDisplay"/>.
/// </returns>
public ProductVariantDisplay GetProductVariantByKey(Guid key)
{
var criteria = SearchProvider.CreateSearchCriteria();
criteria.Field("productVariantKey", key.ToString());
var result = CachedSearch(criteria, ExamineDisplayExtensions.ToProductVariantDisplay).FirstOrDefault();
if (result != null)
{
result.EnsureValueConversion(this._conversionType);
return this.ModifyData(result);
}
var variant = _productService.GetProductVariantByKey(key);
if (variant != null)
{
this.ReindexEntity(variant);
return this.ModifyData(variant.ToProductVariantDisplay(this._conversionType));
}
return null;
}
/// <summary>
/// Gets a <see cref="ProductVariantDisplay"/> by it's unique SKU
/// </summary>
/// <param name="sku">
/// The SKU.
/// </param>
/// <returns>
/// The <see cref="ProductVariantDisplay"/>.
/// </returns>
public ProductVariantDisplay GetProductVariantBySku(string sku)
{
var criteria = SearchProvider.CreateSearchCriteria();
criteria.Field("sku", sku).Not().Field("master", "True");
var result = CachedSearch(criteria, ExamineDisplayExtensions.ToProductVariantDisplay).FirstOrDefault();
if (result != null)
{
result.EnsureValueConversion(this._conversionType);
return this.ModifyData(result);
}
var variant = _productService.GetProductVariantBySku(sku);
if (variant != null)
{
this.ReindexEntity(variant);
return this.ModifyData(variant.ToProductVariantDisplay(this._conversionType));
}
return null;
}
/// <summary>
/// Searches all products
/// </summary>
/// <param name="page">
/// The page.
/// </param>
/// <param name="itemsPerPage">
/// The items per page.
/// </param>
/// <param name="sortBy">
/// The sort by.
/// </param>
/// <param name="sortDirection">
/// The sort direction.
/// </param>
/// <returns>
/// The <see cref="QueryResultDisplay"/>.
/// </returns>
public QueryResultDisplay Search(long page, long itemsPerPage, string sortBy = "name", SortDirection sortDirection = SortDirection.Descending)
{
var cacheKey = PagedKeyCache.GetPagedQueryCacheKey<ICachedProductQuery>("Search", page, itemsPerPage, sortBy, sortDirection);
var pagedKeys = PagedKeyCache.GetPageByCacheKey(cacheKey);
return GetQueryResultDisplay(
pagedKeys ??
PagedKeyCache.CachePage(cacheKey, _productService.GetPagedKeys(page, itemsPerPage, sortBy, sortDirection)));
}
/// <summary>
/// Searches all products for a term
/// </summary>
/// <param name="term">
/// The term.
/// </param>
/// <param name="page">
/// The page.
/// </param>
/// <param name="itemsPerPage">
/// The items per page.
/// </param>
/// <param name="sortBy">
/// The sort by.
/// </param>
/// <param name="sortDirection">
/// The sort direction.
/// </param>
/// <returns>
/// The <see cref="QueryResultDisplay"/>.
/// </returns>
public QueryResultDisplay Search(string term, long page, long itemsPerPage, string sortBy = "name", SortDirection sortDirection = SortDirection.Ascending)
{
var cacheKey = PagedKeyCache.GetPagedQueryCacheKey<ICachedProductQuery>("Search", page, itemsPerPage, sortBy, sortDirection, new Dictionary<string, string> { { "term", term } });
var pagedKeys = PagedKeyCache.GetPageByCacheKey(cacheKey);
return GetQueryResultDisplay(
pagedKeys ??
PagedKeyCache.CachePage(cacheKey, _productService.GetPagedKeys(term, page, itemsPerPage, sortBy, sortDirection)));
}
/// <summary>
/// Gets products with that have an option with name.
/// </summary>
/// <param name="optionKey">
/// The option key.
/// </param>
/// <param name="page">
/// The page.
/// </param>
/// <param name="itemsPerPage">
/// The items per page.
/// </param>
/// <param name="sortBy">
/// The sort by.
/// </param>
/// <param name="sortDirection">
/// The sort direction.
/// </param>
/// <returns>
/// The <see cref="QueryResultDisplay"/>.
/// </returns>
public QueryResultDisplay GetProductsWithOption(
Guid optionKey,
long page,
long itemsPerPage,
string sortBy = "",
SortDirection sortDirection = SortDirection.Descending)
{
var cacheKey = PagedKeyCache.GetPagedQueryCacheKey<ICachedProductQuery>(
"GetProductsWithOption",
page,
itemsPerPage,
sortBy,
sortDirection,
new Dictionary<string, string> { { "optionKey", optionKey.ToString() } });
var pagedKeys = PagedKeyCache.GetPageByCacheKey(cacheKey);
return
this.GetQueryResultDisplay(
pagedKeys ??
PagedKeyCache.CachePage(
cacheKey,
_productService.GetProductsKeysWithOption(optionKey, page, itemsPerPage, sortBy, sortDirection)));
}
/// <summary>
/// Gets products with that have an option with name and a collection of choice names
/// </summary>
/// <param name="optionName">
/// The option name.
/// </param>
/// <param name="choiceNames">
/// The choice names.
/// </param>
/// <param name="page">
/// The page.
/// </param>
/// <param name="itemsPerPage">
/// The items per page.
/// </param>
/// <param name="sortBy">
/// The sort by.
/// </param>
/// <param name="sortDirection">
/// The sort direction.
/// </param>
/// <returns>
/// The <see cref="QueryResultDisplay"/>.
/// </returns>
public QueryResultDisplay GetProductsWithOption(
string optionName,
IEnumerable<string> choiceNames,
long page,
long itemsPerPage,
string sortBy = "name",
SortDirection sortDirection = SortDirection.Descending)
{
var choices = choiceNames as string[] ?? choiceNames.ToArray();
var args = new Dictionary<string, string>
{
{ "optionName", optionName },
{ "choiceNames", string.Join(string.Empty, choices.OrderBy(x => x)) }
};
var cacheKey = PagedKeyCache.GetPagedQueryCacheKey<ICachedProductQuery>(
"GetProductsWithOption",
page,
itemsPerPage,
sortBy,
sortDirection,
args);
var pagedKeys = PagedKeyCache.GetPageByCacheKey(cacheKey);
return
this.GetQueryResultDisplay(
pagedKeys ??
PagedKeyCache.CachePage(
cacheKey,
_productService.GetProductsKeysWithOption(optionName, choices, page, itemsPerPage, sortBy, sortDirection)));
}
/// <summary>
/// Gets products with that have an option with name.
/// </summary>
/// <param name="optionName">
/// The option name.
/// </param>
/// <param name="page">
/// The page.
/// </param>
/// <param name="itemsPerPage">
/// The items per page.
/// </param>
/// <param name="sortBy">
/// The sort by.
/// </param>
/// <param name="sortDirection">
/// The sort direction.
/// </param>
/// <returns>
/// The <see cref="QueryResultDisplay"/>.
/// </returns>
public QueryResultDisplay GetProductsWithOption(
string optionName,
long page,
long itemsPerPage,
string sortBy = "",
SortDirection sortDirection = SortDirection.Descending)
{
var cacheKey = PagedKeyCache.GetPagedQueryCacheKey<ICachedProductQuery>(
"GetProductsWithOption",
page,
itemsPerPage,
sortBy,
sortDirection,
new Dictionary<string, string> { { "optionName", optionName } });
var pagedKeys = PagedKeyCache.GetPageByCacheKey(cacheKey);
return
this.GetQueryResultDisplay(
pagedKeys
?? PagedKeyCache.CachePage(
cacheKey,
_productService.GetProductsKeysWithOption(optionName, page, itemsPerPage, sortBy, sortDirection)));
}
/// <summary>
/// Gets products with that have an options with name and choice name
/// </summary>
/// <param name="optionName">
/// The option name.
/// </param>
/// <param name="choiceName">
/// The choice name.
/// </param>
/// <param name="page">
/// The page.
/// </param>
/// <param name="itemsPerPage">
/// The items per page.
/// </param>
/// <param name="sortBy">
/// The sort by.
/// </param>
/// <param name="sortDirection">
/// The sort direction.
/// </param>
/// <returns>
/// The <see cref="QueryResultDisplay"/>.
/// </returns>
public QueryResultDisplay GetProductsWithOption(
string optionName,
string choiceName,
long page,
long itemsPerPage,
string sortBy = "",
SortDirection sortDirection = SortDirection.Descending)
{
var cacheKey = PagedKeyCache.GetPagedQueryCacheKey<ICachedProductQuery>(
"GetProductsWithOption",
page,
itemsPerPage,
sortBy,
sortDirection,
new Dictionary<string, string>
{
{ "optionName", optionName },
{ "choiceName", choiceName }
});
var pagedKeys = PagedKeyCache.GetPageByCacheKey(cacheKey);
return
this.GetQueryResultDisplay(
pagedKeys ??
PagedKeyCache.CachePage(
cacheKey,
_productService.GetProductsKeysWithOption(optionName, choiceName, page, itemsPerPage, sortBy, sortDirection)));
}
/// <summary>
/// Gets products with that have an options with names
/// </summary>
/// <param name="optionNames">
/// The option names.
/// </param>
/// <param name="page">
/// The page.
/// </param>
/// <param name="itemsPerPage">
/// The items per page.
/// </param>
/// <param name="sortBy">
/// The sort by.
/// </param>
/// <param name="sortDirection">
/// The sort direction.
/// </param>
/// <returns>
/// The <see cref="QueryResultDisplay"/>.
/// </returns>
public QueryResultDisplay GetProductsWithOption(
IEnumerable<string> optionNames,
long page,
long itemsPerPage,
string sortBy = "",
SortDirection sortDirection = SortDirection.Descending)
{
var names = optionNames as string[] ?? optionNames.ToArray();
var cacheKey = PagedKeyCache.GetPagedQueryCacheKey<ICachedProductQuery>(
"GetProductsWithOption",
page,
itemsPerPage,
sortBy,
sortDirection,
new Dictionary<string, string>
{
{ "optionNames", string.Join(string.Empty, names.OrderBy(x => x)) }
});
var pagedKeys = PagedKeyCache.GetPageByCacheKey(cacheKey);
return
this.GetQueryResultDisplay(
pagedKeys ??
PagedKeyCache.CachePage(
cacheKey,
_productService.GetProductsKeysWithOption(names, page, itemsPerPage, sortBy, sortDirection)));
}
/// <summary>
/// Get products that have prices within a price range
/// </summary>
/// <param name="min">
/// The min.
/// </param>
/// <param name="max">
/// The max.
/// </param>
/// <param name="page">
/// The page.
/// </param>
/// <param name="itemsPerPage">
/// The items per page.
/// </param>
/// <param name="sortBy">
/// The sort by.
/// </param>
/// <param name="sortDirection">
/// The sort direction.
/// </param>
/// <returns>
/// The <see cref="QueryResultDisplay"/>.
/// </returns>
public QueryResultDisplay GetProductsInPriceRange(
decimal min,
decimal max,
long page,
long itemsPerPage,
string sortBy = "",
SortDirection sortDirection = SortDirection.Descending)
{
var cacheKey = PagedKeyCache.GetPagedQueryCacheKey<ICachedProductQuery>(
"GetProductsInPriceRange",
page,
itemsPerPage,
sortBy,
sortDirection,
new Dictionary<string, string>
{
{ "min", min.ToString(CultureInfo.InvariantCulture) },
{ "max", max.ToString(CultureInfo.InvariantCulture) }
});
var pagedKeys = PagedKeyCache.GetPageByCacheKey(cacheKey);
return
this.GetQueryResultDisplay(
pagedKeys ??
PagedKeyCache.CachePage(
cacheKey,
_productService.GetProductsKeysInPriceRange(min, max, page, itemsPerPage, sortBy, sortDirection)));
}
/// <summary>
/// Get products that have prices within a price range allowing for a tax modifier
/// </summary>
/// <param name="min">
/// The min.
/// </param>
/// <param name="max">
/// The max.
/// </param>
/// <param name="taxModifier">
/// The tax modifier.
/// </param>
/// <param name="page">
/// The page.
/// </param>
/// <param name="itemsPerPage">
/// The items per page.
/// </param>
/// <param name="sortBy">
/// The sort by.
/// </param>
/// <param name="sortDirection">
/// The sort direction.
/// </param>
/// <returns>
/// The <see cref="QueryResultDisplay"/>.
/// </returns>
public QueryResultDisplay GetProductsInPriceRange(
decimal min,
decimal max,
decimal taxModifier,
long page,
long itemsPerPage,
string sortBy = "",
SortDirection sortDirection = SortDirection.Descending)
{
var cacheKey = PagedKeyCache.GetPagedQueryCacheKey<ICachedProductQuery>(
"GetProductsInPriceRange",
page,
itemsPerPage,
sortBy,
sortDirection,
new Dictionary<string, string>
{
{ "min", min.ToString(CultureInfo.InvariantCulture) },
{ "max", max.ToString(CultureInfo.InvariantCulture) },
{ "taxModifier", taxModifier.ToString(CultureInfo.InvariantCulture) }
});
var pagedKeys = PagedKeyCache.GetPageByCacheKey(cacheKey);
return
this.GetQueryResultDisplay(
pagedKeys ??
PagedKeyCache.CachePage(
cacheKey,
_productService.GetProductsKeysInPriceRange(min, max, taxModifier, page, itemsPerPage, sortBy, sortDirection)));
}
/// <summary>
/// The get products by barcode.
/// </summary>
/// <param name="barcode">
/// The barcode.
/// </param>
/// <param name="page">
/// The page.
/// </param>
/// <param name="itemsPerPage">
/// The items per page.
/// </param>
/// <param name="sortBy">
/// The sort by.
/// </param>
/// <param name="sortDirection">
/// The sort direction.
/// </param>
/// <returns>
/// The <see cref="QueryResultDisplay"/>.
/// </returns>
public QueryResultDisplay GetProductsByBarcode(
string barcode,
long page,
long itemsPerPage,
string sortBy = "",
SortDirection sortDirection = SortDirection.Descending)
{
var cacheKey = PagedKeyCache.GetPagedQueryCacheKey<ICachedProductQuery>(
"GetProductsByBarcode",
page,
itemsPerPage,
sortBy,
sortDirection,
new Dictionary<string, string> { { "barcode", barcode } });
var pagedKeys = PagedKeyCache.GetPageByCacheKey(cacheKey);
return
this.GetQueryResultDisplay(
pagedKeys ??
PagedKeyCache.CachePage(
cacheKey,
_productService.GetProductsByBarcode(barcode, page, itemsPerPage, sortBy, sortDirection)));
}
/// <summary>
/// The get products by barcode.
/// </summary>
/// <param name="barcodes">
/// The barcodes.
/// </param>
/// <param name="page">
/// The page.
/// </param>
/// <param name="itemsPerPage">
/// The items per page.
/// </param>
/// <param name="sortBy">
/// The sort by.
/// </param>
/// <param name="sortDirection">
/// The sort direction.
/// </param>
/// <returns>
/// The <see cref="QueryResultDisplay"/>.
/// </returns>
public QueryResultDisplay GetProductsByBarcode(
IEnumerable<string> barcodes,
long page,
long itemsPerPage,
string sortBy = "",
SortDirection sortDirection = SortDirection.Descending)
{
var barcodesArray = barcodes as string[] ?? barcodes.ToArray();
var cacheKey = PagedKeyCache.GetPagedQueryCacheKey<ICachedProductQuery>(
"GetProductsByBarcode",
page,
itemsPerPage,
sortBy,
sortDirection,
new Dictionary<string, string>
{
{ "barcodes", string.Join(string.Empty, barcodesArray.OrderBy(x => x)) }
});
var pagedKeys = PagedKeyCache.GetPageByCacheKey(cacheKey);
return
this.GetQueryResultDisplay(
pagedKeys ??
PagedKeyCache.CachePage(
cacheKey,
_productService.GetProductsByBarcode(barcodesArray, page, itemsPerPage, sortBy, sortDirection)));
}
/// <summary>
/// Gets products by manufacturer.
/// </summary>
/// <param name="manufacturer">
/// The manufacturer.
/// </param>
/// <param name="page">
/// The page.
/// </param>
/// <param name="itemsPerPage">
/// The items per page.
/// </param>
/// <param name="sortBy">
/// The sort by.
/// </param>
/// <param name="sortDirection">
/// The sort direction.
/// </param>
/// <returns>
/// The <see cref="QueryResultDisplay"/>.
/// </returns>
public QueryResultDisplay GetProductsByManufacturer(
string manufacturer,
long page,
long itemsPerPage,
string sortBy = "",
SortDirection sortDirection = SortDirection.Descending)
{
var cacheKey = PagedKeyCache.GetPagedQueryCacheKey<ICachedProductQuery>(
"GetProductsByManufacturer",
page,
itemsPerPage,
sortBy,
sortDirection,
new Dictionary<string, string> { { "manufacturer", manufacturer} });
var pagedKeys = PagedKeyCache.GetPageByCacheKey(cacheKey);
return
this.GetQueryResultDisplay(
pagedKeys ??
PagedKeyCache.CachePage(
cacheKey,
_productService.GetProductsKeysByManufacturer(manufacturer, page, itemsPerPage, sortBy, sortDirection)));
}
/// <summary>
/// Get products for a list of manufacturers.
/// </summary>
/// <param name="manufacturer">
/// The manufacturer.
/// </param>
/// <param name="page">
/// The page.
/// </param>
/// <param name="itemsPerPage">
/// The items per page.
/// </param>
/// <param name="sortBy">
/// The sort by.
/// </param>
/// <param name="sortDirection">
/// The sort direction.
/// </param>
/// <returns>
/// The <see cref="QueryResultDisplay"/>.
/// </returns>
public QueryResultDisplay GetProductsByManufacturer(
IEnumerable<string> manufacturer,
long page,
long itemsPerPage,
string sortBy = "",
SortDirection sortDirection = SortDirection.Descending)
{
var manufacturerArray = manufacturer as string[] ?? manufacturer.ToArray();
var cacheKey = PagedKeyCache.GetPagedQueryCacheKey<ICachedProductQuery>(
"GetProductsByManufacturer",
page,
itemsPerPage,
sortBy,
sortDirection,
new Dictionary<string, string> { { "manufacturer", string.Join(string.Empty, manufacturerArray.OrderBy(x => x)) } });
var pagedKeys = PagedKeyCache.GetPageByCacheKey(cacheKey);
return
this.GetQueryResultDisplay(
pagedKeys ??
PagedKeyCache.CachePage(
cacheKey,
_productService.GetProductsKeysByManufacturer(manufacturerArray, page, itemsPerPage, sortBy, sortDirection)));
}
/// <summary>
/// Gets products that are in stock or do not track inventory
/// </summary>
/// <param name="page">
/// The page.
/// </param>
/// <param name="itemsPerPage">
/// The items per page.
/// </param>
/// <param name="sortBy">
/// The sort by.
/// </param>
/// <param name="sortDirection">
/// The sort direction.
/// </param>
/// <param name="includeAllowOutOfStockPurchase">
/// The include allow out of stock purchase.
/// </param>
/// <returns>
/// The <see cref="QueryResultDisplay"/>.
/// </returns>
public QueryResultDisplay GetProductsInStock(
long page,
long itemsPerPage,
string sortBy = "",
SortDirection sortDirection = SortDirection.Descending,
bool includeAllowOutOfStockPurchase = false)
{
var cacheKey = PagedKeyCache.GetPagedQueryCacheKey<ICachedProductQuery>(
"GetProductsInStock",
page,
itemsPerPage,
sortBy,
sortDirection,
new Dictionary<string, string>
{
{
"includeAllowOutOfStockPurchase",
includeAllowOutOfStockPurchase.ToString()
}
});
var pagedKeys = PagedKeyCache.GetPageByCacheKey(cacheKey);
return
this.GetQueryResultDisplay(
pagedKeys ??
PagedKeyCache.CachePage(
cacheKey,
_productService.GetProductsKeysInStock(page, itemsPerPage, sortBy, sortDirection)));
}
/// <summary>
/// Gets a paged collection of entity keys for a collection.
/// </summary>
/// <param name="collectionKey">
/// The collection key.
/// </param>
/// <param name="page">
/// The page.
/// </param>
/// <param name="itemsPerPage">
/// The items per page.
/// </param>
/// <param name="sortBy">
/// The sort by.
/// </param>
/// <param name="sortDirection">
/// The sort direction.
/// </param>
/// <returns>
/// The <see cref="Page{Guid}"/>.
/// </returns>
protected Page<Guid> GetCollectionPagedKeys(
Guid collectionKey,
long page,
long itemsPerPage,
string sortBy = "",
SortDirection sortDirection = SortDirection.Ascending,
bool includeUnavailable = false)
{
var args = new Dictionary<string, string>
{
{ "collectionKey", collectionKey.ToString() }
};
var cacheKey = PagedKeyCache.GetPagedQueryCacheKey<CachedQueryableCollectionQueryBase<IProduct, ProductDisplay>>(
"GetFromCollection",
page,
itemsPerPage,
sortBy,
sortDirection,
includeUnavailable,
args);
var pagedKeys = PagedKeyCache.GetPageByCacheKey(cacheKey);
if (pagedKeys != null) return pagedKeys;
var provider = this.GetEntityCollectionProvider(collectionKey);
return PagedKeyCache.CachePage(
cacheKey,
_productService.GetPagedKeys(page, itemsPerPage, sortBy, sortDirection, includeUnavailable));
}
/// <summary>
/// Gets products that are marked on sale
/// </summary>
/// <param name="page">
/// The page.
/// </param>
/// <param name="itemsPerPage">
/// The items per page.
/// </param>
/// <param name="sortBy">
/// The sort by.
/// </param>
/// <param name="sortDirection">
/// The sort direction.
/// </param>
/// <returns>
/// The <see cref="QueryResultDisplay"/>.
/// </returns>
public QueryResultDisplay GetProductsOnSale(
long page,
long itemsPerPage,
string sortBy = "",
SortDirection sortDirection = SortDirection.Descending)
{
var cacheKey = PagedKeyCache.GetPagedQueryCacheKey<ICachedProductQuery>(
"GetProductsOnSale",
page,
itemsPerPage,
sortBy,
sortDirection);
var pagedKeys = PagedKeyCache.GetPageByCacheKey(cacheKey);
return
this.GetQueryResultDisplay(
pagedKeys ??
PagedKeyCache.CachePage(
cacheKey,
_productService.GetProductsKeysOnSale(page, itemsPerPage, sortBy, sortDirection)));
}
/// <summary>
/// Gets the <see cref="ProductVariantDisplay"/> for a product
/// </summary>
/// <param name="productKey">
/// The product key.
/// </param>
/// <returns>
/// The <see cref="IEnumerable{ProductVariantDisplay}"/>.
/// </returns>
public IEnumerable<ProductVariantDisplay> GetVariantsByProduct(Guid productKey)
{
var criteria = SearchProvider.CreateSearchCriteria();
criteria.Field(KeyFieldInIndex, productKey.ToString()).Not().Field("master", "True");
var results = SearchProvider.Search(criteria);
return results.Select(x => this.ModifyData(x.ToProductVariantDisplay()));
}
/// <summary>
/// Re-indexes the <see cref="IProduct"/>
/// </summary>
/// <param name="entity">
/// The entity.
/// </param>
internal override void ReindexEntity(IProduct entity)
{
((ProductIndexer)IndexProvider).AddProductToIndex(entity);
}
/// <summary>
/// Re-indexes entity document via Examine.
/// </summary>
/// <param name="entity">
/// The entity.
/// </param>
internal void ReindexEntity(IProductVariant entity)
{
IndexProvider.ReIndexNode(entity.SerializeToXml().Root, IndexTypes.ProductVariant);
}
/// <summary>
/// The modify data.
/// </summary>
/// <param name="data">
/// The data.
/// </param>
/// <typeparam name="T">
/// The type of data to be modified
/// </typeparam>
/// <returns>
/// The <see cref="T"/>.
/// </returns>
internal T ModifyData<T>(T data)
where T : class, IProductVariantDataModifierData
{
if (!EnableDataModifiers) return data;
var attempt = _dataModifier.Value.Modify(data);
if (!attempt.Success) return data;
var modified = attempt.Result as T;
return modified ?? data;
}
/// <summary>
/// Gets a display object from the Examine cache or falls back the the database if not found
/// </summary>
/// <param name="key">
/// The key.
/// </param>
/// <returns>
/// The <see cref="ProductDisplay"/>.
/// </returns>
protected override ProductDisplay GetDisplayObject(Guid key)
{
var criteria = SearchProvider.CreateSearchCriteria();
criteria.Field(KeyFieldInIndex, key.ToString());
var allProducts = SearchProvider.Search(criteria).ToArray();
var defaultProduct = allProducts.FirstOrDefault(x => x.Fields["master"] == "True");
if (defaultProduct != null)
{
// Get the variant
var display = this.ModifyData(defaultProduct.ToProductDisplay(GetVariantsByProduct(allProducts), this._conversionType));
if (display != null)
{
display.EnsureValueConversion(this._conversionType);
return display;
}
}
var entity = Service.GetByKey(key);
if (entity == null) return null;
ReindexEntity(entity);
return this.ModifyData(entity.ToProductDisplay(this._conversionType));
}
/// <summary>
/// Maps a <see cref="SearchResult"/> to <see cref="ProductDisplay"/>
/// </summary>
/// <param name="result">
/// The result.
/// </param>
/// <returns>
/// The <see cref="ProductDisplay"/>.
/// </returns>
protected override ProductDisplay PerformMapSearchResultToDisplayObject(SearchResult result)
{
return this.ModifyData(result.ToProductDisplay(GetVariantsByProduct, this._conversionType));
}
/// <summary>
/// Gets the <see cref="ProductVariantDisplay"/> for a product
/// </summary>
/// <param name="searchResults"></param>
/// <returns></returns>
private IEnumerable<ProductVariantDisplay> GetVariantsByProduct(IEnumerable<SearchResult> searchResults)
{
return searchResults.Where(x => x.Fields["master"] != "True").Select(x => ModifyData(x.ToProductVariantDisplay()));
}
/// <summary>
/// Gets the virtual content.
/// </summary>
/// <param name="key">
/// The key.
/// </param>
/// <returns>
/// The <see cref="IProductContent"/>.
/// </returns>
private IProductContent GetProductContent(Guid key)
{
var display = GetByKey(key);
return display == null ? null :
display.AsProductContent(_productContentFactory.Value);
}
/// <summary>
/// Gest the <see cref="IProductContent"/> by sku.
/// </summary>
/// <param name="sku">
/// The sku.
/// </param>
/// <returns>
/// The <see cref="IProductContent"/>.
/// </returns>
private IProductContent GetProductContentBySku(string sku)
{
var display = GetBySku(sku);
return display == null ? null :
display.AsProductContent(_productContentFactory.Value);
}
/// <summary>
/// Gets the <see cref="IProductContent"/> by slug.
/// </summary>
/// <param name="slug">
/// The slug.
/// </param>
/// <returns>
/// The <see cref="IProductContent"/>.
/// </returns>
private IProductContent GetProductContentBySlug(string slug)
{
var display = GetBySlug(slug);
return display == null ? null :
display.AsProductContent(_productContentFactory.Value);
}
/// <summary>
/// Initializes the lazy
/// </summary>
private void Initialize()
{
if (MerchelloContext.HasCurrent)
_dataModifier = new Lazy<IDataModifierChain<IProductVariantDataModifierData>>(() => new ProductVariantDataModifierChain(MerchelloContext.Current));
DataModifierChanged += OnDataModifierChanged;
}
private void OnDataModifierChanged(CachedProductQuery sender, bool e)
{
_cache.ModifiedVersion = e;
}
}
}
| 35.947095
| 212
| 0.542089
|
[
"MIT"
] |
HiteshMah-Jan/Merchello
|
src/Merchello.Web/Search/CachedProductQuery.cs
| 69,308
|
C#
|
using DungeonTools.Save.File;
using System;
using System.IO;
using System.Threading.Tasks;
namespace MCDSaveEdit
{
public static class FileProcessHelper
{
public static async ValueTask ProcessFile(FileInfo file, bool overwrite)
{
if (!file.Exists)
{
EventLogger.logError($"File \"{file.FullName}\" could not be found and has been skipped.");
return;
}
using FileStream inputStream = file.OpenRead();
bool encrypted = SaveFileHandler.IsFileEncrypted(inputStream);
Stream? processed = encrypted ? await Decrypt(inputStream) : await Encrypt(inputStream);
if (processed == null)
{
EventLogger.logError($"Content of file \"{file.Name}\" could not be converted to a supported format.");
return;
}
processed.Seek(0, SeekOrigin.Begin);
string outputFile = GetOutputFilePath(file, encrypted, overwrite);
using FileStream outputStream = File.Open(outputFile, FileMode.Create, FileAccess.Write);
await processed.CopyToAsync(outputStream);
}
public static async ValueTask<Stream?> Decrypt(Stream data)
{
Stream decrypted = await AesEncryptionProvider.DecryptAsync(data);
Stream result = SaveFileHandler.RemoveTrailingZeroes(decrypted);
result.Seek(0, SeekOrigin.Begin);
return result;
}
public static async ValueTask<Stream?> Encrypt(Stream data)
{
using Stream encrypted = await AesEncryptionProvider.EncryptAsync(data);
Stream result = SaveFileHandler.PrependMagicToEncrypted(encrypted);
result.Seek(0, SeekOrigin.Begin);
return result;
}
private static string GetOutputFilePath(FileInfo fileInfo, bool isEncrypted, bool overwrite)
{
string targetExtension = fileInfo.Extension.ToUpperInvariant() switch
{
"" => isEncrypted ? ".json" : "", // Special case for Switch which has no file extension
_ => isEncrypted ? ".json" : ".dat",
};
string idealFileName = $"{Path.GetFileNameWithoutExtension(fileInfo.Name)}{targetExtension}";
if (string.Equals(fileInfo.Name, idealFileName, StringComparison.CurrentCultureIgnoreCase))
{
idealFileName = $"{Path.GetFileNameWithoutExtension(idealFileName)}_{(isEncrypted ? "Decrypted" : "Encrypted")}{targetExtension}";
}
string outFileName = Path.Combine(fileInfo.DirectoryName, idealFileName);
if (overwrite || !File.Exists(outFileName))
{
return outFileName;
}
int fileNumber = 1;
while (File.Exists(outFileName))
{
outFileName = $"{outFileName.Substring(outFileName.Length - targetExtension.Length)}_{fileNumber++}{targetExtension}";
}
return outFileName;
}
}
}
| 37.361446
| 146
| 0.604966
|
[
"MIT"
] |
ACKREIK/MCDSaveEdit
|
MCDSaveEdit/Logic/FileProcessHelper.cs
| 3,103
|
C#
|
// Copyright (c) 2007-2018 ppy Pty Ltd <contact@ppy.sh>.
// Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu-framework/master/LICENCE
namespace osu.Framework.Configuration
{
public interface IConfigManager
{
/// <summary>
/// Loads this config.
/// </summary>
void Load();
/// <summary>
/// Saves this config.
/// </summary>
/// <returns>Whether the operation succeeded.</returns>
bool Save();
}
}
| 26.5
| 103
| 0.566038
|
[
"MIT"
] |
AlFasGD/osu-framework
|
osu.Framework/Configuration/IConfigManager.cs
| 513
|
C#
|
using ArcGIS.Core.CIM;
using ArcGIS.Core.Data;
using ArcGIS.Core.Geometry;
using ArcGIS.Desktop.Catalog;
using ArcGIS.Desktop.Core;
using ArcGIS.Desktop.Editing;
using ArcGIS.Desktop.Extensions;
using ArcGIS.Desktop.Framework;
using ArcGIS.Desktop.Framework.Contracts;
using ArcGIS.Desktop.Framework.Dialogs;
using ArcGIS.Desktop.Framework.Threading.Tasks;
using ArcGIS.Desktop.Layouts;
using ArcGIS.Desktop.Mapping;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace GraphicElementSymbolPicker
{
internal class LastToolActive : CheckBox
{
protected override void OnClick()
{
try
{
Module1.Current.LayoutOptions.KeepLastToolActive = !Module1.Current.LayoutOptions.KeepLastToolActive;
}
catch (Exception e) { ArcGIS.Desktop.Framework.Utilities.EventLog.Write(ArcGIS.Desktop.Framework.Utilities.EventLog.EventType.Warning, "Save ApplicationSetttings.LastToolActive: " + e.Message); }
}
protected override void OnUpdate()
{
IsChecked = Module1.Current.LayoutOptions.KeepLastToolActive;
}
}
}
| 30.052632
| 201
| 0.767951
|
[
"Apache-2.0"
] |
Dithn/arcgis-pro-sdk-community-samples
|
Map-Authoring/GraphicElementSymbolPicker/LastToolActive.cs
| 1,144
|
C#
|
using System;
using System.Collections.Generic;
using System.Windows;
using System.Windows.Controls;
namespace FlexibleLayout.Wpf.Layout
{
public abstract class FlexLayout : Panel
{
/**
* Dependency and attached Properties
*/
/// <summary>
/// Specify if control needs to fill the available space
/// </summary>
public static readonly DependencyProperty FlexProperty = DependencyProperty.RegisterAttached(
"Flex",
typeof(bool),
typeof(FlexLayout),
new FrameworkPropertyMetadata(false, FrameworkPropertyMetadataOptions.AffectsRender)
);
public static void SetFlex(UIElement element, bool value)
{
element.SetValue(FlexProperty, value);
}
public static bool GetFlex(UIElement element)
{
return (bool)element.GetValue(FlexProperty);
}
/// <summary>
/// Controls the amount of space the control gets relative to other flex controls
/// </summary>
public static readonly DependencyProperty GrowProperty = DependencyProperty.RegisterAttached(
"Grow",
typeof(int),
typeof(FlexLayout),
new FrameworkPropertyMetadata(1, FrameworkPropertyMetadataOptions.AffectsRender)
);
public static void SetGrow(UIElement element, int value)
{
element.SetValue(GrowProperty, value);
}
public static int GetGrow(UIElement element)
{
return (int)element.GetValue(GrowProperty);
}
/// <summary>
/// Set positioning method relative to parent
/// </summary>
public static readonly DependencyProperty PositionProperty = DependencyProperty.RegisterAttached(
"Position",
typeof(Position),
typeof(FlexLayout),
new FrameworkPropertyMetadata(Position.Relative, FrameworkPropertyMetadataOptions.AffectsRender)
);
public static void SetPosition(UIElement element, Position value)
{
element.SetValue(PositionProperty, value);
}
public static Position GetPosition(UIElement element)
{
return (Position)element.GetValue(PositionProperty);
}
/// <summary>
/// Specify spacing between child controls
/// </summary>
public static readonly DependencyProperty SpacingProperty = DependencyProperty.Register(
"Spacing",
typeof(int),
typeof(FlexLayout),
new FrameworkPropertyMetadata(0, FrameworkPropertyMetadataOptions.AffectsRender)
);
public int Spacing
{
get => (int)GetValue(SpacingProperty);
set => SetValue(SpacingProperty, value);
}
/// <summary>
/// Specify to skip measure on child control. Only recommended for childs that have no children themselfs.
/// This could improve performance when measure takes a long time while isn't really used in Flex controls.
/// </summary>
public static readonly DependencyProperty SkipMeasureProperty = DependencyProperty.RegisterAttached(
"SkipMeasure",
typeof(bool),
typeof(FlexLayout),
new FrameworkPropertyMetadata(false, FrameworkPropertyMetadataOptions.AffectsRender)
);
public static void SetSkipMeasure(UIElement element, bool value)
{
element.SetValue(SkipMeasureProperty, value);
}
public static bool GetSkipMeasure(UIElement element)
{
return (bool)element.GetValue(SkipMeasureProperty);
}
protected virtual List<IChildAdapter> ChildAdapters { get => throw new NotImplementedException(); }
/**
* Methods
*/
public void Add(UIElement widget)
{
Children.Add(widget);
}
/// <summary>
/// Measures the desired space for the layout
/// </summary>
/// <param name="availableSize"></param>
/// <returns>Desired space</returns>
protected FlexSize MeasureOverride(FlexSize availableSize)
{
(var availableContentSize, var totalSpacing) = CalculateAvailableContentSize(availableSize);
foreach (var adapter in ChildAdapters)
{
if (GetSkipMeasure(adapter.Child))
{
continue;
}
adapter.Measure(availableContentSize);
}
// calculate total width and height from children
var desiredContentSize = CalculateDesiredContentSize(availableContentSize);
var totalLongitudinalSize = desiredContentSize.Longitudinal + totalSpacing;
(var flexLongitunal, var flexTotalGrowCount, var flex) = CalculateFlexLongitudinal(availableContentSize.Longitudinal, totalSpacing);
if (flex)
{
foreach (var adapter in ChildAdapters)
{
var desiredLongitudinal = adapter.DesiredSize.Longitudinal;
if (GetPosition(adapter.Child) == Position.Absolute || GetSkipMeasure(adapter.Child))
{
continue;
}
var childIsFlex = GetFlex(adapter.Child);
if (childIsFlex)
{
var childFlexGrow = GetGrow(adapter.Child);
if (flexTotalGrowCount > 0)
desiredLongitudinal = flexLongitunal * (childFlexGrow / (double)flexTotalGrowCount);
}
var availableChildSize = new FlexSize(desiredLongitudinal, availableContentSize.Lateral);
adapter.Measure(availableChildSize);
}
}
else
{
var scaleFactor = 1.0;
if (!double.IsInfinity(availableContentSize.Longitudinal) && !double.IsNaN(availableContentSize.Longitudinal))
{
scaleFactor = desiredContentSize.Longitudinal > 0 ? availableContentSize.Longitudinal / desiredContentSize.Longitudinal : 0;
}
foreach (var adapter in ChildAdapters)
{
if (GetPosition(adapter.Child) == Position.Absolute || GetSkipMeasure(adapter.Child))
{
continue;
}
var childLongitudinal = 0d;
if (scaleFactor > 0 && adapter.DesiredSize.Longitudinal > 0)
{
childLongitudinal = adapter.DesiredSize.Longitudinal * scaleFactor;
}
var availableChildSize = new FlexSize(childLongitudinal, availableContentSize.Lateral);
adapter.Measure(availableChildSize);
}
}
return new FlexSize(totalLongitudinalSize, desiredContentSize.Lateral);
}
protected (double flexLongitudinal, int flexTotalGrowCount, bool flex) CalculateFlexLongitudinal(double finalLongitudinal, double spacing)
{
var flex = false;
int flexTotalGrowCount = 0;
foreach (var adapter in ChildAdapters)
{
if (GetPosition(adapter.Child) == Position.Absolute)
{
continue;
}
if (!GetFlex(adapter.Child))
{
if (finalLongitudinal > adapter.DesiredSize.Longitudinal)
finalLongitudinal -= adapter.DesiredSize.Longitudinal;
else
finalLongitudinal = 0;
continue;
}
flex = true;
flexTotalGrowCount += GetGrow(adapter.Child);
}
return (finalLongitudinal, flexTotalGrowCount, flex);
}
private (FlexSize availableContentSize, int totalSpacing) CalculateAvailableContentSize(FlexSize availableSize)
{
var availableContentSize = new FlexSize(longitudinal: 0d, lateral: availableSize.Lateral);
if (InternalChildren.Count <= 1)
return (availableSize, 0);
var totalSpacing = (InternalChildren.Count - 1) * Spacing;
if (availableSize.Longitudinal > totalSpacing)
availableContentSize.Longitudinal = availableSize.Longitudinal - totalSpacing;
return (availableContentSize, totalSpacing);
}
/// <summary>
/// Calculate content size
/// </summary>
private FlexSize CalculateDesiredContentSize(FlexSize availableContentSize)
{
var desiredSize = new FlexSize(0, 0);
// calculate total width and height from children
foreach (var adapter in ChildAdapters)
{
desiredSize.Longitudinal += adapter.DesiredSize.Longitudinal;
if (adapter.DesiredSize.Lateral > desiredSize.Lateral)
desiredSize.Lateral = adapter.DesiredSize.Lateral;
}
// Limit to available size
if (desiredSize.Longitudinal > availableContentSize.Longitudinal)
desiredSize.Longitudinal = availableContentSize.Longitudinal;
if (desiredSize.Lateral > availableContentSize.Lateral)
desiredSize.Lateral = availableContentSize.Lateral;
return desiredSize;
}
/// <summary>
/// Arranges children based on space assigned to this layout
/// </summary>
/// <param name="finalSize"></param>
/// <returns></returns>
protected virtual FlexSize ArrangeOverride(FlexSize finalSize)
{
double l = 0;
(var availableContentSize, var totalSpacing) = CalculateAvailableContentSize(finalSize);
var desiredContentSize = CalculateDesiredContentSize(availableContentSize);
(var flexLongitudinal, var flexTotalGrowCount, var flex) = CalculateFlexLongitudinal(availableContentSize.Longitudinal, totalSpacing);
if (flex)
{
foreach (var adapter in ChildAdapters)
{
if (GetPosition(adapter.Child) == Position.Absolute)
{
adapter.Arrange(availableContentSize, new FlexSize(0, 0));
continue;
}
var childLongitudinal = adapter.DesiredSize.Longitudinal;
var childIsFlex = GetFlex(adapter.Child);
if (childIsFlex)
{
var childFlexGrow = GetGrow(adapter.Child);
if (flexTotalGrowCount > 0)
childLongitudinal = flexLongitudinal * (childFlexGrow / (double)flexTotalGrowCount);
}
var availableChildSize = new FlexSize(childLongitudinal, availableContentSize.Lateral);
adapter.Arrange(availableChildSize, new FlexSize(l, 0));
l += childLongitudinal + Spacing;
}
}
else
{
var scaleFactor = desiredContentSize.Longitudinal > 0 ? availableContentSize.Longitudinal / desiredContentSize.Longitudinal : 0;
foreach (var adapter in ChildAdapters)
{
if (GetPosition(adapter.Child) == Position.Absolute)
{
adapter.Arrange(availableContentSize, new FlexSize(0d, 0d));
continue;
}
var childLongitudinal = adapter.DesiredSize.Longitudinal * scaleFactor;
var availableSize = new FlexSize(childLongitudinal, availableContentSize.Lateral);
adapter.Arrange(availableSize, new FlexSize(l, 0d));
l += childLongitudinal + Spacing;
}
}
return finalSize;
}
}
}
| 38.034056
| 146
| 0.570615
|
[
"MIT"
] |
SimonEverts/flex-layout-wpf
|
src/FlexLayout.Wpf/Layout/FlexLayout.cs
| 12,287
|
C#
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.InteropServices;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Interop;
using System.Windows.Media;
using System.Windows.Threading;
using HandyControl.Data;
using HandyControl.Expression.Drawing;
using HandyControl.Tools;
using HandyControl.Tools.Interop;
namespace HandyControl.Controls
{
public class GlowWindow : Window
{
internal int DeferGlowChangesCount;
private readonly GlowEdge[] _glowEdges = new GlowEdge[4];
private DispatcherTimer _makeGlowVisibleTimer;
private bool _isGlowVisible;
private bool _useLogicalSizeForRestore;
private bool _updatingZOrder;
private Rect _logicalSizeForRestore = Rect.Empty;
public static readonly DependencyProperty ActiveGlowColorProperty = DependencyProperty.Register(
"ActiveGlowColor", typeof(Color), typeof(GlowWindow), new PropertyMetadata(default(Color), OnGlowColorChanged));
public Color ActiveGlowColor
{
get => (Color)GetValue(ActiveGlowColorProperty);
set => SetValue(ActiveGlowColorProperty, value);
}
public static readonly DependencyProperty InactiveGlowColorProperty = DependencyProperty.Register(
"InactiveGlowColor", typeof(Color), typeof(GlowWindow), new PropertyMetadata(default(Color), OnGlowColorChanged));
public Color InactiveGlowColor
{
get => (Color)GetValue(InactiveGlowColorProperty);
set => SetValue(InactiveGlowColorProperty, value);
}
static GlowWindow()
{
StyleProperty.OverrideMetadata(typeof(GlowWindow), new FrameworkPropertyMetadata(Application.Current.FindResource(ResourceToken.WindowGlow)));
ResizeModeProperty.OverrideMetadata(typeof(GlowWindow), new FrameworkPropertyMetadata(OnResizeModeChanged));
}
#region internal
internal void EndDeferGlowChanges()
{
foreach (var current in LoadedGlowWindows) current.CommitChanges();
}
#endregion
#region protected
protected virtual bool ShouldShowGlow
{
get
{
var handle = this.GetHandle();
return InteropMethods.IsWindowVisible(handle) && !InteropMethods.IsIconic(handle) &&
!InteropMethods.IsZoomed(handle) && ResizeMode != ResizeMode.NoResize;
}
}
protected virtual IntPtr HwndSourceHook(IntPtr hWnd, int msg, IntPtr wParam, IntPtr lParam, ref bool handled)
{
if (msg <= InteropValues.WM_WINDOWPOSCHANGED)
{
if (msg == InteropValues.WM_ACTIVATE)
{
return IntPtr.Zero;
}
if (msg != InteropValues.WM_QUIT)
{
switch (msg)
{
case InteropValues.WM_WINDOWPOSCHANGING:
WmWindowPosChanging(lParam);
return IntPtr.Zero;
case InteropValues.WM_WINDOWPOSCHANGED:
WmWindowPosChanged(lParam);
return IntPtr.Zero;
default:
return IntPtr.Zero;
}
}
}
else
{
if (msg <= InteropValues.WM_NCRBUTTONDBLCLK)
{
switch (msg)
{
case InteropValues.WM_SETICON:
break;
case InteropValues.WM_NCCREATE:
case InteropValues.WM_NCDESTROY:
return IntPtr.Zero;
case InteropValues.WM_NCACTIVATE:
handled = true;
return WmNcActivate(hWnd, wParam);
default:
switch (msg)
{
case InteropValues.WM_NCRBUTTONDOWN:
case InteropValues.WM_NCRBUTTONUP:
case InteropValues.WM_NCRBUTTONDBLCLK:
handled = true;
return IntPtr.Zero;
default:
return IntPtr.Zero;
}
}
}
else
{
switch (msg)
{
case InteropValues.WM_NCUAHDRAWCAPTION:
case InteropValues.WM_NCUAHDRAWFRAME:
handled = true;
return IntPtr.Zero;
default:
if (msg != InteropValues.WM_SYSCOMMAND) return IntPtr.Zero;
WmSysCommand(hWnd, wParam);
return IntPtr.Zero;
}
}
}
handled = true;
return CallDefWindowProcWithoutVisibleStyle(hWnd, msg, wParam, lParam);
}
protected override void OnActivated(EventArgs e)
{
UpdateGlowActiveState();
base.OnActivated(e);
}
protected override void OnDeactivated(EventArgs e)
{
UpdateGlowActiveState();
base.OnDeactivated(e);
}
protected override void OnClosed(EventArgs e)
{
StopTimer();
DestroyGlowWindows();
base.OnClosed(e);
}
protected override void OnSourceInitialized(EventArgs e)
{
var hwndSource = HwndSource.FromHwnd(new WindowInteropHelper(this).Handle);
if (hwndSource != null)
{
hwndSource.AddHook(HwndSourceHook);
CreateGlowWindowHandles();
}
base.OnSourceInitialized(e);
}
#endregion
#region private
private IEnumerable<GlowEdge> LoadedGlowWindows => from w in _glowEdges where w != null select w;
private bool IsGlowVisible
{
get => _isGlowVisible;
set
{
if (_isGlowVisible != value)
{
_isGlowVisible = value;
for (var i = 0; i < _glowEdges.Length; i++)
{
GetOrCreateGlowWindow(i).IsVisible = value;
}
}
}
}
private GlowEdge GetOrCreateGlowWindow(int direction)
{
return _glowEdges[direction] ?? (_glowEdges[direction] = new GlowEdge(this, (Dock)direction)
{
ActiveGlowColor = ActiveGlowColor,
InactiveGlowColor = InactiveGlowColor,
IsActive = IsActive
});
}
private static void OnResizeModeChanged(DependencyObject obj, DependencyPropertyChangedEventArgs e)
{
var customChromeWindow = (GlowWindow)obj;
customChromeWindow.UpdateGlowVisibility(false);
}
private static void OnGlowColorChanged(DependencyObject obj, DependencyPropertyChangedEventArgs args) => ((GlowWindow)obj).UpdateGlowColors();
private void UpdateGlowColors()
{
using (DeferGlowChanges())
{
foreach (var current in LoadedGlowWindows)
{
current.ActiveGlowColor = ActiveGlowColor;
current.InactiveGlowColor = InactiveGlowColor;
}
}
}
private void UpdateGlowVisibility(bool delayIfNecessary)
{
var shouldShowGlow = ShouldShowGlow;
if (shouldShowGlow != IsGlowVisible)
{
if (SystemParameters.MinimizeAnimation && shouldShowGlow && delayIfNecessary)
{
if (_makeGlowVisibleTimer != null)
{
_makeGlowVisibleTimer.Stop();
}
else
{
_makeGlowVisibleTimer = new DispatcherTimer
{
Interval = TimeSpan.FromMilliseconds(200.0)
};
_makeGlowVisibleTimer.Tick += OnDelayedVisibilityTimerTick;
}
_makeGlowVisibleTimer.Start();
return;
}
StopTimer();
IsGlowVisible = shouldShowGlow;
}
}
private void StopTimer()
{
if (_makeGlowVisibleTimer != null)
{
_makeGlowVisibleTimer.Stop();
_makeGlowVisibleTimer.Tick -= OnDelayedVisibilityTimerTick;
_makeGlowVisibleTimer = null;
}
}
private void OnDelayedVisibilityTimerTick(object sender, EventArgs e)
{
StopTimer();
UpdateGlowWindowPositions(false);
}
private void UpdateGlowWindowPositions(bool delayIfNecessary)
{
using (DeferGlowChanges())
{
UpdateGlowVisibility(delayIfNecessary);
foreach (var current in LoadedGlowWindows) current.UpdateWindowPos();
}
}
private IDisposable DeferGlowChanges() => new ChangeScope(this);
private void UpdateGlowActiveState()
{
using (DeferGlowChanges())
{
foreach (var current in LoadedGlowWindows)
{
current.IsActive = IsActive;
}
}
}
private void DestroyGlowWindows()
{
for (var i = 0; i < _glowEdges.Length; i++)
{
using (_glowEdges[i])
{
_glowEdges[i] = null;
}
}
}
private void WmWindowPosChanging(IntPtr lParam)
{
var windowpos = (InteropValues.WINDOWPOS)Marshal.PtrToStructure(lParam, typeof(InteropValues.WINDOWPOS));
if ((windowpos.flags & 2u) == 0u && (windowpos.flags & 1u) == 0u && windowpos.cx > 0 && windowpos.cy > 0)
{
var rect = new Rect(windowpos.x, windowpos.y, windowpos.cx, windowpos.cy);
rect = rect.DeviceToLogicalUnits();
if (_useLogicalSizeForRestore)
{
rect = _logicalSizeForRestore;
_logicalSizeForRestore = Rect.Empty;
_useLogicalSizeForRestore = false;
}
var logicalRect = GetOnScreenPosition(rect);
logicalRect = logicalRect.LogicalToDeviceUnits();
windowpos.x = (int)logicalRect.X;
windowpos.y = (int)logicalRect.Y;
Marshal.StructureToPtr(windowpos, lParam, true);
}
}
private void UpdateZOrderOfOwner(IntPtr hwndOwner)
{
var lastOwnedWindow = IntPtr.Zero;
InteropMethods.EnumThreadWindows(InteropMethods.GetCurrentThreadId(), delegate (IntPtr hwnd, IntPtr lParam)
{
if (InteropMethods.GetWindow(hwnd, 4) == hwndOwner) lastOwnedWindow = hwnd;
return true;
}, IntPtr.Zero);
if (lastOwnedWindow != IntPtr.Zero && InteropMethods.GetWindow(hwndOwner, 3) != lastOwnedWindow)
InteropMethods.SetWindowPos(hwndOwner, lastOwnedWindow, 0, 0, 0, 0, 19);
}
private void UpdateZOrderOfThisAndOwner()
{
if (_updatingZOrder) return;
try
{
_updatingZOrder = true;
var windowInteropHelper = new WindowInteropHelper(this);
var handle = windowInteropHelper.Handle;
foreach (var current in LoadedGlowWindows)
{
var window = InteropMethods.GetWindow(current.Handle, 3);
if (window != handle) InteropMethods.SetWindowPos(current.Handle, handle, 0, 0, 0, 0, 19);
handle = current.Handle;
}
var owner = windowInteropHelper.Owner;
if (owner != IntPtr.Zero) UpdateZOrderOfOwner(owner);
}
finally
{
_updatingZOrder = false;
}
}
private void WmWindowPosChanged(IntPtr lParam)
{
try
{
var windowpos = (InteropValues.WINDOWPOS)Marshal.PtrToStructure(lParam, typeof(InteropValues.WINDOWPOS));
UpdateGlowWindowPositions((windowpos.flags & 64u) == 0u);
UpdateZOrderOfThisAndOwner();
}
catch
{
// ignored
}
}
private Rect GetOnScreenPosition(Rect floatRect)
{
var result = floatRect;
floatRect = floatRect.LogicalToDeviceUnits();
ScreenHelper.FindMaximumSingleMonitorRectangle(floatRect, out _, out var rect2);
if (!floatRect.IntersectsWith(rect2))
{
ScreenHelper.FindMonitorRectsFromPoint(InteropMethods.GetCursorPos(), out _, out rect2);
rect2 = rect2.DeviceToLogicalUnits();
if (result.Width > rect2.Width) result.Width = rect2.Width;
if (result.Height > rect2.Height) result.Height = rect2.Height;
if (rect2.Right <= result.X) result.X = rect2.Right - result.Width;
if (rect2.Left > result.X + result.Width) result.X = rect2.Left;
if (rect2.Bottom <= result.Y) result.Y = rect2.Bottom - result.Height;
if (rect2.Top > result.Y + result.Height) result.Y = rect2.Top;
}
return result;
}
private static InteropValues.MONITORINFO MonitorInfoFromWindow(IntPtr hWnd)
{
var hMonitor = InteropMethods.MonitorFromWindow(hWnd, 2);
var result = default(InteropValues.MONITORINFO);
result.cbSize = (uint)Marshal.SizeOf(typeof(InteropValues.MONITORINFO));
InteropMethods.GetMonitorInfo(hMonitor, ref result);
return result;
}
private IntPtr WmNcActivate(IntPtr hWnd, IntPtr wParam) => InteropMethods.DefWindowProc(hWnd, InteropValues.WM_NCACTIVATE, wParam, InteropMethods.HRGN_NONE);
private bool IsAeroSnappedToMonitor(IntPtr hWnd)
{
var monitorinfo = MonitorInfoFromWindow(hWnd);
var logicalRect = new Rect(Left, Top, Width, Height);
logicalRect = logicalRect.LogicalToDeviceUnits();
return MathHelper.AreClose(monitorinfo.rcWork.Height, logicalRect.Height) && MathHelper.AreClose(monitorinfo.rcWork.Top, logicalRect.Top);
}
private void WmSysCommand(IntPtr hWnd, IntPtr wParam)
{
var num = InteropMethods.GET_SC_WPARAM(wParam);
if (num == InteropValues.SC_MOVE)
{
InteropMethods.RedrawWindow(hWnd, IntPtr.Zero, IntPtr.Zero,
InteropValues.RedrawWindowFlags.Invalidate | InteropValues.RedrawWindowFlags.NoChildren |
InteropValues.RedrawWindowFlags.UpdateNow | InteropValues.RedrawWindowFlags.Frame);
}
if ((num == InteropValues.SC_MAXIMIZE || num == InteropValues.SC_MINIMIZE || num == InteropValues.SC_MOVE ||
num == InteropValues.SC_SIZE) && WindowState == WindowState.Normal && !IsAeroSnappedToMonitor(hWnd))
{
_logicalSizeForRestore = new Rect(Left, Top, Width, Height);
}
if (num == InteropValues.SC_MOVE && WindowState == WindowState.Maximized && _logicalSizeForRestore == Rect.Empty)
{
_logicalSizeForRestore = new Rect(Left, Top, Width, Height);
}
if (num == InteropValues.SC_RESTORE && WindowState != WindowState.Minimized &&
_logicalSizeForRestore.Width > 0.0 && _logicalSizeForRestore.Height > 0.0)
{
Left = _logicalSizeForRestore.Left;
Top = _logicalSizeForRestore.Top;
Width = _logicalSizeForRestore.Width;
Height = _logicalSizeForRestore.Height;
_useLogicalSizeForRestore = true;
}
}
private IntPtr CallDefWindowProcWithoutVisibleStyle(IntPtr hWnd, int msg, IntPtr wParam, IntPtr lParam)
{
var flag = VisualHelper.ModifyStyle(hWnd, InteropValues.WS_VISIBLE, 0);
var result = InteropMethods.DefWindowProc(hWnd, msg, wParam, lParam);
if (flag) VisualHelper.ModifyStyle(hWnd, 0, InteropValues.WS_VISIBLE);
return result;
}
private void CreateGlowWindowHandles()
{
for (var i = 0; i < _glowEdges.Length; i++) GetOrCreateGlowWindow(i).EnsureHandle();
}
#endregion
}
}
| 36.875
| 165
| 0.538811
|
[
"MIT"
] |
3400442579/HandyControl
|
src/Shared/HandyControl_Shared/Controls/Window/GlowWindow.cs
| 17,407
|
C#
|
using System.Collections.Generic;
using Microsoft.AspNetCore.Mvc;
using BandTracker.Models;
using System;
namespace BandTracker.Controllers
{
public class VenuesController : Controller
{
[HttpGet("/venues")]
public ActionResult Index()
{
List<Venue> allVenues = Venue.GetAllVenues();
return View(allVenues);
}
[HttpGet("/venues/new")]
public ActionResult CreateForm()
{
return View("VenueForm");
}
[HttpPost("/venueForm")]
public ActionResult Create()
{
Venue newVenue = new Venue(Request.Form["venueName"], Request.Form["venueDescription"], Request.Form["venueLocation"], Int32.Parse(Request.Form["venueCapacity"]));
newVenue.Save();
return RedirectToAction("Success", "Home");
}
[HttpGet("/venues/{id}")]
public ActionResult VenueDetails(int id)
{
Dictionary<string, object> foundVenueDetails = new Dictionary<string, object> ();
Venue selectedVenue = Venue.Find(id);
List<Band> venueBands = selectedVenue.GetBands();
List<Band> allBands = Band.GetAllBands();
foundVenueDetails.Add("selectedVenue", selectedVenue);
foundVenueDetails.Add("venueBands", venueBands);
foundVenueDetails.Add("allBands", allBands);
return View(foundVenueDetails);
}
[HttpPost("/venues/{venueId}/bands/new")]
public ActionResult AddABand(int venueId)
{
Venue venue = Venue.Find(venueId);
Band band = Band.Find(Int32.Parse(Request.Form["band-id"]));
venue.AddBand(band);
return RedirectToAction("VenueDetails", new { id = venueId });
}
[HttpGet("/venues/{id}/edit")]
public ActionResult VenueEditForm(int id)
{
Venue thisVenue = Venue.Find(id);
return View("VenueEditForm", thisVenue);
}
[HttpPost("/venues/edit/{venueId}/change")]
public ActionResult EditVenueInfo(int venueId)
{
Venue selectedVenue = Venue.Find(venueId);
selectedVenue.UpdateVenueDetails(Request.Form["editName"], Request.Form["editDescription"], Request.Form["editLocation"], Int32.Parse(Request.Form["editCapacity"]));
return RedirectToAction("Update", "Home");
}
[HttpPost("/venues/{venueId}/delete")]
public ActionResult DeleteVenue(int venueId)
{
Venue selectedVenue = Venue.Find(venueId);
selectedVenue.Delete();
return RedirectToAction("Delete", "Home");
}
}
}
| 35.661972
| 173
| 0.637046
|
[
"MIT"
] |
azamatbekmurat/BandTracker
|
BandTracker/Controllers/VenuesController.cs
| 2,532
|
C#
|
using Prolliance.Membership.Business;
using Prolliance.Membership.Common;
using Prolliance.Membership.DataTransfer.Models;
using System.Collections.Generic;
using System.Linq;
namespace Prolliance.Membership.DataTransfer
{
public static class AppAdapter
{
public static bool CheckApp(string appKey, string secret)
{
if (appKey == AppSettings.Name)
{
return false;
}
App app = App.GetApp(appKey);
return app != null && app.Secret == secret && app.IsActive;
}
public static void RemoveAllCache()
{
App.RemoveAllCache();
}
public static void ExecuteDynamicSql(string dynamicSql)
{
App.ExecuteDynamicSql(dynamicSql);
}
public static void ImportManifestText(string appKey, string manifest)
{
if (string.IsNullOrWhiteSpace(appKey)) return;
App app = App.GetApp(appKey);
if (app != null)
{
app.ImportManifestText(manifest);
}
}
public static void ImportManifest(string appKey, List<TargetInfo> targetList)
{
if (string.IsNullOrWhiteSpace(appKey)) return;
App app = App.GetApp(appKey);
if (app != null)
{
app.ImportManifest(targetList.MappingToList<App.TargetPetty>());
}
}
public static List<AppInfo> GetAppList()
{
var appLst = App.GetAppList();
if(appLst == null)
{
return new List<AppInfo>();
}
return appLst.MappingToList<AppInfo>();
}
public static List<TargetInfo> GetTargetList(string appKey)
{
if (string.IsNullOrWhiteSpace(appKey)) return null;
App app = App.GetApp(appKey);
if (app == null) return null;
return app.TargetList.MappingToList<TargetInfo>();
}
public static List<OperationInfo> GetOperationList()
{
var operationList = Operation.GetOperationList();
if (operationList == null)
return new List<OperationInfo>();
return operationList.MappingToList<OperationInfo>();
}
public static void UpdateTargetList(string appKey, List<TargetInfo> targetList)
{
if (string.IsNullOrWhiteSpace(appKey)) return;
App app = App.GetApp(appKey);
if (app == null) return;
var oriList = app.TargetList.MappingToList<App.TargetPetty>();
oriList.RemoveAll(t => targetList.Select(nt => nt.Code).ToList().Contains(t.Code));
oriList.AddRange(targetList.MappingToList<App.TargetPetty>());
app.ImportManifest(oriList);
}
public static void AddTargetList(string appKey, List<TargetInfo> targetList)
{
if (string.IsNullOrWhiteSpace(appKey) || targetList == null) return;
App app = App.GetApp(appKey);
if (app == null) return;
foreach (var targetInfo in targetList)
{
if (targetInfo == null) continue;
var target = app.TargetList.FirstOrDefault(t => t.Id == targetInfo.Id
|| t.Code == targetInfo.Code);
//如果不存在则添加
if (target == null)
{
target = targetInfo.MappingTo<Target>(new List<string>() { "AppKey", "OperationList" });
target = app.AddTarget(target);
}
//处理opeation
if (targetInfo.OperationList == null) continue;
foreach (OperationInfo operationInfo in targetInfo.OperationList)
{
var operation = target.OperationList
.FirstOrDefault(o => o.Id == operationInfo.Id
|| (o.Code == operationInfo.Code));
//如果不存在则添加
if (operation == null)
{
target.AddOperation(operationInfo.MappingTo<Operation>());
}
}
}
}
public static void DeleteTargetList(string appKey, List<TargetInfo> targetList)
{
if (string.IsNullOrWhiteSpace(appKey) || targetList == null) return;
App app = App.GetApp(appKey);
if (app == null || app.TargetList == null) return;
foreach (var targetInfo in targetList)
{
if (targetInfo == null) continue;
var target = app.TargetList.FirstOrDefault(t => t.Id == targetInfo.Id
|| (t.AppKey == targetInfo.AppKey && t.Code == targetInfo.Code)
|| (t.AppId == targetInfo.AppId && t.Code == targetInfo.Code));
if (target != null)
{
app.RemoveTarget(target);
}
}
}
public static void AddOperationList(string appKey, List<OperationInfo> operationList)
{
if (string.IsNullOrWhiteSpace(appKey) || operationList == null) return;
App app = App.GetApp(appKey);
if (app == null || app.TargetList == null) return;
foreach (var operationInfo in operationList)
{
var target = app.TargetList
.FirstOrDefault(t => t.Id == operationInfo.TargetId
|| t.Code == operationInfo.TargetCode);
if (target != null)
{
target.AddOperation(operationInfo.MappingTo<Operation>(new List<string>() { "AppKey", "TargetCode" }));
}
}
}
public static void DeleteOperationList(string appKey, List<OperationInfo> operationList)
{
if (string.IsNullOrWhiteSpace(appKey) || operationList == null) return;
App app = App.GetApp(appKey);
if (app == null || app.TargetList == null) return;
foreach (var operationInfo in operationList)
{
var target = app.TargetList
.FirstOrDefault(t => t.Id == operationInfo.TargetId
|| t.Code == operationInfo.TargetCode);
if (target != null)
{
Operation operation = target.OperationList.FirstOrDefault(o => o.Code == operationInfo.Code);
if (operation != null)
{
target.RemoveOperation(operation);
}
}
}
}
}
}
| 37.903955
| 123
| 0.52437
|
[
"Apache-2.0"
] |
Prolliance/Membership
|
Prolliance.Membership.DataTransfer/AppAdapter.cs
| 6,747
|
C#
|
using System;
using System.Collections.Generic;
using System.Text;
namespace ManiaPlanetSharp.GameBox.Parsing
{
/// <summary>
/// Manages global settings for the GameBox parser
/// </summary>
public static class GlobalParserSettings
{
/// <summary>
/// The maximum size in bytes for which the body of a GameBox file will be analyzed. If the body size of a GameBox file exceeds this limit, an exception will be thrown.
/// </summary>
public static uint MaximumUncompressedGameBoxBodySize { get; set; } = 100000000; //100MB
private static bool usePrecompiledParsers = true;
/// <summary>
/// Specifies whether precompiled parsers from the ManiaPlanetSharp.GameBox.AutoGenerated assembly should be used, should they be present. This is primarily for development and testing purposes, as the proper way to disable the use of precompiled parsers is to just not include the additional assembly and not change any settings here.
/// </summary>
public static bool UsePrecompiledParsersIfPresent
{
get
{
return usePrecompiledParsers;
}
set
{
if (value != UsePrecompiledParsersIfPresent)
{
usePrecompiledParsers = value;
if (UsePrecompiledParsersIfPresent)
{
ParserFactory.InitializePrecompiledParsers();
}
else
{
ParserFactory.ClearParsers();
}
}
}
}
private static bool useDynamicallyCompiledChunkParsers = true;
/// <summary>
/// Specifies whether dynamically generated and compiled parsers should be used if no precompiled parser is available (or they are disabled).
/// </summary>
public static bool UseDynamicallyCompiledChunkParsers
{
get
{
return useDynamicallyCompiledChunkParsers;
}
set
{
if (value != UseDynamicallyCompiledChunkParsers)
{
useDynamicallyCompiledChunkParsers = value;
if (!UseDynamicallyCompiledChunkParsers)
{
ParserFactory.ClearParsers();
ParserFactory.InitializePrecompiledParsers();
}
else
{
ParserFactory.ScanForParseableChunks();
}
}
}
}
}
}
| 37.09589
| 343
| 0.54579
|
[
"MIT"
] |
stefan-baumann/ManiaPlanetSharp
|
src/ManiaPlanetSharp/GameBox/Parsing/GlobalParserSettings.cs
| 2,710
|
C#
|
using System.Threading.Tasks;
using JiraEpicRoadmapper.UI.Shared.Components;
using JiraEpicRoadmapper.UI.Tests.Scaffolding;
using LightBDD.Framework.Scenarios;
using LightBDD.XUnit2;
namespace JiraEpicRoadmapper.UI.Tests.Components
{
public class ErrorPanelTests : FeatureFixture
{
[Scenario]
public async Task Bar_with_no_label()
{
await Runner
.WithContext<ErrorPanelFixture>()
.AddSteps(
x => x.Given_a_error_panel(),
x => x.When_I_render_it(),
x => x.Then_I_should_see_content("<div class=\"error-panel\"></div>"))
.RunAsync();
}
[Scenario]
public async Task Bar_with_label()
{
await Runner
.WithContext<ErrorPanelFixture>()
.AddSteps(
x => x.Given_a_error_panel(),
x => x.Given_it_has_parameter_value(nameof(ErrorPanel.Errors), "boom"),
x => x.When_I_render_it(),
x => x.Then_I_should_see_content("<div class=\"error-panel\">boom</div>"))
.RunAsync();
}
public class ErrorPanelFixture : ComponentFixture<ErrorPanel>
{
public void Given_a_error_panel()
{
}
}
}
}
| 31.744186
| 94
| 0.545788
|
[
"BSD-2-Clause"
] |
Suremaker/epic-roadmapper
|
test/JiraEpicRoadmapper.UI.Tests/Components/ErrorPanelTests.cs
| 1,365
|
C#
|
using System;
using System.Collections.Generic;
using System.Linq;
using NUnit.Framework;
using PivotalTrackerDotNet.Domain;
namespace PivotalTrackerDotNet.Tests
{
// ReSharper disable InconsistentNaming
[TestFixture]
public class StoryServiceTest
{
private StoryService storyService;
[TestFixtureSetUp]
public void TestFixtureSetUp()
{
this.storyService = new StoryService(Constants.ApiToken);
}
[TearDown]
public void Cleanup()
{
var stories = this.storyService.GetAllStories(Constants.ProjectId);
foreach (var storey in stories)
{
this.storyService.RemoveStory(Constants.ProjectId, storey.Id);
}
}
[Test]
public void CanRetrieveStoriesWithNestedObjects()
{
var savedStory = this.storyService.AddNewStory(Constants.ProjectId, new Story
{
Name = "Nouvelle histoire",
RequestedById = Constants.UserId,
StoryType = StoryType.Feature,
Description = "bla bla bla and more bla",
ProjectId = Constants.ProjectId,
Estimate = 2
});
this.storyService.AddNewTask(new Task
{
Description = "wololo",
StoryId = savedStory.Id,
ProjectId = savedStory.ProjectId
});
this.storyService.AddComment(savedStory.ProjectId, savedStory.Id, "Comment 1");
this.storyService.AddComment(savedStory.ProjectId, savedStory.Id, "Comment 2");
var items = storyService.GetAllStories(Constants.ProjectId, StoryIncludeFields.Owners |
StoryIncludeFields.OwnerIds |
StoryIncludeFields.Followers |
StoryIncludeFields.FollowerIds |
StoryIncludeFields.Comments |
StoryIncludeFields.Tasks |
StoryIncludeFields.RequestedBy);
Assert.AreEqual(1, items.Count);
Assert.IsNotNull(items.First().Followers);
Assert.IsNotNull(items.First().RequestedBy);
Assert.IsNotNull(items.First().Comments);
Assert.IsNotNull(items.First().Tasks);
Assert.Greater(items.First().Comments.Count, 0);
Assert.Greater(items.First().Tasks.Count, 0);
items.First().Comments.ForEach(c => Assert.IsNotNull(c.Person));
}
[Test]
public void CanRetrieveSingleStory()
{
var savedStory = this.storyService.AddNewStory(Constants.ProjectId, new Story
{
Name = "Nouvelle histoire",
RequestedById = Constants.UserId,
StoryType = StoryType.Feature,
Description = "bla bla bla and more bla",
ProjectId = Constants.ProjectId,
Estimate = 2
});
this.storyService.AddNewTask(new Task
{
Description = "wololo",
StoryId = savedStory.Id,
ProjectId = savedStory.ProjectId
});
List<Task> tasks = this.storyService.GetTasksForStory(Constants.ProjectId, savedStory);
var retrieved = this.storyService.GetStory(Constants.ProjectId, savedStory.Id);
Assert.NotNull(retrieved);
Assert.AreEqual(Constants.ProjectId, retrieved.ProjectId);
Assert.AreEqual(savedStory.Id, retrieved.Id);
Assert.AreEqual(savedStory.StoryType, retrieved.StoryType);
Assert.AreEqual(savedStory.Name, retrieved.Name);
Assert.AreEqual(savedStory.Estimate, retrieved.Estimate);
Assert.AreEqual(1, tasks.Count);
Assert.AreEqual(savedStory.Id, tasks[0].StoryId);
}
[Test]
public void CanRetrieveSingleStoryWithOwner()
{
var savedStory = this.storyService.AddNewStory(Constants.ProjectId, new Story
{
Name = "Nouvelle histoire",
RequestedById = Constants.UserId,
StoryType = StoryType.Feature,
Description = "bla bla bla and more bla",
ProjectId = Constants.ProjectId,
Estimate = 2,
OwnerIds = new List<int>() { Constants.UserId }
});
var retrieved = this.storyService.GetStory(Constants.ProjectId, savedStory.Id, StoryIncludeFields.OwnerIds);
Assert.NotNull(retrieved);
Assert.AreEqual(savedStory.OwnerIds, retrieved.OwnerIds);
}
[Test]
public void CanRetrieveSingleStoryWithFields()
{
var savedStory = this.storyService.AddNewStory(Constants.ProjectId, new Story
{
Name = "Nouvelle histoire",
RequestedById = Constants.UserId,
StoryType = StoryType.Feature,
Description = "bla bla bla and more bla",
ProjectId = Constants.ProjectId,
Estimate = 2,
});
this.storyService.AddNewTask(new Task
{
Description = "wololo",
StoryId = savedStory.Id,
ProjectId = savedStory.ProjectId
});
this.storyService.AddComment(savedStory.ProjectId, savedStory.Id, "Comment 1");
this.storyService.AddComment(savedStory.ProjectId, savedStory.Id, "Comment 2");
var retrieved = this.storyService.GetStory(Constants.ProjectId, savedStory.Id, StoryIncludeFields.Tasks | StoryIncludeFields.Comments);
Assert.NotNull(retrieved);
Assert.AreEqual(Constants.ProjectId, retrieved.ProjectId);
Assert.AreEqual(savedStory.Id, retrieved.Id);
Assert.AreEqual(savedStory.StoryType, retrieved.StoryType);
Assert.AreEqual(savedStory.Name, retrieved.Name);
Assert.AreEqual(savedStory.Estimate, retrieved.Estimate);
Assert.AreEqual(1, retrieved.Tasks.Count);
Assert.AreEqual(savedStory.Id, retrieved.Tasks[0].StoryId);
Assert.AreEqual(2, retrieved.Comments.Count);
}
[Test]
public void CanRetrieveAllStories()
{
var story = new Story
{
Name = "Nouvelle histoire",
RequestedById = Constants.UserId,
StoryType = StoryType.Feature,
Description = "bla bla bla and more bla",
ProjectId = Constants.ProjectId
};
var savedStory = this.storyService.AddNewStory(Constants.ProjectId, story);
Assert.AreEqual(StoryType.Feature, savedStory.StoryType);
var stories = this.storyService.GetAllStories(Constants.ProjectId);
Assert.NotNull(stories);
Assert.AreEqual(1, stories.Count);
Assert.AreEqual(savedStory.Id, stories[0].Id);
Assert.AreEqual(StoryType.Feature, stories[0].StoryType);
}
[Test] //, Ignore("The code works, but the lag from pivotal is such that it requires to sleep for close to a minute to pass")]
public void CanRetrieveAllStories_Paging()
{
var story = new Story
{
Name = "Nouvelle histoire",
RequestedById = Constants.UserId,
StoryType = StoryType.Feature,
Description = "bla bla bla and more bla",
ProjectId = Constants.ProjectId
};
var story2 = new Story
{
Name = "Nouvelle histoire",
RequestedById = Constants.UserId,
StoryType = StoryType.Bug,
Description = "bla bla bla and more bla",
ProjectId = Constants.ProjectId
};
this.storyService.AddNewStory(Constants.ProjectId, story);
this.storyService.AddNewStory(Constants.ProjectId, story2);
//// System.Threading.Thread.Sleep(30000); // There is a lag in pivotal tracker's filter search. removing the slepp will cause the test to fail occasionally
var stories = this.storyService.GetAllStories(Constants.ProjectId, 2, 0);
Assert.NotNull(stories);
Assert.AreEqual(2, stories.Data.Count);
Assert.AreEqual(2, stories.Pagination.Returned);
Assert.AreEqual(2, stories.Pagination.Total);
stories = this.storyService.GetAllStories(Constants.ProjectId, 1, 1);
Assert.NotNull(stories);
Assert.AreEqual(1, stories.Data.Count);
Assert.AreEqual(1, stories.Pagination.Returned);
Assert.AreEqual(2, stories.Pagination.Total);
}
[Test]
public void CanGetAllStoriesMatchingFilter_FreeForm()
{
var story1 = new Story
{
Name = "Nouvelle histoire",
RequestedById = Constants.UserId,
StoryType = StoryType.Bug,
Description = "some story",
ProjectId = Constants.ProjectId
};
var story2 = new Story
{
Name = "Nouvelle histoire",
RequestedById = Constants.UserId,
StoryType = StoryType.Feature,
Description = "another story",
ProjectId = Constants.ProjectId
};
var story3 = new Story
{
Name = "Nouvelle histoire",
RequestedById = Constants.UserId,
StoryType = StoryType.Feature,
Description = "yet another story",
ProjectId = Constants.ProjectId
};
var savedStory = this.storyService.AddNewStory(Constants.ProjectId, story1);
this.storyService.AddNewStory(Constants.ProjectId, story2);
this.storyService.AddNewStory(Constants.ProjectId, story3);
System.Threading.Thread.Sleep(5000); // There is a lag in pivotal tracker's filter search. removing the slepp will cause the test to fail occasionally
var stories = this.storyService.GetAllStoriesMatchingFilter(Constants.ProjectId, "type:bug requester:\"pivotaltrackerdotnet\"");
Assert.NotNull(stories);
Assert.AreEqual(1, stories.Count);
Assert.AreEqual(savedStory.Id, stories[0].Id);
}
[Test]
public void CanGetAllStoriesMatchingFilter_WithFields()
{
var story1 = new Story
{
Name = "Nouvelle histoire",
RequestedById = Constants.UserId,
StoryType = StoryType.Bug,
Description = "some story",
ProjectId = Constants.ProjectId
};
var story2 = new Story
{
Name = "Nouvelle histoire",
RequestedById = Constants.UserId,
StoryType = StoryType.Feature,
Description = "another story",
ProjectId = Constants.ProjectId
};
var story3 = new Story
{
Name = "Nouvelle histoire",
RequestedById = Constants.UserId,
StoryType = StoryType.Feature,
Description = "yet another story",
ProjectId = Constants.ProjectId
};
var savedStory = this.storyService.AddNewStory(Constants.ProjectId, story1);
this.storyService.AddNewStory(Constants.ProjectId, story2);
this.storyService.AddNewStory(Constants.ProjectId, story3);
this.storyService.AddNewTask(new Task { Description = "stuff stuff stuff", StoryId = savedStory.Id, ProjectId = Constants.ProjectId });
this.storyService.AddComment(Constants.ProjectId, savedStory.Id, "A comment");
System.Threading.Thread.Sleep(5000); // There is a lag in pivotal tracker's filter search. removing the slepp will cause the test to fail occasionally
var stories = this.storyService.GetAllStoriesMatchingFilter(
Constants.ProjectId,
"type:bug requester:\"pivotaltrackerdotnet\"",
StoryIncludeFields.Owners |
StoryIncludeFields.OwnerIds |
StoryIncludeFields.Followers |
StoryIncludeFields.FollowerIds |
StoryIncludeFields.Comments |
StoryIncludeFields.Tasks |
StoryIncludeFields.RequestedBy);
Assert.NotNull(stories);
Assert.AreEqual(1, stories.Count);
Assert.AreEqual(savedStory.Id, stories[0].Id);
Assert.NotNull(stories[0].Followers);
Assert.NotNull(stories[0].Comments);
Assert.NotNull(stories[0].Tasks);
Assert.Greater(stories[0].Followers.Count, 0);
Assert.Greater(stories[0].Comments.Count, 0);
Assert.Greater(stories[0].Tasks.Count, 0);
Assert.NotNull(stories[0].RequestedBy);
}
[Test]
public void CanGetAllStoriesMatchingFilter_Strict()
{
var story1 = new Story
{
Name = "Nouvelle histoire",
RequestedById = Constants.UserId,
StoryType = StoryType.Bug,
Description = "some story",
ProjectId = Constants.ProjectId
};
var story2 = new Story
{
Name = "Nouvelle histoire",
RequestedById = Constants.UserId,
StoryType = StoryType.Feature,
Description = "another story",
ProjectId = Constants.ProjectId
};
var story3 = new Story
{
Name = "Nouvelle histoire",
RequestedById = Constants.UserId,
StoryType = StoryType.Feature,
Description = "yet another story",
ProjectId = Constants.ProjectId
};
var savedStory = this.storyService.AddNewStory(Constants.ProjectId, story1);
savedStory.Labels = new List<Label> { "5.1.30", "plume" };
savedStory = this.storyService.UpdateStory(Constants.ProjectId, savedStory);
this.storyService.AddNewStory(Constants.ProjectId, story2);
this.storyService.AddNewStory(Constants.ProjectId, story3);
System.Threading.Thread.Sleep(5000); // There is a lag in pivotal tracker's filter search. removing the slepp will cause the test to fail occasionally
var stories = this.storyService.GetAllStoriesMatchingFilter(Constants.ProjectId, FilteringCriteria.FilterBy.Label("5.1.30").Type(StoryType.Bug));
Assert.NotNull(stories);
Assert.AreEqual(1, stories.Count);
Assert.AreEqual(savedStory.Id, stories[0].Id);
}
[Test]
public void CanGetAllStoriesMatchingFilterCreatedSince_Strict()
{
var story1 = new Story
{
Name = "Nouvelle histoire",
RequestedById = Constants.UserId,
StoryType = StoryType.Bug,
Description = "some story",
ProjectId = Constants.ProjectId
};
var story2 = new Story
{
Name = "Nouvelle histoire",
RequestedById = Constants.UserId,
StoryType = StoryType.Feature,
Description = "another story",
ProjectId = Constants.ProjectId
};
var story3 = new Story
{
Name = "Nouvelle histoire",
RequestedById = Constants.UserId,
StoryType = StoryType.Feature,
Description = "yet another story",
ProjectId = Constants.ProjectId
};
var savedStory1 = this.storyService.AddNewStory(Constants.ProjectId, story1);
savedStory1.Labels = new List<Label> { "5.1.30", "plume" };
savedStory1 = this.storyService.UpdateStory(Constants.ProjectId, savedStory1);
var savedStory2 = this.storyService.AddNewStory(Constants.ProjectId, story2);
var savedStory3 = this.storyService.AddNewStory(Constants.ProjectId, story3);
System.Threading.Thread.Sleep(5000); // There is a lag in pivotal tracker's filter search. removing the slepp will cause the test to fail occasionally
var stories = this.storyService.GetAllStoriesMatchingFilter(Constants.ProjectId, FilteringCriteria.FilterBy.CreatedSince(new DateTime(2008, 1, 1)));
Assert.NotNull(stories);
Assert.AreEqual(3, stories.Count);
var savedIds = new[] { savedStory1.Id, savedStory2.Id, savedStory3.Id }.OrderBy(i => i).ToArray();
var storyIds = stories.Select(s => s.Id).OrderBy(i => i).ToArray();
Assert.IsTrue(storyIds.SequenceEqual(savedIds));
}
[Test]
public void CanRetrieveIceBoxStories()
{
var story = new Story
{
Name = "Nouvelle histoire",
RequestedById = Constants.UserId,
StoryType = StoryType.Feature,
Description = "bla bla bla and more bla",
ProjectId = Constants.ProjectId,
CurrentState = StoryStatus.Unscheduled,
Estimate = 2
};
var savedStory = this.storyService.AddNewStory(Constants.ProjectId, story);
System.Threading.Thread.Sleep(5000); // There is a lag in pivotal tracker's filter search. removing the slepp will cause the test to fail occasionally
var stories = this.storyService.GetIceboxStories(Constants.ProjectId);
Assert.NotNull(stories);
Assert.AreEqual(1, stories.Count);
Assert.AreEqual(savedStory.Id, stories[0].Id);
}
[Test]
public void CanAddAndDeleteStories()
{
var story = new Story
{
Name = "Nouvelle histoire",
RequestedById = Constants.UserId,
StoryType = StoryType.Feature,
Description = "bla bla bla and more bla",
ProjectId = Constants.ProjectId,
Estimate = 2
};
var savedStory = this.storyService.AddNewStory(Constants.ProjectId, story);
Assert.AreEqual(story.Name, savedStory.Name);
Assert.AreEqual(Constants.ProjectId, savedStory.ProjectId);
Assert.AreEqual(story.RequestedById, savedStory.RequestedById);
Assert.AreEqual(story.StoryType, savedStory.StoryType);
Assert.AreEqual(story.Description, savedStory.Description);
Assert.AreEqual(2, savedStory.Estimate);
this.storyService.RemoveStory(Constants.ProjectId, savedStory.Id);
}
[Test]
public void CanUpdateStory()
{
var story = new Story
{
Name = "Nouvelle histoire",
RequestedById = Constants.UserId,
StoryType = StoryType.Feature,
Description = "bla bla bla and more bla",
ProjectId = Constants.ProjectId,
Estimate = 2
};
var savedStory = this.storyService.AddNewStory(Constants.ProjectId, story);
savedStory.Name = "Call be New name";
savedStory.Description = "wololo";
savedStory.Estimate = 1;
savedStory.Labels = new List<Label> { "laby hh", "pool" };
var updatedStory = this.storyService.UpdateStory(Constants.ProjectId, savedStory);
VerifyStory(savedStory, updatedStory);
}
[Test]
public void CanSaveTask()
{
var story = new Story
{
Name = "Nouvelle histoire",
RequestedById = Constants.UserId,
StoryType = StoryType.Feature,
Description = "bla bla bla and more bla",
ProjectId = Constants.ProjectId
};
var savedStory = this.storyService.AddNewStory(Constants.ProjectId, story);
var task = this.storyService.AddNewTask(new Task { Description = "stuff stuff stuff", StoryId = savedStory.Id, ProjectId = Constants.ProjectId });
var guid = Guid.NewGuid().ToString();
task.Description = guid;
var savedTask = this.storyService.SaveTask(task);
Assert.AreEqual(task.Description, savedTask.Description);
Assert.AreEqual(task.ProjectId, savedTask.ProjectId);
Assert.AreEqual(task.StoryId, savedTask.StoryId);
var tasks = this.storyService.GetTasksForStory(Constants.ProjectId, savedStory);
Assert.AreEqual(guid, tasks[0].Description);
}
[Test]
public void CanAddGetAndDeleteNewTasks()
{
var story = new Story
{
Name = "Nouvelle histoire",
RequestedById = Constants.UserId,
StoryType = StoryType.Feature,
Description = "bla bla bla and more bla",
ProjectId = Constants.ProjectId
};
var savedStory = this.storyService.AddNewStory(Constants.ProjectId, story);
var task = new Task { Description = "stuff stuff stuff", StoryId = savedStory.Id, ProjectId = Constants.ProjectId };
var savedTask = this.storyService.AddNewTask(task);
Assert.AreEqual(task.Description, savedTask.Description);
var retrievedTask = this.storyService.GetTask(Constants.ProjectId, savedTask.StoryId, savedTask.Id);
Assert.NotNull(retrievedTask);
Assert.IsTrue(this.storyService.RemoveTask(retrievedTask.ProjectId, task.StoryId, retrievedTask.Id));
}
[Test]
public void CanGetAllIterations()
{
var story = new Story
{
Name = "Nouvelle histoire",
RequestedById = Constants.UserId,
StoryType = StoryType.Feature,
Description = "bla bla bla and more bla",
ProjectId = Constants.ProjectId,
Deadline = DateTimeOffset.Now,
CurrentState = StoryStatus.Unstarted
};
var savedStory = this.storyService.AddNewStory(Constants.ProjectId, story);
var task = this.storyService.AddNewTask(new Task { Description = "stuff stuff stuff", StoryId = savedStory.Id, ProjectId = Constants.ProjectId });
this.storyService.AddComment(Constants.ProjectId, savedStory.Id, "A comment");
var iterations = this.storyService.GetAllIterations(Constants.ProjectId);
Assert.Greater(iterations.Count, 0);
Assert.NotNull(iterations[0].Start);
Assert.NotNull(iterations[0].Stories);
Assert.Greater(iterations[0].Stories.Count, 0);
Assert.IsNull(iterations[0].Stories[0].Followers);
Assert.IsNull(iterations[0].Stories[0].Comments);
Assert.IsNull(iterations[0].Stories[0].Tasks);
Assert.IsNull(iterations[0].Stories[0].RequestedBy);
}
[Test]
public void CanGetAllIterationsWithStoryFields()
{
var story = new Story
{
Name = "Nouvelle histoire",
RequestedById = Constants.UserId,
StoryType = StoryType.Feature,
Description = "bla bla bla and more bla",
ProjectId = Constants.ProjectId,
Deadline = DateTimeOffset.Now,
CurrentState = StoryStatus.Unstarted
};
var savedStory = this.storyService.AddNewStory(Constants.ProjectId, story);
var task = this.storyService.AddNewTask(new Task { Description = "stuff stuff stuff", StoryId = savedStory.Id, ProjectId = Constants.ProjectId });
this.storyService.AddComment(Constants.ProjectId, savedStory.Id, "A comment");
var iterations = this.storyService.GetAllIterations(Constants.ProjectId, StoryIncludeFields.Owners |
StoryIncludeFields.OwnerIds |
StoryIncludeFields.Followers |
StoryIncludeFields.FollowerIds |
StoryIncludeFields.Comments |
StoryIncludeFields.Tasks |
StoryIncludeFields.RequestedBy);
Assert.Greater(iterations.Count, 0);
Assert.NotNull(iterations[0].Start);
Assert.NotNull(iterations[0].Stories);
Assert.Greater(iterations[0].Stories.Count, 0);
Assert.NotNull(iterations[0].Stories[0].Followers);
Assert.NotNull(iterations[0].Stories[0].Comments);
Assert.NotNull(iterations[0].Stories[0].Tasks);
Assert.Greater(iterations[0].Stories[0].Followers.Count, 0);
Assert.Greater(iterations[0].Stories[0].Comments.Count, 0);
Assert.Greater(iterations[0].Stories[0].Tasks.Count, 0);
Assert.NotNull(iterations[0].Stories[0].RequestedBy);
}
[Test]
public void StoryNotFoundThrowsException()
{
Assert.That(() => this.storyService.GetStory(Constants.ProjectId, 1234), Throws.TypeOf<PivotalTrackerResourceNotFoundException>());
}
[Test]
public void ActivityProcessingTest()
{
int storyId;
{
var story = new Story
{
Name = "Nouvelle histoire",
RequestedById = Constants.UserId,
StoryType = StoryType.Feature,
Description = "bla bla bla and more bla",
ProjectId = Constants.ProjectId
};
var savedStory = this.storyService.AddNewStory(Constants.ProjectId, story);
var task1 = new Task { Description = "stuff stuff stuff", StoryId = savedStory.Id, ProjectId = Constants.ProjectId };
var task2 = new Task { Description = "stuff stuff stuff", StoryId = savedStory.Id, ProjectId = Constants.ProjectId };
var savedTask1 = this.storyService.AddNewTask(task1);
savedStory.Labels = new List<Label>() { "Label1", "Label2" };
savedStory.Estimate = 3;
savedStory = this.storyService.UpdateStory(Constants.ProjectId, savedStory);
var savedTask2 = this.storyService.AddNewTask(task2);
this.storyService.AddComment(savedStory.ProjectId, savedStory.Id, "Comment 1");
this.storyService.AddComment(savedStory.ProjectId, savedStory.Id, "Comment 2");
savedStory.Name = "New story";
savedStory.Deadline = DateTimeOffset.Now.AddDays(10);
savedStory.Estimate = 3;
savedStory = this.storyService.UpdateStory(Constants.ProjectId, savedStory);
storyId = savedStory.Id;
}
var activities = this.storyService.GetStoryActivity(Constants.ProjectId, storyId);
activities = activities.OrderBy(a => a.OccurredAt).ToList();
var accumulatedStoryValues = new Dictionary<string, object>();
var accumulatedTasksValues = new Dictionary<int, Dictionary<string, object>>();
var accumulatedCommentValues = new Dictionary<int, Dictionary<string, object>>();
var accumulatedLabelValues = new Dictionary<int, Dictionary<string, object>>();
var deserializer = new DictionaryDeserializer();
var foundObjects = new List<object>();
foreach (var activity in activities)
{
foreach (var change in activity.Changes)
{
if (change.NewValues != null && change.NewValues.Count == 1 && change.NewValues.ContainsKey("updated_at"))
continue; // Skip story changes without any significat changes
switch (change.Kind)
{
case ResourceKind.Story:
{
if (change.NewValues != null)
change.NewValues.ToList().ForEach(kp => accumulatedStoryValues[kp.Key] = kp.Value);
else if (change.OriginalValues != null)
change.OriginalValues.ToList().ForEach(kp => accumulatedStoryValues[kp.Key] = kp.Value);
var story = deserializer.Deserialize<Story>(accumulatedStoryValues);
if (activity.OccurredAt != DateTimeOffset.MinValue ||
(change.NewValues != null && !change.NewValues.ContainsKey("updated_at")))
{
story.UpdatedAt = activity.OccurredAt;
}
foundObjects.Add(story);
break;
}
case ResourceKind.Comment:
{
Dictionary<string, object> values;
if (!accumulatedTasksValues.TryGetValue(change.Id, out values))
{
values = accumulatedTasksValues[change.Id] = new Dictionary<string, object>();
}
if (change.NewValues != null)
change.NewValues.ToList().ForEach(kp => values[kp.Key] = kp.Value);
else if (change.OriginalValues != null)
change.OriginalValues.ToList().ForEach(kp => values[kp.Key] = kp.Value);
var comment = deserializer.Deserialize<Comment>(values);
if (activity.OccurredAt != DateTimeOffset.MinValue ||
(change.NewValues != null && !change.NewValues.ContainsKey("updated_at")))
{
comment.UpdatedAt = activity.OccurredAt;
}
foundObjects.Add(comment);
break;
}
case ResourceKind.Task:
{
Dictionary<string, object> values;
if (!accumulatedCommentValues.TryGetValue(change.Id, out values))
{
values = accumulatedCommentValues[change.Id] = new Dictionary<string, object>();
}
if (change.NewValues != null)
change.NewValues.ToList().ForEach(kp => values[kp.Key] = kp.Value);
else if (change.OriginalValues != null)
change.OriginalValues.ToList().ForEach(kp => values[kp.Key] = kp.Value);
var task = deserializer.Deserialize<Task>(values);
if (activity.OccurredAt != DateTimeOffset.MinValue ||
(change.NewValues != null && !change.NewValues.ContainsKey("updated_at")))
{
task.UpdatedAt = activity.OccurredAt;
}
foundObjects.Add(task);
break;
}
case ResourceKind.Label:
{
Dictionary<string, object> values;
if (!accumulatedLabelValues.TryGetValue(change.Id, out values))
{
values = accumulatedLabelValues[change.Id] = new Dictionary<string, object>();
}
if (change.NewValues != null)
change.NewValues.ToList().ForEach(kp => values[kp.Key] = kp.Value);
else if (change.OriginalValues != null)
change.OriginalValues.ToList().ForEach(kp => values[kp.Key] = kp.Value);
var label = deserializer.Deserialize<Label>(values);
if (activity.OccurredAt != DateTimeOffset.MinValue ||
(change.NewValues != null && !change.NewValues.ContainsKey("updated_at")))
{
label.UpdatedAt = activity.OccurredAt;
}
foundObjects.Add(label);
break;
}
default:
throw new Exception("Unhandled resource kind: " + change.Kind);
}
}
}
Assert.IsNotEmpty(foundObjects);
Assert.AreEqual(4, foundObjects.Where(o => o is Story).Count());
Assert.AreEqual(2, foundObjects.Where(o => o is Comment).Count());
Assert.AreEqual(2, foundObjects.Where(o => o is Task).Count());
Assert.AreEqual(2, foundObjects.Where(o => o is Label).Count());
}
private static void VerifyStory(Story expected, Story actual)
{
Assert.AreEqual(expected.Id, actual.Id);
Assert.AreEqual(expected.Name, actual.Name);
Assert.AreEqual(Constants.ProjectId, actual.ProjectId);
Assert.AreEqual(expected.RequestedById, actual.RequestedById);
Assert.AreEqual(expected.StoryType, actual.StoryType);
Assert.AreEqual(expected.Description, actual.Description);
Assert.AreEqual(expected.Estimate, actual.Estimate);
Assert.AreEqual(expected.Labels.Count, actual.Labels.Count);
Assert.AreEqual(expected.Labels, actual.Labels);
}
}
// ReSharper restore InconsistentNaming
}
| 47.244694
| 168
| 0.50802
|
[
"MIT"
] |
Charcoals/PivotalTracker.NET
|
PivotalTrackerDotNet.Tests/StoryServiceTest.cs
| 37,843
|
C#
|
using UnityEngine;
using UnityEngine.Events;
using System.Collections;
using System.Collections.Generic;
using VNToolkit.VNEditor.VNUtility;
namespace VNToolkit.VNEditor {
public class VNPanelManager {
// Public Variables
// Private Variables
// Static Variables
public static VNIPanel CurrentPanel { get; set; }
public static VN_EditorState VnEditorState { get { return vnEditorState; } }
private static VN_EditorState vnEditorState;
private static VNStartupEditor VNStartup { get; set; }
private static VNSetupEditor VNSetup { get; set; }
private static UnityAction Repaint;
public static void Initialize(UnityAction repaint) {
if (VNStartup == null) {
VNStartup = ScriptableObject.CreateInstance<VNStartupEditor>();
}
if (VNSetup == null) {
VNSetup = ScriptableObject.CreateInstance<VNSetupEditor>();
}
Repaint = repaint;
}
public static void DrawPanels(Rect position) {
VNPanelAbstract currentPanel = CurrentPanel as VNPanelAbstract;
if (currentPanel != null) {
currentPanel.OnPanelDraw(position);
}
}
public static void SetEditorState(VN_EditorState state) {
vnEditorState = state;
if (vnEditorState == VN_EditorState.STARTUP) {
VNStartup.OnPanelEnable(Repaint);
SetCurrentPanel(VNStartup);
VNMainEditor.VnWindow.SetWindowResolution(VNConstants.EDITOR_WINDOW_START_WIDTH, VNConstants.EDITOR_WINDOW_START_HEIGHT);
}
else if (vnEditorState == VN_EditorState.SETUP) {
VNSetup.OnPanelEnable(Repaint);
SetCurrentPanel(VNSetup);
VNMainEditor.VnWindow.SetWindowResolution(VNConstants.EDITOR_WINDOW_DEFAULT_WIDTH, VNConstants.EDITOR_WINDOW_DEFAULT_HEIGHT);
}
}
public static VNIPanel GetCurrentChild(string title) {
return CurrentPanel.GetChild(title);
}
private static void SetCurrentPanel(VNIPanel panel) {
if (CurrentPanel == panel)
return;
CurrentPanel = panel;
}
}
}
| 27.328571
| 129
| 0.751176
|
[
"MIT"
] |
pixelsquare/unity-tools
|
Assets/VN Toolkit/Scripts/Editor/Managers/VNPanelManager.cs
| 1,915
|
C#
|
// *** WARNING: this file was generated by the Pulumi Terraform Bridge (tfgen) Tool. ***
// *** Do not edit by hand unless you're certain you know what you are doing! ***
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Threading.Tasks;
using Pulumi.Serialization;
namespace Pulumi.Auth0.Outputs
{
[OutputType]
public sealed class ClientRefreshToken
{
/// <summary>
/// String. Options include `expiring`, `non-expiring`. Whether a refresh token will expire based on an absolute lifetime, after which the token can no longer be used. If rotation is `rotating`, this must be set to `expiring`.
/// </summary>
public readonly string ExpirationType;
/// <summary>
/// Integer. The time in seconds after which inactive refresh tokens will expire.
/// </summary>
public readonly int? IdleTokenLifetime;
/// <summary>
/// Boolean, (Default=false) Whether or not inactive refresh tokens should be remain valid indefinitely.
/// </summary>
public readonly bool? InfiniteIdleTokenLifetime;
/// <summary>
/// Boolean, (Default=false) Whether or not refresh tokens should remain valid indefinitely. If false, `token_lifetime` should also be set
/// </summary>
public readonly bool? InfiniteTokenLifetime;
/// <summary>
/// Integer. The amount of time in seconds in which a refresh token may be reused without trigging reuse detection.
/// </summary>
public readonly int? Leeway;
/// <summary>
/// String. Options include `rotating`, `non-rotating`. When `rotating`, exchanging a refresh token will cause a new refresh token to be issued and the existing token will be invalidated. This allows for automatic detection of token reuse if the token is leaked.
/// </summary>
public readonly string RotationType;
/// <summary>
/// Integer. The absolute lifetime of a refresh token in seconds.
/// </summary>
public readonly int? TokenLifetime;
[OutputConstructor]
private ClientRefreshToken(
string expirationType,
int? idleTokenLifetime,
bool? infiniteIdleTokenLifetime,
bool? infiniteTokenLifetime,
int? leeway,
string rotationType,
int? tokenLifetime)
{
ExpirationType = expirationType;
IdleTokenLifetime = idleTokenLifetime;
InfiniteIdleTokenLifetime = infiniteIdleTokenLifetime;
InfiniteTokenLifetime = infiniteTokenLifetime;
Leeway = leeway;
RotationType = rotationType;
TokenLifetime = tokenLifetime;
}
}
}
| 39.380282
| 270
| 0.648069
|
[
"ECL-2.0",
"Apache-2.0"
] |
kevinschoonover/pulumi-auth0
|
sdk/dotnet/Outputs/ClientRefreshToken.cs
| 2,796
|
C#
|
using EugenePetrenko.Gui2.MorseKernel2;
namespace EugenePetrenko.Gui2.Actions.ActionImpl.MS2D.Create
{
/// <summary>
/// Summary description for MS2DActionParameters.
/// </summary>
public class MS2DCreateActionParameters : ActionParameters
{
protected override IParameters LoadParameters(int[] factor)
{
return new MS2DCreateActionParametersImpl(factor);
}
public override string BoxCaption
{
get { return "Angle Method Projective Bundle Creation"; }
}
}
}
| 25.35
| 63
| 0.723866
|
[
"Apache-2.0"
] |
jonnyzzz/phd-project
|
morse/DotNet/guiActions/src/actionImpl/MS2D/Create/MS2DCreateActionParameters.cs
| 507
|
C#
|
using Adnc.Infra.Caching.Interceptor;
using System.Reflection;
using System.Text;
namespace Adnc.Infra.Core.Interceptor
{
/// <summary>
/// Default Adnc.Infra.Caching key generator.
/// </summary>
public class DefaultCachingKeyGenerator : ICachingKeyGenerator
{
private const char LinkChar = ':';
//public string GetCacheKey(MethodInfo methodInfo, object[] args, string prefix)
//{
// var methodArguments = args?.Any() == true
// ? args.Select(ParameterCacheKeys.GenerateCacheKey)
// : new[] { "0" };
// return GenerateCacheKey(methodInfo, prefix, methodArguments);
//}
public string GetCacheKey(MethodInfo methodInfo, object[] args, string prefix)
{
IEnumerable<string> methodArguments = new[] { "0" };
if (args?.Any() == true)
{
var cacheParams = methodInfo.GetParameters().Where(x => x.GetCustomAttribute<CachingParamAttribute>() != null)
.Select(x => x.Position);
if (cacheParams?.Any() == true)
methodArguments = args.Where(x => cacheParams.Contains(Array.IndexOf(args, x)))
.Select(ParameterCacheKeys.GenerateCacheKey);
else
methodArguments = args.Select(ParameterCacheKeys.GenerateCacheKey);
}
return GenerateCacheKey(methodInfo, prefix, methodArguments);
}
public string[] GetCacheKeys(MethodInfo methodInfo, object[] args, string prefix)
{
var cacheKeys = new List<string>();
if (args?.Any() == true && args[0].GetType().IsArray)
{
foreach (var arg0 in (Array)args[0])
{
var cloneArgs = (object[])args.Clone();
cloneArgs[0] = arg0;
cacheKeys.Add(GetCacheKey(methodInfo, cloneArgs, prefix));
}
}
else
{
cacheKeys.Add(GetCacheKey(methodInfo, args, prefix));
}
return cacheKeys.ToArray();
}
public string GetCacheKeyPrefix(MethodInfo methodInfo, string prefix)
{
if (!string.IsNullOrWhiteSpace(prefix)) return $"{prefix}{LinkChar}";
var typeName = methodInfo.DeclaringType?.Name;
var methodName = methodInfo.Name;
return $"{typeName}{LinkChar}{methodName}{LinkChar}";
}
private string GenerateCacheKey(MethodInfo methodInfo, string prefix, IEnumerable<string> parameters)
{
var cacheKeyPrefix = GetCacheKeyPrefix(methodInfo, prefix);
var builder = new StringBuilder();
builder.Append(cacheKeyPrefix);
builder.Append(string.Join(LinkChar.ToString(), parameters));
return builder.ToString();
}
}
}
| 38.974684
| 126
| 0.541085
|
[
"MIT"
] |
Jiayg/Adnc
|
src/ServerApi/Infrastructures/Adnc.Infra.Caching/Core/Interceptor/DefaultCachingKeyGenerator.cs
| 3,081
|
C#
|
using System;
using System.IO;
using System.IO.Abstractions;
using Kudu.Contracts.Tracing;
using Kudu.Core.Infrastructure;
using Kudu.Core.Tracing;
using Newtonsoft.Json;
namespace Kudu.Core.Jobs
{
public abstract class JobLogger : IJobLogger
{
private static readonly JsonSerializerSettings JsonSerializerSettings = new JsonSerializerSettings()
{
DefaultValueHandling = DefaultValueHandling.Ignore,
Formatting = Formatting.None,
MissingMemberHandling = MissingMemberHandling.Ignore,
NullValueHandling = NullValueHandling.Ignore,
PreserveReferencesHandling = PreserveReferencesHandling.None
};
protected IEnvironment Environment { get; private set; }
protected IFileSystem FileSystem { get; private set; }
protected ITraceFactory TraceFactory { get; private set; }
protected string InstanceId { get; private set; }
private string _statusFilePath;
private readonly string _statusFileName;
protected JobLogger(string statusFileName, IEnvironment environment, IFileSystem fileSystem, ITraceFactory traceFactory)
{
_statusFileName = statusFileName;
TraceFactory = traceFactory;
FileSystem = fileSystem;
Environment = environment;
InstanceId = InstanceIdUtility.GetShortInstanceId();
}
public abstract void LogError(string error);
public abstract void LogWarning(string warning);
public abstract void LogInformation(string message);
public abstract void LogStandardOutput(string message);
public abstract void LogStandardError(string message);
protected abstract string HistoryPath { get; }
protected string GetStatusFilePath()
{
if (_statusFilePath == null)
{
_statusFilePath = Path.Combine(HistoryPath, _statusFileName);
}
return _statusFilePath;
}
public TJobStatus GetStatus<TJobStatus>() where TJobStatus : class, IJobStatus
{
return ReadJobStatusFromFile<TJobStatus>(TraceFactory, FileSystem, GetStatusFilePath());
}
public void ReportStatus<TJobStatus>(TJobStatus status) where TJobStatus : class, IJobStatus
{
ReportStatus(status, logStatus: true);
}
protected void ReportStatus<TJobStatus>(TJobStatus status, bool logStatus) where TJobStatus : class, IJobStatus
{
try
{
string content = JsonConvert.SerializeObject(status, JsonSerializerSettings);
SafeLogToFile(GetStatusFilePath(), content, isAppend: false);
if (logStatus)
{
LogInformation("Status changed to " + status.Status);
}
}
catch (Exception ex)
{
TraceFactory.GetTracer().TraceError(ex);
}
}
public static TJobStatus ReadJobStatusFromFile<TJobStatus>(ITraceFactory traceFactory, IFileSystem fileSystem, string statusFilePath) where TJobStatus : class, IJobStatus
{
try
{
if (!fileSystem.File.Exists(statusFilePath))
{
return null;
}
return OperationManager.Attempt(() =>
{
string content = FileSystemHelpers.ReadAllTextFromFile(statusFilePath).Trim();
return JsonConvert.DeserializeObject<TJobStatus>(content, JsonSerializerSettings);
});
}
catch (Exception ex)
{
traceFactory.GetTracer().TraceError(ex);
return null;
}
}
protected void SafeLogToFile(string path, string content, bool isAppend = true)
{
try
{
if (isAppend)
{
OperationManager.Attempt(() => FileSystemHelpers.AppendAllTextToFile(path, content));
}
else
{
OperationManager.Attempt(() => FileSystemHelpers.WriteAllTextToFile(path, content));
}
}
catch (Exception ex)
{
TraceFactory.GetTracer().TraceError(ex);
}
}
protected enum Level
{
Info,
Warn,
Err
}
protected string GetFormattedMessage(Level level, string message, bool isSystem)
{
return isSystem
? "[{0} > {1}: SYS {2,-4}] {3}\r\n".FormatInvariant(DateTime.UtcNow, InstanceId, level.ToString().ToUpperInvariant(), message)
: "[{0} > {1}: {2,-4}] {3}\r\n".FormatInvariant(DateTime.UtcNow, InstanceId, level.ToString().ToUpperInvariant(), message);
}
}
}
| 33.601351
| 178
| 0.584758
|
[
"Apache-2.0"
] |
silentworks/kudu
|
Kudu.Core/Jobs/JobLogger.cs
| 4,975
|
C#
|
////////////////////////////////////////////////////////////////////////////////
//EF Core Provider for LCPI OLE DB.
// IBProvider and Contributors. 01.05.2021.
using System;
using System.Reflection;
namespace Lcpi.EntityFrameworkCore.DataProvider.LcpiOleDb.Basement.EF.Root.Query.Local.Expressions.Op2.Code{
////////////////////////////////////////////////////////////////////////////////
//using
using T_ARG1
=System.Nullable<System.Double>;
using T_ARG2
=System.Single;
using T_RESULT
=System.Nullable<System.Boolean>;
////////////////////////////////////////////////////////////////////////////////
//class Op2_Code__LessThan___NullableDouble__Single
static class Op2_Code__LessThan___NullableDouble__Single
{
public static readonly System.Reflection.MethodInfo MethodInfo_V_V
=typeof(Op2_Code__LessThan___NullableDouble__Single)
.GetTypeInfo()
.GetDeclaredMethod(nameof(Exec_V_V));
//-----------------------------------------------------------------------
private static T_RESULT Exec_V_V(T_ARG1 a,T_ARG2 b)
{
if(!a.HasValue)
return null;
return MasterCode.Op2_MasterCode__LessThan___Double__Double.Exec
(a.Value,
b);
}//Exec_V_V
};//class Op2_Code__LessThan___NullableDouble__Single
////////////////////////////////////////////////////////////////////////////////
}//namespace Lcpi.EntityFrameworkCore.DataProvider.LcpiOleDb.Basement.EF.Root.Query.Local.Expressions.Op2.Code
| 33.5
| 110
| 0.561058
|
[
"MIT"
] |
ibprovider/Lcpi.EFCore.LcpiOleDb
|
Code/Provider/Source/Basement/EF/Root/Query/Local/Expressions/Op2/Code/LessThan/NullableDouble/Op2_Code__LessThan___NullableDouble__Single.cs
| 1,476
|
C#
|
namespace SkbKontur.EdiApi.Client.Types.Messages.BoxEventsContents.Outbox
{
public class MessageCheckingFailEventContent : OutboxEventContentBase
{
public string[] Errors { get; set; }
public string ReportNumber { get; set; }
}
}
| 32.125
| 73
| 0.715953
|
[
"MIT"
] |
JTOne123/edi-api-client
|
EdiApi.Client/Types/Messages/BoxEventsContents/Outbox/MessageCheckingFailEventContent.cs
| 257
|
C#
|
using System;
using System.Collections;
using System.Linq;
using NUnit.Framework;
namespace Xamarin.Forms.Core.UnitTests
{
internal class NaiveLayout : Layout<View>
{
protected override void LayoutChildren (double x, double y, double width, double height)
{
foreach (var child in ((IElementController)this).LogicalChildren.Cast<View>()) {
var result = new Rectangle (x, y, 0, 0);
var request = child.GetSizeRequest (double.PositiveInfinity, double.PositiveInfinity);
result.Width = request.Request.Width;
result.Height = request.Request.Height;
child.Layout (result);
}
}
}
[TestFixture]
public class LayoutUnitTests : BaseTestFixture
{
[Test]
public void TestRaiseChild ()
{
var view = new NaiveLayout ();
var child1 = new View ();
var child2 = new View ();
var child3 = new View ();
view.Children.Add (child1);
view.Children.Add (child2);
view.Children.Add (child3);
bool reordered = false;
view.ChildrenReordered += (sender, args) => reordered = true;
view.RaiseChild (child1);
Assert.AreEqual (child1, ((IElementController)view).LogicalChildren [2]);
Assert.True (reordered);
view.RaiseChild (child2);
Assert.AreEqual (child2, ((IElementController)view).LogicalChildren [2]);
}
[Test]
public void TestRaiseUnownedChild ()
{
var view = new NaiveLayout ();
var child1 = new View ();
var child2 = new View ();
var child3 = new View ();
view.Children.Add (child1);
view.Children.Add (child3);
bool reordered = false;
view.ChildrenReordered += (sender, args) => reordered = true;
view.RaiseChild (child2);
Assert.False (reordered);
}
[Test]
public void TestLowerChild ()
{
var view = new NaiveLayout ();
var child1 = new View ();
var child2 = new View ();
var child3 = new View ();
view.Children.Add (child1);
view.Children.Add (child2);
view.Children.Add (child3);
bool reordered = false;
view.ChildrenReordered += (sender, args) => reordered = true;
view.LowerChild (child3);
Assert.AreEqual (child3, ((IElementController)view).LogicalChildren [0]);
Assert.True (reordered);
view.LowerChild (child2);
Assert.AreEqual (child2, ((IElementController)view).LogicalChildren [0]);
}
[Test]
public void TestLowerUnownedChild ()
{
var view = new NaiveLayout ();
var child1 = new View ();
var child2 = new View ();
var child3 = new View ();
view.Children.Add (child1);
view.Children.Add (child3);
bool reordered = false;
view.ChildrenReordered += (sender, args) => reordered = true;
view.LowerChild (child2);
Assert.False (reordered);
}
[Test]
public void TestAdd ()
{
var view = new NaiveLayout ();
var child1 = new View ();
bool added = false;
view.ChildAdded += (sender, args) => added = true;
view.Children.Add (child1);
Assert.True (added);
Assert.AreEqual (child1, ((IElementController)view).LogicalChildren [0]);
}
[Test]
public void TestDoubleAdd ()
{
var view = new NaiveLayout ();
var child1 = new View ();
view.Children.Add (child1);
bool added = false;
view.ChildAdded += (sender, args) => added = true;
view.Children.Add (child1);
Assert.False (added);
Assert.AreEqual (child1, ((IElementController)view).LogicalChildren [0]);
}
[Test]
public void TestRemove ()
{
var view = new NaiveLayout ();
var child1 = new View ();
view.Children.Add (child1);
bool removed = false;
view.ChildRemoved += (sender, args) => removed = true;
view.Children.Remove (child1);
Assert.True (removed);
Assert.False (((IElementController)view).LogicalChildren.Any ());
}
[Test]
public void TestGenericEnumerator ()
{
var view = new NaiveLayout ();
var children = new[] {
new View (),
new View (),
new View ()
};
foreach (var child in children)
view.Children.Add (child);
int i = 0;
foreach (var child in ((IElementController)view).LogicalChildren) {
Assert.AreEqual (children[i], child);
i++;
}
}
[Test]
public void TestEnumerator ()
{
var view = new NaiveLayout ();
var children = new [] {
new View (),
new View (),
new View ()
};
foreach (var child in children)
view.Children.Add (child);
int i = 0;
var enumerator = (((IElementController)view).LogicalChildren as IEnumerable).GetEnumerator ();
while (enumerator.MoveNext ()) {
Assert.AreEqual (children [i], enumerator.Current as View);
i++;
}
}
[Test]
public void TestInitializerSyntax ()
{
View view1, view2;
var group = new NaiveLayout {
Children = {
(view1 = new View ()),
(view2 = new View ())
}
};
Assert.AreEqual (2, ((IElementController)group).LogicalChildren.Count);
Assert.IsTrue (((IElementController)group).LogicalChildren.Contains (view1));
Assert.IsTrue (((IElementController)group).LogicalChildren.Contains (view2));
Assert.AreEqual (view1, ((IElementController)group).LogicalChildren[0]);
}
[Test]
public void TestChildren ()
{
View view1, view2;
var group = new NaiveLayout {
Children = {
(view1 = new View ()),
(view2 = new View ())
}
};
Assert.AreEqual (2, group.Children.Count);
Assert.IsTrue (group.Children.Contains (view1));
Assert.IsTrue (group.Children.Contains (view2));
Assert.AreEqual (view1, group.Children[0]);
}
[Test]
public void TestDefaultLayout ()
{
View view;
var group = new NaiveLayout {
IsPlatformEnabled = true,
Children = {
(view = new View {
WidthRequest = 50,
HeightRequest = 20,
IsPlatformEnabled = true,
})
}
};
group.Layout (new Rectangle (0, 0, 400, 400));
Assert.AreEqual (new Rectangle (0, 0, 50, 20), view.Bounds);
}
[Test]
public void ThrowsInvalidOperationOnSelfAdd ()
{
var group = new NaiveLayout ();
Assert.Throws<InvalidOperationException> (() => group.Children.Add (group));
}
[Test]
public void ReorderChildrenDoesNotRaiseChildAddedOrRemoved ()
{
var child1 = new BoxView ();
var child2 = new BoxView ();
var layout = new NaiveLayout {
Children = {child1, child2}
};
var added = false;
var removed = false;
layout.ChildAdded += (sender, args) => added = true;
layout.ChildRemoved += (sender, args) => removed = true;
layout.RaiseChild (child1);
Assert.False (added);
Assert.False (removed);
}
[Test]
public void AddToSecondLayoutRemovesFromOriginal()
{
var child = new BoxView();
var layout1 = new NaiveLayout();
var layout2 = new NaiveLayout();
layout1.Children.Add(child);
layout2.Children.Add(child);
Assert.False(layout1.Children.Contains(child));
}
}
}
| 22.289474
| 97
| 0.645661
|
[
"MIT"
] |
07101994/Xamarin.Forms
|
Xamarin.Forms.Core.UnitTests/GroupViewUnitTests.cs
| 6,776
|
C#
|
using System;
using System.Threading;
using System.Threading.Tasks;
using NUnit.Framework;
using Rebus.Activation;
using Rebus.Bus;
using Rebus.Config;
using Rebus.Exceptions;
using Rebus.Extensions;
using Rebus.Logging;
using Rebus.Messages;
using Rebus.Retry.Simple;
using Rebus.Routing.TypeBased;
using Rebus.Tests.Contracts;
using Rebus.Tests.Contracts.Extensions;
using Rebus.Transport.InMem;
using Rebus.Retry.FailFast;
using Rebus.Tests.Extensions;
#pragma warning disable 1998
namespace Rebus.Tests.Integration;
[TestFixture]
public class TestFailFast : FixtureBase
{
static readonly string InputQueueName = TestConfig.GetName($"test.rebus2.retries.input@{GetMachineName()}");
static readonly string ErrorQueueName = TestConfig.GetName("rebus2.error");
BuiltinHandlerActivator _handlerActivator;
IBus _bus;
InMemNetwork _network;
void InitializeBus(int numberOfRetries, IFailFastChecker failFastChecker = null)
{
_network = new InMemNetwork();
_handlerActivator = new BuiltinHandlerActivator();
_bus = Configure.With(_handlerActivator)
.Logging(l => l.Console(minLevel: LogLevel.Warn))
.Transport(t => t.UseInMemoryTransport(_network, InputQueueName))
.Routing(r => r.TypeBased().Map<string>(InputQueueName))
.Options(o =>
{
o.SetNumberOfWorkers(1);
o.SetMaxParallelism(1);
o.SimpleRetryStrategy(maxDeliveryAttempts: numberOfRetries, errorQueueAddress: ErrorQueueName);
if (failFastChecker != null)
{
o.Register(_ => failFastChecker);
}
})
.Start();
Using(_bus);
}
[Test]
public async Task ItWorks()
{
const int numberOfRetries = 5;
InitializeBus(numberOfRetries);
var attemptedDeliveries = 0;
_handlerActivator.AddHandlerWithBusTemporarilyStopped<string>(async _ =>
{
Interlocked.Increment(ref attemptedDeliveries);
throw new FailFastException("omgwtf!");
});
await _bus.Send("hej");
var failedMessage = await _network.WaitForNextMessageFrom(ErrorQueueName);
Assert.That(attemptedDeliveries, Is.EqualTo(1));
Assert.That(failedMessage.Headers.GetValue(Headers.ErrorDetails), Contains.Substring("1 unhandled exceptions"));
Assert.That(failedMessage.Headers.GetValue(Headers.SourceQueue), Is.EqualTo(InputQueueName));
}
[Test]
public async Task ItUsesSimpleRetryStrategyWhenCustomException()
{
const int numberOfRetries = 5;
InitializeBus(numberOfRetries);
var attemptedDeliveries = 0;
_handlerActivator.AddHandlerWithBusTemporarilyStopped<string>(async _ =>
{
Interlocked.Increment(ref attemptedDeliveries);
throw new InvalidOperationException("omgwtf!");
});
await _bus.Send("hej");
var failedMessage = await _network.WaitForNextMessageFrom(ErrorQueueName);
Assert.That(attemptedDeliveries, Is.EqualTo(numberOfRetries));
Assert.That(failedMessage.Headers.GetValue(Headers.ErrorDetails), Contains.Substring($"{numberOfRetries} unhandled exceptions"));
Assert.That(failedMessage.Headers.GetValue(Headers.SourceQueue), Is.EqualTo(InputQueueName));
}
[Test]
public async Task CanConfigureCustomFailFastChecker()
{
const int numberOfRetries = 5;
InitializeBus(numberOfRetries, new CustomFailFastChecker());
var attemptedDeliveries = 0;
_handlerActivator.AddHandlerWithBusTemporarilyStopped<string>(async _ =>
{
Interlocked.Increment(ref attemptedDeliveries);
throw new InvalidOperationException("omgwtf!");
});
await _bus.Send("hej");
var failedMessage = await _network.WaitForNextMessageFrom(ErrorQueueName);
Assert.That(attemptedDeliveries, Is.EqualTo(1));
Assert.That(failedMessage.Headers.GetValue(Headers.ErrorDetails), Contains.Substring("1 unhandled exceptions"));
Assert.That(failedMessage.Headers.GetValue(Headers.SourceQueue), Is.EqualTo(InputQueueName));
}
class CustomFailFastChecker : IFailFastChecker
{
public bool ShouldFailFast(string messageId, Exception exception)
{
return exception is InvalidOperationException;
}
}
static string GetMachineName() => Environment.MachineName;
}
| 31.922535
| 137
| 0.683212
|
[
"MIT"
] |
bog1978/Rebus
|
Rebus.Tests/Integration/TestFailFast.cs
| 4,535
|
C#
|
namespace Ray.Core
{
public interface IActorOwned<PrimaryKey>
{
PrimaryKey StateId { get; set; }
}
}
| 15.25
| 44
| 0.614754
|
[
"Apache-2.0"
] |
a8744965/Ray
|
src/Ray.Core/Core/Abstractions/IActorOwned.cs
| 124
|
C#
|
using System;
using System.Collections.Generic;
namespace KuzeyYeli.ORM.Models
{
public partial class Customer_and_Suppliers_by_City
{
public string City { get; set; }
public string CompanyName { get; set; }
public string ContactName { get; set; }
public string Relationship { get; set; }
}
}
| 24.142857
| 55
| 0.66568
|
[
"MIT"
] |
coshkun/KuzeyYeliWCF
|
KuzeyYeli/KuzeyYeli.ORM/Models/Customer_and_Suppliers_by_City.cs
| 338
|
C#
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.