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.Xml; using System.Xml.Linq; using Orchard.FileSystems.AppData; using Orchard.ImportExport.Models; using Orchard.Logging; using Orchard.Services; namespace Orchard.ImportExport.Services { public class ImportExportService : Component, IImportExportService { private readonly IOrchardServices _orchardServices; private readonly IAppDataFolder _appDataFolder; private readonly IClock _clock; private readonly IEnumerable<IExportAction> _exportActions; private readonly IEnumerable<IImportAction> _importActions; private const string ExportsDirectory = "Exports"; public ImportExportService( IOrchardServices orchardServices, IAppDataFolder appDataFolder, IClock clock, IEnumerable<IExportAction> exportActions, IEnumerable<IImportAction> importActions) { _orchardServices = orchardServices; _appDataFolder = appDataFolder; _clock = clock; _exportActions = exportActions; _importActions = importActions; } public string Import(ImportActionContext context, IEnumerable<IImportAction> actions = null) { foreach (var action in actions ?? _importActions) { action.Execute(context); } return context.ExecutionId; } public void Export(ExportActionContext context, IEnumerable<IExportAction> actions = null) { foreach (var action in actions ?? _exportActions) { action.Execute(context); } } public string WriteExportFile(XDocument recipeDocument) { var exportFile = String.Format("Export-{0}-{1}.xml", _orchardServices.WorkContext.CurrentUser.UserName, _clock.UtcNow.Ticks); if (!_appDataFolder.DirectoryExists(ExportsDirectory)) { _appDataFolder.CreateDirectory(ExportsDirectory); } var path = _appDataFolder.Combine(ExportsDirectory, exportFile); using (var writer = new XmlTextWriter(_appDataFolder.CreateFile(path), Encoding.UTF8)) { writer.Formatting = Formatting.Indented; recipeDocument.WriteTo(writer); } return _appDataFolder.MapPath(path); } public IEnumerable<IExportAction> ParseExportActions(XDocument configurationDocument) { var actionElements = configurationDocument.Root.Elements(); foreach (var actionElement in actionElements) { var action = _exportActions.SingleOrDefault(x => x.Name == actionElement.Name.LocalName); if (action == null) { Logger.Warning("The export action '{0}' could not be found. Did you forget to enable a feature?", actionElement.Name.LocalName); continue; } action.Configure(new ExportActionConfigurationContext(actionElement)); yield return action; } } public void ConfigureImportActions(ConfigureImportActionsContext context) { var actionConfigElements = context.ConfigurationDocument.Root; foreach (var action in _importActions) { var actionConfigElement = actionConfigElements.Element(action.Name); if (actionConfigElement != null) { action.Configure(new ImportActionConfigurationContext(actionConfigElement)); } } } public IEnumerable<IImportAction> ParseImportActions(XDocument configurationDocument) { var actionElements = configurationDocument.Root.Elements(); foreach (var actionElement in actionElements) { var action = _importActions.SingleOrDefault(x => x.Name == actionElement.Name.LocalName); if (action == null) { Logger.Warning("The import action '{0}' could not be found. Did you forget to enable a feature?", actionElement.Name.LocalName); continue; } action.Configure(new ImportActionConfigurationContext(actionElement)); yield return action; } } } }
41.37963
149
0.622958
[ "BSD-3-Clause" ]
Lombiq/Associativy
src/Orchard.Web/Modules/Orchard.ImportExport/Services/ImportExportService.cs
4,471
C#
using System.Collections.Generic; using NunitGo.NunitGoItems.Subscriptions; namespace NunitGo.NunitGoItems { public class NunitGoConfiguration { public string LocalOutputPath; public bool TakeScreenshotAfterTestFailed; public bool GenerateReport; public bool SendEmails; public bool AddLinksInsideEmail; public string ServerLink; public List<Subsciption> Subsciptions; public List<SingleTestSubscription> SingleTestSubscriptions; public string SmtpHost; public int SmtpPort; public bool EnableSsl; public List<Address> SendFromList; } }
28.173913
68
0.708333
[ "MIT" ]
codacy-review/NUnitGo
NunitGo/NunitGoItems/NunitGoConfiguration.cs
650
C#
using System; using System.Reflection; using System.Text; using MoonSharp.Interpreter.Interop.RegistrationPolicies; namespace MoonSharp.Interpreter.Interop.Converters { internal static class ClrToScriptConversions { /// <summary> /// Tries to convert a CLR object to a MoonSharp value, using "trivial" logic. /// Skips on custom conversions, etc. /// Does NOT throw on failure. /// </summary> internal static DynValue TryObjectToTrivialDynValue(Script script, object obj) { if (obj == null) return DynValue.Nil; if (obj is DynValue) return (DynValue)obj; Type t = obj.GetType(); if (obj is bool) return DynValue.NewBoolean((bool)obj); if (obj is string || obj is StringBuilder || obj is char) return DynValue.NewString(obj.ToString()); if (NumericConversions.NumericTypes.Contains(t)) return DynValue.NewNumber(NumericConversions.TypeToDouble(t, obj)); if (obj is Table) return DynValue.NewTable((Table)obj); return null; } /// <summary> /// Tries to convert a CLR object to a MoonSharp value, using "simple" logic. /// Does NOT throw on failure. /// </summary> internal static DynValue TryObjectToSimpleDynValue(Script script, object obj) { if (obj == null) return DynValue.Nil; if (obj is DynValue) return (DynValue)obj; var converter = Script.GlobalOptions.CustomConverters.GetClrToScriptCustomConversion(obj.GetType()); if (converter != null) { var v = converter(script, obj); if (v != null) return v; } Type t = obj.GetType(); if (obj is bool) return DynValue.NewBoolean((bool)obj); if (obj is string || obj is StringBuilder || obj is char) return DynValue.NewString(obj.ToString()); if (obj is Closure) return DynValue.NewClosure((Closure)obj); if (NumericConversions.NumericTypes.Contains(t)) return DynValue.NewNumber(NumericConversions.TypeToDouble(t, obj)); if (obj is Table) return DynValue.NewTable((Table)obj); if (obj is CallbackFunction) return DynValue.NewCallback((CallbackFunction)obj); if (obj is Delegate) { Delegate d = (Delegate)obj; #if NETFX_CORE MethodInfo mi = d.GetMethodInfo(); #else MethodInfo mi = d.Method; #endif if (CallbackFunction.CheckCallbackSignature(mi, false)) return DynValue.NewCallback((Func<ScriptExecutionContext, CallbackArguments, DynValue>)d); } return null; } /// <summary> /// Tries to convert a CLR object to a MoonSharp value, using more in-depth analysis /// </summary> internal static DynValue ObjectToDynValue(Script script, object obj) { DynValue v = TryObjectToSimpleDynValue(script, obj); if (v != null) return v; v = UserData.Create(obj); if (v != null) return v; if (obj is Type) v = UserData.CreateStatic(obj as Type); // unregistered enums go as integers if (obj is Enum) return DynValue.NewNumber(NumericConversions.TypeToDouble(Enum.GetUnderlyingType(obj.GetType()), obj)); if (v != null) return v; if (obj is Delegate) return DynValue.NewCallback(CallbackFunction.FromDelegate(script, (Delegate)obj)); if (obj is MethodInfo) { MethodInfo mi = (MethodInfo)obj; if (mi.IsStatic) { return DynValue.NewCallback(CallbackFunction.FromMethodInfo(script, mi)); } } if (obj is System.Collections.IList) { Table t = TableConversions.ConvertIListToTable(script, (System.Collections.IList)obj); return DynValue.NewTable(t); } if (obj is System.Collections.IDictionary) { Table t = TableConversions.ConvertIDictionaryToTable(script, (System.Collections.IDictionary)obj); return DynValue.NewTable(t); } var enumerator = EnumerationToDynValue(script, obj); if (enumerator != null) return enumerator; throw ScriptRuntimeException.ConvertObjectFailed(obj); } /// <summary> /// Converts an IEnumerable or IEnumerator to a DynValue /// </summary> /// <param name="script">The script.</param> /// <param name="obj">The object.</param> /// <returns></returns> public static DynValue EnumerationToDynValue(Script script, object obj) { if (obj is System.Collections.IEnumerable) { var enumer = (System.Collections.IEnumerable)obj; return EnumerableWrapper.ConvertIterator(script, enumer.GetEnumerator()); } if (obj is System.Collections.IEnumerator) { var enumer = (System.Collections.IEnumerator)obj; return EnumerableWrapper.ConvertIterator(script, enumer); } return null; } } }
25.154696
107
0.69295
[ "MIT" ]
CommonTimeGames/Caminho-Unity
Assets/Plugins/MoonSharp/Interpreter/Interop/Converters/ClrToScriptConversions.cs
4,555
C#
using Magento.RestClient.Abstractions.Repositories; namespace Magento.RestClient.Abstractions.Abstractions { public interface IAdminContext : IContext { IProductAttributeGroupRepository ProductAttributeGroups { get; } IStoreRepository Stores { get; } IProductRepository Products { get; } IProductMediaRepository ProductMedia { get; } IConfigurableProductRepository ConfigurableProducts { get; } IOrderRepository Orders { get; } ICustomerRepository Customers { get; } ICustomerGroupRepository CustomerGroups { get; } IDirectoryRepository Directory { get; } IAttributeSetRepository AttributeSets { get; } IInvoiceRepository Invoices { get; } ICategoryRepository Categories { get; } IInventoryStockRepository InventoryStocks { get; } IInventorySourceItemRepository InventorySourceItems { get; } IInventorySourceRepository InventorySources { get; } ICartRepository Carts { get; } IAttributeRepository Attributes { get; } IShipmentRepository Shipments { get; } IBulkRepository Bulk { get; } ISpecialPriceRepository SpecialPrices { get; } IModuleRepository Modules { get; } } }
38.586207
66
0.785523
[ "BSD-3-Clause" ]
mlof/Magento.RestClient
source/Magento.RestClient.Abstractions/Abstractions/IAdminContext.cs
1,121
C#
using CachingManager.Abstraction; using Microsoft.Extensions.Caching.Memory; namespace CachingManager { public class Cache<TValue, TKey> : ICache<TValue, TKey> where TValue : IMesurable { #region Public Properties public TValue this[TKey key] { get => this.Get(key); set => this.Set(key, value); } public string Name { get; } public long SizeLimit { get; } private MemoryCache _cache; #endregion #region c'tor internal Cache(string name, long sizeLimit) { this.Name = name; this.SizeLimit = sizeLimit; this.InitializeCache(); } #endregion #region Public Methods public void Clear() { this._cache.Dispose(); this.InitializeCache(); } public bool Exists(TKey key) { return this.Get(key) != null; } public TValue Get(TKey key, TValue defaultValue = default(TValue)) { var cacheEntry = _cache.Get<CacheEntry<TValue, TKey>>(key); return cacheEntry != null ? cacheEntry.Value : defaultValue; } public void Remove(TKey key) { _cache.Remove(key); } public void Set(TKey key, TValue value) { if (value == null) { _cache.Remove(key); } else { var cacheEntry = new CacheEntry<TValue, TKey>(key, value); _cache.Set(key, cacheEntry, new MemoryCacheEntryOptions() { Size = value.GetSizeInBytes() }); } } #endregion #region Private Methods private void InitializeCache() { this._cache = new MemoryCache(new MemoryCacheOptions() { SizeLimit = this.SizeLimit, CompactionPercentage = 0.1, }); } #endregion #region IDisposable Implementation public void Dispose() { _cache?.Dispose(); } #endregion } }
21.601942
85
0.497079
[ "MIT" ]
almez/CachingManager
src/CachingManager/Cache.cs
2,227
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 Pds.Data; namespace Pds.Data.Migrations { [DbContext(typeof(ApplicationDbContext))] [Migration("20210330174006_AddContentStatus")] partial class AddContentStatus { protected override void BuildTargetModel(ModelBuilder modelBuilder) { #pragma warning disable 612, 618 modelBuilder .UseIdentityColumns() .HasAnnotation("Relational:MaxIdentifierLength", 128) .HasAnnotation("ProductVersion", "5.0.2"); modelBuilder.Entity("ChannelPerson", b => { b.Property<Guid>("ChannelsId") .HasColumnType("uniqueidentifier"); b.Property<Guid>("PersonsId") .HasColumnType("uniqueidentifier"); b.HasKey("ChannelsId", "PersonsId"); b.HasIndex("PersonsId"); b.ToTable("ChannelPerson"); }); modelBuilder.Entity("Pds.Data.Entities.Bill", b => { b.Property<Guid>("Id") .ValueGeneratedOnAdd() .HasColumnType("uniqueidentifier"); b.Property<Guid>("ChannelId") .HasColumnType("uniqueidentifier"); b.Property<Guid?>("ClientId") .HasColumnType("uniqueidentifier"); b.Property<string>("Comment") .HasColumnType("nvarchar(max)"); b.Property<Guid?>("ContentId") .HasColumnType("uniqueidentifier"); b.Property<decimal>("Cost") .HasColumnType("decimal(18,2)"); b.Property<DateTime>("CreatedAt") .HasColumnType("datetime2"); b.Property<int?>("PaymentType") .HasColumnType("int"); b.Property<string>("PrimaryContact") .IsRequired() .HasColumnType("varchar(300)"); b.Property<int>("PrimaryContactType") .HasColumnType("int"); b.Property<int>("Status") .HasColumnType("int"); b.Property<int>("Type") .HasColumnType("int"); b.Property<DateTime?>("UpdatedAt") .HasColumnType("datetime2"); b.HasKey("Id"); b.HasIndex("ChannelId"); b.HasIndex("ClientId"); b.HasIndex("ContentId") .IsUnique() .HasFilter("[ContentId] IS NOT NULL"); b.ToTable("Bills"); }); modelBuilder.Entity("Pds.Data.Entities.Channel", b => { b.Property<Guid>("Id") .ValueGeneratedOnAdd() .HasColumnType("uniqueidentifier"); b.Property<DateTime>("CreatedAt") .HasColumnType("datetime2"); b.Property<string>("Name") .IsRequired() .HasColumnType("varchar(300)"); b.Property<DateTime?>("UpdatedAt") .HasColumnType("datetime2"); b.Property<string>("Url") .IsRequired() .HasColumnType("varchar(300)"); b.HasKey("Id"); b.ToTable("Channels"); }); modelBuilder.Entity("Pds.Data.Entities.Client", b => { b.Property<Guid>("Id") .ValueGeneratedOnAdd() .HasColumnType("uniqueidentifier"); b.Property<string>("Comment") .HasColumnType("nvarchar(max)"); b.Property<DateTime>("CreatedAt") .HasColumnType("datetime2"); b.Property<string>("Name") .IsRequired() .HasColumnType("varchar(300)"); b.Property<DateTime?>("UpdatedAt") .HasColumnType("datetime2"); b.HasKey("Id"); b.ToTable("Clients"); }); modelBuilder.Entity("Pds.Data.Entities.Content", b => { b.Property<Guid>("Id") .ValueGeneratedOnAdd() .HasColumnType("uniqueidentifier"); b.Property<Guid>("BillId") .HasColumnType("uniqueidentifier"); b.Property<Guid>("ChannelId") .HasColumnType("uniqueidentifier"); b.Property<string>("Comment") .HasColumnType("nvarchar(max)"); b.Property<DateTime>("CreatedAt") .HasColumnType("datetime2"); b.Property<DateTime?>("EndDateUtc") .HasColumnType("datetime2"); b.Property<Guid?>("PersonId") .HasColumnType("uniqueidentifier"); b.Property<DateTime>("ReleaseDateUtc") .HasColumnType("datetime2"); b.Property<int>("SocialMediaType") .ValueGeneratedOnAdd() .HasColumnType("int") .HasDefaultValue(1); b.Property<int>("Status") .HasColumnType("int"); b.Property<string>("Title") .IsRequired() .HasColumnType("varchar(300)"); b.Property<int>("Type") .HasColumnType("int"); b.Property<DateTime?>("UpdatedAt") .HasColumnType("datetime2"); b.HasKey("Id"); b.HasIndex("ChannelId"); b.HasIndex("PersonId"); b.ToTable("Contents"); }); modelBuilder.Entity("Pds.Data.Entities.Person", b => { b.Property<Guid>("Id") .ValueGeneratedOnAdd() .HasColumnType("uniqueidentifier"); b.Property<DateTime?>("ArchivedAt") .HasColumnType("datetime2"); b.Property<string>("City") .HasColumnType("nvarchar(max)"); b.Property<string>("Country") .HasColumnType("nvarchar(max)"); b.Property<DateTime>("CreatedAt") .HasColumnType("datetime2"); b.Property<string>("FirstName") .IsRequired() .HasColumnType("varchar(300)"); b.Property<string>("Info") .HasColumnType("nvarchar(max)"); b.Property<string>("LastName") .IsRequired() .HasColumnType("varchar(300)"); b.Property<string>("Latitude") .HasColumnType("nvarchar(max)"); b.Property<string>("Longitude") .HasColumnType("nvarchar(max)"); b.Property<int?>("Rate") .HasColumnType("int"); b.Property<int>("Status") .ValueGeneratedOnAdd() .HasColumnType("int") .HasDefaultValue(1); b.Property<string>("ThirdName") .HasColumnType("varchar(300)"); b.Property<DateTime?>("UnarchivedAt") .HasColumnType("datetime2"); b.Property<DateTime?>("UpdatedAt") .HasColumnType("datetime2"); b.HasKey("Id"); b.ToTable("Persons"); }); modelBuilder.Entity("Pds.Data.Entities.Resource", b => { b.Property<Guid>("Id") .ValueGeneratedOnAdd() .HasColumnType("uniqueidentifier"); b.Property<DateTime>("CreatedAt") .HasColumnType("datetime2"); b.Property<string>("Name") .IsRequired() .HasColumnType("nvarchar(max)"); b.Property<Guid>("PersonId") .HasColumnType("uniqueidentifier"); b.Property<DateTime?>("UpdatedAt") .HasColumnType("datetime2"); b.Property<string>("Url") .IsRequired() .HasColumnType("nvarchar(max)"); b.HasKey("Id"); b.HasIndex("PersonId"); b.ToTable("Resources"); }); modelBuilder.Entity("ChannelPerson", b => { b.HasOne("Pds.Data.Entities.Channel", null) .WithMany() .HasForeignKey("ChannelsId") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); b.HasOne("Pds.Data.Entities.Person", null) .WithMany() .HasForeignKey("PersonsId") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); }); modelBuilder.Entity("Pds.Data.Entities.Bill", b => { b.HasOne("Pds.Data.Entities.Channel", "Channel") .WithMany("Bills") .HasForeignKey("ChannelId") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); b.HasOne("Pds.Data.Entities.Client", "Client") .WithMany("Bills") .HasForeignKey("ClientId"); b.HasOne("Pds.Data.Entities.Content", "Content") .WithOne("Bill") .HasForeignKey("Pds.Data.Entities.Bill", "ContentId"); b.Navigation("Channel"); b.Navigation("Client"); b.Navigation("Content"); }); modelBuilder.Entity("Pds.Data.Entities.Content", b => { b.HasOne("Pds.Data.Entities.Channel", "Channel") .WithMany("Contents") .HasForeignKey("ChannelId") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); b.HasOne("Pds.Data.Entities.Person", "Person") .WithMany("Contents") .HasForeignKey("PersonId"); b.Navigation("Channel"); b.Navigation("Person"); }); modelBuilder.Entity("Pds.Data.Entities.Resource", b => { b.HasOne("Pds.Data.Entities.Person", "Person") .WithMany("Resources") .HasForeignKey("PersonId") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); b.Navigation("Person"); }); modelBuilder.Entity("Pds.Data.Entities.Channel", b => { b.Navigation("Bills"); b.Navigation("Contents"); }); modelBuilder.Entity("Pds.Data.Entities.Client", b => { b.Navigation("Bills"); }); modelBuilder.Entity("Pds.Data.Entities.Content", b => { b.Navigation("Bill"); }); modelBuilder.Entity("Pds.Data.Entities.Person", b => { b.Navigation("Contents"); b.Navigation("Resources"); }); #pragma warning restore 612, 618 } } }
33.843915
78
0.427265
[ "Apache-2.0" ]
SelitskiySergey/bloggers-cms
Pds/Pds.Data/Migrations/20210330174006_AddContentStatus.Designer.cs
12,795
C#
// -------------------------------------------------------------------------------------------------------------------- // <copyright file="JsonSerializationFacts.cs" company="Catel development team"> // Copyright (c) 2008 - 2015 Catel development team. All rights reserved. // </copyright> // -------------------------------------------------------------------------------------------------------------------- namespace Catel.Test.Runtime.Serialization { using System; using System.Globalization; using Catel.IoC; using Catel.Runtime.Serialization; using Catel.Runtime.Serialization.Json; using NUnit.Framework; using TestModels; public class JsonSerializationFacts { [TestFixture] public class BasicSerializationFacts { } [TestFixture] public class AdvancedSerializationFacts { [TestCase] public void CorrectlySerializesObjectsImplementingICustomJsonSerializable_Simple() { var serviceLocator = ServiceLocator.Default; var serializer = serviceLocator.ResolveType<IJsonSerializer>(); var model = new CustomJsonSerializationModel { FirstName = "Geert" }; var clonedModel = SerializationTestHelper.SerializeAndDeserialize(model, serializer, null); // Note: yes, the *model* is serialized, the *clonedModel* is deserialized Assert.IsTrue(model.IsCustomSerialized); Assert.IsTrue(clonedModel.IsCustomDeserialized); Assert.AreEqual(model.FirstName, clonedModel.FirstName); } [TestCase] public void CorrectlySerializesObjectsImplementingICustomJsonSerializable_Nested() { var serviceLocator = ServiceLocator.Default; var serializer = serviceLocator.ResolveType<IJsonSerializer>(); var model = new CustomJsonSerializationModelWithNesting { Name = "Test model with nesting", NestedModel = new CustomJsonSerializationModel { FirstName = "Geert" } }; var clonedModel = SerializationTestHelper.SerializeAndDeserialize(model, serializer, null); Assert.IsNotNull(clonedModel.NestedModel); // Note: yes, the *model* is serialized, the *clonedModel* is deserialized Assert.IsTrue(model.NestedModel.IsCustomSerialized); Assert.IsTrue(clonedModel.NestedModel.IsCustomDeserialized); Assert.AreEqual(model.Name, clonedModel.Name); Assert.AreEqual(model.NestedModel.FirstName, clonedModel.NestedModel.FirstName); } [TestCase] public void CorrectlySerializesToJsonString() { var testModel = new TestModel(); testModel._excludedField = "excluded"; testModel._includedField = "included"; testModel.ExcludedRegularProperty = "excluded"; testModel.IncludedRegularProperty = "included"; testModel.ExcludedCatelProperty = "excluded"; testModel.IncludedCatelProperty = "included"; var configuration = new JsonSerializationConfiguration { UseBson = true }; var json = testModel.ToJson(configuration); Assert.IsFalse(json.Contains("Excluded")); } [TestCase] public void CorrectlySerializesToBsonString() { var testModel = new TestModel(); testModel._excludedField = "excluded"; testModel._includedField = "included"; testModel.ExcludedRegularProperty = "excluded"; testModel.IncludedRegularProperty = "included"; testModel.ExcludedCatelProperty = "excluded"; testModel.IncludedCatelProperty = "included"; var configuration = new JsonSerializationConfiguration { UseBson = true }; var json = testModel.ToJson(configuration); Assert.IsFalse(json.Contains("Excluded")); } //[TestCase] //public void CorrectlySerializesToJsonStringWithInvariantCulture() //{ // TestSerializationUsingCulture(CultureInfo.InvariantCulture); //} //[TestCase] //public void CorrectlySerializesToJsonStringWithDutchCulture() //{ // TestSerializationUsingCulture(new CultureInfo("nl-NL")); //} //[TestCase] //public void CorrectlySerializesToJsonStringWithCustomCulture() //{ // var cultureInfo = new CultureInfo("en-US", true); // cultureInfo.DateTimeFormat = new DateTimeFormatInfo // { // } // TestSerializationUsingCulture(cultureInfo); //} private void TestSerializationUsingCulture(CultureInfo culture) { var testModel = new TestModel(); var currentDateTime = DateTime.Now; testModel.DateTimeProperty = currentDateTime; var configuration = new SerializationConfiguration { Culture = culture }; var json = testModel.ToJson(configuration); Assert.IsTrue(json.Contains(currentDateTime.ToString(culture))); } } } }
35.333333
120
0.544768
[ "MIT" ]
uQr/Catel
src/Catel.Test/Catel.Test.Shared/Runtime/Serialization/JsonSerialization/JsonSerializationFacts.cs
5,832
C#
using System; using System.Collections.Generic; using System.Collections.Specialized; using System.Linq; using System.Text; using Framework.Core; using Framework.DomainDriven.DAL.Sql; using Framework.DomainDriven.DBGenerator.Contracts; using Framework.DomainDriven.DBGenerator.Team; using Framework.DomainDriven.Metadata; using Microsoft.SqlServer.Management.Smo; using Index = Microsoft.SqlServer.Management.Smo.Index; namespace Framework.DomainDriven.DBGenerator.ScriptGenerators.ScriptGeneratorStrategy { /// <summary> /// Создает таблицы и колонки в этих таблицах для всех доменных типов /// </summary> /// <remarks>Если установлен флаг DatabaseScriptGeneratorMode.AutoGenerateUpdateChangeTypeScript и в доменном объекте поменялся тип колонки, то колонка будет переименовано с постфиксом '_previusVersion' и в скрипт допишется строка update {0} set [{1}]=[{2}]. /// Созданные колонки добавляются в parameter.AddedColumns</remarks> internal class AddOrUpdateStrategy : ScriptGeneratorStrategyBase { public AddOrUpdateStrategy(DatabaseScriptGeneratorStrategyInfo parameter) : base(parameter) { } /// <summary> /// Мод применяемого миграционого скрипта /// </summary> public override ApplyMigrationDbScriptMode ApplyMigrationDbScriptMode { get { return ApplyMigrationDbScriptMode.AddOrUpdate; } } /// <summary> /// Модификации базы данных по определенной стратегии /// </summary> protected override void ExecuteBase() { var mainDatabase = this.Parameter.Context.GetMainDatabase(); mainDatabase.Tables.Refresh(); foreach (var typeDescription in this.Parameter.DomainTypesLocal) { this.GenerateTableForDomainType(typeDescription); } } private void GenerateTableForDomainType(DomainTypeMetadata typeDescription) { var table = this.Parameter.Context.GetOrCreateTable(typeDescription.DomainType); this.GenerateColumns(typeDescription, table); foreach (var childDomainType in typeDescription.NotAbstractChildrenDomainTypes) { this.GenerateTableForDomainType(childDomainType); } } private void GenerateColumns(DomainTypeMetadata typeDescription, Table table) { var sqlMappings = typeDescription.GetPersistentFields().SelectMany(MapperFactory.GetMapping).ToList(); var mainDatabase = this.Parameter.Context.GetMainDatabase(); if (typeDescription.Parent != null) { sqlMappings = sqlMappings.Union(typeDescription.Root.Fields.SelectMany(MapperFactory.GetMapping).Where(f => f.IsPrimaryKey)) .ToList(); } foreach (var sqlMapping in sqlMappings.OrderBy(z => z.Name)) { var column = this.GetOrCreateColumn(table, sqlMapping); if (!this.Parameter.DataTypeComparer.Equals(column.DataType, sqlMapping.SqlType)) { var columnName = sqlMapping.Name; var columnType = sqlMapping.SqlType; if (null != column.DefaultConstraint) { column.UnbindDefault(); } column.Rename(column.Name + this.Parameter.PreviusPostfix); column.Alter(); this.Parameter.RemovableColumns.Add(column); var newColumn = this.CreateColumn(table, columnName, columnType, sqlMapping.IsNullable, sqlMapping.DefaultConstraint); // TODO: move this if to custom script if (this.Parameter.DatabaseGeneratorMode.HasFlag(DatabaseScriptGeneratorMode.AutoGenerateUpdateChangeTypeScript)) { this.Server.ConnectionContext.CapturedSql.Add(ScriptsHelper.KeywordGo); var script = new StringCollection { $"use [{mainDatabase.Name}]", $"update {table.ToString()} set [{newColumn.Name}]=[{column.Name}]" }; this.Server.ConnectionContext.ExecuteNonQuery(script); } if (column.Nullable != sqlMapping.IsNullable && !this.Parameter.DataTypeComparer.Equals(column.DataType, sqlMapping.SqlType)) { column.Alter(); table.ForeignKeys.Cast<ForeignKey>() .Where(z => z.Columns.Cast<ForeignKeyColumn>().Any(q => q.Name == column.Name)) .ToList() .Foreach(z => z.Drop()); table.Indexes.Cast<Index>() .Where(z => z.IndexedColumns.Cast<IndexedColumn>().Any(q => q.Name == column.Name)) .ToList() .Foreach(z => { z.Drop(); }); } // ProcessDefaultConstraint(sqlMapping, newColumn); } } } private Column GetOrCreateColumn(Table table, SqlFieldMappingInfo sqlMapping) { var fieldName = sqlMapping.Name; var dataType = sqlMapping.SqlType; var isNullable = sqlMapping.IsNullable; var defaultConstraint = sqlMapping.DefaultConstraint; var column = this.GetColumn(table, sqlMapping); if (null == column) { column = this.CreateColumn(table, fieldName, dataType, isNullable, defaultConstraint); } return column; } private Column CreateColumn(Table table, string fieldName, DataType dataType, bool isNullable, string defaultConstraint) { var result = new Column(table, fieldName, dataType); defaultConstraint.MaybeString(z => result.AddDefaultConstraint().Text = z); table.Columns.Add(result); if (table.State == SqlSmoState.Creating) { table.Create(); } else { result.Create(); } this.Parameter.AddedColumns.Add(new Tuple<Table, Column, string>(table, result, defaultConstraint)); return result; } } }
39.377143
263
0.556958
[ "MIT" ]
Luxoft/BSSFramework
src/_DomainDriven/Framework.DomainDriven.DBGenerator/ScriptGenerators/ScriptGeneratorStrategy/AddOrUpdateStrategy.cs
6,995
C#
/* * DivikResultTests.cs * Tests DivikResult class. * Copyright 2017 Grzegorz Mrukwa, Michał Gallus Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ using System; using System.IO; using Newtonsoft.Json; using NUnit.Framework; using Spectre.Algorithms.Methods; using Spectre.Algorithms.Parameterization; using Spectre.Algorithms.Results; using Spectre.Data.Datasets; namespace Spectre.Algorithms.Tests.Results { [TestFixture] [Category(name: "Algorithm")] [Category(name: "VeryLong")] public class DivikResultTests { private DivikResult _result; private Segmentation _segmentation; private readonly string TestDirectory = TestContext.CurrentContext.TestDirectory + "\\..\\..\\..\\..\\..\\test_files"; private readonly string _testFilePath = TestContext.CurrentContext.TestDirectory + "\\..\\..\\..\\..\\..\\test_files\\hnc1_tumor.txt"; [OneTimeSetUp] public void SetUpFixture() { var dataset = new BasicTextDataset(_testFilePath); var options = DivikOptions.ForLevels(levels: 1); options.MaxK = 2; options.Caching = false; options.PlottingPartitions = false; options.PlottingDecomposition = false; options.PlottingDecompositionRecursively = false; options.PlottingRecursively = false; options.UsingAmplitudeFiltration = false; _segmentation = new Segmentation(); _result = _segmentation.Divik(dataset, options); } [OneTimeTearDown] public void TearDownFixture() { _segmentation.Dispose(); _segmentation = null; } [Test] public void Save() { var path = TestDirectory + "\\test-path.json"; _result.Save(path, indentation: true); Assert.True(condition: File.Exists(path), message: "File doesn't exist"); Assert.AreNotEqual(expected: 0, actual: new FileInfo(path).Length, message: "File is empty"); var jsonData = File.ReadAllText(path); var deserialisedResult = JsonConvert.DeserializeObject<DivikResult>(jsonData); Assert.AreEqual(_result, deserialisedResult, message: "Divik results differ"); File.Delete(path); } [Test] public void SavedIdented() { var path = TestDirectory + "\\test-path.json"; _result.Save(path, indentation: false); var contents = File.ReadAllText(path); Assert.False(condition: contents.Contains(value: "\n"), message: "Non-idented formatting contains new line"); File.Delete(path); } [Test] public void EqualsAgainstIdenticalInstance() { var dataset = new BasicTextDataset(_testFilePath); var options = DivikOptions.ForLevels(levels: 1); options.MaxK = 2; options.Caching = false; options.PlottingPartitions = false; options.PlottingDecomposition = false; options.PlottingDecompositionRecursively = false; options.PlottingRecursively = false; options.UsingAmplitudeFiltration = false; var result = _segmentation.Divik(dataset, options); Assert.True(condition: result.Equals(_result), message: "Equal objects not indicated."); } [Test] public void EqualsAgainstDifferentInstance() { var dataset = new BasicTextDataset(_testFilePath); var options = DivikOptions.ForLevels(levels: 1); options.MaxK = 2; options.Caching = false; options.PlottingPartitions = false; options.PlottingDecomposition = false; options.PlottingDecompositionRecursively = false; options.PlottingRecursively = false; options.UsingVarianceFiltration = false; var result = _segmentation.Divik(dataset, options); Assert.False(condition: result.Equals(_result), message: "Unequal objects not indicated."); } [Test] public void EqualsAgainstNull() { Assert.False(condition: _result.Equals(obj: null), message: "Instance equalized with null"); } [Test] public void EqualityOperatorForNulls() { DivikResult r1 = null; DivikResult r2 = null; Assert.True(condition: r1 == r2, message: "Nulls not indicated as equal"); } [Test] public void DifferenceOperatorForNulls() { DivikResult r1 = null; DivikResult r2 = null; Assert.False(condition: r1 != r2, message: "Nulls indicated as unequal"); } [Test] public void EqualityOperatorAgainstNull() { DivikResult r1 = null; Assert.False(condition: r1 == _result, message: "null indicated equal to instance"); } [Test] public void InequalityOperatorAgainstNull() { DivikResult r1 = null; Assert.True(condition: r1 != _result, message: "null not indicated unequal to instance"); } } }
35.143713
105
0.609303
[ "Apache-2.0" ]
spectre-team/DiviK-standalone-client
src/Spectre.Algorithms.Tests/Results/DivikResultTests.cs
5,872
C#
namespace ClearHl7.Codes.V280 { /// <summary> /// HL7 Version 2 Table 0242 - Primary Observer's Qualification. /// </summary> /// <remarks>https://www.hl7.org/fhir/v2/0242</remarks> public enum CodePrimaryObserversQualification { /// <summary> /// C - Health care consumer/patient. /// </summary> HealthCareConsumerPatient, /// <summary> /// H - Other health professional. /// </summary> OtherHealthProfessional, /// <summary> /// L - Lawyer/attorney. /// </summary> LawyerAttorney, /// <summary> /// M - Mid-level professional (nurse, nurse practitioner, physician's assistant). /// </summary> MidLevelProfessional, /// <summary> /// O - Other non-health professional. /// </summary> OtherNonHealthProfessional, /// <summary> /// P - Physician (osteopath, homeopath). /// </summary> PhysicianOsteopathHomeopath, /// <summary> /// R - Pharmacist. /// </summary> Pharmacist } }
26.886364
90
0.512257
[ "MIT" ]
davebronson/clear-hl7-net
src/ClearHl7.Codes/V280/CodePrimaryObserversQualification.cs
1,185
C#
namespace ESFA.DC.CollectionsManagement.Data.Entities { public partial class OrganisationCollection { public int OrganisationId { get; set; } public int CollectionId { get; set; } public Collection Collection { get; set; } public Organisation Organisation { get; set; } } }
23
54
0.658385
[ "MIT" ]
SkillsFundingAgency/DC-CollectionsManagement
src/ESFA.DC.CollectionsManagement.Data/Entities/OrganisationCollection.cs
324
C#
/******************************************************************************* * Copyright 2012-2019 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. * ***************************************************************************** * * AWS Tools for Windows (TM) PowerShell (TM) * */ using System; using System.Collections.Generic; using System.Linq; using System.Management.Automation; using System.Text; using Amazon.PowerShell.Common; using Amazon.Runtime; using Amazon.APIGateway; using Amazon.APIGateway.Model; namespace Amazon.PowerShell.Cmdlets.AG { /// <summary> /// Describe an existing <a>Method</a> resource. /// </summary> [Cmdlet("Get", "AGMethod")] [OutputType("Amazon.APIGateway.Model.GetMethodResponse")] [AWSCmdlet("Calls the Amazon API Gateway GetMethod API operation.", Operation = new[] {"GetMethod"}, SelectReturnType = typeof(Amazon.APIGateway.Model.GetMethodResponse))] [AWSCmdletOutput("Amazon.APIGateway.Model.GetMethodResponse", "This cmdlet returns an Amazon.APIGateway.Model.GetMethodResponse object containing multiple properties. The object can also be referenced from properties attached to the cmdlet entry in the $AWSHistory stack." )] public partial class GetAGMethodCmdlet : AmazonAPIGatewayClientCmdlet, IExecutor { #region Parameter HttpMethod /// <summary> /// <para> /// <para>[Required] Specifies the method request's HTTP method type.</para> /// </para> /// </summary> #if !MODULAR [System.Management.Automation.Parameter(ValueFromPipelineByPropertyName = true)] #else [System.Management.Automation.Parameter(ValueFromPipelineByPropertyName = true, Mandatory = true)] [System.Management.Automation.AllowEmptyString] [System.Management.Automation.AllowNull] #endif [Amazon.PowerShell.Common.AWSRequiredParameter] public System.String HttpMethod { get; set; } #endregion #region Parameter ResourceId /// <summary> /// <para> /// <para>[Required] The <a>Resource</a> identifier for the <a>Method</a> resource.</para> /// </para> /// </summary> #if !MODULAR [System.Management.Automation.Parameter(ValueFromPipelineByPropertyName = true)] #else [System.Management.Automation.Parameter(ValueFromPipelineByPropertyName = true, Mandatory = true)] [System.Management.Automation.AllowEmptyString] [System.Management.Automation.AllowNull] #endif [Amazon.PowerShell.Common.AWSRequiredParameter] public System.String ResourceId { get; set; } #endregion #region Parameter RestApiId /// <summary> /// <para> /// <para>[Required] The string identifier of the associated <a>RestApi</a>.</para> /// </para> /// </summary> #if !MODULAR [System.Management.Automation.Parameter(Position = 0, ValueFromPipelineByPropertyName = true, ValueFromPipeline = true)] #else [System.Management.Automation.Parameter(Position = 0, ValueFromPipelineByPropertyName = true, ValueFromPipeline = true, Mandatory = true)] [System.Management.Automation.AllowEmptyString] [System.Management.Automation.AllowNull] #endif [Amazon.PowerShell.Common.AWSRequiredParameter] public System.String RestApiId { get; set; } #endregion #region Parameter Select /// <summary> /// Use the -Select parameter to control the cmdlet output. The default value is '*'. /// Specifying -Select '*' will result in the cmdlet returning the whole service response (Amazon.APIGateway.Model.GetMethodResponse). /// Specifying the name of a property of type Amazon.APIGateway.Model.GetMethodResponse will result in that property being returned. /// Specifying -Select '^ParameterName' will result in the cmdlet returning the selected cmdlet parameter value. /// </summary> [System.Management.Automation.Parameter(ValueFromPipelineByPropertyName = true)] public string Select { get; set; } = "*"; #endregion #region Parameter PassThru /// <summary> /// Changes the cmdlet behavior to return the value passed to the RestApiId parameter. /// The -PassThru parameter is deprecated, use -Select '^RestApiId' instead. This parameter will be removed in a future version. /// </summary> [System.Obsolete("The -PassThru parameter is deprecated, use -Select '^RestApiId' instead. This parameter will be removed in a future version.")] [System.Management.Automation.Parameter(ValueFromPipelineByPropertyName = true)] public SwitchParameter PassThru { get; set; } #endregion protected override void ProcessRecord() { base.ProcessRecord(); var context = new CmdletContext(); // allow for manipulation of parameters prior to loading into context PreExecutionContextLoad(context); #pragma warning disable CS0618, CS0612 //A class member was marked with the Obsolete attribute if (ParameterWasBound(nameof(this.Select))) { context.Select = CreateSelectDelegate<Amazon.APIGateway.Model.GetMethodResponse, GetAGMethodCmdlet>(Select) ?? throw new System.ArgumentException("Invalid value for -Select parameter.", nameof(this.Select)); if (this.PassThru.IsPresent) { throw new System.ArgumentException("-PassThru cannot be used when -Select is specified.", nameof(this.Select)); } } else if (this.PassThru.IsPresent) { context.Select = (response, cmdlet) => this.RestApiId; } #pragma warning restore CS0618, CS0612 //A class member was marked with the Obsolete attribute context.HttpMethod = this.HttpMethod; #if MODULAR if (this.HttpMethod == null && ParameterWasBound(nameof(this.HttpMethod))) { WriteWarning("You are passing $null as a value for parameter HttpMethod which is marked as required. In case you believe this parameter was incorrectly marked as required, report this by opening an issue at https://github.com/aws/aws-tools-for-powershell/issues."); } #endif context.ResourceId = this.ResourceId; #if MODULAR if (this.ResourceId == null && ParameterWasBound(nameof(this.ResourceId))) { WriteWarning("You are passing $null as a value for parameter ResourceId which is marked as required. In case you believe this parameter was incorrectly marked as required, report this by opening an issue at https://github.com/aws/aws-tools-for-powershell/issues."); } #endif context.RestApiId = this.RestApiId; #if MODULAR if (this.RestApiId == null && ParameterWasBound(nameof(this.RestApiId))) { WriteWarning("You are passing $null as a value for parameter RestApiId which is marked as required. In case you believe this parameter was incorrectly marked as required, report this by opening an issue at https://github.com/aws/aws-tools-for-powershell/issues."); } #endif // allow further manipulation of loaded context prior to processing PostExecutionContextLoad(context); var output = Execute(context) as CmdletOutput; ProcessOutput(output); } #region IExecutor Members public object Execute(ExecutorContext context) { var cmdletContext = context as CmdletContext; // create request var request = new Amazon.APIGateway.Model.GetMethodRequest(); if (cmdletContext.HttpMethod != null) { request.HttpMethod = cmdletContext.HttpMethod; } if (cmdletContext.ResourceId != null) { request.ResourceId = cmdletContext.ResourceId; } if (cmdletContext.RestApiId != null) { request.RestApiId = cmdletContext.RestApiId; } CmdletOutput output; // issue call var client = Client ?? CreateClient(_CurrentCredentials, _RegionEndpoint); try { var response = CallAWSServiceOperation(client, request); object pipelineOutput = null; pipelineOutput = cmdletContext.Select(response, this); output = new CmdletOutput { PipelineOutput = pipelineOutput, ServiceResponse = response }; } catch (Exception e) { output = new CmdletOutput { ErrorResponse = e }; } return output; } public ExecutorContext CreateContext() { return new CmdletContext(); } #endregion #region AWS Service Operation Call private Amazon.APIGateway.Model.GetMethodResponse CallAWSServiceOperation(IAmazonAPIGateway client, Amazon.APIGateway.Model.GetMethodRequest request) { Utils.Common.WriteVerboseEndpointMessage(this, client.Config, "Amazon API Gateway", "GetMethod"); try { #if DESKTOP return client.GetMethod(request); #elif CORECLR return client.GetMethodAsync(request).GetAwaiter().GetResult(); #else #error "Unknown build edition" #endif } catch (AmazonServiceException exc) { var webException = exc.InnerException as System.Net.WebException; if (webException != null) { throw new Exception(Utils.Common.FormatNameResolutionFailureMessage(client.Config, webException.Message), webException); } throw; } } #endregion internal partial class CmdletContext : ExecutorContext { public System.String HttpMethod { get; set; } public System.String ResourceId { get; set; } public System.String RestApiId { get; set; } public System.Func<Amazon.APIGateway.Model.GetMethodResponse, GetAGMethodCmdlet, object> Select { get; set; } = (response, cmdlet) => response; } } }
44.731518
281
0.606298
[ "Apache-2.0" ]
5u5hma/aws-tools-for-powershell
modules/AWSPowerShell/Cmdlets/APIGateway/Basic/Get-AGMethod-Cmdlet.cs
11,496
C#
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace Pathfinder.Visualizer.Data { public class Node { public int Id { get; set; } public double X { get; set; } public double Y { get; set; } public State state { get; set; } } }
19.294118
40
0.625
[ "MIT" ]
MickJar/Pathfinder.Visualizer
GraphSolver/Services/Node.cs
330
C#
#if ENABLE_IL2CPP #define INLINE_METHODS #endif namespace ME.ECS.Collections { public struct IntrusiveHashSetBucket : IStructComponent { public IntrusiveList list; } public interface IIntrusiveHashSet { int Count { get; } void Add(in Entity entityData); bool Remove(in Entity entityData); int RemoveAll(in Entity entityData); void Clear(bool destroyData = false); bool Contains(in Entity entityData); BufferArray<Entity> ToArray(); IntrusiveHashSet.Enumerator GetEnumerator(); } #if ECS_COMPILE_IL2CPP_OPTIONS [Unity.IL2CPP.CompilerServices.Il2CppSetOptionAttribute(Unity.IL2CPP.CompilerServices.Option.NullChecks, false)] [Unity.IL2CPP.CompilerServices.Il2CppSetOptionAttribute(Unity.IL2CPP.CompilerServices.Option.ArrayBoundsChecks, false)] [Unity.IL2CPP.CompilerServices.Il2CppSetOptionAttribute(Unity.IL2CPP.CompilerServices.Option.DivideByZeroChecks, false)] #endif public struct IntrusiveHashSet : IIntrusiveHashSet { #if ECS_COMPILE_IL2CPP_OPTIONS [Unity.IL2CPP.CompilerServices.Il2CppSetOptionAttribute(Unity.IL2CPP.CompilerServices.Option.NullChecks, false)] [Unity.IL2CPP.CompilerServices.Il2CppSetOptionAttribute(Unity.IL2CPP.CompilerServices.Option.ArrayBoundsChecks, false)] [Unity.IL2CPP.CompilerServices.Il2CppSetOptionAttribute(Unity.IL2CPP.CompilerServices.Option.DivideByZeroChecks, false)] #endif public struct Enumerator : System.Collections.Generic.IEnumerator<Entity> { private IntrusiveHashSet hashSet; private int bucketIndex; private IntrusiveList.Enumerator listEnumerator; Entity System.Collections.Generic.IEnumerator<Entity>.Current => this.listEnumerator.Current; public ref Entity Current => ref this.listEnumerator.Current; #if INLINE_METHODS [System.Runtime.CompilerServices.MethodImplAttribute(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] #endif public Enumerator(IntrusiveHashSet hashSet) { this.hashSet = hashSet; this.bucketIndex = 0; this.listEnumerator = default; } #if INLINE_METHODS [System.Runtime.CompilerServices.MethodImplAttribute(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] #endif public bool MoveNext() { while (this.bucketIndex <= this.hashSet.buckets.Length) { if (this.listEnumerator.MoveNext() == true) { return true; } var bucket = this.hashSet.buckets[this.bucketIndex]; if (bucket.IsAlive() == true) { var node = bucket.Get<IntrusiveHashSetBucket>(); this.listEnumerator = node.list.GetEnumerator(); } ++this.bucketIndex; } return false; } #if INLINE_METHODS [System.Runtime.CompilerServices.MethodImplAttribute(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] #endif public void Reset() { this.bucketIndex = 0; this.listEnumerator = default; } object System.Collections.IEnumerator.Current { get { throw new AllocationException(); } } public void Dispose() { } } [ME.ECS.Serializer.SerializeField] private StackArray10<Entity> buckets; [ME.ECS.Serializer.SerializeField] private int count; public int Count => this.count; #if INLINE_METHODS [System.Runtime.CompilerServices.MethodImplAttribute(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] #endif public Enumerator GetEnumerator() { return new Enumerator(this); } /// <summary> /// Put entity data into array. /// </summary> /// <returns>Buffer array from pool</returns> #if INLINE_METHODS [System.Runtime.CompilerServices.MethodImplAttribute(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] #endif public BufferArray<Entity> ToArray() { var arr = PoolArray<Entity>.Spawn(this.count); var i = 0; foreach (var entity in this) { arr.arr[i++] = entity; } return arr; } /// <summary> /// Find an element. /// </summary> /// <param name="entityData"></param> /// <returns>Returns TRUE if data was found</returns> #if INLINE_METHODS [System.Runtime.CompilerServices.MethodImplAttribute(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] #endif public bool Contains(in Entity entityData) { var bucket = (entityData.GetHashCode() & 0x7fffffff) % this.buckets.Length; var bucketEntity = this.buckets[bucket]; if (bucketEntity.IsAlive() == false) return false; ref var bucketList = ref bucketEntity.Get<IntrusiveHashSetBucket>(); return bucketList.list.Contains(entityData); } /// <summary> /// Clear the list. /// </summary> #if INLINE_METHODS [System.Runtime.CompilerServices.MethodImplAttribute(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] #endif public void Clear(bool destroyData = false) { for (int i = 0; i < this.buckets.Length; ++i) { var bucket = this.buckets[i]; if (bucket.IsAlive() == true) { ref var data = ref bucket.Get<IntrusiveHashSetBucket>(); data.list.Clear(); } } this.count = 0; } /// <summary> /// Disposes this instance /// </summary> public void Dispose() { this.Clear(); for (int i = 0; i < this.buckets.Length; ++i) { this.buckets[i].Destroy(); this.buckets[i] = default; } } /// <summary> /// Remove data from list. /// </summary> /// <param name="entityData"></param> /// <returns>Returns TRUE if data was found</returns> #if INLINE_METHODS [System.Runtime.CompilerServices.MethodImplAttribute(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] #endif public bool Remove(in Entity entityData) { var bucket = (entityData.GetHashCode() & 0x7fffffff) % this.buckets.Length; var bucketEntity = this.buckets[bucket]; if (bucketEntity.IsAlive() == false) return false; ref var bucketList = ref bucketEntity.Get<IntrusiveHashSetBucket>(false); if (bucketList.list.Remove(entityData) == true) { --this.count; return true; } return false; } /// <summary> /// Remove all nodes data from list. /// </summary> /// <param name="entityData"></param> /// <returns>Returns TRUE if data was found</returns> #if INLINE_METHODS [System.Runtime.CompilerServices.MethodImplAttribute(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] #endif public int RemoveAll(in Entity entityData) { var bucket = (entityData.GetHashCode() & 0x7fffffff) % this.buckets.Length; var bucketEntity = this.buckets[bucket]; if (bucketEntity.IsAlive() == false) return 0; ref var bucketList = ref bucketEntity.Get<IntrusiveHashSetBucket>(false); var count = bucketList.list.RemoveAll(in entityData); this.count -= count; return count; } /// <summary> /// Add new data at the end of the list. /// </summary> /// <param name="entityData"></param> #if INLINE_METHODS [System.Runtime.CompilerServices.MethodImplAttribute(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] #endif public void Add(in Entity entityData) { IntrusiveHashSet.Initialize(ref this); var bucket = (entityData.GetHashCode() & 0x7fffffff) % this.buckets.Length; var bucketEntity = this.buckets[bucket]; if (bucketEntity.IsAlive() == false) bucketEntity = this.buckets[bucket] = new Entity("IntrusiveHashSetBucket"); ref var bucketList = ref bucketEntity.Get<IntrusiveHashSetBucket>(); bucketList.list.Add(entityData); ++this.count; } #if INLINE_METHODS [System.Runtime.CompilerServices.MethodImplAttribute(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] #endif public void Add(in Entity entityData, out Entity node) { IntrusiveHashSet.Initialize(ref this); var bucket = (entityData.GetHashCode() & 0x7fffffff) % this.buckets.Length; var bucketEntity = this.buckets[bucket]; if (bucketEntity.IsAlive() == false) bucketEntity = this.buckets[bucket] = new Entity("IntrusiveHashSetBucket"); ref var bucketList = ref bucketEntity.Get<IntrusiveHashSetBucket>(); bucketList.list.Add(entityData, out node); ++this.count; } #region Helpers #if INLINE_METHODS [System.Runtime.CompilerServices.MethodImplAttribute(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] #endif private static void Initialize(ref IntrusiveHashSet hashSet) { if (hashSet.buckets.Length == 0) hashSet.buckets = new StackArray10<Entity>(10); } #endregion } }
33.873333
135
0.609821
[ "MIT" ]
IgorAtorin/ecs-submodule
ECS/Core/Collections/Intrusive/IntrusiveHashSet.cs
10,164
C#
using System; namespace FluentInterface.Examples.Classes { internal class ForthService : IForthService { public ForthService(string someData) { } public void DestroyMe() { throw new NotImplementedException(); } } }
17
48
0.588235
[ "MIT" ]
tmaconko/FluentInterface
FluentInterface.Examples/Classes/ForthService.cs
289
C#
using System.Collections.Generic; using System.ComponentModel.DataAnnotations; namespace TaskListMvc.Web.Models { public class ExternalLoginConfirmationViewModel { [Required] [Display(Name = "Email")] public string Email { get; set; } } public class ExternalLoginListViewModel { public string ReturnUrl { get; set; } } public class SendCodeViewModel { public string SelectedProvider { get; set; } public ICollection<System.Web.Mvc.SelectListItem> Providers { get; set; } public string ReturnUrl { get; set; } public bool RememberMe { get; set; } } public class VerifyCodeViewModel { [Required] public string Provider { get; set; } [Required] [Display(Name = "Code")] public string Code { get; set; } public string ReturnUrl { get; set; } [Display(Name = "Remember this browser?")] public bool RememberBrowser { get; set; } public bool RememberMe { get; set; } } public class ForgotViewModel { [Required] [Display(Name = "Email")] public string Email { get; set; } } public class LoginViewModel { [Required] [Display(Name = "Email")] [EmailAddress] public string Email { get; set; } [Required] [DataType(DataType.Password)] [Display(Name = "Password")] public string Password { get; set; } [Display(Name = "Remember me?")] public bool RememberMe { get; set; } } public class RegisterViewModel { [Required] [EmailAddress] [Display(Name = "Email")] public string Email { get; set; } [Required] [StringLength(100, ErrorMessage = "The {0} must be at least {2} characters long.", MinimumLength = 6)] [DataType(DataType.Password)] [Display(Name = "Password")] public string Password { get; set; } [DataType(DataType.Password)] [Display(Name = "Confirm password")] [Compare("Password", ErrorMessage = "The password and confirmation password do not match.")] public string ConfirmPassword { get; set; } } public class ResetPasswordViewModel { [Required] [EmailAddress] [Display(Name = "Email")] public string Email { get; set; } [Required] [StringLength(100, ErrorMessage = "The {0} must be at least {2} characters long.", MinimumLength = 6)] [DataType(DataType.Password)] [Display(Name = "Password")] public string Password { get; set; } [DataType(DataType.Password)] [Display(Name = "Confirm password")] [Compare("Password", ErrorMessage = "The password and confirmation password do not match.")] public string ConfirmPassword { get; set; } public string Code { get; set; } } public class ForgotPasswordViewModel { [Required] [EmailAddress] [Display(Name = "Email")] public string Email { get; set; } } }
27.557522
110
0.588632
[ "MIT" ]
NCGTC/task-list-mvc
TaskListMvc.Web/Models/AccountViewModels.cs
3,116
C#
// <copyright file="RoomGenCross.cs" company="Audino"> // Copyright (c) Audino // Licensed under the MIT license. See LICENSE file in the project root for full license information. // </copyright> using System; using System.Collections.Generic; namespace RogueElements { [Serializable] public class RoomGenCross<T> : RoomGen<T> where T : ITiledGenContext { [NonSerialized] private int chosenMinorWidth; [NonSerialized] private int chosenMinorHeight; [NonSerialized] private int chosenOffsetX; [NonSerialized] private int chosenOffsetY; public RoomGenCross() { } public RoomGenCross(RandRange majorWidth, RandRange majorHeight, RandRange minorHeight, RandRange minorWidth) { this.MajorWidth = majorWidth; this.MajorHeight = majorHeight; this.MinorWidth = minorWidth; this.MinorHeight = minorHeight; } protected RoomGenCross(RoomGenCross<T> other) { this.MajorWidth = other.MajorWidth; this.MajorHeight = other.MajorHeight; this.MinorWidth = other.MinorWidth; this.MinorHeight = other.MinorHeight; } public RandRange MajorWidth { get; set; } public RandRange MajorHeight { get; set; } public RandRange MinorHeight { get; set; } public RandRange MinorWidth { get; set; } protected int ChosenMinorWidth { get => this.chosenMinorWidth; set => this.chosenMinorWidth = value; } protected int ChosenMinorHeight { get => this.chosenMinorHeight; set => this.chosenMinorHeight = value; } protected int ChosenOffsetX { get => this.chosenOffsetX; set => this.chosenOffsetX = value; } protected int ChosenOffsetY { get => this.chosenOffsetY; set => this.chosenOffsetY = value; } public override RoomGen<T> Copy() => new RoomGenCross<T>(this); public override Loc ProposeSize(IRandom rand) { return new Loc(this.MajorWidth.Pick(rand), this.MajorHeight.Pick(rand)); } public override void DrawOnMap(T map) { Loc size1 = new Loc(this.Draw.Width, this.ChosenMinorHeight); Loc size2 = new Loc(this.ChosenMinorWidth, this.Draw.Height); Loc start1 = new Loc(this.Draw.X, this.Draw.Y + this.ChosenOffsetY); Loc start2 = new Loc(this.Draw.X + this.ChosenOffsetX, this.Draw.Y); for (int x = 0; x < size1.X; x++) { for (int y = 0; y < size1.Y; y++) map.SetTile(new Loc(start1.X + x, start1.Y + y), map.RoomTerrain.Copy()); } GenContextDebug.DebugProgress("First Rect"); for (int x = 0; x < size2.X; x++) { for (int y = 0; y < size2.Y; y++) map.SetTile(new Loc(start2.X + x, start2.Y + y), map.RoomTerrain.Copy()); } GenContextDebug.DebugProgress("Second Rect"); // hall restrictions this.SetRoomBorders(map); } protected override void PrepareFulfillableBorders(IRandom rand) { this.ChosenMinorWidth = Math.Min(this.Draw.Width, this.MinorWidth.Pick(rand)); this.ChosenMinorHeight = Math.Min(this.Draw.Height, this.MinorHeight.Pick(rand)); this.ChosenOffsetX = rand.Next(this.Draw.Width - this.ChosenMinorWidth + 1); this.ChosenOffsetY = rand.Next(this.Draw.Height - this.ChosenMinorHeight + 1); for (int jj = this.ChosenOffsetX; jj < this.ChosenOffsetX + this.ChosenMinorWidth; jj++) { this.FulfillableBorder[Dir4.Up][jj] = true; this.FulfillableBorder[Dir4.Down][jj] = true; } for (int jj = this.ChosenOffsetY; jj < this.ChosenOffsetY + this.ChosenMinorHeight; jj++) { this.FulfillableBorder[Dir4.Left][jj] = true; this.FulfillableBorder[Dir4.Right][jj] = true; } } } }
34.537815
117
0.595134
[ "MIT" ]
AntyMew/RogueElements
RogueElements/MapGen/Rooms/RoomGenCross.cs
4,112
C#
using System; namespace MetricsForceApp.Models { public class ErrorViewModel { public string RequestId { get; set; } public bool ShowRequestId => !string.IsNullOrEmpty(RequestId); } }
17.833333
70
0.672897
[ "MIT" ]
christineschutz/MetricsForce
src/MetricsForceApp/Models/ErrorViewModel.cs
214
C#
// Copyright (c) .NET Foundation. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for details. namespace mshtml { using System; using System.Collections; using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.InteropServices.CustomMarshalers; [ComImport, Guid("3050F377-98B5-11CF-BB82-00AA00BDCE0B"), TypeLibType((short) 0x1040), DefaultMember("item")] public interface IHTMLFontSizesCollection : IEnumerable { [DispId(0x5de)] int length { [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType=MethodCodeType.Runtime), TypeLibFunc((short) 0x40), DispId(0x5de)] get; } [return: MarshalAs(UnmanagedType.CustomMarshaler, MarshalTypeRef=typeof(EnumeratorToEnumVariantMarshaler))] [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType=MethodCodeType.Runtime), TypeLibFunc((short) 0x41), DispId(-4)] new IEnumerator GetEnumerator(); [DispId(0x5df)] string forFont { [return: MarshalAs(UnmanagedType.BStr)] [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType=MethodCodeType.Runtime), DispId(0x5df)] get; } [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType=MethodCodeType.Runtime), DispId(0)] int item([In] int index); } }
47.137931
170
0.744696
[ "MIT" ]
augustoproiete-forks/OpenLiveWriter--OpenLiveWriter
src/managed/OpenLiveWriter.Interop.Mshtml/mshtml/IHTMLFontSizesCollection.cs
1,367
C#
namespace WebServer.Server.Controllers { using HTTP; using Results; using System.Runtime.CompilerServices; using Contracts; using Identity; using Results.ViewEngine; public abstract class Controller { private UserIdentity user; private IViewEngine viewEngine; protected Controller() => this.Response = new Response(StatusCode.OK); protected Request Request { get; private init; } protected Response Response { get; private init; } protected UserIdentity User { get { if (this.user == null) { this.user = this.Request.Session.ContainsKey(Session.SessionUserKey) ? this.user = new() { Id = this.Request.Session[Session.SessionUserKey] } : this.user = new(); } return this.user; } private set => this.user = value; } protected IViewEngine ViewEngine { get { if (this.viewEngine == null) { this.viewEngine = this.Request.Services.GetService<IViewEngine>(); } return this.viewEngine; } } protected IModelState ModelState { get; private init; } protected void SignIn(string userId) { this.Request.Session[Session.SessionUserKey] = userId; this.User = new() { Id = userId }; } protected void SignOut() { this.Request.Session.Remove(Session.SessionUserKey); this.User = new(); } protected Response Text(string text) => new TextResult(this.Response, text); protected Response Html(string html) => new HtmlResult(this.Response, html); protected Response BadRequest() => new BadRequestResult(this.Response); protected Response Unauthorized() => new UnauthorizedResult(this.Response); protected Response NotFound() => new NotFoundResult(this.Response); protected Response Redirect(string location) => new RedirectResult(this.Response, location); protected Response File(string fileName, string disposition = "") => new TextFileResult(this.Response, fileName, disposition); protected Response View([CallerMemberName] string viewName = "") => new ViewResult( this.Response, this.ViewEngine, this.User, viewName, this.GetType().GetControllerName()); protected Response View(object model, [CallerMemberName] string viewName = "") => new ViewResult( this.Response, this.ViewEngine, this.User, viewName, this.GetType().GetControllerName(), model); } }
29.037383
97
0.52945
[ "MIT" ]
GosuMonkeyManiak/CSharp-Web-Server
WebServer.Server/Controllers/Controller.cs
3,109
C#
//------------------------------------------------------------------------------ // <copyright file="TreeNodeBinding.cs" company="Microsoft"> // Copyright (c) Microsoft Corporation. All rights reserved. // </copyright> //------------------------------------------------------------------------------ namespace System.Web.UI.WebControls { using System; using System.ComponentModel; using System.Drawing.Design; using System.Web; /// <devdoc> /// Provides a data mapping definition for a TreeView /// </devdoc> [DefaultProperty("TextField")] public sealed class TreeNodeBinding : IStateManager, ICloneable, IDataSourceViewSchemaAccessor { private bool _isTrackingViewState; private StateBag _viewState; /// <devdoc> /// The data member to use in the mapping /// </devdoc> [ DefaultValue(""), WebCategory("Data"), WebSysDescription(SR.Binding_DataMember), ] public string DataMember { get { string s = (string)ViewState["DataMember"]; if (s == null) { return String.Empty; } else { return s; } } set { ViewState["DataMember"] = value; } } /// <devdoc> /// The depth of the level for which this TreeNodeBinding is defining a data mapping /// </devdoc> [ DefaultValue(-1), TypeConverter("System.Web.UI.Design.WebControls.TreeNodeBindingDepthConverter, " + AssemblyRef.SystemDesign), WebCategory("Data"), WebSysDescription(SR.TreeNodeBinding_Depth), ] public int Depth { get { object o = ViewState["Depth"]; if (o == null) { return -1; } return (int)o; } set { ViewState["Depth"] = value; } } [DefaultValue("")] [Localizable(true)] [WebCategory("Databindings")] [WebSysDescription(SR.TreeNodeBinding_FormatString)] public string FormatString { get { string s = (string)ViewState["FormatString"]; if (s == null) { return String.Empty; } return s; } set { ViewState["FormatString"] = value; } } /// <devdoc> /// Gets and sets the TreeNodeBinding ImageToolTip /// </devdoc> [DefaultValue("")] [Localizable(true)] [WebCategory("DefaultProperties")] [WebSysDescription(SR.TreeNodeBinding_ImageToolTip)] public string ImageToolTip { get { string s = (string)ViewState["ImageToolTip"]; if (s == null) { return String.Empty; } return s; } set { ViewState["ImageToolTip"] = value; } } /// <devdoc> /// Get and sets the fieldname to use for the ImageToolTip property in a TreeNode /// </devdoc> [DefaultValue("")] [TypeConverter("System.Web.UI.Design.DataSourceViewSchemaConverter, " + AssemblyRef.SystemDesign), WebSysDescription(SR.TreeNodeBinding_ImageToolTipField)] [WebCategory("Databindings")] public string ImageToolTipField { get { string s = (string)ViewState["ImageToolTipField"]; if (s == null) { return String.Empty; } else { return s; } } set { ViewState["ImageToolTipField"] = value; } } /// <devdoc> /// Gets and sets the image URl to be rendered for this node /// </devdoc> [DefaultValue("")] [Editor("System.Web.UI.Design.ImageUrlEditor, " + AssemblyRef.SystemDesign, typeof(UITypeEditor))] [UrlProperty()] [WebCategory("DefaultProperties")] [WebSysDescription(SR.TreeNodeBinding_ImageUrl)] public string ImageUrl { get { string s = (string)ViewState["ImageUrl"]; if (s == null) { return String.Empty; } return s; } set { ViewState["ImageUrl"] = value; } } /// <devdoc> /// Get and sets the fieldname to use for the ImageUrl property in a TreeNode /// </devdoc> [ DefaultValue(""), TypeConverter("System.Web.UI.Design.DataSourceViewSchemaConverter, " + AssemblyRef.SystemDesign), WebCategory("Databindings"), WebSysDescription(SR.TreeNodeBinding_ImageUrlField), ] public string ImageUrlField { get { string s = (string)ViewState["ImageUrlField"]; if (s == null) { return String.Empty; } else { return s; } } set { ViewState["ImageUrlField"] = value; } } /// <devdoc> /// Gets and sets the URL to navigate to when the node is clicked /// </devdoc> [DefaultValue("")] [Editor("System.Web.UI.Design.UrlEditor, " + AssemblyRef.SystemDesign, typeof(UITypeEditor))] [UrlProperty()] [WebCategory("DefaultProperties")] [WebSysDescription(SR.TreeNodeBinding_NavigateUrl)] public string NavigateUrl { get { string s = (string)ViewState["NavigateUrl"]; if (s == null) { return String.Empty; } return s; } set { ViewState["NavigateUrl"] = value; } } /// <devdoc> /// Get and sets the fieldname to use for the NavigateUrl property in a TreeNode /// </devdoc> [ DefaultValue(""), TypeConverter("System.Web.UI.Design.DataSourceViewSchemaConverter, " + AssemblyRef.SystemDesign), WebCategory("Databindings"), WebSysDescription(SR.TreeNodeBinding_NavigateUrlField), ] public string NavigateUrlField { get { string s = (string)ViewState["NavigateUrlField"]; if (s == null) { return String.Empty; } else { return s; } } set { ViewState["NavigateUrlField"] = value; } } /// <devdoc> /// Gets and sets whether to populate this binding immediately or on the next request for population /// </devdoc> [ DefaultValue(false), WebCategory("DefaultProperties"), WebSysDescription(SR.TreeNodeBinding_PopulateOnDemand), ] public bool PopulateOnDemand { get { object o = ViewState["PopulateOnDemand"]; if (o == null) { return false; } return (bool)o; } set { ViewState["PopulateOnDemand"] = value; } } /// <devdoc> /// Gets and sets the action which the TreeNodeBinding will perform when selected /// </devdoc> [DefaultValue(TreeNodeSelectAction.Select)] [WebCategory("DefaultProperties")] [WebSysDescription(SR.TreeNodeBinding_SelectAction)] public TreeNodeSelectAction SelectAction { get { object o = ViewState["SelectAction"]; if (o == null) { return TreeNodeSelectAction.Select; } return (TreeNodeSelectAction)o; } set { ViewState["SelectAction"] = value; } } /// <devdoc> /// Gets and sets whether the TreeNodeBinding has a CheckBox /// </devdoc> [DefaultValue(typeof(Nullable<bool>), "")] [WebCategory("DefaultProperties")] [WebSysDescription(SR.TreeNodeBinding_ShowCheckBox)] public bool? ShowCheckBox { get { object o = ViewState["ShowCheckBox"]; if (o == null) { return null; } return (bool?)o; } set { ViewState["ShowCheckBox"] = value; } } /// <devdoc> /// Gets and sets the target window that the TreeNodeBinding will browse to if selected /// </devdoc> [DefaultValue("")] [WebCategory("DefaultProperties")] [WebSysDescription(SR.TreeNodeBinding_Target)] public string Target { get { string s = (string)ViewState["Target"]; if (s == null) { return String.Empty; } return s; } set { ViewState["Target"] = value; } } [ DefaultValue(""), TypeConverter("System.Web.UI.Design.DataSourceViewSchemaConverter, " + AssemblyRef.SystemDesign), WebCategory("Databindings"), WebSysDescription(SR.TreeNodeBinding_TargetField), ] public string TargetField { get { string s = (string)ViewState["TargetField"]; if (s == null) { return String.Empty; } else { return s; } } set { ViewState["TargetField"] = value; } } /// <devdoc> /// Gets and sets the display text /// </devdoc> [DefaultValue("")] [Localizable(true)] [WebCategory("DefaultProperties")] [WebSysDescription(SR.TreeNodeBinding_Text)] public string Text { get { string s = (string)ViewState["Text"]; if (s == null) { s = (string)ViewState["Value"]; if (s == null) { return String.Empty; } } return s; } set { ViewState["Text"] = value; } } /// <devdoc> /// Get and sets the fieldname to use for the Text property in a TreeNode /// </devdoc> [ DefaultValue(""), TypeConverter("System.Web.UI.Design.DataSourceViewSchemaConverter, " + AssemblyRef.SystemDesign), WebCategory("Databindings"), WebSysDescription(SR.TreeNodeBinding_TextField), ] public string TextField { get { string s = (string)ViewState["TextField"]; if (s == null) { return String.Empty; } else { return s; } } set { ViewState["TextField"] = value; } } /// <devdoc> /// Gets and sets the TreeNodeBinding tooltip /// </devdoc> [DefaultValue("")] [Localizable(true)] [WebCategory("DefaultProperties")] [WebSysDescription(SR.TreeNodeBinding_ToolTip)] public string ToolTip { get { string s = (string)ViewState["ToolTip"]; if (s == null) { return String.Empty; } return s; } set { ViewState["ToolTip"] = value; } } /// <devdoc> /// Get and sets the fieldname to use for the ToolTip property in a TreeNode /// </devdoc> [ DefaultValue(""), TypeConverter("System.Web.UI.Design.DataSourceViewSchemaConverter, " + AssemblyRef.SystemDesign), WebCategory("Databindings"), WebSysDescription(SR.TreeNodeBinding_ToolTipField), ] public string ToolTipField { get { string s = (string)ViewState["ToolTipField"]; if (s == null) { return String.Empty; } else { return s; } } set { ViewState["ToolTipField"] = value; } } /// <devdoc> /// Gets and sets the value /// </devdoc> [DefaultValue("")] [Localizable(true)] [WebCategory("DefaultProperties")] [WebSysDescription(SR.TreeNodeBinding_Value)] public string Value { get { string s = (string)ViewState["Value"]; if (s == null) { s = (string)ViewState["Text"]; if (s == null) { return String.Empty; } } return s; } set { ViewState["Value"] = value; } } /// <devdoc> /// Get and sets the fieldname to use for the Value property in a TreeNode /// </devdoc> [ DefaultValue(""), TypeConverter("System.Web.UI.Design.DataSourceViewSchemaConverter, " + AssemblyRef.SystemDesign), WebCategory("Databindings"), WebSysDescription(SR.TreeNodeBinding_ValueField), ] public string ValueField { get { string s = (string)ViewState["ValueField"]; if (s == null) { return String.Empty; } else { return s; } } set { ViewState["ValueField"] = value; } } /// <devdoc> /// The state for this TreeNodeBinding /// </devdoc> private StateBag ViewState { get { if (_viewState == null) { _viewState = new StateBag(); if (_isTrackingViewState) { ((IStateManager)_viewState).TrackViewState(); } } return _viewState; } } internal void SetDirty() { ViewState.SetDirty(true); } public override string ToString() { return (String.IsNullOrEmpty(DataMember) ? SR.GetString(SR.TreeNodeBinding_EmptyBindingText) : DataMember); } #region ICloneable implemention /// <internalonly/> /// <devdoc> /// Creates a clone of the TreeNodeBinding. /// </devdoc> object ICloneable.Clone() { TreeNodeBinding clone = new TreeNodeBinding(); clone.DataMember = DataMember; clone.Depth = Depth; clone.FormatString = FormatString; clone.ImageToolTip = ImageToolTip; clone.ImageToolTipField = ImageToolTipField; clone.ImageUrl = ImageUrl; clone.ImageUrlField = ImageUrlField; clone.NavigateUrl = NavigateUrl; clone.NavigateUrlField = NavigateUrlField; clone.PopulateOnDemand = PopulateOnDemand; clone.SelectAction = SelectAction; clone.ShowCheckBox = ShowCheckBox; clone.Target = Target; clone.TargetField = TargetField; clone.Text = Text; clone.TextField = TextField; clone.ToolTip = ToolTip; clone.ToolTipField = ToolTipField; clone.Value = Value; clone.ValueField = ValueField; return clone; } #endregion #region IStateManager implementation /// <internalonly/> bool IStateManager.IsTrackingViewState { get { return _isTrackingViewState; } } /// <internalonly/> void IStateManager.LoadViewState(object state) { if (state != null) { ((IStateManager)ViewState).LoadViewState(state); } } /// <internalonly/> object IStateManager.SaveViewState() { if (_viewState != null) { return ((IStateManager)_viewState).SaveViewState(); } return null; } /// <internalonly/> void IStateManager.TrackViewState() { _isTrackingViewState = true; if (_viewState != null) { ((IStateManager)_viewState).TrackViewState(); } } #endregion #region IDataSourceViewSchemaAccessor implementation /// <internalonly/> object IDataSourceViewSchemaAccessor.DataSourceViewSchema { get { return ViewState["IDataSourceViewSchemaAccessor.DataSourceViewSchema"]; } set { ViewState["IDataSourceViewSchemaAccessor.DataSourceViewSchema"] = value; } } #endregion } }
30.166096
163
0.472612
[ "Apache-2.0" ]
295007712/295007712.github.io
sourceCode/dotNet4.6/ndp/fx/src/xsp/system/Web/UI/WebControls/TreeNodeBinding.cs
17,617
C#
using System; using NightlyCode.Scripting.Data; using NightlyCode.Scripting.Extensions; namespace NightlyCode.Scripting.Operations.Values { /// <summary> /// shifts the bits of LHS by RHS to the right /// </summary> public class ShiftRight : ValueOperation { internal ShiftRight() { } /// <inheritdoc /> protected override object Operate(object lhs, object rhs, ScriptContext context) { object value = lhs; int steps = rhs.Convert<int>(); int numberofbits = value.GetNumberOfBits(this); if (steps >= numberofbits) return Activator.CreateInstance(value.GetType()); object mask = ValueExtensions.GetMask(value.GetType(), numberofbits-steps); return ((dynamic) value >> (dynamic) steps) & (dynamic) mask; } /// <inheritdoc /> public override Operator Operator => Operator.ShiftRight; /// <inheritdoc /> public override string ToString() { return $"{Lhs} >> {Rhs}"; } /// <inheritdoc /> public override string Literal => ">>"; } }
29.717949
90
0.58585
[ "Unlicense" ]
telmengedar/NightlyCode.Scripting
NightlyCode.Scripts/Operations/Values/ShiftRight.cs
1,161
C#
using System.Collections.Generic; using UnityEngine; namespace Hairibar.Ragdoll { public class RagdollBone { public PowerSetting PowerSetting { get => _powerSetting; set { PowerSetting oldValue = _powerSetting; _powerSetting = value; if (oldValue != value) { OnPowerSettingChanged?.Invoke(oldValue, value); } } } public delegate void OnPowerSettingChangedHandler(PowerSetting previousSetting, PowerSetting newSetting); public event OnPowerSettingChangedHandler OnPowerSettingChanged; public BoneName Name { get; } public bool IsRoot { get; } public Transform Transform { get; } public Rigidbody Rigidbody { get; } public ConfigurableJoint Joint { get; } public IEnumerable<Collider> Colliders { get; } public Quaternion StartingJointRotation { get; } PowerSetting _powerSetting = PowerSetting.Kinematic; #region Initialization internal RagdollBone(BoneName name, Transform transform, Rigidbody rigidbody, ConfigurableJoint joint, bool isRoot) { Name = name; Transform = transform; Rigidbody = rigidbody; Joint = joint; IsRoot = isRoot; Colliders = GatherColliders(); ConfigureJoint(); StartingJointRotation = GetStartingJointRotation(); } Collider[] GatherColliders() { List<Collider> colliders = new List<Collider>(); GatherCollidersAtTransform(Transform); VisitChildren(Transform); return colliders.ToArray(); void GatherCollidersAtTransform(Transform transform) { colliders.AddRange(transform.GetComponents<Collider>()); } void VisitChildren(Transform parent) { for (int i = 0; i < parent.childCount; i++) { Transform child = parent.GetChild(i); bool isItsOwnBone = child.GetComponent<ConfigurableJoint>(); if (!isItsOwnBone) { GatherCollidersAtTransform(child); VisitChildren(child); } } } } void ConfigureJoint() { Joint.configuredInWorldSpace = IsRoot; Joint.rotationDriveMode = RotationDriveMode.Slerp; } Quaternion GetStartingJointRotation() { return Joint.configuredInWorldSpace ? Transform.rotation : Transform.localRotation; } #endregion public override string ToString() { return Name.ToString(); } } }
28.821782
123
0.5517
[ "MIT" ]
H-man/Hairibar.Ragdoll
Core/Runtime/Core/RagdollBone.cs
2,913
C#
/* * Copyright 2018 JDCLOUD.COM * * 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. * * * * * * Contact: * * NOTE: This class is auto generated by the jdcloud code generator program. */ using System; using System.Collections.Generic; using System.Text; using JDCloudSDK.Core.Annotation; namespace JDCloudSDK.Monitor.Model { /// <summary> /// updatePanelSpec /// </summary> public class UpdatePanelSpec { ///<summary> /// 要更新panel所属dashboard的uid ///Required:true ///</summary> [Required] public string DashboardUid{ get; set; } ///<summary> /// 要更新panel所属维度 ///</summary> public string Dimension{ get; set; } ///<summary> /// 要更新panel包含的metric ///Required:true ///</summary> [Required] public List<PanelMetricForCreate> PanelMetrics{ get; set; } ///<summary> /// 要更新panel的名字 ///</summary> public string PanelName{ get; set; } ///<summary> /// 资源id列表,与标签服务互斥,且资源id列表与标签服务列表至少传一个 ///</summary> public List<PanelResource> PanelResources{ get; set; } ///<summary> /// 标签服务列表,与资源id列表互斥,且资源id列表与标签服务列表至少传一个 ///</summary> public List<PanelTagResource> PanelTagResources{ get; set; } ///<summary> /// topN的数量,图表类型为3(topN表格)时必填 ///</summary> public long? PanelTopNum{ get; set; } ///<summary> /// 要更新panel的类型,1-折线图(明细);2-折线图(汇总);3-topN表格 ///Required:true ///</summary> [Required] public long PanelType{ get; set; } ///<summary> /// 要更新panel的uuid ///Required:true ///</summary> [Required] public string PanelUid{ get; set; } ///<summary> /// 要更新panel所属产品 ///Required:true ///</summary> [Required] public string Product{ get; set; } ///<summary> /// 依据tag过滤(维度) ///</summary> public List<TagFilter> Tags{ get; set; } } }
26.701031
76
0.579537
[ "Apache-2.0" ]
jdcloud-api/jdcloud-sdk-net
sdk/src/Service/Monitor/Model/UpdatePanelSpec.cs
2,856
C#
using System; using WallF.BaseNEncodings.Inner; namespace WallF.BaseNEncodings { public partial class Base16Encoding : BaseEncoding { private Base16 b; private void InitAlgorithm(char[] alphabet) { this.b = new Base16(alphabet); } /// <summary> /// See <see cref="BaseEncoding.GetEncodeCountWithoutArgumentsValidation(int)"/>. /// </summary> protected override int GetEncodeCountWithoutArgumentsValidation(int length) { return b.EncodeSize(length); } /// <summary> /// See <see cref="BaseEncoding.EncodeWithoutArgumentsValidation(byte[], int, int)"/>. /// </summary> protected override char[] EncodeWithoutArgumentsValidation(byte[] bytes, int offset, int length) { char[] r = new char[b.EncodeSize(length)]; b.Encode(bytes, offset, length, r, 0, r.Length); return r; } /// <summary> /// See <see cref="BaseEncoding.EncodeWithoutArgumentsValidation(byte[], int, int, char[], int)"/>. /// </summary> /// <exception cref="ArgumentException">output sequence does not have enough capacity</exception> protected override int EncodeWithoutArgumentsValidation(byte[] bytesIn, int offsetIn, int lengthIn, char[] charsOut, int offsetOut) { return b.Encode(bytesIn, offsetIn, lengthIn, charsOut, offsetOut); } /// <summary> /// See <see cref="BaseEncoding.GetDecodeCountWithoutArgumentsValidation(char[], int, int)"/>. /// </summary> /// <exception cref="FormatException">input sequence is not a valid base sequence</exception> protected override int GetDecodeCountWithoutArgumentsValidation(char[] chars, int offset, int length) { return b.DecodeSize(length); } /// <summary> /// See <see cref="BaseEncoding.DecodeWithoutArgumentsValidation(char[], int, int)"/>. /// </summary> /// <exception cref="FormatException">input sequence is not a valid base sequence</exception> protected override byte[] DecodeWithoutArgumentsValidation(char[] chars, int offset, int length) { byte[] r = new byte[b.DecodeSize(length)]; b.Decode(chars, offset, length, r, 0, r.Length); return r; } /// <summary> /// See <see cref="BaseEncoding.DecodeWithoutArgumentsValidation(char[], int, int, byte[], int)"/>. /// </summary> /// <exception cref="FormatException">input sequence is not a valid base sequence</exception> /// <exception cref="ArgumentException">output sequence does not have enough capacity</exception> protected override int DecodeWithoutArgumentsValidation(char[] charsIn, int offsetIn, int lengthIn, byte[] bytesOut, int offsetOut) { return b.Decode(charsIn, offsetIn, lengthIn, bytesOut, offsetOut); } /// <summary> /// See <see cref="BaseEncoding.IsValidBaseSequenceWithoutArgumentsValidation(char[], int, int)"/>. /// </summary> protected override bool IsValidBaseSequenceWithoutArgumentsValidation(char[] chars, int offset, int length) { return b.IsValidBaseSequence(chars, offset, length); } } }
41.506173
139
0.624926
[ "Apache-2.0" ]
wujikui/BaseNEncodings.Net
BaseNEncodings/Base16Encoding_Algorithm.cs
3,364
C#
using System; using System.Linq; using Moq; using NModbus.Device; using NModbus.IO; using Xunit; namespace NModbus.UnitTests.Device { public class ModbusMasterFixture { private static IStreamResource StreamRsource => new Mock<IStreamResource>(MockBehavior.Strict).Object; private static IModbusSerialTransport Transport => new Mock<IModbusSerialTransport>().Object; private ModbusSerialClient Master => new ModbusSerialClient(Transport); [Fact] public void ReadCoils() { Assert.Throws<ArgumentException>(() => Master.ReadCoils(1, 1, 0)); Assert.Throws<ArgumentException>(() => Master.ReadCoils(1, 1, 2001)); } [Fact] public void ReadInputs() { Assert.Throws<ArgumentException>(() => Master.ReadInputs(1, 1, 0)); Assert.Throws<ArgumentException>(() => Master.ReadInputs(1, 1, 2001)); } [Fact] public void ReadHoldingRegisters() { Assert.Throws<ArgumentException>(() => Master.ReadHoldingRegisters(1, 1, 0)); Assert.Throws<ArgumentException>(() => Master.ReadHoldingRegisters(1, 1, 126)); } [Fact] public void ReadInputRegisters() { Assert.Throws<ArgumentException>(() => Master.ReadInputRegisters(1, 1, 0)); Assert.Throws<ArgumentException>(() => Master.ReadInputRegisters(1, 1, 126)); } [Fact] public void WriteMultipleRegisters() { Assert.Throws<ArgumentNullException>(() => Master.WriteMultipleRegisters(1, 1, null)); Assert.Throws<ArgumentException>(() => Master.WriteMultipleRegisters(1, 1, new ushort[0])); Assert.Throws<ArgumentException>(() => Master.WriteMultipleRegisters(1, 1, Enumerable.Repeat<ushort>(1, 124).ToArray())); } [Fact] public void WriteMultipleCoils() { Assert.Throws<ArgumentNullException>(() => Master.WriteMultipleCoils(1, 1, null)); Assert.Throws<ArgumentException>(() => Master.WriteMultipleCoils(1, 1, new bool[0])); Assert.Throws<ArgumentException>(() => Master.WriteMultipleCoils(1, 1, Enumerable.Repeat(false, 1969).ToArray())); } [Fact] public void ReadWriteMultipleRegisters() { // validate numberOfPointsToRead Assert.Throws<ArgumentException>(() => Master.ReadWriteMultipleRegisters(1, 1, 0, 1, new ushort[] { 1 })); Assert.Throws<ArgumentException>(() => Master.ReadWriteMultipleRegisters(1, 1, 126, 1, new ushort[] { 1 })); // validate writeData Assert.Throws<ArgumentNullException>(() => Master.ReadWriteMultipleRegisters(1, 1, 1, 1, null)); Assert.Throws<ArgumentException>(() => Master.ReadWriteMultipleRegisters(1, 1, 1, 1, new ushort[0])); Assert.Throws<ArgumentException>(() => Master.ReadWriteMultipleRegisters(1, 1, 1, 1, Enumerable.Repeat<ushort>(1, 122).ToArray())); } [Fact] public void WriteFileRecord() { Assert.Throws<ArgumentNullException>(() => Master.WriteFileRecord(1, 1, 2, null)); // Max message byte size is 256, minus 11 for overhead, // 244 data bytes are allowed (must be even), 246 should throw. Assert.Throws<ArgumentException>(() => Master.WriteFileRecord(1, 1, 2, Enumerable.Repeat<byte>(1, 246).ToArray())); } } }
41.546512
144
0.603974
[ "MIT" ]
matt-floyd-captiveaire/NModbus
NModbus.UnitTests/Device/ModbusMasterFixture.cs
3,575
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 organizations-2016-11-28.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.Organizations.Model { /// <summary> /// Contains information about a root, OU, or account that a policy is attached to. /// </summary> public partial class PolicyTargetSummary { private string _arn; private string _name; private string _targetId; private TargetType _type; /// <summary> /// Gets and sets the property Arn. /// <para> /// The Amazon Resource Name (ARN) of the policy target. /// </para> /// /// <para> /// For more information about ARNs in Organizations, see <a href="https://docs.aws.amazon.com/organizations/latest/userguide/orgs_permissions.html#orgs-permissions-arns">ARN /// Formats Supported by Organizations</a> in the <i>AWS Organizations User Guide</i>. /// </para> /// </summary> public string Arn { get { return this._arn; } set { this._arn = value; } } // Check to see if Arn property is set internal bool IsSetArn() { return this._arn != null; } /// <summary> /// Gets and sets the property Name. /// <para> /// The friendly name of the policy target. /// </para> /// /// <para> /// The <a href="http://wikipedia.org/wiki/regex">regex pattern</a> that is used to validate /// this parameter is a string of any of the characters in the ASCII character range. /// </para> /// </summary> [AWSProperty(Min=1, Max=128)] public string Name { get { return this._name; } set { this._name = value; } } // Check to see if Name property is set internal bool IsSetName() { return this._name != null; } /// <summary> /// Gets and sets the property TargetId. /// <para> /// The unique identifier (ID) of the policy target. /// </para> /// /// <para> /// The <a href="http://wikipedia.org/wiki/regex">regex pattern</a> for a target ID string /// requires one of the following: /// </para> /// <ul> <li> /// <para> /// Root: A string that begins with "r-" followed by from 4 to 32 lower-case letters or /// digits. /// </para> /// </li> <li> /// <para> /// Account: A string that consists of exactly 12 digits. /// </para> /// </li> <li> /// <para> /// Organizational unit (OU): A string that begins with "ou-" followed by from 4 to 32 /// lower-case letters or digits (the ID of the root that the OU is in). This string is /// followed by a second "-" dash and from 8 to 32 additional lower-case letters or digits. /// </para> /// </li> </ul> /// </summary> public string TargetId { get { return this._targetId; } set { this._targetId = value; } } // Check to see if TargetId property is set internal bool IsSetTargetId() { return this._targetId != null; } /// <summary> /// Gets and sets the property Type. /// <para> /// The type of the policy target. /// </para> /// </summary> public TargetType Type { get { return this._type; } set { this._type = value; } } // Check to see if Type property is set internal bool IsSetType() { return this._type != null; } } }
31.438356
182
0.554031
[ "Apache-2.0" ]
Melvinerall/aws-sdk-net
sdk/src/Services/Organizations/Generated/Model/PolicyTargetSummary.cs
4,590
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Xml.Serialization; using System.ComponentModel; using CommonUI; using Common; namespace ControlEngine { [Serializable] [XmlInclude(typeof(ControlButton))] [XmlInclude(typeof(ControlImage))] [XmlInclude(typeof(ControlTapScene))] [XmlInclude(typeof(ControlBehavior))] [XmlInclude(typeof(ControlText))] [XmlInclude(typeof(ControlCircle))] [XmlInclude(typeof(ControlPanel))] public class ControlBase : IPathConvertible, ISupportId { /// <summary> /// Индентификатор контрола /// </summary> [CategoryAttribute("Базовые")] [DescriptionAttribute("Индентификатор контрола")] [ReadOnlyAttribute(true)] public string Id { get; set; } /// <summary> /// Наименование контрола /// </summary> [CategoryAttribute("Базовые")] [DescriptionAttribute("Наименование контрола")] public string Name { get; set; } [CategoryAttribute("Базовые")] [DescriptionAttribute("Видимость контрола")] public bool IsVisible { get; set; } [CategoryAttribute("Редактор")] [DescriptionAttribute("Видимость контрола в редакторе")] public bool IsVisibleInEditor { get; set; } /// <summary> /// Событие при создании контрола /// </summary> [CategoryAttribute("События")] [DescriptionAttribute("Событие при появлении пакета контрола")] [Editor(typeof(CommonUI.UITypeEditors.UITypeEditorScriptFileName), typeof(System.Drawing.Design.UITypeEditor))] [ParserAutocompleteAttribute(ParserAutocompleteAttribute.ParserTypeWords.Controls | ParserAutocompleteAttribute.ParserTypeWords.Units)] public string OnPackageShow { get; set; } public ControlBase() { Id = Guid.NewGuid().ToString("B").ToUpper(); Name = string.Empty; OnPackageShow = string.Empty; IsVisible = true; IsVisibleInEditor = true; } public virtual void ToRelativePaths(string root) { } public virtual void ToAbsolutePaths(string root) { } public ControlBase DeepClone() { return Common.SerializeWorker.Clone(this) as ControlBase; } } }
31.932432
143
0.647905
[ "MIT" ]
twesd/editor
ControlEngine/ControlBase.cs
2,588
C#
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; namespace webfrontend { public class Startup { public Startup(IConfiguration configuration) { Configuration = configuration; } public IConfiguration Configuration { get; } // This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { services.AddMvc(); } // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IHostingEnvironment env) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } else { app.UseExceptionHandler("/Home/Error"); } app.UseStaticFiles(); app.UseMvc(routes => { routes.MapRoute( name: "default", template: "{controller=Home}/{action=Index}/{id?}"); }); } } }
27.58
106
0.591008
[ "MIT" ]
Azure/dev-spaces
samples/existingWindowsBackend/webfrontend-linux/Startup.cs
1,381
C#
using RimWorld; using RimWorld.BaseGen; using System; using Verse; namespace KCSG { internal class SymbolResolver_ScatterStuffAround : SymbolResolver { public override void Resolve(ResolveParams rp) { Map map = BaseGen.globalSettings.map; if (CGO.factionSettlement.scatterThings?.Count > 0) { Random r = new Random(Find.TickManager.TicksGame); foreach (IntVec3 cell in rp.rect) { if (cell.Roofed(map) && cell.Walkable(map) && r.NextDouble() < CGO.factionSettlement.scatterChance) { ThingDef thingDef = CGO.factionSettlement.scatterThings.RandomElement(); Thing thing = ThingMaker.MakeThing(thingDef, thingDef.MadeFromStuff ? thingDef.defaultStuff : null); thing.stackCount = Math.Min(r.Next(5, thing.def.stackLimit), 75); thing.SetForbidden(true, false); GenSpawn.Spawn(thing, cell, map, WipeMode.FullRefund); } } } } } }
37.16129
124
0.554688
[ "MIT" ]
AndroidQuazar/VanillaFactionsExpanded-Core
Source/KCSG/SymbolResolvers/StructureRuining/SymbolResolver_ScatterStuffAround.cs
1,154
C#
using UnityEngine; using UnityEngine.UI; using TMPro; public class TechReference : MonoBehaviour { [SerializeField] private Image icon; [SerializeField] private TextMeshProUGUI nameText; [SerializeField] private TextMeshProUGUI description; [SerializeField] private Image back; [SerializeField] public bool availableInEditMode { get { return available; } private set { available = value; } } private bool available = true; public void Init(BuildingType techType) { icon.sprite = Services.TechDataLibrary.GetIcon(techType); TechBuilding tech = TechBuilding.GetBuildingFromType(techType); nameText.text = tech.GetName().ToLower(); description.text = tech.GetDescription().ToLower(); back.color = Services.GameManager.NeutralColor; } public void TurnOnTech() { availableInEditMode = true; back.color = new Color(108f/255f, 174f/255f, 117f/255f); icon.color = new Color(108f / 255f, 174f / 255f, 117f / 255f); } public void ToggleTechAvailability() { if (Services.GameManager.mode != TitleSceneScript.GameMode.Edit || Services.GameManager.mode != TitleSceneScript.GameMode.DungeonEdit) return; availableInEditMode = !availableInEditMode; if (availableInEditMode) { back.color = new Color(108f / 255f, 174f / 255f, 117f / 255f); icon.color = new Color(108f / 255f, 174f / 255f, 117f / 255f); } else { back.color = Color.white; icon.color = Color.white; } } }
31.641509
151
0.623137
[ "Unlicense" ]
chrsjwilliams/Omino
Assets/Scripts/UI/TechReference.cs
1,679
C#
using Crt.Model.Dtos.RolePermission; using System; using System.Collections.Generic; using System.Text; using System.Text.Json.Serialization; namespace Crt.Model.Dtos.Permission { public class PermissionDto { [JsonPropertyName("id")] public decimal PermissionId { get; set; } public string Name { get; set; } public string Description { get; set; } public DateTime? EndDate { get; set; } } }
24.777778
49
0.672646
[ "Apache-2.0" ]
AdvSol-Darrel/crt
api/Crt.Model/Dtos/Permission/PermissionDto.cs
448
C#
/* * Copyright (c) 2018 THL A29 Limited, a Tencent company. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ namespace TencentCloud.Vod.V20180717.Models { using Newtonsoft.Json; using System.Collections.Generic; using TencentCloud.Common; public class AiSampleWordInfo : AbstractModel { /// <summary> /// 关键词,长度限制:20 个字符。 /// </summary> [JsonProperty("Keyword")] public string Keyword{ get; set; } /// <summary> /// 关键词标签 /// <li>数组长度限制:20 个标签;</li> /// <li>单个标签长度限制:128 个字符。</li> /// </summary> [JsonProperty("Tags")] public string[] Tags{ get; set; } /// <summary> /// For internal usage only. DO NOT USE IT. /// </summary> public override void ToMap(Dictionary<string, string> map, string prefix) { this.SetParamSimple(map, prefix + "Keyword", this.Keyword); this.SetParamArraySimple(map, prefix + "Tags.", this.Tags); } } }
29.698113
81
0.621347
[ "Apache-2.0" ]
TencentCloud/tencentcloud-sdk-dotnet
TencentCloud/Vod/V20180717/Models/AiSampleWordInfo.cs
1,658
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 Amazon.Runtime; using Amazon.Runtime.Internal; namespace Amazon.Kendra.Model { /// <summary> /// Container for the parameters to the Query operation. /// Searches an active index. Use this API to search your documents using query. The <code>Query</code> /// operation enables to do faceted search and to filter results based on document attributes. /// /// /// <para> /// It also enables you to provide user context that Amazon Kendra uses to enforce document /// access control in the search results. /// </para> /// /// <para> /// Amazon Kendra searches your index for text content and question and answer (FAQ) content. /// By default the response contains three types of results. /// </para> /// <ul> <li> /// <para> /// Relevant passages /// </para> /// </li> <li> /// <para> /// Matching FAQs /// </para> /// </li> <li> /// <para> /// Relevant documents /// </para> /// </li> </ul> /// <para> /// You can specify that the query return only one type of result using the <code>QueryResultTypeConfig</code> /// parameter. /// </para> /// </summary> public partial class QueryRequest : AmazonKendraRequest { private AttributeFilter _attributeFilter; private List<Facet> _facets = new List<Facet>(); private string _indexId; private int? _pageNumber; private int? _pageSize; private QueryResultType _queryResultTypeFilter; private string _queryText; private List<string> _requestedDocumentAttributes = new List<string>(); /// <summary> /// Gets and sets the property AttributeFilter. /// <para> /// Enables filtered searches based on document attributes. You can only provide one attribute /// filter; however, the <code>AndAllFilters</code>, <code>NotFilter</code>, and <code>OrAllFilters</code> /// parameters contain a list of other filters. /// </para> /// /// <para> /// The <code>AttributeFilter</code> parameter enables you to create a set of filtering /// rules that a document must satisfy to be included in the query results. /// </para> /// </summary> public AttributeFilter AttributeFilter { get { return this._attributeFilter; } set { this._attributeFilter = value; } } // Check to see if AttributeFilter property is set internal bool IsSetAttributeFilter() { return this._attributeFilter != null; } /// <summary> /// Gets and sets the property Facets. /// <para> /// An array of documents attributes. Amazon Kendra returns a count for each attribute /// key specified. You can use this information to help narrow the search for your user. /// </para> /// </summary> public List<Facet> Facets { get { return this._facets; } set { this._facets = value; } } // Check to see if Facets property is set internal bool IsSetFacets() { return this._facets != null && this._facets.Count > 0; } /// <summary> /// Gets and sets the property IndexId. /// <para> /// The unique identifier of the index to search. The identifier is returned in the response /// from the operation. /// </para> /// </summary> [AWSProperty(Required=true, Min=36, Max=36)] public string IndexId { get { return this._indexId; } set { this._indexId = value; } } // Check to see if IndexId property is set internal bool IsSetIndexId() { return this._indexId != null; } /// <summary> /// Gets and sets the property PageNumber. /// <para> /// Query results are returned in pages the size of the <code>PageSize</code> parameter. /// By default, Amazon Kendra returns the first page of results. Use this parameter to /// get result pages after the first one. /// </para> /// </summary> public int PageNumber { get { return this._pageNumber.GetValueOrDefault(); } set { this._pageNumber = value; } } // Check to see if PageNumber property is set internal bool IsSetPageNumber() { return this._pageNumber.HasValue; } /// <summary> /// Gets and sets the property PageSize. /// <para> /// Sets the number of results that are returned in each page of results. The default /// page size is 100. /// </para> /// </summary> public int PageSize { get { return this._pageSize.GetValueOrDefault(); } set { this._pageSize = value; } } // Check to see if PageSize property is set internal bool IsSetPageSize() { return this._pageSize.HasValue; } /// <summary> /// Gets and sets the property QueryResultTypeFilter. /// <para> /// Sets the type of query. Only results for the specified query type are returned. /// </para> /// </summary> public QueryResultType QueryResultTypeFilter { get { return this._queryResultTypeFilter; } set { this._queryResultTypeFilter = value; } } // Check to see if QueryResultTypeFilter property is set internal bool IsSetQueryResultTypeFilter() { return this._queryResultTypeFilter != null; } /// <summary> /// Gets and sets the property QueryText. /// <para> /// The text to search for. /// </para> /// </summary> [AWSProperty(Required=true, Min=1, Max=1000)] public string QueryText { get { return this._queryText; } set { this._queryText = value; } } // Check to see if QueryText property is set internal bool IsSetQueryText() { return this._queryText != null; } /// <summary> /// Gets and sets the property RequestedDocumentAttributes. /// <para> /// An array of document attributes to include in the response. No other document attributes /// are included in the response. By default all document attributes are included in the /// response. /// </para> /// </summary> [AWSProperty(Min=1, Max=100)] public List<string> RequestedDocumentAttributes { get { return this._requestedDocumentAttributes; } set { this._requestedDocumentAttributes = value; } } // Check to see if RequestedDocumentAttributes property is set internal bool IsSetRequestedDocumentAttributes() { return this._requestedDocumentAttributes != null && this._requestedDocumentAttributes.Count > 0; } } }
33.885593
114
0.58722
[ "Apache-2.0" ]
UpendoVentures/aws-sdk-net
sdk/src/Services/Kendra/Generated/Model/QueryRequest.cs
7,997
C#
using System; using System.Globalization; using System.Linq; using System.Text.RegularExpressions; using Disruptor.PerfTests.Queue; namespace Disruptor.PerfTests { public class Program { public static void Main(string[] args) { if (!Options.TryParse(args, out var options)) { Options.PrintUsage(); return; } if (!TryLoadPerfTestTypes(options.Target, out var perfTestTypes)) { Console.WriteLine($"Invalid target: [{options.Target}]"); return; } foreach (var perfTestType in perfTestTypes) { RunTestForType(perfTestType, options); } } private static bool TryLoadPerfTestTypes(string target, out Type[] perfTestTypes) { if ("all".Equals(target, StringComparison.OrdinalIgnoreCase)) { perfTestTypes = typeof(Program).Assembly.GetTypes().Where(x => IsValidTestType(x) && !typeof(IQueueTest).IsAssignableFrom(x)).ToArray(); return true; } var type = Resolve(target); if (type != null && IsValidTestType(type)) { perfTestTypes = new[] { type }; return true; } perfTestTypes = null; return false; bool IsValidTestType(Type t) => !t.IsAbstract && (typeof(IThroughputTest).IsAssignableFrom(t) || typeof(ILatencyTest).IsAssignableFrom(t)); Type Resolve(string typeName) => Type.GetType(typeName) ?? typeof(Program).Assembly.ExportedTypes.FirstOrDefault(x => x.Name == typeName); } private static void RunTestForType(Type perfTestType, Options options) { var isThroughputTest = typeof(IThroughputTest).IsAssignableFrom(perfTestType); var isLatencyTest = typeof(ILatencyTest).IsAssignableFrom(perfTestType); //Process.GetCurrentProcess().PriorityClass = ProcessPriorityClass.AboveNormal; if (isThroughputTest) { var session = new ThroughputTestSession(perfTestType); session.Run(options); session.Report(options); } if (isLatencyTest) { var session = new LatencyTestSession(perfTestType); session.Run(options); session.Report(options); } } public class Options { public int? RunCount { get; set; } public string Target { get; set; } public bool ShouldPrintComputerSpecifications { get; set; } public bool ShouldGenerateReport { get; set; } public bool ShouldOpenReport { get; set; } public static bool TryParse(string[] args, out Options options) { options = new Options { ShouldPrintComputerSpecifications = true, ShouldGenerateReport = true, ShouldOpenReport = false, }; if (args.Length == 0 || string.IsNullOrEmpty(args[0])) return false; options.Target = args[0]; foreach (var arg in args.Skip(1)) { switch (arg.ToLowerInvariant()) { case string s when Regex.Match(s, "--report=(true|false)") is var m && m.Success: options.ShouldGenerateReport = bool.Parse(m.Groups[1].Value); break; case string s when Regex.Match(s, "--openreport=(true|false)") is var m && m.Success: options.ShouldOpenReport = bool.Parse(m.Groups[1].Value); break; case string s when Regex.Match(s, "--printspec=(true|false)") is var m && m.Success: options.ShouldPrintComputerSpecifications = bool.Parse(m.Groups[1].Value); break; case string s when Regex.Match(s, "--runs=(\\d+)") is var m && m.Success: options.RunCount = int.Parse(m.Groups[1].Value, CultureInfo.InvariantCulture); break; default: return false; } } return true; } public static void PrintUsage() { Console.WriteLine($"Usage: {AppDomain.CurrentDomain.FriendlyName} target [--report=false] [--openreport=false] [--printspec=false] [--runs=count]"); Console.WriteLine(); Console.WriteLine("Options:"); Console.WriteLine(" target Test type full name or \"all\" for all tests"); Console.WriteLine(" --runs=count Number of runs"); Console.WriteLine(); } } } }
37.291971
164
0.516148
[ "Apache-2.0" ]
ikvm/Disruptor-net
src/Disruptor.PerfTests/Program.cs
5,111
C#
//--------------------------------------------------------------------------------------------------------- // ▽ Submarine Mirage Framework for Unity // Copyright (c) 2020 夢想海の水底より(from Seabed of Reverie) // Released under the MIT License : // https://github.com/FromSeabedOfReverie/SubmarineMirageFrameworkForUnity/blob/master/LICENSE //--------------------------------------------------------------------------------------------------------- namespace SubmarineMirage.Setting { /// <summary>1秒間の画面描画回数(FPS)</summary> public enum SMFrameRate { /// <summary>1秒間に、30回描画(FPS)</summary> _30, /// <summary>1秒間に、60回描画(FPS)</summary> _60 } }
36.277778
107
0.486983
[ "MIT" ]
TatemonSugorokuGame/TatemonSugorokuGame
Assets/SubmarineMirageFramework/Scripts/Setting/Application/SMFrameRate.cs
729
C#
using System.Windows.Controls; namespace PrestoCoverage.Options { /// <summary> /// Interaction logic for OptionsDialogPageControl.xaml /// </summary> public partial class OptionsDialogPageControl : UserControl { //public List<System.Drawing.Color> Colours = new List<System.Drawing.Color>(); public OptionsDialogPageControl() { InitializeComponent(); ColourCovered.Text = PrestoCoverageCore.PrestoConfiguration.Colours.Covered; ColourPartialCovered.Text = PrestoCoverageCore.PrestoConfiguration.Colours.Partial; ColourUncovered.Text = PrestoCoverageCore.PrestoConfiguration.Colours.Uncovered; ClearCoverageOnChangeCheckbox.IsChecked = PrestoCoverageCore.PrestoConfiguration.ClearOnBuild; WatchFolderPath.Text = PrestoCoverageCore.PrestoConfiguration.WatchFolder.Path; WatchFolderFilter.Text = PrestoCoverageCore.PrestoConfiguration.WatchFolder.Filter; if (PrestoCoverageCore.PrestoConfiguration.IsJsonConfigDriven) LockAllControls(); } private void LockAllControls() { ColourCovered.IsEnabled = false; ColourPartialCovered.IsEnabled = false; ColourUncovered.IsEnabled = false; ClearCoverageOnChangeCheckbox.IsEnabled = false; WatchFolderFilter.IsEnabled = false; WatchFolderPath.IsEnabled = false; HeaderLabel.Content = "Configuration driven by presto.config.json"; HeaderLabel.Foreground = new System.Windows.Media.SolidColorBrush(System.Windows.Media.Color.FromRgb(0xff, 0x00, 0x00)); } private void TextBox_Covered_TextChanged(object sender, TextChangedEventArgs e) { try { var c = (System.Windows.Media.Color)System.Windows.Media.ColorConverter.ConvertFromString(ColourCovered.Text); PrestoCoverageCore.Colour_Covered = new System.Windows.Media.SolidColorBrush(c); ColourCoveredFill.Fill = PrestoCoverageCore.Colour_Covered; GeneralSettings.Default.Glyph_CoveredColour = c.ToString(); GeneralSettings.Default.Save(); PrestoCoverageCore.reloadTaggers(); } catch (System.Exception) { } } private void TextBox_Partial_TextChanged(object sender, TextChangedEventArgs e) { try { var c = (System.Windows.Media.Color)System.Windows.Media.ColorConverter.ConvertFromString(ColourPartialCovered.Text); PrestoCoverageCore.Colour_CoveredPartial = new System.Windows.Media.SolidColorBrush(c); ColourPartialFill.Fill = PrestoCoverageCore.Colour_CoveredPartial; GeneralSettings.Default.Glyph_PartialCoverColour = c.ToString(); GeneralSettings.Default.Save(); PrestoCoverageCore.reloadTaggers(); } catch (System.Exception) { } } private void TextBox_Uncovered_TextChanged(object sender, TextChangedEventArgs e) { try { var c = (System.Windows.Media.Color)System.Windows.Media.ColorConverter.ConvertFromString(ColourUncovered.Text); PrestoCoverageCore.Colour_Uncovered = new System.Windows.Media.SolidColorBrush(c); ColourUncoveredFill.Fill = PrestoCoverageCore.Colour_Uncovered; GeneralSettings.Default.Glyph_UncoveredColour = c.ToString(); GeneralSettings.Default.Save(); PrestoCoverageCore.reloadTaggers(); } catch (System.Exception) { } } private void CheckBox_ClearCoverageOnChange_Checked(object sender, System.Windows.RoutedEventArgs e) { GeneralSettings.Default.ClearCoverageOnChange = ClearCoverageOnChangeCheckbox.IsChecked.Value; GeneralSettings.Default.Save(); PrestoCoverageCore.ClearCoverageOnChange = ClearCoverageOnChangeCheckbox.IsChecked.Value; } private void WatchFolderPath_TextChanged(object sender, TextChangedEventArgs e) { GeneralSettings.Default.WatchFolderPath = WatchFolderPath.Text; GeneralSettings.Default.Save(); } private void WatchFolderFilter_TextChanged(object sender, TextChangedEventArgs e) { GeneralSettings.Default.WatchFolderFilter = WatchFolderFilter.Text; GeneralSettings.Default.Save(); } } }
37.677419
133
0.653682
[ "Apache-2.0" ]
bobted/PrestoCoverage
PrestoCoverage/PrestoCoverage/Options/OptionsDialogPageControl.xaml.cs
4,674
C#
using Microsoft.Extensions.Options; using Microsoft.WindowsAzure.Storage; using Microsoft.WindowsAzure.Storage.Table; using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations.Schema; using System.Linq; using System.Threading.Tasks; namespace LuckyDrawBot.Infrastructure.Database { public interface IDataTable<TSettings, TEntity> where TSettings : DataTableSettings, new() where TEntity : ITableEntity, new() { Task InsertOrReplace(TEntity entity); Task<TEntity> Retrieve(TEntity entity); Task<TEntity> Retrieve(string partitionKey, string rowKey); Task<bool> Delete(TEntity entity); Task<bool> Delete(string partitionKey, string rowKey); Task<List<TEntity>> Query(string filterString = null, int? takeCount = null, IList<string> selectColumns = null); Task Query(Action<List<TEntity>> segmentAction, string filterString = null, int? takeCount = null, IList<string> selectColumns = null); } public class DataTable<TSettings, TEntity> : IDataTable<TSettings, TEntity> where TSettings : DataTableSettings, new() where TEntity : ITableEntity, new() { private readonly CloudTable _table; public DataTable(IOptions<TSettings> options) { var settings = options.Value; var storageAccount = CloudStorageAccount.Parse(settings.ConnectionString); var client = storageAccount.CreateCloudTableClient(); _table = client.GetTableReference(GetTableName()); } private string GetTableName() { var type = typeof(TEntity); var attributes = type.GetCustomAttributes(typeof(TableAttribute), false); if (attributes.Length > 0) { var tableAttribute = (TableAttribute)attributes[0]; return tableAttribute.Name; } var typeName = type.Name; var tableName = typeName.EndsWith("Entity") ? typeName.Substring(0, typeName.Length - "Entity".Length) : typeName; tableName = tableName.ToLowerInvariant(); return tableName; } public async Task InsertOrReplace(TEntity entity) { TableOperation operation = TableOperation.InsertOrReplace(entity); await _table.ExecuteAsync(operation); } public Task<TEntity> Retrieve(TEntity entity) { return Retrieve(entity.PartitionKey, entity.RowKey); } public async Task<TEntity> Retrieve(string partitionKey, string rowKey) { TableOperation operation = TableOperation.Retrieve<TEntity>(partitionKey, rowKey); var result = await _table.ExecuteAsync(operation); if (result.Result != null) { return (TEntity)result.Result; } return default(TEntity); } public Task<bool> Delete(TEntity entity) { return Delete(entity.PartitionKey, entity.RowKey); } public async Task<bool> Delete(string partitionKey, string rowKey) { TableOperation operation = TableOperation.Retrieve<TEntity>(partitionKey, rowKey); var result = await _table.ExecuteAsync(operation); if (result.Result != null) { operation = TableOperation.Delete((TEntity)result.Result); await _table.ExecuteAsync(operation); return true; } return false; } public async Task<List<TEntity>> Query(string filterString = null, int? takeCount = null, IList<string> selectColumns = null) { var result = new List<TEntity>(); await Query( (segment) => result.AddRange(segment), filterString, takeCount, selectColumns); return result; } public async Task Query(Action<List<TEntity>> segmentAction, string filterString = null, int? takeCount = null, IList<string> selectColumns = null) { var query = new TableQuery<TEntity>(); if (!string.IsNullOrEmpty(filterString)) { query = query.Where(filterString); } if (takeCount.HasValue) { query = query.Take(takeCount.Value); } if (selectColumns != null) { query = query.Select(selectColumns); } List<TEntity> result; TableContinuationToken token = null; do { var seg = await _table.ExecuteQuerySegmentedAsync<TEntity>(query, token); token = seg.ContinuationToken; result = seg.ToList(); segmentAction(result); } while (token != null && (query.TakeCount == null || result.Count < query.TakeCount.Value)); } } }
37.765152
158
0.602407
[ "MIT" ]
Office365DevOps/lucky-draw-bot
src/LuckyDrawBot/Infrastructure/Database/DataTable.cs
4,985
C#
namespace Microsoft.Azure.PowerShell.Cmdlets.DesktopVirtualization.Models.Api20210201Preview { using static Microsoft.Azure.PowerShell.Cmdlets.DesktopVirtualization.Runtime.Extensions; /// <summary>Desktop properties that can be patched.</summary> public partial class DesktopPatchProperties : Microsoft.Azure.PowerShell.Cmdlets.DesktopVirtualization.Models.Api20210201Preview.IDesktopPatchProperties, Microsoft.Azure.PowerShell.Cmdlets.DesktopVirtualization.Models.Api20210201Preview.IDesktopPatchPropertiesInternal { /// <summary>Backing field for <see cref="Description" /> property.</summary> private string _description; /// <summary>Description of Desktop.</summary> [Microsoft.Azure.PowerShell.Cmdlets.DesktopVirtualization.Origin(Microsoft.Azure.PowerShell.Cmdlets.DesktopVirtualization.PropertyOrigin.Owned)] public string Description { get => this._description; set => this._description = value; } /// <summary>Backing field for <see cref="FriendlyName" /> property.</summary> private string _friendlyName; /// <summary>Friendly name of Desktop.</summary> [Microsoft.Azure.PowerShell.Cmdlets.DesktopVirtualization.Origin(Microsoft.Azure.PowerShell.Cmdlets.DesktopVirtualization.PropertyOrigin.Owned)] public string FriendlyName { get => this._friendlyName; set => this._friendlyName = value; } /// <summary>Creates an new <see cref="DesktopPatchProperties" /> instance.</summary> public DesktopPatchProperties() { } } /// Desktop properties that can be patched. public partial interface IDesktopPatchProperties : Microsoft.Azure.PowerShell.Cmdlets.DesktopVirtualization.Runtime.IJsonSerializable { /// <summary>Description of Desktop.</summary> [Microsoft.Azure.PowerShell.Cmdlets.DesktopVirtualization.Runtime.Info( Required = false, ReadOnly = false, Description = @"Description of Desktop.", SerializedName = @"description", PossibleTypes = new [] { typeof(string) })] string Description { get; set; } /// <summary>Friendly name of Desktop.</summary> [Microsoft.Azure.PowerShell.Cmdlets.DesktopVirtualization.Runtime.Info( Required = false, ReadOnly = false, Description = @"Friendly name of Desktop.", SerializedName = @"friendlyName", PossibleTypes = new [] { typeof(string) })] string FriendlyName { get; set; } } /// Desktop properties that can be patched. internal partial interface IDesktopPatchPropertiesInternal { /// <summary>Description of Desktop.</summary> string Description { get; set; } /// <summary>Friendly name of Desktop.</summary> string FriendlyName { get; set; } } }
46.365079
153
0.682985
[ "MIT" ]
AndriiKalinichenko/azure-powershell
src/DesktopVirtualization/generated/api/Models/Api20210201Preview/DesktopPatchProperties.cs
2,859
C#
using System; using UnityEngine; public class CustomerBehaviour : MonoBehaviour { private TextMesh text; public GameObject renderedCustomer; public ProgressBarBehaviour attachedBar; public Salad order; public Salad submittedFood = null; public GameObject powerUpPrefab; [NonSerialized] public PlayerBehaviour submittingPlayer = null; public bool isActive = false; public bool canAcceptFood = false; public bool player1Mad = false; public bool player2Mad = false; private Vector3 position; void Start() { renderedCustomer.SetActive(false); text = GetComponentInChildren<TextMesh>(); position = transform.position; } void Update() { transform.position = position; //customer has order? display it if (order != null) text.text = order.ToString().Replace(' ', '\n'); else text.text = ""; if (submittedFood != null) { //customer has food placed on them, evaluate the players' efforts if (order.CompareTo(submittedFood)) DoLeave(true); else GetAngry(); submittingPlayer = null; submittedFood = null; } //time's up! customer is gone! if (attachedBar.isDone) DoLeave(false); } public void StartCustomer() { canAcceptFood = true; renderedCustomer.SetActive(true); order = new Salad(); var ingredients = RandomUtil.CreateRandomCombination(); foreach (var ingredient in ingredients) { order.AddIngredient(ingredient); } if (attachedBar != null) attachedBar.StartProgressBar(GameConstants.WaitTime * GameConstants.RecipeComplexityScale * order.GetIngredientCount()); } public void DoLeave(bool satisfied) { canAcceptFood = false; renderedCustomer.SetActive(false); var controller = FindObjectOfType<MainSceneController>(); //is order fulfilled correctly? if (satisfied) { //get player who made customer happy switch (submittingPlayer.playerNumber) { //add score based on complexity of order case 1: controller.player1Score += GameConstants.ScorePerIngredient * order.GetIngredientCount(); break; case 2: controller.player2Score += GameConstants.ScorePerIngredient * order.GetIngredientCount(); break; } //conditions are correct for spawning powerup, so do so //50% of time is TimeUp, 25% of time is PointsUp, 25% of time is SpeedUp if (attachedBar.percentComplete <= 0.3F) { if (RandomUtil.GenerateFloat() > 0.5F) { //Do spawn time up DoSpawnPowerUp(PowerUpType.TimeUp); } else { if (RandomUtil.GenerateFloat() > 0.5F) { //Do spawn score up DoSpawnPowerUp(PowerUpType.PointsUp); } else { //Do spawn speed up DoSpawnPowerUp(PowerUpType.SpeedUp); } } } } else { //customer is angry. Find out which player(s) customer is angry at and deduct score accordingly if (player1Mad && player2Mad) { controller.player1Score -= GameConstants.ScorePerIngredient * order.GetIngredientCount() * 2; controller.player2Score -= GameConstants.ScorePerIngredient * order.GetIngredientCount() * 2; } else if (player1Mad) controller.player1Score -= GameConstants.ScorePerIngredient * order.GetIngredientCount() * 2; else if (player2Mad) controller.player2Score -= GameConstants.ScorePerIngredient * order.GetIngredientCount() * 2; //customer's order was not fulfilled, deduct points from both players accordingly else { controller.player1Score -= GameConstants.ScorePerIngredient * order.GetIngredientCount(); controller.player2Score -= GameConstants.ScorePerIngredient * order.GetIngredientCount(); } } order = null; isActive = false; player1Mad = false; player2Mad = false; attachedBar.ResetProgressBar(); } public void GetAngry() { //increase rate at which customer leaves attachedBar.DoAngryCountdownStep(); //get player to get angry at switch (submittingPlayer.playerNumber) { case 1: player1Mad = true; break; case 2: player2Mad = true; break; } } //create new powerup of dictated type private void DoSpawnPowerUp(PowerUpType type) { var newPowerUp = Instantiate(powerUpPrefab); PowerUpBehaviour powerUp = newPowerUp.GetComponent<PowerUpBehaviour>(); powerUp.type = type; powerUp.transform.position = RandomUtil.GenerateNonOccupiedPosition(); powerUp.owningPlayer = submittingPlayer.playerNumber; } //used by restart game to clear all active customers from previous game and start over public void ForceResetCustomer() { canAcceptFood = false; order = null; isActive = false; renderedCustomer.SetActive(false); player1Mad = false; player2Mad = false; attachedBar.ResetProgressBar(); } }
33.581395
153
0.578428
[ "MIT" ]
seanboyy/Salad-Maker
Assets/AssetLibrary/Scripts/CustomerBehaviour.cs
5,778
C#
using System; using Microsoft.VisualStudio.TestTools.UnitTesting; namespace UnitTests { using PandaSocialNetworkLibrary; [TestClass] public class UnitTests { [TestMethod, ExpectedException(typeof(ArgumentException))] public void EmailWithoutAtSign() { Panda panda = new Panda("panda", "pandaabv.bg", GenderType.Male); bool validEmail = true; if () { } } } }
21.304348
77
0.569388
[ "MIT" ]
ddyakov/PandaSocialNetwork
PandaSocialNetwork/UnitTests/UnitTests.cs
492
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.Buffers; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Threading; using System.Threading.Tasks; namespace System.IO { public abstract class Stream : MarshalByRefObject, IDisposable, IAsyncDisposable { public static readonly Stream Null = new NullStream(); /// <summary>To serialize async operations on streams that don't implement their own.</summary> private protected SemaphoreSlim? _asyncActiveSemaphore; [MemberNotNull(nameof(_asyncActiveSemaphore))] private protected SemaphoreSlim EnsureAsyncActiveSemaphoreInitialized() => // Lazily-initialize _asyncActiveSemaphore. As we're never accessing the SemaphoreSlim's // WaitHandle, we don't need to worry about Disposing it in the case of a race condition. #pragma warning disable CS8774 // We lack a NullIffNull annotation for Volatile.Read Volatile.Read(ref _asyncActiveSemaphore) ?? #pragma warning restore CS8774 Interlocked.CompareExchange(ref _asyncActiveSemaphore, new SemaphoreSlim(1, 1), null) ?? _asyncActiveSemaphore; public abstract bool CanRead { get; } public abstract bool CanWrite { get; } public abstract bool CanSeek { get; } public virtual bool CanTimeout => false; public abstract long Length { get; } public abstract long Position { get; set; } public virtual int ReadTimeout { get => throw new InvalidOperationException(SR.InvalidOperation_TimeoutsNotSupported); set => throw new InvalidOperationException(SR.InvalidOperation_TimeoutsNotSupported); } public virtual int WriteTimeout { get => throw new InvalidOperationException(SR.InvalidOperation_TimeoutsNotSupported); set => throw new InvalidOperationException(SR.InvalidOperation_TimeoutsNotSupported); } public void CopyTo(Stream destination) => CopyTo(destination, GetCopyBufferSize()); public virtual void CopyTo(Stream destination, int bufferSize) { ValidateCopyToArguments(destination, bufferSize); if (!CanRead) { if (CanWrite) { ThrowHelper.ThrowNotSupportedException_UnreadableStream(); } ThrowHelper.ThrowObjectDisposedException_StreamClosed(GetType().Name); } byte[] buffer = ArrayPool<byte>.Shared.Rent(bufferSize); try { int bytesRead; while ((bytesRead = Read(buffer, 0, buffer.Length)) != 0) { destination.Write(buffer, 0, bytesRead); } } finally { ArrayPool<byte>.Shared.Return(buffer); } } public Task CopyToAsync(Stream destination) => CopyToAsync(destination, GetCopyBufferSize()); public Task CopyToAsync(Stream destination, int bufferSize) => CopyToAsync(destination, bufferSize, CancellationToken.None); public Task CopyToAsync(Stream destination, CancellationToken cancellationToken) => CopyToAsync(destination, GetCopyBufferSize(), cancellationToken); public virtual Task CopyToAsync(Stream destination, int bufferSize, CancellationToken cancellationToken) { ValidateCopyToArguments(destination, bufferSize); if (!CanRead) { if (CanWrite) { ThrowHelper.ThrowNotSupportedException_UnreadableStream(); } ThrowHelper.ThrowObjectDisposedException_StreamClosed(GetType().Name); } return Core(this, destination, bufferSize, cancellationToken); static async Task Core(Stream source, Stream destination, int bufferSize, CancellationToken cancellationToken) { byte[] buffer = ArrayPool<byte>.Shared.Rent(bufferSize); try { int bytesRead; while ((bytesRead = await source.ReadAsync(new Memory<byte>(buffer), cancellationToken).ConfigureAwait(false)) != 0) { await destination.WriteAsync(new ReadOnlyMemory<byte>(buffer, 0, bytesRead), cancellationToken).ConfigureAwait(false); } } finally { ArrayPool<byte>.Shared.Return(buffer); } } } private int GetCopyBufferSize() { // This value was originally picked to be the largest multiple of 4096 that is still smaller than the large object heap threshold (85K). // The CopyTo{Async} buffer is short-lived and is likely to be collected at Gen0, and it offers a significant improvement in Copy // performance. Since then, the base implementations of CopyTo{Async} have been updated to use ArrayPool, which will end up rounding // this size up to the next power of two (131,072), which will by default be on the large object heap. However, most of the time // the buffer should be pooled, the LOH threshold is now configurable and thus may be different than 85K, and there are measurable // benefits to using the larger buffer size. So, for now, this value remains. const int DefaultCopyBufferSize = 81920; int bufferSize = DefaultCopyBufferSize; if (CanSeek) { long length = Length; long position = Position; if (length <= position) // Handles negative overflows { // There are no bytes left in the stream to copy. // However, because CopyTo{Async} is virtual, we need to // ensure that any override is still invoked to provide its // own validation, so we use the smallest legal buffer size here. bufferSize = 1; } else { long remaining = length - position; if (remaining > 0) { // In the case of a positive overflow, stick to the default size bufferSize = (int)Math.Min(bufferSize, remaining); } } } return bufferSize; } public void Dispose() => Close(); public virtual void Close() { // When initially designed, Stream required that all cleanup logic went into Close(), // but this was thought up before IDisposable was added and never revisited. All subclasses // should put their cleanup now in Dispose(bool). Dispose(true); GC.SuppressFinalize(this); } protected virtual void Dispose(bool disposing) { // Note: Never change this to call other virtual methods on Stream // like Write, since the state on subclasses has already been // torn down. This is the last code to run on cleanup for a stream. } public virtual ValueTask DisposeAsync() { try { Dispose(); return default; } catch (Exception exc) { return ValueTask.FromException(exc); } } public abstract void Flush(); public Task FlushAsync() => FlushAsync(CancellationToken.None); public virtual Task FlushAsync(CancellationToken cancellationToken) => Task.Factory.StartNew( static state => ((Stream)state!).Flush(), this, cancellationToken, TaskCreationOptions.DenyChildAttach, TaskScheduler.Default); [Obsolete("CreateWaitHandle has been deprecated. Use the ManualResetEvent(false) constructor instead.")] protected virtual WaitHandle CreateWaitHandle() => new ManualResetEvent(false); public virtual IAsyncResult BeginRead(byte[] buffer, int offset, int count, AsyncCallback? callback, object? state) => BeginReadInternal(buffer, offset, count, callback, state, serializeAsynchronously: false, apm: true); internal Task<int> BeginReadInternal( byte[] buffer, int offset, int count, AsyncCallback? callback, object? state, bool serializeAsynchronously, bool apm) { ValidateBufferArguments(buffer, offset, count); if (!CanRead) { ThrowHelper.ThrowNotSupportedException_UnreadableStream(); } // To avoid a race with a stream's position pointer & generating race conditions // with internal buffer indexes in our own streams that // don't natively support async IO operations when there are multiple // async requests outstanding, we will block the application's main // thread if it does a second IO request until the first one completes. SemaphoreSlim semaphore = EnsureAsyncActiveSemaphoreInitialized(); Task? semaphoreTask = null; if (serializeAsynchronously) { semaphoreTask = semaphore.WaitAsync(); } else { #pragma warning disable CA1416 // Validate platform compatibility, issue: https://github.com/dotnet/runtime/issues/44543 semaphore.Wait(); #pragma warning restore CA1416 } // Create the task to asynchronously do a Read. This task serves both // as the asynchronous work item and as the IAsyncResult returned to the user. var task = new ReadWriteTask(true /*isRead*/, apm, delegate { // The ReadWriteTask stores all of the parameters to pass to Read. // As we're currently inside of it, we can get the current task // and grab the parameters from it. var thisTask = Task.InternalCurrent as ReadWriteTask; Debug.Assert(thisTask != null && thisTask._stream != null, "Inside ReadWriteTask, InternalCurrent should be the ReadWriteTask, and stream should be set"); try { // Do the Read and return the number of bytes read return thisTask._stream.Read(thisTask._buffer!, thisTask._offset, thisTask._count); } finally { // If this implementation is part of Begin/EndXx, then the EndXx method will handle // finishing the async operation. However, if this is part of XxAsync, then there won't // be an end method, and this task is responsible for cleaning up. if (!thisTask._apm) { thisTask._stream.FinishTrackingAsyncOperation(thisTask); } thisTask.ClearBeginState(); // just to help alleviate some memory pressure } }, state, this, buffer, offset, count, callback); // Schedule it if (semaphoreTask != null) { RunReadWriteTaskWhenReady(semaphoreTask, task); } else { RunReadWriteTask(task); } return task; // return it } public virtual int EndRead(IAsyncResult asyncResult) { if (asyncResult is null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.asyncResult); } ReadWriteTask? readTask = asyncResult as ReadWriteTask; if (readTask is null || !readTask._isRead) { ThrowHelper.ThrowArgumentException(ExceptionResource.InvalidOperation_WrongAsyncResultOrEndCalledMultiple); } else if (readTask._endCalled) { ThrowHelper.ThrowInvalidOperationException(ExceptionResource.InvalidOperation_WrongAsyncResultOrEndCalledMultiple); } try { return readTask.GetAwaiter().GetResult(); // block until completion, then get result / propagate any exception } finally { FinishTrackingAsyncOperation(readTask); } } public Task<int> ReadAsync(byte[] buffer, int offset, int count) => ReadAsync(buffer, offset, count, CancellationToken.None); public virtual Task<int> ReadAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken) => cancellationToken.IsCancellationRequested ? Task.FromCanceled<int>(cancellationToken) : BeginEndReadAsync(buffer, offset, count); public virtual ValueTask<int> ReadAsync(Memory<byte> buffer, CancellationToken cancellationToken = default) { if (MemoryMarshal.TryGetArray(buffer, out ArraySegment<byte> array)) { return new ValueTask<int>(ReadAsync(array.Array!, array.Offset, array.Count, cancellationToken)); } byte[] sharedBuffer = ArrayPool<byte>.Shared.Rent(buffer.Length); return FinishReadAsync(ReadAsync(sharedBuffer, 0, buffer.Length, cancellationToken), sharedBuffer, buffer); static async ValueTask<int> FinishReadAsync(Task<int> readTask, byte[] localBuffer, Memory<byte> localDestination) { try { int result = await readTask.ConfigureAwait(false); new ReadOnlySpan<byte>(localBuffer, 0, result).CopyTo(localDestination.Span); return result; } finally { ArrayPool<byte>.Shared.Return(localBuffer); } } } #if CORERT // TODO: https://github.com/dotnet/corert/issues/3251 private bool HasOverriddenBeginEndRead() => true; private bool HasOverriddenBeginEndWrite() => true; #else [MethodImpl(MethodImplOptions.InternalCall)] private extern bool HasOverriddenBeginEndRead(); [MethodImpl(MethodImplOptions.InternalCall)] private extern bool HasOverriddenBeginEndWrite(); #endif private Task<int> BeginEndReadAsync(byte[] buffer, int offset, int count) { if (!HasOverriddenBeginEndRead()) { // If the Stream does not override Begin/EndRead, then we can take an optimized path // that skips an extra layer of tasks / IAsyncResults. return BeginReadInternal(buffer, offset, count, null, null, serializeAsynchronously: true, apm: false); } // Otherwise, we need to wrap calls to Begin/EndWrite to ensure we use the derived type's functionality. return TaskFactory<int>.FromAsyncTrim( this, new ReadWriteParameters { Buffer = buffer, Offset = offset, Count = count }, (stream, args, callback, state) => stream.BeginRead(args.Buffer, args.Offset, args.Count, callback, state), // cached by compiler (stream, asyncResult) => stream.EndRead(asyncResult)); // cached by compiler } private struct ReadWriteParameters // struct for arguments to Read and Write calls { internal byte[] Buffer; internal int Offset; internal int Count; } public virtual IAsyncResult BeginWrite(byte[] buffer, int offset, int count, AsyncCallback? callback, object? state) => BeginWriteInternal(buffer, offset, count, callback, state, serializeAsynchronously: false, apm: true); internal Task BeginWriteInternal( byte[] buffer, int offset, int count, AsyncCallback? callback, object? state, bool serializeAsynchronously, bool apm) { ValidateBufferArguments(buffer, offset, count); if (!CanWrite) { ThrowHelper.ThrowNotSupportedException_UnwritableStream(); } // To avoid a race condition with a stream's position pointer & generating conditions // with internal buffer indexes in our own streams that // don't natively support async IO operations when there are multiple // async requests outstanding, we will block the application's main // thread if it does a second IO request until the first one completes. SemaphoreSlim semaphore = EnsureAsyncActiveSemaphoreInitialized(); Task? semaphoreTask = null; if (serializeAsynchronously) { semaphoreTask = semaphore.WaitAsync(); // kick off the asynchronous wait, but don't block } else { #pragma warning disable CA1416 // Validate platform compatibility, issue: https://github.com/dotnet/runtime/issues/44543 semaphore.Wait(); // synchronously wait here #pragma warning restore CA1416 } // Create the task to asynchronously do a Write. This task serves both // as the asynchronous work item and as the IAsyncResult returned to the user. var task = new ReadWriteTask(false /*isRead*/, apm, delegate { // The ReadWriteTask stores all of the parameters to pass to Write. // As we're currently inside of it, we can get the current task // and grab the parameters from it. var thisTask = Task.InternalCurrent as ReadWriteTask; Debug.Assert(thisTask != null && thisTask._stream != null, "Inside ReadWriteTask, InternalCurrent should be the ReadWriteTask, and stream should be set"); try { // Do the Write thisTask._stream.Write(thisTask._buffer!, thisTask._offset, thisTask._count); return 0; // not used, but signature requires a value be returned } finally { // If this implementation is part of Begin/EndXx, then the EndXx method will handle // finishing the async operation. However, if this is part of XxAsync, then there won't // be an end method, and this task is responsible for cleaning up. if (!thisTask._apm) { thisTask._stream.FinishTrackingAsyncOperation(thisTask); } thisTask.ClearBeginState(); // just to help alleviate some memory pressure } }, state, this, buffer, offset, count, callback); // Schedule it if (semaphoreTask != null) { RunReadWriteTaskWhenReady(semaphoreTask, task); } else { RunReadWriteTask(task); } return task; // return it } private static void RunReadWriteTaskWhenReady(Task asyncWaiter, ReadWriteTask readWriteTask) { Debug.Assert(readWriteTask != null); Debug.Assert(asyncWaiter != null); // If the wait has already completed, run the task. if (asyncWaiter.IsCompleted) { Debug.Assert(asyncWaiter.IsCompletedSuccessfully, "The semaphore wait should always complete successfully."); RunReadWriteTask(readWriteTask); } else // Otherwise, wait for our turn, and then run the task. { asyncWaiter.ContinueWith(static (t, state) => { Debug.Assert(t.IsCompletedSuccessfully, "The semaphore wait should always complete successfully."); var rwt = (ReadWriteTask)state!; Debug.Assert(rwt._stream != null, "Validates that this code isn't run a second time."); RunReadWriteTask(rwt); // RunReadWriteTask(readWriteTask); }, readWriteTask, default, TaskContinuationOptions.ExecuteSynchronously, TaskScheduler.Default); } } private static void RunReadWriteTask(ReadWriteTask readWriteTask) { Debug.Assert(readWriteTask != null); // Schedule the task. ScheduleAndStart must happen after the write to _activeReadWriteTask to avoid a race. // Internally, we're able to directly call ScheduleAndStart rather than Start, avoiding // two interlocked operations. However, if ReadWriteTask is ever changed to use // a cancellation token, this should be changed to use Start. readWriteTask.m_taskScheduler = TaskScheduler.Default; readWriteTask.ScheduleAndStart(needsProtection: false); } private void FinishTrackingAsyncOperation(ReadWriteTask task) { Debug.Assert(_asyncActiveSemaphore != null, "Must have been initialized in order to get here."); task._endCalled = true; _asyncActiveSemaphore.Release(); } public virtual void EndWrite(IAsyncResult asyncResult) { if (asyncResult is null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.asyncResult); } ReadWriteTask? writeTask = asyncResult as ReadWriteTask; if (writeTask is null || writeTask._isRead) { ThrowHelper.ThrowArgumentException(ExceptionResource.InvalidOperation_WrongAsyncResultOrEndCalledMultiple); } else if (writeTask._endCalled) { ThrowHelper.ThrowInvalidOperationException(ExceptionResource.InvalidOperation_WrongAsyncResultOrEndCalledMultiple); } try { writeTask.GetAwaiter().GetResult(); // block until completion, then propagate any exceptions Debug.Assert(writeTask.Status == TaskStatus.RanToCompletion); } finally { FinishTrackingAsyncOperation(writeTask); } } // Task used by BeginRead / BeginWrite to do Read / Write asynchronously. // A single instance of this task serves four purposes: // 1. The work item scheduled to run the Read / Write operation // 2. The state holding the arguments to be passed to Read / Write // 3. The IAsyncResult returned from BeginRead / BeginWrite // 4. The completion action that runs to invoke the user-provided callback. // This last item is a bit tricky. Before the AsyncCallback is invoked, the // IAsyncResult must have completed, so we can't just invoke the handler // from within the task, since it is the IAsyncResult, and thus it's not // yet completed. Instead, we use AddCompletionAction to install this // task as its own completion handler. That saves the need to allocate // a separate completion handler, it guarantees that the task will // have completed by the time the handler is invoked, and it allows // the handler to be invoked synchronously upon the completion of the // task. This all enables BeginRead / BeginWrite to be implemented // with a single allocation. private sealed class ReadWriteTask : Task<int>, ITaskCompletionAction { internal readonly bool _isRead; internal readonly bool _apm; // true if this is from Begin/EndXx; false if it's from XxAsync internal bool _endCalled; internal Stream? _stream; internal byte[]? _buffer; internal readonly int _offset; internal readonly int _count; private AsyncCallback? _callback; private ExecutionContext? _context; internal void ClearBeginState() // Used to allow the args to Read/Write to be made available for GC { _stream = null; _buffer = null; } public ReadWriteTask( bool isRead, bool apm, Func<object?, int> function, object? state, Stream stream, byte[] buffer, int offset, int count, AsyncCallback? callback) : base(function, state, CancellationToken.None, TaskCreationOptions.DenyChildAttach) { Debug.Assert(function != null); Debug.Assert(stream != null); // Store the arguments _isRead = isRead; _apm = apm; _stream = stream; _buffer = buffer; _offset = offset; _count = count; // If a callback was provided, we need to: // - Store the user-provided handler // - Capture an ExecutionContext under which to invoke the handler // - Add this task as its own completion handler so that the Invoke method // will run the callback when this task completes. if (callback != null) { _callback = callback; _context = ExecutionContext.Capture(); base.AddCompletionAction(this); } } private static void InvokeAsyncCallback(object? completedTask) { Debug.Assert(completedTask is ReadWriteTask); var rwc = (ReadWriteTask)completedTask; AsyncCallback? callback = rwc._callback; Debug.Assert(callback != null); rwc._callback = null; callback(rwc); } private static ContextCallback? s_invokeAsyncCallback; void ITaskCompletionAction.Invoke(Task completingTask) { // Get the ExecutionContext. If there is none, just run the callback // directly, passing in the completed task as the IAsyncResult. // If there is one, process it with ExecutionContext.Run. ExecutionContext? context = _context; if (context is null) { AsyncCallback? callback = _callback; Debug.Assert(callback != null); _callback = null; callback(completingTask); } else { _context = null; ContextCallback? invokeAsyncCallback = s_invokeAsyncCallback ??= InvokeAsyncCallback; ExecutionContext.RunInternal(context, invokeAsyncCallback, this); } } bool ITaskCompletionAction.InvokeMayRunArbitraryCode => true; } public Task WriteAsync(byte[] buffer, int offset, int count) => WriteAsync(buffer, offset, count, CancellationToken.None); public virtual Task WriteAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken) => // If cancellation was requested, bail early with an already completed task. // Otherwise, return a task that represents the Begin/End methods. cancellationToken.IsCancellationRequested ? Task.FromCanceled(cancellationToken) : BeginEndWriteAsync(buffer, offset, count); public virtual ValueTask WriteAsync(ReadOnlyMemory<byte> buffer, CancellationToken cancellationToken = default) { if (MemoryMarshal.TryGetArray(buffer, out ArraySegment<byte> array)) { return new ValueTask(WriteAsync(array.Array!, array.Offset, array.Count, cancellationToken)); } byte[] sharedBuffer = ArrayPool<byte>.Shared.Rent(buffer.Length); buffer.Span.CopyTo(sharedBuffer); return new ValueTask(FinishWriteAsync(WriteAsync(sharedBuffer, 0, buffer.Length, cancellationToken), sharedBuffer)); } private static async Task FinishWriteAsync(Task writeTask, byte[] localBuffer) { try { await writeTask.ConfigureAwait(false); } finally { ArrayPool<byte>.Shared.Return(localBuffer); } } private Task BeginEndWriteAsync(byte[] buffer, int offset, int count) { if (!HasOverriddenBeginEndWrite()) { // If the Stream does not override Begin/EndWrite, then we can take an optimized path // that skips an extra layer of tasks / IAsyncResults. return BeginWriteInternal(buffer, offset, count, null, null, serializeAsynchronously: true, apm: false); } // Otherwise, we need to wrap calls to Begin/EndWrite to ensure we use the derived type's functionality. return TaskFactory<VoidTaskResult>.FromAsyncTrim( this, new ReadWriteParameters { Buffer = buffer, Offset = offset, Count = count }, (stream, args, callback, state) => stream.BeginWrite(args.Buffer, args.Offset, args.Count, callback, state), // cached by compiler (stream, asyncResult) => // cached by compiler { stream.EndWrite(asyncResult); return default; }); } public abstract long Seek(long offset, SeekOrigin origin); public abstract void SetLength(long value); public abstract int Read(byte[] buffer, int offset, int count); public virtual int Read(Span<byte> buffer) { byte[] sharedBuffer = ArrayPool<byte>.Shared.Rent(buffer.Length); try { int numRead = Read(sharedBuffer, 0, buffer.Length); if ((uint)numRead > (uint)buffer.Length) { throw new IOException(SR.IO_StreamTooLong); } new ReadOnlySpan<byte>(sharedBuffer, 0, numRead).CopyTo(buffer); return numRead; } finally { ArrayPool<byte>.Shared.Return(sharedBuffer); } } public virtual int ReadByte() { var oneByteArray = new byte[1]; int r = Read(oneByteArray, 0, 1); return r == 0 ? -1 : oneByteArray[0]; } public abstract void Write(byte[] buffer, int offset, int count); public virtual void Write(ReadOnlySpan<byte> buffer) { byte[] sharedBuffer = ArrayPool<byte>.Shared.Rent(buffer.Length); try { buffer.CopyTo(sharedBuffer); Write(sharedBuffer, 0, buffer.Length); } finally { ArrayPool<byte>.Shared.Return(sharedBuffer); } } public virtual void WriteByte(byte value) => Write(new byte[1] { value }, 0, 1); public static Stream Synchronized(Stream stream) => stream is null ? throw new ArgumentNullException(nameof(stream)) : stream is SyncStream ? stream : new SyncStream(stream); [Obsolete("Do not call or override this method.")] protected virtual void ObjectInvariant() { } /// <summary>Validates arguments provided to reading and writing methods on <see cref="Stream"/>.</summary> /// <param name="buffer">The array "buffer" argument passed to the reading or writing method.</param> /// <param name="offset">The integer "offset" argument passed to the reading or writing method.</param> /// <param name="count">The integer "count" argument passed to the reading or writing method.</param> /// <exception cref="ArgumentNullException"><paramref name="buffer"/> was null.</exception> /// <exception cref="ArgumentOutOfRangeException"> /// <paramref name="offset"/> was outside the bounds of <paramref name="buffer"/>, or /// <paramref name="count"/> was negative, or the range specified by the combination of /// <paramref name="offset"/> and <paramref name="count"/> exceed the length of <paramref name="buffer"/>. /// </exception> [MethodImpl(MethodImplOptions.AggressiveInlining)] protected static void ValidateBufferArguments(byte[] buffer, int offset, int count) { if (buffer is null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.buffer); } if (offset < 0) { ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.offset, ExceptionResource.ArgumentOutOfRange_NeedNonNegNum); } if ((uint)count > buffer.Length - offset) { ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.count, ExceptionResource.Argument_InvalidOffLen); } } /// <summary>Validates arguments provided to the <see cref="CopyTo(Stream, int)"/> or <see cref="CopyToAsync(Stream, int, CancellationToken)"/> methods.</summary> /// <param name="destination">The <see cref="Stream"/> "destination" argument passed to the copy method.</param> /// <param name="bufferSize">The integer "bufferSize" argument passed to the copy method.</param> /// <exception cref="ArgumentNullException"><paramref name="destination"/> was null.</exception> /// <exception cref="ArgumentOutOfRangeException"><paramref name="bufferSize"/> was not a positive value.</exception> /// <exception cref="NotSupportedException"><paramref name="destination"/> does not support writing.</exception> /// <exception cref="ObjectDisposedException"><paramref name="destination"/> does not support writing or reading.</exception> protected static void ValidateCopyToArguments(Stream destination, int bufferSize) { if (destination is null) { throw new ArgumentNullException(nameof(destination)); } if (bufferSize <= 0) { throw new ArgumentOutOfRangeException(nameof(bufferSize), bufferSize, SR.ArgumentOutOfRange_NeedPosNum); } if (!destination.CanWrite) { if (destination.CanRead) { ThrowHelper.ThrowNotSupportedException_UnwritableStream(); } ThrowHelper.ThrowObjectDisposedException_StreamClosed(destination.GetType().Name); } } /// <summary>Provides a nop stream.</summary> private sealed class NullStream : Stream { internal NullStream() { } public override bool CanRead => true; public override bool CanWrite => true; public override bool CanSeek => true; public override long Length => 0; public override long Position { get => 0; set { } } public override void CopyTo(Stream destination, int bufferSize) { } public override Task CopyToAsync(Stream destination, int bufferSize, CancellationToken cancellationToken) => cancellationToken.IsCancellationRequested ? Task.FromCanceled(cancellationToken) : Task.CompletedTask; protected override void Dispose(bool disposing) { // Do nothing - we don't want NullStream singleton (static) to be closable } public override void Flush() { } public override Task FlushAsync(CancellationToken cancellationToken) => cancellationToken.IsCancellationRequested ? Task.FromCanceled(cancellationToken) : Task.CompletedTask; public override IAsyncResult BeginRead(byte[] buffer, int offset, int count, AsyncCallback? callback, object? state) => TaskToApm.Begin(Task<int>.s_defaultResultTask, callback, state); public override int EndRead(IAsyncResult asyncResult) => TaskToApm.End<int>(asyncResult); public override IAsyncResult BeginWrite(byte[] buffer, int offset, int count, AsyncCallback? callback, object? state) => TaskToApm.Begin(Task.CompletedTask, callback, state); public override void EndWrite(IAsyncResult asyncResult) => TaskToApm.End(asyncResult); public override int Read(byte[] buffer, int offset, int count) => 0; public override int Read(Span<byte> buffer) => 0; public override Task<int> ReadAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken) => cancellationToken.IsCancellationRequested ? Task.FromCanceled<int>(cancellationToken) : Task.FromResult(0); public override ValueTask<int> ReadAsync(Memory<byte> buffer, CancellationToken cancellationToken) => cancellationToken.IsCancellationRequested ? ValueTask.FromCanceled<int>(cancellationToken) : default; public override int ReadByte() => -1; public override void Write(byte[] buffer, int offset, int count) { } public override void Write(ReadOnlySpan<byte> buffer) { } public override Task WriteAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken) => cancellationToken.IsCancellationRequested ? Task.FromCanceled(cancellationToken) : Task.CompletedTask; public override ValueTask WriteAsync(ReadOnlyMemory<byte> buffer, CancellationToken cancellationToken = default) => cancellationToken.IsCancellationRequested ? ValueTask.FromCanceled(cancellationToken) : default; public override void WriteByte(byte value) { } public override long Seek(long offset, SeekOrigin origin) => 0; public override void SetLength(long length) { } } /// <summary>Provides a wrapper around a stream that takes a lock for every operation.</summary> private sealed class SyncStream : Stream, IDisposable { private readonly Stream _stream; internal SyncStream(Stream stream) => _stream = stream ?? throw new ArgumentNullException(nameof(stream)); public override bool CanRead => _stream.CanRead; public override bool CanWrite => _stream.CanWrite; public override bool CanSeek => _stream.CanSeek; public override bool CanTimeout => _stream.CanTimeout; public override long Length { get { lock (_stream) { return _stream.Length; } } } public override long Position { get { lock (_stream) { return _stream.Position; } } set { lock (_stream) { _stream.Position = value; } } } public override int ReadTimeout { get => _stream.ReadTimeout; set => _stream.ReadTimeout = value; } public override int WriteTimeout { get => _stream.WriteTimeout; set => _stream.WriteTimeout = value; } public override void Close() { lock (_stream) { // On the off chance that some wrapped stream has different // semantics for Close vs. Dispose, let's preserve that. try { _stream.Close(); } finally { base.Dispose(true); } } } protected override void Dispose(bool disposing) { lock (_stream) { try { // Explicitly pick up a potentially methodimpl'ed Dispose if (disposing) { ((IDisposable)_stream).Dispose(); } } finally { base.Dispose(disposing); } } } public override ValueTask DisposeAsync() { lock (_stream) { return _stream.DisposeAsync(); } } public override void Flush() { lock (_stream) { _stream.Flush(); } } public override int Read(byte[] bytes, int offset, int count) { lock (_stream) { return _stream.Read(bytes, offset, count); } } public override int Read(Span<byte> buffer) { lock (_stream) { return _stream.Read(buffer); } } public override int ReadByte() { lock (_stream) { return _stream.ReadByte(); } } public override IAsyncResult BeginRead(byte[] buffer, int offset, int count, AsyncCallback? callback, object? state) { #if CORERT throw new NotImplementedException(); // TODO: https://github.com/dotnet/corert/issues/3251 #else bool overridesBeginRead = _stream.HasOverriddenBeginEndRead(); lock (_stream) { // If the Stream does have its own BeginRead implementation, then we must use that override. // If it doesn't, then we'll use the base implementation, but we'll make sure that the logic // which ensures only one asynchronous operation does so with an asynchronous wait rather // than a synchronous wait. A synchronous wait will result in a deadlock condition, because // the EndXx method for the outstanding async operation won't be able to acquire the lock on // _stream due to this call blocked while holding the lock. return overridesBeginRead ? _stream.BeginRead(buffer, offset, count, callback, state) : _stream.BeginReadInternal(buffer, offset, count, callback, state, serializeAsynchronously: true, apm: true); } #endif } public override int EndRead(IAsyncResult asyncResult) { if (asyncResult is null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.asyncResult); } lock (_stream) { return _stream.EndRead(asyncResult); } } public override long Seek(long offset, SeekOrigin origin) { lock (_stream) { return _stream.Seek(offset, origin); } } public override void SetLength(long length) { lock (_stream) { _stream.SetLength(length); } } public override void Write(byte[] bytes, int offset, int count) { lock (_stream) { _stream.Write(bytes, offset, count); } } public override void Write(ReadOnlySpan<byte> buffer) { lock (_stream) { _stream.Write(buffer); } } public override void WriteByte(byte b) { lock (_stream) { _stream.WriteByte(b); } } public override IAsyncResult BeginWrite(byte[] buffer, int offset, int count, AsyncCallback? callback, object? state) { #if CORERT throw new NotImplementedException(); // TODO: https://github.com/dotnet/corert/issues/3251 #else bool overridesBeginWrite = _stream.HasOverriddenBeginEndWrite(); lock (_stream) { // If the Stream does have its own BeginWrite implementation, then we must use that override. // If it doesn't, then we'll use the base implementation, but we'll make sure that the logic // which ensures only one asynchronous operation does so with an asynchronous wait rather // than a synchronous wait. A synchronous wait will result in a deadlock condition, because // the EndXx method for the outstanding async operation won't be able to acquire the lock on // _stream due to this call blocked while holding the lock. return overridesBeginWrite ? _stream.BeginWrite(buffer, offset, count, callback, state) : _stream.BeginWriteInternal(buffer, offset, count, callback, state, serializeAsynchronously: true, apm: true); } #endif } public override void EndWrite(IAsyncResult asyncResult) { if (asyncResult is null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.asyncResult); } lock (_stream) { _stream.EndWrite(asyncResult); } } } } }
42.502254
170
0.570447
[ "MIT" ]
333fred/runtime
src/libraries/System.Private.CoreLib/src/System/IO/Stream.cs
47,135
C#
using AllReady.Areas.Admin.Models; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Linq; using Xunit; namespace AllReady.UnitTest.ViewModels { public class TaskSummaryModelTests { [Fact] public void ValidationShouldFail_IfNoNameIsSupplied() { var model = new TaskSummaryModel(); var result = ValidateModel(model); var nameError = result.Where(r => r.ErrorMessage == "The Name field is required.").FirstOrDefault(); Assert.NotNull(nameError); } private IList<ValidationResult> ValidateModel(object model) { var validationResults = new List<ValidationResult>(); var ctx = new ValidationContext(model, null, null); Validator.TryValidateObject(model, ctx, validationResults, true); return validationResults; } } }
29.774194
112
0.654388
[ "MIT" ]
HydAu/AllReadyCopyJune10_2016
AllReadyApp/Web-App/AllReady.UnitTest/Models/TaskSummaryModelTests.cs
925
C#
using System.Linq; using Microsoft.EntityFrameworkCore; using Abp.Configuration; using Abp.Localization; using Abp.Net.Mail; namespace MyCore.BaseProject.EntityFrameworkCore.Seed.Host { public class DefaultSettingsCreator { private readonly BaseProjectDbContext _context; public DefaultSettingsCreator(BaseProjectDbContext context) { _context = context; } public void Create() { // Emailing AddSettingIfNotExists(EmailSettingNames.DefaultFromAddress, "admin@mydomain.com"); AddSettingIfNotExists(EmailSettingNames.DefaultFromDisplayName, "mydomain.com mailer"); // Languages AddSettingIfNotExists(LocalizationSettingNames.DefaultLanguage, "en"); } private void AddSettingIfNotExists(string name, string value, int? tenantId = null) { if (_context.Settings.IgnoreQueryFilters().Any(s => s.Name == name && s.TenantId == tenantId && s.UserId == null)) { return; } _context.Settings.Add(new Setting(tenantId, null, name, value)); _context.SaveChanges(); } } }
30.075
126
0.637573
[ "MIT" ]
liyahui520/BaseProject
aspnet-core/src/MyCore.BaseProject.EntityFrameworkCore/EntityFrameworkCore/Seed/Host/DefaultSettingsCreator.cs
1,205
C#
using System.Threading; using Construct.Admin.State; using NUnit.Framework; namespace Construct.Admin.Test.State { public class SessionTest { /// <summary> /// Session under test. /// </summary> private Session _session; /// <summary> /// Creates the test Session. /// </summary> [SetUp] public void SetUp() { this._session = new Session() { MaxSessions = 3, MaxSessionDuration = 1, }; } /// <summary> /// Tests getting a single instance. /// </summary> [Test] public void TestSingleton() { Assert.AreEqual(Session.GetSingleton(), Session.GetSingleton()); } /// <summary> /// Tests creating the maximum amount of sessions. /// </summary> [Test] public void TestMaxSessions() { var initialSession = this._session.CreateSession("test"); Assert.AreNotEqual(initialSession, this._session.CreateSession("test")); Assert.IsTrue(this._session.SessionValid(initialSession)); Assert.AreEqual("test", this._session.GetIdentifier(initialSession)); Assert.AreNotEqual(initialSession, this._session.CreateSession("test")); Assert.IsTrue(this._session.SessionValid(initialSession)); Assert.AreEqual("test", this._session.GetIdentifier(initialSession)); Assert.AreNotEqual(initialSession, this._session.CreateSession("test")); Assert.IsFalse(this._session.SessionValid(initialSession)); Assert.AreNotEqual("test", this._session.GetIdentifier(initialSession)); } /// <summary> /// Tests expiring sessions. /// </summary> [Test] public void TestExpiringSessions() { var initialSession = this._session.CreateSession("test"); Assert.IsTrue(this._session.SessionValid(initialSession)); Assert.AreEqual("test", this._session.GetIdentifier(initialSession)); Thread.Sleep(500); Assert.IsTrue(this._session.SessionValid(initialSession)); Assert.AreEqual("test", this._session.GetIdentifier(initialSession)); Thread.Sleep(750); Assert.IsFalse(this._session.SessionValid(initialSession)); Assert.IsNull(this._session.GetIdentifier(initialSession)); } /// <summary> /// Tests getting the identifiers of sessions. /// </summary> [Test] public void TestGetIdentifier() { Assert.IsNull(this._session.GetIdentifier("unknown")); Assert.AreEqual("test", this._session.GetIdentifier(this._session.CreateSession("test"))); Assert.AreEqual("test2", this._session.GetIdentifier(this._session.CreateSession("test2"))); } /// <summary> /// Tests refreshing a missing session. /// </summary> [Test] public void TestRefreshMissing() { Assert.IsFalse(this._session.RefreshSession("unknown")); } /// <summary> /// Tests refreshing an expired session. /// </summary> [Test] public void TestRefreshExpired() { var initialSession = this._session.CreateSession("test"); Thread.Sleep(1500); Assert.IsFalse(this._session.RefreshSession(initialSession)); } /// <summary> /// Tests refreshing single sessions. /// </summary> [Test] public void TestRefreshSingleSession() { var initialSession = this._session.CreateSession("test"); Thread.Sleep(500); Assert.IsTrue(this._session.RefreshSession(initialSession)); Thread.Sleep(750); Assert.IsTrue(this._session.SessionValid(initialSession)); } /// <summary> /// Tests refreshing the first session. /// Later sessions that don't get refreshed must expire. /// </summary> [Test] public void TestRefreshFirstSession() { var session1 = this._session.CreateSession("test"); var session2 = this._session.CreateSession("test"); Thread.Sleep(500); Assert.IsTrue(this._session.RefreshSession(session1)); Assert.IsTrue(this._session.SessionValid(session2)); Thread.Sleep(750); Assert.IsTrue(this._session.SessionValid(session1)); Assert.IsFalse(this._session.SessionValid(session2)); } } }
35.704545
104
0.581583
[ "MIT" ]
ChrisFigura/Makerspace-Database-Server
Construct.Admin.Test/State/SessionTest.cs
4,713
C#
using SFA.DAS.Commitments.Domain.Entities.TrainingProgramme; namespace SFA.DAS.Commitments.Infrastructure.Configuration { public class ApprenticeshipInfoServiceConfiguration : IApprenticeshipInfoServiceConfiguration { public string BaseUrl { get; set; } } }
31
97
0.784946
[ "MIT" ]
Ryan-Fitchett/Test
src/SFA.DAS.Commitments.Infrastructure/Configuration/ApprenticeshipInfoServiceConfiguration.cs
281
C#
using System.IO; using System; using UnityEngine; using KianCommons; namespace HideCrosswalks.Utils { using static TextureUtils; public static class DumpUtils { public static void LogUVs(NetInfo info1, NetInfo info2) { string m = "info1: " + info1.GetUncheckedLocalizedTitle() + "\n"; m += "info2: " + info2.GetUncheckedLocalizedTitle() + "\n\n"; // info1 info2 // S.<x y> // N.<x y> Vector2[] UVseg1 = info1.m_segments[0].m_mesh.uv; Vector2[] UVseg2 = info2.m_segments[0].m_mesh.uv; Vector2[] UVnode1 = info1.m_nodes[0].m_mesh.uv; Vector2[] UVnode2 = info2.m_nodes[0].m_mesh.uv; Vector2[] v11 = UVseg1; Vector2[] v21 = UVnode1; Vector2[] v12 = UVseg2; Vector2[] v22 = UVnode2; int n = Math.Min(Math.Min(UVseg1.Length, UVseg2.Length), Math.Min(UVnode1.Length, UVnode2.Length)); string str(Vector2 v) => "<" + v.x.ToString("0.000") + " " + v.y.ToString("0.000") + ">"; for (int i = 0; i < n; ++i) { string s1 = str(v11[i]) + " | " + str(v12[i]); string s2 = str(v21[i]) + " | " + str(v22[i]); string s = i.ToString("000") + " " + s1 + "\n"; s += $" " + s2 + "\n\n"; m += s; } Log.Info(m); } public static void Dump(NetInfo info) { for (int i = 0; i < info.m_segments.Length; ++i) { var seg = info.m_segments[i]; Material material = seg.m_segmentMaterial; string baseName = "segment"; //if (info.m_segments.Length > 1) baseName += i; Dump(material, baseName, info); //break; //first one is enough } for (int i = 0; i < info.m_nodes.Length; ++i) { var node = info.m_nodes[i]; Material material = node.m_nodeMaterial; string baseName = "node"; if (info.m_nodes.Length > 1) baseName += i; Dump(material, baseName, info); //break; //first one is enough } } public static void Dump(Material material, string baseName, NetInfo info) { if (baseName == null) baseName = material.name; Dump(material, ID_Defuse, baseName, info); Dump(material, ID_APRMap, baseName, info); try { Dump(material, ID_XYSMap, baseName, info); } catch { } } public static void Dump(Material material, int texID, string baseName, NetInfo info) { if (material == null) throw new ArgumentNullException("material"); Texture2D texture = material.TryGetTexture2D(texID); string path = GetFilePath(texID, baseName ?? material.name, info); if(texture!=null)Dump(texture, path); } public static void Dump(Texture tex, string path) { if (tex == null) throw new ArgumentNullException("tex"); Texture2D texture = tex is Texture2D ? tex as Texture2D : throw new Exception($"texture:{tex} is not texture2D"); Log.Info($"Dumping texture:<{tex.name}> size:<{tex.width}x{tex.height}>"); texture = texture.TryMakeReadable(); byte[] bytes = texture.EncodeToPNG(); if (bytes == null) { Log.Info($"Warning! bytes == null. Failed to dump {tex?.name} with format {(tex as Texture2D).format} to {path}."); return; } Log.Info("Dumping to " + path); File.WriteAllBytes(path, bytes); } public static void Dump(Texture tex, NetInfo info) { string path = GetFilePath( texType: "", baseName: tex.name ?? throw new NullReferenceException("tex.name is null"), dir: info.GetUncheckedLocalizedTitle()); Dump(tex, path); } public static string GetFilePath(int texID, string baseName, NetInfo info) { string dir = info?.GetUncheckedLocalizedTitle() ?? "dummy"; return GetFilePath(getTexName(texID), baseName, dir); } public static string GetFilePath(string texType, string baseName, string dir) { string filename = baseName + texType + ".png"; foreach (char c in @"\/:<>|" + "\"") { filename = filename.Replace(c.ToString(), ""); } foreach (char c in @":<>|" + "\"") { dir = dir.Replace(c.ToString(), ""); } string path = Path.Combine("HTC dumps", dir); Directory.CreateDirectory(path); path = Path.Combine(path, filename); return path; } public static Texture2D Load(string path) { Log.Info("Loading Texture from " + path); byte[] bytes = File.ReadAllBytes(path); Texture2D texture = new Texture2D(1, 1); texture.LoadImage(bytes); texture.anisoLevel = 16; texture.Compress(true); texture.name = path; return texture; } } }
41.275591
132
0.5248
[ "MIT" ]
CitiesSkylinesMods/HideCrosswalks
HideTMPECrosswalks/Utils/DumpUtils.cs
5,242
C#
#if __IOS__ || MACCATALYST using PlatformView = UIKit.UIStepper; #elif MONOANDROID using PlatformView = Microsoft.Maui.Platform.MauiStepper; #elif WINDOWS using PlatformView = Microsoft.Maui.Platform.MauiStepper; #elif (NETSTANDARD || !PLATFORM) || (NET6_0 && !IOS && !ANDROID) using PlatformView = System.Object; #endif namespace Microsoft.Maui.Handlers { public partial interface IStepperHandler : IViewHandler { new IStepper VirtualView { get; } new PlatformView PlatformView { get; } } }
27.777778
64
0.764
[ "MIT" ]
10088/maui
src/Core/src/Handlers/Stepper/IStepperHandler.cs
502
C#
using System; public class StartUp { public static void Main() { Book bookOne = new Book("Animal Farm", 2003, "George Orwell"); Book bookTwo = new Book("The Documents in the Case", 2002, "Dorothy Sayers", "Robert Eustace"); Book bookThree = new Book("The Documents in the Case", 1930); Library libraryOne = new Library(); Library libraryTwo = new Library(bookOne, bookTwo, bookThree); foreach (var book in libraryTwo) { Console.WriteLine(book); } } }
25.904762
103
0.606618
[ "MIT" ]
GitHarr/SoftUni
Homework/C#Fundamentals/C# OOP Advanced/03. Iterators and Comparators/Lab/01.Library/StartUp.cs
546
C#
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace eBordo.Api.Database { public class Pozicija { public int pozicijaId { get; set; } public string nazivPozicije { get; set; } public string skracenica { get; set; } } }
20.8
49
0.669872
[ "MIT" ]
harispandzic/eBordo-desktop-mobile
eBordo.Api/Database/Pozicija.cs
314
C#
using System; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Text; namespace QRCoder { public class QRCodeGenerator : IDisposable { private static readonly char[] numTable = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9' }; private static readonly char[] alphanumEncTable = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', ' ', '$', '%', '*', '+', '-', '.', '/', ':' }; private static readonly int[] capacityBaseValues = { 41, 25, 17, 10, 34, 20, 14, 8, 27, 16, 11, 7, 17, 10, 7, 4, 77, 47, 32, 20, 63, 38, 26, 16, 48, 29, 20, 12, 34, 20, 14, 8, 127, 77, 53, 32, 101, 61, 42, 26, 77, 47, 32, 20, 58, 35, 24, 15, 187, 114, 78, 48, 149, 90, 62, 38, 111, 67, 46, 28, 82, 50, 34, 21, 255, 154, 106, 65, 202, 122, 84, 52, 144, 87, 60, 37, 106, 64, 44, 27, 322, 195, 134, 82, 255, 154, 106, 65, 178, 108, 74, 45, 139, 84, 58, 36, 370, 224, 154, 95, 293, 178, 122, 75, 207, 125, 86, 53, 154, 93, 64, 39, 461, 279, 192, 118, 365, 221, 152, 93, 259, 157, 108, 66, 202, 122, 84, 52, 552, 335, 230, 141, 432, 262, 180, 111, 312, 189, 130, 80, 235, 143, 98, 60, 652, 395, 271, 167, 513, 311, 213, 131, 364, 221, 151, 93, 288, 174, 119, 74, 772, 468, 321, 198, 604, 366, 251, 155, 427, 259, 177, 109, 331, 200, 137, 85, 883, 535, 367, 226, 691, 419, 287, 177, 489, 296, 203, 125, 374, 227, 155, 96, 1022, 619, 425, 262, 796, 483, 331, 204, 580, 352, 241, 149, 427, 259, 177, 109, 1101, 667, 458, 282, 871, 528, 362, 223, 621, 376, 258, 159, 468, 283, 194, 120, 1250, 758, 520, 320, 991, 600, 412, 254, 703, 426, 292, 180, 530, 321, 220, 136, 1408, 854, 586, 361, 1082, 656, 450, 277, 775, 470, 322, 198, 602, 365, 250, 154, 1548, 938, 644, 397, 1212, 734, 504, 310, 876, 531, 364, 224, 674, 408, 280, 173, 1725, 1046, 718, 442, 1346, 816, 560, 345, 948, 574, 394, 243, 746, 452, 310, 191, 1903, 1153, 792, 488, 1500, 909, 624, 384, 1063, 644, 442, 272, 813, 493, 338, 208, 2061, 1249, 858, 528, 1600, 970, 666, 410, 1159, 702, 482, 297, 919, 557, 382, 235, 2232, 1352, 929, 572, 1708, 1035, 711, 438, 1224, 742, 509, 314, 969, 587, 403, 248, 2409, 1460, 1003, 618, 1872, 1134, 779, 480, 1358, 823, 565, 348, 1056, 640, 439, 270, 2620, 1588, 1091, 672, 2059, 1248, 857, 528, 1468, 890, 611, 376, 1108, 672, 461, 284, 2812, 1704, 1171, 721, 2188, 1326, 911, 561, 1588, 963, 661, 407, 1228, 744, 511, 315, 3057, 1853, 1273, 784, 2395, 1451, 997, 614, 1718, 1041, 715, 440, 1286, 779, 535, 330, 3283, 1990, 1367, 842, 2544, 1542, 1059, 652, 1804, 1094, 751, 462, 1425, 864, 593, 365, 3517, 2132, 1465, 902, 2701, 1637, 1125, 692, 1933, 1172, 805, 496, 1501, 910, 625, 385, 3669, 2223, 1528, 940, 2857, 1732, 1190, 732, 2085, 1263, 868, 534, 1581, 958, 658, 405, 3909, 2369, 1628, 1002, 3035, 1839, 1264, 778, 2181, 1322, 908, 559, 1677, 1016, 698, 430, 4158, 2520, 1732, 1066, 3289, 1994, 1370, 843, 2358, 1429, 982, 604, 1782, 1080, 742, 457, 4417, 2677, 1840, 1132, 3486, 2113, 1452, 894, 2473, 1499, 1030, 634, 1897, 1150, 790, 486, 4686, 2840, 1952, 1201, 3693, 2238, 1538, 947, 2670, 1618, 1112, 684, 2022, 1226, 842, 518, 4965, 3009, 2068, 1273, 3909, 2369, 1628, 1002, 2805, 1700, 1168, 719, 2157, 1307, 898, 553, 5253, 3183, 2188, 1347, 4134, 2506, 1722, 1060, 2949, 1787, 1228, 756, 2301, 1394, 958, 590, 5529, 3351, 2303, 1417, 4343, 2632, 1809, 1113, 3081, 1867, 1283, 790, 2361, 1431, 983, 605, 5836, 3537, 2431, 1496, 4588, 2780, 1911, 1176, 3244, 1966, 1351, 832, 2524, 1530, 1051, 647, 6153, 3729, 2563, 1577, 4775, 2894, 1989, 1224, 3417, 2071, 1423, 876, 2625, 1591, 1093, 673, 6479, 3927, 2699, 1661, 5039, 3054, 2099, 1292, 3599, 2181, 1499, 923, 2735, 1658, 1139, 701, 6743, 4087, 2809, 1729, 5313, 3220, 2213, 1362, 3791, 2298, 1579, 972, 2927, 1774, 1219, 750, 7089, 4296, 2953, 1817, 5596, 3391, 2331, 1435, 3993, 2420, 1663, 1024, 3057, 1852, 1273, 784 }; private static readonly int[] capacityECCBaseValues = { 19, 7, 1, 19, 0, 0, 16, 10, 1, 16, 0, 0, 13, 13, 1, 13, 0, 0, 9, 17, 1, 9, 0, 0, 34, 10, 1, 34, 0, 0, 28, 16, 1, 28, 0, 0, 22, 22, 1, 22, 0, 0, 16, 28, 1, 16, 0, 0, 55, 15, 1, 55, 0, 0, 44, 26, 1, 44, 0, 0, 34, 18, 2, 17, 0, 0, 26, 22, 2, 13, 0, 0, 80, 20, 1, 80, 0, 0, 64, 18, 2, 32, 0, 0, 48, 26, 2, 24, 0, 0, 36, 16, 4, 9, 0, 0, 108, 26, 1, 108, 0, 0, 86, 24, 2, 43, 0, 0, 62, 18, 2, 15, 2, 16, 46, 22, 2, 11, 2, 12, 136, 18, 2, 68, 0, 0, 108, 16, 4, 27, 0, 0, 76, 24, 4, 19, 0, 0, 60, 28, 4, 15, 0, 0, 156, 20, 2, 78, 0, 0, 124, 18, 4, 31, 0, 0, 88, 18, 2, 14, 4, 15, 66, 26, 4, 13, 1, 14, 194, 24, 2, 97, 0, 0, 154, 22, 2, 38, 2, 39, 110, 22, 4, 18, 2, 19, 86, 26, 4, 14, 2, 15, 232, 30, 2, 116, 0, 0, 182, 22, 3, 36, 2, 37, 132, 20, 4, 16, 4, 17, 100, 24, 4, 12, 4, 13, 274, 18, 2, 68, 2, 69, 216, 26, 4, 43, 1, 44, 154, 24, 6, 19, 2, 20, 122, 28, 6, 15, 2, 16, 324, 20, 4, 81, 0, 0, 254, 30, 1, 50, 4, 51, 180, 28, 4, 22, 4, 23, 140, 24, 3, 12, 8, 13, 370, 24, 2, 92, 2, 93, 290, 22, 6, 36, 2, 37, 206, 26, 4, 20, 6, 21, 158, 28, 7, 14, 4, 15, 428, 26, 4, 107, 0, 0, 334, 22, 8, 37, 1, 38, 244, 24, 8, 20, 4, 21, 180, 22, 12, 11, 4, 12, 461, 30, 3, 115, 1, 116, 365, 24, 4, 40, 5, 41, 261, 20, 11, 16, 5, 17, 197, 24, 11, 12, 5, 13, 523, 22, 5, 87, 1, 88, 415, 24, 5, 41, 5, 42, 295, 30, 5, 24, 7, 25, 223, 24, 11, 12, 7, 13, 589, 24, 5, 98, 1, 99, 453, 28, 7, 45, 3, 46, 325, 24, 15, 19, 2, 20, 253, 30, 3, 15, 13, 16, 647, 28, 1, 107, 5, 108, 507, 28, 10, 46, 1, 47, 367, 28, 1, 22, 15, 23, 283, 28, 2, 14, 17, 15, 721, 30, 5, 120, 1, 121, 563, 26, 9, 43, 4, 44, 397, 28, 17, 22, 1, 23, 313, 28, 2, 14, 19, 15, 795, 28, 3, 113, 4, 114, 627, 26, 3, 44, 11, 45, 445, 26, 17, 21, 4, 22, 341, 26, 9, 13, 16, 14, 861, 28, 3, 107, 5, 108, 669, 26, 3, 41, 13, 42, 485, 30, 15, 24, 5, 25, 385, 28, 15, 15, 10, 16, 932, 28, 4, 116, 4, 117, 714, 26, 17, 42, 0, 0, 512, 28, 17, 22, 6, 23, 406, 30, 19, 16, 6, 17, 1006, 28, 2, 111, 7, 112, 782, 28, 17, 46, 0, 0, 568, 30, 7, 24, 16, 25, 442, 24, 34, 13, 0, 0, 1094, 30, 4, 121, 5, 122, 860, 28, 4, 47, 14, 48, 614, 30, 11, 24, 14, 25, 464, 30, 16, 15, 14, 16, 1174, 30, 6, 117, 4, 118, 914, 28, 6, 45, 14, 46, 664, 30, 11, 24, 16, 25, 514, 30, 30, 16, 2, 17, 1276, 26, 8, 106, 4, 107, 1000, 28, 8, 47, 13, 48, 718, 30, 7, 24, 22, 25, 538, 30, 22, 15, 13, 16, 1370, 28, 10, 114, 2, 115, 1062, 28, 19, 46, 4, 47, 754, 28, 28, 22, 6, 23, 596, 30, 33, 16, 4, 17, 1468, 30, 8, 122, 4, 123, 1128, 28, 22, 45, 3, 46, 808, 30, 8, 23, 26, 24, 628, 30, 12, 15, 28, 16, 1531, 30, 3, 117, 10, 118, 1193, 28, 3, 45, 23, 46, 871, 30, 4, 24, 31, 25, 661, 30, 11, 15, 31, 16, 1631, 30, 7, 116, 7, 117, 1267, 28, 21, 45, 7, 46, 911, 30, 1, 23, 37, 24, 701, 30, 19, 15, 26, 16, 1735, 30, 5, 115, 10, 116, 1373, 28, 19, 47, 10, 48, 985, 30, 15, 24, 25, 25, 745, 30, 23, 15, 25, 16, 1843, 30, 13, 115, 3, 116, 1455, 28, 2, 46, 29, 47, 1033, 30, 42, 24, 1, 25, 793, 30, 23, 15, 28, 16, 1955, 30, 17, 115, 0, 0, 1541, 28, 10, 46, 23, 47, 1115, 30, 10, 24, 35, 25, 845, 30, 19, 15, 35, 16, 2071, 30, 17, 115, 1, 116, 1631, 28, 14, 46, 21, 47, 1171, 30, 29, 24, 19, 25, 901, 30, 11, 15, 46, 16, 2191, 30, 13, 115, 6, 116, 1725, 28, 14, 46, 23, 47, 1231, 30, 44, 24, 7, 25, 961, 30, 59, 16, 1, 17, 2306, 30, 12, 121, 7, 122, 1812, 28, 12, 47, 26, 48, 1286, 30, 39, 24, 14, 25, 986, 30, 22, 15, 41, 16, 2434, 30, 6, 121, 14, 122, 1914, 28, 6, 47, 34, 48, 1354, 30, 46, 24, 10, 25, 1054, 30, 2, 15, 64, 16, 2566, 30, 17, 122, 4, 123, 1992, 28, 29, 46, 14, 47, 1426, 30, 49, 24, 10, 25, 1096, 30, 24, 15, 46, 16, 2702, 30, 4, 122, 18, 123, 2102, 28, 13, 46, 32, 47, 1502, 30, 48, 24, 14, 25, 1142, 30, 42, 15, 32, 16, 2812, 30, 20, 117, 4, 118, 2216, 28, 40, 47, 7, 48, 1582, 30, 43, 24, 22, 25, 1222, 30, 10, 15, 67, 16, 2956, 30, 19, 118, 6, 119, 2334, 28, 18, 47, 31, 48, 1666, 30, 34, 24, 34, 25, 1276, 30, 20, 15, 61, 16 }; private static readonly int[] alignmentPatternBaseValues = { 0, 0, 0, 0, 0, 0, 0, 6, 18, 0, 0, 0, 0, 0, 6, 22, 0, 0, 0, 0, 0, 6, 26, 0, 0, 0, 0, 0, 6, 30, 0, 0, 0, 0, 0, 6, 34, 0, 0, 0, 0, 0, 6, 22, 38, 0, 0, 0, 0, 6, 24, 42, 0, 0, 0, 0, 6, 26, 46, 0, 0, 0, 0, 6, 28, 50, 0, 0, 0, 0, 6, 30, 54, 0, 0, 0, 0, 6, 32, 58, 0, 0, 0, 0, 6, 34, 62, 0, 0, 0, 0, 6, 26, 46, 66, 0, 0, 0, 6, 26, 48, 70, 0, 0, 0, 6, 26, 50, 74, 0, 0, 0, 6, 30, 54, 78, 0, 0, 0, 6, 30, 56, 82, 0, 0, 0, 6, 30, 58, 86, 0, 0, 0, 6, 34, 62, 90, 0, 0, 0, 6, 28, 50, 72, 94, 0, 0, 6, 26, 50, 74, 98, 0, 0, 6, 30, 54, 78, 102, 0, 0, 6, 28, 54, 80, 106, 0, 0, 6, 32, 58, 84, 110, 0, 0, 6, 30, 58, 86, 114, 0, 0, 6, 34, 62, 90, 118, 0, 0, 6, 26, 50, 74, 98, 122, 0, 6, 30, 54, 78, 102, 126, 0, 6, 26, 52, 78, 104, 130, 0, 6, 30, 56, 82, 108, 134, 0, 6, 34, 60, 86, 112, 138, 0, 6, 30, 58, 86, 114, 142, 0, 6, 34, 62, 90, 118, 146, 0, 6, 30, 54, 78, 102, 126, 150, 6, 24, 50, 76, 102, 128, 154, 6, 28, 54, 80, 106, 132, 158, 6, 32, 58, 84, 110, 136, 162, 6, 26, 54, 82, 110, 138, 166, 6, 30, 58, 86, 114, 142, 170 }; private static readonly int[] remainderBits = { 0, 7, 7, 7, 7, 7, 0, 0, 0, 0, 0, 0, 0, 3, 3, 3, 3, 3, 3, 3, 4, 4, 4, 4, 4, 4, 4, 3, 3, 3, 3, 3, 3, 3, 0, 0, 0, 0, 0, 0 }; private static readonly List<AlignmentPattern> alignmentPatternTable = CreateAlignmentPatternTable(); private static readonly List<ECCInfo> capacityECCTable = CreateCapacityECCTable(); private static readonly List<VersionInfo> capacityTable = CreateCapacityTable(); private static readonly List<Antilog> galoisField = CreateAntilogTable(); private static readonly Dictionary<char, int> alphanumEncDict = CreateAlphanumEncDict(); public enum EciMode { Default = 0, Iso8859_1 = 3, Iso8859_2 = 4, Utf8 = 26 } /// <summary> /// Initializes the QR code generator /// </summary> public QRCodeGenerator() { } /// <summary> /// Calculates the QR code data which than can be used in one of the rendering classes to generate a graphical representation. /// </summary> /// <param name="payload">A payload object, generated by the PayloadGenerator-class</param> /// <exception cref="QRCoder.Exceptions.DataTooLongException">Thrown when the payload is too big to be encoded in a QR code.</exception> /// <returns>Returns the raw QR code data which can be used for rendering.</returns> public QRCodeData CreateQrCode(PayloadGenerator.Payload payload) { return GenerateQrCode(payload); } /// <summary> /// Calculates the QR code data which than can be used in one of the rendering classes to generate a graphical representation. /// </summary> /// <param name="payload">A payload object, generated by the PayloadGenerator-class</param> /// <param name="eccLevel">The level of error correction data</param> /// <exception cref="QRCoder.Exceptions.DataTooLongException">Thrown when the payload is too big to be encoded in a QR code.</exception> /// <returns>Returns the raw QR code data which can be used for rendering.</returns> public QRCodeData CreateQrCode(PayloadGenerator.Payload payload, ECCLevel eccLevel) { return GenerateQrCode(payload, eccLevel); } /// <summary> /// Calculates the QR code data which than can be used in one of the rendering classes to generate a graphical representation. /// </summary> /// <param name="plainText">The payload which shall be encoded in the QR code</param> /// <param name="eccLevel">The level of error correction data</param> /// <param name="forceUtf8">Shall the generator be forced to work in UTF-8 mode?</param> /// <param name="utf8BOM">Should the byte-order-mark be used?</param> /// <param name="eciMode">Which ECI mode shall be used?</param> /// <param name="requestedVersion">Set fixed QR code target version. Will be overridded to accomodate data if trimDataToEnforceRequestedVersion is set to false</param> /// <param name="trimDataToEnforceRequestedVersion">Allow data to be trimmed to keep output version same as requested version.</param> /// <exception cref="QRCoder.Exceptions.DataTooLongException">Thrown when the payload is too big to be encoded in a QR code.</exception> /// <returns>Returns the raw QR code data which can be used for rendering.</returns> public QRCodeData CreateQrCode(string plainText, ECCLevel eccLevel, bool forceUtf8 = false, bool utf8BOM = false, EciMode eciMode = EciMode.Default, int requestedVersion = -1, bool trimDataToEnforceRequestedVersion = true) { return GenerateQrCode(plainText, eccLevel, forceUtf8, utf8BOM, eciMode, requestedVersion, trimDataToEnforceRequestedVersion); } /// <summary> /// Calculates the QR code data which than can be used in one of the rendering classes to generate a graphical representation. /// </summary> /// <param name="binaryData">A byte array which shall be encoded/stored in the QR code</param> /// <param name="eccLevel">The level of error correction data</param> /// <exception cref="QRCoder.Exceptions.DataTooLongException">Thrown when the payload is too big to be encoded in a QR code.</exception> /// <returns>Returns the raw QR code data which can be used for rendering.</returns> public QRCodeData CreateQrCode(byte[] binaryData, ECCLevel eccLevel) { return GenerateQrCode(binaryData, eccLevel); } /// <summary> /// Calculates the QR code data which than can be used in one of the rendering classes to generate a graphical representation. /// </summary> /// <param name="payload">A payload object, generated by the PayloadGenerator-class</param> /// <exception cref="QRCoder.Exceptions.DataTooLongException">Thrown when the payload is too big to be encoded in a QR code.</exception> /// <returns>Returns the raw QR code data which can be used for rendering.</returns> public static QRCodeData GenerateQrCode(PayloadGenerator.Payload payload) { return GenerateQrCode(payload.ToString(), payload.EccLevel, false, false, payload.EciMode, payload.Version); } /// <summary> /// Calculates the QR code data which than can be used in one of the rendering classes to generate a graphical representation. /// </summary> /// <param name="payload">A payload object, generated by the PayloadGenerator-class</param> /// <param name="eccLevel">The level of error correction data</param> /// <exception cref="QRCoder.Exceptions.DataTooLongException">Thrown when the payload is too big to be encoded in a QR code.</exception> /// <returns>Returns the raw QR code data which can be used for rendering.</returns> public static QRCodeData GenerateQrCode(PayloadGenerator.Payload payload, ECCLevel eccLevel) { return GenerateQrCode(payload.ToString(), eccLevel, false, false, payload.EciMode, payload.Version); } /// <summary> /// Calculates the QR code data which than can be used in one of the rendering classes to generate a graphical representation. /// </summary> /// <param name="plainText">The payload which shall be encoded in the QR code</param> /// <param name="eccLevel">The level of error correction data</param> /// <param name="forceUtf8">Shall the generator be forced to work in UTF-8 mode?</param> /// <param name="utf8BOM">Should the byte-order-mark be used?</param> /// <param name="eciMode">Which ECI mode shall be used?</param> /// <param name="requestedVersion">Set fixed QR code target version. Will be overridded to accomodate data if trimDataToEnforceRequestedVersion is set to false</param> /// <param name="trimDataToEnforceRequestedVersion">Allow data to be trimmed to keep output version same as requested version.</param> /// <exception cref="QRCoder.Exceptions.DataTooLongException">Thrown when the payload is too big to be encoded in a QR code.</exception> /// <returns>Returns the raw QR code data which can be used for rendering.</returns> public static QRCodeData GenerateQrCode(string plainText, ECCLevel eccLevel, bool forceUtf8 = false, bool utf8BOM = false, EciMode eciMode = EciMode.Default, int requestedVersion = -1, bool trimDataToEnforceRequestedVersion = true) { EncodingMode encoding = GetEncodingFromPlaintext(plainText, forceUtf8); var codedText = PlainTextToBinary(plainText, encoding, eciMode, utf8BOM, forceUtf8); var dataInputLength = GetDataLength(encoding, plainText, codedText, forceUtf8); int version = (trimDataToEnforceRequestedVersion && requestedVersion >= 1) ? requestedVersion : Math.Max(requestedVersion, GetVersion(dataInputLength, encoding, eccLevel)); string modeIndicator = String.Empty; if (eciMode != EciMode.Default) { modeIndicator = DecToBin((int)EncodingMode.ECI, 4); modeIndicator += DecToBin((int)eciMode, 8); } modeIndicator += DecToBin((int)encoding, 4); var countIndicator = DecToBin(dataInputLength, GetCountIndicatorLength(version, encoding)); var bitString = modeIndicator + countIndicator; bitString += codedText; return GenerateQrCode(bitString, eccLevel, version); } /// <summary> /// Calculates the QR code data which than can be used in one of the rendering classes to generate a graphical representation. /// </summary> /// <param name="binaryData">A byte array which shall be encoded/stored in the QR code</param> /// <param name="eccLevel">The level of error correction data</param> /// <exception cref="QRCoder.Exceptions.DataTooLongException">Thrown when the payload is too big to be encoded in a QR code.</exception> /// <returns>Returns the raw QR code data which can be used for rendering.</returns> public static QRCodeData GenerateQrCode(byte[] binaryData, ECCLevel eccLevel) { int version = GetVersion(binaryData.Length, EncodingMode.Byte, eccLevel); string modeIndicator = DecToBin((int)EncodingMode.Byte, 4); string countIndicator = DecToBin(binaryData.Length, GetCountIndicatorLength(version, EncodingMode.Byte)); string bitString = modeIndicator + countIndicator; foreach (byte b in binaryData) { bitString += DecToBin(b, 8); } return GenerateQrCode(bitString, eccLevel, version); } private static QRCodeData GenerateQrCode(string bitString, ECCLevel eccLevel, int version) { //Fill up data code word var eccInfo = capacityECCTable.Single(x => x.Version == version && x.ErrorCorrectionLevel.Equals(eccLevel)); var dataLength = eccInfo.TotalDataCodewords * 8; var lengthDiff = dataLength - bitString.Length; if (lengthDiff > 0) bitString += new string('0', Math.Min(lengthDiff, 4)); if ((bitString.Length % 8) != 0) bitString += new string('0', 8 - (bitString.Length % 8)); while (bitString.Length < dataLength) bitString += "1110110000010001"; if (bitString.Length > dataLength) bitString = bitString.Substring(0, dataLength); //Calculate error correction words var codeWordWithECC = new List<CodewordBlock>(); for (var i = 0; i < eccInfo.BlocksInGroup1; i++) { var bitStr = bitString.Substring(i * eccInfo.CodewordsInGroup1 * 8, eccInfo.CodewordsInGroup1 * 8); var bitBlockList = BinaryStringToBitBlockList(bitStr); var bitBlockListDec = BinaryStringListToDecList(bitBlockList); var eccWordList = CalculateECCWords(bitStr, eccInfo); var eccWordListDec = BinaryStringListToDecList(eccWordList); codeWordWithECC.Add( new CodewordBlock(1, i + 1, bitStr, bitBlockList, eccWordList, bitBlockListDec, eccWordListDec) ); } bitString = bitString.Substring(eccInfo.BlocksInGroup1 * eccInfo.CodewordsInGroup1 * 8); for (var i = 0; i < eccInfo.BlocksInGroup2; i++) { var bitStr = bitString.Substring(i * eccInfo.CodewordsInGroup2 * 8, eccInfo.CodewordsInGroup2 * 8); var bitBlockList = BinaryStringToBitBlockList(bitStr); var bitBlockListDec = BinaryStringListToDecList(bitBlockList); var eccWordList = CalculateECCWords(bitStr, eccInfo); var eccWordListDec = BinaryStringListToDecList(eccWordList); codeWordWithECC.Add(new CodewordBlock(2, i + 1, bitStr, bitBlockList, eccWordList, bitBlockListDec, eccWordListDec) ); } //Interleave code words var interleavedWordsSb = new StringBuilder(); for (var i = 0; i < Math.Max(eccInfo.CodewordsInGroup1, eccInfo.CodewordsInGroup2); i++) { foreach (var codeBlock in codeWordWithECC) if (codeBlock.CodeWords.Count > i) interleavedWordsSb.Append(codeBlock.CodeWords[i]); } for (var i = 0; i < eccInfo.ECCPerBlock; i++) { foreach (var codeBlock in codeWordWithECC) if (codeBlock.ECCWords.Count > i) interleavedWordsSb.Append(codeBlock.ECCWords[i]); } interleavedWordsSb.Append(new string('0', remainderBits[version - 1])); var interleavedData = interleavedWordsSb.ToString(); //Place interleaved data on module matrix var qr = new QRCodeData(version); var blockedModules = new List<Rectangle>(); ModulePlacer.PlaceFinderPatterns(ref qr, ref blockedModules); ModulePlacer.ReserveSeperatorAreas(qr.ModuleMatrix.Count, ref blockedModules); ModulePlacer.PlaceAlignmentPatterns(ref qr, alignmentPatternTable.Where(x => x.Version == version).Select(x => x.PatternPositions).First(), ref blockedModules); ModulePlacer.PlaceTimingPatterns(ref qr, ref blockedModules); ModulePlacer.PlaceDarkModule(ref qr, version, ref blockedModules); ModulePlacer.ReserveVersionAreas(qr.ModuleMatrix.Count, version, ref blockedModules); ModulePlacer.PlaceDataWords(ref qr, interleavedData, ref blockedModules); var maskVersion = ModulePlacer.MaskCode(ref qr, version, ref blockedModules, eccLevel); var formatStr = GetFormatString(eccLevel, maskVersion); ModulePlacer.PlaceFormat(ref qr, formatStr); if (version >= 7) { var versionString = GetVersionString(version); ModulePlacer.PlaceVersion(ref qr, versionString); } ModulePlacer.AddQuietZone(ref qr); return qr; } private static string GetFormatString(ECCLevel level, int maskVersion) { var generator = "10100110111"; var fStrMask = "101010000010010"; var fStr = (level == ECCLevel.L) ? "01" : (level == ECCLevel.M) ? "00" : (level == ECCLevel.Q) ? "11" : "10"; fStr += DecToBin(maskVersion, 3); var fStrEcc = fStr.PadRight(15, '0').TrimStart('0'); while (fStrEcc.Length > 10) { var sb = new StringBuilder(); generator = generator.PadRight(fStrEcc.Length, '0'); for (var i = 0; i < fStrEcc.Length; i++) sb.Append((Convert.ToInt32(fStrEcc[i]) ^ Convert.ToInt32(generator[i])).ToString()); fStrEcc = sb.ToString().TrimStart('0'); } fStrEcc = fStrEcc.PadLeft(10, '0'); fStr += fStrEcc; var sbMask = new StringBuilder(); for (var i = 0; i < fStr.Length; i++) sbMask.Append((Convert.ToInt32(fStr[i]) ^ Convert.ToInt32(fStrMask[i])).ToString()); return sbMask.ToString(); } private static string GetVersionString(int version) { var generator = "1111100100101"; var vStr = DecToBin(version, 6); var vStrEcc = vStr.PadRight(18, '0').TrimStart('0'); while (vStrEcc.Length > 12) { var sb = new StringBuilder(); generator = generator.PadRight(vStrEcc.Length, '0'); for (var i = 0; i < vStrEcc.Length; i++) sb.Append((Convert.ToInt32(vStrEcc[i]) ^ Convert.ToInt32(generator[i])).ToString()); vStrEcc = sb.ToString().TrimStart('0'); } vStrEcc = vStrEcc.PadLeft(12, '0'); vStr += vStrEcc; return vStr; } private static class ModulePlacer { public static void AddQuietZone(ref QRCodeData qrCode) { var quietLine = new bool[qrCode.ModuleMatrix.Count + 8]; for (var i = 0; i < quietLine.Length; i++) quietLine[i] = false; for (var i = 0; i < 4; i++) qrCode.ModuleMatrix.Insert(0, new BitArray(quietLine)); for (var i = 0; i < 4; i++) qrCode.ModuleMatrix.Add(new BitArray(quietLine)); for (var i = 4; i < qrCode.ModuleMatrix.Count - 4; i++) { bool[] quietPart = { false, false, false, false }; var tmpLine = new List<bool>(quietPart); tmpLine.AddRange(qrCode.ModuleMatrix[i].Cast<bool>()); tmpLine.AddRange(quietPart); qrCode.ModuleMatrix[i] = new BitArray(tmpLine.ToArray()); } } private static string ReverseString(string inp) { string newStr = string.Empty; if (inp.Length > 0) { for (int i = inp.Length - 1; i >= 0; i--) newStr += inp[i]; } return newStr; } public static void PlaceVersion(ref QRCodeData qrCode, string versionStr) { var size = qrCode.ModuleMatrix.Count; var vStr = ReverseString(versionStr); for (var x = 0; x < 6; x++) { for (var y = 0; y < 3; y++) { qrCode.ModuleMatrix[y + size - 11][x] = vStr[x * 3 + y] == '1'; qrCode.ModuleMatrix[x][y + size - 11] = vStr[x * 3 + y] == '1'; } } } public static void PlaceFormat(ref QRCodeData qrCode, string formatStr) { var size = qrCode.ModuleMatrix.Count; var fStr = ReverseString(formatStr); var modules = new[,] { { 8, 0, size - 1, 8 }, { 8, 1, size - 2, 8 }, { 8, 2, size - 3, 8 }, { 8, 3, size - 4, 8 }, { 8, 4, size - 5, 8 }, { 8, 5, size - 6, 8 }, { 8, 7, size - 7, 8 }, { 8, 8, size - 8, 8 }, { 7, 8, 8, size - 7 }, { 5, 8, 8, size - 6 }, { 4, 8, 8, size - 5 }, { 3, 8, 8, size - 4 }, { 2, 8, 8, size - 3 }, { 1, 8, 8, size - 2 }, { 0, 8, 8, size - 1 } }; for (var i = 0; i < 15; i++) { var p1 = new Point(modules[i, 0], modules[i, 1]); var p2 = new Point(modules[i, 2], modules[i, 3]); qrCode.ModuleMatrix[p1.Y][p1.X] = fStr[i] == '1'; qrCode.ModuleMatrix[p2.Y][p2.X] = fStr[i] == '1'; } } public static int MaskCode(ref QRCodeData qrCode, int version, ref List<Rectangle> blockedModules, ECCLevel eccLevel) { var patternName = string.Empty; var patternScore = 0; var size = qrCode.ModuleMatrix.Count; #if NET40 var methods = typeof(MaskPattern).GetMethods(); #else var methods = typeof(MaskPattern).GetTypeInfo().DeclaredMethods; #endif foreach (var pattern in methods) { if (pattern.Name.Length == 8 && pattern.Name.StartsWith("Pattern")) { var qrTemp = new QRCodeData(version); for (var y = 0; y < size; y++) { for (var x = 0; x < size; x++) { qrTemp.ModuleMatrix[y][x] = qrCode.ModuleMatrix[y][x]; } } var formatStr = GetFormatString(eccLevel, Convert.ToInt32((pattern.Name.Substring(7, 1))) - 1); ModulePlacer.PlaceFormat(ref qrTemp, formatStr); if (version >= 7) { var versionString = GetVersionString(version); ModulePlacer.PlaceVersion(ref qrTemp, versionString); } for (var x = 0; x < size; x++) { for (var y = 0; y < size; y++) { if (!IsBlocked(new Rectangle(x, y, 1, 1), blockedModules)) { qrTemp.ModuleMatrix[y][x] ^= (bool)pattern.Invoke(null, new object[] { x, y }); } } } var score = MaskPattern.Score(ref qrTemp); if (string.IsNullOrEmpty(patternName) || patternScore > score) { patternName = pattern.Name; patternScore = score; } } } #if NET40 var patterMethod = typeof(MaskPattern).GetMethods().First(x => x.Name == patternName); #else var patterMethod = typeof(MaskPattern).GetTypeInfo().GetDeclaredMethod(patternName); #endif for (var x = 0; x < size; x++) { for (var y = 0; y < size; y++) { if (!IsBlocked(new Rectangle(x, y, 1, 1), blockedModules)) { qrCode.ModuleMatrix[y][x] ^= (bool)patterMethod.Invoke(null, new object[] { x, y }); } } } return Convert.ToInt32(patterMethod.Name.Substring(patterMethod.Name.Length - 1, 1)) - 1; } public static void PlaceDataWords(ref QRCodeData qrCode, string data, ref List<Rectangle> blockedModules) { var size = qrCode.ModuleMatrix.Count; var up = true; var datawords = new Queue<bool>(); for (int i = 0; i < data.Length; i++) { datawords.Enqueue(data[i] != '0'); } for (var x = size - 1; x >= 0; x = x - 2) { if (x == 6) x = 5; for (var yMod = 1; yMod <= size; yMod++) { int y; if (up) { y = size - yMod; if (datawords.Count > 0 && !IsBlocked(new Rectangle(x, y, 1, 1), blockedModules)) qrCode.ModuleMatrix[y][x] = datawords.Dequeue(); if (datawords.Count > 0 && x > 0 && !IsBlocked(new Rectangle(x - 1, y, 1, 1), blockedModules)) qrCode.ModuleMatrix[y][x - 1] = datawords.Dequeue(); } else { y = yMod - 1; if (datawords.Count > 0 && !IsBlocked(new Rectangle(x, y, 1, 1), blockedModules)) qrCode.ModuleMatrix[y][x] = datawords.Dequeue(); if (datawords.Count > 0 && x > 0 && !IsBlocked(new Rectangle(x - 1, y, 1, 1), blockedModules)) qrCode.ModuleMatrix[y][x - 1] = datawords.Dequeue(); } } up = !up; } } public static void ReserveSeperatorAreas(int size, ref List<Rectangle> blockedModules) { blockedModules.AddRange(new[]{ new Rectangle(7, 0, 1, 8), new Rectangle(0, 7, 7, 1), new Rectangle(0, size-8, 8, 1), new Rectangle(7, size-7, 1, 7), new Rectangle(size-8, 0, 1, 8), new Rectangle(size-7, 7, 7, 1) }); } public static void ReserveVersionAreas(int size, int version, ref List<Rectangle> blockedModules) { blockedModules.AddRange(new[]{ new Rectangle(8, 0, 1, 6), new Rectangle(8, 7, 1, 1), new Rectangle(0, 8, 6, 1), new Rectangle(7, 8, 2, 1), new Rectangle(size-8, 8, 8, 1), new Rectangle(8, size-7, 1, 7) }); if (version >= 7) { blockedModules.AddRange(new[]{ new Rectangle(size-11, 0, 3, 6), new Rectangle(0, size-11, 6, 3) }); } } public static void PlaceDarkModule(ref QRCodeData qrCode, int version, ref List<Rectangle> blockedModules) { qrCode.ModuleMatrix[4 * version + 9][8] = true; blockedModules.Add(new Rectangle(8, 4 * version + 9, 1, 1)); } public static void PlaceFinderPatterns(ref QRCodeData qrCode, ref List<Rectangle> blockedModules) { var size = qrCode.ModuleMatrix.Count; int[] locations = { 0, 0, size - 7, 0, 0, size - 7 }; for (var i = 0; i < 6; i = i + 2) { for (var x = 0; x < 7; x++) { for (var y = 0; y < 7; y++) { if (!(((x == 1 || x == 5) && y > 0 && y < 6) || (x > 0 && x < 6 && (y == 1 || y == 5)))) { qrCode.ModuleMatrix[y + locations[i + 1]][x + locations[i]] = true; } } } blockedModules.Add(new Rectangle(locations[i], locations[i + 1], 7, 7)); } } public static void PlaceAlignmentPatterns(ref QRCodeData qrCode, List<Point> alignmentPatternLocations, ref List<Rectangle> blockedModules) { foreach (var loc in alignmentPatternLocations) { var alignmentPatternRect = new Rectangle(loc.X, loc.Y, 5, 5); var blocked = false; foreach (var blockedRect in blockedModules) { if (Intersects(alignmentPatternRect, blockedRect)) { blocked = true; break; } } if (blocked) continue; for (var x = 0; x < 5; x++) { for (var y = 0; y < 5; y++) { if (y == 0 || y == 4 || x == 0 || x == 4 || (x == 2 && y == 2)) { qrCode.ModuleMatrix[loc.Y + y][loc.X + x] = true; } } } blockedModules.Add(new Rectangle(loc.X, loc.Y, 5, 5)); } } public static void PlaceTimingPatterns(ref QRCodeData qrCode, ref List<Rectangle> blockedModules) { var size = qrCode.ModuleMatrix.Count; for (var i = 8; i < size - 8; i++) { if (i % 2 == 0) { qrCode.ModuleMatrix[6][i] = true; qrCode.ModuleMatrix[i][6] = true; } } blockedModules.AddRange(new[]{ new Rectangle(6, 8, 1, size-16), new Rectangle(8, 6, size-16, 1) }); } private static bool Intersects(Rectangle r1, Rectangle r2) { return r2.X < r1.X + r1.Width && r1.X < r2.X + r2.Width && r2.Y < r1.Y + r1.Height && r1.Y < r2.Y + r2.Height; } private static bool IsBlocked(Rectangle r1, List<Rectangle> blockedModules) { var isBlocked = false; foreach (var blockedMod in blockedModules) { if (Intersects(blockedMod, r1)) isBlocked = true; } return isBlocked; } private static class MaskPattern { public static bool Pattern1(int x, int y) { return (x + y) % 2 == 0; } public static bool Pattern2(int x, int y) { return y % 2 == 0; } public static bool Pattern3(int x, int y) { return x % 3 == 0; } public static bool Pattern4(int x, int y) { return (x + y) % 3 == 0; } public static bool Pattern5(int x, int y) { return ((int)(Math.Floor(y / 2d) + Math.Floor(x / 3d)) % 2) == 0; } public static bool Pattern6(int x, int y) { return ((x * y) % 2) + ((x * y) % 3) == 0; } public static bool Pattern7(int x, int y) { return (((x * y) % 2) + ((x * y) % 3)) % 2 == 0; } public static bool Pattern8(int x, int y) { return (((x + y) % 2) + ((x * y) % 3)) % 2 == 0; } public static int Score(ref QRCodeData qrCode) { int score1 = 0, score2 = 0, score3 = 0, score4 = 0; var size = qrCode.ModuleMatrix.Count; //Penalty 1 for (var y = 0; y < size; y++) { var modInRow = 0; var modInColumn = 0; var lastValRow = qrCode.ModuleMatrix[y][0]; var lastValColumn = qrCode.ModuleMatrix[0][y]; for (var x = 0; x < size; x++) { if (qrCode.ModuleMatrix[y][x] == lastValRow) modInRow++; else modInRow = 1; if (modInRow == 5) score1 += 3; else if (modInRow > 5) score1++; lastValRow = qrCode.ModuleMatrix[y][x]; if (qrCode.ModuleMatrix[x][y] == lastValColumn) modInColumn++; else modInColumn = 1; if (modInColumn == 5) score1 += 3; else if (modInColumn > 5) score1++; lastValColumn = qrCode.ModuleMatrix[x][y]; } } //Penalty 2 for (var y = 0; y < size - 1; y++) { for (var x = 0; x < size - 1; x++) { if (qrCode.ModuleMatrix[y][x] == qrCode.ModuleMatrix[y][x + 1] && qrCode.ModuleMatrix[y][x] == qrCode.ModuleMatrix[y + 1][x] && qrCode.ModuleMatrix[y][x] == qrCode.ModuleMatrix[y + 1][x + 1]) score2 += 3; } } //Penalty 3 for (var y = 0; y < size; y++) { for (var x = 0; x < size - 10; x++) { if ((qrCode.ModuleMatrix[y][x] && !qrCode.ModuleMatrix[y][x + 1] && qrCode.ModuleMatrix[y][x + 2] && qrCode.ModuleMatrix[y][x + 3] && qrCode.ModuleMatrix[y][x + 4] && !qrCode.ModuleMatrix[y][x + 5] && qrCode.ModuleMatrix[y][x + 6] && !qrCode.ModuleMatrix[y][x + 7] && !qrCode.ModuleMatrix[y][x + 8] && !qrCode.ModuleMatrix[y][x + 9] && !qrCode.ModuleMatrix[y][x + 10]) || (!qrCode.ModuleMatrix[y][x] && !qrCode.ModuleMatrix[y][x + 1] && !qrCode.ModuleMatrix[y][x + 2] && !qrCode.ModuleMatrix[y][x + 3] && qrCode.ModuleMatrix[y][x + 4] && !qrCode.ModuleMatrix[y][x + 5] && qrCode.ModuleMatrix[y][x + 6] && qrCode.ModuleMatrix[y][x + 7] && qrCode.ModuleMatrix[y][x + 8] && !qrCode.ModuleMatrix[y][x + 9] && qrCode.ModuleMatrix[y][x + 10])) { score3 += 40; } if ((qrCode.ModuleMatrix[x][y] && !qrCode.ModuleMatrix[x + 1][y] && qrCode.ModuleMatrix[x + 2][y] && qrCode.ModuleMatrix[x + 3][y] && qrCode.ModuleMatrix[x + 4][y] && !qrCode.ModuleMatrix[x + 5][y] && qrCode.ModuleMatrix[x + 6][y] && !qrCode.ModuleMatrix[x + 7][y] && !qrCode.ModuleMatrix[x + 8][y] && !qrCode.ModuleMatrix[x + 9][y] && !qrCode.ModuleMatrix[x + 10][y]) || (!qrCode.ModuleMatrix[x][y] && !qrCode.ModuleMatrix[x + 1][y] && !qrCode.ModuleMatrix[x + 2][y] && !qrCode.ModuleMatrix[x + 3][y] && qrCode.ModuleMatrix[x + 4][y] && !qrCode.ModuleMatrix[x + 5][y] && qrCode.ModuleMatrix[x + 6][y] && qrCode.ModuleMatrix[x + 7][y] && qrCode.ModuleMatrix[x + 8][y] && !qrCode.ModuleMatrix[x + 9][y] && qrCode.ModuleMatrix[x + 10][y])) { score3 += 40; } } } //Penalty 4 double blackModules = 0; foreach (var row in qrCode.ModuleMatrix) foreach (bool bit in row) if (bit) blackModules++; var percent = (blackModules / (qrCode.ModuleMatrix.Count * qrCode.ModuleMatrix.Count)) * 100; var prevMultipleOf5 = Math.Abs((int)Math.Floor(percent / 5) * 5 - 50) / 5; var nextMultipleOf5 = Math.Abs((int)Math.Floor(percent / 5) * 5 - 45) / 5; score4 = Math.Min(prevMultipleOf5, nextMultipleOf5) * 10; return score1 + score2 + score3 + score4; } } } private static List<string> CalculateECCWords(string bitString, ECCInfo eccInfo) { var eccWords = eccInfo.ECCPerBlock; var messagePolynom = CalculateMessagePolynom(bitString); var generatorPolynom = CalculateGeneratorPolynom(eccWords); for (var i = 0; i < messagePolynom.PolyItems.Count; i++) messagePolynom.PolyItems[i] = new PolynomItem(messagePolynom.PolyItems[i].Coefficient, messagePolynom.PolyItems[i].Exponent + eccWords); for (var i = 0; i < generatorPolynom.PolyItems.Count; i++) generatorPolynom.PolyItems[i] = new PolynomItem(generatorPolynom.PolyItems[i].Coefficient, generatorPolynom.PolyItems[i].Exponent + (messagePolynom.PolyItems.Count - 1)); var leadTermSource = messagePolynom; for (var i = 0; (leadTermSource.PolyItems.Count > 0 && leadTermSource.PolyItems[leadTermSource.PolyItems.Count - 1].Exponent > 0); i++) { if (leadTermSource.PolyItems[0].Coefficient == 0) { leadTermSource.PolyItems.RemoveAt(0); leadTermSource.PolyItems.Add(new PolynomItem(0, leadTermSource.PolyItems[leadTermSource.PolyItems.Count - 1].Exponent - 1)); } else { var resPoly = MultiplyGeneratorPolynomByLeadterm(generatorPolynom, ConvertToAlphaNotation(leadTermSource).PolyItems[0], i); resPoly = ConvertToDecNotation(resPoly); resPoly = XORPolynoms(leadTermSource, resPoly); leadTermSource = resPoly; } } return leadTermSource.PolyItems.Select(x => DecToBin(x.Coefficient, 8)).ToList(); } private static Polynom ConvertToAlphaNotation(Polynom poly) { var newPoly = new Polynom(); for (var i = 0; i < poly.PolyItems.Count; i++) newPoly.PolyItems.Add( new PolynomItem( (poly.PolyItems[i].Coefficient != 0 ? GetAlphaExpFromIntVal(poly.PolyItems[i].Coefficient) : 0), poly.PolyItems[i].Exponent)); return newPoly; } private static Polynom ConvertToDecNotation(Polynom poly) { var newPoly = new Polynom(); for (var i = 0; i < poly.PolyItems.Count; i++) newPoly.PolyItems.Add(new PolynomItem(GetIntValFromAlphaExp(poly.PolyItems[i].Coefficient), poly.PolyItems[i].Exponent)); return newPoly; } private static int GetVersion(int length, EncodingMode encMode, ECCLevel eccLevel) { var fittingVersions = capacityTable.Where( x => x.Details.Count( y => (y.ErrorCorrectionLevel == eccLevel && y.CapacityDict[encMode] >= Convert.ToInt32(length) ) ) > 0 ).Select(x => new { version = x.Version, capacity = x.Details.Single(y => y.ErrorCorrectionLevel == eccLevel) .CapacityDict[encMode] }); if (fittingVersions.Any()) return fittingVersions.Min(x => x.version); var maxSizeByte = capacityTable.Where( x => x.Details.Any( y => (y.ErrorCorrectionLevel == eccLevel)) ).Select(x => x.Details.Single(y => y.ErrorCorrectionLevel == eccLevel).CapacityDict[encMode]).Max(); throw new QRCoder.Exceptions.DataTooLongException(eccLevel.ToString(), encMode.ToString(), maxSizeByte); } private static EncodingMode GetEncodingFromPlaintext(string plainText, bool forceUtf8) { EncodingMode result = EncodingMode.Numeric; foreach (char c in plainText) { if (forceUtf8 || !alphanumEncTable.Contains(c)) return EncodingMode.Byte; if (!numTable.Contains(c)) result = EncodingMode.Alphanumeric; } return result; } private static Polynom CalculateMessagePolynom(string bitString) { var messagePol = new Polynom(); for (var i = bitString.Length / 8 - 1; i >= 0; i--) { messagePol.PolyItems.Add(new PolynomItem(BinToDec(bitString.Substring(0, 8)), i)); bitString = bitString.Remove(0, 8); } return messagePol; } private static Polynom CalculateGeneratorPolynom(int numEccWords) { var generatorPolynom = new Polynom(); generatorPolynom.PolyItems.AddRange(new[]{ new PolynomItem(0,1), new PolynomItem(0,0) }); for (var i = 1; i <= numEccWords - 1; i++) { var multiplierPolynom = new Polynom(); multiplierPolynom.PolyItems.AddRange(new[]{ new PolynomItem(0,1), new PolynomItem(i,0) }); generatorPolynom = MultiplyAlphaPolynoms(generatorPolynom, multiplierPolynom); } return generatorPolynom; } private static List<string> BinaryStringToBitBlockList(string bitString) { return new List<char>(bitString.ToCharArray()).Select((x, i) => new { Index = i, Value = x }) .GroupBy(x => x.Index / 8) .Select(x => String.Join("", x.Select(v => v.Value.ToString()).ToArray())) .ToList(); } private static List<int> BinaryStringListToDecList(List<string> binaryStringList) { return binaryStringList.Select(binaryString => BinToDec(binaryString)).ToList(); } private static int BinToDec(string binStr) { return Convert.ToInt32(binStr, 2); } private static string DecToBin(int decNum) { return Convert.ToString(decNum, 2); } private static string DecToBin(int decNum, int padLeftUpTo) { var binStr = DecToBin(decNum); return binStr.PadLeft(padLeftUpTo, '0'); } private static int GetCountIndicatorLength(int version, EncodingMode encMode) { if (version < 10) { if (encMode.Equals(EncodingMode.Numeric)) return 10; else if (encMode.Equals(EncodingMode.Alphanumeric)) return 9; else return 8; } else if (version < 27) { if (encMode.Equals(EncodingMode.Numeric)) return 12; else if (encMode.Equals(EncodingMode.Alphanumeric)) return 11; else if (encMode.Equals(EncodingMode.Byte)) return 16; else return 10; } else { if (encMode.Equals(EncodingMode.Numeric)) return 14; else if (encMode.Equals(EncodingMode.Alphanumeric)) return 13; else if (encMode.Equals(EncodingMode.Byte)) return 16; else return 12; } } private static int GetDataLength(EncodingMode encoding, string plainText, string codedText, bool forceUtf8) { return forceUtf8 || IsUtf8(encoding, plainText) ? (codedText.Length / 8) : plainText.Length; } private static bool IsUtf8(EncodingMode encoding, string plainText) { return (encoding == EncodingMode.Byte && !IsValidISO(plainText)); } private static bool IsValidISO(string input) { var bytes = Encoding.GetEncoding("ISO-8859-1").GetBytes(input); //var result = Encoding.GetEncoding("ISO-8859-1").GetString(bytes); var result = Encoding.GetEncoding("ISO-8859-1").GetString(bytes, 0, bytes.Length); return String.Equals(input, result); } private static string PlainTextToBinary(string plainText, EncodingMode encMode, EciMode eciMode, bool utf8BOM, bool forceUtf8) { switch (encMode) { case EncodingMode.Alphanumeric: return PlainTextToBinaryAlphanumeric(plainText); case EncodingMode.Numeric: return PlainTextToBinaryNumeric(plainText); case EncodingMode.Byte: return PlainTextToBinaryByte(plainText, eciMode, utf8BOM, forceUtf8); case EncodingMode.Kanji: return string.Empty; case EncodingMode.ECI: default: return string.Empty; } } private static string PlainTextToBinaryNumeric(string plainText) { var codeText = string.Empty; while (plainText.Length >= 3) { var dec = Convert.ToInt32(plainText.Substring(0, 3)); codeText += DecToBin(dec, 10); plainText = plainText.Substring(3); } if (plainText.Length == 2) { var dec = Convert.ToInt32(plainText); codeText += DecToBin(dec, 7); } else if (plainText.Length == 1) { var dec = Convert.ToInt32(plainText); codeText += DecToBin(dec, 4); } return codeText; } private static string PlainTextToBinaryAlphanumeric(string plainText) { var codeText = string.Empty; while (plainText.Length >= 2) { var token = plainText.Substring(0, 2); var dec = alphanumEncDict[token[0]] * 45 + alphanumEncDict[token[1]]; codeText += DecToBin(dec, 11); plainText = plainText.Substring(2); } if (plainText.Length > 0) { codeText += DecToBin(alphanumEncDict[plainText[0]], 6); } return codeText; } private string PlainTextToBinaryECI(string plainText) { var codeText = string.Empty; byte[] _bytes = Encoding.GetEncoding("ascii").GetBytes(plainText); foreach (byte _byte in _bytes) { codeText += DecToBin(_byte, 8); } return codeText; } private static string ConvertToIso8859(string value, string Iso = "ISO-8859-2") { Encoding iso = Encoding.GetEncoding(Iso); Encoding utf8 = Encoding.UTF8; byte[] utfBytes = utf8.GetBytes(value); byte[] isoBytes = Encoding.Convert(utf8, iso, utfBytes); #if !PCL return iso.GetString(isoBytes); #else return iso.GetString(isoBytes, 0, isoBytes.Length); #endif } private static string PlainTextToBinaryByte(string plainText, EciMode eciMode, bool utf8BOM, bool forceUtf8) { byte[] codeBytes; var codeText = string.Empty; if (IsValidISO(plainText) && !forceUtf8) codeBytes = Encoding.GetEncoding("ISO-8859-1").GetBytes(plainText); else { switch (eciMode) { case EciMode.Iso8859_1: codeBytes = Encoding.GetEncoding("ISO-8859-1").GetBytes(ConvertToIso8859(plainText, "ISO-8859-1")); break; case EciMode.Iso8859_2: codeBytes = Encoding.GetEncoding("ISO-8859-2").GetBytes(ConvertToIso8859(plainText, "ISO-8859-2")); break; case EciMode.Default: case EciMode.Utf8: default: codeBytes = utf8BOM ? Encoding.UTF8.GetPreamble().Concat(Encoding.UTF8.GetBytes(plainText)).ToArray() : Encoding.UTF8.GetBytes(plainText); break; } } foreach (var b in codeBytes) codeText += DecToBin(b, 8); return codeText; } private static Polynom XORPolynoms(Polynom messagePolynom, Polynom resPolynom) { var resultPolynom = new Polynom(); Polynom longPoly, shortPoly; if (messagePolynom.PolyItems.Count >= resPolynom.PolyItems.Count) { longPoly = messagePolynom; shortPoly = resPolynom; } else { longPoly = resPolynom; shortPoly = messagePolynom; } for (var i = 0; i < longPoly.PolyItems.Count; i++) { var polItemRes = new PolynomItem ( longPoly.PolyItems[i].Coefficient ^ (shortPoly.PolyItems.Count > i ? shortPoly.PolyItems[i].Coefficient : 0), messagePolynom.PolyItems[0].Exponent - i ); resultPolynom.PolyItems.Add(polItemRes); } resultPolynom.PolyItems.RemoveAt(0); return resultPolynom; } private static Polynom MultiplyGeneratorPolynomByLeadterm(Polynom genPolynom, PolynomItem leadTerm, int lowerExponentBy) { var resultPolynom = new Polynom(); foreach (var polItemBase in genPolynom.PolyItems) { var polItemRes = new PolynomItem( (polItemBase.Coefficient + leadTerm.Coefficient) % 255, polItemBase.Exponent - lowerExponentBy ); resultPolynom.PolyItems.Add(polItemRes); } return resultPolynom; } private static Polynom MultiplyAlphaPolynoms(Polynom polynomBase, Polynom polynomMultiplier) { var resultPolynom = new Polynom(); foreach (var polItemBase in polynomMultiplier.PolyItems) { foreach (var polItemMulti in polynomBase.PolyItems) { var polItemRes = new PolynomItem ( ShrinkAlphaExp(polItemBase.Coefficient + polItemMulti.Coefficient), (polItemBase.Exponent + polItemMulti.Exponent) ); resultPolynom.PolyItems.Add(polItemRes); } } var exponentsToGlue = resultPolynom.PolyItems.GroupBy(x => x.Exponent).Where(x => x.Count() > 1).Select(x => x.First().Exponent); var gluedPolynoms = new List<PolynomItem>(); var toGlue = exponentsToGlue as IList<int> ?? exponentsToGlue.ToList(); foreach (var exponent in toGlue) { var coefficient = resultPolynom.PolyItems.Where(x => x.Exponent == exponent).Aggregate(0, (current, polynomOld) => current ^ GetIntValFromAlphaExp(polynomOld.Coefficient)); var polynomFixed = new PolynomItem(GetAlphaExpFromIntVal(coefficient), exponent); gluedPolynoms.Add(polynomFixed); } resultPolynom.PolyItems.RemoveAll(x => toGlue.Contains(x.Exponent)); resultPolynom.PolyItems.AddRange(gluedPolynoms); resultPolynom.PolyItems = resultPolynom.PolyItems.OrderByDescending(x => x.Exponent).ToList(); return resultPolynom; } private static int GetIntValFromAlphaExp(int exp) { return galoisField.Where(alog => alog.ExponentAlpha == exp).Select(alog => alog.IntegerValue).First(); } private static int GetAlphaExpFromIntVal(int intVal) { return galoisField.Where(alog => alog.IntegerValue == intVal).Select(alog => alog.ExponentAlpha).First(); } private static int ShrinkAlphaExp(int alphaExp) { // ReSharper disable once PossibleLossOfFraction return (int)((alphaExp % 256) + Math.Floor((double)(alphaExp / 256))); } private static Dictionary<char, int> CreateAlphanumEncDict() { var localAlphanumEncDict = new Dictionary<char, int>(); for (int i = 0; i < alphanumEncTable.Length; i++) localAlphanumEncDict.Add(alphanumEncTable[i], i); return localAlphanumEncDict; } private static List<AlignmentPattern> CreateAlignmentPatternTable() { var localAlignmentPatternTable = new List<AlignmentPattern>(); for (var i = 0; i < (7 * 40); i = i + 7) { var points = new List<Point>(); for (var x = 0; x < 7; x++) { if (alignmentPatternBaseValues[i + x] != 0) { for (var y = 0; y < 7; y++) { if (alignmentPatternBaseValues[i + y] != 0) { var p = new Point(alignmentPatternBaseValues[i + x] - 2, alignmentPatternBaseValues[i + y] - 2); if (!points.Contains(p)) points.Add(p); } } } } localAlignmentPatternTable.Add(new AlignmentPattern() { Version = (i + 7) / 7, PatternPositions = points } ); } return localAlignmentPatternTable; } private static List<ECCInfo> CreateCapacityECCTable() { var localCapacityECCTable = new List<ECCInfo>(); for (var i = 0; i < (4 * 6 * 40); i = i + (4 * 6)) { localCapacityECCTable.AddRange( new[] { new ECCInfo( (i+24) / 24, ECCLevel.L, capacityECCBaseValues[i], capacityECCBaseValues[i+1], capacityECCBaseValues[i+2], capacityECCBaseValues[i+3], capacityECCBaseValues[i+4], capacityECCBaseValues[i+5]), new ECCInfo ( version: (i + 24) / 24, errorCorrectionLevel: ECCLevel.M, totalDataCodewords: capacityECCBaseValues[i+6], eccPerBlock: capacityECCBaseValues[i+7], blocksInGroup1: capacityECCBaseValues[i+8], codewordsInGroup1: capacityECCBaseValues[i+9], blocksInGroup2: capacityECCBaseValues[i+10], codewordsInGroup2: capacityECCBaseValues[i+11] ), new ECCInfo ( version: (i + 24) / 24, errorCorrectionLevel: ECCLevel.Q, totalDataCodewords: capacityECCBaseValues[i+12], eccPerBlock: capacityECCBaseValues[i+13], blocksInGroup1: capacityECCBaseValues[i+14], codewordsInGroup1: capacityECCBaseValues[i+15], blocksInGroup2: capacityECCBaseValues[i+16], codewordsInGroup2: capacityECCBaseValues[i+17] ), new ECCInfo ( version: (i + 24) / 24, errorCorrectionLevel: ECCLevel.H, totalDataCodewords: capacityECCBaseValues[i+18], eccPerBlock: capacityECCBaseValues[i+19], blocksInGroup1: capacityECCBaseValues[i+20], codewordsInGroup1: capacityECCBaseValues[i+21], blocksInGroup2: capacityECCBaseValues[i+22], codewordsInGroup2: capacityECCBaseValues[i+23] ) }); } return localCapacityECCTable; } private static List<VersionInfo> CreateCapacityTable() { var localCapacityTable = new List<VersionInfo>(); for (var i = 0; i < (16 * 40); i = i + 16) { localCapacityTable.Add(new VersionInfo( (i + 16) / 16, new List<VersionInfoDetails> { new VersionInfoDetails( ECCLevel.L, new Dictionary<EncodingMode,int>(){ { EncodingMode.Numeric, capacityBaseValues[i] }, { EncodingMode.Alphanumeric, capacityBaseValues[i+1] }, { EncodingMode.Byte, capacityBaseValues[i+2] }, { EncodingMode.Kanji, capacityBaseValues[i+3] }, } ), new VersionInfoDetails( ECCLevel.M, new Dictionary<EncodingMode,int>(){ { EncodingMode.Numeric, capacityBaseValues[i+4] }, { EncodingMode.Alphanumeric, capacityBaseValues[i+5] }, { EncodingMode.Byte, capacityBaseValues[i+6] }, { EncodingMode.Kanji, capacityBaseValues[i+7] }, } ), new VersionInfoDetails( ECCLevel.Q, new Dictionary<EncodingMode,int>(){ { EncodingMode.Numeric, capacityBaseValues[i+8] }, { EncodingMode.Alphanumeric, capacityBaseValues[i+9] }, { EncodingMode.Byte, capacityBaseValues[i+10] }, { EncodingMode.Kanji, capacityBaseValues[i+11] }, } ), new VersionInfoDetails( ECCLevel.H, new Dictionary<EncodingMode,int>(){ { EncodingMode.Numeric, capacityBaseValues[i+12] }, { EncodingMode.Alphanumeric, capacityBaseValues[i+13] }, { EncodingMode.Byte, capacityBaseValues[i+14] }, { EncodingMode.Kanji, capacityBaseValues[i+15] }, } ) } )); } return localCapacityTable; } private static List<Antilog> CreateAntilogTable() { var localGaloisField = new List<Antilog>(); int gfItem = 1; for (var i = 0; i < 256; i++) { localGaloisField.Add(new Antilog(i, gfItem)); gfItem *= 2; if (gfItem > 255) gfItem ^= 285; } return localGaloisField; } /// <summary> /// Error correction level. These define the tolerance levels for how much of the code can be lost before the code cannot be recovered. /// </summary> public enum ECCLevel { /// <summary> /// 7% may be lost before recovery is not possible /// </summary> L, /// <summary> /// 15% may be lost before recovery is not possible /// </summary> M, /// <summary> /// 25% may be lost before recovery is not possible /// </summary> Q, /// <summary> /// 30% may be lost before recovery is not possible /// </summary> H } private enum EncodingMode { Numeric = 1, Alphanumeric = 2, Byte = 4, Kanji = 8, ECI = 7 } private struct AlignmentPattern { public int Version; public List<Point> PatternPositions; } private struct CodewordBlock { public CodewordBlock(int groupNumber, int blockNumber, string bitString, List<string> codeWords, List<string> eccWords, List<int> codeWordsInt, List<int> eccWordsInt) { this.GroupNumber = groupNumber; this.BlockNumber = blockNumber; this.BitString = bitString; this.CodeWords = codeWords; this.ECCWords = eccWords; this.CodeWordsInt = codeWordsInt; this.ECCWordsInt = eccWordsInt; } public int GroupNumber { get; } public int BlockNumber { get; } public string BitString { get; } public List<string> CodeWords { get; } public List<int> CodeWordsInt { get; } public List<string> ECCWords { get; } public List<int> ECCWordsInt { get; } } private struct ECCInfo { public ECCInfo(int version, ECCLevel errorCorrectionLevel, int totalDataCodewords, int eccPerBlock, int blocksInGroup1, int codewordsInGroup1, int blocksInGroup2, int codewordsInGroup2) { this.Version = version; this.ErrorCorrectionLevel = errorCorrectionLevel; this.TotalDataCodewords = totalDataCodewords; this.ECCPerBlock = eccPerBlock; this.BlocksInGroup1 = blocksInGroup1; this.CodewordsInGroup1 = codewordsInGroup1; this.BlocksInGroup2 = blocksInGroup2; this.CodewordsInGroup2 = codewordsInGroup2; } public int Version { get; } public ECCLevel ErrorCorrectionLevel { get; } public int TotalDataCodewords { get; } public int ECCPerBlock { get; } public int BlocksInGroup1 { get; } public int CodewordsInGroup1 { get; } public int BlocksInGroup2 { get; } public int CodewordsInGroup2 { get; } } private struct VersionInfo { public VersionInfo(int version, List<VersionInfoDetails> versionInfoDetails) { this.Version = version; this.Details = versionInfoDetails; } public int Version { get; } public List<VersionInfoDetails> Details { get; } } private struct VersionInfoDetails { public VersionInfoDetails(ECCLevel errorCorrectionLevel, Dictionary<EncodingMode, int> capacityDict) { this.ErrorCorrectionLevel = errorCorrectionLevel; this.CapacityDict = capacityDict; } public ECCLevel ErrorCorrectionLevel { get; } public Dictionary<EncodingMode, int> CapacityDict { get; } } private struct Antilog { public Antilog(int exponentAlpha, int integerValue) { this.ExponentAlpha = exponentAlpha; this.IntegerValue = integerValue; } public int ExponentAlpha { get; } public int IntegerValue { get; } } private struct PolynomItem { public PolynomItem(int coefficient, int exponent) { this.Coefficient = coefficient; this.Exponent = exponent; } public int Coefficient { get; } public int Exponent { get; } } private class Polynom { public Polynom() { this.PolyItems = new List<PolynomItem>(); } public List<PolynomItem> PolyItems { get; set; } public override string ToString() { var sb = new StringBuilder(); //this.PolyItems.ForEach(x => sb.Append("a^" + x.Coefficient + "*x^" + x.Exponent + " + ")); foreach (var polyItem in this.PolyItems) { sb.Append("a^" + polyItem.Coefficient + "*x^" + polyItem.Exponent + " + "); } return sb.ToString().TrimEnd(new[] { ' ', '+' }); } } private class Point { public int X { get; } public int Y { get; } public Point(int x, int y) { this.X = x; this.Y = y; } } private class Rectangle { public int X { get; } public int Y { get; } public int Width { get; } public int Height { get; } public Rectangle(int x, int y, int w, int h) { this.X = x; this.Y = y; this.Width = w; this.Height = h; } } public void Dispose() { // left for back-compat } } }
48.579885
3,911
0.49183
[ "MIT" ]
riteshbxr/QRCoder
QRCoder/QRCodeGenerator.cs
76,319
C#
//----------------------------------------------------------------------------- // FILE: CancelRequest.cs // CONTRIBUTOR: Jeff Lill // COPYRIGHT: Copyright (c) 2005-2022 by neonFORGE LLC. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. using System; using System.Collections.Generic; using System.ComponentModel; using Neon.Common; using Neon.Temporal; namespace Neon.Temporal.Internal { /// <summary> /// <b>client --> proxy:</b> Sent periodically to confirm that the proxy is /// still healthy. The proxy should send a <see cref="CancelReply"/> /// optionally indicating that there's a problem by specifying an error. /// </summary> [InternalProxyMessage(InternalMessageTypes.CancelRequest)] internal class CancelRequest : ProxyRequest { /// <summary> /// Default constructor. /// </summary> public CancelRequest() { Type = InternalMessageTypes.CancelRequest; } /// <inheritdoc/> public override InternalMessageTypes ReplyType => InternalMessageTypes.CancelReply; /// <summary> /// The ID of the request being cancelled. /// </summary> public long TargetRequestId { get => GetLongProperty(PropertyNames.TargetRequestId); set => SetLongProperty(PropertyNames.TargetRequestId, value); } /// <inheritdoc/> internal override ProxyMessage Clone() { var clone = new CancelRequest(); CopyTo(clone); return clone; } /// <inheritdoc/> protected override void CopyTo(ProxyMessage target) { base.CopyTo(target); var typedTarget = (CancelRequest)target; typedTarget.TargetRequestId = this.TargetRequestId; } } }
31.197368
91
0.623366
[ "Apache-2.0" ]
codelastnight/neonKUBE
Lib/Neon.Temporal/Internal/ClientMessages/CancelRequest.cs
2,373
C#
using System; using System.Collections; using System.Collections.Generic; using TransactionService.Interfaces; namespace TransactionService { /// <summary> /// Validation Rules /// </summary> public class ValidationRules : IValidationRules { private Object _businessObject; private Boolean _validationStatus { get; set; } private List<String> _validationMessage { get; set; } private Hashtable _validationErrors; public Boolean ValidationStatus { get { return _validationStatus; } } public List<String> ValidationMessage { get { return _validationMessage; } } public Hashtable ValidationErrors { get { return _validationErrors; } } public Object BusinessObject { set { _businessObject = value; } } public ValidationRules() { _validationStatus = true; _validationMessage = new List<string>(); _validationErrors = new Hashtable(); } /// <summary> /// Update Messages /// </summary> /// <param name="validationStatus"></param> /// <param name="validationMessages"></param> /// <param name="validationErrors"></param> public void UpdateMessages(Boolean validationStatus, List<String> validationMessages, Hashtable validationErrors) { if (validationStatus == false) _validationStatus = false; foreach (string validationMessage in validationMessages) { _validationMessage.Add(validationMessage); } foreach (DictionaryEntry validationError in validationErrors) { if (_validationErrors.ContainsKey(validationError.Key) == false) { _validationErrors.Add(validationError.Key, validationError.Value); } } } /// <summary> /// Initialize Validation Rules /// </summary> /// <param name="businessObject"></param> public void InitializeValidationRules(Object businessObject) { _businessObject = businessObject; } /// <summary> /// Validate Required /// </summary> /// <param name="propertyName"></param> public Boolean ValidateRequired(string propertyName) { return ValidateRequired(propertyName, propertyName); } /// <summary> /// Validate Required /// </summary> /// <param name="propertyName"></param> /// <param name="friendlyName"></param> public Boolean ValidateRequired(string propertyName, string friendlyName) { object valueOf = GetPropertyValue(propertyName); if (Validations.ValidateRequired(valueOf) == false) { string errorMessage = friendlyName + " is a required field."; AddValidationError(propertyName, errorMessage); return false; } return true; } /// <summary> /// Validate Guid Required /// </summary> /// <param name="propertyName"></param> /// <param name="friendlyName"></param> public Boolean ValidateGuidRequired(string propertyName, string friendlyName, string displayPropertyName) { object valueOf = GetPropertyValue(propertyName); if (Validations.ValidateRequiredGuid(valueOf) == false) { string errorMessage = friendlyName + " is a required field."; if (displayPropertyName == string.Empty) { AddValidationError(propertyName, errorMessage); } else { AddValidationError(displayPropertyName, errorMessage); } return false; } return true; } public void ValidationError(string propertyName, string errorMessage) { AddValidationError(propertyName, errorMessage); } /// <summary> /// Validate Length /// </summary> /// <param name="propertyName"></param> /// <param name="maxLength"></param> public Boolean ValidateLength(string propertyName, int maxLength) { return ValidateLength(propertyName, propertyName, maxLength); } /// <summary> /// Validate Length /// </summary> /// <param name="propertyName"></param> /// <param name="maxLength"></param> public Boolean ValidateLength(string propertyName, string friendlyName, int maxLength) { object valueOf = GetPropertyValue(propertyName); if (Validations.ValidateLength(valueOf, maxLength) == false) { string errorMessage = friendlyName + " exceeds the maximum of " + maxLength + " characters long."; AddValidationError(propertyName, errorMessage); return false; } return true; } /// <summary> /// Validate Numeric /// </summary> /// <param name="propertyName"></param> /// <param name="maxLength"></param> public Boolean ValidateNumeric(string propertyName, string friendlyName) { object valueOf = GetPropertyValue(propertyName); if (Validations.IsInteger(valueOf) == false) { string errorMessage = friendlyName + " is not a valid number."; AddValidationError(propertyName, errorMessage); return false; } return true; } /// <summary> /// Validate Greater Than Zero /// </summary> /// <param name="propertyName"></param> /// <param name="maxLength"></param> public Boolean ValidateGreaterThanZero(string propertyName, string friendlyName) { object valueOf = GetPropertyValue(propertyName); if (Validations.ValidateGreaterThanZero(valueOf) == false) { string errorMessage = friendlyName + " must be greater than zero."; AddValidationError(propertyName, errorMessage); return false; } return true; } /// <summary> /// Validate Decimal Greater Than Zero /// </summary> /// <param name="propertyName"></param> /// <param name="maxLength"></param> public Boolean ValidateDecimalGreaterThanZero(string propertyName, string friendlyName) { object valueOf = GetPropertyValue(propertyName); if (Validations.ValidateDecimalGreaterThanZero(valueOf) == false) { string errorMessage = friendlyName + " must be greater than zero."; AddValidationError(propertyName, errorMessage); return false; } return true; } public Boolean ValidateDecimalIsNotZero(string propertyName, string friendlyName) { object valueOf = GetPropertyValue(propertyName); if (Validations.ValidateDecimalIsNotZero(valueOf) == false) { string errorMessage = friendlyName + " must not equal zero."; AddValidationError(propertyName, errorMessage); return false; } return true; } /// <summary> /// Item has a selected value /// </summary> /// <param name="propertyName"></param> /// <param name="maxLength"></param> public Boolean ValidateSelectedValue(string propertyName, string friendlyName) { object valueOf = GetPropertyValue(propertyName); if (Validations.ValidateGreaterThanZero(valueOf) == false) { string errorMessage = friendlyName + " not selected."; AddValidationError(propertyName, errorMessage); return false; } return true; } /// <summary> /// Validate Is Date /// </summary> /// <param name="propertyName"></param> /// <param name="maxLength"></param> public Boolean ValidateIsDate(string propertyName, string friendlyName) { object valueOf = GetPropertyValue(propertyName); if (Validations.IsDate(valueOf) == false) { string errorMessage = friendlyName + " is not a valid date."; AddValidationError(propertyName, errorMessage); return false; } return true; } /// <summary> /// Validate Is Date or Null Date /// </summary> /// <param name="propertyName"></param> /// <param name="maxLength"></param> public Boolean ValidateIsDateOrNullDate(string propertyName, string friendlyName) { object valueOf = GetPropertyValue(propertyName); if (Validations.IsDateOrNullDate(valueOf) == false) { string errorMessage = friendlyName + " is not a valid date."; AddValidationError(propertyName, errorMessage); return false; } return true; } /// <summary> /// Validate Required Date /// </summary> /// <param name="propertyName"></param> /// <param name="maxLength"></param> public Boolean ValidateRequiredDate(string propertyName, string friendlyName) { object valueOf = GetPropertyValue(propertyName); if (Validations.IsDateGreaterThanDefaultDate(valueOf) == false) { string errorMessage = friendlyName + " is a required field."; AddValidationError(propertyName, errorMessage); return false; } return true; } /// <summary> /// Validate Date Greater Than or Equal to Today /// </summary> /// <param name="propertyName"></param> /// <param name="maxLength"></param> public Boolean ValidateDateGreaterThanOrEqualToToday(string propertyName, string friendlyName) { object valueOf = GetPropertyValue(propertyName); if (Validations.IsDateGreaterThanOrEqualToToday(valueOf) == false) { string errorMessage = friendlyName + " must be greater than or equal to today."; AddValidationError(propertyName, errorMessage); return false; } return true; } /// <summary> /// Validate Email Address /// </summary> /// <param name="propertyName"></param> public Boolean ValidateEmailAddress(string propertyName) { return ValidateEmailAddress(propertyName, propertyName); } /// <summary> /// Validate Email Address /// </summary> /// <param name="propertyName"></param> public Boolean ValidateEmailAddress(string propertyName, string friendlyName) { object valueOf = GetPropertyValue(propertyName); string stringValue; if (valueOf == null) return true; stringValue = valueOf.ToString(); if (stringValue == string.Empty) return true; if (Validations.ValidateEmailAddress(valueOf.ToString()) == false) { string emailAddressErrorMessage = friendlyName + " is not a valid email address"; AddValidationError(propertyName, emailAddressErrorMessage); return false; } return true; } /// <summary> /// Validatie URL /// </summary> /// <param name="propertyName"></param> /// <param name="friendlyName"></param> /// <returns></returns> public Boolean ValidateURL(string propertyName, string friendlyName) { object valueOf = GetPropertyValue(propertyName); string stringValue; if (valueOf == null) return true; stringValue = valueOf.ToString(); if (stringValue == string.Empty) return true; if (Validations.ValidateURL(valueOf.ToString()) == false) { string urlErrorMessage = friendlyName + " is not a valid URL address"; AddValidationError(propertyName, urlErrorMessage); return false; } return true; } /// <summary> /// Gets value for given business object's property using reflection. /// </summary> /// <param name="businessObject"></param> /// <param name="propertyName"></param> /// <returns></returns> protected object GetPropertyValue(string propertyName) { return _businessObject.GetType().GetProperty(propertyName).GetValue(_businessObject, null); } /// <summary> /// Add Validation Error /// </summary> /// <param name="propertyName"></param> /// <param name="friendlyName"></param> /// <param name="errorMessage"></param> public void AddValidationError(string propertyName, string errorMessage) { if (_validationErrors.Contains(propertyName) == false) { _validationErrors.Add(propertyName, errorMessage); _validationMessage.Add(errorMessage); } _validationStatus = false; } } }
34.04703
121
0.561323
[ "MIT" ]
mantnguyen/BudgetBalance
src/TransactionService/ValidationRules.cs
13,757
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace VRCWorldPersistency { internal class Json { private const string JSON_FILE_NAME = "PersistentWorldData.json"; internal FileStructure ReadJsonFile() { if (!JsonFileExists()) { return new FileStructure(); } else { string path = GetJsonFilePath(); string fileContent = System.IO.File.ReadAllText(path); FileStructure fileStructure = Newtonsoft.Json.JsonConvert.DeserializeObject<FileStructure>(fileContent); return fileStructure; } } internal void SaveJsonFile(FileStructure fileStructure) { string path = GetJsonFilePath(); string fileContent = Newtonsoft.Json.JsonConvert.SerializeObject(fileStructure); System.IO.File.WriteAllText(path, fileContent); } /// <summary> /// Checks if the json file exists /// </summary> private bool JsonFileExists() { string path = GetJsonFilePath(); return System.IO.File.Exists(path); } /// <summary> /// Returns the path to the json file /// </summary> private string GetJsonFilePath() { return System.IO.Path.Combine(Environment.CurrentDirectory, JSON_FILE_NAME); } } }
31.040816
120
0.582512
[ "MIT" ]
Reimajo/VRCWorldPersistency
VRCWorldPersistency/VRCWorldPersistency/Json.cs
1,523
C#
using OpenMysticSimpleTcp.Multithreading; using OpenMysticSimpleTcp.ReadWrite; using System; using System.Collections.Generic; using System.Net.Sockets; using System.Text; namespace OpenMysticSimpleTcp { public class ServerConnectedClient { public int UniqueId { get; private set; } private NetworkStream networkStream; private StreamReadHandler streamReadHandler; public ServerConnectedClient(Socket connectedClientSocket, int uniqueId) { this.networkStream = new NetworkStream(connectedClientSocket); this.streamReadHandler = new StreamReadHandler(networkStream, null); this.UniqueId = uniqueId; } public void StartClientConnectionHandler() { streamReadHandler.StartReadThread(); } public void CloseConnectionSynchronous() { streamReadHandler.StopThreadIfApplicable(); } public void SendData(byte[] buffer, int offset, int size) { networkStream.Write(buffer, offset, size); } } }
27.3
82
0.669414
[ "Apache-2.0" ]
P3TE/OpenMysticSimpleTcp
OpenMysticSimpleTcp/Server/ServerConnectedClient.cs
1,094
C#
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ using System; using System.Collections.Generic; using Aliyun.Acs.Core.Transform; using Aliyun.Acs.Emr.Model.V20160408; namespace Aliyun.Acs.Emr.Transform.V20160408 { public class DeleteClusterTemplateResponseUnmarshaller { public static DeleteClusterTemplateResponse Unmarshall(UnmarshallerContext _ctx) { DeleteClusterTemplateResponse deleteClusterTemplateResponse = new DeleteClusterTemplateResponse(); deleteClusterTemplateResponse.HttpResponse = _ctx.HttpResponse; deleteClusterTemplateResponse.RequestId = _ctx.StringValue("DeleteClusterTemplate.RequestId"); return deleteClusterTemplateResponse; } } }
37.05
102
0.765857
[ "Apache-2.0" ]
AxiosCros/aliyun-openapi-net-sdk
aliyun-net-sdk-emr/Emr/Transform/V20160408/DeleteClusterTemplateResponseUnmarshaller.cs
1,482
C#
namespace NewFormDB { public enum EditMode { Create, Edit, View } }
10.5
24
0.47619
[ "MIT" ]
DLPUIT/TrainingField2019
171NE_xiongxinqiang/StudentMansge/NewFormDB/EditMode.cs
107
C#
using MahApps.Metro.Controls; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows; using System.Windows.Controls; using System.Windows.Data; using System.Windows.Documents; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Imaging; using System.Windows.Shapes; namespace DisplayCenter.UI.Solution.Views { /// <summary> /// Interaction logic for CachedImageWindow.xaml /// </summary> public partial class CachedImageWindow : MetroWindow { public CachedImageWindow() { InitializeComponent(); } } }
23.310345
56
0.727811
[ "MIT" ]
DaneSpiritGOD/SimpleEye
DisplayCenter.UI.Solution/Views/CachedImageWindow.xaml.cs
678
C#
using Microsoft.Management.Infrastructure; using Microsoft.Management.Infrastructure.Options; using SimCim.Core; using System; using System.Collections.Generic; using System.Linq; using System.Reactive.Linq; namespace SimCim.Root.StandardCimV2 { public struct MSFTNetConSecRuleMMAuthSetAssociation { private static AssociationResolver _resolver = new AssociationResolver("MSFT_NetConSecRuleMMAuthSet", "MSFT_NetConSecRule", "MSFT_NetIKEP1AuthSet", "GroupComponent", "PartComponent"); private IInfrastructureObjectScope _scope; public MSFTNetConSecRuleMMAuthSetAssociation(IInfrastructureObjectScope scope) { _scope = scope; } public IEnumerable<MSFTNetIKEP1AuthSet> PartComponent(MSFTNetConSecRule inGroupComponent, CimOperationOptions options = null) { var scope = _scope; var instances = _resolver.ResolveTarget(scope, inGroupComponent.AsCimInstance(), options); return instances.Select(i => (MSFTNetIKEP1AuthSet)scope.Mapper.Create(scope, i)); } public IEnumerable<MSFTNetConSecRule> GroupComponent(MSFTNetIKEP1AuthSet inPartComponent, CimOperationOptions options = null) { var scope = _scope; var instances = _resolver.ResolveSource(scope, inPartComponent.AsCimInstance(), options); return instances.Select(i => (MSFTNetConSecRule)scope.Mapper.Create(scope, i)); } public IObservable<MSFTNetIKEP1AuthSet> PartComponentAsync(MSFTNetConSecRule inGroupComponent, CimOperationOptions options = null) { var scope = _scope; var instances = _resolver.ResolveTargetAsync(scope, inGroupComponent.AsCimInstance(), options); return instances.Select(i => (MSFTNetIKEP1AuthSet)scope.Mapper.Create(scope, i)); } public IObservable<MSFTNetConSecRule> GroupComponentAsync(MSFTNetIKEP1AuthSet inPartComponent, CimOperationOptions options = null) { var scope = _scope; var instances = _resolver.ResolveSourceAsync(scope, inPartComponent.AsCimInstance(), options); return instances.Select(i => (MSFTNetConSecRule)scope.Mapper.Create(scope, i)); } } }
47.75
192
0.702443
[ "Apache-2.0" ]
simonferquel/simcim
SimCim.Root.StandardCimV2/AssociationMSFTNetConSecRuleMMAuthSet.cs
2,294
C#
using System.Net.Http; using System.Net.Http.Headers; using System.Threading; using System.Threading.Tasks; using Altinn.Common.AccessTokenClient.Services; using Altinn.Studio.Designer.Configuration; using Altinn.Studio.Designer.TypedHttpClients.AltinnAuthentication; using Microsoft.Extensions.Options; namespace Altinn.Studio.Designer.TypedHttpClients.DelegatingHandlers { /// <summary> /// Adds a Bearer token to the Authorization header /// </summary> public class PlatformBearerTokenHandler : DelegatingHandler { private readonly IAltinnAuthenticationClient _altinnAuthenticationClient; private readonly IAccessTokenGenerator _accesTokenGenerator; private readonly GeneralSettings _generalSettings; private const string AccessTokenIssuerProd = "studio"; private const string AccessTokenIssuerDev = "dev-studio"; private const string AccessTokenApp = "studio.designer"; /// <summary> /// Constructor /// </summary> public PlatformBearerTokenHandler( IAccessTokenGenerator accessTokenGenerator, IAltinnAuthenticationClient altinnAuthenticationClient, IOptions<GeneralSettings> generalSettings) { _altinnAuthenticationClient = altinnAuthenticationClient; _accesTokenGenerator = accessTokenGenerator; _generalSettings = generalSettings.Value; } /// <summary> /// Checks to see if response is success /// Otherwise, throws Exception /// </summary> /// <param name="request">System.Net.Http.HttpResponseMessage</param> /// <param name="cancellationToken">System.Threading.CancellationToken</param> /// <returns>HttpResponseMessage</returns> protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) { string issuer = _generalSettings.HostName.Contains("dev") ? AccessTokenIssuerDev : AccessTokenIssuerProd; string designerToken = _accesTokenGenerator.GenerateAccessToken(issuer, AccessTokenApp); string altinnToken = await _altinnAuthenticationClient.ConvertTokenAsync(designerToken, request.RequestUri); request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", altinnToken); return await base.SendAsync(request, cancellationToken); } } }
45.481481
133
0.720684
[ "BSD-3-Clause" ]
TheTechArch/altinn-studio
src/studio/src/designer/backend/TypedHttpClients/DelegatingHandlers/PlatformBearerTokenHandler.cs
2,456
C#
using System.ComponentModel; namespace DataWF.Gui { public class ListEditorEventArgs : CancelEventArgs { public ListEditorEventArgs() : this(null) { } public ListEditorEventArgs(object item) { Item = item; } public object Item { get; set; } } }
17.55
55
0.529915
[ "MIT" ]
alexandrvslv/datawf
DataWF.Gui/Editors/ListEditorEventArgs.cs
353
C#
using System; using System.Collections.Generic; using System.Text; namespace Ace.AutoMapper { public class MapperDescritor { public MapperDescritor(Type sourceType, Type targetType, bool reverseMap) { this.SourceType = sourceType; this.TargetType = targetType; this.ReverseMap = reverseMap; this.MemberRelationships = new List<MapperMemberRelationship>(); } public Type SourceType { get; private set; } public Type TargetType { get; private set; } public bool ReverseMap { get; set; } public List<MapperMemberRelationship> MemberRelationships { get; private set; } } }
30.869565
88
0.633803
[ "Apache-2.0" ]
a574676848/Ace
src/DotNetCore/Ace.AutoMapper/MapperDescritor.cs
712
C#
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Runtime.InteropServices.WindowsRuntime; using Windows.Foundation; using Windows.Foundation.Collections; using Windows.UI.Xaml; using Windows.UI.Xaml.Controls; using Windows.UI.Xaml.Controls.Primitives; using Windows.UI.Xaml.Data; using Windows.UI.Xaml.Input; using Windows.UI.Xaml.Media; using Windows.UI.Xaml.Navigation; // The Blank Page item template is documented at http://go.microsoft.com/fwlink/?LinkId=402352&clcid=0x409 namespace StepperDemo.UWP { /// <summary> /// An empty page that can be used on its own or navigated to within a Frame. /// </summary> public sealed partial class MainPage : Xamarin.Forms.Platform.UWP.WindowsPage { public MainPage() { this.InitializeComponent(); LoadApplication(new StepperDemo.App()); } } }
27.606061
106
0.723381
[ "Apache-2.0" ]
NoleHealth/xamarin-forms-book-preview-2
Chapter15/StepperDemo/StepperDemo/StepperDemo.UWP/MainPage.xaml.cs
913
C#
//----------------------------------------------------------------------------- // FILE: InternalPendingActivityInfo.cs // CONTRIBUTOR: Jeff Lill // COPYRIGHT: Copyright (c) 2005-2022 by neonFORGE LLC. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. using System; using System.Collections.Generic; using System.ComponentModel; using Newtonsoft.Json; using Neon.Cadence; using Neon.Common; namespace Neon.Cadence.Internal { /// <summary> /// <b>INTERNAL USE ONLY:</b> Describes an executing activity. /// </summary> internal class InternalPendingActivityInfo { /// <summary> /// The activity ID. /// </summary> [JsonProperty(PropertyName = "activityID", DefaultValueHandling = DefaultValueHandling.IgnoreAndPopulate)] [DefaultValue(null)] public string ActivityID { get; set; } /// <summary> /// The activity type. /// </summary> [JsonProperty(PropertyName = "activityType", DefaultValueHandling = DefaultValueHandling.IgnoreAndPopulate)] [DefaultValue(null)] public InternalActivityType ActivityType { get; set; } /// <summary> /// The activity state. /// </summary> [JsonProperty(PropertyName = "state", DefaultValueHandling = DefaultValueHandling.IgnoreAndPopulate)] [DefaultValue(InternalPendingActivityState.SCHEDULED)] public InternalPendingActivityState State { get; set; } /// <summary> /// Details from the last activity heartbeart. /// </summary> [JsonProperty(PropertyName = "heartbeatDetails", DefaultValueHandling = DefaultValueHandling.IgnoreAndPopulate)] [DefaultValue(null)] public byte[] HeartbeatDetails { get; set; } /// <summary> /// Time when the last activity heartbeat was received. /// </summary> [JsonProperty(PropertyName = "lastHeartbeatTimestamp", DefaultValueHandling = DefaultValueHandling.IgnoreAndPopulate)] [DefaultValue(0)] public long LastHeartbeatTimestamp { get; set; } /// <summary> /// Time when the activity was most recently started. /// </summary> [JsonProperty(PropertyName = "lastStartedTimestamp", DefaultValueHandling = DefaultValueHandling.IgnoreAndPopulate)] [DefaultValue(0)] public long LastStartedTimestamp { get; set; } /// <summary> /// The number of times the activity has been started/restarted. /// </summary> [JsonProperty(PropertyName = "attempt", DefaultValueHandling = DefaultValueHandling.IgnoreAndPopulate)] [DefaultValue(0)] public int Attempt { get; set; } /// <summary> /// The maximum times the activity may be started. /// </summary> [JsonProperty(PropertyName = "maximumAttempts", DefaultValueHandling = DefaultValueHandling.IgnoreAndPopulate)] [DefaultValue(0)] public int MaximumAttempts { get; set; } /// <summary> /// Time when the activity is scheduled to run. /// </summary> [JsonProperty(PropertyName = "scheduledTimestamp", DefaultValueHandling = DefaultValueHandling.IgnoreAndPopulate)] [DefaultValue(0)] public long ScheduledTimestamp { get; set; } /// <summary> /// Time when the activity must complete. /// </summary> [JsonProperty(PropertyName = "expirationTimestamp", DefaultValueHandling = DefaultValueHandling.IgnoreAndPopulate)] [DefaultValue(0)] public long ExpirationTimestamp { get; set; } /// <summary> /// Converts the instance into the corresponding public <see cref="PendingActivityInfo"/>. /// </summary> public PendingActivityInfo ToPublic() { return new PendingActivityInfo() { ActivityID = this.ActivityID, Name = this.ActivityType?.Name, Status = (ActivityStatus)this.State, HeartbeatDetails = this.HeartbeatDetails, LastHeartbeatTimeUtc = new DateTime(this.LastHeartbeatTimestamp), LastStartedTimeUtc = new DateTime(this.LastStartedTimestamp), Attempt = this.Attempt, MaximumAttempts = this.MaximumAttempts, ScheduledTimeUtc = new DateTime(this.ScheduledTimestamp), ExpirationTimeUtc = new DateTime(this.ExpirationTimestamp) }; } } }
40.808
136
0.631249
[ "Apache-2.0" ]
codelastnight/neonKUBE
Lib/Neon.Cadence/Internal/InternalPendingActivityInfo.cs
5,103
C#
using System.Collections; using System.Collections.Generic; using UnityEngine; public interface ICar { void ApplySteer(); void Drive(); void Break(); }
15.090909
33
0.710843
[ "MIT" ]
ToniGalmes/GlobalGameJam2020
GlobalGameJam/Assets/Scripts/ICar.cs
168
C#
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for license information. using Microsoft.Azure.Management.Compute; using Microsoft.Azure.Management.Compute.Models; using Microsoft.Azure.Management.Network; using Microsoft.Azure.Management.Network.Models; using Microsoft.Azure.Management.ResourceManager; using Microsoft.Azure.Management.ResourceManager.Models; using Microsoft.Azure.Management.Storage; using Microsoft.Azure.Management.Storage.Models; using Microsoft.Rest.ClientRuntime.Azure.TestFramework; using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Net; using System.Reflection; using Xunit; using CM=Microsoft.Azure.Management.Compute.Models; using NM=Microsoft.Azure.Management.Network.Models; namespace Compute.Tests { public class VMTestBase { protected const string TestPrefix = "crptestar"; protected const string PLACEHOLDER = "[PLACEHOLDER]"; protected const string ComputerName = "Test"; protected ResourceManagementClient m_ResourcesClient; protected ComputeManagementClient m_CrpClient; protected StorageManagementClient m_SrpClient; protected NetworkManagementClient m_NrpClient; protected bool m_initialized = false; protected object m_lock = new object(); protected string m_subId; protected string m_location; ImageReference m_windowsImageReference, m_linuxImageReference; protected void EnsureClientsInitialized(MockContext context) { if (!m_initialized) { lock (m_lock) { if (!m_initialized) { m_ResourcesClient = ComputeManagementTestUtilities.GetResourceManagementClient(context, new RecordedDelegatingHandler { StatusCodeToReturn = HttpStatusCode.OK }); m_CrpClient = ComputeManagementTestUtilities.GetComputeManagementClient(context, new RecordedDelegatingHandler { StatusCodeToReturn = HttpStatusCode.OK }); m_SrpClient = ComputeManagementTestUtilities.GetStorageManagementClient(context, new RecordedDelegatingHandler { StatusCodeToReturn = HttpStatusCode.OK }); m_NrpClient = ComputeManagementTestUtilities.GetNetworkManagementClient(context, new RecordedDelegatingHandler { StatusCodeToReturn = HttpStatusCode.OK }); m_subId = m_CrpClient.SubscriptionId; if (string.IsNullOrEmpty(Environment.GetEnvironmentVariable("AZURE_VM_TEST_LOCATION"))) { m_location = ComputeManagementTestUtilities.DefaultLocation; } else { m_location = Environment.GetEnvironmentVariable("AZURE_VM_TEST_LOCATION").Replace(" ", ""); } } } } } protected ImageReference FindVMImage(string publisher, string offer, string sku) { var query = new Microsoft.Rest.Azure.OData.ODataQuery<VirtualMachineImageResource>(); query.Top = 1; var images = m_CrpClient.VirtualMachineImages.List( location: m_location, publisherName: publisher, offer: offer, skus: sku, odataQuery: query); var image = images.First(); return new ImageReference { Publisher = publisher, Offer = offer, Sku = sku, Version = image.Name }; } protected ImageReference GetPlatformVMImage(bool useWindowsImage) { if (useWindowsImage) { if (m_windowsImageReference == null) { Trace.TraceInformation("Querying available Windows Server image from PIR..."); m_windowsImageReference = FindVMImage("MicrosoftWindowsServer", "WindowsServer", "2012-R2-Datacenter"); } return m_windowsImageReference; } if (m_linuxImageReference == null) { Trace.TraceInformation("Querying available Ubuntu image from PIR..."); // If this sku disappears, query latest with // GET https://management.azure.com/subscriptions/<subId>/providers/Microsoft.Compute/locations/SoutheastAsia/publishers/Canonical/artifacttypes/vmimage/offers/UbuntuServer/skus?api-version=2015-06-15 m_linuxImageReference = FindVMImage("Canonical", "UbuntuServer", "17.04"); } return m_linuxImageReference; } protected DiagnosticsProfile GetDiagnosticsProfile(string storageAccountName) { return new DiagnosticsProfile { BootDiagnostics = new BootDiagnostics { Enabled = true, StorageUri = string.Format(Constants.StorageAccountBlobUriTemplate, storageAccountName) } }; } protected DiskEncryptionSettings GetEncryptionSettings(bool addKek = false) { string testVaultId = @"/subscriptions/" + this.m_subId + @"/resourceGroups/RgTest1/providers/Microsoft.KeyVault/vaults/TestVault123"; string encryptionKeyFakeUri = @"https://testvault123.vault.azure.net/secrets/Test1/514ceb769c984379a7e0230bdd703272"; DiskEncryptionSettings diskEncryptionSettings = new DiskEncryptionSettings { DiskEncryptionKey = new KeyVaultSecretReference { SecretUrl = encryptionKeyFakeUri, SourceVault = new Microsoft.Azure.Management.Compute.Models.SubResource { Id = testVaultId } } }; if (addKek) { string nonExistentKekUri = @"https://testvault123.vault.azure.net/keys/TestKey/514ceb769c984379a7e0230bdd703272"; diskEncryptionSettings.KeyEncryptionKey = new KeyVaultKeyReference { KeyUrl = nonExistentKekUri, SourceVault = new Microsoft.Azure.Management.Compute.Models.SubResource { Id = testVaultId } }; } return diskEncryptionSettings; } protected StorageAccount CreateStorageAccount(string rgName, string storageAccountName) { try { // Create the resource Group. var resourceGroup = m_ResourcesClient.ResourceGroups.CreateOrUpdate( rgName, new ResourceGroup { Location = m_location, Tags = new Dictionary<string, string>() { { rgName, DateTime.UtcNow.ToString("u") } } }); var stoInput = new StorageAccountCreateParameters { Location = m_location, AccountType = AccountType.StandardGRS }; StorageAccount storageAccountOutput = m_SrpClient.StorageAccounts.Create(rgName, storageAccountName, stoInput); bool created = false; while (!created) { ComputeManagementTestUtilities.WaitSeconds(10); var stos = m_SrpClient.StorageAccounts.ListByResourceGroup(rgName); created = stos.Any( t => StringComparer.OrdinalIgnoreCase.Equals(t.Name, storageAccountName)); } return m_SrpClient.StorageAccounts.GetProperties(rgName, storageAccountName); } catch { m_ResourcesClient.ResourceGroups.Delete(rgName); throw; } } protected VirtualMachine CreateVM( string rgName, string asName, StorageAccount storageAccount, ImageReference imageRef, out VirtualMachine inputVM, Action<VirtualMachine> vmCustomizer = null, bool createWithPublicIpAddress = false, bool waitForCompletion = true, bool hasManagedDisks = false) { return CreateVM(rgName, asName, storageAccount.Name, imageRef, out inputVM, vmCustomizer, createWithPublicIpAddress, waitForCompletion, hasManagedDisks); } protected VirtualMachine CreateVM( string rgName, string asName, string storageAccountName, ImageReference imageRef, out VirtualMachine inputVM, Action<VirtualMachine> vmCustomizer = null, bool createWithPublicIpAddress = false, bool waitForCompletion = true, bool hasManagedDisks = false, string vmSize = VirtualMachineSizeTypes.StandardA0, string storageAccountType = StorageAccountTypes.StandardLRS, bool? writeAcceleratorEnabled = null, IList<string> zones = null) { try { // Create the resource Group, it might have been already created during StorageAccount creation. m_ResourcesClient.ResourceGroups.CreateOrUpdate( rgName, new ResourceGroup { Location = m_location, Tags = new Dictionary<string, string>() { { rgName, DateTime.UtcNow.ToString("u") } } }); PublicIPAddress getPublicIpAddressResponse = createWithPublicIpAddress ? null : CreatePublicIP(rgName); // Do not add Dns server for managed disks, as they cannot resolve managed disk url ( https://md-xyz ) without // explicitly setting up the rules for resolution. The VMs upon booting would need to contact the // DNS server to access the VMStatus agent blob. Without proper Dns resolution, The VMs cannot access the // VMStatus agent blob and there by fail to boot. bool addDnsServer = !hasManagedDisks; Subnet subnetResponse = CreateVNET(rgName, addDnsServer); NetworkInterface nicResponse = CreateNIC( rgName, subnetResponse, getPublicIpAddressResponse != null ? getPublicIpAddressResponse.IpAddress : null); string asetId = CreateAvailabilitySet(rgName, asName, hasManagedDisks); inputVM = CreateDefaultVMInput(rgName, storageAccountName, imageRef, asetId, nicResponse.Id, hasManagedDisks, vmSize, storageAccountType, writeAcceleratorEnabled); if (zones != null) { inputVM.AvailabilitySet = null; inputVM.HardwareProfile.VmSize = VirtualMachineSizeTypes.StandardA1V2; inputVM.Zones = zones; } if (vmCustomizer != null) { vmCustomizer(inputVM); } string expectedVMReferenceId = Helpers.GetVMReferenceId(m_subId, rgName, inputVM.Name); VirtualMachine createOrUpdateResponse = null; if (waitForCompletion) { // CreateOrUpdate polls for the operation completion and returns once the operation reaches a terminal state createOrUpdateResponse = m_CrpClient.VirtualMachines.CreateOrUpdate(rgName, inputVM.Name, inputVM); } else { // BeginCreateOrUpdate returns immediately after the request is accepted by CRP createOrUpdateResponse = m_CrpClient.VirtualMachines.BeginCreateOrUpdate(rgName, inputVM.Name, inputVM); } Assert.True(createOrUpdateResponse.Name == inputVM.Name); Assert.True(createOrUpdateResponse.Location == inputVM.Location.ToLower().Replace(" ", "") || createOrUpdateResponse.Location.ToLower() == inputVM.Location.ToLower()); if (zones == null) { Assert.True(createOrUpdateResponse.AvailabilitySet.Id.ToLowerInvariant() == asetId.ToLowerInvariant()); } else { Assert.True(createOrUpdateResponse.Zones.Count == 1); Assert.True(createOrUpdateResponse.Zones.FirstOrDefault() == zones.FirstOrDefault()); } // The intent here is to validate that the GET response is as expected. var getResponse = m_CrpClient.VirtualMachines.Get(rgName, inputVM.Name); ValidateVM(inputVM, getResponse, expectedVMReferenceId, hasManagedDisks, writeAcceleratorEnabled: writeAcceleratorEnabled, hasUserDefinedAS: zones == null); return getResponse; } catch { // Just trigger DeleteRG, rest would be taken care of by ARM m_ResourcesClient.ResourceGroups.BeginDelete(rgName); throw; } } protected PublicIPAddress CreatePublicIP(string rgName) { // Create publicIP string publicIpName = ComputeManagementTestUtilities.GenerateName("pip"); string domainNameLabel = ComputeManagementTestUtilities.GenerateName("dn"); var publicIp = new PublicIPAddress() { Location = m_location, Tags = new Dictionary<string, string>() { {"key", "value"} }, PublicIPAllocationMethod = IPAllocationMethod.Dynamic, DnsSettings = new PublicIPAddressDnsSettings() { DomainNameLabel = domainNameLabel } }; var putPublicIpAddressResponse = m_NrpClient.PublicIPAddresses.CreateOrUpdate(rgName, publicIpName, publicIp); var getPublicIpAddressResponse = m_NrpClient.PublicIPAddresses.Get(rgName, publicIpName); return getPublicIpAddressResponse; } protected Subnet CreateVNET(string rgName, bool addDnsServer = true) { // Create Vnet // Populate parameter for Put Vnet string vnetName = ComputeManagementTestUtilities.GenerateName("vn"); string subnetName = ComputeManagementTestUtilities.GenerateName("sn"); var vnet = new VirtualNetwork() { Location = m_location, AddressSpace = new AddressSpace() { AddressPrefixes = new List<string>() { "10.0.0.0/16", } }, DhcpOptions = !addDnsServer ? null : new DhcpOptions() { DnsServers = new List<string>() { "10.1.1.1", "10.1.2.4" } }, Subnets = new List<Subnet>() { new Subnet() { Name = subnetName, AddressPrefix = "10.0.0.0/24", } } }; var putVnetResponse = m_NrpClient.VirtualNetworks.CreateOrUpdate(rgName, vnetName, vnet); var getSubnetResponse = m_NrpClient.Subnets.Get(rgName, vnetName, subnetName); return getSubnetResponse; } protected VirtualNetwork CreateVNETWithSubnets(string rgName, int subnetCount = 2) { // Create Vnet // Populate parameter for Put Vnet string vnetName = ComputeManagementTestUtilities.GenerateName("vn"); var vnet = new VirtualNetwork() { Location = m_location, AddressSpace = new AddressSpace() { AddressPrefixes = new List<string>() { "10.0.0.0/16", } }, DhcpOptions = new DhcpOptions() { DnsServers = new List<string>() { "10.1.1.1", "10.1.2.4" } }, }; vnet.Subnets = new List<Subnet>(); for (int i = 1; i <= subnetCount; i++) { Subnet subnet = new Subnet() { Name = ComputeManagementTestUtilities.GenerateName("sn" + i), AddressPrefix = "10.0." + i + ".0/24", }; vnet.Subnets.Add(subnet); } var putVnetResponse = m_NrpClient.VirtualNetworks.CreateOrUpdate(rgName, vnetName, vnet); return putVnetResponse; } protected NetworkSecurityGroup CreateNsg(string rgName, string nsgName = null) { nsgName = nsgName ?? ComputeManagementTestUtilities.GenerateName("nsg"); var nsgParameters = new NetworkSecurityGroup() { Location = m_location }; var putNSgResponse = m_NrpClient.NetworkSecurityGroups.CreateOrUpdate(rgName, nsgName, nsgParameters); var getNsgResponse = m_NrpClient.NetworkSecurityGroups.Get(rgName, nsgName); return getNsgResponse; } protected NetworkInterface CreateNIC(string rgName, Subnet subnet, string publicIPaddress, string nicname = null, NetworkSecurityGroup nsg = null) { // Create Nic nicname = nicname ?? ComputeManagementTestUtilities.GenerateName("nic"); string ipConfigName = ComputeManagementTestUtilities.GenerateName("ip"); var nicParameters = new NetworkInterface() { Location = m_location, Tags = new Dictionary<string, string>() { { "key" ,"value" } }, IpConfigurations = new List<NetworkInterfaceIPConfiguration>() { new NetworkInterfaceIPConfiguration() { Name = ipConfigName, PrivateIPAllocationMethod = IPAllocationMethod.Dynamic, Subnet = subnet, } }, NetworkSecurityGroup = nsg }; if (publicIPaddress != null) { nicParameters.IpConfigurations[0].PublicIPAddress = new Microsoft.Azure.Management.Network.Models.PublicIPAddress() { Id = publicIPaddress }; } var putNicResponse = m_NrpClient.NetworkInterfaces.CreateOrUpdate(rgName, nicname, nicParameters); var getNicResponse = m_NrpClient.NetworkInterfaces.Get(rgName, nicname); return getNicResponse; } protected NetworkInterface CreateMultiIpConfigNIC(string rgName, Subnet subnet, string nicname) { // Create Nic nicname = nicname ?? ComputeManagementTestUtilities.GenerateName("nic"); string ipConfigName = ComputeManagementTestUtilities.GenerateName("ip"); string ipConfigName2 = ComputeManagementTestUtilities.GenerateName("ip2"); var nicParameters = new NetworkInterface() { Location = m_location, Tags = new Dictionary<string, string>() { { "key" ,"value" } }, IpConfigurations = new List<NetworkInterfaceIPConfiguration>() { new NetworkInterfaceIPConfiguration() { Name = ipConfigName, Primary = true, PrivateIPAllocationMethod = IPAllocationMethod.Dynamic, Subnet = subnet, }, new NetworkInterfaceIPConfiguration() { Name = ipConfigName2, Primary = false, PrivateIPAllocationMethod = IPAllocationMethod.Dynamic, Subnet = subnet, } } }; var putNicResponse = m_NrpClient.NetworkInterfaces.CreateOrUpdate(rgName, nicname, nicParameters); var getNicResponse = m_NrpClient.NetworkInterfaces.Get(rgName, nicname); return getNicResponse; } private static string GetChildAppGwResourceId(string subscriptionId, string resourceGroupName, string appGwname, string childResourceType, string childResourceName) { return string.Format( "/subscriptions/{0}/resourceGroups/{1}/providers/Microsoft.Network/applicationGateways/{2}/{3}/{4}", subscriptionId, resourceGroupName, appGwname, childResourceType, childResourceName); } protected ApplicationGateway CreateApplicationGateway(string rgName, Subnet subnet, string gatewayName = null) { gatewayName = gatewayName ?? ComputeManagementTestUtilities.GenerateName("gw"); var gatewayIPConfigName = ComputeManagementTestUtilities.GenerateName("gwIp"); var frontendIPConfigName = ComputeManagementTestUtilities.GenerateName("fIp"); var frontendPortName = ComputeManagementTestUtilities.GenerateName("fPort"); var backendAddressPoolName = ComputeManagementTestUtilities.GenerateName("pool"); var backendHttpSettingsName = ComputeManagementTestUtilities.GenerateName("setting"); var requestRoutingRuleName = ComputeManagementTestUtilities.GenerateName("rule"); var httpListenerName = ComputeManagementTestUtilities.GenerateName("listener"); var gatewayIPConfig = new ApplicationGatewayIPConfiguration() { Name = gatewayIPConfigName, Subnet = new Microsoft.Azure.Management.Network.Models.SubResource { Id = subnet.Id }, }; var frontendIPConfig = new ApplicationGatewayFrontendIPConfiguration() { Name = frontendIPConfigName, PrivateIPAllocationMethod = IPAllocationMethod.Dynamic, Subnet = new Microsoft.Azure.Management.Network.Models.SubResource { Id = subnet.Id } }; ApplicationGatewayFrontendPort frontendPort = new ApplicationGatewayFrontendPort() { Name = frontendPortName, Port = 80 }; var backendAddressPool = new ApplicationGatewayBackendAddressPool() { Name = backendAddressPoolName, }; var backendHttpSettings = new ApplicationGatewayBackendHttpSettings() { Name = backendHttpSettingsName, Port = 80, Protocol = ApplicationGatewayProtocol.Http, CookieBasedAffinity = ApplicationGatewayCookieBasedAffinity.Disabled, }; var httpListener = new ApplicationGatewayHttpListener() { Name = httpListenerName, FrontendPort = new Microsoft.Azure.Management.Network.Models.SubResource { Id = GetChildAppGwResourceId(m_subId, rgName, gatewayName, "frontendPorts", frontendPortName) }, FrontendIPConfiguration = new Microsoft.Azure.Management.Network.Models.SubResource { Id = GetChildAppGwResourceId(m_subId, rgName, gatewayName, "frontendIPConfigurations", frontendIPConfigName) }, SslCertificate = null, Protocol = ApplicationGatewayProtocol.Http }; var requestRoutingRules = new ApplicationGatewayRequestRoutingRule() { Name = requestRoutingRuleName, RuleType = ApplicationGatewayRequestRoutingRuleType.Basic, HttpListener = new Microsoft.Azure.Management.Network.Models.SubResource { Id = GetChildAppGwResourceId(m_subId, rgName, gatewayName, "httpListeners", httpListenerName) }, BackendAddressPool = new Microsoft.Azure.Management.Network.Models.SubResource { Id = GetChildAppGwResourceId(m_subId, rgName, gatewayName, "backendAddressPools", backendAddressPoolName) }, BackendHttpSettings = new Microsoft.Azure.Management.Network.Models.SubResource { Id = GetChildAppGwResourceId(m_subId, rgName, gatewayName, "backendHttpSettingsCollection", backendHttpSettingsName) } }; var appGw = new ApplicationGateway() { Location = m_location, Sku = new ApplicationGatewaySku() { Name = ApplicationGatewaySkuName.StandardSmall, Tier = ApplicationGatewayTier.Standard, Capacity = 2 }, GatewayIPConfigurations = new List<ApplicationGatewayIPConfiguration>() { gatewayIPConfig, }, FrontendIPConfigurations = new List<ApplicationGatewayFrontendIPConfiguration>() { frontendIPConfig, }, FrontendPorts = new List<ApplicationGatewayFrontendPort> { frontendPort, }, BackendAddressPools = new List<ApplicationGatewayBackendAddressPool> { backendAddressPool, }, BackendHttpSettingsCollection = new List<ApplicationGatewayBackendHttpSettings> { backendHttpSettings, }, HttpListeners = new List<ApplicationGatewayHttpListener> { httpListener, }, RequestRoutingRules = new List<ApplicationGatewayRequestRoutingRule>() { requestRoutingRules, } }; var putGwResponse = m_NrpClient.ApplicationGateways.CreateOrUpdate(rgName, gatewayName, appGw); var getGwResponse = m_NrpClient.ApplicationGateways.Get(rgName, gatewayName); return getGwResponse; } protected LoadBalancer CreatePublicLoadBalancerWithProbe(string rgName, PublicIPAddress publicIPAddress) { var loadBalancerName = ComputeManagementTestUtilities.GenerateName("lb"); var frontendIPConfigName = ComputeManagementTestUtilities.GenerateName("feip"); var backendAddressPoolName = ComputeManagementTestUtilities.GenerateName("beap"); var loadBalancingRuleName = ComputeManagementTestUtilities.GenerateName("lbr"); var loadBalancerProbeName = ComputeManagementTestUtilities.GenerateName("lbp"); var frontendIPConfigId = $"/subscriptions/{m_subId}/resourceGroups/{rgName}/providers/Microsoft.Network/loadBalancers/{loadBalancerName}/frontendIPConfigurations/{frontendIPConfigName}"; var backendAddressPoolId = $"/subscriptions/{m_subId}/resourceGroups/{rgName}/providers/Microsoft.Network/loadBalancers/{loadBalancerName}/backendAddressPools/{backendAddressPoolName}"; var probeId = $"/subscriptions/{m_subId}/resourceGroups/{rgName}/providers/Microsoft.Network/loadBalancers/{loadBalancerName}/probes/{loadBalancerProbeName}"; var putLBResponse = m_NrpClient.LoadBalancers.CreateOrUpdate(rgName, loadBalancerName, new LoadBalancer { Location = m_location, FrontendIPConfigurations = new List<FrontendIPConfiguration> { new FrontendIPConfiguration { Name = frontendIPConfigName, PublicIPAddress = publicIPAddress } }, BackendAddressPools = new List<BackendAddressPool> { new BackendAddressPool { Name = backendAddressPoolName } }, LoadBalancingRules = new List<LoadBalancingRule> { new LoadBalancingRule { Name = loadBalancingRuleName, LoadDistribution = "Default", FrontendIPConfiguration = new NM.SubResource { Id = frontendIPConfigId }, BackendAddressPool = new NM.SubResource { Id = backendAddressPoolId }, Protocol = "Tcp", FrontendPort = 80, BackendPort = 80, EnableFloatingIP = false, IdleTimeoutInMinutes = 5, Probe = new NM.SubResource { Id = probeId } } }, Probes = new List<Probe> { new Probe { Port = 3389, // RDP port IntervalInSeconds = 5, NumberOfProbes = 2, Name = loadBalancerProbeName, Protocol = "Tcp", } } }); var getLBResponse = m_NrpClient.LoadBalancers.Get(rgName, loadBalancerName); return getLBResponse; } protected string CreateAvailabilitySet(string rgName, string asName, bool hasManagedDisks = false) { // Setup availability set var inputAvailabilitySet = new AvailabilitySet { Location = m_location, Tags = new Dictionary<string, string>() { {"RG", "rg"}, {"testTag", "1"} }, PlatformFaultDomainCount = hasManagedDisks ? 2 : 3, PlatformUpdateDomainCount = 5, Sku = new CM.Sku { Name = hasManagedDisks ? "Aligned" : "Classic" } }; // Create an Availability Set and then create a VM inside this availability set var asCreateOrUpdateResponse = m_CrpClient.AvailabilitySets.CreateOrUpdate( rgName, asName, inputAvailabilitySet ); var asetId = Helpers.GetAvailabilitySetRef(m_subId, rgName, asCreateOrUpdateResponse.Name); return asetId; } protected VirtualMachine CreateDefaultVMInput(string rgName, string storageAccountName, ImageReference imageRef, string asetId, string nicId, bool hasManagedDisks = false, string vmSize = VirtualMachineSizeTypes.StandardA0, string storageAccountType = StorageAccountTypes.StandardLRS, bool? writeAcceleratorEnabled = null) { // Generate Container name to hold disk VHds string containerName = ComputeManagementTestUtilities.GenerateName(TestPrefix); var vhdContainer = "https://" + storageAccountName + ".blob.core.windows.net/" + containerName; var vhduri = vhdContainer + string.Format("/{0}.vhd", ComputeManagementTestUtilities.GenerateName(TestPrefix)); var osVhduri = vhdContainer + string.Format("/os{0}.vhd", ComputeManagementTestUtilities.GenerateName(TestPrefix)); if (writeAcceleratorEnabled.HasValue) { // WriteAccelerator is only allowed on VMs with Managed disks Assert.True(hasManagedDisks); } var vm = new VirtualMachine { Location = m_location, Tags = new Dictionary<string, string>() { { "RG", "rg" }, { "testTag", "1" } }, AvailabilitySet = new Microsoft.Azure.Management.Compute.Models.SubResource() { Id = asetId }, HardwareProfile = new HardwareProfile { VmSize = vmSize }, StorageProfile = new StorageProfile { ImageReference = imageRef, OsDisk = new OSDisk { Caching = CachingTypes.None, WriteAcceleratorEnabled = writeAcceleratorEnabled, CreateOption = DiskCreateOptionTypes.FromImage, Name = "test", Vhd = hasManagedDisks ? null : new VirtualHardDisk { Uri = osVhduri }, ManagedDisk = !hasManagedDisks ? null : new ManagedDiskParameters { StorageAccountType = storageAccountType } }, DataDisks = !hasManagedDisks ? null : new List<DataDisk>() { new DataDisk() { Caching = CachingTypes.None, WriteAcceleratorEnabled = writeAcceleratorEnabled, CreateOption = DiskCreateOptionTypes.Empty, Lun = 0, DiskSizeGB = 30, ManagedDisk = new ManagedDiskParameters() { StorageAccountType = storageAccountType } } }, }, NetworkProfile = new NetworkProfile { NetworkInterfaces = new List<NetworkInterfaceReference> { new NetworkInterfaceReference { Id = nicId } } }, OsProfile = new OSProfile { AdminUsername = "Foo12", AdminPassword = PLACEHOLDER, ComputerName = ComputerName } }; typeof(Microsoft.Azure.Management.Compute.Models.Resource).GetRuntimeProperty("Name").SetValue(vm, ComputeManagementTestUtilities.GenerateName("vm")); typeof(Microsoft.Azure.Management.Compute.Models.Resource).GetRuntimeProperty("Type").SetValue(vm, ComputeManagementTestUtilities.GenerateName("Microsoft.Compute/virtualMachines")); return vm; } protected void ValidateVM(VirtualMachine vm, VirtualMachine vmOut, string expectedVMReferenceId, bool hasManagedDisks = false, bool hasUserDefinedAS = true, bool? writeAcceleratorEnabled = null) { Assert.True(vmOut.LicenseType == vm.LicenseType); Assert.True(!string.IsNullOrEmpty(vmOut.ProvisioningState)); Assert.True(vmOut.HardwareProfile.VmSize == vm.HardwareProfile.VmSize); Assert.NotNull(vmOut.StorageProfile.OsDisk); if (vm.StorageProfile.OsDisk != null) { Assert.True(vmOut.StorageProfile.OsDisk.Name == vm.StorageProfile.OsDisk.Name); Assert.True(vmOut.StorageProfile.OsDisk.Caching == vm.StorageProfile.OsDisk.Caching); if (hasManagedDisks) { // vhd is null for managed disks Assert.NotNull(vmOut.StorageProfile.OsDisk.ManagedDisk); Assert.NotNull(vmOut.StorageProfile.OsDisk.ManagedDisk.StorageAccountType); if (vm.StorageProfile.OsDisk.ManagedDisk != null && vm.StorageProfile.OsDisk.ManagedDisk.StorageAccountType != null) { Assert.True(vmOut.StorageProfile.OsDisk.ManagedDisk.StorageAccountType == vm.StorageProfile.OsDisk.ManagedDisk.StorageAccountType); } else { Assert.NotNull(vmOut.StorageProfile.OsDisk.ManagedDisk.StorageAccountType); } if (vm.StorageProfile.OsDisk.ManagedDisk != null && vm.StorageProfile.OsDisk.ManagedDisk.Id != null) { Assert.True(vmOut.StorageProfile.OsDisk.ManagedDisk.Id == vm.StorageProfile.OsDisk.ManagedDisk.Id); } else { Assert.NotNull(vmOut.StorageProfile.OsDisk.ManagedDisk.Id); } if (writeAcceleratorEnabled.HasValue) { Assert.Equal(writeAcceleratorEnabled.Value, vmOut.StorageProfile.OsDisk.WriteAcceleratorEnabled); } else { Assert.Null(vmOut.StorageProfile.OsDisk.WriteAcceleratorEnabled); } } else { Assert.NotNull(vmOut.StorageProfile.OsDisk.Vhd); Assert.Equal(vm.StorageProfile.OsDisk.Vhd.Uri, vmOut.StorageProfile.OsDisk.Vhd.Uri); if (vm.StorageProfile.OsDisk.Image != null && vm.StorageProfile.OsDisk.Image.Uri != null) { Assert.Equal(vm.StorageProfile.OsDisk.Image.Uri, vmOut.StorageProfile.OsDisk.Image.Uri); } } } if (vm.StorageProfile.DataDisks != null && vm.StorageProfile.DataDisks.Any()) { foreach (var dataDisk in vm.StorageProfile.DataDisks) { var dataDiskOut = vmOut.StorageProfile.DataDisks.FirstOrDefault(d => dataDisk.Lun == d.Lun); Assert.NotNull(dataDiskOut); Assert.Equal(dataDiskOut.DiskSizeGB, dataDisk.DiskSizeGB); Assert.Equal(dataDiskOut.CreateOption, dataDisk.CreateOption); if (dataDisk.Caching != null) { Assert.Equal(dataDiskOut.Caching, dataDisk.Caching); } if (dataDisk.Name != null) { Assert.Equal(dataDiskOut.Name, dataDisk.Name); } // Disabling resharper null-ref check as it doesn't seem to understand the not-null assert above. // ReSharper disable PossibleNullReferenceException if (hasManagedDisks) { Assert.NotNull(dataDiskOut.ManagedDisk); Assert.NotNull(dataDiskOut.ManagedDisk.StorageAccountType); if (dataDisk.ManagedDisk != null && dataDisk.ManagedDisk.StorageAccountType != null) { Assert.True(dataDiskOut.ManagedDisk.StorageAccountType == dataDisk.ManagedDisk.StorageAccountType); } Assert.NotNull(dataDiskOut.ManagedDisk.Id); if (writeAcceleratorEnabled.HasValue) { Assert.Equal(writeAcceleratorEnabled.Value, dataDiskOut.WriteAcceleratorEnabled); } else { Assert.Null(vmOut.StorageProfile.OsDisk.WriteAcceleratorEnabled); } } else { Assert.NotNull(dataDiskOut.Vhd); Assert.NotNull(dataDiskOut.Vhd.Uri); if (dataDisk.Image != null && dataDisk.Image.Uri != null) { Assert.NotNull(dataDiskOut.Image); Assert.Equal(dataDisk.Image.Uri, dataDiskOut.Image.Uri); } Assert.Null(vmOut.StorageProfile.OsDisk.WriteAcceleratorEnabled); } // ReSharper enable PossibleNullReferenceException } } if(vm.OsProfile != null && vm.OsProfile.Secrets != null && vm.OsProfile.Secrets.Any()) { foreach (var secret in vm.OsProfile.Secrets) { Assert.NotNull(secret.VaultCertificates); var secretOut = vmOut.OsProfile.Secrets.FirstOrDefault(s => string.Equals(secret.SourceVault.Id, s.SourceVault.Id)); Assert.NotNull(secretOut); // Disabling resharper null-ref check as it doesn't seem to understand the not-null assert above. // ReSharper disable PossibleNullReferenceException Assert.NotNull(secretOut.VaultCertificates); var VaultCertComparer = new VaultCertComparer(); Assert.True(secretOut.VaultCertificates.SequenceEqual(secret.VaultCertificates, VaultCertComparer)); // ReSharper enable PossibleNullReferenceException } } if (hasUserDefinedAS) { Assert.NotNull(vmOut.AvailabilitySet); Assert.True(vm.AvailabilitySet.Id.ToLowerInvariant() == vmOut.AvailabilitySet.Id.ToLowerInvariant()); } ValidatePlan(vm.Plan, vmOut.Plan); Assert.NotNull(vmOut.VmId); } protected void ValidateVMInstanceView(VirtualMachine vmIn, VirtualMachine vmOut, bool hasManagedDisks = false, string expectedComputerName = null, string expectedOSName = null, string expectedOSVersion = null) { Assert.NotNull(vmOut.InstanceView); ValidateVMInstanceView(vmIn, vmOut.InstanceView, hasManagedDisks, expectedComputerName, expectedOSName, expectedOSVersion); } protected void ValidateVMInstanceView(VirtualMachine vmIn, VirtualMachineInstanceView vmInstanceView, bool hasManagedDisks = false, string expectedComputerName = null, string expectedOSName = null, string expectedOSVersion = null) { ValidateVMInstanceView(vmInstanceView, hasManagedDisks, !hasManagedDisks ? vmIn.StorageProfile.OsDisk.Name : null, expectedComputerName, expectedOSName, expectedOSVersion); } private void ValidateVMInstanceView(VirtualMachineInstanceView vmInstanceView, bool hasManagedDisks = false, string osDiskName = null, string expectedComputerName = null, string expectedOSName = null, string expectedOSVersion = null) { #if NET46 Assert.True(vmInstanceView.Statuses.Any(s => !string.IsNullOrEmpty(s.Code))); #else Assert.Contains(vmInstanceView.Statuses, s => !string.IsNullOrEmpty(s.Code)); #endif if (!hasManagedDisks) { Assert.NotNull(vmInstanceView.Disks); Assert.True(vmInstanceView.Disks.Any()); if (osDiskName != null) { #if NET46 Assert.True(vmInstanceView.Disks.Any(x => x.Name == osDiskName)); #else Assert.Contains(vmInstanceView.Disks, x => x.Name == osDiskName); #endif } DiskInstanceView diskInstanceView = vmInstanceView.Disks.First(); Assert.NotNull(diskInstanceView); Assert.NotNull(diskInstanceView.Statuses[0].DisplayStatus); Assert.NotNull(diskInstanceView.Statuses[0].Code); Assert.NotNull(diskInstanceView.Statuses[0].Level); //Assert.NotNull(diskInstanceView.Statuses[0].Message); // TODO: it's null somtimes. //Assert.NotNull(diskInstanceView.Statuses[0].Time); // TODO: it's null somtimes. } if (expectedComputerName != null) { Assert.Equal(expectedComputerName, vmInstanceView.ComputerName); } if (expectedOSName != null) { Assert.Equal(expectedOSName, vmInstanceView.OsName); } if (expectedOSVersion != null) { Assert.Equal(expectedOSVersion, vmInstanceView.OsVersion); } } protected void ValidatePlan(Microsoft.Azure.Management.Compute.Models.Plan inputPlan, Microsoft.Azure.Management.Compute.Models.Plan outPutPlan) { if (inputPlan == null || outPutPlan == null ) { Assert.Equal(inputPlan, outPutPlan); return; } Assert.Equal(inputPlan.Name, outPutPlan.Name); Assert.Equal(inputPlan.Publisher, outPutPlan.Publisher); Assert.Equal(inputPlan.Product, outPutPlan.Product); Assert.Equal(inputPlan.PromotionCode, outPutPlan.PromotionCode); } } }
44.954155
216
0.544585
[ "MIT" ]
Mattlk13/azure-sdk-for-net
src/SDKs/Compute/Compute.Tests/ScenarioTests/VMTestBase.cs
47,069
C#
using System; namespace HallOfBeorn.Models.LotR.ProductGroups { public class ScenarioPackProductGroup : ProductGroup { public ScenarioPackProductGroup() : base("Scenario Packs") { AddChildProduct(Product.TheHuntForTheDreadnaught); AddChildProduct(Product.TheDarkOfMirkwood); } } }
25.066667
63
0.619681
[ "MIT" ]
danpoage/hall-of-beorn
src/HallOfBeorn/Models/LotR/ProductGroups/ScenarioPackProductGroup.cs
378
C#
using System.Threading; using System.Windows.Forms; namespace MFDExtractor { internal interface IInstrumentFactory { IInstrument Create(InstrumentType instrumentType); } class InstrumentFactory : IInstrumentFactory { private readonly IInstrumentStateSnapshotCache _instrumentStateSnapshotCache; private readonly IRendererFactory _rendererFactory; private readonly IPerformanceCounterInstanceFactory _performanceCounterInstanceFactory; public InstrumentFactory( InstrumentStateSnapshotCache instrumentStateSnapshotCache = null, IRendererFactory rendererFactory=null, IPerformanceCounterInstanceFactory performanceCounterInstanceFactory = null) { _instrumentStateSnapshotCache = instrumentStateSnapshotCache ?? new InstrumentStateSnapshotCache(); _rendererFactory = rendererFactory ?? new RendererFactory(); _performanceCounterInstanceFactory = performanceCounterInstanceFactory ?? new PerformanceCounterInstanceInstanceFactory(); } public IInstrument Create(InstrumentType instrumentType) { var renderer = _rendererFactory.CreateRenderer(instrumentType); var instrument = new Instrument(_instrumentStateSnapshotCache) { Type = instrumentType, Renderer =renderer, RenderedFramesCounter = _performanceCounterInstanceFactory.CreatePerformanceCounterInstance(Application.ProductName, string.Format("Rendered Frames per second - {0}", instrumentType)), SkippedFramesCounter = _performanceCounterInstanceFactory.CreatePerformanceCounterInstance(Application.ProductName, string.Format("Skipped Frames per second - {0}", instrumentType)), TimeoutFramesCounter = _performanceCounterInstanceFactory.CreatePerformanceCounterInstance(Application.ProductName, string.Format("Timeout Frames per second - {0}", instrumentType)), TotalFramesCounter = _performanceCounterInstanceFactory.CreatePerformanceCounterInstance(Application.ProductName, string.Format("Total Frames per second - {0}", instrumentType)), }; return instrument; } } }
52.511628
200
0.735607
[ "MIT" ]
aliostad/deep-learning-lang-detection
data/train/csharp/90baa1f863a7674b0c601ff82e7b5ec9453771ecInstrumentFactory.cs
2,260
C#
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ using System; using System.Collections.Generic; using Aliyun.Acs.Core.Transform; using Aliyun.Acs.adb.Model.V20190315; namespace Aliyun.Acs.adb.Transform.V20190315 { public class ModifyDBClusterAccessWhiteListResponseUnmarshaller { public static ModifyDBClusterAccessWhiteListResponse Unmarshall(UnmarshallerContext context) { ModifyDBClusterAccessWhiteListResponse modifyDBClusterAccessWhiteListResponse = new ModifyDBClusterAccessWhiteListResponse(); modifyDBClusterAccessWhiteListResponse.HttpResponse = context.HttpResponse; modifyDBClusterAccessWhiteListResponse.RequestId = context.StringValue("ModifyDBClusterAccessWhiteList.RequestId"); return modifyDBClusterAccessWhiteListResponse; } } }
39.3
129
0.779262
[ "Apache-2.0" ]
bbs168/aliyun-openapi-net-sdk
aliyun-net-sdk-adb/Adb/Transform/V20190315/ModifyDBClusterAccessWhiteListResponseUnmarshaller.cs
1,572
C#
using System; using System.Reactive; using System.Reactive.Linq; using System.Threading.Tasks; using Pirac.Commands; namespace Pirac { public static partial class PublicExtensions { public static void RaiseCanExecuteChanged(this System.Windows.Input.ICommand command) { var canExecuteChanged = command as IRaiseCanExecuteChanged; if (canExecuteChanged != null) canExecuteChanged.RaiseCanExecuteChanged(); } public static IObservableCommand ToCommand(this IObservable<bool> canExecuteObservable, Func<object, Task> action) { return new ObservableCommand(canExecuteObservable, action); } public static IObservableCommand ToCommand(this IObservable<PropertyChangedData<bool>> canExecuteObservable, Func<object, Task> action) { return new ObservableCommand(canExecuteObservable.Select(pc => pc.After), action); } public static IObservableCommand ToCommand(this IObservable<bool> canExecuteObservable, Action<object> action) { return new ObservableCommand(canExecuteObservable, p => { action(p); return Task.FromResult(0); }); } public static IObservableCommand ToCommand(this IObservable<PropertyChangedData<bool>> canExecuteObservable, Action<object> action) { return new ObservableCommand(canExecuteObservable.Select(pc => pc.After), p => { action(p); return Task.FromResult(0); }); } public static IDisposable Execute<T>(this IObservable<T> observable, System.Windows.Input.ICommand command) { return observable.Do(t => { if (command.CanExecute(t)) command.Execute(t); }).Subscribe(); } public static IDisposable Execute<T>(this IObservable<T> observable, ICommand<T> command) { return observable.Do(t => { if (command.CanExecute(t)) command.Execute(t); }).Subscribe(); } public static IDisposable ExecuteAsync<T>(this IObservable<T> observable, IAsyncCommand<T> command) { return observable.SelectMany(async t => { if (command.CanExecute(t)) await command.ExecuteAsync(t); return Unit.Default; }).Subscribe(); } } }
42.685185
149
0.661171
[ "MIT" ]
distantcam/Pirac
src/Pirac/Extensions/CommandExtensions.cs
2,252
C#
using System; using System.Collections.Generic; using System.Linq; using System.Reflection; using System.Text.RegularExpressions; namespace ALE.Http { public class Route { public static readonly Regex PathParser = new Regex(@"\:(\w+?)(\W|$)"); public MethodInfo HandlerInfo; public readonly Dictionary<string, ParameterInfo> HandlerParameters; public readonly string Path; public readonly Regex PathTester; public readonly string[] Parameters; public readonly Type ControllerType; public Route(string path, string methodName, Type controllerType) { if (String.IsNullOrWhiteSpace(path)) throw new ArgumentNullException("path"); if (String.IsNullOrWhiteSpace(methodName)) throw new ArgumentNullException("methodName"); Path = path; Parameters = GetParameters(path); PathTester = CreatePathTester(path); ControllerType = controllerType; HandlerInfo = controllerType.GetMethod(methodName); HandlerParameters = HandlerInfo.GetParameters().ToDictionary(x => x.Name, x => x); if (HandlerParameters.Count == 0 || HandlerParameters.First().Value.ParameterType != typeof(Action)) { throw new InvalidOperationException("First argument of a route must be the 'next' delegate."); } } public static string[] GetParameters(string path) { var matches = PathParser.Matches(path); var results = new string[matches.Count]; for (int i = 0; i < matches.Count; i++) { results[i] = matches[i].Groups[1].Value; } return results; } public static Regex CreatePathTester(string path) { var pattern = PathParser.Replace(path, m => "(?<" + m.Groups[1].Value + @">.+)" + m.Groups[2].Value); return new Regex("^" + pattern); } public bool TryExecute(IContext context, Action next) { var req = context.Request; var res = context.Response; var path = req.Url.PathAndQuery; var isMatch = PathTester.IsMatch(path); if (isMatch) { var match = PathTester.Match(path); var args = new string[Parameters.Length]; for (int i = 0; i < Parameters.Length; i++) { var parameterName = Parameters[i]; args[i] = Uri.UnescapeDataString(match.Groups[parameterName].Value); } var controller = (IController)Activator.CreateInstance(ControllerType); controller.Request = req; controller.Response = res; controller.Context = context; var typedController = Convert.ChangeType(controller, ControllerType); var typedArgs = new object[args.Length + 1]; typedArgs[0] = next; for (int i = 0; i < Parameters.Length; i++) { var paramKey = Parameters[i]; var arg = args[i]; var parameter = HandlerParameters[paramKey]; typedArgs[i + 1] = Convert.ChangeType(arg, parameter.ParameterType); } HandlerInfo.Invoke(typedController, typedArgs); } return isMatch; } } }
40.686047
113
0.563304
[ "MIT" ]
benlesh/ALE
ALE.Http/Route.cs
3,499
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("TestExSsdp")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("TestExSsdp")] [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("ec7c81c8-75a3-4083-b839-e8e4b1fa18f0")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
37.648649
84
0.744436
[ "MIT" ]
qine/ExSsdp
src/TestExSsdp/Properties/AssemblyInfo.cs
1,396
C#
namespace Generic.Delegates { class Animal { public string Name { get; set; } } }
13
40
0.557692
[ "MIT" ]
PrasadHonrao/Learn.CSharp
Language/Generics/Basic/Generic.Delegates/Animal.cs
106
C#
// Copyright (c) Microsoft Open Technologies, Inc. All rights reserved. See License.txt in the project root for license information. namespace System.Data.Entity.Core.Common.Internal.Materialization { using System.Data.Entity.Core.Objects.Internal; using System.Linq.Expressions; // <summary> // Type returned by the Translator visitor; allows us to put the logic // to ensure a specific return type in a single place, instead of in // each Visit method. // </summary> internal class TranslatorResult { private readonly Expression ReturnedExpression; private readonly Type RequestedType; internal TranslatorResult(Expression returnedExpression, Type requestedType) { RequestedType = requestedType; ReturnedExpression = returnedExpression; } // <summary> // Return the expression; wrapped with the appropriate cast/convert // logic to guarantee its type. // </summary> internal Expression Expression { get { var result = CodeGenEmitter.Emit_EnsureType(ReturnedExpression, RequestedType); return result; } } // <summary> // Return the expression without attempting to cast/convert to the requested type. // </summary> internal Expression UnconvertedExpression { get { return ReturnedExpression; } } // <summary> // Checks if the expression represents an wrapped entity and if so creates an expression // that extracts the raw entity from the wrapper. // </summary> internal Expression UnwrappedExpression { get { if (!typeof(IEntityWrapper).IsAssignableFrom(ReturnedExpression.Type)) { return ReturnedExpression; } return CodeGenEmitter.Emit_UnwrapAndEnsureType(ReturnedExpression, RequestedType); } } } }
33.451613
132
0.614272
[ "Apache-2.0" ]
CZEMacLeod/EntityFramework6
src/EntityFramework/Core/Common/internal/materialization/TranslatorResult.cs
2,074
C#
// <auto-generated /> namespace Lpp.Dns.Data.Migrations { using System.CodeDom.Compiler; using System.Data.Entity.Migrations; using System.Data.Entity.Migrations.Infrastructure; using System.Resources; [GeneratedCode("EntityFramework.Migrations", "6.1.3-40302")] public sealed partial class AddRequestDocumentsTable : IMigrationMetadata { private readonly ResourceManager Resources = new ResourceManager(typeof(AddRequestDocumentsTable)); string IMigrationMetadata.Id { get { return "201607131954474_AddRequestDocumentsTable"; } } string IMigrationMetadata.Source { get { return null; } } string IMigrationMetadata.Target { get { return Resources.GetString("Target"); } } } }
28.533333
107
0.635514
[ "Apache-2.0" ]
Missouri-BMI/popmednet
Lpp.Dns.Data/Migrations/201607131954474_AddRequestDocumentsTable.Designer.cs
856
C#
using System.Collections.Generic; using System.Text; namespace CtfTools { public static class EnumerableExtensions { public static string ToFlag(this IEnumerable<object> collection, string prefix = "") { var builder = new StringBuilder(); using (var e = collection.GetEnumerator()) { builder.Append(prefix); e.MoveNext(); var part = e.Current.ToString(); if (part != prefix) { builder.Append("-"); builder.Append(part); } while (e.MoveNext()) { builder.Append("-"); builder.Append(e.Current); } } return builder.ToString(); } } }
24.457143
92
0.449766
[ "MIT" ]
michaeloyer/CtfTools
CtfTools/EnumerableExtensions.cs
858
C#
using Alabo.Datas.UnitOfWorks; using Alabo.Domains.Enums; using Alabo.Domains.Repositories; using Alabo.Domains.Repositories.EFCore; using Alabo.Extensions; using Alabo.Framework.Reports.Domain.Entities; using Alabo.Helpers; using Alabo.UI; using Alabo.UI.Design.AutoReports; using Alabo.UI.Design.AutoReports.Dtos; using Alabo.UI.Design.AutoReports.Enums; using Alabo.Users.Repositories; using MongoDB.Bson; using System; using System.Collections.Generic; using System.Data; using System.Text; using Convert = System.Convert; namespace Alabo.Framework.Reports.Domain.Repositories { /// <summary> /// AutoReportRepository /// </summary> public class AutoReportRepository : RepositoryMongo<Report, ObjectId>, IAutoReportRepository { /// <summary> /// AutoReportRepository /// </summary> /// <param name="unitOfWork"></param> public AutoReportRepository(IUnitOfWork unitOfWork) : base(unitOfWork) { } /// <summary> /// 按天数统计数量 报图图状 /// </summary> /// <returns></returns> public List<object> GetDayCountReport(CountReportInput countReportInput) { countReportInput.Condition.EntityType = countReportInput.EntityType; var tableName = countReportInput.Condition.GetTableName(); var dbContext = Ioc.Resolve<IAlaboUserRepository>().RepositoryContext; var tempSqlWhere = string.Empty; //日期验证 if (countReportInput.Condition.StartTime.ToString().IndexOf("0001") == -1 || countReportInput.Condition.EndTime.ToString().IndexOf("0001") == -1) { var varStartTime = string.Format("{0:yyyy-MM-dd}", countReportInput.Condition.StartTime); var varEndTime = string.Format("{0:yyyy-MM-dd}", countReportInput.Condition.EndTime); tempSqlWhere = @" and (CONVERT(VARCHAR(100), CreateTime, 23) >='" + varStartTime + "' and CONVERT(VARCHAR(100), CreateTime, 23)<= '" + varEndTime + "') "; } var sqlCountByDay = @" select CONVERT(VARCHAR(100), CreateTime, 23) Day, count(" + countReportInput.Field + @") as TotalNum, cast( convert (decimal(18,2),100*cast(count(distinct isnull(" + countReportInput.Field + @",0)) as float)/cast(((select count(" + countReportInput.Field + @") from " + tableName + @") )as float) ) as varchar)+'%' as SaleRatio from " + tableName + @" where 1 = 1 " + tempSqlWhere + @"group by CONVERT(VARCHAR(100), CreateTime, 23) "; var lists = new List<object>(); if (FilterSqlScript(sqlCountByDay) != true) { using (var dr = dbContext.ExecuteDataReader(sqlCountByDay)) { while (dr.Read()) { var item = ReadAutoReport(dr); lists.Add(item); } } } return lists; } /// <summary> /// 按天数根据状态 统计数量 扩展 报图图状 /// </summary> /// <returns></returns> public List<AutoReport> GetDayCountReportByFiled(CountReportInput countReport) { var tableName = ""; var specialField = ""; var startTime = DateTime.Now; var endTime = DateTime.Now; var sqlWhere = ""; var tempSqlWhere = string.Empty; var chartCols = new List<string>(); chartCols.Add("日期"); chartCols.Add("全部数量"); chartCols.Add("比率"); //查询条件 if (!string.IsNullOrEmpty(sqlWhere)) { tempSqlWhere = " and " + sqlWhere; } //日期验证 if (startTime.ToString().IndexOf("0001") == -1 || endTime.ToString().IndexOf("0001") == -1) { var varStartTime = string.Format("{0:yyyy-MM-dd}", startTime); var varEndTime = string.Format("{0:yyyy-MM-dd}", endTime); tempSqlWhere = @" and (CONVERT(VARCHAR(100), CreateTime, 23) >='" + varStartTime + "' and CONVERT(VARCHAR(100), CreateTime, 23)<= '" + varEndTime + "') "; } var tempSqlStatusCount = string.Empty; //枚举 if (!string.IsNullOrEmpty(specialField)) { var typeEnum = specialField.GetTypeByName(); foreach (Enum item in Enum.GetValues(typeEnum)) { var itemName = item.GetDisplayName(); var itemValue = item.ToString(); var key = Convert.ToInt16(item); tempSqlStatusCount = tempSqlStatusCount + @" count(CASE WHEN " + specialField + " =" + key + " THEN " + specialField + " END) AS " + itemName + " , "; chartCols.Add(itemName); } } var dbContext = Ioc.Resolve<IAlaboUserRepository>().RepositoryContext; var sqlCountByDay = @" select CONVERT(VARCHAR(100), CreateTime, 23) 日期, count(id) as 全部数量," + tempSqlStatusCount + @"cast( convert (decimal(18,2),100*cast(count(distinct isnull(id,0)) as float)/cast(((select count(id) from " + tableName + @") )as float) ) as varchar)+'%' as 比率 from " + tableName + @" where 1 = 1 " + tempSqlWhere + @" group by CONVERT(VARCHAR(100), CreateTime, 23) "; var result = new List<AutoReport>(); var typeEnumExt = specialField.GetTypeByName(); if (FilterSqlScript(sqlCountByDay) != true) { using (var dr = dbContext.ExecuteDataReader(sqlCountByDay)) { while (dr.Read()) { var listItem = new List<AutoReportItem>(); var output = new AutoReport(); chartCols.ForEach(p => { if (p.ToLower() == "日期") { output.Date = dr[p].ToString(); } else if (p.ToLower() == "全部数量") { output.Date = dr[p].ToString(); } else if (p.ToLower() == "比率") { output.Date = dr[p].ToString(); } else { listItem.Add(new AutoReportItem { Name = p.ToString(), Value = dr[p].ToString() }); } }); output.AutoReportItem = listItem; } } } return result; } /// <summary> /// 根据字段 日期 统计报表 /// </summary> /// <param name="dateCountReportInput"></param> /// <param name="EnumName"></param> /// <returns></returns> public List<AutoReport> GetReportFormWithField(CountReportInput dateCountReportInput, string EnumName) { var queryResult = ExeclCountSql(dateCountReportInput, EnumName); var strSql = queryResult.Item1; var chartCols = queryResult.Item2; var chartRows = new List<object>(); var dbContext = Ioc.Resolve<IAlaboUserRepository>().RepositoryContext; using (var dr = dbContext.ExecuteDataReader(strSql)) { while (dr.Read()) { var dic = new Dictionary<string, string>(); chartCols.ForEach(p => { dic.Add(p, dr[p].ToString()); }); chartRows.Add(dic); } } var line = (ReportChartType)Enum.Parse(typeof(ReportChartType), "0"); var result = new List<AutoReport> { new AutoReport { Name = "数据走势图", Icon = Flaticon.Alarm.GetIcon(), AutoReportChart = new AutoReportChart {Type = line, Columns = chartCols, Rows = chartRows} } }; return result; } /// <summary> /// 根据日期 状态 统计报表表格 /// </summary> /// <returns></returns> public List<object> GetDayCountReportTableByFiled(CountReportInput countReport) { var tableName = ""; var specialField = ""; var startTime = DateTime.Now; var endTime = DateTime.Now; var sqlWhere = ""; //字段别名 var otherColName = string.Empty; var tempSqlWhere = string.Empty; //查询条件 if (!string.IsNullOrEmpty(sqlWhere)) { tempSqlWhere = " and " + sqlWhere; } //日期验证 if (startTime.ToString().IndexOf("0001") == -1 || endTime.ToString().IndexOf("0001") == -1) { var varStartTime = string.Format("{0:yyyy-MM-dd}", startTime); var varEndTime = string.Format("{0:yyyy-MM-dd}", endTime); tempSqlWhere = @" and (CONVERT(VARCHAR(100), CreateTime, 23) >='" + varStartTime + "' and CONVERT(VARCHAR(100), CreateTime, 23)<= '" + varEndTime + "') "; } var tempSqlStatusCount = string.Empty; var tempSqlStatusRatioCount = string.Empty; if (!string.IsNullOrEmpty(specialField)) { foreach (Status item in Enum.GetValues(typeof(Status))) { var itemName = item.ToString(); var itemValue = (int)item; //统计状态数量 tempSqlStatusCount = tempSqlStatusCount + @" count(CASE WHEN " + specialField + " =" + itemValue + " THEN " + specialField + " END) AS CountStatus" + itemName + " , "; //统计状态比率 tempSqlStatusRatioCount = tempSqlStatusRatioCount + @" cast( convert (decimal(18,2),100*cast(count(CASE WHEN " + specialField + "=" + itemValue + " THEN Status END) as float)/cast(((count(1) ) )as float) ) as varchar)+'%' as CountStatusRatio" + itemName + ","; } } var dbContext = Ioc.Resolve<IAlaboUserRepository>().RepositoryContext; var sqlCountByDay = @" select CONVERT(VARCHAR(100), CreateTime, 23) Day, count(id) as TotalNum," + tempSqlStatusCount + tempSqlStatusRatioCount + @"cast( convert (decimal(18,2),100*cast(count(distinct isnull(id,0)) as float)/cast(((select count(id) from " + tableName + @") )as float) ) as varchar)+'%' as SaleRatio from " + tableName + @" where 1 = 1 " + tempSqlWhere + @" group by CONVERT(VARCHAR(100), CreateTime, 23) "; var lists = new List<object>(); if (FilterSqlScript(sqlCountByDay) != true) { using (var dr = dbContext.ExecuteDataReader(sqlCountByDay)) { while (dr.Read()) { var item = ReadAutoReportTableSpec(dr); lists.Add(item); } } } return lists; } /// <summary> /// 根据日期 状态 统计报表表格 /// </summary> /// <param name="countReport"></param> /// <param name="EnumName"></param> /// <returns></returns> public List<CountReportTable> GetCountReportTableWithField(CountReportInput countReport, string EnumName) { var dbContext = Ioc.Resolve<IAlaboUserRepository>().RepositoryContext; var queryResult = ExeclCountTableSql(countReport, EnumName); var strSql = queryResult.Item1; var chartCols = queryResult.Item2; var chartRows = new List<object>(); using (var dr = dbContext.ExecuteDataReader(strSql)) { while (dr.Read()) { var dic = new Dictionary<string, string>(); foreach (var item in chartCols) { var value = item.name; var key = item.type; if (!dic.ContainsKey(key)) { dic.Add(key, dr[key].ToString()); } } chartRows.Add(dic); } } var result = new List<CountReportTable> { new CountReportTable {Name = "报表数据", AutoReportChart = new CountReportItem {Columns = chartCols, Rows = chartRows}} }; return result; } /// <summary> /// </summary> /// <param name="singleReportInput"></param> /// <returns></returns> public decimal GetSingleData(SingleReportInput singleReportInput) { if (string.IsNullOrEmpty(singleReportInput.Field)) { singleReportInput.Field = "id"; } singleReportInput.Condition.EntityType = singleReportInput.EntityType; var tableName = singleReportInput.Condition.GetTableName(); var dbContext = Ioc.Resolve<IAlaboUserRepository>().RepositoryContext; var sql = new StringBuilder(); switch (singleReportInput.Style) { case ReportStyle.Count: sql.Append(@"SELECT ISNULL(COUNT(" + singleReportInput.Field + "),0) AS " + singleReportInput.Field + " FROM " + tableName); break; case ReportStyle.Sum: sql.Append(@"SELECT ISNULL(SUM(" + singleReportInput.Field + "),0) AS " + singleReportInput.Field + " FROM " + tableName); break; case ReportStyle.Avg: sql.Append(@"SELECT ISNULL(AVG(" + singleReportInput.Field + "),0) AS " + singleReportInput.Field + " FROM " + tableName); break; case ReportStyle.Min: sql.Append(@"SELECT ISNULL(MIN(" + singleReportInput.Field + "),0) AS " + singleReportInput.Field + " FROM " + tableName); break; case ReportStyle.Max: sql.Append(@"SELECT ISNULL(MAX(" + singleReportInput.Field + "),0) AS " + singleReportInput.Field + " FROM " + tableName); break; case ReportStyle.ChainRatioYesterday: var yesterday = DateTime.Now.AddDays(-1); var today = DateTime.Now; sql.Append(@" SELECT ISNULL(T2." + singleReportInput.Field + " - T1." + singleReportInput.Field + ",0) AS " + singleReportInput.Field + " FROM "); sql.Append(@" (SELECT ISNULL(SUM(" + singleReportInput.Field + "),0) AS " + singleReportInput.Field + " FROM " + tableName + " where convert(varchar(10),CreateTime,120)=convert(varchar(10),'" + yesterday + "',120) )T1 left join "); sql.Append(@" (SELECT ISNULL(SUM(" + singleReportInput.Field + "),0) AS " + singleReportInput.Field + " FROM " + tableName + " where convert(varchar(10),CreateTime,120)=convert(varchar(10),'" + today + "',120) )T2 on 1=1"); break; case ReportStyle.ChainRatioLastWeek: var day = (int)DateTime.Now.DayOfWeek; var thisWeekStart = DateTime.Now.AddDays(-day + 1).ToString("yyyy-MM-dd 00:00:00"); //本周第一天 var thisWeekNow = DateTime.Now; //当前天 var lastWeekStart = DateTime.Now.AddDays(-day - 6).ToString("yyyy-MM-dd 00:00:00"); //上周第一天 var lastWeekEnd = DateTime.Now.AddDays(-day - 6).AddDays(day - 1).ToString("yyyy-MM-dd 23:59:59"); //上周对应当天 sql.Append(@" SELECT ISNULL(T2." + singleReportInput.Field + "-T1." + singleReportInput.Field + ",0) AS " + singleReportInput.Field + " FROM "); sql.Append(@" (SELECT ISNULL(SUM(" + singleReportInput.Field + "),0) AS " + singleReportInput.Field + " FROM " + tableName + " where CreateTime between '" + lastWeekStart + "' and '" + lastWeekEnd + "' )T1 left join "); sql.Append(@" (SELECT ISNULL(SUM(" + singleReportInput.Field + "),0) AS " + singleReportInput.Field + " FROM " + tableName + " where CreateTime between '" + thisWeekStart + "' and '" + thisWeekNow + "' )T2 on 1=1"); break; case ReportStyle.ChainRatioLastMonth: var thisMonthStart = DateTime.Now.GetMonthBegin().ToString("yyyy-MM-dd 00:00:00"); //本月第一天 var thisMonthNow = DateTime.Now; //当前天 var lastMonthStart = DateTime.Now.GetMonthBegin().AddMonths(-1); //上个月第一天 var lastMonthEnd = DateTime.Now.AddMonths(-1).ToString("yyyy-MM-dd 23:59:59"); //上月对应当天 sql.Append(@" SELECT ISNULL(T2." + singleReportInput.Field + "-T1." + singleReportInput.Field + ",0) AS " + singleReportInput.Field + " FROM "); sql.Append(@" (SELECT ISNULL(SUM(" + singleReportInput.Field + "),0) AS " + singleReportInput.Field + " FROM " + tableName + " where CreateTime between '" + lastMonthStart + "' and '" + lastMonthEnd + "' )T1 left join "); sql.Append(@" (SELECT ISNULL(SUM(" + singleReportInput.Field + "),0) AS " + singleReportInput.Field + " FROM " + tableName + " where CreateTime between '" + thisMonthStart + "' and '" + thisMonthNow + "' )T2 on 1=1"); break; case ReportStyle.ChainRatioLastQuarter: sql.Append(@" SELECT ISNULL(T2." + singleReportInput.Field + "- T1." + singleReportInput.Field + ",0) AS " + singleReportInput.Field + " FROM "); sql.Append(@"(select ISNULL(SUM(" + singleReportInput.Field + "),0) AS " + singleReportInput.Field + " FROM " + tableName + " where DATEPART(qq,CreateTime)= DATEPART(qq,GETDATE())-1)T1 left join "); sql.Append(@"(select ISNULL(SUM(" + singleReportInput.Field + "),0) AS " + singleReportInput.Field + " FROM " + tableName + " where DATEPART(qq,CreateTime)= DATEPART(qq,GETDATE()))T2 on 1=1 "); break; case ReportStyle.ChainRatioLastYear: sql.Append(@"SELECT ISNULL(SUM(" + singleReportInput.Field + "),0) AS " + singleReportInput.Field + " FROM " + tableName); break; } sql.Append(singleReportInput.Condition.ToSqlWhere(singleReportInput.Style)); var returnValue = dbContext.ExecuteScalar(sql.ToString()); if (returnValue == null) { returnValue = 0; } return returnValue.ToDecimal(); } /// <summary> /// ExeclCountSql:根据特殊字段 统计报表图状语句 /// </summary> /// <param name="countReportInput"></param> /// <param name="EnumName"></param> /// <returns></returns> private Tuple<string, List<string>> ExeclCountSql(CountReportInput countReportInput, string EnumName) { var tempSqlWhere = string.Empty; var chartCols = new List<string>(); chartCols.Add("日期"); chartCols.Add("全部数量"); chartCols.Add("比率"); #region 条件查询 ////查询条件 //if (!string.IsNullOrEmpty(sqlWhere)) //{ // tempSqlWhere = " and " + sqlWhere; //} // tempSqlWhere += countReportInput.Condition.ToSqlWhere(); //日期验证 if (countReportInput.Condition.StartTime.ToString().IndexOf("0001") == -1 || countReportInput.Condition.EndTime.ToString().IndexOf("0001") == -1) { var varStartTime = string.Format("{0:yyyy-MM-dd}", countReportInput.Condition.StartTime); var varEndTime = string.Format("{0:yyyy-MM-dd}", countReportInput.Condition.EndTime); tempSqlWhere = @" and (CONVERT(VARCHAR(100), CreateTime, 23) >='" + varStartTime + "' and CONVERT(VARCHAR(100), CreateTime, 23)<= '" + varEndTime + "') "; } #endregion 条件查询 var tempSqlStatusCount = string.Empty; countReportInput.Condition.EntityType = countReportInput.EntityType; var tableName = countReportInput.Condition.GetTableName(); //枚举 if (!string.IsNullOrEmpty(EnumName)) { var typeEnum = EnumName.GetTypeByName(); if (typeEnum != null) { foreach (Enum item in Enum.GetValues(typeEnum)) { var itemName = item.GetDisplayName(); itemName = FilterSpecial(itemName); var itemValue = item.ToString(); var key = Convert.ToInt16(item); tempSqlStatusCount = tempSqlStatusCount + @" count(CASE WHEN " + countReportInput.Field + " =" + key + " THEN " + countReportInput.Field + " END) AS " + itemName + " , "; chartCols.Add(itemName); } } } var sqlCountByDay = @" select CONVERT(VARCHAR(100), CreateTime, 23) 日期, count(id) as 全部数量," + tempSqlStatusCount + @"cast( convert (decimal(18,2),100*cast(count(distinct isnull(id,0)) as float)/cast(((select count(id) from " + tableName + @") )as float) ) as varchar)+'%' as 比率 from " + tableName + @" where 1 = 1 " + tempSqlWhere + @" group by CONVERT(VARCHAR(100), CreateTime, 23) "; return Tuple.Create(sqlCountByDay, chartCols); } /// <summary> /// ExeclCountTableSql 根据特殊字段统计报表表格语句 /// </summary> /// <param name="reportInput"></param> /// <param name="EnumName"></param> /// <returns></returns> private Tuple<string, List<Columns>> ExeclCountTableSql(CountReportInput reportInput, string EnumName) { var listCol = new List<Columns>(); var col = new Columns(); var tempSqlWhere = string.Empty; col.name = "日期"; col.type = "date"; listCol.Add(col); col = new Columns(); col.name = "全部数量"; col.type = "count"; listCol.Add(col); col = new Columns(); col.name = "比率"; col.type = "rate"; listCol.Add(col); #region 条件查询 ////查询条件 //if (!string.IsNullOrEmpty(sqlWhere)) //{ // tempSqlWhere = " and " + sqlWhere; //} //日期验证 if (reportInput.Condition.StartTime.ToString().IndexOf("0001") == -1 || reportInput.Condition.EndTime.ToString().IndexOf("0001") == -1) { var varStartTime = string.Format("{0:yyyy-MM-dd}", reportInput.Condition.StartTime); var varEndTime = string.Format("{0:yyyy-MM-dd}", reportInput.Condition.EndTime); tempSqlWhere = @" and (CONVERT(VARCHAR(100), CreateTime, 23) >='" + varStartTime + "' and CONVERT(VARCHAR(100), CreateTime, 23)<= '" + varEndTime + "') "; } #endregion 条件查询 var tempSqlStatusCount = string.Empty; var tempSqlStatusRatioCount = string.Empty; reportInput.Condition.EntityType = reportInput.EntityType; var tableName = reportInput.Condition.GetTableName(); //枚举 if (!string.IsNullOrEmpty(EnumName)) { var typeEnum = EnumName.GetTypeByName(); foreach (Enum item in Enum.GetValues(typeEnum)) { var itemName = item.GetDisplayName(); itemName = FilterSpecial(itemName); var itemValue = item.ToString(); var key = Convert.ToInt16(item); col = new Columns(); //统计状态数量 tempSqlStatusCount = tempSqlStatusCount + @" count(CASE WHEN " + reportInput.Field + " =" + key + " THEN " + reportInput.Field + " END) AS " + itemValue + " , "; col.name = itemName; col.type = itemValue; listCol.Add(col); col = new Columns(); //统计状态比率字段 var itemNameRatio = itemName + "比率"; var itemNameRatioValue = itemValue + "Rate"; col.name = itemNameRatio; col.type = itemNameRatioValue; //统计状态比率 tempSqlStatusRatioCount = tempSqlStatusRatioCount + @" cast( convert (decimal(18,2),100*cast(count(CASE WHEN " + reportInput.Field + "=" + key + " THEN " + reportInput.Field + " END) as float)/cast(((count(1) ) )as float) ) as varchar)+'%' as " + itemNameRatioValue + " , "; listCol.Add(col); } } var sqlCountByDay = @" select CONVERT(VARCHAR(100), CreateTime, 23) date, count(1) as count," + tempSqlStatusCount + tempSqlStatusRatioCount + @"cast( convert (decimal(18,2),100*cast(count(distinct isnull(id,0)) as float)/cast(((select count(id) from " + tableName + @") )as float) ) as varchar)+'%' as rate from " + tableName + @" where 1 = 1 " + tempSqlWhere + @" group by CONVERT(VARCHAR(100), CreateTime, 23) "; return Tuple.Create(sqlCountByDay, listCol); } /// <summary> /// 图形报表普通实体 /// </summary> /// <param name="reader"></param> /// <returns></returns> private object ReadAutoReport(IDataReader reader) { var item = new { Date = reader["Day"].ToString(), Count = reader["TotalNum"].ToString(), Rate = reader["SaleRatio"].ToString() }; return item; } /// <summary> /// 图形报表特殊实体 /// </summary> /// <param name="reader"></param> /// <returns></returns> private object ReadAutoReportSpec(IDataReader reader) { var item = new { Date = reader["Day"].ToString(), Count = reader["TotalNum"].ToString(), Rate = reader["SaleRatio"].ToString() }; return item; } private object ReadAutoReportSpec1(IDataReader reader, string specialField) { var typeEnum = specialField.GetTypeByName(); object obj = null; foreach (Enum il in Enum.GetValues(typeEnum)) { var itemValue = il.ToString(); itemValue = reader[itemValue].ToString(); obj = new { ItemValue = reader[itemValue].ToString() }; } return obj; } /// <summary> /// 图形报表表格特殊实体 /// </summary> /// <param name="reader"></param> /// <returns></returns> private object ReadAutoReportTableSpec(IDataReader reader) { var item = new { Date = reader["Day"].ToString(), Count = reader["TotalNum"].ToString(), CountStatusNormal = reader["CountStatusNormal"].ToString(), CountStatusRatioNormal = reader["CountStatusRatioNormal"].ToString(), CountStatusFreeze = reader["CountStatusFreeze"].ToString(), CountStatusRatioFreeze = reader["CountStatusRatioFreeze"].ToString(), CountStatusDeleted = reader["CountStatusDeleted"].ToString(), CountStatusRatioDeleted = reader["CountStatusRatioDeleted"].ToString(), SaleRatio = reader["SaleRatio"].ToString() }; return item; } #region 过滤工具 /// <summary> /// 过滤Sql脚本关键字 /// </summary> /// <param name="sSql">The s SQL.</param> private bool FilterSqlScript(string sSql) { int srcLen, decLen = 0; sSql = sSql.ToLower().Trim(); srcLen = sSql.Length; sSql = sSql.Replace("exec", ""); sSql = sSql.Replace("delete", ""); sSql = sSql.Replace("master", ""); sSql = sSql.Replace("truncate", ""); sSql = sSql.Replace("declare", ""); sSql = sSql.Replace("create", ""); sSql = sSql.Replace("xp_", "no"); decLen = sSql.Length; if (srcLen == decLen) { return true; } return false; } /// <summary> /// 过滤特殊字符 /// 如果字符串为空,直接返回。 /// </summary> /// <param name="str">需要过滤的字符串</param> /// <returns>过滤好的字符串</returns> public static string FilterSpecial(string str) { if (str == "") { return str; } str = str.Replace("'", ""); str = str.Replace("<", ""); str = str.Replace(">", ""); str = str.Replace("%", ""); str = str.Replace("'delete", ""); str = str.Replace("''", ""); str = str.Replace("\"\"", ""); str = str.Replace(",", ""); str = str.Replace(".", ""); str = str.Replace(">=", ""); str = str.Replace("=<", ""); str = str.Replace("-", ""); str = str.Replace("_", ""); str = str.Replace(";", ""); str = str.Replace("||", ""); str = str.Replace("[", ""); str = str.Replace("]", ""); str = str.Replace("&", ""); str = str.Replace("#", ""); str = str.Replace("/", ""); str = str.Replace("-", ""); str = str.Replace("|", ""); str = str.Replace("?", ""); str = str.Replace(">?", ""); str = str.Replace("?<", ""); str = str.Replace(" ", ""); return str; } #endregion 过滤工具 #region 求和统计 报表-表格 /// <summary> /// 根据字段求和 统计报表 /// </summary> /// <returns></returns> public List<AutoReport> GetSumReport(SumReportInput sumReportInput) { var dbContext = Ioc.Resolve<IAlaboUserRepository>().RepositoryContext; var queryResult = GetSumReportQuerySql(sumReportInput); var strSql = queryResult.Item1; var chartCols = queryResult.Item2; var chartRows = new List<object>(); using (var dr = dbContext.ExecuteDataReader(strSql)) { while (dr.Read()) { var dic = new Dictionary<string, string>(); chartCols.ForEach(p => { dic.Add(p, dr[p].ToString()); }); chartRows.Add(dic); } } var line = (ReportChartType)Enum.Parse(typeof(ReportChartType), "0"); var result = new List<AutoReport> { new AutoReport { Name = "数据走势图", Icon = Flaticon.Alarm.GetIcon(), AutoReportChart = new AutoReportChart {Type = line, Columns = chartCols, Rows = chartRows} } }; return result; } /// <summary> /// 按天统计实体增加数据,输出表格形式 /// </summary> /// <param name="reportInput"></param> /// <param name="EnumName"></param> /// <returns></returns> public List<SumReportTable> GetSumReportTable(SumReportInput reportInput, string EnumName) { var dbContext = Ioc.Resolve<IAlaboUserRepository>().RepositoryContext; var queryResult = GetSumTableQuerySql(reportInput, EnumName); var strSql = queryResult.Item1; var chartCols = queryResult.Item2; var chartRows = new List<object>(); using (var dr = dbContext.ExecuteDataReader(strSql)) { while (dr.Read()) { var dic = new Dictionary<string, string>(); foreach (var item in chartCols) { var value = item.name; var key = item.type; if (!dic.ContainsKey(key)) { dic.Add(key, dr[key].ToString()); } } chartRows.Add(dic); } } var result = new List<SumReportTable> { new SumReportTable { Name = "报表数据", SumReportTableItem = new SumReportTableItems {Columns = chartCols, Rows = chartRows} } }; return result; } /// <summary> /// 获取Sum报表Sql语句 /// </summary> /// <param name="sumReportInput"></param> /// <returns></returns> private Tuple<string, List<string>> GetSumReportQuerySql(SumReportInput sumReportInput) { var tempSqlField = string.Empty; var chartCols = new List<string>(); chartCols.Add("日期"); //实体字段 过滤 foreach (var field in sumReportInput.Fields) { var tempDisplayName = sumReportInput.EntityType.GetFiledDisplayName(field); tempSqlField = tempSqlField + " ,sum(" + field + ") as " + tempDisplayName; chartCols.Add(tempDisplayName); //根据传入的查询字段个数 } ////查询条件 //if (!string.IsNullOrEmpty(sqlWhere)) //{ // tempSqlWhere = tempSqlWhere + " and " + sqlWhere; //} //日期验证 var tempSqlWhere = string.Empty; if (sumReportInput.Condition.StartTime.ToString().IndexOf("0001") == -1 || sumReportInput.Condition.EndTime.ToString().IndexOf("0001") == -1) { tempSqlWhere = " and CreateTime between CONVERT(VARCHAR(100), '" + sumReportInput.Condition.StartTime + "', 23) and CONVERT(VARCHAR(100), '" + sumReportInput.Condition.EndTime + "', 23)"; } sumReportInput.Condition.EntityType = sumReportInput.EntityType; var tableName = sumReportInput.Condition.GetTableName(); var sqlBaseExec = @" select CONVERT(VARCHAR(100), CreateTime, 23) as 日期 " + tempSqlField + @" from " + tableName + @" where 1=1 " + tempSqlWhere + @"group by CONVERT(VARCHAR(100), CreateTime, 23)"; if (FilterSqlScript(sqlBaseExec)) { throw new ArgumentNullException("sql语句有异常!"); } return Tuple.Create(sqlBaseExec, chartCols); } /// <summary> /// sum报表表格Sql语句 /// </summary> /// <param name="reportInput">表字段</param> /// <returns></returns> private Tuple<string, List<SumColumns>> GetSumTableQuerySql(SumReportInput reportInput, string EnumName) { //还得扩展 SpecialField var tempSqlWhere = string.Empty; var tempSqlField = string.Empty; var tempSqlStatusCount = string.Empty; var colList = new List<SumColumns>(); var col = new SumColumns(); col.name = "日期"; col.type = "Date"; colList.Add(col); if (!string.IsNullOrEmpty(EnumName)) { var typeEnum = EnumName.GetTypeByName(); if (typeEnum != null) { foreach (Enum item in Enum.GetValues(typeEnum)) { var itemName = item.GetDisplayName(); itemName = FilterSpecial(itemName); var itemValue = item.ToString(); var itemKey = Convert.ToInt16(item); col = new SumColumns(); //实体字段 foreach (var field in reportInput.Fields) { var tempDisplayName = reportInput.EntityType.GetFiledDisplayName(field); //统计 Sum状态数量 var TotalAmountName = tempDisplayName + itemName; var TotalAmountValue = field + itemValue; //待完成 已完成 等状态 tempSqlStatusCount = tempSqlStatusCount + @" , SUM(CASE WHEN " + reportInput.Field + "=" + itemKey + " THEN " + field + " ELSE 0 END) AS " + TotalAmountValue; //var tempTableHeadName= tempDisplayName+"["+ itemName + "]"; col.name = TotalAmountName; col.type = TotalAmountValue; colList.Add(col); } } } } if (reportInput.Fields.Count > 0) //实体字段 过滤 { foreach (var field in reportInput.Fields) { var tempDisplayName = reportInput.EntityType.GetFiledDisplayName(field); tempSqlField = tempSqlField + " ,sum(" + field + ") as " + field; col = new SumColumns(); col.name = tempDisplayName; col.type = field; colList.Add(col); } } ////查询条件 //if (!string.IsNullOrEmpty(sqlWhere)) //{ // tempSqlWhere = tempSqlWhere + " and " + sqlWhere; //} //日期验证 if (reportInput.Condition.StartTime.ToString().IndexOf("0001") == -1 || reportInput.Condition.EndTime.ToString().IndexOf("0001") == -1) { tempSqlWhere = tempSqlWhere + " and CreateTime between CONVERT(VARCHAR(100), '" + reportInput.Condition.StartTime + "', 23) and CONVERT(VARCHAR(100), '" + reportInput.Condition.EndTime + "', 23)"; } reportInput.Condition.EntityType = reportInput.EntityType; var tableName = reportInput.Condition.GetTableName(); var sqlBaseExec = @" select CONVERT(VARCHAR(100), CreateTime, 23) as Date " + tempSqlField + tempSqlStatusCount + @" from " + tableName + @" where 1=1 " + tempSqlWhere + @" group by CONVERT(VARCHAR(100), CreateTime, 23)"; if (FilterSqlScript(sqlBaseExec)) { throw new ArgumentNullException("sql语句有异常!"); } return Tuple.Create(sqlBaseExec, colList); } #endregion 求和统计 报表-表格 } }
44.355748
144
0.484228
[ "MIT" ]
tongxin3267/alabo
src/01.framework/04-Alabo.Framework.Reports/Domain/Repositories/AutoReportRepository.cs
41,906
C#
using LinFx.Test.Domain.Models; using Microsoft.Extensions.Caching.Distributed; using Microsoft.Extensions.DependencyInjection; using System.Threading.Tasks; using Xunit; namespace LinFx.Test.Caching { public class MemoryCacheTest { private readonly IDistributedCache _cache; public MemoryCacheTest() { var services = new ServiceCollection(); services .AddLinFx() .AddDistributedMemoryCache(); var container = services.BuildServiceProvider(); _cache = container.GetService<IDistributedCache>(); } [Fact] public async Task MemoryCache_GetAndSet_Tests() { var expected = 100; await _cache.SetAsync("key1", 100); var actual = await _cache.GetAsync<int>("key1"); Assert.Equal(expected, actual); } [Fact] public async Task MemoryCache_GetOrAdd_Tests() { var expected = new User { Id = 100 }; var actual = await _cache.GetOrAddAsync("key2", () => { return Task.FromResult(new User { Id = 100 }); }); Assert.Equal(expected, actual); } } }
24.472727
65
0.533432
[ "MIT" ]
ailuozhu/LinFx
test/LinFx.Test/Caching/MemoryCacheTests.cs
1,348
C#
namespace Curso.api.Business.Entities { public class Usuario { public int Codigo { get; set; } public string Login { get; set; } public string Email { get; set;} public string Senha { get; set; } } }
22.818182
44
0.561753
[ "MIT" ]
Raphael-Azevedo/Segunda-api-Dio
Curso.api/Business/Entities/Usuario.cs
253
C#
/* Copyright 2006-2015 Stefano Chizzolini. http://www.pdfclown.org Contributors: * Stefano Chizzolini (original code developer, http://www.stefanochizzolini.it) * Manuel Guilbault (code contributor [FIX:27], manuel.guilbault at gmail.com) This file should be part of the source code distribution of "PDF Clown library" (the Program): see the accompanying README files for more info. This Program is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version. This Program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY, either expressed or implied; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the License for more details. You should have received a copy of the GNU Lesser General Public License along with this Program (see README files); if not, go to the GNU website (http://www.gnu.org/licenses/). Redistribution and use, with or without modification, are permitted provided that such redistributions retain the above copyright notice, license and disclaimer, along with this list of conditions. */ using org.pdfclown.bytes; using org.pdfclown.documents; using org.pdfclown.files; using org.pdfclown.objects; using org.pdfclown.tokens; using org.pdfclown.util; using System; using io = System.IO; using System.Collections.Generic; using System.Linq; using System.Text; namespace org.pdfclown.documents.contents.fonts { /** <summary>Abstract font [PDF:1.6:5.4].</summary> */ [PDF(VersionEnum.PDF10)] public abstract class Font : PdfObjectWrapper<PdfDictionary> { #region types /** <summary>Font descriptor flags [PDF:1.6:5.7.1].</summary> */ [Flags] public enum FlagsEnum { /** <summary>All glyphs have the same width.</summary> */ FixedPitch = 0x1, /** <summary>Glyphs have serifs.</summary> */ Serif = 0x2, /** <summary>Font contains glyphs outside the Adobe standard Latin character set.</summary> */ Symbolic = 0x4, /** <summary>Glyphs resemble cursive handwriting.</summary> */ Script = 0x8, /** <summary>Font uses the Adobe standard Latin character set.</summary> */ Nonsymbolic = 0x20, /** <summary>Glyphs have dominant vertical strokes that are slanted.</summary> */ Italic = 0x40, /** <summary>Font contains no lowercase letters.</summary> */ AllCap = 0x10000, /** <summary>Font contains both uppercase and lowercase letters.</summary> */ SmallCap = 0x20000, /** <summary>Thicken bold glyphs at small text sizes.</summary> */ ForceBold = 0x40000 } #endregion #region static #region fields private const int UndefinedDefaultCode = int.MinValue; private const int UndefinedWidth = int.MinValue; #endregion #region interface #region public /** <summary>Creates the representation of a font.</summary> */ public static Font Get( Document context, string path ) { return Get( context, new bytes.Stream( new io::FileStream( path, io::FileMode.Open, io::FileAccess.Read ) ) ); } /** <summary>Creates the representation of a font.</summary> */ public static Font Get( Document context, IInputStream fontData ) { if(OpenFontParser.IsOpenFont(fontData)) return CompositeFont.Get(context,fontData); else throw new NotImplementedException(); } /** <summary>Gets the scaling factor to be applied to unscaled metrics to get actual measures.</summary> */ public static double GetScalingFactor( double size ) {return 0.001 * size;} /** <summary>Wraps a font reference into a font object.</summary> <param name="baseObject">Font base object.</param> <returns>Font object associated to the reference.</returns> */ public static Font Wrap( PdfDirectObject baseObject ) { if(baseObject == null) return null; PdfReference reference = (PdfReference)baseObject; { // Has the font been already instantiated? /* NOTE: Font structures are reified as complex objects, both IO- and CPU-intensive to load. So, it's convenient to retrieve them from a common cache whenever possible. */ Dictionary<PdfReference,object> cache = reference.IndirectObject.File.Document.Cache; if(cache.ContainsKey(reference)) {return (Font)cache[reference];} } PdfDictionary fontDictionary = (PdfDictionary)reference.DataObject; PdfName fontType = (PdfName)fontDictionary[PdfName.Subtype]; if(fontType == null) throw new Exception("Font type undefined (reference: " + reference + ")"); if(fontType.Equals(PdfName.Type1)) // Type 1. { if(!fontDictionary.ContainsKey(PdfName.FontDescriptor)) // Standard Type 1. return new StandardType1Font(reference); else // Custom Type 1. { PdfDictionary fontDescriptor = (PdfDictionary)fontDictionary.Resolve(PdfName.FontDescriptor); if(fontDescriptor.ContainsKey(PdfName.FontFile3) && ((PdfName)((PdfStream)fontDescriptor.Resolve(PdfName.FontFile3)).Header.Resolve(PdfName.Subtype)).Equals(PdfName.OpenType)) // OpenFont/CFF. throw new NotImplementedException(); else // Non-OpenFont Type 1. return new Type1Font(reference); } } else if(fontType.Equals(PdfName.TrueType)) // TrueType. return new TrueTypeFont(reference); else if(fontType.Equals(PdfName.Type0)) // OpenFont. { PdfDictionary cidFontDictionary = (PdfDictionary)((PdfArray)fontDictionary.Resolve(PdfName.DescendantFonts)).Resolve(0); PdfName cidFontType = (PdfName)cidFontDictionary[PdfName.Subtype]; if(cidFontType.Equals(PdfName.CIDFontType0)) // OpenFont/CFF. return new Type0Font(reference); else if(cidFontType.Equals(PdfName.CIDFontType2)) // OpenFont/TrueType. return new Type2Font(reference); else throw new NotImplementedException("Type 0 subtype " + cidFontType + " not supported yet."); } else if(fontType.Equals(PdfName.Type3)) // Type 3. return new Type3Font(reference); else if(fontType.Equals(PdfName.MMType1)) // MMType1. return new MMType1Font(reference); else // Unknown. throw new NotSupportedException("Unknown font type: " + fontType + " (reference: " + reference + ")"); } #endregion #endregion #endregion #region dynamic #region fields /* NOTE: In order to avoid nomenclature ambiguities, these terms are used consistently within the code: * character code: internal codepoint corresponding to a character expressed inside a string object of a content stream; * unicode: external codepoint corresponding to a character expressed according to the Unicode standard encoding; * glyph index: internal identifier of the graphical representation of a character. */ /** <summary>Unicodes by character code.</summary> <remarks> <para>When this map is populated, <code>symbolic</code> variable shall accordingly be set.</para> </remarks> */ protected BiDictionary<ByteArray,int> codes; /** <summary>Glyph indexes by unicode.</summary> */ protected Dictionary<int,int> glyphIndexes; /** <summary>Glyph kernings by (left-right) glyph index pairs.</summary> */ protected Dictionary<int,int> glyphKernings; /** <summary>Glyph widths by glyph index.</summary> */ protected Dictionary<int,int> glyphWidths; /** <summary>Whether the font encoding is custom (that is non-Unicode).</summary> */ protected bool symbolic = true; /** <summary>Used unicodes.</summary> */ protected HashSet<int> usedCodes; /** <summary>Average glyph width.</summary> */ private int averageWidth = UndefinedWidth; /** <summary>Maximum character code byte size.</summary> */ private int charCodeMaxLength = 0; /** <summary>Default Unicode for missing characters.</summary> */ private int defaultCode = UndefinedDefaultCode; /** <summary>Default glyph width.</summary> */ private int defaultWidth = UndefinedWidth; #endregion #region constructors /** <summary>Creates a new font structure within the given document context.</summary> */ protected Font( Document context ) : base( context, new PdfDictionary( new PdfName[1]{PdfName.Type}, new PdfDirectObject[1]{PdfName.Font} ) ) {Initialize();} /** <summary>Loads an existing font structure.</summary> */ protected Font( PdfDirectObject baseObject ) : base(baseObject) { Initialize(); Load(); } #endregion #region interface #region public /** <summary>Gets the unscaled vertical offset from the baseline to the ascender line (ascent). The value is a positive number.</summary> */ public virtual double Ascent { get { IPdfNumber ascentObject = (IPdfNumber)GetDescriptorValue(PdfName.Ascent); return ascentObject != null ? ascentObject.DoubleValue : 750; } } /** <summary>Gets the Unicode code-points supported by this font.</summary> */ public ICollection<int> CodePoints { get {return glyphIndexes.Keys;} } /** <summary>Gets the text from the given internal representation.</summary> <param name="code">Internal representation to decode.</param> <exception cref="DecodeException"/> */ public string Decode( byte[] code ) { StringBuilder textBuilder = new StringBuilder(); { byte[][] codeBuffers = new byte[charCodeMaxLength+1][]; for( int codeBufferIndex = 0; codeBufferIndex <= charCodeMaxLength; codeBufferIndex++ ) {codeBuffers[codeBufferIndex] = new byte[codeBufferIndex];} int index = 0; int codeLength = code.Length; int codeBufferSize = 1; while(index < codeLength) { byte[] codeBuffer = codeBuffers[codeBufferSize]; System.Buffer.BlockCopy(code, index, codeBuffer, 0, codeBufferSize); int textChar = 0; if(!codes.TryGetValue(new ByteArray(codeBuffer), out textChar)) { if(codeBufferSize < charCodeMaxLength && codeBufferSize < codeLength - index) { codeBufferSize++; continue; } else // Missing character. { switch(Document.Configuration.EncodingFallback) { case EncodingFallbackEnum.Exclusion: textChar = -1; break; case EncodingFallbackEnum.Substitution: textChar = defaultCode; break; case EncodingFallbackEnum.Exception: throw new DecodeException(code, index); default: throw new NotImplementedException(); } } } if(textChar > -1) {textBuilder.Append((char)textChar);} index += codeBufferSize; codeBufferSize = 1; } } return textBuilder.ToString(); } /** <summary>Gets/Sets the Unicode codepoint used to substitute missing characters.</summary> <exception cref="EncodeException">If the value is not mapped in the font's encoding.</exception> */ public int DefaultCode { get {return defaultCode;} set { if(!glyphIndexes.ContainsKey(value)) throw new EncodeException((char)value); defaultCode = value; } } /** <summary>Gets the unscaled vertical offset from the baseline to the descender line (descent). The value is a negative number.</summary> */ public virtual double Descent { get { /* NOTE: Sometimes font descriptors specify positive descent, therefore normalization is required [FIX:27]. */ IPdfNumber descentObject = (IPdfNumber)GetDescriptorValue(PdfName.Descent); return -Math.Abs(descentObject != null ? descentObject.DoubleValue : 250); } } /** <summary>Gets the internal representation of the given text.</summary> <param name="text">Text to encode.</param> <exception cref="EncodeException"/> */ public byte[] Encode( string text ) { io::MemoryStream encodedStream = new io::MemoryStream(); for(int index = 0, length = text.Length; index < length; index++) { int textCode = text[index]; if(textCode < 32) // NOTE: Control characters are ignored [FIX:7]. continue; ByteArray code = codes.GetKey(textCode); if(code == null) // Missing glyph. { switch(Document.Configuration.EncodingFallback) { case EncodingFallbackEnum.Exclusion: continue; case EncodingFallbackEnum.Substitution: code = codes.GetKey(defaultCode); break; case EncodingFallbackEnum.Exception: throw new EncodeException(text, index); default: throw new NotImplementedException(); } } byte[] charCode = code.Data; encodedStream.Write(charCode, 0, charCode.Length); usedCodes.Add(textCode); } encodedStream.Close(); return encodedStream.ToArray(); } public override bool Equals( object obj ) { return obj != null && obj.GetType().Equals(GetType()) && ((Font)obj).Name.Equals(Name); } /** <summary>Gets the font descriptor flags.</summary> */ public virtual FlagsEnum Flags { get { PdfInteger flagsObject = (PdfInteger)GetDescriptorValue(PdfName.Flags); return flagsObject != null ? (FlagsEnum)Enum.ToObject(typeof(FlagsEnum),flagsObject.RawValue) : 0; } } /** <summary>Gets the vertical offset from the baseline to the ascender line (ascent), scaled to the given font size. The value is a positive number.</summary> <param name="size">Font size.</param> */ public double GetAscent( double size ) {return Ascent * GetScalingFactor(size);} /** <summary>Gets the vertical offset from the baseline to the descender line (descent), scaled to the given font size. The value is a negative number.</summary> <param name="size">Font size.</param> */ public double GetDescent( double size ) {return Descent * GetScalingFactor(size);} public override int GetHashCode( ) {return Name.GetHashCode();} private double textHeight = -1; // TODO: temporary until glyph bounding boxes are implemented. /** <summary>Gets the unscaled height of the given character.</summary> <param name="textChar">Character whose height has to be calculated.</param> */ public double GetHeight( char textChar ) { /* TODO: Calculate actual text height through glyph bounding box. */ if(textHeight == -1) {textHeight = Ascent - Descent;} return textHeight; } /** <summary>Gets the height of the given character, scaled to the given font size.</summary> <param name="textChar">Character whose height has to be calculated.</param> <param name="size">Font size.</param> */ public double GetHeight( char textChar, double size ) {return GetHeight(textChar) * GetScalingFactor(size);} /** <summary>Gets the unscaled height of the given text.</summary> <param name="text">Text whose height has to be calculated.</param> */ public double GetHeight( string text ) { double height = 0; for(int index = 0, length = text.Length; index < length; index++) { double charHeight = GetHeight(text[index]); if(charHeight > height) {height = charHeight;} } return height; } /** <summary>Gets the height of the given text, scaled to the given font size.</summary> <param name="text">Text whose height has to be calculated.</param> <param name="size">Font size.</param> */ public double GetHeight( string text, double size ) {return GetHeight(text) * GetScalingFactor(size);} /** <summary>Gets the width (kerning inclusive) of the given text, scaled to the given font size.</summary> <param name="text">Text whose width has to be calculated.</param> <param name="size">Font size.</param> <exception cref="EncodeException"/> */ public double GetKernedWidth( string text, double size ) {return (GetWidth(text) + GetKerning(text)) * GetScalingFactor(size);} /** <summary>Gets the unscaled kerning width between two given characters.</summary> <param name="textChar1">Left character.</param> <param name="textChar2">Right character,</param> */ public int GetKerning( char textChar1, char textChar2 ) { if(glyphKernings == null) return 0; int textChar1Index; if(!glyphIndexes.TryGetValue((int)textChar1, out textChar1Index)) return 0; int textChar2Index; if(!glyphIndexes.TryGetValue((int)textChar2, out textChar2Index)) return 0; int kerning; return glyphKernings.TryGetValue( textChar1Index << 16 // Left-hand glyph index. + textChar2Index, // Right-hand glyph index. out kerning) ? kerning : 0; } /** <summary>Gets the unscaled kerning width inside the given text.</summary> <param name="text">Text whose kerning has to be calculated.</param> */ public int GetKerning( string text ) { int kerning = 0; for(int index = 0, length = text.Length - 1; index < length; index++) { kerning += GetKerning( text[index], text[index + 1] ); } return kerning; } /** <summary>Gets the kerning width inside the given text, scaled to the given font size.</summary> <param name="text">Text whose kerning has to be calculated.</param> <param name="size">Font size.</param> */ public double GetKerning( string text, double size ) {return GetKerning(text) * GetScalingFactor(size);} /** <summary>Gets the line height, scaled to the given font size.</summary> <param name="size">Font size.</param> */ public double GetLineHeight( double size ) {return LineHeight * GetScalingFactor(size);} /** <summary>Gets the unscaled width of the given character.</summary> <param name="textChar">Character whose width has to be calculated.</param> <exception cref="EncodeException"/> */ public int GetWidth( char textChar ) { int glyphIndex; if(!glyphIndexes.TryGetValue((int)textChar, out glyphIndex)) { switch(Document.Configuration.EncodingFallback) { case EncodingFallbackEnum.Exclusion: return 0; case EncodingFallbackEnum.Substitution: return DefaultWidth; case EncodingFallbackEnum.Exception: throw new EncodeException(textChar); default: throw new NotImplementedException(); } } int glyphWidth; return glyphWidths.TryGetValue(glyphIndex, out glyphWidth) ? glyphWidth : DefaultWidth; } /** <summary>Gets the width of the given character, scaled to the given font size.</summary> <param name="textChar">Character whose height has to be calculated.</param> <param name="size">Font size.</param> <exception cref="EncodeException"/> */ public double GetWidth( char textChar, double size ) {return GetWidth(textChar) * GetScalingFactor(size);} /** <summary>Gets the unscaled width (kerning exclusive) of the given text.</summary> <param name="text">Text whose width has to be calculated.</param> <exception cref="EncodeException"/> */ public int GetWidth( string text ) { int width = 0; for(int index = 0, length = text.Length; index < length; index++) {width += GetWidth(text[index]);} return width; } /** <summary>Gets the width (kerning exclusive) of the given text, scaled to the given font size.</summary> <param name="text">Text whose width has to be calculated.</param> <param name="size">Font size.</param> <exception cref="EncodeException"/> */ public double GetWidth( string text, double size ) {return GetWidth(text) * GetScalingFactor(size);} /** <summary>Gets the unscaled line height.</summary> */ public double LineHeight { get {return Ascent - Descent;} } /** <summary>Gets the PostScript name of the font.</summary> */ public string Name { get {return ((PdfName)BaseDataObject[PdfName.BaseFont]).ToString();} } /** <summary>Gets whether the font encoding is custom (that is non-Unicode).</summary> */ public bool Symbolic { get {return symbolic;} } #endregion #region protected /** <summary>Gets/Sets the average glyph width.</summary> */ protected int AverageWidth { get { if(averageWidth == UndefinedWidth) { if(glyphWidths.Count == 0) {averageWidth = 1000;} else { averageWidth = 0; foreach(int glyphWidth in glyphWidths.Values) {averageWidth += glyphWidth;} averageWidth /= glyphWidths.Count; } } return averageWidth; } set {averageWidth = value;} } /** <summary>Gets/Sets the default glyph width.</summary> */ protected int DefaultWidth { get { if(defaultWidth == UndefinedWidth) {defaultWidth = AverageWidth;} return defaultWidth; } set {defaultWidth = value;} } /** <summary>Gets the specified font descriptor entry value.</summary> */ protected abstract PdfDataObject GetDescriptorValue( PdfName key ); /** <summary>Loads font information from existing PDF font structure.</summary> */ protected void Load( ) { if(BaseDataObject.ContainsKey(PdfName.ToUnicode)) // To-Unicode explicit mapping. { PdfStream toUnicodeStream = (PdfStream)BaseDataObject.Resolve(PdfName.ToUnicode); CMapParser parser = new CMapParser(toUnicodeStream.Body); codes = new BiDictionary<ByteArray,int>(parser.Parse()); symbolic = false; } OnLoad(); // Maximum character code length. foreach(ByteArray charCode in codes.Keys) { if(charCode.Data.Length > charCodeMaxLength) {charCodeMaxLength = charCode.Data.Length;} } // Missing character substitute. if(defaultCode == UndefinedDefaultCode) { ICollection<int> codePoints = CodePoints; if(codePoints.Contains((int)'?')) {DefaultCode = '?';} else if(codePoints.Contains((int)' ')) {DefaultCode = ' ';} else {DefaultCode = codePoints.First();} } } /** <summary>Notifies font information loading from an existing PDF font structure.</summary> */ protected abstract void OnLoad( ); #endregion #region private private void Initialize( ) { usedCodes = new HashSet<int>(); // Put the newly-instantiated font into the common cache! /* NOTE: Font structures are reified as complex objects, both IO- and CPU-intensive to load. So, it's convenient to put them into a common cache for later reuse. */ Document.Cache[(PdfReference)BaseObject] = this; } #endregion #endregion #endregion } }
29.813317
155
0.613489
[ "MIT" ]
diegolido/DanfeSharpCore
pdfclown.lib/src/org/pdfclown/documents/contents/fonts/Font.cs
25,073
C#
using System.Collections; using System.Collections.Generic; using UnityEngine; public class ChooseEnemy : MonoBehaviour { public enum Enemy { Rotate, Follow }; public Enemy ActiveState = Enemy.Rotate; public EnemyFollow enemyFollow; public LookAt enemyRotation; private void Start() { enemyFollow = GetComponent<EnemyFollow>(); enemyRotation = GetComponent<LookAt>(); } void Update() { switch (ActiveState) { case Enemy.Rotate: enemyRotation.enabled = true; enemyFollow.enabled = false; break; case Enemy.Follow: enemyFollow.enabled = true; break; } } }
23.15625
50
0.582996
[ "Apache-2.0" ]
Belijoha/vectores-belisario-unity
Assets/Scripts/ChooseEnemy.cs
741
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using MP3ManagerBase.helpers; namespace MP3ManagerBase.manager.Export { /// <summary> /// Dient zum Export einer Playliste im Extneded M3U-Format /// </summary> internal class M3UExtended : IExport { /// <summary> /// Generiert einen Eintrag für den Text-Export /// </summary> /// <param name="artistName"> /// Nam des Interpreten /// </param> /// <param name="titleName"> /// Name des Titels /// </param> /// <returns> /// Umgewandelte Zeichenkette im Text-Format /// </returns> private string ExportTextFormat(string artistName, string titleName) { return string.Format("#EXTINF:-1,{0} - {1}", artistName, titleName); } #region IExport public Encoding TextEncoding { get { return UTF8Encoding.UTF8; } } public byte[] Export(IEnumerable<WSongInformation> songs) { if (songs == null || songs.Count() == 0) { return null; } StringBuilder result = new StringBuilder(); result.AppendLine("#EXTM3U"); foreach (var song in songs) { result.AppendLine(ExportTextFormat(song.Interpret, song.Title)); } return TextEncoding.GetBytes(result.ToString()); } #endregion } }
25.741935
80
0.537594
[ "MIT" ]
Kostarsus/MP3Manager
src/MP3ManagerBase/manager/Export/M3UExtended.cs
1,599
C#
using System.Reflection; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("SqlServer.Rules.Generator")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Tim Cartwright / Troy Phoenix")] [assembly: AssemblyProduct("SqlServer.Rules.Generator")] [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("fa176464-41c2-4ef5-8fbc-ada435f33fae")] // 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")]
40.171429
84
0.748933
[ "MIT" ]
Rogue-Archivists/SqlServer.Rules
SqlServer.Rules.Generator/Properties/AssemblyInfo.cs
1,409
C#
using UnityEngine; using System.Collections; using UnityEditor; namespace TerrainFromMesh { [CustomEditor(typeof(TerrainFromMeshComponent))] public class TerrainFromMeshInspector : Editor { void OnEnable() { EditorApplication.update += Update; } void OnDisable() { EditorApplication.update -= Update; } void Update() { if (generator != null) { if (!generator.MoveNext()) generator = null; } } IEnumerator generator; public override void OnInspectorGUI() { base.OnInspectorGUI(); if (generator == null) { if (GUILayout.Button("Generate from Mesh")) { generator = Generate(); } } else { if (GUILayout.Button("Cancel")) { generator = null; } } } IEnumerator Generate() { TerrainFromMeshComponent tfm = target as TerrainFromMeshComponent; Collider[] colliders = tfm.TerrainParent.GetComponentsInChildren<Collider>(); if (colliders.Length <= 0) { EditorUtility.DisplayDialog("No Colliders found", "The Terrain parent object does not contain any colliders. Please enable Collider generation upon import of the mesh. ", "Dismiss"); Debug.LogError("No colliders found in terrain parent. Aborting. "); yield break; } tfm.mResolution = (float)Mathf.NextPowerOfTwo((int)tfm.mResolution); tfm.mBounds = colliders[0].bounds; Terrain terrain = tfm.GetComponent<Terrain>(); foreach (var c in colliders) { tfm.mBounds.Encapsulate(c.bounds); yield return 0; } tfm.transform.position = tfm.mBounds.min; if (terrain.terrainData == null) { if (EditorUtility.DisplayDialog("No Terrain Data found", "The target Terrain does not contain Terrain Data. ", "Create New", "Abort")) { var terrainData = new TerrainData(); var terrainDataPath = AssetDatabase.GenerateUniqueAssetPath("Assets/Terrain Data.asset"); AssetDatabase.CreateAsset(terrainData, terrainDataPath); terrain.terrainData = terrainData; } else { Debug.LogError("No Terrain Data found. Aborting. "); yield break; } } terrain.terrainData.heightmapResolution = (int)tfm.mResolution; terrain.terrainData.size = tfm.mBounds.size; RaycastHit hitInfo; float[,] data = new float[1, (int)tfm.mResolution]; for (int y = 0; y < tfm.mResolution; y++) { for (int x = 0; x < tfm.mResolution; x++) { Ray r = GetRay(x, y, tfm); tfm.mRays.Enqueue(r); if (Physics.Raycast(r, out hitInfo)) { data[0, x] = 1 - ((hitInfo.distance - 50) / tfm.mBounds.size.y); } } terrain.terrainData.SetHeights(0, y, data); yield return 0; tfm.mRays.Clear(); } } Ray GetRay(int x, int y, TerrainFromMeshComponent pTarget) { Vector3 source = pTarget.mBounds.min; source += new Vector3(pTarget.mBounds.size.x * x / pTarget.mResolution, 0, 0); source += new Vector3(0, 0, pTarget.mBounds.size.z * y / pTarget.mResolution); source.y = pTarget.mBounds.max.y + 50; return new Ray(source, Vector3.down); } } }
31.387597
198
0.496172
[ "MIT" ]
kwnetzwelt/unity-blender-terrain-tools
Assets/TerrainFromMesh/scripts/Editor/TerrainFromMeshInspector.cs
4,049
C#
using Stump.DofusProtocol.Enums; using Stump.Server.WorldServer.Database.Items; using Stump.Server.WorldServer.Game.Actors.Look; using Stump.Server.WorldServer.Game.Actors.RolePlay.Characters; namespace Stump.Server.WorldServer.Game.Items.Player.Custom { [ItemId(ItemIdEnum.DOCTEUR_MINEUR_13754)] // ID ITEM - NOM public class Rebours : BasePlayerItem { public Rebours(Character owner, PlayerItemRecord record) : base(owner, record) { } public override bool OnEquipItem(bool unequip) { var spellid = 2811; //ID SORT string name = "Rebours";//NOM SORT if (IsEquiped() && !Owner.Spells.HasSpell(spellid)) { Owner.Spells.LearnSpell(spellid); Owner.SendServerMessage("Vous venez d'apprendre le sort "+name+"."); Owner.RefreshActor(); } else { if (Owner.Spells.HasSpell(spellid)) { Owner.SendServerMessage("Vous venez de désapprendre le sort " + name + "."); Owner.Spells.UnLearnSpell(spellid); Owner.RefreshActor(); } } return base.OnEquipItem(unequip); } } }
30.302326
96
0.56485
[ "Apache-2.0" ]
Daymortel/Stump
src/Stump.Server.WorldServer/game/items/player/Custom/SpellItem/roublard/Rebours.cs
1,304
C#
using System.Collections; using System.Collections.Generic; using UnityEngine; using Cysharp.Threading.Tasks; using static Helpers; public class GameManager : MonoBehaviour { public Texture2D cursorTexture; public Vector2 cursorHotSpot = Vector2.zero; public GameObject clockWidget; public GameObject scoreWidget; public GameObject startButton; public GameObject playAgainButton; private Globals globals; public float totalGameTime; float currentGameTime = 0.0f; void Start() { globals = GetComponent<Globals>(); Cursor.SetCursor(cursorTexture, cursorHotSpot, CursorMode.ForceSoftware); startButton.GetComponent<TextButtonController>() .OnButtonClicked += StartGame; playAgainButton.GetComponent<TextButtonController>() .OnButtonClicked += UniTask.Action(RestartGame); } void Update() { currentGameTime += Time.deltaTime; if (currentGameTime >= totalGameTime) { if (!globals.gameOver) { globals.gameOver = true; EndGame().Forget(); } } else if (!globals.gameOver) { var timeLeft = (totalGameTime - currentGameTime) / totalGameTime; clockWidget.GetComponent<MeterScript>().SetHealth(timeLeft); globals.speed = 1.0f + 3.0f * (currentGameTime / totalGameTime); } } private void StartGame() { currentGameTime = 0.0f; globals.gameOver = false; Events.OnGameStart.Invoke(); var fadeDuration = 0.5f; UniTask.Void(async () => { await Animations.FadeOut(startButton, fadeDuration); Destroy(startButton); }); var renderers = GameObject.Find("Logo").GetComponentsInChildren<SpriteRenderer>(); foreach (var renderer in renderers) { UniTask.Void(async () => { await UniTask.Delay(Seconds(Random.Range(0.0f, 1.0f))); await Animations.FadeOut(renderer.gameObject, fadeDuration); Destroy(renderer.gameObject); }); } } private async UniTaskVoid EndGame() { clockWidget.GetComponent<MeterScript>().SetHealth(0); Events.OnGameEnd.Invoke(); await UniTask.Delay(Seconds(3)); playAgainButton.SetActive(true); await Animations.FadeIn(playAgainButton, 0.5f); } private async UniTaskVoid RestartGame() { currentGameTime = 0.0f; globals.gameOver = false; Events.OnGameRestart.Invoke(); await Animations.FadeOut(playAgainButton, 0.5f); playAgainButton.SetActive(false); } }
28.904255
90
0.622378
[ "MIT" ]
letmaik/leafy
Assets/Scripts/GameManager.cs
2,717
C#
using Microsoft.EntityFrameworkCore.Migrations; namespace Registru_Intrari_Iesiri.Migrations { public partial class CreateDocumentsNumbersSequence : Migration { protected override void Up(MigrationBuilder migrationBuilder) { migrationBuilder.CreateSequence<int>("DocumentNumberSequence", startValue: 1, incrementBy: 1); } protected override void Down(MigrationBuilder migrationBuilder) { migrationBuilder.DropSequence("DocumentNumberSequence"); } } }
29.888889
106
0.710037
[ "MIT" ]
rododendron1001/Registru_Intrari_Iesiri_V1
Registru_Intrari_Iesiri/Registru_Intrari_Iesiri/Migrations/20200824165948_CreateDocumentsNumbersSequence.cs
540
C#
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Threading; using System.Threading.Tasks; namespace AzurePipelines.TestLogger { internal class LoggerQueue { private readonly AsyncProducerConsumerCollection<ITestResult> _queue = new AsyncProducerConsumerCollection<ITestResult>(); private readonly Task _consumeTask; private readonly CancellationTokenSource _consumeTaskCancellationSource = new CancellationTokenSource(); private readonly IApiClient _apiClient; private readonly string _buildId; private readonly string _agentName; private readonly string _jobName; private readonly bool _groupTestResultsByClassName; // Internal for testing internal Dictionary<string, TestResultParent> Parents { get; } = new Dictionary<string, TestResultParent>(); internal DateTime StartedDate { get; } = DateTime.UtcNow; internal int RunId { get; set; } internal string Source { get; set; } public LoggerQueue(IApiClient apiClient, string buildId, string agentName, string jobName, bool groupTestResultsByClassName = true) { _apiClient = apiClient; _buildId = buildId; _agentName = agentName; _jobName = jobName; _groupTestResultsByClassName = groupTestResultsByClassName; _consumeTask = ConsumeItemsAsync(_consumeTaskCancellationSource.Token); } public void Enqueue(ITestResult testResult) => _queue.Add(testResult); public void Flush() { // Cancel any idle consumers and let them return _queue.Cancel(); try { // Any active consumer will circle back around and batch post the remaining queue _consumeTask.Wait(TimeSpan.FromSeconds(60)); // Update the run and parents to a completed state SendTestsCompleted(_consumeTaskCancellationSource.Token).Wait(TimeSpan.FromSeconds(60)); // Cancel any active HTTP requests if still hasn't finished flushing _consumeTaskCancellationSource.Cancel(); if (!_consumeTask.Wait(TimeSpan.FromSeconds(10))) { throw new TimeoutException("Cancellation didn't happen quickly"); } } catch (Exception ex) { Console.WriteLine(ex); } } private async Task ConsumeItemsAsync(CancellationToken cancellationToken) { while (true) { ITestResult[] nextItems = await _queue.TakeAsync().ConfigureAwait(false); if (nextItems == null || nextItems.Length == 0) { // Queue is canceling and is empty return; } await SendResultsAsync(nextItems, cancellationToken).ConfigureAwait(false); if (cancellationToken.IsCancellationRequested) { return; } } } private async Task SendResultsAsync(ITestResult[] testResults, CancellationToken cancellationToken) { try { // Create a test run if we need it if (RunId == 0) { Source = GetSource(testResults); RunId = await CreateTestRun(cancellationToken).ConfigureAwait(false); } // Group results by their parent IEnumerable<IGrouping<string, ITestResult>> testResultsByParent = GroupTestResultsByParent(testResults); // Create any required parent nodes await CreateParents(testResultsByParent, cancellationToken).ConfigureAwait(false); // Update parents with the test results await SendTestResults(testResultsByParent, cancellationToken).ConfigureAwait(false); } catch (Exception) { // Eat any communications exceptions } } // Internal for testing internal static string GetSource(ITestResult[] testResults) { string source = Array.Find(testResults, x => !string.IsNullOrEmpty(x.Source))?.Source; if (source != null) { source = Path.GetFileName(source); if (source.EndsWith(".dll")) { return source.Substring(0, source.Length - 4); } } return source; } // Internal for testing internal async Task<int> CreateTestRun(CancellationToken cancellationToken) { string runName = $"{(string.IsNullOrEmpty(Source) ? "Unknown Test Source" : Source)} (OS: {System.Runtime.InteropServices.RuntimeInformation.OSDescription}, Job: {_jobName}, Agent: {_agentName})"; TestRun testRun = new TestRun { Name = runName, BuildId = _buildId, StartedDate = StartedDate, IsAutomated = true }; return await _apiClient.AddTestRun(testRun, cancellationToken).ConfigureAwait(false); } // Internal for testing internal IEnumerable<IGrouping<string, ITestResult>> GroupTestResultsByParent(ITestResult[] testResults) => testResults.GroupBy(x => { // Namespace.ClassName.MethodName string name = x.FullyQualifiedName; if (Source != null && name.StartsWith(Source + ".")) { // remove the namespace name = name.Substring(Source.Length + 1); } // At this point, name should always have at least one '.' to represent the Class.Method if (_groupTestResultsByClassName) { // We need to start at the opening method if there is one int startIndex = name.IndexOf('('); if (startIndex < 0) { startIndex = name.Length - 1; } // remove the method name to get just the class name return name.Substring(0, name.LastIndexOf('.', startIndex)); } else { // remove the class name to get just the method name return name.Substring(name.IndexOf('.') + 1); } }); // Internal for testing internal async Task CreateParents(IEnumerable<IGrouping<string, ITestResult>> testResultsByParent, CancellationToken cancellationToken) { // Find the parents that don't exist string[] parentsToAdd = testResultsByParent .Select(x => x.Key) .Where(x => !Parents.ContainsKey(x)) .ToArray(); // Batch an add operation and record the new parent IDs DateTime startedDate = DateTime.UtcNow; if (parentsToAdd.Length > 0) { int[] parents = await _apiClient.AddTestCases(RunId, parentsToAdd, startedDate, Source, cancellationToken).ConfigureAwait(false); for (int i = 0; i < parents.Length; i++) { Parents.Add(parentsToAdd[i], new TestResultParent(parents[i], startedDate)); } } } private Task SendTestResults(IEnumerable<IGrouping<string, ITestResult>> testResultsByParent, CancellationToken cancellationToken) { return _apiClient.UpdateTestResults(RunId, Parents, testResultsByParent, cancellationToken); } private async Task SendTestsCompleted(CancellationToken cancellationToken) { DateTime completedDate = DateTime.UtcNow; // Mark all parents as completed (but only if we actually created a parent) if (RunId != 0) { if (Parents.Values.Count > 0) { await _apiClient.MarkTestCasesCompleted(RunId, Parents.Values, completedDate, cancellationToken).ConfigureAwait(false); } await _apiClient.MarkTestRunCompleted(RunId, StartedDate, completedDate, cancellationToken).ConfigureAwait(false); } } } }
39.504545
208
0.563456
[ "MIT" ]
daveaglick/AzurePipelines.TestLogger
src/AzurePipelines.TestLogger/LoggerQueue.cs
8,693
C#
using System; using System.Collections.Generic; using System.Text; namespace TMS.ShopSimulator { internal class Cashier { private static Random rnd = new Random(); public int TimeToProcess { get; } public string Name { get; } public Cashier(int num) { this.TimeToProcess = rnd.Next(3000); this.Name = $"#{num}"; } } }
18.5
49
0.572482
[ "MIT" ]
tms-net/NET06
HomeWorks/HomeWork11/TMS.ShopSimulator/Cashier.cs
409
C#
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.UnitTests { public partial class IOperationTests : SemanticModelTestBase { // The tests in this file right now are just to verify that we do not assert in the CFG builder. These need to be expanded. // https://github.com/dotnet/roslyn/issues/31545 [Fact] public void PatternIndexAndRangeIndexer() { var src = @" class C { public int Length => 0; public int this[int i] => i; public int Slice(int i, int j) => i; public void M() /*<bind*/{ _ = this[^0]; _ = this[0..]; }/*</bind>*/ }"; var comp = CreateCompilationWithIndexAndRange(src); const string expectedOperationTree = @" IBlockOperation (2 statements) (OperationKind.Block, Type: null) (Syntax: '{ ... }') IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: '_ = this[^0];') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32) (Syntax: '_ = this[^0]') Left: IDiscardOperation (Symbol: System.Int32 _) (OperationKind.Discard, Type: System.Int32) (Syntax: '_') Right: IOperation: (OperationKind.None, Type: null) (Syntax: 'this[^0]') Children(2): IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: C) (Syntax: 'this') IUnaryOperation (UnaryOperatorKind.Hat) (OperationKind.Unary, Type: System.Index) (Syntax: '^0') Operand: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 0) (Syntax: '0') IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: '_ = this[0..];') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32) (Syntax: '_ = this[0..]') Left: IDiscardOperation (Symbol: System.Int32 _) (OperationKind.Discard, Type: System.Int32) (Syntax: '_') Right: IOperation: (OperationKind.None, Type: null) (Syntax: 'this[0..]') Children(2): IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: C) (Syntax: 'this') IRangeOperation (OperationKind.Range, Type: System.Range) (Syntax: '0..') LeftOperand: IConversionOperation (TryCast: False, Unchecked) (OperatorMethod: System.Index System.Index.op_Implicit(System.Int32 value)) (OperationKind.Conversion, Type: System.Index, IsImplicit) (Syntax: '0') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: True) (MethodSymbol: System.Index System.Index.op_Implicit(System.Int32 value)) Operand: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 0) (Syntax: '0') RightOperand: null"; VerifyOperationTreeAndDiagnosticsForTest<BlockSyntax>(comp, expectedOperationTree, DiagnosticDescription.None); VerifyOperationTreeAndDiagnosticsForTest<BlockSyntax>(comp, expectedOperationTree, DiagnosticDescription.None); var expectedFlowGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Block[B1] - Block Predecessors: [B0] Statements (2) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: '_ = this[^0];') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32) (Syntax: '_ = this[^0]') Left: IDiscardOperation (Symbol: System.Int32 _) (OperationKind.Discard, Type: System.Int32) (Syntax: '_') Right: IOperation: (OperationKind.None, Type: null) (Syntax: 'this[^0]') Children(2): IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: C) (Syntax: 'this') IUnaryOperation (UnaryOperatorKind.Hat) (OperationKind.Unary, Type: System.Index) (Syntax: '^0') Operand: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 0) (Syntax: '0') IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: '_ = this[0..];') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32) (Syntax: '_ = this[0..]') Left: IDiscardOperation (Symbol: System.Int32 _) (OperationKind.Discard, Type: System.Int32) (Syntax: '_') Right: IOperation: (OperationKind.None, Type: null) (Syntax: 'this[0..]') Children(2): IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: C) (Syntax: 'this') IRangeOperation (OperationKind.Range, Type: System.Range) (Syntax: '0..') LeftOperand: IConversionOperation (TryCast: False, Unchecked) (OperatorMethod: System.Index System.Index.op_Implicit(System.Int32 value)) (OperationKind.Conversion, Type: System.Index, IsImplicit) (Syntax: '0') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: True) (MethodSymbol: System.Index System.Index.op_Implicit(System.Int32 value)) (ImplicitUserDefined) Operand: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 0) (Syntax: '0') RightOperand: null Next (Regular) Block[B2] Block[B2] - Exit Predecessors: [B1] Statements (0)"; VerifyFlowGraphForTest<BlockSyntax>(comp, expectedFlowGraph); } [Fact] public void FromEndIndexFlow_01() { var source = @" class Test { void M(int arg) /*<bind>*/{ var x = ^arg; }/*</bind>*/ }"; var compilation = CreateCompilationWithIndex(source); var expectedOperationTree = @" IBlockOperation (1 statements, 1 locals) (OperationKind.Block, Type: null) (Syntax: '{ ... }') Locals: Local_1: System.Index x IVariableDeclarationGroupOperation (1 declarations) (OperationKind.VariableDeclarationGroup, Type: null) (Syntax: 'var x = ^arg;') IVariableDeclarationOperation (1 declarators) (OperationKind.VariableDeclaration, Type: null) (Syntax: 'var x = ^arg') Declarators: IVariableDeclaratorOperation (Symbol: System.Index x) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'x = ^arg') Initializer: IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null) (Syntax: '= ^arg') IUnaryOperation (UnaryOperatorKind.Hat) (OperationKind.Unary, Type: System.Index) (Syntax: '^arg') Operand: IParameterReferenceOperation: arg (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'arg') Initializer: null"; var diagnostics = DiagnosticDescription.None; VerifyOperationTreeAndDiagnosticsForTest<BlockSyntax>(compilation, expectedOperationTree, diagnostics); var expectedFlowGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { Locals: [System.Index x] Block[B1] - Block Predecessors: [B0] Statements (1) ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Index, IsImplicit) (Syntax: 'x = ^arg') Left: ILocalReferenceOperation: x (IsDeclaration: True) (OperationKind.LocalReference, Type: System.Index, IsImplicit) (Syntax: 'x = ^arg') Right: IUnaryOperation (UnaryOperatorKind.Hat) (OperationKind.Unary, Type: System.Index) (Syntax: '^arg') Operand: IParameterReferenceOperation: arg (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'arg') Next (Regular) Block[B2] Leaving: {R1} } Block[B2] - Exit Predecessors: [B1] Statements (0)"; VerifyFlowGraphForTest<BlockSyntax>(compilation, expectedFlowGraph); } [Fact] public void RangeFlow_01() { var source = @" using System; class Test { void M(Index start, Index end) /*<bind>*/{ var a = start..end; var b = start..; var c = ..end; var d = ..; }/*</bind>*/ }"; var compilation = CreateCompilationWithIndexAndRange(source); var expectedOperationTree = @" IBlockOperation (4 statements, 4 locals) (OperationKind.Block, Type: null) (Syntax: '{ ... }') Locals: Local_1: System.Range a Local_2: System.Range b Local_3: System.Range c Local_4: System.Range d IVariableDeclarationGroupOperation (1 declarations) (OperationKind.VariableDeclarationGroup, Type: null) (Syntax: 'var a = start..end;') IVariableDeclarationOperation (1 declarators) (OperationKind.VariableDeclaration, Type: null) (Syntax: 'var a = start..end') Declarators: IVariableDeclaratorOperation (Symbol: System.Range a) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'a = start..end') Initializer: IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null) (Syntax: '= start..end') IRangeOperation (OperationKind.Range, Type: System.Range) (Syntax: 'start..end') LeftOperand: IParameterReferenceOperation: start (OperationKind.ParameterReference, Type: System.Index) (Syntax: 'start') RightOperand: IParameterReferenceOperation: end (OperationKind.ParameterReference, Type: System.Index) (Syntax: 'end') Initializer: null IVariableDeclarationGroupOperation (1 declarations) (OperationKind.VariableDeclarationGroup, Type: null) (Syntax: 'var b = start..;') IVariableDeclarationOperation (1 declarators) (OperationKind.VariableDeclaration, Type: null) (Syntax: 'var b = start..') Declarators: IVariableDeclaratorOperation (Symbol: System.Range b) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'b = start..') Initializer: IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null) (Syntax: '= start..') IRangeOperation (OperationKind.Range, Type: System.Range) (Syntax: 'start..') LeftOperand: IParameterReferenceOperation: start (OperationKind.ParameterReference, Type: System.Index) (Syntax: 'start') RightOperand: null Initializer: null IVariableDeclarationGroupOperation (1 declarations) (OperationKind.VariableDeclarationGroup, Type: null) (Syntax: 'var c = ..end;') IVariableDeclarationOperation (1 declarators) (OperationKind.VariableDeclaration, Type: null) (Syntax: 'var c = ..end') Declarators: IVariableDeclaratorOperation (Symbol: System.Range c) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'c = ..end') Initializer: IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null) (Syntax: '= ..end') IRangeOperation (OperationKind.Range, Type: System.Range) (Syntax: '..end') LeftOperand: null RightOperand: IParameterReferenceOperation: end (OperationKind.ParameterReference, Type: System.Index) (Syntax: 'end') Initializer: null IVariableDeclarationGroupOperation (1 declarations) (OperationKind.VariableDeclarationGroup, Type: null) (Syntax: 'var d = ..;') IVariableDeclarationOperation (1 declarators) (OperationKind.VariableDeclaration, Type: null) (Syntax: 'var d = ..') Declarators: IVariableDeclaratorOperation (Symbol: System.Range d) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'd = ..') Initializer: IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null) (Syntax: '= ..') IRangeOperation (OperationKind.Range, Type: System.Range) (Syntax: '..') LeftOperand: null RightOperand: null Initializer: null "; var diagnostics = DiagnosticDescription.None; VerifyOperationTreeAndDiagnosticsForTest<BlockSyntax>(compilation, expectedOperationTree, diagnostics); var expectedFlowGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { Locals: [System.Range a] [System.Range b] [System.Range c] [System.Range d] Block[B1] - Block Predecessors: [B0] Statements (4) ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Range, IsImplicit) (Syntax: 'a = start..end') Left: ILocalReferenceOperation: a (IsDeclaration: True) (OperationKind.LocalReference, Type: System.Range, IsImplicit) (Syntax: 'a = start..end') Right: IRangeOperation (OperationKind.Range, Type: System.Range) (Syntax: 'start..end') LeftOperand: IParameterReferenceOperation: start (OperationKind.ParameterReference, Type: System.Index) (Syntax: 'start') RightOperand: IParameterReferenceOperation: end (OperationKind.ParameterReference, Type: System.Index) (Syntax: 'end') ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Range, IsImplicit) (Syntax: 'b = start..') Left: ILocalReferenceOperation: b (IsDeclaration: True) (OperationKind.LocalReference, Type: System.Range, IsImplicit) (Syntax: 'b = start..') Right: IRangeOperation (OperationKind.Range, Type: System.Range) (Syntax: 'start..') LeftOperand: IParameterReferenceOperation: start (OperationKind.ParameterReference, Type: System.Index) (Syntax: 'start') RightOperand: null ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Range, IsImplicit) (Syntax: 'c = ..end') Left: ILocalReferenceOperation: c (IsDeclaration: True) (OperationKind.LocalReference, Type: System.Range, IsImplicit) (Syntax: 'c = ..end') Right: IRangeOperation (OperationKind.Range, Type: System.Range) (Syntax: '..end') LeftOperand: null RightOperand: IParameterReferenceOperation: end (OperationKind.ParameterReference, Type: System.Index) (Syntax: 'end') ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Range, IsImplicit) (Syntax: 'd = ..') Left: ILocalReferenceOperation: d (IsDeclaration: True) (OperationKind.LocalReference, Type: System.Range, IsImplicit) (Syntax: 'd = ..') Right: IRangeOperation (OperationKind.Range, Type: System.Range) (Syntax: '..') LeftOperand: null RightOperand: null Next (Regular) Block[B2] Leaving: {R1} } Block[B2] - Exit Predecessors: [B1] Statements (0) "; VerifyFlowGraphForTest<BlockSyntax>(compilation, expectedFlowGraph); } } }
50.507692
223
0.629302
[ "MIT" ]
Acidburn0zzz/roslyn
src/Compilers/CSharp/Test/IOperation/IOperation/IOperationTests_IFromEndIndexOperation_IRangeOperation.cs
16,417
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.Collections.Generic; namespace Microsoft.AspNetCore.Razor.Language; public interface IImportProjectFeature : IRazorProjectEngineFeature { IReadOnlyList<RazorProjectItem> GetImports(RazorProjectItem projectItem); }
31
77
0.814516
[ "MIT" ]
MitrichDot/aspnetcore
src/Razor/Microsoft.AspNetCore.Razor.Language/src/IImportProjectFeature.cs
374
C#
namespace R1Engine { public class GBC_Knot : R1Serializable { public byte ActorsCount { get; set; } public ushort[] Actors { get; set; } public override void SerializeImpl(SerializerObject s) { ActorsCount = s.Serialize<byte>(ActorsCount, name: nameof(ActorsCount)); Actors = s.SerializeArray<ushort>(Actors, ActorsCount, name: nameof(Actors)); } } }
30.571429
89
0.621495
[ "MIT" ]
rtsonneveld/Ray1Map
Assets/Scripts/DataTypes/GBC/Level/Scene/GBC_Knot.cs
430
C#
/* Generated By:CSharpCC: Do not edit this line. Token.cs Version 3.0 */ /// <summary> /// Describes the input token stream. /// </summary> public class Token { /// <summary> /// Gets an integer that describes the kind of this token. /// </summary> /// <remarks> /// This numbering system is determined by CSharpCCParser, and /// a table of these numbers is stored in the class <see cref="SelectorParserConstants"/>. /// </remarks> public int kind; /** * beginLine and beginColumn describe the position of the first character * of this token; endLine and endColumn describe the position of the * last character of this token. */ public int beginLine, beginColumn, endLine, endColumn; /** * The string image of the token. */ public string image; /** * A reference to the next regular (non-special) token from the input * stream. If this is the last token from the input stream, or if the * token manager has not read tokens beyond this one, this field is * set to null. This is true only if this token is also a regular * token. Otherwise, see below for a description of the contents of * this field. */ public Token next; /** * This field is used to access special tokens that occur prior to this * token, but after the immediately preceding regular (non-special) token. * If there are no such special tokens, this field is set to null. * When there are more than one such special token, this field refers * to the last of these special tokens, which in turn refers to the next * previous special token through its specialToken field, and so on * until the first special token (whose specialToken field is null). * The next fields of special tokens refer to other special tokens that * immediately follow it (without an intervening regular token). If there * is no such token, this field is null. */ public Token specialToken; /** * Returns the image. */ public override string ToString() { return image; } /** * Returns a new Token object, by default. However, if you want, you * can create and return subclass objects based on the value of ofKind. * Simply add the cases to the switch for all those special cases. * For example, if you have a subclass of Token called IDToken that * you want to create if ofKind is ID, simlpy add something like : * * case MyParserConstants.ID : return new IDToken(); * * to the following switch statement. Then you can cast matchedToken * variable to the appropriate type and use it in your lexical actions. */ public static Token NewToken(int ofKind) { switch(ofKind) { default : return new Token(); } } }
34.658228
92
0.691015
[ "Apache-2.0" ]
apache/activemq-nms-msmq
src/main/csharp/Selector/Token.cs
2,738
C#
using System; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Maui.Internals; namespace System.Maui { internal sealed class ReadOnlyListAdapter : IList { readonly IReadOnlyCollection<object> _collection; readonly IReadOnlyList<object> _list; public ReadOnlyListAdapter(IReadOnlyList<object> list) { _list = list; _collection = list; } public ReadOnlyListAdapter(IReadOnlyCollection<object> collection) { _collection = collection; } public void CopyTo(Array array, int index) { throw new NotImplementedException(); } public int Count { get { return _collection.Count; } } public bool IsSynchronized { get { throw new NotImplementedException(); } } public object SyncRoot { get { throw new NotImplementedException(); } } public IEnumerator GetEnumerator() { return _collection.GetEnumerator(); } public int Add(object value) { throw new NotImplementedException(); } public void Clear() { throw new NotImplementedException(); } public bool Contains(object value) { return _list.Contains(value); } public int IndexOf(object value) { return _list.IndexOf(value); } public void Insert(int index, object value) { throw new NotImplementedException(); } public bool IsFixedSize { get { throw new NotImplementedException(); } } public bool IsReadOnly { get { return true; } } public object this[int index] { get { return _list[index]; } set { throw new NotImplementedException(); } } public void Remove(object value) { throw new NotImplementedException(); } public void RemoveAt(int index) { throw new NotImplementedException(); } } }
17.346535
68
0.694635
[ "MIT" ]
AswinPG/maui
System.Maui.Core/ReadOnlyListAdapter.cs
1,752
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using NewLife.Caching; using NewLife.Log; using Xunit; namespace XUnitTest { public class HashTest { private readonly FullRedis _redis; public HashTest() { _redis = new FullRedis("127.0.0.1:6379", null, 2); #if DEBUG _redis.Log = XTrace.Log; #endif } [Fact] public void HMSETTest() { var key = "hash_key"; // 删除已有 _redis.Remove(key); var hash = _redis.GetDictionary<String>(key) as RedisHash<String, String>; Assert.NotNull(hash); var dic = new Dictionary<String, String> { ["aaa"] = "123", ["bbb"] = "456" }; var rs = hash.HMSet(dic); Assert.True(rs); Assert.Equal(2, hash.Count); Assert.True(hash.ContainsKey("aaa")); } [Fact] public void Search() { var rkey = "hash_Search"; // 删除已有 _redis.Remove(rkey); var hash = _redis.GetDictionary<Double>(rkey); var hash2 = hash as RedisHash<String, Double>; // 插入数据 hash.Add("stone1", 12.34); hash.Add("stone2", 13.56); hash.Add("stone3", 14.34); hash.Add("stone4", 15.34); Assert.Equal(4, hash.Count); var dic = hash2.Search("*one?", 3).ToDictionary(e => e.Key, e => e.Value); Assert.Equal(3, dic.Count); Assert.Equal("stone1", dic.Skip(0).First().Key); Assert.Equal("stone2", dic.Skip(1).First().Key); Assert.Equal("stone3", dic.Skip(2).First().Key); } [Fact] public void QuoteTest() { var key = "hash_quote"; // 删除已有 _redis.Remove(key); var hash = _redis.GetDictionary<String>(key); Assert.NotNull(hash); var org1 = "\"TypeName\":\"集团\""; var org5 = "\"LastUpdateTime\":\"2021-10-12 20:07:03\""; hash["org1"] = org1; hash["org5"] = org5; Assert.Equal(org1, hash["org1"]); Assert.Equal(org5, hash["org5"]); } } }
25.282609
86
0.484953
[ "MIT" ]
JohnZhaoXiaoHu/NewLife.Redis
XUnitTest/HashTest.cs
2,364
C#
 namespace BrmsGeneratorResearcher { partial class CptForm { /// <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.NameGroupBox = new System.Windows.Forms.GroupBox(); this.NameTextBox = new System.Windows.Forms.TextBox(); this.groupBox2 = new System.Windows.Forms.GroupBox(); this.StimulusShapeUpDown = new System.Windows.Forms.DomainUpDown(); this.label1 = new System.Windows.Forms.Label(); this.AddOtherColorTextBox = new System.Windows.Forms.TextBox(); this.ChoicesButton = new System.Windows.Forms.Button(); this.OtherColorsTextBox = new System.Windows.Forms.TextBox(); this.label2 = new System.Windows.Forms.Label(); this.StimulusColorTextBox = new System.Windows.Forms.TextBox(); this.label19 = new System.Windows.Forms.Label(); this.SubBlockNumeric = new System.Windows.Forms.NumericUpDown(); this.SubBlockLabel = new System.Windows.Forms.Label(); this.BlockNumeric = new System.Windows.Forms.NumericUpDown(); this.BlockLabel = new System.Windows.Forms.Label(); this.SaveButton = new System.Windows.Forms.Button(); this.NameGroupBox.SuspendLayout(); this.groupBox2.SuspendLayout(); ((System.ComponentModel.ISupportInitialize)(this.SubBlockNumeric)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.BlockNumeric)).BeginInit(); this.SuspendLayout(); // // NameGroupBox // this.NameGroupBox.Controls.Add(this.NameTextBox); this.NameGroupBox.Location = new System.Drawing.Point(32, 29); this.NameGroupBox.Margin = new System.Windows.Forms.Padding(8, 7, 8, 7); this.NameGroupBox.Name = "NameGroupBox"; this.NameGroupBox.Padding = new System.Windows.Forms.Padding(8, 7, 8, 7); this.NameGroupBox.Size = new System.Drawing.Size(1184, 122); this.NameGroupBox.TabIndex = 37; this.NameGroupBox.TabStop = false; this.NameGroupBox.Text = "Name"; // // NameTextBox // this.NameTextBox.Location = new System.Drawing.Point(21, 41); this.NameTextBox.Margin = new System.Windows.Forms.Padding(5, 2, 5, 2); this.NameTextBox.Name = "NameTextBox"; this.NameTextBox.Size = new System.Drawing.Size(1119, 38); this.NameTextBox.TabIndex = 0; // // groupBox2 // this.groupBox2.Controls.Add(this.StimulusShapeUpDown); this.groupBox2.Controls.Add(this.label1); this.groupBox2.Controls.Add(this.AddOtherColorTextBox); this.groupBox2.Controls.Add(this.ChoicesButton); this.groupBox2.Controls.Add(this.OtherColorsTextBox); this.groupBox2.Controls.Add(this.label2); this.groupBox2.Controls.Add(this.StimulusColorTextBox); this.groupBox2.Controls.Add(this.label19); this.groupBox2.Location = new System.Drawing.Point(32, 162); this.groupBox2.Margin = new System.Windows.Forms.Padding(5); this.groupBox2.Name = "groupBox2"; this.groupBox2.Padding = new System.Windows.Forms.Padding(5); this.groupBox2.Size = new System.Drawing.Size(1184, 262); this.groupBox2.TabIndex = 38; this.groupBox2.TabStop = false; this.groupBox2.Text = "Parameters"; // // StimulusShapeUpDown // this.StimulusShapeUpDown.Items.Add("square"); this.StimulusShapeUpDown.Items.Add("circle"); this.StimulusShapeUpDown.Items.Add("triangle"); this.StimulusShapeUpDown.Items.Add("down_triangle"); this.StimulusShapeUpDown.Location = new System.Drawing.Point(434, 112); this.StimulusShapeUpDown.Margin = new System.Windows.Forms.Padding(8, 7, 8, 7); this.StimulusShapeUpDown.Name = "StimulusShapeUpDown"; this.StimulusShapeUpDown.Size = new System.Drawing.Size(275, 38); this.StimulusShapeUpDown.TabIndex = 77; // // label1 // this.label1.AutoSize = true; this.label1.Location = new System.Drawing.Point(13, 112); this.label1.Margin = new System.Windows.Forms.Padding(8, 0, 8, 0); this.label1.Name = "label1"; this.label1.Size = new System.Drawing.Size(215, 32); this.label1.TabIndex = 76; this.label1.Text = "Stimulus Shape"; // // AddOtherColorTextBox // this.AddOtherColorTextBox.Location = new System.Drawing.Point(405, 176); this.AddOtherColorTextBox.Margin = new System.Windows.Forms.Padding(5, 2, 5, 2); this.AddOtherColorTextBox.MaxLength = 7; this.AddOtherColorTextBox.Name = "AddOtherColorTextBox"; this.AddOtherColorTextBox.Size = new System.Drawing.Size(223, 38); this.AddOtherColorTextBox.TabIndex = 75; // // ChoicesButton // this.ChoicesButton.Location = new System.Drawing.Point(648, 176); this.ChoicesButton.Margin = new System.Windows.Forms.Padding(8, 7, 8, 7); this.ChoicesButton.Name = "ChoicesButton"; this.ChoicesButton.Size = new System.Drawing.Size(61, 45); this.ChoicesButton.TabIndex = 74; this.ChoicesButton.Text = "+"; this.ChoicesButton.UseVisualStyleBackColor = true; this.ChoicesButton.Click += new System.EventHandler(this.ChoicesButton_Click); // // OtherColorsTextBox // this.OtherColorsTextBox.Enabled = false; this.OtherColorsTextBox.Location = new System.Drawing.Point(723, 181); this.OtherColorsTextBox.Margin = new System.Windows.Forms.Padding(5, 2, 5, 2); this.OtherColorsTextBox.Name = "OtherColorsTextBox"; this.OtherColorsTextBox.Size = new System.Drawing.Size(417, 38); this.OtherColorsTextBox.TabIndex = 73; // // label2 // this.label2.AutoSize = true; this.label2.Location = new System.Drawing.Point(13, 181); this.label2.Margin = new System.Windows.Forms.Padding(8, 0, 8, 0); this.label2.Name = "label2"; this.label2.Size = new System.Drawing.Size(377, 32); this.label2.TabIndex = 72; this.label2.Text = "Other colors (RGB include #)"; // // StimulusColorTextBox // this.StimulusColorTextBox.Location = new System.Drawing.Point(434, 53); this.StimulusColorTextBox.Margin = new System.Windows.Forms.Padding(5); this.StimulusColorTextBox.MaxLength = 7; this.StimulusColorTextBox.Name = "StimulusColorTextBox"; this.StimulusColorTextBox.Size = new System.Drawing.Size(268, 38); this.StimulusColorTextBox.TabIndex = 71; // // label19 // this.label19.AutoSize = true; this.label19.Location = new System.Drawing.Point(13, 48); this.label19.Margin = new System.Windows.Forms.Padding(8, 0, 8, 0); this.label19.Name = "label19"; this.label19.Size = new System.Drawing.Size(408, 32); this.label19.TabIndex = 70; this.label19.Text = "Stimulus Color (RGB Include #)"; // // SubBlockNumeric // this.SubBlockNumeric.Location = new System.Drawing.Point(464, 441); this.SubBlockNumeric.Margin = new System.Windows.Forms.Padding(8, 7, 8, 7); this.SubBlockNumeric.Name = "SubBlockNumeric"; this.SubBlockNumeric.Size = new System.Drawing.Size(136, 38); this.SubBlockNumeric.TabIndex = 44; // // SubBlockLabel // this.SubBlockLabel.AutoSize = true; this.SubBlockLabel.Location = new System.Drawing.Point(293, 446); this.SubBlockLabel.Margin = new System.Windows.Forms.Padding(8, 0, 8, 0); this.SubBlockLabel.Name = "SubBlockLabel"; this.SubBlockLabel.Size = new System.Drawing.Size(143, 32); this.SubBlockLabel.TabIndex = 43; this.SubBlockLabel.Text = "Sub Block"; // // BlockNumeric // this.BlockNumeric.Location = new System.Drawing.Point(144, 441); this.BlockNumeric.Margin = new System.Windows.Forms.Padding(8, 7, 8, 7); this.BlockNumeric.Name = "BlockNumeric"; this.BlockNumeric.Size = new System.Drawing.Size(136, 38); this.BlockNumeric.TabIndex = 42; // // BlockLabel // this.BlockLabel.AutoSize = true; this.BlockLabel.Location = new System.Drawing.Point(32, 446); this.BlockLabel.Margin = new System.Windows.Forms.Padding(8, 0, 8, 0); this.BlockLabel.Name = "BlockLabel"; this.BlockLabel.Size = new System.Drawing.Size(85, 32); this.BlockLabel.TabIndex = 41; this.BlockLabel.Text = "Block"; // // SaveButton // this.SaveButton.Location = new System.Drawing.Point(1011, 434); this.SaveButton.Margin = new System.Windows.Forms.Padding(8, 7, 8, 7); this.SaveButton.Name = "SaveButton"; this.SaveButton.Size = new System.Drawing.Size(200, 55); this.SaveButton.TabIndex = 39; this.SaveButton.Text = "Save"; this.SaveButton.UseVisualStyleBackColor = true; this.SaveButton.Click += new System.EventHandler(this.SaveButton_Click); // // CptForm // this.AutoScaleDimensions = new System.Drawing.SizeF(16F, 31F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.ClientSize = new System.Drawing.Size(1243, 517); this.Controls.Add(this.SubBlockNumeric); this.Controls.Add(this.SubBlockLabel); this.Controls.Add(this.BlockNumeric); this.Controls.Add(this.BlockLabel); this.Controls.Add(this.SaveButton); this.Controls.Add(this.groupBox2); this.Controls.Add(this.NameGroupBox); this.Margin = new System.Windows.Forms.Padding(8, 7, 8, 7); this.Name = "CptForm"; this.Text = "cpt"; this.Load += new System.EventHandler(this.cpt_Load); this.NameGroupBox.ResumeLayout(false); this.NameGroupBox.PerformLayout(); this.groupBox2.ResumeLayout(false); this.groupBox2.PerformLayout(); ((System.ComponentModel.ISupportInitialize)(this.SubBlockNumeric)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.BlockNumeric)).EndInit(); this.ResumeLayout(false); this.PerformLayout(); } #endregion private System.Windows.Forms.GroupBox NameGroupBox; private System.Windows.Forms.TextBox NameTextBox; private System.Windows.Forms.GroupBox groupBox2; private System.Windows.Forms.TextBox StimulusColorTextBox; private System.Windows.Forms.Label label19; private System.Windows.Forms.Label label1; private System.Windows.Forms.TextBox AddOtherColorTextBox; private System.Windows.Forms.Button ChoicesButton; private System.Windows.Forms.TextBox OtherColorsTextBox; private System.Windows.Forms.Label label2; private System.Windows.Forms.DomainUpDown StimulusShapeUpDown; private System.Windows.Forms.NumericUpDown SubBlockNumeric; private System.Windows.Forms.Label SubBlockLabel; private System.Windows.Forms.NumericUpDown BlockNumeric; private System.Windows.Forms.Label BlockLabel; private System.Windows.Forms.Button SaveButton; } }
49.131579
107
0.602035
[ "MIT" ]
nadavWeisler/PopUpResearcher
PopUp_Researcher/cpt.Designer.cs
13,071
C#
 using MsgPack.Serialization; using System; namespace Stormancer.Server.Plugins.Analytics { /// <summary> /// An analytics event sent by a game client/server. /// </summary> public class EventDto { /// <summary> /// Type of the event. /// </summary> [MessagePackMember(0)] public string Type { get; set; } = default!; /// <summary> /// Content of the event. /// </summary> [MessagePackMember(1)] public string Content { get; set; } = default!; /// <summary> /// Category of the analytic event. /// </summary> [MessagePackMember(2)] public string Category { get; set; } = default!; /// <summary> /// Date the event was created on. /// </summary> [MessagePackMember(3)] public DateTime CreatedOn { get; set; } } }
24.540541
56
0.529736
[ "MIT" ]
Stormancer/plugins
src/Stormancer.Plugins/Analytics/Stormancer.Server.Plugins.Analytics/Dto/EventDto.cs
910
C#
//BSD, 2014-present, WinterDev //---------------------------------------------------------------------------- // Anti-Grain Geometry - Version 2.4 // Copyright (C) 2002-2005 Maxim Shemanarev (http://www.antigrain.com) // // C# Port port by: Lars Brubaker // larsbrubaker@gmail.com // Copyright (C) 2007 // // Permission to copy, use, modify, sell and distribute this software // is granted provided this copyright notice appears in all copies. // This software is provided "as is" without express or implied // warranty, and with no claim as to its suitability for any purpose. // //---------------------------------------------------------------------------- // Contact: mcseem@antigrain.com // mcseemagg@yahoo.com // http://www.antigrain.com //---------------------------------------------------------------------------- using System; using PixelFarm.CpuBlit.VertexProcessing; namespace PixelFarm.CpuBlit.FragmentProcessing { //============================================span_interpolator_persp_lerp sealed class SpanInterpolatorPerspectiveLerp : FragmentProcessing.ISpanInterpolator { Perspective _trans_dir; Perspective _trans_inv; LineInterpolatorDDA2 _coord_x; LineInterpolatorDDA2 _coord_y; LineInterpolatorDDA2 _scale_x; LineInterpolatorDDA2 _scale_y; const int SUBPIXEL_SHIFT = 8; const int SUBPIXEL_SCALE = 1 << SUBPIXEL_SHIFT; //-------------------------------------------------------------------- public SpanInterpolatorPerspectiveLerp() { _trans_dir = new Perspective(); _trans_inv = new Perspective(); } //-------------------------------------------------------------------- // Arbitrary quadrangle transformations public SpanInterpolatorPerspectiveLerp(double[] src, double[] dst) : this() { quad_to_quad(src, dst); } //-------------------------------------------------------------------- // Direct transformations public SpanInterpolatorPerspectiveLerp(double x1, double y1, double x2, double y2, double[] quad) : this() { rect_to_quad(x1, y1, x2, y2, quad); } //-------------------------------------------------------------------- // Reverse transformations public SpanInterpolatorPerspectiveLerp(double[] quad, double x1, double y1, double x2, double y2) : this() { quad_to_rect(quad, x1, y1, x2, y2); } //-------------------------------------------------------------------- // Set the transformations using two arbitrary quadrangles. public void quad_to_quad(double[] src, double[] dst) { _trans_dir.quad_to_quad(src, dst); _trans_inv.quad_to_quad(dst, src); } //-------------------------------------------------------------------- // Set the direct transformations, i.e., rectangle -> quadrangle public void rect_to_quad(double x1, double y1, double x2, double y2, double[] quad) { double[] src = new double[8]; src[0] = src[6] = x1; src[2] = src[4] = x2; src[1] = src[3] = y1; src[5] = src[7] = y2; quad_to_quad(src, quad); } //-------------------------------------------------------------------- // Set the reverse transformations, i.e., quadrangle -> rectangle public void quad_to_rect(double[] quad, double x1, double y1, double x2, double y2) { double[] dst = new double[8]; dst[0] = dst[6] = x1; dst[2] = dst[4] = x2; dst[1] = dst[3] = y1; dst[5] = dst[7] = y2; quad_to_quad(quad, dst); } //-------------------------------------------------------------------- // Check if the equations were solved successfully public bool IsValid =>_trans_dir.IsValid; //---------------------------------------------------------------- public void Begin(double x, double y, int len) { // Calculate transformed coordinates at x1,y1 double xt = x; double yt = y; _trans_dir.Transform(ref xt, ref yt); int x1 = AggMath.iround(xt * SUBPIXEL_SCALE); int y1 = AggMath.iround(yt * SUBPIXEL_SCALE); double dx; double dy; double delta = 1 / (double)SUBPIXEL_SCALE; // Calculate scale by X at x1,y1 dx = xt + delta; dy = yt; _trans_inv.Transform(ref dx, ref dy); dx -= x; dy -= y; int sx1 = (int)AggMath.uround(SUBPIXEL_SCALE / Math.Sqrt(dx * dx + dy * dy)) >> SUBPIXEL_SHIFT; // Calculate scale by Y at x1,y1 dx = xt; dy = yt + delta; _trans_inv.Transform(ref dx, ref dy); dx -= x; dy -= y; int sy1 = (int)AggMath.uround(SUBPIXEL_SCALE / Math.Sqrt(dx * dx + dy * dy)) >> SUBPIXEL_SHIFT; // Calculate transformed coordinates at x2,y2 x += len; xt = x; yt = y; _trans_dir.Transform(ref xt, ref yt); int x2 = AggMath.iround(xt * SUBPIXEL_SCALE); int y2 = AggMath.iround(yt * SUBPIXEL_SCALE); // Calculate scale by X at x2,y2 dx = xt + delta; dy = yt; _trans_inv.Transform(ref dx, ref dy); dx -= x; dy -= y; int sx2 = (int)AggMath.uround(SUBPIXEL_SCALE / Math.Sqrt(dx * dx + dy * dy)) >> SUBPIXEL_SHIFT; // Calculate scale by Y at x2,y2 dx = xt; dy = yt + delta; _trans_inv.Transform(ref dx, ref dy); dx -= x; dy -= y; int sy2 = (int)AggMath.uround(SUBPIXEL_SCALE / Math.Sqrt(dx * dx + dy * dy)) >> SUBPIXEL_SHIFT; // Initialize the interpolators _coord_x = new LineInterpolatorDDA2(x1, x2, len); _coord_y = new LineInterpolatorDDA2(y1, y2, len); _scale_x = new LineInterpolatorDDA2(sx1, sx2, len); _scale_y = new LineInterpolatorDDA2(sy1, sy2, len); } public VertexProcessing.ICoordTransformer Transformer { get { throw new System.NotImplementedException(); } set { throw new System.NotImplementedException(); } } //---------------------------------------------------------------- public void Next() { _coord_x.Next(); _coord_y.Next(); _scale_x.Next(); _scale_y.Next(); } //---------------------------------------------------------------- public void GetCoord(out int x, out int y) { x = _coord_x.Y; y = _coord_y.Y; } //---------------------------------------------------------------- public void transform(ref double x, ref double y) { _trans_dir.Transform(ref x, ref y); } } }
38.572917
107
0.447205
[ "MIT" ]
Ferdowsur/Typography
PixelFarm/PixelFarm.CpuBlit/04_FragmentProcessing/SpanInterpolatorPerspectiveLerp.cs
7,406
C#
using System; using System.Collections.Generic; namespace AirTableProxy.WebAPI.Business.Dtos.AirTableDtos { public record MessageInfoDto(string Id, string Summary, string Message, DateTime? ReceivedAt); public record MessageResponseDto(string Id, MessageInfoDto Fields, DateTime CreatedTime); public record MessageRequestDto(MessageInfoDto Fields); public record MessagesResponseDto(IEnumerable<MessageResponseDto> Records); public record MessagesRequestDto(IEnumerable<MessageRequestDto> Records); }
32.9375
98
0.812144
[ "MIT" ]
matusmrazik/air-table-proxy
AirTableProxy/AirTableProxy.WebAPI/Business/Dtos/AirTableDtos.cs
529
C#
/* Copyright 2017 Cimpress Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ using Moq; using NUnit.Framework; using System; using System.Collections.Generic; using System.IO; using System.Threading; using VP.FF.PT.Common.Infrastructure.Logging; using VP.FF.PT.Common.Utils.Backup.BackupProviders; namespace VP.FF.PT.Common.Utils.Backup.UnitTests { public class FileBackupProviderDebouncedTests { private FileBackupProviderDebounced _fileBackupProviderDebounced; private Mock<IFileStore> _fileStoreMock; private Mock<ILogger> _loggerMock; private string _fileToMonitor1; private string _fileToMonitor2; [SetUp] public void SetUp() { string tempPath = Path.GetTempPath(); _fileToMonitor1 = Path.Combine(tempPath, "fileToMonitor1"); _fileToMonitor2 = Path.Combine(tempPath, "fileToMonitor2"); _fileStoreMock = new Mock<IFileStore>(); _loggerMock = new Mock<ILogger>(); Dictionary<string, string> filePathsToMonitor = GetFilePathsToMonitor(); _fileBackupProviderDebounced = new FileBackupProviderDebounced(_fileStoreMock.Object, _loggerMock.Object); _fileBackupProviderDebounced.Initialize(filePathsToMonitor); } [TearDown] public void TearDown() { _fileBackupProviderDebounced.StopMonitoring(); _fileBackupProviderDebounced.Dispose(); foreach (var filePath in GetFilePathsToMonitor().Keys) { if (File.Exists(filePath)) { File.Delete(filePath); } } } [Test, Category("Integration")] public void CheckFilesAreMonitoredAsExpected() { _fileBackupProviderDebounced.StartMonitoring(); // Modify a file, verify that it persisted File.WriteAllText(_fileToMonitor1, "Write some stuff to the file"); string fileId = _fileToMonitor1.Replace(Path.DirectorySeparatorChar, '_').Replace(Path.VolumeSeparatorChar, '_'); Thread.Sleep(TimeSpan.FromSeconds(1)); _fileStoreMock.Verify(x => x.SaveFile(fileId, _fileToMonitor1)); _fileBackupProviderDebounced.StopMonitoring(); } [Test, Category("Integration")] public void CheckFilesAreMonitoredOnCreation() { string tempPath = Path.GetTempPath(); string filePath = Path.Combine(tempPath, "tempFileToMonitor1.txt"); RemoveFile(filePath); Assert.IsFalse(File.Exists(filePath), "File already exists."); _fileBackupProviderDebounced.Add(filePath, null); _fileBackupProviderDebounced.StartMonitoring(); File.WriteAllText(filePath, "some content in the newly created file"); Assert.IsTrue(File.Exists(filePath), "File has not been created."); string fileId = filePath.Replace(Path.DirectorySeparatorChar, '_').Replace(Path.VolumeSeparatorChar, '_'); Thread.Sleep(TimeSpan.FromSeconds(1)); _fileStoreMock.Verify(x => x.SaveFile(fileId, filePath), Times.Once); _fileBackupProviderDebounced.StopMonitoring(); } private void RemoveFile(string filePath) { if (File.Exists(filePath)) { File.Delete(filePath); } } [Test, Category("Integration")] public void CheckFilesAreMonitoredWhenModified() { string tempPath = Path.GetTempPath(); string filePath = Path.Combine(tempPath, "tempFileToMonitor2.txt"); File.WriteAllText(filePath, "Existing file content"); Assert.IsTrue(File.Exists(filePath), "File exists."); _fileBackupProviderDebounced.Add(filePath, null); _fileBackupProviderDebounced.StartMonitoring(); File.AppendAllText(filePath, "- add content to the file -"); string fileId = filePath.Replace(Path.DirectorySeparatorChar, '_').Replace(Path.VolumeSeparatorChar, '_'); Thread.Sleep(TimeSpan.FromSeconds(1)); _fileStoreMock.Verify(x => x.SaveFile(fileId, filePath), Times.Once); _fileBackupProviderDebounced.StopMonitoring(); } [Test, Category("Integration")] public void CheckFilesAreMonitoredWhenModifiedLongWaitingTime() { string tempPath = Path.GetTempPath(); string filePath = Path.Combine(tempPath, "tempFileToMonitorLong.txt"); string filePathCopy = Path.Combine(tempPath, "tempFileToMonitorCopy.txt"); string identifier = "some_sort_of_ID"; File.WriteAllText(filePath, "Existing file content"); Assert.IsTrue(File.Exists(filePath), "File exists."); _fileBackupProviderDebounced.Add(filePath, identifier); _fileBackupProviderDebounced.StartMonitoring(); File.AppendAllText(filePath, "- add content to the file -"); Thread.Sleep(TimeSpan.FromMilliseconds(300)); File.Copy(filePath, filePathCopy, true); Thread.Sleep(TimeSpan.FromSeconds(3)); _fileStoreMock.Verify(x => x.SaveFile(identifier, filePath), Times.Once); _fileBackupProviderDebounced.StopMonitoring(); RemoveFile(filePath); RemoveFile(filePathCopy); } [Test, Category("Integration")] public void CheckFilesIdentifierProvidedIsUsed() { const string fileName = "tempFileToMonitor3.txt"; const string identifier = "idForMyFile"; string tempPath = Path.GetTempPath(); string filePath = Path.Combine(tempPath, fileName); File.WriteAllText(filePath, "Existing file content"); Assert.IsTrue(File.Exists(filePath), "File exists."); _fileBackupProviderDebounced.Add(filePath, identifier); _fileBackupProviderDebounced.StartMonitoring(); File.AppendAllText(filePath, "- add content to the file -"); Thread.Sleep(TimeSpan.FromSeconds(1)); _fileStoreMock.Verify(x => x.SaveFile(identifier, filePath), Times.Once); _fileBackupProviderDebounced.StopMonitoring(); } [Test, Category("Integration")] public void CheckFilesAreMonitoredWhenAddedToTheList() { _fileBackupProviderDebounced.StartMonitoring(); string tempPath = Path.GetTempPath(); string filePath = Path.Combine(tempPath, "fileThere.txt"); string fileId = filePath.Replace(Path.DirectorySeparatorChar, '_').Replace(Path.VolumeSeparatorChar, '_'); File.WriteAllText(filePath, "Existing file content"); Assert.IsTrue(File.Exists(filePath), "File exists."); // Nothing saved _fileStoreMock.Verify(x => x.SaveFile(fileId, filePath), Times.Never); _fileBackupProviderDebounced.Add(filePath, null); File.AppendAllText(filePath, "Additional text"); Thread.Sleep(TimeSpan.FromSeconds(1)); _fileStoreMock.Verify(x => x.SaveFile(fileId, filePath), Times.Once); _fileBackupProviderDebounced.StopMonitoring(); RemoveFile(filePath); } [Test, Category("Integration")] public void CheckFilesAreNotMonitoredWhenRemoved() { _fileBackupProviderDebounced.StopMonitoring(); string tempPath = Path.GetTempPath(); string filePath = Path.Combine(tempPath, "aNewFile.txt"); RemoveFile(filePath); string fileId = filePath.Replace(Path.DirectorySeparatorChar, '_').Replace(Path.VolumeSeparatorChar, '_'); _fileBackupProviderDebounced.Add(filePath, null); // using default identifier _fileBackupProviderDebounced.StartMonitoring(); File.WriteAllText(filePath, "some content"); Assert.IsTrue(File.Exists(filePath), "File exists."); Thread.Sleep(TimeSpan.FromSeconds(1)); _fileStoreMock.Verify(x => x.SaveFile(fileId, filePath), Times.Once); _fileStoreMock.ResetCalls(); _fileBackupProviderDebounced.Remove(filePath); File.AppendAllText(filePath, "Additional text"); Thread.Sleep(TimeSpan.FromSeconds(1)); _fileStoreMock.Verify(x => x.SaveFile(fileId, filePath), Times.Never); _fileBackupProviderDebounced.StopMonitoring(); RemoveFile(filePath); } [Test, Category("Integration")] public void ChangedNotMonitoredFileInMonitoredFolder_DoNotGetSaved() { _fileBackupProviderDebounced.StartMonitoring(); string someFilePath = Path.Combine(Path.GetTempPath(), "someFile.Txt"); File.WriteAllText(someFilePath, "Write some stuff to the file"); string fileId = someFilePath.Replace(Path.DirectorySeparatorChar, '_').Replace(Path.VolumeSeparatorChar, '_'); _fileStoreMock.Verify(x => x.SaveFile(fileId, someFilePath), Times.Never); _fileBackupProviderDebounced.StopMonitoring(); RemoveFile(someFilePath); } [Test] public void ExceptionRaisedWhenVcsAccessorIsNull() { Assert.That(() => new FileBackupProvider(null, _loggerMock.Object), Throws.Exception.TypeOf<ArgumentNullException>()); } [Test] public void ExceptionRaisedWhenLoggerIsNull() { Assert.That(() => new FileBackupProvider(_fileStoreMock.Object, null), Throws.Exception.TypeOf<ArgumentNullException>()); } [Test] public void ExceptionRaisedWhenNullFileListIsProvided() { var anotherFileBackupProvider = new FileBackupProvider(_fileStoreMock.Object, _loggerMock.Object); Assert.That(() => anotherFileBackupProvider.Initialize((Dictionary<string, string>)null), Throws.Exception.TypeOf<ArgumentNullException>()); } [Test] public void ExceptionRaisedWhenNullFileListIsProvidedOtherCtr() { var anotherFileBackupProvider = new FileBackupProvider(_fileStoreMock.Object, _loggerMock.Object); Assert.That(() => anotherFileBackupProvider.Initialize((IEnumerable<IConfigItem>)null), Throws.Exception.TypeOf<ArgumentNullException>()); } private Dictionary<string, string> GetFilePathsToMonitor() { return new Dictionary<string, string> { { _fileToMonitor1, null }, { _fileToMonitor2, null } }; } } }
34.446154
152
0.648236
[ "Apache-2.0" ]
Cimpress-ACS/Mosaic
src/Utils/Backup.Tests/FileBackupProviderDebouncedTests.cs
11,195
C#