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 System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace MZcms.Core { /// <summary> /// 依赖注入接口 /// </summary> public interface IinjectContainer { void RegisterType<T>(); T Resolve<T>(); } }
15.894737
37
0.629139
[ "MIT" ]
MiZoneRom/MZcms
MZcms/MZcms.Core/IOC/IIinjectContainer.cs
316
C#
using Soludus.Energy; using System.Collections; using System.Collections.Generic; using UnityEngine; public class EnergyValueProvider : MonoBehaviour, IValueProvider<float> { public EnergyValue value = null; public float GetValue() { return value.value; } public void InitValue() { } }
17.157895
71
0.696319
[ "CC0-1.0", "MIT" ]
Soludus/Soludus2Enercity
Assets/Soludus/VR Game/Value Providers/EnergyValueProvider.cs
328
C#
using System; using System.Collections.Generic; using System.Text; namespace WildFarm.Models { public class Seeds : Food { public Seeds(int quantity) : base(quantity) { } } }
14.1875
35
0.581498
[ "MIT" ]
Siafarikas/SoftUni
OOP/Polymorphism/WildFarm/Models/Food/Seeds.cs
229
C#
// Copyright (c) .NET Foundation. All rights reserved. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using System.Collections.Generic; using System.Data.Common; using System.Data.Entity; using System.Data.Entity.Infrastructure.Interception; using System.IO; using System.Linq; using System.Net; using System.Net.Http; using System.Net.Mail; using System.Security.Principal; using System.Threading; using System.Threading.Tasks; using System.Web; using System.Web.Hosting; using System.Web.Mvc; using AnglicanGeek.MarkdownMailer; using Autofac; using Autofac.Core; using Autofac.Extensions.DependencyInjection; using Elmah; using Microsoft.ApplicationInsights.Extensibility; using Microsoft.ApplicationInsights.Extensibility.Implementation; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Http; using Microsoft.Extensions.Logging; using Microsoft.WindowsAzure.ServiceRuntime; using NuGet.Services.Configuration; using NuGet.Services.Entities; using NuGet.Services.FeatureFlags; using NuGet.Services.KeyVault; using NuGet.Services.Licenses; using NuGet.Services.Logging; using NuGet.Services.Messaging; using NuGet.Services.Messaging.Email; using NuGet.Services.ServiceBus; using NuGet.Services.Sql; using NuGet.Services.Validation; using NuGetGallery.Areas.Admin; using NuGetGallery.Areas.Admin.Models; using NuGetGallery.Areas.Admin.Services; using NuGetGallery.Auditing; using NuGetGallery.Authentication; using NuGetGallery.Configuration; using NuGetGallery.Cookies; using NuGetGallery.Diagnostics; using NuGetGallery.Features; using NuGetGallery.Helpers; using NuGetGallery.Infrastructure; using NuGetGallery.Infrastructure.Authentication; using NuGetGallery.Infrastructure.Lucene; using NuGetGallery.Infrastructure.Mail; using NuGetGallery.Infrastructure.Search; using NuGetGallery.Infrastructure.Search.Correlation; using NuGetGallery.Security; using NuGetGallery.Services; using Role = NuGet.Services.Entities.Role; using SecretReaderFactory = NuGetGallery.Configuration.SecretReader.SecretReaderFactory; namespace NuGetGallery { public class DefaultDependenciesModule : Module { public static class BindingKeys { public const string AsyncDeleteAccountName = "AsyncDeleteAccountService"; public const string SyncDeleteAccountName = "SyncDeleteAccountService"; public const string AccountDeleterTopic = "AccountDeleterBindingKey"; public const string PackageValidationTopic = "PackageValidationBindingKey"; public const string SymbolsPackageValidationTopic = "SymbolsPackageValidationBindingKey"; public const string PackageValidationEnqueuer = "PackageValidationEnqueuerBindingKey"; public const string SymbolsPackageValidationEnqueuer = "SymbolsPackageValidationEnqueuerBindingKey"; public const string EmailPublisherTopic = "EmailPublisherBindingKey"; public const string PreviewSearchClient = "PreviewSearchClientBindingKey"; } public static class ParameterNames { public const string PackagesController_PreviewSearchService = "previewSearchService"; } protected override void Load(ContainerBuilder builder) { var services = new ServiceCollection(); var configuration = new ConfigurationService(); var secretReaderFactory = new SecretReaderFactory(configuration); var secretReader = secretReaderFactory.CreateSecretReader(); var secretInjector = secretReaderFactory.CreateSecretInjector(secretReader); builder.RegisterInstance(secretInjector) .AsSelf() .As<ISecretInjector>() .SingleInstance(); configuration.SecretInjector = secretInjector; // Register the ILoggerFactory and configure AppInsights. var applicationInsightsConfiguration = ConfigureApplicationInsights( configuration.Current, out ITelemetryClient telemetryClient); var loggerConfiguration = LoggingSetup.CreateDefaultLoggerConfiguration(withConsoleLogger: false); var loggerFactory = LoggingSetup.CreateLoggerFactory( loggerConfiguration, telemetryConfiguration: applicationInsightsConfiguration.TelemetryConfiguration); builder.RegisterInstance(applicationInsightsConfiguration.TelemetryConfiguration) .AsSelf() .SingleInstance(); builder.RegisterInstance(telemetryClient) .AsSelf() .As<ITelemetryClient>() .SingleInstance(); var diagnosticsService = new DiagnosticsService(telemetryClient); builder.RegisterInstance(diagnosticsService) .AsSelf() .As<IDiagnosticsService>() .SingleInstance(); services.AddSingleton(loggerFactory); services.AddSingleton(typeof(ILogger<>), typeof(Logger<>)); UrlHelperExtensions.SetConfigurationService(configuration); builder.RegisterInstance(configuration) .AsSelf() .As<IConfigurationFactory>() .As<IGalleryConfigurationService>(); builder.Register(c => configuration.Current) .AsSelf() .AsImplementedInterfaces(); // Force the read of this configuration, so it will be initialized on startup builder.Register(c => configuration.Features) .AsSelf() .As<FeatureConfiguration>(); builder.Register(c => configuration.PackageDelete) .As<IPackageDeleteConfiguration>(); var telemetryService = new TelemetryService( new TraceDiagnosticsSource(nameof(TelemetryService), telemetryClient), telemetryClient); builder.RegisterInstance(telemetryService) .AsSelf() .As<ITelemetryService>() .As<IFeatureFlagTelemetryService>() .SingleInstance(); builder.RegisterType<CredentialBuilder>().As<ICredentialBuilder>().SingleInstance(); builder.RegisterType<CredentialValidator>().As<ICredentialValidator>().SingleInstance(); builder.RegisterInstance(LuceneCommon.GetDirectory(configuration.Current.LuceneIndexLocation)) .As<Lucene.Net.Store.Directory>() .SingleInstance(); ConfigureSearch(loggerFactory, configuration, telemetryService, services, builder); builder.RegisterType<DateTimeProvider>().AsSelf().As<IDateTimeProvider>().SingleInstance(); builder.RegisterType<HttpContextCacheService>() .AsSelf() .As<ICacheService>() .InstancePerLifetimeScope(); DbInterception.Add(new QueryHintInterceptor()); var galleryDbConnectionFactory = CreateDbConnectionFactory( loggerFactory, nameof(EntitiesContext), configuration.Current.SqlConnectionString, secretInjector); builder.RegisterInstance(galleryDbConnectionFactory) .AsSelf() .As<ISqlConnectionFactory>() .SingleInstance(); builder.Register(c => new EntitiesContext(CreateDbConnection(galleryDbConnectionFactory), configuration.Current.ReadOnlyMode)) .AsSelf() .As<IEntitiesContext>() .As<DbContext>() .InstancePerLifetimeScope(); builder.RegisterType<EntityRepository<User>>() .AsSelf() .As<IEntityRepository<User>>() .InstancePerLifetimeScope(); builder.RegisterType<EntityRepository<Role>>() .AsSelf() .As<IEntityRepository<Role>>() .InstancePerLifetimeScope(); builder.RegisterType<EntityRepository<ReservedNamespace>>() .AsSelf() .As<IEntityRepository<ReservedNamespace>>() .InstancePerLifetimeScope(); builder.RegisterType<EntityRepository<PackageRegistration>>() .AsSelf() .As<IEntityRepository<PackageRegistration>>() .InstancePerLifetimeScope(); builder.RegisterType<EntityRepository<Package>>() .AsSelf() .As<IEntityRepository<Package>>() .InstancePerLifetimeScope(); builder.RegisterType<EntityRepository<PackageDependency>>() .AsSelf() .As<IEntityRepository<PackageDependency>>() .InstancePerLifetimeScope(); builder.RegisterType<EntityRepository<PackageDelete>>() .AsSelf() .As<IEntityRepository<PackageDelete>>() .InstancePerLifetimeScope(); builder.RegisterType<EntityRepository<Certificate>>() .AsSelf() .As<IEntityRepository<Certificate>>() .InstancePerLifetimeScope(); builder.RegisterType<EntityRepository<AccountDelete>>() .AsSelf() .As<IEntityRepository<AccountDelete>>() .InstancePerLifetimeScope(); builder.RegisterType<EntityRepository<Credential>>() .AsSelf() .As<IEntityRepository<Credential>>() .InstancePerLifetimeScope(); builder.RegisterType<EntityRepository<Scope>>() .AsSelf() .As<IEntityRepository<Scope>>() .InstancePerLifetimeScope(); builder.RegisterType<EntityRepository<PackageOwnerRequest>>() .AsSelf() .As<IEntityRepository<PackageOwnerRequest>>() .InstancePerLifetimeScope(); builder.RegisterType<EntityRepository<Organization>>() .AsSelf() .As<IEntityRepository<Organization>>() .InstancePerLifetimeScope(); builder.RegisterType<EntityRepository<SymbolPackage>>() .AsSelf() .As<IEntityRepository<SymbolPackage>>() .InstancePerLifetimeScope(); builder.RegisterType<EntityRepository<PackageDeprecation>>() .AsSelf() .As<IEntityRepository<PackageDeprecation>>() .InstancePerLifetimeScope(); builder.RegisterType<EntityRepository<PackageRename>>() .AsSelf() .As<IEntityRepository<PackageRename>>() .InstancePerLifetimeScope(); ConfigureGalleryReadOnlyReplicaEntitiesContext(builder, loggerFactory, configuration, secretInjector); var supportDbConnectionFactory = CreateDbConnectionFactory( loggerFactory, nameof(SupportRequestDbContext), configuration.Current.SqlConnectionStringSupportRequest, secretInjector); builder.Register(c => new SupportRequestDbContext(CreateDbConnection(supportDbConnectionFactory))) .AsSelf() .As<ISupportRequestDbContext>() .InstancePerLifetimeScope(); builder.RegisterType<SupportRequestService>() .AsSelf() .As<ISupportRequestService>() .InstancePerLifetimeScope(); builder.RegisterType<UserService>() .AsSelf() .As<IUserService>() .InstancePerLifetimeScope(); builder.RegisterType<PackageService>() .AsSelf() .As<IPackageService>() .InstancePerLifetimeScope(); builder.RegisterType<PackageFilter>() .AsSelf() .As<IPackageFilter>() .InstancePerLifetimeScope(); builder.RegisterType<PackageDeleteService>() .AsSelf() .As<IPackageDeleteService>() .InstancePerLifetimeScope(); RegisterDeleteAccountService(builder, configuration); builder.RegisterType<PackageOwnerRequestService>() .AsSelf() .As<IPackageOwnerRequestService>() .InstancePerLifetimeScope(); builder.RegisterType<FormsAuthenticationService>() .As<IFormsAuthenticationService>() .InstancePerLifetimeScope(); builder.RegisterType<CookieTempDataProvider>() .As<ITempDataProvider>() .InstancePerLifetimeScope(); builder.RegisterType<StatusService>() .AsSelf() .As<IStatusService>() .InstancePerLifetimeScope(); builder.RegisterType<SecurityPolicyService>() .AsSelf() .As<ISecurityPolicyService>() .InstancePerLifetimeScope(); builder.RegisterType<ReservedNamespaceService>() .AsSelf() .As<IReservedNamespaceService>() .InstancePerLifetimeScope(); builder.RegisterType<SymbolPackageService>() .AsSelf() .As<ISymbolPackageService>() .InstancePerLifetimeScope(); builder.RegisterType<PackageUploadService>() .AsSelf() .As<IPackageUploadService>() .InstancePerLifetimeScope(); builder.RegisterType<SymbolPackageUploadService>() .AsSelf() .As<ISymbolPackageUploadService>() .InstancePerLifetimeScope(); builder.RegisterType<PackageOwnershipManagementService>() .AsSelf() .As<IPackageOwnershipManagementService>() .InstancePerLifetimeScope(); builder.RegisterType<ValidationService>() .AsSelf() .As<IValidationService>() .InstancePerLifetimeScope(); builder.RegisterType<ReadMeService>() .AsSelf() .As<IReadMeService>() .InstancePerLifetimeScope(); builder.RegisterType<ApiScopeEvaluator>() .AsSelf() .As<IApiScopeEvaluator>() .InstancePerLifetimeScope(); builder.RegisterType<ContentObjectService>() .AsSelf() .As<IContentObjectService>() .SingleInstance(); builder.RegisterType<CertificateValidator>() .AsSelf() .As<ICertificateValidator>() .SingleInstance(); builder.RegisterType<CertificateService>() .AsSelf() .As<ICertificateService>() .InstancePerLifetimeScope(); builder.RegisterType<TyposquattingService>() .AsSelf() .As<ITyposquattingService>() .InstancePerLifetimeScope(); builder.RegisterType<TyposquattingCheckListCacheService>() .AsSelf() .As<ITyposquattingCheckListCacheService>() .SingleInstance(); builder.RegisterType<LicenseExpressionSplitter>() .As<ILicenseExpressionSplitter>() .InstancePerLifetimeScope(); builder.RegisterType<LicenseExpressionParser>() .As<ILicenseExpressionParser>() .InstancePerLifetimeScope(); builder.RegisterType<LicenseExpressionSegmentator>() .As<ILicenseExpressionSegmentator>() .InstancePerLifetimeScope(); builder.RegisterType<PackageDeprecationManagementService>() .As<IPackageDeprecationManagementService>() .InstancePerLifetimeScope(); builder.RegisterType<PackageDeprecationService>() .As<IPackageDeprecationService>() .InstancePerLifetimeScope(); builder.RegisterType<PackageRenameService>() .As<IPackageRenameService>() .InstancePerLifetimeScope(); builder.RegisterType<PackageUpdateService>() .As<IPackageUpdateService>() .InstancePerLifetimeScope(); builder.RegisterType<GalleryCloudBlobContainerInformationProvider>() .As<ICloudBlobContainerInformationProvider>() .InstancePerLifetimeScope(); builder.RegisterType<ConfigurationIconFileProvider>() .As<IIconUrlProvider>() .InstancePerLifetimeScope(); builder.RegisterType<IconUrlTemplateProcessor>() .As<IIconUrlTemplateProcessor>() .InstancePerLifetimeScope(); builder.RegisterType<PackageVulnerabilityService>() .As<IPackageVulnerabilityService>() .InstancePerLifetimeScope(); services.AddHttpClient(); services.AddScoped<IGravatarProxyService, GravatarProxyService>(); RegisterFeatureFlagsService(builder, configuration); RegisterMessagingService(builder, configuration); builder.Register(c => HttpContext.Current.User) .AsSelf() .As<IPrincipal>() .InstancePerLifetimeScope(); IAuditingService defaultAuditingService = null; switch (configuration.Current.StorageType) { case StorageType.FileSystem: case StorageType.NotSpecified: ConfigureForLocalFileSystem(builder, configuration); defaultAuditingService = GetAuditingServiceForLocalFileSystem(configuration); break; case StorageType.AzureStorage: ConfigureForAzureStorage(builder, configuration, telemetryService); defaultAuditingService = GetAuditingServiceForAzureStorage(builder, configuration); break; } RegisterAsynchronousValidation(builder, loggerFactory, configuration, secretInjector); RegisterAuditingServices(builder, defaultAuditingService); RegisterCookieComplianceService(builder, configuration, diagnosticsService); RegisterABTestServices(builder); builder.RegisterType<MicrosoftTeamSubscription>() .AsSelf() .InstancePerLifetimeScope(); if (configuration.Current.Environment == ServicesConstants.DevelopmentEnvironment) { builder.RegisterType<AllowLocalHttpRedirectPolicy>() .As<ISourceDestinationRedirectPolicy>() .InstancePerLifetimeScope(); } else { builder.RegisterType<NoLessSecureDestinationRedirectPolicy>() .As<ISourceDestinationRedirectPolicy>() .InstancePerLifetimeScope(); } ConfigureAutocomplete(builder, configuration); builder.Populate(services); } // Internal for testing purposes internal static ApplicationInsightsConfiguration ConfigureApplicationInsights( IAppConfiguration configuration, out ITelemetryClient telemetryClient) { var instrumentationKey = configuration.AppInsightsInstrumentationKey; var heartbeatIntervalSeconds = configuration.AppInsightsHeartbeatIntervalSeconds; ApplicationInsightsConfiguration applicationInsightsConfiguration; if (heartbeatIntervalSeconds > 0) { applicationInsightsConfiguration = ApplicationInsights.Initialize( instrumentationKey, TimeSpan.FromSeconds(heartbeatIntervalSeconds)); } else { applicationInsightsConfiguration = ApplicationInsights.Initialize(instrumentationKey); } var telemetryConfiguration = applicationInsightsConfiguration.TelemetryConfiguration; // Add enrichers try { if (RoleEnvironment.IsAvailable) { telemetryConfiguration.TelemetryInitializers.Add( new DeploymentIdTelemetryEnricher(RoleEnvironment.DeploymentId)); } } catch { // This likely means the cloud service runtime is not available. } if (configuration.DeploymentLabel != null) { telemetryConfiguration.TelemetryInitializers.Add(new DeploymentLabelEnricher(configuration.DeploymentLabel)); } telemetryConfiguration.TelemetryInitializers.Add(new ClientInformationTelemetryEnricher()); telemetryConfiguration.TelemetryInitializers.Add(new KnownOperationNameEnricher()); telemetryConfiguration.TelemetryInitializers.Add(new AzureWebAppTelemetryInitializer()); telemetryConfiguration.TelemetryInitializers.Add(new CustomerResourceIdEnricher()); // Add processors telemetryConfiguration.TelemetryProcessorChainBuilder.Use(next => { var processor = new RequestTelemetryProcessor(next); processor.SuccessfulResponseCodes.Add(400); processor.SuccessfulResponseCodes.Add(404); processor.SuccessfulResponseCodes.Add(405); return processor; }); telemetryConfiguration.TelemetryProcessorChainBuilder.Use(next => new ClientTelemetryPIIProcessor(next)); // Hook-up TelemetryModules manually... RegisterApplicationInsightsTelemetryModules(telemetryConfiguration); var telemetryClientWrapper = TelemetryClientWrapper.UseTelemetryConfiguration(applicationInsightsConfiguration.TelemetryConfiguration); telemetryConfiguration.TelemetryProcessorChainBuilder.Use( next => new ExceptionTelemetryProcessor(next, telemetryClientWrapper.UnderlyingClient)); // Note: sampling rate must be a factor 100/N where N is a whole number // e.g.: 50 (= 100/2), 33.33 (= 100/3), 25 (= 100/4), ... // https://azure.microsoft.com/en-us/documentation/articles/app-insights-sampling/ var instrumentationSamplingPercentage = configuration.AppInsightsSamplingPercentage; if (instrumentationSamplingPercentage > 0 && instrumentationSamplingPercentage < 100) { telemetryConfiguration.TelemetryProcessorChainBuilder.UseSampling(instrumentationSamplingPercentage); } telemetryConfiguration.TelemetryProcessorChainBuilder.Build(); QuietLog.UseTelemetryClient(telemetryClientWrapper); telemetryClient = telemetryClientWrapper; return applicationInsightsConfiguration; } private static void RegisterApplicationInsightsTelemetryModules(TelemetryConfiguration configuration) { RegisterApplicationInsightsTelemetryModule( new Microsoft.ApplicationInsights.WindowsServer.AppServicesHeartbeatTelemetryModule(), configuration); RegisterApplicationInsightsTelemetryModule( new Microsoft.ApplicationInsights.WindowsServer.AzureInstanceMetadataTelemetryModule(), configuration); RegisterApplicationInsightsTelemetryModule( new Microsoft.ApplicationInsights.WindowsServer.DeveloperModeWithDebuggerAttachedTelemetryModule(), configuration); RegisterApplicationInsightsTelemetryModule( new Microsoft.ApplicationInsights.WindowsServer.UnhandledExceptionTelemetryModule(), configuration); RegisterApplicationInsightsTelemetryModule( new Microsoft.ApplicationInsights.WindowsServer.UnobservedExceptionTelemetryModule(), configuration); var requestTrackingModule = new Microsoft.ApplicationInsights.Web.RequestTrackingTelemetryModule(); requestTrackingModule.Handlers.Add("Microsoft.VisualStudio.Web.PageInspector.Runtime.Tracing.RequestDataHttpHandler"); requestTrackingModule.Handlers.Add("System.Web.StaticFileHandler"); requestTrackingModule.Handlers.Add("System.Web.Handlers.AssemblyResourceLoader"); requestTrackingModule.Handlers.Add("System.Web.Optimization.BundleHandler"); requestTrackingModule.Handlers.Add("System.Web.Script.Services.ScriptHandlerFactory"); requestTrackingModule.Handlers.Add("System.Web.Handlers.TraceHandler"); requestTrackingModule.Handlers.Add("System.Web.Services.Discovery.DiscoveryRequestHandler"); requestTrackingModule.Handlers.Add("System.Web.HttpDebugHandler"); RegisterApplicationInsightsTelemetryModule( requestTrackingModule, configuration); RegisterApplicationInsightsTelemetryModule( new Microsoft.ApplicationInsights.Web.ExceptionTrackingTelemetryModule(), configuration); RegisterApplicationInsightsTelemetryModule( new Microsoft.ApplicationInsights.Web.AspNetDiagnosticTelemetryModule(), configuration); var dependencyTrackingModule = new Microsoft.ApplicationInsights.DependencyCollector.DependencyTrackingTelemetryModule(); dependencyTrackingModule.ExcludeComponentCorrelationHttpHeadersOnDomains.Add("core.windows.net"); dependencyTrackingModule.ExcludeComponentCorrelationHttpHeadersOnDomains.Add("core.chinacloudapi.cn"); dependencyTrackingModule.ExcludeComponentCorrelationHttpHeadersOnDomains.Add("core.cloudapi.de"); dependencyTrackingModule.ExcludeComponentCorrelationHttpHeadersOnDomains.Add("core.usgovcloudapi.net"); dependencyTrackingModule.IncludeDiagnosticSourceActivities.Add("Microsoft.Azure.EventHubs"); dependencyTrackingModule.IncludeDiagnosticSourceActivities.Add("Microsoft.Azure.ServiceBus"); RegisterApplicationInsightsTelemetryModule( dependencyTrackingModule, configuration); RegisterApplicationInsightsTelemetryModule( new Microsoft.ApplicationInsights.Extensibility.PerfCounterCollector.PerformanceCollectorModule(), configuration); RegisterApplicationInsightsTelemetryModule( new Microsoft.ApplicationInsights.Extensibility.PerfCounterCollector.QuickPulse.QuickPulseTelemetryModule(), configuration); } private static void RegisterApplicationInsightsTelemetryModule(ITelemetryModule telemetryModule, TelemetryConfiguration configuration) { var existingModule = TelemetryModules.Instance.Modules.SingleOrDefault(m => m.GetType().Equals(telemetryModule.GetType())); if (existingModule != null) { TelemetryModules.Instance.Modules.Remove(existingModule); } telemetryModule.Initialize(configuration); TelemetryModules.Instance.Modules.Add(telemetryModule); } private void RegisterABTestServices(ContainerBuilder builder) { builder .RegisterType<ABTestEnrollmentFactory>() .As<IABTestEnrollmentFactory>(); builder .RegisterType<CookieBasedABTestService>() .As<IABTestService>(); } private static void RegisterDeleteAccountService(ContainerBuilder builder, ConfigurationService configuration) { if (configuration.Current.AsynchronousDeleteAccountServiceEnabled) { RegisterSwitchingDeleteAccountService(builder, configuration); } else { builder.RegisterType<DeleteAccountService>() .AsSelf() .As<IDeleteAccountService>() .InstancePerLifetimeScope(); } } private static void RegisterSwitchingDeleteAccountService(ContainerBuilder builder, ConfigurationService configuration) { var asyncAccountDeleteConnectionString = configuration.ServiceBus.AccountDeleter_ConnectionString; var asyncAccountDeleteTopicName = configuration.ServiceBus.AccountDeleter_TopicName; builder .Register(c => new TopicClientWrapper(asyncAccountDeleteConnectionString, asyncAccountDeleteTopicName)) .SingleInstance() .Keyed<ITopicClient>(BindingKeys.AccountDeleterTopic) .OnRelease(x => x.Close()); builder .RegisterType<AsynchronousDeleteAccountService>() .WithParameter(new ResolvedParameter( (pi, ctx) => pi.ParameterType == typeof(ITopicClient), (pi, ctx) => ctx.ResolveKeyed<ITopicClient>(BindingKeys.AccountDeleterTopic))); builder.RegisterType<DeleteAccountService>(); builder.RegisterType<AccountDeleteMessageSerializer>() .As<IBrokeredMessageSerializer<AccountDeleteMessage>>(); builder .Register<IDeleteAccountService>(c => { var featureFlagService = c.Resolve<IFeatureFlagService>(); if (featureFlagService.IsAsyncAccountDeleteEnabled()) { return c.Resolve<AsynchronousDeleteAccountService>(); } return c.Resolve<DeleteAccountService>(); }) .InstancePerLifetimeScope(); } private static void RegisterFeatureFlagsService(ContainerBuilder builder, ConfigurationService configuration) { builder .Register(context => new FeatureFlagOptions { RefreshInterval = configuration.Current.FeatureFlagsRefreshInterval, }) .AsSelf() .SingleInstance(); builder .Register(context => context.Resolve<EditableFeatureFlagFileStorageService>()) .As<IEditableFeatureFlagStorageService>() .SingleInstance(); builder .RegisterType<FeatureFlagCacheService>() .As<IFeatureFlagCacheService>() .SingleInstance(); builder .RegisterType<FeatureFlagClient>() .As<IFeatureFlagClient>() .SingleInstance(); builder .RegisterType<FeatureFlagService>() .As<IFeatureFlagService>() .SingleInstance(); } private static void RegisterMessagingService(ContainerBuilder builder, ConfigurationService configuration) { if (configuration.Current.AsynchronousEmailServiceEnabled) { // Register NuGet.Services.Messaging infrastructure RegisterAsynchronousEmailMessagingService(builder, configuration); } else { // Register legacy SMTP messaging infrastructure RegisterSmtpEmailMessagingService(builder, configuration); } } private static void RegisterSmtpEmailMessagingService(ContainerBuilder builder, ConfigurationService configuration) { MailSender mailSenderFactory() { var settings = configuration; if (settings.Current.SmtpUri != null && settings.Current.SmtpUri.IsAbsoluteUri) { var smtpUri = new SmtpUri(settings.Current.SmtpUri); var mailSenderConfiguration = new MailSenderConfiguration { DeliveryMethod = SmtpDeliveryMethod.Network, Host = smtpUri.Host, Port = smtpUri.Port, EnableSsl = smtpUri.Secure }; if (!string.IsNullOrWhiteSpace(smtpUri.UserName)) { mailSenderConfiguration.UseDefaultCredentials = false; mailSenderConfiguration.Credentials = new NetworkCredential( smtpUri.UserName, smtpUri.Password); } return new MailSender(mailSenderConfiguration); } else { var mailSenderConfiguration = new MailSenderConfiguration { DeliveryMethod = SmtpDeliveryMethod.SpecifiedPickupDirectory, PickupDirectoryLocation = HostingEnvironment.MapPath("~/App_Data/Mail") }; return new MailSender(mailSenderConfiguration); } } builder.Register(c => mailSenderFactory()) .AsSelf() .As<IMailSender>() .InstancePerDependency(); builder.RegisterType<BackgroundMarkdownMessageService>() .AsSelf() .As<IMessageService>() .InstancePerDependency(); } private static void RegisterAsynchronousEmailMessagingService(ContainerBuilder builder, ConfigurationService configuration) { builder .RegisterType<NuGet.Services.Messaging.ServiceBusMessageSerializer>() .As<NuGet.Services.Messaging.IServiceBusMessageSerializer>(); var emailPublisherConnectionString = configuration.ServiceBus.EmailPublisher_ConnectionString; var emailPublisherTopicName = configuration.ServiceBus.EmailPublisher_TopicName; builder .Register(c => new TopicClientWrapper(emailPublisherConnectionString, emailPublisherTopicName)) .As<ITopicClient>() .SingleInstance() .Keyed<ITopicClient>(BindingKeys.EmailPublisherTopic) .OnRelease(x => x.Close()); builder .RegisterType<EmailMessageEnqueuer>() .WithParameter(new ResolvedParameter( (pi, ctx) => pi.ParameterType == typeof(ITopicClient), (pi, ctx) => ctx.ResolveKeyed<ITopicClient>(BindingKeys.EmailPublisherTopic))) .As<IEmailMessageEnqueuer>(); builder.RegisterType<AsynchronousEmailMessageService>() .AsSelf() .As<IMessageService>() .InstancePerDependency(); } private static ISqlConnectionFactory CreateDbConnectionFactory( ILoggerFactory loggerFactory, string name, string connectionString, ISecretInjector secretInjector) { var logger = loggerFactory.CreateLogger($"AzureSqlConnectionFactory-{name}"); return new AzureSqlConnectionFactory(connectionString, secretInjector, logger); } private static DbConnection CreateDbConnection(ISqlConnectionFactory connectionFactory) { return Task.Run(() => connectionFactory.CreateAsync()).Result; } private static void ConfigureGalleryReadOnlyReplicaEntitiesContext( ContainerBuilder builder, ILoggerFactory loggerFactory, ConfigurationService configuration, ISecretInjector secretInjector) { var galleryDbReadOnlyReplicaConnectionFactory = CreateDbConnectionFactory( loggerFactory, nameof(ReadOnlyEntitiesContext), configuration.Current.SqlReadOnlyReplicaConnectionString ?? configuration.Current.SqlConnectionString, secretInjector); builder.Register(c => new ReadOnlyEntitiesContext(CreateDbConnection(galleryDbReadOnlyReplicaConnectionFactory))) .As<IReadOnlyEntitiesContext>() .InstancePerLifetimeScope(); builder.RegisterType<ReadOnlyEntityRepository<Package>>() .As<IReadOnlyEntityRepository<Package>>() .InstancePerLifetimeScope(); } private static void ConfigureValidationEntitiesContext( ContainerBuilder builder, ILoggerFactory loggerFactory, ConfigurationService configuration, ISecretInjector secretInjector) { var validationDbConnectionFactory = CreateDbConnectionFactory( loggerFactory, nameof(ValidationEntitiesContext), configuration.Current.SqlConnectionStringValidation, secretInjector); builder.Register(c => new ValidationEntitiesContext(CreateDbConnection(validationDbConnectionFactory))) .AsSelf() .InstancePerLifetimeScope(); builder.RegisterType<ValidationEntityRepository<PackageValidationSet>>() .As<IEntityRepository<PackageValidationSet>>() .InstancePerLifetimeScope(); builder.RegisterType<ValidationEntityRepository<PackageValidation>>() .As<IEntityRepository<PackageValidation>>() .InstancePerLifetimeScope(); builder.RegisterType<ValidationEntityRepository<PackageRevalidation>>() .As<IEntityRepository<PackageRevalidation>>() .InstancePerLifetimeScope(); } private void RegisterAsynchronousValidation( ContainerBuilder builder, ILoggerFactory loggerFactory, ConfigurationService configuration, ISecretInjector secretInjector) { builder .RegisterType<NuGet.Services.Validation.ServiceBusMessageSerializer>() .As<NuGet.Services.Validation.IServiceBusMessageSerializer>(); // We need to setup two enqueuers for Package validation and symbol validation each publishes // to a different topic for validation. builder .RegisterType<PackageValidationEnqueuer>() .WithParameter(new ResolvedParameter( (pi, ctx) => pi.ParameterType == typeof(ITopicClient), (pi, ctx) => ctx.ResolveKeyed<ITopicClient>(BindingKeys.PackageValidationTopic))) .Keyed<IPackageValidationEnqueuer>(BindingKeys.PackageValidationEnqueuer) .As<IPackageValidationEnqueuer>(); builder .RegisterType<PackageValidationEnqueuer>() .WithParameter(new ResolvedParameter( (pi, ctx) => pi.ParameterType == typeof(ITopicClient), (pi, ctx) => ctx.ResolveKeyed<ITopicClient>(BindingKeys.SymbolsPackageValidationTopic))) .Keyed<IPackageValidationEnqueuer>(BindingKeys.SymbolsPackageValidationEnqueuer) .As<IPackageValidationEnqueuer>(); if (configuration.Current.AsynchronousPackageValidationEnabled) { ConfigureValidationEntitiesContext(builder, loggerFactory, configuration, secretInjector); builder .Register(c => { return new AsynchronousPackageValidationInitiator<Package>( c.ResolveKeyed<IPackageValidationEnqueuer>(BindingKeys.PackageValidationEnqueuer), c.Resolve<IAppConfiguration>(), c.Resolve<IDiagnosticsService>()); }).As<IPackageValidationInitiator<Package>>(); builder .Register(c => { return new AsynchronousPackageValidationInitiator<SymbolPackage>( c.ResolveKeyed<IPackageValidationEnqueuer>(BindingKeys.SymbolsPackageValidationEnqueuer), c.Resolve<IAppConfiguration>(), c.Resolve<IDiagnosticsService>()); }).As<IPackageValidationInitiator<SymbolPackage>>(); // we retrieve the values here (on main thread) because otherwise it would run in another thread // and potentially cause a deadlock on async operation. var validationConnectionString = configuration.ServiceBus.Validation_ConnectionString; var validationTopicName = configuration.ServiceBus.Validation_TopicName; var symbolsValidationConnectionString = configuration.ServiceBus.SymbolsValidation_ConnectionString; var symbolsValidationTopicName = configuration.ServiceBus.SymbolsValidation_TopicName; builder .Register(c => new TopicClientWrapper(validationConnectionString, validationTopicName)) .As<ITopicClient>() .SingleInstance() .Keyed<ITopicClient>(BindingKeys.PackageValidationTopic) .OnRelease(x => x.Close()); builder .Register(c => new TopicClientWrapper(symbolsValidationConnectionString, symbolsValidationTopicName)) .As<ITopicClient>() .SingleInstance() .Keyed<ITopicClient>(BindingKeys.SymbolsPackageValidationTopic) .OnRelease(x => x.Close()); } else { // This will register all the instances of ImmediatePackageValidator<T> as IPackageValidationInitiator<T> where T is a typeof(IPackageEntity) builder .RegisterGeneric(typeof(ImmediatePackageValidator<>)) .As(typeof(IPackageValidationInitiator<>)); } builder.RegisterType<ValidationAdminService>() .AsSelf() .InstancePerLifetimeScope(); builder.RegisterType<RevalidationAdminService>() .AsSelf() .InstancePerLifetimeScope(); } private static List<(string name, Uri searchUri)> GetSearchClientsFromConfiguration(IGalleryConfigurationService configuration) { var searchClients = new List<(string name, Uri searchUri)>(); if (configuration.Current.SearchServiceUriPrimary != null) { searchClients.Add((SearchClientConfiguration.SearchPrimaryInstance, configuration.Current.SearchServiceUriPrimary)); } if (configuration.Current.SearchServiceUriSecondary != null) { searchClients.Add((SearchClientConfiguration.SearchSecondaryInstance, configuration.Current.SearchServiceUriSecondary)); } return searchClients; } private static List<(string name, Uri searchUri)> GetPreviewSearchClientsFromConfiguration(IGalleryConfigurationService configuration) { var searchClients = new List<(string name, Uri searchUri)>(); if (configuration.Current.PreviewSearchServiceUriPrimary != null) { searchClients.Add((SearchClientConfiguration.PreviewSearchPrimaryInstance, configuration.Current.PreviewSearchServiceUriPrimary)); } if (configuration.Current.PreviewSearchServiceUriSecondary != null) { searchClients.Add((SearchClientConfiguration.PreviewSearchSecondaryInstance, configuration.Current.PreviewSearchServiceUriSecondary)); } return searchClients; } private static void ConfigureSearch( ILoggerFactory loggerFactory, IGalleryConfigurationService configuration, ITelemetryService telemetryService, ServiceCollection services, ContainerBuilder builder) { var searchClients = GetSearchClientsFromConfiguration(configuration); if (searchClients.Count >= 1) { services.AddTransient<CorrelatingHttpClientHandler>(); services.AddTransient((s) => new TracingHttpHandler(DependencyResolver.Current.GetService<IDiagnosticsService>().SafeGetSource("ExternalSearchService"))); // Register the default search service implementation and its dependencies. RegisterSearchService( loggerFactory, configuration, telemetryService, services, builder, searchClients); // Register the preview search service and its dependencies with a binding key. var previewSearchClients = GetPreviewSearchClientsFromConfiguration(configuration); RegisterSearchService( loggerFactory, configuration, telemetryService, services, builder, previewSearchClients, BindingKeys.PreviewSearchClient); } else { builder.RegisterType<LuceneSearchService>() .AsSelf() .As<ISearchService>() .Keyed<ISearchService>(BindingKeys.PreviewSearchClient) .InstancePerLifetimeScope(); builder.RegisterType<LuceneIndexingService>() .AsSelf() .As<IIndexingService>() .As<IIndexingJobFactory>() .InstancePerLifetimeScope(); builder.RegisterType<LuceneDocumentFactory>() .As<ILuceneDocumentFactory>() .InstancePerLifetimeScope(); } builder .Register(c => new SearchSideBySideService( c.Resolve<ISearchService>(), c.ResolveKeyed<ISearchService>(BindingKeys.PreviewSearchClient), c.Resolve<ITelemetryService>(), c.Resolve<IMessageService>(), c.Resolve<IMessageServiceConfiguration>(), c.Resolve<IIconUrlProvider>())) .As<ISearchSideBySideService>() .InstancePerLifetimeScope(); builder .Register(c => new HijackSearchServiceFactory( c.Resolve<HttpContextBase>(), c.Resolve<IFeatureFlagService>(), c.Resolve<IContentObjectService>(), c.Resolve<ISearchService>(), c.ResolveKeyed<ISearchService>(BindingKeys.PreviewSearchClient))) .As<IHijackSearchServiceFactory>() .InstancePerLifetimeScope(); builder .Register(c => new SearchServiceFactory( c.Resolve<ISearchService>(), c.ResolveKeyed<ISearchService>(BindingKeys.PreviewSearchClient))) .As<ISearchServiceFactory>() .InstancePerLifetimeScope(); } private static void RegisterSearchService( ILoggerFactory loggerFactory, IGalleryConfigurationService configuration, ITelemetryService telemetryService, ServiceCollection services, ContainerBuilder builder, List<(string name, Uri searchUri)> searchClients, string bindingKey = null) { var logger = loggerFactory.CreateLogger<SearchClientPolicies>(); foreach (var searchClient in searchClients) { // The policy handlers will be applied from the bottom to the top. // The most inner one is the one added last. services .AddHttpClient<IHttpClientWrapper, HttpClientWrapper>( searchClient.name, c => { c.BaseAddress = searchClient.searchUri; // Here we calculate a timeout for HttpClient that allows for all of the retries to occur. // This is not strictly necessary today since the timeout exception is not a case that is // retried but it's best to set this right now instead of the default (100) or something // too small. The timeout on HttpClient is not really used. Instead, we depend on a timeout // policy from Polly. var perRetryMs = configuration.Current.SearchHttpRequestTimeoutInMilliseconds; var betweenRetryMs = configuration.Current.SearchCircuitBreakerWaitAndRetryIntervalInMilliseconds; var maxAttempts = configuration.Current.SearchCircuitBreakerWaitAndRetryCount + 1; var maxMs = (maxAttempts * perRetryMs) + ((maxAttempts - 1) * betweenRetryMs); // Add another timeout on top of the theoretical max to account for CPU time. maxMs += perRetryMs; c.Timeout = TimeSpan.FromMilliseconds(maxMs); }) .ConfigurePrimaryHttpMessageHandler(() => new HttpClientHandler() { AllowAutoRedirect = true }) .AddHttpMessageHandler<CorrelatingHttpClientHandler>() .AddSearchPolicyHandlers( logger, searchClient.name, telemetryService, configuration.Current); } var registrationBuilder = builder .Register(c => { var httpClientFactory = c.Resolve<IHttpClientFactory>(); var httpClientWrapperFactory = c.Resolve<ITypedHttpClientFactory<HttpClientWrapper>>(); var httpClientWrappers = new List<IHttpClientWrapper>(searchClients.Count); foreach (var searchClient in searchClients) { var httpClient = httpClientFactory.CreateClient(searchClient.name); var httpClientWrapper = httpClientWrapperFactory.CreateClient(httpClient); httpClientWrappers.Add(httpClientWrapper); } return new ResilientSearchHttpClient( httpClientWrappers, c.Resolve<ITelemetryService>()); }); if (bindingKey != null) { registrationBuilder .Named<IResilientSearchClient>(bindingKey) .InstancePerLifetimeScope(); builder .RegisterType<GallerySearchClient>() .WithParameter(new ResolvedParameter( (pi, ctx) => pi.ParameterType == typeof(IResilientSearchClient), (pi, ctx) => ctx.ResolveKeyed<IResilientSearchClient>(bindingKey))) .Named<ISearchClient>(bindingKey) .InstancePerLifetimeScope(); builder.RegisterType<ExternalSearchService>() .WithParameter(new ResolvedParameter( (pi, ctx) => pi.ParameterType == typeof(ISearchClient), (pi, ctx) => ctx.ResolveKeyed<ISearchClient>(bindingKey))) .Named<ISearchService>(bindingKey) .InstancePerLifetimeScope(); } else { registrationBuilder .As<IResilientSearchClient>() .InstancePerLifetimeScope(); builder .RegisterType<GallerySearchClient>() .As<ISearchClient>() .InstancePerLifetimeScope(); builder.RegisterType<ExternalSearchService>() .AsSelf() .As<ISearchService>() .As<IIndexingService>() .As<IIndexingJobFactory>() .InstancePerLifetimeScope(); } } private static void ConfigureAutocomplete(ContainerBuilder builder, IGalleryConfigurationService configuration) { if (configuration.Current.SearchServiceUriPrimary != null || configuration.Current.SearchServiceUriSecondary != null) { builder.RegisterType<AutocompleteServicePackageIdsQuery>() .AsSelf() .As<IAutocompletePackageIdsQuery>() .SingleInstance(); builder.RegisterType<AutocompleteServicePackageVersionsQuery>() .AsSelf() .As<IAutocompletePackageVersionsQuery>() .InstancePerLifetimeScope(); } else { builder.RegisterType<AutocompleteDatabasePackageIdsQuery>() .AsSelf() .As<IAutocompletePackageIdsQuery>() .InstancePerLifetimeScope(); builder.RegisterType<AutocompleteDatabasePackageVersionsQuery>() .AsSelf() .As<IAutocompletePackageVersionsQuery>() .InstancePerLifetimeScope(); } } private static void ConfigureForLocalFileSystem(ContainerBuilder builder, IGalleryConfigurationService configuration) { builder.RegisterType<FileSystemService>() .AsSelf() .As<IFileSystemService>() .SingleInstance(); builder.RegisterType<FileSystemFileStorageService>() .AsSelf() .As<IFileStorageService>() .As<ICoreFileStorageService>() .SingleInstance(); foreach (var dependent in StorageDependent.GetAll(configuration.Current)) { var registration = builder.RegisterType(dependent.ImplementationType) .AsSelf() .As(dependent.InterfaceType); if (dependent.IsSingleInstance) { registration.SingleInstance(); } else { registration.InstancePerLifetimeScope(); } } builder.RegisterInstance(NullReportService.Instance) .AsSelf() .As<IReportService>() .SingleInstance(); builder.RegisterInstance(NullStatisticsService.Instance) .AsSelf() .As<IStatisticsService>() .SingleInstance(); // If we're not using azure storage, then aggregate stats comes from SQL builder.RegisterType<SqlAggregateStatsService>() .AsSelf() .As<IAggregateStatsService>() .InstancePerLifetimeScope(); builder.RegisterInstance(new SqlErrorLog(configuration.Current.SqlConnectionString)) .As<ErrorLog>() .SingleInstance(); builder.RegisterType<GalleryContentFileMetadataService>() .As<IContentFileMetadataService>() .SingleInstance(); } private static IAuditingService GetAuditingServiceForLocalFileSystem(IGalleryConfigurationService configuration) { var auditingPath = Path.Combine( FileSystemFileStorageService.ResolvePath(configuration.Current.FileStorageDirectory), FileSystemAuditingService.DefaultContainerName); return new FileSystemAuditingService(auditingPath, AuditActor.GetAspNetOnBehalfOfAsync); } private static void ConfigureForAzureStorage(ContainerBuilder builder, IGalleryConfigurationService configuration, ITelemetryService telemetryService) { /// The goal here is to initialize a <see cref="ICloudBlobClient"/> and <see cref="IFileStorageService"/> /// instance for each unique connection string. Each dependent of <see cref="IFileStorageService"/> (that /// is, each service that has a <see cref="IFileStorageService"/> constructor parameter) is registered in /// <see cref="StorageDependent.GetAll(IAppConfiguration)"/> and is grouped by the respective storage /// connection string. Each group is given a binding key which refers to the appropriate instance of the /// <see cref="IFileStorageService"/>. var completedBindingKeys = new HashSet<string>(); foreach (var dependent in StorageDependent.GetAll(configuration.Current)) { if (completedBindingKeys.Add(dependent.BindingKey)) { builder.RegisterInstance(new CloudBlobClientWrapper(dependent.AzureStorageConnectionString, configuration.Current.AzureStorageReadAccessGeoRedundant)) .AsSelf() .As<ICloudBlobClient>() .SingleInstance() .Keyed<ICloudBlobClient>(dependent.BindingKey); // Do not register the service as ICloudStorageStatusDependency because // the CloudAuditingService registers it and the gallery uses the same storage account for all the containers. builder.RegisterType<CloudBlobFileStorageService>() .WithParameter(new ResolvedParameter( (pi, ctx) => pi.ParameterType == typeof(ICloudBlobClient), (pi, ctx) => ctx.ResolveKeyed<ICloudBlobClient>(dependent.BindingKey))) .AsSelf() .As<IFileStorageService>() .As<ICoreFileStorageService>() .SingleInstance() .Keyed<IFileStorageService>(dependent.BindingKey); } var registration = builder.RegisterType(dependent.ImplementationType) .WithParameter(new ResolvedParameter( (pi, ctx) => pi.ParameterType.IsAssignableFrom(typeof(IFileStorageService)), (pi, ctx) => ctx.ResolveKeyed<IFileStorageService>(dependent.BindingKey))) .AsSelf() .As(dependent.InterfaceType); if (dependent.IsSingleInstance) { registration.SingleInstance(); } else { registration.InstancePerLifetimeScope(); } } // when running on Windows Azure, we use a back-end job to calculate stats totals and store in the blobs builder.RegisterInstance(new JsonAggregateStatsService(configuration.Current.AzureStorage_Statistics_ConnectionString, configuration.Current.AzureStorageReadAccessGeoRedundant)) .AsSelf() .As<IAggregateStatsService>() .SingleInstance(); // when running on Windows Azure, pull the statistics from the warehouse via storage builder.RegisterInstance(new CloudReportService(configuration.Current.AzureStorage_Statistics_ConnectionString, configuration.Current.AzureStorageReadAccessGeoRedundant)) .AsSelf() .As<IReportService>() .SingleInstance(); // when running on Windows Azure, download counts come from the downloads.v1.json blob var downloadCountService = new CloudDownloadCountService( telemetryService, configuration.Current.AzureStorage_Statistics_ConnectionString, configuration.Current.AzureStorageReadAccessGeoRedundant); builder.RegisterInstance(downloadCountService) .AsSelf() .As<IDownloadCountService>() .SingleInstance(); ObjectMaterializedInterception.AddInterceptor(new DownloadCountObjectMaterializedInterceptor(downloadCountService, telemetryService)); builder.RegisterType<JsonStatisticsService>() .AsSelf() .As<IStatisticsService>() .SingleInstance(); builder.RegisterInstance(new TableErrorLog(configuration.Current.AzureStorage_Errors_ConnectionString, configuration.Current.AzureStorageReadAccessGeoRedundant)) .As<ErrorLog>() .SingleInstance(); builder.RegisterType<FlatContainerContentFileMetadataService>() .As<IContentFileMetadataService>() .SingleInstance(); } private static IAuditingService GetAuditingServiceForAzureStorage(ContainerBuilder builder, IGalleryConfigurationService configuration) { string instanceId = HostMachine.Name; var localIp = AuditActor.GetLocalIpAddressAsync().Result; var service = new CloudAuditingService(instanceId, localIp, configuration.Current.AzureStorage_Auditing_ConnectionString, configuration.Current.AzureStorageReadAccessGeoRedundant, AuditActor.GetAspNetOnBehalfOfAsync); builder.RegisterInstance(service) .As<ICloudStorageStatusDependency>() .SingleInstance(); return service; } private static IAuditingService CombineAuditingServices(IEnumerable<IAuditingService> services) { if (!services.Any()) { return null; } if (services.Count() == 1) { return services.First(); } return new AggregateAuditingService(services); } private static IEnumerable<T> GetAddInServices<T>() { return GetAddInServices<T>(sp => { }); } private static IEnumerable<T> GetAddInServices<T>(Action<RuntimeServiceProvider> populateProvider) { var addInsDirectoryPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "bin", "add-ins"); using (var serviceProvider = RuntimeServiceProvider.Create(addInsDirectoryPath)) { populateProvider(serviceProvider); return serviceProvider.GetExportedValues<T>(); } } private static void RegisterAuditingServices(ContainerBuilder builder, IAuditingService defaultAuditingService) { var auditingServices = GetAddInServices<IAuditingService>(); var services = new List<IAuditingService>(auditingServices); if (defaultAuditingService != null) { services.Add(defaultAuditingService); } var service = CombineAuditingServices(services); builder.RegisterInstance(service) .AsSelf() .As<IAuditingService>() .SingleInstance(); } private static void RegisterCookieComplianceService(ContainerBuilder builder, ConfigurationService configuration, DiagnosticsService diagnostics) { CookieComplianceServiceBase service = null; if (configuration.Current.IsHosted) { var siteName = configuration.GetSiteRoot(true); service = GetAddInServices<ICookieComplianceService>(sp => { sp.ComposeExportedValue("Domain", siteName); sp.ComposeExportedValue<IDiagnosticsService>(diagnostics); }).FirstOrDefault() as CookieComplianceServiceBase; if (service != null) { // Initialize the service on App_Start to avoid any performance degradation during initial requests. HostingEnvironment.QueueBackgroundWorkItem(async cancellationToken => await service.InitializeAsync(siteName, diagnostics, cancellationToken)); } } builder.RegisterInstance(service ?? new NullCookieComplianceService()) .AsSelf() .As<ICookieComplianceService>() .SingleInstance(); } } }
43.763441
229
0.609613
[ "Apache-2.0" ]
johnarthur1/NuGetGallery
src/NuGetGallery/App_Start/DefaultDependenciesModule.cs
65,120
C#
using ScadaIssuesPortal.Core.Entities; using System; using System.Collections.Generic; using System.ComponentModel; using System.ComponentModel.DataAnnotations; namespace ScadaIssuesPortal.Web.Models { public class ReportingCaseEditVM { public List<ReportingCaseItem> CaseItems { get; set; } = new List<ReportingCaseItem>(); [Display(Name = "Concerned People")] public List<ReportingCaseConcerned> ConcernedAgencies { get; set; } = new List<ReportingCaseConcerned>(); [Display(Name = "New Agency")] public string ConcernedAgencyId { get; set; } [Display(Name = "Issue Time")] public DateTime DownTime { get; set; } public DateTime ResolutionTime { get; set; } public string ResolutionRemarks { get; set; } public string AdminRemarks { get; set; } } }
36.73913
113
0.688757
[ "MIT" ]
nagasudhirpulla/wrldc_scada_issues_portal
src/WrldcScadaIssuesPortal/ScadaIssuesPortal.Web/Models/ReportingCaseEditVM.cs
847
C#
// c:\program files (x86)\windows kits\10\include\10.0.18362.0\um\d2d1_3.h(1250,1) using System; using System.Runtime.InteropServices; namespace DirectN { /// <summary> /// This object supplies the values for context-fill, context-stroke, and context-value that are used when rendering SVG glyphs. /// </summary> [Guid("af671749-d241-4db8-8e41-dcc2e5c1a438"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] public partial interface ID2D1SvgGlyphStyle : ID2D1Resource { // ID2D1Resource [PreserveSig] new void GetFactory(/* _Outptr_ */ out ID2D1Factory factory); // ID2D1SvgGlyphStyle [PreserveSig] HRESULT SetFill(/* _In_opt_ */ ID2D1Brush brush); [PreserveSig] void GetFill(/* _Outptr_result_maybenull_ */ out ID2D1Brush brush); [PreserveSig] HRESULT SetStroke(/* _In_opt_ */ ID2D1Brush brush, float strokeWidth, /* _In_reads_opt_(dashesCount) */ [MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 3)] float[] dashes, int dashesCount, float dashOffset); [PreserveSig] uint GetStrokeDashesCount(); [PreserveSig] void GetStroke(/* _Outptr_opt_result_maybenull_ */ out ID2D1Brush brush, /* _Out_opt_ */ out float strokeWidth, /* _Out_writes_opt_(dashesCount) */ [Out, MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 3)] float[] dashes, int dashesCount, /* _Out_opt_ */ out float dashOffset); } }
43.794118
287
0.677636
[ "MIT" ]
bbday/DirectN
DirectN/DirectN/Generated/ID2D1SvgGlyphStyle.cs
1,491
C#
using System; using System.Diagnostics; using System.Linq; using Deveroom.VisualStudio.Connectors; using Deveroom.VisualStudio.Diagonostics; using Deveroom.VisualStudio.Monitoring; using Deveroom.VisualStudio.ProjectSystem; using Deveroom.VisualStudio.ProjectSystem.Configuration; using Deveroom.VisualStudio.ProjectSystem.Settings; using Deveroom.VisualStudio.SpecFlowConnector.Models; namespace Deveroom.VisualStudio.Generation { public class GenerationService { private readonly IProjectScope _projectScope; private readonly IDeveroomLogger _logger; private IMonitoringService MonitoringService => _projectScope.IdeScope.MonitoringService; public GenerationService(IProjectScope projectScope) { _projectScope = projectScope; _logger = projectScope.IdeScope.Logger; } public static bool CheckSpecFlowToolsFolder(IProjectScope projectScope) { var toolsFolder = GetSpecFlowToolsFolderSafe(projectScope, projectScope.GetProjectSettings(), out _); return toolsFolder != null; } private static string GetSpecFlowToolsFolderSafe(IProjectScope projectScope, ProjectSettings projectSettings, out string toolsFolderErrorMessage) { toolsFolderErrorMessage = null; try { var specFlowToolsFolder = projectSettings.SpecFlowGeneratorFolder; if (string.IsNullOrEmpty(specFlowToolsFolder)) { projectScope.IdeScope.Actions.ShowProblem($"Unable to generate feature-file code behind, because SpecFlow NuGet package folder could not be detected. For configuring SpecFlow tools folder manually, check http://speclink.me/deveroomsfassref."); toolsFolderErrorMessage = "Folder is not configured. See http://speclink.me/deveroomsfassref for details."; return null; } if (!projectScope.IdeScope.FileSystem.Directory.Exists(specFlowToolsFolder)) { projectScope.IdeScope.Actions.ShowProblem($"Unable to find SpecFlow tools folder: '{specFlowToolsFolder}'. Build solution to ensure that all packages are restored. The feature file has to be re-generated (e.g. by saving) after the packages have been restored."); toolsFolderErrorMessage = "Folder does not exist"; return null; } return specFlowToolsFolder; } catch (Exception ex) { projectScope.IdeScope.Logger.LogException(projectScope.IdeScope.MonitoringService, ex); toolsFolderErrorMessage = ex.Message; return null; } } public GenerationResult GenerateFeatureFile(string featureFilePath, string targetExtension, string targetNamespace) { var projectSettings = _projectScope.GetProjectSettings(); var specFlowToolsFolder = GetSpecFlowToolsFolderSafe(_projectScope, projectSettings, out var toolsFolderErrorMessage); if (specFlowToolsFolder == null) return CreateErrorResult(featureFilePath, $"Unable to use SpecFlow tools folder '{projectSettings.SpecFlowGeneratorFolder}': {toolsFolderErrorMessage}"); var stopwatch = new Stopwatch(); stopwatch.Start(); try { var connector = OutProcSpecFlowConnectorFactory.Create(_projectScope); var result = connector.RunGenerator(featureFilePath, projectSettings.SpecFlowConfigFilePath, targetExtension, targetNamespace, _projectScope.ProjectFolder, specFlowToolsFolder); _projectScope.IdeScope.MonitoringService.MonitorSpecFlowGeneration(result.IsFailed, projectSettings); if (result.IsFailed) { _logger.LogWarning(result.ErrorMessage); SetErrorContent(featureFilePath, result); _logger.LogVerbose(() => result.FeatureFileCodeBehind.Content); } else { _logger.LogInfo($"code-behind file generated for file {featureFilePath} in project {_projectScope.ProjectName}"); _logger.LogVerbose(() => result.FeatureFileCodeBehind.Content.Substring(0, Math.Min(450, result.FeatureFileCodeBehind.Content.Length))); } return result; } catch (Exception ex) { _logger.LogException(MonitoringService, ex); return CreateErrorResult(featureFilePath, ex.Message); } finally { stopwatch.Stop(); _logger.LogVerbose($"Generation: {stopwatch.ElapsedMilliseconds} ms"); } } private GenerationResult CreateErrorResult(string featureFilePath, string errorMessage) { var result = new GenerationResult { ErrorMessage = errorMessage }; SetErrorContent(featureFilePath, result); return result; } private void SetErrorContent(string featureFilePath, GenerationResult result) { result.FeatureFileCodeBehind = new FeatureFileCodeBehind() { FeatureFilePath = featureFilePath, Content = GetErrorContent(result.ErrorMessage) }; } private string GetErrorContent(string resultErrorMessage) { var errorLines = resultErrorMessage.Split(new[] {'\r', '\n'}, StringSplitOptions.RemoveEmptyEntries); return "#error " + errorLines[0] + Environment.NewLine + string.Join(Environment.NewLine, errorLines.Skip(1) .Select(l => l.StartsWith("(") ? "#error " + l : "//" + l)); } } }
43.883212
282
0.630905
[ "MIT" ]
specsolutions/deveroom-feedback
Deveroom.VisualStudio/Generation/GenerationService.cs
6,014
C#
#if WITH_GAME #if PLATFORM_64BITS using System; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; namespace UnrealEngine { [StructLayout(LayoutKind.Explicit,Size=16)] public partial struct FVector4 { [FieldOffset(0)] public float X; [FieldOffset(4)] public float Y; [FieldOffset(8)] public float Z; [FieldOffset(12)] public float W; } } #endif #endif
16.12
44
0.736973
[ "MIT" ]
RobertAcksel/UnrealCS
Engine/Plugins/UnrealCS/UECSharpDomain/UnrealEngine/GeneratedScriptFile_Game_64bits/FVector4.cs
403
C#
using AutoMapper; using Shouldly; using System.Collections.Generic; using System.Linq; using System.Threading; using System.Threading.Tasks; using TechRSSReader.Application.Common.Interfaces; using TechRSSReader.Application.UnitTests.Common; using TechRSSReader.Application.WeeklyBlogSummaries.Queries; using TechRSSReader.Domain.Entities; using TechRSSReader.Infrastructure.Persistence; using Xunit; namespace TechRSSReader.Application.UnitTests.WeeklyBlogSummaries.Queries { [Collection("QueryTests")] public class GetLatestSummariesQueryTests { private readonly ApplicationDbContext _context; private readonly IMapper _mapper; private readonly ICurrentUserService _currentUserService; public GetLatestSummariesQueryTests(QueryTestFixture fixture) { _context = fixture.Context; _mapper = fixture.Mapper; _currentUserService = fixture.CurrentUserService; } [Fact] public async Task Handle_ReturnsValid() { var query = new GetLatestSummariesQuery { BlogId = 1 }; var handler = new GetLatestSummariesQuery.GetLatestSummariesQueryHandler(_context, _mapper, _currentUserService); WeeklyBlogSummaryViewModel result = await handler.Handle(query, CancellationToken.None); List<WeeklyBlogSummary> weeklyBlogSummaries = _context.WeeklyBlogSummaries .Where(item => item.BlogId == 1) .OrderByDescending(item => item.WeekBegins) .ToList(); result.ShouldNotBeNull(); result.WeeklyBlogSummaries.Count.ShouldBe(1); WeeklyBlogSummaryDto firstResult = result.WeeklyBlogSummaries[0]; WeeklyBlogSummary expectedResult = weeklyBlogSummaries[0]; firstResult.BlogId.ShouldBe(expectedResult.BlogId); firstResult.NewItems.ShouldBe(expectedResult.NewItems); firstResult.ItemsExcluded.ShouldBe(expectedResult.ItemsExcluded); firstResult.ItemsRatedAtLeastThree.ShouldBe(expectedResult.ItemsRatedAtLeastThree); firstResult.ItemsRead.ShouldBe(expectedResult.ItemsRead); } } }
37.419355
125
0.678017
[ "MIT" ]
Andrew-netizen/TechRSSReader
tests/Application.UnitTests/WeeklyBlogSummaries/Queries/GetLatestSummariesQueryTests.cs
2,322
C#
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // アセンブリに関する一般情報は以下の属性セットをとおして制御されます。 // アセンブリに関連付けられている情報を変更するには、 // これらの属性値を変更してください。 [assembly: AssemblyTitle("ALDS1_1_B")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("ALDS1_1_B")] [assembly: AssemblyCopyright("Copyright © 2016")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // ComVisible を false に設定すると、その型はこのアセンブリ内で COM コンポーネントから // 参照不可能になります。COM からこのアセンブリ内の型にアクセスする場合は、 // その型の ComVisible 属性を true に設定してください。 [assembly: ComVisible(false)] // このプロジェクトが COM に公開される場合、次の GUID が typelib の ID になります [assembly: Guid("592f4acf-c00c-4a45-b3c0-322bad62a83b")] // アセンブリのバージョン情報は次の 4 つの値で構成されています: // // メジャー バージョン // マイナー バージョン // ビルド番号 // Revision // // すべての値を指定するか、下のように '*' を使ってビルドおよびリビジョン番号を // 既定値にすることができます: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
29.054054
57
0.743256
[ "MIT" ]
yu3mars/procon
aoj/ALDS/ALDS1_1_B/Properties/AssemblyInfo.cs
1,644
C#
using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; namespace jhray.com.Database.Entities { public class Picture { [Key] [ForeignKey("FK_Picture_Gem")] public int Id { get; set; } public string ArtistLink { get; set; } public string ArtistName { get; set; } public string Location { get; set; } public long FileSize { get; set; } public string HoverText { get; set; } public DateTime CreatedDate { get; set; } public List<PictureLink> BlogLinks { get; set; } public List<PictureTag> PictureTags { get; set; } public Gem GemData { get; set; } } }
30
57
0.64
[ "MIT" ]
PurplePenguin4102/jhray.com
Database/Entities/Picture.cs
752
C#
using System; using Assets.HeroEditor4D.Common.CommonScripts.Springs; using HeroEditor.Common.Enums; using UnityEngine; namespace Assets.HeroEditor4D.Common.CharacterScripts { /// <summary> /// Used to play animations. /// </summary> public class AnimationManager : MonoBehaviour { public Character4D Character; public Animator Animator; public bool IsAction { get => Animator.GetBool("Action"); set => Animator.SetBool("Action", value); } /// <summary> /// Set animation parameter State that controls transition. /// </summary> public void SetState(CharacterState state) { Animator.SetInteger("State", (int) state); } /// <summary> /// Play Attack animation according to selected weapon. /// </summary> public void Attack() { switch (Character.WeaponType) { case WeaponType.Melee1H: case WeaponType.Melee2H: Slash1H(); break; case WeaponType.Bow: ShotBow(); break; default: throw new NotImplementedException("This feature may be implemented in next updates."); } } /// <summary> /// Play Slash1H animation. /// </summary> public void Slash1H() { Animator.SetTrigger("Slash1H"); IsAction = true; } /// <summary> /// Play Slash2H animation. /// </summary> public void Slash2H() { Animator.SetTrigger("Slash2H"); IsAction = true; } public void Slash(bool twoHanded) { Animator.SetTrigger(twoHanded ? "Slash2H" : "Slash1H"); IsAction = true; } /// <summary> /// Play Stab animation. /// </summary> public void Stab() { Animator.SetTrigger("Stab"); IsAction = true; } /// <summary> /// Play Slash1H animation. /// </summary> public void HeavySlash1H() { Animator.SetTrigger("HeavySlash1H"); IsAction = true; } /// <summary> /// Play PowerStab animation. /// </summary> public void FastStab() { Animator.SetTrigger("FastStab"); IsAction = true; } /// <summary> /// Play Shot animation (bow). /// </summary> public void ShotBow() { Animator.SetTrigger("ShotBow"); IsAction = true; } /// <summary> /// Play Death animation. /// </summary> public void Die() { SetState(CharacterState.Death); } /// <summary> /// Play Hit animation. This will just scale character up and down. /// Hit will not break currently playing animation, for example you can Hit character while it's playing Attack animation. /// </summary> public void Hit() { Animator.SetTrigger("Hit"); } public void ShieldBlock() { SetState(CharacterState.ShieldBlock); } public void WeaponBlock() { SetState(CharacterState.WeaponBlock); } public void Evade() { Animator.SetTrigger("Evade"); } public void SetTwoHanded(bool twoHanded) { Animator.SetBool("TwoHanded", twoHanded); } public void SetWeaponType(WeaponType weaponType) { Animator.SetInteger("WeaponType", (int) weaponType); } public void SecondaryShot() { Animator.SetTrigger("SecondaryShot"); IsAction = true; } /// <summary> /// Alternative way to Hit character (with a script). /// </summary> public void Spring() { ScaleSpring.Begin(this, 1f, 1.1f, 40, 2); } } }
22.636364
130
0.556359
[ "Unlicense" ]
FunzoftAli/system-of-shop
GitHub Test Project/Assets/HeroEditor4D/Common/CharacterScripts/AnimationManager.cs
3,737
C#
using Akka.Actor; using DocSearchAIO.Classes; using DocSearchAIO.Configuration; using DocSearchAIO.Services; using DocSearchAIO.Utilities; using LanguageExt.UnsafeValueAccess; using Microsoft.Extensions.Caching.Memory; using Quartz; namespace DocSearchAIO.Scheduler.PdfJobs; public class PdfCleanupJob : IJob { private readonly ILogger _logger; private readonly ConfigurationObject _cfg; private readonly SchedulerUtilities _schedulerUtilities; private readonly ElasticUtilities _elasticUtilities; private readonly ReverseComparerService<ComparerModelPdf> _reverseComparerService; private readonly JobStateMemoryCache<MemoryCacheModelPdfCleanup> _jobStateMemoryCache; private readonly CleanUpEntry _cleanUpEntry; public PdfCleanupJob(ILoggerFactory loggerFactory, IConfiguration configuration, IElasticSearchService elasticSearchService, IMemoryCache memoryCache, ActorSystem actorSystem) { _logger = loggerFactory.CreateLogger<PdfCleanupJob>(); _cfg = new ConfigurationObject(); configuration.GetSection("configurationObject").Bind(_cfg); _cleanUpEntry = _cfg.Cleanup[nameof(PdfCleanupDocument)]; _schedulerUtilities = new SchedulerUtilities(loggerFactory); _elasticUtilities = new ElasticUtilities(loggerFactory, elasticSearchService); _reverseComparerService = new ReverseComparerService<ComparerModelPdf>(loggerFactory, new ComparerModelPdf(_cfg.ComparerDirectory), elasticSearchService, actorSystem); _jobStateMemoryCache = JobStateMemoryCacheProxy.GetPdfCleanupJobStateMemoryCache(loggerFactory, memoryCache); } public async Task Execute(IJobExecutionContext context) { await Task.Run(async () => { _jobStateMemoryCache.SetCacheEntry(JobState.Running); if (!_cleanUpEntry.Active) { await _schedulerUtilities.SetTriggerStateByUserAction(context.Scheduler, _cleanUpEntry.TriggerName, _cfg.CleanupGroupName, TriggerState.Paused); _logger.LogWarning( "skip cleanup of pdf documents because the scheduler is inactive per config"); } else { await Task.Run(async () => { var cacheEntryOpt = _jobStateMemoryCache.CacheEntry(new MemoryCacheModelPdf()); if (cacheEntryOpt.IsSome && (cacheEntryOpt.IsNone || cacheEntryOpt.ValueUnsafe().JobState != JobState.Stopped)) { _logger.LogInformation( "cannot execute cleanup documents, opponent job scanning and processing running"); return; } _logger.LogInformation("start processing cleanup job"); var cleanupIndexName = _elasticUtilities.CreateIndexName(_cfg.IndexName, _cleanUpEntry.ForIndexSuffix); await _reverseComparerService.Process(cleanupIndexName); }); } _jobStateMemoryCache.SetCacheEntry(JobState.Stopped); }); } }
44.040541
110
0.667996
[ "Apache-2.0" ]
LaszloLueck/DocSearchAIO
DocSearchAIO/Scheduler/PdfJobs/PdfCleanupJob.cs
3,259
C#
// (c) Copyright HutongGames, all rights reserved. // See also: EasingFunctionLicense.txt using UnityEditor; namespace HutongGames.PlayMakerEditor { [CustomActionEditor(typeof(PlayMaker.Actions.TweenUiSize))] public class TweenUiSizeEditor : TweenEditorBase { public override bool OnGUI() { EditorGUI.BeginChangeCheck(); EditField("gameObject"); EditField("tweenDirection", "Tween"); EditField("targetSize", "Size"); DoEasingUI(); return EditorGUI.EndChangeCheck(); } } }
24.541667
63
0.629881
[ "MIT" ]
aiden-ji/oneButtonBoB
Assets/PlayMaker/Actions/Tween/Editor/TweenUiSizeEditor.cs
591
C#
using System; using System.CodeDom.Compiler; using System.ComponentModel; using System.Diagnostics; using System.ServiceModel; namespace Workday.RevenueManagement { [GeneratedCode("System.ServiceModel", "4.0.0.0"), EditorBrowsable(EditorBrowsableState.Advanced), DebuggerStepThrough, MessageContract(IsWrapped = false)] public class Submit_Customer_InvoiceInput { [MessageHeader(Namespace = "urn:com.workday/bsvc")] public Workday_Common_HeaderType Workday_Common_Header; [MessageBodyMember(Namespace = "urn:com.workday/bsvc", Order = 0)] public Submit_Customer_Invoice_RequestType Submit_Customer_Invoice_Request; public Submit_Customer_InvoiceInput() { } public Submit_Customer_InvoiceInput(Workday_Common_HeaderType Workday_Common_Header, Submit_Customer_Invoice_RequestType Submit_Customer_Invoice_Request) { this.Workday_Common_Header = Workday_Common_Header; this.Submit_Customer_Invoice_Request = Submit_Customer_Invoice_Request; } } }
33.689655
155
0.828045
[ "MIT" ]
matteofabbri/Workday.WebServices
Workday.RevenueManagement/Submit_Customer_InvoiceInput.cs
977
C#
// Copyright (c) 2010-2014 SharpDX - Alexandre Mutel // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. using System; using System.Collections.Generic; using System.IO; using System.Text; #if W8CORE using SharpDX.Text; #endif using System.Text.RegularExpressions; using SharpDX.Direct3D11; using SharpDX.Serialization; namespace SharpDX.Toolkit.Graphics { public class ModelReader : BinarySerializer { private DataPointer sharedPtr; public ModelReader(GraphicsDevice graphicsDevice, Stream stream, ModelMaterialTextureLoaderDelegate textureLoader) : base(stream, SerializerMode.Read, ASCIIEncoding.ASCII) { if (graphicsDevice == null) { throw new ArgumentNullException("graphicsDevice"); } if (stream == null) { throw new ArgumentNullException("stream"); } if (textureLoader == null) { throw new ArgumentNullException("textureLoader"); } GraphicsDevice = graphicsDevice; TextureLoaderDelegate = textureLoader; ArrayLengthType = ArrayLengthType.Int; } internal void AllocateSharedMemory(int size) { sharedPtr = new DataPointer(Utilities.AllocateMemory(size), size); ToDispose(sharedPtr.Pointer); } internal IntPtr SharedMemoryPointer { get { return sharedPtr.Pointer; } } protected Model Model; protected ModelMesh CurrentMesh; protected readonly GraphicsDevice GraphicsDevice; private List<Texture> EmbeddedTextures = new List<Texture>(); protected readonly ModelMaterialTextureLoaderDelegate TextureLoaderDelegate; protected virtual Model CreateModel() { return new Model(); } protected virtual Material CreateModelMaterial() { return new Material(); } protected virtual ModelBone CreateModelBone() { return new ModelBone(); } protected virtual ModelSkinnedBone CreateModelSkinnedBone() { return new ModelSkinnedBone(); } protected virtual ModelMesh CreateModelMesh() { return new ModelMesh(); } protected virtual ModelMeshPart CreateModelMeshPart() { return new ModelMeshPart(); } protected virtual ModelAnimation CreateModelAnimation() { return new ModelAnimation(); } protected virtual MaterialCollection CreateModelMaterialCollection(int capacity) { return new MaterialCollection(capacity); } protected virtual ModelBoneCollection CreateModelBoneCollection(int capacity) { return new ModelBoneCollection(capacity); } protected virtual ModelSkinnedBoneCollection CreateModelSkinnedBoneCollection(int capacity) { return new ModelSkinnedBoneCollection(capacity); } protected virtual ModelMeshCollection CreateModelMeshCollection(int capacity) { return new ModelMeshCollection(capacity); } protected virtual ModelMeshPartCollection CreateModelMeshPartCollection(int capacity) { return new ModelMeshPartCollection(capacity); } protected virtual VertexBufferBindingCollection CreateVertexBufferBindingCollection(int capacity) { return new VertexBufferBindingCollection(capacity); } protected virtual PropertyCollection CreatePropertyCollection(int capacity) { return new PropertyCollection(capacity); } protected virtual ModelAnimationCollection CreateModelAnimationCollection(int capacity) { return new ModelAnimationCollection(capacity); } protected virtual PropertyCollection CreateMaterialPropertyCollection(int capacity) { return new PropertyCollection(capacity); } protected virtual BufferCollection CreateBufferCollection(int capacity) { return new BufferCollection(capacity); } protected virtual VertexBufferBinding CreateVertexBufferBinding() { return new VertexBufferBinding(); } protected virtual MaterialTexture CreateMaterialTexture() { return new MaterialTexture(); } protected virtual MaterialTextureStack CreateMaterialTextureStack(int capacity) { return new MaterialTextureStack(capacity); } public Model ReadModel() { Model = CreateModel(); var model = Model; ReadModel(ref model); return model; } protected virtual void ReadModel(ref Model model) { // Starts the whole ModelData by the magiccode "TKMD" // If the serializer don't find the TKMD, It will throw an // exception that will be catched by Load method. BeginChunk(ModelData.MagicCode); // Writes the version int version = Reader.ReadInt32(); if (version != ModelData.Version) { throw new NotSupportedException(string.Format("EffectData version [0x{0:X}] is not supported. Expecting [0x{1:X}]", version, ModelData.Version)); } // Allocated the shared memory used to load this Model AllocateSharedMemory(Reader.ReadInt32()); // Textures / preload embedded textures BeginChunk("TEXS"); int textureCount = Reader.ReadInt32(); for (int i = 0; i < textureCount; i++) { byte[] textureData = null; Serialize(ref textureData); EmbeddedTextures.Add(Texture.Load(GraphicsDevice, new MemoryStream(textureData))); } EndChunk(); // Material section BeginChunk("MATL"); ReadMaterials(ref model.Materials); EndChunk(); // Bones section BeginChunk("BONE"); ReadBones(ref model.Bones); EndChunk(); // Mesh section BeginChunk("MESH"); ReadMeshes(ref model.Meshes); EndChunk(); // Animation section BeginChunk("ANIM"); ReadAnimations(ref model.Animations); EndChunk(); // Serialize attributes ReadProperties(ref model.Properties); // Close TKMD section EndChunk(); } protected virtual void ReadBones(ref ModelBoneCollection bones) { // Read all bones ReadList(ref bones, CreateModelBoneCollection, CreateModelBone, ReadBone); // Fix all children bones int count = bones.Count; for (int i = 0; i < count; i++) { var bone = bones[i]; // If bone has no children, then move on if (bone.Children == null) continue; var children = bone.Children; var childIndices = children.ChildIndices; foreach (int childIndex in childIndices) { if (childIndex < 0) { children.Add(null); } else if (childIndex < count) { children.Add(bones[childIndex]); } else { throw new InvalidOperationException("Invalid children index for bone"); } } children.ChildIndices = null; } } protected virtual void ReadSkinnedBones(ref ModelSkinnedBoneCollection skinnedBones) { // Read all bones ReadList(ref skinnedBones, CreateModelSkinnedBoneCollection, CreateModelSkinnedBone, ReadSkinnedBone); } public delegate PropertyKey NameToPropertyKeyDelegate(string name); protected virtual void ReadProperties(ref PropertyCollection properties) { ReadProperties(ref properties, name => new PropertyKey(name)); } protected virtual void ReadProperties(ref PropertyCollection properties, NameToPropertyKeyDelegate nameToKey) { if (nameToKey == null) { throw new ArgumentNullException("nameToKey"); } int count = Reader.ReadInt32(); if (properties == null) { properties = CreatePropertyCollection(count); } for (int i = 0; i < count; i++) { string name = null; object value = null; Serialize(ref name); SerializeDynamic(ref value, SerializeFlags.Nullable);; var key = nameToKey(name); if (key == null) { throw new InvalidOperationException(string.Format("Cannot convert property name [{0}] to null key", name)); } properties[key] = value; } } protected virtual void ReadMaterials(ref MaterialCollection materials) { ReadList(ref materials, CreateModelMaterialCollection, CreateModelMaterial, ReadMaterial); } protected virtual void ReadMeshes(ref ModelMeshCollection meshes) { ReadList(ref meshes, CreateModelMeshCollection, CreateModelMesh, ReadMesh); } protected virtual void ReadVertexBuffers(ref VertexBufferBindingCollection vertices) { ReadList(ref vertices, CreateVertexBufferBindingCollection, CreateVertexBufferBinding, ReadVertexBuffer); } protected virtual void ReadMeshParts(ref ModelMeshPartCollection meshParts) { ReadList(ref meshParts, CreateModelMeshPartCollection, CreateModelMeshPart, ReadMeshPart); } protected virtual void ReadIndexBuffers(ref BufferCollection list) { int count = Reader.ReadInt32(); list = CreateBufferCollection(count); for (int i = 0; i < count; i++) { list.Add(ReadIndexBuffer()); } } protected virtual void ReadAnimations(ref ModelAnimationCollection meshes) { ReadList(ref meshes, CreateModelAnimationCollection, CreateModelAnimation, ReadAnimation); } protected virtual void ReadMaterial(ref Material material) { var textureStackCount = Reader.ReadInt32(); var properties = CreateMaterialPropertyCollection(textureStackCount + 32); material.Properties = properties; for (int i = 0; i < textureStackCount; i++) { string keyName = null; Serialize(ref keyName); MaterialTextureStack textureStack = null; ReadList(ref textureStack, CreateMaterialTextureStack, CreateMaterialTexture, ReadMaterialTexture); var key = MaterialKeys.FindKeyByName(keyName) ?? new PropertyKey(keyName); properties[key] = textureStack; } ReadProperties(ref material.Properties, name => MaterialKeys.FindKeyByName(name) ?? new PropertyKey(name)); } private static Regex RegexMatchEmbeddedTexture = new Regex(@"^\*(\d+)$"); protected virtual void ReadMaterialTexture(ref MaterialTexture materialTexture) { // Loads the texture string filePath = null; Serialize(ref filePath); materialTexture.Name = Path.GetFileNameWithoutExtension(filePath); if (!string.IsNullOrEmpty(filePath)) { var match = RegexMatchEmbeddedTexture.Match(filePath); if (match.Success) { var textureIndex = int.Parse(match.Groups[1].Value); if (textureIndex > EmbeddedTextures.Count) { throw new InvalidOperationException(string.Format("Out of range embedded texture with index [{0}] vs max [{1}]", textureIndex, EmbeddedTextures.Count)); } materialTexture.Texture = EmbeddedTextures[textureIndex]; } else { // If the texture name is empty, the texture was probably not located when compiling, so we skip it // TODO Check if we want another behavior? if (!string.IsNullOrEmpty(filePath)) { materialTexture.Texture = TextureLoaderDelegate(filePath); } } } materialTexture.Index = Reader.ReadInt32(); materialTexture.UVIndex = Reader.ReadInt32(); materialTexture.BlendFactor = Reader.ReadSingle(); materialTexture.Operation = (MaterialTextureOperator)Reader.ReadByte(); materialTexture.WrapMode = (TextureAddressMode)Reader.ReadInt32(); materialTexture.Flags = (MaterialTextureFlags)Reader.ReadByte(); } protected virtual void ReadBone(ref ModelBone bone) { // Read ModelBone index bone.Index = Reader.ReadInt32(); // Read Parent Index int parentIndex = Reader.ReadInt32(); if (parentIndex > Model.Bones.Count) { throw new InvalidOperationException("Invalid index for parent bone"); } bone.Parent = parentIndex >= 0 ? Model.Bones[parentIndex] : null; // Transform Serialize(ref bone.Transform); // Name string boneName = null; Serialize(ref boneName, false, SerializeFlags.Nullable); bone.Name = boneName; // Indices List<int> indices = null; Serialize(ref indices, Serialize, SerializeFlags.Nullable); if (indices != null) { bone.Children = CreateModelBoneCollection(indices.Count); bone.Children.ChildIndices = indices; } } protected virtual void ReadSkinnedBone(ref ModelSkinnedBone skinnedBone) { var boneIndex = Reader.ReadInt32(); if (boneIndex > Model.Bones.Count) { throw new InvalidOperationException("Invalid bone index"); } skinnedBone.Bone = Model.Bones[boneIndex]; Serialize(ref skinnedBone.OffsetMatrix); } protected virtual void ReadMesh(ref ModelMesh mesh) { CurrentMesh = mesh; string meshName = null; Serialize(ref meshName, false, SerializeFlags.Nullable); mesh.Name = meshName; int parentBoneIndex = Reader.ReadInt32(); if (parentBoneIndex >= 0) mesh.ParentBone = Model.Bones[parentBoneIndex]; // Read the bounding sphere Serialize(ref mesh.BoundingSphere); ReadVertexBuffers(ref mesh.VertexBuffers); ReadIndexBuffers(ref mesh.IndexBuffers); ReadMeshParts(ref mesh.MeshParts); ReadProperties(ref mesh.Properties); CurrentMesh = null; } protected virtual void ReadMeshPart(ref ModelMeshPart meshPart) { // Set the Parent mesh for the current ModelMeshPart. meshPart.ParentMesh = CurrentMesh; // Material int materialIndex = Reader.ReadInt32(); meshPart.Material = Model.Materials[materialIndex]; // IndexBuffer var indexBufferRange = default(ModelData.BufferRange); indexBufferRange.Serialize(this); meshPart.IndexBuffer = GetFromList(indexBufferRange, CurrentMesh.IndexBuffers); // VertexBuffer var vertexBufferRange = default(ModelData.BufferRange); vertexBufferRange.Serialize(this); meshPart.VertexBuffer = GetFromList(vertexBufferRange, CurrentMesh.VertexBuffers); // Skinned bones ReadSkinnedBones(ref meshPart.SkinnedBones); // Properties ReadProperties(ref meshPart.Properties); } protected virtual void ReadAnimation(ref ModelAnimation animation) { Serialize(ref animation.Name); Serialize(ref animation.Duration); Serialize(ref animation.Channels); } protected virtual void ReadVertexBuffer(ref VertexBufferBinding vertexBufferBinding) { // Read the number of vertices int count = Reader.ReadInt32(); // Read vertex elements int vertexElementCount = Reader.ReadInt32(); var elements = new VertexElement[vertexElementCount]; for (int i = 0; i < vertexElementCount; i++) { elements[i].Serialize(this); } vertexBufferBinding.Layout = VertexInputLayout.New(0, elements); // Read Vertex Buffer int sizeInBytes = Reader.ReadInt32(); SerializeMemoryRegion(SharedMemoryPointer, sizeInBytes); vertexBufferBinding.Buffer = Buffer.New(GraphicsDevice, new DataPointer(SharedMemoryPointer, sizeInBytes), sizeInBytes / count, BufferFlags.VertexBuffer, ResourceUsage.Immutable); } protected virtual Buffer ReadIndexBuffer() { int indexCount = Reader.ReadInt32(); int sizeInBytes = Reader.ReadInt32(); SerializeMemoryRegion(SharedMemoryPointer, sizeInBytes); return Buffer.New(GraphicsDevice, new DataPointer(SharedMemoryPointer, sizeInBytes), sizeInBytes / indexCount, BufferFlags.IndexBuffer, ResourceUsage.Immutable); } protected delegate TLIST CreateListDelegate<out TLIST, TITEM>(int list) where TLIST : List<TITEM>; protected delegate T CreateItemDelegate<out T>(); protected delegate void ReadItemDelegate<T>(ref T item); protected virtual TLIST ReadList<TLIST, TITEM>(ref TLIST list, CreateListDelegate<TLIST, TITEM> listCreate, CreateItemDelegate<TITEM> itemCreate, ReadItemDelegate<TITEM> itemReader) where TLIST : List<TITEM> { int count = Reader.ReadInt32(); list = listCreate(count); for (int i = 0; i < count; i++) { var item = itemCreate(); itemReader(ref item); list.Add(item); } return list; } private ModelBufferRange<T> GetFromList<T>(ModelData.BufferRange range, IList<T> list) { var index = range.Slot; if (index >= list.Count) { throw new InvalidOperationException(string.Format("Invalid slot [{0}] for {1} (Max: {2})", index, typeof(T).Name, list.Count)); } return new ModelBufferRange<T> { Resource = list[index], Count = range.Count, Start = range.Start }; } } }
35.699653
215
0.594028
[ "MIT" ]
VirusFree/SharpDX
Source/Toolkit/SharpDX.Toolkit.Graphics/ModelReader.cs
20,565
C#
using UnityEngine; using System.Collections; public class OneWayFollow : MonoBehaviour { public GameObject target; public Vector3 followDirection = new Vector3(1,0,0); public Vector3 positionDifference; public Vector3 newLocation; public string targetName = "Mario(Clone)"; GameObject newTarget; void Reset () { target = this.gameObject; followDirection = new Vector3(1,0,0); } void Start () { } // Update is called once per frame void Update () { if(target == null) {target = this.gameObject;} if(target != this.gameObject) { tryUpdate(); } else { tryFindTarget(); } } public void tryFindTarget() { newTarget = GameObject.Find (targetName); if(newTarget != null) target = newTarget; } public void tryUpdate() { positionDifference = (target.transform.position - this.transform.position); newLocation = positionDifference; if((newLocation.x * followDirection.x) <= 0) newLocation.x = 0; if((newLocation.y * followDirection.y) <= 0) newLocation.y = 0; if((newLocation.z * followDirection.z) <= 0) newLocation.z = 0; this.transform.position = this.transform.position + newLocation; } }
24.978261
77
0.70148
[ "MIT" ]
rusticgames/rts
Assets/Scripts/OneWayFollow.cs
1,151
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Kooboo.CMS.Sites.Extension.Management { public class AssemblyReferenceData { public AssemblyReferenceData() { } public AssemblyReferenceData(string assemblyName, string version, params string[] users) { this.AssemblyName = assemblyName; this.Version = version; if (users != null) { this.UserList = new List<string>(users); } else { this.UserList = new List<string>(); } } public string AssemblyName { get; set; } public string Version { get; set; } /// <summary> /// Gets or sets a value indicating whether [system assembly]. /// The assembly is built-in Kooboo CMS, can be updated via Kooboo CMS upgradation only. /// </summary> /// <value> /// <c>true</c> if [system assembly]; otherwise, <c>false</c>. /// </value> public bool IsSystemAssembly { get; set; } public List<string> UserList { get; set; } } }
29.625
96
0.553586
[ "BSD-3-Clause" ]
Bringsy/Kooboo.CMS
Kooboo.CMS/Kooboo.CMS.Sites/Extension/Management/AssemblyReferenceData.cs
1,187
C#
namespace AquariumAdventure { using System.Text; public class Fish { public Fish(string name, string color, int fins) { this.Name = name; this.Color = color; this.Fins = fins; } public string Name { get; } public string Color { get; } public int Fins { get; } public override string ToString() { var sb = new StringBuilder(); sb.AppendLine($"Fish: {this.Name}"); sb.AppendLine($"Color: {this.Color}"); sb.AppendLine($"Number of fins: {this.Fins}"); return sb.ToString().TrimEnd(); } } }
21.870968
58
0.50295
[ "MIT" ]
DIMITRINALU/SoftUni-Projects
C#Advanced/11. AdvancedExamPreparation/AquariumAdventure/Fish.cs
680
C#
using System; using System.Numerics; namespace Snowballs { class Program { static void Main(string[] args) { int snowballsMade = int.Parse(Console.ReadLine()); BigInteger maxValue = 0; int biggestSnowballSnow = 0; int biggestSnowballTime = 0; int biggestSnowballQuality = 0; for (int i = 1; i <= snowballsMade; i++) { int snowballSnow = int.Parse(Console.ReadLine()); int snowballTime = int.Parse(Console.ReadLine()); int snowballQuality = int.Parse(Console.ReadLine()); BigInteger snowballValue = BigInteger.Pow((snowballSnow / snowballTime), snowballQuality); if (snowballValue > maxValue) { biggestSnowballSnow = snowballSnow; biggestSnowballTime = snowballTime; biggestSnowballQuality = snowballQuality; maxValue = snowballValue; } } Console.WriteLine($"{biggestSnowballSnow} : {biggestSnowballTime} = {maxValue} ({biggestSnowballQuality})"); } } }
34.085714
120
0.549874
[ "MIT" ]
Wa4e7o/C--Fundamentals
Data Types and Variables - Exercise/Snowballs/Program.cs
1,195
C#
using Ow.Game.Movements; using Ow.Managers; using Ow.Net.netty.commands; using Ow.Utils; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Ow.Game.Objects.Collectables { class BlueBooty : Collectable { public BlueBooty(int collectableId, Position position, Spacemap spacemap, bool respawnable, Player toPlayer = null) : base(collectableId, position, spacemap, respawnable, toPlayer) { } public override void Reward(Player player) { QueryManager.SavePlayer.Information(player); } } }
26.869565
192
0.723301
[ "MIT" ]
yusufsahinhamza/darkorbit-emulators
DarkOrbit 7.5.3/Game/Objects/Collectables/BlueBooty.cs
620
C#
using System.Collections; using System.Collections.Generic; using System.Linq; using UnityEngine; public class EllipseContour : FaceElement { public LineRenderer lineRenderer; public int segments; public ControlPoint center, leftPoint, rightPoint, topPoint, bottomPoint; private List<ControlPoint> points; void Start() { leftPoint.Lock(); rightPoint.LockOnY(); topPoint.Lock(); bottomPoint.LockOnX(); points = new List<ControlPoint> { center, leftPoint, rightPoint, topPoint, bottomPoint }; lineRenderer.positionCount = segments + 1; lineRenderer.useWorldSpace = false; } // Update is called once per frame void Update() { // stretch the axis according to the contorl points leftPoint.transform.position = (transform.position - rightPoint.transform.position) + transform.position; topPoint.transform.position = (transform.position - bottomPoint.transform.position) + transform.position; // recenter the transform at the middle of the control points var centerMovement = center.transform.position - transform.position; transform.position += centerMovement; center.transform.position -= centerMovement; float xradius = (rightPoint.transform.position - transform.position).magnitude; float yradius = (bottomPoint.transform.position - transform.position).magnitude; float x; float y; float z = 0f; float angle = 20f; for (int i = 0; i < (segments + 1); i++) { x = Mathf.Sin(Mathf.Deg2Rad * angle) * xradius; y = Mathf.Cos(Mathf.Deg2Rad * angle) * yradius; lineRenderer.SetPosition(i, new Vector3(x, y, z)); angle += (360f / segments); } } public override List<Point> LockAndReturnPoints() { foreach (var p in points) p.Lock(); return points.Select(p => p.Point).ToList(); } public void Rotate(float rotation) { transform.Rotate(Vector3.forward, rotation); } }
30.376812
113
0.643607
[ "MIT" ]
effacestudios/ImageTo3DCharacter
Assets/EllipseContour.cs
2,098
C#
namespace ICSSoft.STORMNET.Web { using System.Web.Routing; using ICSSoft.STORMNET.Web.Tools; using NewPlatform.Flexberry.Web.Routing; /// <summary> /// Класс конфигурации маршрутов приложения. /// </summary> public static class RouteConfig { /// <summary> /// Метод для регистрации маршрутов в коллекции. /// При изменении адреса страниц не забудьте произвести соответсвующие изменения в SiteMap. /// </summary> /// <param name="routes">Коллекция маршрутов, в которую необходимо добавить новые элементы.</param> public static void RegisterRoutes(RouteCollection routes) { // Маршруты до технологических страниц. routes.AddDynamicPageRoute("flexberry/AuditEntitiesList", DynamicPageIdentifier.AuditEntitiesList); routes.AddDynamicPageRoute("flexberry/AuditEntityByObjectView/{PK}", DynamicPageIdentifier.AuditEntityByObjectView); routes.AddDynamicPageRoute("flexberry/AuditEntityByObjectsList", DynamicPageIdentifier.AuditEntityByObjectsList); routes.AddDynamicPageRoute("flexberry/AuditEntityView/{PK}", DynamicPageIdentifier.AuditEntityView); routes.AddDynamicPageRoute("flexberry/LocksList", DynamicPageIdentifier.LocksList); routes.AddDynamicPageRoute("flexberry/LogList", DynamicPageIdentifier.LogList); routes.AddDynamicPageRoute("flexberry/LogEntry/{PK}", DynamicPageIdentifier.LogEntry); // Регистрируем маршруты на технологические формы отчетов только в том случае, если загружена сборка // ICSSoft.STORMNET.Web.Reports, т.к. она вынесена в отдельный пакет с веб-отчетами. if (AssemblyHelper.IsWebReportsPackageLoaded()) { routes.AddDynamicPageRoute("flexberry/ModuleReportTemplateEdit/{PK}", DynamicPageIdentifier.ModuleReportTemplateEdit); routes.AddDynamicPageRoute("flexberry/ReportDocumentEdit/{PK}", DynamicPageIdentifier.ReportDocumentEdit); routes.AddDynamicPageRoute("flexberry/ReportDocumentsList", DynamicPageIdentifier.ReportDocumentsList); routes.AddDynamicPageRoute("flexberry/ReportExportTaskView/{PK}", DynamicPageIdentifier.ReportExportTaskView); routes.AddDynamicPageRoute("flexberry/ReportExportTasksList", DynamicPageIdentifier.ReportExportTasksList); routes.AddDynamicPageRoute("flexberry/ReportTemplateEdit/{PK}", DynamicPageIdentifier.ReportTemplateEdit); routes.AddDynamicPageRoute("flexberry/ReportTemplatesList", DynamicPageIdentifier.ReportTemplatesList); routes.AddDynamicPageRoute("flexberry/ReportTypeEdit/{PK}", DynamicPageIdentifier.ReportTypeEdit); routes.AddDynamicPageRoute("flexberry/ReportTypesList", DynamicPageIdentifier.ReportTypesList); } routes.AddDynamicPageRoute("flexberry/SecurityClassEdit/{PK}", DynamicPageIdentifier.SecurityClassEdit); routes.AddDynamicPageRoute("flexberry/SecurityClassEdit", DynamicPageIdentifier.SecurityClassNew); routes.AddDynamicPageRoute("flexberry/SecurityClassesList", DynamicPageIdentifier.SecurityClassesList); routes.AddDynamicPageRoute("flexberry/SecurityRoleEdit/{PK}", DynamicPageIdentifier.SecurityRoleEdit); routes.AddDynamicPageRoute("flexberry/SecurityRoleEdit", DynamicPageIdentifier.SecurityRoleNew); routes.AddDynamicPageRoute("flexberry/SecurityRolesList", DynamicPageIdentifier.SecurityRolesList); routes.AddDynamicPageRoute("flexberry/SecurityUserEdit/{PK}", DynamicPageIdentifier.SecurityUserEdit); routes.AddDynamicPageRoute("flexberry/SecurityUserEdit", DynamicPageIdentifier.SecurityUserNew); routes.AddDynamicPageRoute("flexberry/SecurityUsersList", DynamicPageIdentifier.SecurityUsersList); routes.AddDynamicPageRoute("flexberry/SecurityGroupEdit/{PK}", DynamicPageIdentifier.SecurityGroupEdit); routes.AddDynamicPageRoute("flexberry/SecurityGroupEdit", DynamicPageIdentifier.SecurityGroupNew); routes.AddDynamicPageRoute("flexberry/SecurityGroupsList", DynamicPageIdentifier.SecurityGroupsList); routes.AddDynamicPageRoute("flexberry/SecurityOperationEdit/{PK}", DynamicPageIdentifier.SecurityOperationEdit); routes.AddDynamicPageRoute("flexberry/SecurityOperationEdit", DynamicPageIdentifier.SecurityOperationNew); routes.AddDynamicPageRoute("flexberry/SecurityOperationsList", DynamicPageIdentifier.SecurityOperationsList); routes.AddDynamicPageRoute("flexberry/Version", DynamicPageIdentifier.Version); routes.AddDynamicPageRoute("flexberry/Cache", DynamicPageIdentifier.CacheAdmin); routes.Ignore("Myfavicon.ico"); } } }
69.385714
134
0.747787
[ "MIT" ]
v1nnyb0y/HSE.Cources.SoftwareDesign
Lab.8.Flexberry/CodeGen/Product_4858/Product_4858/ASP.NET/App_Start/RouteConfig.cs
5,215
C#
//MIT, 2020, Brezza92 using PixelFarm.Drawing.Internal; using System; using System.Collections.Generic; using System.Text; namespace MathLayout { public class OperatorTableCreator { public void AutogenFrom(string filename) { OperatorInfoDictionary operatorInfo = new OperatorInfoDictionary(); operatorInfo.Read(filename); SeparateToPropertyDict(operatorInfo.Result); Autogen(); } private void SeparateToPropertyDict(Dictionary<string, OperatorInfo> opDict) { foreach (var op in opDict) { OperatorInfo info = op.Value; OperatorProperty property = info.Properties; if (property == OperatorProperty.None) { continue; } AddToDictIfContainProperty(info, OperatorProperty.Accent); AddToDictIfContainProperty(info, OperatorProperty.Fence); AddToDictIfContainProperty(info, OperatorProperty.LargeOp); AddToDictIfContainProperty(info, OperatorProperty.LineBreakStyle); AddToDictIfContainProperty(info, OperatorProperty.MovableLimits); AddToDictIfContainProperty(info, OperatorProperty.Separator); AddToDictIfContainProperty(info, OperatorProperty.Stretchy); AddToDictIfContainProperty(info, OperatorProperty.Symmetric); } } private void Autogen() { CodeWriter codeWriter = new CodeWriter(); codeWriter.AppendLine("//Autogen," + DateTime.Now.ToString("s")); codeWriter.AppendLine("//-----"); codeWriter.AppendLine("//Operator dictionary entries reference https://www.w3.org/TR/MathML3/appendixc.html"); codeWriter.AppendLine(); //generate namespace codeWriter.AppendLine("namespace MathLayout"); codeWriter.AppendLine("{");//start namespace area codeWriter.Indent++; codeWriter.AppendLine("public static class MathMLOperatorTable"); codeWriter.AppendLine("{");//start class area codeWriter.Indent++; codeWriter.AppendLine(); //extend case codeWriter.AppendLine("public static bool IsInvicibleCharacter (char ch)"); codeWriter.AppendLine("{"); codeWriter.Indent++; codeWriter.AppendLine("switch ((int)ch)"); codeWriter.AppendLine("{"); codeWriter.Indent++; codeWriter.AppendLine("case 0x2061:"); codeWriter.AppendLine("case 0x2062:"); codeWriter.AppendLine("case 0x2063:"); codeWriter.AppendLine("case 0x2064:"); codeWriter.Indent++; codeWriter.AppendLine("return true;"); codeWriter.Indent--; codeWriter.AppendLine("default:"); codeWriter.Indent++; codeWriter.AppendLine("return false;"); codeWriter.Indent--; codeWriter.Indent--; codeWriter.AppendLine("}"); codeWriter.Indent--; codeWriter.AppendLine("}"); foreach (var prop in _propertyDict) { codeWriter.AppendLine("public static bool Is" + prop.Key + "PropertyOperator (string op)"); codeWriter.AppendLine("{");//start method area codeWriter.Indent++; codeWriter.AppendLine("switch (op)"); codeWriter.AppendLine("{");//start switch case area codeWriter.Indent++; codeWriter.AppendLine("default: return false;"); //each op in List foreach(var op in prop.Value) { if (op.Operator != "\"") { codeWriter.AppendLine("case \"" + op.Operator + "\":"); } else { codeWriter.AppendLine("case \"\\" + op.Operator + "\":"); } } codeWriter.AppendLine("return true;"); codeWriter.Indent--; codeWriter.AppendLine("}");//end switch case area codeWriter.Indent--; codeWriter.AppendLine("}");//end method area } codeWriter.AppendLine(); codeWriter.Indent--; codeWriter.AppendLine("}");//end class area codeWriter.Indent--; codeWriter.AppendLine("}");//end namespace area System.IO.File.WriteAllText("..\\..\\Operator Dictionary\\OperatorTableAutogen.cs", codeWriter.ToString()); } private Dictionary<OperatorProperty, List<OperatorInfo>> _propertyDict = new Dictionary<OperatorProperty, List<OperatorInfo>>(); private void AddToDictIfContainProperty(OperatorInfo info, OperatorProperty targetProoerty) { OperatorProperty infoProp = info.Properties; if ((infoProp &= targetProoerty) > 0) { List<OperatorInfo> temp; if (_propertyDict.TryGetValue(targetProoerty, out temp)) { temp.Add(info); } else { List<OperatorInfo> infos = new List<OperatorInfo>(); infos.Add(info); _propertyDict.Add(targetProoerty, infos); } } } } }
37.657718
136
0.546427
[ "MIT" ]
Ferdowsur/Typography
Demo/Windows/MathLayout/MathLayout/Tools/OpeatorTableCreator.cs
5,613
C#
#nullable enable using Uno.Extensions; using Uno.UI.DataBinding; using Windows.UI.Xaml; using Uno.UI.Extensions; using Windows.UI.Xaml.Data; using System; using System.Collections.Generic; using System.Drawing; using Uno.Disposables; using System.Runtime.CompilerServices; using System.Text; using System.Linq; using Foundation; using UIKit; using CoreGraphics; namespace Windows.UI.Xaml.Controls { public partial class ScrollViewer : ContentControl, ICustomClippingElement { /// <summary> /// On iOS 10-, we set a flag on the view controller such that the CommandBar doesn't automatically affect ScrollViewer content /// placement. On iOS 11+, we set this behavior on the UIScrollView itself. /// </summary> internal static bool UseContentInsetAdjustmentBehavior => UIDevice.CurrentDevice.CheckSystemVersion(11, 0); /// <summary> /// The <see cref="UIScrollView"/> which will actually scroll. Mostly this will be identical to <see cref="_presenter"/>, but if we're inside a /// multi-line TextBox we set it to <see cref="MultilineTextBoxView"/>. /// </summary> private IUIScrollView? _scrollableContainer; partial void OnApplyTemplatePartial() { SetScrollableContainer(); } private protected override void OnLoaded() { SetScrollableContainer(); base.OnLoaded(); } private void SetScrollableContainer() { _scrollableContainer = _presenter; if (this.FindFirstParent<TextBox>() != null) { var multiline = ((UIView)this).FindFirstChild<MultilineTextBoxView>(); if (multiline != null) { _scrollableContainer = multiline; } } } private (double? horizontal, double? vertical, bool disableAnimation)? _pendingChangeView; protected override void OnAfterArrange() { base.OnAfterArrange(); if (_pendingChangeView is {} req) { var success = ChangeViewNative(req.horizontal, req.vertical, null, req.disableAnimation); if (success || !IsArrangeDirty) { _pendingChangeView = default; } } } private bool ChangeViewNative(double? horizontalOffset, double? verticalOffset, float? zoomFactor, bool disableAnimation) { if (_scrollableContainer != null) { // iOS doesn't limit the offset to the scrollable bounds by itself var limit = _scrollableContainer.UpperScrollLimit; var desiredOffsets = new Windows.Foundation.Point(horizontalOffset ?? HorizontalOffset, verticalOffset ?? VerticalOffset); var clampedOffsets = new Windows.Foundation.Point(MathEx.Clamp(desiredOffsets.X, 0, limit.X), MathEx.Clamp(desiredOffsets.Y, 0, limit.Y)); var success = desiredOffsets == clampedOffsets; if (!success && IsArrangeDirty) { // If the the requested offsets are out-of - bounds, but we actually does have our final bounds yet, // we allow to set the desired offsets. If needed, they will then be clamped by the OnAfterArrange(). // This is needed to allow a ScrollTo before the SV has been layouted. _pendingChangeView = (horizontalOffset, verticalOffset, disableAnimation); _scrollableContainer.SetContentOffset(desiredOffsets, !disableAnimation); } else { _scrollableContainer.SetContentOffset(clampedOffsets, !disableAnimation); } if(zoomFactor is { } zoom) { ChangeViewZoom(zoom, disableAnimation); } // Return true if successfully scrolled to asked offsets return success; } return false; } partial void OnZoomModeChangedPartial(ZoomMode zoomMode) { // On iOS, zooming is disabled by setting Minimum/MaximumZoomScale both to 1 switch (zoomMode) { case ZoomMode.Disabled: default: _presenter?.OnMinZoomFactorChanged(1f); _presenter?.OnMaxZoomFactorChanged(1f); break; case ZoomMode.Enabled: _presenter?.OnMinZoomFactorChanged(MinZoomFactor); _presenter?.OnMaxZoomFactorChanged(MaxZoomFactor); break; } } private void ChangeViewZoom(float zoomFactor, bool disableAnimation) { _scrollableContainer?.SetZoomScale(zoomFactor, animated: !disableAnimation); } private void UpdateZoomedContentAlignment() { if (ZoomFactor != 1 && Content is IFrameworkElement fe) { double insetLeft, insetTop; var scaledWidth = fe.ActualWidth * ZoomFactor; var viewportWidth = ActualWidth; if (viewportWidth <= scaledWidth) { insetLeft = 0; } else { switch (fe.HorizontalAlignment) { case HorizontalAlignment.Left: insetLeft = 0; break; case HorizontalAlignment.Right: insetLeft = viewportWidth - scaledWidth; break; case HorizontalAlignment.Center: case HorizontalAlignment.Stretch: insetLeft = .5 * (viewportWidth - scaledWidth); break; default: throw new InvalidOperationException(); } } var scaledHeight = fe.ActualHeight * ZoomFactor; var viewportHeight = ActualHeight; if (viewportHeight <= scaledHeight) { insetTop = 0; } else { switch (fe.VerticalAlignment) { case VerticalAlignment.Top: insetTop = 0; break; case VerticalAlignment.Bottom: insetTop = viewportHeight - scaledHeight; break; case VerticalAlignment.Center: case VerticalAlignment.Stretch: insetTop = .5 * (viewportHeight - scaledHeight); break; default: throw new InvalidOperationException(); } } if (_presenter != null) { _presenter.ContentInset = new UIEdgeInsets((nfloat)insetTop, (nfloat)insetLeft, 0, 0); } } } public override void WillMoveToSuperview(UIView newsuper) { base.WillMoveToSuperview(newsuper); UpdateSizeChangedSubscription(isCleanupRequired: newsuper == null); } bool ICustomClippingElement.AllowClippingToLayoutSlot => true; bool ICustomClippingElement.ForceClippingToLayoutSlot => true; // force scrollviewer to always clip } }
28.475962
145
0.703866
[ "Apache-2.0" ]
Abhishek-Sharma-Msft/uno
src/Uno.UI/UI/Xaml/Controls/ScrollViewer/ScrollViewer.iOS.cs
5,925
C#
#nullable enable using System; namespace Avalonia.LogicalTree { /// <summary> /// Event args for <see cref="IChildIndexProvider.ChildIndexChanged"/> event. /// </summary> public class ChildIndexChangedEventArgs : EventArgs { public static new ChildIndexChangedEventArgs Empty { get; } = new ChildIndexChangedEventArgs(); private ChildIndexChangedEventArgs() { } public ChildIndexChangedEventArgs(ILogical child) { Child = child; } /// <summary> /// Logical child which index was changed. /// If null, all children should be reset. /// </summary> public ILogical? Child { get; } } }
24.793103
103
0.607789
[ "MIT" ]
0x0ade/Avalonia
src/Avalonia.Base/LogicalTree/ChildIndexChangedEventArgs.cs
721
C#
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. using System.Collections.Generic; using System.Text.RegularExpressions; namespace Microsoft.Recognizers.Text.DateTime { public interface ITimePeriodExtractorConfiguration : IDateTimeOptionsConfiguration { string TokenBeforeDate { get; } IExtractor IntegerExtractor { get; } IEnumerable<Regex> SimpleCasesRegex { get; } IEnumerable<Regex> PureNumberRegex { get; } bool CheckBothBeforeAfter { get; } Regex TillRegex { get; } Regex TimeOfDayRegex { get; } Regex GeneralEndingRegex { get; } IDateTimeExtractor SingleTimeExtractor { get; } IDateTimeExtractor TimeZoneExtractor { get; } bool GetFromTokenIndex(string text, out int index); bool IsConnectorToken(string text); bool GetBetweenTokenIndex(string text, out int index); List<ExtractResult> ApplyPotentialPeriodAmbiguityHotfix(string text, List<ExtractResult> timePeriodErs); } }
27.384615
112
0.705993
[ "MIT" ]
17000cyh/Recognizers-Text
.NET/Microsoft.Recognizers.Text.DateTime/Extractors/ITimePeriodExtractorConfiguration.cs
1,070
C#
// *** WARNING: this file was generated by the Pulumi SDK Generator. *** // *** 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.AzureNative.DataFactory.Latest.Inputs { /// <summary> /// A copy activity Azure SQL source. /// </summary> public sealed class AzureSqlSourceArgs : Pulumi.ResourceArgs { [Input("additionalColumns")] private InputList<Inputs.AdditionalColumnsArgs>? _additionalColumns; /// <summary> /// Specifies the additional columns to be added to source data. Type: array of objects (or Expression with resultType array of objects). /// </summary> public InputList<Inputs.AdditionalColumnsArgs> AdditionalColumns { get => _additionalColumns ?? (_additionalColumns = new InputList<Inputs.AdditionalColumnsArgs>()); set => _additionalColumns = value; } /// <summary> /// The maximum concurrent connection count for the source data store. Type: integer (or Expression with resultType integer). /// </summary> [Input("maxConcurrentConnections")] public Input<object>? MaxConcurrentConnections { get; set; } /// <summary> /// The partition mechanism that will be used for Sql read in parallel. Possible values include: "None", "PhysicalPartitionsOfTable", "DynamicRange". /// </summary> [Input("partitionOption")] public Input<object>? PartitionOption { get; set; } /// <summary> /// The settings that will be leveraged for Sql source partitioning. /// </summary> [Input("partitionSettings")] public Input<Inputs.SqlPartitionSettingsArgs>? PartitionSettings { get; set; } /// <summary> /// Which additional types to produce. /// </summary> [Input("produceAdditionalTypes")] public Input<object>? ProduceAdditionalTypes { get; set; } /// <summary> /// Query timeout. Type: string (or Expression with resultType string), pattern: ((\d+)\.)?(\d\d):(60|([0-5][0-9])):(60|([0-5][0-9])). /// </summary> [Input("queryTimeout")] public Input<object>? QueryTimeout { get; set; } /// <summary> /// Source retry count. Type: integer (or Expression with resultType integer). /// </summary> [Input("sourceRetryCount")] public Input<object>? SourceRetryCount { get; set; } /// <summary> /// Source retry wait. Type: string (or Expression with resultType string), pattern: ((\d+)\.)?(\d\d):(60|([0-5][0-9])):(60|([0-5][0-9])). /// </summary> [Input("sourceRetryWait")] public Input<object>? SourceRetryWait { get; set; } /// <summary> /// SQL reader query. Type: string (or Expression with resultType string). /// </summary> [Input("sqlReaderQuery")] public Input<object>? SqlReaderQuery { get; set; } /// <summary> /// Name of the stored procedure for a SQL Database source. This cannot be used at the same time as SqlReaderQuery. Type: string (or Expression with resultType string). /// </summary> [Input("sqlReaderStoredProcedureName")] public Input<object>? SqlReaderStoredProcedureName { get; set; } [Input("storedProcedureParameters")] private InputMap<Inputs.StoredProcedureParameterArgs>? _storedProcedureParameters; /// <summary> /// Value and type setting for stored procedure parameters. Example: "{Parameter1: {value: "1", type: "int"}}". /// </summary> public InputMap<Inputs.StoredProcedureParameterArgs> StoredProcedureParameters { get => _storedProcedureParameters ?? (_storedProcedureParameters = new InputMap<Inputs.StoredProcedureParameterArgs>()); set => _storedProcedureParameters = value; } /// <summary> /// Copy source type. /// Expected value is 'TabularSource'. /// </summary> [Input("type", required: true)] public Input<string> Type { get; set; } = null!; public AzureSqlSourceArgs() { } } }
40.277778
176
0.621149
[ "Apache-2.0" ]
pulumi-bot/pulumi-azure-native
sdk/dotnet/DataFactory/Latest/Inputs/AzureSqlSourceArgs.cs
4,350
C#
/****************************************************************************** * The MIT License * Copyright (c) 2003 Novell Inc. www.novell.com * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the Software), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED AS IS, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. *******************************************************************************/ using Novell.Directory.Ldap.Asn1; namespace Novell.Directory.Ldap.Rfc2251 { /// <summary> /// Represents an Ldap Substring Filter. /// <pre> /// SubstringFilter ::= SEQUENCE { /// type AttributeDescription, /// -- at least one must be present /// substrings SEQUENCE OF CHOICE { /// initial [0] LdapString, /// any [1] LdapString, /// final [2] LdapString } } /// </pre> /// </summary> public class RfcSubstringFilter : Asn1Sequence { // ************************************************************************* // Constructors for SubstringFilter // ************************************************************************* /// <summary> </summary> public RfcSubstringFilter(RfcAttributeDescription type, Asn1SequenceOf substrings) : base(2) { Add(type); Add(substrings); } } }
41.981818
90
0.570377
[ "MIT" ]
dogguts/Novell.Directory.Ldap.NETStandard
src/Novell.Directory.Ldap.NETStandard/Rfc2251/RfcSubstringFilter.cs
2,311
C#
using InterflowFramework.Core.Channel.OutputPoint; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace InterflowFramework.Core.Factory.Point { public class OutPointCreateInfo: PointCreateInfo<IOutputPoint> { } }
20.785714
63
0.821306
[ "Apache-2.0" ]
AlexanderMykulych/InterflowFramework
InterflowFramework/InterflowFramework/Core/Factory/Point/OutPointCreateInfo.cs
293
C#
using System; using System.Reflection; [assembly: AssemblyVersion("2.0.0.53")] [assembly: AssemblyFileVersion("2.0.0.53")]
20.833333
43
0.736
[ "MIT" ]
horseyhorsey/Hypermint.2.0
src/SharedAssemblyInfo.cs
127
C#
using System.Collections.Generic; using System.Net; using System.Threading.Tasks; namespace Octokit { /// <summary> /// A client for GitHub's Pull Request Review Comments API. /// </summary> /// <remarks> /// See the <a href="https://developer.github.com/v3/pulls/comments/">Review Comments API documentation</a> for more information. /// </remarks> public class PullRequestReviewCommentsClient : ApiClient, IPullRequestReviewCommentsClient { public PullRequestReviewCommentsClient(IApiConnection apiConnection) : base(apiConnection) { } /// <summary> /// Gets review comments for a specified pull request. /// </summary> /// <remarks>http://developer.github.com/v3/pulls/comments/#list-comments-on-a-pull-request</remarks> /// <param name="owner">The owner of the repository</param> /// <param name="name">The name of the repository</param> /// <param name="number">The pull request number</param> public Task<IReadOnlyList<PullRequestReviewComment>> GetAll(string owner, string name, int number) { Ensure.ArgumentNotNullOrEmptyString(owner, nameof(owner)); Ensure.ArgumentNotNullOrEmptyString(name, nameof(name)); return GetAll(owner, name, number, ApiOptions.None); } /// <summary> /// Gets review comments for a specified pull request. /// </summary> /// <remarks>http://developer.github.com/v3/pulls/comments/#list-comments-on-a-pull-request</remarks> /// <param name="repositoryId">The Id of the repository</param> /// <param name="number">The pull request number</param> public Task<IReadOnlyList<PullRequestReviewComment>> GetAll(long repositoryId, int number) { return GetAll(repositoryId, number, ApiOptions.None); } /// <summary> /// Gets review comments for a specified pull request. /// </summary> /// <remarks>http://developer.github.com/v3/pulls/comments/#list-comments-on-a-pull-request</remarks> /// <param name="owner">The owner of the repository</param> /// <param name="name">The name of the repository</param> /// <param name="number">The pull request number</param> /// <param name="options">Options for changing the API response</param> public Task<IReadOnlyList<PullRequestReviewComment>> GetAll(string owner, string name, int number, ApiOptions options) { Ensure.ArgumentNotNullOrEmptyString(owner, nameof(owner)); Ensure.ArgumentNotNullOrEmptyString(name, nameof(name)); Ensure.ArgumentNotNull(options, nameof(options)); return ApiConnection.GetAll<PullRequestReviewComment>(ApiUrls.PullRequestReviewComments(owner, name, number), null, AcceptHeaders.ReactionsPreview, options); } /// <summary> /// Gets review comments for a specified pull request. /// </summary> /// <remarks>http://developer.github.com/v3/pulls/comments/#list-comments-on-a-pull-request</remarks> /// <param name="repositoryId">The Id of the repository</param> /// <param name="number">The pull request number</param> /// <param name="options">Options for changing the API response</param> public Task<IReadOnlyList<PullRequestReviewComment>> GetAll(long repositoryId, int number, ApiOptions options) { Ensure.ArgumentNotNull(options, nameof(options)); return ApiConnection.GetAll<PullRequestReviewComment>(ApiUrls.PullRequestReviewComments(repositoryId, number), options); } /// <summary> /// Gets a list of the pull request review comments in a specified repository. /// </summary> /// <remarks>http://developer.github.com/v3/pulls/comments/#list-comments-in-a-repository</remarks> /// <param name="owner">The owner of the repository</param> /// <param name="name">The name of the repository</param> public Task<IReadOnlyList<PullRequestReviewComment>> GetAllForRepository(string owner, string name) { Ensure.ArgumentNotNullOrEmptyString(owner, nameof(owner)); Ensure.ArgumentNotNullOrEmptyString(name, nameof(name)); return GetAllForRepository(owner, name, new PullRequestReviewCommentRequest(), ApiOptions.None); } /// <summary> /// Gets a list of the pull request review comments in a specified repository. /// </summary> /// <remarks>http://developer.github.com/v3/pulls/comments/#list-comments-in-a-repository</remarks> /// <param name="repositoryId">The Id of the repository</param> public Task<IReadOnlyList<PullRequestReviewComment>> GetAllForRepository(long repositoryId) { return GetAllForRepository(repositoryId, new PullRequestReviewCommentRequest(), ApiOptions.None); } /// <summary> /// Gets a list of the pull request review comments in a specified repository. /// </summary> /// <remarks>http://developer.github.com/v3/pulls/comments/#list-comments-in-a-repository</remarks> /// <param name="owner">The owner of the repository</param> /// <param name="name">The name of the repository</param> /// <param name="options">Options for changing the API response</param> public Task<IReadOnlyList<PullRequestReviewComment>> GetAllForRepository(string owner, string name, ApiOptions options) { Ensure.ArgumentNotNullOrEmptyString(owner, nameof(owner)); Ensure.ArgumentNotNullOrEmptyString(name, nameof(name)); Ensure.ArgumentNotNull(options, nameof(options)); return GetAllForRepository(owner, name, new PullRequestReviewCommentRequest(), options); } /// <summary> /// Gets a list of the pull request review comments in a specified repository. /// </summary> /// <remarks>http://developer.github.com/v3/pulls/comments/#list-comments-in-a-repository</remarks> /// <param name="repositoryId">The Id of the repository</param> /// <param name="options">Options for changing the API response</param> public Task<IReadOnlyList<PullRequestReviewComment>> GetAllForRepository(long repositoryId, ApiOptions options) { Ensure.ArgumentNotNull(options, nameof(options)); return GetAllForRepository(repositoryId, new PullRequestReviewCommentRequest(), options); } /// <summary> /// Gets a list of the pull request review comments in a specified repository. /// </summary> /// <remarks>http://developer.github.com/v3/pulls/comments/#list-comments-in-a-repository</remarks> /// <param name="owner">The owner of the repository</param> /// <param name="name">The name of the repository</param> /// <param name="request">The sorting <see cref="PullRequestReviewCommentRequest">parameters</see></param> public Task<IReadOnlyList<PullRequestReviewComment>> GetAllForRepository(string owner, string name, PullRequestReviewCommentRequest request) { Ensure.ArgumentNotNullOrEmptyString(owner, nameof(owner)); Ensure.ArgumentNotNullOrEmptyString(name, nameof(name)); Ensure.ArgumentNotNull(request, nameof(request)); return GetAllForRepository(owner, name, request, ApiOptions.None); } /// <summary> /// Gets a list of the pull request review comments in a specified repository. /// </summary> /// <remarks>http://developer.github.com/v3/pulls/comments/#list-comments-in-a-repository</remarks> /// <param name="repositoryId">The Id of the repository</param> /// <param name="request">The sorting <see cref="PullRequestReviewCommentRequest">parameters</see></param> public Task<IReadOnlyList<PullRequestReviewComment>> GetAllForRepository(long repositoryId, PullRequestReviewCommentRequest request) { Ensure.ArgumentNotNull(request, nameof(request)); return GetAllForRepository(repositoryId, request, ApiOptions.None); } /// <summary> /// Gets a list of the pull request review comments in a specified repository. /// </summary> /// <remarks>http://developer.github.com/v3/pulls/comments/#list-comments-in-a-repository</remarks> /// <param name="owner">The owner of the repository</param> /// <param name="name">The name of the repository</param> /// <param name="request">The sorting <see cref="PullRequestReviewCommentRequest">parameters</see></param> /// <param name="options">Options for changing the API response</param> public Task<IReadOnlyList<PullRequestReviewComment>> GetAllForRepository(string owner, string name, PullRequestReviewCommentRequest request, ApiOptions options) { Ensure.ArgumentNotNullOrEmptyString(owner, nameof(owner)); Ensure.ArgumentNotNullOrEmptyString(name, nameof(name)); Ensure.ArgumentNotNull(request, nameof(request)); Ensure.ArgumentNotNull(options, nameof(options)); return ApiConnection.GetAll<PullRequestReviewComment>(ApiUrls.PullRequestReviewCommentsRepository(owner, name), request.ToParametersDictionary(), AcceptHeaders.ReactionsPreview, options); } /// <summary> /// Gets a list of the pull request review comments in a specified repository. /// </summary> /// <remarks>http://developer.github.com/v3/pulls/comments/#list-comments-in-a-repository</remarks> /// <param name="repositoryId">The Id of the repository</param> /// <param name="request">The sorting <see cref="PullRequestReviewCommentRequest">parameters</see></param> /// <param name="options">Options for changing the API response</param> public Task<IReadOnlyList<PullRequestReviewComment>> GetAllForRepository(long repositoryId, PullRequestReviewCommentRequest request, ApiOptions options) { Ensure.ArgumentNotNull(request, nameof(request)); Ensure.ArgumentNotNull(options, nameof(options)); return ApiConnection.GetAll<PullRequestReviewComment>(ApiUrls.PullRequestReviewCommentsRepository(repositoryId), request.ToParametersDictionary(), AcceptHeaders.ReactionsPreview, options); } /// <summary> /// Gets a single pull request review comment by number. /// </summary> /// <remarks>http://developer.github.com/v3/pulls/comments/#get-a-single-comment</remarks> /// <param name="owner">The owner of the repository</param> /// <param name="name">The name of the repository</param> /// <param name="number">The pull request review comment number</param> public Task<PullRequestReviewComment> GetComment(string owner, string name, int number) { Ensure.ArgumentNotNullOrEmptyString(owner, nameof(owner)); Ensure.ArgumentNotNullOrEmptyString(name, nameof(name)); return ApiConnection.Get<PullRequestReviewComment>(ApiUrls.PullRequestReviewComment(owner, name, number), new Dictionary<string, string>(), AcceptHeaders.ReactionsPreview); } /// <summary> /// Gets a single pull request review comment by number. /// </summary> /// <remarks>http://developer.github.com/v3/pulls/comments/#get-a-single-comment</remarks> /// <param name="repositoryId">The Id of the repository</param> /// <param name="number">The pull request review comment number</param> public Task<PullRequestReviewComment> GetComment(long repositoryId, int number) { return ApiConnection.Get<PullRequestReviewComment>(ApiUrls.PullRequestReviewComment(repositoryId, number)); } /// <summary> /// Creates a comment on a pull request review. /// </summary> /// <remarks>http://developer.github.com/v3/pulls/comments/#create-a-comment</remarks> /// <param name="owner">The owner of the repository</param> /// <param name="name">The name of the repository</param> /// <param name="number">The Pull Request number</param> /// <param name="comment">The comment</param> public async Task<PullRequestReviewComment> Create(string owner, string name, int number, PullRequestReviewCommentCreate comment) { Ensure.ArgumentNotNullOrEmptyString(owner, nameof(owner)); Ensure.ArgumentNotNullOrEmptyString(name, nameof(name)); Ensure.ArgumentNotNull(comment, nameof(comment)); var endpoint = ApiUrls.PullRequestReviewComments(owner, name, number); var response = await ApiConnection.Connection.Post<PullRequestReviewComment>(endpoint, comment, null, null).ConfigureAwait(false); if (response.HttpResponse.StatusCode != HttpStatusCode.Created) { throw new ApiException("Invalid Status Code returned. Expected a 201", response.HttpResponse.StatusCode); } return response.Body; } /// <summary> /// Creates a comment on a pull request review. /// </summary> /// <remarks>http://developer.github.com/v3/pulls/comments/#create-a-comment</remarks> /// <param name="repositoryId">The Id of the repository</param> /// <param name="number">The Pull Request number</param> /// <param name="comment">The comment</param> public async Task<PullRequestReviewComment> Create(long repositoryId, int number, PullRequestReviewCommentCreate comment) { Ensure.ArgumentNotNull(comment, nameof(comment)); var endpoint = ApiUrls.PullRequestReviewComments(repositoryId, number); var response = await ApiConnection.Connection.Post<PullRequestReviewComment>(endpoint, comment, null, null).ConfigureAwait(false); if (response.HttpResponse.StatusCode != HttpStatusCode.Created) { throw new ApiException("Invalid Status Code returned. Expected a 201", response.HttpResponse.StatusCode); } return response.Body; } /// <summary> /// Creates a comment on a pull request review as a reply to another comment. /// </summary> /// <remarks>http://developer.github.com/v3/pulls/comments/#create-a-comment</remarks> /// <param name="owner">The owner of the repository</param> /// <param name="name">The name of the repository</param> /// <param name="number">The pull request number</param> /// <param name="comment">The comment</param> public async Task<PullRequestReviewComment> CreateReply(string owner, string name, int number, PullRequestReviewCommentReplyCreate comment) { Ensure.ArgumentNotNullOrEmptyString(owner, nameof(owner)); Ensure.ArgumentNotNullOrEmptyString(name, nameof(name)); Ensure.ArgumentNotNull(comment, nameof(comment)); var endpoint = ApiUrls.PullRequestReviewComments(owner, name, number); var response = await ApiConnection.Connection.Post<PullRequestReviewComment>(endpoint, comment, null, null).ConfigureAwait(false); if (response.HttpResponse.StatusCode != HttpStatusCode.Created) { throw new ApiException("Invalid Status Code returned. Expected a 201", response.HttpResponse.StatusCode); } return response.Body; } /// <summary> /// Creates a comment on a pull request review as a reply to another comment. /// </summary> /// <remarks>http://developer.github.com/v3/pulls/comments/#create-a-comment</remarks> /// <param name="repositoryId">The Id of the repository</param> /// <param name="number">The pull request number</param> /// <param name="comment">The comment</param> public async Task<PullRequestReviewComment> CreateReply(long repositoryId, int number, PullRequestReviewCommentReplyCreate comment) { Ensure.ArgumentNotNull(comment, nameof(comment)); var endpoint = ApiUrls.PullRequestReviewComments(repositoryId, number); var response = await ApiConnection.Connection.Post<PullRequestReviewComment>(endpoint, comment, null, null).ConfigureAwait(false); if (response.HttpResponse.StatusCode != HttpStatusCode.Created) { throw new ApiException("Invalid Status Code returned. Expected a 201", response.HttpResponse.StatusCode); } return response.Body; } /// <summary> /// Edits a comment on a pull request review. /// </summary> /// <remarks>http://developer.github.com/v3/pulls/comments/#edit-a-comment</remarks> /// <param name="owner">The owner of the repository</param> /// <param name="name">The name of the repository</param> /// <param name="number">The pull request review comment number</param> /// <param name="comment">The edited comment</param> public Task<PullRequestReviewComment> Edit(string owner, string name, int number, PullRequestReviewCommentEdit comment) { Ensure.ArgumentNotNullOrEmptyString(owner, nameof(owner)); Ensure.ArgumentNotNullOrEmptyString(name, nameof(name)); Ensure.ArgumentNotNull(comment, nameof(comment)); return ApiConnection.Patch<PullRequestReviewComment>(ApiUrls.PullRequestReviewComment(owner, name, number), comment); } /// <summary> /// Edits a comment on a pull request review. /// </summary> /// <remarks>http://developer.github.com/v3/pulls/comments/#edit-a-comment</remarks> /// <param name="repositoryId">The Id of the repository</param> /// <param name="number">The pull request review comment number</param> /// <param name="comment">The edited comment</param> public Task<PullRequestReviewComment> Edit(long repositoryId, int number, PullRequestReviewCommentEdit comment) { Ensure.ArgumentNotNull(comment, nameof(comment)); return ApiConnection.Patch<PullRequestReviewComment>(ApiUrls.PullRequestReviewComment(repositoryId, number), comment); } /// <summary> /// Deletes a comment on a pull request review. /// </summary> /// <remarks>http://developer.github.com/v3/pulls/comments/#delete-a-comment</remarks> /// <param name="owner">The owner of the repository</param> /// <param name="name">The name of the repository</param> /// <param name="number">The pull request review comment number</param> public Task Delete(string owner, string name, int number) { Ensure.ArgumentNotNullOrEmptyString(owner, nameof(owner)); Ensure.ArgumentNotNullOrEmptyString(name, nameof(name)); return ApiConnection.Delete(ApiUrls.PullRequestReviewComment(owner, name, number)); } /// <summary> /// Deletes a comment on a pull request review. /// </summary> /// <remarks>http://developer.github.com/v3/pulls/comments/#delete-a-comment</remarks> /// <param name="repositoryId">The Id of the repository</param> /// <param name="number">The pull request review comment number</param> public Task Delete(long repositoryId, int number) { return ApiConnection.Delete(ApiUrls.PullRequestReviewComment(repositoryId, number)); } } }
53.435135
200
0.663396
[ "MIT" ]
7enderhead/octokit.net
Octokit/Clients/PullRequestReviewCommentsClient.cs
19,773
C#
// ---------------------------------------------------------------------- // <copyright file="StringCommandHandler.cs"> // Copyright (c) The Loxone.NET Authors. All rights reserved. // </copyright> // <license> // Use of this source code is governed by the MIT license that can be // found in the LICENSE.txt file. // </license> // ---------------------------------------------------------------------- namespace Loxone.Client.Transport { using System; using System.Threading; using System.Threading.Tasks; internal class StringCommandHandler : TaskCompletionCommandHandler<string> { public override bool CanHandleMessage(MessageIdentifier identifier) => identifier == MessageIdentifier.Binary; public override async Task HandleMessageAsync(MessageHeader header, LXWebSocket socket, CancellationToken cancellationToken) { var content = new byte[header.Length]; await socket.ReceiveAtomicAsync(new ArraySegment<byte>(content), true, cancellationToken).ConfigureAwait(false); var s = LXWebSocket.Encoding.GetString(content); base.TrySetResult(s); } } }
39.066667
132
0.613481
[ "MIT" ]
graspea/Loxone.NET
Loxone.Client/Transport/StringCommandHandler.cs
1,174
C#
//------------------------------------------------------------------------------ // <自動產生的> // 這段程式碼是由工具產生的。 // // 對這個檔案所做的變更可能會造成錯誤的行為,而且如果重新產生程式碼, // 所做的變更將會遺失。 // </自動產生的> //------------------------------------------------------------------------------ namespace RinnaiPortal.Area.Training.TrainingPrint { public partial class YearlyOkChart { /// <summary> /// PageTitle 控制項。 /// </summary> /// <remarks> /// 自動產生的欄位。 /// 將移動欄位宣告從設計檔案修改為程式碼後置檔案。 /// </remarks> protected global::System.Web.UI.HtmlControls.HtmlInputText PageTitle; /// <summary> /// YearlyOkChartFrame1 控制項。 /// </summary> /// <remarks> /// 自動產生的欄位。 /// 將移動欄位宣告從設計檔案修改為程式碼後置檔案。 /// </remarks> protected global::System.Web.UI.HtmlControls.HtmlIframe YearlyOkChartFrame1; } }
28.088235
85
0.433508
[ "MIT" ]
systemgregorypc/Agatha-inteligencia-artificial-
agathaIA-voice/agathaiaportal/Area/Training/TrainingPrint/YearlyOkChart.aspx.designer.cs
1,229
C#
using System; using System.Collections.Immutable; using System.Diagnostics; using System.IO; using System.Linq; using System.Threading.Tasks; using System.Text; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.Emit; using System.Collections.Generic; namespace Core.Workspace { public static class Extensions { public static void WriteDebug(this SolutionInfo info) { var sb = new StringBuilder(); sb.AppendLine("--- Solution Info ---"); sb.Append("Id: "); sb.AppendLine(info.Id.ToString()); sb.Append("Path: "); sb.AppendLine(info.FilePath); foreach(var p in info.Projects) { } Debug.Write(sb.ToString()); } public static void WriteDebug(this ProjectInfo info) { var sb = new StringBuilder(); sb.AppendLine("--- Project Info ---"); sb.Append("Id: "); sb.Append("Path: "); } /// <summary> /// Delete a document /// </summary> /// <param name="document"></param> public static void Delete(this Document document) { } /// <summary> /// Delete a project /// </summary> /// <param name="document"></param> public static void Delete(this Project project) { } /// <summary> /// Delete a solution /// </summary> /// <param name="solution"></param> public static void Delete(this Solution solution) { } /// <summary> /// Evaluate a project /// </summary> /// <param name="project"></param> /// <returns></returns> public static ImmutableArray<Diagnostic> Evaluate(this Project project) { return project.GetCompilationAsync().Result.GetDiagnostics(); } /// <summary> /// Evaluate all projects in a solution /// </summary> /// <param name="solution"></param> /// <returns></returns> public static ImmutableArray<Diagnostic> Evaluate(this Solution solution) { var builder = ImmutableArray.CreateBuilder<Diagnostic>(); if (solution != null) { foreach (var project in solution.Projects) { builder.AddRange(project.Evaluate()); } } return builder.ToImmutableArray(); } /// <summary> /// Evaluate all projects in the current solution /// </summary> /// <param name="workspace"></param> /// <returns></returns> public static ImmutableArray<Diagnostic> Evaluate(this IWorkspace workspace) { return workspace.CurrentSolution.Evaluate(); } public static void Emit(this Solution solution) { foreach(var id in solution.ProjectIds) { var project = solution.GetProject(id); var compile = project.GetCompilationAsync().Result; var fileInfo = new FileInfo(project.OutputFilePath); var dirInfo = fileInfo.Directory; var pdbPath = Path.Combine(dirInfo.FullName, project.Name + ".pdb"); // Make sure output directory exists if (!dirInfo.Exists) { dirInfo.Create(); } // Emit fill and PDB (used for debugging) var result = compile.Emit(fileInfo.FullName, pdbPath); Debug.WriteLine("" + (result.Success ? "Success" : "Failure")); Debug.WriteLine(string.Format("Errors: {0}", result.Diagnostics.Length)); } } /// <summary> /// Rename a project /// </summary> /// <param name="project"></param> /// <param name="name"></param> public static void Rename(this Project project, string name) { // A new project has to be created } /// <summary> /// Rename a document /// </summary> /// <param name="document"></param> /// <param name="name"></param> public static void Rename(this Document document, string name) { var old = new FileInfo(document.FilePath); // position of file name var index = old.FullName.LastIndexOf(old.Name); //old.Name //old.CopyTo() var oldFile = document.FilePath; //var newFile = ""; } public static bool Try(this Action action) { string message; return Try(action, out message); } public static bool Try(this Action action, out string message) { message = string.Empty; string stack = string.Empty; return Try(action, out message, out stack); } public static bool Try(this Action action, out string message, out string stack) { message = string.Empty; stack = string.Empty; try { action(); } catch (Exception ex) { message = ex.Message; stack = ex.StackTrace; return false; } return true; } } }
28.984211
89
0.514799
[ "MIT" ]
DefectiveCube/MyIDE
Core/Workspace/Extensions.cs
5,509
C#
/******************************************************************************* * Copyright 2009-2016 Amazon Services. All Rights Reserved. * Licensed under the Apache License, Version 2.0 (the "License"); * * You may not use this file except in compliance with the License. * You may obtain a copy of the License at: http://aws.amazon.com/apache2.0 * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR * CONDITIONS OF ANY KIND, either express or implied. See the License for the * specific language governing permissions and limitations under the License. ******************************************************************************* * FBA Inbound Service MWS * API Version: 2010-10-01 * Library Version: 2016-10-05 * Generated: Wed Oct 05 06:15:39 PDT 2016 */ using System; using Claytondus.AmazonMWS.Runtime; using Claytondus.AmazonMWS.FbaInbound.Model; namespace Claytondus.AmazonMWS.FbaInbound { /// <summary> /// FBAInboundServiceMWSClient is an implementation of FBAInboundServiceMWS /// </summary> public class FBAInboundServiceMWSClient : FBAInboundServiceMWS { private const string libraryVersion = "2016-10-05"; private string servicePath; private MwsConnection connection; /// <summary> /// Create client. /// </summary> /// <param name="accessKey">Access Key</param> /// <param name="secretKey">Secret Key</param> /// <param name="applicationName">Application Name</param> /// <param name="applicationVersion">Application Version</param> /// <param name="config">configuration</param> public FBAInboundServiceMWSClient( string accessKey, string secretKey, string applicationName, string applicationVersion, FBAInboundServiceMWSConfig config) { connection = config.CopyConnection(); connection.AwsAccessKeyId = accessKey; connection.AwsSecretKeyId = secretKey; connection.ApplicationName = applicationName; connection.ApplicationVersion = applicationVersion; connection.LibraryVersion = libraryVersion; servicePath = config.ServicePath; } /// <summary> /// Create client. /// </summary> /// <param name="accessKey">Access Key</param> /// <param name="secretKey">Secret Key</param> /// <param name="config">configuration</param> public FBAInboundServiceMWSClient(String accessKey, String secretKey, FBAInboundServiceMWSConfig config) { connection = config.CopyConnection(); connection.AwsAccessKeyId = accessKey; connection.AwsSecretKeyId = secretKey; connection.LibraryVersion = libraryVersion; servicePath = config.ServicePath; } /// <summary> /// Create client. /// </summary> /// <param name="accessKey">Access Key</param> /// <param name="secretKey">Secret Key</param> public FBAInboundServiceMWSClient(String accessKey, String secretKey) : this(accessKey, secretKey, new FBAInboundServiceMWSConfig()) { } /// <summary> /// Create client. /// </summary> /// <param name="accessKey">Access Key</param> /// <param name="secretKey">Secret Key</param> /// <param name="applicationName">Application Name</param> /// <param name="applicationVersion">Application Version</param> public FBAInboundServiceMWSClient( String accessKey, String secretKey, String applicationName, String applicationVersion ) : this(accessKey, secretKey, applicationName, applicationVersion, new FBAInboundServiceMWSConfig()) { } public ConfirmPreorderResponse ConfirmPreorder(ConfirmPreorderRequest request) { return connection.Call( new FBAInboundServiceMWSClient.Request<ConfirmPreorderResponse>("ConfirmPreorder", typeof(ConfirmPreorderResponse), servicePath), request); } public ConfirmTransportRequestResponse ConfirmTransportRequest(ConfirmTransportInputRequest request) { return connection.Call( new FBAInboundServiceMWSClient.Request<ConfirmTransportRequestResponse>("ConfirmTransportRequest", typeof(ConfirmTransportRequestResponse), servicePath), request); } public CreateInboundShipmentResponse CreateInboundShipment(CreateInboundShipmentRequest request) { return connection.Call( new FBAInboundServiceMWSClient.Request<CreateInboundShipmentResponse>("CreateInboundShipment", typeof(CreateInboundShipmentResponse), servicePath), request); } public CreateInboundShipmentPlanResponse CreateInboundShipmentPlan(CreateInboundShipmentPlanRequest request) { return connection.Call( new FBAInboundServiceMWSClient.Request<CreateInboundShipmentPlanResponse>("CreateInboundShipmentPlan", typeof(CreateInboundShipmentPlanResponse), servicePath), request); } public EstimateTransportRequestResponse EstimateTransportRequest(EstimateTransportInputRequest request) { return connection.Call( new FBAInboundServiceMWSClient.Request<EstimateTransportRequestResponse>("EstimateTransportRequest", typeof(EstimateTransportRequestResponse), servicePath), request); } public GetBillOfLadingResponse GetBillOfLading(GetBillOfLadingRequest request) { return connection.Call( new FBAInboundServiceMWSClient.Request<GetBillOfLadingResponse>("GetBillOfLading", typeof(GetBillOfLadingResponse), servicePath), request); } public GetInboundGuidanceForASINResponse GetInboundGuidanceForASIN(GetInboundGuidanceForASINRequest request) { return connection.Call( new FBAInboundServiceMWSClient.Request<GetInboundGuidanceForASINResponse>("GetInboundGuidanceForASIN", typeof(GetInboundGuidanceForASINResponse), servicePath), request); } public GetInboundGuidanceForSKUResponse GetInboundGuidanceForSKU(GetInboundGuidanceForSKURequest request) { return connection.Call( new FBAInboundServiceMWSClient.Request<GetInboundGuidanceForSKUResponse>("GetInboundGuidanceForSKU", typeof(GetInboundGuidanceForSKUResponse), servicePath), request); } public GetPackageLabelsResponse GetPackageLabels(GetPackageLabelsRequest request) { return connection.Call( new FBAInboundServiceMWSClient.Request<GetPackageLabelsResponse>("GetPackageLabels", typeof(GetPackageLabelsResponse), servicePath), request); } public GetPalletLabelsResponse GetPalletLabels(GetPalletLabelsRequest request) { return connection.Call( new FBAInboundServiceMWSClient.Request<GetPalletLabelsResponse>("GetPalletLabels", typeof(GetPalletLabelsResponse), servicePath), request); } public GetPreorderInfoResponse GetPreorderInfo(GetPreorderInfoRequest request) { return connection.Call( new FBAInboundServiceMWSClient.Request<GetPreorderInfoResponse>("GetPreorderInfo", typeof(GetPreorderInfoResponse), servicePath), request); } public GetPrepInstructionsForASINResponse GetPrepInstructionsForASIN(GetPrepInstructionsForASINRequest request) { return connection.Call( new FBAInboundServiceMWSClient.Request<GetPrepInstructionsForASINResponse>("GetPrepInstructionsForASIN", typeof(GetPrepInstructionsForASINResponse), servicePath), request); } public GetPrepInstructionsForSKUResponse GetPrepInstructionsForSKU(GetPrepInstructionsForSKURequest request) { return connection.Call( new FBAInboundServiceMWSClient.Request<GetPrepInstructionsForSKUResponse>("GetPrepInstructionsForSKU", typeof(GetPrepInstructionsForSKUResponse), servicePath), request); } public GetServiceStatusResponse GetServiceStatus(GetServiceStatusRequest request) { return connection.Call( new FBAInboundServiceMWSClient.Request<GetServiceStatusResponse>("GetServiceStatus", typeof(GetServiceStatusResponse), servicePath), request); } public GetTransportContentResponse GetTransportContent(GetTransportContentRequest request) { return connection.Call( new FBAInboundServiceMWSClient.Request<GetTransportContentResponse>("GetTransportContent", typeof(GetTransportContentResponse), servicePath), request); } public GetUniquePackageLabelsResponse GetUniquePackageLabels(GetUniquePackageLabelsRequest request) { return connection.Call( new FBAInboundServiceMWSClient.Request<GetUniquePackageLabelsResponse>("GetUniquePackageLabels", typeof(GetUniquePackageLabelsResponse), servicePath), request); } public ListInboundShipmentItemsResponse ListInboundShipmentItems(ListInboundShipmentItemsRequest request) { return connection.Call( new FBAInboundServiceMWSClient.Request<ListInboundShipmentItemsResponse>("ListInboundShipmentItems", typeof(ListInboundShipmentItemsResponse), servicePath), request); } public ListInboundShipmentItemsByNextTokenResponse ListInboundShipmentItemsByNextToken(ListInboundShipmentItemsByNextTokenRequest request) { return connection.Call( new FBAInboundServiceMWSClient.Request<ListInboundShipmentItemsByNextTokenResponse>("ListInboundShipmentItemsByNextToken", typeof(ListInboundShipmentItemsByNextTokenResponse), servicePath), request); } public ListInboundShipmentsResponse ListInboundShipments(ListInboundShipmentsRequest request) { return connection.Call( new FBAInboundServiceMWSClient.Request<ListInboundShipmentsResponse>("ListInboundShipments", typeof(ListInboundShipmentsResponse), servicePath), request); } public ListInboundShipmentsByNextTokenResponse ListInboundShipmentsByNextToken(ListInboundShipmentsByNextTokenRequest request) { return connection.Call( new FBAInboundServiceMWSClient.Request<ListInboundShipmentsByNextTokenResponse>("ListInboundShipmentsByNextToken", typeof(ListInboundShipmentsByNextTokenResponse), servicePath), request); } public PutTransportContentResponse PutTransportContent(PutTransportContentRequest request) { return connection.Call( new FBAInboundServiceMWSClient.Request<PutTransportContentResponse>("PutTransportContent", typeof(PutTransportContentResponse), servicePath), request); } public UpdateInboundShipmentResponse UpdateInboundShipment(UpdateInboundShipmentRequest request) { return connection.Call( new FBAInboundServiceMWSClient.Request<UpdateInboundShipmentResponse>("UpdateInboundShipment", typeof(UpdateInboundShipmentResponse), servicePath), request); } public VoidTransportRequestResponse VoidTransportRequest(VoidTransportInputRequest request) { return connection.Call( new FBAInboundServiceMWSClient.Request<VoidTransportRequestResponse>("VoidTransportRequest", typeof(VoidTransportRequestResponse), servicePath), request); } private class Request<R> : IMwsRequestType<R> where R : IMwsObject { private string operationName; private Type responseClass; private string servicePath; public Request(string operationName, Type responseClass, string servicePath) { this.operationName = operationName; this.responseClass = responseClass; this.servicePath = servicePath; } public string ServicePath { get { return servicePath; } } public string OperationName { get { return operationName; } } public Type ResponseClass { get { return responseClass; } } public MwsException WrapException(Exception cause) { return new FBAInboundServiceMWSException(cause); } public void SetResponseHeaderMetadata(IMwsObject response, MwsResponseHeaderMetadata rhmd) { ((IMWSResponse)response).ResponseHeaderMetadata = new ResponseHeaderMetadata(rhmd); } } } }
44.063123
205
0.667873
[ "Apache-2.0" ]
claytondus/Claytondus.AmazonMWS
Claytondus.AmazonMWS.FbaInbound/FBAInboundServiceMWSClient.cs
13,263
C#
namespace Morsley.UK.People.API.Test.Fixture; public abstract class ApplicationTestFixture<TProgram> where TProgram : class { //protected ILogger Logger; //protected bool HasBus = false; //protected bool HasDatabase = false; // Test Fixture for the People Bus... //protected BusTestFixture? BusTestFixture; // Test Fixture for the People Databases... //protected DatabaseTestFixture? DatabaseTestFixture; //protected DatabaseTestFixture? WriteDatabaseTestFixture; //protected DatabaseTestFixture? DatabaseTestFixture; // The HttpClient to hit the application under test... protected HttpClient? HttpClient; private int _applicationPort; protected IConfiguration? _configuration; protected global::AutoFixture.Fixture? AutoFixture; protected int ApplicationPort { get { //if (_applicationPort == 0) _applicationPort = GetApplicationPort(DatabaseTestFixture.Configuration); if (_applicationPort == 0) _applicationPort = GetApplicationPort(GetConfiguration()); return _applicationPort; } } protected ApplicationTestFixture() { AutoFixture = new global::AutoFixture.Fixture(); AutoFixture.Customizations.Add(new DateOfBirthSpecimenBuilder()); AutoFixture.Customizations.Add(new AddPersonRequestSpecimenBuilder()); } [OneTimeSetUp] protected async virtual Task OneTimeSetUp() { await Task.CompletedTask; } [SetUp] protected async virtual Task SetUp() { var factory = new WebApplicationFactory<TProgram>() .WithWebHostBuilder(builder => { builder.UseUrls($"https://localhost:{ApplicationPort}"); builder.UseKestrel(); builder.ConfigureKestrel(options => { options.ListenLocalhost(ApplicationPort); } ); builder.ConfigureAppConfiguration(configuration => { configuration.AddConfiguration(GetConfiguration()); }); }); HttpClient = factory.CreateClient(new WebApplicationFactoryClientOptions { BaseAddress = new System.Uri($"https://localhost:{ApplicationPort}") }); await Task.CompletedTask; } [TearDown] protected async virtual Task TearDown() { _configuration = null; HttpClient?.Dispose(); await Task.CompletedTask; } [OneTimeTearDown] protected async virtual Task OneTimeTearDown() { _configuration = null; await Task.CompletedTask; } protected static string AddToFieldsIfMissing(string toAdd, string fields) { var listOfFields = new List<string>(); var hasId = false; foreach (var field in fields.Split(',')) { if (field.ToLower() == toAdd.ToLower()) hasId = true; listOfFields.Add(field); } if (!hasId) listOfFields.Add(toAdd); return string.Join(",", listOfFields); } private static IList<string> AllPublicFields<T>() where T : class { var fields = new List<string>(); var properties = typeof(T).GetProperties(BindingFlags.IgnoreCase | BindingFlags.Public | BindingFlags.Instance); foreach (var property in properties) { fields.Add(property.Name); } return fields; } protected static string BuildExpectedUrl( int pageNumber, int pageSize, string? fields = null, string? filter = null, string? search = null, string? sort = null) { const string baseUrl = "/api/people"; var fieldsParameter = ""; if (fields != null) fieldsParameter = $"&fields={fields}"; var filterParameter = ""; if (filter != null) filterParameter = $"&filter={filter}"; var searchParameter = ""; if (search != null) searchParameter = $"&search={search}"; var sortParameter = $"&sort={sort}"; if (sort == null) { sortParameter = $"&sort={Defaults.DefaultPageSort}"; } var expectedUrl = $"{baseUrl}" + $"?pageNumber={pageNumber}&pageSize={pageSize}" + $"{fieldsParameter}" + $"{filterParameter}" + $"{searchParameter}" + $"{sortParameter}"; return expectedUrl; } protected static PersonResource? DeserializePersonResource(string json) { var options = new JsonSerializerOptions { PropertyNameCaseInsensitive = true, Converters = { new PersonResourceJsonConverter(), new JsonStringEnumConverter(JsonNamingPolicy.CamelCase) } }; return JsonSerializer.Deserialize<PersonResource>(json, options); } protected static (IList<string> Expected, IList<string> Unexpected) DetermineExpectedAndUnexpectedFields(string validFields) { var expectedFields = new List<string>(); var unexpectedFields = AllPublicFields<PersonResponse>(); foreach (var expectedField in validFields.Split(',')) { expectedFields.Add(expectedField); unexpectedFields.Remove(expectedField); } unexpectedFields.Remove("Links"); return (expectedFields, unexpectedFields); } protected async Task<long> DetermineExpectedContentLength(string url) { var result = await HttpClient!.GetAsync(url); result.IsSuccessStatusCode.Should().BeTrue(); result.StatusCode.Should().Be(HttpStatusCode.OK); var content = await result.Content.ReadAsStringAsync(); return content.Length; } protected AddPersonRequest GenerateAddPersonRequest() { var request = AutoFixture.Create<AddPersonRequest>(); return request; } protected UpdatePersonRequest GenerateTestUpdatePersonRequest( Guid personId, Sex? sex = null, Gender? gender = null, string? dateOfBirth = null) { var testUpdatePerson = AutoFixture.Create<UpdatePersonRequest>(); testUpdatePerson.Id = personId; if (testUpdatePerson.Sex == sex) testUpdatePerson.Sex = sex.GenerateDifferentSex(); if (testUpdatePerson.Gender == gender) testUpdatePerson.Gender = gender.GenerateDifferentGender(); testUpdatePerson.DateOfBirth = dateOfBirth.GenerateDifferentDate(); return testUpdatePerson; } protected int GetApplicationPort(IConfiguration configuration) { var potentialPort = configuration["ApplicationPort"]; if (string.IsNullOrEmpty(potentialPort)) throw new InvalidProgramException("Invalid configuration --> Port is missing!"); if (int.TryParse(potentialPort, out var port)) return port; throw new InvalidProgramException("Invalid configuration --> port is not a number!"); } public IConfiguration GetConfiguration() { if (_configuration is not null) return _configuration; var builder = new ConfigurationBuilder(); builder.AddJsonFile("appsettings.json"); var additional = GetInMemoryConfiguration(); if (additional.Count > 0) builder.AddInMemoryCollection(additional); _configuration = builder.Build(); return _configuration; } protected virtual Dictionary<string, string> GetInMemoryConfiguration() { var additional = new Dictionary<string, string>(); //if (HasBus) //{ // foreach (var additionalBusConfiguration in BusTestFixture!.GetInMemoryConfiguration()) // { // additional.Add(additionalBusConfiguration.Key, additionalBusConfiguration.Value); // } //} //if (HasDatabase) //{ // foreach (var additionalDatabaseConfiguration in DatabaseTestFixture!.GetInMemoryConfiguration()) // { // additional.Add(additionalDatabaseConfiguration.Key, additionalDatabaseConfiguration.Value); // } //} return additional; } protected static object? GetValue<T>(T t, string fieldName) where T : class { var propertyInfo = typeof(T).GetProperty(fieldName, BindingFlags.IgnoreCase | BindingFlags.Public | BindingFlags.Instance); var type = propertyInfo?.PropertyType; if (type == null) return null; var value = propertyInfo?.GetValue(t); if (value == null) return null; var underlying = Nullable.GetUnderlyingType(type); if (underlying != null) { switch (underlying.FullName) { case "System.DateTime": return ((DateTime)value).ToString("yyyy-MM-dd"); case "Morsley.UK.People.Domain.Enumerations.Gender": case "Morsley.UK.People.Domain.Enumerations.Sex": return value.ToString(); } } return value; } protected static void LinksForPeopleShouldBeCorrect( IList<Link>? links, int pageNumber, int pageSize, int totalNumber, string? fields = null, string? filter = null, string? search = null, string? sort = null) { string expectedUrl; // Previous page... if (pageNumber > 1) { var previousPageOfPeopleLink = links.Single(_ => _.Relationship == "previous" && _.Method == "GET"); previousPageOfPeopleLink.Should().NotBeNull(); //expectedUrl = BuildExpectedUrl(pageNumber - 1, pageSize, fields, filter, search, sort); //var previousPageOfPeopleUrl = HttpUtility.UrlDecode(previousPageOfPeopleLink.HypertextReference); //previousPageOfPeopleUrl.Should().Be(expectedUrl); } // Current page... var currentPageOfPeopleLink = links.Single(_ => _.Relationship == "self" && _.Method == "GET"); currentPageOfPeopleLink.Should().NotBeNull(); //expectedUrl = BuildExpectedUrl(pageNumber, pageSize, fields, filter, search, sort); //var currentPageOfPeopleUrl = HttpUtility.UrlDecode(currentPageOfPeopleLink.HypertextReference); //currentPageOfPeopleUrl.Should().Be(expectedUrl); // Next page... if (totalNumber > pageSize * pageNumber) { var nextPageOfPeopleLink = links.Single(_ => _.Relationship == "next" && _.Method == "GET"); nextPageOfPeopleLink.Should().NotBeNull(); // expectedUrl = BuildExpectedUrl(pageNumber + 1, pageSize, fields, filter, search, sort); // var nextPageOfPeopleUrl = HttpUtility.UrlDecode(nextPageOfPeopleLink.HypertextReference); // nextPageOfPeopleUrl.Should().Be(expectedUrl); } } protected static void LinksForPersonShouldBeCorrect(IList<Link> links, Guid personId) { links.Should().NotBeNull(); links.Count.Should().Be(3); var getPersonLink = links.Single(_ => _.Method == "GET" && _.Relationship == "self"); getPersonLink.Should().NotBeNull(); getPersonLink.HypertextReference.Should().Be($"/api/person/{personId}"); var updatePersonLink = links.Single(_ => _.Method == "PUT" && _.Relationship == "self"); updatePersonLink.Should().NotBeNull(); updatePersonLink.HypertextReference.Should().Be($"/api/person/{personId}"); var deletePersonLink = links.Single(_ => _.Method == "DELETE" && _.Relationship == "self"); deletePersonLink.Should().NotBeNull(); deletePersonLink.HypertextReference.Should().Be($"/api/person/{personId}"); } protected static void LinksForPeopleShouldBeCorrect(IList<PersonResource>? embedded) { foreach (var person in embedded) { } } protected void ProblemDetailsShouldContainValidationIssues(string content, Dictionary<string, string> validationErrors) { var problemDetails = JsonSerializer.Deserialize<ValidationProblemDetails>(content); problemDetails.Should().NotBeNull(); problemDetails!.Status.Should().Be((int)HttpStatusCode.UnprocessableEntity); problemDetails.Title.Should().Be("Validation error(s) occurred!"); problemDetails.Detail.Should().Be("See the errors field for details."); problemDetails.Extensions.Should().NotBeNull(); problemDetails.Extensions.Count().Should().Be(validationErrors.Count); foreach (var validationError in validationErrors) { var error = problemDetails.Extensions.SingleOrDefault(_ => _.Key == validationError.Key); error.Should().NotBeNull(); error.Value.Should().NotBeNull(); error.Value?.ToString().Should().Be(validationError.Value); } } protected void ProblemDetailsShouldContain( string content, string title, string detail, Dictionary<string, string> issues) { var problemDetails = JsonSerializer.Deserialize<ValidationProblemDetails>(content); problemDetails.Should().NotBeNull(); problemDetails!.Status.Should().Be((int)HttpStatusCode.UnprocessableEntity); problemDetails.Title.Should().Be(title); problemDetails.Detail.Should().Be(detail); problemDetails.Extensions.Should().NotBeNull(); problemDetails.Extensions.Count().Should().Be(issues.Count); foreach (var issue in issues) { var error = problemDetails.Extensions.SingleOrDefault(_ => _.Key == issue.Key); error.Should().NotBeNull(); error.Value.Should().NotBeNull(); error.Value?.ToString().Should().Be(issue.Value); } } protected void ShouldBeEquivalentTo(PersonResource resource, Person person) { resource.Should().NotBeNull(); person.Should().NotBeNull(); resource.Data.Should().NotBeNull(); resource.Data!.Id.Should().Be(person.Id); resource.Data.FirstName.Should().Be(person.FirstName); resource.Data.LastName.Should().Be(person.LastName); if (person.DateOfBirth.HasValue) { resource.Data.DateOfBirth.Should().Be(person.DateOfBirth?.ToString("yyyy-MM-dd")); } if (person.Sex.HasValue) { resource.Data.Sex.Should().Be(person.Sex.ToString()); } if (person.Gender.HasValue) { resource.Data.Gender.Should().Be(person.Gender.ToString()); } } protected void ShouldBeEquivalentTo(IList<PersonResource> embedded, IList<Person> people) { foreach (var resource in embedded) { resource.Should().NotBeNull(); var embeddedPerson = resource.Data; var personId = embeddedPerson.Id; var person = people.Single(_ => _.Id == personId); person.Should().NotBeNull(); ShouldBeEquivalentTo(resource, person); resource.Links.Should().NotBeNull(); LinksForPersonShouldBeCorrect(resource.Links!, personId); } } protected IConfiguration UpdateConfiguration( IConfiguration configuration, IConfiguration extraConfiguration) { var builder = new ConfigurationBuilder() .AddConfiguration(configuration) .AddConfiguration(extraConfiguration); var updatedConfiguration = builder.Build(); return updatedConfiguration; } }
35.962054
132
0.609273
[ "MIT" ]
john-morsley/Users
tests/Fixtures/Morsley.UK.People.API.Test.Fixture/ApplicationTestFixture.cs
16,113
C#
namespace V5_DataPublish.Forms.Desk { partial class frmHandInsert { /// <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() { this.components = new System.ComponentModel.Container(); this.label1 = new System.Windows.Forms.Label(); this.txtTitle = new System.Windows.Forms.TextBox(); this.label3 = new System.Windows.Forms.Label(); this.btnSubmit = new System.Windows.Forms.Button(); this.btnCancel = new System.Windows.Forms.Button(); this.backgroundWorker = new System.ComponentModel.BackgroundWorker(); this.btnAutoCreateArticle = new System.Windows.Forms.Button(); this.errorProvider = new System.Windows.Forms.ErrorProvider(this.components); this.label2 = new System.Windows.Forms.Label(); this.btnSelectWebSite = new System.Windows.Forms.Button(); this.label4 = new System.Windows.Forms.Label(); this.lblProcess = new System.Windows.Forms.Label(); this.comboBox1 = new System.Windows.Forms.ComboBox(); this.txtContent = new System.Windows.Forms.TextBox(); ((System.ComponentModel.ISupportInitialize)(this.errorProvider)).BeginInit(); this.SuspendLayout(); // // label1 // this.label1.AutoSize = true; this.label1.Location = new System.Drawing.Point(13, 16); this.label1.Name = "label1"; this.label1.Size = new System.Drawing.Size(29, 12); this.label1.TabIndex = 0; this.label1.Text = "标题"; // // txtTitle // this.txtTitle.Location = new System.Drawing.Point(48, 12); this.txtTitle.Name = "txtTitle"; this.txtTitle.Size = new System.Drawing.Size(547, 21); this.txtTitle.TabIndex = 1; // // label3 // this.label3.AutoSize = true; this.label3.Location = new System.Drawing.Point(13, 73); this.label3.Name = "label3"; this.label3.Size = new System.Drawing.Size(29, 12); this.label3.TabIndex = 2; this.label3.Text = "内容"; // // btnSubmit // this.btnSubmit.Location = new System.Drawing.Point(560, 492); this.btnSubmit.Name = "btnSubmit"; this.btnSubmit.Size = new System.Drawing.Size(75, 23); this.btnSubmit.TabIndex = 5; this.btnSubmit.Text = "确定(&S)"; this.btnSubmit.UseVisualStyleBackColor = true; this.btnSubmit.Click += new System.EventHandler(this.btnSubmit_Click); // // btnCancel // this.btnCancel.Location = new System.Drawing.Point(653, 492); this.btnCancel.Name = "btnCancel"; this.btnCancel.Size = new System.Drawing.Size(75, 23); this.btnCancel.TabIndex = 5; this.btnCancel.Text = "取消(&C)"; this.btnCancel.UseVisualStyleBackColor = true; this.btnCancel.Click += new System.EventHandler(this.btnCancel_Click); // // backgroundWorker // this.backgroundWorker.WorkerReportsProgress = true; this.backgroundWorker.WorkerSupportsCancellation = true; this.backgroundWorker.DoWork += new System.ComponentModel.DoWorkEventHandler(this.backgroundWorker_DoWork); this.backgroundWorker.RunWorkerCompleted += new System.ComponentModel.RunWorkerCompletedEventHandler(this.backgroundWorker_RunWorkerCompleted); // // btnAutoCreateArticle // this.btnAutoCreateArticle.Location = new System.Drawing.Point(605, 10); this.btnAutoCreateArticle.Name = "btnAutoCreateArticle"; this.btnAutoCreateArticle.Size = new System.Drawing.Size(121, 23); this.btnAutoCreateArticle.TabIndex = 26; this.btnAutoCreateArticle.Text = "随机生成一篇文章"; this.btnAutoCreateArticle.UseVisualStyleBackColor = true; this.btnAutoCreateArticle.Click += new System.EventHandler(this.btnAutoCreateArticle_Click); // // errorProvider // this.errorProvider.ContainerControl = this; // // label2 // this.label2.AutoSize = true; this.label2.Location = new System.Drawing.Point(13, 46); this.label2.Name = "label2"; this.label2.Size = new System.Drawing.Size(29, 12); this.label2.TabIndex = 27; this.label2.Text = "分类"; // // btnSelectWebSite // this.btnSelectWebSite.Location = new System.Drawing.Point(308, 42); this.btnSelectWebSite.Name = "btnSelectWebSite"; this.btnSelectWebSite.Size = new System.Drawing.Size(75, 23); this.btnSelectWebSite.TabIndex = 31; this.btnSelectWebSite.Text = "选择网站"; this.btnSelectWebSite.UseVisualStyleBackColor = true; this.btnSelectWebSite.Click += new System.EventHandler(this.btnSelectWebSite_Click); // // label4 // this.label4.AutoSize = true; this.label4.Location = new System.Drawing.Point(19, 497); this.label4.Name = "label4"; this.label4.Size = new System.Drawing.Size(29, 12); this.label4.TabIndex = 34; this.label4.Text = "状态"; // // lblProcess // this.lblProcess.AutoSize = true; this.lblProcess.ForeColor = System.Drawing.Color.Red; this.lblProcess.Location = new System.Drawing.Point(53, 503); this.lblProcess.Name = "lblProcess"; this.lblProcess.Size = new System.Drawing.Size(0, 12); this.lblProcess.TabIndex = 35; // // comboBox1 // this.comboBox1.FormattingEnabled = true; this.comboBox1.Location = new System.Drawing.Point(49, 42); this.comboBox1.Name = "comboBox1"; this.comboBox1.Size = new System.Drawing.Size(241, 20); this.comboBox1.TabIndex = 36; // // txtContent // this.txtContent.Location = new System.Drawing.Point(49, 73); this.txtContent.Multiline = true; this.txtContent.Name = "txtContent"; this.txtContent.ScrollBars = System.Windows.Forms.ScrollBars.Both; this.txtContent.Size = new System.Drawing.Size(673, 413); this.txtContent.TabIndex = 37; this.txtContent.WordWrap = false; // // frmHandInsert // this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 12F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.ClientSize = new System.Drawing.Size(738, 527); this.Controls.Add(this.txtContent); this.Controls.Add(this.comboBox1); this.Controls.Add(this.lblProcess); this.Controls.Add(this.label4); this.Controls.Add(this.btnSelectWebSite); this.Controls.Add(this.label2); this.Controls.Add(this.btnAutoCreateArticle); this.Controls.Add(this.btnCancel); this.Controls.Add(this.btnSubmit); this.Controls.Add(this.label3); this.Controls.Add(this.txtTitle); this.Controls.Add(this.label1); this.DoubleBuffered = true; this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedSingle; this.MaximizeBox = false; this.MinimizeBox = false; this.Name = "frmHandInsert"; this.ShowInTaskbar = false; this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen; this.Text = "数据插入"; this.Load += new System.EventHandler(this.frmHandInsert_Load); ((System.ComponentModel.ISupportInitialize)(this.errorProvider)).EndInit(); this.ResumeLayout(false); this.PerformLayout(); } #endregion private System.Windows.Forms.Label label1; private System.Windows.Forms.TextBox txtTitle; private System.Windows.Forms.Label label3; private System.Windows.Forms.Button btnSubmit; private System.Windows.Forms.Button btnCancel; private System.ComponentModel.BackgroundWorker backgroundWorker; private System.Windows.Forms.Button btnAutoCreateArticle; private System.Windows.Forms.ErrorProvider errorProvider; private System.Windows.Forms.Label label2; private System.Windows.Forms.Button btnSelectWebSite; private System.Windows.Forms.Label label4; private System.Windows.Forms.Label lblProcess; private System.Windows.Forms.ComboBox comboBox1; private System.Windows.Forms.TextBox txtContent; } }
45.324201
155
0.589865
[ "Apache-2.0" ]
Haxine/V5_DataCollection
V5_DataPublish/Forms/Desk/frmHandInsert.designer.cs
9,984
C#
using System; using System.Threading; using System.Threading.Tasks; using Newtonsoft.Json.Linq; using OmniSharp.Extensions.LanguageServer.Protocol; using OmniSharp.Extensions.LanguageServer.Protocol.Serialization; namespace OmniSharp.Extensions.LanguageServer.Client.Handlers { /// <summary> /// A delegate-based handler for requests whose responses have payloads. /// </summary> /// <typeparam name="TRequest"> /// The request message type. /// </typeparam> /// <typeparam name="TResponse"> /// The response message type. /// </typeparam> public class DelegateRequestResponseHandler<TRequest, TResponse> : DelegateHandler, IInvokeRequestHandler { /// <summary> /// Create a new <see cref="DelegateRequestResponseHandler{TRequest, TResponse}"/>. /// </summary> /// <param name="method"> /// The name of the method handled by the handler. /// </param> /// <param name="handler"> /// The <see cref="RequestHandler{TRequest, TResponse}"/> delegate that implements the handler. /// </param> public DelegateRequestResponseHandler(string method, RequestHandler<TRequest, TResponse> handler) : base(method) { if (handler == null) throw new ArgumentNullException(nameof(handler)); Handler = handler; } /// <summary> /// The <see cref="RequestHandler{TRequest, TResponse}"/> delegate that implements the handler. /// </summary> public RequestHandler<TRequest, TResponse> Handler { get; } /// <summary> /// The expected CLR type of the request payload. /// </summary> public override Type PayloadType => typeof(TRequest); /// <summary> /// Invoke the handler. /// </summary> /// <param name="request"> /// The request message. /// </param> /// <param name="cancellationToken"> /// A <see cref="CancellationToken"/> that can be used to cancel the operation. /// </param> /// <returns> /// A <see cref="Task{TResult}"/> representing the operation. /// </returns> public async Task<object> Invoke(object request, CancellationToken cancellationToken) { return await Handler( (TRequest)request, cancellationToken ); } } }
35.267606
107
0.587061
[ "MIT" ]
Bia10/csharp-language-server-protocol
src/Client/Handlers/DelegateRequestResponseHandler.cs
2,504
C#
using System; using System.IO; using System.Runtime.InteropServices; using System.Threading.Tasks; using static HRM.Model.CoreDI; namespace HRM.Model { /// <summary> /// Handles reading/writing and querying the file system /// </summary> public class BaseFileManager : IFileManager { /// <summary> /// Writes the text to the specified file /// </summary> /// <param name="text">The text to write</param> /// <param name="path">The path of the file to write to</param> /// <param name="append">If true, writes the text to the end of the file, otherwise overrides any existing file</param> /// <returns></returns> public async Task WriteTextToFileAsync(string text, string path, bool append = false) { // TODO: Add exception catching // Normalize path path = NormalizePath(path); // Resolve to absolute path path = ResolvePath(path); // Lock the task await AsyncAwaiter.AwaitAsync(nameof(BaseFileManager) + path, async () => { // Run the synchronous file access as a new task await TaskManager.Run(() => { // Write the log message to file using (var fileStream = (TextWriter)new StreamWriter(File.Open(path, append ? FileMode.Append : FileMode.Create))) fileStream.Write(text); }); }); } /// <summary> /// Normalizing a path based on the current operating system /// </summary> /// <param name="path">The path to normalize</param> /// <returns></returns> public string NormalizePath(string path) { // If on Windows... if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) // Replace any / with \ return path?.Replace('/', '\\').Trim(); // If on Linux/Mac else // Replace any \ with / return path?.Replace('\\', '/').Trim(); } /// <summary> /// Resolves any relative elements of the path to absolute /// </summary> /// <param name="path">The path to resolve</param> /// <returns></returns> public string ResolvePath(string path) { // Resolve the path to absolute return Path.GetFullPath(path); } } }
33.945946
134
0.537818
[ "MIT" ]
mdnm/husources-hrm
Source/HRM.Model/File/BaseFileManager.cs
2,514
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 Aliyun.Acs.Core; using System.Collections.Generic; namespace Aliyun.Acs.EHPC.Model.V20180412 { public class SetJobUserResponse : AcsResponse { private string requestId; public string RequestId { get { return requestId; } set { requestId = value; } } } }
27.463415
63
0.717584
[ "Apache-2.0" ]
brightness007/unofficial-aliyun-openapi-net-sdk
aliyun-net-sdk-ehpc/EHPC/Model/V20180412/SetJobUserResponse.cs
1,126
C#
#region Imports using System; using System.Data; #endregion namespace CrazyflieDotNet.Crazyflie.TransferProtocol { public abstract class PacketPayload : IPacketPayload { private static readonly byte[] EmptyPacketPayloadBytes = new byte[0]; /// <summary> /// Gets the bytes. /// </summary> /// <returns>The bytes.</returns> public byte[] GetBytes() { try { var packetBytes = GetPacketPayloadBytes(); // so we never return null return packetBytes ?? EmptyPacketPayloadBytes; } catch (Exception ex) { throw new DataException("Error obtaining packet payload bytes.", ex); } } protected abstract byte[] GetPacketPayloadBytes(); /// <summary> /// Returns a <see cref="T:System.String"/> that represents the current <see cref="T:CrazyflieDotNet.Crazyflie.TransferProtocol.PingPacketHeader"/>. /// </summary> /// <returns>A <see cref="T:System.String"/> that represents the current <see cref="T:CrazyflieDotNet.Crazyflie.TransferProtocol.PingPacketHeader"/>.</returns> public override string ToString() { return string.Format("[{0}]", BitConverter.ToString(GetBytes())); } } }
25.533333
161
0.698869
[ "MIT" ]
SupraBitKid/CrazyflieDotNet
CrazyflieDotNet/Source/CrazyflieDotNet.Crazyflie/TransferProtocol/PacketPayload.cs
1,149
C#
namespace Charlotte { partial class MainWin { /// <summary> /// 必要なデザイナー変数です。 /// </summary> private System.ComponentModel.IContainer components = null; /// <summary> /// 使用中のリソースをすべてクリーンアップします。 /// </summary> /// <param name="disposing">マネージ リソースが破棄される場合 true、破棄されない場合は false です。</param> protected override void Dispose(bool disposing) { if (disposing && (components != null)) { components.Dispose(); } base.Dispose(disposing); } #region Windows フォーム デザイナーで生成されたコード /// <summary> /// デザイナー サポートに必要なメソッドです。このメソッドの内容を /// コード エディターで変更しないでください。 /// </summary> private void InitializeComponent() { System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(MainWin)); this.SuspendLayout(); // // MainWin // this.AutoScaleDimensions = new System.Drawing.SizeF(8F, 20F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.ClientSize = new System.Drawing.Size(284, 261); this.Font = new System.Drawing.Font("メイリオ", 9.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(128))); this.Icon = ((System.Drawing.Icon)(resources.GetObject("$this.Icon"))); this.Location = new System.Drawing.Point(-400, -400); this.Margin = new System.Windows.Forms.Padding(4, 5, 4, 5); this.MaximizeBox = false; this.MinimizeBox = false; this.Name = "MainWin"; this.ShowInTaskbar = false; this.StartPosition = System.Windows.Forms.FormStartPosition.Manual; this.Text = "MakeMovie"; this.FormClosing += new System.Windows.Forms.FormClosingEventHandler(this.MainWin_FormClosing); this.FormClosed += new System.Windows.Forms.FormClosedEventHandler(this.MainWin_FormClosed); this.Load += new System.EventHandler(this.MainWin_Load); this.Shown += new System.EventHandler(this.MainWin_Shown); this.ResumeLayout(false); } #endregion } }
31.33871
138
0.711271
[ "MIT" ]
stackprobe/Annex
wb/t20200430_MakeMovie/MakeMovie/MakeMovie/MakeMovie/MainWin.Designer.cs
2,219
C#
// <auto-generated /> using System; using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Infrastructure; using Microsoft.EntityFrameworkCore.Metadata; using Microsoft.EntityFrameworkCore.Migrations; using Microsoft.EntityFrameworkCore.Storage.ValueConversion; using PaymentServiceSample.EntityFrameworkCore; using Volo.Abp.EntityFrameworkCore; namespace PaymentServiceSample.Migrations { [DbContext(typeof(PaymentServiceSampleMigrationsDbContext))] [Migration("20200803152922_AddedExtraPropertiesToPaymentItem")] partial class AddedExtraPropertiesToPaymentItem { protected override void BuildTargetModel(ModelBuilder modelBuilder) { #pragma warning disable 612, 618 modelBuilder .HasAnnotation("_Abp_DatabaseProvider", EfCoreDatabaseProvider.SqlServer) .HasAnnotation("ProductVersion", "3.1.5") .HasAnnotation("Relational:MaxIdentifierLength", 128) .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); modelBuilder.Entity("EasyAbp.PaymentService.Payments.Payment", b => { b.Property<Guid>("Id") .ValueGeneratedOnAdd() .HasColumnType("uniqueidentifier"); b.Property<decimal>("ActualPaymentAmount") .HasColumnType("decimal(18,6)"); b.Property<DateTime?>("CanceledTime") .HasColumnType("datetime2"); b.Property<DateTime?>("CompletionTime") .HasColumnType("datetime2"); b.Property<string>("ConcurrencyStamp") .IsConcurrencyToken() .HasColumnName("ConcurrencyStamp") .HasColumnType("nvarchar(40)") .HasMaxLength(40); b.Property<DateTime>("CreationTime") .HasColumnName("CreationTime") .HasColumnType("datetime2"); b.Property<Guid?>("CreatorId") .HasColumnName("CreatorId") .HasColumnType("uniqueidentifier"); b.Property<string>("Currency") .HasColumnType("nvarchar(max)"); b.Property<Guid?>("DeleterId") .HasColumnName("DeleterId") .HasColumnType("uniqueidentifier"); b.Property<DateTime?>("DeletionTime") .HasColumnName("DeletionTime") .HasColumnType("datetime2"); b.Property<string>("ExternalTradingCode") .HasColumnType("nvarchar(max)"); b.Property<string>("ExtraProperties") .HasColumnName("ExtraProperties") .HasColumnType("nvarchar(max)"); b.Property<bool>("IsDeleted") .ValueGeneratedOnAdd() .HasColumnName("IsDeleted") .HasColumnType("bit") .HasDefaultValue(false); b.Property<DateTime?>("LastModificationTime") .HasColumnName("LastModificationTime") .HasColumnType("datetime2"); b.Property<Guid?>("LastModifierId") .HasColumnName("LastModifierId") .HasColumnType("uniqueidentifier"); b.Property<decimal>("OriginalPaymentAmount") .HasColumnType("decimal(18,6)"); b.Property<string>("PayeeAccount") .HasColumnType("nvarchar(max)"); b.Property<decimal>("PaymentDiscount") .HasColumnType("decimal(18,6)"); b.Property<string>("PaymentMethod") .HasColumnType("nvarchar(max)"); b.Property<decimal>("PendingRefundAmount") .HasColumnType("decimal(18,6)"); b.Property<decimal>("RefundAmount") .HasColumnType("decimal(18,6)"); b.Property<Guid?>("TenantId") .HasColumnName("TenantId") .HasColumnType("uniqueidentifier"); b.Property<Guid>("UserId") .HasColumnType("uniqueidentifier"); b.HasKey("Id"); b.ToTable("PaymentServicePayments"); }); modelBuilder.Entity("EasyAbp.PaymentService.Payments.PaymentItem", b => { b.Property<Guid>("Id") .ValueGeneratedOnAdd() .HasColumnType("uniqueidentifier"); b.Property<decimal>("ActualPaymentAmount") .HasColumnType("decimal(18,6)"); b.Property<DateTime>("CreationTime") .HasColumnName("CreationTime") .HasColumnType("datetime2"); b.Property<Guid?>("CreatorId") .HasColumnName("CreatorId") .HasColumnType("uniqueidentifier"); b.Property<string>("Currency") .HasColumnType("nvarchar(max)"); b.Property<Guid?>("DeleterId") .HasColumnName("DeleterId") .HasColumnType("uniqueidentifier"); b.Property<DateTime?>("DeletionTime") .HasColumnName("DeletionTime") .HasColumnType("datetime2"); b.Property<string>("ExtraProperties") .HasColumnName("ExtraProperties") .HasColumnType("nvarchar(max)"); b.Property<bool>("IsDeleted") .ValueGeneratedOnAdd() .HasColumnName("IsDeleted") .HasColumnType("bit") .HasDefaultValue(false); b.Property<Guid>("ItemKey") .HasColumnType("uniqueidentifier"); b.Property<string>("ItemType") .HasColumnType("nvarchar(max)"); b.Property<DateTime?>("LastModificationTime") .HasColumnName("LastModificationTime") .HasColumnType("datetime2"); b.Property<Guid?>("LastModifierId") .HasColumnName("LastModifierId") .HasColumnType("uniqueidentifier"); b.Property<decimal>("OriginalPaymentAmount") .HasColumnType("decimal(18,6)"); b.Property<decimal>("PaymentDiscount") .HasColumnType("decimal(18,6)"); b.Property<Guid?>("PaymentId") .HasColumnType("uniqueidentifier"); b.Property<decimal>("PendingRefundAmount") .HasColumnType("decimal(18,6)"); b.Property<decimal>("RefundAmount") .HasColumnType("decimal(18,6)"); b.HasKey("Id"); b.HasIndex("PaymentId"); b.ToTable("PaymentServicePaymentItems"); }); modelBuilder.Entity("EasyAbp.PaymentService.Refunds.Refund", b => { b.Property<Guid>("Id") .ValueGeneratedOnAdd() .HasColumnType("uniqueidentifier"); b.Property<DateTime?>("CanceledTime") .HasColumnType("datetime2"); b.Property<DateTime?>("CompletedTime") .HasColumnType("datetime2"); b.Property<string>("ConcurrencyStamp") .IsConcurrencyToken() .HasColumnName("ConcurrencyStamp") .HasColumnType("nvarchar(40)") .HasMaxLength(40); b.Property<DateTime>("CreationTime") .HasColumnName("CreationTime") .HasColumnType("datetime2"); b.Property<Guid?>("CreatorId") .HasColumnName("CreatorId") .HasColumnType("uniqueidentifier"); b.Property<string>("Currency") .HasColumnType("nvarchar(max)"); b.Property<string>("CustomerRemark") .HasColumnType("nvarchar(max)"); b.Property<Guid?>("DeleterId") .HasColumnName("DeleterId") .HasColumnType("uniqueidentifier"); b.Property<DateTime?>("DeletionTime") .HasColumnName("DeletionTime") .HasColumnType("datetime2"); b.Property<string>("ExternalTradingCode") .HasColumnType("nvarchar(max)"); b.Property<string>("ExtraProperties") .HasColumnName("ExtraProperties") .HasColumnType("nvarchar(max)"); b.Property<bool>("IsDeleted") .ValueGeneratedOnAdd() .HasColumnName("IsDeleted") .HasColumnType("bit") .HasDefaultValue(false); b.Property<DateTime?>("LastModificationTime") .HasColumnName("LastModificationTime") .HasColumnType("datetime2"); b.Property<Guid?>("LastModifierId") .HasColumnName("LastModifierId") .HasColumnType("uniqueidentifier"); b.Property<Guid>("PaymentId") .HasColumnType("uniqueidentifier"); b.Property<Guid>("PaymentItemId") .HasColumnType("uniqueidentifier"); b.Property<decimal>("RefundAmount") .HasColumnType("decimal(18,6)"); b.Property<string>("RefundPaymentMethod") .HasColumnType("nvarchar(max)"); b.Property<string>("StaffRemark") .HasColumnType("nvarchar(max)"); b.Property<Guid?>("TenantId") .HasColumnName("TenantId") .HasColumnType("uniqueidentifier"); b.HasKey("Id"); b.ToTable("PaymentServiceRefunds"); }); modelBuilder.Entity("EasyAbp.PaymentService.WeChatPay.PaymentRecords.PaymentRecord", b => { b.Property<Guid>("Id") .ValueGeneratedOnAdd() .HasColumnType("uniqueidentifier"); b.Property<string>("AppId") .HasColumnType("nvarchar(max)"); b.Property<string>("Attach") .HasColumnType("nvarchar(max)"); b.Property<string>("BankType") .HasColumnType("nvarchar(max)"); b.Property<int>("CashFee") .HasColumnType("int"); b.Property<string>("CashFeeType") .HasColumnType("nvarchar(max)"); b.Property<string>("ConcurrencyStamp") .IsConcurrencyToken() .HasColumnName("ConcurrencyStamp") .HasColumnType("nvarchar(40)") .HasMaxLength(40); b.Property<int?>("CouponCount") .HasColumnType("int"); b.Property<int?>("CouponFee") .HasColumnType("int"); b.Property<string>("CouponFees") .HasColumnType("nvarchar(max)"); b.Property<string>("CouponIds") .HasColumnType("nvarchar(max)"); b.Property<string>("CouponTypes") .HasColumnType("nvarchar(max)"); b.Property<DateTime>("CreationTime") .HasColumnName("CreationTime") .HasColumnType("datetime2"); b.Property<Guid?>("CreatorId") .HasColumnName("CreatorId") .HasColumnType("uniqueidentifier"); b.Property<string>("DeviceInfo") .HasColumnType("nvarchar(max)"); b.Property<string>("ErrCode") .HasColumnType("nvarchar(max)"); b.Property<string>("ErrCodeDes") .HasColumnType("nvarchar(max)"); b.Property<string>("ExtraProperties") .HasColumnName("ExtraProperties") .HasColumnType("nvarchar(max)"); b.Property<string>("FeeType") .HasColumnType("nvarchar(max)"); b.Property<string>("IsSubscribe") .HasColumnType("nvarchar(max)"); b.Property<string>("MchId") .HasColumnType("nvarchar(max)"); b.Property<string>("Openid") .HasColumnType("nvarchar(max)"); b.Property<string>("OutTradeNo") .HasColumnType("nvarchar(max)"); b.Property<Guid>("PaymentId") .HasColumnType("uniqueidentifier"); b.Property<string>("ResultCode") .HasColumnType("nvarchar(max)"); b.Property<string>("ReturnCode") .HasColumnType("nvarchar(max)"); b.Property<string>("ReturnMsg") .HasColumnType("nvarchar(max)"); b.Property<int?>("SettlementTotalFee") .HasColumnType("int"); b.Property<Guid?>("TenantId") .HasColumnName("TenantId") .HasColumnType("uniqueidentifier"); b.Property<string>("TimeEnd") .HasColumnType("nvarchar(max)"); b.Property<int>("TotalFee") .HasColumnType("int"); b.Property<string>("TradeType") .HasColumnType("nvarchar(max)"); b.Property<string>("TransactionId") .HasColumnType("nvarchar(max)"); b.HasKey("Id"); b.HasIndex("PaymentId"); b.ToTable("PaymentServiceWeChatPayPaymentRecords"); }); modelBuilder.Entity("EasyAbp.PaymentService.WeChatPay.RefundRecords.RefundRecord", b => { b.Property<Guid>("Id") .ValueGeneratedOnAdd() .HasColumnType("uniqueidentifier"); b.Property<string>("AppId") .HasColumnType("nvarchar(max)"); b.Property<int>("CashFee") .HasColumnType("int"); b.Property<string>("CashFeeType") .HasColumnType("nvarchar(max)"); b.Property<int?>("CashRefundFee") .HasColumnType("int"); b.Property<string>("ConcurrencyStamp") .IsConcurrencyToken() .HasColumnName("ConcurrencyStamp") .HasColumnType("nvarchar(40)") .HasMaxLength(40); b.Property<string>("CouponIds") .HasColumnType("nvarchar(max)"); b.Property<int?>("CouponRefundCount") .HasColumnType("int"); b.Property<int?>("CouponRefundFee") .HasColumnType("int"); b.Property<string>("CouponRefundFees") .HasColumnType("nvarchar(max)"); b.Property<string>("CouponTypes") .HasColumnType("nvarchar(max)"); b.Property<DateTime>("CreationTime") .HasColumnName("CreationTime") .HasColumnType("datetime2"); b.Property<Guid?>("CreatorId") .HasColumnName("CreatorId") .HasColumnType("uniqueidentifier"); b.Property<string>("ExtraProperties") .HasColumnName("ExtraProperties") .HasColumnType("nvarchar(max)"); b.Property<string>("FeeType") .HasColumnType("nvarchar(max)"); b.Property<string>("MchId") .HasColumnType("nvarchar(max)"); b.Property<string>("OutRefundNo") .HasColumnType("nvarchar(max)"); b.Property<string>("OutTradeNo") .HasColumnType("nvarchar(max)"); b.Property<Guid>("PaymentId") .HasColumnType("uniqueidentifier"); b.Property<string>("RefundAccount") .HasColumnType("nvarchar(max)"); b.Property<int>("RefundFee") .HasColumnType("int"); b.Property<string>("RefundId") .HasColumnType("nvarchar(max)"); b.Property<string>("RefundRecvAccout") .HasColumnType("nvarchar(max)"); b.Property<string>("RefundRequestSource") .HasColumnType("nvarchar(max)"); b.Property<string>("RefundStatus") .HasColumnType("nvarchar(max)"); b.Property<string>("ReturnCode") .HasColumnType("nvarchar(max)"); b.Property<string>("ReturnMsg") .HasColumnType("nvarchar(max)"); b.Property<int?>("SettlementRefundFee") .HasColumnType("int"); b.Property<int?>("SettlementTotalFee") .HasColumnType("int"); b.Property<string>("SuccessTime") .HasColumnType("nvarchar(max)"); b.Property<Guid?>("TenantId") .HasColumnName("TenantId") .HasColumnType("uniqueidentifier"); b.Property<int>("TotalFee") .HasColumnType("int"); b.Property<string>("TransactionId") .HasColumnType("nvarchar(max)"); b.HasKey("Id"); b.HasIndex("PaymentId"); b.ToTable("PaymentServiceWeChatPayRefundRecords"); }); modelBuilder.Entity("Volo.Abp.AuditLogging.AuditLog", b => { b.Property<Guid>("Id") .ValueGeneratedOnAdd() .HasColumnType("uniqueidentifier"); b.Property<string>("ApplicationName") .HasColumnName("ApplicationName") .HasColumnType("nvarchar(96)") .HasMaxLength(96); b.Property<string>("BrowserInfo") .HasColumnName("BrowserInfo") .HasColumnType("nvarchar(512)") .HasMaxLength(512); b.Property<string>("ClientId") .HasColumnName("ClientId") .HasColumnType("nvarchar(64)") .HasMaxLength(64); b.Property<string>("ClientIpAddress") .HasColumnName("ClientIpAddress") .HasColumnType("nvarchar(64)") .HasMaxLength(64); b.Property<string>("ClientName") .HasColumnName("ClientName") .HasColumnType("nvarchar(128)") .HasMaxLength(128); b.Property<string>("Comments") .HasColumnName("Comments") .HasColumnType("nvarchar(256)") .HasMaxLength(256); b.Property<string>("ConcurrencyStamp") .IsConcurrencyToken() .HasColumnName("ConcurrencyStamp") .HasColumnType("nvarchar(40)") .HasMaxLength(40); b.Property<string>("CorrelationId") .HasColumnName("CorrelationId") .HasColumnType("nvarchar(64)") .HasMaxLength(64); b.Property<string>("Exceptions") .HasColumnName("Exceptions") .HasColumnType("nvarchar(4000)") .HasMaxLength(4000); b.Property<int>("ExecutionDuration") .HasColumnName("ExecutionDuration") .HasColumnType("int"); b.Property<DateTime>("ExecutionTime") .HasColumnType("datetime2"); b.Property<string>("ExtraProperties") .HasColumnName("ExtraProperties") .HasColumnType("nvarchar(max)"); b.Property<string>("HttpMethod") .HasColumnName("HttpMethod") .HasColumnType("nvarchar(16)") .HasMaxLength(16); b.Property<int?>("HttpStatusCode") .HasColumnName("HttpStatusCode") .HasColumnType("int"); b.Property<Guid?>("ImpersonatorTenantId") .HasColumnName("ImpersonatorTenantId") .HasColumnType("uniqueidentifier"); b.Property<Guid?>("ImpersonatorUserId") .HasColumnName("ImpersonatorUserId") .HasColumnType("uniqueidentifier"); b.Property<Guid?>("TenantId") .HasColumnName("TenantId") .HasColumnType("uniqueidentifier"); b.Property<string>("TenantName") .HasColumnType("nvarchar(max)"); b.Property<string>("Url") .HasColumnName("Url") .HasColumnType("nvarchar(256)") .HasMaxLength(256); b.Property<Guid?>("UserId") .HasColumnName("UserId") .HasColumnType("uniqueidentifier"); b.Property<string>("UserName") .HasColumnName("UserName") .HasColumnType("nvarchar(256)") .HasMaxLength(256); b.HasKey("Id"); b.HasIndex("TenantId", "ExecutionTime"); b.HasIndex("TenantId", "UserId", "ExecutionTime"); b.ToTable("AbpAuditLogs"); }); modelBuilder.Entity("Volo.Abp.AuditLogging.AuditLogAction", b => { b.Property<Guid>("Id") .ValueGeneratedOnAdd() .HasColumnType("uniqueidentifier"); b.Property<Guid>("AuditLogId") .HasColumnName("AuditLogId") .HasColumnType("uniqueidentifier"); b.Property<int>("ExecutionDuration") .HasColumnName("ExecutionDuration") .HasColumnType("int"); b.Property<DateTime>("ExecutionTime") .HasColumnName("ExecutionTime") .HasColumnType("datetime2"); b.Property<string>("ExtraProperties") .HasColumnName("ExtraProperties") .HasColumnType("nvarchar(max)"); b.Property<string>("MethodName") .HasColumnName("MethodName") .HasColumnType("nvarchar(128)") .HasMaxLength(128); b.Property<string>("Parameters") .HasColumnName("Parameters") .HasColumnType("nvarchar(2000)") .HasMaxLength(2000); b.Property<string>("ServiceName") .HasColumnName("ServiceName") .HasColumnType("nvarchar(256)") .HasMaxLength(256); b.Property<Guid?>("TenantId") .HasColumnName("TenantId") .HasColumnType("uniqueidentifier"); b.HasKey("Id"); b.HasIndex("AuditLogId"); b.HasIndex("TenantId", "ServiceName", "MethodName", "ExecutionTime"); b.ToTable("AbpAuditLogActions"); }); modelBuilder.Entity("Volo.Abp.AuditLogging.EntityChange", b => { b.Property<Guid>("Id") .ValueGeneratedOnAdd() .HasColumnType("uniqueidentifier"); b.Property<Guid>("AuditLogId") .HasColumnName("AuditLogId") .HasColumnType("uniqueidentifier"); b.Property<DateTime>("ChangeTime") .HasColumnName("ChangeTime") .HasColumnType("datetime2"); b.Property<byte>("ChangeType") .HasColumnName("ChangeType") .HasColumnType("tinyint"); b.Property<string>("EntityId") .IsRequired() .HasColumnName("EntityId") .HasColumnType("nvarchar(128)") .HasMaxLength(128); b.Property<Guid?>("EntityTenantId") .HasColumnType("uniqueidentifier"); b.Property<string>("EntityTypeFullName") .IsRequired() .HasColumnName("EntityTypeFullName") .HasColumnType("nvarchar(128)") .HasMaxLength(128); b.Property<string>("ExtraProperties") .HasColumnName("ExtraProperties") .HasColumnType("nvarchar(max)"); b.Property<Guid?>("TenantId") .HasColumnName("TenantId") .HasColumnType("uniqueidentifier"); b.HasKey("Id"); b.HasIndex("AuditLogId"); b.HasIndex("TenantId", "EntityTypeFullName", "EntityId"); b.ToTable("AbpEntityChanges"); }); modelBuilder.Entity("Volo.Abp.AuditLogging.EntityPropertyChange", b => { b.Property<Guid>("Id") .ValueGeneratedOnAdd() .HasColumnType("uniqueidentifier"); b.Property<Guid>("EntityChangeId") .HasColumnType("uniqueidentifier"); b.Property<string>("NewValue") .HasColumnName("NewValue") .HasColumnType("nvarchar(512)") .HasMaxLength(512); b.Property<string>("OriginalValue") .HasColumnName("OriginalValue") .HasColumnType("nvarchar(512)") .HasMaxLength(512); b.Property<string>("PropertyName") .IsRequired() .HasColumnName("PropertyName") .HasColumnType("nvarchar(128)") .HasMaxLength(128); b.Property<string>("PropertyTypeFullName") .IsRequired() .HasColumnName("PropertyTypeFullName") .HasColumnType("nvarchar(64)") .HasMaxLength(64); b.Property<Guid?>("TenantId") .HasColumnName("TenantId") .HasColumnType("uniqueidentifier"); b.HasKey("Id"); b.HasIndex("EntityChangeId"); b.ToTable("AbpEntityPropertyChanges"); }); modelBuilder.Entity("Volo.Abp.BackgroundJobs.BackgroundJobRecord", b => { b.Property<Guid>("Id") .ValueGeneratedOnAdd() .HasColumnType("uniqueidentifier"); b.Property<string>("ConcurrencyStamp") .IsConcurrencyToken() .HasColumnName("ConcurrencyStamp") .HasColumnType("nvarchar(40)") .HasMaxLength(40); b.Property<DateTime>("CreationTime") .HasColumnName("CreationTime") .HasColumnType("datetime2"); b.Property<string>("ExtraProperties") .HasColumnName("ExtraProperties") .HasColumnType("nvarchar(max)"); b.Property<bool>("IsAbandoned") .ValueGeneratedOnAdd() .HasColumnType("bit") .HasDefaultValue(false); b.Property<string>("JobArgs") .IsRequired() .HasColumnType("nvarchar(max)") .HasMaxLength(1048576); b.Property<string>("JobName") .IsRequired() .HasColumnType("nvarchar(128)") .HasMaxLength(128); b.Property<DateTime?>("LastTryTime") .HasColumnType("datetime2"); b.Property<DateTime>("NextTryTime") .HasColumnType("datetime2"); b.Property<byte>("Priority") .ValueGeneratedOnAdd() .HasColumnType("tinyint") .HasDefaultValue((byte)15); b.Property<short>("TryCount") .ValueGeneratedOnAdd() .HasColumnType("smallint") .HasDefaultValue((short)0); b.HasKey("Id"); b.HasIndex("IsAbandoned", "NextTryTime"); b.ToTable("AbpBackgroundJobs"); }); modelBuilder.Entity("Volo.Abp.FeatureManagement.FeatureValue", b => { b.Property<Guid>("Id") .ValueGeneratedOnAdd() .HasColumnType("uniqueidentifier"); b.Property<string>("Name") .IsRequired() .HasColumnType("nvarchar(128)") .HasMaxLength(128); b.Property<string>("ProviderKey") .HasColumnType("nvarchar(64)") .HasMaxLength(64); b.Property<string>("ProviderName") .HasColumnType("nvarchar(64)") .HasMaxLength(64); b.Property<string>("Value") .IsRequired() .HasColumnType("nvarchar(128)") .HasMaxLength(128); b.HasKey("Id"); b.HasIndex("Name", "ProviderName", "ProviderKey"); b.ToTable("AbpFeatureValues"); }); modelBuilder.Entity("Volo.Abp.Identity.IdentityClaimType", b => { b.Property<Guid>("Id") .ValueGeneratedOnAdd() .HasColumnType("uniqueidentifier"); b.Property<string>("ConcurrencyStamp") .IsConcurrencyToken() .HasColumnName("ConcurrencyStamp") .HasColumnType("nvarchar(40)") .HasMaxLength(40); b.Property<string>("Description") .HasColumnType("nvarchar(256)") .HasMaxLength(256); b.Property<string>("ExtraProperties") .HasColumnName("ExtraProperties") .HasColumnType("nvarchar(max)"); b.Property<bool>("IsStatic") .HasColumnType("bit"); b.Property<string>("Name") .IsRequired() .HasColumnType("nvarchar(256)") .HasMaxLength(256); b.Property<string>("Regex") .HasColumnType("nvarchar(512)") .HasMaxLength(512); b.Property<string>("RegexDescription") .HasColumnType("nvarchar(128)") .HasMaxLength(128); b.Property<bool>("Required") .HasColumnType("bit"); b.Property<int>("ValueType") .HasColumnType("int"); b.HasKey("Id"); b.ToTable("AbpClaimTypes"); }); modelBuilder.Entity("Volo.Abp.Identity.IdentityRole", b => { b.Property<Guid>("Id") .ValueGeneratedOnAdd() .HasColumnType("uniqueidentifier"); b.Property<string>("ConcurrencyStamp") .IsConcurrencyToken() .HasColumnName("ConcurrencyStamp") .HasColumnType("nvarchar(40)") .HasMaxLength(40); b.Property<string>("ExtraProperties") .HasColumnName("ExtraProperties") .HasColumnType("nvarchar(max)"); b.Property<bool>("IsDefault") .HasColumnName("IsDefault") .HasColumnType("bit"); b.Property<bool>("IsPublic") .HasColumnName("IsPublic") .HasColumnType("bit"); b.Property<bool>("IsStatic") .HasColumnName("IsStatic") .HasColumnType("bit"); b.Property<string>("Name") .IsRequired() .HasColumnType("nvarchar(256)") .HasMaxLength(256); b.Property<string>("NormalizedName") .IsRequired() .HasColumnType("nvarchar(256)") .HasMaxLength(256); b.Property<Guid?>("TenantId") .HasColumnName("TenantId") .HasColumnType("uniqueidentifier"); b.HasKey("Id"); b.HasIndex("NormalizedName"); b.ToTable("AbpRoles"); }); modelBuilder.Entity("Volo.Abp.Identity.IdentityRoleClaim", b => { b.Property<Guid>("Id") .HasColumnType("uniqueidentifier"); b.Property<string>("ClaimType") .IsRequired() .HasColumnType("nvarchar(256)") .HasMaxLength(256); b.Property<string>("ClaimValue") .HasColumnType("nvarchar(1024)") .HasMaxLength(1024); b.Property<Guid>("RoleId") .HasColumnType("uniqueidentifier"); b.Property<Guid?>("TenantId") .HasColumnName("TenantId") .HasColumnType("uniqueidentifier"); b.HasKey("Id"); b.HasIndex("RoleId"); b.ToTable("AbpRoleClaims"); }); modelBuilder.Entity("Volo.Abp.Identity.IdentityUser", b => { b.Property<Guid>("Id") .ValueGeneratedOnAdd() .HasColumnType("uniqueidentifier"); b.Property<int>("AccessFailedCount") .ValueGeneratedOnAdd() .HasColumnName("AccessFailedCount") .HasColumnType("int") .HasDefaultValue(0); b.Property<string>("ConcurrencyStamp") .IsConcurrencyToken() .HasColumnName("ConcurrencyStamp") .HasColumnType("nvarchar(40)") .HasMaxLength(40); b.Property<DateTime>("CreationTime") .HasColumnName("CreationTime") .HasColumnType("datetime2"); b.Property<Guid?>("CreatorId") .HasColumnName("CreatorId") .HasColumnType("uniqueidentifier"); b.Property<Guid?>("DeleterId") .HasColumnName("DeleterId") .HasColumnType("uniqueidentifier"); b.Property<DateTime?>("DeletionTime") .HasColumnName("DeletionTime") .HasColumnType("datetime2"); b.Property<string>("Email") .IsRequired() .HasColumnName("Email") .HasColumnType("nvarchar(256)") .HasMaxLength(256); b.Property<bool>("EmailConfirmed") .ValueGeneratedOnAdd() .HasColumnName("EmailConfirmed") .HasColumnType("bit") .HasDefaultValue(false); b.Property<string>("ExtraProperties") .HasColumnName("ExtraProperties") .HasColumnType("nvarchar(max)"); b.Property<bool>("IsDeleted") .ValueGeneratedOnAdd() .HasColumnName("IsDeleted") .HasColumnType("bit") .HasDefaultValue(false); b.Property<DateTime?>("LastModificationTime") .HasColumnName("LastModificationTime") .HasColumnType("datetime2"); b.Property<Guid?>("LastModifierId") .HasColumnName("LastModifierId") .HasColumnType("uniqueidentifier"); b.Property<bool>("LockoutEnabled") .ValueGeneratedOnAdd() .HasColumnName("LockoutEnabled") .HasColumnType("bit") .HasDefaultValue(false); b.Property<DateTimeOffset?>("LockoutEnd") .HasColumnType("datetimeoffset"); b.Property<string>("Name") .HasColumnName("Name") .HasColumnType("nvarchar(64)") .HasMaxLength(64); b.Property<string>("NormalizedEmail") .IsRequired() .HasColumnName("NormalizedEmail") .HasColumnType("nvarchar(256)") .HasMaxLength(256); b.Property<string>("NormalizedUserName") .IsRequired() .HasColumnName("NormalizedUserName") .HasColumnType("nvarchar(256)") .HasMaxLength(256); b.Property<string>("PasswordHash") .HasColumnName("PasswordHash") .HasColumnType("nvarchar(256)") .HasMaxLength(256); b.Property<string>("PhoneNumber") .HasColumnName("PhoneNumber") .HasColumnType("nvarchar(16)") .HasMaxLength(16); b.Property<bool>("PhoneNumberConfirmed") .ValueGeneratedOnAdd() .HasColumnName("PhoneNumberConfirmed") .HasColumnType("bit") .HasDefaultValue(false); b.Property<string>("SecurityStamp") .IsRequired() .HasColumnName("SecurityStamp") .HasColumnType("nvarchar(256)") .HasMaxLength(256); b.Property<string>("Surname") .HasColumnName("Surname") .HasColumnType("nvarchar(64)") .HasMaxLength(64); b.Property<Guid?>("TenantId") .HasColumnName("TenantId") .HasColumnType("uniqueidentifier"); b.Property<bool>("TwoFactorEnabled") .ValueGeneratedOnAdd() .HasColumnName("TwoFactorEnabled") .HasColumnType("bit") .HasDefaultValue(false); b.Property<string>("UserName") .IsRequired() .HasColumnName("UserName") .HasColumnType("nvarchar(256)") .HasMaxLength(256); b.HasKey("Id"); b.HasIndex("Email"); b.HasIndex("NormalizedEmail"); b.HasIndex("NormalizedUserName"); b.HasIndex("UserName"); b.ToTable("AbpUsers"); }); modelBuilder.Entity("Volo.Abp.Identity.IdentityUserClaim", b => { b.Property<Guid>("Id") .HasColumnType("uniqueidentifier"); b.Property<string>("ClaimType") .IsRequired() .HasColumnType("nvarchar(256)") .HasMaxLength(256); b.Property<string>("ClaimValue") .HasColumnType("nvarchar(1024)") .HasMaxLength(1024); b.Property<Guid?>("TenantId") .HasColumnName("TenantId") .HasColumnType("uniqueidentifier"); b.Property<Guid>("UserId") .HasColumnType("uniqueidentifier"); b.HasKey("Id"); b.HasIndex("UserId"); b.ToTable("AbpUserClaims"); }); modelBuilder.Entity("Volo.Abp.Identity.IdentityUserLogin", b => { b.Property<Guid>("UserId") .HasColumnType("uniqueidentifier"); b.Property<string>("LoginProvider") .HasColumnType("nvarchar(64)") .HasMaxLength(64); b.Property<string>("ProviderDisplayName") .HasColumnType("nvarchar(128)") .HasMaxLength(128); b.Property<string>("ProviderKey") .IsRequired() .HasColumnType("nvarchar(196)") .HasMaxLength(196); b.Property<Guid?>("TenantId") .HasColumnName("TenantId") .HasColumnType("uniqueidentifier"); b.HasKey("UserId", "LoginProvider"); b.HasIndex("LoginProvider", "ProviderKey"); b.ToTable("AbpUserLogins"); }); modelBuilder.Entity("Volo.Abp.Identity.IdentityUserOrganizationUnit", b => { b.Property<Guid>("OrganizationUnitId") .HasColumnType("uniqueidentifier"); b.Property<Guid>("UserId") .HasColumnType("uniqueidentifier"); b.Property<DateTime>("CreationTime") .HasColumnName("CreationTime") .HasColumnType("datetime2"); b.Property<Guid?>("CreatorId") .HasColumnName("CreatorId") .HasColumnType("uniqueidentifier"); b.Property<Guid?>("TenantId") .HasColumnName("TenantId") .HasColumnType("uniqueidentifier"); b.HasKey("OrganizationUnitId", "UserId"); b.HasIndex("UserId", "OrganizationUnitId"); b.ToTable("AbpUserOrganizationUnits"); }); modelBuilder.Entity("Volo.Abp.Identity.IdentityUserRole", b => { b.Property<Guid>("UserId") .HasColumnType("uniqueidentifier"); b.Property<Guid>("RoleId") .HasColumnType("uniqueidentifier"); b.Property<Guid?>("TenantId") .HasColumnName("TenantId") .HasColumnType("uniqueidentifier"); b.HasKey("UserId", "RoleId"); b.HasIndex("RoleId", "UserId"); b.ToTable("AbpUserRoles"); }); modelBuilder.Entity("Volo.Abp.Identity.IdentityUserToken", b => { b.Property<Guid>("UserId") .HasColumnType("uniqueidentifier"); b.Property<string>("LoginProvider") .HasColumnType("nvarchar(64)") .HasMaxLength(64); b.Property<string>("Name") .HasColumnType("nvarchar(128)") .HasMaxLength(128); b.Property<Guid?>("TenantId") .HasColumnName("TenantId") .HasColumnType("uniqueidentifier"); b.Property<string>("Value") .HasColumnType("nvarchar(max)"); b.HasKey("UserId", "LoginProvider", "Name"); b.ToTable("AbpUserTokens"); }); modelBuilder.Entity("Volo.Abp.Identity.OrganizationUnit", b => { b.Property<Guid>("Id") .ValueGeneratedOnAdd() .HasColumnType("uniqueidentifier"); b.Property<string>("Code") .IsRequired() .HasColumnName("Code") .HasColumnType("nvarchar(95)") .HasMaxLength(95); b.Property<string>("ConcurrencyStamp") .IsConcurrencyToken() .HasColumnName("ConcurrencyStamp") .HasColumnType("nvarchar(40)") .HasMaxLength(40); b.Property<DateTime>("CreationTime") .HasColumnName("CreationTime") .HasColumnType("datetime2"); b.Property<Guid?>("CreatorId") .HasColumnName("CreatorId") .HasColumnType("uniqueidentifier"); b.Property<Guid?>("DeleterId") .HasColumnName("DeleterId") .HasColumnType("uniqueidentifier"); b.Property<DateTime?>("DeletionTime") .HasColumnName("DeletionTime") .HasColumnType("datetime2"); b.Property<string>("DisplayName") .IsRequired() .HasColumnName("DisplayName") .HasColumnType("nvarchar(128)") .HasMaxLength(128); b.Property<string>("ExtraProperties") .HasColumnName("ExtraProperties") .HasColumnType("nvarchar(max)"); b.Property<bool>("IsDeleted") .ValueGeneratedOnAdd() .HasColumnName("IsDeleted") .HasColumnType("bit") .HasDefaultValue(false); b.Property<DateTime?>("LastModificationTime") .HasColumnName("LastModificationTime") .HasColumnType("datetime2"); b.Property<Guid?>("LastModifierId") .HasColumnName("LastModifierId") .HasColumnType("uniqueidentifier"); b.Property<Guid?>("ParentId") .HasColumnType("uniqueidentifier"); b.Property<Guid?>("TenantId") .HasColumnName("TenantId") .HasColumnType("uniqueidentifier"); b.HasKey("Id"); b.HasIndex("Code"); b.HasIndex("ParentId"); b.ToTable("AbpOrganizationUnits"); }); modelBuilder.Entity("Volo.Abp.Identity.OrganizationUnitRole", b => { b.Property<Guid>("OrganizationUnitId") .HasColumnType("uniqueidentifier"); b.Property<Guid>("RoleId") .HasColumnType("uniqueidentifier"); b.Property<DateTime>("CreationTime") .HasColumnName("CreationTime") .HasColumnType("datetime2"); b.Property<Guid?>("CreatorId") .HasColumnName("CreatorId") .HasColumnType("uniqueidentifier"); b.Property<Guid?>("TenantId") .HasColumnName("TenantId") .HasColumnType("uniqueidentifier"); b.HasKey("OrganizationUnitId", "RoleId"); b.HasIndex("RoleId", "OrganizationUnitId"); b.ToTable("AbpOrganizationUnitRoles"); }); modelBuilder.Entity("Volo.Abp.IdentityServer.ApiResources.ApiResource", b => { b.Property<Guid>("Id") .ValueGeneratedOnAdd() .HasColumnType("uniqueidentifier"); b.Property<string>("ConcurrencyStamp") .IsConcurrencyToken() .HasColumnName("ConcurrencyStamp") .HasColumnType("nvarchar(40)") .HasMaxLength(40); b.Property<DateTime>("CreationTime") .HasColumnName("CreationTime") .HasColumnType("datetime2"); b.Property<Guid?>("CreatorId") .HasColumnName("CreatorId") .HasColumnType("uniqueidentifier"); b.Property<Guid?>("DeleterId") .HasColumnName("DeleterId") .HasColumnType("uniqueidentifier"); b.Property<DateTime?>("DeletionTime") .HasColumnName("DeletionTime") .HasColumnType("datetime2"); b.Property<string>("Description") .HasColumnType("nvarchar(1000)") .HasMaxLength(1000); b.Property<string>("DisplayName") .HasColumnType("nvarchar(200)") .HasMaxLength(200); b.Property<bool>("Enabled") .HasColumnType("bit"); b.Property<string>("ExtraProperties") .HasColumnName("ExtraProperties") .HasColumnType("nvarchar(max)"); b.Property<bool>("IsDeleted") .ValueGeneratedOnAdd() .HasColumnName("IsDeleted") .HasColumnType("bit") .HasDefaultValue(false); b.Property<DateTime?>("LastModificationTime") .HasColumnName("LastModificationTime") .HasColumnType("datetime2"); b.Property<Guid?>("LastModifierId") .HasColumnName("LastModifierId") .HasColumnType("uniqueidentifier"); b.Property<string>("Name") .IsRequired() .HasColumnType("nvarchar(200)") .HasMaxLength(200); b.Property<string>("Properties") .HasColumnType("nvarchar(max)"); b.HasKey("Id"); b.ToTable("IdentityServerApiResources"); }); modelBuilder.Entity("Volo.Abp.IdentityServer.ApiResources.ApiResourceClaim", b => { b.Property<Guid>("ApiResourceId") .HasColumnType("uniqueidentifier"); b.Property<string>("Type") .HasColumnType("nvarchar(200)") .HasMaxLength(200); b.HasKey("ApiResourceId", "Type"); b.ToTable("IdentityServerApiClaims"); }); modelBuilder.Entity("Volo.Abp.IdentityServer.ApiResources.ApiScope", b => { b.Property<Guid>("ApiResourceId") .HasColumnType("uniqueidentifier"); b.Property<string>("Name") .HasColumnType("nvarchar(200)") .HasMaxLength(200); b.Property<string>("Description") .HasColumnType("nvarchar(1000)") .HasMaxLength(1000); b.Property<string>("DisplayName") .HasColumnType("nvarchar(200)") .HasMaxLength(200); b.Property<bool>("Emphasize") .HasColumnType("bit"); b.Property<bool>("Required") .HasColumnType("bit"); b.Property<bool>("ShowInDiscoveryDocument") .HasColumnType("bit"); b.HasKey("ApiResourceId", "Name"); b.ToTable("IdentityServerApiScopes"); }); modelBuilder.Entity("Volo.Abp.IdentityServer.ApiResources.ApiScopeClaim", b => { b.Property<Guid>("ApiResourceId") .HasColumnType("uniqueidentifier"); b.Property<string>("Name") .HasColumnType("nvarchar(200)") .HasMaxLength(200); b.Property<string>("Type") .HasColumnType("nvarchar(200)") .HasMaxLength(200); b.HasKey("ApiResourceId", "Name", "Type"); b.ToTable("IdentityServerApiScopeClaims"); }); modelBuilder.Entity("Volo.Abp.IdentityServer.ApiResources.ApiSecret", b => { b.Property<Guid>("ApiResourceId") .HasColumnType("uniqueidentifier"); b.Property<string>("Type") .HasColumnType("nvarchar(250)") .HasMaxLength(250); b.Property<string>("Value") .HasColumnType("nvarchar(4000)") .HasMaxLength(4000); b.Property<string>("Description") .HasColumnType("nvarchar(2000)") .HasMaxLength(2000); b.Property<DateTime?>("Expiration") .HasColumnType("datetime2"); b.HasKey("ApiResourceId", "Type", "Value"); b.ToTable("IdentityServerApiSecrets"); }); modelBuilder.Entity("Volo.Abp.IdentityServer.Clients.Client", b => { b.Property<Guid>("Id") .ValueGeneratedOnAdd() .HasColumnType("uniqueidentifier"); b.Property<int>("AbsoluteRefreshTokenLifetime") .HasColumnType("int"); b.Property<int>("AccessTokenLifetime") .HasColumnType("int"); b.Property<int>("AccessTokenType") .HasColumnType("int"); b.Property<bool>("AllowAccessTokensViaBrowser") .HasColumnType("bit"); b.Property<bool>("AllowOfflineAccess") .HasColumnType("bit"); b.Property<bool>("AllowPlainTextPkce") .HasColumnType("bit"); b.Property<bool>("AllowRememberConsent") .HasColumnType("bit"); b.Property<bool>("AlwaysIncludeUserClaimsInIdToken") .HasColumnType("bit"); b.Property<bool>("AlwaysSendClientClaims") .HasColumnType("bit"); b.Property<int>("AuthorizationCodeLifetime") .HasColumnType("int"); b.Property<bool>("BackChannelLogoutSessionRequired") .HasColumnType("bit"); b.Property<string>("BackChannelLogoutUri") .HasColumnType("nvarchar(2000)") .HasMaxLength(2000); b.Property<string>("ClientClaimsPrefix") .HasColumnType("nvarchar(200)") .HasMaxLength(200); b.Property<string>("ClientId") .IsRequired() .HasColumnType("nvarchar(200)") .HasMaxLength(200); b.Property<string>("ClientName") .HasColumnType("nvarchar(200)") .HasMaxLength(200); b.Property<string>("ClientUri") .HasColumnType("nvarchar(2000)") .HasMaxLength(2000); b.Property<string>("ConcurrencyStamp") .IsConcurrencyToken() .HasColumnName("ConcurrencyStamp") .HasColumnType("nvarchar(40)") .HasMaxLength(40); b.Property<int?>("ConsentLifetime") .HasColumnType("int"); b.Property<DateTime>("CreationTime") .HasColumnName("CreationTime") .HasColumnType("datetime2"); b.Property<Guid?>("CreatorId") .HasColumnName("CreatorId") .HasColumnType("uniqueidentifier"); b.Property<Guid?>("DeleterId") .HasColumnName("DeleterId") .HasColumnType("uniqueidentifier"); b.Property<DateTime?>("DeletionTime") .HasColumnName("DeletionTime") .HasColumnType("datetime2"); b.Property<string>("Description") .HasColumnType("nvarchar(1000)") .HasMaxLength(1000); b.Property<int>("DeviceCodeLifetime") .HasColumnType("int"); b.Property<bool>("EnableLocalLogin") .HasColumnType("bit"); b.Property<bool>("Enabled") .HasColumnType("bit"); b.Property<string>("ExtraProperties") .HasColumnName("ExtraProperties") .HasColumnType("nvarchar(max)"); b.Property<bool>("FrontChannelLogoutSessionRequired") .HasColumnType("bit"); b.Property<string>("FrontChannelLogoutUri") .HasColumnType("nvarchar(2000)") .HasMaxLength(2000); b.Property<int>("IdentityTokenLifetime") .HasColumnType("int"); b.Property<bool>("IncludeJwtId") .HasColumnType("bit"); b.Property<bool>("IsDeleted") .ValueGeneratedOnAdd() .HasColumnName("IsDeleted") .HasColumnType("bit") .HasDefaultValue(false); b.Property<DateTime?>("LastModificationTime") .HasColumnName("LastModificationTime") .HasColumnType("datetime2"); b.Property<Guid?>("LastModifierId") .HasColumnName("LastModifierId") .HasColumnType("uniqueidentifier"); b.Property<string>("LogoUri") .HasColumnType("nvarchar(2000)") .HasMaxLength(2000); b.Property<string>("PairWiseSubjectSalt") .HasColumnType("nvarchar(200)") .HasMaxLength(200); b.Property<string>("ProtocolType") .IsRequired() .HasColumnType("nvarchar(200)") .HasMaxLength(200); b.Property<int>("RefreshTokenExpiration") .HasColumnType("int"); b.Property<int>("RefreshTokenUsage") .HasColumnType("int"); b.Property<bool>("RequireClientSecret") .HasColumnType("bit"); b.Property<bool>("RequireConsent") .HasColumnType("bit"); b.Property<bool>("RequirePkce") .HasColumnType("bit"); b.Property<int>("SlidingRefreshTokenLifetime") .HasColumnType("int"); b.Property<bool>("UpdateAccessTokenClaimsOnRefresh") .HasColumnType("bit"); b.Property<string>("UserCodeType") .HasColumnType("nvarchar(100)") .HasMaxLength(100); b.Property<int?>("UserSsoLifetime") .HasColumnType("int"); b.HasKey("Id"); b.HasIndex("ClientId"); b.ToTable("IdentityServerClients"); }); modelBuilder.Entity("Volo.Abp.IdentityServer.Clients.ClientClaim", b => { b.Property<Guid>("ClientId") .HasColumnType("uniqueidentifier"); b.Property<string>("Type") .HasColumnType("nvarchar(250)") .HasMaxLength(250); b.Property<string>("Value") .HasColumnType("nvarchar(250)") .HasMaxLength(250); b.HasKey("ClientId", "Type", "Value"); b.ToTable("IdentityServerClientClaims"); }); modelBuilder.Entity("Volo.Abp.IdentityServer.Clients.ClientCorsOrigin", b => { b.Property<Guid>("ClientId") .HasColumnType("uniqueidentifier"); b.Property<string>("Origin") .HasColumnType("nvarchar(150)") .HasMaxLength(150); b.HasKey("ClientId", "Origin"); b.ToTable("IdentityServerClientCorsOrigins"); }); modelBuilder.Entity("Volo.Abp.IdentityServer.Clients.ClientGrantType", b => { b.Property<Guid>("ClientId") .HasColumnType("uniqueidentifier"); b.Property<string>("GrantType") .HasColumnType("nvarchar(250)") .HasMaxLength(250); b.HasKey("ClientId", "GrantType"); b.ToTable("IdentityServerClientGrantTypes"); }); modelBuilder.Entity("Volo.Abp.IdentityServer.Clients.ClientIdPRestriction", b => { b.Property<Guid>("ClientId") .HasColumnType("uniqueidentifier"); b.Property<string>("Provider") .HasColumnType("nvarchar(200)") .HasMaxLength(200); b.HasKey("ClientId", "Provider"); b.ToTable("IdentityServerClientIdPRestrictions"); }); modelBuilder.Entity("Volo.Abp.IdentityServer.Clients.ClientPostLogoutRedirectUri", b => { b.Property<Guid>("ClientId") .HasColumnType("uniqueidentifier"); b.Property<string>("PostLogoutRedirectUri") .HasColumnType("nvarchar(2000)") .HasMaxLength(2000); b.HasKey("ClientId", "PostLogoutRedirectUri"); b.ToTable("IdentityServerClientPostLogoutRedirectUris"); }); modelBuilder.Entity("Volo.Abp.IdentityServer.Clients.ClientProperty", b => { b.Property<Guid>("ClientId") .HasColumnType("uniqueidentifier"); b.Property<string>("Key") .HasColumnType("nvarchar(250)") .HasMaxLength(250); b.Property<string>("Value") .IsRequired() .HasColumnType("nvarchar(2000)") .HasMaxLength(2000); b.HasKey("ClientId", "Key"); b.ToTable("IdentityServerClientProperties"); }); modelBuilder.Entity("Volo.Abp.IdentityServer.Clients.ClientRedirectUri", b => { b.Property<Guid>("ClientId") .HasColumnType("uniqueidentifier"); b.Property<string>("RedirectUri") .HasColumnType("nvarchar(2000)") .HasMaxLength(2000); b.HasKey("ClientId", "RedirectUri"); b.ToTable("IdentityServerClientRedirectUris"); }); modelBuilder.Entity("Volo.Abp.IdentityServer.Clients.ClientScope", b => { b.Property<Guid>("ClientId") .HasColumnType("uniqueidentifier"); b.Property<string>("Scope") .HasColumnType("nvarchar(200)") .HasMaxLength(200); b.HasKey("ClientId", "Scope"); b.ToTable("IdentityServerClientScopes"); }); modelBuilder.Entity("Volo.Abp.IdentityServer.Clients.ClientSecret", b => { b.Property<Guid>("ClientId") .HasColumnType("uniqueidentifier"); b.Property<string>("Type") .HasColumnType("nvarchar(250)") .HasMaxLength(250); b.Property<string>("Value") .HasColumnType("nvarchar(4000)") .HasMaxLength(4000); b.Property<string>("Description") .HasColumnType("nvarchar(2000)") .HasMaxLength(2000); b.Property<DateTime?>("Expiration") .HasColumnType("datetime2"); b.HasKey("ClientId", "Type", "Value"); b.ToTable("IdentityServerClientSecrets"); }); modelBuilder.Entity("Volo.Abp.IdentityServer.Devices.DeviceFlowCodes", b => { b.Property<Guid>("Id") .ValueGeneratedOnAdd() .HasColumnType("uniqueidentifier"); b.Property<string>("ClientId") .IsRequired() .HasColumnType("nvarchar(200)") .HasMaxLength(200); b.Property<string>("ConcurrencyStamp") .IsConcurrencyToken() .HasColumnName("ConcurrencyStamp") .HasColumnType("nvarchar(40)") .HasMaxLength(40); b.Property<DateTime>("CreationTime") .HasColumnName("CreationTime") .HasColumnType("datetime2"); b.Property<Guid?>("CreatorId") .HasColumnName("CreatorId") .HasColumnType("uniqueidentifier"); b.Property<string>("Data") .IsRequired() .HasColumnType("nvarchar(max)") .HasMaxLength(50000); b.Property<string>("DeviceCode") .IsRequired() .HasColumnType("nvarchar(200)") .HasMaxLength(200); b.Property<DateTime?>("Expiration") .IsRequired() .HasColumnType("datetime2"); b.Property<string>("ExtraProperties") .HasColumnName("ExtraProperties") .HasColumnType("nvarchar(max)"); b.Property<string>("SubjectId") .HasColumnType("nvarchar(200)") .HasMaxLength(200); b.Property<string>("UserCode") .IsRequired() .HasColumnType("nvarchar(200)") .HasMaxLength(200); b.HasKey("Id"); b.HasIndex("DeviceCode") .IsUnique(); b.HasIndex("Expiration"); b.HasIndex("UserCode") .IsUnique(); b.ToTable("IdentityServerDeviceFlowCodes"); }); modelBuilder.Entity("Volo.Abp.IdentityServer.Grants.PersistedGrant", b => { b.Property<string>("Key") .HasColumnType("nvarchar(200)") .HasMaxLength(200); b.Property<string>("ClientId") .IsRequired() .HasColumnType("nvarchar(200)") .HasMaxLength(200); b.Property<string>("ConcurrencyStamp") .IsConcurrencyToken() .HasColumnName("ConcurrencyStamp") .HasColumnType("nvarchar(40)") .HasMaxLength(40); b.Property<DateTime>("CreationTime") .HasColumnType("datetime2"); b.Property<string>("Data") .IsRequired() .HasColumnType("nvarchar(max)") .HasMaxLength(50000); b.Property<DateTime?>("Expiration") .HasColumnType("datetime2"); b.Property<string>("ExtraProperties") .HasColumnName("ExtraProperties") .HasColumnType("nvarchar(max)"); b.Property<Guid>("Id") .HasColumnType("uniqueidentifier"); b.Property<string>("SubjectId") .HasColumnType("nvarchar(200)") .HasMaxLength(200); b.Property<string>("Type") .IsRequired() .HasColumnType("nvarchar(50)") .HasMaxLength(50); b.HasKey("Key"); b.HasIndex("Expiration"); b.HasIndex("SubjectId", "ClientId", "Type"); b.ToTable("IdentityServerPersistedGrants"); }); modelBuilder.Entity("Volo.Abp.IdentityServer.IdentityResources.IdentityClaim", b => { b.Property<Guid>("IdentityResourceId") .HasColumnType("uniqueidentifier"); b.Property<string>("Type") .HasColumnType("nvarchar(200)") .HasMaxLength(200); b.HasKey("IdentityResourceId", "Type"); b.ToTable("IdentityServerIdentityClaims"); }); modelBuilder.Entity("Volo.Abp.IdentityServer.IdentityResources.IdentityResource", b => { b.Property<Guid>("Id") .ValueGeneratedOnAdd() .HasColumnType("uniqueidentifier"); b.Property<string>("ConcurrencyStamp") .IsConcurrencyToken() .HasColumnName("ConcurrencyStamp") .HasColumnType("nvarchar(40)") .HasMaxLength(40); b.Property<DateTime>("CreationTime") .HasColumnName("CreationTime") .HasColumnType("datetime2"); b.Property<Guid?>("CreatorId") .HasColumnName("CreatorId") .HasColumnType("uniqueidentifier"); b.Property<Guid?>("DeleterId") .HasColumnName("DeleterId") .HasColumnType("uniqueidentifier"); b.Property<DateTime?>("DeletionTime") .HasColumnName("DeletionTime") .HasColumnType("datetime2"); b.Property<string>("Description") .HasColumnType("nvarchar(1000)") .HasMaxLength(1000); b.Property<string>("DisplayName") .HasColumnType("nvarchar(200)") .HasMaxLength(200); b.Property<bool>("Emphasize") .HasColumnType("bit"); b.Property<bool>("Enabled") .HasColumnType("bit"); b.Property<string>("ExtraProperties") .HasColumnName("ExtraProperties") .HasColumnType("nvarchar(max)"); b.Property<bool>("IsDeleted") .ValueGeneratedOnAdd() .HasColumnName("IsDeleted") .HasColumnType("bit") .HasDefaultValue(false); b.Property<DateTime?>("LastModificationTime") .HasColumnName("LastModificationTime") .HasColumnType("datetime2"); b.Property<Guid?>("LastModifierId") .HasColumnName("LastModifierId") .HasColumnType("uniqueidentifier"); b.Property<string>("Name") .IsRequired() .HasColumnType("nvarchar(200)") .HasMaxLength(200); b.Property<string>("Properties") .HasColumnType("nvarchar(max)"); b.Property<bool>("Required") .HasColumnType("bit"); b.Property<bool>("ShowInDiscoveryDocument") .HasColumnType("bit"); b.HasKey("Id"); b.ToTable("IdentityServerIdentityResources"); }); modelBuilder.Entity("Volo.Abp.PermissionManagement.PermissionGrant", b => { b.Property<Guid>("Id") .ValueGeneratedOnAdd() .HasColumnType("uniqueidentifier"); b.Property<string>("Name") .IsRequired() .HasColumnType("nvarchar(128)") .HasMaxLength(128); b.Property<string>("ProviderKey") .IsRequired() .HasColumnType("nvarchar(64)") .HasMaxLength(64); b.Property<string>("ProviderName") .IsRequired() .HasColumnType("nvarchar(64)") .HasMaxLength(64); b.Property<Guid?>("TenantId") .HasColumnName("TenantId") .HasColumnType("uniqueidentifier"); b.HasKey("Id"); b.HasIndex("Name", "ProviderName", "ProviderKey"); b.ToTable("AbpPermissionGrants"); }); modelBuilder.Entity("Volo.Abp.SettingManagement.Setting", b => { b.Property<Guid>("Id") .ValueGeneratedOnAdd() .HasColumnType("uniqueidentifier"); b.Property<string>("Name") .IsRequired() .HasColumnType("nvarchar(128)") .HasMaxLength(128); b.Property<string>("ProviderKey") .HasColumnType("nvarchar(64)") .HasMaxLength(64); b.Property<string>("ProviderName") .HasColumnType("nvarchar(64)") .HasMaxLength(64); b.Property<string>("Value") .IsRequired() .HasColumnType("nvarchar(2048)") .HasMaxLength(2048); b.HasKey("Id"); b.HasIndex("Name", "ProviderName", "ProviderKey"); b.ToTable("AbpSettings"); }); modelBuilder.Entity("Volo.Abp.TenantManagement.Tenant", b => { b.Property<Guid>("Id") .ValueGeneratedOnAdd() .HasColumnType("uniqueidentifier"); b.Property<string>("ConcurrencyStamp") .IsConcurrencyToken() .HasColumnName("ConcurrencyStamp") .HasColumnType("nvarchar(40)") .HasMaxLength(40); b.Property<DateTime>("CreationTime") .HasColumnName("CreationTime") .HasColumnType("datetime2"); b.Property<Guid?>("CreatorId") .HasColumnName("CreatorId") .HasColumnType("uniqueidentifier"); b.Property<Guid?>("DeleterId") .HasColumnName("DeleterId") .HasColumnType("uniqueidentifier"); b.Property<DateTime?>("DeletionTime") .HasColumnName("DeletionTime") .HasColumnType("datetime2"); b.Property<string>("ExtraProperties") .HasColumnName("ExtraProperties") .HasColumnType("nvarchar(max)"); b.Property<bool>("IsDeleted") .ValueGeneratedOnAdd() .HasColumnName("IsDeleted") .HasColumnType("bit") .HasDefaultValue(false); b.Property<DateTime?>("LastModificationTime") .HasColumnName("LastModificationTime") .HasColumnType("datetime2"); b.Property<Guid?>("LastModifierId") .HasColumnName("LastModifierId") .HasColumnType("uniqueidentifier"); b.Property<string>("Name") .IsRequired() .HasColumnType("nvarchar(64)") .HasMaxLength(64); b.HasKey("Id"); b.HasIndex("Name"); b.ToTable("AbpTenants"); }); modelBuilder.Entity("Volo.Abp.TenantManagement.TenantConnectionString", b => { b.Property<Guid>("TenantId") .HasColumnType("uniqueidentifier"); b.Property<string>("Name") .HasColumnType("nvarchar(64)") .HasMaxLength(64); b.Property<string>("Value") .IsRequired() .HasColumnType("nvarchar(1024)") .HasMaxLength(1024); b.HasKey("TenantId", "Name"); b.ToTable("AbpTenantConnectionStrings"); }); modelBuilder.Entity("EasyAbp.PaymentService.Payments.PaymentItem", b => { b.HasOne("EasyAbp.PaymentService.Payments.Payment", null) .WithMany("PaymentItems") .HasForeignKey("PaymentId"); }); modelBuilder.Entity("Volo.Abp.AuditLogging.AuditLogAction", b => { b.HasOne("Volo.Abp.AuditLogging.AuditLog", null) .WithMany("Actions") .HasForeignKey("AuditLogId") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); }); modelBuilder.Entity("Volo.Abp.AuditLogging.EntityChange", b => { b.HasOne("Volo.Abp.AuditLogging.AuditLog", null) .WithMany("EntityChanges") .HasForeignKey("AuditLogId") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); }); modelBuilder.Entity("Volo.Abp.AuditLogging.EntityPropertyChange", b => { b.HasOne("Volo.Abp.AuditLogging.EntityChange", null) .WithMany("PropertyChanges") .HasForeignKey("EntityChangeId") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); }); modelBuilder.Entity("Volo.Abp.Identity.IdentityRoleClaim", b => { b.HasOne("Volo.Abp.Identity.IdentityRole", null) .WithMany("Claims") .HasForeignKey("RoleId") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); }); modelBuilder.Entity("Volo.Abp.Identity.IdentityUserClaim", b => { b.HasOne("Volo.Abp.Identity.IdentityUser", null) .WithMany("Claims") .HasForeignKey("UserId") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); }); modelBuilder.Entity("Volo.Abp.Identity.IdentityUserLogin", b => { b.HasOne("Volo.Abp.Identity.IdentityUser", null) .WithMany("Logins") .HasForeignKey("UserId") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); }); modelBuilder.Entity("Volo.Abp.Identity.IdentityUserOrganizationUnit", b => { b.HasOne("Volo.Abp.Identity.OrganizationUnit", null) .WithMany() .HasForeignKey("OrganizationUnitId") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); b.HasOne("Volo.Abp.Identity.IdentityUser", null) .WithMany("OrganizationUnits") .HasForeignKey("UserId") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); }); modelBuilder.Entity("Volo.Abp.Identity.IdentityUserRole", b => { b.HasOne("Volo.Abp.Identity.IdentityRole", null) .WithMany() .HasForeignKey("RoleId") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); b.HasOne("Volo.Abp.Identity.IdentityUser", null) .WithMany("Roles") .HasForeignKey("UserId") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); }); modelBuilder.Entity("Volo.Abp.Identity.IdentityUserToken", b => { b.HasOne("Volo.Abp.Identity.IdentityUser", null) .WithMany("Tokens") .HasForeignKey("UserId") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); }); modelBuilder.Entity("Volo.Abp.Identity.OrganizationUnit", b => { b.HasOne("Volo.Abp.Identity.OrganizationUnit", null) .WithMany() .HasForeignKey("ParentId"); }); modelBuilder.Entity("Volo.Abp.Identity.OrganizationUnitRole", b => { b.HasOne("Volo.Abp.Identity.OrganizationUnit", null) .WithMany("Roles") .HasForeignKey("OrganizationUnitId") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); b.HasOne("Volo.Abp.Identity.IdentityRole", null) .WithMany() .HasForeignKey("RoleId") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); }); modelBuilder.Entity("Volo.Abp.IdentityServer.ApiResources.ApiResourceClaim", b => { b.HasOne("Volo.Abp.IdentityServer.ApiResources.ApiResource", null) .WithMany("UserClaims") .HasForeignKey("ApiResourceId") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); }); modelBuilder.Entity("Volo.Abp.IdentityServer.ApiResources.ApiScope", b => { b.HasOne("Volo.Abp.IdentityServer.ApiResources.ApiResource", null) .WithMany("Scopes") .HasForeignKey("ApiResourceId") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); }); modelBuilder.Entity("Volo.Abp.IdentityServer.ApiResources.ApiScopeClaim", b => { b.HasOne("Volo.Abp.IdentityServer.ApiResources.ApiScope", null) .WithMany("UserClaims") .HasForeignKey("ApiResourceId", "Name") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); }); modelBuilder.Entity("Volo.Abp.IdentityServer.ApiResources.ApiSecret", b => { b.HasOne("Volo.Abp.IdentityServer.ApiResources.ApiResource", null) .WithMany("Secrets") .HasForeignKey("ApiResourceId") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); }); modelBuilder.Entity("Volo.Abp.IdentityServer.Clients.ClientClaim", b => { b.HasOne("Volo.Abp.IdentityServer.Clients.Client", null) .WithMany("Claims") .HasForeignKey("ClientId") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); }); modelBuilder.Entity("Volo.Abp.IdentityServer.Clients.ClientCorsOrigin", b => { b.HasOne("Volo.Abp.IdentityServer.Clients.Client", null) .WithMany("AllowedCorsOrigins") .HasForeignKey("ClientId") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); }); modelBuilder.Entity("Volo.Abp.IdentityServer.Clients.ClientGrantType", b => { b.HasOne("Volo.Abp.IdentityServer.Clients.Client", null) .WithMany("AllowedGrantTypes") .HasForeignKey("ClientId") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); }); modelBuilder.Entity("Volo.Abp.IdentityServer.Clients.ClientIdPRestriction", b => { b.HasOne("Volo.Abp.IdentityServer.Clients.Client", null) .WithMany("IdentityProviderRestrictions") .HasForeignKey("ClientId") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); }); modelBuilder.Entity("Volo.Abp.IdentityServer.Clients.ClientPostLogoutRedirectUri", b => { b.HasOne("Volo.Abp.IdentityServer.Clients.Client", null) .WithMany("PostLogoutRedirectUris") .HasForeignKey("ClientId") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); }); modelBuilder.Entity("Volo.Abp.IdentityServer.Clients.ClientProperty", b => { b.HasOne("Volo.Abp.IdentityServer.Clients.Client", null) .WithMany("Properties") .HasForeignKey("ClientId") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); }); modelBuilder.Entity("Volo.Abp.IdentityServer.Clients.ClientRedirectUri", b => { b.HasOne("Volo.Abp.IdentityServer.Clients.Client", null) .WithMany("RedirectUris") .HasForeignKey("ClientId") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); }); modelBuilder.Entity("Volo.Abp.IdentityServer.Clients.ClientScope", b => { b.HasOne("Volo.Abp.IdentityServer.Clients.Client", null) .WithMany("AllowedScopes") .HasForeignKey("ClientId") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); }); modelBuilder.Entity("Volo.Abp.IdentityServer.Clients.ClientSecret", b => { b.HasOne("Volo.Abp.IdentityServer.Clients.Client", null) .WithMany("ClientSecrets") .HasForeignKey("ClientId") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); }); modelBuilder.Entity("Volo.Abp.IdentityServer.IdentityResources.IdentityClaim", b => { b.HasOne("Volo.Abp.IdentityServer.IdentityResources.IdentityResource", null) .WithMany("UserClaims") .HasForeignKey("IdentityResourceId") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); }); modelBuilder.Entity("Volo.Abp.TenantManagement.TenantConnectionString", b => { b.HasOne("Volo.Abp.TenantManagement.Tenant", null) .WithMany("ConnectionStrings") .HasForeignKey("TenantId") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); }); #pragma warning restore 612, 618 } } }
38.725
117
0.443692
[ "MIT" ]
LGinC/PaymentService
samples/PaymentServiceSample/aspnet-core/src/PaymentServiceSample.EntityFrameworkCore.DbMigrations/Migrations/20200803152922_AddedExtraPropertiesToPaymentItem.Designer.cs
94,491
C#
using AssessmentApp.WebClient.Models; using Kendo.Mvc.Extensions; using Kendo.Mvc.UI; using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Web; using System.Web.Mvc; namespace AssessmentApp.WebClient.Controllers { [Authorize] public class ClassesController : BaseController { // GET: Classes public ActionResult Add() { var model = new AddClassViewModel { TeacherClass = new Data.Models.Class { TeacherId = SessionItems.TeacherId.Value }, FirstTime = !DataRepository.GetTeachersClasses(SessionItems.TeacherId.Value).Any() }; ViewBag.Title = model.FirstTime ? "Let's Get Started... " : string.Empty + "Add New Class"; return View(model); } [HttpPost] public ActionResult Add(AddClassViewModel model) { Debug.Assert(SessionItems.TeacherId != null, "SessionItems.TeacherId != null"); if (DataRepository.CheckIfClassAlreadyExists(SessionItems.TeacherId.Value, model.TeacherClass.ClassName)) { ModelState.AddModelError("alreadyExists", $"{model.TeacherClass.ClassName} already exists"); } if (!ModelState.IsValid) { return View(model); } DataRepository.CreateClass(model.TeacherClass); return RedirectToAction("Index"); } [HttpPost] public ActionResult List([DataSourceRequest] DataSourceRequest request) { return Json(DataRepository.GetTeachersClasses(SessionItems.TeacherId.Value).OrderByDescending(x => x.Active).ThenBy(x => x.ClassName).ToDataSourceResult(request)); } public ActionResult Index() { //var model = new ClassIndexViewModel { TableItems = DataRepository.GetTeachersClasses(SessionItems.TeacherId.Value).OrderByDescending(x => x.Active).ThenBy(x => x.ClassName).ToList()}; return View(); } public ActionResult Edit(int id) { //*todo add security check var model = DataRepository.GetClass(id); if (!DataRepository.IsChild<Data.Models.Class>(SessionItems.TeacherId.Value, model)){ throw new AccessViolationException($"User does not have access to {id.ToString()}"); } return View(model); } [HttpPost] public ActionResult Edit(Data.Models.Class model) { if (!ModelState.IsValid) { return View(model); } DataRepository.UpdateClass(model); return RedirectToAction("Index"); } //[HttpPost] //public ActionResult AddNewClass(string className) { // return Json(new PostResultModel { Success = true }); //} } }
33.97619
217
0.620533
[ "MIT" ]
thilehoffer/Student-Assessment-Web
KindAssessment/KindAssessment/Controllers/ClassesController.cs
2,856
C#
using System.Threading.Tasks; using Hangfire; using Hangfire.Console; using Hangfire.Server; using Programemein.Services.Instagram; namespace Programemein.Services.RecurringJobs { public class UploadImageToInstagramCronJob { private readonly IInstagramService instagramService; public UploadImageToInstagramCronJob(IInstagramService instagramService) { this.instagramService = instagramService; } [AutomaticRetry(Attempts = 2)] public async Task StartWorking(PerformContext context) => context.WriteLine(await this.instagramService.UploadAsync()); } }
27.826087
80
0.73125
[ "MIT" ]
georgidelchev/programemein
src/Services/Programemein.Services.RecurringJobs/UploadImageToInstagramCronJob.cs
642
C#
using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Diagnostics; using System.Linq; using System.Reactive.Disposables; using System.Text; using System.Threading.Tasks; using System.Threading; using Avalonia.Controls; using Avalonia.Controls.Platform; using Avalonia.Controls.Primitives.PopupPositioning; using Avalonia.FreeDesktop; using Avalonia.Input; using Avalonia.Input.Raw; using Avalonia.Input.TextInput; using Avalonia.OpenGL; using Avalonia.OpenGL.Egl; using Avalonia.Platform; using Avalonia.Rendering; using Avalonia.Threading; using Avalonia.X11.Glx; using static Avalonia.X11.XLib; // ReSharper disable IdentifierTypo // ReSharper disable StringLiteralTypo namespace Avalonia.X11 { unsafe partial class X11Window : IWindowImpl, IPopupImpl, IXI2Client, ITopLevelImplWithNativeMenuExporter, ITopLevelImplWithNativeControlHost, ITopLevelImplWithTextInputMethod { private readonly AvaloniaX11Platform _platform; private readonly bool _popup; private readonly X11Info _x11; private XConfigureEvent? _configure; private PixelPoint? _configurePoint; private bool _triggeredExpose; private IInputRoot _inputRoot; private readonly MouseDevice _mouse; private readonly TouchDevice _touch; private readonly IKeyboardDevice _keyboard; private PixelPoint? _position; private PixelSize _realSize; private IntPtr _handle; private IntPtr _xic; private IntPtr _renderHandle; private IntPtr _xSyncCounter; private XSyncValue _xSyncValue; private XSyncState _xSyncState = 0; private bool _mapped; private bool _wasMappedAtLeastOnce = false; private double? _scalingOverride; private bool _disabled; private TransparencyHelper _transparencyHelper; private RawEventGrouper _rawEventGrouper; private bool _useRenderWindow = false; enum XSyncState { None, WaitConfigure, WaitPaint } public X11Window(AvaloniaX11Platform platform, IWindowImpl popupParent) { _platform = platform; _popup = popupParent != null; _x11 = platform.Info; _mouse = new MouseDevice(); _touch = new TouchDevice(); _keyboard = platform.KeyboardDevice; var glfeature = AvaloniaLocator.Current.GetService<IPlatformOpenGlInterface>(); XSetWindowAttributes attr = new XSetWindowAttributes(); var valueMask = default(SetWindowValuemask); attr.backing_store = 1; attr.bit_gravity = Gravity.NorthWestGravity; attr.win_gravity = Gravity.NorthWestGravity; valueMask |= SetWindowValuemask.BackPixel | SetWindowValuemask.BorderPixel | SetWindowValuemask.BackPixmap | SetWindowValuemask.BackingStore | SetWindowValuemask.BitGravity | SetWindowValuemask.WinGravity; if (_popup) { attr.override_redirect = 1; valueMask |= SetWindowValuemask.OverrideRedirect; } XVisualInfo? visualInfo = null; // OpenGL seems to be do weird things to it's current window which breaks resize sometimes _useRenderWindow = glfeature != null; var glx = glfeature as GlxPlatformOpenGlInterface; if (glx != null) visualInfo = *glx.Display.VisualInfo; else if (glfeature == null) visualInfo = _x11.TransparentVisualInfo; var egl = glfeature as EglPlatformOpenGlInterface; var visual = IntPtr.Zero; var depth = 24; if (visualInfo != null) { visual = visualInfo.Value.visual; depth = (int)visualInfo.Value.depth; attr.colormap = XCreateColormap(_x11.Display, _x11.RootWindow, visualInfo.Value.visual, 0); valueMask |= SetWindowValuemask.ColorMap; } int defaultWidth = 0, defaultHeight = 0; if (!_popup && Screen != null) { var monitor = Screen.AllScreens.OrderBy(x => x.PixelDensity) .FirstOrDefault(m => m.Bounds.Contains(Position)); if (monitor != null) { // Emulate Window 7+'s default window size behavior. defaultWidth = (int)(monitor.WorkingArea.Width * 0.75d); defaultHeight = (int)(monitor.WorkingArea.Height * 0.7d); } } // check if the calculated size is zero then compensate to hardcoded resolution defaultWidth = Math.Max(defaultWidth, 300); defaultHeight = Math.Max(defaultHeight, 200); _handle = XCreateWindow(_x11.Display, _x11.RootWindow, 10, 10, defaultWidth, defaultHeight, 0, depth, (int)CreateWindowArgs.InputOutput, visual, new UIntPtr((uint)valueMask), ref attr); if (_useRenderWindow) _renderHandle = XCreateWindow(_x11.Display, _handle, 0, 0, defaultWidth, defaultHeight, 0, depth, (int)CreateWindowArgs.InputOutput, visual, new UIntPtr((uint)(SetWindowValuemask.BorderPixel | SetWindowValuemask.BitGravity | SetWindowValuemask.WinGravity | SetWindowValuemask.BackingStore)), ref attr); else _renderHandle = _handle; Handle = new SurfacePlatformHandle(this); _realSize = new PixelSize(defaultWidth, defaultHeight); platform.Windows[_handle] = OnEvent; XEventMask ignoredMask = XEventMask.SubstructureRedirectMask | XEventMask.ResizeRedirectMask | XEventMask.PointerMotionHintMask; if (platform.XI2 != null) ignoredMask |= platform.XI2.AddWindow(_handle, this); var mask = new IntPtr(0xffffff ^ (int)ignoredMask); XSelectInput(_x11.Display, _handle, mask); var protocols = new[] { _x11.Atoms.WM_DELETE_WINDOW }; XSetWMProtocols(_x11.Display, _handle, protocols, protocols.Length); XChangeProperty(_x11.Display, _handle, _x11.Atoms._NET_WM_WINDOW_TYPE, _x11.Atoms.XA_ATOM, 32, PropertyMode.Replace, new[] {_x11.Atoms._NET_WM_WINDOW_TYPE_NORMAL}, 1); if (platform.Options.WmClass != null) SetWmClass(platform.Options.WmClass); var surfaces = new List<object> { new X11FramebufferSurface(_x11.DeferredDisplay, _renderHandle, depth, () => RenderScaling) }; if (egl != null) surfaces.Insert(0, new EglGlPlatformSurface(egl, new SurfaceInfo(this, _x11.DeferredDisplay, _handle, _renderHandle))); if (glx != null) surfaces.Insert(0, new GlxGlPlatformSurface(glx.Display, glx.DeferredContext, new SurfaceInfo(this, _x11.Display, _handle, _renderHandle))); surfaces.Add(Handle); Surfaces = surfaces.ToArray(); UpdateMotifHints(); UpdateSizeHints(null); _rawEventGrouper = new RawEventGrouper(e => Input?.Invoke(e)); _transparencyHelper = new TransparencyHelper(_x11, _handle, platform.Globals); _transparencyHelper.SetTransparencyRequest(WindowTransparencyLevel.None); CreateIC(); XFlush(_x11.Display); if(_popup) PopupPositioner = new ManagedPopupPositioner(new ManagedPopupPositionerPopupImplHelper(popupParent, MoveResize)); if (platform.Options.UseDBusMenu) NativeMenuExporter = DBusMenuExporter.TryCreateTopLevelNativeMenu(_handle); NativeControlHost = new X11NativeControlHost(_platform, this); InitializeIme(); XChangeProperty(_x11.Display, _handle, _x11.Atoms.WM_PROTOCOLS, _x11.Atoms.XA_ATOM, 32, PropertyMode.Replace, new[] { _x11.Atoms.WM_DELETE_WINDOW, _x11.Atoms._NET_WM_SYNC_REQUEST }, 2); if (_x11.HasXSync) { _xSyncCounter = XSyncCreateCounter(_x11.Display, _xSyncValue); XChangeProperty(_x11.Display, _handle, _x11.Atoms._NET_WM_SYNC_REQUEST_COUNTER, _x11.Atoms.XA_CARDINAL, 32, PropertyMode.Replace, ref _xSyncCounter, 1); } } class SurfaceInfo : EglGlPlatformSurface.IEglWindowGlPlatformSurfaceInfo { private readonly X11Window _window; private readonly IntPtr _display; private readonly IntPtr _parent; public SurfaceInfo(X11Window window, IntPtr display, IntPtr parent, IntPtr xid) { _window = window; _display = display; _parent = parent; Handle = xid; } public IntPtr Handle { get; } public PixelSize Size { get { XLockDisplay(_display); XGetGeometry(_display, _parent, out var geo); XResizeWindow(_display, Handle, geo.width, geo.height); XUnlockDisplay(_display); return new PixelSize(geo.width, geo.height); } } public double Scaling => _window.RenderScaling; } void UpdateMotifHints() { var functions = MotifFunctions.Move | MotifFunctions.Close | MotifFunctions.Resize | MotifFunctions.Minimize | MotifFunctions.Maximize; var decorations = MotifDecorations.Menu | MotifDecorations.Title | MotifDecorations.Border | MotifDecorations.Maximize | MotifDecorations.Minimize | MotifDecorations.ResizeH; if (_popup || _systemDecorations == SystemDecorations.None) decorations = 0; if (!_canResize) { functions &= ~(MotifFunctions.Resize | MotifFunctions.Maximize); decorations &= ~(MotifDecorations.Maximize | MotifDecorations.ResizeH); } var hints = new MotifWmHints { flags = new IntPtr((int)(MotifFlags.Decorations | MotifFlags.Functions)), decorations = new IntPtr((int)decorations), functions = new IntPtr((int)functions) }; XChangeProperty(_x11.Display, _handle, _x11.Atoms._MOTIF_WM_HINTS, _x11.Atoms._MOTIF_WM_HINTS, 32, PropertyMode.Replace, ref hints, 5); } void UpdateSizeHints(PixelSize? preResize) { var min = _minMaxSize.minSize; var max = _minMaxSize.maxSize; if (!_canResize) max = min = _realSize; if (preResize.HasValue) { var desired = preResize.Value; max = new PixelSize(Math.Max(desired.Width, max.Width), Math.Max(desired.Height, max.Height)); min = new PixelSize(Math.Min(desired.Width, min.Width), Math.Min(desired.Height, min.Height)); } var hints = new XSizeHints { min_width = min.Width, min_height = min.Height }; hints.height_inc = hints.width_inc = 1; var flags = XSizeHintsFlags.PMinSize | XSizeHintsFlags.PResizeInc; // People might be passing double.MaxValue if (max.Width < 100000 && max.Height < 100000) { hints.max_width = max.Width; hints.max_height = max.Height; flags |= XSizeHintsFlags.PMaxSize; } hints.flags = (IntPtr)flags; XSetWMNormalHints(_x11.Display, _handle, ref hints); } public Size ClientSize => new Size(_realSize.Width / RenderScaling, _realSize.Height / RenderScaling); public Size? FrameSize { get { XGetWindowProperty(_x11.Display, _handle, _x11.Atoms._NET_FRAME_EXTENTS, IntPtr.Zero, new IntPtr(4), false, (IntPtr)Atom.AnyPropertyType, out var _, out var _, out var nitems, out var _, out var prop); if (nitems.ToInt64() != 4) { // Window hasn't been mapped by the WM yet, so can't get the extents. return null; } var data = (IntPtr*)prop.ToPointer(); var extents = new Thickness(data[0].ToInt32(), data[2].ToInt32(), data[1].ToInt32(), data[3].ToInt32()); XFree(prop); return new Size( (_realSize.Width + extents.Left + extents.Right) / RenderScaling, (_realSize.Height + extents.Top + extents.Bottom) / RenderScaling); } } public double RenderScaling { get => Interlocked.CompareExchange(ref _scaling, 0.0, 0.0); private set => Interlocked.Exchange(ref _scaling, value); } public double DesktopScaling => RenderScaling; public IEnumerable<object> Surfaces { get; } public Action<RawInputEventArgs> Input { get; set; } public Action<Rect> Paint { get; set; } public Action<Size, PlatformResizeReason> Resized { get; set; } //TODO public Action<double> ScalingChanged { get; set; } public Action Deactivated { get; set; } public Action Activated { get; set; } public Func<bool> Closing { get; set; } public Action<WindowState> WindowStateChanged { get; set; } public Action<WindowTransparencyLevel> TransparencyLevelChanged { get => _transparencyHelper?.TransparencyLevelChanged; set { if (_transparencyHelper != null) _transparencyHelper.TransparencyLevelChanged = value; } } public Action<bool> ExtendClientAreaToDecorationsChanged { get; set; } public Thickness ExtendedMargins { get; } = new Thickness(); public Thickness OffScreenMargin { get; } = new Thickness(); public bool IsClientAreaExtendedToDecorations { get; } public Action Closed { get; set; } public Action<PixelPoint> PositionChanged { get; set; } public Action LostFocus { get; set; } public IRenderer CreateRenderer(IRenderRoot root) { var loop = AvaloniaLocator.Current.GetService<IRenderLoop>(); var customRendererFactory = AvaloniaLocator.Current.GetService<IRendererFactory>(); if (customRendererFactory != null) return customRendererFactory.Create(root, loop); return _platform.Options.UseDeferredRendering ? new DeferredRenderer(root, loop) { RenderOnlyOnRenderThread = true } : (IRenderer)new X11ImmediateRendererProxy(root, loop); } void OnEvent(ref XEvent ev) { if (ev.type == XEventName.MapNotify) { _mapped = true; if (_useRenderWindow) XMapWindow(_x11.Display, _renderHandle); } else if (ev.type == XEventName.UnmapNotify) _mapped = false; else if (ev.type == XEventName.Expose || (ev.type == XEventName.VisibilityNotify && ev.VisibilityEvent.state < 2)) { EnqueuePaint(); } else if (ev.type == XEventName.FocusIn) { if (ActivateTransientChildIfNeeded()) return; Activated?.Invoke(); _imeControl?.SetWindowActive(true); } else if (ev.type == XEventName.FocusOut) { _imeControl?.SetWindowActive(false); Deactivated?.Invoke(); } else if (ev.type == XEventName.MotionNotify) MouseEvent(RawPointerEventType.Move, ref ev, ev.MotionEvent.state); else if (ev.type == XEventName.LeaveNotify) MouseEvent(RawPointerEventType.LeaveWindow, ref ev, ev.CrossingEvent.state); else if (ev.type == XEventName.PropertyNotify) { OnPropertyChange(ev.PropertyEvent.atom, ev.PropertyEvent.state == 0); } else if (ev.type == XEventName.ButtonPress) { if (ActivateTransientChildIfNeeded()) return; if (ev.ButtonEvent.button < 4 || ev.ButtonEvent.button == 8 || ev.ButtonEvent.button == 9) MouseEvent( ev.ButtonEvent.button switch { 1 => RawPointerEventType.LeftButtonDown, 2 => RawPointerEventType.MiddleButtonDown, 3 => RawPointerEventType.RightButtonDown, 8 => RawPointerEventType.XButton1Down, 9 => RawPointerEventType.XButton2Down }, ref ev, ev.ButtonEvent.state); else { var delta = ev.ButtonEvent.button == 4 ? new Vector(0, 1) : ev.ButtonEvent.button == 5 ? new Vector(0, -1) : ev.ButtonEvent.button == 6 ? new Vector(1, 0) : new Vector(-1, 0); ScheduleInput(new RawMouseWheelEventArgs(_mouse, (ulong)ev.ButtonEvent.time.ToInt64(), _inputRoot, new Point(ev.ButtonEvent.x, ev.ButtonEvent.y), delta, TranslateModifiers(ev.ButtonEvent.state)), ref ev); } } else if (ev.type == XEventName.ButtonRelease) { if (ev.ButtonEvent.button < 4 || ev.ButtonEvent.button == 8 || ev.ButtonEvent.button == 9) MouseEvent( ev.ButtonEvent.button switch { 1 => RawPointerEventType.LeftButtonUp, 2 => RawPointerEventType.MiddleButtonUp, 3 => RawPointerEventType.RightButtonUp, 8 => RawPointerEventType.XButton1Up, 9 => RawPointerEventType.XButton2Up }, ref ev, ev.ButtonEvent.state); } else if (ev.type == XEventName.ConfigureNotify) { if (ev.ConfigureEvent.window != _handle) return; var needEnqueue = (_configure == null); _configure = ev.ConfigureEvent; if (ev.ConfigureEvent.override_redirect != 0 || ev.ConfigureEvent.send_event != 0) _configurePoint = new PixelPoint(ev.ConfigureEvent.x, ev.ConfigureEvent.y); else { XTranslateCoordinates(_x11.Display, _handle, _x11.RootWindow, 0, 0, out var tx, out var ty, out _); _configurePoint = new PixelPoint(tx, ty); } if (needEnqueue) Dispatcher.UIThread.Post(() => { if (_configure == null) return; var cev = _configure.Value; var npos = _configurePoint.Value; _configure = null; _configurePoint = null; var nsize = new PixelSize(cev.width, cev.height); var changedSize = _realSize != nsize; var changedPos = _position == null || npos != _position; _realSize = nsize; _position = npos; bool updatedSizeViaScaling = false; if (changedPos) { PositionChanged?.Invoke(npos); updatedSizeViaScaling = UpdateScaling(); } UpdateImePosition(); if (changedSize && !updatedSizeViaScaling && !_popup) Resized?.Invoke(ClientSize, PlatformResizeReason.Unspecified); Dispatcher.UIThread.RunJobs(DispatcherPriority.Layout); }, DispatcherPriority.Layout); if (_useRenderWindow) XConfigureResizeWindow(_x11.Display, _renderHandle, ev.ConfigureEvent.width, ev.ConfigureEvent.height); if (_xSyncState == XSyncState.WaitConfigure) { _xSyncState = XSyncState.WaitPaint; EnqueuePaint(); } } else if (ev.type == XEventName.DestroyNotify && ev.DestroyWindowEvent.window == _handle) { Cleanup(); } else if (ev.type == XEventName.ClientMessage) { if (ev.ClientMessageEvent.message_type == _x11.Atoms.WM_PROTOCOLS) { if (ev.ClientMessageEvent.ptr1 == _x11.Atoms.WM_DELETE_WINDOW) { if (Closing?.Invoke() != true) Dispose(); } else if (ev.ClientMessageEvent.ptr1 == _x11.Atoms._NET_WM_SYNC_REQUEST) { _xSyncValue.Lo = new UIntPtr(ev.ClientMessageEvent.ptr3.ToPointer()).ToUInt32(); _xSyncValue.Hi = ev.ClientMessageEvent.ptr4.ToInt32(); _xSyncState = XSyncState.WaitConfigure; } } } else if (ev.type == XEventName.KeyPress || ev.type == XEventName.KeyRelease) { if (ActivateTransientChildIfNeeded()) return; HandleKeyEvent(ref ev); } } private bool UpdateScaling(bool skipResize = false) { double newScaling; if (_scalingOverride.HasValue) newScaling = _scalingOverride.Value; else { var monitor = _platform.X11Screens.Screens.OrderBy(x => x.PixelDensity) .FirstOrDefault(m => m.Bounds.Contains(Position)); newScaling = monitor?.PixelDensity ?? RenderScaling; } if (RenderScaling != newScaling) { var oldScaledSize = ClientSize; RenderScaling = newScaling; ScalingChanged?.Invoke(RenderScaling); UpdateImePosition(); SetMinMaxSize(_scaledMinMaxSize.minSize, _scaledMinMaxSize.maxSize); if(!skipResize) Resize(oldScaledSize, true, PlatformResizeReason.DpiChange); return true; } return false; } private WindowState _lastWindowState; public WindowState WindowState { get => _lastWindowState; set { if(_lastWindowState == value) return; _lastWindowState = value; if (value == WindowState.Minimized) { XIconifyWindow(_x11.Display, _handle, _x11.DefaultScreen); } else if (value == WindowState.Maximized) { ChangeWMAtoms(false, _x11.Atoms._NET_WM_STATE_HIDDEN); ChangeWMAtoms(false, _x11.Atoms._NET_WM_STATE_FULLSCREEN); ChangeWMAtoms(true, _x11.Atoms._NET_WM_STATE_MAXIMIZED_VERT, _x11.Atoms._NET_WM_STATE_MAXIMIZED_HORZ); } else if (value == WindowState.FullScreen) { ChangeWMAtoms(false, _x11.Atoms._NET_WM_STATE_HIDDEN); ChangeWMAtoms(true, _x11.Atoms._NET_WM_STATE_FULLSCREEN); ChangeWMAtoms(false, _x11.Atoms._NET_WM_STATE_MAXIMIZED_VERT, _x11.Atoms._NET_WM_STATE_MAXIMIZED_HORZ); } else { ChangeWMAtoms(false, _x11.Atoms._NET_WM_STATE_HIDDEN); ChangeWMAtoms(false, _x11.Atoms._NET_WM_STATE_FULLSCREEN); ChangeWMAtoms(false, _x11.Atoms._NET_WM_STATE_MAXIMIZED_VERT, _x11.Atoms._NET_WM_STATE_MAXIMIZED_HORZ); } } } private void OnPropertyChange(IntPtr atom, bool hasValue) { if (atom == _x11.Atoms._NET_FRAME_EXTENTS) { // Occurs once the window has been mapped, which is the earliest the extents // can be retrieved, so invoke event to force update of TopLevel.FrameSize. Resized.Invoke(ClientSize, PlatformResizeReason.Unspecified); } if (atom == _x11.Atoms._NET_WM_STATE) { WindowState state = WindowState.Normal; if(hasValue) { XGetWindowProperty(_x11.Display, _handle, _x11.Atoms._NET_WM_STATE, IntPtr.Zero, new IntPtr(256), false, (IntPtr)Atom.XA_ATOM, out _, out _, out var nitems, out _, out var prop); int maximized = 0; var pitems = (IntPtr*)prop.ToPointer(); for (var c = 0; c < nitems.ToInt32(); c++) { if (pitems[c] == _x11.Atoms._NET_WM_STATE_HIDDEN) { state = WindowState.Minimized; break; } if(pitems[c] == _x11.Atoms._NET_WM_STATE_FULLSCREEN) { state = WindowState.FullScreen; break; } if (pitems[c] == _x11.Atoms._NET_WM_STATE_MAXIMIZED_HORZ || pitems[c] == _x11.Atoms._NET_WM_STATE_MAXIMIZED_VERT) { maximized++; if (maximized == 2) { state = WindowState.Maximized; break; } } } XFree(prop); } if (_lastWindowState != state) { _lastWindowState = state; WindowStateChanged?.Invoke(state); } } } RawInputModifiers TranslateModifiers(XModifierMask state) { var rv = default(RawInputModifiers); if (state.HasAllFlags(XModifierMask.Button1Mask)) rv |= RawInputModifiers.LeftMouseButton; if (state.HasAllFlags(XModifierMask.Button2Mask)) rv |= RawInputModifiers.RightMouseButton; if (state.HasAllFlags(XModifierMask.Button3Mask)) rv |= RawInputModifiers.MiddleMouseButton; if (state.HasAllFlags(XModifierMask.Button4Mask)) rv |= RawInputModifiers.XButton1MouseButton; if (state.HasAllFlags(XModifierMask.Button5Mask)) rv |= RawInputModifiers.XButton2MouseButton; if (state.HasAllFlags(XModifierMask.ShiftMask)) rv |= RawInputModifiers.Shift; if (state.HasAllFlags(XModifierMask.ControlMask)) rv |= RawInputModifiers.Control; if (state.HasAllFlags(XModifierMask.Mod1Mask)) rv |= RawInputModifiers.Alt; if (state.HasAllFlags(XModifierMask.Mod4Mask)) rv |= RawInputModifiers.Meta; return rv; } private SystemDecorations _systemDecorations = SystemDecorations.Full; private bool _canResize = true; private const int MaxWindowDimension = 100000; private (Size minSize, Size maxSize) _scaledMinMaxSize = (new Size(1, 1), new Size(double.PositiveInfinity, double.PositiveInfinity)); private (PixelSize minSize, PixelSize maxSize) _minMaxSize = (new PixelSize(1, 1), new PixelSize(MaxWindowDimension, MaxWindowDimension)); private double _scaling = 1; void ScheduleInput(RawInputEventArgs args, ref XEvent xev) { _x11.LastActivityTimestamp = xev.ButtonEvent.time; ScheduleInput(args); } public void ScheduleXI2Input(RawInputEventArgs args) { if (args is RawPointerEventArgs pargs) { if ((pargs.Type == RawPointerEventType.TouchBegin || pargs.Type == RawPointerEventType.TouchUpdate || pargs.Type == RawPointerEventType.LeftButtonDown || pargs.Type == RawPointerEventType.RightButtonDown || pargs.Type == RawPointerEventType.MiddleButtonDown || pargs.Type == RawPointerEventType.NonClientLeftButtonDown) && ActivateTransientChildIfNeeded()) return; if (pargs.Type == RawPointerEventType.TouchEnd && ActivateTransientChildIfNeeded()) pargs.Type = RawPointerEventType.TouchCancel; } ScheduleInput(args); } private void ScheduleInput(RawInputEventArgs args) { if (args is RawPointerEventArgs mouse) mouse.Position = mouse.Position / RenderScaling; if (args is RawDragEvent drag) drag.Location = drag.Location / RenderScaling; _rawEventGrouper.HandleEvent(args); } void MouseEvent(RawPointerEventType type, ref XEvent ev, XModifierMask mods) { var mev = new RawPointerEventArgs( _mouse, (ulong)ev.ButtonEvent.time.ToInt64(), _inputRoot, type, new Point(ev.ButtonEvent.x, ev.ButtonEvent.y), TranslateModifiers(mods)); ScheduleInput(mev, ref ev); } void EnqueuePaint() { if (!_triggeredExpose) { _triggeredExpose = true; Dispatcher.UIThread.Post(() => { _triggeredExpose = false; DoPaint(); }, DispatcherPriority.Render); } } void DoPaint() { Paint?.Invoke(new Rect()); if (_xSyncCounter != IntPtr.Zero && _xSyncState == XSyncState.WaitPaint) { _xSyncState = XSyncState.None; XSyncSetCounter(_x11.Display, _xSyncCounter, _xSyncValue); } } public void Invalidate(Rect rect) { } public IInputRoot InputRoot => _inputRoot; public void SetInputRoot(IInputRoot inputRoot) { _inputRoot = inputRoot; } public void Dispose() { Cleanup(); } void Cleanup() { if (_rawEventGrouper != null) { _rawEventGrouper.Dispose(); _rawEventGrouper = null; } if (_transparencyHelper != null) { _transparencyHelper.Dispose(); _transparencyHelper = null; } if (_imeControl != null) { _imeControl.Dispose(); _imeControl = null; _ime = null; } if (_xic != IntPtr.Zero) { XDestroyIC(_xic); _xic = IntPtr.Zero; } if (_xSyncCounter != IntPtr.Zero) { XSyncDestroyCounter(_x11.Display, _xSyncCounter); _xSyncCounter = IntPtr.Zero; } if (_handle != IntPtr.Zero) { _platform.Windows.Remove(_handle); _platform.XI2?.OnWindowDestroyed(_handle); var handle = _handle; _handle = IntPtr.Zero; Closed?.Invoke(); _mouse.Dispose(); _touch.Dispose(); XDestroyWindow(_x11.Display, handle); } if (_useRenderWindow && _renderHandle != IntPtr.Zero) { _renderHandle = IntPtr.Zero; } } bool ActivateTransientChildIfNeeded() { if (_disabled) { GotInputWhenDisabled?.Invoke(); return true; } return false; } public void SetParent(IWindowImpl parent) { if (parent == null || parent.Handle == null || parent.Handle.Handle == IntPtr.Zero) XDeleteProperty(_x11.Display, _handle, _x11.Atoms.XA_WM_TRANSIENT_FOR); else XSetTransientForHint(_x11.Display, _handle, parent.Handle.Handle); } public void Show(bool activate, bool isDialog) { _wasMappedAtLeastOnce = true; XMapWindow(_x11.Display, _handle); XFlush(_x11.Display); } public void Hide() => XUnmapWindow(_x11.Display, _handle); public Point PointToClient(PixelPoint point) => new Point((point.X - Position.X) / RenderScaling, (point.Y - Position.Y) / RenderScaling); public PixelPoint PointToScreen(Point point) => new PixelPoint( (int)(point.X * RenderScaling + Position.X), (int)(point.Y * RenderScaling + Position.Y)); public void SetSystemDecorations(SystemDecorations enabled) { _systemDecorations = enabled == SystemDecorations.Full ? SystemDecorations.Full : SystemDecorations.None; UpdateMotifHints(); UpdateSizeHints(null); } public void Resize(Size clientSize, PlatformResizeReason reason) => Resize(clientSize, false, reason); public void Move(PixelPoint point) => Position = point; private void MoveResize(PixelPoint position, Size size, double scaling) { Move(position); _scalingOverride = scaling; UpdateScaling(true); Resize(size, true, PlatformResizeReason.Layout); } PixelSize ToPixelSize(Size size) => new PixelSize((int)(size.Width * RenderScaling), (int)(size.Height * RenderScaling)); void Resize(Size clientSize, bool force, PlatformResizeReason reason) { if (!force && clientSize == ClientSize) return; var needImmediatePopupResize = clientSize != ClientSize; var pixelSize = ToPixelSize(clientSize); UpdateSizeHints(pixelSize); XConfigureResizeWindow(_x11.Display, _handle, pixelSize); if (_useRenderWindow) XConfigureResizeWindow(_x11.Display, _renderHandle, pixelSize); XFlush(_x11.Display); if (force || !_wasMappedAtLeastOnce || (_popup && needImmediatePopupResize)) { _realSize = pixelSize; Resized?.Invoke(ClientSize, reason); } } public void CanResize(bool value) { _canResize = value; UpdateMotifHints(); UpdateSizeHints(null); } public void SetCursor(ICursorImpl cursor) { if (cursor == null) XDefineCursor(_x11.Display, _handle, _x11.DefaultCursor); else if (cursor is CursorImpl impl) { XDefineCursor(_x11.Display, _handle, impl.Handle); } } public IPlatformHandle Handle { get; } public PixelPoint Position { get => _position ?? default; set { var changes = new XWindowChanges { x = (int)value.X, y = (int)value.Y }; XConfigureWindow(_x11.Display, _handle, ChangeWindowFlags.CWX | ChangeWindowFlags.CWY, ref changes); XFlush(_x11.Display); if (!_wasMappedAtLeastOnce) { _position = value; PositionChanged?.Invoke(value); } } } public IMouseDevice MouseDevice => _mouse; public TouchDevice TouchDevice => _touch; public IPopupImpl CreatePopup() => _platform.Options.OverlayPopups ? null : new X11Window(_platform, this); public void Activate() { if (_x11.Atoms._NET_ACTIVE_WINDOW != IntPtr.Zero) { SendNetWMMessage(_x11.Atoms._NET_ACTIVE_WINDOW, (IntPtr)1, _x11.LastActivityTimestamp, IntPtr.Zero); } else { XRaiseWindow(_x11.Display, _handle); XSetInputFocus(_x11.Display, _handle, 0, IntPtr.Zero); } } public IScreenImpl Screen => _platform.Screens; public Size MaxAutoSizeHint => _platform.X11Screens.Screens.Select(s => s.Bounds.Size.ToSize(s.PixelDensity)) .OrderByDescending(x => x.Width + x.Height).FirstOrDefault(); void SendNetWMMessage(IntPtr message_type, IntPtr l0, IntPtr? l1 = null, IntPtr? l2 = null, IntPtr? l3 = null, IntPtr? l4 = null) { var xev = new XEvent { ClientMessageEvent = { type = XEventName.ClientMessage, send_event = 1, window = _handle, message_type = message_type, format = 32, ptr1 = l0, ptr2 = l1 ?? IntPtr.Zero, ptr3 = l2 ?? IntPtr.Zero, ptr4 = l3 ?? IntPtr.Zero } }; xev.ClientMessageEvent.ptr4 = l4 ?? IntPtr.Zero; XSendEvent(_x11.Display, _x11.RootWindow, false, new IntPtr((int)(EventMask.SubstructureRedirectMask | EventMask.SubstructureNotifyMask)), ref xev); } void BeginMoveResize(NetWmMoveResize side, PointerPressedEventArgs e) { var pos = GetCursorPos(_x11); XUngrabPointer(_x11.Display, new IntPtr(0)); SendNetWMMessage (_x11.Atoms._NET_WM_MOVERESIZE, (IntPtr) pos.x, (IntPtr) pos.y, (IntPtr) side, (IntPtr) 1, (IntPtr)1); // left button e.Pointer.Capture(null); } public void BeginMoveDrag(PointerPressedEventArgs e) { BeginMoveResize(NetWmMoveResize._NET_WM_MOVERESIZE_MOVE, e); } public void BeginResizeDrag(WindowEdge edge, PointerPressedEventArgs e) { var side = NetWmMoveResize._NET_WM_MOVERESIZE_CANCEL; if (edge == WindowEdge.East) side = NetWmMoveResize._NET_WM_MOVERESIZE_SIZE_RIGHT; if (edge == WindowEdge.North) side = NetWmMoveResize._NET_WM_MOVERESIZE_SIZE_TOP; if (edge == WindowEdge.South) side = NetWmMoveResize._NET_WM_MOVERESIZE_SIZE_BOTTOM; if (edge == WindowEdge.West) side = NetWmMoveResize._NET_WM_MOVERESIZE_SIZE_LEFT; if (edge == WindowEdge.NorthEast) side = NetWmMoveResize._NET_WM_MOVERESIZE_SIZE_TOPRIGHT; if (edge == WindowEdge.NorthWest) side = NetWmMoveResize._NET_WM_MOVERESIZE_SIZE_TOPLEFT; if (edge == WindowEdge.SouthEast) side = NetWmMoveResize._NET_WM_MOVERESIZE_SIZE_BOTTOMRIGHT; if (edge == WindowEdge.SouthWest) side = NetWmMoveResize._NET_WM_MOVERESIZE_SIZE_BOTTOMLEFT; BeginMoveResize(side, e); } public void SetTitle(string title) { if (string.IsNullOrEmpty(title)) { XDeleteProperty(_x11.Display, _handle, _x11.Atoms._NET_WM_NAME); XDeleteProperty(_x11.Display, _handle, _x11.Atoms.XA_WM_NAME); } else { var data = Encoding.UTF8.GetBytes(title); fixed (void* pdata = data) { XChangeProperty(_x11.Display, _handle, _x11.Atoms._NET_WM_NAME, _x11.Atoms.UTF8_STRING, 8, PropertyMode.Replace, pdata, data.Length); XStoreName(_x11.Display, _handle, title); } } } public void SetWmClass(string wmClass) { var data = Encoding.ASCII.GetBytes(wmClass); fixed (void* pdata = data) { XChangeProperty(_x11.Display, _handle, _x11.Atoms.XA_WM_CLASS, _x11.Atoms.XA_STRING, 8, PropertyMode.Replace, pdata, data.Length); } } public void SetMinMaxSize(Size minSize, Size maxSize) { _scaledMinMaxSize = (minSize, maxSize); var min = new PixelSize( (int)(minSize.Width < 1 ? 1 : minSize.Width * RenderScaling), (int)(minSize.Height < 1 ? 1 : minSize.Height * RenderScaling)); const int maxDim = MaxWindowDimension; var max = new PixelSize( (int)(maxSize.Width > maxDim ? maxDim : Math.Max(min.Width, maxSize.Width * RenderScaling)), (int)(maxSize.Height > maxDim ? maxDim : Math.Max(min.Height, maxSize.Height * RenderScaling))); _minMaxSize = (min, max); UpdateSizeHints(null); } public void SetTopmost(bool value) { ChangeWMAtoms(value, _x11.Atoms._NET_WM_STATE_ABOVE); } public void SetEnabled(bool enable) { _disabled = !enable; } public void SetExtendClientAreaToDecorationsHint(bool extendIntoClientAreaHint) { } public void SetExtendClientAreaChromeHints(ExtendClientAreaChromeHints hints) { } public void SetExtendClientAreaTitleBarHeightHint(double titleBarHeight) { } public Action GotInputWhenDisabled { get; set; } public void SetIcon(IWindowIconImpl icon) { if (icon != null) { var data = ((X11IconData)icon).Data; fixed (void* pdata = data) XChangeProperty(_x11.Display, _handle, _x11.Atoms._NET_WM_ICON, new IntPtr((int)Atom.XA_CARDINAL), 32, PropertyMode.Replace, pdata, data.Length); } else { XDeleteProperty(_x11.Display, _handle, _x11.Atoms._NET_WM_ICON); } } public void ShowTaskbarIcon(bool value) { ChangeWMAtoms(!value, _x11.Atoms._NET_WM_STATE_SKIP_TASKBAR); } void ChangeWMAtoms(bool enable, params IntPtr[] atoms) { if (atoms.Length != 1 && atoms.Length != 2) throw new ArgumentException(); if (!_mapped) { XGetWindowProperty(_x11.Display, _handle, _x11.Atoms._NET_WM_STATE, IntPtr.Zero, new IntPtr(256), false, (IntPtr)Atom.XA_ATOM, out _, out _, out var nitems, out _, out var prop); var ptr = (IntPtr*)prop.ToPointer(); var newAtoms = new HashSet<IntPtr>(); for (var c = 0; c < nitems.ToInt64(); c++) newAtoms.Add(*ptr); XFree(prop); foreach(var atom in atoms) if (enable) newAtoms.Add(atom); else newAtoms.Remove(atom); XChangeProperty(_x11.Display, _handle, _x11.Atoms._NET_WM_STATE, (IntPtr)Atom.XA_ATOM, 32, PropertyMode.Replace, newAtoms.ToArray(), newAtoms.Count); } SendNetWMMessage(_x11.Atoms._NET_WM_STATE, (IntPtr)(enable ? 1 : 0), atoms[0], atoms.Length > 1 ? atoms[1] : IntPtr.Zero, atoms.Length > 2 ? atoms[2] : IntPtr.Zero, atoms.Length > 3 ? atoms[3] : IntPtr.Zero ); } public IPopupPositioner PopupPositioner { get; } public ITopLevelNativeMenuExporter NativeMenuExporter { get; } public INativeControlHostImpl NativeControlHost { get; } public ITextInputMethodImpl TextInputMethod => _ime; public void SetTransparencyLevelHint(WindowTransparencyLevel transparencyLevel) => _transparencyHelper?.SetTransparencyRequest(transparencyLevel); public void SetWindowManagerAddShadowHint(bool enabled) { } public WindowTransparencyLevel TransparencyLevel => _transparencyHelper?.CurrentLevel ?? WindowTransparencyLevel.None; public AcrylicPlatformCompensationLevels AcrylicCompensationLevels { get; } = new AcrylicPlatformCompensationLevels(1, 0.8, 0.8); public bool NeedsManagedDecorations => false; public class SurfacePlatformHandle : IPlatformNativeSurfaceHandle { private readonly X11Window _owner; public PixelSize Size => _owner.ToPixelSize(_owner.ClientSize); public double Scaling => _owner.RenderScaling; public SurfacePlatformHandle(X11Window owner) { _owner = owner; } public IntPtr Handle => _owner._renderHandle; public string HandleDescriptor => "XID"; } } }
39.158979
146
0.535287
[ "MIT" ]
Kibnet/Avalonia
src/Avalonia.X11/X11Window.cs
47,539
C#
// Copyright (c) Source Tree Solutions, LLC. All rights reserved. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. // Author: Joe Audette // Created: 2014-12-10 // Last Modified: 2016-05-16 using Microsoft.AspNetCore.Html; using Microsoft.AspNetCore.Mvc.Rendering; using System; using System.Collections.Generic; using System.Linq; namespace cloudscribe.Web.Pagination { /// <summary> /// note that this html helper hasbeen superceded by a newer AlphaPagerTagHelper /// </summary> public static class AlphabeticPagination { public static IHtmlContent AlphabeticPager( this IHtmlHelper html, string selectedLetter, string alphabet, IEnumerable<string> firstLetters, string allLabel, string allValue, bool includeNumbers, Func<string, string> pageLink) { var numbers = Enumerable.Range(0, 10).Select(i => i.ToString()); List<string> alphabetList; if (string.IsNullOrEmpty(alphabet)) { alphabetList = "ABCDEFGHIJKLMNOPQRSTUVWXYZ".ToCharArray().ToStringList(); } else { alphabetList = alphabet.ToCharArray().ToStringList(); } if (string.IsNullOrEmpty(allLabel)) { allLabel = "All"; } alphabetList.Insert(0, allLabel); if (includeNumbers) { alphabetList.Insert(1, "0-9"); } var ul = new TagBuilder("ul"); ul.AddCssClass("pagination"); ul.AddCssClass("alpha"); foreach (var letter in alphabetList) { var li = new TagBuilder("li"); // firstletters is a list of which alpha chars actually have results // so that ones without data can be non links // if not provided then always make a link for every letter if (letter == "All" || firstLetters == null || firstLetters.Contains(letter) || (firstLetters.Intersect(numbers).Any() && letter == "0-9")) { if (selectedLetter == letter || string.IsNullOrEmpty(selectedLetter) && letter == "All") { li.AddCssClass("active"); var span = new TagBuilder("span"); span.InnerHtml.Append(letter); li.InnerHtml.AppendHtml(span); } else { var a = new TagBuilder("a"); if (letter == allLabel) { a.MergeAttribute("href", pageLink(allValue)); } else { a.MergeAttribute("href", pageLink(letter)); } a.InnerHtml.Append(letter); li.InnerHtml.AppendHtml(a); } } else { li.AddCssClass("inactive"); var span = new TagBuilder("span"); span.InnerHtml.Append(letter); li.InnerHtml.AppendHtml(span); } ul.InnerHtml.AppendHtml(li); } return ul; } } }
33.630631
111
0.464506
[ "Apache-2.0" ]
John0King/cloudscribe.Web.Pagination
src/cloudscribe.Web.Pagination/AlphabeticPagination.cs
3,735
C#
using System; using System.Collections.Generic; namespace SugarChat.Message.Dtos { public class MessageDto { public string Id { get; set; } public string GroupId { get; set; } public string Content { get; set; } public int Type { get; set; } public string SentBy { get; set; } public DateTimeOffset SentTime { get; set; } public bool IsSystem { get; set; } public string Payload { get; set; } public bool IsRevoked { get; set; } public Dictionary<string, string> CustomProperties { get; set; } public string Url { get; set; } } }
31.55
72
0.605388
[ "Apache-2.0" ]
SugarChat/SugarChat.Message
SugarChat.Message/Dtos/MessageDto.cs
633
C#
//////////////////////////////////////////////////////////////////////////////// //NUnit tests for "EF Core Provider for LCPI OLE DB" // IBProvider and Contributors. 02.05.2021. using System; using System.Data; using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; using System.Linq; using Microsoft.EntityFrameworkCore; using NUnit.Framework; using xdb=lcpi.data.oledb; namespace EFCore_LcpiOleDb_Tests.General.Work.DBMS.Firebird.V03_0_0.D1.Query.Operators.SET_001.GreaterThanOrEqual.Complete.NullableInt64.NullableInt32{ //////////////////////////////////////////////////////////////////////////////// using T_DATA1 =System.Nullable<System.Int64>; using T_DATA2 =System.Nullable<System.Int32>; //////////////////////////////////////////////////////////////////////////////// //class TestSet_504__param__03__NV public static class TestSet_504__param__03__NV { private const string c_NameOf__TABLE ="DUAL"; private sealed class MyContext:TestBaseDbContext { [Table(c_NameOf__TABLE)] public sealed class TEST_RECORD { [Key] [Column("ID")] public System.Int32? TEST_ID { get; set; } };//class TEST_RECORD //---------------------------------------------------------------------- public DbSet<TEST_RECORD> testTable { get; set; } //---------------------------------------------------------------------- public MyContext(xdb.OleDbTransaction tr) :base(tr) { }//MyContext };//class MyContext //----------------------------------------------------------------------- [Test] public static void Test_001() { using(var cn=LocalCnHelper.CreateCn()) { cn.Open(); using(var tr=cn.BeginTransaction()) { //insert new record in external transaction using(var db=new MyContext(tr)) { T_DATA1 vv1=null; T_DATA2 vv2=4; var recs=db.testTable.Where(r => vv1 /*OP{*/ >= /*}OP*/ vv2); foreach(var r in recs) { TestServices.ThrowSelectedRow(); }//foreach r db.CheckTextOfLastExecutedCommand (new TestSqlTemplate() .T("SELECT ").N("d","ID").EOL() .T("FROM ").N(c_NameOf__TABLE).T(" AS ").N("d").EOL() .T("WHERE NULL")); }//using db tr.Commit(); }//using tr }//using cn }//Test_001 //----------------------------------------------------------------------- [Test] public static void Test_002() { using(var cn=LocalCnHelper.CreateCn()) { cn.Open(); using(var tr=cn.BeginTransaction()) { //insert new record in external transaction using(var db=new MyContext(tr)) { T_DATA1 vv1=null; T_DATA2 vv2=4; var recs=db.testTable.Where(r => !(vv1 /*OP{*/ >= /*}OP*/ vv2)); foreach(var r in recs) { TestServices.ThrowSelectedRow(); }//foreach r db.CheckTextOfLastExecutedCommand (new TestSqlTemplate() .T("SELECT ").N("d","ID").EOL() .T("FROM ").N(c_NameOf__TABLE).T(" AS ").N("d").EOL() .T("WHERE NULL")); }//using db tr.Commit(); }//using tr }//using cn }//Test_002 };//class TestSet_504__param__03__NV //////////////////////////////////////////////////////////////////////////////// }//namespace EFCore_LcpiOleDb_Tests.General.Work.DBMS.Firebird.V03_0_0.D1.Query.Operators.SET_001.GreaterThanOrEqual.Complete.NullableInt64.NullableInt32
28.166667
153
0.538757
[ "MIT" ]
ibprovider/Lcpi.EFCore.LcpiOleDb
Tests/General/Source/Work/DBMS/Firebird/V03_0_0/D1/Query/Operators/SET_001/GreaterThanOrEqual/Complete/NullableInt64/NullableInt32/TestSet_504__param__03__NV.cs
3,382
C#
/* * Copyright 2010-2014 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ /* * Do not modify this file. This file is generated from the kendra-2019-02-03.normal.json service model. */ using System; using System.Collections.Generic; using System.Xml.Serialization; using System.Text; using System.IO; using System.Net; using Amazon.Runtime; using Amazon.Runtime.Internal; namespace Amazon.Kendra.Model { /// <summary> /// /// </summary> #if !NETSTANDARD [Serializable] #endif public partial class ResourceAlreadyExistException : AmazonKendraException { /// <summary> /// Constructs a new ResourceAlreadyExistException with the specified error /// message. /// </summary> /// <param name="message"> /// Describes the error encountered. /// </param> public ResourceAlreadyExistException(string message) : base(message) {} /// <summary> /// Construct instance of ResourceAlreadyExistException /// </summary> /// <param name="message"></param> /// <param name="innerException"></param> public ResourceAlreadyExistException(string message, Exception innerException) : base(message, innerException) {} /// <summary> /// Construct instance of ResourceAlreadyExistException /// </summary> /// <param name="innerException"></param> public ResourceAlreadyExistException(Exception innerException) : base(innerException) {} /// <summary> /// Construct instance of ResourceAlreadyExistException /// </summary> /// <param name="message"></param> /// <param name="innerException"></param> /// <param name="errorType"></param> /// <param name="errorCode"></param> /// <param name="requestId"></param> /// <param name="statusCode"></param> public ResourceAlreadyExistException(string message, Exception innerException, ErrorType errorType, string errorCode, string requestId, HttpStatusCode statusCode) : base(message, innerException, errorType, errorCode, requestId, statusCode) {} /// <summary> /// Construct instance of ResourceAlreadyExistException /// </summary> /// <param name="message"></param> /// <param name="errorType"></param> /// <param name="errorCode"></param> /// <param name="requestId"></param> /// <param name="statusCode"></param> public ResourceAlreadyExistException(string message, ErrorType errorType, string errorCode, string requestId, HttpStatusCode statusCode) : base(message, errorType, errorCode, requestId, statusCode) {} #if !NETSTANDARD /// <summary> /// Constructs a new instance of the ResourceAlreadyExistException class with serialized data. /// </summary> /// <param name="info">The <see cref="T:System.Runtime.Serialization.SerializationInfo" /> that holds the serialized object data about the exception being thrown.</param> /// <param name="context">The <see cref="T:System.Runtime.Serialization.StreamingContext" /> that contains contextual information about the source or destination.</param> /// <exception cref="T:System.ArgumentNullException">The <paramref name="info" /> parameter is null. </exception> /// <exception cref="T:System.Runtime.Serialization.SerializationException">The class name is null or <see cref="P:System.Exception.HResult" /> is zero (0). </exception> protected ResourceAlreadyExistException(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context) : base(info, context) { } /// <summary> /// Sets the <see cref="T:System.Runtime.Serialization.SerializationInfo" /> with information about the exception. /// </summary> /// <param name="info">The <see cref="T:System.Runtime.Serialization.SerializationInfo" /> that holds the serialized object data about the exception being thrown.</param> /// <param name="context">The <see cref="T:System.Runtime.Serialization.StreamingContext" /> that contains contextual information about the source or destination.</param> /// <exception cref="T:System.ArgumentNullException">The <paramref name="info" /> parameter is a null reference (Nothing in Visual Basic). </exception> #if BCL35 [System.Security.Permissions.SecurityPermission( System.Security.Permissions.SecurityAction.LinkDemand, Flags = System.Security.Permissions.SecurityPermissionFlag.SerializationFormatter)] #endif [System.Security.SecurityCritical] // These FxCop rules are giving false-positives for this method [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Security", "CA2123:OverrideLinkDemandsShouldBeIdenticalToBase")] [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Security", "CA2134:MethodsMustOverrideWithConsistentTransparencyFxCopRule")] public override void GetObjectData(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context) { base.GetObjectData(info, context); } #endif } }
47.145161
178
0.681834
[ "Apache-2.0" ]
DetlefGolze/aws-sdk-net
sdk/src/Services/Kendra/Generated/Model/ResourceAlreadyExistException.cs
5,846
C#
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; using TMPro; public class DialogueManager : MonoBehaviour { public TextMeshProUGUI nameText; public TextMeshProUGUI dialogueText; public Animator animator; private Queue<string> sentences; private void Awake() { sentences = new Queue<string>(); } public void StartDialogue(List<List<string>> listOfDialogue, string who) { animator.SetTrigger("FadeIn"); if (who == "Player") { nameText.text = "Player"; } int index = Random.Range(0, listOfDialogue.Count); Debug.Log(listOfDialogue.Count); Debug.Log(index); List<string> dialogue = listOfDialogue[index]; sentences.Clear(); foreach (string sentence in dialogue) { sentences.Enqueue(sentence); } DisplayNewSentence(); } public void DisplayNewSentence() { if (sentences.Count == 0) { EndDialogue(); return; } string sentence = sentences.Dequeue(); StopAllCoroutines(); StartCoroutine(TypeSentence(sentence)); StartCoroutine(WaitFiveSeconds()); } IEnumerator TypeSentence(string sentence) { dialogueText.text = ""; foreach (char letter in sentence.ToCharArray()) { dialogueText.text += letter; yield return null; } } IEnumerator WaitFiveSeconds() { yield return new WaitForSeconds(3.0f); DisplayNewSentence(); } void EndDialogue() { animator.SetTrigger("FadeOut"); } public void Trigger(GameController.Choise choise) { switch (choise) { case GameController.Choise.player: StartDialogue(GetComponent<DialogueList>().PlayerSpeach, "Player"); break; case GameController.Choise.Sacrificesheep: StartDialogue(GetComponent<DialogueList>().SheepChoise, "Player"); break; case GameController.Choise.SlapaDragon: StartDialogue(GetComponent<DialogueList>().DragonChoise, "Player"); break; case GameController.Choise.HugaGiraffe: StartDialogue(GetComponent<DialogueList>().GiraffeChoise, "Player"); break; case GameController.Choise.Sacrificeababy: StartDialogue(GetComponent<DialogueList>().PlayerSpeach, "Player"); break; case GameController.Choise.Sacrificeahand: StartDialogue(GetComponent<DialogueList>().PlayerSpeach, "Player"); break; case GameController.Choise.Sacrificeaneye: StartDialogue(GetComponent<DialogueList>().PlayerSpeach, "Player"); break; case GameController.Choise.SacrificeHuman: StartDialogue(GetComponent<DialogueList>().HumanChoise, "Player"); break; } } public void TriggerStartSpeach(GameController.Choise choise) { Debug.Log("Starter Dialog"); switch (choise) { case GameController.Choise.player: StartDialogue(GetComponent<DialogueList>().StarterSpeach, "Player"); break; } } }
27.102362
84
0.585997
[ "MIT" ]
ankanx/LudumDare43
LD43/Assets/Scrips/Dialogue/DialogueManager.cs
3,442
C#
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. /****************************************************************************** * This file is auto-generated from a template file by the GenerateTests.csx * * script in tests\src\JIT\HardwareIntrinsics\General\Shared. In order to make * * changes, please update the corresponding template and run according to the * * directions listed in the file. * ******************************************************************************/ using System; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Intrinsics; namespace JIT.HardwareIntrinsics.General { public static partial class Program { private static void Vector256BooleanAsGeneric_Int16() { bool succeeded = false; try { Vector256<short> result = default(Vector256<bool>).As<bool, short>(); } catch (NotSupportedException) { succeeded = true; } if (!succeeded) { TestLibrary.TestFramework.LogInformation($"Vector256BooleanAsGeneric_Int16: RunNotSupportedScenario failed to throw NotSupportedException."); TestLibrary.TestFramework.LogInformation(string.Empty); throw new Exception("One or more scenarios did not complete as expected."); } } } }
36.72093
157
0.566814
[ "MIT" ]
2m0nd/runtime
src/tests/JIT/HardwareIntrinsics/General/NotSupported/Vector256BooleanAsGeneric_Int16.cs
1,579
C#
using System; using System.Collections; using System.Collections.Generic; using System.ComponentModel; using System.Configuration; using System.Linq; using System.Reflection; using HermaFx.SimpleConfig.BasicExtensions; namespace HermaFx.SimpleConfig { internal class ConfigurationPropertyCollection : IEnumerable<ConfigurationProperty> { //private readonly Type _ownerType; private readonly IEnumerable<ConfigurationProperty> _properties; private readonly IConfigurationPropertyFactory _configurationPropertyFactory; public ConfigurationPropertyCollection(Type interfaceType, Type ownerType) { //_ownerType = ownerType; _configurationPropertyFactory = ConfigurationPropertyFactory.Create(); _properties = GetPublicProperties(interfaceType).Select(CreateConfigurationProperty); } public IEnumerator<ConfigurationProperty> GetEnumerator() { return _properties.GetEnumerator(); } IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); } private ConfigurationProperty CreateConfigurationProperty(PropertyInfo pi) { var propertyType = pi.PropertyType; ConfigurationProperty result = null; if (propertyType.IsInterface) { if (propertyType.IsGenericIEnumerable()) { var elementType = propertyType.GetGenericArguments()[0]; result = elementType.IsEnum ? _configurationPropertyFactory.Simple(pi) : _configurationPropertyFactory.Collection(pi, elementType); }else { result = _configurationPropertyFactory.Interface(pi); } }else { if(propertyType.IsClass && false == TypeDescriptor.GetConverter(propertyType).CanConvertFrom(typeof(string))) { result = _configurationPropertyFactory.Class(pi); } else { result = _configurationPropertyFactory.Simple(pi); } } return result; } private static PropertyInfo[] GetPublicProperties(Type type) { if (type.IsInterface) { var propertyInfos = new List<PropertyInfo>(); var considered = new List<Type>(); var queue = new Queue<Type>(); considered.Add(type); queue.Enqueue(type); while (queue.Count > 0) { var subType = queue.Dequeue(); foreach (var subInterface in subType.GetInterfaces()) { if (considered.Contains(subInterface)) continue; considered.Add(subInterface); queue.Enqueue(subInterface); } var typeProperties = subType.GetProperties( BindingFlags.FlattenHierarchy | BindingFlags.Public | BindingFlags.Instance); var newPropertyInfos = typeProperties .Where(x => !propertyInfos.Contains(x)); propertyInfos.InsertRange(0, newPropertyInfos); } return propertyInfos.ToArray(); } return type.GetProperties(BindingFlags.FlattenHierarchy | BindingFlags.Public | BindingFlags.Instance); } } }
34.82243
125
0.556361
[ "MIT" ]
RVINAA/HermaFx
HermaFx.SimpleConfig/ConfigurationPropertyCollection.cs
3,728
C#
using System; namespace OutronicShop.Backend.Database.Context { public class DatabaseConfiguration { public string Ip { get; } public string Username { get; } public string Password { get; } public string DBName { get; } public ushort Port { get; } public override string ToString() => $"Host={Ip};Port={Port.ToString()};Database={DBName};Username={Username};Password={Password}"; public DatabaseConfiguration() { Ip = Environment.GetEnvironmentVariable("WEB_DATABASE_IP") ?? "127.0.0.1"; Username = Environment.GetEnvironmentVariable("WEB_DATABASE_USER") ?? "postgres"; Password = Environment.GetEnvironmentVariable("WEB_DATABASE_PASSWORD") ?? "postgres"; DBName = Environment.GetEnvironmentVariable("WEB_DATABASE_NAME") ?? "postgres"; if (!ushort.TryParse(Environment.GetEnvironmentVariable("WEB_DATABASE_PORT") ?? "5432", out ushort port)) { port = 5432; } Port = port; } } }
38.5
139
0.618738
[ "MPL-2.0", "MPL-2.0-no-copyleft-exception" ]
mathieu900v/outronicshop
dotnet/srcs/OutronicShop.Backend.Database/Context/DatabaseConfiguration.cs
1,080
C#
namespace MintingUi.Client.Features.EventStream { using MintingUi.Client.Features.Base; internal partial class EventStreamState { public class AddEventAction : BaseAction { public string Message { get; set; } } } }
20.166667
48
0.706612
[ "Unlicense" ]
stefanbemelmans/MintingUi
Source/Client/Features/EventStream/Actions/AddEvent/AddEventAction.cs
244
C#
using System; using System.Collections.Generic; using System.Globalization; using System.Linq; using System.Reflection; using System.Runtime.CompilerServices; using Umbraco.Core.Models.EntityBase; namespace Umbraco.Core.Models { /// <summary> /// Implementation of the <see cref="IUmbracoEntity"/> for internal use. /// </summary> internal class UmbracoEntity : Entity, IUmbracoEntity { private int _creatorId; private int _level; private string _name; private int _parentId; private string _path; private int _sortOrder; private bool _trashed; private bool _hasChildren; private bool _isPublished; private bool _isDraft; private bool _hasPendingChanges; private string _contentTypeAlias; private Guid _nodeObjectTypeId; private static readonly PropertyInfo CreatorIdSelector = ExpressionHelper.GetPropertyInfo<UmbracoEntity, int>(x => x.CreatorId); private static readonly PropertyInfo LevelSelector = ExpressionHelper.GetPropertyInfo<UmbracoEntity, int>(x => x.Level); private static readonly PropertyInfo NameSelector = ExpressionHelper.GetPropertyInfo<UmbracoEntity, string>(x => x.Name); private static readonly PropertyInfo ParentIdSelector = ExpressionHelper.GetPropertyInfo<UmbracoEntity, int>(x => x.ParentId); private static readonly PropertyInfo PathSelector = ExpressionHelper.GetPropertyInfo<UmbracoEntity, string>(x => x.Path); private static readonly PropertyInfo SortOrderSelector = ExpressionHelper.GetPropertyInfo<UmbracoEntity, int>(x => x.SortOrder); private static readonly PropertyInfo TrashedSelector = ExpressionHelper.GetPropertyInfo<UmbracoEntity, bool>(x => x.Trashed); private static readonly PropertyInfo HasChildrenSelector = ExpressionHelper.GetPropertyInfo<UmbracoEntity, bool>(x => x.HasChildren); private static readonly PropertyInfo IsPublishedSelector = ExpressionHelper.GetPropertyInfo<UmbracoEntity, bool>(x => x.IsPublished); private static readonly PropertyInfo IsDraftSelector = ExpressionHelper.GetPropertyInfo<UmbracoEntity, bool>(x => x.IsDraft); private static readonly PropertyInfo HasPendingChangesSelector = ExpressionHelper.GetPropertyInfo<UmbracoEntity, bool>(x => x.HasPendingChanges); private static readonly PropertyInfo ContentTypeAliasSelector = ExpressionHelper.GetPropertyInfo<UmbracoEntity, string>(x => x.ContentTypeAlias); private static readonly PropertyInfo ContentTypeIconSelector = ExpressionHelper.GetPropertyInfo<UmbracoEntity, string>(x => x.ContentTypeIcon); private static readonly PropertyInfo ContentTypeThumbnailSelector = ExpressionHelper.GetPropertyInfo<UmbracoEntity, string>(x => x.ContentTypeThumbnail); private static readonly PropertyInfo NodeObjectTypeIdSelector = ExpressionHelper.GetPropertyInfo<UmbracoEntity, Guid>(x => x.NodeObjectTypeId); private string _contentTypeIcon; private string _contentTypeThumbnail; public UmbracoEntity() { AdditionalData = new Dictionary<string, object>(); } public UmbracoEntity(bool trashed) { AdditionalData = new Dictionary<string, object>(); Trashed = trashed; } // for MySql public UmbracoEntity(UInt64 trashed) { AdditionalData = new Dictionary<string, object>(); Trashed = trashed == 1; } public int CreatorId { get { return _creatorId; } set { SetPropertyValueAndDetectChanges(o => { _creatorId = value; return _creatorId; }, _creatorId, CreatorIdSelector); } } public int Level { get { return _level; } set { SetPropertyValueAndDetectChanges(o => { _level = value; return _level; }, _level, LevelSelector); } } public string Name { get { return _name; } set { SetPropertyValueAndDetectChanges(o => { _name = value; return _name; }, _name, NameSelector); } } public int ParentId { get { return _parentId; } set { SetPropertyValueAndDetectChanges(o => { _parentId = value; return _parentId; }, _parentId, ParentIdSelector); } } public string Path { get { return _path; } set { SetPropertyValueAndDetectChanges(o => { _path = value; return _path; }, _path, PathSelector); } } public int SortOrder { get { return _sortOrder; } set { SetPropertyValueAndDetectChanges(o => { _sortOrder = value; return _sortOrder; }, _sortOrder, SortOrderSelector); } } public bool Trashed { get { return _trashed; } private set { SetPropertyValueAndDetectChanges(o => { _trashed = value; return _trashed; }, _trashed, TrashedSelector); } } public IDictionary<string, object> AdditionalData { get; private set; } public bool HasChildren { get { return _hasChildren; } set { SetPropertyValueAndDetectChanges(o => { _hasChildren = value; return _hasChildren; }, _hasChildren, HasChildrenSelector); //This is a custom property that is not exposed in IUmbracoEntity so add it to the additional data AdditionalData["HasChildren"] = value; } } public bool IsPublished { get { return _isPublished; } set { SetPropertyValueAndDetectChanges(o => { _isPublished = value; return _isPublished; }, _isPublished, IsPublishedSelector); //This is a custom property that is not exposed in IUmbracoEntity so add it to the additional data AdditionalData["IsPublished"] = value; } } public bool IsDraft { get { return _isDraft; } set { SetPropertyValueAndDetectChanges(o => { _isDraft = value; return _isDraft; }, _isDraft, IsDraftSelector); //This is a custom property that is not exposed in IUmbracoEntity so add it to the additional data AdditionalData["IsDraft"] = value; } } public bool HasPendingChanges { get { return _hasPendingChanges; } set { SetPropertyValueAndDetectChanges(o => { _hasPendingChanges = value; return _hasPendingChanges; }, _hasPendingChanges, HasPendingChangesSelector); //This is a custom property that is not exposed in IUmbracoEntity so add it to the additional data AdditionalData["HasPendingChanges"] = value; } } public string ContentTypeAlias { get { return _contentTypeAlias; } set { SetPropertyValueAndDetectChanges(o => { _contentTypeAlias = value; return _contentTypeAlias; }, _contentTypeAlias, ContentTypeAliasSelector); //This is a custom property that is not exposed in IUmbracoEntity so add it to the additional data AdditionalData["ContentTypeAlias"] = value; } } public string ContentTypeIcon { get { return _contentTypeIcon; } set { SetPropertyValueAndDetectChanges(o => { _contentTypeIcon = value; return _contentTypeIcon; }, _contentTypeIcon, ContentTypeIconSelector); //This is a custom property that is not exposed in IUmbracoEntity so add it to the additional data AdditionalData["ContentTypeIcon"] = value; } } public string ContentTypeThumbnail { get { return _contentTypeThumbnail; } set { SetPropertyValueAndDetectChanges(o => { _contentTypeThumbnail = value; return _contentTypeThumbnail; }, _contentTypeThumbnail, ContentTypeThumbnailSelector); //This is a custom property that is not exposed in IUmbracoEntity so add it to the additional data AdditionalData["ContentTypeThumbnail"] = value; } } public Guid NodeObjectTypeId { get { return _nodeObjectTypeId; } set { SetPropertyValueAndDetectChanges(o => { _nodeObjectTypeId = value; return _nodeObjectTypeId; }, _nodeObjectTypeId, NodeObjectTypeIdSelector); //This is a custom property that is not exposed in IUmbracoEntity so add it to the additional data AdditionalData["NodeObjectTypeId"] = value; } } public override object DeepClone() { var clone = (UmbracoEntity) base.DeepClone(); //turn off change tracking clone.DisableChangeTracking(); //This ensures that any value in the dictionary that is deep cloneable is cloned too foreach (var key in clone.AdditionalData.Keys.ToArray()) { var deepCloneable = clone.AdditionalData[key] as IDeepCloneable; if (deepCloneable != null) { clone.AdditionalData[key] = deepCloneable.DeepClone(); } } //this shouldn't really be needed since we're not tracking clone.ResetDirtyProperties(false); //re-enable tracking clone.EnableChangeTracking(); return clone; } /// <summary> /// A struction that can be contained in the additional data of an UmbracoEntity representing /// a user defined property /// </summary> public class EntityProperty : IDeepCloneable { public string PropertyEditorAlias { get; set; } public object Value { get; set; } public object DeepClone() { //Memberwise clone on Entity will work since it doesn't have any deep elements // for any sub class this will work for standard properties as well that aren't complex object's themselves. var clone = MemberwiseClone(); return clone; } protected bool Equals(EntityProperty other) { return PropertyEditorAlias.Equals(other.PropertyEditorAlias) && string.Equals(Value, other.Value); } public override bool Equals(object obj) { if (ReferenceEquals(null, obj)) return false; if (ReferenceEquals(this, obj)) return true; if (obj.GetType() != this.GetType()) return false; return Equals((EntityProperty) obj); } public override int GetHashCode() { unchecked { return (PropertyEditorAlias.GetHashCode() * 397) ^ (Value != null ? Value.GetHashCode() : 0); } } } } }
37.216138
162
0.536859
[ "MIT" ]
Heather-Herbert/Umbraco-CMS
src/Umbraco.Core/Models/UmbracoEntity.cs
12,916
C#
using System.Collections.Generic; using System.Threading.Tasks; using AlmOps.ConsoleApp.Tasks; using FluentAssertions; using Xunit; namespace AlmOps.ConsoleApp.UnitTests.Tasks { [Trait("Category", "UnitTests")] public class TaskBaseTest { class DummyTask : TaskBase { public override Task<string> ExecuteAsync(CommandLineOptions options) { return null; } public new Dictionary<string, string> GetVariables(List<string> inputVariables, string separator) { return base.GetVariables(inputVariables, separator); } } [Fact] public void TaskBaseGetVariables_ShouldReturnDictionary() { var task = new DummyTask(); var output = task.GetVariables(new List<string> { "toto:titi", "tutu:tyty" }, ":"); output.Should().NotBeNull(); output.Should().NotBeEmpty(); output.Count.Should().Be(2); output.Should().ContainKey("toto"); output["toto"].Should().Be("titi"); output.Should().ContainKey("tutu"); output["tutu"].Should().Be("tyty"); } [Fact] public void TaskBaseGetVariables_WithSeperatorCharacter_ShouldReturnDictionary() { var task = new DummyTask(); var output = task.GetVariables(new List<string> { "connectionString:https://www.google.com", "complexPassword:Pass:Word:123" }, ":"); output.Should().NotBeNull(); output.Should().NotBeEmpty(); output.Count.Should().Be(2); output.Should().ContainKey("connectionString"); output["connectionString"].Should().Be("https://www.google.com"); output.Should().ContainKey("complexPassword"); output["complexPassword"].Should().Be("Pass:Word:123"); } } }
35.5
145
0.586854
[ "Apache-2.0" ]
devpro/almops
test/ConsoleApp.UnitTests/Tasks/TaskBaseTest.cs
1,919
C#
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. namespace Microsoft.VisualStudio.TestPlatform.CommandLine.UnitTests.Internal { using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Globalization; using System.Threading; using Microsoft.VisualStudio.TestPlatform.CommandLine.Internal; using Microsoft.VisualStudio.TestPlatform.CommandLine.UnitTests.Processors; using Microsoft.VisualStudio.TestPlatform.Common.Logging; using Microsoft.VisualStudio.TestPlatform.ObjectModel; using Microsoft.VisualStudio.TestPlatform.ObjectModel.Client; using Microsoft.VisualStudio.TestPlatform.ObjectModel.Logging; using Microsoft.VisualStudio.TestPlatform.Utilities; using Microsoft.VisualStudio.TestTools.UnitTesting; using Moq; using vstest.console.UnitTests.TestDoubles; using CommandLineResources = Microsoft.VisualStudio.TestPlatform.CommandLine.Resources.Resources; [TestClass] public class ConsoleLoggerTests { private Mock<ITestRunRequest> testRunRequest; private Mock<TestLoggerEvents> events; private Mock<IOutput> mockOutput; private TestLoggerManager testLoggerManager; private ConsoleLogger consoleLogger; [TestInitialize] public void Initialize() { RunTestsArgumentProcessorTests.SetupMockExtensions(); // Setup Mocks and other dependencies this.Setup(); } [TestCleanup] public void Cleanup() { DummyTestLoggerManager.Cleanup(); } [TestMethod] public void InitializeShouldThrowExceptionIfEventsIsNull() { Assert.ThrowsException<ArgumentNullException>(() => { this.consoleLogger.Initialize(null, string.Empty); }); } [TestMethod] public void InitializeShouldNotThrowExceptionIfEventsIsNotNull() { this.consoleLogger.Initialize(new Mock<TestLoggerEvents>().Object, string.Empty); } [TestMethod] public void InitializeWithParametersShouldThrowExceptionIfEventsIsNull() { Assert.ThrowsException<ArgumentNullException>(() => { var parameters = new Dictionary<string, string>(); parameters.Add("parma1", "value"); this.consoleLogger.Initialize(null, parameters); }); } [TestMethod] public void InitializeWithParametersShouldThrowExceptionIfParametersIsEmpty() { Assert.ThrowsException<ArgumentException>(() => { this.consoleLogger.Initialize(new Mock<TestLoggerEvents>().Object, new Dictionary<string, string>()); }); } [TestMethod] public void InitializeWithParametersShouldThrowExceptionIfParametersIsNull() { Assert.ThrowsException<ArgumentNullException>(() => { this.consoleLogger.Initialize(new Mock<TestLoggerEvents>().Object, (Dictionary<string, string>)null); }); } [TestMethod] public void InitializeWithParametersShouldSetVerbosityLevel() { var parameters = new Dictionary<string, string>(); parameters.Add("verbosity", "minimal"); this.consoleLogger.Initialize(new Mock<TestLoggerEvents>().Object, parameters); Assert.AreEqual(ConsoleLogger.Verbosity.Minimal, this.consoleLogger.VerbosityLevel); } [TestMethod] public void InitializeWithParametersShouldDefaultToMinimalVerbosityLevelForInvalidVerbosity() { var parameters = new Dictionary<string, string>(); parameters.Add("verbosity", "random"); this.consoleLogger.Initialize(new Mock<TestLoggerEvents>().Object, parameters); Assert.AreEqual(ConsoleLogger.Verbosity.Minimal, this.consoleLogger.VerbosityLevel); } [TestMethod] public void TestMessageHandlerShouldThrowExceptionIfEventArgsIsNull() { // Raise an event on mock object Assert.ThrowsException<ArgumentNullException>(() => { this.testRunRequest.Raise(m => m.TestRunMessage += null, default(TestRunMessageEventArgs)); }); } [TestMethod] public void TestMessageHandlerShouldWriteToConsoleIfTestRunEventsAreRaised() { // Raise events on mock object this.testRunRequest.Raise(m => m.TestRunMessage += null, new TestRunMessageEventArgs(TestMessageLevel.Informational, "Informational123")); this.testRunRequest.Raise(m => m.TestRunMessage += null, new TestRunMessageEventArgs(TestMessageLevel.Error, "Error123")); this.testRunRequest.Raise(m => m.TestRunMessage += null, new TestRunMessageEventArgs(TestMessageLevel.Warning, "Warning123")); this.FlushLoggerMessages(); this.mockOutput.Verify(o => o.WriteLine("Informational123", OutputLevel.Information), Times.Once()); this.mockOutput.Verify(o => o.WriteLine("Warning123", OutputLevel.Warning), Times.Once()); this.mockOutput.Verify(o => o.WriteLine("Error123", OutputLevel.Error), Times.Once()); } [TestMethod] public void TestResultHandlerShouldThowExceptionIfEventArgsIsNull() { var eventarg = default(TestRunChangedEventArgs); // Raise an event on mock object Assert.ThrowsException<NullReferenceException>(() => { testRunRequest.Raise(m => m.OnRunStatsChange += null, eventarg); }); } [TestMethod] public void TestResultHandlerShouldWriteToConsoleShouldShowPassedTestsForNormalVebosity() { var parameters = new Dictionary<string, string>(); parameters.Add("verbosity", "normal"); this.consoleLogger.Initialize(this.events.Object, parameters); var eventArgs = new TestRunChangedEventArgs(null, this.GetTestResultsObject(), null); // Raise an event on mock object this.testRunRequest.Raise(m => m.OnRunStatsChange += null, eventArgs); this.FlushLoggerMessages(); this.mockOutput.Verify(o => o.WriteLine(string.Format(CultureInfo.CurrentCulture, CommandLineResources.PassedTestIndicator, "TestName"), OutputLevel.Information), Times.Once()); this.mockOutput.Verify(o => o.WriteLine(string.Format(CultureInfo.CurrentCulture, CommandLineResources.FailedTestIndicator, "TestName"), OutputLevel.Information), Times.Once()); this.mockOutput.Verify(o => o.WriteLine(string.Format(CultureInfo.CurrentCulture, CommandLineResources.SkippedTestIndicator, "TestName"), OutputLevel.Warning), Times.Once()); this.mockOutput.Verify(o => o.WriteLine(string.Format(CultureInfo.CurrentCulture, CommandLineResources.NotRunTestIndicator, "TestName"), OutputLevel.Information), Times.Exactly(2)); } [TestMethod] public void TestResultHandlerShouldWriteToConsoleButSkipPassedTestsForMinimalVerbosity() { var parameters = new Dictionary<string, string>(); parameters.Add("verbosity", "minimal"); this.consoleLogger.Initialize(new Mock<TestLoggerEvents>().Object, parameters); var eventArgs = new TestRunChangedEventArgs(null, this.GetTestResultsObject(), null); // Raise an event on mock object this.testRunRequest.Raise(m => m.OnRunStatsChange += null, eventArgs); this.FlushLoggerMessages(); this.mockOutput.Verify(o => o.WriteLine(string.Format(CultureInfo.CurrentCulture, CommandLineResources.FailedTestIndicator, "TestName"), OutputLevel.Information), Times.Once()); this.mockOutput.Verify(o => o.WriteLine(string.Format(CultureInfo.CurrentCulture, CommandLineResources.SkippedTestIndicator, "TestName"), OutputLevel.Warning), Times.Once()); this.mockOutput.Verify(o => o.WriteLine(string.Format(CultureInfo.CurrentCulture, CommandLineResources.NotRunTestIndicator, "TestName"), OutputLevel.Information), Times.Exactly(2)); } [TestMethod] public void TestResultHandlerShouldWriteToNoTestResultForQuietVerbosity() { var parameters = new Dictionary<string, string>(); parameters.Add("verbosity", "quiet"); this.consoleLogger.Initialize(new Mock<TestLoggerEvents>().Object, parameters); var eventArgs = new TestRunChangedEventArgs(null, this.GetTestResultsObject(), null); // Raise an event on mock object this.testRunRequest.Raise(m => m.OnRunStatsChange += null, eventArgs); this.FlushLoggerMessages(); this.mockOutput.Verify(o => o.WriteLine(string.Format(CultureInfo.CurrentCulture, CommandLineResources.PassedTestIndicator, "TestName"), OutputLevel.Information), Times.Never); this.mockOutput.Verify(o => o.WriteLine(string.Format(CultureInfo.CurrentCulture, CommandLineResources.FailedTestIndicator, "TestName"), OutputLevel.Information), Times.Never); this.mockOutput.Verify(o => o.WriteLine(string.Format(CultureInfo.CurrentCulture, CommandLineResources.SkippedTestIndicator, "TestName"), OutputLevel.Warning), Times.Never); this.mockOutput.Verify(o => o.WriteLine(string.Format(CultureInfo.CurrentCulture, CommandLineResources.NotRunTestIndicator, "TestName"), OutputLevel.Information), Times.Never); } [TestMethod] public void TestResulCompleteHandlerShouldThowExceptionIfEventArgsIsNull() { // Raise an event on mock object Assert.ThrowsException<NullReferenceException>(() => { this.testRunRequest.Raise(m => m.OnRunCompletion += null, default(TestRunCompleteEventArgs)); }); } [TestMethod] public void TestRunCompleteHandlerShouldWriteToConsoleIfTestsPass() { // Raise an event on mock object raised to register test case count var eventArgs = new TestRunChangedEventArgs(null, this.GetTestResultObject(TestOutcome.Passed), null); this.testRunRequest.Raise(m => m.OnRunStatsChange += null, eventArgs); // Raise an event on mock object this.testRunRequest.Raise(m => m.OnRunCompletion += null, new TestRunCompleteEventArgs(null, false, false, null, null, new TimeSpan(1, 0, 0, 0))); this.mockOutput.Verify(o => o.WriteLine(string.Format(CultureInfo.CurrentCulture, CommandLineResources.TestRunSummary, 1, 1, 0, 0), OutputLevel.Information), Times.Once()); this.mockOutput.Verify(o => o.WriteLine(CommandLineResources.TestRunSuccessful, OutputLevel.Information), Times.Once()); } [TestMethod] public void TestRunCompleteHandlerShouldWriteToConsoleIfTestsFail() { // Raise an event on mock object raised to register test case count and mark Outcome as Outcome.Failed var eventArgs = new TestRunChangedEventArgs(null, this.GetTestResultObject(TestOutcome.Failed), null); this.testRunRequest.Raise(m => m.OnRunStatsChange += null, eventArgs); // Raise an event on mock object this.testRunRequest.Raise(m => m.OnRunCompletion += null, new TestRunCompleteEventArgs(null, false, false, null, null, new TimeSpan(1, 0, 0, 0))); this.mockOutput.Verify(o => o.WriteLine(string.Format(CultureInfo.CurrentCulture, CommandLineResources.TestRunSummary, 1, 0, 1, 0), OutputLevel.Information), Times.Once()); this.mockOutput.Verify(o => o.WriteLine(CommandLineResources.TestRunFailed, OutputLevel.Error), Times.Once()); } [TestMethod] public void PrintTimeHandlerShouldPrintElapsedTimeOnConsole() { // Raise an event on mock object raised to register test case count var eventArgs = new TestRunChangedEventArgs(null, this.GetTestResultObject(TestOutcome.Passed), null); this.testRunRequest.Raise(m => m.OnRunStatsChange += null, eventArgs); // Raise events on mock object this.testRunRequest.Raise(m => m.OnRunCompletion += null, new TestRunCompleteEventArgs(null, false, false, null, null, new TimeSpan(1, 0, 0, 0))); this.testRunRequest.Raise(m => m.OnRunCompletion += null, new TestRunCompleteEventArgs(null, false, false, null, null, new TimeSpan(0, 1, 0, 0))); this.testRunRequest.Raise(m => m.OnRunCompletion += null, new TestRunCompleteEventArgs(null, false, false, null, null, new TimeSpan(0, 0, 1, 0))); this.testRunRequest.Raise(m => m.OnRunCompletion += null, new TestRunCompleteEventArgs(null, false, false, null, null, new TimeSpan(0, 0, 0, 1))); // Verify PrintTimeSpan with different formats this.mockOutput.Verify(o => o.WriteLine(string.Format(CultureInfo.CurrentCulture, CommandLineResources.ExecutionTimeFormatString, 1, CommandLineResources.Days), OutputLevel.Information), Times.Once()); this.mockOutput.Verify(o => o.WriteLine(string.Format(CultureInfo.CurrentCulture, CommandLineResources.ExecutionTimeFormatString, 1, CommandLineResources.Hours), OutputLevel.Information), Times.Once()); this.mockOutput.Verify(o => o.WriteLine(string.Format(CultureInfo.CurrentCulture, CommandLineResources.ExecutionTimeFormatString, 1, CommandLineResources.Minutes), OutputLevel.Information), Times.Once()); this.mockOutput.Verify(o => o.WriteLine(string.Format(CultureInfo.CurrentCulture, CommandLineResources.ExecutionTimeFormatString, 1, CommandLineResources.Seconds), OutputLevel.Information), Times.Once()); } [TestMethod] public void DisplayFullInformationShouldWriteErrorMessageAndStackTraceToConsole() { var testresults = this.GetTestResultObject(TestOutcome.Failed); testresults[0].ErrorMessage = "ErrorMessage"; testresults[0].ErrorStackTrace = "ErrorStackTrace"; var eventArgs = new TestRunChangedEventArgs(null, testresults, null); // Raise an event on mock object this.testRunRequest.Raise(m => m.OnRunStatsChange += null, eventArgs); this.FlushLoggerMessages(); this.mockOutput.Verify(o => o.WriteLine(string.Format(CultureInfo.CurrentCulture, "{0}", " ErrorMessage"), OutputLevel.Information), Times.Once()); this.mockOutput.Verify(o => o.WriteLine(string.Format(CultureInfo.CurrentCulture, "{0}", "ErrorStackTrace"), OutputLevel.Information), Times.Once()); this.mockOutput.Verify(o => o.WriteLine(CommandLineResources.ErrorMessageBanner, OutputLevel.Information), Times.Once()); this.mockOutput.Verify(o => o.WriteLine(CommandLineResources.StacktraceBanner, OutputLevel.Information), Times.Once()); } [TestMethod] public void GetTestMessagesShouldWriteMessageAndStackTraceToConsole() { var count = 0; this.mockOutput.Setup(o => o.WriteLine(It.IsAny<string>(), It.IsAny<OutputLevel>())).Callback<string, OutputLevel>( (s, o) => { count++; }); var testresults = this.GetTestResultObject(TestOutcome.Failed); testresults[0].Messages.Add(new TestResultMessage(TestResultMessage.StandardOutCategory, "StandardOutCategory")); testresults[0].Messages.Add(new TestResultMessage(TestResultMessage.StandardErrorCategory, "StandardErrorCategory")); testresults[0].Messages.Add(new TestResultMessage(TestResultMessage.AdditionalInfoCategory, "AdditionalInfoCategory")); testresults[0].Messages.Add(new TestResultMessage(TestResultMessage.AdditionalInfoCategory, "AnotherAdditionalInfoCategory")); var eventArgs = new TestRunChangedEventArgs(null, testresults, null); // Raise an event on mock object this.testRunRequest.Raise(m => m.OnRunStatsChange += null, eventArgs); this.FlushLoggerMessages(); // Added this for synchronization SpinWait.SpinUntil(() => count == 3, 300); this.mockOutput.Verify(o => o.WriteLine(CommandLineResources.StdOutMessagesBanner, OutputLevel.Information), Times.Once()); this.mockOutput.Verify(o => o.WriteLine(" StandardOutCategory", OutputLevel.Information), Times.Once()); this.mockOutput.Verify(o => o.WriteLine(CommandLineResources.StdErrMessagesBanner, OutputLevel.Information), Times.Once()); this.mockOutput.Verify(o => o.WriteLine(" StandardErrorCategory", OutputLevel.Information), Times.Once()); this.mockOutput.Verify(o => o.WriteLine(CommandLineResources.AddnlInfoMessagesBanner, OutputLevel.Information), Times.Once()); this.mockOutput.Verify(o => o.WriteLine(" AdditionalInfoCategory AnotherAdditionalInfoCategory", OutputLevel.Information), Times.Once()); } [TestMethod] public void AttachmentInformationShouldBeWrittenToConsoleIfAttachmentsArePresent() { var attachmentSet = new AttachmentSet(new Uri("test://uri"), "myattachmentset"); var uriDataAttachment = new UriDataAttachment(new Uri("file://server/filename.ext"), "description"); attachmentSet.Attachments.Add(uriDataAttachment); var uriDataAttachment1 = new UriDataAttachment(new Uri("file://server/filename1.ext"), "description"); attachmentSet.Attachments.Add(uriDataAttachment1); var attachmentSetList = new List<AttachmentSet>(); attachmentSetList.Add(attachmentSet); var testRunCompleteEventArgs = new TestRunCompleteEventArgs(null, false, false, null, new Collection<AttachmentSet>(attachmentSetList), new TimeSpan(1, 0, 0, 0)); // Raise an event on mock object raised to register test case count and mark Outcome as Outcome.Failed this.testRunRequest.Raise(m => m.OnRunCompletion += null, testRunCompleteEventArgs); this.mockOutput.Verify(o => o.WriteLine(string.Format(CultureInfo.CurrentCulture, CommandLineResources.AttachmentOutputFormat, uriDataAttachment.Uri.LocalPath), OutputLevel.Information), Times.Once()); this.mockOutput.Verify(o => o.WriteLine(string.Format(CultureInfo.CurrentCulture, CommandLineResources.AttachmentOutputFormat, uriDataAttachment1.Uri.LocalPath), OutputLevel.Information), Times.Once()); } /// <summary> /// Setup Mocks and other dependencies /// </summary> private void Setup() { // mock for ITestRunRequest this.testRunRequest = new Mock<ITestRunRequest>(); this.events = new Mock<TestLoggerEvents>(); this.mockOutput = new Mock<IOutput>(); this.consoleLogger = new ConsoleLogger(this.mockOutput.Object); DummyTestLoggerManager.Cleanup(); // Create Instance of TestLoggerManager this.testLoggerManager = TestLoggerManager.Instance; this.testLoggerManager.AddLogger(this.consoleLogger, ConsoleLogger.ExtensionUri, new Dictionary<string, string>()); this.testLoggerManager.EnableLogging(); // Register TestRunRequest object this.testLoggerManager.RegisterTestRunEvents(this.testRunRequest.Object); } private void FlushLoggerMessages() { // Raise a test run complete message to flush out any pending messages in queue this.testRunRequest.Raise( m => m.OnRunCompletion += null, new TestRunCompleteEventArgs(stats: null, isCanceled: false, isAborted: false, error: null, attachmentSets: null, elapsedTime: new TimeSpan(1, 0, 0, 0))); } private List<ObjectModel.TestResult> GetTestResultsObject() { var testcase = new TestCase("TestName", new Uri("some://uri"), "TestSource"); var testresult = new ObjectModel.TestResult(testcase); testresult.Outcome = TestOutcome.Passed; var testresult1 = new ObjectModel.TestResult(testcase); testresult1.Outcome = TestOutcome.Failed; var testresult2 = new ObjectModel.TestResult(testcase); testresult2.Outcome = TestOutcome.None; var testresult3 = new ObjectModel.TestResult(testcase); testresult3.Outcome = TestOutcome.NotFound; var testresult4 = new ObjectModel.TestResult(testcase); testresult4.Outcome = TestOutcome.Skipped; var testresultList = new List<ObjectModel.TestResult> { testresult, testresult1, testresult2, testresult3, testresult4 }; return testresultList; } private List<ObjectModel.TestResult> GetTestResultObject(TestOutcome outcome) { var testcase = new TestCase("TestName", new Uri("some://uri"), "TestSource"); var testresult = new ObjectModel.TestResult(testcase); testresult.Outcome = outcome; var testresultList = new List<ObjectModel.TestResult> { testresult }; return testresultList; } } }
54.346835
216
0.681558
[ "MIT" ]
tmds/vstest
test/vstest.console.UnitTests/Internal/ConsoleLoggerTests.cs
21,467
C#
using Microsoft.Azure.WebJobs.Description; using System; namespace SiaConsulting.Azure.WebJobs.Extensions.SqliteExtension { [AttributeUsage(AttributeTargets.Parameter)] [Binding] public class SqliteAttribute : Attribute { public SqliteAttribute() { } [AppSetting] public string ConnectionString { get; set; } } }
22.5
64
0.702778
[ "Apache-2.0" ]
dersia/sqlite-binding-extension
src/SiaConsulting.Azure.WebJobs.Extensions.SqliteExtension/SqliteAttribute.cs
362
C#
// <auto-generated> // Generated by the protocol buffer compiler. DO NOT EDIT! // source: io/common/integration.proto // </auto-generated> #pragma warning disable 1591, 0612, 3021 #region Designer generated code using pb = global::Google.Protobuf; using pbc = global::Google.Protobuf.Collections; using pbr = global::Google.Protobuf.Reflection; using scg = global::System.Collections.Generic; namespace PKIo { /// <summary>Holder for reflection information generated from io/common/integration.proto</summary> public static partial class IntegrationReflection { #region Descriptor /// <summary>File descriptor for io/common/integration.proto</summary> public static pbr::FileDescriptor Descriptor { get { return descriptor; } } private static pbr::FileDescriptor descriptor; static IntegrationReflection() { byte[] descriptorData = global::System.Convert.FromBase64String( string.Concat( "Chtpby9jb21tb24vaW50ZWdyYXRpb24ucHJvdG8SAmlvGhRpby9jb21tb24v", "cGFzcy5wcm90bxoYaW8vY29tbW9uL3RlbXBsYXRlLnByb3RvGixwcm90b2Mt", "Z2VuLXN3YWdnZXIvb3B0aW9ucy9hbm5vdGF0aW9ucy5wcm90bxoZaW8vY29t", "bW9uL3Byb3RvY29scy5wcm90bxofZ29vZ2xlL3Byb3RvYnVmL3RpbWVzdGFt", "cC5wcm90byI4ChJNZW1iZXJzaGlwRXZlbnRJZHMSIgoDaWRzGAEgAygOMhUu", "aW8uTWVtYmVyc2hpcEV2ZW50SWQiMAoOQ291cG9uRXZlbnRJZHMSHgoDaWRz", "GAEgAygOMhEuaW8uQ291cG9uRXZlbnRJZCKgAQoSSW50ZWdyYXRpb25Db25m", "aWdzEg8KB2NsYXNzSWQYASABKAkSQgoOY29uZmlndXJhdGlvbnMYAiADKAsy", "Ki5pby5JbnRlZ3JhdGlvbkNvbmZpZ3MuQ29uZmlndXJhdGlvbnNFbnRyeRo1", "ChNDb25maWd1cmF0aW9uc0VudHJ5EgsKA2tleRgBIAEoBRINCgV2YWx1ZRgC", "IAEoCToCOAEiRgoPUHJvdG9jb2xJZElucHV0EiIKCHByb3RvY29sGAEgASgO", "MhAuaW8uUGFzc1Byb3RvY29sEg8KB2NsYXNzSWQYAiABKAkiUQoTU3Vic2Ny", "aXB0aW9uUmVxdWVzdBIiCghwcm90b2NvbBgBIAEoDjIQLmlvLlBhc3NQcm90", "b2NvbBIWCg5zdWJzY3JpcHRpb25JZBgCIAEoCSKOAQoMRmllbGRNYXBwaW5n", "EhsKE2Rlc3RpbmF0aW9uRmllbGRLZXkYASABKAkSLgoYZGVzdGluYXRpb25G", "aWVsZERhdGFUeXBlGAIgASgOMgwuaW8uRGF0YVR5cGUSEgoKaXNSZXF1aXJl", "ZBgDIAEoCBIdChVzb3VyY2VGaWVsZFVuaXF1ZU5hbWUYBCABKAkicgoNV2Vi", "aG9va0NvbmZpZxIRCgl0YXJnZXRVcmwYASABKAkSJgoMYWN0aW9uTWV0aG9k", "GAIgASgOMhAuaW8uQWN0aW9uTWV0aG9kEiYKDGZpZWxkTWFwcGluZxgDIAEo", "CzIQLmlvLkZpZWxkTWFwcGluZyJAChdTaW5rU3Vic2NyaXB0aW9uUGF5bG9h", "ZBINCgVldmVudBgBIAEoCRIWCgRwYXNzGAIgASgLMgguaW8uUGFzcyLFBQoQ", "U2lua1N1YnNjcmlwdGlvbhIKCgJpZBgBIAEoCRIPCgdjbGFzc0lkGAIgASgJ", "EiIKCHByb3RvY29sGAMgASgOMhAuaW8uUGFzc1Byb3RvY29sEiQKC3Bhc3NF", "dmVudElkGAQgAygOMg8uaW8uUGFzc0V2ZW50SWQSJQoGc3RhdHVzGAUgASgO", "MhUuaW8uSW50ZWdyYXRpb25TdGF0dXMSKQoKY29uZmlnVHlwZRgGIAEoDjIV", "LmlvLkNvbmZpZ3VyYXRpb25UeXBlEhUKDWNvbmZpZ3VyYXRpb24YByABKAkS", "LQoJY3JlYXRlZEF0GAggASgLMhouZ29vZ2xlLnByb3RvYnVmLlRpbWVzdGFt", "cBItCgl1cGRhdGVkQXQYCSABKAsyGi5nb29nbGUucHJvdG9idWYuVGltZXN0", "YW1wEjIKEG1lbWJlcnNoaXBFdmVudHMYCiABKAsyFi5pby5NZW1iZXJzaGlw", "RXZlbnRJZHNIABIqCgxjb3Vwb25FdmVudHMYCyABKAsyEi5pby5Db3Vwb25F", "dmVudElkc0gAOo8CkkGLAgqIAioRU2luayBTdWJzY3JpcHRpb24y4AFTZXQg", "dXAgYSBzdWJzY3JpcHRpb24gZm9yIHNpbmsgaW50ZWdyYXRpb24uIFNpbmsg", "c3Vic2NyaXB0aW9uIGlzIHRyaWdnZXJlZCBhZnRlciBhbGwgY2hhaW4gb2Yg", "ZXZlbnRzIGZpbmlzaGVkIGluc2lkZSBQYXNzS2l0LiBFLmcuIENyZWF0ZSBh", "IHBhc3MgaG9sZGVyIHJlY29yZCBhbmQgaXNzdWUgYSBwYXNzLCB0aGVuIGNy", "ZWF0ZSBhIHJlY29yZCBvbiBhIHRoaXJkIHBhcnR5IHBsYXRmb3JtLtIBD2Rl", "ZmF1bHRMYW5ndWFnZUIRCg9wcm90b2NvbEV2ZW50SWQqfQoRSW50ZWdyYXRp", "b25TdGF0dXMSGwoXSU5URUdSQVRJT05fU1RBVFVTX05PTkUQABIYChRJTlRF", "R1JBVElPTl9ESVNBQkxFRBABEhYKEklOVEVHUkFUSU9OX0FDVElWRRACEhkK", "FUlOVEVHUkFUSU9OX1NVU1BFTkRFRBADKm8KEUNvbmZpZ3VyYXRpb25UeXBl", "EhYKEkNPTkZJR1VSQVRJT05fTk9ORRAAEgsKB1dFQkhPT0sQARIMCghEQl9N", "WVNRTBACEggKBFpPSE8QAxIJCgVCUkFaRRAEEhIKDl9DT05GSUdfVFlQRV8x", "EGQqowQKD0ludGVncmF0aW9uVHlwZRIZChVJTlRFR1JBVElPTl9UWVBFX05P", "TkUQABIWChJTT1VSQ0VfSU5URUdSQVRJT04QARImCiJIT09LX0JFRk9SRV9P", "QkpFQ1RfUkVDT1JEX0NSRUFUSU9OEAQSJQohSE9PS19BRlRFUl9PQkpFQ1Rf", "UkVDT1JEX0NSRUFUSU9OEAgSGgoWSE9PS19CRUZPUkVfUEFTU19JU1NVRRAQ", "EhkKFUhPT0tfQUZURVJfUEFTU19JU1NVRRAgEhsKF0hPT0tfQUZURVJfUEFT", "U19JTlNUQUxMEEASHgoZSE9PS19BRlRFUl9QQVNTX1VOSU5TVEFMTBCAARIl", "CiBIT09LX0JFRk9SRV9PQkpFQ1RfUkVDT1JEX1VQREFURRCAAhIkCh9IT09L", "X0FGVEVSX09CSkVDVF9SRUNPUkRfVVBEQVRFEIAEEiMKHkhPT0tfQkVGT1JF", "X1BBU1NfUkVDT1JEX1VQREFURRCACBIiCh1IT09LX0FGVEVSX1BBU1NfUkVD", "T1JEX1VQREFURRCAEBIcChdIT09LX0JFRk9SRV9QQVNTX1VQREFURRCAIBIb", "ChZIT09LX0FGVEVSX1BBU1NfVVBEQVRFEIBAEiQKHkhPT0tfQkVGT1JFX1BB", "U1NfUkVDT1JEX0RFTEVURRCAgAESIwodSE9PS19BRlRFUl9QQVNTX1JFQ09S", "RF9ERUxFVEUQgIACKtEBCgtQYXNzRXZlbnRJZBITCg9QQVNTX0VWRU5UX05P", "TkUQABIdChlQQVNTX0VWRU5UX1JFQ09SRF9DUkVBVEVEEAESGAoUUEFTU19F", "VkVOVF9JTlNUQUxMRUQQAhIdChlQQVNTX0VWRU5UX1JFQ09SRF9VUERBVEVE", "EAQSGgoWUEFTU19FVkVOVF9VTklOU1RBTExFRBAIEhoKFlBBU1NfRVZFTlRf", "SU5WQUxJREFURUQQEBIdChlQQVNTX0VWRU5UX1JFQ09SRF9ERUxFVEVEECAq", "XwoRTWVtYmVyc2hpcEV2ZW50SWQSFQoRTUVNQkVSX0VWRU5UX05PTkUQABIZ", "ChVNRU1CRVJfRVZFTlRfRU5ST0xMRUQQARIYChRNRU1CRVJfRVZFTlRfVVBE", "QVRFRBACKo8BCg1Db3Vwb25FdmVudElkEhUKEUNPVVBPTl9FVkVOVF9OT05F", "EAASGAoUQ09VUE9OX0VWRU5UX0NSRUFURUQQARIZChVDT1VQT05fRVZFTlRf", "UkVERUVNRUQQAhIYChRDT1VQT05fRVZFTlRfVVBEQVRFRBAEEhgKFENPVVBP", "Tl9FVkVOVF9ERUxFVEVEEAgqUwoMQWN0aW9uTWV0aG9kEg8KC01FVEhPRF9O", "T05FEAASDwoLTUVUSE9EX1BPU1QQARIOCgpNRVRIT0RfUFVUEAISEQoNTUVU", "SE9EX0RFTEVURRADQj4KD2lvLnBhc3NraXQuUEtpb1okc3Rhc2gucGFzc2tp", "dC5jb20vaW8vbW9kZWwvc2RrL2dvL2lvqgIEUEtJb2IGcHJvdG8z")); descriptor = pbr::FileDescriptor.FromGeneratedCode(descriptorData, new pbr::FileDescriptor[] { global::PKIo.PassReflection.Descriptor, global::PKIo.TemplateReflection.Descriptor, global::Grpc.Gateway.ProtocGenSwagger.Options.AnnotationsReflection.Descriptor, global::PKIo.ProtocolsReflection.Descriptor, global::Google.Protobuf.WellKnownTypes.TimestampReflection.Descriptor, }, new pbr::GeneratedClrTypeInfo(new[] {typeof(global::PKIo.IntegrationStatus), typeof(global::PKIo.ConfigurationType), typeof(global::PKIo.IntegrationType), typeof(global::PKIo.PassEventId), typeof(global::PKIo.MembershipEventId), typeof(global::PKIo.CouponEventId), typeof(global::PKIo.ActionMethod), }, null, new pbr::GeneratedClrTypeInfo[] { new pbr::GeneratedClrTypeInfo(typeof(global::PKIo.MembershipEventIds), global::PKIo.MembershipEventIds.Parser, new[]{ "Ids" }, null, null, null, null), new pbr::GeneratedClrTypeInfo(typeof(global::PKIo.CouponEventIds), global::PKIo.CouponEventIds.Parser, new[]{ "Ids" }, null, null, null, null), new pbr::GeneratedClrTypeInfo(typeof(global::PKIo.IntegrationConfigs), global::PKIo.IntegrationConfigs.Parser, new[]{ "ClassId", "Configurations" }, null, null, null, new pbr::GeneratedClrTypeInfo[] { null, }), new pbr::GeneratedClrTypeInfo(typeof(global::PKIo.ProtocolIdInput), global::PKIo.ProtocolIdInput.Parser, new[]{ "Protocol", "ClassId" }, null, null, null, null), new pbr::GeneratedClrTypeInfo(typeof(global::PKIo.SubscriptionRequest), global::PKIo.SubscriptionRequest.Parser, new[]{ "Protocol", "SubscriptionId" }, null, null, null, null), new pbr::GeneratedClrTypeInfo(typeof(global::PKIo.FieldMapping), global::PKIo.FieldMapping.Parser, new[]{ "DestinationFieldKey", "DestinationFieldDataType", "IsRequired", "SourceFieldUniqueName" }, null, null, null, null), new pbr::GeneratedClrTypeInfo(typeof(global::PKIo.WebhookConfig), global::PKIo.WebhookConfig.Parser, new[]{ "TargetUrl", "ActionMethod", "FieldMapping" }, null, null, null, null), new pbr::GeneratedClrTypeInfo(typeof(global::PKIo.SinkSubscriptionPayload), global::PKIo.SinkSubscriptionPayload.Parser, new[]{ "Event", "Pass" }, null, null, null, null), new pbr::GeneratedClrTypeInfo(typeof(global::PKIo.SinkSubscription), global::PKIo.SinkSubscription.Parser, new[]{ "Id", "ClassId", "Protocol", "PassEventId", "Status", "ConfigType", "Configuration", "CreatedAt", "UpdatedAt", "MembershipEvents", "CouponEvents" }, new[]{ "ProtocolEventId" }, null, null, null) })); } #endregion } #region Enums /// <summary> /// Turn on and off the integration. /// </summary> public enum IntegrationStatus { [pbr::OriginalName("INTEGRATION_STATUS_NONE")] None = 0, /// <summary> /// Turn off the integration. /// </summary> [pbr::OriginalName("INTEGRATION_DISABLED")] IntegrationDisabled = 1, /// <summary> /// Turn on the integration. /// </summary> [pbr::OriginalName("INTEGRATION_ACTIVE")] IntegrationActive = 2, /// <summary> /// The status assigned by PassKit when the account or record is not satisfying the requirements to conduct integration process. /// </summary> [pbr::OriginalName("INTEGRATION_SUSPENDED")] IntegrationSuspended = 3, } /// <summary> /// Configuration of the third party app which can be integrated with PassKit. /// </summary> public enum ConfigurationType { [pbr::OriginalName("CONFIGURATION_NONE")] ConfigurationNone = 0, [pbr::OriginalName("WEBHOOK")] Webhook = 1, [pbr::OriginalName("DB_MYSQL")] DbMysql = 2, [pbr::OriginalName("ZOHO")] Zoho = 3, [pbr::OriginalName("BRAZE")] Braze = 4, [pbr::OriginalName("_CONFIG_TYPE_1")] ConfigType1 = 100, } /// <summary> /// IntegrationType allows to select the timing of integration occurs and the order of data processing. /// </summary> public enum IntegrationType { [pbr::OriginalName("INTEGRATION_TYPE_NONE")] None = 0, /// <summary> /// Trigger event occurs on a third party platform which triggers action (chain of events) inside the PassKit. E.g. Database update triggers PassKit to issue a pass. /// </summary> [pbr::OriginalName("SOURCE_INTEGRATION")] SourceIntegration = 1, /// <summary> /// Pass holder data is processed by a third party application first then its outcome and original data are stored in PassKit. /// </summary> [pbr::OriginalName("HOOK_BEFORE_OBJECT_RECORD_CREATION")] HookBeforeObjectRecordCreation = 4, /// <summary> /// A hook event occurs after pass holder's data is created on PassKit. /// </summary> [pbr::OriginalName("HOOK_AFTER_OBJECT_RECORD_CREATION")] HookAfterObjectRecordCreation = 8, /// <summary> /// A hook event occurs after pass holder record creation and before pass issue. /// </summary> [pbr::OriginalName("HOOK_BEFORE_PASS_ISSUE")] HookBeforePassIssue = 16, /// <summary> /// A hook event occurs after pass issue. /// </summary> [pbr::OriginalName("HOOK_AFTER_PASS_ISSUE")] HookAfterPassIssue = 32, /// <summary> /// A hook event occurs after pass has been installed on mobile. /// </summary> [pbr::OriginalName("HOOK_AFTER_PASS_INSTALL")] HookAfterPassInstall = 64, /// <summary> /// A hook event occurs after pass has been uninstalled from mobile. /// </summary> [pbr::OriginalName("HOOK_AFTER_PASS_UNINSTALL")] HookAfterPassUninstall = 128, /// <summary> /// A hook event occurs before pass holder's record is updated on PassKit. /// </summary> [pbr::OriginalName("HOOK_BEFORE_OBJECT_RECORD_UPDATE")] HookBeforeObjectRecordUpdate = 256, /// <summary> /// A hook event occurs after pass holder's record is updated on PassKit. /// </summary> [pbr::OriginalName("HOOK_AFTER_OBJECT_RECORD_UPDATE")] HookAfterObjectRecordUpdate = 512, /// <summary> /// A hook event occurs before the pass is updated. This includes changes in dynamic information (e.g. displayName), generic information (e.g. links, legal disclaimer), pass design (e.g. background color). /// </summary> [pbr::OriginalName("HOOK_BEFORE_PASS_RECORD_UPDATE")] HookBeforePassRecordUpdate = 1024, /// <summary> /// A hook event occurs after the pass is updated. This includes changes in dynamic information (e.g. displayName), generic information (e.g. links, legal disclaimer), pass design (e.g. background color). /// </summary> [pbr::OriginalName("HOOK_AFTER_PASS_RECORD_UPDATE")] HookAfterPassRecordUpdate = 2048, /// <summary> /// A hook event occurs before the information on the pass is updated. /// </summary> [pbr::OriginalName("HOOK_BEFORE_PASS_UPDATE")] HookBeforePassUpdate = 4096, /// <summary> /// A hook event occurs after the information on the pass is updated. /// </summary> [pbr::OriginalName("HOOK_AFTER_PASS_UPDATE")] HookAfterPassUpdate = 8192, /// <summary> /// A hook event occurs before a pass is deleted. /// </summary> [pbr::OriginalName("HOOK_BEFORE_PASS_RECORD_DELETE")] HookBeforePassRecordDelete = 16384, /// <summary> /// A hook event occurs after a pass is deleted. /// </summary> [pbr::OriginalName("HOOK_AFTER_PASS_RECORD_DELETE")] HookAfterPassRecordDelete = 32768, } /// <summary> /// Name of pass event the third part app can subscribe to. /// </summary> public enum PassEventId { /// <summary> /// The pass payload will not be sent. /// </summary> [pbr::OriginalName("PASS_EVENT_NONE")] PassEventNone = 0, /// <summary> /// The pass payload will be sent to destination when pass record is created and issued. /// </summary> [pbr::OriginalName("PASS_EVENT_RECORD_CREATED")] PassEventRecordCreated = 1, /// <summary> /// The pass payload will be sent to destination when pass is installed on a mobile device. /// </summary> [pbr::OriginalName("PASS_EVENT_INSTALLED")] PassEventInstalled = 2, /// <summary> /// The pass payload will be sent to destination when pass record or contents have been updated. /// </summary> [pbr::OriginalName("PASS_EVENT_RECORD_UPDATED")] PassEventRecordUpdated = 4, /// <summary> /// The pass payload will be sent to destination when pass is uninstalled from a mobile device. /// </summary> [pbr::OriginalName("PASS_EVENT_UNINSTALLED")] PassEventUninstalled = 8, /// <summary> /// The pass payload will be sent to destination when pass is invalidated or expired. When pass is invalidated or expired, a pass will lose its barcode and pass content cannot be updated anymore. /// </summary> [pbr::OriginalName("PASS_EVENT_INVALIDATED")] PassEventInvalidated = 16, /// <summary> /// The pass payload will be sent to destination when pass record is deleted from the PassKit database. /// </summary> [pbr::OriginalName("PASS_EVENT_RECORD_DELETED")] PassEventRecordDeleted = 32, } /// <summary> /// Protocol specific events for the Membership protocol. /// </summary> public enum MembershipEventId { [pbr::OriginalName("MEMBER_EVENT_NONE")] MemberEventNone = 0, /// <summary> /// The member payload will be sent to destination when member record is created. /// </summary> [pbr::OriginalName("MEMBER_EVENT_ENROLLED")] MemberEventEnrolled = 1, /// <summary> /// The member payload will be sent to destination when any of member field is updated. /// </summary> [pbr::OriginalName("MEMBER_EVENT_UPDATED")] MemberEventUpdated = 2, } /// <summary> /// Protocol specific events for the Single Use Coupon protocol. /// </summary> public enum CouponEventId { [pbr::OriginalName("COUPON_EVENT_NONE")] CouponEventNone = 0, /// <summary> /// Triggered when coupon is issued. /// </summary> [pbr::OriginalName("COUPON_EVENT_CREATED")] CouponEventCreated = 1, /// <summary> /// Triggered when coupon is redeemed. /// </summary> [pbr::OriginalName("COUPON_EVENT_REDEEMED")] CouponEventRedeemed = 2, /// <summary> /// Triggered when any of coupon field is updated. /// </summary> [pbr::OriginalName("COUPON_EVENT_UPDATED")] CouponEventUpdated = 4, /// <summary> /// Triggered when coupon record is deleted. /// </summary> [pbr::OriginalName("COUPON_EVENT_DELETED")] CouponEventDeleted = 8, } /// <summary> /// Action method is an api call method (post, put, delete) used when data get integrated with the third party application. /// This enum will be useful if topic is not directly produced by debezium and want to know the original debezium event operation. /// </summary> public enum ActionMethod { [pbr::OriginalName("METHOD_NONE")] MethodNone = 0, /// <summary> /// Invokes POST request to create a record the third party app. /// </summary> [pbr::OriginalName("METHOD_POST")] MethodPost = 1, /// <summary> /// Invokes PUT request to update existing record on the third party app. /// </summary> [pbr::OriginalName("METHOD_PUT")] MethodPut = 2, /// <summary> /// Invokes DELETE request to delete existing record on the third party app. /// </summary> [pbr::OriginalName("METHOD_DELETE")] MethodDelete = 3, } #endregion #region Messages /// <summary> /// Array of subscribing membership protocol events. /// </summary> public sealed partial class MembershipEventIds : pb::IMessage<MembershipEventIds> { private static readonly pb::MessageParser<MembershipEventIds> _parser = new pb::MessageParser<MembershipEventIds>(() => new MembershipEventIds()); private pb::UnknownFieldSet _unknownFields; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pb::MessageParser<MembershipEventIds> Parser { get { return _parser; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pbr::MessageDescriptor Descriptor { get { return global::PKIo.IntegrationReflection.Descriptor.MessageTypes[0]; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] pbr::MessageDescriptor pb::IMessage.Descriptor { get { return Descriptor; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public MembershipEventIds() { OnConstruction(); } partial void OnConstruction(); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public MembershipEventIds(MembershipEventIds other) : this() { ids_ = other.ids_.Clone(); _unknownFields = pb::UnknownFieldSet.Clone(other._unknownFields); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public MembershipEventIds Clone() { return new MembershipEventIds(this); } /// <summary>Field number for the "ids" field.</summary> public const int IdsFieldNumber = 1; private static readonly pb::FieldCodec<global::PKIo.MembershipEventId> _repeated_ids_codec = pb::FieldCodec.ForEnum(10, x => (int) x, x => (global::PKIo.MembershipEventId) x); private readonly pbc::RepeatedField<global::PKIo.MembershipEventId> ids_ = new pbc::RepeatedField<global::PKIo.MembershipEventId>(); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public pbc::RepeatedField<global::PKIo.MembershipEventId> Ids { get { return ids_; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override bool Equals(object other) { return Equals(other as MembershipEventIds); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public bool Equals(MembershipEventIds other) { if (ReferenceEquals(other, null)) { return false; } if (ReferenceEquals(other, this)) { return true; } if(!ids_.Equals(other.ids_)) return false; return Equals(_unknownFields, other._unknownFields); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override int GetHashCode() { int hash = 1; hash ^= ids_.GetHashCode(); if (_unknownFields != null) { hash ^= _unknownFields.GetHashCode(); } return hash; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override string ToString() { return pb::JsonFormatter.ToDiagnosticString(this); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void WriteTo(pb::CodedOutputStream output) { ids_.WriteTo(output, _repeated_ids_codec); if (_unknownFields != null) { _unknownFields.WriteTo(output); } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public int CalculateSize() { int size = 0; size += ids_.CalculateSize(_repeated_ids_codec); if (_unknownFields != null) { size += _unknownFields.CalculateSize(); } return size; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(MembershipEventIds other) { if (other == null) { return; } ids_.Add(other.ids_); _unknownFields = pb::UnknownFieldSet.MergeFrom(_unknownFields, other._unknownFields); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(pb::CodedInputStream input) { uint tag; while ((tag = input.ReadTag()) != 0) { switch(tag) { default: _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input); break; case 10: case 8: { ids_.AddEntriesFrom(input, _repeated_ids_codec); break; } } } } } /// <summary> /// Array of subscribing coupon protocol events. /// </summary> public sealed partial class CouponEventIds : pb::IMessage<CouponEventIds> { private static readonly pb::MessageParser<CouponEventIds> _parser = new pb::MessageParser<CouponEventIds>(() => new CouponEventIds()); private pb::UnknownFieldSet _unknownFields; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pb::MessageParser<CouponEventIds> Parser { get { return _parser; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pbr::MessageDescriptor Descriptor { get { return global::PKIo.IntegrationReflection.Descriptor.MessageTypes[1]; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] pbr::MessageDescriptor pb::IMessage.Descriptor { get { return Descriptor; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public CouponEventIds() { OnConstruction(); } partial void OnConstruction(); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public CouponEventIds(CouponEventIds other) : this() { ids_ = other.ids_.Clone(); _unknownFields = pb::UnknownFieldSet.Clone(other._unknownFields); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public CouponEventIds Clone() { return new CouponEventIds(this); } /// <summary>Field number for the "ids" field.</summary> public const int IdsFieldNumber = 1; private static readonly pb::FieldCodec<global::PKIo.CouponEventId> _repeated_ids_codec = pb::FieldCodec.ForEnum(10, x => (int) x, x => (global::PKIo.CouponEventId) x); private readonly pbc::RepeatedField<global::PKIo.CouponEventId> ids_ = new pbc::RepeatedField<global::PKIo.CouponEventId>(); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public pbc::RepeatedField<global::PKIo.CouponEventId> Ids { get { return ids_; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override bool Equals(object other) { return Equals(other as CouponEventIds); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public bool Equals(CouponEventIds other) { if (ReferenceEquals(other, null)) { return false; } if (ReferenceEquals(other, this)) { return true; } if(!ids_.Equals(other.ids_)) return false; return Equals(_unknownFields, other._unknownFields); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override int GetHashCode() { int hash = 1; hash ^= ids_.GetHashCode(); if (_unknownFields != null) { hash ^= _unknownFields.GetHashCode(); } return hash; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override string ToString() { return pb::JsonFormatter.ToDiagnosticString(this); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void WriteTo(pb::CodedOutputStream output) { ids_.WriteTo(output, _repeated_ids_codec); if (_unknownFields != null) { _unknownFields.WriteTo(output); } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public int CalculateSize() { int size = 0; size += ids_.CalculateSize(_repeated_ids_codec); if (_unknownFields != null) { size += _unknownFields.CalculateSize(); } return size; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(CouponEventIds other) { if (other == null) { return; } ids_.Add(other.ids_); _unknownFields = pb::UnknownFieldSet.MergeFrom(_unknownFields, other._unknownFields); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(pb::CodedInputStream input) { uint tag; while ((tag = input.ReadTag()) != 0) { switch(tag) { default: _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input); break; case 10: case 8: { ids_.AddEntriesFrom(input, _repeated_ids_codec); break; } } } } } /// <summary> /// Integration object contains configuration data to integrate PassKit application with third party application. /// </summary> public sealed partial class IntegrationConfigs : pb::IMessage<IntegrationConfigs> { private static readonly pb::MessageParser<IntegrationConfigs> _parser = new pb::MessageParser<IntegrationConfigs>(() => new IntegrationConfigs()); private pb::UnknownFieldSet _unknownFields; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pb::MessageParser<IntegrationConfigs> Parser { get { return _parser; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pbr::MessageDescriptor Descriptor { get { return global::PKIo.IntegrationReflection.Descriptor.MessageTypes[2]; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] pbr::MessageDescriptor pb::IMessage.Descriptor { get { return Descriptor; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public IntegrationConfigs() { OnConstruction(); } partial void OnConstruction(); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public IntegrationConfigs(IntegrationConfigs other) : this() { classId_ = other.classId_; configurations_ = other.configurations_.Clone(); _unknownFields = pb::UnknownFieldSet.Clone(other._unknownFields); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public IntegrationConfigs Clone() { return new IntegrationConfigs(this); } /// <summary>Field number for the "classId" field.</summary> public const int ClassIdFieldNumber = 1; private string classId_ = ""; /// <summary> /// The uuid for the class object. /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public string ClassId { get { return classId_; } set { classId_ = pb::ProtoPreconditions.CheckNotNull(value, "value"); } } /// <summary>Field number for the "configurations" field.</summary> public const int ConfigurationsFieldNumber = 2; private static readonly pbc::MapField<int, string>.Codec _map_configurations_codec = new pbc::MapField<int, string>.Codec(pb::FieldCodec.ForInt32(8, 0), pb::FieldCodec.ForString(18, ""), 18); private readonly pbc::MapField<int, string> configurations_ = new pbc::MapField<int, string>(); /// <summary> /// Key string is enum of ConfigurationType (e.g. WEBHOOK, DB_MYSQL, ZOHO). Value string is a json string of configuration object. /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public pbc::MapField<int, string> Configurations { get { return configurations_; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override bool Equals(object other) { return Equals(other as IntegrationConfigs); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public bool Equals(IntegrationConfigs other) { if (ReferenceEquals(other, null)) { return false; } if (ReferenceEquals(other, this)) { return true; } if (ClassId != other.ClassId) return false; if (!Configurations.Equals(other.Configurations)) return false; return Equals(_unknownFields, other._unknownFields); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override int GetHashCode() { int hash = 1; if (ClassId.Length != 0) hash ^= ClassId.GetHashCode(); hash ^= Configurations.GetHashCode(); if (_unknownFields != null) { hash ^= _unknownFields.GetHashCode(); } return hash; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override string ToString() { return pb::JsonFormatter.ToDiagnosticString(this); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void WriteTo(pb::CodedOutputStream output) { if (ClassId.Length != 0) { output.WriteRawTag(10); output.WriteString(ClassId); } configurations_.WriteTo(output, _map_configurations_codec); if (_unknownFields != null) { _unknownFields.WriteTo(output); } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public int CalculateSize() { int size = 0; if (ClassId.Length != 0) { size += 1 + pb::CodedOutputStream.ComputeStringSize(ClassId); } size += configurations_.CalculateSize(_map_configurations_codec); if (_unknownFields != null) { size += _unknownFields.CalculateSize(); } return size; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(IntegrationConfigs other) { if (other == null) { return; } if (other.ClassId.Length != 0) { ClassId = other.ClassId; } configurations_.Add(other.configurations_); _unknownFields = pb::UnknownFieldSet.MergeFrom(_unknownFields, other._unknownFields); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(pb::CodedInputStream input) { uint tag; while ((tag = input.ReadTag()) != 0) { switch(tag) { default: _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input); break; case 10: { ClassId = input.ReadString(); break; } case 18: { configurations_.AddEntriesFrom(input, _map_configurations_codec); break; } } } } } public sealed partial class ProtocolIdInput : pb::IMessage<ProtocolIdInput> { private static readonly pb::MessageParser<ProtocolIdInput> _parser = new pb::MessageParser<ProtocolIdInput>(() => new ProtocolIdInput()); private pb::UnknownFieldSet _unknownFields; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pb::MessageParser<ProtocolIdInput> Parser { get { return _parser; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pbr::MessageDescriptor Descriptor { get { return global::PKIo.IntegrationReflection.Descriptor.MessageTypes[3]; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] pbr::MessageDescriptor pb::IMessage.Descriptor { get { return Descriptor; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public ProtocolIdInput() { OnConstruction(); } partial void OnConstruction(); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public ProtocolIdInput(ProtocolIdInput other) : this() { protocol_ = other.protocol_; classId_ = other.classId_; _unknownFields = pb::UnknownFieldSet.Clone(other._unknownFields); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public ProtocolIdInput Clone() { return new ProtocolIdInput(this); } /// <summary>Field number for the "protocol" field.</summary> public const int ProtocolFieldNumber = 1; private global::PKIo.PassProtocol protocol_ = global::PKIo.PassProtocol.DoNotUse; /// <summary> /// The protocol which the class object belongs to. /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public global::PKIo.PassProtocol Protocol { get { return protocol_; } set { protocol_ = value; } } /// <summary>Field number for the "classId" field.</summary> public const int ClassIdFieldNumber = 2; private string classId_ = ""; /// <summary> /// The class object Id which integration belongs to. /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public string ClassId { get { return classId_; } set { classId_ = pb::ProtoPreconditions.CheckNotNull(value, "value"); } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override bool Equals(object other) { return Equals(other as ProtocolIdInput); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public bool Equals(ProtocolIdInput other) { if (ReferenceEquals(other, null)) { return false; } if (ReferenceEquals(other, this)) { return true; } if (Protocol != other.Protocol) return false; if (ClassId != other.ClassId) return false; return Equals(_unknownFields, other._unknownFields); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override int GetHashCode() { int hash = 1; if (Protocol != global::PKIo.PassProtocol.DoNotUse) hash ^= Protocol.GetHashCode(); if (ClassId.Length != 0) hash ^= ClassId.GetHashCode(); if (_unknownFields != null) { hash ^= _unknownFields.GetHashCode(); } return hash; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override string ToString() { return pb::JsonFormatter.ToDiagnosticString(this); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void WriteTo(pb::CodedOutputStream output) { if (Protocol != global::PKIo.PassProtocol.DoNotUse) { output.WriteRawTag(8); output.WriteEnum((int) Protocol); } if (ClassId.Length != 0) { output.WriteRawTag(18); output.WriteString(ClassId); } if (_unknownFields != null) { _unknownFields.WriteTo(output); } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public int CalculateSize() { int size = 0; if (Protocol != global::PKIo.PassProtocol.DoNotUse) { size += 1 + pb::CodedOutputStream.ComputeEnumSize((int) Protocol); } if (ClassId.Length != 0) { size += 1 + pb::CodedOutputStream.ComputeStringSize(ClassId); } if (_unknownFields != null) { size += _unknownFields.CalculateSize(); } return size; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(ProtocolIdInput other) { if (other == null) { return; } if (other.Protocol != global::PKIo.PassProtocol.DoNotUse) { Protocol = other.Protocol; } if (other.ClassId.Length != 0) { ClassId = other.ClassId; } _unknownFields = pb::UnknownFieldSet.MergeFrom(_unknownFields, other._unknownFields); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(pb::CodedInputStream input) { uint tag; while ((tag = input.ReadTag()) != 0) { switch(tag) { default: _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input); break; case 8: { Protocol = (global::PKIo.PassProtocol) input.ReadEnum(); break; } case 18: { ClassId = input.ReadString(); break; } } } } } public sealed partial class SubscriptionRequest : pb::IMessage<SubscriptionRequest> { private static readonly pb::MessageParser<SubscriptionRequest> _parser = new pb::MessageParser<SubscriptionRequest>(() => new SubscriptionRequest()); private pb::UnknownFieldSet _unknownFields; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pb::MessageParser<SubscriptionRequest> Parser { get { return _parser; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pbr::MessageDescriptor Descriptor { get { return global::PKIo.IntegrationReflection.Descriptor.MessageTypes[4]; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] pbr::MessageDescriptor pb::IMessage.Descriptor { get { return Descriptor; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public SubscriptionRequest() { OnConstruction(); } partial void OnConstruction(); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public SubscriptionRequest(SubscriptionRequest other) : this() { protocol_ = other.protocol_; subscriptionId_ = other.subscriptionId_; _unknownFields = pb::UnknownFieldSet.Clone(other._unknownFields); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public SubscriptionRequest Clone() { return new SubscriptionRequest(this); } /// <summary>Field number for the "protocol" field.</summary> public const int ProtocolFieldNumber = 1; private global::PKIo.PassProtocol protocol_ = global::PKIo.PassProtocol.DoNotUse; /// <summary> /// The protocol which the class object belongs to. /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public global::PKIo.PassProtocol Protocol { get { return protocol_; } set { protocol_ = value; } } /// <summary>Field number for the "subscriptionId" field.</summary> public const int SubscriptionIdFieldNumber = 2; private string subscriptionId_ = ""; /// <summary> /// The class object Id which integration belongs to. /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public string SubscriptionId { get { return subscriptionId_; } set { subscriptionId_ = pb::ProtoPreconditions.CheckNotNull(value, "value"); } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override bool Equals(object other) { return Equals(other as SubscriptionRequest); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public bool Equals(SubscriptionRequest other) { if (ReferenceEquals(other, null)) { return false; } if (ReferenceEquals(other, this)) { return true; } if (Protocol != other.Protocol) return false; if (SubscriptionId != other.SubscriptionId) return false; return Equals(_unknownFields, other._unknownFields); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override int GetHashCode() { int hash = 1; if (Protocol != global::PKIo.PassProtocol.DoNotUse) hash ^= Protocol.GetHashCode(); if (SubscriptionId.Length != 0) hash ^= SubscriptionId.GetHashCode(); if (_unknownFields != null) { hash ^= _unknownFields.GetHashCode(); } return hash; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override string ToString() { return pb::JsonFormatter.ToDiagnosticString(this); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void WriteTo(pb::CodedOutputStream output) { if (Protocol != global::PKIo.PassProtocol.DoNotUse) { output.WriteRawTag(8); output.WriteEnum((int) Protocol); } if (SubscriptionId.Length != 0) { output.WriteRawTag(18); output.WriteString(SubscriptionId); } if (_unknownFields != null) { _unknownFields.WriteTo(output); } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public int CalculateSize() { int size = 0; if (Protocol != global::PKIo.PassProtocol.DoNotUse) { size += 1 + pb::CodedOutputStream.ComputeEnumSize((int) Protocol); } if (SubscriptionId.Length != 0) { size += 1 + pb::CodedOutputStream.ComputeStringSize(SubscriptionId); } if (_unknownFields != null) { size += _unknownFields.CalculateSize(); } return size; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(SubscriptionRequest other) { if (other == null) { return; } if (other.Protocol != global::PKIo.PassProtocol.DoNotUse) { Protocol = other.Protocol; } if (other.SubscriptionId.Length != 0) { SubscriptionId = other.SubscriptionId; } _unknownFields = pb::UnknownFieldSet.MergeFrom(_unknownFields, other._unknownFields); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(pb::CodedInputStream input) { uint tag; while ((tag = input.ReadTag()) != 0) { switch(tag) { default: _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input); break; case 8: { Protocol = (global::PKIo.PassProtocol) input.ReadEnum(); break; } case 18: { SubscriptionId = input.ReadString(); break; } } } } } /// <summary> /// Sets up source and destination field /// </summary> public sealed partial class FieldMapping : pb::IMessage<FieldMapping> { private static readonly pb::MessageParser<FieldMapping> _parser = new pb::MessageParser<FieldMapping>(() => new FieldMapping()); private pb::UnknownFieldSet _unknownFields; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pb::MessageParser<FieldMapping> Parser { get { return _parser; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pbr::MessageDescriptor Descriptor { get { return global::PKIo.IntegrationReflection.Descriptor.MessageTypes[5]; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] pbr::MessageDescriptor pb::IMessage.Descriptor { get { return Descriptor; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public FieldMapping() { OnConstruction(); } partial void OnConstruction(); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public FieldMapping(FieldMapping other) : this() { destinationFieldKey_ = other.destinationFieldKey_; destinationFieldDataType_ = other.destinationFieldDataType_; isRequired_ = other.isRequired_; sourceFieldUniqueName_ = other.sourceFieldUniqueName_; _unknownFields = pb::UnknownFieldSet.Clone(other._unknownFields); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public FieldMapping Clone() { return new FieldMapping(this); } /// <summary>Field number for the "destinationFieldKey" field.</summary> public const int DestinationFieldKeyFieldNumber = 1; private string destinationFieldKey_ = ""; /// <summary> /// Field string key of destination data field. /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public string DestinationFieldKey { get { return destinationFieldKey_; } set { destinationFieldKey_ = pb::ProtoPreconditions.CheckNotNull(value, "value"); } } /// <summary>Field number for the "destinationFieldDataType" field.</summary> public const int DestinationFieldDataTypeFieldNumber = 2; private global::PKIo.DataType destinationFieldDataType_ = global::PKIo.DataType.None; /// <summary> /// Field string key of destination data field. /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public global::PKIo.DataType DestinationFieldDataType { get { return destinationFieldDataType_; } set { destinationFieldDataType_ = value; } } /// <summary>Field number for the "isRequired" field.</summary> public const int IsRequiredFieldNumber = 3; private bool isRequired_; /// <summary> /// If true, when value is empty default data will be used. /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public bool IsRequired { get { return isRequired_; } set { isRequired_ = value; } } /// <summary>Field number for the "sourceFieldUniqueName" field.</summary> public const int SourceFieldUniqueNameFieldNumber = 4; private string sourceFieldUniqueName_ = ""; /// <summary> /// Unique name of data field which becomes the data source. /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public string SourceFieldUniqueName { get { return sourceFieldUniqueName_; } set { sourceFieldUniqueName_ = pb::ProtoPreconditions.CheckNotNull(value, "value"); } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override bool Equals(object other) { return Equals(other as FieldMapping); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public bool Equals(FieldMapping other) { if (ReferenceEquals(other, null)) { return false; } if (ReferenceEquals(other, this)) { return true; } if (DestinationFieldKey != other.DestinationFieldKey) return false; if (DestinationFieldDataType != other.DestinationFieldDataType) return false; if (IsRequired != other.IsRequired) return false; if (SourceFieldUniqueName != other.SourceFieldUniqueName) return false; return Equals(_unknownFields, other._unknownFields); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override int GetHashCode() { int hash = 1; if (DestinationFieldKey.Length != 0) hash ^= DestinationFieldKey.GetHashCode(); if (DestinationFieldDataType != global::PKIo.DataType.None) hash ^= DestinationFieldDataType.GetHashCode(); if (IsRequired != false) hash ^= IsRequired.GetHashCode(); if (SourceFieldUniqueName.Length != 0) hash ^= SourceFieldUniqueName.GetHashCode(); if (_unknownFields != null) { hash ^= _unknownFields.GetHashCode(); } return hash; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override string ToString() { return pb::JsonFormatter.ToDiagnosticString(this); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void WriteTo(pb::CodedOutputStream output) { if (DestinationFieldKey.Length != 0) { output.WriteRawTag(10); output.WriteString(DestinationFieldKey); } if (DestinationFieldDataType != global::PKIo.DataType.None) { output.WriteRawTag(16); output.WriteEnum((int) DestinationFieldDataType); } if (IsRequired != false) { output.WriteRawTag(24); output.WriteBool(IsRequired); } if (SourceFieldUniqueName.Length != 0) { output.WriteRawTag(34); output.WriteString(SourceFieldUniqueName); } if (_unknownFields != null) { _unknownFields.WriteTo(output); } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public int CalculateSize() { int size = 0; if (DestinationFieldKey.Length != 0) { size += 1 + pb::CodedOutputStream.ComputeStringSize(DestinationFieldKey); } if (DestinationFieldDataType != global::PKIo.DataType.None) { size += 1 + pb::CodedOutputStream.ComputeEnumSize((int) DestinationFieldDataType); } if (IsRequired != false) { size += 1 + 1; } if (SourceFieldUniqueName.Length != 0) { size += 1 + pb::CodedOutputStream.ComputeStringSize(SourceFieldUniqueName); } if (_unknownFields != null) { size += _unknownFields.CalculateSize(); } return size; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(FieldMapping other) { if (other == null) { return; } if (other.DestinationFieldKey.Length != 0) { DestinationFieldKey = other.DestinationFieldKey; } if (other.DestinationFieldDataType != global::PKIo.DataType.None) { DestinationFieldDataType = other.DestinationFieldDataType; } if (other.IsRequired != false) { IsRequired = other.IsRequired; } if (other.SourceFieldUniqueName.Length != 0) { SourceFieldUniqueName = other.SourceFieldUniqueName; } _unknownFields = pb::UnknownFieldSet.MergeFrom(_unknownFields, other._unknownFields); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(pb::CodedInputStream input) { uint tag; while ((tag = input.ReadTag()) != 0) { switch(tag) { default: _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input); break; case 10: { DestinationFieldKey = input.ReadString(); break; } case 16: { DestinationFieldDataType = (global::PKIo.DataType) input.ReadEnum(); break; } case 24: { IsRequired = input.ReadBool(); break; } case 34: { SourceFieldUniqueName = input.ReadString(); break; } } } } } public sealed partial class WebhookConfig : pb::IMessage<WebhookConfig> { private static readonly pb::MessageParser<WebhookConfig> _parser = new pb::MessageParser<WebhookConfig>(() => new WebhookConfig()); private pb::UnknownFieldSet _unknownFields; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pb::MessageParser<WebhookConfig> Parser { get { return _parser; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pbr::MessageDescriptor Descriptor { get { return global::PKIo.IntegrationReflection.Descriptor.MessageTypes[6]; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] pbr::MessageDescriptor pb::IMessage.Descriptor { get { return Descriptor; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public WebhookConfig() { OnConstruction(); } partial void OnConstruction(); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public WebhookConfig(WebhookConfig other) : this() { targetUrl_ = other.targetUrl_; actionMethod_ = other.actionMethod_; fieldMapping_ = other.fieldMapping_ != null ? other.fieldMapping_.Clone() : null; _unknownFields = pb::UnknownFieldSet.Clone(other._unknownFields); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public WebhookConfig Clone() { return new WebhookConfig(this); } /// <summary>Field number for the "targetUrl" field.</summary> public const int TargetUrlFieldNumber = 1; private string targetUrl_ = ""; /// <summary> /// The destination url for PassKit backend to send the data to. /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public string TargetUrl { get { return targetUrl_; } set { targetUrl_ = pb::ProtoPreconditions.CheckNotNull(value, "value"); } } /// <summary>Field number for the "actionMethod" field.</summary> public const int ActionMethodFieldNumber = 2; private global::PKIo.ActionMethod actionMethod_ = global::PKIo.ActionMethod.MethodNone; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public global::PKIo.ActionMethod ActionMethod { get { return actionMethod_; } set { actionMethod_ = value; } } /// <summary>Field number for the "fieldMapping" field.</summary> public const int FieldMappingFieldNumber = 3; private global::PKIo.FieldMapping fieldMapping_; /// <summary> /// Set source fields (fields used within the PassKit platform) and destination fields (fields set on the third party app). /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public global::PKIo.FieldMapping FieldMapping { get { return fieldMapping_; } set { fieldMapping_ = value; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override bool Equals(object other) { return Equals(other as WebhookConfig); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public bool Equals(WebhookConfig other) { if (ReferenceEquals(other, null)) { return false; } if (ReferenceEquals(other, this)) { return true; } if (TargetUrl != other.TargetUrl) return false; if (ActionMethod != other.ActionMethod) return false; if (!object.Equals(FieldMapping, other.FieldMapping)) return false; return Equals(_unknownFields, other._unknownFields); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override int GetHashCode() { int hash = 1; if (TargetUrl.Length != 0) hash ^= TargetUrl.GetHashCode(); if (ActionMethod != global::PKIo.ActionMethod.MethodNone) hash ^= ActionMethod.GetHashCode(); if (fieldMapping_ != null) hash ^= FieldMapping.GetHashCode(); if (_unknownFields != null) { hash ^= _unknownFields.GetHashCode(); } return hash; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override string ToString() { return pb::JsonFormatter.ToDiagnosticString(this); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void WriteTo(pb::CodedOutputStream output) { if (TargetUrl.Length != 0) { output.WriteRawTag(10); output.WriteString(TargetUrl); } if (ActionMethod != global::PKIo.ActionMethod.MethodNone) { output.WriteRawTag(16); output.WriteEnum((int) ActionMethod); } if (fieldMapping_ != null) { output.WriteRawTag(26); output.WriteMessage(FieldMapping); } if (_unknownFields != null) { _unknownFields.WriteTo(output); } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public int CalculateSize() { int size = 0; if (TargetUrl.Length != 0) { size += 1 + pb::CodedOutputStream.ComputeStringSize(TargetUrl); } if (ActionMethod != global::PKIo.ActionMethod.MethodNone) { size += 1 + pb::CodedOutputStream.ComputeEnumSize((int) ActionMethod); } if (fieldMapping_ != null) { size += 1 + pb::CodedOutputStream.ComputeMessageSize(FieldMapping); } if (_unknownFields != null) { size += _unknownFields.CalculateSize(); } return size; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(WebhookConfig other) { if (other == null) { return; } if (other.TargetUrl.Length != 0) { TargetUrl = other.TargetUrl; } if (other.ActionMethod != global::PKIo.ActionMethod.MethodNone) { ActionMethod = other.ActionMethod; } if (other.fieldMapping_ != null) { if (fieldMapping_ == null) { FieldMapping = new global::PKIo.FieldMapping(); } FieldMapping.MergeFrom(other.FieldMapping); } _unknownFields = pb::UnknownFieldSet.MergeFrom(_unknownFields, other._unknownFields); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(pb::CodedInputStream input) { uint tag; while ((tag = input.ReadTag()) != 0) { switch(tag) { default: _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input); break; case 10: { TargetUrl = input.ReadString(); break; } case 16: { ActionMethod = (global::PKIo.ActionMethod) input.ReadEnum(); break; } case 26: { if (fieldMapping_ == null) { FieldMapping = new global::PKIo.FieldMapping(); } input.ReadMessage(FieldMapping); break; } } } } } public sealed partial class SinkSubscriptionPayload : pb::IMessage<SinkSubscriptionPayload> { private static readonly pb::MessageParser<SinkSubscriptionPayload> _parser = new pb::MessageParser<SinkSubscriptionPayload>(() => new SinkSubscriptionPayload()); private pb::UnknownFieldSet _unknownFields; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pb::MessageParser<SinkSubscriptionPayload> Parser { get { return _parser; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pbr::MessageDescriptor Descriptor { get { return global::PKIo.IntegrationReflection.Descriptor.MessageTypes[7]; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] pbr::MessageDescriptor pb::IMessage.Descriptor { get { return Descriptor; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public SinkSubscriptionPayload() { OnConstruction(); } partial void OnConstruction(); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public SinkSubscriptionPayload(SinkSubscriptionPayload other) : this() { event_ = other.event_; pass_ = other.pass_ != null ? other.pass_.Clone() : null; _unknownFields = pb::UnknownFieldSet.Clone(other._unknownFields); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public SinkSubscriptionPayload Clone() { return new SinkSubscriptionPayload(this); } /// <summary>Field number for the "event" field.</summary> public const int EventFieldNumber = 1; private string event_ = ""; /// <summary> /// PassEventId enum string to identify trigger event type /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public string Event { get { return event_; } set { event_ = pb::ProtoPreconditions.CheckNotNull(value, "value"); } } /// <summary>Field number for the "pass" field.</summary> public const int PassFieldNumber = 2; private global::PKIo.Pass pass_; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public global::PKIo.Pass Pass { get { return pass_; } set { pass_ = value; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override bool Equals(object other) { return Equals(other as SinkSubscriptionPayload); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public bool Equals(SinkSubscriptionPayload other) { if (ReferenceEquals(other, null)) { return false; } if (ReferenceEquals(other, this)) { return true; } if (Event != other.Event) return false; if (!object.Equals(Pass, other.Pass)) return false; return Equals(_unknownFields, other._unknownFields); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override int GetHashCode() { int hash = 1; if (Event.Length != 0) hash ^= Event.GetHashCode(); if (pass_ != null) hash ^= Pass.GetHashCode(); if (_unknownFields != null) { hash ^= _unknownFields.GetHashCode(); } return hash; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override string ToString() { return pb::JsonFormatter.ToDiagnosticString(this); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void WriteTo(pb::CodedOutputStream output) { if (Event.Length != 0) { output.WriteRawTag(10); output.WriteString(Event); } if (pass_ != null) { output.WriteRawTag(18); output.WriteMessage(Pass); } if (_unknownFields != null) { _unknownFields.WriteTo(output); } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public int CalculateSize() { int size = 0; if (Event.Length != 0) { size += 1 + pb::CodedOutputStream.ComputeStringSize(Event); } if (pass_ != null) { size += 1 + pb::CodedOutputStream.ComputeMessageSize(Pass); } if (_unknownFields != null) { size += _unknownFields.CalculateSize(); } return size; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(SinkSubscriptionPayload other) { if (other == null) { return; } if (other.Event.Length != 0) { Event = other.Event; } if (other.pass_ != null) { if (pass_ == null) { Pass = new global::PKIo.Pass(); } Pass.MergeFrom(other.Pass); } _unknownFields = pb::UnknownFieldSet.MergeFrom(_unknownFields, other._unknownFields); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(pb::CodedInputStream input) { uint tag; while ((tag = input.ReadTag()) != 0) { switch(tag) { default: _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input); break; case 10: { Event = input.ReadString(); break; } case 18: { if (pass_ == null) { Pass = new global::PKIo.Pass(); } input.ReadMessage(Pass); break; } } } } } public sealed partial class SinkSubscription : pb::IMessage<SinkSubscription> { private static readonly pb::MessageParser<SinkSubscription> _parser = new pb::MessageParser<SinkSubscription>(() => new SinkSubscription()); private pb::UnknownFieldSet _unknownFields; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pb::MessageParser<SinkSubscription> Parser { get { return _parser; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pbr::MessageDescriptor Descriptor { get { return global::PKIo.IntegrationReflection.Descriptor.MessageTypes[8]; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] pbr::MessageDescriptor pb::IMessage.Descriptor { get { return Descriptor; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public SinkSubscription() { OnConstruction(); } partial void OnConstruction(); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public SinkSubscription(SinkSubscription other) : this() { id_ = other.id_; classId_ = other.classId_; protocol_ = other.protocol_; passEventId_ = other.passEventId_.Clone(); status_ = other.status_; configType_ = other.configType_; configuration_ = other.configuration_; createdAt_ = other.createdAt_ != null ? other.createdAt_.Clone() : null; updatedAt_ = other.updatedAt_ != null ? other.updatedAt_.Clone() : null; switch (other.ProtocolEventIdCase) { case ProtocolEventIdOneofCase.MembershipEvents: MembershipEvents = other.MembershipEvents.Clone(); break; case ProtocolEventIdOneofCase.CouponEvents: CouponEvents = other.CouponEvents.Clone(); break; } _unknownFields = pb::UnknownFieldSet.Clone(other._unknownFields); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public SinkSubscription Clone() { return new SinkSubscription(this); } /// <summary>Field number for the "id" field.</summary> public const int IdFieldNumber = 1; private string id_ = ""; /// <summary> /// The uuid for the sink subscription config. /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public string Id { get { return id_; } set { id_ = pb::ProtoPreconditions.CheckNotNull(value, "value"); } } /// <summary>Field number for the "classId" field.</summary> public const int ClassIdFieldNumber = 2; private string classId_ = ""; /// <summary> /// The uuid for the class object. /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public string ClassId { get { return classId_; } set { classId_ = pb::ProtoPreconditions.CheckNotNull(value, "value"); } } /// <summary>Field number for the "protocol" field.</summary> public const int ProtocolFieldNumber = 3; private global::PKIo.PassProtocol protocol_ = global::PKIo.PassProtocol.DoNotUse; /// <summary> /// The protocol of class object which owns this sink subscription. /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public global::PKIo.PassProtocol Protocol { get { return protocol_; } set { protocol_ = value; } } /// <summary>Field number for the "passEventId" field.</summary> public const int PassEventIdFieldNumber = 4; private static readonly pb::FieldCodec<global::PKIo.PassEventId> _repeated_passEventId_codec = pb::FieldCodec.ForEnum(34, x => (int) x, x => (global::PKIo.PassEventId) x); private readonly pbc::RepeatedField<global::PKIo.PassEventId> passEventId_ = new pbc::RepeatedField<global::PKIo.PassEventId>(); /// <summary> /// Identifies pass event type you are subscribing to. /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public pbc::RepeatedField<global::PKIo.PassEventId> PassEventId { get { return passEventId_; } } /// <summary>Field number for the "status" field.</summary> public const int StatusFieldNumber = 5; private global::PKIo.IntegrationStatus status_ = global::PKIo.IntegrationStatus.None; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public global::PKIo.IntegrationStatus Status { get { return status_; } set { status_ = value; } } /// <summary>Field number for the "configType" field.</summary> public const int ConfigTypeFieldNumber = 6; private global::PKIo.ConfigurationType configType_ = global::PKIo.ConfigurationType.ConfigurationNone; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public global::PKIo.ConfigurationType ConfigType { get { return configType_; } set { configType_ = value; } } /// <summary>Field number for the "configuration" field.</summary> public const int ConfigurationFieldNumber = 7; private string configuration_ = ""; /// <summary> /// Configuration details for the integration. /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public string Configuration { get { return configuration_; } set { configuration_ = pb::ProtoPreconditions.CheckNotNull(value, "value"); } } /// <summary>Field number for the "createdAt" field.</summary> public const int CreatedAtFieldNumber = 8; private global::Google.Protobuf.WellKnownTypes.Timestamp createdAt_; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public global::Google.Protobuf.WellKnownTypes.Timestamp CreatedAt { get { return createdAt_; } set { createdAt_ = value; } } /// <summary>Field number for the "updatedAt" field.</summary> public const int UpdatedAtFieldNumber = 9; private global::Google.Protobuf.WellKnownTypes.Timestamp updatedAt_; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public global::Google.Protobuf.WellKnownTypes.Timestamp UpdatedAt { get { return updatedAt_; } set { updatedAt_ = value; } } /// <summary>Field number for the "membershipEvents" field.</summary> public const int MembershipEventsFieldNumber = 10; /// <summary> /// For membership protocol subscription. /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public global::PKIo.MembershipEventIds MembershipEvents { get { return protocolEventIdCase_ == ProtocolEventIdOneofCase.MembershipEvents ? (global::PKIo.MembershipEventIds) protocolEventId_ : null; } set { protocolEventId_ = value; protocolEventIdCase_ = value == null ? ProtocolEventIdOneofCase.None : ProtocolEventIdOneofCase.MembershipEvents; } } /// <summary>Field number for the "couponEvents" field.</summary> public const int CouponEventsFieldNumber = 11; /// <summary> /// For coupon protocol subscription. /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public global::PKIo.CouponEventIds CouponEvents { get { return protocolEventIdCase_ == ProtocolEventIdOneofCase.CouponEvents ? (global::PKIo.CouponEventIds) protocolEventId_ : null; } set { protocolEventId_ = value; protocolEventIdCase_ = value == null ? ProtocolEventIdOneofCase.None : ProtocolEventIdOneofCase.CouponEvents; } } private object protocolEventId_; /// <summary>Enum of possible cases for the "protocolEventId" oneof.</summary> public enum ProtocolEventIdOneofCase { None = 0, MembershipEvents = 10, CouponEvents = 11, } private ProtocolEventIdOneofCase protocolEventIdCase_ = ProtocolEventIdOneofCase.None; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public ProtocolEventIdOneofCase ProtocolEventIdCase { get { return protocolEventIdCase_; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void ClearProtocolEventId() { protocolEventIdCase_ = ProtocolEventIdOneofCase.None; protocolEventId_ = null; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override bool Equals(object other) { return Equals(other as SinkSubscription); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public bool Equals(SinkSubscription other) { if (ReferenceEquals(other, null)) { return false; } if (ReferenceEquals(other, this)) { return true; } if (Id != other.Id) return false; if (ClassId != other.ClassId) return false; if (Protocol != other.Protocol) return false; if(!passEventId_.Equals(other.passEventId_)) return false; if (Status != other.Status) return false; if (ConfigType != other.ConfigType) return false; if (Configuration != other.Configuration) return false; if (!object.Equals(CreatedAt, other.CreatedAt)) return false; if (!object.Equals(UpdatedAt, other.UpdatedAt)) return false; if (!object.Equals(MembershipEvents, other.MembershipEvents)) return false; if (!object.Equals(CouponEvents, other.CouponEvents)) return false; if (ProtocolEventIdCase != other.ProtocolEventIdCase) return false; return Equals(_unknownFields, other._unknownFields); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override int GetHashCode() { int hash = 1; if (Id.Length != 0) hash ^= Id.GetHashCode(); if (ClassId.Length != 0) hash ^= ClassId.GetHashCode(); if (Protocol != global::PKIo.PassProtocol.DoNotUse) hash ^= Protocol.GetHashCode(); hash ^= passEventId_.GetHashCode(); if (Status != global::PKIo.IntegrationStatus.None) hash ^= Status.GetHashCode(); if (ConfigType != global::PKIo.ConfigurationType.ConfigurationNone) hash ^= ConfigType.GetHashCode(); if (Configuration.Length != 0) hash ^= Configuration.GetHashCode(); if (createdAt_ != null) hash ^= CreatedAt.GetHashCode(); if (updatedAt_ != null) hash ^= UpdatedAt.GetHashCode(); if (protocolEventIdCase_ == ProtocolEventIdOneofCase.MembershipEvents) hash ^= MembershipEvents.GetHashCode(); if (protocolEventIdCase_ == ProtocolEventIdOneofCase.CouponEvents) hash ^= CouponEvents.GetHashCode(); hash ^= (int) protocolEventIdCase_; if (_unknownFields != null) { hash ^= _unknownFields.GetHashCode(); } return hash; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override string ToString() { return pb::JsonFormatter.ToDiagnosticString(this); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void WriteTo(pb::CodedOutputStream output) { if (Id.Length != 0) { output.WriteRawTag(10); output.WriteString(Id); } if (ClassId.Length != 0) { output.WriteRawTag(18); output.WriteString(ClassId); } if (Protocol != global::PKIo.PassProtocol.DoNotUse) { output.WriteRawTag(24); output.WriteEnum((int) Protocol); } passEventId_.WriteTo(output, _repeated_passEventId_codec); if (Status != global::PKIo.IntegrationStatus.None) { output.WriteRawTag(40); output.WriteEnum((int) Status); } if (ConfigType != global::PKIo.ConfigurationType.ConfigurationNone) { output.WriteRawTag(48); output.WriteEnum((int) ConfigType); } if (Configuration.Length != 0) { output.WriteRawTag(58); output.WriteString(Configuration); } if (createdAt_ != null) { output.WriteRawTag(66); output.WriteMessage(CreatedAt); } if (updatedAt_ != null) { output.WriteRawTag(74); output.WriteMessage(UpdatedAt); } if (protocolEventIdCase_ == ProtocolEventIdOneofCase.MembershipEvents) { output.WriteRawTag(82); output.WriteMessage(MembershipEvents); } if (protocolEventIdCase_ == ProtocolEventIdOneofCase.CouponEvents) { output.WriteRawTag(90); output.WriteMessage(CouponEvents); } if (_unknownFields != null) { _unknownFields.WriteTo(output); } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public int CalculateSize() { int size = 0; if (Id.Length != 0) { size += 1 + pb::CodedOutputStream.ComputeStringSize(Id); } if (ClassId.Length != 0) { size += 1 + pb::CodedOutputStream.ComputeStringSize(ClassId); } if (Protocol != global::PKIo.PassProtocol.DoNotUse) { size += 1 + pb::CodedOutputStream.ComputeEnumSize((int) Protocol); } size += passEventId_.CalculateSize(_repeated_passEventId_codec); if (Status != global::PKIo.IntegrationStatus.None) { size += 1 + pb::CodedOutputStream.ComputeEnumSize((int) Status); } if (ConfigType != global::PKIo.ConfigurationType.ConfigurationNone) { size += 1 + pb::CodedOutputStream.ComputeEnumSize((int) ConfigType); } if (Configuration.Length != 0) { size += 1 + pb::CodedOutputStream.ComputeStringSize(Configuration); } if (createdAt_ != null) { size += 1 + pb::CodedOutputStream.ComputeMessageSize(CreatedAt); } if (updatedAt_ != null) { size += 1 + pb::CodedOutputStream.ComputeMessageSize(UpdatedAt); } if (protocolEventIdCase_ == ProtocolEventIdOneofCase.MembershipEvents) { size += 1 + pb::CodedOutputStream.ComputeMessageSize(MembershipEvents); } if (protocolEventIdCase_ == ProtocolEventIdOneofCase.CouponEvents) { size += 1 + pb::CodedOutputStream.ComputeMessageSize(CouponEvents); } if (_unknownFields != null) { size += _unknownFields.CalculateSize(); } return size; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(SinkSubscription other) { if (other == null) { return; } if (other.Id.Length != 0) { Id = other.Id; } if (other.ClassId.Length != 0) { ClassId = other.ClassId; } if (other.Protocol != global::PKIo.PassProtocol.DoNotUse) { Protocol = other.Protocol; } passEventId_.Add(other.passEventId_); if (other.Status != global::PKIo.IntegrationStatus.None) { Status = other.Status; } if (other.ConfigType != global::PKIo.ConfigurationType.ConfigurationNone) { ConfigType = other.ConfigType; } if (other.Configuration.Length != 0) { Configuration = other.Configuration; } if (other.createdAt_ != null) { if (createdAt_ == null) { CreatedAt = new global::Google.Protobuf.WellKnownTypes.Timestamp(); } CreatedAt.MergeFrom(other.CreatedAt); } if (other.updatedAt_ != null) { if (updatedAt_ == null) { UpdatedAt = new global::Google.Protobuf.WellKnownTypes.Timestamp(); } UpdatedAt.MergeFrom(other.UpdatedAt); } switch (other.ProtocolEventIdCase) { case ProtocolEventIdOneofCase.MembershipEvents: if (MembershipEvents == null) { MembershipEvents = new global::PKIo.MembershipEventIds(); } MembershipEvents.MergeFrom(other.MembershipEvents); break; case ProtocolEventIdOneofCase.CouponEvents: if (CouponEvents == null) { CouponEvents = new global::PKIo.CouponEventIds(); } CouponEvents.MergeFrom(other.CouponEvents); break; } _unknownFields = pb::UnknownFieldSet.MergeFrom(_unknownFields, other._unknownFields); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(pb::CodedInputStream input) { uint tag; while ((tag = input.ReadTag()) != 0) { switch(tag) { default: _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input); break; case 10: { Id = input.ReadString(); break; } case 18: { ClassId = input.ReadString(); break; } case 24: { Protocol = (global::PKIo.PassProtocol) input.ReadEnum(); break; } case 34: case 32: { passEventId_.AddEntriesFrom(input, _repeated_passEventId_codec); break; } case 40: { Status = (global::PKIo.IntegrationStatus) input.ReadEnum(); break; } case 48: { ConfigType = (global::PKIo.ConfigurationType) input.ReadEnum(); break; } case 58: { Configuration = input.ReadString(); break; } case 66: { if (createdAt_ == null) { CreatedAt = new global::Google.Protobuf.WellKnownTypes.Timestamp(); } input.ReadMessage(CreatedAt); break; } case 74: { if (updatedAt_ == null) { UpdatedAt = new global::Google.Protobuf.WellKnownTypes.Timestamp(); } input.ReadMessage(UpdatedAt); break; } case 82: { global::PKIo.MembershipEventIds subBuilder = new global::PKIo.MembershipEventIds(); if (protocolEventIdCase_ == ProtocolEventIdOneofCase.MembershipEvents) { subBuilder.MergeFrom(MembershipEvents); } input.ReadMessage(subBuilder); MembershipEvents = subBuilder; break; } case 90: { global::PKIo.CouponEventIds subBuilder = new global::PKIo.CouponEventIds(); if (protocolEventIdCase_ == ProtocolEventIdOneofCase.CouponEvents) { subBuilder.MergeFrom(CouponEvents); } input.ReadMessage(subBuilder); CouponEvents = subBuilder; break; } } } } } #endregion } #endregion Designer generated code
38.461756
352
0.672534
[ "MIT" ]
rafaelbarrelo/passkit-csharp-grpc-sdk
lib/PKIo/Integration.g.cs
81,462
C#
namespace Pizza.Persistence { public interface IPizzaUser : IPersistenceModel { string UserName { get; set; } string Password { get; set; } } }
21.375
51
0.625731
[ "MIT" ]
dwdkls/pizzamvc
framework/Pizza.Persistence/IPizzaUser.cs
171
C#
/** * Copyright (C) 2014 Patrick Mours. All rights reserved. * License: https://github.com/crosire/reshade#license */ using System.Collections.Generic; using System.ComponentModel; using System.IO; using System.Linq; using System.Windows; using System.Windows.Controls; namespace ReShade.Setup { public partial class SelectWindow : Window { public class EffectItem : INotifyPropertyChanged { public string Name { get; set; } public string Path { get; set; } public bool IsChecked { get { return _isChecked; } set { _isChecked = value; PropertyChanged?.Invoke(this, new PropertyChangedEventArgs("IsChecked")); } } private bool _isChecked = true; public event PropertyChangedEventHandler PropertyChanged; } public SelectWindow(IEnumerable<string> effectFiles) { InitializeComponent(); EffectList.ItemsSource = effectFiles .Where(it => Path.GetExtension(it) == ".fx") .Select(it => new EffectItem { Name = Path.GetFileName(it), Path = it }); } public IEnumerable<EffectItem> GetSelection() { return EffectList.Items.Cast<EffectItem>(); } private void ChangeChecked(object sender, RoutedEventArgs e) { var button = (Button)sender; bool check = (string)button.Content == "Check All"; button.Content = check ? "Uncheck All" : "Check All"; foreach (EffectItem item in EffectList.Items) { item.IsChecked = check; } } private void ConfirmSelection(object sender, RoutedEventArgs e) { Close(); } } }
21.094595
78
0.67713
[ "BSD-3-Clause" ]
04348/reshade_custom
setup/Select.xaml.cs
1,563
C#
using System; using Com.Bigdata.Dis.Sdk.DISCommon.DISWeb; using OBS.Runtime.Internal.Util; namespace Com.Bigdata.Dis.Sdk.DISCommon.DISWeb { public class RecordResource : RestResource { private static string DEFAULT_RESOURCE_NAME = "records"; private string resourceName; private string resourceId; public RecordResource(string resourceId) { this.resourceId = resourceId; } public RecordResource(string resourceName, string resourceId) { this.resourceName = resourceName; this.resourceId = resourceId; } public override string GetResourceName() { if (string.IsNullOrEmpty(resourceName)) { return DEFAULT_RESOURCE_NAME; } return resourceName; } public override string GetResourceId() { return resourceId; } public override string GetAction() { return null; } } }
23.311111
69
0.584366
[ "Apache-2.0" ]
huaweicloud/huaweicloud-sdk-net-dis
DotNet/DISCommon/DISWeb/RecordResource.cs
1,051
C#
public abstract class Mission : IMission { protected Mission(double scoreToComplete) { this.ScoreToComplete = scoreToComplete; } public double ScoreToComplete { get; } public abstract double EnduranceRequired { get; } public abstract double WearLevelDecrement { get; } public abstract string Name { get; } }
23.466667
54
0.690341
[ "MIT" ]
George221b/SoftUni-Taks
C#OOP-Advanced/Exam/Last Army/Entities/Missions/Mission.cs
354
C#
// // Authors: // Marek Habersack <mhabersack@novell.com> // // Copyright (C) 2010 Novell, Inc. (http://novell.com/) // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // #if NET_4_0 using System; using System.Collections.Generic; using System.IO; using System.Text; using System.Web; using System.Web.Util; using NUnit.Framework; using MonoTests.SystemWeb.Framework; using MonoTests.stand_alone.WebHarness; using MonoTests.Common; namespace MonoTests.System.Web.Util { class HttpEncoderPoker : HttpEncoder { public void CallHtmlAttributeEncode (string value, TextWriter output) { HtmlAttributeEncode (value, output); } public void CallHtmlDecode (string value, TextWriter output) { HtmlDecode (value, output); } public void CallHtmlEncode (string value, TextWriter output) { HtmlEncode (value, output); } public byte [] CallUrlEncode (byte [] bytes, int offset, int count) { return UrlEncode (bytes, offset, count); } public string CallUrlPathEncode (string value) { return UrlPathEncode (value); } public void CallHeaderNameValueEncode (string headerName, string headerValue, out string encodedHeaderName, out string encodedHeaderValue) { HeaderNameValueEncode (headerName, headerValue, out encodedHeaderName, out encodedHeaderValue); } } [TestFixture] public class HttpEncoderTest { #if NET_4_0 const string notEncoded = "!()*-._"; #else const string notEncoded = "!'()*-._"; #endif static char [] hexChars = "0123456789abcdef".ToCharArray (); [Test] public void HtmlAttributeEncode () { var encoder = new HttpEncoderPoker (); var sw = new StringWriter (); AssertExtensions.Throws<ArgumentNullException> (() => { encoder.CallHtmlAttributeEncode ("string", null); }, "#A1"); encoder.CallHtmlAttributeEncode ("<script>", sw); Assert.AreEqual ("&lt;script>", sw.ToString (), "#A2"); sw = new StringWriter (); encoder.CallHtmlAttributeEncode ("\"a&b\"", sw); Assert.AreEqual ("&quot;a&amp;b&quot;", sw.ToString (), "#A3"); sw = new StringWriter (); encoder.CallHtmlAttributeEncode ("'string'", sw); Assert.AreEqual ("&#39;string&#39;", sw.ToString (), "#A4"); sw = new StringWriter (); encoder.CallHtmlAttributeEncode ("\\string\\", sw); Assert.AreEqual ("\\string\\", sw.ToString (), "#A5"); sw = new StringWriter (); encoder.CallHtmlAttributeEncode (null, sw); Assert.AreEqual (String.Empty, sw.ToString (), "#A6"); sw = new StringWriter (); encoder.CallHtmlAttributeEncode (null, sw); Assert.AreEqual (String.Empty, sw.ToString (), "#A7"); } [Test] public void HtmlDecode () { var encoder = new HttpEncoderPoker (); StringWriter sw; AssertExtensions.Throws<ArgumentNullException> (() => { encoder.CallHtmlDecode ("string", null); }, "#A1"); sw = new StringWriter (); encoder.CallHtmlDecode (null, sw); Assert.AreEqual (String.Empty, sw.ToString (), "#A2"); sw = new StringWriter (); encoder.CallHtmlDecode (String.Empty, sw); Assert.AreEqual (String.Empty, sw.ToString (), "#A3"); for (int i = 0; i < decoding_pairs.Length; i += 2) { sw = new StringWriter (); encoder.CallHtmlDecode (decoding_pairs [i], sw); Assert.AreEqual (decoding_pairs [i + 1], sw.ToString (), "#B" + (i / 2).ToString ()); } } [Test] public void HtmlDecode_Specials () { var encoder = new HttpEncoderPoker (); var sw = new StringWriter (); encoder.CallHtmlDecode ("&hearts;&#6iQj", sw); Assert.AreEqual ("♥&#6iQj", sw.ToString (), "#A1"); } [Test] public void HtmlEncode () { var encoder = new HttpEncoderPoker (); StringWriter sw; AssertExtensions.Throws<ArgumentNullException> (() => { encoder.CallHtmlEncode ("string", null); }, "#A1"); sw = new StringWriter (); encoder.CallHtmlEncode (null, sw); Assert.AreEqual (String.Empty, sw.ToString (), "#A2"); sw = new StringWriter (); encoder.CallHtmlEncode (String.Empty, sw); Assert.AreEqual (String.Empty, sw.ToString (), "#A3"); for (int i = 0; i < encoding_pairs.Length; i += 2) { sw = new StringWriter (); encoder.CallHtmlEncode (encoding_pairs [i], sw); Assert.AreEqual (encoding_pairs [i + 1], sw.ToString (), "#B" + (i / 2).ToString ()); } } [Test] public void UrlEncode () { var encoder = new HttpEncoderPoker (); byte [] bytes = new byte [10]; AssertExtensions.Throws<ArgumentOutOfRangeException> (() => { encoder.CallUrlEncode (bytes, -1, 1); }, "#A1-1"); AssertExtensions.Throws<ArgumentOutOfRangeException> (() => { encoder.CallUrlEncode (bytes, 11, 1); }, "#A1-2"); AssertExtensions.Throws<ArgumentOutOfRangeException> (() => { encoder.CallUrlEncode (bytes, 0, -1); }, "#A1-3"); AssertExtensions.Throws<ArgumentOutOfRangeException> (() => { encoder.CallUrlEncode (bytes, 01, 11); }, "#A1-4"); AssertExtensions.Throws<ArgumentNullException> (() => { encoder.CallUrlEncode (null, 0, 1); }, "#A1-5"); for (char c = char.MinValue; c < char.MaxValue; c++) { byte [] bIn; bIn = Encoding.UTF8.GetBytes (c.ToString ()); MemoryStream expected = new MemoryStream (); MemoryStream expUnicode = new MemoryStream (); //build expected result for UrlEncode for (int i = 0; i < bIn.Length; i++) UrlEncodeChar ((char) bIn [i], expected, false); byte [] expectedBytes = expected.ToArray (); byte [] encodedBytes = encoder.CallUrlEncode (bIn, 0, bIn.Length); Assert.IsNotNull (encodedBytes, "#B1-1"); Assert.AreEqual (expectedBytes.Length, encodedBytes.Length, "#B1-2"); for (int i = 0; i < expectedBytes.Length; i++) Assert.AreEqual (expectedBytes [i], encodedBytes [i], String.Format ("[Char: {0}] [Pos: {1}]", c, i)); } byte [] encoded = encoder.CallUrlEncode (new byte [0], 0, 0); Assert.IsNotNull (encoded, "#C1-1"); Assert.AreEqual (0, encoded.Length, "#C1-2"); } static void UrlEncodeChar (char c, Stream result, bool isUnicode) { if (c > 255) { //FIXME: what happens when there is an internal error? //if (!isUnicode) // throw new ArgumentOutOfRangeException ("c", c, "c must be less than 256"); int idx; int i = (int) c; result.WriteByte ((byte) '%'); result.WriteByte ((byte) 'u'); idx = i >> 12; result.WriteByte ((byte) hexChars [idx]); idx = (i >> 8) & 0x0F; result.WriteByte ((byte) hexChars [idx]); idx = (i >> 4) & 0x0F; result.WriteByte ((byte) hexChars [idx]); idx = i & 0x0F; result.WriteByte ((byte) hexChars [idx]); return; } if (c > ' ' && notEncoded.IndexOf (c) != -1) { result.WriteByte ((byte) c); return; } if (c == ' ') { result.WriteByte ((byte) '+'); return; } if ((c < '0') || (c < 'A' && c > '9') || (c > 'Z' && c < 'a') || (c > 'z')) { if (isUnicode && c > 127) { result.WriteByte ((byte) '%'); result.WriteByte ((byte) 'u'); result.WriteByte ((byte) '0'); result.WriteByte ((byte) '0'); } else result.WriteByte ((byte) '%'); int idx = ((int) c) >> 4; result.WriteByte ((byte) hexChars [idx]); idx = ((int) c) & 0x0F; result.WriteByte ((byte) hexChars [idx]); } else result.WriteByte ((byte) c); } [Test] public void UrlPathEncode () { var encoder = new HttpEncoderPoker (); Assert.AreEqual (null, encoder.CallUrlPathEncode (null), "#A1-1"); Assert.AreEqual (String.Empty, encoder.CallUrlPathEncode (String.Empty), "#A1-2"); for (char c = char.MinValue; c < char.MaxValue; c++) { MemoryStream expected = new MemoryStream (); UrlPathEncodeChar (c, expected); string exp = Encoding.ASCII.GetString (expected.ToArray ()); string act = encoder.CallUrlPathEncode (c.ToString ()); Assert.AreEqual (exp, act, "UrlPathEncode " + c.ToString ()); } } [Test] public void UrlPathEncode2 () { var encoder = new HttpEncoderPoker (); string s = "default.xxx?sdsd=sds"; string s2 = encoder.CallUrlPathEncode (s); Assert.AreEqual (s, s2, "UrlPathEncode " + s); } static void UrlPathEncodeChar (char c, Stream result) { if (c < 33 || c > 126) { byte [] bIn = Encoding.UTF8.GetBytes (c.ToString ()); for (int i = 0; i < bIn.Length; i++) { result.WriteByte ((byte) '%'); int idx = ((int) bIn [i]) >> 4; result.WriteByte ((byte) hexChars [idx]); idx = ((int) bIn [i]) & 0x0F; result.WriteByte ((byte) hexChars [idx]); } } else if (c == ' ') { result.WriteByte ((byte) '%'); result.WriteByte ((byte) '2'); result.WriteByte ((byte) '0'); } else result.WriteByte ((byte) c); } [Test] public void HeaderNameValueEncode () { var encoder = new HttpEncoderPoker (); string encodedName; string encodedValue; encoder.CallHeaderNameValueEncode (null, null, out encodedName, out encodedValue); Assert.AreEqual (null, encodedName, "#A1-1"); Assert.AreEqual (null, encodedValue, "#A1-2"); encoder.CallHeaderNameValueEncode (String.Empty, String.Empty, out encodedName, out encodedValue); Assert.AreEqual (String.Empty, encodedName, "#A2-1"); Assert.AreEqual (String.Empty, encodedValue, "#A2-2"); char ch; for (int i = Char.MinValue; i <= Char.MaxValue; i++) { ch = (char) i; encoder.CallHeaderNameValueEncode (ch.ToString (), null, out encodedName, out encodedValue); if (headerNameEncodedChars.ContainsKey (ch)) Assert.AreEqual (headerNameEncodedChars [ch], encodedName, "#B1-" + i.ToString ()); else Assert.AreEqual (ch.ToString (), encodedName, "#B1-" + i.ToString ()); encoder.CallHeaderNameValueEncode (null, ch.ToString (), out encodedName, out encodedValue); if (headerValueEncodedChars.ContainsKey (ch)) Assert.AreEqual (headerValueEncodedChars [ch], encodedValue, "#C1-" + i.ToString ()); else Assert.AreEqual (ch.ToString (), encodedValue, "#C1-" + i.ToString ()); } } Dictionary<char, string> headerNameEncodedChars = new Dictionary<char, string> { {'\u0000', "%00"}, {'\u0001', "%01"}, {'\u0002', "%02"}, {'\u0003', "%03"}, {'\u0004', "%04"}, {'\u0005', "%05"}, {'\u0006', "%06"}, {'\u0007', "%07"}, {'\u0008', "%08"}, {'\u000A', "%0a"}, {'\u000B', "%0b"}, {'\u000C', "%0c"}, {'\u000D', "%0d"}, {'\u000E', "%0e"}, {'\u000F', "%0f"}, {'\u0010', "%10"}, {'\u0011', "%11"}, {'\u0012', "%12"}, {'\u0013', "%13"}, {'\u0014', "%14"}, {'\u0015', "%15"}, {'\u0016', "%16"}, {'\u0017', "%17"}, {'\u0018', "%18"}, {'\u0019', "%19"}, {'\u001A', "%1a"}, {'\u001B', "%1b"}, {'\u001C', "%1c"}, {'\u001D', "%1d"}, {'\u001E', "%1e"}, {'\u001F', "%1f"}, {'', "%7f"}, }; Dictionary<char, string> headerValueEncodedChars = new Dictionary<char, string> { {'\u0000', "%00"}, {'\u0001', "%01"}, {'\u0002', "%02"}, {'\u0003', "%03"}, {'\u0004', "%04"}, {'\u0005', "%05"}, {'\u0006', "%06"}, {'\u0007', "%07"}, {'\u0008', "%08"}, {'\u000A', "%0a"}, {'\u000B', "%0b"}, {'\u000C', "%0c"}, {'\u000D', "%0d"}, {'\u000E', "%0e"}, {'\u000F', "%0f"}, {'\u0010', "%10"}, {'\u0011', "%11"}, {'\u0012', "%12"}, {'\u0013', "%13"}, {'\u0014', "%14"}, {'\u0015', "%15"}, {'\u0016', "%16"}, {'\u0017', "%17"}, {'\u0018', "%18"}, {'\u0019', "%19"}, {'\u001A', "%1a"}, {'\u001B', "%1b"}, {'\u001C', "%1c"}, {'\u001D', "%1d"}, {'\u001E', "%1e"}, {'\u001F', "%1f"}, {'', "%7f"}, }; #region Long arrays of strings string [] decoding_pairs = { @"&aacute;&Aacute;&acirc;&Acirc;&acute;&aelig;&AElig;&agrave;&Agrave;&alefsym;&alpha;&Alpha;&amp;&and;&ang;&aring;&Aring;&asymp;&atilde;&Atilde;&auml;&Auml;&bdquo;&beta;&Beta;&brvbar;&bull;&cap;&ccedil;&Ccedil;&cedil;&cent;&chi;&Chi;&circ;&clubs;&cong;&copy;&crarr;&cup;&curren;&dagger;&Dagger;&darr;&dArr;&deg;&delta;&Delta;&diams;&divide;&eacute;&Eacute;&ecirc;&Ecirc;&egrave;&Egrave;&empty;&emsp;&ensp;&epsilon;&Epsilon;&equiv;&eta;&Eta;&eth;&ETH;&euml;&Euml;&euro;&exist;&fnof;&forall;&frac12;&frac14;&frac34;&frasl;&gamma;&Gamma;&ge;&gt;&harr;&hArr;&hearts;&hellip;&iacute;&Iacute;&icirc;&Icirc;&iexcl;&igrave;&Igrave;&image;&infin;&int;&iota;&Iota;&iquest;&isin;&iuml;&Iuml;&kappa;&Kappa;&lambda;&Lambda;&lang;&laquo;&larr;&lArr;&lceil;&ldquo;&le;&lfloor;&lowast;&loz;&lrm;&lsaquo;&lsquo;&lt;&macr;&mdash;&micro;&middot;&minus;&mu;&Mu;&nabla;&nbsp;&ndash;&ne;&ni;&not;&notin;&nsub;&ntilde;&Ntilde;&nu;&Nu;&oacute;&Oacute;&ocirc;&Ocirc;&oelig;&OElig;&ograve;&Ograve;&oline;&omega;&Omega;&omicron;&Omicron;&oplus;&or;&ordf;&ordm;&oslash;&Oslash;&otilde;&Otilde;&otimes;&ouml;&Ouml;&para;&part;&permil;&perp;&phi;&Phi;&pi;&Pi;&piv;&plusmn;&pound;&prime;&Prime;&prod;&prop;&psi;&Psi;&quot;&radic;&rang;&raquo;&rarr;&rArr;&rceil;&rdquo;&real;&reg;&rfloor;&rho;&Rho;&rlm;&rsaquo;&rsquo;&sbquo;&scaron;&Scaron;&sdot;&sect;&shy;&sigma;&Sigma;&sigmaf;&sim;&spades;&sub;&sube;&sum;&sup;&sup1;&sup2;&sup3;&supe;&szlig;&tau;&Tau;&there4;&theta;&Theta;&thetasym;&thinsp;&thorn;&THORN;&tilde;&times;&trade;&uacute;&Uacute;&uarr;&uArr;&ucirc;&Ucirc;&ugrave;&Ugrave;&uml;&upsih;&upsilon;&Upsilon;&uuml;&Uuml;&weierp;&xi;&Xi;&yacute;&Yacute;&yen;&yuml;&Yuml;&zeta;&Zeta;&zwj;&zwnj;", @"áÁâ´æÆàÀℵαΑ&∧∠åÅ≈ãÃäÄ„βΒ¦•∩çǸ¢χΧˆ♣≅©↵∪¤†‡↓⇓°δΔ♦÷éÉêÊèÈ∅  εΕ≡ηΗðÐëË€∃ƒ∀½¼¾⁄γΓ≥>↔⇔♥…íÍîΡìÌℑ∞∫ιΙ¿∈ïÏκΚλΛ〈«←⇐⌈“≤⌊∗◊‎‹‘<¯—µ·−μΜ∇ –≠∋¬∉⊄ñÑνΝóÓôÔœŒòÒ‾ωΩοΟ⊕∨ªºøØõÕ⊗öÖ¶∂‰⊥φΦπΠϖ±£′″∏∝ψΨ""√〉»→⇒⌉”ℜ®⌋ρΡ‏›’‚šŠ⋅§­σΣς∼♠⊂⊆∑⊃¹²³⊇ßτΤ∴θΘϑ þޘיúÚ↑⇑ûÛùÙ¨ϒυΥüÜ℘ξΞýÝ¥ÿŸζΖ‍‌", @"&aacute;?dCO+6Mk'2R&Aacute;T148quH^^=972 &acirc;#&Acirc;js""{1LZz)U&acute;u@Rv-05n L&aelig;3x}&AElig;!&agrave;,=*-J*&Agrave;=P|B&alefsym;Y<g?cg>jB)&alpha;&Alpha;9#4V`)|&J/n&amp;JVK56X\2q*F&and;Js&ang;6k6&aring;""&Aring;?rGt&asymp;\F <9IM{s-&atilde;(ShK&Atilde;w/[%,ksf93'k&auml;+b$@Q{5&Auml;Uo&bdquo;aN~'ycb>VKGcjo&beta;oR8""%B`L&Beta;I7g""k5]A>^B&brvbar;lllUPg5#b&bull;8Pw,bwSiY ""5]a&cap;_R@m&D+Lz""dKLT&ccedil;KH&I}6)_Q&Ccedil;mS%BZV/*Xo&cedil;s5[&cent;-$|)|L&5~&chi;Y/3cdUrn&Chi;8&circ;&)@KU@scEW2I&clubs;p2,US7f>&m!F&cong;Fr9A%,Ci'y[]F+&copy;PY&crarr;FeCrQI<:pPP~;>&cup;&curren;y J#R&%%i&dagger;Ow,&Dagger;T&darr;KpY`WSAo$i:r&dArr;']=&deg;k12&UI@_&delta;(9xD&Delta;dz&diams;RJdB""F^Y}g&divide;2kbZ2>@yBfu&eacute;9!9J(v&Eacute;\TwTS2X5i&ecirc;SLWaTMQE]e&&Ecirc;jW{\#JAh{Ua=&egrave;5&Egrave;6/GY&empty;U&emsp;n:&ensp;dcSf&epsilon;&Epsilon;1Yoi?X&equiv;.-s!n|i9U?3:6&eta;+|6&Eta;ha?>fm!v,&eth;c;Ky]88&ETH;4T@qO#.&euml;@Kl3%&Euml;X-VvUoE& &euro;o9T:r8\||^ha;&exist;1;/BMT*xJ(a>B&fnof;bH'-TH!6NrP&forall;n&frac12;5Fqvq_e9_""XJ&frac14;vmLXTtu:TVZ,&frac34;syl;qEe:b$5j&frasl;b Hg%T&gamma;[&Gamma;H&ge;&gt;{1wT&harr;o6i~jjKC02&hArr;Q4i6m(2tpl&hearts;&#6iQj!&hellip;4le""4} Lv5{Cs&iacute;D*u]j&Iacute;s}#br=&icirc;fh&Icirc;&iexcl;_B:|&igrave;k2U7lZ;_sI\c]&Igrave;s&image; T!5h"".um9ctz&infin; YDL&int;b(S^&iota;bCm&Iota;_L(\-F&iquest;m9g.h$^HSv&isin;cWH#>&iuml;m0&Iuml;KtgRE3c5@0&&kappa;T[2?\>T^H**&Kappa;=^6 [&lambda;um&Lambda;[3wQ5gT?H(Bo\/&lang;6car8P@AjF4e|b&laquo;397jxG:m&larr;U~?~""f&lArr;`O9iwJ#&lceil;L:q-* !V&ldquo;os)Wq6S{t&le;=80A&lfloor;#tS6&lowast;x`g6a>]U-b&loz;SHb/-]&lrm;m9dm""/d<;xR)4&lsaquo;jrb/,q&lsquo;RW}n2shoM11D|&lt;{}*]WPE#d#&macr;&mdash;yhT k&micro;&middot;`f~o&minus;{Kmf&mu;d7fmt&Mu;PT@OOrzj&nabla;y ;M01XyI:&nbsp;+l<&ndash;x5|a>62y&ne;GNKJQjmj3&ni;Az&not;?V&notin;,<&nsub;R]Lc&ntilde;kV:&Ntilde;9LLf&Z%`d-H^L&nu;v_yXht&Nu;R1yuF!&oacute;j3]zOwQf_YtT9t&Oacute;}s]&1T&ocirc;&Ocirc;2lEN&oelig;:Rp^X+tPNL.&OElig;x0 ?c3ZP&ograve;3&Ograve;&oline;@nE&omega;uK-*HjL-h5z&Omega;~x&omicron;FNQ8D#{&Omicron;Yj|]'LX&oplus;ie-Y&or;&ordf;$*.c&ordm;VM7KQ.b]hmV &oslash;x{R>J-D_0v&Oslash;Hp&otilde;L'IG&Otilde;`&otimes;E &ouml;>KNCm&Ouml;O2dH_&jd^ >2&para;U%""_n&part;U>F&permil;?TSz0~~&perp;!p@G~bH^E&phi;dg)A&Phi; J<<j_,7Q)dEs,&pi;Z&Pi;_B<@%.&?70&piv;9Y^C|VRPrb4}&plusmn;Yn=9=SQ;`}(e%&pound;y;6|RN;|w&prime;AH=XXf&Prime;&prod;DGf6ol&prop;&psi;]UXZU\vzW4&Psi;e`NY[vrvs&quot;xay&radic;[@\scKIznodD<s&rang;PB C)<itm+&raquo;{t-L&rarr;s^^x<:&sh3&rArr;p^s6Y~3Csw=&rceil;_pKnhDNTmA*p&rdquo;]yG6;,ZuPx&real;xsd&reg;`hXlUn~(pK=N:^&rfloor;OS""P{%j-Wjbx.w&rho;ts^&Rho;r$h<:u^&rlm;Vj}\?7SIauBh&rsaquo;u[ !rto/[UHog&rsquo;xe6gY<24BY.&sbquo;`ZNR}&scaron;uY{Gg;F&Scaron;&sdot;az4TlWKYbJ.h&sect;c`9FrP&shy;5_)&sigma;wx.nP}z@&Sigma;NP9-$@j5&sigmaf;&sim;'ogIt:.@Gul&spades;""p\\rH[)&sub;Om/|3G+BQe&sube;5s!f/O9SA\RJkv&sum;GOFMAXu&sup;W&sup1;&sup2;L`r""}u/n&sup3;.ouLC&supe;(f&szlig;{&tau;B%e [&Tau;$DD>kIdV#X`?^\&there4;|S?W&theta;x)2P.![^5&Theta;zqF""pj&thetasym;#BE1u?&thinsp;GGG>(EQE&thorn;!""y1r/&THORN;m&@[\mw[kNR&tilde;|1G#i[(&times;X<UotTID uY&trade;sWW+TbxY&uacute;kQXr!H6&Uacute;~0TiH1POP&uarr;(CRZttz\EY<&uArr;&bN7ki|&ucirc;r,3j!e$kJE&Z$z&Ucirc;5{0[bvD""[<P)&ugrave;;1EeRSrz/gY/&Ugrave;/1 S`I*q8:Z-&uml;%N)W&upsih;O[2P9 ?&upsilon;O&Upsilon;t&uuml;&Uuml;VLq&weierp;2""(Z'~~""uiX&xi;NCq&Xi;9)S]^v 3&yacute;x""|2&$`G&Yacute;<&Nr&yen;[3NB5f&yuml; c""MzMw3(;""s&Yuml;&zeta;{!&Zeta;oevp1'j(E`vJ&zwj;Si&zwnj;gw>yc*U", @"á?dCO+6Mk'2RÁT148quH^^=972 â#Âjs""{1LZz)U´u@Rv-05n Læ3x}Æ!à,=*-J*À=P|BℵY<g?cg>jB)αΑ9#4V`)|&J/n&JVK56X\2q*F∧Js∠6k6å""Å?rGt≈\F <9IM{s-ã(ShKÃw/[%,ksf93'kä+b$@Q{5ÄUo„aN~'ycb>VKGcjoβoR8""%B`LΒI7g""k5]A>^B¦lllUPg5#b•8Pw,bwSiY ""5]a∩_R@m&D+Lz""dKLTçKH&I}6)_QÇmS%BZV/*Xo¸s5[¢-$|)|L&5~χY/3cdUrnΧ8ˆ&)@KU@scEW2I♣p2,US7f>&m!F≅Fr9A%,Ci'y[]F+©PY↵FeCrQI<:pPP~;>∪¤y J#R&%%i†Ow,‡T↓KpY`WSAo$i:r⇓']=°k12&UI@_δ(9xDΔdz♦RJdB""F^Y}g÷2kbZ2>@yBfué9!9J(vÉ\TwTS2X5iêSLWaTMQE]e&ÊjW{\#JAh{Ua=è5È6/GY∅U n: dcSfεΕ1Yoi?X≡.-s!n|i9U?3:6η+|6Ηha?>fm!v,ðc;Ky]88Ð4T@qO#.ë@Kl3%ËX-VvUoE& €o9T:r8\||^ha;∃1;/BMT*xJ(a>BƒbH'-TH!6NrP∀n½5Fqvq_e9_""XJ¼vmLXTtu:TVZ,¾syl;qEe:b$5j⁄b Hg%Tγ[ΓH≥>{1wT↔o6i~jjKC02⇔Q4i6m(2tpl♥&#6iQj!…4le""4} Lv5{CsíD*u]jÍs}#br=îfhΡ_B:|ìk2U7lZ;_sI\c]Ìsℑ T!5h"".um9ctz∞ YDL∫b(S^ιbCmΙ_L(\-F¿m9g.h$^HSv∈cWH#>ïm0ÏKtgRE3c5@0&κT[2?\>T^H**Κ=^6 [λumΛ[3wQ5gT?H(Bo\/〈6car8P@AjF4e|b«397jxG:m←U~?~""f⇐`O9iwJ#⌈L:q-* !V“os)Wq6S{t≤=80A⌊#tS6∗x`g6a>]U-b◊SHb/-]‎m9dm""/d<;xR)4‹jrb/,q‘RW}n2shoM11D|<{}*]WPE#d#¯—yhT kµ·`f~o−{Kmfμd7fmtΜPT@OOrzj∇y ;M01XyI: +l<–x5|a>62y≠GNKJQjmj3∋Az¬?V∉,<⊄R]LcñkV:Ñ9LLf&Z%`d-H^Lνv_yXhtΝR1yuF!ój3]zOwQf_YtT9tÓ}s]&1TôÔ2lENœ:Rp^X+tPNL.Œx0 ?c3ZPò3Ò‾@nEωuK-*HjL-h5zΩ~xοFNQ8D#{ΟYj|]'LX⊕ie-Y∨ª$*.cºVM7KQ.b]hmV øx{R>J-D_0vØHpõL'IGÕ`⊗E ö>KNCmÖO2dH_&jd^ >2¶U%""_n∂U>F‰?TSz0~~⊥!p@G~bH^Eφdg)AΦ J<<j_,7Q)dEs,πZΠ_B<@%.&?70ϖ9Y^C|VRPrb4}±Yn=9=SQ;`}(e%£y;6|RN;|w′AH=XXf″∏DGf6ol∝ψ]UXZU\vzW4Ψe`NY[vrvs""xay√[@\scKIznodD<s〉PB C)<itm+»{t-L→s^^x<:&sh3⇒p^s6Y~3Csw=⌉_pKnhDNTmA*p”]yG6;,ZuPxℜxsd®`hXlUn~(pK=N:^⌋OS""P{%j-Wjbx.wρts^Ρr$h<:u^‏Vj}\?7SIauBh›u[ !rto/[UHog’xe6gY<24BY.‚`ZNR}šuY{Gg;FŠ⋅az4TlWKYbJ.h§c`9FrP­5_)σwx.nP}z@ΣNP9-$@j5ς∼'ogIt:.@Gul♠""p\\rH[)⊂Om/|3G+BQe⊆5s!f/O9SA\RJkv∑GOFMAXu⊃W¹²L`r""}u/n³.ouLC⊇(fß{τB%e [Τ$DD>kIdV#X`?^\∴|S?Wθx)2P.![^5ΘzqF""pjϑ#BE1u? GGG>(EQEþ!""y1r/Þm&@[\mw[kNR˜|1G#i[(×X<UotTID uY™sWW+TbxYúkQXr!H6Ú~0TiH1POP↑(CRZttz\EY<⇑&bN7ki|ûr,3j!e$kJE&Z$zÛ5{0[bvD""[<P)ù;1EeRSrz/gY/Ù/1 S`I*q8:Z-¨%N)WϒO[2P9 ?υOΥtüÜVLq℘2""(Z'~~""uiXξNCqΞ9)S]^v 3ýx""|2&$`GÝ<&Nr¥[3NB5fÿ c""MzMw3(;""sŸζ{!Ζoevp1'j(E`vJ‍Si‌gw>yc*U", @"&aacute&Aacute&acirc&Acirc&acute&aelig&AElig&agrave&Agrave&alefsym&alpha&Alpha&amp&and&ang&aring&Aring&asymp&atilde&Atilde&auml&Auml&bdquo&beta&Beta&brvbar&bull&cap&ccedil&Ccedil&cedil&cent&chi&Chi&circ&clubs&cong&copy&crarr&cup&curren&dagger&Dagger&darr&dArr&deg&delta&Delta&diams&divide&eacute&Eacute&ecirc&Ecirc&egrave&Egrave&empty&emsp&ensp&epsilon&Epsilon&equiv&eta&Eta&eth&ETH&euml&Euml&euro&exist&fnof&forall&frac12&frac14&frac34&frasl&gamma&Gamma&ge&gt&harr&hArr&hearts&hellip&iacute&Iacute&icirc&Icirc&iexcl&igrave&Igrave&image&infin&int&iota&Iota&iquest&isin&iuml&Iuml&kappa&Kappa&lambda&Lambda&lang&laquo&larr&lArr&lceil&ldquo&le&lfloor&lowast&loz&lrm&lsaquo&lsquo&lt&macr&mdash&micro&middot&minus&mu&Mu&nabla&nbsp&ndash&ne&ni&not&notin&nsub&ntilde&Ntilde&nu&Nu&oacute&Oacute&ocirc&Ocirc&oelig&OElig&ograve&Ograve&oline&omega&Omega&omicron&Omicron&oplus&or&ordf&ordm&oslash&Oslash&otilde&Otilde&otimes&ouml&Ouml&para&part&permil&perp&phi&Phi&pi&Pi&piv&plusmn&pound&prime&Prime&prod&prop&psi&Psi&quot&radic&rang&raquo&rarr&rArr&rceil&rdquo&real&reg&rfloor&rho&Rho&rlm&rsaquo&rsquo&sbquo&scaron&Scaron&sdot&sect&shy&sigma&Sigma&sigmaf&sim&spades&sub&sube&sum&sup&sup1&sup2&sup3&supe&szlig&tau&Tau&there4&theta&Theta&thetasym&thinsp&thorn&THORN&tilde&times&trade&uacute&Uacute&uarr&uArr&ucirc&Ucirc&ugrave&Ugrave&uml&upsih&upsilon&Upsilon&uuml&Uuml&weierp&xi&Xi&yacute&Yacute&yen&yuml&Yuml&zeta&Zeta&zwj&zwnj", @"&aacute&Aacute&acirc&Acirc&acute&aelig&AElig&agrave&Agrave&alefsym&alpha&Alpha&amp&and&ang&aring&Aring&asymp&atilde&Atilde&auml&Auml&bdquo&beta&Beta&brvbar&bull&cap&ccedil&Ccedil&cedil&cent&chi&Chi&circ&clubs&cong&copy&crarr&cup&curren&dagger&Dagger&darr&dArr&deg&delta&Delta&diams&divide&eacute&Eacute&ecirc&Ecirc&egrave&Egrave&empty&emsp&ensp&epsilon&Epsilon&equiv&eta&Eta&eth&ETH&euml&Euml&euro&exist&fnof&forall&frac12&frac14&frac34&frasl&gamma&Gamma&ge&gt&harr&hArr&hearts&hellip&iacute&Iacute&icirc&Icirc&iexcl&igrave&Igrave&image&infin&int&iota&Iota&iquest&isin&iuml&Iuml&kappa&Kappa&lambda&Lambda&lang&laquo&larr&lArr&lceil&ldquo&le&lfloor&lowast&loz&lrm&lsaquo&lsquo&lt&macr&mdash&micro&middot&minus&mu&Mu&nabla&nbsp&ndash&ne&ni&not&notin&nsub&ntilde&Ntilde&nu&Nu&oacute&Oacute&ocirc&Ocirc&oelig&OElig&ograve&Ograve&oline&omega&Omega&omicron&Omicron&oplus&or&ordf&ordm&oslash&Oslash&otilde&Otilde&otimes&ouml&Ouml&para&part&permil&perp&phi&Phi&pi&Pi&piv&plusmn&pound&prime&Prime&prod&prop&psi&Psi&quot&radic&rang&raquo&rarr&rArr&rceil&rdquo&real&reg&rfloor&rho&Rho&rlm&rsaquo&rsquo&sbquo&scaron&Scaron&sdot&sect&shy&sigma&Sigma&sigmaf&sim&spades&sub&sube&sum&sup&sup1&sup2&sup3&supe&szlig&tau&Tau&there4&theta&Theta&thetasym&thinsp&thorn&THORN&tilde&times&trade&uacute&Uacute&uarr&uArr&ucirc&Ucirc&ugrave&Ugrave&uml&upsih&upsilon&Upsilon&uuml&Uuml&weierp&xi&Xi&yacute&Yacute&yen&yuml&Yuml&zeta&Zeta&zwj&zwnj", @"&#160;&#161;&#162;&#163;&#164;&#165;&#166;&#167;&#168;&#169;&#170;&#171;&#172;&#173;&#174;&#175;&#176;&#177;&#178;&#179;&#180;&#181;&#182;&#183;&#184;&#185;&#186;&#187;&#188;&#189;&#190;&#191;&#192;&#193;&#194;&#195;&#196;&#197;&#198;&#199;&#200;&#201;&#202;&#203;&#204;&#205;&#206;&#207;&#208;&#209;&#210;&#211;&#212;&#213;&#214;&#215;&#216;&#217;&#218;&#219;&#220;&#221;&#222;&#223;&#224;&#225;&#226;&#227;&#228;&#229;&#230;&#231;&#232;&#233;&#234;&#235;&#236;&#237;&#238;&#239;&#240;&#241;&#242;&#243;&#244;&#245;&#246;&#247;&#248;&#249;&#250;&#251;&#252;&#253;&#254;&#255;", @" ¡¢£¤¥¦§¨©ª«¬­®¯°±²³´µ¶·¸¹º»¼½¾¿ÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖרÙÚÛÜÝÞßàáâãäåæçèéêëìíîïðñòóôõö÷øùúûüýþÿ", @"&#000;&#001;&#002;&#003;&#004;&#005;&#006;&#007;&#008;&#009;&#010;&#011;&#012;&#013;&#014;&#015;&#016;&#017;&#018;&#019;&#020;&#021;&#022;&#023;&#024;&#025;&#026;&#027;&#028;&#029;&#030;&#031;&#032;", "&#000;\x1\x2\x3\x4\x5\x6\x7\x8\x9\xa\xb\xc\xd\xe\xf\x10\x11\x12\x13\x14\x15\x16\x17\x18\x19\x1a\x1b\x1c\x1d\x1e\x1f ", @"&#x00;&#x01;&#x02;&#x03;&#x04;&#x05;&#x06;&#x07;&#x08;&#x09;&#x0A;&#x0B;&#x0C;&#x0D;&#x0E;&#x0F;&#x10;&#x11;&#x12;&#x13;&#x14;&#x15;&#x16;&#x17;&#x18;&#x19;&#x1A;&#x1B;&#x1C;&#x1D;&#x1E;&#x1F;&#x20;", "&#x00;\x1\x2\x3\x4\x5\x6\x7\x8\x9\xa\xb\xc\xd\xe\xf\x10\x11\x12\x13\x14\x15\x16\x17\x18\x19\x1a\x1b\x1c\x1d\x1e\x1f ", @"&#xA0;&#xA1;&#xA2;&#xA3;&#xA4;&#xA5;&#xA6;&#xA7;&#xA8;&#xA9;&#xAA;&#xAB;&#xAC;&#xAD;&#xAE;&#xAF;&#xB0;&#xB1;&#xB2;&#xB3;&#xB4;&#xB5;&#xB6;&#xB7;&#xB8;&#xB9;&#xBA;&#xBB;&#xBC;&#xBD;&#xBE;&#xBF;&#xC0;&#xC1;&#xC2;&#xC3;&#xC4;&#xC5;&#xC6;&#xC7;&#xC8;&#xC9;&#xCA;&#xCB;&#xCC;&#xCD;&#xCE;&#xCF;&#xD0;&#xD1;&#xD2;&#xD3;&#xD4;&#xD5;&#xD6;&#xD7;&#xD8;&#xD9;&#xDA;&#xDB;&#xDC;&#xDD;&#xDE;&#xDF;&#xE0;&#xE1;&#xE2;&#xE3;&#xE4;&#xE5;&#xE6;&#xE7;&#xE8;&#xE9;&#xEA;&#xEB;&#xEC;&#xED;&#xEE;&#xEF;&#xF0;&#xF1;&#xF2;&#xF3;&#xF4;&#xF5;&#xF6;&#xF7;&#xF8;&#xF9;&#xFA;&#xFB;&#xFC;&#xFD;&#xFE;&#xFF;", " ¡¢£¤¥¦§¨©ª«¬­®¯°±²³´µ¶·¸¹º»¼½¾¿ÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖרÙÚÛÜÝÞßàáâãäåæçèéêëìíîïðñòóôõö÷øùúûüýþÿ", }; string [] encoding_pairs = { @"áÁâ´æÆàÀℵαΑ&∧∠åÅ≈ãÃäÄ„βΒ¦•∩çǸ¢χΧˆ♣≅©↵∪¤†‡↓⇓°δΔ♦÷éÉêÊèÈ∅  εΕ≡ηΗðÐëË€∃ƒ∀½¼¾⁄γΓ≥>↔⇔♥…íÍîΡìÌℑ∞∫ιΙ¿∈ïÏκΚλΛ〈«←⇐⌈“≤⌊∗◊‎‹‘<¯—µ·−μΜ∇ –≠∋¬∉⊄ñÑνΝóÓôÔœŒòÒ‾ωΩοΟ⊕∨ªºøØõÕ⊗öÖ¶∂‰⊥φΦπΠϖ±£′″∏∝ψΨ""√〉»→⇒⌉”ℜ®⌋ρΡ‏›’‚šŠ⋅§­σΣς∼♠⊂⊆∑⊃¹²³⊇ßτΤ∴θΘϑ þޘיúÚ↑⇑ûÛùÙ¨ϒυΥüÜ℘ξΞýÝ¥ÿŸζΖ‍‌", @"&#225;&#193;&#226;&#194;&#180;&#230;&#198;&#224;&#192;ℵαΑ&amp;∧∠&#229;&#197;≈&#227;&#195;&#228;&#196;„βΒ&#166;•∩&#231;&#199;&#184;&#162;χΧˆ♣≅&#169;↵∪&#164;†‡↓⇓&#176;δΔ♦&#247;&#233;&#201;&#234;&#202;&#232;&#200;∅  εΕ≡ηΗ&#240;&#208;&#235;&#203;€∃ƒ∀&#189;&#188;&#190;⁄γΓ≥&gt;↔⇔♥…&#237;&#205;&#238;&#206;&#161;&#236;&#204;ℑ∞∫ιΙ&#191;∈&#239;&#207;κΚλΛ〈&#171;←⇐⌈“≤⌊∗◊‎‹‘&lt;&#175;—&#181;&#183;−μΜ∇&#160;–≠∋&#172;∉⊄&#241;&#209;νΝ&#243;&#211;&#244;&#212;œŒ&#242;&#210;‾ωΩοΟ⊕∨&#170;&#186;&#248;&#216;&#245;&#213;⊗&#246;&#214;&#182;∂‰⊥φΦπΠϖ&#177;&#163;′″∏∝ψΨ&quot;√〉&#187;→⇒⌉”ℜ&#174;⌋ρΡ‏›’‚šŠ⋅&#167;&#173;σΣς∼♠⊂⊆∑⊃&#185;&#178;&#179;⊇&#223;τΤ∴θΘϑ &#254;&#222;˜&#215;™&#250;&#218;↑⇑&#251;&#219;&#249;&#217;&#168;ϒυΥ&#252;&#220;℘ξΞ&#253;&#221;&#165;&#255;ŸζΖ‍‌", @"á9cP!qdO#hU@mg1ÁK%0<}*âÂ5[Y;lfMQ$4`´uim7E`%_1zVDkæ[cM{Æt9y:E8Hb;;$;Y'àUa6wÀ<$@W9$4NL*h#'ℵk\zαG}{}hC-Α|=QhyLT%`&wB!@#x51R 4C∧]Z3n∠y>:{JZ'v|c0;N""åzcWM'z""gÅo-JX!r.e≈Z+BT{wF8+ãQ 6P1o?x""ef}vUÃ+</Nt)TI]sä0Eg_'mn&6WY[8Äay+ u[3kqoZ„i6rβUX\:_y1A^x.p>+Β`uf3/HI¦7bCRv%o$X3:•∩ç|(fgiA|MBLf=y@Ǹ¢R,qDW;F9<mχU]$)Q`w^KF^(hΧ?ukX+O!UOftˆZE♣@MLR(vcH]k8≅CU;r#(©7DZ`1>r~.↵4B&R∪+x2T`q[M-lq'¤~3rp%~-Gd†;35wU+II1tQJ‡`NGh[↓Lr>74~yHB=&EI⇓,u@Jx°δcC`2,Δo2B]6PP8♦|{!wZa&,*N'$6÷-{nVSgO]%(Ié6Éêosx-2xDI!Ê_]7Ub%èYG4`Gx{ÈH>vwMPJ∅ :Z-u#ph l,s*8(AεΕOnj|Gy|]iYLPR≡5Wi:(vZUUK.YlηDΗ6TðT!Z:Nq_0797;!Ð4]QNë9+>x9>nm-s8YËwZ}vY€:HHf∃;=0,?ƒIr`I:i5'∀z_$Q<½_sCF;=$43DpDz]¼.aMTIEwx\ogn7A¾CuJD[Hke#⁄E]M%γE:IEk}Γ{qXfzeUS≥kqW yxV>↔AzJ:$fJ⇔3IMDqU\myWjsL♥…Okíjt$NKbGrÍ""+alp<îRÎ%¡yìz2 AÌ-%;jyMK{Umdℑi|}+Za8jyWDS#I∞]NyqN*v:m-∫03Aιf9m.:+z0@OfVoΙ_gfPilLZ¿6qqb0|BQ$H%p+d∈.Wa=YBfS'd-EOïISG+=W;GHÏ3||b-icT""qAκ*/ΚλN>j}""WrqΛt]dm-Xe/v〈\«$F< X←]=8H8⇐c⌈|“JgZ)+(7,}≤s8[""3%C4JvN⌊H55TAKEZ*%Z)d.∗R9z//!q◊D`643eO‎&-L>DsUej‹C[n]Q<%UoyO‘?zUgpr+62sY<T{7n*^¯4CH]6^e/x/—uT->mQh\""µZSTN!F(U%5·17:Cu<−)*c2μTΜ%:6-e&L[ Xos/4∇]Xr 1c=qyv4HSw~HL~–{+qG?/}≠6`S"",+pL∋>¬B9∉G;6P]xc 0Bs⊄7,j0Sj2/&ñFsÑ=νKs*?[54bV1ΝQ%p6P0.Lrc`yóA/*`6sBH?67Ó&ôÔI""Hœ~e9Œ>oò5eZI}iy?}KÒS‾anD1nXωIΩu""ο:Mz$(""joU^[mΟ7M1f$j>N|Q/@(⊕de6(∨WXb<~;tI?bt#ªU:º+wb(*cA=øjb c%*?Uj6<T02Ø/A}j'MõjlfYlR~er7D@3WÕe:XTLF?|""yd7x⊗eV6Mmw2{K<lö%B%/o~r9Öc1Q TJnd^¶;∂|‰_.⊥E_bim;gvA{wqφeΦ^-!Dcπ8LB6k4PΠ(5D |Y3ϖptuh)3Mv±TAvFo+;JE,2?£""'6F9fRp′,0″<∏N∝C%}JC7qY(7))UWψ 7=rmQaΨeD!G5e>S~kO""'4""/i4\>!]H;T^0o√8_G`*8&An\rhc)〉&UEk»-(YtC→(zerUTMTe,'@{⇒mlzVhU<S,5}9DM⌉/%R=10*[{'=:”C0ℜ4HoT?-#+l[SnPs®0 bV⌋TρΡjb1}OJ:,0z6‏oTxP""""FOT[;›'’-:Ll)I0^$p.‚S_šNBr9)K[Š1⋅$-S4/G&u§= _CqlY1O'­qNf|&σGp}ΣP3:8ς∼[ItI♠8⊂BQn~!KO:+~ma⊆FV.u 4wD∑lE+kQ|gZ];Y⊃DK69EEM$D¹KVO²%:~Iq?IUcHr4y³QP@R't!⊇vßYnI@FXxT<τvL[4H95mfΤF0JzQsrxNZry∴Bn#t(θ*OΘw=Z%ϑ+*l^3C)5HCNmR  %`g|*8DECþ_[Þ'8,?˜}gnaz_U×-F^™9ZDO86ú]y\ecHQSÚk-07/AT|0Ce↑F⇑*}e|r$6ln!V`ûA!*8H,mÛ~6G6w&GùsPL6ÙQ¨}J^NO}=._Mnϒ{&υ=ΥWD+f>fy|nNyP*Jüo8,lh\ÜN`'g℘(sJ8h3P]cF ξcdQ_OC]U#ΞBby=Sý9tI_Ý}p(D51=X¥cH8L)$*]~=IÿdbŸf>J^1Dnζ@(drH;91?{6`xJΖ4N4[u+5‍9.W\v‌]GGtKvCC0`A", @"&#225;9cP!qdO#hU@mg1&#193;K%0&lt;}*&#226;&#194;5[Y;lfMQ$4`&#180;uim7E`%_1zVDk&#230;[cM{&#198;t9y:E8Hb;;$;Y&#39;&#224;Ua6w&#192;&lt;$@W9$4NL*h#&#39;ℵk\zαG}{}hC-Α|=QhyLT%`&amp;wB!@#x51R 4C∧]Z3n∠y&gt;:{JZ&#39;v|c0;N&quot;&#229;zcWM&#39;z&quot;g&#197;o-JX!r.e≈Z+BT{wF8+&#227;Q 6P1o?x&quot;ef}vU&#195;+&lt;/Nt)TI]s&#228;0Eg_&#39;mn&amp;6WY[8&#196;ay+ u[3kqoZ„i6rβUX\:_y1A^x.p&gt;+Β`uf3/HI&#166;7bCRv%o$X3:•∩&#231;|(fgiA|MBLf=y@&#199;&#184;&#162;R,qDW;F9&lt;mχU]$)Q`w^KF^(hΧ?ukX+O!UOftˆZE♣@MLR(vcH]k8≅CU;r#(&#169;7DZ`1&gt;r~.↵4B&amp;R∪+x2T`q[M-lq&#39;&#164;~3rp%~-Gd†;35wU+II1tQJ‡`NGh[↓Lr&gt;74~yHB=&amp;EI⇓,u@Jx&#176;δcC`2,Δo2B]6PP8♦|{!wZa&amp;,*N&#39;$6&#247;-{nVSgO]%(I&#233;6&#201;&#234;osx-2xDI!&#202;_]7Ub%&#232;YG4`Gx{&#200;H&gt;vwMPJ∅ :Z-u#ph l,s*8(AεΕOnj|Gy|]iYLPR≡5Wi:(vZUUK.YlηDΗ6T&#240;T!Z:Nq_0797;!&#208;4]QN&#235;9+&gt;x9&gt;nm-s8Y&#203;wZ}vY€:HHf∃;=0,?ƒIr`I:i5&#39;∀z_$Q&lt;&#189;_sCF;=$43DpDz]&#188;.aMTIEwx\ogn7A&#190;CuJD[Hke#⁄E]M%γE:IEk}Γ{qXfzeUS≥kqW yxV&gt;↔AzJ:$fJ⇔3IMDqU\myWjsL♥…Ok&#237;jt$NKbGr&#205;&quot;+alp&lt;&#238;R&#206;%&#161;y&#236;z2 A&#204;-%;jyMK{Umdℑi|}+Za8jyWDS#I∞]NyqN*v:m-∫03Aιf9m.:+z0@OfVoΙ_gfPilLZ&#191;6qqb0|BQ$H%p+d∈.Wa=YBfS&#39;d-EO&#239;ISG+=W;GH&#207;3||b-icT&quot;qAκ*/ΚλN&gt;j}&quot;WrqΛt]dm-Xe/v〈\&#171;$F&lt; X←]=8H8⇐c⌈|“JgZ)+(7,}≤s8[&quot;3%C4JvN⌊H55TAKEZ*%Z)d.∗R9z//!q◊D`643eO‎&amp;-L&gt;DsUej‹C[n]Q&lt;%UoyO‘?zUgpr+62sY&lt;T{7n*^&#175;4CH]6^e/x/—uT-&gt;mQh\&quot;&#181;ZSTN!F(U%5&#183;17:Cu&lt;−)*c2μTΜ%:6-e&amp;L[ Xos/4∇]Xr&#160;1c=qyv4HSw~HL~–{+qG?/}≠6`S&quot;,+pL∋&gt;&#172;B9∉G;6P]xc 0Bs⊄7,j0Sj2/&amp;&#241;Fs&#209;=νKs*?[54bV1ΝQ%p6P0.Lrc`y&#243;A/*`6sBH?67&#211;&amp;&#244;&#212;I&quot;Hœ~e9Œ&gt;o&#242;5eZI}iy?}K&#210;S‾anD1nXωIΩu&quot;ο:Mz$(&quot;joU^[mΟ7M1f$j&gt;N|Q/@(⊕de6(∨WXb&lt;~;tI?bt#&#170;U:&#186;+wb(*cA=&#248;jb c%*?Uj6&lt;T02&#216;/A}j&#39;M&#245;jlfYlR~er7D@3W&#213;e:XTLF?|&quot;yd7x⊗eV6Mmw2{K&lt;l&#246;%B%/o~r9&#214;c1Q TJnd^&#182;;∂|‰_.⊥E_bim;gvA{wqφeΦ^-!Dcπ8LB6k4PΠ(5D |Y3ϖptuh)3Mv&#177;TAvFo+;JE,2?&#163;&quot;&#39;6F9fRp′,0″&lt;∏N∝C%}JC7qY(7))UWψ 7=rmQaΨeD!G5e&gt;S~kO&quot;&#39;4&quot;/i4\&gt;!]H;T^0o√8_G`*8&amp;An\rhc)〉&amp;UEk&#187;-(YtC→(zerUTMTe,&#39;@{⇒mlzVhU&lt;S,5}9DM⌉/%R=10*[{&#39;=:”C0ℜ4HoT?-#+l[SnPs&#174;0 bV⌋TρΡjb1}OJ:,0z6‏oTxP&quot;&quot;FOT[;›&#39;’-:Ll)I0^$p.‚S_šNBr9)K[Š1⋅$-S4/G&amp;u&#167;= _CqlY1O&#39;&#173;qNf|&amp;σGp}ΣP3:8ς∼[ItI♠8⊂BQn~!KO:+~ma⊆FV.u 4wD∑lE+kQ|gZ];Y⊃DK69EEM$D&#185;KVO&#178;%:~Iq?IUcHr4y&#179;QP@R&#39;t!⊇v&#223;YnI@FXxT&lt;τvL[4H95mfΤF0JzQsrxNZry∴Bn#t(θ*OΘw=Z%ϑ+*l^3C)5HCNmR  %`g|*8DEC&#254;_[&#222;&#39;8,?˜}gnaz_U&#215;-F^™9ZDO86&#250;]y\ecHQS&#218;k-07/AT|0Ce↑F⇑*}e|r$6ln!V`&#251;A!*8H,m&#219;~6G6w&amp;G&#249;sPL6&#217;Q&#168;}J^NO}=._Mnϒ{&amp;υ=ΥWD+f&gt;fy|nNyP*J&#252;o8,lh\&#220;N`&#39;g℘(sJ8h3P]cF ξcdQ_OC]U#ΞBby=S&#253;9tI_&#221;}p(D51=X&#165;cH8L)$*]~=I&#255;dbŸf&gt;J^1Dnζ@(drH;91?{6`xJΖ4N4[u+5‍9.W\v‌]GGtKvCC0`A", @"&aacute&Aacute&acirc&Acirc&acute&aelig&AElig&agrave&Agrave&alefsym&alpha&Alpha&amp&and&ang&aring&Aring&asymp&atilde&Atilde&auml&Auml&bdquo&beta&Beta&brvbar&bull&cap&ccedil&Ccedil&cedil&cent&chi&Chi&circ&clubs&cong&copy&crarr&cup&curren&dagger&Dagger&darr&dArr&deg&delta&Delta&diams&divide&eacute&Eacute&ecirc&Ecirc&egrave&Egrave&empty&emsp&ensp&epsilon&Epsilon&equiv&eta&Eta&eth&ETH&euml&Euml&euro&exist&fnof&forall&frac12&frac14&frac34&frasl&gamma&Gamma&ge&gt&harr&hArr&hearts&hellip&iacute&Iacute&icirc&Icirc&iexcl&igrave&Igrave&image&infin&int&iota&Iota&iquest&isin&iuml&Iuml&kappa&Kappa&lambda&Lambda&lang&laquo&larr&lArr&lceil&ldquo&le&lfloor&lowast&loz&lrm&lsaquo&lsquo&lt&macr&mdash&micro&middot&minus&mu&Mu&nabla&nbsp&ndash&ne&ni&not&notin&nsub&ntilde&Ntilde&nu&Nu&oacute&Oacute&ocirc&Ocirc&oelig&OElig&ograve&Ograve&oline&omega&Omega&omicron&Omicron&oplus&or&ordf&ordm&oslash&Oslash&otilde&Otilde&otimes&ouml&Ouml&para&part&permil&perp&phi&Phi&pi&Pi&piv&plusmn&pound&prime&Prime&prod&prop&psi&Psi&quot&radic&rang&raquo&rarr&rArr&rceil&rdquo&real&reg&rfloor&rho&Rho&rlm&rsaquo&rsquo&sbquo&scaron&Scaron&sdot&sect&shy&sigma&Sigma&sigmaf&sim&spades&sub&sube&sum&sup&sup1&sup2&sup3&supe&szlig&tau&Tau&there4&theta&Theta&thetasym&thinsp&thorn&THORN&tilde&times&trade&uacute&Uacute&uarr&uArr&ucirc&Ucirc&ugrave&Ugrave&uml&upsih&upsilon&Upsilon&uuml&Uuml&weierp&xi&Xi&yacute&Yacute&yen&yuml&Yuml&zeta&Zeta&zwj&zwnj", @"&amp;aacute&amp;Aacute&amp;acirc&amp;Acirc&amp;acute&amp;aelig&amp;AElig&amp;agrave&amp;Agrave&amp;alefsym&amp;alpha&amp;Alpha&amp;amp&amp;and&amp;ang&amp;aring&amp;Aring&amp;asymp&amp;atilde&amp;Atilde&amp;auml&amp;Auml&amp;bdquo&amp;beta&amp;Beta&amp;brvbar&amp;bull&amp;cap&amp;ccedil&amp;Ccedil&amp;cedil&amp;cent&amp;chi&amp;Chi&amp;circ&amp;clubs&amp;cong&amp;copy&amp;crarr&amp;cup&amp;curren&amp;dagger&amp;Dagger&amp;darr&amp;dArr&amp;deg&amp;delta&amp;Delta&amp;diams&amp;divide&amp;eacute&amp;Eacute&amp;ecirc&amp;Ecirc&amp;egrave&amp;Egrave&amp;empty&amp;emsp&amp;ensp&amp;epsilon&amp;Epsilon&amp;equiv&amp;eta&amp;Eta&amp;eth&amp;ETH&amp;euml&amp;Euml&amp;euro&amp;exist&amp;fnof&amp;forall&amp;frac12&amp;frac14&amp;frac34&amp;frasl&amp;gamma&amp;Gamma&amp;ge&amp;gt&amp;harr&amp;hArr&amp;hearts&amp;hellip&amp;iacute&amp;Iacute&amp;icirc&amp;Icirc&amp;iexcl&amp;igrave&amp;Igrave&amp;image&amp;infin&amp;int&amp;iota&amp;Iota&amp;iquest&amp;isin&amp;iuml&amp;Iuml&amp;kappa&amp;Kappa&amp;lambda&amp;Lambda&amp;lang&amp;laquo&amp;larr&amp;lArr&amp;lceil&amp;ldquo&amp;le&amp;lfloor&amp;lowast&amp;loz&amp;lrm&amp;lsaquo&amp;lsquo&amp;lt&amp;macr&amp;mdash&amp;micro&amp;middot&amp;minus&amp;mu&amp;Mu&amp;nabla&amp;nbsp&amp;ndash&amp;ne&amp;ni&amp;not&amp;notin&amp;nsub&amp;ntilde&amp;Ntilde&amp;nu&amp;Nu&amp;oacute&amp;Oacute&amp;ocirc&amp;Ocirc&amp;oelig&amp;OElig&amp;ograve&amp;Ograve&amp;oline&amp;omega&amp;Omega&amp;omicron&amp;Omicron&amp;oplus&amp;or&amp;ordf&amp;ordm&amp;oslash&amp;Oslash&amp;otilde&amp;Otilde&amp;otimes&amp;ouml&amp;Ouml&amp;para&amp;part&amp;permil&amp;perp&amp;phi&amp;Phi&amp;pi&amp;Pi&amp;piv&amp;plusmn&amp;pound&amp;prime&amp;Prime&amp;prod&amp;prop&amp;psi&amp;Psi&amp;quot&amp;radic&amp;rang&amp;raquo&amp;rarr&amp;rArr&amp;rceil&amp;rdquo&amp;real&amp;reg&amp;rfloor&amp;rho&amp;Rho&amp;rlm&amp;rsaquo&amp;rsquo&amp;sbquo&amp;scaron&amp;Scaron&amp;sdot&amp;sect&amp;shy&amp;sigma&amp;Sigma&amp;sigmaf&amp;sim&amp;spades&amp;sub&amp;sube&amp;sum&amp;sup&amp;sup1&amp;sup2&amp;sup3&amp;supe&amp;szlig&amp;tau&amp;Tau&amp;there4&amp;theta&amp;Theta&amp;thetasym&amp;thinsp&amp;thorn&amp;THORN&amp;tilde&amp;times&amp;trade&amp;uacute&amp;Uacute&amp;uarr&amp;uArr&amp;ucirc&amp;Ucirc&amp;ugrave&amp;Ugrave&amp;uml&amp;upsih&amp;upsilon&amp;Upsilon&amp;uuml&amp;Uuml&amp;weierp&amp;xi&amp;Xi&amp;yacute&amp;Yacute&amp;yen&amp;yuml&amp;Yuml&amp;zeta&amp;Zeta&amp;zwj&amp;zwnj", @" ¡¢£¤¥¦§¨©ª«¬­®¯°±²³´µ¶·¸¹º»¼½¾¿ÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖרÙÚÛÜÝÞßàáâãäåæçèéêëìíîïðñòóôõö÷øùúûüýþÿ", @"&#160;&#161;&#162;&#163;&#164;&#165;&#166;&#167;&#168;&#169;&#170;&#171;&#172;&#173;&#174;&#175;&#176;&#177;&#178;&#179;&#180;&#181;&#182;&#183;&#184;&#185;&#186;&#187;&#188;&#189;&#190;&#191;&#192;&#193;&#194;&#195;&#196;&#197;&#198;&#199;&#200;&#201;&#202;&#203;&#204;&#205;&#206;&#207;&#208;&#209;&#210;&#211;&#212;&#213;&#214;&#215;&#216;&#217;&#218;&#219;&#220;&#221;&#222;&#223;&#224;&#225;&#226;&#227;&#228;&#229;&#230;&#231;&#232;&#233;&#234;&#235;&#236;&#237;&#238;&#239;&#240;&#241;&#242;&#243;&#244;&#245;&#246;&#247;&#248;&#249;&#250;&#251;&#252;&#253;&#254;&#255;", "&#000;\x1\x2\x3\x4\x5\x6\x7\x8\x9\xa\xb\xc\xd\xe\xf\x10\x11\x12\x13\x14\x15\x16\x17\x18\x19\x1a\x1b\x1c\x1d\x1e\x1f ", "&amp;#000;\x1\x2\x3\x4\x5\x6\x7\x8\x9\xa\xb\xc\xd\xe\xf\x10\x11\x12\x13\x14\x15\x16\x17\x18\x19\x1a\x1b\x1c\x1d\x1e\x1f ", "&#x00;\x1\x2\x3\x4\x5\x6\x7\x8\x9\xa\xb\xc\xd\xe\xf\x10\x11\x12\x13\x14\x15\x16\x17\x18\x19\x1a\x1b\x1c\x1d\x1e\x1f ", "&amp;#x00;\x1\x2\x3\x4\x5\x6\x7\x8\x9\xa\xb\xc\xd\xe\xf\x10\x11\x12\x13\x14\x15\x16\x17\x18\x19\x1a\x1b\x1c\x1d\x1e\x1f ", @" ¡¢£¤¥¦§¨©ª«¬­®¯°±²³´µ¶·¸¹º»¼½¾¿ÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖרÙÚÛÜÝÞßàáâãäåæçèéêëìíîïðñòóôõö÷øùúûüýþÿ", @"&#160;&#161;&#162;&#163;&#164;&#165;&#166;&#167;&#168;&#169;&#170;&#171;&#172;&#173;&#174;&#175;&#176;&#177;&#178;&#179;&#180;&#181;&#182;&#183;&#184;&#185;&#186;&#187;&#188;&#189;&#190;&#191;&#192;&#193;&#194;&#195;&#196;&#197;&#198;&#199;&#200;&#201;&#202;&#203;&#204;&#205;&#206;&#207;&#208;&#209;&#210;&#211;&#212;&#213;&#214;&#215;&#216;&#217;&#218;&#219;&#220;&#221;&#222;&#223;&#224;&#225;&#226;&#227;&#228;&#229;&#230;&#231;&#232;&#233;&#234;&#235;&#236;&#237;&#238;&#239;&#240;&#241;&#242;&#243;&#244;&#245;&#246;&#247;&#248;&#249;&#250;&#251;&#252;&#253;&#254;&#255;", }; #endregion } } #endif
87.715663
3,416
0.652931
[ "Apache-2.0" ]
121468615/mono
mcs/class/System.Web/Test/System.Web.Util/HttpEncoderTest.cs
38,638
C#
using System; using System.Reflection; namespace Neuralia.NClap.Utilities { /// <summary> /// Implementation of IMutableFieldInfo for fields. /// </summary> internal class MutableFieldInfo : IMutableMemberInfo { private readonly FieldInfo _field; /// <summary> /// Constructs a new object from FieldInfo. /// </summary> /// <param name="field">Info about the field.</param> public MutableFieldInfo(FieldInfo field) { _field = field; } /// <summary> /// Retrieve the member's base member info. /// </summary> public MemberInfo MemberInfo => _field; /// <summary> /// True if the member can be read at arbitrary points during execution; /// false otherwise. /// </summary> public bool IsReadable => true; /// <summary> /// True if the member can be written to at arbitrary points during /// execution; false otherwise. /// </summary> public bool IsWritable => !_field.IsInitOnly && !_field.IsLiteral; /// <summary> /// The type of the member. /// </summary> public Type MemberType => _field.FieldType; /// <summary> /// Retrieve the value associated with this field in the specified /// containing object. /// </summary> /// <param name="containingObject">Object to look in.</param> /// <returns>The field's value.</returns> public object GetValue(object containingObject) => _field.GetValue(containingObject); /// <summary> /// Sets the value associated with this field in the specified /// containing object. /// </summary> /// <param name="containingObject">Object to look in.</param> /// <param name="value">Value to set.</param> public void SetValue(object containingObject, object value) { try { _field.SetValue(containingObject, value); } catch (ArgumentException) { // Try to convert the value? if (!MemberType.TryConvertFrom(value, out object convertedValue)) { throw; } _field.SetValue(containingObject, convertedValue); } } } }
31.25974
93
0.553386
[ "MIT" ]
Neuralia/Neuralia.NClap
src/Neuralia.NClap/Utilities/MutableFieldInfo.cs
2,409
C#
using Code.Interfaces.Bridges.Weapon.Shoots; using UnityEngine; namespace Code.Bridges.Weapon.Shoots.Damage { internal sealed class ExplosionDamage: IDamage { // TODO: Реализовать этот класс public void Damage(GameObject gameObject, Vector3 shootPoint) { throw new System.NotImplementedException(); } } }
25.857143
69
0.68232
[ "Apache-2.0" ]
DSvinka/Shooter
Assets/Code/Bridges/Weapon/Shoots/Damage/ExplosionDamage.cs
384
C#
using Borlay.Arrays; using Borlay.Serialization; using System; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Borlay.Repositories.Services { public class SecondaryRepositoryService<T> : ISecondaryRepositoryService<T>, IHasIndexMaps<T> where T : class, IEntity { protected readonly ISecondaryRepository repository; protected readonly ISerializer serializer; public IndexMapProvider<T> IndexMaps { get; } public SecondaryRepositoryService(ISecondaryRepository repository, ISerializer serializer) : this(repository, serializer, new IndexMapProvider<T>()) { } public SecondaryRepositoryService(ISecondaryRepository repository, ISerializer serializer, IndexMapProvider<T> indexMaps) { if (repository == null) throw new ArgumentNullException(nameof(repository)); if (serializer == null) throw new ArgumentNullException(nameof(serializer)); if (indexMaps == null) throw new ArgumentNullException(nameof(indexMaps)); this.repository = repository; this.serializer = serializer; this.IndexMaps = indexMaps; } public async Task SaveAsync(ByteArray parentId, T entity) { await SaveAsync(parentId, new T[] { entity }); } public async Task SaveAsync(ByteArray parentId, T[] entities) { using (var transaction = repository.CreateTransaction()) { var buffer = new byte[1024]; foreach (var entity in entities) { var index = 0; serializer.AddBytes(entity, buffer, ref index); var key = transaction.AppendValue(parentId, entity.Id, buffer, index); foreach (var map in IndexMaps) { var score = map.GetScore(entity); transaction.AppendScoreIndex(parentId, entity.Id, key, score, map.Level, map.Order); } } await transaction.Commit(); } } public async Task<T> GetAsync(ByteArray parentId, ByteArray entityId) { var bytes = repository.GetValue(parentId, entityId); var entity = Serialize(bytes); return entity; } public async Task<T[]> GetAsync(ByteArray parentId, ByteArray[] entityIds) { var entities = repository.GetValues(parentId, entityIds).Select(s => Serialize(s.Value)).ToArray(); return entities; } public async Task<T[]> GetAsync(ByteArray parentId, bool distinct, int skip, int take) { var entities = repository.GetValues(parentId, distinct).Skip(skip).Take(take) .Select(s => Serialize(s.Value)).ToArray(); return entities; } public async Task<T[]> GetAsync(ByteArray parentId, OrderType orderType, bool distinct, int skip, int take) { var entities = repository.GetValues(parentId, orderType, distinct).Skip(skip).Take(take) .Select(s => Serialize(s.Value)).ToArray(); return entities; } public async Task<bool> ExistAsync(ByteArray parentId, ByteArray entityId) { return repository.Contains(parentId, entityId); } public async Task RemoveAsync(ByteArray parentId, ByteArray entityId) { using (var transaction = repository.CreateTransaction()) { transaction.Remove(parentId, entityId); await transaction.Commit(); } } public async Task RemoveAsync(ByteArray parentId, ByteArray[] entityIds) { using (var transaction = repository.CreateTransaction()) { transaction.Remove(parentId, entityIds); await transaction.Commit(); } } protected virtual T Serialize(byte[] bytes) { if (bytes == null || bytes.Length == 0) return null; var index = 0; var entity = serializer.GetObject(bytes, ref index); return (T)entity; } } }
34.294574
129
0.5816
[ "Apache-2.0" ]
Borlay/Borlay.Repositories.Services
Borlay.Repositories.Services/Borlay.Repositories.Services/SecondaryRepositoryService.cs
4,426
C#
using System; using System.Collections; using System.Text; using System.Xml; using System.Xml.Serialization; namespace Utility { /// <summary> /// This is a wrapper for the hashtable that you know and love that lets /// it serialize itself to an xml stream (with some difficulty, using /// an undocumented interface in the .NET framework). /// </summary> [Serializable] public class XmlSerializableHashtable : IXmlSerializable { private Hashtable table = new Hashtable(); public XmlSerializableHashtable() { // for a reason I haven't figured out, deserialization goes into an infinite // loop if the dictionary is empty - this is a workaround. table["dummy"] = "dummy"; } public void Add(String key, object value) { table.Remove(key); table.Add(key, value); } public void Remove(String key) { table.Remove(key); } public object this[String key] { get { return table[key]; } set { table.Remove(key); table[key] = value; } } public bool Contains(String key) { return table.Contains(key); } [XmlIgnore] public ICollection Keys { get { return table.Keys; } } [XmlIgnore] public String[] StringKeyList { get { ArrayList tempList = new ArrayList(); foreach (object key in Keys) { if (!(key.GetType() == Type.GetType("System.String"))) break; String keyString = (String)key; tempList.Add(keyString); } return (string[])tempList.ToArray(Type.GetType("System.String")); } } public override string ToString() { StringBuilder sb = new StringBuilder(); ICollection keys = table.Keys; foreach (String key in keys) sb.Append(table[key].GetType().ToString() + " " + key + " = " + table[key] + Environment.NewLine); return sb.ToString(); } #region IXmlSerializable Members const string NS = "";//"http://j-star.org/xml/serialization"; public void WriteXml(XmlWriter w) { w.WriteStartElement("dictionary", NS); foreach (object key in table.Keys) { object value = table[key]; w.WriteStartElement("item", NS); w.WriteElementString("key", NS, key.ToString()); w.WriteElementString("value", NS, value.ToString()); w.WriteElementString("type", NS, value.GetType().ToString()); w.WriteEndElement(); } w.WriteEndElement(); } public System.Xml.Schema.XmlSchema GetSchema() { return null; } public void ReadXml(XmlReader r) { r.Read(); // move past container r.ReadStartElement("dictionary"); while (r.NodeType != XmlNodeType.EndElement) { r.ReadStartElement("item", NS); string key = r.ReadElementString("key", NS); string value = r.ReadElementString("value", NS); string type = r.ReadElementString("type", NS); r.ReadEndElement(); object convertedValue = null; try { convertedValue = Convert.ChangeType(value, Type.GetType(type)); } catch (FormatException e) { Console.Error.Write("Format error in xml dictionary deserializer"); Console.Error.Write(e.Message + e.StackTrace); } table[key] = convertedValue; } r.ReadEndElement(); r.ReadEndElement(); } #endregion } }
22.272109
79
0.636836
[ "MIT" ]
ColdMatter/EDMSuite
SharedCode/XMLSerializableHashtable.cs
3,274
C#
using System; using System.Collections.Generic; using System.Linq; using Windows.Foundation.Collections; using Windows.System; using Windows.UI.Core; using Windows.UI.ViewManagement; using Windows.UI.Xaml; using Windows.UI.Xaml.Controls; namespace FindWord.Common { /// <summary> /// Typical implementation of Page that provides several important conveniences: /// <list type="bullet"> /// <item> /// <description>Application view state to visual state mapping</description> /// </item> /// <item> /// <description>GoBack, GoForward, and GoHome event handlers</description> /// </item> /// <item> /// <description>Mouse and keyboard shortcuts for navigation</description> /// </item> /// <item> /// <description>State management for navigation and process lifetime management</description> /// </item> /// <item> /// <description>A default view model</description> /// </item> /// </list> /// </summary> [Windows.Foundation.Metadata.WebHostHidden] public class LayoutAwarePage : Page { /// <summary> /// Identifies the <see cref="DefaultViewModel"/> dependency property. /// </summary> public static readonly DependencyProperty DefaultViewModelProperty = DependencyProperty.Register("DefaultViewModel", typeof(IObservableMap<String, Object>), typeof(LayoutAwarePage), null); private List<Control> _layoutAwareControls; /// <summary> /// Initializes a new instance of the <see cref="LayoutAwarePage"/> class. /// </summary> public LayoutAwarePage() { if (Windows.ApplicationModel.DesignMode.DesignModeEnabled) return; // Create an empty default view model this.ItemsViewModel = new ObservableDictionary<String, Object>(); // When this page is part of the visual tree make two changes: // 1) Map application view state to visual state for the page // 2) Handle keyboard and mouse navigation requests this.Loaded += (sender, e) => { this.StartLayoutUpdates(sender, e); // Keyboard and mouse navigation only apply when occupying the entire window if (this.ActualHeight == Window.Current.Bounds.Height && this.ActualWidth == Window.Current.Bounds.Width) { // Listen to the window directly so focus isn't required Window.Current.CoreWindow.Dispatcher.AcceleratorKeyActivated += CoreDispatcher_AcceleratorKeyActivated; Window.Current.CoreWindow.PointerPressed += this.CoreWindow_PointerPressed; } }; // Undo the same changes when the page is no longer visible this.Unloaded += (sender, e) => { this.StopLayoutUpdates(sender, e); Window.Current.CoreWindow.Dispatcher.AcceleratorKeyActivated -= CoreDispatcher_AcceleratorKeyActivated; Window.Current.CoreWindow.PointerPressed -= this.CoreWindow_PointerPressed; }; } /// <summary> /// An implementation of <see cref="IObservableMap&lt;String, Object&gt;"/> designed to be /// used as a trivial view model. /// </summary> protected IObservableMap<String, Object> ItemsViewModel { get { return this.GetValue(DefaultViewModelProperty) as IObservableMap<String, Object>; } set { this.SetValue(DefaultViewModelProperty, value); } } #region Navigation support /// <summary> /// Invoked as an event handler to navigate backward in the page's associated /// <see cref="Frame"/> until it reaches the top of the navigation stack. /// </summary> /// <param name="sender">Instance that triggered the event.</param> /// <param name="e">Event data describing the conditions that led to the event.</param> protected virtual void GoHome(object sender, RoutedEventArgs e) { // Use the navigation frame to return to the topmost page if (this.Frame != null) { while (this.Frame.CanGoBack) this.Frame.GoBack(); } } /// <summary> /// Invoked as an event handler to navigate backward in the navigation stack /// associated with this page's <see cref="Frame"/>. /// </summary> /// <param name="sender">Instance that triggered the event.</param> /// <param name="e">Event data describing the conditions that led to the /// event.</param> protected virtual void GoBack(object sender, RoutedEventArgs e) { // Use the navigation frame to return to the previous page if (this.Frame != null && this.Frame.CanGoBack) this.Frame.GoBack(); } /// <summary> /// Invoked as an event handler to navigate forward in the navigation stack /// associated with this page's <see cref="Frame"/>. /// </summary> /// <param name="sender">Instance that triggered the event.</param> /// <param name="e">Event data describing the conditions that led to the /// event.</param> protected virtual void GoForward(object sender, RoutedEventArgs e) { // Use the navigation frame to move to the next page if (this.Frame != null && this.Frame.CanGoForward) this.Frame.GoForward(); } /// <summary> /// Invoked on every keystroke, including system keys such as Alt key combinations, when /// this page is active and occupies the entire window. Used to detect keyboard navigation /// between pages even when the page itself doesn't have focus. /// </summary> /// <param name="sender">Instance that triggered the event.</param> /// <param name="args">Event data describing the conditions that led to the event.</param> private void CoreDispatcher_AcceleratorKeyActivated(CoreDispatcher sender, AcceleratorKeyEventArgs args) { var virtualKey = args.VirtualKey; // Only investigate further when Left, Right, or the dedicated Previous or Next keys // are pressed if ((args.EventType == CoreAcceleratorKeyEventType.SystemKeyDown || args.EventType == CoreAcceleratorKeyEventType.KeyDown) && (virtualKey == VirtualKey.Left || virtualKey == VirtualKey.Right || (int)virtualKey == 166 || (int)virtualKey == 167)) { var coreWindow = Window.Current.CoreWindow; var downState = CoreVirtualKeyStates.Down; bool menuKey = (coreWindow.GetKeyState(VirtualKey.Menu) & downState) == downState; bool controlKey = (coreWindow.GetKeyState(VirtualKey.Control) & downState) == downState; bool shiftKey = (coreWindow.GetKeyState(VirtualKey.Shift) & downState) == downState; bool noModifiers = !menuKey && !controlKey && !shiftKey; bool onlyAlt = menuKey && !controlKey && !shiftKey; if (((int)virtualKey == 166 && noModifiers) || (virtualKey == VirtualKey.Left && onlyAlt)) { // When the previous key or Alt+Left are pressed navigate back args.Handled = true; this.GoBack(this, new RoutedEventArgs()); } else if (((int)virtualKey == 167 && noModifiers) || (virtualKey == VirtualKey.Right && onlyAlt)) { // When the next key or Alt+Right are pressed navigate forward args.Handled = true; this.GoForward(this, new RoutedEventArgs()); } } } /// <summary> /// Invoked on every mouse click, touch screen tap, or equivalent interaction when this /// page is active and occupies the entire window. Used to detect browser-style next and /// previous mouse button clicks to navigate between pages. /// </summary> /// <param name="sender">Instance that triggered the event.</param> /// <param name="args">Event data describing the conditions that led to the event.</param> private void CoreWindow_PointerPressed(CoreWindow sender, PointerEventArgs args) { var properties = args.CurrentPoint.Properties; // Ignore button chords with the left, right, and middle buttons if (properties.IsLeftButtonPressed || properties.IsRightButtonPressed || properties.IsMiddleButtonPressed) return; // If back or foward are pressed (but not both) navigate appropriately bool backPressed = properties.IsXButton1Pressed; bool forwardPressed = properties.IsXButton2Pressed; if (backPressed ^ forwardPressed) { args.Handled = true; if (backPressed) this.GoBack(this, new RoutedEventArgs()); if (forwardPressed) this.GoForward(this, new RoutedEventArgs()); } } #endregion #region Visual state switching /// <summary> /// Invoked as an event handler, typically on the <see cref="FrameworkElement.Loaded"/> /// event of a <see cref="Control"/> within the page, to indicate that the sender should /// start receiving visual state management changes that correspond to application view /// state changes. /// </summary> /// <param name="sender">Instance of <see cref="Control"/> that supports visual state /// management corresponding to view states.</param> /// <param name="e">Event data that describes how the request was made.</param> /// <remarks>The current view state will immediately be used to set the corresponding /// visual state when layout updates are requested. A corresponding /// <see cref="FrameworkElement.Unloaded"/> event handler connected to /// <see cref="StopLayoutUpdates"/> is strongly encouraged. Instances of /// <see cref="LayoutAwarePage"/> automatically invoke these handlers in their Loaded and /// Unloaded events.</remarks> /// <seealso cref="DetermineVisualState"/> /// <seealso cref="InvalidateVisualState"/> public void StartLayoutUpdates(object sender, RoutedEventArgs e) { if (BottomAppBar != null) { this.BottomAppBar.Opened += BottomAppBarOpened; this.BottomAppBar.Closed += BottomAppBarClosed; if (this.BottomAppBar.IsOpen) { BottomAppBarOpened(null, null); } else { BottomAppBarClosed(null, null); } } var control = sender as Control; if (control == null) return; if (this._layoutAwareControls == null) { // Start listening to view state changes when there are controls interested in updates Window.Current.SizeChanged += this.WindowSizeChanged; this.SizeChanged += LayoutAwarePage_SizeChanged; this._layoutAwareControls = new List<Control>(); } this._layoutAwareControls.Add(control); // Set the initial visual state of the control VisualStateManager.GoToState(control, DetermineVisualState(ApplicationView.Value), false); } private void LayoutAwarePage_SizeChanged(object sender, SizeChangedEventArgs e) { this.InvalidateVisualState(); } private void WindowSizeChanged(object sender, WindowSizeChangedEventArgs e) { this.InvalidateVisualState(); } void BottomAppBarOpened(object sender, object e) { VisualStateManager.GoToState(this, "Opened", true); } void BottomAppBarClosed(object sender, object e) { VisualStateManager.GoToState(this, "Closed", true); } /// <summary> /// Invoked as an event handler, typically on the <see cref="FrameworkElement.Unloaded"/> /// event of a <see cref="Control"/>, to indicate that the sender should start receiving /// visual state management changes that correspond to application view state changes. /// </summary> /// <param name="sender">Instance of <see cref="Control"/> that supports visual state /// management corresponding to view states.</param> /// <param name="e">Event data that describes how the request was made.</param> /// <remarks>The current view state will immediately be used to set the corresponding /// visual state when layout updates are requested.</remarks> /// <seealso cref="StartLayoutUpdates"/> public void StopLayoutUpdates(object sender, RoutedEventArgs e) { var control = sender as Control; if (control == null || this._layoutAwareControls == null) return; this._layoutAwareControls.Remove(control); if (this._layoutAwareControls.Count == 0) { // Stop listening to view state changes when no controls are interested in updates this._layoutAwareControls = null; Window.Current.SizeChanged -= this.WindowSizeChanged; } } /// <summary> /// Translates <see cref="ApplicationViewState"/> values into strings for visual state /// management within the page. The default implementation uses the names of enum values. /// Subclasses may override this method to control the mapping scheme used. /// </summary> /// <param name="viewState">View state for which a visual state is desired.</param> /// <returns>Visual state name used to drive the /// <see cref="VisualStateManager"/></returns> /// <seealso cref="InvalidateVisualState"/> protected virtual string DetermineVisualState(ApplicationViewState viewState) { return viewState.ToString(); } /// <summary> /// Updates all controls that are listening for visual state changes with the correct /// visual state. /// </summary> /// <remarks> /// Typically used in conjunction with overriding <see cref="DetermineVisualState"/> to /// signal that a different value may be returned even though the view state has not /// changed. /// </remarks> public void InvalidateVisualState() { if (this._layoutAwareControls != null) { string visualState = DetermineVisualState(ApplicationView.Value); foreach (var layoutAwareControl in this._layoutAwareControls) { VisualStateManager.GoToState(layoutAwareControl, visualState, false); } } } #endregion #region Process lifetime management //private String _pageKey; ///// <summary> ///// Invoked when this page is about to be displayed in a Frame. ///// </summary> ///// <param name="e">Event data that describes how this page was reached. The Parameter ///// property provides the group to be displayed.</param> //protected override void OnNavigatedTo(NavigationEventArgs e) //{ // // Returning to a cached page through navigation shouldn't trigger state loading // if (this._pageKey != null) return; // var frameState = SuspensionManager.SessionStateForFrame(this.Frame); // this._pageKey = "Page-" + this.Frame.BackStackDepth; // if (e.NavigationMode == NavigationMode.New) // { // // Clear existing state for forward navigation when adding a new page to the // // navigation stack // var nextPageKey = this._pageKey; // int nextPageIndex = this.Frame.BackStackDepth; // while (frameState.Remove(nextPageKey)) // { // nextPageIndex++; // nextPageKey = "Page-" + nextPageIndex; // } // // Pass the navigation parameter to the new page // this.LoadState(e.Parameter, null); // } // else // { // // Pass the navigation parameter and preserved page state to the page, using // // the same strategy for loading suspended state and recreating pages discarded // // from cache // this.LoadState(e.Parameter, (Dictionary<String, Object>)frameState[this._pageKey]); // } //} ///// <summary> ///// Invoked when this page will no longer be displayed in a Frame. ///// </summary> ///// <param name="e">Event data that describes how this page was reached. The Parameter ///// property provides the group to be displayed.</param> //protected override void OnNavigatedFrom(NavigationEventArgs e) //{ // var frameState = SuspensionManager.SessionStateForFrame(this.Frame); // var pageState = new Dictionary<String, Object>(); // this.SaveState(pageState); // frameState[_pageKey] = pageState; //} ///// <summary> ///// Populates the page with content passed during navigation. Any saved state is also ///// provided when recreating a page from a prior session. ///// </summary> ///// <param name="navigationParameter">The parameter value passed to ///// <see cref="Frame.Navigate(Type, Object)"/> when this page was initially requested. ///// </param> ///// <param name="pageState">A dictionary of state preserved by this page during an earlier ///// session. This will be null the first time a page is visited.</param> //protected virtual void LoadState(Object navigationParameter, Dictionary<String, Object> pageState) //{ //} ///// <summary> ///// Preserves state associated with this page in case the application is suspended or the ///// page is discarded from the navigation cache. Values must conform to the serialization ///// requirements of <see cref="SuspensionManager.SessionState"/>. ///// </summary> ///// <param name="pageState">An empty dictionary to be populated with serializable state.</param> //protected virtual void SaveState(Dictionary<String, Object> pageState) //{ //} #endregion /// <summary> /// Implementation of IObservableMap that supports reentrancy for use as a default view /// model. /// </summary> private class ObservableDictionary<K, V> : IObservableMap<K, V> { private class ObservableDictionaryChangedEventArgs : IMapChangedEventArgs<K> { public ObservableDictionaryChangedEventArgs(CollectionChange change, K key) { this.CollectionChange = change; this.Key = key; } public CollectionChange CollectionChange { get; private set; } public K Key { get; private set; } } private Dictionary<K, V> _dictionary = new Dictionary<K, V>(); public event MapChangedEventHandler<K, V> MapChanged; private void InvokeMapChanged(CollectionChange change, K key) { var eventHandler = MapChanged; if (eventHandler != null) { eventHandler(this, new ObservableDictionaryChangedEventArgs(CollectionChange.ItemInserted, key)); } } public void Add(K key, V value) { this._dictionary.Add(key, value); this.InvokeMapChanged(CollectionChange.ItemInserted, key); } public void Add(KeyValuePair<K, V> item) { this.Add(item.Key, item.Value); } public bool Remove(K key) { if (this._dictionary.Remove(key)) { this.InvokeMapChanged(CollectionChange.ItemRemoved, key); return true; } return false; } public bool Remove(KeyValuePair<K, V> item) { V currentValue; if (this._dictionary.TryGetValue(item.Key, out currentValue) && Object.Equals(item.Value, currentValue) && this._dictionary.Remove(item.Key)) { this.InvokeMapChanged(CollectionChange.ItemRemoved, item.Key); return true; } return false; } public V this[K key] { get { return this._dictionary[key]; } set { this._dictionary[key] = value; this.InvokeMapChanged(CollectionChange.ItemChanged, key); } } public void Clear() { var priorKeys = this._dictionary.Keys.ToArray(); this._dictionary.Clear(); foreach (var key in priorKeys) { this.InvokeMapChanged(CollectionChange.ItemRemoved, key); } } public ICollection<K> Keys { get { return this._dictionary.Keys; } } public bool ContainsKey(K key) { return this._dictionary.ContainsKey(key); } public bool TryGetValue(K key, out V value) { return this._dictionary.TryGetValue(key, out value); } public ICollection<V> Values { get { return this._dictionary.Values; } } public bool Contains(KeyValuePair<K, V> item) { return this._dictionary.Contains(item); } public int Count { get { return this._dictionary.Count; } } public bool IsReadOnly { get { return false; } } public IEnumerator<KeyValuePair<K, V>> GetEnumerator() { return this._dictionary.GetEnumerator(); } System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { return this._dictionary.GetEnumerator(); } public void CopyTo(KeyValuePair<K, V>[] array, int arrayIndex) { int arraySize = array.Length; foreach (var pair in this._dictionary) { if (arrayIndex >= arraySize) break; array[arrayIndex++] = pair; } } } } }
42.84507
118
0.558473
[ "Apache-2.0" ]
EugeneBichel/XAML-Application-For-WindowsRT-Windows8
FindWord/WordFinder/Common/LayoutAwarePage.cs
24,338
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Rate.Repository.Abstract { class IReviewRepository { } }
15.153846
34
0.751269
[ "MIT" ]
jcnavarro/rateflicks
Rate.Repository/Abstract/IReviewRepository.cs
199
C#
// <auto-generated /> namespace Vidly.Migrations { using System.CodeDom.Compiler; using System.Data.Entity.Migrations; using System.Data.Entity.Migrations.Infrastructure; using System.Resources; [GeneratedCode("EntityFramework.Migrations", "6.2.0-61023")] public sealed partial class AddNewEntityGenre : IMigrationMetadata { private readonly ResourceManager Resources = new ResourceManager(typeof(AddNewEntityGenre)); string IMigrationMetadata.Id { get { return "202002121022048_AddNewEntityGenre"; } } string IMigrationMetadata.Source { get { return null; } } string IMigrationMetadata.Target { get { return Resources.GetString("Target"); } } } }
27.6
100
0.625604
[ "MIT" ]
SonicTheCat/Vidly-mvc-5
Vidly/Vidly/Migrations/202002121022048_AddNewEntityGenre.Designer.cs
828
C#
namespace DXDecompiler.DebugParser.Psv0 { public class DebugASInfo : DebugValidationInfo { public uint PayloadSizeInBytes { get; private set; } internal override int StructSize => 4; public static DebugASInfo Parse(DebugBytecodeReader reader) { return new DebugASInfo() { PayloadSizeInBytes = reader.ReadUInt32("PayloadSizeInBytes") }; } } }
23.0625
64
0.739837
[ "MIT" ]
lanyizi/DXDecompiler
src/DebugParser/DebugParser/Psv0/DebugASInfo.cs
371
C#
// This file is part of the DSharpPlus project. // // Copyright (c) 2015 Mike Santiago // Copyright (c) 2016-2022 DSharpPlus Contributors // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. using System; using DSharpPlus.Net; using Newtonsoft.Json.Linq; namespace DSharpPlus.Exceptions { /// <summary> /// Represents an exception thrown when a requested resource is not found. /// </summary> public class NotFoundException : DiscordException { internal NotFoundException(BaseRestRequest request, RestResponse response) : base("Not found: " + response.ResponseCode) { this.WebRequest = request; this.WebResponse = response; try { var j = JObject.Parse(response.Response); if (j["message"] != null) this.JsonMessage = j["message"].ToString(); } catch (Exception) { } } } }
38.627451
128
0.691878
[ "MIT" ]
Erisa/DSharpPlus
DSharpPlus/Exceptions/NotFoundException.cs
1,970
C#
using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Linq; using System.Text; using System.Threading.Tasks; namespace JohnLambe.Util.Db { public class FlagDeletedEntityBase : IHasActiveFlag { [Key] public int Id { get; set; } public virtual bool IsActive { get; set; } } }
19.263158
55
0.699454
[ "MIT" ]
JohnLambe/JLCSUtils
JLCSUtils/JLUtilsEF/Db/FlagDeletedEntity.cs
368
C#
// *** WARNING: this file was generated by the Pulumi SDK Generator. *** // *** 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.AzureNextGen.Web.Latest { /// <summary> /// Hybrid Connection for an App Service app. /// </summary> public partial class WebAppRelayServiceConnectionSlot : Pulumi.CustomResource { [Output("biztalkUri")] public Output<string?> BiztalkUri { get; private set; } = null!; [Output("entityConnectionString")] public Output<string?> EntityConnectionString { get; private set; } = null!; [Output("entityName")] public Output<string?> EntityName { get; private set; } = null!; [Output("hostname")] public Output<string?> Hostname { get; private set; } = null!; /// <summary> /// Kind of resource. /// </summary> [Output("kind")] public Output<string?> Kind { get; private set; } = null!; /// <summary> /// Resource Name. /// </summary> [Output("name")] public Output<string> Name { get; private set; } = null!; [Output("port")] public Output<int?> Port { get; private set; } = null!; [Output("resourceConnectionString")] public Output<string?> ResourceConnectionString { get; private set; } = null!; [Output("resourceType")] public Output<string?> ResourceType { get; private set; } = null!; /// <summary> /// Resource type. /// </summary> [Output("type")] public Output<string> Type { get; private set; } = null!; /// <summary> /// Create a WebAppRelayServiceConnectionSlot 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 WebAppRelayServiceConnectionSlot(string name, WebAppRelayServiceConnectionSlotArgs args, CustomResourceOptions? options = null) : base("azure-nextgen:web/latest:WebAppRelayServiceConnectionSlot", name, args ?? new WebAppRelayServiceConnectionSlotArgs(), MakeResourceOptions(options, "")) { } private WebAppRelayServiceConnectionSlot(string name, Input<string> id, CustomResourceOptions? options = null) : base("azure-nextgen:web/latest:WebAppRelayServiceConnectionSlot", name, null, MakeResourceOptions(options, id)) { } private static CustomResourceOptions MakeResourceOptions(CustomResourceOptions? options, Input<string>? id) { var defaultOptions = new CustomResourceOptions { Version = Utilities.Version, Aliases = { new Pulumi.Alias { Type = "azure-nextgen:web/v20150801:WebAppRelayServiceConnectionSlot"}, new Pulumi.Alias { Type = "azure-nextgen:web/v20160801:WebAppRelayServiceConnectionSlot"}, new Pulumi.Alias { Type = "azure-nextgen:web/v20180201:WebAppRelayServiceConnectionSlot"}, new Pulumi.Alias { Type = "azure-nextgen:web/v20181101:WebAppRelayServiceConnectionSlot"}, new Pulumi.Alias { Type = "azure-nextgen:web/v20190801:WebAppRelayServiceConnectionSlot"}, new Pulumi.Alias { Type = "azure-nextgen:web/v20200601:WebAppRelayServiceConnectionSlot"}, }, }; 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 WebAppRelayServiceConnectionSlot 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="options">A bag of options that control this resource's behavior</param> public static WebAppRelayServiceConnectionSlot Get(string name, Input<string> id, CustomResourceOptions? options = null) { return new WebAppRelayServiceConnectionSlot(name, id, options); } } public sealed class WebAppRelayServiceConnectionSlotArgs : Pulumi.ResourceArgs { [Input("biztalkUri")] public Input<string>? BiztalkUri { get; set; } [Input("entityConnectionString")] public Input<string>? EntityConnectionString { get; set; } [Input("entityName", required: true)] public Input<string> EntityName { get; set; } = null!; [Input("hostname")] public Input<string>? Hostname { get; set; } /// <summary> /// Kind of resource. /// </summary> [Input("kind")] public Input<string>? Kind { get; set; } /// <summary> /// Name of the app. /// </summary> [Input("name", required: true)] public Input<string> Name { get; set; } = null!; [Input("port")] public Input<int>? Port { get; set; } [Input("resourceConnectionString")] public Input<string>? ResourceConnectionString { get; set; } /// <summary> /// Name of the resource group to which the resource belongs. /// </summary> [Input("resourceGroupName", required: true)] public Input<string> ResourceGroupName { get; set; } = null!; [Input("resourceType")] public Input<string>? ResourceType { get; set; } /// <summary> /// Name of the deployment slot. If a slot is not specified, the API will create or update a hybrid connection for the production slot. /// </summary> [Input("slot", required: true)] public Input<string> Slot { get; set; } = null!; public WebAppRelayServiceConnectionSlotArgs() { } } }
40.45625
171
0.613317
[ "Apache-2.0" ]
test-wiz-sec/pulumi-azure-nextgen
sdk/dotnet/Web/Latest/WebAppRelayServiceConnectionSlot.cs
6,473
C#
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System; using System.Diagnostics.CodeAnalysis; using Microsoft.AspNetCore.Components.WebAssembly.Authentication; using Microsoft.Authentication.WebAssembly.Msal; using Microsoft.Authentication.WebAssembly.Msal.Models; using Microsoft.Extensions.DependencyInjection.Extensions; using Microsoft.Extensions.Options; using static Microsoft.AspNetCore.Internal.LinkerFlags; namespace Microsoft.Extensions.DependencyInjection { /// <summary> /// Contains extension methods to add authentication to Blazor WebAssembly applications using /// Azure Active Directory or Azure Active Directory B2C. /// </summary> public static class MsalWebAssemblyServiceCollectionExtensions { /// <summary> /// Adds authentication using msal.js to Blazor applications. /// </summary> /// <param name="services">The <see cref="IServiceCollection"/>.</param> /// <param name="configure">A callback to configure the <see cref="RemoteAuthenticationOptions{MsalProviderOptions}"/>.</param> /// <returns>The <see cref="IServiceCollection"/>.</returns> public static IRemoteAuthenticationBuilder<RemoteAuthenticationState, RemoteUserAccount> AddMsalAuthentication(this IServiceCollection services, Action<RemoteAuthenticationOptions<MsalProviderOptions>> configure) { return AddMsalAuthentication<RemoteAuthenticationState>(services, configure); } /// <summary> /// Adds authentication using msal.js to Blazor applications. /// </summary> /// <typeparam name="TRemoteAuthenticationState">The type of the remote authentication state.</typeparam> /// <param name="services">The <see cref="IServiceCollection"/>.</param> /// <param name="configure">A callback to configure the <see cref="RemoteAuthenticationOptions{MsalProviderOptions}"/>.</param> /// <returns>The <see cref="IServiceCollection"/>.</returns> public static IRemoteAuthenticationBuilder<TRemoteAuthenticationState, RemoteUserAccount> AddMsalAuthentication<TRemoteAuthenticationState>(this IServiceCollection services, Action<RemoteAuthenticationOptions<MsalProviderOptions>> configure) where TRemoteAuthenticationState : RemoteAuthenticationState, new() { return AddMsalAuthentication<TRemoteAuthenticationState, RemoteUserAccount>(services, configure); } /// <summary> /// Adds authentication using msal.js to Blazor applications. /// </summary> /// <typeparam name="TRemoteAuthenticationState">The type of the remote authentication state.</typeparam> /// <typeparam name="TAccount">The type of the <see cref="RemoteUserAccount"/>.</typeparam> /// <param name="services">The <see cref="IServiceCollection"/>.</param> /// <param name="configure">A callback to configure the <see cref="RemoteAuthenticationOptions{MsalProviderOptions}"/>.</param> /// <returns>The <see cref="IServiceCollection"/>.</returns> public static IRemoteAuthenticationBuilder<TRemoteAuthenticationState, TAccount> AddMsalAuthentication<TRemoteAuthenticationState, [DynamicallyAccessedMembers(JsonSerialized)] TAccount>(this IServiceCollection services, Action<RemoteAuthenticationOptions<MsalProviderOptions>> configure) where TRemoteAuthenticationState : RemoteAuthenticationState, new() where TAccount : RemoteUserAccount { services.AddRemoteAuthentication<TRemoteAuthenticationState, TAccount, MsalProviderOptions>(configure); services.TryAddEnumerable(ServiceDescriptor.Scoped<IPostConfigureOptions<RemoteAuthenticationOptions<MsalProviderOptions>>, MsalDefaultOptionsConfiguration>()); return new MsalRemoteAuthenticationBuilder<TRemoteAuthenticationState, TAccount>(services); } } internal class MsalRemoteAuthenticationBuilder<TRemoteAuthenticationState, TRemoteUserAccount> : IRemoteAuthenticationBuilder<TRemoteAuthenticationState, TRemoteUserAccount> where TRemoteAuthenticationState : RemoteAuthenticationState, new() where TRemoteUserAccount : RemoteUserAccount { public MsalRemoteAuthenticationBuilder(IServiceCollection services) => Services = services; public IServiceCollection Services { get; } } }
60.540541
295
0.747321
[ "MIT" ]
48355746/AspNetCore
src/Components/WebAssembly/Authentication.Msal/src/MsalWebAssemblyServiceCollectionExtensions.cs
4,480
C#
// <auto-generated> // 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. // </auto-generated> namespace Microsoft.Azure.Management.RecoveryServices.SiteRecovery.Models { using Newtonsoft.Json; using System.Linq; /// <summary> /// Implements the event query parameter. /// </summary> public partial class EventQueryParameter { /// <summary> /// Initializes a new instance of the EventQueryParameter class. /// </summary> public EventQueryParameter() { CustomInit(); } /// <summary> /// Initializes a new instance of the EventQueryParameter class. /// </summary> /// <param name="eventCode">The source id of the events to be /// queried.</param> /// <param name="severity">The severity of the events to be /// queried.</param> /// <param name="eventType">The type of the events to be /// queried.</param> /// <param name="fabricName">The affected object server id of the /// events to be queried.</param> /// <param name="affectedObjectFriendlyName">The affected object name /// of the events to be queried.</param> /// <param name="startTime">The start time of the time range within /// which the events are to be queried.</param> /// <param name="endTime">The end time of the time range within which /// the events are to be queried.</param> public EventQueryParameter(string eventCode = default(string), string severity = default(string), string eventType = default(string), string fabricName = default(string), string affectedObjectFriendlyName = default(string), System.DateTime? startTime = default(System.DateTime?), System.DateTime? endTime = default(System.DateTime?)) { EventCode = eventCode; Severity = severity; EventType = eventType; FabricName = fabricName; AffectedObjectFriendlyName = affectedObjectFriendlyName; StartTime = startTime; EndTime = endTime; CustomInit(); } /// <summary> /// An initialization method that performs custom operations like setting defaults /// </summary> partial void CustomInit(); /// <summary> /// Gets or sets the source id of the events to be queried. /// </summary> [JsonProperty(PropertyName = "EventCode")] public string EventCode { get; set; } /// <summary> /// Gets or sets the severity of the events to be queried. /// </summary> [JsonProperty(PropertyName = "Severity")] public string Severity { get; set; } /// <summary> /// Gets or sets the type of the events to be queried. /// </summary> [JsonProperty(PropertyName = "EventType")] public string EventType { get; set; } /// <summary> /// Gets or sets the affected object server id of the events to be /// queried. /// </summary> [JsonProperty(PropertyName = "FabricName")] public string FabricName { get; set; } /// <summary> /// Gets or sets the affected object name of the events to be queried. /// </summary> [JsonProperty(PropertyName = "AffectedObjectFriendlyName")] public string AffectedObjectFriendlyName { get; set; } /// <summary> /// Gets or sets the start time of the time range within which the /// events are to be queried. /// </summary> [JsonProperty(PropertyName = "StartTime")] public System.DateTime? StartTime { get; set; } /// <summary> /// Gets or sets the end time of the time range within which the events /// are to be queried. /// </summary> [JsonProperty(PropertyName = "EndTime")] public System.DateTime? EndTime { get; set; } } }
38.354545
341
0.608438
[ "MIT" ]
payiAzure/azure-sdk-for-net
src/SDKs/RecoveryServices.SiteRecovery/Management.RecoveryServices.SiteRecovery/Generated/Models/EventQueryParameter.cs
4,219
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("CATM.DevTools.Helpers")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("CATM.DevTools.Helpers")] [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("dc4cf3ef-19d5-4d01-8c2b-37336423ddde")] // 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.243243
84
0.745583
[ "BSD-3-Clause" ]
ctapiamori/dev-tools
CATM.DevTools.Helpers/Properties/AssemblyInfo.cs
1,418
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("EP.SignalRSelfHost.Client.Web")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("EP.SignalRSelfHost.Client.Web")] [assembly: AssemblyCopyright("Copyright © 2015")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("f52917c4-d1a0-4ae2-9d85-bee6e684dfc8")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Revision and Build Numbers // by using the '*' as shown below: [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
38.5
84
0.753247
[ "MIT" ]
EduardoPires/SignalRWindowsService
src/EP.SignalRSelfHost.Client.Web/Properties/AssemblyInfo.cs
1,389
C#
using System; using System.Security.Cryptography; using System.Security.Cryptography.X509Certificates; // ReSharper disable InconsistentNaming namespace Mastercard.Developer.OAuth1Signer.Core.Utils { /// <summary> /// Utility class. /// </summary> public static class AuthenticationUtils { /// <summary> /// Load an RSA key out of a PKCS#12 container. /// </summary> public static RSACryptoServiceProvider LoadSigningKey(string pkcs12KeyFilePath, string signingKeyAlias, string signingKeyPassword, X509KeyStorageFlags keyStorageFlags = X509KeyStorageFlags.DefaultKeySet) { if (pkcs12KeyFilePath == null) throw new ArgumentNullException(nameof(pkcs12KeyFilePath)); var signingCertificate = new X509Certificate2(pkcs12KeyFilePath, signingKeyPassword, keyStorageFlags); RSACryptoServiceProvider rsa = (RSACryptoServiceProvider)signingCertificate.PrivateKey; byte[] privateKeyBlob = rsa.ExportCspBlob(true); var key = new RSACryptoServiceProvider(); key.ImportCspBlob(privateKeyBlob); return key; } /// <summary> /// Load an RSA key out of a PKCS#12 container. /// </summary> public static RSACryptoServiceProvider LoadSigningKey(byte[] pkcs12RawData, string signingKeyPassword, X509KeyStorageFlags keyStorageFlags = X509KeyStorageFlags.DefaultKeySet) { if (pkcs12RawData == null) throw new ArgumentNullException(nameof(pkcs12RawData)); var signingCertificate = new X509Certificate2(pkcs12RawData, signingKeyPassword, keyStorageFlags); RSACryptoServiceProvider rsa = (RSACryptoServiceProvider)signingCertificate.PrivateKey; byte[] privateKeyBlob = rsa.ExportCspBlob(true); var key = new RSACryptoServiceProvider(); key.ImportCspBlob(privateKeyBlob); return key; } } }
44.977273
138
0.689742
[ "MIT" ]
jaaufauvre/oauth1-signer-csharp-net45
Mastercard.Developer.OAuth1Signer.Core/Utils/AuthenticationUtils.cs
1,981
C#
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System; interface I<S> { string Method(S param); string Method<M>(S param); } struct MyStruct : I<string>, I<object> { public string Method(string param) { return "string"; } public string Method(object param) { return "object"; } public string Method<M>(string param) { return "GEN-string"; } public string Method<M>(object param) { return "GEN-object"; } } class Conversion1<T, U> where U : I<T>, new() { public string Caller1(T param) { U instance = new U(); return instance.Method(param); } public string Caller2(T param) { U instance = new U(); return instance.Method<object>(param); } } class Conversion2<U> where U : I<string>, new() { public string Caller1() { U instance = new U(); return instance.Method("mystring"); } public string Caller2() { U instance = new U(); return instance.Method<object>("mystring"); } } class Test { static string Caller1<T, U>(T param) where U : I<T>, new() { U instance = new U(); return instance.Method(param); } static string Caller2<T, U>(T param) where U : I<T>, new() { U instance = new U(); return instance.Method<object>(param); } static string Caller3<U>() where U : I<string>, new() { U instance = new U(); return instance.Method("mystring"); } static string Caller4<U>() where U : I<string>, new() { U instance = new U(); return instance.Method<object>("mystring"); } static int Main() { int numFailures = 0; Conversion1<string, MyStruct> c1 = new Conversion1<string, MyStruct>(); Conversion2<MyStruct> c2 = new Conversion2<MyStruct>(); string res1 = Caller1<string, MyStruct>("mystring"); string res2 = Caller2<string, MyStruct>("mystring"); Console.WriteLine(res1); Console.WriteLine(res2); if (res1 != "string" && res2 != "GEN-string") numFailures++; res1 = Caller3<MyStruct>(); res2 = Caller4<MyStruct>(); Console.WriteLine(res1); Console.WriteLine(res2); if (res1 != "string" && res2 != "GEN-string") numFailures++; res1 = c1.Caller1("mystring"); res2 = c1.Caller2("mystring"); Console.WriteLine(res1); Console.WriteLine(res2); if (res1 != "string" && res2 != "GEN-string") numFailures++; res1 = c2.Caller1(); res2 = c2.Caller2(); Console.WriteLine(res1); Console.WriteLine(res2); if (res1 != "string" && res2 != "GEN-string") numFailures++; return ((numFailures == 0) ? (100) : (-1)); } }
23.046512
79
0.553986
[ "MIT" ]
belav/runtime
src/tests/Loader/classloader/regressions/dev10_568786/4_Misc/ConstrainedMethods.cs
2,973
C#
// <auto-generated /> using BlazorWasm.Server.Data; using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Infrastructure; using Microsoft.EntityFrameworkCore.Metadata; using Microsoft.EntityFrameworkCore.Storage.ValueConversion; using System; namespace BlazorWasm.Server.Data.Migrations { [DbContext(typeof(ApplicationDbContext))] partial class ApplicationDbContextModelSnapshot : ModelSnapshot { protected override void BuildModel(ModelBuilder modelBuilder) { #pragma warning disable 612, 618 modelBuilder .HasAnnotation("ProductVersion", "3.0.0-rc1.19455.8") .HasAnnotation("Relational:MaxIdentifierLength", 128) .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); modelBuilder.Entity("BlazorWasm.Server.Models.ApplicationUser", b => { b.Property<string>("Id") .HasColumnType("nvarchar(450)"); b.Property<int>("AccessFailedCount") .HasColumnType("int"); b.Property<string>("ConcurrencyStamp") .IsConcurrencyToken() .HasColumnType("nvarchar(max)"); b.Property<string>("Email") .HasColumnType("nvarchar(256)") .HasMaxLength(256); b.Property<bool>("EmailConfirmed") .HasColumnType("bit"); b.Property<bool>("LockoutEnabled") .HasColumnType("bit"); b.Property<DateTimeOffset?>("LockoutEnd") .HasColumnType("datetimeoffset"); b.Property<string>("NormalizedEmail") .HasColumnType("nvarchar(256)") .HasMaxLength(256); b.Property<string>("NormalizedUserName") .HasColumnType("nvarchar(256)") .HasMaxLength(256); b.Property<string>("PasswordHash") .HasColumnType("nvarchar(max)"); b.Property<string>("PhoneNumber") .HasColumnType("nvarchar(max)"); b.Property<bool>("PhoneNumberConfirmed") .HasColumnType("bit"); b.Property<string>("SecurityStamp") .HasColumnType("nvarchar(max)"); b.Property<bool>("TwoFactorEnabled") .HasColumnType("bit"); b.Property<string>("UserName") .HasColumnType("nvarchar(256)") .HasMaxLength(256); b.HasKey("Id"); b.HasIndex("NormalizedEmail") .HasName("EmailIndex"); b.HasIndex("NormalizedUserName") .IsUnique() .HasName("UserNameIndex") .HasFilter("[NormalizedUserName] IS NOT NULL"); b.ToTable("AspNetUsers"); }); modelBuilder.Entity("IdentityServer4.EntityFramework.Entities.DeviceFlowCodes", b => { b.Property<string>("UserCode") .HasColumnType("nvarchar(200)") .HasMaxLength(200); b.Property<string>("ClientId") .IsRequired() .HasColumnType("nvarchar(200)") .HasMaxLength(200); b.Property<DateTime>("CreationTime") .HasColumnType("datetime2"); b.Property<string>("Data") .IsRequired() .HasColumnType("nvarchar(max)") .HasMaxLength(50000); b.Property<string>("DeviceCode") .IsRequired() .HasColumnType("nvarchar(200)") .HasMaxLength(200); b.Property<DateTime?>("Expiration") .IsRequired() .HasColumnType("datetime2"); b.Property<string>("SubjectId") .HasColumnType("nvarchar(200)") .HasMaxLength(200); b.HasKey("UserCode"); b.HasIndex("DeviceCode") .IsUnique(); b.HasIndex("Expiration"); b.ToTable("DeviceCodes"); }); modelBuilder.Entity("IdentityServer4.EntityFramework.Entities.PersistedGrant", b => { b.Property<string>("Key") .HasColumnType("nvarchar(200)") .HasMaxLength(200); b.Property<string>("ClientId") .IsRequired() .HasColumnType("nvarchar(200)") .HasMaxLength(200); b.Property<DateTime>("CreationTime") .HasColumnType("datetime2"); b.Property<string>("Data") .IsRequired() .HasColumnType("nvarchar(max)") .HasMaxLength(50000); b.Property<DateTime?>("Expiration") .HasColumnType("datetime2"); b.Property<string>("SubjectId") .HasColumnType("nvarchar(200)") .HasMaxLength(200); b.Property<string>("Type") .IsRequired() .HasColumnType("nvarchar(50)") .HasMaxLength(50); b.HasKey("Key"); b.HasIndex("Expiration"); b.HasIndex("SubjectId", "ClientId", "Type"); b.ToTable("PersistedGrants"); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRole", b => { b.Property<string>("Id") .HasColumnType("nvarchar(450)"); b.Property<string>("ConcurrencyStamp") .IsConcurrencyToken() .HasColumnType("nvarchar(max)"); b.Property<string>("Name") .HasColumnType("nvarchar(256)") .HasMaxLength(256); b.Property<string>("NormalizedName") .HasColumnType("nvarchar(256)") .HasMaxLength(256); b.HasKey("Id"); b.HasIndex("NormalizedName") .IsUnique() .HasName("RoleNameIndex") .HasFilter("[NormalizedName] IS NOT NULL"); b.ToTable("AspNetRoles"); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRoleClaim<string>", b => { b.Property<int>("Id") .ValueGeneratedOnAdd() .HasColumnType("int") .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); b.Property<string>("ClaimType") .HasColumnType("nvarchar(max)"); b.Property<string>("ClaimValue") .HasColumnType("nvarchar(max)"); b.Property<string>("RoleId") .IsRequired() .HasColumnType("nvarchar(450)"); b.HasKey("Id"); b.HasIndex("RoleId"); b.ToTable("AspNetRoleClaims"); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserClaim<string>", b => { b.Property<int>("Id") .ValueGeneratedOnAdd() .HasColumnType("int") .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); b.Property<string>("ClaimType") .HasColumnType("nvarchar(max)"); b.Property<string>("ClaimValue") .HasColumnType("nvarchar(max)"); b.Property<string>("UserId") .IsRequired() .HasColumnType("nvarchar(450)"); b.HasKey("Id"); b.HasIndex("UserId"); b.ToTable("AspNetUserClaims"); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserLogin<string>", b => { b.Property<string>("LoginProvider") .HasColumnType("nvarchar(128)") .HasMaxLength(128); b.Property<string>("ProviderKey") .HasColumnType("nvarchar(128)") .HasMaxLength(128); b.Property<string>("ProviderDisplayName") .HasColumnType("nvarchar(max)"); b.Property<string>("UserId") .IsRequired() .HasColumnType("nvarchar(450)"); b.HasKey("LoginProvider", "ProviderKey"); b.HasIndex("UserId"); b.ToTable("AspNetUserLogins"); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserRole<string>", b => { b.Property<string>("UserId") .HasColumnType("nvarchar(450)"); b.Property<string>("RoleId") .HasColumnType("nvarchar(450)"); b.HasKey("UserId", "RoleId"); b.HasIndex("RoleId"); b.ToTable("AspNetUserRoles"); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserToken<string>", b => { b.Property<string>("UserId") .HasColumnType("nvarchar(450)"); b.Property<string>("LoginProvider") .HasColumnType("nvarchar(128)") .HasMaxLength(128); b.Property<string>("Name") .HasColumnType("nvarchar(128)") .HasMaxLength(128); b.Property<string>("Value") .HasColumnType("nvarchar(max)"); b.HasKey("UserId", "LoginProvider", "Name"); b.ToTable("AspNetUserTokens"); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRoleClaim<string>", b => { b.HasOne("Microsoft.AspNetCore.Identity.IdentityRole", null) .WithMany() .HasForeignKey("RoleId") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserClaim<string>", b => { b.HasOne("BlazorWasm.Server.Models.ApplicationUser", null) .WithMany() .HasForeignKey("UserId") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserLogin<string>", b => { b.HasOne("BlazorWasm.Server.Models.ApplicationUser", null) .WithMany() .HasForeignKey("UserId") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserRole<string>", b => { b.HasOne("Microsoft.AspNetCore.Identity.IdentityRole", null) .WithMany() .HasForeignKey("RoleId") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); b.HasOne("BlazorWasm.Server.Models.ApplicationUser", null) .WithMany() .HasForeignKey("UserId") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserToken<string>", b => { b.HasOne("BlazorWasm.Server.Models.ApplicationUser", null) .WithMany() .HasForeignKey("UserId") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); }); #pragma warning restore 612, 618 } } }
37.195531
125
0.455092
[ "MIT" ]
brunoresende1991/BlazorWasmMisc
Server/Data/Migrations/ApplicationDbContextModelSnapshot.cs
13,316
C#
using Newtonsoft.Json; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace DataTables.Demo.Models { public class Product { public Product(string name, string position, string office, string extn, string date, string salary) { this.Name = name; this.Id = Convert.ToInt32(extn); this.Created = DateTime.Parse(date); this.Salary = salary; this.Office = office; this.Position = position; } public int Id { get; set; } [JsonProperty(PropertyName = "name")] public string Name { get; set; } [JsonProperty(PropertyName = "position")] public string Position { get; set; } [JsonProperty(PropertyName = "office")] public string Office { get; set; } [JsonProperty(PropertyName = "salary")] public string Salary { get; set; } [JsonProperty(PropertyName = "created")] public DateTime Created { get; set; } } }
23.307692
102
0.69747
[ "MIT" ]
LZorglub/DataTables.AspnetCore.Mvc
DataTables.Demo/Models/Product.cs
911
C#
using System; using System.Runtime.InteropServices; using System.Text; using System.Windows.Forms; using GTA; using GTA.Native; namespace CoopClient { /// <summary> /// Don't use it! /// </summary> public class Chat { private readonly Scaleform MainScaleForm; internal string CurrentInput { get; set; } private bool CurrentFocused { get; set; } internal bool Focused { get { return CurrentFocused; } set { if (value && Hidden) { Hidden = false; } MainScaleForm.CallFunction("SET_FOCUS", value ? 2 : 1, 2, "ALL"); CurrentFocused = value; } } private ulong LastMessageTime { get; set; } private bool CurrentHidden { get; set; } private bool Hidden { get { return CurrentHidden; } set { if (value) { if (!CurrentHidden) { MainScaleForm.CallFunction("hide"); } } else if (CurrentHidden) { MainScaleForm.CallFunction("showFeed"); } CurrentHidden = value; } } /// <summary> /// Don't use it! /// </summary> public Chat() { MainScaleForm = new Scaleform("multiplayer_chat"); } internal void Init() { MainScaleForm.CallFunction("SET_FOCUS", 2, 2, "ALL"); MainScaleForm.CallFunction("SET_FOCUS", 1, 2, "ALL"); } internal void Clear() { MainScaleForm.CallFunction("RESET"); } internal void Tick() { if ((Util.GetTickCount64() - LastMessageTime) > 15000 && !Focused && !Hidden) { Hidden = true; } if (!Hidden) { MainScaleForm.Render2D(); } if (!CurrentFocused) { return; } Function.Call(Hash.DISABLE_ALL_CONTROL_ACTIONS, 0); } internal void AddMessage(string sender, string msg) { MainScaleForm.CallFunction("ADD_MESSAGE", sender + ":", msg); LastMessageTime = Util.GetTickCount64(); Hidden = false; } internal void OnKeyDown(Keys key) { if (key == Keys.Escape) { Focused = false; CurrentInput = ""; return; } if (key == Keys.PageUp) { MainScaleForm.CallFunction("PAGE_UP"); } else if (key == Keys.PageDown) { MainScaleForm.CallFunction("PAGE_DOWN"); } string keyChar = GetCharFromKey(key, Game.IsKeyPressed(Keys.ShiftKey), false); if (keyChar.Length == 0) { return; } switch (keyChar[0]) { case (char)8: if (CurrentInput.Length > 0) { CurrentInput = CurrentInput.Remove(CurrentInput.Length - 1); MainScaleForm.CallFunction("DELETE_TEXT"); } return; case (char)13: MainScaleForm.CallFunction("ADD_TEXT", "ENTER"); if (!string.IsNullOrWhiteSpace(CurrentInput)) { Main.MainNetworking.SendChatMessage(CurrentInput); } Focused = false; CurrentInput = ""; return; default: CurrentInput += keyChar; MainScaleForm.CallFunction("ADD_TEXT", keyChar); return; } } [DllImport("user32.dll")] internal static extern int ToUnicodeEx(uint virtualKeyCode, uint scanCode, byte[] keyboardState, [Out, MarshalAs(UnmanagedType.LPWStr, SizeConst = 64)] StringBuilder receivingBuffer, int bufferSize, uint flags, IntPtr kblayout); internal static string GetCharFromKey(Keys key, bool shift, bool altGr) { StringBuilder buf = new StringBuilder(256); byte[] keyboardState = new byte[256]; if (shift) { keyboardState[(int)Keys.ShiftKey] = 0xff; } if (altGr) { keyboardState[(int)Keys.ControlKey] = 0xff; keyboardState[(int)Keys.Menu] = 0xff; } ToUnicodeEx((uint)key, 0, keyboardState, buf, 256, 0, InputLanguage.CurrentInputLanguage.Handle); return buf.ToString(); } } }
27.166667
109
0.454779
[ "MIT" ]
jr111/GTACoop-R
Client/Chat.cs
5,055
C#
// Project: Daggerfall Tools For Unity // Copyright: Copyright (C) 2009-2019 Daggerfall Workshop // Web Site: http://www.dfworkshop.net // License: MIT License (http://www.opensource.org/licenses/mit-license.php) // Source Code: https://github.com/Interkarma/daggerfall-unity // Original Author: Gavin Clayton (interkarma@dfworkshop.net) // Contributors: Numidium // // Notes: // using UnityEngine; using System; using System.Collections; using System.Collections.Generic; using DaggerfallWorkshop.Utility; using DaggerfallConnect; using DaggerfallConnect.Arena2; using DaggerfallConnect.Utility; using DaggerfallWorkshop.Game.Serialization; using DaggerfallWorkshop.Game.UserInterfaceWindows; using DaggerfallWorkshop.Game.Entity; using DaggerfallWorkshop.Game.MagicAndEffects; namespace DaggerfallWorkshop.Game { /// <summary> /// Assist player controller to enter and exit building interiors and dungeons. /// Should be attached to player object with PlayerGPS for climate tracking. /// </summary> public class PlayerEnterExit : MonoBehaviour { const HideFlags defaultHideFlags = HideFlags.None; UnderwaterFog underwaterFog; DaggerfallUnity dfUnity; CharacterController controller; bool isPlayerInside = false; bool isPlayerInsideDungeon = false; bool isPlayerInsideDungeonCastle = false; bool isPlayerInsideSpecialArea = false; bool isPlayerInsideOpenShop = false; bool isPlayerSwimming = false; bool isPlayerSubmerged = false; bool isPlayerInSunlight = false; bool isPlayerInHolyPlace = false; bool isRespawning = false; bool lastInteriorStartFlag; bool displayAfloatMessage = false; DaggerfallInterior interior; DaggerfallDungeon dungeon; StreamingWorld world; PlayerGPS playerGPS; Entity.DaggerfallEntityBehaviour player; LevitateMotor levitateMotor; List<StaticDoor> exteriorDoors = new List<StaticDoor>(); public GameObject ExteriorParent; public GameObject InteriorParent; public GameObject DungeonParent; public DaggerfallLocation OverrideLocation; int lastPlayerDungeonBlockIndex = -1; DFLocation.DungeonBlock playerDungeonBlockData = new DFLocation.DungeonBlock(); public short blockWaterLevel = 10000; DFLocation.BuildingTypes buildingType = DFLocation.BuildingTypes.None; ushort factionID = 0; PlayerGPS.DiscoveredBuilding buildingDiscoveryData; DaggerfallLocation holidayTextLocation; bool holidayTextPrimed = false; float holidayTextTimer = 0f; /// <summary> /// Gets player world context. /// </summary> public WorldContext WorldContext { get { return GetWorldContext(); } } /// <summary> /// Gets start flag from most recent interior transition. /// Helps inform other systems if first-time load or enter/exit transition /// </summary> public bool LastInteriorStartFlag { get { return lastInteriorStartFlag; } } /// <summary> /// True when player is inside any structure. /// </summary> public bool IsPlayerInside { get { return isPlayerInside; } } /// <summary> /// True only when player is inside a building. /// </summary> public bool IsPlayerInsideBuilding { get { return (IsPlayerInside && !IsPlayerInsideDungeon); } } /// <summary> /// True only when player is inside a dungeon. /// </summary> public bool IsPlayerInsideDungeon { get { return isPlayerInsideDungeon; } } /// <summary> /// True only when player inside castle blocks of a dungeon. /// For example, main hall in Daggerfall castle. /// </summary> public bool IsPlayerInsideDungeonCastle { get { return isPlayerInsideDungeonCastle; } } /// <summary> /// True only when player inside special blocks of a dungeon. /// For example, treasure room in Daggerfall castle. /// </summary> public bool IsPlayerInsideSpecialArea { get { return isPlayerInsideSpecialArea; } } /// <summary> /// True when player is inside an open shop. /// Set upon entry, so doesn't matter if shop 'closes' with player inside. /// </summary> public bool IsPlayerInsideOpenShop { get { return isPlayerInsideOpenShop; } set { isPlayerInsideOpenShop = value; } } /// <summary> /// True when player is swimming in water. /// </summary> public bool IsPlayerSwimming { get { return isPlayerSwimming; } set { isPlayerSwimming = value; } } /// <summary> /// True when player is submerged in water. /// </summary> public bool IsPlayerSubmerged { get { return isPlayerSubmerged; } } /// <summary> /// True when player is in sunlight. /// </summary> public bool IsPlayerInSunlight { get { return isPlayerInSunlight; } } /// <summary> /// True when player is in darkness. /// Same as !IsPlayerInSunlight. /// </summary> public bool IsPlayerInDarkness { get { return !isPlayerInSunlight; } } /// <summary> /// True when player is in a holy place. /// Holy places include all Temples and guildhalls of the Fighter Trainers (faction #849) /// https://en.uesp.net/wiki/Daggerfall:ClassMaker#Special_Disadvantages /// Refreshed once per game minute. /// </summary> public bool IsPlayerInHolyPlace { get { return isPlayerInHolyPlace; } } /// <summary> /// True when a player respawn is in progress. /// e.g. After loading a game or teleporting back to a marked location. /// </summary> public bool IsRespawning { get { return isRespawning; } } /// <summary> /// Gets current player dungeon. /// Only valid when player is inside a dungeon. /// </summary> public DaggerfallDungeon Dungeon { get { return dungeon; } } /// <summary> /// Gets information about current player dungeon block. /// Only valid when player is inside a dungeon. /// </summary> public DFLocation.DungeonBlock DungeonBlock { get { return playerDungeonBlockData; } } /// <summary> /// Gets current building interior. /// Only valid when player inside building. /// </summary> public DaggerfallInterior Interior { get { return interior; } } /// <summary> /// Gets current building type. /// Only valid when player inside building. /// </summary> public DFLocation.BuildingTypes BuildingType { get { return buildingType; } } /// <summary> /// Gets current building's faction ID. /// </summary> public uint FactionID { get { return factionID; } } /// <summary> /// Gets current building's discovery data. /// Only valid when player is inside a building. /// This is set every time player enters a building and is saved/loaded with each save game. /// Notes: /// Older save games will not carry this data until player exits and enters building again. /// When consuming this property, try to handle empty BuildingDiscoveryData (buildingKey == 0) if possible. /// </summary> public PlayerGPS.DiscoveredBuilding BuildingDiscoveryData { get { return buildingDiscoveryData; } internal set { buildingDiscoveryData = value; } } /// <summary> /// Gets or sets exterior doors of current interior. /// Returns empty array if player not inside. /// </summary> public StaticDoor[] ExteriorDoors { get { return exteriorDoors.ToArray(); } set { SetExteriorDoors(value); } } void Awake() { dfUnity = DaggerfallUnity.Instance; playerGPS = GetComponent<PlayerGPS>(); world = FindObjectOfType<StreamingWorld>(); player = GameManager.Instance.PlayerEntityBehaviour; } void Start() { // Wire event for when player enters a new location PlayerGPS.OnEnterLocationRect += PlayerGPS_OnEnterLocationRect; EntityEffectBroker.OnNewMagicRound += EntityEffectBroker_OnNewMagicRound; levitateMotor = GetComponent<LevitateMotor>(); underwaterFog = new UnderwaterFog(); } void Update() { // Track which dungeon block player is inside of if (dungeon && isPlayerInsideDungeon) { int playerBlockIndex = dungeon.GetPlayerBlockIndex(transform.position); if (playerBlockIndex != lastPlayerDungeonBlockIndex) { lastPlayerDungeonBlockIndex = playerBlockIndex; if (playerBlockIndex != -1) { dungeon.GetBlockData(playerBlockIndex, out playerDungeonBlockData); blockWaterLevel = playerDungeonBlockData.WaterLevel; isPlayerInsideDungeonCastle = playerDungeonBlockData.CastleBlock; SpecialAreaCheck(); } else { blockWaterLevel = 10000; isPlayerInsideDungeonCastle = false; isPlayerInsideSpecialArea = false; } //Debug.Log(string.Format("Player is now inside block {0}", playerDungeonBlockData.BlockName)); } if (playerBlockIndex != -1) { underwaterFog.UpdateFog(blockWaterLevel); } } if (holidayTextPrimed && holidayTextLocation != GameManager.Instance.StreamingWorld.CurrentPlayerLocationObject) { holidayTextTimer = 0; holidayTextPrimed = false; } // Count down holiday text display if (holidayTextTimer > 0) holidayTextTimer -= Time.deltaTime; if (holidayTextTimer <= 0 && holidayTextPrimed) { holidayTextPrimed = false; ShowHolidayText(); } // Player in sunlight or darkness isPlayerInSunlight = DaggerfallUnity.Instance.WorldTime.Now.IsDay && !IsPlayerInside && !GameManager.Instance.PlayerEntity.InPrison; // Do not process underwater logic if not playing game // This prevents player catching breath during load if (!GameManager.Instance.IsPlayingGame()) return; // Underwater swimming logic should only be processed in dungeons at this time if (isPlayerInsideDungeon) { // NOTE: Player's y value in DF unity is 0.95 units off from classic, so subtracting it to get correct comparison if (blockWaterLevel == 10000 || (player.transform.position.y + (50 * MeshReader.GlobalScale) - 0.95f) >= (blockWaterLevel * -1 * MeshReader.GlobalScale)) { isPlayerSwimming = false; levitateMotor.IsSwimming = false; } else { if (!isPlayerSwimming) SendMessage("PlayLargeSplash", SendMessageOptions.DontRequireReceiver); isPlayerSwimming = true; levitateMotor.IsSwimming = true; } bool overEncumbered = (GameManager.Instance.PlayerEntity.CarriedWeight * 4 > 250); if ((overEncumbered && levitateMotor.IsSwimming) && !displayAfloatMessage && !GameManager.Instance.PlayerEntity.IsWaterWalking) { DaggerfallUI.AddHUDText(HardStrings.cannotFloat, 1.75f); displayAfloatMessage = true; } else if ((!overEncumbered || !levitateMotor.IsSwimming) && displayAfloatMessage) { displayAfloatMessage = false; } // Check if player is submerged and needs to start holding breath if (blockWaterLevel == 10000 || (player.transform.position.y + (76 * MeshReader.GlobalScale) - 0.95f) >= (blockWaterLevel * -1 * MeshReader.GlobalScale)) { isPlayerSubmerged = false; } else isPlayerSubmerged = true; } else { // Clear flags when not in a dungeon // don't clear swimming if we're outside on a water tile - MeteoricDragon if (GameManager.Instance.StreamingWorld.PlayerTileMapIndex != 0) isPlayerSwimming = false; isPlayerSubmerged = false; levitateMotor.IsSwimming = false; } } #region Public Methods /// <summary> /// Respawn player at the specified world coordinates, optionally inside dungeon. /// </summary> public void RespawnPlayer( int worldX, int worldZ, bool insideDungeon = false, bool importEnemies = true) { RespawnPlayer(worldX, worldZ, insideDungeon, false, null, false, importEnemies); } /// <summary> /// Respawn player at the specified world coordinates, optionally inside dungeon or building. /// Player can be forced to respawn to closest start marker or origin. /// </summary> public void RespawnPlayer( int worldX, int worldZ, bool insideDungeon, bool insideBuilding, StaticDoor[] exteriorDoors = null, bool forceReposition = false, bool importEnemies = true, bool start = true) { // Mark any existing world data for destruction if (dungeon) { Destroy(dungeon.gameObject); } if (interior) { Destroy(interior.gameObject); } // Deregister all serializable objects SaveLoadManager.DeregisterAllSerializableGameObjects(); // Start respawn process isRespawning = true; SetExteriorDoors(exteriorDoors); StartCoroutine(Respawner(worldX, worldZ, insideDungeon, insideBuilding, forceReposition, importEnemies, start)); } IEnumerator Respawner(int worldX, int worldZ, bool insideDungeon, bool insideBuilding, bool forceReposition, bool importEnemies, bool start = true) { // Wait for end of frame so existing world data can be removed yield return new WaitForEndOfFrame(); // Store if player was inside a dungeon or building before respawning bool playerWasInDungeon = IsPlayerInsideDungeon; bool playerWasInBuilding = IsPlayerInsideBuilding; // Reset dungeon block on new spawn lastPlayerDungeonBlockIndex = -1; playerDungeonBlockData = new DFLocation.DungeonBlock(); // Reset inside state isPlayerInside = false; isPlayerInsideDungeon = false; isPlayerInsideDungeonCastle = false; blockWaterLevel = 10000; // Set player GPS coordinates playerGPS.WorldX = worldX; playerGPS.WorldZ = worldZ; // Set streaming world coordinates DFPosition pos = MapsFile.WorldCoordToMapPixel(worldX, worldZ); world.MapPixelX = pos.X; world.MapPixelY = pos.Y; // Get location at this position ContentReader.MapSummary summary; bool hasLocation = dfUnity.ContentReader.HasLocation(pos.X, pos.Y, out summary); if (!insideDungeon && !insideBuilding) { // Start outside EnableExteriorParent(); if (!forceReposition) { // Teleport to explicit world coordinates world.TeleportToWorldCoordinates(worldX, worldZ); } else { // Force reposition to closest start marker if available world.TeleportToCoordinates(pos.X, pos.Y, StreamingWorld.RepositionMethods.RandomStartMarker); } // Wait until world is ready while (world.IsInit) yield return new WaitForEndOfFrame(); // Raise transition exterior event if player was inside a dungeon or building // This helps inform other systems player has transitioned to exterior without clicking a door or reloading game if (playerWasInDungeon) RaiseOnTransitionDungeonExteriorEvent(); else if (playerWasInBuilding) RaiseOnTransitionExteriorEvent(); } else if (hasLocation && insideDungeon) { // Start in dungeon DFLocation location; world.TeleportToCoordinates(pos.X, pos.Y, StreamingWorld.RepositionMethods.None); dfUnity.ContentReader.GetLocation(summary.RegionIndex, summary.MapIndex, out location); StartDungeonInterior(location, true, importEnemies); world.suppressWorld = true; } else if (hasLocation && insideBuilding && exteriorDoors != null) { // Start in building DFLocation location; world.TeleportToCoordinates(pos.X, pos.Y, StreamingWorld.RepositionMethods.None); dfUnity.ContentReader.GetLocation(summary.RegionIndex, summary.MapIndex, out location); StartBuildingInterior(location, exteriorDoors[0], start); world.suppressWorld = false; } else { // All else fails teleport to map pixel DaggerfallUnity.LogMessage("Something went wrong! Teleporting to origin of nearest map pixel."); EnableExteriorParent(); world.TeleportToCoordinates(pos.X, pos.Y); } // Lower respawn flag isRespawning = false; RaiseOnRespawnerCompleteEvent(); } public void ShowHolidayText() { const int holidaysStartID = 8349; uint minutes = DaggerfallUnity.Instance.WorldTime.DaggerfallDateTime.ToClassicDaggerfallTime(); int holidayId = Formulas.FormulaHelper.GetHolidayId(minutes, GameManager.Instance.PlayerGPS.CurrentRegionIndex); if (holidayId != 0) { DaggerfallMessageBox messageBox = new DaggerfallMessageBox(DaggerfallUI.UIManager); messageBox.SetTextTokens(holidaysStartID + holidayId); messageBox.ClickAnywhereToClose = true; messageBox.ParentPanel.BackgroundColor = Color.clear; messageBox.ScreenDimColor = new Color32(0, 0, 0, 0); messageBox.Show(); } // Set holiday text timer to a somewhat large value so it doesn't show again and again if the player is repeatedly crossing the // border of a city. holidayTextTimer = 10f; } /// <summary> /// Helper to reposition player to anywhere in world either at load or during player. /// </summary> /// <param name="playerPosition">Player position data.</param> /// <param name="start">Use true if this is a load/start operation, otherwise false.</param> public void RestorePositionHelper(PlayerPositionData_v1 playerPosition, bool start, bool importEnemies) { // Raise reposition flag if terrain sampler changed // This is required as changing terrain samplers will invalidate serialized player coordinates // Make an exception for dungeons as exterior world does not matter bool repositionPlayer = false; if ((playerPosition.terrainSamplerName != DaggerfallUnity.Instance.TerrainSampler.ToString() || playerPosition.terrainSamplerVersion != DaggerfallUnity.Instance.TerrainSampler.Version) && !playerPosition.insideDungeon) { repositionPlayer = true; if (DaggerfallUI.Instance.DaggerfallHUD != null) DaggerfallUI.Instance.DaggerfallHUD.PopupText.AddText("Terrain sampler changed. Repositioning player."); } // Check exterior doors are included in save, we need these to exit building bool hasExteriorDoors; if (playerPosition.exteriorDoors == null || playerPosition.exteriorDoors.Length == 0) hasExteriorDoors = false; else hasExteriorDoors = true; // Raise reposition flag if player is supposed to start indoors but building has no doors if (playerPosition.insideBuilding && !hasExteriorDoors) { repositionPlayer = true; if (DaggerfallUI.Instance.DaggerfallHUD != null) DaggerfallUI.Instance.DaggerfallHUD.PopupText.AddText("Building has no exterior doors. Repositioning player."); } // Start the respawn process based on saved player location if (playerPosition.insideDungeon/* && !repositionPlayer*/) // Do not need to resposition outside for dungeons { // Start in dungeon RespawnPlayer( playerPosition.worldPosX, playerPosition.worldPosZ, true, importEnemies); } else if (playerPosition.insideBuilding && hasExteriorDoors && !repositionPlayer) { // Start in building RespawnPlayer( playerPosition.worldPosX, playerPosition.worldPosZ, playerPosition.insideDungeon, playerPosition.insideBuilding, playerPosition.exteriorDoors, false, false, start); } else { // Start outside RespawnPlayer( playerPosition.worldPosX, playerPosition.worldPosZ, false, false, null, repositionPlayer); } } #endregion #region Building Transitions /// <summary> /// Transition player through an exterior door into building interior. /// </summary> /// <param name="doorOwner">Parent transform owning door array..</param> /// <param name="door">Exterior door player clicked on.</param> public void TransitionInterior(Transform doorOwner, StaticDoor door, bool doFade = false, bool start = true) { // Store start flag lastInteriorStartFlag = start; // Ensure we have component references if (!ReferenceComponents()) return; // Copy owner position to door // This ensures the door itself is all we need to reposition interior // Useful when loading a save and doorOwner is null (as outside world does not exist) if (doorOwner) { door.ownerPosition = doorOwner.position; door.ownerRotation = doorOwner.rotation; } if (!start) { // Update scene cache from serializable state for exterior->interior transition SaveLoadManager.CacheScene(world.SceneName); // Explicitly deregister all stateful objects since exterior isn't destroyed SaveLoadManager.DeregisterAllSerializableGameObjects(true); // Clear all stateful objects from world loose object tracking world.ClearStatefulLooseObjects(); } // Raise event RaiseOnPreTransitionEvent(TransitionType.ToBuildingInterior, door); // Ensure expired rooms are removed GameManager.Instance.PlayerEntity.RemoveExpiredRentedRooms(); // Get climate ClimateBases climateBase = ClimateBases.Temperate; if (OverrideLocation) climateBase = OverrideLocation.Summary.Climate; else if (playerGPS) climateBase = ClimateSwaps.FromAPIClimateBase(playerGPS.ClimateSettings.ClimateType); // Layout interior // This needs to be done first so we know where the enter markers are GameObject newInterior = new GameObject(DaggerfallInterior.GetSceneName(playerGPS.CurrentLocation, door)); newInterior.hideFlags = defaultHideFlags; interior = newInterior.AddComponent<DaggerfallInterior>(); // Try to layout interior // If we fail for any reason, use that old chestnut "this house has nothing of value" try { interior.DoLayout(doorOwner, door, climateBase, buildingDiscoveryData); } catch (Exception e) { DaggerfallUI.AddHUDText(HardStrings.thisHouseHasNothingOfValue); Debug.LogException(e); Destroy(newInterior); RaiseOnFailedTransition(TransitionType.ToBuildingInterior); return; } // Position interior directly inside of exterior // This helps with finding closest enter/exit point relative to player position interior.transform.position = door.ownerPosition + (Vector3)door.buildingMatrix.GetColumn(3); interior.transform.rotation = GameObjectHelper.QuaternionFromMatrix(door.buildingMatrix); // Find closest enter marker to exterior door position within building interior // If a marker is found, it will be used as the new check position to find actual interior door Vector3 closestEnterMarkerPosition; Vector3 checkPosition = DaggerfallStaticDoors.GetDoorPosition(door); if (interior.FindClosestEnterMarker(checkPosition, out closestEnterMarkerPosition)) checkPosition = closestEnterMarkerPosition; // Position player in front of closest interior door Vector3 landingPosition = Vector3.zero; Vector3 foundDoorNormal = Vector3.zero; if (interior.FindClosestInteriorDoor(checkPosition, out landingPosition, out foundDoorNormal)) { landingPosition += foundDoorNormal * (GameManager.Instance.PlayerController.radius + 0.4f); } else { // If no door found position player above closest enter marker if (interior.FindClosestEnterMarker(checkPosition, out landingPosition)) { landingPosition += Vector3.up * (controller.height * 0.6f); } else { // Could not find an door or enter marker, probably not a valid interior Destroy(newInterior); RaiseOnFailedTransition(TransitionType.ToBuildingInterior); return; } } // Enumerate all exterior doors belonging to this building DaggerfallStaticDoors exteriorStaticDoors = interior.ExteriorDoors; if (exteriorStaticDoors && doorOwner) { List<StaticDoor> buildingDoors = new List<StaticDoor>(); for (int i = 0; i < exteriorStaticDoors.Doors.Length; i++) { if (exteriorStaticDoors.Doors[i].recordIndex == door.recordIndex) { StaticDoor newDoor = exteriorStaticDoors.Doors[i]; newDoor.ownerPosition = doorOwner.position; newDoor.ownerRotation = doorOwner.rotation; buildingDoors.Add(newDoor); } } SetExteriorDoors(buildingDoors.ToArray()); } // Assign new interior to parent if (InteriorParent != null) newInterior.transform.parent = InteriorParent.transform; // Cache some information about this interior buildingType = interior.BuildingData.BuildingType; factionID = interior.BuildingData.FactionId; // Set player to landng position transform.position = landingPosition; SetStanding(); EnableInteriorParent(); // Add quest resources GameObjectHelper.AddQuestResourceObjects(SiteTypes.Building, interior.transform, interior.EntryDoor.buildingKey); // Update serializable state from scene cache for exterior->interior transition (unless new/load game) if (!start) SaveLoadManager.RestoreCachedScene(interior.name); // Raise event RaiseOnTransitionInteriorEvent(door, interior); // Fade in from black if (doFade) DaggerfallUI.Instance.FadeBehaviour.FadeHUDFromBlack(); } /// <summary> /// Transition player through an interior door to building exterior. Player must be inside. /// Interior stores information about exterior, no need for extra params. /// </summary> public void TransitionExterior(bool doFade = false) { // Exit if missing required components or not currently inside if (!ReferenceComponents() || !interior || !isPlayerInside) return; // Redirect to coroutine verion for fade support if (doFade) { StartCoroutine(FadedTransitionExterior()); return; } // Perform transition BuildingTransitionExteriorLogic(); } private IEnumerator FadedTransitionExterior() { // Smash to black DaggerfallUI.Instance.FadeBehaviour.SmashHUDToBlack(); yield return new WaitForEndOfFrame(); // Perform transition BuildingTransitionExteriorLogic(); // Increase fade time if outside world not ready // This indicates a first-time transition on fresh load float fadeTime = 0.7f; if (!GameManager.Instance.StreamingWorld.IsInit) fadeTime = 1.5f; // Fade in from black DaggerfallUI.Instance.FadeBehaviour.FadeHUDFromBlack(fadeTime); } private void BuildingTransitionExteriorLogic() { // Raise event RaiseOnPreTransitionEvent(TransitionType.ToBuildingExterior); // Update scene cache from serializable state for interior->exterior transition SaveLoadManager.CacheScene(interior.name); // Find closest door and position player outside of it StaticDoor closestDoor; Vector3 closestDoorPos = DaggerfallStaticDoors.FindClosestDoor(transform.position, ExteriorDoors, out closestDoor); Vector3 normal = DaggerfallStaticDoors.GetDoorNormal(closestDoor); Vector3 position = closestDoorPos + normal * (controller.radius * 3f); world.SetAutoReposition(StreamingWorld.RepositionMethods.Offset, position); EnableExteriorParent(); // Player is now outside building isPlayerInside = false; buildingType = DFLocation.BuildingTypes.None; factionID = 0; // Update serializable state from scene cache for interior->exterior transition SaveLoadManager.RestoreCachedScene(world.SceneName); // Fire event RaiseOnTransitionExteriorEvent(); } #endregion #region Dungeon Transitions /// <summary> /// Transition player through a dungeon entrance door into dungeon interior. /// </summary> /// <param name="doorOwner">Parent transform owning door array.</param> /// <param name="door">Exterior door player clicked on.</param> public void TransitionDungeonInterior(Transform doorOwner, StaticDoor door, DFLocation location, bool doFade = false) { // Ensure we have component references if (!ReferenceComponents()) return; // Reset dungeon block on entering dungeon lastPlayerDungeonBlockIndex = -1; playerDungeonBlockData = new DFLocation.DungeonBlock(); // Override location if specified if (OverrideLocation != null) { DFLocation overrideLocation = dfUnity.ContentReader.MapFileReader.GetLocation(OverrideLocation.Summary.RegionName, OverrideLocation.Summary.LocationName); if (overrideLocation.Loaded) location = overrideLocation; } // Raise event RaiseOnPreTransitionEvent(TransitionType.ToDungeonInterior, door); // Layout dungeon GameObject newDungeon = GameObjectHelper.CreateDaggerfallDungeonGameObject(location, DungeonParent.transform); newDungeon.hideFlags = defaultHideFlags; dungeon = newDungeon.GetComponent<DaggerfallDungeon>(); // Find start marker to position player if (!dungeon.StartMarker) { // Could not find a start marker Destroy(newDungeon); RaiseOnFailedTransition(TransitionType.ToDungeonInterior); return; } EnableDungeonParent(); // Set to start position MovePlayerToMarker(dungeon.StartMarker); // Find closest dungeon exit door to orient player StaticDoor[] doors = DaggerfallStaticDoors.FindDoorsInCollections(dungeon.StaticDoorCollections, DoorTypes.DungeonExit); if (doors != null && doors.Length > 0) { Vector3 doorPos; int doorIndex; if (DaggerfallStaticDoors.FindClosestDoorToPlayer(transform.position, doors, out doorPos, out doorIndex)) { // Set player facing away from door PlayerMouseLook playerMouseLook = GameManager.Instance.PlayerMouseLook; if (playerMouseLook) { Vector3 normal = DaggerfallStaticDoors.GetDoorNormal(doors[doorIndex]); playerMouseLook.SetFacing(normal); } } } // Add quest resources GameObjectHelper.AddQuestResourceObjects(SiteTypes.Dungeon, dungeon.transform); // Raise event RaiseOnTransitionDungeonInteriorEvent(door, dungeon); // Fade in from black if (doFade) DaggerfallUI.Instance.FadeBehaviour.FadeHUDFromBlack(); } /// <summary> /// Starts player inside dungeon with no exterior world. /// </summary> public void StartDungeonInterior(DFLocation location, bool preferEnterMarker = true, bool importEnemies = true) { // Ensure we have component references if (!ReferenceComponents()) return; // Raise event RaiseOnPreTransitionEvent(TransitionType.ToDungeonInterior); // Layout dungeon GameObject newDungeon = GameObjectHelper.CreateDaggerfallDungeonGameObject(location, DungeonParent.transform, importEnemies); newDungeon.hideFlags = defaultHideFlags; dungeon = newDungeon.GetComponent<DaggerfallDungeon>(); GameObject marker = null; if (preferEnterMarker && dungeon.EnterMarker != null) marker = dungeon.EnterMarker; else marker = dungeon.StartMarker; // Find start marker to position player if (!marker) { // Could not find marker DaggerfallUnity.LogMessage("No start or enter marker found for this dungeon. Aborting load."); Destroy(newDungeon); RaiseOnFailedTransition(TransitionType.ToDungeonInterior); return; } EnableDungeonParent(); // Add quest resources - except foes, these are loaded from enemy save data GameObjectHelper.AddQuestResourceObjects(SiteTypes.Dungeon, dungeon.transform, 0, true, false, true); // Set to start position MovePlayerToMarker(marker); // Set player facing north PlayerMouseLook playerMouseLook = GameManager.Instance.PlayerMouseLook; if (playerMouseLook) playerMouseLook.SetFacing(Vector3.forward); // Raise event RaiseOnTransitionDungeonInteriorEvent(new StaticDoor(), dungeon); } /// <summary> /// Starts player inside building with no exterior world. /// </summary> public void StartBuildingInterior(DFLocation location, StaticDoor exteriorDoor, bool start = true) { // Store start flag lastInteriorStartFlag = start; // Ensure we have component references if (!ReferenceComponents()) return; // Discover building GameManager.Instance.PlayerGPS.DiscoverBuilding(exteriorDoor.buildingKey); TransitionInterior(null, exteriorDoor, false, start); } public void DisableAllParents(bool cleanup = true) { if (!GameManager.Instance.IsReady) GameManager.Instance.GetProperties(); if (cleanup) { if (dungeon) Destroy(dungeon.gameObject); if (interior) Destroy(interior.gameObject); } if (ExteriorParent != null) ExteriorParent.SetActive(false); if (InteriorParent != null) InteriorParent.SetActive(false); if (DungeonParent != null) DungeonParent.SetActive(false); } /// <summary> /// Enable ExteriorParent. /// </summary> public void EnableExteriorParent(bool cleanup = true) { if (cleanup) { if (dungeon) Destroy(dungeon.gameObject); if (interior) Destroy(interior.gameObject); SetExteriorDoors(null); } DisableAllParents(false); if (ExteriorParent != null) ExteriorParent.SetActive(true); world.suppressWorld = false; isPlayerInside = false; isPlayerInsideDungeon = false; GameManager.UpdateShadowDistance(); } /// <summary> /// Enable InteriorParent. /// </summary> public void EnableInteriorParent(bool cleanup = true) { if (cleanup) { if (dungeon) Destroy(dungeon.gameObject); } DisableAllParents(false); if (InteriorParent != null) InteriorParent.SetActive(true); isPlayerInside = true; isPlayerInsideDungeon = false; GameManager.UpdateShadowDistance(); } /// <summary> /// Enable DungeonParent. /// </summary> public void EnableDungeonParent(bool cleanup = true) { if (cleanup) { if (interior) { Destroy(interior.gameObject); buildingType = DFLocation.BuildingTypes.None; factionID = 0; } } DisableAllParents(false); if (DungeonParent != null) DungeonParent.SetActive(true); isPlayerInside = true; isPlayerInsideDungeon = true; GameManager.UpdateShadowDistance(); } public void MovePlayerToMarker(GameObject marker) { if (!isPlayerInsideDungeon || !marker) return; // Set player to start position transform.position = marker.transform.position + Vector3.up * (controller.height * 0.6f); // Fix player standing SetStanding(); // Raise event RaiseOnMovePlayerToDungeonStartEvent(); } public void MovePlayerToDungeonStart() { MovePlayerToMarker(dungeon.StartMarker); } /// <summary> /// Player is leaving dungeon, transition them back outside. /// </summary> public void TransitionDungeonExterior(bool doFade = false) { if (!ReferenceComponents() || !dungeon || !isPlayerInsideDungeon) return; // Redirect to coroutine verion for fade support if (doFade) { StartCoroutine(FadedTransitionDungeonExterior()); return; } // Perform transition DungeonTransitionExteriorLogic(); } private IEnumerator FadedTransitionDungeonExterior() { // Smash to black DaggerfallUI.Instance.FadeBehaviour.SmashHUDToBlack(); yield return new WaitForEndOfFrame(); // Perform transition DungeonTransitionExteriorLogic(); // Increase fade time if outside world not ready // This indicates a first-time transition on fresh load float fadeTime = 0.7f; if (!GameManager.Instance.StreamingWorld.IsInit) fadeTime = 1.5f; // Fade in from black DaggerfallUI.Instance.FadeBehaviour.FadeHUDFromBlack(fadeTime); } private void DungeonTransitionExteriorLogic() { // Raise event RaiseOnPreTransitionEvent(TransitionType.ToDungeonExterior); EnableExteriorParent(); // Player is now outside dungeon isPlayerInside = false; isPlayerInsideDungeon = false; isPlayerInsideDungeonCastle = false; lastPlayerDungeonBlockIndex = -1; playerDungeonBlockData = new DFLocation.DungeonBlock(); // Position player to door world.SetAutoReposition(StreamingWorld.RepositionMethods.DungeonEntrance, Vector3.zero); // Raise event RaiseOnTransitionDungeonExteriorEvent(); } public void TransitionDungeonExteriorImmediate() { if (!ReferenceComponents() || !dungeon || !isPlayerInsideDungeon) return; RaiseOnPreTransitionEvent(PlayerEnterExit.TransitionType.ToDungeonExterior); } #endregion #region Private Methods private void SpecialAreaCheck() { if (!isPlayerInsideDungeon) { isPlayerInsideSpecialArea = false; return; } switch (playerDungeonBlockData.BlockName) { case "S0000161.RDB": // Daggerfall treasure room isPlayerInsideSpecialArea = true; break; default: isPlayerInsideSpecialArea = false; break; } } private void SetStanding() { // Snap player to ground RaycastHit hit; Ray ray = new Ray(transform.position, Vector3.down); if (Physics.Raycast(ray, out hit, PlayerHeightChanger.controllerStandingHeight * 2f)) { // Clear falling damage so player doesn't take damage if they transitioned into a dungeon while jumping GameManager.Instance.AcrobatMotor.ClearFallingDamage(); // Position player at hit position plus just over half controller height up Vector3 pos = hit.point; pos.y += controller.height / 2f + 0.25f; transform.position = pos; } } private bool ReferenceComponents() { // Look for required components if (controller == null) controller = GetComponent<CharacterController>(); // Fail if missing required components if (dfUnity == null || controller == null) return false; return true; } private void SetExteriorDoors(StaticDoor[] doors) { exteriorDoors.Clear(); if (doors != null && doors.Length > 0) exteriorDoors.AddRange(doors); } private WorldContext GetWorldContext() { if (!IsPlayerInside) return WorldContext.Exterior; else if (IsPlayerInsideBuilding) return WorldContext.Interior; else if (isPlayerInsideDungeon) return WorldContext.Dungeon; else return WorldContext.Nothing; } #endregion #region Event Arguments /// <summary> /// Types of transition encountered by event system. /// </summary> public enum TransitionType { NotDefined, ToBuildingInterior, ToBuildingExterior, ToDungeonInterior, ToDungeonExterior, } /// <summary> /// Arguments for PlayerEnterExit events. /// All interior/exterior/dungeon transitions use these arguments. /// Valid members will depend on which transition event was fired. /// </summary> public class TransitionEventArgs : System.EventArgs { /// <summary>The type of transition.</summary> public TransitionType TransitionType { get; set; } /// <summary>The exterior StaticDoor clicked to initiate transition. For exterior to interior transitions only.</summary> public StaticDoor StaticDoor { get; set; } /// <summary>The newly instanced building interior. For building interior transitions only.</summary> public DaggerfallInterior DaggerfallInterior { get; set; } /// <summary>The newly instanced dungeon interior. For dungeon interior transitions only.</summary> public DaggerfallDungeon DaggerfallDungeon { get; set; } /// <summary>Constructor.</summary> public TransitionEventArgs() { TransitionType = PlayerEnterExit.TransitionType.NotDefined; StaticDoor = new StaticDoor(); DaggerfallInterior = null; DaggerfallDungeon = null; } /// <summary>Constructor helper.</summary> public TransitionEventArgs(TransitionType transitionType) : base() { this.TransitionType = transitionType; } /// <summary>Constructor helper.</summary> public TransitionEventArgs(TransitionType transitionType, StaticDoor staticDoor, DaggerfallInterior daggerfallInterior = null, DaggerfallDungeon daggerfallDungeon = null) : base() { this.TransitionType = transitionType; this.StaticDoor = staticDoor; this.DaggerfallInterior = daggerfallInterior; this.DaggerfallDungeon = daggerfallDungeon; } } #endregion #region Event Handlers // Notify player when they enter location rect // For exterior towns, print out "You are entering %s". // For exterior dungeons, print out flavour text. private void PlayerGPS_OnEnterLocationRect(DFLocation location) { const int set1StartID = 500; const int set2StartID = 520; if (playerGPS && !isPlayerInside) { if (location.MapTableData.LocationType == DFRegion.LocationTypes.DungeonLabyrinth || location.MapTableData.LocationType == DFRegion.LocationTypes.DungeonKeep || location.MapTableData.LocationType == DFRegion.LocationTypes.DungeonRuin || location.MapTableData.LocationType == DFRegion.LocationTypes.Graveyard) { // Get text ID based on set start and dungeon type index int dungeonTypeIndex = (int)location.MapTableData.DungeonType; int set1ID = set1StartID + dungeonTypeIndex; int set2ID = set2StartID + dungeonTypeIndex; // Select two sets of flavour text based on dungeon type string flavourText1 = DaggerfallUnity.Instance.TextProvider.GetRandomText(set1ID); string flavourText2 = DaggerfallUnity.Instance.TextProvider.GetRandomText(set2ID); // Show flavour text a bit longer than in classic DaggerfallUI.AddHUDText(flavourText1, 3); DaggerfallUI.AddHUDText(flavourText2, 3); } else if (location.MapTableData.LocationType != DFRegion.LocationTypes.Coven && location.MapTableData.LocationType != DFRegion.LocationTypes.HomeYourShips) { // Show "You are entering %s" string youAreEntering = HardStrings.youAreEntering; youAreEntering = youAreEntering.Replace("%s", location.Name); DaggerfallUI.AddHUDText(youAreEntering, 2); // Check room rentals in this location, and display how long any rooms are rented for int mapId = playerGPS.CurrentLocation.MapTableData.MapId; PlayerEntity playerEntity = GameManager.Instance.PlayerEntity; playerEntity.RemoveExpiredRentedRooms(); List<RoomRental_v1> rooms = playerEntity.GetRentedRooms(mapId); if (rooms.Count > 0) { foreach (RoomRental_v1 room in rooms) { string remainingHours = PlayerEntity.GetRemainingHours(room).ToString(); DaggerfallUI.AddHUDText(HardStrings.youHaveRentedRoom.Replace("%s", room.name).Replace("%d", remainingHours), 6); } } if (holidayTextTimer <= 0 && !holidayTextPrimed) { holidayTextTimer = 2.5f; // Short delay to give save game fade-in time to finish holidayTextPrimed = true; } holidayTextLocation = GameManager.Instance.StreamingWorld.CurrentPlayerLocationObject; // note Nystul: this next line is not enough to manage questor dictionary update since player might load a savegame in an interior - // so this never gets triggered and questor list is rebuild always as a consequence // a better thing is if talkmanager handles all this by itself without making changes to PlayerEnterExit necessary and use events/delegates // -> so I will outcomment next line but leave it in so that original author stumbles across this comment // fixed this in TalkManager class // TalkManager.Instance.LastExteriorEntered = location.LocationIndex; } } } private void EntityEffectBroker_OnNewMagicRound() { // Player in holy place isPlayerInHolyPlace = false; if (WorldContext == WorldContext.Interior && interior != null) { if (interior.BuildingData.BuildingType == DFLocation.BuildingTypes.Temple || interior.BuildingData.FactionId == (int)FactionFile.FactionIDs.Fighter_Trainers) isPlayerInHolyPlace = true; } } #endregion #region Events // OnPreTransition - Called PRIOR to any transition, other events called AFTER transition. public delegate void OnPreTransitionEventHandler(TransitionEventArgs args); /// <summary> /// Unlike other events in this class, this one is raised before the transition has been performed. /// It's always followed by <see cref="OnFailedTransition"/> or one of the other events for success. /// </summary> public static event OnPreTransitionEventHandler OnPreTransition; protected virtual void RaiseOnPreTransitionEvent(TransitionType transitionType) { TransitionEventArgs args = new TransitionEventArgs(transitionType); if (OnPreTransition != null) OnPreTransition(args); } protected virtual void RaiseOnPreTransitionEvent(TransitionType transitionType, StaticDoor staticDoor) { TransitionEventArgs args = new TransitionEventArgs(transitionType, staticDoor); if (OnPreTransition != null) OnPreTransition(args); } // OnTransitionInterior public delegate void OnTransitionInteriorEventHandler(TransitionEventArgs args); public static event OnTransitionInteriorEventHandler OnTransitionInterior; protected virtual void RaiseOnTransitionInteriorEvent(StaticDoor staticDoor, DaggerfallInterior daggerfallInterior) { TransitionEventArgs args = new TransitionEventArgs(TransitionType.ToBuildingInterior, staticDoor, daggerfallInterior); if (OnTransitionInterior != null) OnTransitionInterior(args); } // OnTransitionExterior public delegate void OnTransitionExteriorEventHandler(TransitionEventArgs args); public static event OnTransitionExteriorEventHandler OnTransitionExterior; protected virtual void RaiseOnTransitionExteriorEvent() { TransitionEventArgs args = new TransitionEventArgs(TransitionType.ToBuildingExterior); if (OnTransitionExterior != null) OnTransitionExterior(args); } // OnTransitionDungeonInterior public delegate void OnTransitionDungeonInteriorEventHandler(TransitionEventArgs args); public static event OnTransitionDungeonInteriorEventHandler OnTransitionDungeonInterior; protected virtual void RaiseOnTransitionDungeonInteriorEvent(StaticDoor staticDoor, DaggerfallDungeon daggerfallDungeon) { TransitionEventArgs args = new TransitionEventArgs(TransitionType.ToDungeonInterior, staticDoor, null, daggerfallDungeon); if (OnTransitionDungeonInterior != null) OnTransitionDungeonInterior(args); } // OnTransitionDungeonExterior public delegate void OnTransitionDungeonExteriorEventHandler(TransitionEventArgs args); public static event OnTransitionDungeonExteriorEventHandler OnTransitionDungeonExterior; protected virtual void RaiseOnTransitionDungeonExteriorEvent() { TransitionEventArgs args = new TransitionEventArgs(TransitionType.ToDungeonExterior); if (OnTransitionDungeonExterior != null) OnTransitionDungeonExterior(args); } /// <summary> /// This event is raised when a transition has started being performed and <see cref="OnPreTransition"/> /// was fired but it couldn't be finished correctly due to an unexpected issue (i.e when /// <see cref="HardStrings.thisHouseHasNothingOfValue"/> is also shown). /// </summary> public static event Action<TransitionEventArgs> OnFailedTransition; protected virtual void RaiseOnFailedTransition(TransitionType transitionType) { if (OnTransitionInterior != null) OnTransitionInterior(new TransitionEventArgs(transitionType)); } // OnMovePlayerToDungeonStart public delegate void OnMovePlayerToDungeonStartEventHandler(); public static event OnMovePlayerToDungeonStartEventHandler OnMovePlayerToDungeonStart; protected virtual void RaiseOnMovePlayerToDungeonStartEvent() { if (OnMovePlayerToDungeonStart != null) OnMovePlayerToDungeonStart(); } // OnRespawnerComplete public delegate void OnRespawnerCompleteEventHandler(); public static event OnRespawnerCompleteEventHandler OnRespawnerComplete; protected virtual void RaiseOnRespawnerCompleteEvent() { if (OnRespawnerComplete != null) OnRespawnerComplete(); } #endregion } }
40.034955
182
0.589273
[ "MIT" ]
ss-gnalvesteffer/daggerfall-unity
Assets/Scripts/Game/PlayerEnterExit.cs
58,411
C#
using System; using System.Text; namespace Miru { public static class IntegerExtensions { public static string Times(this int value, Func<string> func) { var ret = new StringBuilder(); for (int i = 0; i < value; i++) { ret.Append(func()); } return ret.ToString(); } public static string Times(this int value, Func<int, string> func) { var ret = new StringBuilder(); for (int i = 0; i < value; i++) { ret.Append(func(i)); } return ret.ToString(); } } }
20.575758
74
0.455081
[ "MIT" ]
MiruFx/Miru
src/Miru/IntegerExtensions.cs
681
C#
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ /* * Do not modify this file. This file is generated from the glue-2017-03-31.normal.json service model. */ using System; using System.Collections.Generic; using System.Xml.Serialization; using System.Text; using System.IO; using System.Net; using Amazon.Runtime; using Amazon.Runtime.Internal; namespace Amazon.Glue.Model { /// <summary> /// This is the response object from the UpdateConnection operation. /// </summary> public partial class UpdateConnectionResponse : AmazonWebServiceResponse { } }
29.184211
102
0.732191
[ "Apache-2.0" ]
ChristopherButtars/aws-sdk-net
sdk/src/Services/Glue/Generated/Model/UpdateConnectionResponse.cs
1,109
C#
using online_judge.utility; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace online_judge.leetcode.medium { internal class Problem167 { public int[] TwoSum(int[] numbers, int target) { int index1 = 0, index2 = numbers.Length - 1; while (index1 < index2) { int sum = numbers[index1] + numbers[index2]; if (sum == target) { index1++; index2++; break; } else if (sum < target) { ++index1; } else { --index2; } } Console.WriteLine(Helper.IteratingString(new int[] { index1, index2 })); return new int[] { index1, index2 }; } } }
25.325
85
0.422507
[ "MIT" ]
wallyjue/online_judge
leetcode/C_sharp/online_judge/leetcode/medium/Problem167.cs
1,015
C#
// Unity built-in shader source. Copyright (c) 2016 Unity Technologies. MIT license (see license.txt) using System; using UnityEngine; namespace UnityEditor { internal class TerrainBlendedStandardShaderGUI : ShaderGUI { private enum WorkflowMode { Specular, Metallic, Dielectric } public enum BlendMode { Opaque, Cutout, Fade, // Old school alpha-blending mode, fresnel does not affect amount of transparency Transparent // Physically plausible transparency mode, implemented as alpha pre-multiply } public enum SmoothnessMapChannel { SpecularMetallicAlpha, AlbedoAlpha, } private static class Styles { public static GUIContent uvSetLabel = EditorGUIUtility.TrTextContent("UV Set"); public static GUIContent albedoText = EditorGUIUtility.TrTextContent("Albedo", "Albedo (RGB) and Transparency (A)"); public static GUIContent alphaCutoffText = EditorGUIUtility.TrTextContent("Alpha Cutoff", "Threshold for alpha cutoff"); public static GUIContent specularMapText = EditorGUIUtility.TrTextContent("Specular", "Specular (RGB) and Smoothness (A)"); public static GUIContent metallicMapText = EditorGUIUtility.TrTextContent("Metallic", "Metallic (R) and Smoothness (A)"); public static GUIContent smoothnessText = EditorGUIUtility.TrTextContent("Smoothness", "Smoothness value"); public static GUIContent smoothnessScaleText = EditorGUIUtility.TrTextContent("Smoothness", "Smoothness scale factor"); public static GUIContent smoothnessMapChannelText = EditorGUIUtility.TrTextContent("Source", "Smoothness texture and channel"); public static GUIContent highlightsText = EditorGUIUtility.TrTextContent("Specular Highlights", "Specular Highlights"); public static GUIContent reflectionsText = EditorGUIUtility.TrTextContent("Reflections", "Glossy Reflections"); public static GUIContent normalMapText = EditorGUIUtility.TrTextContent("Normal Map", "Normal Map"); public static GUIContent heightMapText = EditorGUIUtility.TrTextContent("Height Map", "Height Map (G)"); public static GUIContent occlusionText = EditorGUIUtility.TrTextContent("Occlusion", "Occlusion (G)"); public static GUIContent emissionText = EditorGUIUtility.TrTextContent("Color", "Emission (RGB)"); public static GUIContent detailMaskText = EditorGUIUtility.TrTextContent("Detail Mask", "Mask for Secondary Maps (A)"); public static GUIContent detailAlbedoText = EditorGUIUtility.TrTextContent("Detail Albedo x2", "Albedo (RGB) multiplied by 2"); public static GUIContent detailNormalMapText = EditorGUIUtility.TrTextContent("Normal Map", "Normal Map"); public static string primaryMapsText = "Main Maps"; public static string secondaryMapsText = "Secondary Maps"; public static string terrainBlendingText = "Terrain blending"; public static string forwardText = "Forward Rendering Options"; public static string renderingMode = "Rendering Mode"; public static string advancedText = "Advanced Options"; public static readonly string[] blendNames = Enum.GetNames(typeof(BlendMode)); } MaterialProperty blendMode = null; MaterialProperty albedoMap = null; MaterialProperty albedoColor = null; MaterialProperty alphaCutoff = null; MaterialProperty specularMap = null; MaterialProperty specularColor = null; MaterialProperty metallicMap = null; MaterialProperty metallic = null; MaterialProperty smoothness = null; MaterialProperty smoothnessScale = null; MaterialProperty smoothnessMapChannel = null; MaterialProperty highlights = null; MaterialProperty reflections = null; MaterialProperty bumpScale = null; MaterialProperty bumpMap = null; MaterialProperty occlusionStrength = null; MaterialProperty occlusionMap = null; MaterialProperty heigtMapScale = null; MaterialProperty heightMap = null; MaterialProperty emissionColorForRendering = null; MaterialProperty emissionMap = null; MaterialProperty detailMask = null; MaterialProperty detailAlbedoMap = null; MaterialProperty detailNormalMapScale = null; MaterialProperty detailNormalMap = null; MaterialProperty uvSetSecondary = null; MaterialProperty terrainBlendingStart = null; MaterialProperty terrainBlendingEnd = null; MaterialEditor m_MaterialEditor; WorkflowMode m_WorkflowMode = WorkflowMode.Specular; bool m_FirstTimeApply = true; public void FindProperties(MaterialProperty[] props) { blendMode = FindProperty("_Mode", props); albedoMap = FindProperty("_MainTex", props); albedoColor = FindProperty("_Color", props); alphaCutoff = FindProperty("_Cutoff", props); specularMap = FindProperty("_SpecGlossMap", props, false); specularColor = FindProperty("_SpecColor", props, false); metallicMap = FindProperty("_MetallicGlossMap", props, false); metallic = FindProperty("_Metallic", props, false); if (specularMap != null && specularColor != null) m_WorkflowMode = WorkflowMode.Specular; else if (metallicMap != null && metallic != null) m_WorkflowMode = WorkflowMode.Metallic; else m_WorkflowMode = WorkflowMode.Dielectric; smoothness = FindProperty("_Glossiness", props); smoothnessScale = FindProperty("_GlossMapScale", props, false); smoothnessMapChannel = FindProperty("_SmoothnessTextureChannel", props, false); highlights = FindProperty("_SpecularHighlights", props, false); reflections = FindProperty("_GlossyReflections", props, false); bumpScale = FindProperty("_BumpScale", props); bumpMap = FindProperty("_BumpMap", props); heigtMapScale = FindProperty("_Parallax", props); heightMap = FindProperty("_ParallaxMap", props); occlusionStrength = FindProperty("_OcclusionStrength", props); occlusionMap = FindProperty("_OcclusionMap", props); emissionColorForRendering = FindProperty("_EmissionColor", props); emissionMap = FindProperty("_EmissionMap", props); detailMask = FindProperty("_DetailMask", props); detailAlbedoMap = FindProperty("_DetailAlbedoMap", props); detailNormalMapScale = FindProperty("_DetailNormalMapScale", props); detailNormalMap = FindProperty("_DetailNormalMap", props); uvSetSecondary = FindProperty("_UVSec", props); terrainBlendingStart = FindProperty("_TerrainBlendingStart", props); terrainBlendingEnd = FindProperty("_TerrainBlendingEnd", props); } public override void OnGUI(MaterialEditor materialEditor, MaterialProperty[] props) { FindProperties(props); // MaterialProperties can be animated so we do not cache them but fetch them every event to ensure animated values are updated correctly m_MaterialEditor = materialEditor; Material material = materialEditor.target as Material; // Make sure that needed setup (ie keywords/renderqueue) are set up if we're switching some existing // material to a standard shader. // Do this before any GUI code has been issued to prevent layout issues in subsequent GUILayout statements (case 780071) if (m_FirstTimeApply) { MaterialChanged(material, m_WorkflowMode); m_FirstTimeApply = false; } ShaderPropertiesGUI(material); } public void ShaderPropertiesGUI(Material material) { // Use default labelWidth EditorGUIUtility.labelWidth = 0f; // Detect any changes to the material EditorGUI.BeginChangeCheck(); { BlendModePopup(); // Primary properties GUILayout.Label(Styles.primaryMapsText, EditorStyles.boldLabel); DoAlbedoArea(material); DoSpecularMetallicArea(); DoNormalArea(); m_MaterialEditor.TexturePropertySingleLine(Styles.heightMapText, heightMap, heightMap.textureValue != null ? heigtMapScale : null); m_MaterialEditor.TexturePropertySingleLine(Styles.occlusionText, occlusionMap, occlusionMap.textureValue != null ? occlusionStrength : null); m_MaterialEditor.TexturePropertySingleLine(Styles.detailMaskText, detailMask); DoEmissionArea(material); EditorGUI.BeginChangeCheck(); m_MaterialEditor.TextureScaleOffsetProperty(albedoMap); if (EditorGUI.EndChangeCheck()) emissionMap.textureScaleAndOffset = albedoMap.textureScaleAndOffset; // Apply the main texture scale and offset to the emission texture as well, for Enlighten's sake EditorGUILayout.Space(); // Secondary properties GUILayout.Label(Styles.secondaryMapsText, EditorStyles.boldLabel); m_MaterialEditor.TexturePropertySingleLine(Styles.detailAlbedoText, detailAlbedoMap); m_MaterialEditor.TexturePropertySingleLine(Styles.detailNormalMapText, detailNormalMap, detailNormalMapScale); m_MaterialEditor.TextureScaleOffsetProperty(detailAlbedoMap); m_MaterialEditor.ShaderProperty(uvSetSecondary, Styles.uvSetLabel.text); EditorGUILayout.Space(); //Terrain blending GUILayout.Label(Styles.terrainBlendingText, EditorStyles.boldLabel); m_MaterialEditor.RangeProperty(terrainBlendingStart, "Terrain blending start"); m_MaterialEditor.RangeProperty(terrainBlendingEnd, "Terrain blending end"); EditorGUILayout.Space(); // Third properties GUILayout.Label(Styles.forwardText, EditorStyles.boldLabel); if (highlights != null) m_MaterialEditor.ShaderProperty(highlights, Styles.highlightsText); if (reflections != null) m_MaterialEditor.ShaderProperty(reflections, Styles.reflectionsText); } if (EditorGUI.EndChangeCheck()) { foreach (var obj in blendMode.targets) MaterialChanged((Material)obj, m_WorkflowMode); } EditorGUILayout.Space(); // NB renderqueue editor is not shown on purpose: we want to override it based on blend mode GUILayout.Label(Styles.advancedText, EditorStyles.boldLabel); m_MaterialEditor.EnableInstancingField(); m_MaterialEditor.DoubleSidedGIField(); } internal void DetermineWorkflow(MaterialProperty[] props) { if (FindProperty("_SpecGlossMap", props, false) != null && FindProperty("_SpecColor", props, false) != null) m_WorkflowMode = WorkflowMode.Specular; else if (FindProperty("_MetallicGlossMap", props, false) != null && FindProperty("_Metallic", props, false) != null) m_WorkflowMode = WorkflowMode.Metallic; else m_WorkflowMode = WorkflowMode.Dielectric; } public override void AssignNewShaderToMaterial(Material material, Shader oldShader, Shader newShader) { // _Emission property is lost after assigning Standard shader to the material // thus transfer it before assigning the new shader if (material.HasProperty("_Emission")) { material.SetColor("_EmissionColor", material.GetColor("_Emission")); } base.AssignNewShaderToMaterial(material, oldShader, newShader); if (oldShader == null || !oldShader.name.Contains("Legacy Shaders/")) { SetupMaterialWithBlendMode(material, (BlendMode)material.GetFloat("_Mode")); return; } BlendMode blendMode = BlendMode.Opaque; if (oldShader.name.Contains("/Transparent/Cutout/")) { blendMode = BlendMode.Cutout; } else if (oldShader.name.Contains("/Transparent/")) { // NOTE: legacy shaders did not provide physically based transparency // therefore Fade mode blendMode = BlendMode.Fade; } material.SetFloat("_Mode", (float)blendMode); DetermineWorkflow(MaterialEditor.GetMaterialProperties(new Material[] { material })); MaterialChanged(material, m_WorkflowMode); } void BlendModePopup() { EditorGUI.showMixedValue = blendMode.hasMixedValue; var mode = (BlendMode)blendMode.floatValue; EditorGUI.BeginChangeCheck(); mode = (BlendMode)EditorGUILayout.Popup(Styles.renderingMode, (int)mode, Styles.blendNames); if (EditorGUI.EndChangeCheck()) { m_MaterialEditor.RegisterPropertyChangeUndo("Rendering Mode"); blendMode.floatValue = (float)mode; } EditorGUI.showMixedValue = false; } void DoNormalArea() { m_MaterialEditor.TexturePropertySingleLine(Styles.normalMapText, bumpMap, bumpMap.textureValue != null ? bumpScale : null); if (bumpScale.floatValue != 1 && UnityEditorInternal.InternalEditorUtility.IsMobilePlatform(EditorUserBuildSettings.activeBuildTarget)) if (m_MaterialEditor.HelpBoxWithButton( EditorGUIUtility.TrTextContent("Bump scale is not supported on mobile platforms"), EditorGUIUtility.TrTextContent("Fix Now"))) { bumpScale.floatValue = 1; } } void DoAlbedoArea(Material material) { m_MaterialEditor.TexturePropertySingleLine(Styles.albedoText, albedoMap, albedoColor); if (((BlendMode)material.GetFloat("_Mode") == BlendMode.Cutout)) { m_MaterialEditor.ShaderProperty(alphaCutoff, Styles.alphaCutoffText.text, MaterialEditor.kMiniTextureFieldLabelIndentLevel + 1); } } void DoEmissionArea(Material material) { // Emission for GI? if (m_MaterialEditor.EmissionEnabledProperty()) { bool hadEmissionTexture = emissionMap.textureValue != null; // Texture and HDR color controls m_MaterialEditor.TexturePropertyWithHDRColor(Styles.emissionText, emissionMap, emissionColorForRendering, false); // If texture was assigned and color was black set color to white float brightness = emissionColorForRendering.colorValue.maxColorComponent; if (emissionMap.textureValue != null && !hadEmissionTexture && brightness <= 0f) emissionColorForRendering.colorValue = Color.white; // change the GI flag and fix it up with emissive as black if necessary m_MaterialEditor.LightmapEmissionFlagsProperty(MaterialEditor.kMiniTextureFieldLabelIndentLevel, true); } } void DoSpecularMetallicArea() { bool hasGlossMap = false; if (m_WorkflowMode == WorkflowMode.Specular) { hasGlossMap = specularMap.textureValue != null; m_MaterialEditor.TexturePropertySingleLine(Styles.specularMapText, specularMap, hasGlossMap ? null : specularColor); } else if (m_WorkflowMode == WorkflowMode.Metallic) { hasGlossMap = metallicMap.textureValue != null; m_MaterialEditor.TexturePropertySingleLine(Styles.metallicMapText, metallicMap, hasGlossMap ? null : metallic); } bool showSmoothnessScale = hasGlossMap; if (smoothnessMapChannel != null) { int smoothnessChannel = (int)smoothnessMapChannel.floatValue; if (smoothnessChannel == (int)SmoothnessMapChannel.AlbedoAlpha) showSmoothnessScale = true; } int indentation = 2; // align with labels of texture properties m_MaterialEditor.ShaderProperty(showSmoothnessScale ? smoothnessScale : smoothness, showSmoothnessScale ? Styles.smoothnessScaleText : Styles.smoothnessText, indentation); ++indentation; if (smoothnessMapChannel != null) m_MaterialEditor.ShaderProperty(smoothnessMapChannel, Styles.smoothnessMapChannelText, indentation); } public static void SetupMaterialWithBlendMode(Material material, BlendMode blendMode) { switch (blendMode) { case BlendMode.Opaque: material.SetOverrideTag("RenderType", ""); material.SetInt("_SrcBlend", (int)UnityEngine.Rendering.BlendMode.One); material.SetInt("_DstBlend", (int)UnityEngine.Rendering.BlendMode.Zero); material.SetInt("_ZWrite", 1); material.DisableKeyword("_ALPHATEST_ON"); material.DisableKeyword("_ALPHABLEND_ON"); material.DisableKeyword("_ALPHAPREMULTIPLY_ON"); material.renderQueue = -1; break; case BlendMode.Cutout: material.SetOverrideTag("RenderType", "TransparentCutout"); material.SetInt("_SrcBlend", (int)UnityEngine.Rendering.BlendMode.One); material.SetInt("_DstBlend", (int)UnityEngine.Rendering.BlendMode.Zero); material.SetInt("_ZWrite", 1); material.EnableKeyword("_ALPHATEST_ON"); material.DisableKeyword("_ALPHABLEND_ON"); material.DisableKeyword("_ALPHAPREMULTIPLY_ON"); material.renderQueue = (int)UnityEngine.Rendering.RenderQueue.AlphaTest; break; case BlendMode.Fade: material.SetOverrideTag("RenderType", "Transparent"); material.SetInt("_SrcBlend", (int)UnityEngine.Rendering.BlendMode.SrcAlpha); material.SetInt("_DstBlend", (int)UnityEngine.Rendering.BlendMode.OneMinusSrcAlpha); material.SetInt("_ZWrite", 0); material.DisableKeyword("_ALPHATEST_ON"); material.EnableKeyword("_ALPHABLEND_ON"); material.DisableKeyword("_ALPHAPREMULTIPLY_ON"); material.renderQueue = (int)UnityEngine.Rendering.RenderQueue.Transparent; break; case BlendMode.Transparent: material.SetOverrideTag("RenderType", "Transparent"); material.SetInt("_SrcBlend", (int)UnityEngine.Rendering.BlendMode.One); material.SetInt("_DstBlend", (int)UnityEngine.Rendering.BlendMode.OneMinusSrcAlpha); material.SetInt("_ZWrite", 0); material.DisableKeyword("_ALPHATEST_ON"); material.DisableKeyword("_ALPHABLEND_ON"); material.EnableKeyword("_ALPHAPREMULTIPLY_ON"); material.renderQueue = (int)UnityEngine.Rendering.RenderQueue.Transparent; break; } } static SmoothnessMapChannel GetSmoothnessMapChannel(Material material) { int ch = (int)material.GetFloat("_SmoothnessTextureChannel"); if (ch == (int)SmoothnessMapChannel.AlbedoAlpha) return SmoothnessMapChannel.AlbedoAlpha; else return SmoothnessMapChannel.SpecularMetallicAlpha; } static void SetMaterialKeywords(Material material, WorkflowMode workflowMode) { // Note: keywords must be based on Material value not on MaterialProperty due to multi-edit & material animation // (MaterialProperty value might come from renderer material property block) SetKeyword(material, "_NORMALMAP", material.GetTexture("_BumpMap") || material.GetTexture("_DetailNormalMap")); if (workflowMode == WorkflowMode.Specular) SetKeyword(material, "_SPECGLOSSMAP", material.GetTexture("_SpecGlossMap")); else if (workflowMode == WorkflowMode.Metallic) SetKeyword(material, "_METALLICGLOSSMAP", material.GetTexture("_MetallicGlossMap")); SetKeyword(material, "_PARALLAXMAP", material.GetTexture("_ParallaxMap")); SetKeyword(material, "_DETAIL_MULX2", material.GetTexture("_DetailAlbedoMap") || material.GetTexture("_DetailNormalMap")); // A material's GI flag internally keeps track of whether emission is enabled at all, it's enabled but has no effect // or is enabled and may be modified at runtime. This state depends on the values of the current flag and emissive color. // The fixup routine makes sure that the material is in the correct state if/when changes are made to the mode or color. MaterialEditor.FixupEmissiveFlag(material); bool shouldEmissionBeEnabled = (material.globalIlluminationFlags & MaterialGlobalIlluminationFlags.EmissiveIsBlack) == 0; SetKeyword(material, "_EMISSION", shouldEmissionBeEnabled); if (material.HasProperty("_SmoothnessTextureChannel")) { SetKeyword(material, "_SMOOTHNESS_TEXTURE_ALBEDO_CHANNEL_A", GetSmoothnessMapChannel(material) == SmoothnessMapChannel.AlbedoAlpha); } } static void MaterialChanged(Material material, WorkflowMode workflowMode) { SetupMaterialWithBlendMode(material, (BlendMode)material.GetFloat("_Mode")); SetMaterialKeywords(material, workflowMode); } static void SetKeyword(Material m, string keyword, bool state) { if (state) m.EnableKeyword(keyword); else m.DisableKeyword(keyword); } } } // namespace UnityEditor
51.875566
185
0.638493
[ "MIT" ]
bad3p/TerrainBlendin
Assets/TerrainBlending/Scripts/Editor/TerrainBlendedStandardShaderGUI.cs
22,929
C#
// <auto-generated /> using System; using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Infrastructure; using Microsoft.EntityFrameworkCore.Metadata; using Microsoft.EntityFrameworkCore.Migrations; using Microsoft.EntityFrameworkCore.Storage.ValueConversion; using SpyStore.Hol.Dal.EfStructures; namespace SpyStore.Hol.Dal.EfStructures.Migrations { [DbContext(typeof(StoreContext))] [Migration("20190304203258_TSQL")] partial class TSQL { protected override void BuildTargetModel(ModelBuilder modelBuilder) { #pragma warning disable 612, 618 modelBuilder .HasAnnotation("ProductVersion", "2.2.0-rtm-35687") .HasAnnotation("Relational:MaxIdentifierLength", 128) .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); modelBuilder.Entity("SpyStore.Hol.Models.Entities.Category", b => { b.Property<int>("Id") .ValueGeneratedOnAdd() .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); b.Property<string>("CategoryName") .HasMaxLength(50); b.Property<byte[]>("TimeStamp") .IsConcurrencyToken() .ValueGeneratedOnAddOrUpdate(); b.HasKey("Id"); b.ToTable("Categories","Store"); }); modelBuilder.Entity("SpyStore.Hol.Models.Entities.Customer", b => { b.Property<int>("Id") .ValueGeneratedOnAdd() .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); b.Property<string>("EmailAddress") .IsRequired() .HasMaxLength(50); b.Property<string>("FullName") .HasMaxLength(50); b.Property<string>("Password") .IsRequired() .HasMaxLength(50); b.Property<byte[]>("TimeStamp") .IsConcurrencyToken() .ValueGeneratedOnAddOrUpdate(); b.HasKey("Id"); b.HasIndex("EmailAddress") .IsUnique() .HasName("IX_Customers"); b.ToTable("Customers","Store"); }); modelBuilder.Entity("SpyStore.Hol.Models.Entities.Order", b => { b.Property<int>("Id") .ValueGeneratedOnAdd() .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); b.Property<int>("CustomerId"); b.Property<DateTime>("OrderDate") .ValueGeneratedOnAdd() .HasColumnType("datetime") .HasDefaultValueSql("getdate()"); b.Property<DateTime>("ShipDate") .ValueGeneratedOnAdd() .HasColumnType("datetime") .HasDefaultValueSql("getdate()"); b.Property<byte[]>("TimeStamp") .IsConcurrencyToken() .ValueGeneratedOnAddOrUpdate(); b.HasKey("Id"); b.HasIndex("CustomerId"); b.ToTable("Orders","Store"); }); modelBuilder.Entity("SpyStore.Hol.Models.Entities.OrderDetail", b => { b.Property<int>("Id") .ValueGeneratedOnAdd() .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); b.Property<int>("OrderId"); b.Property<int>("ProductId"); b.Property<int>("Quantity"); b.Property<byte[]>("TimeStamp") .IsConcurrencyToken() .ValueGeneratedOnAddOrUpdate(); b.Property<decimal>("UnitCost") .HasColumnType("money"); b.HasKey("Id"); b.HasIndex("OrderId"); b.HasIndex("ProductId"); b.ToTable("OrderDetails","Store"); }); modelBuilder.Entity("SpyStore.Hol.Models.Entities.Product", b => { b.Property<int>("Id") .ValueGeneratedOnAdd() .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); b.Property<int>("CategoryId"); b.Property<decimal>("CurrentPrice") .HasColumnType("money"); b.Property<bool>("IsFeatured"); b.Property<byte[]>("TimeStamp") .IsConcurrencyToken() .ValueGeneratedOnAddOrUpdate(); b.Property<decimal>("UnitCost") .HasColumnType("money"); b.Property<int>("UnitsInStock"); b.HasKey("Id"); b.HasIndex("CategoryId"); b.ToTable("Products","Store"); }); modelBuilder.Entity("SpyStore.Hol.Models.Entities.ShoppingCartRecord", b => { b.Property<int>("Id") .ValueGeneratedOnAdd() .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); b.Property<int>("CustomerId"); b.Property<DateTime?>("DateCreated") .ValueGeneratedOnAdd() .HasColumnType("datetime") .HasDefaultValueSql("getdate()"); b.Property<decimal>("LineItemTotal"); b.Property<int>("ProductId"); b.Property<int>("Quantity") .ValueGeneratedOnAdd() .HasDefaultValue(1); b.Property<byte[]>("TimeStamp") .IsConcurrencyToken() .ValueGeneratedOnAddOrUpdate(); b.HasKey("Id"); b.HasIndex("CustomerId"); b.HasIndex("ProductId"); b.HasIndex("Id", "ProductId", "CustomerId") .IsUnique() .HasName("IX_ShoppingCart"); b.ToTable("ShoppingCartRecords","Store"); }); modelBuilder.Entity("SpyStore.Hol.Models.Entities.Order", b => { b.HasOne("SpyStore.Hol.Models.Entities.Customer", "CustomerNavigation") .WithMany("Orders") .HasForeignKey("CustomerId") .OnDelete(DeleteBehavior.Cascade); }); modelBuilder.Entity("SpyStore.Hol.Models.Entities.OrderDetail", b => { b.HasOne("SpyStore.Hol.Models.Entities.Order", "OrderNavigation") .WithMany("OrderDetails") .HasForeignKey("OrderId") .OnDelete(DeleteBehavior.Cascade); b.HasOne("SpyStore.Hol.Models.Entities.Product", "ProductNavigation") .WithMany("OrderDetails") .HasForeignKey("ProductId") .OnDelete(DeleteBehavior.Cascade); }); modelBuilder.Entity("SpyStore.Hol.Models.Entities.Product", b => { b.HasOne("SpyStore.Hol.Models.Entities.Category", "CategoryNavigation") .WithMany("Products") .HasForeignKey("CategoryId") .OnDelete(DeleteBehavior.Cascade); b.OwnsOne("SpyStore.Hol.Models.Entities.Base.ProductDetails", "Details", b1 => { b1.Property<int>("ProductId") .ValueGeneratedOnAdd() .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); b1.Property<string>("Description") .HasColumnName("Description") .HasMaxLength(3800); b1.Property<string>("ModelName") .HasColumnName("ModelName") .HasMaxLength(50); b1.Property<string>("ModelNumber") .HasColumnName("ModelNumber") .HasMaxLength(50); b1.Property<string>("ProductImage") .HasColumnName("ProductImage") .HasMaxLength(150); b1.Property<string>("ProductImageLarge") .HasColumnName("ProductImageLarge") .HasMaxLength(150); b1.Property<string>("ProductImageThumb") .HasColumnName("ProductImageThumb") .HasMaxLength(150); b1.HasKey("ProductId"); b1.ToTable("Products","Store"); b1.HasOne("SpyStore.Hol.Models.Entities.Product") .WithOne("Details") .HasForeignKey("SpyStore.Hol.Models.Entities.Base.ProductDetails", "ProductId") .OnDelete(DeleteBehavior.Cascade); }); }); modelBuilder.Entity("SpyStore.Hol.Models.Entities.ShoppingCartRecord", b => { b.HasOne("SpyStore.Hol.Models.Entities.Customer", "CustomerNavigation") .WithMany("ShoppingCartRecords") .HasForeignKey("CustomerId") .OnDelete(DeleteBehavior.Cascade); b.HasOne("SpyStore.Hol.Models.Entities.Product", "ProductNavigation") .WithMany("ShoppingCartRecords") .HasForeignKey("ProductId") .OnDelete(DeleteBehavior.Cascade); }); #pragma warning restore 612, 618 } } }
38.982206
133
0.475534
[ "BSD-3-Clause", "MIT" ]
MalikWaseemJaved/presentations
.NETCore/ASP.NETCore/v3.1/SpyStore/SpyStore.Hol.Dal/EfStructures/Migrations/20190304203258_TSQL.Designer.cs
10,956
C#
using System; using NUnit.Framework; using OpenQA.Selenium.Appium; using OpenQA.Selenium.Appium.Windows; using OpenQA.Selenium.Remote; using WinAppDriverPageObjects.Views; namespace WinAppDriverPageObjects { [TestFixture] public class CalculatorPageObjectsTests { private WindowsDriver<WindowsElement> _driver; private CalculatorStandardView _calcStandardView; [SetUp] public void TestInit() { var options = new AppiumOptions(); options.AddAdditionalCapability("app", "Microsoft.WindowsCalculator_8wekyb3d8bbwe!App"); options.AddAdditionalCapability("deviceName", "WindowsPC"); _driver = new WindowsDriver<WindowsElement>(new Uri("http://127.0.0.1:4723"), options); _driver.Manage().Timeouts().ImplicitWait = TimeSpan.FromSeconds(5); _calcStandardView = new CalculatorStandardView(_driver); } [TearDown] public void TestCleanup() { if (_driver != null) { _driver.Quit(); _driver = null; } } [Test] public void Addition() { _calcStandardView.PerformCalculation(5, '+', 7); _calcStandardView.AssertResult(12); } [Test] public void Division() { _calcStandardView.PerformCalculation(8, '/', 1); _calcStandardView.AssertResult(8); } [Test] public void Multiplication() { _calcStandardView.PerformCalculation(9, '*', 9); _calcStandardView.AssertResult(81); } [Test] public void Subtraction() { _calcStandardView.PerformCalculation(9, '-', 1); _calcStandardView.AssertResult(8); } [Test] [TestCase(1, '+', 7, 8)] [TestCase(9, '-', 7, 2)] [TestCase(8, '/', 4, 2)] public void Templatized(int num1, char operation, int num2, decimal result) { _calcStandardView.PerformCalculation(num1, operation, num2); _calcStandardView.AssertResult(result); } } }
26.780488
100
0.577413
[ "Apache-2.0" ]
AutomateThePlanet/AutomateThePlanet-Learning-Series
dotnet/DesktopAutomation-Series/WinAppDriverPageObjects/CalculatorPageObjectsTests.cs
2,198
C#
// ***************************************************************************** // BSD 3-Clause License (https://github.com/ComponentFactory/Krypton/blob/master/LICENSE) // © Component Factory Pty Ltd, 2006 - 2016, All rights reserved. // The software and associated documentation supplied hereunder are the // proprietary information of Component Factory Pty Ltd, 13 Swallows Close, // Mornington, Vic 3931, Australia and are supplied subject to license terms. // // Modifications by Peter Wagner(aka Wagnerp) & Simon Coghlan(aka Smurf-IV) 2017 - 2020. All rights reserved. (https://github.com/Wagnerp/Krypton-Toolkit-Suite-NET-Core) // Version 5.500.0.0 www.ComponentFactory.com // ***************************************************************************** using System.Drawing; using System.Diagnostics; namespace ComponentFactory.Krypton.Ribbon { /// <summary> /// Draws a large image from a gallery. /// </summary> internal class ViewDrawRibbonGroupGalleryImage : ViewDrawRibbonGroupImageBase { #region Static Fields private static readonly Size _largeSize = new Size(32, 32); #endregion #region Instance Fields private readonly KryptonRibbonGroupGallery _ribbonGallery; #endregion #region Identity /// <summary> /// Initialize a new instance of the ViewDrawRibbonGroupGalleryImage class. /// </summary> /// <param name="ribbon">Reference to owning ribbon control.</param> /// <param name="ribbonGallery">Reference to ribbon group gallery definition.</param> public ViewDrawRibbonGroupGalleryImage(KryptonRibbon ribbon, KryptonRibbonGroupGallery ribbonGallery) : base(ribbon) { Debug.Assert(ribbonGallery != null); _ribbonGallery = ribbonGallery; } /// <summary> /// Obtains the String representation of this instance. /// </summary> /// <returns>User readable name of the instance.</returns> public override string ToString() { // Return the class name and instance identifier return "ViewDrawRibbonGroupGalleryImage:" + Id; } #endregion #region Protected /// <summary> /// Gets the size to draw the image. /// </summary> protected override Size DrawSize => _largeSize; /// <summary> /// Gets the image to be drawn. /// </summary> protected override Image DrawImage => _ribbonGallery.ImageLarge; #endregion } }
37.887324
170
0.589963
[ "BSD-3-Clause" ]
Krypton-Suite-Legacy-Archive/Krypton-Toolkit-Suite-NET-Core
Source/Krypton Components/ComponentFactory.Krypton.Ribbon/View Draw/ViewDrawRibbonGroupGalleryImage.cs
2,693
C#
namespace AutoRepair.Catalogs { using AutoRepair.Descriptors; using AutoRepair.Enums; using System; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using UnityEngine; /// <summary> /// This is just a temporary place to store items prior to moving them in to /// more logical catalogs. /// </summary> public partial class Catalog { /// <summary> /// Add mods to list. /// </summary> private void UnsortedMods() { string catalog = "Unsorted"; AddMod(new Review(1751039059u, "Taxes Helper Mod") { Affect = Factor.Budget | Factor.Money, Authors = "Zenya", Catalog = catalog, Compatibility = new Dictionary<ulong, Status>() { { 2090425593uL, Status.Compatible }, // Game Speed mod }, CompatibleWith = GameVersion.SunsetHarbor, Flags = ItemFlags.SourceAvailable, LastSeen = WorkshopDate("10 May, 2020"), Published = WorkshopDate("25 May, 2019"), SourceURL = "https://github.com/ZenyaIse/Cities-Skylines-Tax-Helper", Updated = WorkshopDate("25 May, 2019"), }); AddMod(new Review(411253368uL, "Steam notification mover") { Affect = Factor.UI, Authors = "(unknown)", Catalog = catalog, Compatibility = new Dictionary<ulong, Status>() { { 794268416uL , Status.Incompatible }, // Steamy - More Steam controls }, CompatibleWith = GameVersion.Patch_1_0_6b, Flags = ItemFlags.Abandonware | ItemFlags.ForceMigration | ItemFlags.GameBreaking | ItemFlags.NoWorkshop | ItemFlags.SourceUnavailable, LastSeen = WorkshopDate("5 Nov, 2016"), // was linked to from 794268416uL Published = WorkshopDate("21 Mar, 2015"), // based on adjacent item Removed = WorkshopDate("9 Jul, 2018"), // based on wayback showing green redirect ReplaceWith = 794268416uL, // Steamy - More Steam controls Suppress = Warning.MissingArchiveURL, Updated = WorkshopDate("21 Mar, 2015"), // unable to determine if there were any updates }); AddMod(new Review(814102166uL, "Image Overlay") { Affect = Factor.UI, Authors = "Lanceris", Catalog = catalog, Compatibility = new Dictionary<ulong, Status>() { { 1864205702uL, Status.Incompatible }, // 地图图片叠加 Image Overlay { 814102166uL , Status.Incompatible }, // Image Overlay { 662933818uL , Status.Incompatible }, // OverLayer v2 { 421400880uL , Status.Incompatible }, // BetterImageOverlay { 413748580uL , Status.Incompatible }, // ImageOverlay }, CompatibleWith = GameVersion.SunsetHarbor, ContinuationOf = 421400880uL, // BetterImageOverlay Flags = ItemFlags.Abandonware | ItemFlags.SourceAvailable | ItemFlags.Unreliable, LastSeen = WorkshopDate("5 May, 2020"), Notes = new Dictionary<ulong, string>() { { NOTE, "Template PNG image with all tiles marked: https://i.imgur.com/12u8Jm7.png" }, { NOTE, "Some users report the keyboard shortcuts no longer work; but it does work for other users." }, { NOTE, "Image must be valid PNG file for the mod to work; try different colour depth and make dimensions 'power of 2' (see wikipedia) for best results." }, { NOTE, "It needs to load image from disk; if you get 'Unauthorized Access' violantion, try running game as Administrator user." }, }, Published = WorkshopDate("7 Dec, 2016"), SourceURL = "https://github.com/lanceris/EvenBetterImageOverlay", Updated = WorkshopDate("19 Jul, 2018"), }); AddMod(new Review(421400880uL, "BetterImageOverlay") { Affect = Factor.UI, Authors = "Omegote", BrokenBy = GameVersion.NaturalDisasters, Catalog = catalog, Compatibility = new Dictionary<ulong, Status>() { { 1864205702uL, Status.Incompatible }, // 地图图片叠加 Image Overlay { 814102166uL , Status.Incompatible }, // Image Overlay { 662933818uL , Status.Incompatible }, // OverLayer v2 { 421400880uL , Status.Incompatible }, // BetterImageOverlay { 413748580uL , Status.Incompatible }, // ImageOverlay }, CompatibleWith = GameVersion.Stadiums, ContinuationOf = 413748580uL, // ImageOverlay Flags = ItemFlags.Abandonware | ItemFlags.BrokenByUpdate | ItemFlags.ForceMigration | ItemFlags.GameBreaking | ItemFlags.Obsolete | ItemFlags.SourceUnavailable, LastSeen = WorkshopDate("5 May, 2020"), Published = WorkshopDate("7 Apr, 2015"), ReplaceWith = 814102166uL, // Image Overlay Updated = WorkshopDate("7 Apr, 2015"), }); AddMod(new Review(413748580uL, "ImageOverlay") { Affect = Factor.UI, Authors = "Play Nicely", BrokenBy = GameVersion.NaturalDisasters, // possibly earlier (1.7.?) Catalog = catalog, Compatibility = new Dictionary<ulong, Status>() { { 1864205702uL, Status.Incompatible }, // 地图图片叠加 Image Overlay { 814102166uL , Status.Incompatible }, // Image Overlay { 662933818uL , Status.Incompatible }, // OverLayer v2 { 421400880uL , Status.Incompatible }, // BetterImageOverlay { 413748580uL , Status.Incompatible }, // ImageOverlay }, CompatibleWith = GameVersion.Stadiums, Flags = ItemFlags.Abandonware | ItemFlags.BrokenByUpdate | ItemFlags.ForceMigration | ItemFlags.GameBreaking | ItemFlags.Obsolete | ItemFlags.SourceUnavailable, LastSeen = WorkshopDate("5 May, 2020"), Published = WorkshopDate("26 Mar, 2015"), ReplaceWith = 814102166uL, // Image Overlay Updated = WorkshopDate("26 Mar, 2015"), }); AddMod(new Review(662933818uL, "OverLayer v2") { Affect = Factor.UI, Authors = "princekolt", Catalog = catalog, Compatibility = new Dictionary<ulong, Status>() { { 1864205702uL, Status.Incompatible }, // 地图图片叠加 Image Overlay { 814102166uL , Status.Incompatible }, // Image Overlay { 662933818uL , Status.Incompatible }, // OverLayer v2 { 421400880uL , Status.Incompatible }, // BetterImageOverlay { 413748580uL , Status.Incompatible }, // ImageOverlay }, CompatibleWith = GameVersion.SunsetHarbor, Flags = ItemFlags.Abandonware | ItemFlags.SourceAvailable | ItemFlags.Unreliable, LastSeen = WorkshopDate("5 May, 2020"), Notes = new Dictionary<ulong, string>() { { NOTE, "Template PNG image with all tiles marked: https://i.imgur.com/12u8Jm7.png" }, { NOTE, "Some users report the keyboard shortcuts no longer work; but it does work for other users." }, { NOTE, "Image must be valid PNG file for the mod to work; try different colour depth and make dimensions 'power of 2' (see wikipedia) for best results." }, { NOTE, "It needs to load image from disk; if you get 'Unauthorized Access' violantion, try running game as Administrator user." }, }, Published = WorkshopDate("10 Apr, 2016"), SourceURL = "https://github.com/brunophilipe/OverLayer", Updated = WorkshopDate("28 May, 2016"), }); AddMod(new Review(1864205702uL, "地图图片叠加 Image Overlay") { Affect = Factor.UI, Authors = "TIMIYANG", Catalog = catalog, CloneOf = 814102166uL, // Image Overlay Compatibility = new Dictionary<ulong, Status>() { { 1864205702uL, Status.Incompatible }, // 地图图片叠加 Image Overlay { 814102166uL , Status.Incompatible }, // Image Overlay { 662933818uL , Status.Incompatible }, // OverLayer v2 { 421400880uL , Status.Incompatible }, // BetterImageOverlay { 413748580uL , Status.Incompatible }, // ImageOverlay }, CompatibleWith = GameVersion.SunsetHarbor, Flags = ItemFlags.Abandonware | ItemFlags.SourceUnavailable | ItemFlags.Unreliable, LastSeen = WorkshopDate("5 May, 2020"), Published = WorkshopDate("15 Sep, 2019"), Updated = WorkshopDate("15 Sep, 2019"), }); AddMod(new Review(1623509958uL, "Real Gas Station") { Affect = Factor.Vehicles, Authors = "pcfantasy, Ciar Aon", Catalog = catalog, Compatibility = new Dictionary<ulong, Status>() { { 2040656402uL, Status.Required }, // Harmony 2.0.0.9 (Mod Dependency) { 1908304789uL, Status.Required }, // Gas Station(w/o NE2) - required asset { 1785774902uL, Status.Compatible }, // Transfer Info (beta) { 1739993783uL, Status.Incompatible }, // Cargo Info (Fix) { 1674732053uL, Status.Compatible }, // Employ Overeducated Workers V2 (1.11+) { 1435741602uL, Status.Incompatible }, // Snooper { 1114249433uL, Status.Incompatible }, // Employ Overeducated Workers (1.10+) { 1072157697uL, Status.Incompatible }, // Cargo Info { 569008960uL , Status.Incompatible }, // Employ Overeducated Workers }, CompatibleWith = GameVersion.SunsetHarbor, Flags = ItemFlags.SourceAvailable, LastSeen = WorkshopDate("10 May, 2020"), Published = WorkshopDate("13 Jan, 2019"), SourceURL = "https://github.com/pcfantasy/RealGasStation", Updated = WorkshopDate("8 May, 2020"), }); // https://github.com/pcfantasy/RealCity/blob/master/Resources/incompatible_mods.txt // https://steamcommunity.com/workshop/filedetails/discussion/1192503086/1488866180603720344/ AddMod(new Review(1192503086uL, "Real City V9.0.03.14") { Affect = Factor.Employment | Factor.Money, Authors = "pcfantasy, Singlewolf", Catalog = catalog, Compatibility = new Dictionary<ulong, Status>() { { 2064509439uL, Status.Incompatible }, // TrafficManager { 2040656402uL, Status.Required }, // Harmony 2.0.0.9 (Mod Dependency) { 1957033250uL, Status.Incompatible }, // TrafficManager Fixed for industry DLC { 1893036262uL, Status.MinorIssues }, // Mayor's Dashboard v2 (includes code from Export Electricity) { 1806963141uL, Status.Compatible }, // TM:PE v11.1.2 LABS { 1739993783uL, Status.Incompatible }, // Cargo Info (Fix) { 1674732053uL, Status.Compatible }, // Employ Overeducated Workers V2 (1.11+) { 1637663252uL, Status.Compatible }, // TM:PE V11 STABLE { 1604291910uL, Status.Incompatible }, // 498363759 Traffic Manager + Improved AI { 1562650024uL, Status.Incompatible }, // Rebalanced Industries { 1553517176uL, Status.MinorIssues }, // Specialized Industry Fix Redux { 1546870472uL, Status.Incompatible }, // TrafficManager Fixed for industry DLC { 1435741602uL, Status.Incompatible }, // Snooper { 1348361731uL, Status.Incompatible }, // Traffic Manager: President Edition ALPHA/DEBUG { 1181352643uL, Status.Incompatible }, // District Service Limit 3.0 { 1114249433uL, Status.Incompatible }, // Employ Overeducated Workers (1.10+) { 1072157697uL, Status.Incompatible }, // Cargo Info { 702070768uL , Status.MinorIssues }, // Export Electricity { 583429740uL , Status.Incompatible }, // Traffic Manager: President Edition [STABLE] { 569008960uL , Status.Incompatible }, // Employ Overeducated Workers { 519781146uL , Status.Incompatible }, // Difficulty Tuning { 409240984uL , Status.Incompatible }, // Difficulty Options // todo: minor incompat - list money mods here }, CompatibleWith = GameVersion.SunsetHarbor, Flags = ItemFlags.Laggy // causes lag on big cities | ItemFlags.Localised | ItemFlags.SourceAvailable, Languages = new[] { "en", "ru", "zh", "zh-cn" }, // https://github.com/pcfantasy/RealCity/blob/master/Resources LastSeen = WorkshopDate("10 May, 2020"), Locale = "en", Published = WorkshopDate("5 Nov, 2017"), SourceURL = "https://github.com/pcfantasy/RealCity/", Updated = WorkshopDate("5 May, 2020"), }); AddMod(new Review(1312735149u, "[OUTDATED] Klyte Commons") { Affect = Factor.Other, Authors = "Klyte45", BrokenBy = GameVersion.SunsetHarbor, Catalog = catalog, Compatibility = new Dictionary<ulong, Status>() { { 1553517176uL, Status.Incompatible }, // Specialized Industry Fix Redux { 543722850uL , Status.Incompatible }, // Network Skins (Park Life compatible) }, CompatibleWith = GameVersion.Campus, Flags = ItemFlags.Abandonware | ItemFlags.BrokenByUpdate | ItemFlags.Obsolete // no longer required for any of Klyte mods | ItemFlags.SourceAvailable, LastSeen = WorkshopDate("5 May, 2020"), Notes = new Dictionary<ulong, string>() { { NOTE, "This mod is no longer required, you can unsubscribe it." }, { NOTE, "This mod causes game to exit to desktop when trying to exit to Main Menu." }, }, Published = WorkshopDate("25 Feb, 2018"), SourceURL = "https://github.com/klyte45/KlyteCommons", Updated = WorkshopDate("9 Jun, 2019"), }); AddMod(new Review(845665815uL, "CSL Map View") { Affect = Factor.Other, Authors = "Gansaku", Catalog = catalog, Compatibility = new Dictionary<ulong, Status>() { }, CompatibleWith = GameVersion.SunsetHarbor, Flags = ItemFlags.Localised | ItemFlags.SourceUnavailable, Languages = new[] { "de", "en", "fr", "ja", "ko", "ru", "zh-cn", "zh-tw" }, LastSeen = WorkshopDate("3 May, 2020"), Locale = "en", Notes = new Dictionary<ulong, string>() { { NOTE, "Command line parameters: https://github.com/gansaku/CSLMapView/wiki/Command-line-parameters" }, { NOTE, "Translation resources: https://github.com/gansaku/CSLMapView/" }, }, Published = WorkshopDate("19 Jan, 2017"), Updated = WorkshopDate("11 Apr, 2020"), }); // OS compatibility for 845665815uL switch (Application.platform) { case RuntimePlatform.OSXPlayer: Reviews[845665815uL].Notes.Add(NOTE, "This mod requires a Windows .exe file to work, it is not compatible with Mac OS/X."); break; case RuntimePlatform.LinuxPlayer: Reviews[845665815uL].Notes.Add(NOTE, "To run on Linux, see: https://steamcommunity.com/workshop/filedetails/discussion/845665815/1776010325130246251/"); break; } AddMod(new Review(856602624uL, "Sandiego") { Affect = Factor.Other, Authors = "Tailgunner", Catalog = catalog, Compatibility = new Dictionary<ulong, Status>() { // prolly incompat with all toolbar mods }, CompatibleWith = GameVersion.Patch_1_11_1_f4, Flags = ItemFlags.Abandonware | ItemFlags.SourceUnavailable, LastSeen = WorkshopDate("3 May, 2020"), Notes = new Dictionary<ulong, string>() { { NOTE, "Double-clicking a building in build menus will center map camera on fist instance of that building." }, { NOTE, "This mod is probably incompatible with any mod that changes the toolbars (unconfirmed)." }, }, Published = WorkshopDate("4 Feb, 2017"), Updated = WorkshopDate("6 Feb, 2017"), }); AddMod(new Review(878991312uL, "Prop It Up! v1.4.4") { Affect = Factor.PlaceAndMove | Factor.Props | Factor.Trees | Factor.UI, Authors = "Judazzz, BloodyPenguin", //BrokenBy = GameVersion.SunsetHarbor, Catalog = catalog, Compatibility = new Dictionary<ulong, Status>() { }, CompatibleWith = GameVersion.ParadoxLauncher, Flags = ItemFlags.Abandonware //| ItemFlags.BrokenByUpdate | ItemFlags.Laggy | ItemFlags.SlowLoad | ItemFlags.SourceAvailable | ItemFlags.Unreliable, LastSeen = WorkshopDate("3 May, 2020"), Notes = new Dictionary<ulong, string>() { { NOTE, "Runs a lot of code in OnUpdate() = can cause lag in-game." }, { NOTE, "User guide: https://steamcommunity.com/workshop/filedetails/discussion/878991312/133259227529823319/" }, { NOTE, "Sunset Harbor: Sometimes causes errors when a save is loaded, but mod still seems to work after that." }, { NOTE, "Sunset Harbor: Some users say tree replacement features are broken." }, { NOTE, "Sunset Harbor: Some users say it crashes when replacing props." }, }, Published = WorkshopDate("7 Mar, 2017"), SourceURL = "https://github.com/Judazzz/CitiesSkylines-PropItUp", Updated = WorkshopDate("3 Mar, 2018"), }); AddMod(new Review(911295408uL, "Prop Scaling 0.3 [Experimental ALPHA]") { Affect = Factor.Props, Authors = "TPB", Catalog = catalog, Compatibility = new Dictionary<ulong, Status>() { }, Flags = ItemFlags.SourceUnavailable | ItemFlags.Unreliable, LastSeen = WorkshopDate("3 May, 2020"), Notes = new Dictionary<ulong, string>() { { NOTE, "The mod takes effect whilst placing props on the map:" }, { NOTE, "Press Ctrl + Up/Down to incease/decrease min scale." }, { NOTE, "Press Alt + Up/Down to incease/decrease max scale." }, { NOTE, "Press Ctrl + Alt + Up/Down to incease/decrease both min and max scale." }, { NOTE, "With shortcuts above, pressing Right arrow will increase/decrease faster." }, { NOTE, "Press Home to reset to default." }, }, Published = WorkshopDate("23 Apr, 2017"), Updated = WorkshopDate("5 May, 2017"), }); AddMod(new Review(903347963uL, "Transparent Selectors") { Affect = Factor.PlaceAndMove | Factor.UI, Authors = "Ronyx69, TPB", Catalog = catalog, Compatibility = new Dictionary<ulong, Status>() { { 1764637396uL, Status.Incompatible }, // Toggle It! { 1540147921uL, Status.Compatible }, // Grid be Gone { 1536223783uL, Status.Compatible }, // Hide Selectors }, CompatibleWith = GameVersion.SunsetHarbor, Flags = ItemFlags.SourceAvailable, LastSeen = WorkshopDate("3 May, 2020"), Published = WorkshopDate("11 Apr, 2017"), SourceURL = "https://gist.github.com/ronyx69/e556609f78efd918aa5895261d38d78e", Updated = WorkshopDate("12 Apr, 2017"), }); AddMod(new Review(2055972178uL, "Custom Zone Mixer") { Affect = Factor.Zoning, Authors = "Klyte45", Catalog = catalog, Compatibility = new Dictionary<ulong, Status>() { { 2055972178uL, Status.Incompatible }, // Custom Zone Mixer { 1800844556uL, Status.Incompatible }, // Zone Mixer 0 (Beta) }, CompatibleWith = GameVersion.SunsetHarbor, ContinuationOf = 1800844556uL, // Zone Mixer 0 (Beta) Flags = ItemFlags.SaveAltering | ItemFlags.SourceAvailable, LastSeen = WorkshopDate("3 May, 2020"), Notes = new Dictionary<ulong, string>() { { NOTE, "Tutorial video explains how to use it, and also how to safely remove it without breaking save game: https://www.youtube.com/watch?v=_MAeV4mkAV8" }, }, Published = WorkshopDate("10 Apr, 2020"), SourceURL = "https://github.com/klyte45/ZoneMixer", Updated = WorkshopDate("11 Apr, 2020"), UserModInspected = true, }); AddMod(new Review(1800844556uL, "Zone Mixer 0 (Beta)") { Affect = Factor.Zoning, Authors = "Klyte45", Catalog = catalog, Compatibility = new Dictionary<ulong, Status>() { { 2055972178uL, Status.Incompatible }, // Custom Zone Mixer { 1800844556uL, Status.Incompatible }, // Zone Mixer 0 (Beta) }, Flags = ItemFlags.Abandonware | ItemFlags.ForceMigration | ItemFlags.GameBreaking | ItemFlags.NoWorkshop // removed ~10 Apr 2020 | ItemFlags.Obsolete // replacement version available | ItemFlags.SourceAvailable, LastSeen = WorkshopDate("26 Mar, 2020"), Published = WorkshopDate("12 Jul, 2019"), // based on adjacent workshop item Removed = WorkshopDate("10 Apr, 2020"), ReplaceWith = 2055972178uL, // Custom Zone Mixer SourceURL = "https://github.com/klyte45/ZoneMixer", Suppress = Warning.MissingArchiveURL, Updated = WorkshopDate("16 Jul, 2019"), // guess based on github commits UserModInspected = true, }); AddMod(new Review(2044145894uL, "Dropouts Sunset Fix") { Affect = Factor.Education, Authors = "Bobinator The Destroyer!", Catalog = catalog, Compatibility = new Dictionary<ulong, Status>() { { 2044145894uL, Status.Incompatible }, // Dropouts Sunset Fix { 506982407uL , Status.Incompatible }, // Dropouts }, CompatibleWith = GameVersion.SunsetHarbor, ContinuationOf = 506982407uL, // Dropouts Flags = ItemFlags.SourceAvailable, LastSeen = WorkshopDate("5 May, 2020"), Notes = new Dictionary<ulong, string>() { { NOTE, "Enacting the 'Education Boost' city/district policy will reduce number of dropouts." }, }, Published = WorkshopDate("1 Apr, 2020"), SourceURL = "https://github.com/AbitFishy/CitiesSkylinesDropoutsModSunsetHarborFix", Updated = WorkshopDate("1 Apr, 2020"), }); AddMod(new Review(506982407uL, "Dropouts") { Affect = Factor.Education, Authors = "FrF", BrokenBy = GameVersion.SunsetHarbor, Catalog = catalog, Compatibility = new Dictionary<ulong, Status>() { { 2044145894uL, Status.Incompatible }, // Dropouts Sunset Fix { 506982407uL , Status.Incompatible }, // Dropouts }, CompatibleWith = GameVersion.Campus, Flags = ItemFlags.Abandonware | ItemFlags.BrokenByUpdate | ItemFlags.ForceMigration | ItemFlags.GameBreaking | ItemFlags.Obsolete | ItemFlags.SourceAvailable, LastSeen = WorkshopDate("5 May, 2020"), Notes = new Dictionary<ulong, string>() { { NOTE, "Sunset Harbor: Causes '.Citizen.m_age' errors which break game." }, }, Published = WorkshopDate("26 Aug, 2015"), ReplaceWith = 2044145894uL, // Dropouts Sunset Fix SourceURL = "https://github.com/markbt/CitiesSkylinesDropoutsMod", Updated = WorkshopDate("26 Aug, 2015"), }); AddMod(new Review(2040656402uL, "Harmony") { Affect = Factor.Other, Authors = "boformer", Catalog = catalog, Compatibility = new Dictionary<ulong, Status>() { { 2059655996uL, Status.Compatible }, // [Beta] PRT-2 { 1440928803uL, Status.Compatible }, // Parallel Road Tool { 1400711138uL, Status.Compatible }, // [BETA] Parallel Road Tool }, CompatibleWith = GameVersion.Active, Flags = ItemFlags.SourceAvailable, LastSeen = WorkshopDate("3 May, 2020"), Notes = new Dictionary<ulong, string>() { { NOTE, "This is a dependency for multiple mods, do not remove." }, }, Published = WorkshopDate("30 Mar, 2020"), SourceURL = "https://github.com/boformer/CitiesHarmony", Updated = WorkshopDate("10 Apr, 2020"), }); // looks like translated clone of Favorite Cims mod AddMod(new Review(1985556066uL, "4546 (Fav Cims)") { Affect = Factor.Other, Authors = "暮", BrokenBy = GameVersion.SunsetHarbor, Catalog = catalog, CloneOf = 426460372uL, // Favorite Cims Compatibility = new Dictionary<ulong, Status>() { { 426460372uL, Status.Incompatible }, // Favorite Cims }, CompatibleWith = GameVersion.ParadoxLauncher, Flags = ItemFlags.Abandonware | ItemFlags.BrokenByUpdate | ItemFlags.SourceUnavailable, LastSeen = WorkshopDate("3 May, 2020"), Published = WorkshopDate("1 Feb, 2020"), ReplaceWith = 426460372uL, // Favorite Cims Suppress = Warning.OlderReplacement, Updated = WorkshopDate("1 Feb, 2020"), }); // Apparently creates some sort of biogas harvesting building that's // dependent on the number of plants in close proximity. AddMod(new Review(1920431318uL, "Biogas-pw") { Affect = Factor.Other, Authors = "dolaritar", Catalog = catalog, Compatibility = new Dictionary<ulong, Status>() { // todo }, // It changes building AI both in editor and game, but doesn't reset it for autosave, save or level unloading. // This will result in broken save games and will likely break assets published from asset editor. // Avoid until code is improved! Flags = ItemFlags.Abandonware | ItemFlags.EditorBreaking | ItemFlags.GameBreaking | ItemFlags.SaveAltering | ItemFlags.SourceUnavailable, LastSeen = WorkshopDate("3 May, 2020"), Published = WorkshopDate("24 Nov, 2019"), Updated = WorkshopDate("24 Nov, 2019"), }); // mesures performance based on time it takes for a game day, and fps AddMod(new Review(1899449152uL, "Game Day Timer") { Affect = Factor.Other, Authors = "rcav8tr", Catalog = catalog, Compatibility = new Dictionary<ulong, Status>() { { 1420955187uL, Status.Compatible }, // Real Time { 1749971558uL, Status.Incompatible }, // Real Time Offline }, CompatibleWith = GameVersion.ParadoxLauncher, Flags = ItemFlags.SourceAvailable, LastSeen = WorkshopDate("5 May, 2020"), Published = WorkshopDate("26 Oct, 2019"), SourceURL = "https://github.com/rcav8tr/GameDayTimer", Updated = WorkshopDate("15 Jan, 2020"), }); AddMod(new Review(1859100867uL, "Klyte's Framework 1.1") { Affect = Factor.Textures, Authors = "Klyte45", Catalog = catalog, Compatibility = new Dictionary<ulong, Status>() { }, CompatibleWith = GameVersion.SunsetHarbor, Flags = ItemFlags.SourceAvailable, SourceURL = "https://github.com/klyte45/KlyteFramework", LastSeen = WorkshopDate("5 May, 2020"), Published = WorkshopDate("10 Sep, 2019"), Updated = WorkshopDate("18 Apr, 2020"), }); // Bundle of Chinese localised mods - will break your game AddMod(new Review(1812384654uL, "(no name specified)") { Affect = Factor.Other, Authors = "打的好不如排的好", Catalog = catalog, Compatibility = new Dictionary<ulong, Status>() { }, Flags = ItemFlags.Abandonware | ItemFlags.GameBreaking | ItemFlags.LargeFileWarning // 165 MB | ItemFlags.SourceUnavailable, Notes = new Dictionary<ulong, string>() { { NOTE, "Unsubscribe. It's a zip of old mods translated to Chinese, they are all broken by subsequent game updates." }, }, LastSeen = WorkshopDate("12 May, 2020"), Published = WorkshopDate("22 Jul, 2019"), Updated = WorkshopDate("22 Jul, 2019"), }); AddMod(new Review(1614061108uL, "Real Construction") { Affect = Factor.Construction | Factor.Consumption | Factor.DemandRCI | Factor.Production | Factor.StorageCapacity | Factor.VehicleLimit, Authors = "pcfantasy", Catalog = catalog, Compatibility = new Dictionary<ulong, Status>() { { 2090425593uL, Status.Incompatible }, // Game Speed mod { 2040656402uL, Status.Required }, // Harmony 2.0.0.9 (Mod Dependency) { 1908304237uL, Status.Required }, // City Resource Building { 1899943042uL, Status.Incompatible }, // No Scaffolding Animation { 1785774902uL, Status.Compatible }, // Transfer Info (beta) { 1764208250uL, Status.Incompatible }, // More Vehicles { 1749971558uL, Status.Incompatible }, // Real Time Offline { 1739993783uL, Status.Incompatible }, // Cargo Info (Fix) { 1674732053uL, Status.Compatible }, // Employ Overeducated Workers V2 (1.11+) { 1435741602uL, Status.Incompatible }, // Snooper { 1420955187uL, Status.Compatible }, // Real Time { 1114249433uL, Status.Incompatible }, // Employ Overeducated Workers (1.10+) { 1108715012uL, Status.Incompatible }, // Adjustable Business Consumption { 1072157697uL, Status.Incompatible }, // Cargo Info { 938049744uL , Status.Incompatible }, // Proper Hardness Fixed { 569008960uL , Status.Incompatible }, // Employ Overeducated Workers { 408706691uL , Status.Incompatible }, // Proper Hardness { Vanilla.HardMode, Status.Incompatible }, // Hard Mode (bundled with Cities: Skylines) }, CompatibleWith = GameVersion.SunsetHarbor, Flags = ItemFlags.SourceAvailable, LastSeen = WorkshopDate("6 May, 2020"), Notes = new Dictionary<ulong, string>() { { NOTE, "User guide: https://steamcommunity.com/sharedfiles/filedetails/?id=1756860335" }, }, Published = WorkshopDate("4 Jan, 2019"), SourceURL = "https://github.com/pcfantasy/RealConstruction", Updated = WorkshopDate("20 Apr, 2020"), }); AddMod(new Review(1383456057uL, "Shicho") { Affect = Factor.BuildingInfo | Factor.Camera | Factor.Health | Factor.HideRemove | Factor.Rendering | Factor.Toolbar | Factor.Trees | Factor.VehicleInfo, ArchiveURL = "https://web.archive.org/web/20190102224333/https://steamcommunity.com/sharedfiles/filedetails/?id=1383456057", Authors = "saki7, Ryuichi Kaminogi", Catalog = catalog, Compatibility = new Dictionary<ulong, Status>() { }, Flags = ItemFlags.Abandonware | ItemFlags.NoWorkshop // removed between mar 26 and apr 26, 2020 | ItemFlags.SourceAvailable, LastSeen = WorkshopDate("26 Mar, 2020"), Published = WorkshopDate("11 May, 2018"), Removed = WorkshopDate("26 Apr, 2020"), SourceURL = "https://github.com/SETNAHQ/Shicho", Updated = WorkshopDate("27 Sep, 2018"), }); AddMod(new Review(1386697922uL, "Garbage Bin Controller") { Affect = Factor.Props | Factor.Emptying, Authors = "Arnold J. Rimmer, TPB", Catalog = catalog, Compatibility = new Dictionary<ulong, Status>() { { 1390252175uL, Status.Recommended }, // Japanese Plastic Bucket { 1389908178uL, Status.Recommended }, // Wheelie Bin - Color Variation { 1386088603uL, Status.Recommended }, // Metal bin - 01 // LSM skipping vanilla garbage bin = game breaking { 2045011960uL, Status.MinorIssues }, // Loading Screen 中文版 { 1894425170uL, Status.MinorIssues }, // Loading Screen Mod 汉化版 { 1860379049uL, Status.Incompatible }, // 加载优化 Loading Screen { 833779378uL , Status.MinorIssues }, // Loading Screen Mod [Test] { 667342976uL , Status.MinorIssues }, // Loading Screen Mod }, CompatibleWith = GameVersion.ParadoxLauncher, Flags = ItemFlags.SourceUnavailable, Notes = new Dictionary<ulong, string>() { { 833779378uL, "[Mod: Loading Screen Mod] If you get crashes, remove 'Garbage Bin' from your skip.txt file." }, { 667342976uL, "[Mod: Loading Screen Mod] If you get crashes, remove 'Garbage Bin' from your skip.txt file." }, }, ReleasedDuring = GameVersion.ParkLife, }); // Known issues (based on author comment): // * Cannot see values that you set the offsets for // * Unable to save/load option settings // * Does not update visual budget panel, but does update budget in the background // Was previously named "Water and Electricity Controller". AddMod(new Review(1239683428uL, "Budget Controller") { Affect = Factor.Budget, Authors = "wboler05", Catalog = catalog, Flags = ItemFlags.MinorIssues | ItemFlags.SourceAvailable, Compatibility = new Dictionary<ulong, Status>() { // todo }, SourceURL = "https://github.com/wboler05/CS-BudgetController", }); } } }
54.431564
176
0.527083
[ "MIT" ]
CitiesSkylinesMods/AutoRepair
AutoRepair/AutoRepair/Catalogs/Catalog.Unsorted.cs
39,083
C#
using NumpyDotNet; using NumpyLib; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Numerics; namespace DoubleVsComplex { class Program { static void Main(string[] args) { int LoopCount = 10000; System.Diagnostics.Stopwatch sw = new System.Diagnostics.Stopwatch(); sw.Start(); var matrix = np.arange(0, 1600, dtype: np.Float64).reshape(new shape(40, -1)); matrix.Name = "SampleApp_Doubles"; for (int i = 0; i < LoopCount; i++) { matrix = matrix / 3; matrix = matrix * 3; } var output = matrix.A(new Slice(15, 25, 2), new Slice(15, 25, 2)); output.Name = "SampleApp_Doubles(View)"; sw.Stop(); Console.WriteLine(string.Format("DOUBLE calculations took {0} milliseconds\n", sw.ElapsedMilliseconds)); Console.WriteLine(output); Console.WriteLine("************\n"); sw.Reset(); sw.Start(); matrix = np.arange(0, 1600, dtype: np.Complex).reshape(new shape(40, -1)); matrix.Name = "SampleApp_Complex"; Complex A = new Complex(3, -2.66); Complex B = new Complex(3, +1.67); for (int i = 0; i < LoopCount; i++) { matrix = matrix / A; matrix = matrix * B; } output = matrix.A(new Slice(15, 25, 2), new Slice(15, 25, 2)); output.Name = "SampleApp_Complex(View)"; sw.Stop(); Console.WriteLine(string.Format("COMPLEX calculations took {0} milliseconds\n", sw.ElapsedMilliseconds)); Console.WriteLine(output); Console.ReadLine(); } } }
27.455882
117
0.531869
[ "BSD-3-Clause" ]
erisonliang/numpy.net
src/NumpyDotNet/SampleApps/DoubleVsComplex/Program.cs
1,869
C#
using System; using System.Threading.Tasks; using Microsoft.AspNetCore.Http; using Microsoft.EntityFrameworkCore; using Prime.Models; namespace Prime.Services { public class DocumentAccessTokenService : BaseService, IDocumentAccessTokenService { public DocumentAccessTokenService( ApiDbContext context, IHttpContextAccessor httpContext) : base(context, httpContext) { } public async Task<DocumentAccessToken> GetDocumentAccessTokenAsync(Guid documentAccessTokenId) { return await _context.DocumentAccessTokens .AsNoTracking() .SingleOrDefaultAsync(d => d.Id == documentAccessTokenId); } public async Task<DocumentAccessToken> CreateDocumentAccessTokenAsync(Guid documentGuid) { var token = new DocumentAccessToken { DocumentGuid = documentGuid }; _context.Add(token); if (await _context.SaveChangesAsync() < 1) { throw new InvalidOperationException("Could not create Document Access Token."); } return token; } public async Task DeleteDocumentAccessTokenAsync(Guid documentAccessTokenId) { var token = await _context.DocumentAccessTokens .SingleOrDefaultAsync(d => d.Id == documentAccessTokenId); if (token != null) { _context.DocumentAccessTokens.Remove(token); await _context.SaveChangesAsync(); } } } }
30.509434
102
0.612245
[ "Apache-2.0" ]
WadeBarnes/moh-prime
prime-dotnet-webapi/Services/DocumentAccessTokenService.cs
1,617
C#
// ---------------------------------------------------------------------------------- // // Copyright Microsoft Corporation // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // ---------------------------------------------------------------------------------- namespace Microsoft.WindowsAzure.Commands.Storage.Common { using System.ServiceModel; using Commands.Utilities.Common; /// <summary> /// Communication exception utility /// </summary> public static class CommunicationExceptionUtil { /// <summary> /// is not found communication exception /// </summary> /// <param name="exception">Communication Exception</param> /// <returns>true if exception caused by resource not found, otherwise, false</returns> public static bool IsNotFoundException(this CommunicationException exception) { return ErrorHelper.IsNotFoundCommunicationException(exception); } } }
41.75
96
0.611444
[ "MIT" ]
Milstein/azure-sdk-tools
WindowsAzurePowershell/src/Commands.Storage/Common/CommunicationExceptionUtil.cs
1,472
C#
using AElf.Contracts.Configuration; using AElf.Contracts.Consensus.AEDPoS; using AElf.Contracts.Economic; using AElf.Contracts.Economic.TestBase; using AElf.Contracts.Election; using AElf.Contracts.Genesis; using AElf.Contracts.MultiToken; using AElf.Contracts.Parliament; using AElf.Contracts.Profit; using AElf.Contracts.TestContract.MethodCallThreshold; using AElf.Contracts.TestContract.TransactionFeeCharging; using AElf.Contracts.TokenConverter; using AElf.Contracts.TokenHolder; using AElf.Contracts.Treasury; using AElf.Contracts.Vote; using AElf.Cryptography.ECDSA; using AElf.Standards.ACS1; using Volo.Abp.Threading; namespace AElf.Contracts.EconomicSystem.Tests { // ReSharper disable InconsistentNaming public class EconomicSystemTestBase : EconomicContractsTestBase { protected void InitializeContracts() { DeployAllContracts(); AsyncHelper.RunSync(InitializeParliamentContract); AsyncHelper.RunSync(InitializeTreasuryConverter); AsyncHelper.RunSync(InitializeElection); AsyncHelper.RunSync(InitializeEconomicContract); AsyncHelper.RunSync(InitializeToken); AsyncHelper.RunSync(InitializeAElfConsensus); AsyncHelper.RunSync(InitializeTokenConverter); AsyncHelper.RunSync(InitializeTransactionFeeChargingContract); } internal BasicContractZeroImplContainer.BasicContractZeroImplStub BasicContractZeroStub => GetBasicContractTester(BootMinerKeyPair); internal TokenContractImplContainer.TokenContractImplStub TokenContractStub => GetTokenContractTester(BootMinerKeyPair); internal TokenContractImplContainer.TokenContractImplStub TokenContractImplStub => GetTokenContractImplTester(BootMinerKeyPair); internal TokenHolderContractImplContainer.TokenHolderContractImplStub TokenHolderStub => GetTokenHolderTester(BootMinerKeyPair); internal TokenConverterContractImplContainer.TokenConverterContractImplStub TokenConverterContractStub => GetTokenConverterContractTester(BootMinerKeyPair); internal VoteContractImplContainer.VoteContractImplStub VoteContractStub => GetVoteContractTester(BootMinerKeyPair); internal ProfitContractImplContainer.ProfitContractImplStub ProfitContractStub => GetProfitContractTester(BootMinerKeyPair); internal ElectionContractImplContainer.ElectionContractImplStub ElectionContractStub => GetElectionContractTester(BootMinerKeyPair); internal AEDPoSContractContainer.AEDPoSContractStub AEDPoSContractStub => GetAEDPoSContractTester(BootMinerKeyPair); internal AEDPoSContractImplContainer.AEDPoSContractImplStub AedPoSContractImplStub => GetAEDPoSImplContractTester(BootMinerKeyPair); internal TreasuryContractImplContainer.TreasuryContractImplStub TreasuryContractStub => GetTreasuryContractTester(BootMinerKeyPair); internal ParliamentContractImplContainer.ParliamentContractImplStub ParliamentContractStub => GetParliamentContractTester(BootMinerKeyPair); internal TransactionFeeChargingContractContainer.TransactionFeeChargingContractStub TransactionFeeChargingContractStub => GetTransactionFeeChargingContractTester(BootMinerKeyPair); internal MethodCallThresholdContractContainer.MethodCallThresholdContractStub MethodCallThresholdContractStub => GetMethodCallThresholdContractTester(BootMinerKeyPair); internal EconomicContractImplContainer.EconomicContractImplStub EconomicContractStub => GetEconomicContractTester(BootMinerKeyPair); internal ConfigurationImplContainer.ConfigurationImplStub ConfigurationContractStub => GetConfigurationContractTester(BootMinerKeyPair); internal BasicContractZeroImplContainer.BasicContractZeroImplStub GetBasicContractTester(ECKeyPair keyPair) { return GetTester<BasicContractZeroImplContainer.BasicContractZeroImplStub>(ContractZeroAddress, keyPair); } internal TokenContractImplContainer.TokenContractImplStub GetTokenContractTester(ECKeyPair keyPair) { return GetTester<TokenContractImplContainer.TokenContractImplStub>(TokenContractAddress, keyPair); } internal TokenContractImplContainer.TokenContractImplStub GetTokenContractImplTester(ECKeyPair keyPair) { return GetTester<TokenContractImplContainer.TokenContractImplStub>(TokenContractAddress, keyPair); } internal TokenHolderContractImplContainer.TokenHolderContractImplStub GetTokenHolderTester(ECKeyPair keyPair) { return GetTester<TokenHolderContractImplContainer.TokenHolderContractImplStub>(TokenHolderContractAddress, keyPair); } internal TokenConverterContractImplContainer.TokenConverterContractImplStub GetTokenConverterContractTester( ECKeyPair keyPair) { return GetTester<TokenConverterContractImplContainer.TokenConverterContractImplStub>(TokenConverterContractAddress, keyPair); } internal VoteContractImplContainer.VoteContractImplStub GetVoteContractTester(ECKeyPair keyPair) { return GetTester<VoteContractImplContainer.VoteContractImplStub>(VoteContractAddress, keyPair); } internal ProfitContractImplContainer.ProfitContractImplStub GetProfitContractTester(ECKeyPair keyPair) { return GetTester<ProfitContractImplContainer.ProfitContractImplStub>(ProfitContractAddress, keyPair); } internal ElectionContractImplContainer.ElectionContractImplStub GetElectionContractTester(ECKeyPair keyPair) { return GetTester<ElectionContractImplContainer.ElectionContractImplStub>(ElectionContractAddress, keyPair); } internal AEDPoSContractContainer.AEDPoSContractStub GetAEDPoSContractTester(ECKeyPair keyPair) { return GetTester<AEDPoSContractContainer.AEDPoSContractStub>(ConsensusContractAddress, keyPair); } internal AEDPoSContractImplContainer.AEDPoSContractImplStub GetAEDPoSImplContractTester(ECKeyPair keyPair) { return GetTester<AEDPoSContractImplContainer.AEDPoSContractImplStub>(ConsensusContractAddress, keyPair); } internal TreasuryContractImplContainer.TreasuryContractImplStub GetTreasuryContractTester(ECKeyPair keyPair) { return GetTester<TreasuryContractImplContainer.TreasuryContractImplStub>(TreasuryContractAddress, keyPair); } internal ParliamentContractImplContainer.ParliamentContractImplStub GetParliamentContractTester( ECKeyPair keyPair) { return GetTester<ParliamentContractImplContainer.ParliamentContractImplStub>(ParliamentContractAddress, keyPair); } internal TransactionFeeChargingContractContainer.TransactionFeeChargingContractStub GetTransactionFeeChargingContractTester(ECKeyPair keyPair) { return GetTester<TransactionFeeChargingContractContainer.TransactionFeeChargingContractStub>( TransactionFeeChargingContractAddress, keyPair); } internal MethodCallThresholdContractContainer.MethodCallThresholdContractStub GetMethodCallThresholdContractTester( ECKeyPair keyPair) { return GetTester<MethodCallThresholdContractContainer.MethodCallThresholdContractStub>( MethodCallThresholdContractAddress, keyPair); } internal EconomicContractImplContainer.EconomicContractImplStub GetEconomicContractTester(ECKeyPair keyPair) { return GetTester<EconomicContractImplContainer.EconomicContractImplStub>(EconomicContractAddress, keyPair); } internal ConfigurationImplContainer.ConfigurationImplStub GetConfigurationContractTester(ECKeyPair keyPair) { return GetTester<ConfigurationImplContainer.ConfigurationImplStub>(ConfigurationAddress, keyPair); } } }
47.079545
128
0.765025
[ "MIT" ]
AElfProject/AElf
test/AElf.Contracts.EconomicSystem.Tests/EconomicSystemTestBase.cs
8,286
C#
using System; namespace PetGameBackend.Attributes { public class PropParserIgnoreAttribute : Attribute { } }
15.25
54
0.729508
[ "MIT" ]
KiaArmani/PetGameBackend
PetGameBackend/Attributes/PropParserIgnoreAttribute.cs
124
C#