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
sequence
repository_name
stringlengths
7
92
path
stringlengths
3
249
size
int64
5
1.04M
lang
stringclasses
2 values
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.IO; using System.Linq; using BuildXL.Cache.ContentStore.Interfaces.FileSystem; using BuildXL.Cache.ContentStore.Interfaces.Utils; using BuildXL.Cache.ContentStore.Synchronization; using CLAP; using BuildXL.Cache.ContentStore.Hashing; // ReSharper disable once UnusedMember.Global namespace BuildXL.Cache.ContentStore.App { internal sealed partial class Application { private readonly HashSet<byte[]> _allNodes = new HashSet<byte[]>(ByteArrayComparer.Instance); private readonly HashSet<byte[]> _allChunks = new HashSet<byte[]>(ByteArrayComparer.Instance); private ulong _uniqueBytes; private ulong _totalBytes; private ulong _totalChunks; private ulong _totalNodes; private bool _displayChunks; private bool _displayChildNodes; /// <summary> /// Hash some files and optionally display their chunks /// </summary> [SuppressMessage("Microsoft.Maintainability", "CA1506:AvoidExcessiveClassCoupling")] [Verb(Aliases = "hf", Description = "Hash content files")] public void DedupHashFile ( [Required] string[] path, [DefaultValue(false)] bool chunks, [DefaultValue(false)] bool childNodes, [DefaultValue(false)] bool rollingHash, [DefaultValue(FileSystemConstants.FileIOBufferSize)] int bufferSize, [DefaultValue((long)0)] long startOffset ) { Initialize(); _displayChunks = chunks; _displayChildNodes = childNodes; var paths = new List<AbsolutePath>(); foreach (AbsolutePath root in path.Select(p => new AbsolutePath(p))) { if (_fileSystem.DirectoryExists(root)) { paths.AddRange(_fileSystem.EnumerateFiles(root, EnumerateOptions.Recurse).Select(fileInfo => fileInfo.FullPath)); } else if (_fileSystem.FileExists(root)) { paths.Add(root); } else { throw new ArgumentException("given path is not an existing file or directory"); } } var buffer = new byte[bufferSize]; using (var hasher = new DedupNodeHashAlgorithm(rollingHash ? DedupNodeTree.Algorithm.RollingHash : DedupNodeTree.Algorithm.MaximallyPacked)) { foreach (var p in paths) { hasher.Initialize(); TaskSafetyHelpers.SyncResultOnThreadPool(async () => { using (var fs = await _fileSystem.OpenReadOnlySafeAsync(p, FileShare.Read | FileShare.Delete)) { fs.Position = startOffset; int bytesRead; while ((bytesRead = await fs.ReadAsync(buffer, 0, buffer.Length)) > 0) { hasher.TransformBlock(buffer, 0, bytesRead, null, 0); } hasher.TransformFinalBlock(new byte[0], 0, 0); DedupNode root = hasher.GetNode(); ulong offset = 0; LogNode(true, string.Empty, root, p, ref offset); } return 0; }); } } _logger.Always("Totals:"); _logger.Always($"Bytes: Unique={_uniqueBytes:N0} Total={_totalBytes:N0}"); _logger.Always($"Chunks: Unique={_allChunks.Count:N0} Total={_totalChunks:N0}"); _logger.Always($"Nodes: Unique={_allNodes.Count:N0} Total={_totalNodes:N0}"); } private void LogNode(bool displayChildNodes, string indent, DedupNode root, AbsolutePath path, ref ulong offset) { _totalNodes++; bool newNode = _allNodes.Add(root.Hash); if (displayChildNodes) { var hash = new ContentHash(HashType.DedupNode, root.Hash); char newNodeChar = newNode ? '*' : 'd'; _logger.Always($"{indent}{hash} {newNodeChar} {path}"); } if (root.ChildNodes != null) { foreach (var child in root.ChildNodes) { switch (child.Type) { case DedupNode.NodeType.ChunkLeaf: _totalBytes += child.TransitiveContentBytes; _totalChunks++; bool newChunk = _allChunks.Add(child.Hash); if (newChunk) { _uniqueBytes += child.TransitiveContentBytes; } if (_displayChunks) { char newChunkChar = newChunk ? '*' : 'd'; _logger.Always($"{indent} {offset} {child.Hash.ToHex()} {newChunkChar}"); } offset += child.TransitiveContentBytes; break; case DedupNode.NodeType.InnerNode: LogNode(_displayChildNodes, indent + " ", child, null, ref offset); break; default: throw new NotImplementedException(); } } } } } }
41.202703
153
0.50082
[ "MIT" ]
MatisseHack/BuildXL
Public/Src/Cache/ContentStore/App/DedupHashContent.cs
6,098
C#
using System; using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Metadata; namespace CorePOC.DataLayer.Repositories { public class EntityCoreContext : DbContext { // public virtual DbSet<Item } }
22.454545
46
0.732794
[ "MIT" ]
ApoTheOne/PPOC
DotNetApi/DataLayer/Repositories/EntityCoreContext.cs
247
C#
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ /* * Do not modify this file. This file is generated from the codestar-connections-2019-12-01.normal.json service model. */ using System; using Amazon.Runtime; using Amazon.Util.Internal; namespace Amazon.CodeStarconnections { /// <summary> /// Configuration for accessing Amazon CodeStarconnections service /// </summary> public partial class AmazonCodeStarconnectionsConfig : ClientConfig { private static readonly string UserAgentString = InternalSDKUtils.BuildUserAgentString("3.7.1.38"); private string _userAgent = UserAgentString; /// <summary> /// Default constructor /// </summary> public AmazonCodeStarconnectionsConfig() { this.AuthenticationServiceName = "codestar-connections"; } /// <summary> /// The constant used to lookup in the region hash the endpoint. /// </summary> public override string RegionEndpointServiceName { get { return "codestar-connections"; } } /// <summary> /// Gets the ServiceVersion property. /// </summary> public override string ServiceVersion { get { return "2019-12-01"; } } /// <summary> /// Gets the value of UserAgent property. /// </summary> public override string UserAgent { get { return _userAgent; } } } }
26.975
118
0.599629
[ "Apache-2.0" ]
mikemissakian/aws-sdk-net
sdk/src/Services/CodeStarconnections/Generated/AmazonCodeStarconnectionsConfig.cs
2,158
C#
 using UnityEngine; namespace Knowdes { public class EntryAfterEditSaver : MonoBehaviour { [SerializeField] private EditPanel _editPanel; private Entry _entry = null; private EntryDataRepository _entryDataRepository; protected virtual void Start() { _editPanel.OnEntryChanged += onEntryChanged; _entryDataRepository = FindObjectOfType<EntryDataRepository>(); } protected virtual void OnDestroy() { _editPanel.OnEntryChanged -= onEntryChanged; } private void onEntryChanged() { if (_entry != null) _entryDataRepository.Save(_entry.Data); _entry = _editPanel.Entry; } } }
20.258065
66
0.732484
[ "MIT" ]
BlackLambert/knowdes
Knowdes Project/Assets/Scripts/Edit/EntryAfterEditSaver.cs
630
C#
// Copyright (c) .NET Core Community. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for license information. using System; using System.Diagnostics; using System.Threading.Tasks; using DotNetCore.CAP.Diagnostics; using DotNetCore.CAP.Infrastructure; using DotNetCore.CAP.Internal; using DotNetCore.CAP.Models; using DotNetCore.CAP.Processor; using DotNetCore.CAP.Processor.States; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Options; namespace DotNetCore.CAP { public abstract class BasePublishMessageSender : IPublishMessageSender, IPublishExecutor { private readonly IStorageConnection _connection; private readonly ILogger _logger; private readonly CapOptions _options; private readonly IStateChanger _stateChanger; protected abstract string ServersAddress { get; } // diagnostics listener // ReSharper disable once InconsistentNaming protected static readonly DiagnosticListener s_diagnosticListener = new DiagnosticListener(CapDiagnosticListenerExtensions.DiagnosticListenerName); protected BasePublishMessageSender( ILogger logger, IOptions<CapOptions> options, IStorageConnection connection, IStateChanger stateChanger) { _options = options.Value; _connection = connection; _stateChanger = stateChanger; _logger = logger; } public abstract Task<OperateResult> PublishAsync(string keyName, string content); public async Task<OperateResult> SendAsync(CapPublishedMessage message) { bool retry; OperateResult result; do { var executedResult = await SendWithoutRetryAsync(message); result = executedResult.Item2; if (result == OperateResult.Success) { return result; } retry = executedResult.Item1; } while (retry); return result; } private async Task<(bool, OperateResult)> SendWithoutRetryAsync(CapPublishedMessage message) { var startTime = DateTimeOffset.UtcNow; var stopwatch = Stopwatch.StartNew(); var tracingResult = TracingBefore(message.Name, message.Content); var operationId = tracingResult.Item1; var sendValues = tracingResult.Item2 != null ? Helper.AddTracingHeaderProperty(message.Content, tracingResult.Item2) : message.Content; var result = await PublishAsync(message.Name, sendValues); stopwatch.Stop(); if (result.Succeeded) { await SetSuccessfulState(message); TracingAfter(operationId, message.Name, sendValues, startTime, stopwatch.Elapsed); return (false, OperateResult.Success); } else { TracingError(operationId, message, result, startTime, stopwatch.Elapsed); var needRetry = await SetFailedState(message, result.Exception); return (needRetry, OperateResult.Failed(result.Exception)); } } private Task SetSuccessfulState(CapPublishedMessage message) { var succeededState = new SucceededState(_options.SucceedMessageExpiredAfter); return _stateChanger.ChangeStateAsync(message, succeededState, _connection); } private async Task<bool> SetFailedState(CapPublishedMessage message, Exception ex) { AddErrorReasonToContent(message, ex); var needRetry = UpdateMessageForRetry(message); await _stateChanger.ChangeStateAsync(message, new FailedState(), _connection); return needRetry; } private static void AddErrorReasonToContent(CapPublishedMessage message, Exception exception) { message.Content = Helper.AddExceptionProperty(message.Content, exception); } private bool UpdateMessageForRetry(CapPublishedMessage message) { var retryBehavior = RetryBehavior.DefaultRetry; var retries = ++message.Retries; message.ExpiresAt = message.Added.AddSeconds(retryBehavior.RetryIn(retries)); var retryCount = Math.Min(_options.FailedRetryCount, retryBehavior.RetryCount); if (retries >= retryCount) { if (retries == _options.FailedRetryCount) { try { _options.FailedThresholdCallback?.Invoke(MessageType.Subscribe, message.Name, message.Content); _logger.SenderAfterThreshold(message.Id, _options.FailedRetryCount); } catch (Exception ex) { _logger.ExecutedThresholdCallbackFailed(ex); } } return false; } _logger.SenderRetrying(message.Id, retries); return true; } private (Guid, TracingHeaders) TracingBefore(string topic, string values) { Guid operationId = Guid.NewGuid(); var eventData = new BrokerPublishEventData( operationId, "", ServersAddress, topic, values, DateTimeOffset.UtcNow); s_diagnosticListener.WritePublishBefore(eventData); return (operationId, eventData.Headers); //if not enabled diagnostics ,the header will be null } private void TracingAfter(Guid operationId, string topic, string values, DateTimeOffset startTime, TimeSpan du) { var eventData = new BrokerPublishEndEventData( operationId, "", ServersAddress, topic, values, startTime, du); s_diagnosticListener.WritePublishAfter(eventData); } private void TracingError(Guid operationId, CapPublishedMessage message, OperateResult result, DateTimeOffset startTime, TimeSpan du) { var ex = new PublisherSentFailedException(result.ToString(), result.Exception); _logger.MessagePublishException(message.Id, result.ToString(), ex); var eventData = new BrokerPublishErrorEventData( operationId, "", ServersAddress, message.Name, message.Content, ex, startTime, du, message.Retries + 1); s_diagnosticListener.WritePublishError(eventData); } } }
34.809045
141
0.604446
[ "MIT" ]
edelibas/CAP
src/DotNetCore.CAP/IPublishMessageSender.Base.cs
6,929
C#
// Copyright 2017 by PeopleWare n.v.. // 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 PPWCode.Vernacular.Persistence.IV; namespace PPWCode.Vernacular.NHibernate.III.MappingByCode { public abstract class AuditableVersionedPersistentObjectMapper<T, TId, TVersion> : VersionedPersistentObjectMapper<T, TId, TVersion> where T : class, IVersionedPersistentObject<TId, TVersion>, IAuditable where TId : IEquatable<TId> where TVersion : IEquatable<TVersion> { protected AuditableVersionedPersistentObjectMapper() { // Satisfy IInsertAuditable Property(x => x.CreatedAt, m => m.Update(false)); Property( x => x.CreatedBy, m => { m.Length(MaxUserNameLength); m.Update(false); }); // Satisfy IUpdateAuditable Property(x => x.LastModifiedAt, m => m.Insert(false)); Property( x => x.LastModifiedBy, m => { m.Length(MaxUserNameLength); m.Insert(false); }); } } }
35.833333
84
0.60814
[ "Apache-2.0" ]
peopleware/net-ppwcode-vernacular-nhibernate
src/III/MappingByCode/Versioned/AuditableVersionedPersistentObjectMapper.cs
1,722
C#
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Dapper; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; using Ray.Core.Serialization; using Ray.Core.Snapshot; using Ray.Core.Storage; using Ray.Storage.SQLCore; using Ray.Storage.SQLCore.Configuration; namespace Ray.Storage.PostgreSQL { public class ArchiveStorage<PrimaryKey, StateType> : IArchiveStorage<PrimaryKey, StateType> where StateType : class, new() { readonly StorageOptions config; private readonly string deleteSql; private readonly string deleteAllSql; private readonly string getByIdSql; private readonly string getListByStateIdSql; private readonly string getLatestByStateIdSql; private readonly string insertSql; private readonly string updateOverSql; private readonly string updateEventIsClearSql; readonly ISerializer serializer; readonly ILogger<ArchiveStorage<PrimaryKey, StateType>> logger; public ArchiveStorage(IServiceProvider serviceProvider, ISerializer serializer, StorageOptions config) { logger = serviceProvider.GetService<ILogger<ArchiveStorage<PrimaryKey, StateType>>>(); this.serializer = serializer; this.config = config; var tableName = config.SnapshotArchiveTable; deleteSql = $"DELETE FROM {tableName} where id=@Id"; deleteAllSql = $"DELETE FROM {tableName} where stateid=@StateId"; getByIdSql = $"select * FROM {tableName} where id=@Id"; getListByStateIdSql = $"select Id,StartVersion,EndVersion,StartTimestamp,EndTimestamp,Index,EventIsCleared FROM {tableName} where stateid=@StateId"; getLatestByStateIdSql = $"select Id,StartVersion,EndVersion,StartTimestamp,EndTimestamp,Index,EventIsCleared FROM {tableName} where stateid=@StateId order by index desc limit 1"; insertSql = $"INSERT into {tableName}(Id,stateid,StartVersion,EndVersion,StartTimestamp,EndTimestamp,Index,EventIsCleared,data,IsOver,Version)VALUES(@Id,@StateId,@StartVersion,@EndVersion,@StartTimestamp,@EndTimestamp,@Index,@EventIsCleared,(@Data)::json,@IsOver,@Version)"; updateOverSql = $"update {tableName} set IsOver=@IsOver where stateid=@StateId"; updateEventIsClearSql = $"update {tableName} set EventIsCleared=true where id=@Id"; } public async Task Delete(PrimaryKey stateId, string briefId) { using var conn = config.CreateConnection(); await conn.ExecuteAsync(deleteSql, new { Id = briefId }); } public async Task DeleteAll(PrimaryKey stateId) { using var conn = config.CreateConnection(); await conn.ExecuteAsync(deleteAllSql, new { StateId = stateId }); } public async Task EventIsClear(PrimaryKey stateId, string briefId) { using var connection = config.CreateConnection(); await connection.ExecuteAsync(updateEventIsClearSql, new { Id = briefId }); } public async Task<List<ArchiveBrief>> GetBriefList(PrimaryKey stateId) { using var connection = config.CreateConnection(); return (await connection.QueryAsync<ArchiveBrief>(getListByStateIdSql, new { StateId = stateId })).AsList(); } public async Task<ArchiveBrief> GetLatestBrief(PrimaryKey stateId) { using var connection = config.CreateConnection(); return await connection.QuerySingleOrDefaultAsync<ArchiveBrief>(getLatestByStateIdSql, new { StateId = stateId }); } public async Task<Snapshot<PrimaryKey, StateType>> GetById(string briefId) { using var connection = config.CreateConnection(); var data = await connection.QuerySingleOrDefaultAsync<SnapshotModel<PrimaryKey>>(getByIdSql, new { Id = briefId }); if (data != null) { return new Snapshot<PrimaryKey, StateType>() { Base = new SnapshotBase<PrimaryKey> { StateId = data.StateId, Version = data.Version, DoingVersion = data.Version, IsLatest = false, IsOver = data.IsOver, StartTimestamp = data.StartTimestamp, LatestMinEventTimestamp = data.StartTimestamp }, State = serializer.Deserialize<StateType>(data.Data) }; } return default; } public async Task Insert(ArchiveBrief brief, Snapshot<PrimaryKey, StateType> snapshot) { using var connection = config.CreateConnection(); await connection.ExecuteAsync(insertSql, new { brief.Id, snapshot.Base.StateId, brief.StartVersion, brief.EndVersion, brief.StartTimestamp, brief.EndTimestamp, brief.Index, brief.EventIsCleared, Data = serializer.Serialize(snapshot.State), snapshot.Base.IsOver, snapshot.Base.Version }); } public async Task Over(PrimaryKey stateId, bool isOver) { using var connection = config.CreateConnection(); await connection.ExecuteAsync(updateOverSql, new { StateId = stateId, IsOver = isOver }); } public Task EventArichive(PrimaryKey stateId, long endVersion, long startTimestamp) { return Task.Run(async () => { var getTableListTask = config.GetSubTables(); if (!getTableListTask.IsCompletedSuccessfully) await getTableListTask; var tableList = getTableListTask.Result.Where(t => t.EndTime >= startTimestamp); using var conn = config.CreateConnection(); await conn.OpenAsync(); using var trans = conn.BeginTransaction(); try { foreach (var table in tableList) { var copySql = $"insert into {config.EventArchiveTable} select * from {table.SubTable} WHERE stateid=@StateId and version<=@EndVersion"; var sql = $"delete from {table.SubTable} WHERE stateid=@StateId and version<=@EndVersion"; await conn.ExecuteAsync(copySql, new { StateId = stateId, EndVersion = endVersion }, transaction: trans); await conn.ExecuteAsync(sql, new { StateId = stateId, EndVersion = endVersion }, transaction: trans); } trans.Commit(); } catch (Exception ex) { trans.Rollback(); logger.LogCritical(ex, ex.Message); throw; } }); } } }
47.217105
286
0.605824
[ "MIT" ]
ElanHasson/Ray
src/Ray.Storage.PostgreSQL/Storage/ArchiveStorage.cs
7,179
C#
// <auto-generated /> using System; using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Infrastructure; using Microsoft.EntityFrameworkCore.Metadata; using Microsoft.EntityFrameworkCore.Storage.ValueConversion; using mcp.Server.Data; namespace mcp.Server.Data.Migrations { [DbContext(typeof(ApplicationDbContext))] partial class ApplicationDbContextModelSnapshot : ModelSnapshot { protected override void BuildModel(ModelBuilder modelBuilder) { #pragma warning disable 612, 618 modelBuilder .HasAnnotation("Relational:MaxIdentifierLength", 128) .HasAnnotation("ProductVersion", "5.0.7") .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); modelBuilder.Entity("IdentityServer4.EntityFramework.Entities.DeviceFlowCodes", b => { b.Property<string>("UserCode") .HasMaxLength(200) .HasColumnType("nvarchar(200)"); b.Property<string>("ClientId") .IsRequired() .HasMaxLength(200) .HasColumnType("nvarchar(200)"); b.Property<DateTime>("CreationTime") .HasColumnType("datetime2"); b.Property<string>("Data") .IsRequired() .HasMaxLength(50000) .HasColumnType("nvarchar(max)"); b.Property<string>("Description") .HasMaxLength(200) .HasColumnType("nvarchar(200)"); b.Property<string>("DeviceCode") .IsRequired() .HasMaxLength(200) .HasColumnType("nvarchar(200)"); b.Property<DateTime?>("Expiration") .IsRequired() .HasColumnType("datetime2"); b.Property<string>("SessionId") .HasMaxLength(100) .HasColumnType("nvarchar(100)"); b.Property<string>("SubjectId") .HasMaxLength(200) .HasColumnType("nvarchar(200)"); b.HasKey("UserCode"); b.HasIndex("DeviceCode") .IsUnique(); b.HasIndex("Expiration"); b.ToTable("DeviceCodes"); }); modelBuilder.Entity("IdentityServer4.EntityFramework.Entities.PersistedGrant", b => { b.Property<string>("Key") .HasMaxLength(200) .HasColumnType("nvarchar(200)"); b.Property<string>("ClientId") .IsRequired() .HasMaxLength(200) .HasColumnType("nvarchar(200)"); b.Property<DateTime?>("ConsumedTime") .HasColumnType("datetime2"); b.Property<DateTime>("CreationTime") .HasColumnType("datetime2"); b.Property<string>("Data") .IsRequired() .HasMaxLength(50000) .HasColumnType("nvarchar(max)"); b.Property<string>("Description") .HasMaxLength(200) .HasColumnType("nvarchar(200)"); b.Property<DateTime?>("Expiration") .HasColumnType("datetime2"); b.Property<string>("SessionId") .HasMaxLength(100) .HasColumnType("nvarchar(100)"); b.Property<string>("SubjectId") .HasMaxLength(200) .HasColumnType("nvarchar(200)"); b.Property<string>("Type") .IsRequired() .HasMaxLength(50) .HasColumnType("nvarchar(50)"); b.HasKey("Key"); b.HasIndex("Expiration"); b.HasIndex("SubjectId", "ClientId", "Type"); b.HasIndex("SubjectId", "SessionId", "Type"); b.ToTable("PersistedGrants"); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRole", b => { b.Property<string>("Id") .HasColumnType("nvarchar(450)"); b.Property<string>("ConcurrencyStamp") .IsConcurrencyToken() .HasColumnType("nvarchar(max)"); b.Property<string>("Name") .HasMaxLength(256) .HasColumnType("nvarchar(256)"); b.Property<string>("NormalizedName") .HasMaxLength(256) .HasColumnType("nvarchar(256)"); b.HasKey("Id"); b.HasIndex("NormalizedName") .IsUnique() .HasDatabaseName("RoleNameIndex") .HasFilter("[NormalizedName] IS NOT NULL"); b.ToTable("AspNetRoles"); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRoleClaim<string>", b => { b.Property<int>("Id") .ValueGeneratedOnAdd() .HasColumnType("int") .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); b.Property<string>("ClaimType") .HasColumnType("nvarchar(max)"); b.Property<string>("ClaimValue") .HasColumnType("nvarchar(max)"); b.Property<string>("RoleId") .IsRequired() .HasColumnType("nvarchar(450)"); b.HasKey("Id"); b.HasIndex("RoleId"); b.ToTable("AspNetRoleClaims"); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserClaim<string>", b => { b.Property<int>("Id") .ValueGeneratedOnAdd() .HasColumnType("int") .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); b.Property<string>("ClaimType") .HasColumnType("nvarchar(max)"); b.Property<string>("ClaimValue") .HasColumnType("nvarchar(max)"); b.Property<string>("UserId") .IsRequired() .HasColumnType("nvarchar(450)"); b.HasKey("Id"); b.HasIndex("UserId"); b.ToTable("AspNetUserClaims"); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserLogin<string>", b => { b.Property<string>("LoginProvider") .HasMaxLength(128) .HasColumnType("nvarchar(128)"); b.Property<string>("ProviderKey") .HasMaxLength(128) .HasColumnType("nvarchar(128)"); b.Property<string>("ProviderDisplayName") .HasColumnType("nvarchar(max)"); b.Property<string>("UserId") .IsRequired() .HasColumnType("nvarchar(450)"); b.HasKey("LoginProvider", "ProviderKey"); b.HasIndex("UserId"); b.ToTable("AspNetUserLogins"); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserRole<string>", b => { b.Property<string>("UserId") .HasColumnType("nvarchar(450)"); b.Property<string>("RoleId") .HasColumnType("nvarchar(450)"); b.HasKey("UserId", "RoleId"); b.HasIndex("RoleId"); b.ToTable("AspNetUserRoles"); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserToken<string>", b => { b.Property<string>("UserId") .HasColumnType("nvarchar(450)"); b.Property<string>("LoginProvider") .HasMaxLength(128) .HasColumnType("nvarchar(128)"); b.Property<string>("Name") .HasMaxLength(128) .HasColumnType("nvarchar(128)"); b.Property<string>("Value") .HasColumnType("nvarchar(max)"); b.HasKey("UserId", "LoginProvider", "Name"); b.ToTable("AspNetUserTokens"); }); modelBuilder.Entity("mcp.Server.Models.ApplicationUser", b => { b.Property<string>("Id") .HasColumnType("nvarchar(450)"); b.Property<int>("AccessFailedCount") .HasColumnType("int"); b.Property<string>("ConcurrencyStamp") .IsConcurrencyToken() .HasColumnType("nvarchar(max)"); b.Property<string>("DisplayName") .HasColumnType("nvarchar(max)"); b.Property<string>("Email") .HasMaxLength(256) .HasColumnType("nvarchar(256)"); b.Property<bool>("EmailConfirmed") .HasColumnType("bit"); b.Property<bool>("LockoutEnabled") .HasColumnType("bit"); b.Property<DateTimeOffset?>("LockoutEnd") .HasColumnType("datetimeoffset"); b.Property<string>("NormalizedEmail") .HasMaxLength(256) .HasColumnType("nvarchar(256)"); b.Property<string>("NormalizedUserName") .HasMaxLength(256) .HasColumnType("nvarchar(256)"); b.Property<string>("PasswordHash") .HasColumnType("nvarchar(max)"); b.Property<string>("PhoneNumber") .HasColumnType("nvarchar(max)"); b.Property<bool>("PhoneNumberConfirmed") .HasColumnType("bit"); b.Property<string>("SecurityStamp") .HasColumnType("nvarchar(max)"); b.Property<bool>("TwoFactorEnabled") .HasColumnType("bit"); b.Property<string>("UniqueName") .HasColumnType("nvarchar(450)"); b.Property<string>("UserName") .HasMaxLength(256) .HasColumnType("nvarchar(256)"); b.HasKey("Id"); b.HasIndex("NormalizedEmail") .HasDatabaseName("EmailIndex"); b.HasIndex("NormalizedUserName") .IsUnique() .HasDatabaseName("UserNameIndex") .HasFilter("[NormalizedUserName] IS NOT NULL"); b.HasIndex("UniqueName") .IsUnique() .HasFilter("[UniqueName] IS NOT NULL"); b.ToTable("AspNetUsers"); }); modelBuilder.Entity("mcp.Server.Models.Category", b => { b.Property<int>("CategoryID") .HasColumnType("int"); b.Property<string>("Name") .HasColumnType("nvarchar(max)"); b.Property<int>("SortOrder") .HasColumnType("int"); b.HasKey("CategoryID"); b.ToTable("Category"); b.HasData( new { CategoryID = 1, Name = "Engine", SortOrder = 1 }, new { CategoryID = 2, Name = "Suspension/Chassis", SortOrder = 2 }, new { CategoryID = 3, Name = "Brakes", SortOrder = 3 }, new { CategoryID = 4, Name = "Interior", SortOrder = 4 }, new { CategoryID = 5, Name = "Body", SortOrder = 5 }, new { CategoryID = 6, Name = "Electrical", SortOrder = 6 }, new { CategoryID = 7, Name = "Audio/Video", SortOrder = 7 }, new { CategoryID = 8, Name = "Drivetrain", SortOrder = 8 }); }); modelBuilder.Entity("mcp.Server.Models.Project", b => { b.Property<int>("ProjectID") .ValueGeneratedOnAdd() .HasColumnType("int") .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); b.Property<decimal?>("ActualCost") .HasColumnType("decimal(10,2)"); b.Property<DateTime?>("ActualEndDate") .HasColumnType("datetime2"); b.Property<string>("Description") .HasColumnType("nvarchar(max)"); b.Property<string>("InstallationNotes") .HasColumnType("nvarchar(max)"); b.Property<bool>("IsCostPublic") .HasColumnType("bit"); b.Property<bool>("IsDeleted") .HasColumnType("bit"); b.Property<bool>("IsPublic") .HasColumnType("bit"); b.Property<DateTime>("LastUpdate") .ValueGeneratedOnAdd() .HasColumnType("datetime2") .HasDefaultValueSql("getdate()"); b.Property<string>("Name") .HasColumnType("nvarchar(max)"); b.Property<int?>("ParentProjectID") .HasColumnType("int"); b.Property<int>("ProjectStatusID") .ValueGeneratedOnAdd() .HasColumnType("int") .HasDefaultValue(1); b.Property<DateTime?>("StartDate") .HasColumnType("datetime2"); b.Property<decimal?>("TargetCost") .HasColumnType("decimal(10,2)"); b.Property<DateTime?>("TargetEndDate") .HasColumnType("datetime2"); b.Property<int?>("UserCategoryID") .HasColumnType("int"); b.Property<int>("VehicleID") .HasColumnType("int"); b.HasKey("ProjectID"); b.HasIndex("ParentProjectID"); b.HasIndex("ProjectStatusID"); b.HasIndex("UserCategoryID"); b.HasIndex("VehicleID"); b.ToTable("Project"); }); modelBuilder.Entity("mcp.Server.Models.ProjectChecklistItem", b => { b.Property<int>("ProjectChecklistItemID") .ValueGeneratedOnAdd() .HasColumnType("int") .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); b.Property<DateTime?>("CheckedDateTime") .HasColumnType("datetime2"); b.Property<string>("Description") .HasColumnType("nvarchar(max)"); b.Property<bool>("IsChecked") .HasColumnType("bit"); b.Property<int>("ProjectID") .HasColumnType("int"); b.Property<int>("SortOrder") .HasColumnType("int"); b.HasKey("ProjectChecklistItemID"); b.HasIndex("ProjectID"); b.ToTable("ProjectChecklistItem"); }); modelBuilder.Entity("mcp.Server.Models.ProjectDependency", b => { b.Property<int>("ProjectDependencyID") .ValueGeneratedOnAdd() .HasColumnType("int") .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); b.Property<int>("DependsOnProjectID") .HasColumnType("int"); b.Property<int>("ProjectID") .HasColumnType("int"); b.HasKey("ProjectDependencyID"); b.HasIndex("DependsOnProjectID"); b.HasIndex("ProjectID"); b.ToTable("ProjectDependency"); }); modelBuilder.Entity("mcp.Server.Models.ProjectPart", b => { b.Property<int>("ProjectPartID") .ValueGeneratedOnAdd() .HasColumnType("int") .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); b.Property<string>("Description") .HasColumnType("nvarchar(max)"); b.Property<bool>("ExcludeFromTotal") .HasColumnType("bit"); b.Property<decimal?>("ExtraCost") .HasColumnType("decimal(10,2)"); b.Property<string>("Link") .HasColumnType("nvarchar(max)"); b.Property<string>("Manufacturer") .HasColumnType("nvarchar(max)"); b.Property<string>("Name") .HasColumnType("nvarchar(max)"); b.Property<string>("PartNumber") .HasColumnType("nvarchar(max)"); b.Property<decimal?>("Price") .HasColumnType("decimal(10,2)"); b.Property<int>("ProjectID") .HasColumnType("int"); b.Property<int>("Quantity") .ValueGeneratedOnAdd() .HasColumnType("int") .HasDefaultValue(1); b.Property<int>("QuantityInstalled") .HasColumnType("int"); b.Property<int>("QuantityPurchased") .HasColumnType("int"); b.HasKey("ProjectPartID"); b.HasIndex("ProjectID"); b.ToTable("ProjectPart"); }); modelBuilder.Entity("mcp.Server.Models.ProjectStatus", b => { b.Property<int>("ProjectStatusID") .HasColumnType("int"); b.Property<string>("Name") .HasColumnType("nvarchar(max)"); b.HasKey("ProjectStatusID"); b.ToTable("ProjectStatus"); b.HasData( new { ProjectStatusID = 1, Name = "Backlog" }, new { ProjectStatusID = 2, Name = "Active" }, new { ProjectStatusID = 3, Name = "Complete" }, new { ProjectStatusID = 4, Name = "Canceled" }); }); modelBuilder.Entity("mcp.Server.Models.ProjectTool", b => { b.Property<int>("ProjectToolID") .ValueGeneratedOnAdd() .HasColumnType("int") .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); b.Property<decimal?>("AppliedPrice") .HasColumnType("decimal(10,2)"); b.Property<string>("Description") .HasColumnType("nvarchar(max)"); b.Property<bool>("IsDeleted") .HasColumnType("bit"); b.Property<string>("Link") .HasColumnType("nvarchar(max)"); b.Property<string>("Manufacturer") .HasColumnType("nvarchar(max)"); b.Property<string>("Name") .HasColumnType("nvarchar(max)"); b.Property<string>("PartNumber") .HasColumnType("nvarchar(max)"); b.Property<decimal?>("Price") .HasColumnType("decimal(10,2)"); b.Property<int>("ProjectID") .HasColumnType("int"); b.Property<int>("Quantity") .ValueGeneratedOnAdd() .HasColumnType("int") .HasDefaultValue(1); b.Property<int>("QuantityPurchased") .HasColumnType("int"); b.HasKey("ProjectToolID"); b.HasIndex("ProjectID"); b.ToTable("ProjectTool"); }); modelBuilder.Entity("mcp.Server.Models.Tag", b => { b.Property<int>("TagID") .HasColumnType("int"); b.Property<string>("Description") .HasColumnType("nvarchar(max)"); b.Property<bool>("IsDeleted") .HasColumnType("bit"); b.Property<string>("Name") .HasColumnType("nvarchar(max)"); b.Property<int>("SortOrder") .HasColumnType("int"); b.HasKey("TagID"); b.ToTable("Tag"); b.HasData( new { TagID = 1, Description = "A vehicle being restored to a like-new state", IsDeleted = false, Name = "Restoration", SortOrder = 0 }, new { TagID = 2, Description = "A vehicle being restored while making modifications along the way", IsDeleted = false, Name = "Restomod", SortOrder = 0 }, new { TagID = 3, Description = "A vehicle that is built for performance but driven on public streets", IsDeleted = false, Name = "Performance Street", SortOrder = 0 }, new { TagID = 4, Description = "A vehicle that is street driven and also goes to the drag strip", IsDeleted = false, Name = "Street/Strip", SortOrder = 0 }, new { TagID = 5, Description = "A vehicle used on the drag strip that is rarely, if ever, street driven", IsDeleted = false, Name = "Drag", SortOrder = 0 }, new { TagID = 6, Description = "A vehicle that competes in autocross competitions", IsDeleted = false, Name = "Autocross", SortOrder = 0 }, new { TagID = 7, Description = "A vehicle that competes in road race competitions", IsDeleted = false, Name = "Road Race", SortOrder = 0 }, new { TagID = 8, Description = "A vehicle built for drift events", IsDeleted = false, Name = "Drift", SortOrder = 0 }, new { TagID = 9, Description = "A vehicle modified to deliberately look worn or unfinished", IsDeleted = false, Name = "Rat Rod", SortOrder = 0 }, new { TagID = 10, Description = "A vehicle that is entered into car shows", IsDeleted = false, Name = "Show", SortOrder = 0 }, new { TagID = 11, Description = "A vehicle with airbags or hydraulics modified in the lowrider style", IsDeleted = false, Name = "Lowrider", SortOrder = 0 }, new { TagID = 12, Description = "A vehicle modified to be lower, often with stretched tires and lots of negative camber", IsDeleted = false, Name = "Stanced", SortOrder = 0 }, new { TagID = 13, Description = "A vehicle from Europe, typically modified by removing seams, badges, or trim", IsDeleted = false, Name = "Euro", SortOrder = 0 }, new { TagID = 14, Description = "A vehicle from Japan often modified in a Japanese style", IsDeleted = false, Name = "JDM", SortOrder = 0 }, new { TagID = 15, Description = "A vehicle that has been lightly modified with upgraded parts from the manufacturer", IsDeleted = false, Name = "OEM+", SortOrder = 0 }, new { TagID = 16, Description = "A vehicle modified to have an impressive stereo, often used in competition", IsDeleted = false, Name = "Stereo", SortOrder = 0 }, new { TagID = 17, Description = "A vehicle from the 1930s and 1940s modified in the hot rod style", IsDeleted = false, Name = "Hot Rod", SortOrder = 0 }, new { TagID = 18, Description = "A vehicle with collector value", IsDeleted = false, Name = "Collector", SortOrder = 0 }, new { TagID = 19, Description = "A vehicle driven on a road course for fun instead of competition", IsDeleted = false, Name = "Open Track", SortOrder = 0 }, new { TagID = 20, Description = "A vehicle that is much faster than it looks", IsDeleted = false, Name = "Sleeper", SortOrder = 0 }); }); modelBuilder.Entity("mcp.Server.Models.UserCategory", b => { b.Property<int>("UserCategoryID") .ValueGeneratedOnAdd() .HasColumnType("int") .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); b.Property<int?>("CategoryID") .HasColumnType("int"); b.Property<bool>("IsDeleted") .HasColumnType("bit"); b.Property<string>("Name") .HasColumnType("nvarchar(max)"); b.Property<int>("SortOrder") .HasColumnType("int"); b.Property<string>("UserID") .HasColumnType("nvarchar(450)"); b.HasKey("UserCategoryID"); b.HasIndex("CategoryID"); b.HasIndex("UserID"); b.ToTable("UserCategory"); }); modelBuilder.Entity("mcp.Server.Models.Vehicle", b => { b.Property<int>("VehicleID") .ValueGeneratedOnAdd() .HasColumnType("int") .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); b.Property<decimal?>("EstimatedValue") .HasColumnType("decimal(10,2)"); b.Property<decimal?>("ForSaleAskingPrice") .HasColumnType("decimal(10,2)"); b.Property<string>("ForSaleLink") .HasColumnType("nvarchar(max)"); b.Property<decimal?>("ForSaleTransactionPrice") .HasColumnType("decimal(10,2)"); b.Property<bool>("IsDeleted") .HasColumnType("bit"); b.Property<bool>("IsForSale") .HasColumnType("bit"); b.Property<bool>("IsSold") .HasColumnType("bit"); b.Property<string>("Name") .HasColumnType("nvarchar(max)"); b.Property<string>("Notes") .HasColumnType("nvarchar(max)"); b.Property<DateTime?>("PurchaseDate") .HasColumnType("datetime2"); b.Property<decimal?>("PurchasePrice") .HasColumnType("decimal(10,2)"); b.Property<decimal?>("TotalInvested") .HasColumnType("decimal(10,2)"); b.Property<string>("UserID") .HasColumnType("nvarchar(450)"); b.HasKey("VehicleID"); b.HasIndex("UserID"); b.ToTable("Vehicle"); }); modelBuilder.Entity("mcp.Server.Models.VehicleModification", b => { b.Property<int>("VehicleModificationID") .ValueGeneratedOnAdd() .HasColumnType("int") .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); b.Property<string>("Description") .HasColumnType("nvarchar(max)"); b.Property<bool>("IsHighlighted") .HasColumnType("bit"); b.Property<string>("Name") .HasColumnType("nvarchar(max)"); b.Property<int>("SortOrder") .HasColumnType("int"); b.Property<int?>("UserCategoryID") .HasColumnType("int"); b.Property<int>("VehicleID") .HasColumnType("int"); b.HasKey("VehicleModificationID"); b.HasIndex("UserCategoryID"); b.HasIndex("VehicleID"); b.ToTable("VehicleModification"); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRoleClaim<string>", b => { b.HasOne("Microsoft.AspNetCore.Identity.IdentityRole", null) .WithMany() .HasForeignKey("RoleId") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserClaim<string>", b => { b.HasOne("mcp.Server.Models.ApplicationUser", null) .WithMany() .HasForeignKey("UserId") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserLogin<string>", b => { b.HasOne("mcp.Server.Models.ApplicationUser", null) .WithMany() .HasForeignKey("UserId") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserRole<string>", b => { b.HasOne("Microsoft.AspNetCore.Identity.IdentityRole", null) .WithMany() .HasForeignKey("RoleId") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); b.HasOne("mcp.Server.Models.ApplicationUser", null) .WithMany() .HasForeignKey("UserId") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserToken<string>", b => { b.HasOne("mcp.Server.Models.ApplicationUser", null) .WithMany() .HasForeignKey("UserId") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); }); modelBuilder.Entity("mcp.Server.Models.Project", b => { b.HasOne("mcp.Server.Models.Project", "ParentProject") .WithMany("SubProjects") .HasForeignKey("ParentProjectID"); b.HasOne("mcp.Server.Models.ProjectStatus", "ProjectStatus") .WithMany() .HasForeignKey("ProjectStatusID") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); b.HasOne("mcp.Server.Models.UserCategory", "UserCategory") .WithMany() .HasForeignKey("UserCategoryID"); b.HasOne("mcp.Server.Models.Vehicle", "Vehicle") .WithMany("Projects") .HasForeignKey("VehicleID") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); b.Navigation("ParentProject"); b.Navigation("ProjectStatus"); b.Navigation("UserCategory"); b.Navigation("Vehicle"); }); modelBuilder.Entity("mcp.Server.Models.ProjectChecklistItem", b => { b.HasOne("mcp.Server.Models.Project", "Project") .WithMany("ChecklistItems") .HasForeignKey("ProjectID") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); b.Navigation("Project"); }); modelBuilder.Entity("mcp.Server.Models.ProjectDependency", b => { b.HasOne("mcp.Server.Models.Project", "DependsOnProject") .WithMany("DependenciesOf") .HasForeignKey("DependsOnProjectID") .OnDelete(DeleteBehavior.Restrict) .IsRequired(); b.HasOne("mcp.Server.Models.Project", "Project") .WithMany("Dependencies") .HasForeignKey("ProjectID") .OnDelete(DeleteBehavior.Restrict) .IsRequired(); b.Navigation("DependsOnProject"); b.Navigation("Project"); }); modelBuilder.Entity("mcp.Server.Models.ProjectPart", b => { b.HasOne("mcp.Server.Models.Project", "Project") .WithMany("Parts") .HasForeignKey("ProjectID") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); b.Navigation("Project"); }); modelBuilder.Entity("mcp.Server.Models.ProjectTool", b => { b.HasOne("mcp.Server.Models.Project", "Project") .WithMany() .HasForeignKey("ProjectID") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); b.Navigation("Project"); }); modelBuilder.Entity("mcp.Server.Models.UserCategory", b => { b.HasOne("mcp.Server.Models.Category", "BaseCategory") .WithMany() .HasForeignKey("CategoryID"); b.HasOne("mcp.Server.Models.ApplicationUser", "User") .WithMany() .HasForeignKey("UserID"); b.Navigation("BaseCategory"); b.Navigation("User"); }); modelBuilder.Entity("mcp.Server.Models.Vehicle", b => { b.HasOne("mcp.Server.Models.ApplicationUser", "User") .WithMany() .HasForeignKey("UserID"); b.Navigation("User"); }); modelBuilder.Entity("mcp.Server.Models.VehicleModification", b => { b.HasOne("mcp.Server.Models.UserCategory", "UserCategory") .WithMany() .HasForeignKey("UserCategoryID"); b.HasOne("mcp.Server.Models.Vehicle", "Vehicle") .WithMany("Modifications") .HasForeignKey("VehicleID") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); b.Navigation("UserCategory"); b.Navigation("Vehicle"); }); modelBuilder.Entity("mcp.Server.Models.Project", b => { b.Navigation("ChecklistItems"); b.Navigation("Dependencies"); b.Navigation("DependenciesOf"); b.Navigation("Parts"); b.Navigation("SubProjects"); }); modelBuilder.Entity("mcp.Server.Models.Vehicle", b => { b.Navigation("Modifications"); b.Navigation("Projects"); }); #pragma warning restore 612, 618 } } }
37.422414
131
0.402695
[ "MIT" ]
srenner/mcp-v2
mcp/mcp/Server/Data/Migrations/ApplicationDbContextModelSnapshot.cs
43,412
C#
using System.Collections.Generic; using Microsoft.VisualStudio.TestTools.UnitTesting; namespace Sensit.TestSDK.Utilities.Tests { [TestClass] public class LineSplitterTests { [TestMethod] public void DetectorTestTwoLinesArrivingTogether() { // Create a list to hold data packets. List<byte[]> result_lines = new List<byte[]>(); // Create a line splitter object. LineSplitter lineSplitter = new LineSplitter(); // When a new data packet is received, add it to the list of data packets. lineSplitter.LineReceived += result_lines.Add; // Send an array of bytes into the splitter. lineSplitter.OnIncomingBinaryBlock(new byte[] { 0x48, 0x65, 0x6C, 0x6C, 0x6F, 0x20, 0x72, 0x65, 0x61, 0x64, 0x65, 0x72, 0x73, 0x21, 0x0D, 0x0A, 0x53, 0x70, 0x61, 0x72, 0x78, 0x20, 0x69, 0x73, 0x20, 0x74, 0x68, 0x65, 0x20, 0x62, 0x65, 0x73, 0x74, 0x2E, 0x0D, 0x0A }); // Check that the line splitter correctly found two lines. Assert.AreEqual(2, result_lines.Count); } } }
34.344828
269
0.718876
[ "MIT" ]
SensitTechnologies/TestSDK
UnitTests/Utility/LineSplitterTests.cs
998
C#
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ /* * Do not modify this file. This file is generated from the datasync-2018-11-09.normal.json service model. */ using System; using System.Collections.Generic; using System.Globalization; using System.IO; using System.Text; using System.Xml.Serialization; using Amazon.DataSync.Model; using Amazon.Runtime; using Amazon.Runtime.Internal; using Amazon.Runtime.Internal.Transform; using Amazon.Runtime.Internal.Util; using ThirdParty.Json.LitJson; namespace Amazon.DataSync.Model.Internal.MarshallTransformations { /// <summary> /// Options Marshaller /// </summary> public class OptionsMarshaller : IRequestMarshaller<Options, JsonMarshallerContext> { /// <summary> /// Unmarshaller the response from the service to the response class. /// </summary> /// <param name="requestObject"></param> /// <param name="context"></param> /// <returns></returns> public void Marshall(Options requestObject, JsonMarshallerContext context) { if(requestObject.IsSetAtime()) { context.Writer.WritePropertyName("Atime"); context.Writer.Write(requestObject.Atime); } if(requestObject.IsSetBytesPerSecond()) { context.Writer.WritePropertyName("BytesPerSecond"); context.Writer.Write(requestObject.BytesPerSecond); } if(requestObject.IsSetGid()) { context.Writer.WritePropertyName("Gid"); context.Writer.Write(requestObject.Gid); } if(requestObject.IsSetLogLevel()) { context.Writer.WritePropertyName("LogLevel"); context.Writer.Write(requestObject.LogLevel); } if(requestObject.IsSetMtime()) { context.Writer.WritePropertyName("Mtime"); context.Writer.Write(requestObject.Mtime); } if(requestObject.IsSetObjectTags()) { context.Writer.WritePropertyName("ObjectTags"); context.Writer.Write(requestObject.ObjectTags); } if(requestObject.IsSetOverwriteMode()) { context.Writer.WritePropertyName("OverwriteMode"); context.Writer.Write(requestObject.OverwriteMode); } if(requestObject.IsSetPosixPermissions()) { context.Writer.WritePropertyName("PosixPermissions"); context.Writer.Write(requestObject.PosixPermissions); } if(requestObject.IsSetPreserveDeletedFiles()) { context.Writer.WritePropertyName("PreserveDeletedFiles"); context.Writer.Write(requestObject.PreserveDeletedFiles); } if(requestObject.IsSetPreserveDevices()) { context.Writer.WritePropertyName("PreserveDevices"); context.Writer.Write(requestObject.PreserveDevices); } if(requestObject.IsSetSecurityDescriptorCopyFlags()) { context.Writer.WritePropertyName("SecurityDescriptorCopyFlags"); context.Writer.Write(requestObject.SecurityDescriptorCopyFlags); } if(requestObject.IsSetTaskQueueing()) { context.Writer.WritePropertyName("TaskQueueing"); context.Writer.Write(requestObject.TaskQueueing); } if(requestObject.IsSetTransferMode()) { context.Writer.WritePropertyName("TransferMode"); context.Writer.Write(requestObject.TransferMode); } if(requestObject.IsSetUid()) { context.Writer.WritePropertyName("Uid"); context.Writer.Write(requestObject.Uid); } if(requestObject.IsSetVerifyMode()) { context.Writer.WritePropertyName("VerifyMode"); context.Writer.Write(requestObject.VerifyMode); } } /// <summary> /// Singleton Marshaller. /// </summary> public readonly static OptionsMarshaller Instance = new OptionsMarshaller(); } }
33.726027
106
0.604184
[ "Apache-2.0" ]
Hazy87/aws-sdk-net
sdk/src/Services/DataSync/Generated/Model/Internal/MarshallTransformations/OptionsMarshaller.cs
4,924
C#
using System.Collections.Generic; using System.Reflection; namespace Umbraco.Core.Plugins { //TODO: Copied locally since we don't want to reference MVC from Core this will change with rc2 public interface IUmbracoAssemblyProvider { IEnumerable<Assembly> CandidateAssemblies { get; } } }
28.363636
99
0.74359
[ "MIT" ]
Shazwazza/Umbraco9
src/Umbraco.Core/Plugins/IUmbracoAssemblyProvider.cs
314
C#
using System.Reflection; using System.Resources; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Windows; // Управление общими сведениями о сборке осуществляется с помощью // набора атрибутов. Измените значения этих атрибутов, чтобы изменить сведения, // связанные со сборкой. [assembly: AssemblyTitle("SemPoliticsWpfDB")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("SemPoliticsWpfDB")] [assembly: AssemblyCopyright("Copyright © 2016")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Параметр ComVisible со значением FALSE делает типы в сборке невидимыми // для COM-компонентов. Если требуется обратиться к типу в этой сборке через // COM, задайте атрибуту ComVisible значение TRUE для этого типа. [assembly: ComVisible(false)] //Чтобы начать сборку локализованных приложений, задайте //<UICulture>CultureYouAreCodingWith</UICulture> в файле .csproj //внутри <PropertyGroup>. Например, если используется английский США //в своих исходных файлах установите <UICulture> в en-US. Затем отмените преобразование в комментарий //атрибута NeutralResourceLanguage ниже. Обновите "en-US" в //строка внизу для обеспечения соответствия настройки UICulture в файле проекта. //[assembly: NeutralResourcesLanguage("en-US", UltimateResourceFallbackLocation.Satellite)] [assembly: ThemeInfo( ResourceDictionaryLocation.None, //где расположены словари ресурсов по конкретным тематикам //(используется, если ресурс не найден на странице // или в словарях ресурсов приложения) ResourceDictionaryLocation.SourceAssembly //где расположен словарь универсальных ресурсов //(используется, если ресурс не найден на странице, // в приложении или в каких-либо словарях ресурсов для конкретной темы) )] // Сведения о версии сборки состоят из следующих четырех значений: // // Основной номер версии // Дополнительный номер версии // Номер сборки // Редакция // // Можно задать все значения или принять номера сборки и редакции по умолчанию // используя "*", как показано ниже: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
43.517857
117
0.725482
[ "MIT" ]
OlegShatin/SemPoliticsWpfDB
SemPoliticsWpfDB/Properties/AssemblyInfo.cs
3,427
C#
namespace Zone.UmbracoPersonalisationGroups.Criteria.Session { public enum SessionSettingMatch { Exists, DoesNotExist, MatchesValue, ContainsValue, GreaterThanValue, GreaterThanOrEqualToValue, LessThanValue, LessThanOrEqualToValue, MatchesRegex, DoesNotMatchRegex, } public class SessionSetting { public string Key { get; set; } public SessionSettingMatch Match { get; set; } public string Value { get; set; } } }
21
61
0.619048
[ "MIT" ]
twaddell/UmbracoPersonalisationGroups
Zone.UmbracoPersonalisationGroups/Criteria/Session/SessionSetting.cs
548
C#
/* * Copyright 2019 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ using System.Collections; using System.Collections.Generic; using UnityEngine; public class RenderableLibraryUI : MonoBehaviour { public UnityEngine.UI.Button closeButton; public UnityEngine.UI.VerticalLayoutGroup content; public TMPro.TMP_InputField searchInput; public UnityEngine.UI.Button clearSearchButton; public GameObject categoriesList; public TextIconButtonUI categoryButtonPrefab; public GameObject inCategoryContainer; public TMPro.TextMeshProUGUI inCategoryLabel; public UnityEngine.UI.Button inCategoryBackButton; public UnityEngine.UI.Button inCategoryLink; public TMPro.TextMeshProUGUI webSearchHint; public GameObject resultsRectContainer; public RectTransform resultsRect; public SquareImageButtonUI resultsPrefab; }
35.789474
75
0.796324
[ "ECL-2.0", "Apache-2.0" ]
AlCapslock/gamebuilder
Assets/UIAssets/Scripts/RenderableLibraryUI.cs
1,360
C#
using System; namespace HotChocolate.Types.Descriptors { public sealed class ClrTypeDirectiveReference : IDirectiveReference { public ClrTypeDirectiveReference(Type clrType) { ClrType = clrType ?? throw new ArgumentNullException(nameof(clrType)); } public Type ClrType { get; } } }
21.411765
68
0.623626
[ "MIT" ]
Coldplayer1995/GraphQLTest
src/Core/Types/Types/Descriptors/TypeReferences/ClrTypeDirectiveReference.cs
364
C#
#region License // Copyright (c) 2007-2009, Sean Chambers <[email protected]> // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #endregion using System.Data; using System.Data.OleDb; using FluentMigrator.Runner.Announcers; using FluentMigrator.Runner.Generators.Jet; using FluentMigrator.Runner.Processors; using FluentMigrator.Runner.Processors.Jet; using FluentMigrator.Tests.Helpers; using NUnit.Framework; using NUnit.Should; namespace FluentMigrator.Tests.Integration.Processors.Jet { [TestFixture] [Category("Integration")] public class JetProcessorTests { public OleDbConnection Connection { get; set; } public JetProcessor Processor { get; set; } [SetUp] public void SetUp() { Connection = new OleDbConnection(IntegrationTestOptions.Jet.ConnectionString); Processor = new JetProcessor(Connection, new JetGenerator(), new TextWriterAnnouncer(System.Console.Out), new ProcessorOptions()); Connection.Open(); } [Test] public void CallingTableExistsReturnsFalseIfTableDoesNotExist() { Processor.TableExists(null, "DoesNotExist").ShouldBeFalse(); } [Test] public void CallingTableExistsReturnsTrueIfTableExists() { using (var table = new JetTestTable(Processor, "id int")) Processor.TableExists(null, table.Name).ShouldBeTrue(); } [Test] public void CallingColumnExistsReturnsTrueIfColumnExists() { using (var table = new JetTestTable(Processor, "id int")) Processor.ColumnExists(null, table.Name, "id").ShouldBeTrue(); } [Test] public void CallingColumnExistsReturnsFalseIfTableDoesNotExist() { Processor.ColumnExists(null, "DoesNotExist", "DoesNotExist").ShouldBeFalse(); } [Test] public void CallingColumnExistsReturnsFalseIfColumnDoesNotExist() { using (var table = new JetTestTable(Processor, "id int")) Processor.ColumnExists(null, table.Name, "DoesNotExist").ShouldBeFalse(); } [Test] public void CanReadData() { using (var table = new JetTestTable(Processor, "id int")) { AddTestData(table); DataSet ds = Processor.Read("SELECT * FROM {0}", table.Name); ds.ShouldNotBeNull(); ds.Tables.Count.ShouldBe(1); ds.Tables[0].Rows.Count.ShouldBe(3); ds.Tables[0].Rows[2][0].ShouldBe(2); } } [Test] public void CanReadTableData() { using (var table = new JetTestTable(Processor, "id int")) { AddTestData(table); DataSet ds = Processor.ReadTableData(null, table.Name); ds.ShouldNotBeNull(); ds.Tables.Count.ShouldBe(1); ds.Tables[0].Rows.Count.ShouldBe(3); ds.Tables[0].Rows[2][0].ShouldBe(2); } } private void AddTestData(JetTestTable table) { for (int i = 0; i < 3; i++) { var cmd = table.Connection.CreateCommand(); cmd.Transaction = table.Transaction; cmd.CommandText = string.Format("INSERT INTO {0} (id) VALUES ({1})", table.Name, i); cmd.ExecuteNonQuery(); } } [TearDown] public void TearDown() { Processor.CommitTransaction(); Processor.Dispose(); } } }
33.087302
142
0.602303
[ "Apache-2.0" ]
BartDM/fluentmigrator
src/FluentMigrator.Tests/Integration/Processors/Jet/JetProcessorTests.cs
4,171
C#
// MonoGame - Copyright (C) The MonoGame Team // This file is subject to the terms and conditions defined in // file 'LICENSE.txt', which is part of this source code package. using System; using System.Collections.ObjectModel; namespace Microsoft.Xna.Framework.Content.Pipeline.Graphics { /// <summary> /// Provides methods for maintaining a mipmap chain. /// </summary> public sealed class MipmapChainCollection : Collection<MipmapChain> { private readonly bool _fixedSize; private const string CannotResizeError = "Cannot resize MipmapChainCollection. This type of texture has a fixed number of faces."; internal MipmapChainCollection(int count, bool fixedSize) { for (var i = 0; i < count; i++) Add(new MipmapChain()); _fixedSize = fixedSize; } protected override void ClearItems() { if (_fixedSize) throw new NotSupportedException(CannotResizeError); base.ClearItems(); } protected override void RemoveItem(int index) { if (_fixedSize) throw new NotSupportedException(CannotResizeError); base.RemoveItem(index); } protected override void InsertItem(int index, MipmapChain item) { if (_fixedSize) throw new NotSupportedException(CannotResizeError); base.InsertItem(index, item); } } }
28.769231
138
0.622995
[ "MIT" ]
06needhamt/MonoGame
MonoGame.Framework.Content.Pipeline/Graphics/MipmapChainCollection.cs
1,498
C#
#region License // Copyright (c) 2016-2018 Cisco Systems, Inc. // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. #endregion using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace KitchenSink { public class DeviceData { public List<WebexSDK.AVIODevice> MicroPhoneList { get; set; } public List<WebexSDK.AVIODevice> SpeakerList { get; set; } public List<WebexSDK.AVIODevice> RingerList { get; set; } public List<WebexSDK.AVIODevice> CameraList { get; set; } public DeviceData(WebexSDK.Webex webex) { MicroPhoneList = webex.Phone.GetAVIODevices(WebexSDK.AVIODeviceType.Microphone); SpeakerList = webex.Phone.GetAVIODevices(WebexSDK.AVIODeviceType.Speaker); RingerList = webex.Phone.GetAVIODevices(WebexSDK.AVIODeviceType.Ringer); CameraList = webex.Phone.GetAVIODevices(WebexSDK.AVIODeviceType.Camera); convertoUTF8(MicroPhoneList); convertoUTF8(SpeakerList); convertoUTF8(RingerList); convertoUTF8(CameraList); systemDefault(MicroPhoneList); systemDefault(SpeakerList); systemDefault(RingerList); systemDefault(CameraList); } private void convertoUTF8(List<WebexSDK.AVIODevice> devices) { foreach (var i in devices) { i.Name = Encoding.UTF8.GetString(Encoding.Default.GetBytes(i.Name)); } } private void systemDefault(List<WebexSDK.AVIODevice> devices) { foreach (var i in devices) { if (i.DefaultDevice == true) { i.Name = "system default"; } } } } }
37.207792
92
0.66911
[ "MIT" ]
webex/webex-windows-sdk-example
KitchenSink-WPF/Models/DeviceData.cs
2,867
C#
//------------------------------------------------------------------------------ // <auto-generated> // Este código foi gerado por uma ferramenta. // Versão de Tempo de Execução:4.0.30319.42000 // // As alterações a este ficheiro poderão provocar um comportamento incorrecto e perder-se-ão se // o código for regenerado. // </auto-generated> //------------------------------------------------------------------------------ using System; using System.Reflection; [assembly: System.Reflection.AssemblyCompanyAttribute("$safeprojectname$.Application.Tests")] [assembly: System.Reflection.AssemblyConfigurationAttribute("Debug")] [assembly: System.Reflection.AssemblyFileVersionAttribute("1.0.0.0")] [assembly: System.Reflection.AssemblyInformationalVersionAttribute("1.0.0")] [assembly: System.Reflection.AssemblyProductAttribute("$safeprojectname$.Application.Tests")] [assembly: System.Reflection.AssemblyTitleAttribute("$safeprojectname$.Application.Tests")] [assembly: System.Reflection.AssemblyVersionAttribute("1.0.0.0")] // Generated by the MSBuild WriteCodeFragment class.
45.75
99
0.669399
[ "MIT" ]
Pedro-Lopes/Template
_template/Copia/tests/Template.Application.Tests/obj/Debug/netcoreapp3.1/Template.Application.Tests.AssemblyInfo.cs
1,107
C#
using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.RazorPages; using FishAquariumWebApp.Models; using Microsoft.AspNetCore.Mvc.Rendering; using Microsoft.EntityFrameworkCore; namespace FishAquariumWebApp.Pages.Portions { public class CreateModel : PageModel { private readonly FishAquariumWebApp.Configurations.FishAquariumContext _context; public CreateModel(FishAquariumWebApp.Configurations.FishAquariumContext context) { _context = context; } public async Task<IActionResult> OnGet() { Foods = (await _context.Food.ToListAsync()).Select(x => new SelectListItem(x.Name, x.Id.ToString())); Supplements = (await _context.Supplement.ToListAsync()).Select(x => new SelectListItem(x.Name, x.Id.ToString())); return Page(); } [BindProperty] public Portion Portion { get; set; } public IEnumerable<SelectListItem> Foods { get; set; } public IEnumerable<SelectListItem> Supplements { get; set; } public async Task<IActionResult> OnPostAsync() { if (!ModelState.IsValid) { return Page(); } _context.Portion.Add(Portion); await _context.SaveChangesAsync(); return RedirectToPage("./Index"); } } }
30.914894
125
0.648314
[ "MIT" ]
youstinus/fish-aquarium
src/server-core/FishAquariumWebApp/Pages/Portions/Create.cshtml.cs
1,455
C#
using System; using System.Reflection; using HarmonyLib; using Verse; namespace Multiplayer.Compat { /// <summary>Stuffed Floors by Fluffy</summary> /// <see href="https://github.com/fluffy-mods/StuffedFloors"/> /// <see href="https://steamcommunity.com/sharedfiles/filedetails/?id=853043503"/> [MpCompatFor("fluffy.stuffedfloors")] class StuffedFloorsCompat { public StuffedFloorsCompat(ModContentPack mod) { MpCompat.harmony.Patch( AccessTools.Method("StuffedFloors.FloorTypeDef:GetStuffedTerrainDef"), postfix: new HarmonyMethod(typeof(StuffedFloorsCompat), nameof(GetStuffedTerrainDefPosfix)) ); } static void GetStuffedTerrainDefPosfix(TerrainDef __result) { DefDatabase<BuildableDef>.Add(__result); } } }
28.8
107
0.659722
[ "MIT" ]
rwmt/RimWorld-Multiplayer-Compatibility
Source/Mods/StuffedFloors.cs
866
C#
using System; using System.Collections; using System.Collections.Generic; using System.Globalization; using System.IO; using System.IO.IsolatedStorage; using System.Linq; using System.Reflection; using System.Runtime.InteropServices; using System.Text; using System.Threading; using accel; using dbg; using er; using er.web; using gs; using gs.backup; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Audio; using Microsoft.Xna.Framework.Content; using Microsoft.Xna.Framework.Graphics; using Microsoft.Xna.Framework.Graphics.PackedVector; using Microsoft.Xna.Framework.Input; using Microsoft.Xna.Framework.Media; using mpp; using setting; public partial class AppMain { public class GMS_GMK_PMARKER_WORK : AppMain.IOBS_OBJECT_WORK { public readonly AppMain.GMS_ENEMY_3D_WORK gmk_work; public int markerdist; public int markerdistlast; public int hitcounter; public ushort marker_prty; public GMS_GMK_PMARKER_WORK() { this.gmk_work = new AppMain.GMS_ENEMY_3D_WORK((object)this); } public AppMain.OBS_OBJECT_WORK Cast() { return this.gmk_work.ene_com.obj_work; } public AppMain.OBS_ACTION3D_NN_WORK OBJ_3D { get { return this.gmk_work.obj_3d; } } public AppMain.GMS_ENEMY_COM_WORK COMWORK { get { return this.gmk_work.ene_com; } } public AppMain.OBS_OBJECT_WORK OBJWORK { get { return this.COMWORK.obj_work; } } } }
23.082192
72
0.642136
[ "Unlicense" ]
WanKerr/Sonic4Episode1
Sonic4Episode1/AppMain/Types/GMS_GMK_PMARKER_WORK.cs
1,685
C#
using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; using Microsoft.EntityFrameworkCore; using Modix.Data.Utilities; namespace Modix.Data.Models.Core { /// <summary> /// Describes a mapping that assigns an arbitrary designation to a particular role within a guild. /// </summary> public class DesignatedRoleMappingEntity { /// <summary> /// A unique identifier for this mapping. /// </summary> [Key] [Required] [DatabaseGenerated(DatabaseGeneratedOption.Identity)] public long Id { get; set; } /// <summary> /// The Discord snowflake ID of the guild to which this mapping applies. /// </summary> [Required] public ulong GuildId { get; set; } /// <summary> /// The <see cref="GuildRoleEntity.RoleId"/> value of <see cref="Role"/>. /// </summary> [Required] [ForeignKey(nameof(Role))] public ulong RoleId { get; set; } /// <summary> /// The role being designated by this mapping. /// </summary> [Required] public virtual GuildRoleEntity Role { get; set; } = null!; /// <summary> /// The type of designation being defined for this role. /// </summary> [Required] public DesignatedRoleType Type { get; set; } /// <summary> /// The <see cref="ConfigurationActionEntity.Id"/> value of <see cref="CreateAction"/>. /// </summary> [Required] public long CreateActionId { get; set; } /// <summary> /// The <see cref="ConfigurationActionEntity"/> that created this <see cref="DesignatedRoleMappingEntity"/>. /// </summary> public virtual ConfigurationActionEntity CreateAction { get; set; } = null!; /// <summary> /// The <see cref="ConfigurationActionEntity.Id"/> value of <see cref="DeleteAction"/>. /// </summary> public long? DeleteActionId { get; set; } /// <summary> /// The <see cref="ConfigurationActionEntity"/> (if any) that deleted this <see cref="DesignatedRoleMappingEntity"/>. /// </summary> public virtual ConfigurationActionEntity? DeleteAction { get; set; } [OnModelCreating] internal static void OnModelCreating(ModelBuilder modelBuilder) { modelBuilder .Entity<DesignatedRoleMappingEntity>() .Property(x => x.Type) .HasConversion<string>(); modelBuilder .Entity<DesignatedRoleMappingEntity>() .Property(x => x.GuildId) .HasConversion<long>(); modelBuilder .Entity<DesignatedRoleMappingEntity>() .Property(x => x.RoleId) .HasConversion<long>(); modelBuilder .Entity<DesignatedRoleMappingEntity>() .HasOne(x => x.CreateAction) .WithOne() .HasForeignKey<DesignatedRoleMappingEntity>(x => x.CreateActionId); modelBuilder .Entity<DesignatedRoleMappingEntity>() .HasOne(x => x.DeleteAction) .WithOne() .HasForeignKey<DesignatedRoleMappingEntity>(x => x.DeleteActionId); } } }
33.544554
125
0.572314
[ "MIT" ]
JasonHughes94/MODiX
Modix.Data/Models/Core/DesignatedRoleMappingEntity.cs
3,390
C#
namespace SKIT.FlurlHttpClient.Wechat.Api.Models { /// <summary> /// <para>表示 [POST] /cgi-bin/comment/unmarkelect 接口的请求。</para> /// </summary> public class CgibinCommentUnmarkElectRequest : CgibinCommentMarkElectRequest, IMapResponse<CgibinCommentUnmarkElectRequest, CgibinCommentUnmarkElectResponse> { } }
33.2
161
0.740964
[ "MIT" ]
vst-h/DotNetCore.SKIT.FlurlHttpClient.Wechat
src/SKIT.FlurlHttpClient.Wechat.Api/Models/CgibinComment/CgibinCommentUnmarkElectRequest.cs
350
C#
 using System.Collections; using System.Collections.Generic; namespace Monster.Entity.DomainModels { public class SaveModel { public Dictionary<string, object> MainData { get; set; } public List<Dictionary<string, object>> DetailData { get; set; } public List<object> DelKeys { get; set; } /// <summary> /// 从前台传入的其他参数(自定义扩展可以使用) /// </summary> public object Extra { get; set; } } }
23.947368
72
0.615385
[ "Apache-2.0" ]
guipie/Api
Monster.Entity/DomainModels/Core/SaveDataModel.cs
495
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; class CharityMarathon { static void Main() { var days = int.Parse(Console.ReadLine()); var participants = int.Parse(Console.ReadLine()); var laps = decimal.Parse(Console.ReadLine()); var length = decimal.Parse(Console.ReadLine()); var capacity = decimal.Parse(Console.ReadLine()); var money = decimal.Parse(Console.ReadLine()); var maxRun = capacity * days; /* var totalRunners = Math.Min(participant, capacyty * days); * var totalKm = (final * laps * length) / 1000; var raised = totalKm * money; Console.WriteLine($@"Money raised: {raised:f2}"); */ var final = 0.0m; if (maxRun >= participants) { final = participants; var totalKm = (final * laps * length) / 1000; var raised = totalKm * money; Console.WriteLine($@"Money raised: {raised:f2}"); } else { final = maxRun; var totalKm = (final * laps * length) / 1000; var raised = totalKm * money; Console.WriteLine($@"Money raised: {raised:f2}"); } } }
28.595745
69
0.53869
[ "MIT" ]
mlkumanova/Programming-Fundamentals
Exams/Problem 1. Charity Marathon/CharityMarathon.cs
1,346
C#
namespace SuperMassive.Tests.Unit.Extensions { using System.Linq; using NUnit.Framework; using SuperMassive.Extensions; public class IntegerExtensionsTest { [TestCase(short.MinValue)] [TestCase(0)] [TestCase(short.MaxValue)] public void IntegerExtensions_AsMask_WithInt16_Returns_BitwiseMask(short value) { var result = value.AsMask(); Assert.That(result, Is.AssignableFrom(typeof(BitwiseMask))); } [TestCase(int.MinValue)] [TestCase(0)] [TestCase(int.MaxValue)] public void IntegerExtensions_AsMask_WithInt32_Returns_BitwiseMask(int value) { var result = value.AsMask(); Assert.That(result, Is.AssignableFrom(typeof(BitwiseMask))); } [TestCase(long.MinValue)] [TestCase(0)] [TestCase(long.MaxValue)] public void IntegerExtensions_AsMask_WithInt64_Returns_BitwiseMask(long value) { var result = value.AsMask(); Assert.That(result, Is.AssignableFrom(typeof(BitwiseMask))); } [TestCase(0, 0)] [TestCase(0, 1)] [TestCase(-1, 1)] [TestCase(-10, 1)] [TestCase(10, -1)] [TestCase(int.MinValue, int.MinValue)] [TestCase(int.MaxValue, int.MaxValue)] [TestCase(int.MinValue, int.MaxValue)] [TestCase(int.MaxValue, int.MinValue)] public void IntegerExtensions_To_Returns_Valid_Sequence(int startingValue, int endingValue) { var result = startingValue.To(endingValue); Assert.That(result.Count() > 0); } } }
31.377358
99
0.612147
[ "MIT" ]
PulsarBlow/SuperMassive
tests/SuperMassive.Tests.Unit/Extensions/IntegerExtensionsTest.cs
1,665
C#
// ***************************************************************************** // BSD 3-Clause License (https://github.com/ComponentFactory/Krypton/blob/master/LICENSE) // © Component Factory Pty Ltd, 2006-2019, All rights reserved. // The software and associated documentation supplied hereunder are the // proprietary information of Component Factory Pty Ltd, 13 Swallows Close, // Mornington, Vic 3931, Australia and are supplied subject to license terms. // // Modifications by Peter Wagner(aka Wagnerp) & Simon Coghlan(aka Smurf-IV) 2017 - 2019. All rights reserved. (https://github.com/Wagnerp/Krypton-NET-5.490) // Version 5.490.0.0 www.ComponentFactory.com // ***************************************************************************** using System; using System.Drawing; using System.Windows.Forms; using System.Diagnostics; using ComponentFactory.Krypton.Toolkit; namespace ComponentFactory.Krypton.Ribbon { /// <summary> /// Draws an design time only for adding a new button to a cluster. /// </summary> internal class ViewDrawRibbonDesignCluster : ViewDrawRibbonDesignBase { #region Static Fields private static readonly Padding _padding = new Padding(1, 2, 0, 2); private static readonly ImageList _imageList; #endregion #region Instance Fields private readonly KryptonRibbonGroupCluster _ribbonCluster; private ContextMenuStrip _cms; #endregion #region Identity static ViewDrawRibbonDesignCluster() { // Use image list to convert background Magenta to transparent _imageList = new ImageList { TransparentColor = Color.Magenta }; _imageList.Images.AddRange(new Image[]{Properties.Resources.KryptonRibbonGroupClusterButton, Properties.Resources.KryptonRibbonGroupClusterColorButton}); } /// <summary> /// Initialize a new instance of the ViewDrawRibbonDesignCluster class. /// </summary> /// <param name="ribbon">Reference to owning ribbon control.</param> /// <param name="ribbonCluster">Reference to cluster definition.</param> /// <param name="needPaint">Delegate for notifying paint requests.</param> public ViewDrawRibbonDesignCluster(KryptonRibbon ribbon, KryptonRibbonGroupCluster ribbonCluster, NeedPaintHandler needPaint) : base(ribbon, needPaint) { Debug.Assert(ribbonCluster != null); _ribbonCluster = ribbonCluster; } /// <summary> /// Obtains the String representation of this instance. /// </summary> /// <returns>User readable name of the instance.</returns> public override string ToString() { // Return the class name and instance identifier return "ViewDrawRibbonDesignCluster:" + Id; } #endregion #region Protected /// <summary> /// Gets the short text used as the main ribbon title. /// </summary> /// <returns>Title string.</returns> public override string GetShortText() { return "Item"; } /// <summary> /// Gets the padding to use when calculating the preferred size. /// </summary> protected override Padding PreferredPadding => _padding; /// <summary> /// Gets the padding to use when laying out the view. /// </summary> protected override Padding LayoutPadding => Padding.Empty; /// <summary> /// Gets the padding to shrink the client area by when laying out. /// </summary> protected override Padding OuterPadding => _padding; /// <summary> /// Raises the Click event. /// </summary> /// <param name="sender">Source of the event.</param> /// <param name="e">An EventArgs containing the event data.</param> protected override void OnClick(object sender, EventArgs e) { // Create the context strip the first time around if (_cms == null) { _cms = new ContextMenuStrip { ImageList = _imageList }; // Create child items ToolStripMenuItem menuButton = new ToolStripMenuItem("Add Cluster Button", null, OnAddButton); ToolStripMenuItem menuColorButton = new ToolStripMenuItem("Add Cluster Color Button", null, OnAddColorButton); // Assign correct images menuButton.ImageIndex = 0; menuColorButton.ImageIndex = 1; // Finally, add all items to the strip _cms.Items.AddRange(new ToolStripItem[] { menuButton, menuColorButton }); } if (CommonHelper.ValidContextMenuStrip(_cms)) { // Find the screen area of this view item Rectangle screenRect = Ribbon.ViewRectangleToScreen(this); // Make sure the popup is shown in a compatible way with any popups VisualPopupManager.Singleton.ShowContextMenuStrip(_cms, new Point(screenRect.X, screenRect.Bottom)); } } #endregion #region Implementation private void OnAddButton(object sender, EventArgs e) { _ribbonCluster.OnDesignTimeAddButton(); } private void OnAddColorButton(object sender, EventArgs e) { _ribbonCluster.OnDesignTimeAddColorButton(); } #endregion } }
39.187919
157
0.581264
[ "BSD-3-Clause" ]
Smurf-IV/Krypton-Toolkit-Suite-NET-Core
Source/Krypton Components/ComponentFactory.Krypton.Ribbon/View Draw/ViewDrawRibbonDesignCluster.cs
5,842
C#
using System; using System.ComponentModel; using System.IO; using System.Windows.Forms; using Alphora.Dataphor.Frontend.Client; namespace Alphora.Dataphor.Dataphoria.FormDesigner.DesignerTree { public class DesignerNode : BaseNode, ISite, IDisposable { /// <summary> Constructs a node, but does not build its children. </summary> public DesignerNode(INode node, DesignerTree tree, bool readOnly) { InitializeNode(node, tree, readOnly); } /// <summary> Constructs a node and builds its children. </summary> public DesignerNode(INode node, DesignerTree tree) { InitializeNode(node, tree, false); foreach (INode child in _node.Children) AddNode(child); } private void InitializeNode(INode node, DesignerTree tree, bool readOnly) { _node = node; _node.Site = this; _designerTree = tree; _readOnly = readOnly; UpdateText(false); ImageIndex = tree.FormDesigner.GetDesignerImage(node.GetType()); SelectedImageIndex = ImageIndex; } protected virtual void Dispose(bool disposing) { foreach (DesignerNode child in Nodes) child.Dispose(); _node.Site = null; } public void Dispose() { Dispose(false); } // Node private INode _node; public INode Node { get { return _node; } } // ReadOnly private bool _readOnly; public bool ReadOnly { get { return _readOnly; } } public void SetReadOnly(bool tempValue, bool recursive) { _readOnly = tempValue; if (recursive) foreach (DesignerNode child in Nodes) child.SetReadOnly(tempValue, true); } // DesignerTree private DesignerTree _designerTree; public DesignerTree DesignerTree { get { return _designerTree; } } // Parent public new DesignerNode Parent { get { return (DesignerNode)base.Parent; } } // Node Operations private DesignerNode Copy() { DesignerNode copy = new DesignerNode(Node, _designerTree, ReadOnly); foreach (DesignerNode node in Nodes) copy.AddBaseNode(node.Copy()); return copy; } public void DeleteNode() { if (Node != null) Node.Dispose(); } private void InternalDelete() { if (IsEditing) EndEdit(true); DeleteNode(); Remove(); } public bool Delete() { if (ReadOnly) return false; else { InternalDelete(); DesignerTree.Modified(); DesignerTree.FormDesigner.ActivateNode(null); return true; } } public void CopyToClipboard() { using (MemoryStream stream = new MemoryStream()) { BOP.Serializer serializer = DesignerTree.FormDesigner.FrontendSession.CreateSerializer(); serializer.RemoveReferencesToObjectsNotSerialized = false; serializer.Serialize(stream, Node); DesignerTree.FormDesigner.Dataphoria.Warnings.AppendErrors(DesignerTree.FormDesigner, serializer.Errors, true); stream.Position = 0; Clipboard.SetDataObject(new DataObject(DataFormats.UnicodeText, new StreamReader(stream).ReadToEnd())); } } public void CutToClipboard() { CopyToClipboard(); InternalDelete(); } private void RecursiveGetUniqueName(INode node) { Node.HostNode.GetUniqueName(node); foreach (INode child in node.Children) RecursiveGetUniqueName(child); } public void PasteFromClipboard() { INode node; using (MemoryStream stream = new MemoryStream()) { StreamWriter writer = new StreamWriter(stream); writer.Write((string)Clipboard.GetDataObject().GetData(DataFormats.UnicodeText, true)); writer.Flush(); stream.Position = 0; BOP.Deserializer deserializer = DesignerTree.FormDesigner.FrontendSession.CreateDeserializer(); deserializer.FindReference += new BOP.FindReferenceHandler(DeserializeFindReference); node = (INode)deserializer.Deserialize(stream, null); DesignerTree.FormDesigner.Dataphoria.Warnings.AppendErrors(DesignerTree.FormDesigner, deserializer.Errors, true); } Node.Children.Add(node); RecursiveGetUniqueName(node); // make names unique after adding the node in order to properly account for all nodes DesignerNode designerNode = AddNode(node); TreeView.SelectedNode = designerNode; designerNode.ExpandAll(); DesignerTree.Modified(); } private DesignerNode PlaceNewNode(INode node, DropLinePosition position) { DesignerNode designerNode; int index; switch (position) { case DropLinePosition.OnNode : Node.Children.Add(node); designerNode = AddNode(node); break; case DropLinePosition.AboveNode : index = Parent.Nodes.IndexOf(this); Node.Parent.Children.Insert(index, node); designerNode = Parent.InsertNode(index, node); break; case DropLinePosition.BelowNode : index = Parent.Nodes.IndexOf(this) + 1; Node.Parent.Children.Insert(index, node); designerNode = Parent.InsertNode(index, node); break; default : System.Diagnostics.Debug.Fail("Invalid DropLinePosition passed to CopyFromNode()"); designerNode = null; break; } TreeView.SelectedNode = designerNode; designerNode.ExpandAll(); return designerNode; } public void CopyFromNode(DesignerNode source, DropLinePosition position) { INode node; using (MemoryStream stream = new MemoryStream()) { BOP.Serializer serializer = DesignerTree.FormDesigner.FrontendSession.CreateSerializer(); serializer.Serialize(stream, source); DesignerTree.FormDesigner.Dataphoria.Warnings.AppendErrors(DesignerTree.FormDesigner, serializer.Errors, true); stream.Position = 0; BOP.Deserializer deserializer = DesignerTree.FormDesigner.FrontendSession.CreateDeserializer(); deserializer.FindReference += new BOP.FindReferenceHandler(DeserializeFindReference); node = (INode)deserializer.Deserialize(stream, null); DesignerTree.FormDesigner.Dataphoria.Warnings.AppendErrors(DesignerTree.FormDesigner, deserializer.Errors, true); } RecursiveGetUniqueName(node); PlaceNewNode(node, position); DesignerTree.Modified(); } private void InternalMoveNode(INode node, INode newParent, int newIndex) { int oldIndex = node.Parent.Children.IndexOf(node); INode oldParent = node.Parent; oldParent.Children.DisownAt(oldIndex); try { newParent.Children.Insert(newIndex, node); } catch { oldParent.Children.Insert(oldIndex, node); // attempt recovery throw; } } private void MoveIntoSibling(DesignerNode source, int index) { int siblingIndex = Parent.Nodes.IndexOf(source); if ((siblingIndex >= 0) && (siblingIndex < index)) index--; InternalMoveNode(source.Node, Node.Parent, index); // Remove and recreate the node -- the tree draws the lines improperly if we just move the node, and ASource.Reposition raises a null reference exception source.Remove(); DesignerNode newNode = source.Copy(); Parent.InsertBaseNode(index, newNode); TreeView.SelectedNode = newNode; Parent.ExpandAll(); } public void MoveFromNode(DesignerNode source, DropLinePosition position) { switch (position) { case DropLinePosition.OnNode : int newIndex = Node.Children.Count; if (Node.Children.Contains(source.Node)) newIndex--; InternalMoveNode(source.Node, Node, newIndex); // Remove and recreate the designer node -- the tree draws the lines improperly if we just move the node, and ASource.Reposition raises a null reference exception source.Remove(); DesignerNode newNode = source.Copy(); AddBaseNode(newNode); TreeView.SelectedNode = newNode; if (Parent != null) Parent.ExpandAll(); break; case DropLinePosition.AboveNode : MoveIntoSibling(source, Node.Parent.Children.IndexOf(Node)); break; case DropLinePosition.BelowNode : MoveIntoSibling(source, Node.Parent.Children.IndexOf(Node) + 1); break; } DesignerTree.Modified(); } public void AddNew(PaletteItem item, DropLinePosition position) { INode node = (INode)DesignerTree.FormDesigner.FrontendSession.NodeTypeTable.CreateInstance(item.ClassName); try { Node.HostNode.GetUniqueName(node); PlaceNewNode(node, position).Rename(); } catch { node.Dispose(); throw; } DesignerTree.Modified(); } private object DeserializeFindReference(string stringValue) { return Node.HostNode.FindNode(stringValue); } /// <remarks> This method does not change the modified state of the editor. </remarks> public DesignerNode AddNode(INode node) { DesignerNode newNode = new DesignerNode(node, _designerTree); AddBaseNode(newNode); if (TreeView != null) // throws if node is not inserted ExpandAll(); return newNode; } /// <remarks> This method does not change the modified state of the editor. </remarks> public DesignerNode InsertNode(int index, INode node) { DesignerNode newNode = new DesignerNode(node, _designerTree); InsertBaseNode(index, newNode); if (TreeView != null) // throws if node is not inserted ExpandAll(); return newNode; } public void UpdateText(bool editText) { if (editText) Text = Node.Name; else { string name = _node.GetType().Name; if ((_node.Name == null) || (_node.Name == String.Empty)) Text = String.Format("[{0}]", name); else Text = String.Format("{0} [{1}]", _node.Name, name); } } public void Rename() { if (!ReadOnly) { TreeView.LabelEdit = true; UpdateText(true); BeginEdit(); } } /// <summary> Searches for AQueryNode optionally in ANode and always in ANode's children. </summary> public static bool IsNodeContained(INode node, INode queryNode, bool checkNode) { if (checkNode && Object.ReferenceEquals(node, queryNode)) return true; foreach (INode child in node.Children) if (IsNodeContained(child, queryNode, true)) return true; return false; } public void QueryAllowedPalettePositions(QueryAllowedPositionsEventArgs args) { args.AllowedCopyPositions = DropLinePosition.None; args.AllowedMovePositions = DropLinePosition.None; PaletteItem item = args.Source as PaletteItem; if (item != null) { INode target = ((DesignerNode)args.TargetNode).Node; Type type = DesignerTree.FormDesigner.FrontendSession.NodeTypeTable.GetClassType(item.ClassName); if (target.IsValidChild(type)) args.AllowedCopyPositions |= DropLinePosition.OnNode; if ((args.TargetNode.Parent != null) && target.Parent.IsValidChild(type)) args.AllowedCopyPositions |= (DropLinePosition.AboveNode | DropLinePosition.BelowNode); } } public void QueryAllowedDragPositions(QueryAllowedPositionsEventArgs args) { args.AllowedCopyPositions = DropLinePosition.None; args.AllowedMovePositions = DropLinePosition.None; DesignerNodeData sourceNodeData = args.Source as DesignerNodeData; if (sourceNodeData != null) { INode source = sourceNodeData.TreeNode.Node; INode target = ((DesignerNode)args.TargetNode).Node; if (target.IsValidChild(source)) { args.AllowedCopyPositions |= DropLinePosition.OnNode; if (!IsNodeContained(source, target, true)) args.AllowedMovePositions |= DropLinePosition.OnNode; } if ((args.TargetNode.Parent != null) && target.Parent.IsValidChild(source)) { args.AllowedCopyPositions |= (DropLinePosition.AboveNode | DropLinePosition.BelowNode); if (!IsNodeContained(source, target.Parent, true) && !Object.ReferenceEquals(target, source)) { int index = target.Parent.Children.IndexOf(target); if ( (index == 0) || ((index > 0) && !ReferenceEquals(target.Parent.Children[index - 1], source)) ) args.AllowedMovePositions |= DropLinePosition.AboveNode; if ( (index == target.Parent.Children.Count - 1) || ((index < target.Parent.Children.Count - 1) && !ReferenceEquals(target.Parent.Children[index + 1], source)) ) args.AllowedMovePositions |= DropLinePosition.BelowNode; } } } } #region ISite Members public IComponent Component { get { return Node; } } public IContainer Container { get { return DesignerTree.FormDesigner; } } public bool DesignMode { get { return true; } } #endregion #region IServiceProvider Members public object GetService(Type serviceType) { return DesignerTree.FormDesigner.GetService(serviceType); } #endregion } }
37.100897
183
0.528978
[ "BSD-3-Clause" ]
DBCG/Dataphor
Dataphor/Dataphoria/FormDesigner/DesignerTree/DesignerNode.cs
16,547
C#
// See the LICENSE file in the project root for more information. using System; using Microsoft.ML.Data; namespace Scikit.ML.ProductionPrediction { public class EmptyCursor : RowCursor { Func<int, bool> _needCol; IDataView _view; CursorState _state; public EmptyCursor(IDataView view, Func<int, bool> needCol) { _needCol = needCol; _view = view; _state = CursorState.NotStarted; } public override int Count() { return 0; } public override CursorState State { get { return _state; } } public override RowCursor GetRootCursor() { return this; } public override long Batch { get { return 0; } } public override long Position { get { return 0; } } public override Schema Schema { get { return _view.Schema; } } public override ValueGetter<RowId> GetIdGetter() { return (ref RowId uid) => { uid = new RowId(0, 1); }; } protected override void Dispose(bool disposing) { GC.SuppressFinalize(this); } public override bool MoveMany(long count) { _state = CursorState.Done; return false; } public override bool MoveNext() { _state = CursorState.Done; return false; } public override bool IsColumnActive(int col) { return _needCol(col); } /// <summary> /// The getter return the default value. A null getter usually fails the pipeline. /// </summary> public override ValueGetter<TValue> GetGetter<TValue>(int col) { return (ref TValue value) => { value = default(TValue); }; } } }
28.140625
114
0.564131
[ "MIT" ]
xadupre/machinelearningext
machinelearningext/ProductionPrediction/EmptyCursor.cs
1,803
C#
using System; using DataStructures; using DataStructures.Stack; using Xunit; namespace DataStructuresTests { public class BracketValidationTests { [Fact] public void CanValidateBalancedStringTest() { BracketValidation bracketValidation = new BracketValidation(); Assert.True(bracketValidation.MultiBracketValidation("(){}[[]]")); } [Fact] public void ReturnsFalseUnbalancedStringTest() { BracketValidation bracketValidation = new BracketValidation(); Assert.False(bracketValidation.MultiBracketValidation("[({}]")); } [Fact] public void ReturnsFalseIfOnlyOneBracketInStringTest() { BracketValidation bracketValidation = new BracketValidation(); Assert.False(bracketValidation.MultiBracketValidation("[")); } } }
25.685714
78
0.644049
[ "MIT" ]
selmaT273/DSA
DataStructuresTests/BracketValidationTests.cs
901
C#
// Mach1 SDK // Copyright © 2017 Mach1. All rights reserved. namespace Mach1 { public enum Mach1DecodeAlgoType : int { Mach1DecodeAlgoSpatial = 0, Mach1DecodeAlgoAltSpatial, Mach1DecodeAlgoHorizon, Mach1DecodeAlgoHorizonPairs, Mach1DecodeAlgoSpatialPairs }; }
25.818182
143
0.75
[ "Unlicense" ]
Mach1Studios/m1-sdk
include/c#/Mach1DecodeAlgoType.cs
287
C#
namespace CinemaAPI.Data.EF { using System; using System.Data.Entity.Migrations; public partial class TicketsTableAdded : DbMigration { public override void Up() { CreateTable( "dbo.Tickets", c => new { Id = c.Long(nullable: false, identity: true), ProjectionId = c.Long(nullable: false), UniqueNumberGuid = c.String(nullable: false), ProjectionStartDate = c.DateTime(nullable: false), MovieName = c.String(nullable: false), CinemaName = c.String(nullable: false), RoomNumber = c.Int(nullable: false), Row = c.Int(nullable: false), Column = c.Int(nullable: false), }) .PrimaryKey(t => t.Id); } public override void Down() { DropTable("dbo.Tickets"); } } }
31.735294
74
0.444856
[ "MIT" ]
bozhidar-slavov/14.ASP.NET-Web-API
CinemaAPI/CinemaAPI.Data.EF/Migrations/202001301058484_TicketsTableAdded.cs
1,079
C#
// *** WARNING: this file was generated by the Pulumi SDK Generator. *** // *** Do not edit by hand unless you're certain you know what you are doing! *** using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Threading.Tasks; using Pulumi.Serialization; namespace Pulumi.AzureNextGen.Network.V20200601.Outputs { [OutputType] public sealed class ConnectionMonitorOutputResponse { /// <summary> /// Connection monitor output destination type. Currently, only "Workspace" is supported. /// </summary> public readonly string? Type; /// <summary> /// Describes the settings for producing output into a log analytics workspace. /// </summary> public readonly Outputs.ConnectionMonitorWorkspaceSettingsResponse? WorkspaceSettings; [OutputConstructor] private ConnectionMonitorOutputResponse( string? type, Outputs.ConnectionMonitorWorkspaceSettingsResponse? workspaceSettings) { Type = type; WorkspaceSettings = workspaceSettings; } } }
31.611111
97
0.679262
[ "Apache-2.0" ]
pulumi/pulumi-azure-nextgen
sdk/dotnet/Network/V20200601/Outputs/ConnectionMonitorOutputResponse.cs
1,138
C#
namespace DomainServices.Logging { using System.Text.Json.Serialization; using System; using System.Collections.Generic; using System.Collections.ObjectModel; using Ardalis.GuardClauses; using Abstractions; /// <summary> /// An immutable structure representing a log entry /// </summary> public readonly struct LogEntry : IComparable<LogEntry>, IEntity<Guid> { private readonly IDictionary<string, object> _metadata; /// <summary> /// Initializes a new instance of the <see cref="LogEntry" /> struct. /// </summary> /// <param name="id">The unique identifier</param> /// <param name="logLevel">The log level.</param> /// <param name="text">The text message.</param> /// <param name="source">The source.</param> /// <param name="tag">A tag.</param> /// <param name="machineName">The machine name.</param> /// <param name="dateTime">The date time.</param> /// <param name="metadata">Metadata.</param> [JsonConstructor] public LogEntry(Guid id, LogLevel logLevel, string text, string source, string? tag = null, string? machineName = null, DateTime dateTime = default, IDictionary<string, object>? metadata = null) : this() { Guard.Against.NullOrEmpty(text, nameof(text)); Guard.Against.NullOrEmpty(source, nameof(source)); Id = id; LogLevel = logLevel; Text = text; Source = source; Tag = tag; DateTime = dateTime == default ? DateTime.Now : dateTime; MachineName = machineName ?? Environment.GetEnvironmentVariable("COMPUTERNAME"); _metadata = metadata ?? new Dictionary<string, object>(); } /// <summary> /// Initializes a new instance of the <see cref="LogEntry" /> struct. /// </summary> /// <param name="logLevel">The log level.</param> /// <param name="text">The text message.</param> /// <param name="source">The source.</param> /// <param name="tag">A tag.</param> /// <param name="machineName">The machine name.</param> /// <param name="dateTime">The date time.</param> public LogEntry(LogLevel logLevel, string text, string source, string? tag = null, string? machineName = null, DateTime dateTime = default) : this(Guid.NewGuid(), logLevel, text, source, tag, machineName, dateTime) { } /// <summary> /// Gets the unique identifier. /// </summary> /// <value>The identifier.</value> public Guid Id { get; } /// <summary> /// Gets the date time. /// </summary> /// <value>The date time.</value> public DateTime DateTime { get; } /// <summary> /// Gets the log level. /// </summary> /// <value>The log level.</value> public LogLevel LogLevel { get; } /// <summary> /// Gets the source. /// </summary> /// <value>The source.</value> public string Source { get; } /// <summary> /// Gets the tag. /// </summary> /// <value>The tag.</value> public string? Tag { get; } /// <summary> /// Gets the machine name. /// </summary> /// <value>The machine name.</value> public string? MachineName { get; } /// <summary> /// Gets the text. /// </summary> /// <value>The text.</value> public string Text { get; } /// <summary> /// Gets the metadata. /// </summary> /// <value>The metadata.</value> public IDictionary<string, object> Metadata => new ReadOnlyDictionary<string, object>(_metadata); /// <summary> /// Compares the current object with another object of the same type. /// </summary> /// <param name="other">An object to compare with this object.</param> /// <returns> /// A value that indicates the relative order of the objects being compared. /// </returns> public int CompareTo(LogEntry other) { return DateTime.CompareTo(other.DateTime); } } }
36.822034
202
0.550058
[ "MIT" ]
larsmichael/DomainServices
Source/DomainServices/Logging/LogEntry.cs
4,347
C#
using Model = StoreModels; using Entity = StoreDL.Entities; namespace StoreDL { public interface ICustomerOrderHistoryMapper { Model.CustomerOrderHistory ParseCustomerOrderHistory(Entity.CustomerOrderHistory customerOrderHistory); Entity.CustomerOrderHistory ParseCustomerOrderHistory(Model.CustomerOrderHistory customerOrderHistory); } }
36.6
111
0.811475
[ "MIT" ]
rjhakes/Richard_Hakes-P0
StoreApp/StoreDL/ICustomerOrderHistoryMapper.cs
366
C#
using System.Text; namespace Leak.Bencoding { public class BencodedText { private readonly BencodedData data; public BencodedText(string value) { this.data = new BencodedData(value); } public BencodedText(BencodedData data) { this.data = data; } public int Length { get { return data.Length; } } public string GetString() { return GetString(Encoding.ASCII); } public string GetString(Encoding encoding) { return encoding.GetString(data.GetBytes()); ; } public byte[] GetBytes() { return data.GetBytes(); } } }
19.307692
57
0.511288
[ "MIT" ]
amacal/leak
sources/Leak.Bencoding/BencodedText.cs
755
C#
namespace Deveroom.VisualStudio.ProjectSystem { public interface IDeveroomOutputPaneServices { void WriteLine(string text); void SendWriteLine(string text); void Activate(); } }
23.777778
48
0.682243
[ "MIT" ]
Philip-Gullick/deveroom-visualstudio
Deveroom.VisualStudio/ProjectSystem/IDeveroomOutputPaneServices.cs
216
C#
using System; using System.Globalization; using System.Reflection; using Jint.Native; using Jint.Native.Function; namespace Jint.Runtime.Interop { /* /// <summary> /// Represents a FunctionInstance wrapper around a CLR method. This is used by user to pass /// custom methods to the engine. /// </summary> public sealed class DelegateWrapper : FunctionInstance { private readonly Delegate _d; private readonly bool _delegateContainsParamsArgument; public DelegateWrapper(Engine engine, Delegate d) : base(engine, "delegate", null, null, false) { _d = d; Prototype = engine.Function.PrototypeObject; var parameterInfos = _d.Method.GetParameters(); _delegateContainsParamsArgument = false; foreach (var p in parameterInfos) { if (Attribute.IsDefined(p, typeof(ParamArrayAttribute))) { _delegateContainsParamsArgument = true; break; } } } public override JsValue Call(JsValue thisObject, JsValue[] jsArguments) { var parameterInfos = _d.Method.GetParameters(); int delegateArgumentsCount = parameterInfos.Length; int delegateNonParamsArgumentsCount = _delegateContainsParamsArgument ? delegateArgumentsCount - 1 : delegateArgumentsCount; int jsArgumentsCount = jsArguments.Length; int jsArgumentsWithoutParamsCount = Math.Min(jsArgumentsCount, delegateNonParamsArgumentsCount); var parameters = new object[delegateArgumentsCount]; // convert non params parameter to expected types for (var i = 0; i < jsArgumentsWithoutParamsCount; i++) { var parameterType = parameterInfos[i].ParameterType; if (parameterType == typeof (JsValue)) { parameters[i] = jsArguments[i]; } else { parameters[i] = Engine.ClrTypeConverter.Convert( jsArguments[i].ToObject(), parameterType, CultureInfo.InvariantCulture); } } // assign null to parameters not provided for (var i = jsArgumentsWithoutParamsCount; i < delegateNonParamsArgumentsCount; i++) { if (parameterInfos[i].ParameterType.IsValueType) { parameters[i] = Activator.CreateInstance(parameterInfos[i].ParameterType); } else { parameters[i] = null; } } // assign params to array and converts each objet to expected type if(_delegateContainsParamsArgument) { int paramsArgumentIndex = delegateArgumentsCount - 1; int paramsCount = Math.Max(0, jsArgumentsCount - delegateNonParamsArgumentsCount); object[] paramsParameter = new object[paramsCount]; var paramsParameterType = parameterInfos[paramsArgumentIndex].ParameterType.GetElementType(); for (var i = paramsArgumentIndex; i < jsArgumentsCount; i++) { var paramsIndex = i - paramsArgumentIndex; if (paramsParameterType == typeof(JsValue)) { paramsParameter[paramsIndex] = jsArguments[i]; } else { paramsParameter[paramsIndex] = Engine.ClrTypeConverter.Convert( jsArguments[i].ToObject(), paramsParameterType, CultureInfo.InvariantCulture); } } parameters[paramsArgumentIndex] = paramsParameter; } try { return JsValue.FromObject(Engine, _d.DynamicInvoke(parameters)); } catch (TargetInvocationException exception) { var meaningfulException = exception.InnerException ?? exception; var handler = Engine.Options._ClrExceptionsHandler; if (handler != null && handler(meaningfulException)) { ExceptionHelper.ThrowError(_engine, meaningfulException.Message); } throw meaningfulException; } } } */ }
36.692913
136
0.543562
[ "BSD-2-Clause" ]
rockyjvec/SpaceJS
Data/Scripts/SpaceJS/Jint/Runtime/Interop/DelegateWrapper.cs
4,660
C#
using System; namespace CHD.Client.Gui.Wcf { public sealed class DataChannelFactory : IDataChannelFactory { private readonly string _enpointAddress; private readonly IBindingProvider _bindingProvider; public DataChannelFactory( string enpointAddress, IBindingProvider bindingProvider ) { if (enpointAddress == null) { throw new ArgumentNullException("enpointAddress"); } if (bindingProvider == null) { throw new ArgumentNullException("bindingProvider"); } _enpointAddress = enpointAddress; _bindingProvider = bindingProvider; } public IDataChannel OpenChannel() { var result = new WcfDataChannel( _enpointAddress, _bindingProvider ); return result; } } }
26.921053
68
0.521017
[ "MIT" ]
lsoft/CHD
CHD.Client.Gui/Wcf/DataChannelFactory.cs
1,023
C#
// Licensed under the Apache License, Version 2.0. See LICENSE.txt in the project root for license information. using QuikSharp.DataStructures; using System; using System.Collections.Generic; using System.Threading.Tasks; namespace QuikSharp { /// <summary> /// Функции для обращения к спискам доступных параметров /// </summary> public interface IClassFunctions : IQuikService { /// <summary> /// Функция предназначена для получения списка кодов классов, переданных с сервера в ходе сеанса связи. /// </summary> /// <returns></returns> Task<string[]> GetClassesList(); /// <summary> /// Функция предназначена для получения информации о классе. /// </summary> /// <param name="classID"></param> Task<ClassInfo> GetClassInfo(string classID); /// <summary> /// Функция предназначена для получения информации по бумаге. /// </summary> Task<SecurityInfo> GetSecurityInfo(string classCode, string secCode); /// <summary> /// Функция предназначена для получения информации по бумаге. /// </summary> Task<SecurityInfo> GetSecurityInfo(ISecurity security); /// <summary> /// Функция предназначена для получения списка кодов бумаг для списка классов, заданного списком кодов. /// </summary> Task<string[]> GetClassSecurities(string classID); /// <summary> /// Функция предназначена для определения класса по коду инструмента из заданного списка классов. /// </summary> Task<string> GetSecurityClass(string classesList, string secCode); /// <summary> /// Функция возвращает код клиента. /// </summary> Task<string> GetClientCode(); /// <summary> /// Функция возвращает таблицу с описанием торгового счета для запрашиваемого кода класса. /// </summary> Task<string> GetTradeAccount(string classCode); /// <summary> /// Функция возвращает таблицу всех счетов в торговой системе. /// </summary> /// <returns></returns> Task<List<TradesAccounts>> GetTradeAccounts(); } /// <summary> /// Функции для обращения к спискам доступных параметров /// </summary> public class ClassFunctions : IClassFunctions { public ClassFunctions(int port) { QuikService = QuikService.Create(port); } public QuikService QuikService { get; private set; } public async Task<string[]> GetClassesList() { var response = await QuikService.Send<Message<string>>( (new Message<string>("", "getClassesList"))).ConfigureAwait(false); return response.Data == null ? new string[0] : response.Data.TrimEnd(',').Split(new[] { "," }, StringSplitOptions.None); } public async Task<ClassInfo> GetClassInfo(string classID) { var response = await QuikService.Send<Message<ClassInfo>>( (new Message<string>(classID, "getClassInfo"))).ConfigureAwait(false); return response.Data; } public async Task<SecurityInfo> GetSecurityInfo(string classCode, string secCode) { var response = await QuikService.Send<Message<SecurityInfo>>( (new Message<string>(classCode + "|" + secCode, "getSecurityInfo"))).ConfigureAwait(false); return response.Data; } public async Task<SecurityInfo> GetSecurityInfo(ISecurity security) { return await GetSecurityInfo(security.ClassCode, security.SecCode).ConfigureAwait(false); } public async Task<string[]> GetClassSecurities(string classID) { var response = await QuikService.Send<Message<string>>( (new Message<string>(classID, "getClassSecurities"))).ConfigureAwait(false); return response.Data == null ? new string[0] : response.Data.TrimEnd(',').Split(new[] { "," }, StringSplitOptions.None); } public async Task<string> GetSecurityClass(string classesList, string secCode) { var response = await QuikService.Send<Message<string>>( (new Message<string>(classesList + "|" + secCode, "getSecurityClass"))).ConfigureAwait(false); return response.Data; } public async Task<string> GetClientCode() { var response = await QuikService.Send<Message<string>>( (new Message<string>("", "getClientCode"))).ConfigureAwait(false); return response.Data; } public async Task<string> GetTradeAccount(string classCode) { var response = await QuikService.Send<Message<string>>( (new Message<string>(classCode, "getTradeAccount"))).ConfigureAwait(false); return response.Data; } public async Task<List<TradesAccounts>> GetTradeAccounts() { var response = await QuikService.Send<Message<List<TradesAccounts>>>( (new Message<string>("", "getTradeAccounts"))).ConfigureAwait(false); return response.Data; } } }
37.602837
112
0.610336
[ "Apache-2.0" ]
DevelopMan/QUIKSharp
src/QuikSharp/ClassFunctions/ClassFunctions.cs
5,947
C#
// ***************************************************************************** // // © Component Factory Pty Ltd 2017. All rights reserved. // The software and associated documentation supplied hereunder are the // proprietary information of Component Factory Pty Ltd, 13 Swallows Close, // Mornington, Vic 3931, Australia and are supplied subject to licence terms. // // Version 4.5.0.0 www.ComponentFactory.com // ***************************************************************************** using System; using System.Drawing; using System.Diagnostics; using System.ComponentModel; using ComponentFactory.Krypton.Toolkit; using ComponentFactory.Krypton.Navigator; using ComponentFactory.Krypton.Workspace; namespace ComponentFactory.Krypton.Docking { /// <summary> /// Event arguments for events that need a page and context menu. /// </summary> public class ContextPageEventArgs : CancelEventArgs { #region Instance Fields private KryptonPage _page; private KryptonContextMenu _contextMenu; #endregion #region Identity /// <summary> /// Initialize a new instance of the ContextPageEventArgs class. /// </summary> /// <param name="page">Page associated with the context menu.</param> /// <param name="contextMenu">Context menu that can be customized.</param> /// <param name="cancel">Initial value for the cancel property.</param> public ContextPageEventArgs(KryptonPage page, KryptonContextMenu contextMenu, bool cancel) : base(cancel) { _page = page; _contextMenu = contextMenu; } #endregion #region Public /// <summary> /// Gets access to page associated with the context menu. /// </summary> public KryptonPage Page { get { return _page; } } /// <summary> /// Gets access to context menu that can be customized. /// </summary> public KryptonContextMenu KryptonContextMenu { get { return _contextMenu; } } #endregion } }
32.402985
82
0.590511
[ "BSD-3-Clause" ]
ALMMa/Krypton
Source/Krypton Components/ComponentFactory.Krypton.Docking/Event Args/ContextPageEventArgs.cs
2,174
C#
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. // <auto-generated/> #nullable disable using System.Text.Json; using Azure.Core; namespace Azure.ResourceManager.Cdn.Models { public partial class ManagedRuleDefinition { internal static ManagedRuleDefinition DeserializeManagedRuleDefinition(JsonElement element) { Optional<string> ruleId = default; Optional<string> description = default; foreach (var property in element.EnumerateObject()) { if (property.NameEquals("ruleId")) { ruleId = property.Value.GetString(); continue; } if (property.NameEquals("description")) { description = property.Value.GetString(); continue; } } return new ManagedRuleDefinition(ruleId.Value, description.Value); } } }
28.75
99
0.568116
[ "MIT" ]
93mishra/azure-sdk-for-net
sdk/cdn/Azure.ResourceManager.Cdn/src/Generated/Models/ManagedRuleDefinition.Serialization.cs
1,035
C#
using System.Linq; using System.Threading.Tasks; using Discord.Commands; using NadekoBot.Services; using NadekoBot.Services.Database.Models; using Discord; using NadekoBot.Extensions; using Discord.WebSocket; using System; using NadekoBot.Common.Attributes; using NadekoBot.Modules.CustomReactions.Services; namespace NadekoBot.Modules.CustomReactions { public class CustomReactions : NadekoTopLevelModule<CustomReactionsService> { private readonly IBotCredentials _creds; private readonly DbService _db; private readonly DiscordSocketClient _client; public CustomReactions(IBotCredentials creds, DbService db, DiscordSocketClient client) { _creds = creds; _db = db; _client = client; } [NadekoCommand, Usage, Description, Aliases] public async Task AddCustReact(string key, [Remainder] string message) { var channel = Context.Channel as ITextChannel; if (string.IsNullOrWhiteSpace(message) || string.IsNullOrWhiteSpace(key)) return; key = key.ToLowerInvariant(); if ((channel == null && !_creds.IsOwner(Context.User)) || (channel != null && !((IGuildUser)Context.User).GuildPermissions.Administrator)) { await ReplyErrorLocalized("insuff_perms").ConfigureAwait(false); return; } var cr = new CustomReaction() { GuildId = channel?.Guild.Id, IsRegex = false, Trigger = key, Response = message, }; using (var uow = _db.UnitOfWork) { uow.CustomReactions.Add(cr); await uow.CompleteAsync().ConfigureAwait(false); } if (channel == null) { await _service.AddGcr(cr).ConfigureAwait(false); } else { _service.GuildReactions.AddOrUpdate(Context.Guild.Id, new CustomReaction[] { cr }, (k, old) => { Array.Resize(ref old, old.Length + 1); old[old.Length - 1] = cr; return old; }); } await Context.Channel.EmbedAsync(new EmbedBuilder().WithOkColor() .WithTitle(GetText("new_cust_react")) .WithDescription($"#{cr.Id}") .AddField(efb => efb.WithName(GetText("trigger")).WithValue(key)) .AddField(efb => efb.WithName(GetText("response")).WithValue(message.Length > 1024 ? GetText("redacted_too_long") : message)) ).ConfigureAwait(false); } [NadekoCommand, Usage, Description, Aliases] public async Task EditCustReact(int id, [Remainder] string message) { var channel = Context.Channel as ITextChannel; if (string.IsNullOrWhiteSpace(message) || id < 0) return; if ((channel == null && !_creds.IsOwner(Context.User)) || (channel != null && !((IGuildUser)Context.User).GuildPermissions.Administrator)) { await ReplyErrorLocalized("insuff_perms").ConfigureAwait(false); return; } CustomReaction cr; using (var uow = _db.UnitOfWork) { cr = uow.CustomReactions.Get(id); if (cr != null) { cr.Response = message; await uow.CompleteAsync().ConfigureAwait(false); } } if (cr != null) { if (channel == null) { await _service.EditGcr(id, message).ConfigureAwait(false); } else { if (_service.GuildReactions.TryGetValue(Context.Guild.Id, out var crs)) { var oldCr = crs.FirstOrDefault(x => x.Id == id); if (oldCr != null) oldCr.Response = message; } } await Context.Channel.EmbedAsync(new EmbedBuilder().WithOkColor() .WithTitle(GetText("edited_cust_react")) .WithDescription($"#{cr.Id}") .AddField(efb => efb.WithName(GetText("trigger")).WithValue(cr.Trigger)) .AddField(efb => efb.WithName(GetText("response")).WithValue(message.Length > 1024 ? GetText("redacted_too_long") : message)) ).ConfigureAwait(false); } else { await ReplyErrorLocalized("edit_fail").ConfigureAwait(false); } } [NadekoCommand, Usage, Description, Aliases] [Priority(1)] public async Task ListCustReact(int page = 1) { if (--page < 0 || page > 999) return; CustomReaction[] customReactions; if (Context.Guild == null) customReactions = _service.GlobalReactions.Where(cr => cr != null).ToArray(); else customReactions = _service.GuildReactions.GetOrAdd(Context.Guild.Id, Array.Empty<CustomReaction>()).Where(cr => cr != null).ToArray(); if (customReactions == null || !customReactions.Any()) { await ReplyErrorLocalized("no_found").ConfigureAwait(false); return; } var lastPage = customReactions.Length / 20; await Context.Channel.SendPaginatedConfirmAsync(_client, page, curPage => new EmbedBuilder().WithOkColor() .WithTitle(GetText("name")) .WithDescription(string.Join("\n", customReactions.OrderBy(cr => cr.Trigger) .Skip(curPage * 20) .Take(20) .Select(cr => { var str = $"`#{cr.Id}` {cr.Trigger}"; if (cr.AutoDeleteTrigger) { str = "🗑" + str; } if (cr.DmResponse) { str = "📪" + str; } return str; }))), lastPage) .ConfigureAwait(false); } public enum All { All } [NadekoCommand, Usage, Description, Aliases] [Priority(0)] public async Task ListCustReact(All x) { CustomReaction[] customReactions; if (Context.Guild == null) customReactions = _service.GlobalReactions.Where(cr => cr != null).ToArray(); else customReactions = _service.GuildReactions.GetOrAdd(Context.Guild.Id, new CustomReaction[]{ }).Where(cr => cr != null).ToArray(); if (customReactions == null || !customReactions.Any()) { await ReplyErrorLocalized("no_found").ConfigureAwait(false); return; } var txtStream = await customReactions.GroupBy(cr => cr.Trigger) .OrderBy(cr => cr.Key) .Select(cr => new { Trigger = cr.Key, Responses = cr.Select(y => new { id = y.Id, text = y.Response }).ToList() }) .ToJson() .ToStream() .ConfigureAwait(false); if (Context.Guild == null) // its a private one, just send back await Context.Channel.SendFileAsync(txtStream, "customreactions.txt", GetText("list_all")).ConfigureAwait(false); else await ((IGuildUser)Context.User).SendFileAsync(txtStream, "customreactions.txt", GetText("list_all"), false).ConfigureAwait(false); } [NadekoCommand, Usage, Description, Aliases] public async Task ListCustReactG(int page = 1) { if (--page < 0 || page > 9999) return; CustomReaction[] customReactions; if (Context.Guild == null) customReactions = _service.GlobalReactions.Where(cr => cr != null).ToArray(); else customReactions = _service.GuildReactions.GetOrAdd(Context.Guild.Id, new CustomReaction[]{ }).Where(cr => cr != null).ToArray(); if (customReactions == null || !customReactions.Any()) { await ReplyErrorLocalized("no_found").ConfigureAwait(false); } else { var ordered = customReactions .GroupBy(cr => cr.Trigger) .OrderBy(cr => cr.Key) .ToList(); var lastPage = ordered.Count / 20; await Context.Channel.SendPaginatedConfirmAsync(_client, page, (curPage) => new EmbedBuilder().WithOkColor() .WithTitle(GetText("name")) .WithDescription(string.Join("\r\n", ordered .Skip(curPage * 20) .Take(20) .Select(cr => $"**{cr.Key.Trim().ToLowerInvariant()}** `x{cr.Count()}`"))), lastPage) .ConfigureAwait(false); } } [NadekoCommand, Usage, Description, Aliases] public async Task ShowCustReact(int id) { CustomReaction[] customReactions; if (Context.Guild == null) customReactions = _service.GlobalReactions; else customReactions = _service.GuildReactions.GetOrAdd(Context.Guild.Id, new CustomReaction[]{ }); var found = customReactions.FirstOrDefault(cr => cr?.Id == id); if (found == null) { await ReplyErrorLocalized("no_found_id").ConfigureAwait(false); return; } else { await Context.Channel.EmbedAsync(new EmbedBuilder().WithOkColor() .WithDescription($"#{id}") .AddField(efb => efb.WithName(GetText("trigger")).WithValue(found.Trigger)) .AddField(efb => efb.WithName(GetText("response")).WithValue(found.Response + "\n```css\n" + found.Response + "```")) ).ConfigureAwait(false); } } [NadekoCommand, Usage, Description, Aliases] public async Task DelCustReact(int id) { if ((Context.Guild == null && !_creds.IsOwner(Context.User)) || (Context.Guild != null && !((IGuildUser)Context.User).GuildPermissions.Administrator)) { await ReplyErrorLocalized("insuff_perms").ConfigureAwait(false); return; } var success = false; CustomReaction toDelete; using (var uow = _db.UnitOfWork) { toDelete = uow.CustomReactions.Get(id); if (toDelete == null) //not found success = false; else { if ((toDelete.GuildId == null || toDelete.GuildId == 0) && Context.Guild == null) { uow.CustomReactions.Remove(toDelete); await _service.DelGcr(toDelete.Id); success = true; } else if ((toDelete.GuildId != null && toDelete.GuildId != 0) && Context.Guild.Id == toDelete.GuildId) { uow.CustomReactions.Remove(toDelete); _service.GuildReactions.AddOrUpdate(Context.Guild.Id, new CustomReaction[] { }, (key, old) => { return old.Where(cr => cr?.Id != toDelete.Id).ToArray(); }); success = true; } if (success) await uow.CompleteAsync().ConfigureAwait(false); } } if (success) { await Context.Channel.EmbedAsync(new EmbedBuilder().WithOkColor() .WithTitle(GetText("deleted")) .WithDescription("#" + toDelete.Id) .AddField(efb => efb.WithName(GetText("trigger")).WithValue(toDelete.Trigger)) .AddField(efb => efb.WithName(GetText("response")).WithValue(toDelete.Response))); } else { await ReplyErrorLocalized("no_found_id").ConfigureAwait(false); } } [NadekoCommand, Usage, Description, Aliases] public async Task CrCa(int id) { if ((Context.Guild == null && !_creds.IsOwner(Context.User)) || (Context.Guild != null && !((IGuildUser)Context.User).GuildPermissions.Administrator)) { await ReplyErrorLocalized("insuff_perms").ConfigureAwait(false); return; } CustomReaction[] reactions = new CustomReaction[0]; if (Context.Guild == null) reactions = _service.GlobalReactions; else { _service.GuildReactions.TryGetValue(Context.Guild.Id, out reactions); } if (reactions.Any()) { var reaction = reactions.FirstOrDefault(x => x.Id == id); if (reaction == null) { await ReplyErrorLocalized("no_found_id").ConfigureAwait(false); return; } var setValue = reaction.ContainsAnywhere = !reaction.ContainsAnywhere; await _service.SetCrCaAsync(reaction.Id, setValue).ConfigureAwait(false); if (setValue) { await ReplyConfirmLocalized("crca_enabled", Format.Code(reaction.Id.ToString())).ConfigureAwait(false); } else { await ReplyConfirmLocalized("crca_disabled", Format.Code(reaction.Id.ToString())).ConfigureAwait(false); } } else { await ReplyErrorLocalized("no_found").ConfigureAwait(false); } } [NadekoCommand, Usage, Description, Aliases] public async Task CrDm(int id) { if ((Context.Guild == null && !_creds.IsOwner(Context.User)) || (Context.Guild != null && !((IGuildUser)Context.User).GuildPermissions.Administrator)) { await ReplyErrorLocalized("insuff_perms").ConfigureAwait(false); return; } CustomReaction[] reactions = new CustomReaction[0]; if (Context.Guild == null) reactions = _service.GlobalReactions; else { _service.GuildReactions.TryGetValue(Context.Guild.Id, out reactions); } if (reactions.Any()) { var reaction = reactions.FirstOrDefault(x => x.Id == id); if (reaction == null) { await ReplyErrorLocalized("no_found_id").ConfigureAwait(false); return; } var setValue = reaction.DmResponse = !reaction.DmResponse; await _service.SetCrDmAsync(reaction.Id, setValue).ConfigureAwait(false); if (setValue) { await ReplyConfirmLocalized("crdm_enabled", Format.Code(reaction.Id.ToString())).ConfigureAwait(false); } else { await ReplyConfirmLocalized("crdm_disabled", Format.Code(reaction.Id.ToString())).ConfigureAwait(false); } } else { await ReplyErrorLocalized("no_found").ConfigureAwait(false); } } [NadekoCommand, Usage, Description, Aliases] public async Task CrAd(int id) { if ((Context.Guild == null && !_creds.IsOwner(Context.User)) || (Context.Guild != null && !((IGuildUser)Context.User).GuildPermissions.Administrator)) { await ReplyErrorLocalized("insuff_perms").ConfigureAwait(false); return; } CustomReaction[] reactions = new CustomReaction[0]; if (Context.Guild == null) reactions = _service.GlobalReactions; else { _service.GuildReactions.TryGetValue(Context.Guild.Id, out reactions); } if (reactions.Any()) { var reaction = reactions.FirstOrDefault(x => x.Id == id); if (reaction == null) { await ReplyErrorLocalized("no_found_id").ConfigureAwait(false); return; } var setValue = reaction.AutoDeleteTrigger = !reaction.AutoDeleteTrigger; await _service.SetCrAdAsync(reaction.Id, setValue).ConfigureAwait(false); if (setValue) { await ReplyConfirmLocalized("crad_enabled", Format.Code(reaction.Id.ToString())).ConfigureAwait(false); } else { await ReplyConfirmLocalized("crad_disabled", Format.Code(reaction.Id.ToString())).ConfigureAwait(false); } } else { await ReplyErrorLocalized("no_found").ConfigureAwait(false); } } [NadekoCommand, Usage, Description, Aliases] [OwnerOnly] public async Task CrStatsClear(string trigger = null) { if (string.IsNullOrWhiteSpace(trigger)) { _service.ClearStats(); await ReplyConfirmLocalized("all_stats_cleared").ConfigureAwait(false); } else { if (_service.ReactionStats.TryRemove(trigger, out _)) { await ReplyErrorLocalized("stats_cleared", Format.Bold(trigger)).ConfigureAwait(false); } else { await ReplyErrorLocalized("stats_not_found").ConfigureAwait(false); } } } [NadekoCommand, Usage, Description, Aliases] public async Task CrStats(int page = 1) { if (--page < 0) return; var ordered = _service.ReactionStats.OrderByDescending(x => x.Value).ToArray(); if (!ordered.Any()) return; var lastPage = ordered.Length / 9; await Context.Channel.SendPaginatedConfirmAsync(_client, page, (curPage) => ordered.Skip(curPage * 9) .Take(9) .Aggregate(new EmbedBuilder().WithOkColor().WithTitle(GetText("stats")), (agg, cur) => agg.AddField(efb => efb.WithName(cur.Key).WithValue(cur.Value.ToString()).WithIsInline(true))), lastPage) .ConfigureAwait(false); } } }
40.59127
170
0.481816
[ "MIT" ]
2UNIEK/tunes-of-turmoil-radio-bot
src/NadekoBot/Modules/CustomReactions/CustomReactions.cs
20,466
C#
using System; using System.Messaging; using System.Text; using System.Threading; using Rhino.ServiceBus.Impl; using Xunit; namespace Rhino.ServiceBus.Tests { public class FailureToProcessMessage : MsmqTestBase { readonly ManualResetEvent gotFirstMessage = new ManualResetEvent(false); readonly ManualResetEvent gotSecondMessage = new ManualResetEvent(false); bool first = true; [Fact] public void A_message_that_fails_processing_should_go_back_to_queue_on_non_transactional_queue() { Transport.MessageArrived += ThrowOnFirstAction(); Transport.Send(TestQueueUri, DateTime.Today); gotFirstMessage.WaitOne(); gotSecondMessage.Set(); } [Fact] public void A_message_that_fails_processing_should_go_back_to_queue_on_transactional_queue() { TransactionalTransport.MessageArrived += ThrowOnFirstAction(); TransactionalTransport.Send(TransactionalTestQueueUri, DateTime.Today); gotFirstMessage.WaitOne(); Assert.NotNull(transactionalQueue.Peek()); gotSecondMessage.Set(); } [Fact] public void When_a_message_fails_enough_times_it_is_moved_to_error_queue_using_non_transactional_queue() { int count = 0; Transport.MessageArrived += o => { Interlocked.Increment(ref count); throw new InvalidOperationException(); }; Transport.Send(TestQueueUri, DateTime.Today); using (var errorQueue = new MessageQueue(testQueuePath + ";errors")) { Assert.NotNull(errorQueue.Peek()); Assert.Equal(5, count); } } [Fact] public void When_a_failed_message_arrives_to_error_queue_will_have_another_message_explaining_what_happened() { int count = 0; Transport.MessageArrived += o => { Interlocked.Increment(ref count); throw new InvalidOperationException(); }; Transport.Send(TestQueueUri, DateTime.Today); using (var errorQueue = new MessageQueue(testQueuePath + ";errors")) { errorQueue.Formatter = new XmlMessageFormatter(new[] { typeof(string) }); errorQueue.MessageReadPropertyFilter.SetAll(); errorQueue.Peek();//for debugging var messageCausingError = errorQueue.Receive(); Assert.NotNull(messageCausingError); errorQueue.Peek();//for debugging var messageErrorDescription = errorQueue.Receive(); var error = (string)messageErrorDescription.Body; Assert.Contains( "System.InvalidOperationException: Operation is not valid due to the current state of the object.", error); Assert.Equal( CorrelationId.Parse(messageErrorDescription.Id).Id, CorrelationId.Parse(messageErrorDescription.CorrelationId).Id); } } [Fact] public void When_a_message_fails_enough_times_it_is_moved_to_error_queue_using_transactional_queue() { int count = 0; TransactionalTransport.MessageArrived += o => { Interlocked.Increment(ref count); throw new InvalidOperationException(); }; TransactionalTransport.Send(TransactionalTestQueueUri, DateTime.Today); using (var errorQueue = new MessageQueue(transactionalTestQueuePath + ";errors")) { Assert.NotNull(errorQueue.Peek()); Assert.Equal(5, count); } } private Action<CurrentMessageInformation> ThrowOnFirstAction() { return o => { if (first) { first = false; try { throw new InvalidOperationException(); } finally { gotFirstMessage.Set(); } } gotSecondMessage.WaitOne(); }; } } public class With_flat_queue_strategy : MsmqFlatQueueTestBase { public class FailureToProcessMessage : With_flat_queue_strategy { readonly ManualResetEvent gotFirstMessage = new ManualResetEvent(false); readonly ManualResetEvent gotSecondMessage = new ManualResetEvent(false); bool first = true; [Fact] public void A_message_that_fails_processing_should_go_back_to_queue_on_non_transactional_queue() { Transport.MessageArrived += ThrowOnFirstAction(); Transport.Send(TestQueueUri, DateTime.Today); gotFirstMessage.WaitOne(); gotSecondMessage.Set(); } [Fact] public void A_message_that_fails_processing_should_go_back_to_queue_on_transactional_queue() { TransactionalTransport.MessageArrived += ThrowOnFirstAction(); TransactionalTransport.Send(TransactionalTestQueueUri, DateTime.Today); gotFirstMessage.WaitOne(); Assert.NotNull(transactionalQueue.Peek()); gotSecondMessage.Set(); } [Fact] public void When_a_message_fails_enough_times_it_is_moved_to_error_queue_using_non_transactional_queue() { int count = 0; Transport.MessageArrived += o => { Interlocked.Increment(ref count); throw new InvalidOperationException(); }; Transport.Send(TestQueueUri, DateTime.Today); using (var errorQueue = new MessageQueue(testQueuePath + "#errors")) { Assert.NotNull(errorQueue.Peek()); Assert.Equal(5, count); } } [Fact] public void When_a_failed_message_arrives_to_error_queue_will_have_another_message_explaining_what_happened() { int count = 0; Transport.MessageArrived += o => { Interlocked.Increment(ref count); throw new InvalidOperationException(); }; Transport.Send(TestQueueUri, DateTime.Today); using (var errorQueue = new MessageQueue(testQueuePath + "#errors")) { errorQueue.Formatter = new XmlMessageFormatter(new[] { typeof(string) }); errorQueue.MessageReadPropertyFilter.SetAll(); errorQueue.Peek();//for debugging var messageCausingError = errorQueue.Receive(); Assert.NotNull(messageCausingError); errorQueue.Peek();//for debugging var messageErrorDescription = errorQueue.Receive(); var error = (string)messageErrorDescription.Body; Assert.Contains( "System.InvalidOperationException: Operation is not valid due to the current state of the object.", error); Assert.Equal( CorrelationId.Parse(messageErrorDescription.Id).Id, CorrelationId.Parse(messageErrorDescription.CorrelationId).Id); } } [Fact] public void When_a_message_fails_enough_times_it_is_moved_to_error_queue_using_transactional_queue() { int count = 0; TransactionalTransport.MessageArrived += o => { Interlocked.Increment(ref count); throw new InvalidOperationException(); }; TransactionalTransport.Send(TransactionalTestQueueUri, DateTime.Today); using (var errorQueue = new MessageQueue(transactionalTestQueuePath + "#errors")) { Assert.NotNull(errorQueue.Peek()); Assert.Equal(5, count); } } private Action<CurrentMessageInformation> ThrowOnFirstAction() { return o => { if (first) { first = false; try { throw new InvalidOperationException(); } finally { gotFirstMessage.Set(); } } gotSecondMessage.WaitOne(); }; } } } }
35.637736
124
0.523401
[ "BSD-3-Clause" ]
brumschlag/rhino-tools
rhino-service.bus/Rhino.ServiceBus.Tests/FailureToProcessMessage.cs
9,444
C#
using System; public static class EnumExtensions { public static Enum InvertFlag(this Enum e, Enum flag) { var eval = Convert.ToInt32(e); var flagval = Convert.ToInt32(flag); if (e.HasFlag(flag)) { return (Enum)Enum.ToObject(e.GetType(), eval - flagval); } else { return (Enum)Enum.ToObject(e.GetType(), eval + flagval); } } }
21.45
68
0.547786
[ "MIT" ]
Haapavuo/UnityExtensions
Net/EnumExtensions.cs
429
C#
using System.Diagnostics; using AutoLot.Dal.Repos.Interfaces; using AutoLot.Models.ViewModels; using AutoLot.Mvc.Extensions; using AutoLot.Mvc.Models; using Microsoft.AspNetCore.Http.Features; using Microsoft.AspNetCore.Mvc; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Options; namespace AutoLot.Mvc.Controllers { [Route("[controller]/[action]")] //[Route("Home/[action]")] public class HomeController : Controller { private readonly ILogger<HomeController> _logger; public HomeController(ILogger<HomeController> logger) { _logger = logger; } [HttpGet] [ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)] public IActionResult Error() { return View(new ErrorViewModel { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier }); } [Route("/")] [Route("/[controller]")] [Route("/[controller]/[action]")] [HttpGet] public IActionResult Index([FromServices] IOptionsMonitor<DealerInfo> dealerMonitor) { var vm = dealerMonitor.CurrentValue; return View(vm); } [HttpGet] public IActionResult Privacy() { return View(); } [HttpGet] public IActionResult RazorSyntax([FromServices] ICarRepo carRepo) { var car = carRepo.Find(1); return View(car); } [HttpGet] public IActionResult GrantConsent() { HttpContext.Features.Get<ITrackingConsentFeature>().GrantConsent(); return RedirectToAction(nameof(Index), nameof(HomeController).RemoveController(), new {area = ""}); } [HttpGet] public IActionResult WithdrawConsent() { HttpContext.Features.Get<ITrackingConsentFeature>().WithdrawConsent(); return RedirectToAction(nameof(Index), nameof(HomeController).RemoveController(), new {area = ""}); } } }
29.521127
112
0.611164
[ "BSD-3-Clause", "MIT" ]
RomitMehta/presentations
DOTNETCORE/ASP.NETCore/v3.1/AutoLot/AutoLot.Mvc/Controllers/HomeController.cs
2,098
C#
using System; namespace NullableValueTypes { class Program { static void Main(string[] args) { bool? flag = true; PrintNullableTypeDetails(flag, true); int? number = null; PrintNullableTypeDetails(number, -10); int? number2 = 10; if (number < number2) { Console.WriteLine($"{number} is less than {number2}"); } else if (number > number2) { Console.WriteLine($"{number} is greater than {number2}"); } else if (number == number2) { Console.WriteLine($"{number} is equal to {number2}"); } else { Console.WriteLine($"Something else!"); } } private static void PrintNullableTypeDetails<T>(T? value, T defaultValue) where T: struct { Console.WriteLine("*******************************************"); Console.WriteLine($"value={value}"); Console.WriteLine($"value.HasValue={value.HasValue}"); bool isNull = value is null; if (!isNull) { Console.WriteLine($"value.Value={value.Value}"); } Console.WriteLine($"value.GetValueOrDefault()={value.GetValueOrDefault()}"); Console.WriteLine($"value.GetValueOrDefault(defaultValue)={value.GetValueOrDefault(defaultValue)}"); Console.WriteLine("*******************************************"); Console.WriteLine(); } } }
29.963636
112
0.472087
[ "MIT" ]
FastTrackIT-WON-3/nullable-value-types
NullableValueTypes/NullableValueTypes/Program.cs
1,650
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.Dcdb.V20180411.Models { using Newtonsoft.Json; using System.Collections.Generic; using TencentCloud.Common; public class DescribeDCDBRenewalPriceResponse : AbstractModel { /// <summary> /// 原价,单位:分 /// </summary> [JsonProperty("OriginalPrice")] public long? OriginalPrice{ get; set; } /// <summary> /// 实际价格,单位:分。受折扣等影响,可能和原价不同。 /// </summary> [JsonProperty("Price")] public long? Price{ get; set; } /// <summary> /// 唯一请求ID,每次请求都会返回。定位问题时需要提供该次请求的RequestId。 /// </summary> [JsonProperty("RequestId")] public string RequestId{ get; set; } /// <summary> /// 内部实现,用户禁止调用 /// </summary> internal override void ToMap(Dictionary<string, string> map, string prefix) { this.SetParamSimple(map, prefix + "OriginalPrice", this.OriginalPrice); this.SetParamSimple(map, prefix + "Price", this.Price); this.SetParamSimple(map, prefix + "RequestId", this.RequestId); } } }
30.603448
83
0.630423
[ "Apache-2.0" ]
geffzhang/tencentcloud-sdk-dotnet
TencentCloud/Dcdb/V20180411/Models/DescribeDCDBRenewalPriceResponse.cs
1,919
C#
using System.Collections.Generic; using System.IO; namespace NetWebScript.JsClr.JsBuilder.JsSyntax { public class JsTokenWriter : StringWriter { internal void WriteTarget(JsToken token) { WriteLeft(JsPrecedence.Member, token); } internal void WriteCommaSeparated(JsToken token) { WriteLeft(JsPrecedence.Comma, token); } // Left-associativity (left-to-right) means that it is processed as (a OP b) OP c, // Right-associativity (right-to-left) means it is interpreted as a OP (b OP c). public void WriteRight(JsPrecedence precedence, JsToken token) { int diff = (int)(precedence & JsPrecedence.PrecedenceMask) - (int)(token.Precedence & JsPrecedence.PrecedenceMask); if (diff < 0 || (diff == 0 && (precedence & JsPrecedence.AssocMask) != JsPrecedence.RightToLeft) ) { Write('('); Write(token.Text); Write(')'); } else { Write(token.Text); } } public void WriteLeft(JsPrecedence precedence, JsToken token) { int diff = (int)(precedence & JsPrecedence.PrecedenceMask) - (int)(token.Precedence & JsPrecedence.PrecedenceMask); if (diff < 0 || (diff == 0 && (precedence & JsPrecedence.AssocMask) != JsPrecedence.LeftToRight)) { Write('('); Write(token.Text); Write(')'); } else { Write(token.Text); } } public void Write ( JsPrecedence precedence, JsToken token ) { if ((precedence & JsPrecedence.PrecedenceMask) <= (token.Precedence & JsPrecedence.PrecedenceMask)) { Write('('); Write(token.Text); Write(')'); } else { Write(token.Text); } } private Stack<bool> argsStack; public void WriteOpenArgs() { if ( argsStack == null ) { argsStack = new Stack<bool>(); } argsStack.Push(true); Write('('); } public void WriteArg(JsToken token) { if (argsStack.Peek()) { argsStack.Pop(); argsStack.Push(false); } else { Write(','); } Write(JsPrecedence.Comma,token); } public void WriteCloseArgs() { argsStack.Pop(); Write(')'); } public void WriteArgs(IEnumerable<JsToken> args) { WriteOpenArgs(); foreach (JsToken arg in args) { WriteArg(arg); } WriteCloseArgs(); } public JsToken ToToken(JsPrecedence precedence) { return new JsToken(precedence, ToString()); } public JsToken ToStatement() { return new JsToken(JsPrecedence.Statement, ToString()); } public JsToken ToFullStatement() { return new JsToken(JsPrecedence.FullStatement, ToString()); } internal void WriteInBlock(bool pretty, IEnumerable<JsToken> statements) { WriteLine('{'); WriteIndented(pretty, statements); Write('}'); } internal void WriteIndented(bool pretty, IEnumerable<JsToken> statements) { foreach (JsToken token in statements) { if (token != null) { if ( pretty ) Write('\t'); if (token.Precedence == JsPrecedence.FullStatement) { if (pretty) { WriteLine(token.Text.Replace("\n", "\n\t")); } else { WriteLine(token.Text); } } else { Write(token.Text); WriteLine(';'); } } } } internal void WriteLiteralString(string value) { Write('"'); Write(value.Replace("\\", "\\\\").Replace("\n", "\\n").Replace("\r", "\\r").Replace("\"", "\\\"").Replace("'", "\\'")); Write('"'); } } }
29.628049
132
0.429101
[ "MIT" ]
jetelain/NetWebScript
NetWebScript/NetWebScript/JsClr/JsBuilder/JsSyntax/JsTokenWriter.cs
4,861
C#
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; using Logica; namespace Presentacion { public partial class Menu : Form { private Form formularioactivo = null; public Menu() { InitializeComponent(); lblnombre.Text = Usuario.apellido + ", " + Usuario.nombre; lbltipo.Text += Usuario.username; panelventas.Visible = false; panelcompras.Visible = false; panelconfiguracion.Visible = false; } private void Menu_FormClosed(object sender, FormClosedEventArgs e) { Application.Exit(); } private void btnventas_Click(object sender, EventArgs e) { bool visible = !panelventas.Visible; panelcompras.Visible = false; panelventas.Visible = visible; } private void btncompras_Click(object sender, EventArgs e) { panelventas.Visible = false; panelcompras.Visible = !panelcompras.Visible; } private void btnprocesarventas_Click(object sender, EventArgs e) { PProcesarVentas procesarVentas = new PProcesarVentas(); AbrirFormulario(procesarVentas); } private void btnestadisticasventas_Click(object sender, EventArgs e) { } private void btnguardarcompras_Click(object sender, EventArgs e) { } private void btnestadisticascompras_Click(object sender, EventArgs e) { } private void btninventario_Click(object sender, EventArgs e) { } private void btnsalir_Click(object sender, EventArgs e) { PInicio pInicio = new PInicio(); pInicio.Show(); this.Hide(); } private void btnconfiguracion_Click(object sender, EventArgs e) { } private void btncrearusuario_Click(object sender, EventArgs e) { } private void btnactualizarusuario_Click(object sender, EventArgs e) { } private void AbrirFormulario(Form form) { if (formularioactivo != null) formularioactivo.Close(); formularioactivo = form; form.TopLevel = false; form.FormBorderStyle = FormBorderStyle.None; form.Dock = DockStyle.Fill; panelcontenedor.Controls.Add(form); panelcontenedor.Tag = form; form.BringToFront(); form.Show(); } } }
25.361111
77
0.589631
[ "Apache-2.0" ]
andres15alvarez/McKaos
Presentacion/Menu.cs
2,741
C#
using System; using System.Diagnostics.CodeAnalysis; using HotChocolate.Resolvers; using static HotChocolate.Utilities.ThrowHelper; #nullable enable namespace HotChocolate { public static class ResolverContextExtensions { [return: MaybeNull] public static T GetGlobalValue<T>( this IResolverContext context, string name) { if (context is null) { throw new ArgumentNullException(nameof(context)); } if (string.IsNullOrEmpty(name)) { throw String_NullOrEmpty(nameof(name)); } if (context.ContextData.TryGetValue(name, out var value) && value is T casted) { return casted; } return default; } [return: MaybeNull] public static T GetScopedValue<T>( this IResolverContext context, string name) { if (context is null) { throw new ArgumentNullException(nameof(context)); } if (string.IsNullOrEmpty(name)) { throw String_NullOrEmpty(nameof(name)); } if (context.ScopedContextData.TryGetValue(name, out var value) && value is T casted) { return casted; } return default; } [return: MaybeNull] public static T GetLocalValue<T>( this IResolverContext context, string name) { if (context is null) { throw new ArgumentNullException(nameof(context)); } if (string.IsNullOrEmpty(name)) { throw String_NullOrEmpty(nameof(name)); } if (context.LocalContextData.TryGetValue(name, out var value) && value is T casted) { return casted; } return default; } public static void SetGlobalValue<T>( this IResolverContext context, string name, [MaybeNull] T value) { if (context is null) { throw new ArgumentNullException(nameof(context)); } if (string.IsNullOrEmpty(name)) { throw String_NullOrEmpty(nameof(name)); } context.ContextData[name] = value; } public static void SetScopedValue<T>( this IResolverContext context, string name, [MaybeNull] T value) { if (context is null) { throw new ArgumentNullException(nameof(context)); } if (string.IsNullOrEmpty(name)) { throw String_NullOrEmpty(nameof(name)); } context.ScopedContextData = context.ScopedContextData.SetItem(name, value); } public static void SetLocalValue<T>( this IResolverContext context, string name, [MaybeNull] T value) { if (context is null) { throw new ArgumentNullException(nameof(context)); } if (string.IsNullOrEmpty(name)) { throw String_NullOrEmpty(nameof(name)); } context.LocalContextData = context.LocalContextData.SetItem(name, value); } [return: MaybeNull] public static T GetOrAddGlobalValue<T>( this IResolverContext context, string name, Func<string, T> createValue) { if (context is null) { throw new ArgumentNullException(nameof(context)); } if (string.IsNullOrEmpty(name)) { throw String_NullOrEmpty(nameof(name)); } if (createValue is null) { throw new ArgumentNullException(nameof(createValue)); } if (context.ContextData.TryGetValue(name, out var value) && value is T casted) { return casted; } else { T newValue = createValue(name); context.ContextData[name] = newValue; return newValue; } } [return: MaybeNull] public static T GetOrAddScopedValue<T>( this IResolverContext context, string name, Func<string, T> createValue) { if (context is null) { throw new ArgumentNullException(nameof(context)); } if (string.IsNullOrEmpty(name)) { throw String_NullOrEmpty(nameof(name)); } if (createValue is null) { throw new ArgumentNullException(nameof(createValue)); } if (context.ScopedContextData.TryGetValue(name, out var value) && value is T casted) { return casted; } else { T newValue = createValue(name); SetScopedValue(context, name, newValue); return newValue; } } [return: MaybeNull] public static T GetOrAddLocalValue<T>( this IResolverContext context, string name, Func<string, T> createValue) { if (context is null) { throw new ArgumentNullException(nameof(context)); } if (string.IsNullOrEmpty(name)) { throw String_NullOrEmpty(nameof(name)); } if (createValue is null) { throw new ArgumentNullException(nameof(createValue)); } if (context.LocalContextData.TryGetValue(name, out var value) && value is T casted) { return casted; } else { T newValue = createValue(name); SetLocalValue(context, name, newValue); return newValue; } } public static void RemoveGlobalValue( this IResolverContext context, string name) { if (context is null) { throw new ArgumentNullException(nameof(context)); } if (string.IsNullOrEmpty(name)) { throw String_NullOrEmpty(nameof(name)); } context.ContextData.Remove(name); } public static void RemoveScopedValue( this IResolverContext context, string name) { if (context is null) { throw new ArgumentNullException(nameof(context)); } if (string.IsNullOrEmpty(name)) { throw String_NullOrEmpty(nameof(name)); } context.ScopedContextData = context.ScopedContextData.Remove(name); } public static void RemoveLocalValue( this IResolverContext context, string name) { if (context is null) { throw new ArgumentNullException(nameof(context)); } if (string.IsNullOrEmpty(name)) { throw String_NullOrEmpty(nameof(name)); } context.LocalContextData = context.LocalContextData.Remove(name); } public static T GetEventMessage<T>(this IResolverContext context) { if (context is null) { throw new ArgumentNullException(nameof(context)); } if (context.ScopedContextData.TryGetValue( WellKnownContextData.EventMessage, out var value) && value is { }) { if(value is T casted) { return casted; } throw EventMessage_InvalidCast(typeof(T), value.GetType()); } throw EventMessage_NotFound(); } } }
27.141479
87
0.484895
[ "MIT" ]
BaptisteGirard/hotchocolate
src/HotChocolate/Core/src/Types/Extensions/ResolverContextExtensions.cs
8,441
C#
using System.Collections.Generic; using System.Xml; using Mozi.HttpEmbedded.Generic; namespace Mozi.HttpEmbedded.WebService { /// <summary> /// SOAP envelope封装 /// SOAP标准内容比较多,目前只实现WebService中需要封装的部分 /// </summary> public class SoapEnvelope { public List<Namespace> Namespaces = new List<Namespace>() { new Namespace { Prefix="xsi",Uri="http://www.w3.org/2001/XMLSchema-instance" }, new Namespace { Prefix="xsd",Uri="http://www.w3.org/2001/XMLSchema" } }; public string NS_EncodingStyle = "http://www.w3.org/2001/12/soap-encoding"; /// <summary> /// SOAP版本 /// </summary> public SoapVersion Version = SoapVersion.Ver11; public SoapHeader Header { get; set; } public SoapBody Body { get; set; } public string Prefix = "m"; public string Namespace = "http://mozi.org/soap"; public SoapEnvelope() { Body = new SoapBody(); } ///// <summary> ///// 构造xml文档 ///// </summary> ///// <param name="envelope"></param> ///// <returns></returns> //public static string CreateDocument2(SOAPEnvelope envelope) //{ // MemoryStream ms = new MemoryStream(); // XmlTextWriter writer = new XmlTextWriter(ms, System.Text.Encoding.UTF8); // writer.WriteStartDocument(true); // writer.WriteStartElement(envelope.Version.Prefix, "Envelope", envelope.Version.Namespace); // writer.WriteAttributeString(envelope.Version.Prefix, "encodingStyle",null,envelope.NS_EncodingStyle); // writer.WriteAttributeString("xmlns", "xsi",null,envelope.NS_XSI); // writer.WriteAttributeString("xmlns", "xsd", null,envelope.NS_XSD); // //header // if (envelope.Header != null) // { // writer.WriteStartElement(envelope.Version.Prefix, "Header", ""); // if (envelope.Header.Childs != null && envelope.Header.Childs.Length > 0) // { // } // writer.WriteEndElement(); // } // //body // writer.WriteStartElement(envelope.Version.Prefix, "Body", envelope.ElementPrefix); // //bodyelements // writer.WriteStartElement(envelope.ElementPrefix, envelope.Body.Method,""); // if (!string.IsNullOrEmpty(envelope.Body.Namespace)) // { // writer.WriteAttributeString("xmlns", "", null, envelope.Body.Namespace); // } // foreach (var r in envelope.Body.Items) // { // writer.WriteElementString(envelope.ElementPrefix, r.Key,null, r.Value); // } // //fault // writer.WriteEndElement(); // writer.WriteEndElement(); // writer.WriteEndElement(); // writer.WriteEndDocument(); // writer.Flush(); // writer.Close(); // string text = System.Text.Encoding.UTF8.GetString(ms.ToArray()); // ms.Close(); // return text;429004198712031889 //} //DONE 这种写法有问题,暂时无法生成完整的XML文档,后期再想办法解决 /// <summary> /// 构造xml文档 /// <para> /// 父元素增加类命名空间定义<see href="XmlDocument.CreateElement(prefix,localName, namespaceUri)"后,创建子元素时命名空间地址会被隐去,此时可以随意添加前缀 /// </para> /// </summary> /// <param name="envelope"></param> /// <returns></returns> public string CreateDocument() { SoapEnvelope envelope = this; XmlDocument doc = new XmlDocument(); //declaration var declare = doc.CreateXmlDeclaration("1.0", "utf-8", "yes"); doc.AppendChild(declare); //envelope var nodeEnvelope = doc.CreateElement( envelope.Version.Prefix,"Envelope", envelope.Version.Namespace); foreach (var ns in envelope.Namespaces) { nodeEnvelope.SetAttribute("xmlns:"+ns.Prefix, ns.Uri); } nodeEnvelope.SetAttribute("xmlns:" + envelope.Version.Prefix, envelope.Version.Namespace); nodeEnvelope.SetAttribute("encodingStyle",envelope.Version.Namespace,envelope.NS_EncodingStyle); //header if (envelope.Header != null) { var nodeHeader = doc.CreateElement(envelope.Version.Prefix,"Header", envelope.Version.Namespace); if (envelope.Header.Childs != null && envelope.Header.Childs.Length > 0) { } nodeEnvelope.AppendChild(nodeHeader); } //body var nodeBody = doc.CreateElement(envelope.Version.Prefix,"Body", envelope.Version.Namespace); //fault if (envelope.Body.Fault != null) { var fault=doc.CreateElement(envelope.Version.Prefix, "Fault", envelope.Version.Namespace); fault.SetAttribute("xmlns", envelope.Namespace); var faultCode = doc.CreateElement(envelope.Prefix, "faultcode", envelope.Namespace); var faultstring = doc.CreateElement(envelope.Prefix, "faultstring", envelope.Namespace); var faultactor = doc.CreateElement(envelope.Prefix, "faultactor", envelope.Namespace); var detail = doc.CreateElement(envelope.Prefix, "detail", envelope.Namespace); faultCode.InnerText = envelope.Body.Fault.faultcode; faultstring.InnerText = envelope.Body.Fault.faultstring; faultactor.InnerText = envelope.Body.Fault.faultactor; detail.InnerText = envelope.Body.Fault.detail; fault.AppendChild(faultCode); fault.AppendChild(faultstring); fault.AppendChild(faultactor); fault.AppendChild(detail); } //bodyelements var nodeBodyMethod = doc.CreateElement(envelope.Prefix,envelope.Body.Method, envelope.Namespace); if (!string.IsNullOrEmpty(envelope.Namespace)) { nodeBodyMethod.SetAttribute("xmlns", envelope.Namespace); } //methodparams foreach (var r in envelope.Body.Items) { var nodeItem = doc.CreateElement(envelope.Prefix,r.Key, envelope.Namespace); nodeItem.InnerText = r.Value; nodeBodyMethod.AppendChild(nodeItem); } nodeBody.AppendChild(nodeBodyMethod); nodeEnvelope.AppendChild(nodeBody); doc.AppendChild(nodeEnvelope); return doc.OuterXml; } /// <summary> /// 解析SOAP文件 /// </summary> /// <param name="content"></param> /// <returns></returns> public static SoapEnvelope ParseDocument(string content,SoapVersion version) { SoapEnvelope envelope = new SoapEnvelope(); XmlDocument doc = new XmlDocument(); XmlNamespaceManager xm = new XmlNamespaceManager(doc.NameTable); xm.AddNamespace(version.Prefix, version.Namespace); doc.LoadXml(content); var body = doc.SelectSingleNode(string.Format("/{0}:Envelope/{0}:Body",version.Prefix),xm); var action = body.FirstChild; if (action.LocalName == "Fault") { XmlNode fault = action; action = action.NextSibling; } envelope.Body.Method = action.LocalName; var childs = action.ChildNodes; for(var i = 0; i < childs.Count; i++) { var child = childs[i]; envelope.Body.Items.Add(child.LocalName, child.InnerText); } //version //header //body //fault return envelope; } } /// <summary> /// SOAP头节点信息 /// </summary> public class SoapHeader { public SoapHeaderChild[] Childs { get; set; } } public class SoapHeaderChild { public string Name { get; set; } public string actor {get;set;} public string mustUnderstand { get; set; } //"0"|"1" public string encodingStyle { get; set; } } /// <summary> /// SOAP内容节点信息 /// </summary> public class SoapBody { public SoapFault Fault { get; set; } public string Method = ""; public Dictionary<string, string> Items = new Dictionary<string, string>(); } /// <summary> /// SOAP错误信息 /// </summary> public class SoapFault { //VersionMismatch SOAP Envelope 元素的无效命名空间被发现 //MustUnderstand Header 元素的一个直接子元素(带有设置为 "1" 的 mustUnderstand 属性)无法被理解。 //Client 消息被不正确地构成,或包含了不正确的信息。 //Server 服务器有问题,因此无法处理进行下去。 public string faultcode { get; set; } public string faultstring { get; set; } public string faultactor { get; set; } public string detail { get; set; } } /// <summary> /// SOAP协议版本 /// </summary> public class SoapVersion : AbsClassEnum { /// <summary> /// SOAPAction: "{ServiceName}/{ActionName}" /// text/xml /// </summary> public static SoapVersion Ver11 = new SoapVersion("1.1","soap", "http://schemas.xmlsoap.org/soap/envelope/"); /// <summary> /// application/soap+xml /// </summary> public static SoapVersion Ver12 = new SoapVersion("1.2","soap12", "http://www.w3.org/2003/05/soap-envelope"); public static SoapVersion Ver12Dotnet = new SoapVersion("dot1.2", "soap2", "http://www.w3.org/2003/05/soap-envelope"); public string Version { get { return _vervalue; } } public string Namespace { get { return _namespace; } } public string Prefix { get { return _prefix; } } protected override string Tag { get { return _vervalue; } } private string _vervalue = ""; private string _namespace = ""; private string _prefix = ""; public SoapVersion(string verValue,string prefix,string nameSpace) { _vervalue = verValue; _prefix = prefix; _namespace = nameSpace; } } }
37.382671
126
0.56562
[ "MIT" ]
MoziCoder/Mozi.Network
Mozi.HttpEmbedded/WebService/SOAP.cs
10,761
C#
// <auto-generated> // ReSharper disable ConvertPropertyToExpressionBody // ReSharper disable DoNotCallOverridableMethodsInConstructor // ReSharper disable InconsistentNaming // ReSharper disable PartialMethodWithSinglePart // ReSharper disable PartialTypeWithSinglePart // ReSharper disable RedundantNameQualifier // ReSharper disable RedundantOverridenMember // ReSharper disable UseNameofExpression // TargetFrameworkVersion = 4.51 #pragma warning disable 1591 // Ignore "Missing XML Comment" warning namespace $safeprojectname$ { using Microsoft.AspNet.Identity.EntityFramework; using System; using System.Data.Entity; using System.Data.Entity.Migrations; public class DbMigrationConfiguration : DbMigrationsConfiguration<ApplicationDbContext> { public DbMigrationConfiguration() { AutomaticMigrationsEnabled = true; AutomaticMigrationDataLossAllowed = true; } //protected override void Seed(ApplicationDbContext context) //{ // This method will be called after migrating to the latest version. // You can use the DbSet<T>.AddOrUpdate() helper extension method // to avoid creating duplicate seed data. E.g. // // context.People.AddOrUpdate( // p => p.FullName, // new Person { FullName = "Andrew Peters" }, // new Person { FullName = "Brice Lambson" }, // new Person { FullName = "Rowan Miller" } // ); // //} } } // </auto-generated>
33.625
91
0.654275
[ "MIT" ]
ansim/MvcSolutionTemplate
MvcProjectTemplate.Data/DbMigrationConfiguration.cs
1,614
C#
using System.Collections.Generic; namespace Maersk.Authentication.External { public interface IExternalAuthConfiguration { List<ExternalLoginProviderInfo> Providers { get; } } }
20
58
0.74
[ "MIT" ]
shalindasilva1/fiverr
aspnet-core/src/Maersk.Web.Core/Authentication/External/IExternalAuthConfiguration.cs
202
C#
//------------------------------------------------------------------------------ // <auto-generated> // This code was generated by a tool. // Runtime Version:4.0.30319.42000 // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ namespace WpfUI.Properties { [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Editors.SettingsDesigner.SettingsSingleFileGenerator", "17.2.0.0")] internal sealed partial class Settings : global::System.Configuration.ApplicationSettingsBase { private static Settings defaultInstance = ((Settings)(global::System.Configuration.ApplicationSettingsBase.Synchronized(new Settings()))); public static Settings Default { get { return defaultInstance; } } } }
39.259259
151
0.579245
[ "MIT" ]
MarcGervais/csla
Samples/SimpleNTier/WpfUI/Properties/Settings.Designer.cs
1,062
C#
/* * Licensed to SharpSoftware under one or more contributor * license agreements. See the NOTICE file distributed with this work for * additional information regarding copyright ownership. * * SharpSoftware 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 Itinero.Attributes; using Itinero.Navigation.Instructions; using Itinero.Profiles.Lua; namespace Itinero.Profiles { /// <summary> /// Represents a dynamic routing profile that is based on a lua function. /// </summary> public class DynamicProfile : Profile { private readonly Script _script; private readonly object _function; private readonly string _name; private readonly ProfileMetric _metric; private readonly string[] _vehicleTypes; private readonly Table _attributesTable; private readonly Table _resultsTable; /// <summary> /// Creates a new dynamic profile. /// </summary> internal DynamicProfile(string name, ProfileMetric metric, string[] vehicleTypes, DynamicVehicle parent, Script script, object factor_and_speed) : base(name, metric, vehicleTypes, null, parent) { _name = name; _metric = metric; _vehicleTypes = vehicleTypes; _script = script; _function = factor_and_speed; _attributesTable = new Table(_script); _resultsTable = new Table(_script); } /// <summary> /// Gets the name. /// </summary> public override string Name { get { return _name; } } /// <summary> /// Gets the metric. /// </summary> public override ProfileMetric Metric { get { return _metric; } } /// <summary> /// Gets the vehicle types. /// </summary> public override string[] VehicleTypes { get { return _vehicleTypes; } } /// <summary> /// Get a function to calculate properties for a set given edge attributes. /// </summary> /// <returns></returns> public sealed override FactorAndSpeed FactorAndSpeed(IAttributeCollection attributes) { lock (_script) { // build lua table. _attributesTable.Clear(); if (attributes == null || attributes.Count == 0) { return Profiles.FactorAndSpeed.NoFactor; } foreach (var attribute in attributes) { _attributesTable.Set(attribute.Key, DynValue.NewString(attribute.Value)); } // call factor_and_speed function. _resultsTable.Clear(); _script.Call(_function, _attributesTable, _resultsTable); // get the results. var result = new FactorAndSpeed(); float val; if (!_resultsTable.TryGetFloat("speed", out val)) { val = 0; } if (val == 0) { return Profiles.FactorAndSpeed.NoFactor; } result.SpeedFactor = 1.0f / (val / 3.6f); // 1/m/s if (_metric == ProfileMetric.TimeInSeconds) { // use 1/speed as factor. result.Value = result.SpeedFactor; } else if (_metric == ProfileMetric.DistanceInMeters) { // use 1 as factor. result.Value = 1; } else { // use a custom factor. if (!_resultsTable.TryGetFloat("factor", out val)) { val = 0; } result.Value = val; } if (!_resultsTable.TryGetFloat("direction", out val)) { val = 0; } result.Direction = (short)val; bool boolVal; if (!_resultsTable.TryGetBool("canstop", out boolVal)) { // default stopping everywhere. boolVal = true; } if (!boolVal) { result.Direction += 3; } return result; } } /// <summary> /// Returns true if the two edges with the given attributes are identical as far as this profile is concerned. /// </summary> /// <remarks> /// Default implementation compares attributes one-by-one. /// </remarks> public override sealed bool Equals(IAttributeCollection attributes1, IAttributeCollection attributes2) { return attributes1.ContainsSame(attributes2); } private DynamicUnimodalInstructionGenerator _instructionGenerator; /// <summary> /// Gets the unimodal instruction generator. /// </summary> public override IUnimodalInstructionGenerator InstructionGenerator { get { if (_instructionGenerator == null) { var vehicle = this.Parent as DynamicVehicle; if (vehicle.Script.Globals.Get("instruction_generators") == null) { throw new System.Exception(string.Format("Profile {0} does not define an instruction generator.", this.FullName)); } _instructionGenerator = new DynamicUnimodalInstructionGenerator(this); } return _instructionGenerator; } } } }
34.226316
152
0.522836
[ "Apache-2.0" ]
AlexanderTaeschner/routing
src/Itinero/Profiles/DynamicProfile.cs
6,505
C#
//------------------------------------------------------------------------------ // <auto-generated> // This code was generated by a tool. // Runtime Version:4.0.30319.42000 // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ namespace WpfDeviceCatcherMvvmFramework45.Properties { /// <summary> /// A strongly-typed resource class, for looking up localized strings, etc. /// </summary> // This class was auto-generated by the StronglyTypedResourceBuilder // class via a tool like ResGen or Visual Studio. // To add or remove a member, edit your .ResX file then rerun ResGen // with the /str option, or rebuild your VS project. [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "4.0.0.0")] [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] internal class Resources { private static global::System.Resources.ResourceManager resourceMan; private static global::System.Globalization.CultureInfo resourceCulture; [global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] internal Resources() { } /// <summary> /// Returns the cached ResourceManager instance used by this class. /// </summary> [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] internal static global::System.Resources.ResourceManager ResourceManager { get { if ((resourceMan == null)) { global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("WpfDeviceCatcherMvvmFramework45.Properties.Resources", typeof(Resources).Assembly); resourceMan = temp; } return resourceMan; } } /// <summary> /// Overrides the current thread's CurrentUICulture property for all /// resource lookups using this strongly typed resource class. /// </summary> [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] internal static global::System.Globalization.CultureInfo Culture { get { return resourceCulture; } set { resourceCulture = value; } } } }
39.690141
197
0.608943
[ "MIT" ]
Bassman2/UsbMonitor
Demo/Demo .NET Framework 4.5/WpfDeviceCatcherMvvmFramework45/Properties/Resources.Designer.cs
2,820
C#
// ------------------------------------------------------------------------------ // Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License in the project root for license information. // ------------------------------------------------------------------------------ // **NOTE** This file was generated by a tool and any changes will be overwritten. // <auto-generated/> // Template Source: EntityCollectionRequest.cs.tt namespace Microsoft.Graph { using System; using System.Collections.Generic; using System.Net.Http; using System.Threading; using System.Linq.Expressions; /// <summary> /// The type IdentityContainerUserFlowsCollectionRequest. /// </summary> public partial class IdentityContainerUserFlowsCollectionRequest : BaseRequest, IIdentityContainerUserFlowsCollectionRequest { /// <summary> /// Constructs a new IdentityContainerUserFlowsCollectionRequest. /// </summary> /// <param name="requestUrl">The URL for the built request.</param> /// <param name="client">The <see cref="IBaseClient"/> for handling requests.</param> /// <param name="options">Query and header option name value pairs for the request.</param> public IdentityContainerUserFlowsCollectionRequest( string requestUrl, IBaseClient client, IEnumerable<Option> options) : base(requestUrl, client, options) { } /// <summary> /// Adds the specified IdentityUserFlow to the collection via POST. /// </summary> /// <param name="identityUserFlow">The IdentityUserFlow to add.</param> /// <returns>The created IdentityUserFlow.</returns> public System.Threading.Tasks.Task<IdentityUserFlow> AddAsync(IdentityUserFlow identityUserFlow) { return this.AddAsync(identityUserFlow, CancellationToken.None); } /// <summary> /// Adds the specified IdentityUserFlow to the collection via POST. /// </summary> /// <param name="identityUserFlow">The IdentityUserFlow to add.</param> /// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param> /// <returns>The created IdentityUserFlow.</returns> public System.Threading.Tasks.Task<IdentityUserFlow> AddAsync(IdentityUserFlow identityUserFlow, CancellationToken cancellationToken) { this.ContentType = "application/json"; this.Method = "POST"; return this.SendAsync<IdentityUserFlow>(identityUserFlow, cancellationToken); } /// <summary> /// Gets the collection page. /// </summary> /// <returns>The collection page.</returns> public System.Threading.Tasks.Task<IIdentityContainerUserFlowsCollectionPage> GetAsync() { return this.GetAsync(CancellationToken.None); } /// <summary> /// Gets the collection page. /// </summary> /// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param> /// <returns>The collection page.</returns> public async System.Threading.Tasks.Task<IIdentityContainerUserFlowsCollectionPage> GetAsync(CancellationToken cancellationToken) { this.Method = "GET"; var response = await this.SendAsync<IdentityContainerUserFlowsCollectionResponse>(null, cancellationToken).ConfigureAwait(false); if (response != null && response.Value != null && response.Value.CurrentPage != null) { if (response.AdditionalData != null) { object nextPageLink; response.AdditionalData.TryGetValue("@odata.nextLink", out nextPageLink); var nextPageLinkString = nextPageLink as string; if (!string.IsNullOrEmpty(nextPageLinkString)) { response.Value.InitializeNextPageRequest( this.Client, nextPageLinkString); } // Copy the additional data collection to the page itself so that information is not lost response.Value.AdditionalData = response.AdditionalData; } return response.Value; } return null; } /// <summary> /// Adds the specified expand value to the request. /// </summary> /// <param name="value">The expand value.</param> /// <returns>The request object to send.</returns> public IIdentityContainerUserFlowsCollectionRequest Expand(string value) { this.QueryOptions.Add(new QueryOption("$expand", value)); return this; } /// <summary> /// Adds the specified expand value to the request. /// </summary> /// <param name="expandExpression">The expression from which to calculate the expand value.</param> /// <returns>The request object to send.</returns> public IIdentityContainerUserFlowsCollectionRequest Expand(Expression<Func<IdentityUserFlow, object>> expandExpression) { if (expandExpression == null) { throw new ArgumentNullException(nameof(expandExpression)); } string error; string value = ExpressionExtractHelper.ExtractMembers(expandExpression, out error); if (value == null) { throw new ArgumentException(error, nameof(expandExpression)); } else { this.QueryOptions.Add(new QueryOption("$expand", value)); } return this; } /// <summary> /// Adds the specified select value to the request. /// </summary> /// <param name="value">The select value.</param> /// <returns>The request object to send.</returns> public IIdentityContainerUserFlowsCollectionRequest Select(string value) { this.QueryOptions.Add(new QueryOption("$select", value)); return this; } /// <summary> /// Adds the specified select value to the request. /// </summary> /// <param name="selectExpression">The expression from which to calculate the select value.</param> /// <returns>The request object to send.</returns> public IIdentityContainerUserFlowsCollectionRequest Select(Expression<Func<IdentityUserFlow, object>> selectExpression) { if (selectExpression == null) { throw new ArgumentNullException(nameof(selectExpression)); } string error; string value = ExpressionExtractHelper.ExtractMembers(selectExpression, out error); if (value == null) { throw new ArgumentException(error, nameof(selectExpression)); } else { this.QueryOptions.Add(new QueryOption("$select", value)); } return this; } /// <summary> /// Adds the specified top value to the request. /// </summary> /// <param name="value">The top value.</param> /// <returns>The request object to send.</returns> public IIdentityContainerUserFlowsCollectionRequest Top(int value) { this.QueryOptions.Add(new QueryOption("$top", value.ToString())); return this; } /// <summary> /// Adds the specified filter value to the request. /// </summary> /// <param name="value">The filter value.</param> /// <returns>The request object to send.</returns> public IIdentityContainerUserFlowsCollectionRequest Filter(string value) { this.QueryOptions.Add(new QueryOption("$filter", value)); return this; } /// <summary> /// Adds the specified skip value to the request. /// </summary> /// <param name="value">The skip value.</param> /// <returns>The request object to send.</returns> public IIdentityContainerUserFlowsCollectionRequest Skip(int value) { this.QueryOptions.Add(new QueryOption("$skip", value.ToString())); return this; } /// <summary> /// Adds the specified orderby value to the request. /// </summary> /// <param name="value">The orderby value.</param> /// <returns>The request object to send.</returns> public IIdentityContainerUserFlowsCollectionRequest OrderBy(string value) { this.QueryOptions.Add(new QueryOption("$orderby", value)); return this; } } }
40.954338
153
0.587691
[ "MIT" ]
GeertVL/msgraph-beta-sdk-dotnet
src/Microsoft.Graph/Generated/requests/IdentityContainerUserFlowsCollectionRequest.cs
8,969
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. namespace System.Reflection { [Flags] public enum ResourceLocation { ContainedInAnotherAssembly = 2, ContainedInManifestFile = 4, Embedded = 1, } }
24.5625
71
0.692112
[ "MIT" ]
2E0PGS/corefx
src/Common/src/CoreLib/System/Reflection/ResourceLocation.cs
393
C#
namespace Apex.ConnectApi { using ApexSharp; using ApexSharp.ApexAttributes; using ApexSharp.Implementation; using global::Apex.System; /// <summary> /// /// </summary> public class SmartDataDiscoveryFilter { // infrastructure public SmartDataDiscoveryFilter(dynamic self) { Self = self; } dynamic Self { get; set; } static dynamic Implementation { get { return Implementor.GetImplementation(typeof(SmartDataDiscoveryFilter)); } } // API object fieldName { get { return Self.fieldName; } set { Self.fieldName = value; } } object @operator { get { return Self.@operator; } set { Self.@operator = value; } } object values { get { return Self.values; } set { Self.values = value; } } public SmartDataDiscoveryFilter() { Self = Implementation.Constructor(); } public object clone() { return Self.clone(); } public bool equals(object obj) { return Self.equals(obj); } public double getBuildVersion() { return Self.getBuildVersion(); } public int hashCode() { return Self.hashCode(); } public string toString() { return Self.toString(); } } }
18.814433
87
0.417534
[ "MIT" ]
apexsharp/apexsharp
Apex/ConnectApi/SmartDataDiscoveryFilter.cs
1,825
C#
/******************************************************************************* * Copyright © 2020 WaterCloud.Framework 版权所有 * Author: WaterCloud * Description: WaterCloud快速开发平台 * Website: *********************************************************************************/ using SqlSugar; using System; using System.ComponentModel.DataAnnotations; namespace WaterCloud.Domain.SystemManage { [SugarTable("sys_module")] public class ModuleEntity : IEntity<ModuleEntity>, ICreationAudited, IModificationAudited, IDeleteAudited { /// <summary> /// 主键Id /// </summary> [SugarColumn(ColumnName ="F_Id", IsPrimaryKey = true,ColumnDescription ="主键Id")] public string F_Id { get; set; } /// <summary> /// 父级Id /// </summary> [Required(ErrorMessage = "上级不能为空")] [SugarColumn(IsNullable = true, ColumnName = "F_ParentId", ColumnDataType = "nvarchar(50)", ColumnDescription = "父级Id")] public string F_ParentId { get; set; } /// <summary> /// 层级 /// </summary> [SugarColumn(IsNullable = true, ColumnDescription = "层级")] public int? F_Layers { get; set; } /// <summary> /// 编号 /// </summary> [Required(ErrorMessage = "编号不能为空")] [SugarColumn(IsNullable = true, ColumnName = "F_EnCode",ColumnDataType = "nvarchar(50)", ColumnDescription = "编号", UniqueGroupNameList = new string[] { "sys_module" })] public string F_EnCode { get; set; } /// <summary> /// 名称 /// </summary> [Required(ErrorMessage = "名称不能为空")] [SugarColumn(IsNullable = true, ColumnName = "F_FullName", ColumnDataType = "nvarchar(50)", ColumnDescription = "删除人Id")] public string F_FullName { get; set; } /// <summary> /// 图标 /// </summary> [SugarColumn(IsNullable = true, ColumnName = "F_Icon",ColumnDataType = "nvarchar(50)", ColumnDescription = "图标")] public string F_Icon { get; set; } /// <summary> /// Url地址 /// </summary> [SugarColumn(IsNullable = true, ColumnName = "F_UrlAddress", ColumnDataType = "longtext,nvarchar(max)", ColumnDescription = "Url地址")] public string F_UrlAddress { get; set; } /// <summary> /// 目标 /// </summary> [Required(ErrorMessage = "目标不能为空")] [SugarColumn(IsNullable = true, ColumnName = "F_Target",ColumnDataType = "nvarchar(50)", ColumnDescription = "目标")] public string F_Target { get; set; } /// <summary> /// 是否是菜单 /// </summary> [SugarColumn(IsNullable = true,ColumnDescription = "是否是菜单")] public bool? F_IsMenu { get; set; } /// <summary> /// 是否展开 /// </summary> [SugarColumn(IsNullable = true, ColumnDescription = "是否展开")] public bool? F_IsExpand { get; set; } /// <summary> /// 是否公共 /// </summary> [SugarColumn(IsNullable = true, ColumnDescription = "是否公共")] public bool? F_IsPublic { get; set; } /// <summary> /// 是否字段 /// </summary> [SugarColumn(IsNullable = true, ColumnDescription = "是否字段")] public bool? F_IsFields { get; set; } /// <summary> /// 允许修改 /// </summary> [SugarColumn(IsNullable = true, ColumnDescription = "允许修改")] public bool? F_AllowEdit { get; set; } /// <summary> /// 允许删除 /// </summary> [SugarColumn(IsNullable = true, ColumnDescription = "允许删除")] public bool? F_AllowDelete { get; set; } /// <summary> /// 排序码 /// </summary> [Required(ErrorMessage = "排序不能为空")] [Range(0, 99999999, ErrorMessage = "排序大小必须介于1~99999999之间")] [SugarColumn(IsNullable = true, ColumnDescription = "排序码")] public int? F_SortCode { get; set; } /// <summary> /// 删除标记 /// </summary> [SugarColumn(IsNullable = true,ColumnDescription = "删除标记")] public bool? F_DeleteMark { get; set; } /// <summary> /// 有效标记 /// </summary> [SugarColumn(IsNullable = true, ColumnDescription = "有效标记")] public bool? F_EnabledMark { get; set; } /// <summary> /// 备注 /// </summary> [SugarColumn(IsNullable = true, ColumnName = "F_Description",ColumnDataType = "longtext,nvarchar(max)", ColumnDescription = "备注")] public string F_Description { get; set; } /// <summary> /// 创建时间 /// </summary> [SugarColumn(IsNullable = true, ColumnDescription = "创建时间")] public DateTime? F_CreatorTime { get; set; } /// <summary> /// 创建人Id /// </summary> [SugarColumn(IsNullable = true, ColumnName = "F_CreatorUserId",ColumnDataType = "nvarchar(50)", ColumnDescription = "创建人Id")] public string F_CreatorUserId { get; set; } /// <summary> /// 修改时间 /// </summary> [SugarColumn(IsNullable = true,ColumnDescription = "修改时间")] public DateTime? F_LastModifyTime { get; set; } /// <summary> /// 修改人Id /// </summary> [SugarColumn(IsNullable = true, ColumnName = "F_LastModifyUserId", ColumnDataType = "nvarchar(50)", ColumnDescription = "修改人Id")] public string F_LastModifyUserId { get; set; } /// <summary> /// 删除时间 /// </summary> [SugarColumn(IsNullable = true,ColumnDescription = "删除时间")] public DateTime? F_DeleteTime { get; set; } /// <summary> /// 删除人Id /// </summary> [SugarColumn(IsNullable = true, ColumnName = "F_DeleteUserId", ColumnDataType = "nvarchar(50)", ColumnDescription = "删除人Id")] public string F_DeleteUserId { get; set; } /// <summary> /// /// </summary> [SugarColumn(IsNullable = true, ColumnName = "F_Authorize", ColumnDataType = "nvarchar(100)")] public string F_Authorize { get; set; } } }
40.892617
176
0.544395
[ "MIT" ]
MonsterUncle/WaterCloud
WaterCloud.Domain/Entity/SystemManage/ModuleEntity.cs
6,500
C#
using HiddenWallet.SharedApi.Models; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace HiddenWallet.Daemon.Models { public class WalletCreateResponse : BaseResponse { public WalletCreateResponse() => Success = true; public string Mnemonic { get; set; } public string CreationTime { get; set; } } }
23.0625
52
0.761518
[ "MIT" ]
bob6664569/HiddenWallet
HiddenWallet.Daemon/Models/WalletCreateResponse.cs
371
C#
namespace YamAndRateApp.Utils { using System; using Windows.Data.Xml.Dom; using Windows.UI.Notifications; public class ToastManager { private ToastTemplateType toastTemplate; private XmlDocument toastXml; public ToastManager() { this.toastTemplate = ToastTemplateType.ToastImageAndText02; this.toastXml = ToastNotificationManager.GetTemplateContent(this.toastTemplate); } public void CreateToast(string heading, string content, string image, string navigateTo) { this.FillToastContent(heading, content, image, navigateTo); ToastNotification toast = new ToastNotification(this.toastXml); ToastNotificationManager.CreateToastNotifier().Show(toast); } public void CreateToast(string heading, string image) { this.FillToastContent(heading, image); ToastNotification toast = new ToastNotification(this.toastXml); ToastNotificationManager.CreateToastNotifier().Show(toast); } private void FillToastContent(string heading, string image) { // Fill in the text elements XmlNodeList stringElements = this.toastXml.GetElementsByTagName("text"); stringElements[0].AppendChild(this.toastXml.CreateTextNode(heading)); // Specify the absolute path to an image XmlNodeList imageElements = this.toastXml.GetElementsByTagName("image"); imageElements[0].Attributes.GetNamedItem("src").NodeValue = image; var toastElement = ((XmlElement)toastXml.SelectSingleNode("/toast")); } private void FillToastContent(string heading, string content, string image, string navigateTo) { // Fill in the text elements XmlNodeList stringElements = this.toastXml.GetElementsByTagName("text"); stringElements[0].AppendChild(this.toastXml.CreateTextNode(heading)); stringElements[1].AppendChild(this.toastXml.CreateTextNode(content)); // Specify the absolute path to an image XmlNodeList imageElements = this.toastXml.GetElementsByTagName("image"); imageElements[0].Attributes.GetNamedItem("src").NodeValue = image; var toastElement = ((XmlElement)toastXml.SelectSingleNode("/toast")); toastElement.SetAttribute("launch", navigateTo); } } }
40.540984
102
0.661949
[ "MIT" ]
WindowsAppsTeam15/WinUniversalApps
YamAndRateApp/YamAndRateApp/Utils/ToastManager.cs
2,475
C#
using System.Collections.Generic; using System.Linq; using UnityEditor; using UnityEngine; using UnityEngine.Internal; namespace LDtkUnity.Editor { [ExcludeFromDocs] public class LDtkSectionIntGrids : LDtkSectionDataDrawer<LayerDefinition> { protected override string PropertyName => LDtkProjectImporter.INTGRID; protected override string GuiText => "IntGrids"; protected override string GuiTooltip => "Assign Int Grid tiles, which has options for custom collision, rendering colors, and GameObjects. Make some at 'Create > LDtkIntGridTile'"; protected override Texture GuiImage => LDtkIconUtility.LoadIntGridIcon(); protected override string ReferenceLink => LDtkHelpURL.SECTION_INTGRID; public LDtkSectionIntGrids(SerializedObject serializedObject) : base(serializedObject) { } protected override void GetDrawers(LayerDefinition[] defs, List<LDtkContentDrawer<LayerDefinition>> drawers) { //iterator is for figuring out which array index we should really be using, since any layer could have any amount of intgrid values LDtkDrawerIntGridValueIterator intGridValueIterator = new LDtkDrawerIntGridValueIterator(); foreach (LayerDefinition def in defs) { LDtkDrawerIntGrid intGridDrawer = new LDtkDrawerIntGrid(def, ArrayProp, intGridValueIterator); drawers.Add(intGridDrawer); } } protected override int GetSizeOfArray(LayerDefinition[] datas) { return datas.SelectMany(p => p.IntGridValues).Count(); } } }
42.487179
188
0.701267
[ "MIT" ]
Cammin/LDtkToUnity
Assets/LDtkUnity/Editor/CustomEditor/SectionDrawers/LDtkSectionIntGrids.cs
1,659
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("Common")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("Common")] [assembly: AssemblyCopyright("Copyright © 2019")] [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("6c454d88-051b-410d-ab37-b2084df20969")] // 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.297297
84
0.745652
[ "MIT" ]
dvinun/CommonDotNet
CommonDotNet/Properties/AssemblyInfo.cs
1,383
C#
using System.Collections; using System.Collections.Generic; using UnityEngine; public class CalculateShanten : MonoBehaviour { public int[] hand; public int shanten; private int[] hc; // acts like Hash table void init_hash() { hc = new int[889]; for (int i1 = 0; i1 < 9; i1++) { for (int i2 = 0; i2 < 9; i2++) { for (int i3 = 0; i3 < 9; i3++) { int ind = i1 * 100 + i2 * 10 + i3; if (i1 == i2 && i1 == i3) // Same 3 hc[ind] = 2; else if (i1 + 1 == i2 && i2 + 1 == i3) // Consecutive hc[ind] = 2; else if (i1 - i2 < 3 && i1 - i2 > -3) hc[ind] = 1; else if (i2 - i3 < 3 && i2 - i3 > -3) hc[ind] = 1; else hc[ind] = 0; } } } } // GetMaxBody : Returns max body count of hand // hand is composed of values 0 to 9. // Suppose that list is sorted. int GetMaxBody(List<int> h) { if (h.Count <= 1) // One cards, doesn't have to count { return 0; } else if (h.Count == 2) // if just two cards, there's possibility to have body candidate { return (h[0] - h[1] < 3 && h[0] - h[1] > -3) ? 1 : 0; } else if (h.Count == 3) // Basic body composition starts { return hc[h[0] * 100 + h[1] * 10 + h[2]]; } else // More than 5, just do the recursive method to find best hand posibility { // Divide into two group if the value is changing a lot for (int i = 1; i < h.Count; i++) { if (h[i] - h[i-1] > 2) { List<int> h1 = new List<int>(h.GetRange(0,i)); List<int> h2 = new List<int>(h.GetRange(i, h.Count - i)); return GetMaxBody(h1) + GetMaxBody(h2); } } // Or, pick 3 values int max_r = 0; for (int i1 = 0; i1 < h.Count-2; i1++) { for (int i2 = 1; i2 < h.Count-1; i2++) { if (i1 >= i2) continue; for (int i3 = 2; i3 < h.Count; i3++) { if (i1 >= i3 || i2 >= i3) continue; // Debug.Log(i1.ToString() + " " + i2.ToString() + " " + i3.ToString() + " " ); List<int> h1 = new List<int>(h); // Remove from here h1.RemoveAt(i3); h1.RemoveAt(i2); h1.RemoveAt(i1); int r_ = hc[h[i1] * 100 + h[i2] * 10 + h[i3]] + GetMaxBody(h1); if (max_r < r_) max_r = r_; } } } // Debug.Log(h.Count.ToString() + " " + max_r.ToString()); return max_r; } } // CalculateShanten : Calculate shanten count // 0 means tenpai, 1~ means shanten, -1 should means agari, but it's not sure // Based on http://ara.moo.jp/mjhmr/shanten.htm int CalculateShanten(int[] hand) { int r = 0; /// Card value // 0~8:1m~9m, 9~17:1p~9p, 18~26:1s~9s, 27~33:tou, nan, sha, be, shiro, hatsu, chu List<int> t_ = new List<int>(); /// Check Chitoitsu short chi_count = 0; for (int i = 0; i < hand.Length - 1; i++) if (hand[i] == hand[i + 1]) { chi_count++; i++; } r = 6 - chi_count; /// Check Kokushi List<int> k_ = new List<int>(); short k_head = 0; for (int i = 0; i < hand.Length; i++) if (hand[i] > 26 || hand[i] % 9 == 0 || hand[i] % 9 == 8) { if (!k_.Contains(hand[i])) { k_.Add(hand[i]); } if (i < hand.Length - 1 && hand[i] == hand[i + 1]) { k_head = 1; } } int r_k = 13 - k_.Count - k_head; if (r > r_k) r = r_k; /// Check Otherwise /// This is quite complicated /// Basically, 8 - 2 * [body] - [body candidate] // I know this is dumb method, but it works fine so... lol List<int> m_ = new List<int>(); // man List<int> p_ = new List<int>(); // pin List<int> s_ = new List<int>(); // sou int[] y_ = new int[7]{0,0,0,0,0,0,0}; for (int i = 0; i < hand.Length; i++) { if (hand[i] <= 8) // man m_.Add(hand[i]); else if (hand[i] <= 17) // pin p_.Add(hand[i] - 9); else if (hand[i] <= 26) // sou s_.Add(hand[i] - 18); else if (hand[i] <= 33) // mozi y_[hand[i] - 27]++; } // Sort each lists m_.Sort(); p_.Sort(); s_.Sort(); // Handle body shanten int r_n = 8 - GetMaxBody(m_) - GetMaxBody(p_) - GetMaxBody(s_); // Handling mozi cards, which can only handled as 3 same cards or head for (int i = 0; i < 7; i++) if (y_[i] == 2) r_n -= 1; // Body Candidate else if (y_[i] == 3 || y_[i] == 4) r_n -= 2; // Body Debug.Log(r_n); // Applying the shanten if (r > r_n) r = r_n; return r; } void Start() { init_hash(); Debug.Log("Start"); shanten = CalculateShanten(hand); Debug.Log("Finish!"); } }
31.86413
103
0.392973
[ "MIT" ]
r3coder/mahjong-shanten-calculator
CalculateShanten.cs
5,863
C#
using System; using System.Collections.Generic; using TddEbook.TddToolkit.CommonTypes; namespace TypeReflection.Interfaces { public interface IType { bool HasPublicParameterlessConstructor(); bool IsImplementationOfOpenGeneric(Type openGenericType); bool IsConcrete(); IEnumerable<IFieldWrapper> GetAllInstanceFields(); IEnumerable<IFieldWrapper> GetAllStaticFields(); IEnumerable<IFieldWrapper> GetAllConstants(); IEnumerable<IPropertyWrapper> GetAllPublicInstanceProperties(); Maybe<IConstructorWrapper> PickConstructorWithLeastNonPointersParameters(); IBinaryOperator Equality(); IBinaryOperator Inequality(); bool IsInterface(); IEnumerable<IEventWrapper> GetAllNonPublicEventsWithoutExplicitlyImplemented(); IEnumerable<IConstructorWrapper> GetAllPublicConstructors(); IEnumerable<IFieldWrapper> GetAllPublicInstanceFields(); IEnumerable<IPropertyWrapper> GetPublicInstanceWritableProperties(); IEnumerable<IMethod> GetAllPublicInstanceMethodsWithReturnValue(); bool HasConstructorWithParameters(); bool CanBeAssignedNullValue(); Type ToClrType(); bool IsException(); bool HasPublicConstructorCountOfAtMost(int i); bool IsOpenGeneric(Type type); } }
39.03125
83
0.796637
[ "MIT" ]
grzesiek-galezowski/tdd-toolkit
TypeReflection.Interfaces/IType.cs
1,249
C#
namespace Bytewizer.TinyCLR.SecureShell { public enum DisconnectReason { None = 0, // Not used by protocol HostNotAllowedToConnect = 1, ProtocolError = 2, KeyExchangeFailed = 3, Reserved = 4, MacError = 5, CompressionError = 6, ServiceNotAvailable = 7, ProtocolVersionNotSupported = 8, HostKeyNotVerifiable = 9, ConnectionLost = 10, ByApplication = 11, TooManyConnections = 12, AuthCancelledByUser = 13, NoMoreAuthMethodsAvailable = 14, IllegalUserName = 15 } }
26.217391
41
0.598673
[ "MIT" ]
bytewizer/microserver
src/Bytewizer.TinyCLR.Terminal.Ssh/Terminal/DisconnectReason.cs
605
C#
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; public class Hebb : Act { public ComputeShader shader; public RenderTexture Synapse; public RenderTexture cortex; public Slider sliderPlastic; public Slider sliderNumber; private int kiMain = 0; private RenderTexture outTexture; private int number = 0; void Start() { outTexture = new RenderTexture(Synapse.width, Synapse.height, 0, RenderTextureFormat.ARGB32); outTexture.enableRandomWrite = true; outTexture.Create(); outTexture.filterMode = FilterMode.Point; } private void Init() { shader.SetTexture(kiMain, "SynapseRW", outTexture); shader.SetTexture(kiMain, "Synapse", Synapse); shader.SetTexture(kiMain, "cortex", cortex); shader.SetFloat("plastic", sliderPlastic.value); } private void SetNumber(int n) { number = n; } private void InitNumber() { shader.SetInt("number", number); } private void Calculate() { shader.Dispatch(kiMain, 1, 10, 1); Graphics.Blit(outTexture, Synapse); } public override void Run(int i) { Init(); SetNumber(i); InitNumber(); Calculate(); } public override void StartAct() { // } public void RunGebb() { Init(); SetNumber((int)sliderNumber.value); InitNumber(); Calculate(); } }
20.77027
101
0.603123
[ "MIT" ]
BelkinAndrey/BrainSquared
Assets/Scripts/Hebb.cs
1,539
C#
//----------------------------------------------------------------------------- // PageFlipControl.cs // // Microsoft XNA Community Game Platform // Copyright (C) Microsoft Corporation. All rights reserved. //----------------------------------------------------------------------------- using Microsoft.Xna.Framework; namespace UserInterfaceSample.Controls { /// <summary> /// This control aligns its child controls horizontally, and allows the user to flick /// through them. /// </summary> class PageFlipControl : PanelControl { #region Fields // PageFlipTracker handles the logic of scrolling / tracking etc. private PageFlipTracker tracker = new PageFlipTracker(); #endregion #region Method overrides protected override void OnChildAdded(int index, Control child) { tracker.PageWidthList.Insert(index, (int)child.Size.X); } protected override void OnChildRemoved(int index, Control child) { tracker.PageWidthList.RemoveAt(index); } public override void Update(GameTime gametime) { tracker.Update(); base.Update(gametime); } public override void HandleInput(InputState input) { tracker.HandleInput(input); if(ChildCount > 0) { // Only the child that currently has focus gets input int current = tracker.CurrentPage; this[current].HandleInput(input); } } public override void Draw(DrawContext context) { int childCount = ChildCount; if (childCount < 2) { // Default rendering behavior if we don't have enough // children to flip through. base.Draw(context); return; } Vector2 origin = context.DrawOffset; int iCurrent = tracker.CurrentPage; float horizontalOffset = tracker.CurrentPageOffset; context.DrawOffset = origin + new Vector2 { X = horizontalOffset }; this[iCurrent].Draw(context); if (horizontalOffset > 0) { // The screen has been dragged to the right, so the edge of another // page is visible to the left. int iLeft = (iCurrent + childCount - 1) % childCount; context.DrawOffset.X = origin.X + horizontalOffset - tracker.EffectivePageWidth(iLeft); this[iLeft].Draw(context); } if (horizontalOffset + this[iCurrent].Size.X < context.Device.Viewport.Width) { // The edge of another page is visible to the right. // Note that if we have two pages, it's possible that a page will be // drawn twice, with parts of it visible on each edge of the screen. int iRight = (iCurrent + 1) % childCount; context.DrawOffset.X = origin.X + horizontalOffset + tracker.EffectivePageWidth(iCurrent); this[iRight].Draw(context); } } #endregion } }
34.580645
106
0.543532
[ "MIT" ]
SimonDarksideJ/XNAGameStudio
Samples/UISample_4_0/UISample/Controls/PageFlipControl.cs
3,216
C#
using System; using System.Collections.Generic; namespace Vertigo.Live { public static partial class LiveCollection { public static ILiveSet<T> AsLiveSet<T, TIDelta>(this ILiveCollection<T, TIDelta> source) where TIDelta : class, ICollectionDelta<T> { var cache = new CollectionStateCache<T, ISet<T>, ISetDelta<T>>(new HashSet<T>()); IDisposable subscription = null; LiveObserver<ICollectionState<T, TIDelta>> observer = null; return LiveSetObservable<T>.Create( innerChanged => { subscription = source.Subscribe(observer = source.CreateObserver(innerChanged)); return cache.WriteLock; }, (innerChanged, notified, stateLock, oldState) => { if (notified) { // get state using (var state = observer.GetState()) { // apply source state to cache cache.AddState(state.Status, state.Inner, state.Delta.ToSetDelta(items => items), state.LastUpdated, true); } } stateLock.DowngradeToReader(); // return state copy return cache.Copy(stateLock); }, () => observer.Dispose()); } } }
36.088889
100
0.453202
[ "MIT" ]
filmackay/live
Live/Collection/Projection/LiveCollectionAsSet.cs
1,626
C#
// *** WARNING: this file was generated by the Pulumi Terraform Bridge (tfgen) Tool. *** // *** Do not edit by hand unless you're certain you know what you are doing! *** using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Threading.Tasks; using Pulumi.Serialization; namespace Pulumi.Aws.Emr.Outputs { [OutputType] public sealed class ClusterCoreInstanceFleet { /// <summary> /// The ID of the EMR Cluster /// </summary> public readonly string? Id; /// <summary> /// Configuration block for instance fleet /// </summary> public readonly ImmutableArray<Outputs.ClusterCoreInstanceFleetInstanceTypeConfig> InstanceTypeConfigs; /// <summary> /// Configuration block for launch specification /// </summary> public readonly Outputs.ClusterCoreInstanceFleetLaunchSpecifications? LaunchSpecifications; /// <summary> /// Friendly name given to the instance fleet. /// </summary> public readonly string? Name; public readonly int? ProvisionedOnDemandCapacity; public readonly int? ProvisionedSpotCapacity; /// <summary> /// The target capacity of On-Demand units for the instance fleet, which determines how many On-Demand instances to provision. /// </summary> public readonly int? TargetOnDemandCapacity; /// <summary> /// The target capacity of Spot units for the instance fleet, which determines how many Spot instances to provision. /// </summary> public readonly int? TargetSpotCapacity; [OutputConstructor] private ClusterCoreInstanceFleet( string? id, ImmutableArray<Outputs.ClusterCoreInstanceFleetInstanceTypeConfig> instanceTypeConfigs, Outputs.ClusterCoreInstanceFleetLaunchSpecifications? launchSpecifications, string? name, int? provisionedOnDemandCapacity, int? provisionedSpotCapacity, int? targetOnDemandCapacity, int? targetSpotCapacity) { Id = id; InstanceTypeConfigs = instanceTypeConfigs; LaunchSpecifications = launchSpecifications; Name = name; ProvisionedOnDemandCapacity = provisionedOnDemandCapacity; ProvisionedSpotCapacity = provisionedSpotCapacity; TargetOnDemandCapacity = targetOnDemandCapacity; TargetSpotCapacity = targetSpotCapacity; } } }
35.694444
134
0.661089
[ "ECL-2.0", "Apache-2.0" ]
Otanikotani/pulumi-aws
sdk/dotnet/Emr/Outputs/ClusterCoreInstanceFleet.cs
2,570
C#
using System.IO; using Path = System.IO.Path; namespace Nicodemus.Controls { public delegate void FileAvailableDelegate(object source, FileAvailableEventArgs args); public class FileAvailableEventArgs { public FileStream FileStream { get; set; } public string FileName { get; set; } public string Extension { get { var extension = Path.GetExtension(FileName); return extension?.Replace(".", ""); } } public FileAvailableEventArgs(FileStream fileStream, string fileName) { FileStream = fileStream; FileName = fileName; } } }
21.363636
91
0.578723
[ "MIT" ]
tessin/Nicodemus.Controls
Nicodemus.Controls/Files/FileAvailableEventArgs.cs
707
C#
using Chloe; using Chloe.Core; using Chloe.PostgreSQL; using Chloe.SqlServer; using Database; using System; using System.Collections.Generic; using System.Data; using System.Linq; using System.Linq.Expressions; using System.Text; using System.Threading.Tasks; namespace ChloeDemo { //[TestClass] public class PostgreSQLDemo { /* WARNING: DbContext 是非线程安全的,正式使用不能设置为 static,并且用完务必要调用 Dispose 方法销毁对象 */ static string ConnString = "User ID=postgres;Password=sa;Host=localhost;Port=5432;Database=chloe;Pooling=true;"; static PostgreSQLContext context = new PostgreSQLContext(new PostgreSQLConnectionFactory(ConnString)); public static void Run() { BasicQuery(); JoinQuery(); AggregateQuery(); GroupQuery(); ComplexQuery(); Insert(); InsertRange(); Update(); Delete(); Method(); ExecuteCommandText(); DoWithTransaction(); DoWithTransactionEx(); ConsoleHelper.WriteLineAndReadKey(); } public static void BasicQuery() { IQuery<User> q = context.Query<User>(); q.Where(a => a.Id == 1).FirstOrDefault(); /* * */ //可以选取指定的字段 q.Where(a => a.Id == 1).Select(a => new { a.Id, a.Name }).FirstOrDefault(); /* * */ //分页 q.Where(a => a.Id > 0).OrderBy(a => a.Age).Skip(20).Take(10).ToList(); /* * */ /* like 查询 */ q.Where(a => a.Name.Contains("so") || a.Name.StartsWith("s") || a.Name.EndsWith("o")).ToList(); /* * */ /* in 一个数组 */ List<User> users = null; List<int> userIds = new List<int>() { 1, 2, 3 }; users = q.Where(a => userIds.Contains(a.Id)).ToList(); /* list.Contains() 方法组合就会生成 in一个数组 sql 语句 */ /* * */ /* in 子查询 */ users = q.Where(a => context.Query<City>().Select(c => c.Id).ToList().Contains((int)a.CityId)).ToList(); /* IQuery<T>.ToList().Contains() 方法组合就会生成 in 子查询 sql 语句 */ /* * */ /* distinct 查询 */ q.Select(a => new { a.Name }).Distinct().ToList(); /* * */ ConsoleHelper.WriteLineAndReadKey(); } public static void JoinQuery() { //建立连接 var user_city_province = context.Query<User>() .InnerJoin<City>((user, city) => user.CityId == city.Id) .InnerJoin<Province>((user, city, province) => city.ProvinceId == province.Id); //查出用户及其隶属的城市和省份的所有信息 var view = user_city_province.Select((user, city, province) => new { User = user, City = city, Province = province }).Where(a => a.User.Id > 1).ToList(); /* * */ //也可以只获取指定的字段信息:UserId,UserName,CityName,ProvinceName user_city_province.Select((user, city, province) => new { UserId = user.Id, UserName = user.Name, CityName = city.Name, ProvinceName = province.Name }).Where(a => a.UserId > 1).ToList(); /* * */ /* quick join and paging. */ context.JoinQuery<User, City>((user, city) => new object[] { JoinType.LeftJoin, user.CityId == city.Id }) .Select((user, city) => new { User = user, City = city }) .Where(a => a.User.Id > -1) .OrderByDesc(a => a.User.Age) .TakePage(1, 20) .ToList(); context.JoinQuery<User, City, Province>((user, city, province) => new object[] { JoinType.LeftJoin, user.CityId == city.Id, /* 表 User 和 City 进行Left连接 */ JoinType.LeftJoin, city.ProvinceId == province.Id /* 表 City 和 Province 进行Left连接 */ }) .Select((user, city, province) => new { User = user, City = city, Province = province }) /* 投影成匿名对象 */ .Where(a => a.User.Id > -1) /* 进行条件过滤 */ .OrderByDesc(a => a.User.Age) /* 排序 */ .TakePage(1, 20) /* 分页 */ .ToList(); ConsoleHelper.WriteLineAndReadKey(); } public static void AggregateQuery() { IQuery<User> q = context.Query<User>(); q.Select(a => Sql.Count()).First(); /* * */ q.Select(a => new { Count = Sql.Count(), LongCount = Sql.LongCount(), Sum = Sql.Sum(a.Age), Max = Sql.Max(a.Age), Min = Sql.Min(a.Age), Average = Sql.Average(a.Age) }).First(); /* * */ var count = q.Count(); /* * */ var longCount = q.LongCount(); /* * */ var sum = q.Sum(a => a.Age); /* * */ var max = q.Max(a => a.Age); /* * */ var min = q.Min(a => a.Age); /* * */ var avg = q.Average(a => a.Age); /* * */ ConsoleHelper.WriteLineAndReadKey(); } public static void GroupQuery() { IQuery<User> q = context.Query<User>(); IGroupingQuery<User> g = q.Where(a => a.Id > 0).GroupBy(a => a.Age); g = g.Having(a => a.Age > 1 && Sql.Count() > 0); g.Select(a => new { a.Age, Count = Sql.Count(), Sum = Sql.Sum(a.Age), Max = Sql.Max(a.Age), Min = Sql.Min(a.Age), Avg = Sql.Average(a.Age) }).ToList(); /* * */ ConsoleHelper.WriteLineAndReadKey(); } /*复杂查询*/ public static void ComplexQuery() { /* * 支持 select * from Users where CityId in (1,2,3) --in一个数组 * 支持 select * from Users where CityId in (select Id from City) --in子查询 * 支持 select * from Users exists (select 1 from City where City.Id=Users.CityId) --exists查询 * 支持 select (select top 1 CityName from City where Users.CityId==City.Id) as CityName, Users.Id, Users.Name from Users --select子查询 * 支持 select * (select count(*) from Users where Users.CityId=City.Id) as UserCount, --总数 * (select max(Users.Age) from Users where Users.CityId=City.Id) as MaxAge, --最大年龄 * (select avg(Users.Age) from Users where Users.CityId=City.Id) as AvgAge --平均年龄 * from City * --统计查询 */ IQuery<User> userQuery = context.Query<User>(); IQuery<City> cityQuery = context.Query<City>(); List<User> users = null; /* in 一个数组 */ List<int> userIds = new List<int>() { 1, 2, 3 }; users = userQuery.Where(a => userIds.Contains(a.Id)).ToList(); /* list.Contains() 方法组合就会生成 in一个数组 sql 语句 */ /* * */ /* in 子查询 */ users = userQuery.Where(a => cityQuery.Select(c => c.Id).ToList().Contains((int)a.CityId)).ToList(); /* IQuery<T>.ToList().Contains() 方法组合就会生成 in 子查询 sql 语句 */ /* * */ /* IQuery<T>.Any() 方法组合就会生成 exists 子查询 sql 语句 */ users = userQuery.Where(a => cityQuery.Where(c => c.Id == a.CityId).Any()).ToList(); /* * */ /* select 子查询 */ var result = userQuery.Select(a => new { CityName = cityQuery.Where(c => c.Id == a.CityId).First().Name, User = a }).ToList(); /* * */ /* 统计 */ var statisticsResult = cityQuery.Select(a => new { UserCount = userQuery.Where(u => u.CityId == a.Id).Count(), MaxAge = userQuery.Where(u => u.CityId == a.Id).Max(c => c.Age), AvgAge = userQuery.Where(u => u.CityId == a.Id).Average(c => c.Age), }).ToList(); /* * */ ConsoleHelper.WriteLineAndReadKey(); } public static void Insert() { //返回主键 Id int id = (int)context.Insert<User>(() => new User() { Name = "lu", Age = 18, Gender = Gender.Man, CityId = 1, OpTime = DateTime.Now }); /* * */ User user = new User(); user.Name = "lu"; user.Age = 18; user.Gender = Gender.Man; user.CityId = 1; user.OpTime = DateTime.Now; //会自动将自增 Id 设置到 user 的 Id 属性上 user = context.Insert(user); /* * */ ConsoleHelper.WriteLineAndReadKey(); } public static void InsertRange() { List<User> models = new List<User>(); models.Add(new User() { Name = "lu", Age = 18, Gender = Gender.Woman, CityId = 1, OpTime = DateTime.Now }); models.Add(new User() { Name = "shuxin", Age = 18, Gender = Gender.Man, CityId = 1, OpTime = DateTime.Now }); context.InsertRange(models); ConsoleHelper.WriteLineAndReadKey(1); } public static void Update() { context.Update<User>(a => a.Id == 1, a => new User() { Name = a.Name, Age = a.Age + 1, Gender = Gender.Man, OpTime = DateTime.Now }); /* * */ //批量更新 //给所有女性年轻 1 岁 context.Update<User>(a => a.Gender == Gender.Woman, a => new User() { Age = a.Age - 1, OpTime = DateTime.Now }); /* * */ User user = new User(); user.Id = 1; user.Name = "lu"; user.Age = 28; user.Gender = Gender.Man; user.OpTime = DateTime.Now; context.Update(user); //会更新所有映射的字段 /* * */ /* * 支持只更新属性值已变的属性 */ context.TrackEntity(user);//在上下文中跟踪实体 user.Name = user.Name + "1"; context.Update(user);//这时只会更新被修改的字段 /* * */ ConsoleHelper.WriteLineAndReadKey(); } public static void Delete() { context.Delete<User>(a => a.Id == 1); /* * */ //批量删除 //删除所有不男不女的用户 context.Delete<User>(a => a.Gender == null); /* * */ User user = new User(); user.Id = 1; context.Delete(user); /* * */ ConsoleHelper.WriteLineAndReadKey(1); } public static void Method() { IQuery<User> q = context.Query<User>(); var space = new char[] { ' ' }; DateTime startTime = DateTime.Now; DateTime endTime = DateTime.Now.AddDays(1); var result = q.Select(a => new { Id = a.Id, CustomFunction = DbFunctions.MyFunction(a.Id), //自定义函数 String_Length = (int?)a.Name.Length,// Substring = a.Name.Substring(0),// Substring1 = a.Name.Substring(1),// Substring1_2 = a.Name.Substring(1, 2),// ToLower = a.Name.ToLower(),// ToUpper = a.Name.ToUpper(),// IsNullOrEmpty = string.IsNullOrEmpty(a.Name),// Contains = (bool?)a.Name.Contains("s"),// Trim = a.Name.Trim(),// TrimStart = a.Name.TrimStart(space),// TrimEnd = a.Name.TrimEnd(space),// StartsWith = (bool?)a.Name.StartsWith("s"),// EndsWith = (bool?)a.Name.EndsWith("s"),// Replace = a.Name.Replace("l", "L"), DateTimeSubtract = endTime.Subtract(startTime), /* pgsql does not support Sql.DiffXX methods. */ //DiffYears = Sql.DiffYears(startTime, endTime),//DATEDIFF(YEAR,@P_0,@P_1) //DiffMonths = Sql.DiffMonths(startTime, endTime),//DATEDIFF(MONTH,@P_0,@P_1) //DiffDays = Sql.DiffDays(startTime, endTime),//DATEDIFF(DAY,@P_0,@P_1) //DiffHours = Sql.DiffHours(startTime, endTime),//DATEDIFF(HOUR,@P_0,@P_1) //DiffMinutes = Sql.DiffMinutes(startTime, endTime),//DATEDIFF(MINUTE,@P_0,@P_1) //DiffSeconds = Sql.DiffSeconds(startTime, endTime),//DATEDIFF(SECOND,@P_0,@P_1) //DiffMilliseconds = Sql.DiffMilliseconds(startTime, endTime),//DATEDIFF(MILLISECOND,@P_0,@P_1) //DiffMicroseconds = Sql.DiffMicroseconds(startTime, endTime),//DATEDIFF(MICROSECOND,@P_0,@P_1) Exception AddYears = startTime.AddYears(1),// AddMonths = startTime.AddMonths(1),// AddDays = startTime.AddDays(1),// AddHours = startTime.AddHours(1),// AddMinutes = startTime.AddMinutes(2),// AddSeconds = startTime.AddSeconds(120),// AddMilliseconds = startTime.AddMilliseconds(20000),// Now = DateTime.Now,//NOW() //UtcNow = DateTime.UtcNow,//GETUTCDATE() Today = DateTime.Today,// Date = DateTime.Now.Date,// Year = DateTime.Now.Year,// Month = DateTime.Now.Month,// Day = DateTime.Now.Day,// Hour = DateTime.Now.Hour,// Minute = DateTime.Now.Minute,// Second = DateTime.Now.Second,// Millisecond = DateTime.Now.Millisecond,// DayOfWeek = DateTime.Now.DayOfWeek,// Int_Parse = int.Parse("32"),// Int16_Parse = Int16.Parse("16"),// Long_Parse = long.Parse("64"),// Double_Parse = double.Parse("3.123"),// Float_Parse = float.Parse("4.123"),// Decimal_Parse = decimal.Parse("5.123"),// //Guid_Parse = Guid.Parse("D544BC4C-739E-4CD3-A3D3-7BF803FCE179"),// Bool_Parse = bool.Parse("1"),// DateTime_Parse = DateTime.Parse("1992-1-16"),// B = a.Age == null ? false : a.Age > 1, //三元表达式 CaseWhen = Case.When(a.Id > 100).Then(1).Else(0) //case when }).ToList(); ConsoleHelper.WriteLineAndReadKey(); } public static void ExecuteCommandText() { List<User> users = context.SqlQuery<User>("select * from Users where Age > @age", DbParam.Create("@age", 12)).ToList(); int rowsAffected = context.Session.ExecuteNonQuery("update Users set name=@name where Id = 1", DbParam.Create("@name", "Chloe")); /* * 执行存储过程: * User user = context.SqlQuery<User>("Proc_GetUser", CommandType.StoredProcedure, DbParam.Create("@id", 1)).FirstOrDefault(); * rowsAffected = context.Session.ExecuteNonQuery("Proc_UpdateUserName", CommandType.StoredProcedure, DbParam.Create("@name", "Chloe")); */ ConsoleHelper.WriteLineAndReadKey(); } public static void DoWithTransactionEx() { context.UseTransaction(() => { context.Update<User>(a => a.Id == 1, a => new User() { Name = a.Name, Age = a.Age + 1, Gender = Gender.Man, OpTime = DateTime.Now }); context.Delete<User>(a => a.Id == 1024); }); ConsoleHelper.WriteLineAndReadKey(); } public static void DoWithTransaction() { context.Session.BeginTransaction(); try { /* do some things here */ context.Update<User>(a => a.Id == 1, a => new User() { Name = a.Name, Age = a.Age + 1, Gender = Gender.Man, OpTime = DateTime.Now }); context.Delete<User>(a => a.Id == 1024); context.Session.CommitTransaction(); } catch { if (context.Session.IsInTransaction) context.Session.RollbackTransaction(); throw; } ConsoleHelper.WriteLineAndReadKey(); } } }
33.983903
198
0.469568
[ "MIT" ]
1163891508/Chloe
src/ChloeDemo/PostgreSQLDemo.cs
17,580
C#
using System; using System.Diagnostics; using System.Resources; using System.Windows; using System.Windows.Markup; using System.Windows.Navigation; using Microsoft.Phone.Controls; using Microsoft.Phone.Shell; using Unity.Tests.WindowsPhone.Resources; namespace Unity.Tests.WindowsPhone { public partial class App : Application { /// <summary> /// Provides easy access to the root frame of the Phone Application. /// </summary> /// <returns>The root frame of the Phone Application.</returns> public static PhoneApplicationFrame RootFrame { get; private set; } /// <summary> /// Constructor for the Application object. /// </summary> public App() { // Global handler for uncaught exceptions. UnhandledException += Application_UnhandledException; // Standard XAML initialization InitializeComponent(); // Phone-specific initialization InitializePhoneApplication(); // Language display initialization InitializeLanguage(); // Show graphics profiling information while debugging. if (Debugger.IsAttached) { // Display the current frame rate counters. Application.Current.Host.Settings.EnableFrameRateCounter = true; // Show the areas of the app that are being redrawn in each frame. //Application.Current.Host.Settings.EnableRedrawRegions = true; // Enable non-production analysis visualization mode, // which shows areas of a page that are handed off to GPU with a colored overlay. //Application.Current.Host.Settings.EnableCacheVisualization = true; // Prevent the screen from turning off while under the debugger by disabling // the application's idle detection. // Caution:- Use this under debug mode only. Application that disables user idle detection will continue to run // and consume battery power when the user is not using the phone. PhoneApplicationService.Current.UserIdleDetectionMode = IdleDetectionMode.Disabled; } } // Code to execute when the application is launching (eg, from Start) // This code will not execute when the application is reactivated private void Application_Launching(object sender, LaunchingEventArgs e) { } // Code to execute when the application is activated (brought to foreground) // This code will not execute when the application is first launched private void Application_Activated(object sender, ActivatedEventArgs e) { } // Code to execute when the application is deactivated (sent to background) // This code will not execute when the application is closing private void Application_Deactivated(object sender, DeactivatedEventArgs e) { } // Code to execute when the application is closing (eg, user hit Back) // This code will not execute when the application is deactivated private void Application_Closing(object sender, ClosingEventArgs e) { } // Code to execute if a navigation fails private void RootFrame_NavigationFailed(object sender, NavigationFailedEventArgs e) { if (Debugger.IsAttached) { // A navigation has failed; break into the debugger Debugger.Break(); } } // Code to execute on Unhandled Exceptions private void Application_UnhandledException(object sender, ApplicationUnhandledExceptionEventArgs e) { if (Debugger.IsAttached) { // An unhandled exception has occurred; break into the debugger Debugger.Break(); } } #region Phone application initialization // Avoid double-initialization private bool phoneApplicationInitialized = false; // Do not add any additional code to this method private void InitializePhoneApplication() { if (phoneApplicationInitialized) return; // Create the frame but don't set it as RootVisual yet; this allows the splash // screen to remain active until the application is ready to render. RootFrame = new PhoneApplicationFrame(); RootFrame.Navigated += CompleteInitializePhoneApplication; // Handle navigation failures RootFrame.NavigationFailed += RootFrame_NavigationFailed; // Handle reset requests for clearing the backstack RootFrame.Navigated += CheckForResetNavigation; // Ensure we don't initialize again phoneApplicationInitialized = true; } // Do not add any additional code to this method private void CompleteInitializePhoneApplication(object sender, NavigationEventArgs e) { // Set the root visual to allow the application to render if (RootVisual != RootFrame) RootVisual = RootFrame; // Remove this handler since it is no longer needed RootFrame.Navigated -= CompleteInitializePhoneApplication; } private void CheckForResetNavigation(object sender, NavigationEventArgs e) { // If the app has received a 'reset' navigation, then we need to check // on the next navigation to see if the page stack should be reset if (e.NavigationMode == NavigationMode.Reset) RootFrame.Navigated += ClearBackStackAfterReset; } private void ClearBackStackAfterReset(object sender, NavigationEventArgs e) { // Unregister the event so it doesn't get called again RootFrame.Navigated -= ClearBackStackAfterReset; // Only clear the stack for 'new' (forward) and 'refresh' navigations if (e.NavigationMode != NavigationMode.New && e.NavigationMode != NavigationMode.Refresh) return; // For UI consistency, clear the entire page stack while (RootFrame.RemoveBackEntry() != null) { ; // do nothing } } #endregion // Initialize the app's font and flow direction as defined in its localized resource strings. // // To ensure that the font of your application is aligned with its supported languages and that the // FlowDirection for each of those languages follows its traditional direction, ResourceLanguage // and ResourceFlowDirection should be initialized in each resx file to match these values with that // file's culture. For example: // // AppResources.es-ES.resx // ResourceLanguage's value should be "es-ES" // ResourceFlowDirection's value should be "LeftToRight" // // AppResources.ar-SA.resx // ResourceLanguage's value should be "ar-SA" // ResourceFlowDirection's value should be "RightToLeft" // // For more info on localizing Windows Phone apps see http://go.microsoft.com/fwlink/?LinkId=262072. // private void InitializeLanguage() { try { // Set the font to match the display language defined by the // ResourceLanguage resource string for each supported language. // // Fall back to the font of the neutral language if the Display // language of the phone is not supported. // // If a compiler error is hit then ResourceLanguage is missing from // the resource file. RootFrame.Language = XmlLanguage.GetLanguage(AppResources.ResourceLanguage); // Set the FlowDirection of all elements under the root frame based // on the ResourceFlowDirection resource string for each // supported language. // // If a compiler error is hit then ResourceFlowDirection is missing from // the resource file. FlowDirection flow = (FlowDirection)Enum.Parse(typeof(FlowDirection), AppResources.ResourceFlowDirection); RootFrame.FlowDirection = flow; } catch { // If an exception is caught here it is most likely due to either // ResourceLangauge not being correctly set to a supported language // code or ResourceFlowDirection is set to a value other than LeftToRight // or RightToLeft. if (Debugger.IsAttached) { Debugger.Break(); } throw; } } } }
40.61435
127
0.614773
[ "Apache-2.0", "MIT" ]
drcarver/unity
BVT/Unity.Tests.WindowsPhone/Unity.Tests.WindowsPhone/App.xaml.cs
9,059
C#
namespace GoCardlessApi.Http.Serialisation { public static class DateFormat { public const string IsoDateFormat = "yyyy-MM-dd"; } }
21.714286
57
0.684211
[ "MIT" ]
john-hartley/GoCardless.Api
src/GoCardless.Api/Http/Serialisation/DateFormat.cs
154
C#
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. using System; using System.Collections.Generic; using System.Threading.Tasks; using NUnit.Framework; namespace Azure.AI.TextAnalytics.Samples { public partial class TextAnalyticsSamples : TextAnalyticsSampleBase { [Test] public async Task AnalyzeHealthcareEntitiesAsync() { // create a text analytics client string endpoint = TestEnvironment.Endpoint; string apiKey = TestEnvironment.ApiKey; var client = new TextAnalyticsClient(new Uri(endpoint), new AzureKeyCredential(apiKey), CreateSampleOptions()); // get input documents string document1 = @"RECORD #333582770390100 | MH | 85986313 | | 054351 | 2/14/2001 12:00:00 AM | CORONARY ARTERY DISEASE | Signed | DIS | Admission Date: 5/22/2001 Report Status: Signed Discharge Date: 4/24/2001 ADMISSION DIAGNOSIS: CORONARY ARTERY DISEASE. HISTORY OF PRESENT ILLNESS: The patient is a 54-year-old gentleman with a history of progressive angina over the past several months. The patient had a cardiac catheterization in July of this year revealing total occlusion of the RCA and 50% left main disease ,\ with a strong family history of coronary artery disease with a brother dying at the age of 52 from a myocardial infarction and \ another brother who is status post coronary artery bypass grafting. The patient had a stress echocardiogram done on July , 2001 , \ which showed no wall motion abnormalities , but this was a difficult study due to body habitus. The patient went for six minutes with \ minimal ST depressions in the anterior lateral leads , thought due to fatigue and wrist pain , his anginal equivalent. Due to the patient's \ increased symptoms and family history and history left main disease with total occasional of his RCA was referred for revascularization with open heart surgery."; string document2 = "Prescribed 100mg ibuprofen, taken twice daily."; // prepare analyze operation input List<TextDocumentInput> batchInput = new List<TextDocumentInput>() { new TextDocumentInput("1", document1) { Language = "en" }, new TextDocumentInput("2", document2) { Language = "en" } }; AnalyzeHealthcareEntitiesOptions options = new AnalyzeHealthcareEntitiesOptions() { IncludeStatistics = true }; // start analysis process AnalyzeHealthcareEntitiesOperation healthOperation = await client.StartAnalyzeHealthcareEntitiesAsync(batchInput, options); await healthOperation.WaitForCompletionAsync(); // view operation status Console.WriteLine($"AnalyzeHealthcareEntities operation was completed"); Console.WriteLine($"Created On : {healthOperation.CreatedOn}"); Console.WriteLine($"Expires On : {healthOperation.ExpiresOn}"); Console.WriteLine($"Id : {healthOperation.Id}"); Console.WriteLine($"Status : {healthOperation.Status}"); Console.WriteLine($"Last Modified: {healthOperation.LastModified}"); // view operation results foreach (AnalyzeHealthcareEntitiesResultCollection documentsInPage in healthOperation.GetValues()) { Console.WriteLine($"Results of \"Healthcare\" Model, version: \"{documentsInPage.ModelVersion}\""); Console.WriteLine(""); int i = 0; foreach (AnalyzeHealthcareEntitiesResult result in documentsInPage) { TextDocumentInput document = batchInput[i++]; Console.WriteLine($"On document (Id={document.Id}, Language=\"{document.Language}\"):"); if (result.HasError) { Console.WriteLine(" Error!"); Console.WriteLine($" Document error code: {result.Error.ErrorCode}."); Console.WriteLine($" Message: {result.Error.Message}"); } else { Console.WriteLine($" Recognized the following {result.Entities.Count} healthcare entities:"); // view recognized healthcare entities foreach (HealthcareEntity entity in result.Entities) { Console.WriteLine($" Entity: {entity.Text}"); Console.WriteLine($" Category: {entity.Category}"); Console.WriteLine($" Offset: {entity.Offset}"); Console.WriteLine($" Length: {entity.Length}"); Console.WriteLine($" NormalizedText: {entity.NormalizedText}"); Console.WriteLine($" Links:"); // view entity data sources foreach (EntityDataSource entityDataSource in entity.DataSources) { Console.WriteLine($" Entity ID in Data Source: {entityDataSource.EntityId}"); Console.WriteLine($" DataSource: {entityDataSource.Name}"); } // view assertion if (entity.Assertion != null) { Console.WriteLine($" Assertions:"); if (entity.Assertion?.Association != null) { Console.WriteLine($" Association: {entity.Assertion?.Association}"); } if (entity.Assertion?.Certainty != null) { Console.WriteLine($" Certainty: {entity.Assertion?.Certainty}"); } if (entity.Assertion?.Conditionality != null) { Console.WriteLine($" Conditionality: {entity.Assertion?.Conditionality}"); } } } Console.WriteLine($" We found {result.EntityRelations.Count} relations in the current document:"); Console.WriteLine(""); // view recognized healthcare relations foreach (HealthcareEntityRelation relations in result.EntityRelations) { Console.WriteLine($" Relation: {relations.RelationType}"); Console.WriteLine($" For this relation there are {relations.Roles.Count} roles"); // view relation roles foreach (HealthcareEntityRelationRole role in relations.Roles) { Console.WriteLine($" Role Name: {role.Name}"); Console.WriteLine($" Associated Entity Text: {role.Entity.Text}"); Console.WriteLine($" Associated Entity Category: {role.Entity.Category}"); Console.WriteLine(""); } Console.WriteLine(""); } Console.WriteLine(""); } // current document statistics Console.WriteLine($" Document statistics:"); Console.WriteLine($" Character count (in Unicode graphemes): {result.Statistics.CharacterCount}"); Console.WriteLine($" Transaction count: {result.Statistics.TransactionCount}"); Console.WriteLine(""); } // view statistics about documents in current page Console.WriteLine($"Batch operation statistics:"); Console.WriteLine($" Document count: {documentsInPage.Statistics.DocumentCount}"); Console.WriteLine($" Valid document count: {documentsInPage.Statistics.ValidDocumentCount}"); Console.WriteLine($" Invalid document count: {documentsInPage.Statistics.InvalidDocumentCount}"); Console.WriteLine($" Transaction count: {documentsInPage.Statistics.TransactionCount}"); } } } }
52.988304
194
0.52886
[ "MIT" ]
damodaravadhani/azure-sdk-for-net
sdk/textanalytics/Azure.AI.TextAnalytics/tests/samples/Sample7_AnalyzeHealthcareEntitiesAsync.cs
9,063
C#
namespace Firebase.Storage { using Newtonsoft.Json; using System; using System.Collections.Generic; using System.IO; using System.Net.Http; using System.Net.Http.Headers; using System.Runtime.CompilerServices; using System.Threading; using System.Threading.Tasks; public class FirebaseStorageTask { private const int ProgressReportDelayMiliseconds = 500; private readonly Task<string> uploadTask; private readonly Stream stream; public FirebaseStorageTask(FirebaseStorageOptions options, string url, string downloadUrl, Stream stream, CancellationToken cancellationToken, string mimeType = null) { this.TargetUrl = url; this.uploadTask = this.UploadFile(options, url, downloadUrl, stream, cancellationToken, mimeType); this.stream = stream; this.Progress = new Progress<FirebaseStorageProgress>(); Task.Factory.StartNew(this.ReportProgressLoop); } public Progress<FirebaseStorageProgress> Progress { get; private set; } public string TargetUrl { get; private set; } public TaskAwaiter<string> GetAwaiter() { return this.uploadTask.GetAwaiter(); } private async Task<string> UploadFile(FirebaseStorageOptions options, string url, string downloadUrl, Stream stream, CancellationToken cancellationToken, string mimeType = null) { var responseData = "N/A"; try { using (var client = await options.CreateHttpClientAsync()) { var request = new HttpRequestMessage(HttpMethod.Post, url) { Content = new StreamContent(stream) }; if (!string.IsNullOrEmpty(mimeType)) { request.Content.Headers.ContentType = new MediaTypeHeaderValue(mimeType); } var response = await client.SendAsync(request, cancellationToken).ConfigureAwait(false); responseData = await response.Content.ReadAsStringAsync().ConfigureAwait(false); response.EnsureSuccessStatusCode(); var data = JsonConvert.DeserializeObject<Dictionary<string, object>>(responseData); return downloadUrl + data["downloadTokens"]; } } catch (TaskCanceledException) { if (options.ThrowOnCancel) { throw; } return string.Empty; } catch (Exception ex) { throw new FirebaseStorageException(url, responseData, ex); } } private async void ReportProgressLoop() { while (!this.uploadTask.IsCompleted) { await Task.Delay(ProgressReportDelayMiliseconds); try { this.OnReportProgress(new FirebaseStorageProgress(this.stream.Position, this.stream.Length)); } catch (ObjectDisposedException) { // there is no 100 % way to prevent ObjectDisposedException, there are bound to be concurrency issues. return; } } } private void OnReportProgress(FirebaseStorageProgress progress) { (this.Progress as IProgress<FirebaseStorageProgress>).Report(progress); } } }
32.614035
185
0.559172
[ "MIT" ]
StephenHodgson/firebase-storage-dotnet
src/Firebase.Storage/FirebaseStorageTask.cs
3,720
C#
using System; using System.ComponentModel.DataAnnotations; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Hosting; using Microsoft.OpenApi.Models; using submissions.Data; using submissions.Services; namespace submissions { 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.AddControllers(); services.AddSwaggerGen(c => { c.SwaggerDoc("v1", new OpenApiInfo { Title = "submissions", Version = "v1" }); }); services.AddDbContext<CosmosContext>( options => { // Read sectionName from file and set cosmos connection // TODO: Rewrite this with IConfiguration.Validate... ICosmosSettings cosmosSettings = new CosmosSettings(); string sectionName = nameof(CosmosSettings); var section = Configuration.GetSection(sectionName); if (!section.Exists()) { System.Diagnostics.Trace.TraceError("Section for cosmos settings doesn't exist"); throw new ArgumentException($"Section {sectionName} doesn't exist, or is empty"); } section.Bind(cosmosSettings); Validator.ValidateObject(cosmosSettings, new ValidationContext(cosmosSettings), true); options.UseCosmos(cosmosSettings.ConnectionString, cosmosSettings.DatabaseName); // TODO: Delete //options.LogTo(Console.WriteLine); }); services.AddSingleton<StorageService>(); } // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IWebHostEnvironment env, CosmosContext cosmosContext) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); app.UseSwagger(); app.UseSwaggerUI(c => c.SwaggerEndpoint("/swagger/v1/swagger.json", "submissions v1")); } app.UseRouting(); app.UseAuthorization(); app.UseEndpoints(endpoints => { endpoints.MapControllers(); }); // Custom setup cosmosContext.Database.EnsureCreated(); } } }
36.333333
108
0.593272
[ "MIT" ]
cppseminar/APC
cppseminar/submissions/Startup.cs
2,943
C#
// Copyright (c) Microsoft Open Technologies, Inc. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using System.Runtime.Serialization; namespace Microsoft.CodeAnalysis { /// <summary> /// Represents parse options common to C# and VB. /// </summary> [Serializable] public abstract class SerializableParseOptions : ISerializable { internal SerializableParseOptions() { } public ParseOptions Options { get { return CommonOptions; } } protected abstract ParseOptions CommonOptions { get; } public abstract void GetObjectData(SerializationInfo info, StreamingContext context); protected static void CommonGetObjectData(ParseOptions options, SerializationInfo info, StreamingContext context) { //public readonly SourceCodeKind Kind; info.AddValue("Kind", options.Kind, typeof(SourceCodeKind)); //public readonly DocumentationMode DocumentationMode; info.AddValue("DocumentationMode", options.DocumentationMode, typeof(DocumentationMode)); } } }
36.151515
184
0.700754
[ "Apache-2.0" ]
enginekit/copy_of_roslyn
Src/Compilers/Core/Desktop/SerializableParseOptions.cs
1,195
C#
using System; using System.Windows.Forms; using System.ComponentModel; using System.ComponentModel.Design; using System.Windows.Forms.Design; namespace PX.HMRC { // This allows us to use the Windows Collection Editor outside of the Properties Control public class ColEditor<T> { public DialogResult ShowDialog(T lst) { CollectionEditor c = new CollectionEditor(typeof(T)); RuntimeServiceProvider serviceProvider = new RuntimeServiceProvider(); c.EditValue(serviceProvider, serviceProvider, lst); return serviceProvider.windowsFormsEditorService.DialogResult; } } public class RuntimeServiceProvider : IServiceProvider, ITypeDescriptorContext { #region IServiceProvider Members public WindowsFormsEditorService windowsFormsEditorService; object IServiceProvider.GetService(Type serviceType) { if (serviceType == typeof(IWindowsFormsEditorService)) { windowsFormsEditorService = new WindowsFormsEditorService(); return windowsFormsEditorService; } return null; } public class WindowsFormsEditorService : IWindowsFormsEditorService { #region IWindowsFormsEditorService Members public DialogResult DialogResult = DialogResult.None; public void DropDownControl(Control control) { } public void CloseDropDown() { } public System.Windows.Forms.DialogResult ShowDialog(Form dialog) { ((System.Windows.Forms.Button)dialog.Controls.Find("okButton", true)[0]).Click += WindowsFormsEditorService_Click; return dialog.ShowDialog(); } private void WindowsFormsEditorService_Click(object sender, EventArgs e) { DialogResult = DialogResult.OK; } #endregion } #endregion #region ITypeDescriptorContext Members public void OnComponentChanged() { } public IContainer Container { get { return null; } } public bool OnComponentChanging() { return true; // true to keep changes, otherwise false } public object Instance { get { return null; } } public PropertyDescriptor PropertyDescriptor { get { return null; } } #endregion } }
27.273684
130
0.60247
[ "MIT" ]
mPisano/MTDCompliance
PX.HMRC/RuntimeServiceProvider.cs
2,593
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("CPUusige")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("CPUusige")] [assembly: AssemblyCopyright("Copyright © 2018")] [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("eea2b491-93ee-4633-b5f6-11a7f4a11fd3")] // 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.405405
84
0.746387
[ "MIT" ]
VanHakobyan/Useful_Pieces_Of_Code
CPUusige/CPUusige/Properties/AssemblyInfo.cs
1,387
C#
#region License /* Copyright © 2014-2022 European Support Limited Licensed under the Apache License, Version 2.0 (the "License") you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ #endregion using Amdocs.Ginger.Common; using Amdocs.Ginger.Common.UIElement; using GingerCore; using System; using System.Collections.Generic; using System.ComponentModel; 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.Navigation; using System.Windows.Shapes; namespace Ginger.UserControlsLib { /// <summary> /// Interaction logic for LiveSpyHandler.xaml /// </summary> public partial class LiveSpyHandler : UserControl { public Agent DriverAgent { get; set; } public event PropertyChangedEventHandler PropertyChanged; private ElementInfo mSpySelectedElement = null; public ElementInfo SpySelectedElement { get { return mSpySelectedElement; } set { mSpySelectedElement = value; if (PropertyChanged != null) { PropertyChanged(this, new PropertyChangedEventArgs(nameof(SpySelectedElement))); } } } System.Windows.Threading.DispatcherTimer mDispatcherTimer = null; public IWindowExplorer mWinExplorer { get { if (DriverAgent != null && ((AgentOperations)DriverAgent.AgentOperations).Status == Agent.eStatus.Running) { return ((AgentOperations)DriverAgent.AgentOperations).Driver as IWindowExplorer; } else { if (DriverAgent != null) { DriverAgent.AgentOperations.Close(); } return null; } } } public LiveSpyHandler() { InitializeComponent(); } private void LiveSpyButton_Click(object sender, RoutedEventArgs e) { if (mWinExplorer == null) { Reporter.ToUser(eUserMsgKey.POMAgentIsNotRunning); xLiveSpyButton.IsChecked = false; return; } if (((AgentOperations)DriverAgent.AgentOperations).Driver.IsDriverBusy) { Reporter.ToUser(eUserMsgKey.POMDriverIsBusy); xLiveSpyButton.IsChecked = false; return; } if (xLiveSpyButton.IsChecked == true) { mWinExplorer.StartSpying(); xStatusLable.Content = "Spying is On"; if (mDispatcherTimer == null) { mDispatcherTimer = new System.Windows.Threading.DispatcherTimer(); mDispatcherTimer.Tick += GetElementInfoOnKeyPress; mDispatcherTimer.Interval = new TimeSpan(0, 0, 1); } mDispatcherTimer.IsEnabled = true; } else { xStatusLable.Content = "Spying is Off"; mDispatcherTimer.IsEnabled = false; } } private void GetElementInfoOnKeyPress(object sender, EventArgs e) { // Get control info only if control key is pressed if (Keyboard.IsKeyDown(Key.LeftCtrl) || Keyboard.IsKeyDown(Key.RightCtrl)) { SetLableStatusText("Spying element, please wait..."); GingerCore.General.DoEvents(); SpySelectedElement = mWinExplorer.GetControlFromMousePosition(); if (SpySelectedElement != null) { SpySelectedElement.WindowExplorer = mWinExplorer; SpySelectedElement.IsAutoLearned = true; mWinExplorer.HighLightElement(SpySelectedElement); } else { SetLableStatusText("Failed to spy element."); GingerCore.General.DoEvents(); } } } public void SetLableStatusText(string labelText) { xStatusLable.Content = labelText; GingerCore.General.DoEvents(); } } }
31.3
122
0.573882
[ "Apache-2.0" ]
FOSSAware/Ginger
Ginger/Ginger/UserControlsLib/LiveSpyHandler.xaml.cs
5,009
C#
using Elite_Hockey_Manager.Classes.GameComponents; using System; using System.Collections.Generic; using System.Linq; namespace Elite_Hockey_Manager.Classes.LeagueComponents { [Serializable] public class Schedule { #region Fields [NonSerialized] public List<TeamPair> _teamsList = new List<TeamPair>(); private List<Team> _firstConference; private int _maxGamesPerDay; private int _scheduleSize; private List<List<Game>> _seasonSchedule = new List<List<Game>>(); private List<Team> _secondConference; private Random rand; #endregion Fields #region Constructors public Schedule(List<Team> firstConference, List<Team> secondConference, Random random) { //Sets random to league-wide random rand = random; _firstConference = firstConference; _secondConference = secondConference; //Each team has 41 home games which accounts for every game of the season in an 82 game schedule _scheduleSize = (_firstConference.Count + _secondConference.Count) * 41; SetTeamsList(); SetMaxGamesInADay(); GenerateRegularSeason(); } #endregion Constructors #region Properties public int Length { get { return _seasonSchedule.Count; } } public List<List<Game>> SeasonSchedule { get { return _seasonSchedule; } } #endregion Properties #region Methods /// <summary> /// Function to force the etnire schedule to be simmed, used in case of error simming schedule /// </summary> public void ForceFinishSimming() { for (int i = 0; i < _seasonSchedule.Count; i++) { foreach (Game game in _seasonSchedule[i]) { if (!game.Finished) { game.PlayGame(); } } } } /// <summary> /// Function to determine if there are any games left to sim /// </summary> /// <returns>Return boolean of if the schedule is done being simmed /// True - League is done simming all games in this class /// False - League still needs to sim games /// </returns> public bool IsFinishedSimming() { for (int i = 0; i < _seasonSchedule.Count; i++) { foreach (Game game in _seasonSchedule[i]) { if (!game.Finished) { return false; } } } return true; } /// <summary> /// Gets the total of games that are not finished that are yet to be simmed or partially simmed /// </summary> /// <returns>Total number of games that need to be simmed</returns> public int RemainingGamesToSim(int dayIndex, int duration) { int totalGames = 0; //If simming rest of season with -1 key. Calculation duration of rest of league if (duration == -1) { duration = _seasonSchedule.Count - dayIndex; } for (int i = 0; i < duration; i++) { if (dayIndex + i >= _seasonSchedule.Count) { break; } foreach (Game game in _seasonSchedule[dayIndex + i]) { if (!game.Finished) { totalGames++; } } } return totalGames; } public void SimDay(int day) { if (day < 0 || day >= SeasonSchedule.Count) { throw new IndexOutOfRangeException("Day must be within the range of season length"); } foreach (Game game in SeasonSchedule[day]) { game.PlayGame(); } } /// <summary> /// Function to return total number of games scheduled for season /// </summary> /// <returns>Integer of number of games scheduled</returns> public int TotalGamesScheduled() { int totalGames = 0; foreach (List<Game> day in _seasonSchedule) { foreach (Game game in day) { totalGames++; } } return totalGames; } private TeamPair ChooseAwayTeam(List<TeamPair> awayTeams) { //Chooses a random team among the away teams list int choice = rand.Next(0, awayTeams.Count); TeamPair chosenTeam = awayTeams[choice]; //Removes chosen away team from the pool awayTeams.RemoveAt(choice); return chosenTeam; } private void FixOddTeamLeague(TeamPair lastTeam, ref int newGameNumber) { //home game missing while (lastTeam.counter.awayGamesScheduled != 41 && lastTeam.counter.homeGamesScheduled != 41) { for (int i = 0; i <= _seasonSchedule.Count; i++) { for (int j = 0; j < _seasonSchedule[i].Count; j++) { if (_seasonSchedule[i][j].HomeTeam != lastTeam.team && _seasonSchedule[i][j].AwayTeam != lastTeam.team) { Game game = _seasonSchedule[i][j]; Team homeTeam = game.HomeTeam; Team awayTeam = game.AwayTeam; int gameNumber = game.GameNumber; _seasonSchedule[i].RemoveAt(j); _seasonSchedule[i].Add(new Game(lastTeam.team, awayTeam, rand, gameNumber)); lastTeam.counter.homeGamesScheduled++; _seasonSchedule[i].Add(new Game(homeTeam, lastTeam.team, rand, newGameNumber)); newGameNumber++; lastTeam.counter.awayGamesScheduled++; i = _seasonSchedule.Count; break; } } } } } private void GenerateRegularSeason() { int gamesScheduled = 0; List<Game> daySchedule; while (gamesScheduled < _scheduleSize) { daySchedule = new List<Game>(); List<TeamPair> homeTeams = GetHomeTeams(); //If an odd number sized league ends up with one team having 40 home games and 40 away games //Bricks system in infinite loop otherwise if (_teamsList.Where(x => x.counter.homeGamesScheduled < 41 || x.counter.awayGamesScheduled < 41).ToList().Count == 1) { TeamPair brokenTeam = _teamsList.Where(x => x.counter.homeGamesScheduled < 41 || x.counter.awayGamesScheduled < 41).ToList().Last(); while (brokenTeam.counter.awayGamesScheduled < 41) { FixOddTeamLeague(brokenTeam, ref gamesScheduled); } } List<TeamPair> awayTeams = GetAwayTeams(homeTeams); for (int i = 0; i < homeTeams.Count; i++) { if (awayTeams.Count == 0) { continue; } TeamPair homeTeam = homeTeams[i]; TeamPair awayTeam = ChooseAwayTeam(awayTeams); daySchedule.Add(new Game(homeTeam.team, awayTeam.team, rand, gamesScheduled)); gamesScheduled++; homeTeam.counter.homeGamesScheduled++; awayTeam.counter.awayGamesScheduled++; } _seasonSchedule.Add(daySchedule); } } private List<TeamPair> GetAwayTeams(List<TeamPair> homeTeams) { List<TeamPair> onlyAwayTeams = _teamsList.Except(homeTeams).ToList(); List<TeamPair> awayTeams = onlyAwayTeams.Where(x => x.counter.awayGamesScheduled < 41).ToList(); for (int i = 0; ;) { if (i == homeTeams.Count) { break; } if (awayTeams.Count >= homeTeams.Count) { break; } if (homeTeams[i].counter.awayGamesScheduled < 41) { awayTeams.Add(homeTeams[i]); homeTeams.RemoveAt(i); } else { i++; } } /*while (awayTeams.Count < homeTeams.Count) { TeamPair transferTeam = homeTeams.Last(); awayTeams.Add(transferTeam); homeTeams.Remove(transferTeam); }*/ return awayTeams; } private List<TeamPair> GetHomeTeams() { //Takes only teams where they have played less than 41 home games List<TeamPair> homeTeams = _teamsList.Where(x => x.counter.homeGamesScheduled < 41) //Sorts by home games the team has played .OrderBy(x => x.counter.homeGamesScheduled) //Takes the max number of games that can be played in a day .Take(_maxGamesPerDay).ToList(); return homeTeams; } private void SetMaxGamesInADay() { //Half of the number of the teams in the league, rounds down int teamsCount = (_teamsList.Count / 2); if (teamsCount > 10) teamsCount = 10; _maxGamesPerDay = teamsCount; } private void SetTeamsList() { List<Team> allTeams = _firstConference.Concat(_secondConference).ToList(); foreach (Team team in allTeams) { _teamsList.Add(new TeamPair(team)); } } #endregion Methods } public class ScheduleCounter { #region Fields public int awayGamesScheduled; public int homeGamesScheduled; #endregion Fields } public class TeamPair { #region Fields public ScheduleCounter counter; public Team team; #endregion Fields #region Constructors public TeamPair(Team newTeam) { team = newTeam; counter = new ScheduleCounter(); } #endregion Constructors #region Methods public override string ToString() { return $"{team.TeamName} Home:{counter.homeGamesScheduled} Away:{counter.awayGamesScheduled}"; } #endregion Methods } }
33.357988
152
0.495166
[ "MIT" ]
skyre5/Elite-Hockey-Manager
Elite Hockey Manager/Elite Hockey Manager/Classes/LeagueComponents/Schedule.cs
11,277
C#
// Copyright (c) Pixel Crushers. All rights reserved. using PixelCrushers.DialogueSystem.SequencerCommands; using System; using System.Collections; using System.Collections.Generic; using System.Text.RegularExpressions; using UnityEngine; namespace PixelCrushers.DialogueSystem { /// <summary> /// A sequencer plays sequences of commands such as camera cuts, animation, audio, activating /// game objects, etc. You can use the sequencer to play cutscenes or perform game actions. /// The dialogue system uses a sequencer to play a sequence for every line of dialogue. If the /// dialogue author hasn't specified a sequence for a line of dialogue, the dialogue system /// will generate a basic, default sequence that aims the camera at the speaker. /// /// See also: @ref sequencer /// /// Each sequence command is implemented as a coroutine. You can add new commands by defining /// subclasses of SequencerCommand. /// </summary> public class Sequencer : MonoBehaviour { /// <summary> /// This handler is called when the sequence is done playing. /// </summary> public event Action FinishedSequenceHandler = null; /// <summary> /// A constant defining the name of the default camera angles prefab in case the cameraAngles property isn't set. /// </summary> private const string DefaultCameraAnglesResourceName = "Default Camera Angles"; /// <summary> /// Indicates whether a sequence is currently playing. The Dialogue System can queue up any number of actions /// using the Play() method. This property returns true if any actions are scheduled or active. /// </summary> /// <value> /// <c>true</c> if is playing; otherwise, <c>false</c>. /// </value> public bool isPlaying { get { return m_isPlaying; } } public GameObject cameraAngles { get { return m_cameraAngles; } } public Camera sequencerCamera { get { return m_sequencerCamera; } } public Transform sequencerCameraTransform { get { return (m_alternateSequencerCameraObject != null) ? m_alternateSequencerCameraObject.transform : m_sequencerCamera.transform; } } public Transform speaker { get { return m_speaker; } } public Transform listener { get { return m_listener; } } public Vector3 originalCameraPosition { get { return m_originalCameraPosition; } } public Quaternion originalCameraRotation { get { return m_originalCameraRotation; } } public float originalOrthographicSize { get { return m_originalOrthographicSize; } } /// <summary> /// The subtitle end time ({{end}}) if playing a dialogue entry sequence. /// </summary> public float subtitleEndTime { get; set; } /// <summary> /// The entrytag for the current dialogue entry, if playing a dialogue entry sequence. /// </summary> public string entrytag { get; set; } public string entrytaglocal { get { return Localization.isDefaultLanguage ? entrytag : entrytag + "_" + Localization.language; } } /// @cond FOR_V1_COMPATIBILITY public bool IsPlaying { get { return isPlaying; } } public GameObject CameraAngles { get { return cameraAngles; } } public Camera SequencerCamera { get { return sequencerCamera; } } public Transform SequencerCameraTransform { get { return sequencerCameraTransform; } } public Transform Speaker { get { return speaker; } } public Transform Listener { get { return listener; } } public Vector3 OriginalCameraPosition { get { return originalCameraPosition; } } public Quaternion OriginalCameraRotation { get { return originalCameraRotation; } } public float OriginalOrthographicSize { get { return originalOrthographicSize; } } public float SubtitleEndTime { get { return subtitleEndTime; } set { subtitleEndTime = value; } } /// @endcond /// <summary> /// Set <c>true</c> to disable the internal sequencer commands -- for example, /// if you want to replace them all with your own. /// </summary> public bool disableInternalSequencerCommands = false; /// <summary> /// <c>true</c> if the sequencer has taken control of the main camera at some point. Used to restore the /// original camera position when the sequencer is closed. /// </summary> private bool m_hasCameraControl = false; private Camera m_originalCamera = null; /// <summary> /// The original camera position before the sequencer took control. If the sequencer doesn't take control /// of the camera, this property is ignored. /// </summary> private Vector3 m_originalCameraPosition = Vector3.zero; /// <summary> /// The original camera rotation before the sequencer took control. If the sequencer doesn't take control /// of the camera, this property is ignored. /// </summary> private Quaternion m_originalCameraRotation = Quaternion.identity; /// <summary> /// The original orthographicSize before the sequencer took control. /// </summary> private float m_originalOrthographicSize = 16; private Transform m_speaker = null; private Transform m_listener = null; private List<QueuedSequencerCommand> m_queuedCommands = new List<QueuedSequencerCommand>(); private List<SequencerCommand> m_activeCommands = new List<SequencerCommand>(); private List<SequencerCommand> m_commandsToDelete = new List<SequencerCommand>(); private float m_delayTimeLeft = 0; // Used to track Delay(#) instead of requiring sep. sequencer command. private bool m_informParticipants = false; private bool m_closeWhenFinished = false; private Camera m_sequencerCameraSource = null; private Camera m_sequencerCamera = null; private GameObject m_alternateSequencerCameraObject = null; private GameObject m_cameraAngles = null; private bool m_isUsingMainCamera = false; private bool m_isPlaying = false; private static Dictionary<string, System.Type> m_cachedComponentTypes = new Dictionary<string, Type>(); private static Dictionary<string, string> m_shortcuts = new Dictionary<string, string>(); private static Dictionary<string, Stack<string>> m_shortcutStack = new Dictionary<string, Stack<string>>(); #if UNITY_2019_3_OR_NEWER [RuntimeInitializeOnLoadMethod(RuntimeInitializeLoadType.SubsystemRegistration)] static void InitStaticVariables() { m_cachedComponentTypes = new Dictionary<string, Type>(); m_shortcuts = new Dictionary<string, string>(); m_shortcutStack = new Dictionary<string, Stack<string>>(); } #endif private SequenceParser m_parser = new SequenceParser(); private const float InstantThreshold = 0.001f; /// <summary> /// Sends OnSequencerMessage(message) to the Dialogue Manager. Since sequencers are usually on /// the Dialogue Manager object, this is a convenient way to send a message to a sequencer. /// You can use this method if your sequence is waiting for a message. /// </summary> /// <param name="message">Message to send.</param> public static void Message(string message) { if (DialogueManager.instance == null) return; DialogueManager.instance.SendMessage(DialogueSystemMessages.OnSequencerMessage, message, SendMessageOptions.DontRequireReceiver); } /// <summary> /// Registers a sequencer shortcut with the Dialogue System. When playing sequences, shortcuts wrapped in /// double braces are replaced by their values. /// </summary> /// <param name="shortcut">Shortcut ID</param> /// <param name="value">Sequence that replaces the shortcut ID.</param> public static void RegisterShortcut(string shortcut, string value) { if (string.IsNullOrEmpty(shortcut) || shortcut.Equals("end") || shortcut.Equals("default")) return; var key = "{{" + shortcut + "}}"; if (m_shortcuts.ContainsKey(key)) { m_shortcuts[key] = value; } else { m_shortcuts.Add(key, value); } // Also add to a stack so we can restore the previous value of the shortcut once unregistered: if (!m_shortcutStack.ContainsKey(key)) { m_shortcutStack.Add(key, new Stack<string>()); } m_shortcutStack[key].Push(value); } /// <summary> /// Unregisters a shortcut from the Dialogue System. /// </summary> /// <param name="shortcut">Shortcut to remove.</param> public static void UnregisterShortcut(string shortcut) { var key = "{{" + shortcut + "}}"; if (m_shortcuts.ContainsKey(key)) { m_shortcuts.Remove(key); } // Remove from stack. If stack has a previous value, set it, too. if (m_shortcutStack.ContainsKey(key)) { if (m_shortcutStack[key].Count > 0) { m_shortcutStack[key].Pop(); if (m_shortcutStack[key].Count > 0) { var previousValue = m_shortcutStack[key].Pop(); m_shortcuts.Add(key, previousValue); } } if (m_shortcutStack[key].Count == 0) { m_shortcutStack.Remove(key); } } } public static string ReplaceShortcuts(string sequence) { if (!sequence.Contains("{{")) return sequence; foreach (var kvp in m_shortcuts) { sequence = sequence.Replace(kvp.Key, kvp.Value); } return sequence; } private static Regex ShortcutRegex = null; private static void ReportUnrecognizedShortcuts(string sequence) { if (ShortcutRegex == null) ShortcutRegex = new Regex(@"{{.+}}"); foreach (Match match in ShortcutRegex.Matches(sequence)) { Debug.LogWarning("Dialogue System: Unrecognized shortcut " + match.Value); } } public void UseCamera(Camera sequencerCamera, GameObject cameraAngles) { UseCamera(sequencerCamera, null, cameraAngles); } public void UseCamera(Camera sequencerCamera, GameObject alternateSequencerCameraObject, GameObject cameraAngles) { this.m_originalCamera = Camera.main; this.m_sequencerCameraSource = sequencerCamera; this.m_alternateSequencerCameraObject = alternateSequencerCameraObject; this.m_cameraAngles = cameraAngles; GetCamera(); GetCameraAngles(); } private void GetCameraAngles() { if (m_cameraAngles == null) { DialogueManager.LoadAsset(DefaultCameraAnglesResourceName, typeof(GameObject), (asset) => { m_cameraAngles = asset as GameObject; }); } } private void GetCamera() { if (m_sequencerCamera == null) { if (m_alternateSequencerCameraObject != null) { m_isUsingMainCamera = true; m_sequencerCamera = m_alternateSequencerCameraObject.GetComponent<Camera>(); } else if (m_sequencerCameraSource != null) { GameObject source = m_sequencerCameraSource.gameObject; GameObject sequencerCameraObject = Instantiate(source, source.transform.position, source.transform.rotation) as GameObject; m_sequencerCamera = sequencerCameraObject.GetComponent<Camera>(); if (m_sequencerCamera != null) { m_sequencerCamera.transform.parent = this.transform; m_sequencerCamera.gameObject.SetActive(false); m_isUsingMainCamera = false; } else { Destroy(sequencerCameraObject); } } if (m_sequencerCamera == null) { m_sequencerCamera = UnityEngine.Camera.main; m_isUsingMainCamera = true; } // Make sure a sequencerCamera exists: if (m_sequencerCamera == null) { if (DialogueDebug.logWarnings) Debug.LogWarning(DialogueDebug.Prefix + ": No MainCamera found in scene. Creating one for the Sequencer Camera.", this); GameObject go = new GameObject("Sequencer Camera", typeof(Camera), typeof(AudioListener)); #if !UNITY_2017_1_OR_NEWER go.AddComponent<GUILayer>(); #endif m_sequencerCamera = go.GetComponent<Camera>(); m_isUsingMainCamera = true; } } // Make sure a camera is tagged MainCamera; use sequencerCamera if no other: if (UnityEngine.Camera.main == null && m_sequencerCamera != null) { m_sequencerCamera.tag = "MainCamera"; m_isUsingMainCamera = true; } } private void DestroyCamera() { if ((m_sequencerCamera != null) && !m_isUsingMainCamera) { m_sequencerCamera.gameObject.SetActive(false); Destroy(m_sequencerCamera.gameObject, 1); m_sequencerCamera = null; } } /// <summary> /// Restores the original camera position. Waits two frames first, to allow any /// active, required actions to finish. /// </summary> private IEnumerator RestoreCamera() { yield return null; yield return null; ReleaseCameraControl(); } /// <summary> /// Switches the sequencer camera to a different camera object immediately. /// Restores the previous camera first. /// </summary> /// <param name="newCamera">New camera.</param> public void SwitchCamera(Camera newCamera) { if ((m_sequencerCamera != null) && !m_isUsingMainCamera) { Destroy(m_sequencerCamera.gameObject, 1); } ReleaseCameraControl(); m_hasCameraControl = false; m_originalCamera = null; m_originalCameraPosition = Vector3.zero; m_originalCameraRotation = Quaternion.identity; m_originalOrthographicSize = 16; m_sequencerCameraSource = null; m_sequencerCamera = null; m_alternateSequencerCameraObject = null; m_isUsingMainCamera = false; UseCamera(newCamera, m_cameraAngles); TakeCameraControl(); } /// <summary> /// Takes control of the camera. /// </summary> public void TakeCameraControl() { if (m_hasCameraControl) return; m_hasCameraControl = true; if (m_alternateSequencerCameraObject != null) { m_originalCamera = m_sequencerCamera; m_originalCameraPosition = m_alternateSequencerCameraObject.transform.position; m_originalCameraRotation = m_alternateSequencerCameraObject.transform.rotation; } else { m_originalCamera = UnityEngine.Camera.main; if (UnityEngine.Camera.main != null) { m_originalCameraPosition = UnityEngine.Camera.main.transform.position; m_originalCameraRotation = UnityEngine.Camera.main.transform.rotation; m_originalCamera.gameObject.SetActive(false); } m_originalOrthographicSize = m_sequencerCamera.orthographicSize; m_sequencerCamera.gameObject.SetActive(true); } } /// <summary> /// Releases control of the camera. /// </summary> private void ReleaseCameraControl() { if (!m_hasCameraControl) return; m_hasCameraControl = false; if (m_alternateSequencerCameraObject != null) { m_alternateSequencerCameraObject.transform.position = m_originalCameraPosition; m_alternateSequencerCameraObject.transform.rotation = m_originalCameraRotation; } else { if (m_sequencerCamera != null) // May have disappeared if changed scene during conversation. { m_sequencerCamera.transform.position = m_originalCameraPosition; m_sequencerCamera.transform.rotation = m_originalCameraRotation; m_sequencerCamera.orthographicSize = m_originalOrthographicSize; m_sequencerCamera.gameObject.SetActive(false); } if (m_originalCamera != null) { m_originalCamera.gameObject.SetActive(true); } } } /// <summary> /// Opens this instance. Simply resets hasCameraControl. /// </summary> public void Open() { entrytag = string.Empty; GetCamera(); m_hasCameraControl = false; GetCameraAngles(); } /// <summary> /// Closes and destroy this sequencer. Stops all actions and restores the original camera /// position. /// </summary> public void Close() { if (FinishedSequenceHandler != null) FinishedSequenceHandler(); FinishedSequenceHandler = null; Stop(); StartCoroutine(RestoreCamera()); Destroy(this, 1); } public void OnDestroy() { DestroyCamera(); } public void Update() { if (m_isPlaying) { CheckQueuedCommands(); CheckActiveCommands(); if (m_delayTimeLeft > 0) m_delayTimeLeft -= Time.unscaledDeltaTime; if ((m_queuedCommands.Count == 0) && (m_activeCommands.Count == 0) && m_delayTimeLeft <= 0) { FinishSequence(); } } } private void FinishSequence() { m_isPlaying = false; if (FinishedSequenceHandler != null) FinishedSequenceHandler(); if (m_informParticipants) InformParticipants(DialogueSystemMessages.OnSequenceEnd); if (m_closeWhenFinished) { FinishedSequenceHandler = null; Close(); } } public void SetParticipants(Transform speaker, Transform listener) { this.m_speaker = speaker; this.m_listener = listener; } private void InformParticipants(string message) { if (m_speaker != null) { m_speaker.BroadcastMessage(message, m_speaker, SendMessageOptions.DontRequireReceiver); if ((m_listener != null) && (m_listener != m_speaker)) m_listener.BroadcastMessage(message, m_speaker, SendMessageOptions.DontRequireReceiver); } if (DialogueManager.instance.transform != m_speaker && DialogueManager.instance.transform != m_listener) { var actor = (m_speaker != null) ? m_speaker : ((m_listener != null) ? m_listener : DialogueManager.instance.transform); DialogueManager.instance.BroadcastMessage(message, actor, SendMessageOptions.DontRequireReceiver); } } /// <summary> /// Parses a sequence string and plays the individual commands. /// </summary> /// <param name='sequence'> /// The sequence to play, in the form: /// /// <code> /// \<sequence\> ::= \<statement\> ; \<statement\> ; ... /// </code> /// /// <code> /// \<statement\> ::= [required] \<command\>( \<arg\>, \<arg\>, ... ) [@\<time\>] [->Message(Y)] /// </code> /// /// For example, the sequence below shows a wide angle shot of the speaker reloading and /// firing, and then cuts to a closeup of the listener. /// /// <code> /// Camera(Wide); Animation(Reload); Animation(Fire)@2; required Camera(Closeup, listener)@3.5 /// </code> /// </param> public void PlaySequence(string sequence) { m_isPlaying = true; if (string.IsNullOrEmpty(sequence)) return; // Replace [var=varName] and [lua()] tags: sequence = FormattedText.ParseCode(sequence); // Replace shortcuts: if (sequence.Contains("{{")) { sequence = ReplaceShortcuts(sequence); sequence = FormattedText.ParseCode(sequence); // Replace any [var] or [lua] in shortcuts. if (DialogueDebug.logWarnings && sequence.Contains("{{")) ReportUnrecognizedShortcuts(sequence); } // Substitute entrytaglocal and entrytag: if (!string.IsNullOrEmpty(entrytag) && sequence.Contains(SequencerKeywords.Entrytag)) { sequence = sequence.Replace(SequencerKeywords.EntrytagLocal, entrytaglocal).Replace(SequencerKeywords.Entrytag, entrytag); } var commands = m_parser.Parse(sequence); if (commands != null) { for (int i = 0; i < commands.Count; i++) { PlayCommand(commands[i]); } } } public void PlaySequence(string sequence, bool informParticipants, bool destroyWhenDone) { this.m_closeWhenFinished = destroyWhenDone; this.m_informParticipants = informParticipants; if (informParticipants) InformParticipants("OnSequenceStart"); PlaySequence(sequence); } public void PlaySequence(string sequence, Transform speaker, Transform listener, bool informParticipants, bool destroyWhenDone) { SetParticipants(speaker, listener); PlaySequence(sequence, informParticipants, destroyWhenDone); } public void PlaySequence(string sequence, Transform speaker, Transform listener, bool informParticipants, bool destroyWhenDone, bool delayOneFrame) { if (delayOneFrame) { StartCoroutine(PlaySequenceAfterOneFrame(sequence, speaker, listener, informParticipants, destroyWhenDone)); } else { PlaySequence(sequence, speaker, listener, informParticipants, destroyWhenDone); } } public IEnumerator PlaySequenceAfterOneFrame(string sequence, Transform speaker, Transform listener, bool informParticipants, bool destroyWhenDone) { yield return null; PlaySequence(sequence, speaker, listener, informParticipants, destroyWhenDone); } /// <summary> /// Schedules a command to be played. /// </summary> /// <param name='commandName'> /// The command to play. See @ref sequencerCommands for the list of valid commands. /// </param> /// <param name='required'> /// If <c>true</c>, the command will play even if Stop() is called. If this command absolutely must run (for example, /// setting up the final camera angle at the end of the sequence), set required to true. /// </param> /// <param name='time'> /// The time delay in seconds at which to start the command. If time is <c>0</c>, the command starts immediately. /// </param> /// <param name='args'> /// An array of arguments for the command. Pass <c>null</c> if no arguments are required. /// </param> /// <example> /// // At the 2 second mark, cut the camera to a closeup of the listener. /// string[] args = new string[] { "Closeup", "listener" }; /// Play("Camera", true, 2, args); /// </example> public void PlayCommand(string commandName, bool required, float time, string message, string endMessage, params string[] args) { PlayCommand(null, commandName, required, time, message, endMessage, args); } public void PlayCommand(QueuedSequencerCommand commandRecord) { if (commandRecord == null) return; PlayCommand(commandRecord, commandRecord.command, commandRecord.required, commandRecord.startTime, commandRecord.messageToWaitFor, commandRecord.endMessage, commandRecord.parameters); } public void PlayCommand(QueuedSequencerCommand commandRecord, string commandName, bool required, float time, string message, string endMessage, params string[] args) { if (DialogueDebug.logInfo) { if (args != null) { if (string.IsNullOrEmpty(message) && string.IsNullOrEmpty(endMessage)) { Debug.Log(string.Format(System.Globalization.CultureInfo.InvariantCulture, "{0}: Sequencer.Play( {1}{2}({3})@{4} )", new System.Object[] { DialogueDebug.Prefix, (required ? "required " : string.Empty), commandName, string.Join(", ", args), time })); } else if (string.IsNullOrEmpty(endMessage)) { Debug.Log(string.Format("{0}: Sequencer.Play( {1}{2}({3})@Message({4}) )", new System.Object[] { DialogueDebug.Prefix, (required ? "required " : string.Empty), commandName, string.Join(", ", args), message })); } else if (string.IsNullOrEmpty(message)) { Debug.Log(string.Format("{0}: Sequencer.Play( {1}{2}({3})->Message({4}) )", new System.Object[] { DialogueDebug.Prefix, (required ? "required " : string.Empty), commandName, string.Join(", ", args), endMessage })); } else { Debug.Log(string.Format("{0}: Sequencer.Play( {1}{2}({3})@Message({4})->Message({5}) )", new System.Object[] { DialogueDebug.Prefix, (required ? "required " : string.Empty), commandName, string.Join(", ", args), message, endMessage })); } } } m_isPlaying = true; if ((time <= InstantThreshold) && !IsTimePaused() && string.IsNullOrEmpty(message)) { ActivateCommand(commandName, endMessage, speaker, listener, args); } else { if (commandRecord != null) { commandRecord.startTime += DialogueTime.time; commandRecord.speaker = speaker; commandRecord.listener = listener; m_queuedCommands.Add(commandRecord); } else { m_queuedCommands.Add(new QueuedSequencerCommand(commandName, args, DialogueTime.time + time, message, endMessage, required, speaker, listener)); } } } private bool IsTimePaused() { return DialogueTime.isPaused; } /// <summary> /// SequencerCommand can refer to these if they run in Awake. /// </summary> public static Sequencer s_awakeSequencer; public static string s_awakeEndMessage; public static Transform s_awakeSpeaker; public static Transform s_awakeListener; public static string[] s_awakeArgs; private void ActivateCommand(string commandName, string endMessage, Transform speaker, Transform listener, string[] args) { float duration = 0; if (string.IsNullOrEmpty(commandName)) { //--- Removed; just a nuisance: if (DialogueDebug.LogInfo) Debug.Log(string.Format("{0}: Sequencer received a blank string as a command name", new System.Object[] { DialogueDebug.Prefix })); } else if (HandleCommandInternally(commandName, args, out duration)) { if (!string.IsNullOrEmpty(endMessage)) StartCoroutine(SendTimedSequencerMessage(endMessage, duration)); } else { System.Type componentType = FindSequencerCommandType(commandName); s_awakeSequencer = this; s_awakeEndMessage = endMessage; s_awakeSpeaker = speaker; s_awakeListener = listener; s_awakeArgs = args; SequencerCommand command = (componentType == null) ? null : gameObject.AddComponent(componentType) as SequencerCommand; if (command != null) { command.Initialize(this, endMessage, speaker, listener, args); m_activeCommands.Add(command); } else { if (DialogueDebug.logWarnings) Debug.LogWarning(string.Format("{0}: Can't find any built-in sequencer command named {1}() or a sequencer command component named SequencerCommand{1}()", new System.Object[] { DialogueDebug.Prefix, commandName })); } } } private System.Type FindSequencerCommandType(string commandName) { if (m_cachedComponentTypes.ContainsKey(commandName)) { return m_cachedComponentTypes[commandName]; } else { var component = GetTypeFromName("SequencerCommand" + commandName); m_cachedComponentTypes[commandName] = component; return component; } } public static void Preload() { var assemblies = System.AppDomain.CurrentDomain.GetAssemblies(); for (int i = 0; i < assemblies.Length; i++) { var assembly = assemblies[i]; try { var types = assembly.GetTypes(); foreach (var type in types) { if (type.Name.StartsWith("SequencerCommand")) { var commandName = type.Name.Substring("SequencerCommand".Length); m_cachedComponentTypes[commandName] = type; } } } catch (Exception) { // Ignore exceptions. } } } public System.Type GetTypeFromName(string typeName) { var assemblies = System.AppDomain.CurrentDomain.GetAssemblies(); for (int i = 0; i < assemblies.Length; i++) { var assembly = assemblies[i]; try { var types = assembly.GetTypes(); for (int j = 0; j < types.Length; j++) { var type = types[j]; if (string.Equals(type.Name, typeName)) return type; } } catch (Exception) { // Ignore exceptions. } } return null; } // Previous method that only looked in specific assemblies: //private System.Type FindSequencerCommandType(string commandName, string assemblyName) //{ // System.Type componentType = FindSequencerCommandType("PixelCrushers.DialogueSystem.SequencerCommands.", commandName, assemblyName); // if (componentType != null) return componentType; // componentType = FindSequencerCommandType("PixelCrushers.DialogueSystem.", commandName, assemblyName); // if (componentType != null) return componentType; // componentType = FindSequencerCommandType(string.Empty, commandName, assemblyName); // return componentType; //} //private System.Type FindSequencerCommandType(string namespacePrefix, string commandName, string assemblyName) //{ // string fullPath = string.Format("{0}SequencerCommand{1},{2}", new System.Object[] { namespacePrefix, commandName, assemblyName }); // return Type.GetType(fullPath, false); //} private IEnumerator SendTimedSequencerMessage(string endMessage, float delay) { yield return StartCoroutine(DialogueTime.WaitForSeconds(delay)); Sequencer.Message(endMessage); } private void ActivateCommand(QueuedSequencerCommand queuedCommand) { ActivateCommand(queuedCommand.command, queuedCommand.endMessage, queuedCommand.speaker, queuedCommand.listener, queuedCommand.parameters); } private void CheckQueuedCommands() { if ((m_queuedCommands.Count > 0) && !IsTimePaused()) { float now = DialogueTime.time; try { foreach (var queuedCommand in m_queuedCommands) { if (now >= queuedCommand.startTime) ActivateCommand(queuedCommand.command, queuedCommand.endMessage, queuedCommand.speaker, queuedCommand.listener, queuedCommand.parameters); } } catch (InvalidOperationException) { } // Allow unusual commands to kill the conversation. m_queuedCommands.RemoveAll(queuedCommand => (now >= queuedCommand.startTime)); } } //private List<QueuedSequencerCommand> m_queuedCommandsToDelete = new List<QueuedSequencerCommand>(); public void OnSequencerMessage(string message) { try { if ((m_queuedCommands.Count > 0) && !IsTimePaused() && !string.IsNullOrEmpty(message)) { // Activate any queued commands that are waiting for the message: var m_queuedCommandsWaitingForMessage = m_queuedCommands.FindAll(x => string.Equals(message, x.messageToWaitFor)); for (int i = 0; i < m_queuedCommandsWaitingForMessage.Count; i++) { var queuedCommand = m_queuedCommandsWaitingForMessage[i]; ActivateCommand(queuedCommand.command, queuedCommand.endMessage, queuedCommand.speaker, queuedCommand.listener, queuedCommand.parameters); } // Then delete them from the queue: for (int i = 0; i < m_queuedCommandsWaitingForMessage.Count; i++) { m_queuedCommands.Remove(m_queuedCommandsWaitingForMessage[i]); } // m_queuedCommands.RemoveAll(queuedCommand => (string.Equals(message, queuedCommand.messageToWaitFor))); } } catch (Exception e) { // We don't care if the collection is modified: bool ignore = (e is InvalidOperationException || e is ArgumentOutOfRangeException); if (!ignore) throw; } } private void CheckActiveCommands() { m_commandsToDelete.Clear(); if (m_activeCommands.Count > 0) { var count = m_activeCommands.Count; for (int i = count - 1; i >= 0; i--) { var command = m_activeCommands[i]; if (command != null && !command.isPlaying) { if (!string.IsNullOrEmpty(command.endMessage)) Sequencer.Message(command.endMessage); m_commandsToDelete.Add(command); //--- if (0 <= i && i < m_activeCommands.Count) m_activeCommands.RemoveAt(i); Destroy(command); } } } for (int i = 0; i < m_commandsToDelete.Count; i++) { m_activeCommands.Remove(m_commandsToDelete[i]); } m_commandsToDelete.Clear(); } /// <summary> /// Stops all scheduled and active commands. /// </summary> public void Stop() { StopQueued(); StopActive(); } public void StopQueued() { if (m_queuedCommands.Count == 0) return; // Put the remaining commands in a new list so we can clear m_queuedCommands // in case one of the required commands causes another invocation of StopQueued(), // such as "required Continue()@Message(X)". var commandsToProcess = new List<QueuedSequencerCommand>(m_queuedCommands); m_queuedCommands.Clear(); foreach (var queuedCommand in commandsToProcess) { if (queuedCommand.required) ActivateCommand(queuedCommand.command, string.Empty, queuedCommand.speaker, queuedCommand.listener, queuedCommand.parameters); } } public void StopActive() { foreach (var command in m_activeCommands) { if (command != null) { if (!string.IsNullOrEmpty(command.endMessage)) Sequencer.Message(command.endMessage); StartCoroutine(DestroyAfterOneFrame(command)); //---Was: Destroy(command); //---Was: Destroy(command, 0.1f); } } m_activeCommands.Clear(); m_delayTimeLeft = 0; } IEnumerator DestroyAfterOneFrame(SequencerCommand command) { yield return null; Destroy(command); } /// <summary> /// Attempts to handles the command internally so the sequencer doesn't have to farm out /// the work to a SequencerCommand component. /// </summary> /// <returns> /// <c>true</c> if this method could handle the command internally; otherwise <c>false</c>. /// </returns> /// <param name='commandName'> /// The command to try to play. /// </param> /// <param name='args'> /// The arguments to the command. /// </param> private bool HandleCommandInternally(string commandName, string[] args, out float duration) { duration = 0; if (disableInternalSequencerCommands) return false; if (string.Equals(commandName, "None") || string.IsNullOrEmpty(commandName)) { return true; } else if (string.Equals(commandName, "Delay")) { return HandleDelayInternally(commandName, args, out duration); } else if (string.Equals(commandName, "Camera")) { return TryHandleCameraInternally(commandName, args); } else if (string.Equals(commandName, "Animation")) { return HandleAnimationInternally(commandName, args, out duration); } else if (string.Equals(commandName, "AnimatorController")) { return HandleAnimatorControllerInternally(commandName, args); } else if (string.Equals(commandName, "AnimatorLayer")) { return TryHandleAnimatorLayerInternally(commandName, args); } else if (string.Equals(commandName, "AnimatorBool")) { return HandleAnimatorBoolInternally(commandName, args); } else if (string.Equals(commandName, "AnimatorInt")) { return HandleAnimatorIntInternally(commandName, args); } else if (string.Equals(commandName, "AnimatorFloat")) { return TryHandleAnimatorFloatInternally(commandName, args); } else if (string.Equals(commandName, "AnimatorTrigger")) { return HandleAnimatorTriggerInternally(commandName, args); } else if (string.Equals(commandName, "AnimatorPlay")) { return HandleAnimatorPlayInternally(commandName, args); } else if (string.Equals(commandName, "Audio")) { return HandleAudioInternally(commandName, args); } else if (string.Equals(commandName, "AudioStop")) { return HandleAudioStopInternally(commandName, args); } else if (string.Equals(commandName, "ClearSubtitleText")) { return HandleClearSubtitleText(commandName, args); } else if (string.Equals(commandName, "MoveTo")) { return TryHandleMoveToInternally(commandName, args); } else if (string.Equals(commandName, "LookAt")) { return TryHandleLookAtInternally(commandName, args); } else if (string.Equals(commandName, "NavMeshAgent")) { return HandleNavMeshAgentInternally(commandName, args); } else if (string.Equals(commandName, "OpenPanel")) { return HandleOpenPanelInternally(commandName, args); } else if (string.Equals(commandName, "SendMessage")) { return HandleSendMessageInternally(commandName, false, args); } else if (string.Equals(commandName, "SendMessageUpwards")) { return HandleSendMessageInternally(commandName, true, args); } else if (string.Equals(commandName, "SetActive")) { return HandleSetActiveInternally(commandName, args); } else if (string.Equals(commandName, "SetEnabled")) { return HandleSetEnabledInternally(commandName, args); } else if (string.Equals(commandName, "HidePanel")) { return HandleHidePanelInternally(commandName, args); } else if (string.Equals(commandName, "SetPanel")) { return HandleSetPanelInternally(commandName, args); } else if (string.Equals(commandName, "SetMenuPanel")) { return HandleSetMenuPanelInternally(commandName, args); } else if (string.Equals(commandName, "SetDialoguePanel")) { return HandleSetDialoguePanelInternally(commandName, args); } else if (string.Equals(commandName, "SetPortrait")) { return HandleSetPortraitInternally(commandName, args); } else if (string.Equals(commandName, "SetTimeout")) { return HandleSetTimeoutInternally(commandName, args); } else if (string.Equals(commandName, "SetContinueMode")) { return HandleSetContinueModeInternally(commandName, args); } else if (string.Equals(commandName, "Continue")) { return HandleContinueInternally(); } else if (string.Equals(commandName, "SetVariable")) { return HandleSetVariableInternally(commandName, args); } else if (string.Equals(commandName, "ShowAlert")) { return HandleShowAlertInternally(commandName, args); } else if (string.Equals(commandName, "UpdateTracker")) { return HandleUpdateTrackerInternally(); } else if (string.Equals(commandName, "RandomizeNextEntry")) { return HandleRandomizeNextEntryInternally(); } return false; } private bool HandleDelayInternally(string commandName, string[] args, out float duration) { duration = SequencerTools.GetParameterAsFloat(args, 0); m_delayTimeLeft = Mathf.Max(m_delayTimeLeft, duration); if (DialogueDebug.logInfo) Debug.Log(string.Format(System.Globalization.CultureInfo.InvariantCulture, "{0}: Sequencer: Delay({1})", new System.Object[] { DialogueDebug.Prefix, duration })); return true; } private bool TryHandleCameraInternally(string commandName, string[] args) { float duration = SequencerTools.GetParameterAsFloat(args, 2, 0); if (duration < InstantThreshold) { // Handle right now: string angle = SequencerTools.GetParameter(args, 0, "default"); Transform subject = SequencerTools.GetSubject(SequencerTools.GetParameter(args, 1), m_speaker, m_listener); // Get the angle: bool isDefault = string.Equals(angle, "default"); if (isDefault) angle = SequencerTools.GetDefaultCameraAngle(subject); bool isOriginal = string.Equals(angle, "original"); Transform angleTransform = isOriginal ? m_originalCamera.transform : ((m_cameraAngles != null) ? m_cameraAngles.transform.Find(angle) : null); bool isLocalTransform = true; if (angleTransform == null) { isLocalTransform = false; GameObject go = GameObject.Find(angle); if (go != null) angleTransform = go.transform; } // Log: if (DialogueDebug.logInfo) Debug.Log(string.Format(System.Globalization.CultureInfo.InvariantCulture, "{0}: Sequencer: Camera({1}, {2}, {3}s)", new System.Object[] { DialogueDebug.Prefix, angle, Tools.GetObjectName(subject), duration })); if ((angleTransform == null) && DialogueDebug.logWarnings) Debug.LogWarning(string.Format("{0}: Sequencer: Camera angle '{1}' wasn't found.", new System.Object[] { DialogueDebug.Prefix, angle })); if ((subject == null) && DialogueDebug.logWarnings) Debug.LogWarning(string.Format("{0}: Sequencer: Camera subject '{1}' wasn't found.", new System.Object[] { DialogueDebug.Prefix, SequencerTools.GetParameter(args, 1) })); // If we have a camera angle and subject, move the camera to it: TakeCameraControl(); if (isOriginal) { sequencerCameraTransform.rotation = originalCameraRotation; sequencerCameraTransform.position = originalCameraPosition; } else if (angleTransform != null && subject != null) { Transform cameraTransform = sequencerCameraTransform; if (isLocalTransform) { cameraTransform.rotation = subject.rotation * angleTransform.localRotation; cameraTransform.position = subject.position + subject.rotation * angleTransform.localPosition; } else { cameraTransform.rotation = angleTransform.rotation; cameraTransform.position = angleTransform.position; } } return true; } else { return false; } } /// <summary> /// Handles the "Animation(animation[, gameobject|speaker|listener[, finalAnimation]])" action. /// /// Arguments: /// -# Name of a legacy animation in the Animation component. /// -# (Optional) The subject; can be speaker, listener, or the name of a game object. Default: speaker. /// </summary> private bool HandleAnimationInternally(string commandName, string[] args, out float duration) { duration = 0; // If the command has >2 args (last is finalAnimation), need to handle in the coroutine version: if ((args != null) && (args.Length > 2)) return false; string animation = SequencerTools.GetParameter(args, 0); Transform subject = SequencerTools.GetSubject(SequencerTools.GetParameter(args, 1), m_speaker, m_listener); Animation anim = (subject == null) ? null : subject.GetComponent<Animation>(); if (DialogueDebug.logInfo) Debug.Log(string.Format("{0}: Sequencer: Animation({1}, {2})", new System.Object[] { DialogueDebug.Prefix, animation, Tools.GetObjectName(subject) })); if (subject == null) { if (DialogueDebug.logWarnings) Debug.LogWarning(string.Format("{0}: Sequencer: Animation() command: subject is null.", new System.Object[] { DialogueDebug.Prefix })); } else if (anim == null) { if (DialogueDebug.logWarnings) Debug.LogWarning(string.Format("{0}: Sequencer: Animation() command: no Animation component found on {1}.", new System.Object[] { DialogueDebug.Prefix, subject.name })); } else if (string.IsNullOrEmpty(animation)) { if (DialogueDebug.logWarnings) Debug.LogWarning(string.Format("{0}: Sequencer: Animation() command: Animation name is blank.", new System.Object[] { DialogueDebug.Prefix })); } else { anim.CrossFade(animation); duration = (anim[animation] != null) ? anim[animation].length : 0; } return true; } /// <summary> /// Handles the "AnimatorController(controllerName[, gameobject|speaker|listener])" action. /// /// Arguments: /// -# Path to an animator controller inside a Resources folder. /// -# (Optional) The subject; can be speaker, listener, or the name of a game object. Default: speaker. /// </summary> private bool HandleAnimatorControllerInternally(string commandName, string[] args) { string controllerName = SequencerTools.GetParameter(args, 0); Transform subject = SequencerTools.GetSubject(SequencerTools.GetParameter(args, 1), m_speaker, m_listener); if (DialogueDebug.logInfo) Debug.Log(string.Format("{0}: Sequencer: AnimatorController({1}, {2})", new System.Object[] { DialogueDebug.Prefix, controllerName, Tools.GetObjectName(subject) })); // Load animator controller: try { DialogueManager.LoadAsset(controllerName, typeof(RuntimeAnimatorController), (asset) => { var animatorControllerAsset = asset as RuntimeAnimatorController; RuntimeAnimatorController animatorController = null; if (animatorControllerAsset != null) animatorController = Instantiate<RuntimeAnimatorController>(animatorControllerAsset); if (subject == null) { if (DialogueDebug.logWarnings) Debug.LogWarning(string.Format("{0}: Sequencer: AnimatorController() command: subject is null.", new System.Object[] { DialogueDebug.Prefix })); } else if (animatorController == null) { if (DialogueDebug.logWarnings) Debug.LogWarning(string.Format("{0}: Sequencer: AnimatorController() command: failed to load animator controller '{1}'.", new System.Object[] { DialogueDebug.Prefix, controllerName })); } else { Animator animator = subject.GetComponentInChildren<Animator>(); if (animator == null) { if (DialogueDebug.logWarnings) Debug.LogWarning(string.Format("{0}: Sequencer: AnimatorController() command: No Animator component found on {1}.", new System.Object[] { DialogueDebug.Prefix, subject.name })); } else { animator.runtimeAnimatorController = animatorController; } } }); } catch (Exception) { } return true; } /// <summary> /// Handles the "AnimatorLayer(layerIndex[, weight[, gameobject|speaker|listener[, duration]]])" /// action if duration is zero. /// /// Arguments: /// -# Index number of a layer on the subject's animator controller. Default: 1. /// -# (Optional) New weight. Default: <c>1f</c>. /// -# (Optional) The subject; can be speaker, listener, or the name of a game object. Default: speaker. /// -# (Optional) Duration in seconds to smooth to the new weight. /// </summary> private bool TryHandleAnimatorLayerInternally(string commandName, string[] args) { float duration = SequencerTools.GetParameterAsFloat(args, 3, 0); if (duration < InstantThreshold) { int layerIndex = SequencerTools.GetParameterAsInt(args, 0, 1); float weight = SequencerTools.GetParameterAsFloat(args, 1, 1f); Transform subject = SequencerTools.GetSubject(SequencerTools.GetParameter(args, 2), m_speaker, m_listener); if (DialogueDebug.logInfo) Debug.Log(string.Format("{0}: Sequencer: AnimatorLayer({1}, {2}, {3})", new System.Object[] { DialogueDebug.Prefix, layerIndex, weight, Tools.GetObjectName(subject) })); if (subject == null) { if (DialogueDebug.logWarnings) Debug.LogWarning(string.Format("{0}: Sequencer: AnimatorLayer() command: subject is null.", new System.Object[] { DialogueDebug.Prefix })); } else { Animator animator = subject.GetComponentInChildren<Animator>(); if (animator == null) { if (DialogueDebug.logWarnings) Debug.LogWarning(string.Format("{0}: Sequencer: AnimatorLayer(): No Animator component found on {1}.", new System.Object[] { DialogueDebug.Prefix, subject.name })); } else { animator.SetLayerWeight(layerIndex, weight); } } return true; } else { return false; } } /// <summary> /// Handles the "AnimatorBool(animatorParameter[, true|false[, gameobject|speaker|listener]])" action. /// /// Arguments: /// -# Name of a Mecanim animator parameter. /// -# (Optional) True or false. Default: <c>true</c>. /// -# (Optional) The subject; can be speaker, listener, or the name of a game object. Default: speaker. /// </summary> private bool HandleAnimatorBoolInternally(string commandName, string[] args) { string animatorParameter = SequencerTools.GetParameter(args, 0); bool parameterValue = SequencerTools.GetParameterAsBool(args, 1, true); Transform subject = SequencerTools.GetSubject(SequencerTools.GetParameter(args, 2), m_speaker, m_listener); if (DialogueDebug.logInfo) Debug.Log(string.Format("{0}: Sequencer: AnimatorBool({1}, {2}, {3})", new System.Object[] { DialogueDebug.Prefix, animatorParameter, parameterValue, Tools.GetObjectName(subject) })); if (subject == null) { if (DialogueDebug.logWarnings) Debug.LogWarning(string.Format("{0}: Sequencer: AnimatorBool() command: subject is null.", new System.Object[] { DialogueDebug.Prefix })); } else if (string.IsNullOrEmpty(animatorParameter)) { if (DialogueDebug.logWarnings) Debug.LogWarning(string.Format("{0}: Sequencer: AnimatorBool() command: animator parameter name is blank.", new System.Object[] { DialogueDebug.Prefix })); } else { Animator animator = subject.GetComponentInChildren<Animator>(); if (animator == null) { if (DialogueDebug.logWarnings) Debug.LogWarning(string.Format("{0}: Sequencer: No Animator component found on {1}.", new System.Object[] { DialogueDebug.Prefix, subject.name })); } else { animator.SetBool(animatorParameter, parameterValue); } } return true; } /// <summary> /// Handles the "AnimatorInt(animatorParameter[, value[, gameobject|speaker|listener]])" action. /// /// Arguments: /// -# Name of a Mecanim animator parameter. /// -# (Optional) Integer value. Default: <c>1</c>. /// -# (Optional) The subject; can be speaker, listener, or the name of a game object. Default: speaker. /// </summary> private bool HandleAnimatorIntInternally(string commandName, string[] args) { string animatorParameter = SequencerTools.GetParameter(args, 0); int parameterValue = SequencerTools.GetParameterAsInt(args, 1, 1); Transform subject = SequencerTools.GetSubject(SequencerTools.GetParameter(args, 2), m_speaker, m_listener); if (DialogueDebug.logInfo) Debug.Log(string.Format("{0}: Sequencer: AnimatorInt({1}, {2}, {3})", new System.Object[] { DialogueDebug.Prefix, animatorParameter, parameterValue, Tools.GetObjectName(subject) })); if (subject == null) { if (DialogueDebug.logWarnings) Debug.LogWarning(string.Format("{0}: Sequencer: AnimatorInt() command: subject is null.", new System.Object[] { DialogueDebug.Prefix })); } else if (string.IsNullOrEmpty(animatorParameter)) { if (DialogueDebug.logWarnings) Debug.LogWarning(string.Format("{0}: Sequencer: AnimatorInt() command: animator parameter name is blank.", new System.Object[] { DialogueDebug.Prefix })); } else { Animator animator = subject.GetComponentInChildren<Animator>(); if (animator == null) { if (DialogueDebug.logWarnings) Debug.LogWarning(string.Format("{0}: Sequencer: No Animator component found on {1}.", new System.Object[] { DialogueDebug.Prefix, subject.name })); } else { animator.SetInteger(animatorParameter, parameterValue); } } return true; } /// <summary> /// Handles the "AnimatorFloat(animatorParameter[, value[, gameobject|speaker|listener[, duration]]])" /// action if duration is zero. /// /// Arguments: /// -# Name of a Mecanim animator parameter. /// -# (Optional) Float value. Default: <c>1f</c>. /// -# (Optional) The subject; can be speaker, listener, or the name of a game object. Default: speaker. /// -# (Optional) Duration in seconds to smooth to the value. /// </summary> private bool TryHandleAnimatorFloatInternally(string commandName, string[] args) { float duration = SequencerTools.GetParameterAsFloat(args, 3, 0); if (duration < InstantThreshold) { string animatorParameter = SequencerTools.GetParameter(args, 0); float parameterValue = SequencerTools.GetParameterAsFloat(args, 1, 1f); Transform subject = SequencerTools.GetSubject(SequencerTools.GetParameter(args, 2), m_speaker, m_listener); if (DialogueDebug.logInfo) Debug.Log(string.Format(System.Globalization.CultureInfo.InvariantCulture, "{0}: Sequencer: AnimatorFloat({1}, {2}, {3})", new System.Object[] { DialogueDebug.Prefix, animatorParameter, parameterValue, Tools.GetObjectName(subject) })); if (subject == null) { if (DialogueDebug.logWarnings) Debug.LogWarning(string.Format("{0}: Sequencer: AnimatorFloat() command: subject is null.", new System.Object[] { DialogueDebug.Prefix })); } else if (string.IsNullOrEmpty(animatorParameter)) { if (DialogueDebug.logWarnings) Debug.LogWarning(string.Format("{0}: Sequencer: AnimatorFloat() command: animator parameter name is blank.", new System.Object[] { DialogueDebug.Prefix })); } else { Animator animator = subject.GetComponentInChildren<Animator>(); if (animator == null) { if (DialogueDebug.logWarnings) Debug.LogWarning(string.Format("{0}: Sequencer: No Animator component found on {1}.", new System.Object[] { DialogueDebug.Prefix, subject.name })); } else { animator.SetFloat(animatorParameter, parameterValue); } } return true; } else { return false; } } /// <summary> /// Handles the "AnimatorTrigger(animatorParameter[, gameobject|speaker|listener])" action, /// which sets a trigger parameter on a subject's Animator. /// /// Arguments: /// -# Name of a Mecanim animator state. /// -# (Optional) The subject; can be speaker, listener, or the name of a game object. Default: speaker. /// </summary> private bool HandleAnimatorTriggerInternally(string commandName, string[] args) { string animatorParameter = SequencerTools.GetParameter(args, 0); Transform subject = SequencerTools.GetSubject(SequencerTools.GetParameter(args, 1), m_speaker, m_listener); Animator animator = (subject != null) ? subject.GetComponentInChildren<Animator>() : null; if (animator == null) { if (DialogueDebug.logWarnings) Debug.Log(string.Format("{0}: Sequencer: AnimatorTrigger({1}, {2}): No Animator found on {2}", new System.Object[] { DialogueDebug.Prefix, animatorParameter, (subject != null) ? subject.name : SequencerTools.GetParameter(args, 1) })); } else { if (DialogueDebug.logInfo) Debug.Log(string.Format("{0}: Sequencer: AnimatorTrigger({1}, {2})", new System.Object[] { DialogueDebug.Prefix, animatorParameter, subject })); } if (animator != null) animator.SetTrigger(animatorParameter); return true; } /// <summary> /// Handles the "AnimatorPlay(stateName[, gameobject|speaker|listener[, [crossfadeDuration[, layer]]])" action. /// /// Arguments: /// -# Name of a Mecanim animator state. /// -# (Optional) The subject; can be speaker, listener, or the name of a game object. Default: speaker. /// -# (Optional) Crossfade duration. Default: 0 (play immediately). /// -# (Optional) Layer. Default: -1 (any layer). /// </summary> private bool HandleAnimatorPlayInternally(string commandName, string[] args) { string stateName = SequencerTools.GetParameter(args, 0); Transform subject = SequencerTools.GetSubject(SequencerTools.GetParameter(args, 1), m_speaker, m_listener); float crossfadeDuration = SequencerTools.GetParameterAsFloat(args, 2); int layer = SequencerTools.GetParameterAsInt(args, 3, -1); if (DialogueDebug.logInfo) Debug.Log(string.Format("{0}: Sequencer: AnimatorPlay({1}, {2}, fade={3}, layer={4})", new System.Object[] { DialogueDebug.Prefix, stateName, Tools.GetObjectName(subject), crossfadeDuration, layer })); if (subject == null) { if (DialogueDebug.logWarnings) Debug.LogWarning(string.Format("{0}: Sequencer: AnimatorPlay() command: subject is null.", new System.Object[] { DialogueDebug.Prefix })); } else if (string.IsNullOrEmpty(stateName)) { if (DialogueDebug.logWarnings) Debug.LogWarning(string.Format("{0}: Sequencer: AnimatorPlay() command: state name is blank.", new System.Object[] { DialogueDebug.Prefix })); } else { Animator animator = subject.GetComponentInChildren<Animator>(); if (animator == null) { if (DialogueDebug.logWarnings) Debug.LogWarning(string.Format("{0}: Sequencer: No Animator component found on {1}.", new System.Object[] { DialogueDebug.Prefix, subject.name })); } else { if (Tools.ApproximatelyZero(crossfadeDuration)) { animator.Play(stateName, layer); } else { animator.CrossFadeInFixedTime(stateName, crossfadeDuration, layer); } } } return true; } /// <summary> /// Handles the "Audio(clip[, gameobject|speaker|listener[, oneshot]])" action. This action loads the /// specified clip from Resources into the subject's audio source component and plays it. /// /// Arguments: /// -# Path to the clip (inside a Resources folder). /// -# (Optional) The subject; can be speaker, listener, or the name of a game object. /// Default: speaker. /// </summary> private bool HandleAudioInternally(string commandName, string[] args) { string clipName = SequencerTools.GetParameter(args, 0); Transform subject = SequencerTools.GetSubject(SequencerTools.GetParameter(args, 1), m_speaker, m_listener); bool oneshot = SequencerTools.GetParameterAsBool(args, 2, false) || string.Equals("oneshot", SequencerTools.GetParameter(args, 2), StringComparison.OrdinalIgnoreCase); // Skip if muted: if (SequencerTools.IsAudioMuted()) { if (DialogueDebug.logInfo) Debug.Log(string.Format("{0}: Sequencer: Audio({1}, {2}): skipping; audio is muted", new System.Object[] { DialogueDebug.Prefix, clipName, subject })); return true; } else { if (DialogueDebug.logInfo) Debug.Log(string.Format("{0}: Sequencer: Audio({1}, {2})", new System.Object[] { DialogueDebug.Prefix, clipName, subject })); } // Load clip: DialogueManager.LoadAsset(clipName, typeof(AudioClip), (asset) => { var clip = asset as AudioClip; if ((clip == null) && DialogueDebug.logWarnings) Debug.LogWarning(string.Format("{0}: Sequencer: Audio() command: clip '{1}' could not be found or loaded.", new System.Object[] { DialogueDebug.Prefix, clipName })); // Play clip: if (clip != null) { AudioSource audioSource = SequencerTools.GetAudioSource(subject); if (audioSource == null) { if (DialogueDebug.logWarnings) Debug.LogWarning(string.Format("{0}: Sequencer: Audio() command: can't find or add AudioSource to {1}.", new System.Object[] { DialogueDebug.Prefix, subject.name })); } else if (oneshot) { audioSource.PlayOneShot(clip); } else { audioSource.clip = clip; audioSource.Play(); } } }); return true; } /// <summary> /// Handles the "AudioStop([gameobject|speaker|listener])" action. This action stops the /// subject's Audio Source. /// /// Arguments: /// -# (Optional) The subject; can be speaker, listener, or the name of a game object. /// Default: speaker. /// </summary> private bool HandleAudioStopInternally(string commandName, string[] args) { Transform subject = SequencerTools.GetSubject(SequencerTools.GetParameter(args, 0), m_speaker, m_listener); if (DialogueDebug.logInfo) Debug.Log(string.Format("{0}: Sequencer: AudioStop({1})", new System.Object[] { DialogueDebug.Prefix, subject })); var audioSource = SequencerTools.GetAudioSource(subject); if (audioSource != null) audioSource.Stop(); return true; } /// <summary> /// Tries to handle the "MoveTo(target, [, subject[, duration]])" action. This action matches the /// subject to the target's position and rotation. /// /// Arguments: /// -# The target. /// -# (Optional) The subject; can be speaker, listener, or the name of a game object. /// -# (Optional) Duration in seconds. /// Default: speaker. /// </summary> private bool TryHandleMoveToInternally(string commandName, string[] args) { float duration = SequencerTools.GetParameterAsFloat(args, 2, 0); if (duration < InstantThreshold) { // Handle now: Transform target = SequencerTools.GetSubject(SequencerTools.GetParameter(args, 0), m_speaker, m_listener); Transform subject = SequencerTools.GetSubject(SequencerTools.GetParameter(args, 1), m_speaker, m_listener); if (DialogueDebug.logInfo) Debug.Log(string.Format(System.Globalization.CultureInfo.InvariantCulture, "{0}: Sequencer: MoveTo({1}, {2}, {3})", new System.Object[] { DialogueDebug.Prefix, target, subject, duration })); if ((subject == null) && DialogueDebug.logWarnings) Debug.LogWarning(string.Format("{0}: Sequencer: MoveTo() command: subject is null.", new System.Object[] { DialogueDebug.Prefix })); if ((target == null) && DialogueDebug.logWarnings) Debug.LogWarning(string.Format("{0}: Sequencer: MoveTo() command: target is null.", new System.Object[] { DialogueDebug.Prefix })); if (subject != null && target != null) { var subjectRigidbody = subject.GetComponent<Rigidbody>(); var navMeshAgent = subject.GetComponent<UnityEngine.AI.NavMeshAgent>(); if (navMeshAgent != null) { navMeshAgent.Warp(target.position); if (subjectRigidbody != null) { subjectRigidbody.MoveRotation(target.rotation); } else { subject.rotation = target.rotation; } } if (subjectRigidbody != null && !subjectRigidbody.isKinematic) { subjectRigidbody.MoveRotation(target.rotation); subjectRigidbody.MovePosition(target.position); } else { subject.position = target.position; subject.rotation = target.rotation; } } return true; } else { return false; } } /// <summary> /// Tries to handle the "LookAt([target[, subject[, duration[, allAxes]]]])" action. This action /// rotates the subject to look at a target. If target is omitted, this action rotates /// the speaker and listener to look at each other. /// /// Arguments: /// -# Target to look at. Can be speaker, listener, or the name of a game object. Default: listener. /// -# (Optional) The subject; can be speaker, listener, or the name of a game object. Default: speaker. /// -# (Optional) Duration in seconds. /// -# (Optional) allAxes to rotate on all axes (otherwise stays upright). /// </summary> private bool TryHandleLookAtInternally(string commandName, string[] args) { float duration = SequencerTools.GetParameterAsFloat(args, 2, 0); bool yAxisOnly = (string.Compare(SequencerTools.GetParameter(args, 3), "allAxes", System.StringComparison.OrdinalIgnoreCase) != 0); if (duration < InstantThreshold) { // Handle now: if ((args == null) || (args.Length == 0) || ((args.Length == 1) && string.IsNullOrEmpty(args[0]))) { // Handle empty args (speaker and listener look at each other): if ((m_speaker != null) && (m_listener != null)) { if (DialogueDebug.logInfo) Debug.Log(string.Format("{0}: Sequencer: LookAt() [speaker<->listener]", new System.Object[] { DialogueDebug.Prefix })); DoLookAt(m_speaker, m_listener.position, yAxisOnly); DoLookAt(m_listener, m_speaker.position, yAxisOnly); } } else { // Otherwise handle subject and target: Transform target = SequencerTools.GetSubject(SequencerTools.GetParameter(args, 0), m_speaker, m_listener); Transform subject = SequencerTools.GetSubject(SequencerTools.GetParameter(args, 1), m_speaker, m_listener); if (DialogueDebug.logInfo) Debug.Log(string.Format(System.Globalization.CultureInfo.InvariantCulture, "{0}: Sequencer: LookAt({1}, {2}, {3})", new System.Object[] { DialogueDebug.Prefix, target, subject, duration })); if ((subject == null) && DialogueDebug.logWarnings) Debug.LogWarning(string.Format("{0}: Sequencer: LookAt() command: subject is null.", new System.Object[] { DialogueDebug.Prefix })); if ((target == null) && DialogueDebug.logWarnings) Debug.LogWarning(string.Format("{0}: Sequencer: LookAt() command: target is null.", new System.Object[] { DialogueDebug.Prefix })); if ((subject != target) && (subject != null) && (target != null)) { DoLookAt(subject, target.position, yAxisOnly); } } return true; } else { return false; } } private void DoLookAt(Transform subject, Vector3 position, bool yAxisOnly) { if (yAxisOnly) { subject.LookAt(new Vector3(position.x, subject.position.y, position.z)); } else { subject.LookAt(position); } } /// <summary> /// Handles NavMeshAgent(stop|destination, [agent]) /// /// - stop|destination: 'stop' stops the agent. Otherwise specify a destination GameObject. /// - agent: NavMeshAgent GameObject. Default: speaker. /// </summary> private bool HandleNavMeshAgentInternally(string commandName, string[] args) { var stop = string.Equals(SequencerTools.GetParameter(args, 0), "stop", System.StringComparison.OrdinalIgnoreCase); var destination = stop ? null : SequencerTools.GetSubject(SequencerTools.GetParameter(args, 0), m_speaker, m_listener); var subject = SequencerTools.GetSubject(SequencerTools.GetParameter(args, 1), m_speaker, m_listener); #if UNITY_5_3 || UNITY_5_4 var navMeshAgent = (subject != null) ? subject.GetComponent<NavMeshAgent>() : null; #else var navMeshAgent = (subject != null) ? subject.GetComponent<UnityEngine.AI.NavMeshAgent>() : null; #endif if (!stop && destination == null) { if (DialogueDebug.logWarnings) Debug.LogWarning("Dialogue System: Sequencer: NavMeshAgent(" + SequencerTools.GetParameter(args, 0) + "," + SequencerTools.GetParameter(args, 1) + "): Destination not found."); } else if (navMeshAgent == null) { if (DialogueDebug.logWarnings) Debug.LogWarning("Dialogue System: Sequencer: NavMeshAgent(" + SequencerTools.GetParameter(args, 0) + "," + SequencerTools.GetParameter(args, 1) + "): NavMeshAgent subject not found."); } else { if (DialogueDebug.logInfo) Debug.Log("Dialogue System: Sequencer: NavMeshAgent(" + SequencerTools.GetParameter(args, 0) + "," + SequencerTools.GetParameter(args, 1) + ")"); if (!stop) navMeshAgent.SetDestination(destination.position); #if UNITY_5_3 || UNITY_5_4 if (stop) navMeshAgent.Stop(); #else navMeshAgent.isStopped = stop; #endif } return true; } /// <summary> /// Handles the "SendMessage(methodName[, arg[, gameobject|speaker|listener|everyone[, broadcast]]])" action. /// This action calls GameObject.SendMessage(methodName, arg) on the subject. Doesn't /// require receiver. /// /// Arguments: /// -# A methodName to run on the subject. /// -# (Optional) A string argument to pass to the method. /// -# (Optional) The subject; can be speaker, listener, or the name of a game object. Default: speaker. /// </summary> private bool HandleSendMessageInternally(string commandName, bool upwards, string[] args) { string methodName = SequencerTools.GetParameter(args, 0); string arg = SequencerTools.GetParameter(args, 1); string subjectArg = SequencerTools.GetParameter(args, 2); bool everyone = string.Equals(subjectArg, "everyone", StringComparison.OrdinalIgnoreCase); Transform subject = everyone ? DialogueManager.instance.transform : SequencerTools.GetSubject(SequencerTools.GetParameter(args, 2), m_speaker, m_listener); bool broadcast = string.Equals(SequencerTools.GetParameter(args, 3), "broadcast", StringComparison.OrdinalIgnoreCase); if (DialogueDebug.logInfo) Debug.Log(string.Format("{0}: Sequencer: {1}({2}, {3}, {4}, {5})", new System.Object[] { DialogueDebug.Prefix, commandName, methodName, arg, subject, SequencerTools.GetParameter(args, 3) })); if ((subject == null) && DialogueDebug.logWarnings) Debug.LogWarning(string.Format("{0}: Sequencer: {1}() command: subject is null.", new System.Object[] { DialogueDebug.Prefix, commandName })); if (string.IsNullOrEmpty(methodName) && DialogueDebug.logWarnings) Debug.LogWarning(string.Format("{0}: Sequencer: {1}() command: message is blank.", new System.Object[] { DialogueDebug.Prefix, commandName })); if (upwards && broadcast && DialogueDebug.logWarnings) Debug.LogWarning(string.Format("{0}: Sequencer: {1}() command: 'broadcast' is ignored by SendCommandUpwards.", new System.Object[] { DialogueDebug.Prefix, commandName })); if (upwards && everyone && DialogueDebug.logWarnings) Debug.LogWarning(string.Format("{0}: Sequencer: {1}() command: 'everyone' is ignored by SendCommandUpwards.", new System.Object[] { DialogueDebug.Prefix, commandName })); if (subject != null && !string.IsNullOrEmpty(methodName)) { if (upwards) { subject.SendMessageUpwards(methodName, arg, SendMessageOptions.DontRequireReceiver); } else { if (everyone) { Tools.SendMessageToEveryone(methodName, arg); } else if (broadcast) { subject.BroadcastMessage(methodName, arg, SendMessageOptions.DontRequireReceiver); } else { subject.SendMessage(methodName, arg, SendMessageOptions.DontRequireReceiver); } } } return true; } /// <summary> /// Handles the "SetActive(gameobject[, true|false|flip])" action. /// /// Arguments: /// -# The name of a game object. Can't be speaker or listener, since they're involved in the conversation. /// -# (Optional) true, false, or flip (negate the current value). /// </summary> private bool HandleSetActiveInternally(string commandName, string[] args) { var specifier = SequencerTools.GetParameter(args, 0); string arg = SequencerTools.GetParameter(args, 1); // Special handling for 'tag=': if (SequencerTools.SpecifierSpecifiesTag(specifier)) { var tag = SequencerTools.GetSpecifiedTag(specifier); if (DialogueDebug.logInfo) Debug.Log(string.Format("{0}: Sequencer: SetActive({1}, {2}): (all GameObjects matching tag)", new System.Object[] { DialogueDebug.Prefix, specifier, arg })); if (string.Equals(arg, "false", StringComparison.OrdinalIgnoreCase)) { // Deactivating is easy; just use FindGameObjectsWithTag: var gameObjects = GameObject.FindGameObjectsWithTag(tag); for (int i = 0; i < gameObjects.Length; i++) { gameObjects[i].SetActive(false); } } else { // Activating or flipping requires finding objects even if they're inactive: var gameObjects = Tools.FindGameObjectsWithTagHard(tag); for (int i = 0; i < gameObjects.Length; i++) { var go = gameObjects[i]; bool newValue = string.Equals(arg, "flip", StringComparison.OrdinalIgnoreCase) ? !go.activeSelf : true; go.SetActive(newValue); } } return true; } var subject = SequencerTools.GetSubject(specifier, speaker, listener); //---Was: SequencerTools.FindSpecifier(specifier); if (DialogueDebug.logInfo) Debug.Log(string.Format("{0}: Sequencer: SetActive({1}, {2})", new System.Object[] { DialogueDebug.Prefix, subject, arg })); if (subject == null) { if (DialogueDebug.logWarnings) Debug.LogWarning(string.Format("{0}: Sequencer: SetActive() command: subject '{1}' is null.", new System.Object[] { DialogueDebug.Prefix, ((args.Length > 0) ? args[0] : string.Empty) })); } else if ((subject == m_speaker) || (subject == m_listener)) { if (DialogueDebug.logWarnings) Debug.LogWarning(string.Format("{0}: Sequencer: SetActive() command: subject '{1}' cannot be speaker or listener.", new System.Object[] { DialogueDebug.Prefix, ((args.Length > 0) ? args[0] : string.Empty) })); } else { bool newValue = true; if (!string.IsNullOrEmpty(arg)) { if (string.Equals(arg.ToLower(), "false")) newValue = false; else if (string.Equals(arg.ToLower(), "flip")) newValue = !subject.gameObject.activeSelf; } subject.gameObject.SetActive(newValue); } return true; } /// <summary> /// Handles the "SetEnabled(component[, true|false|flip[, subject]])" action. /// /// Arguments: /// -# The name of a component on the subject. /// -# (Optional) true, false, or flip (negate the current value). /// -# (Optional) The subject (speaker, listener, or the name of a game object); defaults to speaker. /// </summary> private bool HandleSetEnabledInternally(string commandName, string[] args) { string componentName = SequencerTools.GetParameter(args, 0); string arg = SequencerTools.GetParameter(args, 1); string specifier = SequencerTools.GetParameter(args, 2); // Special handling for 'tag=': if (SequencerTools.SpecifierSpecifiesTag(specifier)) { var tag = SequencerTools.GetSpecifiedTag(specifier); if (DialogueDebug.logInfo) Debug.Log(string.Format("{0}: Sequencer: SetEnabled({1}, {2}, {3})", new System.Object[] { DialogueDebug.Prefix, componentName, arg, specifier })); var gameObjects = GameObject.FindGameObjectsWithTag(tag); for (int i = 0; i < gameObjects.Length; i++) { var go = gameObjects[i]; var comp = (go != null) ? go.GetComponent(componentName) as Component : null; if (comp != null) { Toggle state = Toggle.True; if (!string.IsNullOrEmpty(arg)) { if (string.Equals(arg.ToLower(), "false")) state = Toggle.False; else if (string.Equals(arg.ToLower(), "flip")) state = Toggle.Flip; } Tools.SetComponentEnabled(comp, state); } } return true; } Transform subject = SequencerTools.GetSubject(specifier, m_speaker, m_listener); if (DialogueDebug.logInfo) Debug.Log(string.Format("{0}: Sequencer: SetEnabled({1}, {2}, {3})", new System.Object[] { DialogueDebug.Prefix, componentName, arg, subject })); if (subject == null) { if (DialogueDebug.logWarnings) Debug.LogWarning(string.Format("{0}: Sequencer: SetEnabled() command: subject is null.", new System.Object[] { DialogueDebug.Prefix })); } else { Component component = subject.GetComponent(componentName) as Component; if (component == null) { if (DialogueDebug.logWarnings) Debug.LogWarning(string.Format("{0}: Sequencer: SetEnabled() command: component '{1}' not found on {2}.", new System.Object[] { DialogueDebug.Prefix, componentName, subject.name })); } else { Toggle state = Toggle.True; if (!string.IsNullOrEmpty(arg)) { if (string.Equals(arg.ToLower(), "false")) state = Toggle.False; else if (string.Equals(arg.ToLower(), "flip")) state = Toggle.Flip; } Tools.SetComponentEnabled(component, state); } } return true; } /// <summary> /// Handles the ClearSubtitleText(panel# | all) sequencer command. /// </summary> private bool HandleClearSubtitleText(string commandName, string[] args) { string panelID = SequencerTools.GetParameter(args, 1); var all = string.Equals(panelID, "all", StringComparison.OrdinalIgnoreCase); var panelNumber = all ? 0 : Tools.StringToInt(panelID); if (DialogueDebug.logInfo) Debug.Log(string.Format("{0}: Sequencer: ClearSubtitleText({1})", new System.Object[] { DialogueDebug.Prefix, panelID })); var standardDialogueUI = DialogueManager.dialogueUI as StandardDialogueUI; if (standardDialogueUI != null) { if (all) { for (int i = 0; i < standardDialogueUI.conversationUIElements.subtitlePanels.Length; i++) { if (standardDialogueUI.conversationUIElements.subtitlePanels[i] == null) continue; standardDialogueUI.conversationUIElements.subtitlePanels[i].ClearText(); } } else if (0 <= panelNumber && panelNumber < standardDialogueUI.conversationUIElements.subtitlePanels.Length && standardDialogueUI.conversationUIElements.subtitlePanels[panelNumber] != null) { standardDialogueUI.conversationUIElements.subtitlePanels[panelNumber].ClearText(); } } return true; } private List<int> m_setDialoguePanelPreviouslyOpenSubtitlePanels = null; private List<int> m_setDialoguePanelPreviouslyOpenMenuPanels = null; private List<bool> m_setDialoguePanelPreviousClearText = null; private List<bool> m_setDialoguePanelPreviousContinueButtonStates = null; public void SetDialoguePanel(bool show, bool immediate) { var dialogueUI = DialogueManager.dialogueUI as AbstractDialogueUI; if (dialogueUI != null) { var standardDialogueUI = dialogueUI as StandardDialogueUI; if (show) { // Show dialogue panel: dialogueUI.dialogueControls.Show(); // Also re-open any recorded previously-open panels: if (standardDialogueUI != null) { if (m_setDialoguePanelPreviouslyOpenSubtitlePanels != null) { for (int i = 0; i < m_setDialoguePanelPreviouslyOpenSubtitlePanels.Count; i++) { var subtitlePanelNumber = m_setDialoguePanelPreviouslyOpenSubtitlePanels[i]; standardDialogueUI.conversationUIElements.subtitlePanels[subtitlePanelNumber].panelState = UIPanel.PanelState.Closed; standardDialogueUI.conversationUIElements.subtitlePanels[subtitlePanelNumber].Open(); standardDialogueUI.conversationUIElements.subtitlePanels[subtitlePanelNumber].ActivateUIElements(); standardDialogueUI.conversationUIElements.subtitlePanels[subtitlePanelNumber].clearTextOnClose = m_setDialoguePanelPreviousClearText[subtitlePanelNumber]; if (m_setDialoguePanelPreviousContinueButtonStates[subtitlePanelNumber] == true) standardDialogueUI.conversationUIElements.subtitlePanels[subtitlePanelNumber].ShowContinueButton(); } } if (m_setDialoguePanelPreviouslyOpenMenuPanels != null) { for (int i = 0; i < m_setDialoguePanelPreviouslyOpenMenuPanels.Count; i++) { var menuPanelNumber = m_setDialoguePanelPreviouslyOpenMenuPanels[i]; standardDialogueUI.conversationUIElements.menuPanels[menuPanelNumber].panelState = UIPanel.PanelState.Closed; standardDialogueUI.conversationUIElements.menuPanels[menuPanelNumber].Open(); } } } } else { // Record currently open panels: if (standardDialogueUI != null) { if (m_setDialoguePanelPreviouslyOpenMenuPanels == null) m_setDialoguePanelPreviouslyOpenMenuPanels = new List<int>(); if (m_setDialoguePanelPreviouslyOpenSubtitlePanels == null) m_setDialoguePanelPreviouslyOpenSubtitlePanels = new List<int>(); if (m_setDialoguePanelPreviousClearText == null) m_setDialoguePanelPreviousClearText = new List<bool>(); if (m_setDialoguePanelPreviousContinueButtonStates == null) m_setDialoguePanelPreviousContinueButtonStates = new List<bool>(); m_setDialoguePanelPreviouslyOpenMenuPanels.Clear(); m_setDialoguePanelPreviouslyOpenSubtitlePanels.Clear(); m_setDialoguePanelPreviousClearText.Clear(); m_setDialoguePanelPreviousContinueButtonStates.Clear(); for (int i = 0; i < standardDialogueUI.conversationUIElements.subtitlePanels.Length; i++) { if (standardDialogueUI.conversationUIElements.subtitlePanels[i] == null) continue; m_setDialoguePanelPreviousClearText.Add(standardDialogueUI.conversationUIElements.subtitlePanels[i].clearTextOnClose); m_setDialoguePanelPreviousContinueButtonStates.Add(standardDialogueUI.conversationUIElements.subtitlePanels[i].continueButton != null && standardDialogueUI.conversationUIElements.subtitlePanels[i].continueButton.gameObject.activeInHierarchy); standardDialogueUI.conversationUIElements.subtitlePanels[i].clearTextOnClose = false; if (standardDialogueUI.conversationUIElements.subtitlePanels[i].isOpen) { if (immediate) standardDialogueUI.conversationUIElements.subtitlePanels[i].HideImmediate(); else standardDialogueUI.conversationUIElements.subtitlePanels[i].Close(); m_setDialoguePanelPreviouslyOpenSubtitlePanels.Add(i); } } for (int i = 0; i < standardDialogueUI.conversationUIElements.menuPanels.Length; i++) { if (standardDialogueUI.conversationUIElements.menuPanels[i] == null) continue; if (standardDialogueUI.conversationUIElements.menuPanels[i].isOpen) { m_setDialoguePanelPreviouslyOpenMenuPanels.Add(i); if (immediate) standardDialogueUI.conversationUIElements.menuPanels[i].HideImmediate(); else standardDialogueUI.conversationUIElements.menuPanels[i].Close(); } } if (immediate) standardDialogueUI.conversationUIElements.HideImmediate(); } // Then hide dialogue panel: dialogueUI.dialogueControls.Hide(); } } } /// <summary> /// Handles the "SetDialoguePanel(true|false)" action. /// /// Arguments: /// -# true|false: Show or hide the main dialogue panel. /// </summary> private bool HandleSetDialoguePanelInternally(string commandName, string[] args) { var arg = SequencerTools.GetParameter(args, 0); if (!(string.Equals(arg, "true", StringComparison.OrdinalIgnoreCase) || string.Equals(arg, "false", StringComparison.OrdinalIgnoreCase))) { if (DialogueDebug.logWarnings) Debug.LogWarning(string.Format("{0}: Sequencer: SetDialoguePanel({1}): Parameter must be true or false", new System.Object[] { DialogueDebug.Prefix, arg })); return true; } var show = string.Equals(arg, "true", StringComparison.OrdinalIgnoreCase); var immediate = string.Equals(SequencerTools.GetParameter(args, 1), "immediate", StringComparison.OrdinalIgnoreCase); if (DialogueDebug.logInfo) Debug.Log(string.Format("{0}: Sequencer: SetDialoguePanel({1})", new System.Object[] { DialogueDebug.Prefix, show })); SetDialoguePanel(show, immediate); //var dialogueUI = DialogueManager.dialogueUI as AbstractDialogueUI; //if (dialogueUI != null) //{ // var standardDialogueUI = dialogueUI as StandardDialogueUI; // if (show) // { // // Show dialogue panel: // dialogueUI.dialogueControls.Show(); // // Also re-open any recorded previously-open panels: // if (standardDialogueUI != null) // { // if (m_setDialoguePanelPreviouslyOpenSubtitlePanels != null) // { // for (int i = 0; i < m_setDialoguePanelPreviouslyOpenSubtitlePanels.Count; i++) // { // var subtitlePanelNumber = m_setDialoguePanelPreviouslyOpenSubtitlePanels[i]; // standardDialogueUI.conversationUIElements.subtitlePanels[subtitlePanelNumber].panelState = UIPanel.PanelState.Closed; // standardDialogueUI.conversationUIElements.subtitlePanels[subtitlePanelNumber].Open(); // } // } // if (m_setDialoguePanelPreviouslyOpenMenuPanels != null) // { // for (int i = 0; i < m_setDialoguePanelPreviouslyOpenMenuPanels.Count; i++) // { // var menuPanelNumber = m_setDialoguePanelPreviouslyOpenMenuPanels[i]; // standardDialogueUI.conversationUIElements.menuPanels[menuPanelNumber].panelState = UIPanel.PanelState.Closed; // standardDialogueUI.conversationUIElements.menuPanels[menuPanelNumber].Open(); // } // } // } // } // else // { // // Record currently open panels: // if (standardDialogueUI != null) // { // if (m_setDialoguePanelPreviouslyOpenMenuPanels == null) m_setDialoguePanelPreviouslyOpenMenuPanels = new List<int>(); // if (m_setDialoguePanelPreviouslyOpenSubtitlePanels == null) m_setDialoguePanelPreviouslyOpenSubtitlePanels = new List<int>(); // m_setDialoguePanelPreviouslyOpenMenuPanels.Clear(); // m_setDialoguePanelPreviouslyOpenSubtitlePanels.Clear(); // for (int i = 0; i < standardDialogueUI.conversationUIElements.subtitlePanels.Length; i++) // { // if (standardDialogueUI.conversationUIElements.subtitlePanels[i] == null) continue; // if (standardDialogueUI.conversationUIElements.subtitlePanels[i].isOpen) // { // if (immediate) standardDialogueUI.conversationUIElements.subtitlePanels[i].HideImmediate(); // else standardDialogueUI.conversationUIElements.subtitlePanels[i].Close(); // m_setDialoguePanelPreviouslyOpenSubtitlePanels.Add(i); // } // } // for (int i = 0; i < standardDialogueUI.conversationUIElements.menuPanels.Length; i++) // { // if (standardDialogueUI.conversationUIElements.menuPanels[i] == null) continue; // if (standardDialogueUI.conversationUIElements.menuPanels[i].isOpen) // { // m_setDialoguePanelPreviouslyOpenMenuPanels.Add(i); // if (immediate) standardDialogueUI.conversationUIElements.menuPanels[i].HideImmediate(); // else standardDialogueUI.conversationUIElements.menuPanels[i].Close(); // } // } // if (immediate) standardDialogueUI.conversationUIElements.HideImmediate(); // } // // Then hide dialogue panel: // dialogueUI.dialogueControls.Hide(); // } //} return true; } /// <summary> /// Handles the "OpenPanel(panelNum, [open|close|focus|unfocus])" action. /// /// Arguments: /// -# The panel number or 'default' or 'bark'. /// -# The state to put the panel in. Default: open. /// </summary> private bool HandleOpenPanelInternally(string commandName, string[] args) { string panelID = SequencerTools.GetParameter(args, 0); var subtitlePanelNumber = string.Equals(panelID, "default", StringComparison.OrdinalIgnoreCase) ? SubtitlePanelNumber.Default : string.Equals(panelID, "bark", StringComparison.OrdinalIgnoreCase) ? SubtitlePanelNumber.UseBarkUI : PanelNumberUtility.IntToSubtitlePanelNumber(Tools.StringToInt(panelID)); var mode = SequencerTools.GetParameter(args, 1); if (string.IsNullOrEmpty(mode)) mode = "open"; if (DialogueDebug.logInfo) Debug.Log(string.Format("{0}: Sequencer: OpenPanel({1}, {2})", new System.Object[] { DialogueDebug.Prefix, subtitlePanelNumber, mode })); var standardDialogueUI = DialogueManager.dialogueUI as StandardDialogueUI; if (standardDialogueUI != null) { var panels = standardDialogueUI.conversationUIElements.subtitlePanels; var i = PanelNumberUtility.GetSubtitlePanelIndex(subtitlePanelNumber); if (0 <= i && i < panels.Length) { var panel = panels[i]; if (string.Equals("open", mode, StringComparison.OrdinalIgnoreCase)) { standardDialogueUI.conversationUIElements.standardSubtitleControls.OpenSubtitlePanelLikeStart(subtitlePanelNumber); } else if (string.Equals("close", mode, StringComparison.OrdinalIgnoreCase)) { panel.Close(); } else if (string.Equals("focus", mode, StringComparison.OrdinalIgnoreCase)) { if (!panel.isOpen) panel.Open(); panel.Focus(); } else if (string.Equals("unfocus", mode, StringComparison.OrdinalIgnoreCase)) { panel.Unfocus(); } else { if (DialogueDebug.logWarnings) Debug.LogWarning(string.Format("{0}: Sequencer: OpenPanel({1}, {2}): Unrecognized mode.", new System.Object[] { DialogueDebug.Prefix, subtitlePanelNumber, mode })); } } else { if (DialogueDebug.logWarnings) Debug.LogWarning(string.Format("{0}: Sequencer: OpenPanel({1}, {2}): Invalid panel number.", new System.Object[] { DialogueDebug.Prefix, subtitlePanelNumber, mode })); } } else { if (DialogueDebug.logWarnings) Debug.LogWarning(string.Format("{0}: Sequencer: OpenPanel({1}, {2}): Current dialogue UI is not a Standard Dialogue UI.", new System.Object[] { DialogueDebug.Prefix, subtitlePanelNumber, mode })); } return true; } private bool HandleHidePanelInternally(string commandName, string[] args) { var panelNumber = SequencerTools.GetParameterAsInt(args, 0); var portraitOnly = string.Equals("portrait", SequencerTools.GetParameter(args, 1), StringComparison.OrdinalIgnoreCase); var portraitImageOnly = string.Equals("portraitimage", SequencerTools.GetParameter(args, 1), StringComparison.OrdinalIgnoreCase); var dialogueUI = DialogueManager.dialogueUI as StandardDialogueUI; var commandSummary = "HidePanel(" + panelNumber + (portraitOnly ? ", portrait" : string.Empty) + ")"; if (dialogueUI == null) { if (DialogueDebug.logWarnings) Debug.LogWarning("Dialogue System: Sequencer: " + commandSummary + " can't run. Not using a Standard Dialogue UI."); } else if (!(0 <= panelNumber && panelNumber < dialogueUI.conversationUIElements.subtitlePanels.Length)) { if (DialogueDebug.logWarnings) Debug.LogWarning("Dialogue System: Sequencer: " + commandSummary + "dialogue UI doesn't have panel #" + panelNumber + "."); } else { if (DialogueDebug.logInfo) Debug.Log("Dialogue System: Sequencer: " + commandSummary); var panel = dialogueUI.conversationUIElements.subtitlePanels[panelNumber]; if (panel == null) return true; if (portraitOnly) { Tools.SetGameObjectActive(panel.portraitImage, false); Tools.SetGameObjectActive(panel.portraitName.gameObject, false); } else if (portraitImageOnly) { Tools.SetGameObjectActive(panel.portraitImage, false); } else { panel.Close(); } } return true; } /// <summary> /// Handles the "SetPanel(actorName, panelNum)" action. /// /// Arguments: /// -# The name of a GameObject or actor in the dialogue database. Default: speaker. /// -# The panel number or 'default' or 'bark'. /// </summary> private bool HandleSetPanelInternally(string commandName, string[] args) { string actorName = SequencerTools.GetParameter(args, 0); var actorTransform = CharacterInfo.GetRegisteredActorTransform(actorName) ?? SequencerTools.GetSubject(actorName, speaker, listener, speaker); string panelID = SequencerTools.GetParameter(args, 1); var subtitlePanelNumber = string.Equals(panelID, "default", StringComparison.OrdinalIgnoreCase) ? SubtitlePanelNumber.Default : string.Equals(panelID, "bark", StringComparison.OrdinalIgnoreCase) ? SubtitlePanelNumber.UseBarkUI : PanelNumberUtility.IntToSubtitlePanelNumber(Tools.StringToInt(panelID)); var dialogueActor = (actorTransform != null) ? actorTransform.GetComponent<DialogueActor>() : null; if (dialogueActor != null) { if (DialogueDebug.logInfo) Debug.Log(string.Format("{0}: Sequencer: SetPanel({1}, {2})", new System.Object[] { DialogueDebug.Prefix, actorTransform, subtitlePanelNumber }), actorTransform); dialogueActor.SetSubtitlePanelNumber(subtitlePanelNumber); return true; } else { var actor = DialogueManager.masterDatabase.GetActor(actorName); if (actor == null) { if (DialogueDebug.logWarnings) Debug.LogWarning(string.Format("{0}: Sequencer: SetPanel({1}, {2}): No actor named {1}", new System.Object[] { DialogueDebug.Prefix, actorName, subtitlePanelNumber })); } else { if (DialogueDebug.logInfo) Debug.Log(string.Format("{0}: Sequencer: SetPanel({1}, {2})", new System.Object[] { DialogueDebug.Prefix, actorName, subtitlePanelNumber })); var standardDialogueUI = DialogueManager.dialogueUI as IStandardDialogueUI; if (standardDialogueUI != null) { standardDialogueUI.OverrideActorPanel(actor, subtitlePanelNumber); } } return true; } } /// <summary> /// Handles the "SetMenuPanel(actorName, panelNum)" action. /// /// Arguments: /// -# The name of a GameObject or actor in the dialogue database. Default: speaker. /// -# The panel number or 'default'. /// </summary> private bool HandleSetMenuPanelInternally(string commandName, string[] args) { string actorName = SequencerTools.GetParameter(args, 0); Transform actorTransform = null; if (string.IsNullOrEmpty(actorName) || string.Equals("speaker", actorName, StringComparison.OrdinalIgnoreCase)) { actorTransform = speaker; } else if (string.Equals("listener", actorName, StringComparison.OrdinalIgnoreCase)) { actorTransform = listener; } else { actorTransform = CharacterInfo.GetRegisteredActorTransform(actorName); if (actorTransform == null) { var actorGO = GameObject.Find(actorName); if (actorGO != null) actorTransform = actorGO.transform; } } string panelID = SequencerTools.GetParameter(args, 1); var menuPanelNumber = string.Equals(panelID, "default", StringComparison.OrdinalIgnoreCase) ? MenuPanelNumber.Default : PanelNumberUtility.IntToMenuPanelNumber(Tools.StringToInt(panelID)); var dialogueActor = (actorTransform != null) ? actorTransform.GetComponent<DialogueActor>() : null; if (actorTransform != null) { // Prefer to override menu panel by transform / DialogueActor: if (DialogueDebug.logInfo) Debug.Log(string.Format("{0}: Sequencer: SetMenuPanel({1}, {2})", new System.Object[] { DialogueDebug.Prefix, actorTransform, menuPanelNumber }), actorTransform); if (dialogueActor != null) { dialogueActor.SetMenuPanelNumber(menuPanelNumber); // Also sets dialogue UI. } else { var standardDialogueUI = DialogueManager.dialogueUI as IStandardDialogueUI; if (standardDialogueUI != null) { standardDialogueUI.OverrideActorMenuPanel(actorTransform, menuPanelNumber, null); } } return true; } else { // If no transform, override menu panel by actor ID: if (DialogueDebug.logInfo) Debug.Log(string.Format("{0}: Sequencer: SetMenuPanel({1}, {2})", new System.Object[] { DialogueDebug.Prefix, actorName, menuPanelNumber })); if (string.Equals(actorName, "speaker", StringComparison.OrdinalIgnoreCase)) { var conversation = DialogueManager.masterDatabase.GetConversation(DialogueManager.lastConversationID); if (conversation != null) actorName = DialogueManager.masterDatabase.GetActor(conversation.ActorID).Name; } var actor = DialogueManager.masterDatabase.GetActor(actorName); var standardDialogueUI = DialogueManager.dialogueUI as StandardDialogueUI; if (actor != null && standardDialogueUI != null) { standardDialogueUI.OverrideActorMenuPanel(actor, menuPanelNumber, null); return true; } } if (DialogueDebug.logWarnings) Debug.LogWarning(string.Format("{0}: Sequencer: SetMenuPanel({1}, {2}): Requires a DialogueActor or GameObject named {1}", new System.Object[] { DialogueDebug.Prefix, actorName, menuPanelNumber })); return false; } /// <summary> /// Handles the "SetPortrait(actorName, textureName)" action. /// /// Arguments: /// -# The name of an actor in the dialogue database. /// -# The name of a texture that can be loaded from Resources, or 'default', /// or 'pic=#' or 'pic=varName'. /// </summary> private bool HandleSetPortraitInternally(string commandName, string[] args) { string actorName = SequencerTools.GetParameter(args, 0); string textureName = SequencerTools.GetParameter(args, 1); if (DialogueDebug.logInfo) Debug.Log(string.Format("{0}: Sequencer: SetPortrait({1}, {2})", new System.Object[] { DialogueDebug.Prefix, actorName, textureName })); Actor actor = DialogueManager.masterDatabase.GetActor(actorName); if (actor == null) { var actorGameObject = SequencerTools.GetSubject(actorName, speaker, listener, speaker); actor = DialogueManager.masterDatabase.GetActor(DialogueActor.GetActorName(actorGameObject)); if (actor != null) actorName = actor.Name; } bool isDefault = string.Equals(textureName, "default"); bool isPicTag = (textureName != null) && textureName.StartsWith("pic="); Sprite sprite = null; if (isDefault) { sprite = null; } else if (isPicTag) { string picValue = textureName.Substring("pic=".Length); int picNumber; if (!int.TryParse(picValue, out picNumber)) { if (DialogueLua.DoesVariableExist(picValue)) { picNumber = DialogueLua.GetVariable(picValue).asInt; } else { Debug.LogWarning(string.Format("{0}: Sequencer: SetPortrait() command: pic variable '{1}' not found.", new System.Object[] { DialogueDebug.Prefix, picValue })); } } sprite = (actor != null) ? actor.GetPortraitSprite(picNumber) : null; } else { DialogueManager.LoadAsset(textureName, typeof(Texture2D), (asset) => { var spriteAsset = UITools.CreateSprite(asset as Texture2D); if (DialogueDebug.logWarnings) { if (actor == null) Debug.LogWarning(string.Format("{0}: Sequencer: SetPortrait() command: actor '{1}' not found.", new System.Object[] { DialogueDebug.Prefix, actorName })); if ((spriteAsset == null) && !isDefault) Debug.LogWarning(string.Format("{0}: Sequencer: SetPortrait() command: texture '{1}' not found.", new System.Object[] { DialogueDebug.Prefix, textureName })); } if (actor != null) { if (isDefault) { DialogueLua.SetActorField(actorName, DialogueSystemFields.CurrentPortrait, string.Empty); } else { if (spriteAsset != null) DialogueLua.SetActorField(actorName, DialogueSystemFields.CurrentPortrait, textureName); } DialogueManager.instance.SetActorPortraitSprite(actorName, spriteAsset); } }); return true; } if (DialogueDebug.logWarnings) { if (actor == null) Debug.LogWarning(string.Format("{0}: Sequencer: SetPortrait() command: actor '{1}' not found.", new System.Object[] { DialogueDebug.Prefix, actorName })); if ((sprite == null) && !isDefault) Debug.LogWarning(string.Format("{0}: Sequencer: SetPortrait() command: texture '{1}' not found.", new System.Object[] { DialogueDebug.Prefix, textureName })); } if (actor != null) { if (isDefault) { DialogueLua.SetActorField(actorName, DialogueSystemFields.CurrentPortrait, string.Empty); } else { if (sprite != null) DialogueLua.SetActorField(actorName, DialogueSystemFields.CurrentPortrait, textureName); } DialogueManager.instance.SetActorPortraitSprite(actorName, sprite); } return true; } /// <summary> /// Handles the "SetMenuPanel(actorName, panelNum)" action. /// /// Arguments: /// -# The name of a GameObject or actor in the dialogue database. Default: speaker. /// -# The panel number or 'default'. /// </summary> private bool HandleSetTimeoutInternally(string commandName, string[] args) { float duration = SequencerTools.GetParameterAsFloat(args, 0); if (DialogueDebug.logInfo) Debug.Log(string.Format(System.Globalization.CultureInfo.InvariantCulture, "{0}: Sequencer: SetTimeout({1})", DialogueDebug.Prefix, duration)); if (DialogueManager.displaySettings != null && DialogueManager.displaySettings.inputSettings != null) { DialogueManager.displaySettings.inputSettings.responseTimeout = duration; } return true; } private static DisplaySettings.SubtitleSettings.ContinueButtonMode savedContinueButtonMode = DisplaySettings.SubtitleSettings.ContinueButtonMode.Always; /// <summary> /// Handles "SetContinueMode(true|false)". /// </summary> private bool HandleSetContinueModeInternally(string commandName, string[] args) { if (args == null || args.Length < 1) { if (DialogueDebug.logWarnings) Debug.LogWarning(string.Format("{0}: Sequencer: SetContinueMode(true|false|original) requires a true/false/original parameter", new System.Object[] { DialogueDebug.Prefix })); return true; } else { var arg = SequencerTools.GetParameter(args, 0); if (DialogueDebug.logInfo) Debug.Log(string.Format("{0}: Sequencer: SetContinueMode({1})", new System.Object[] { DialogueDebug.Prefix, arg })); if (DialogueManager.instance == null || DialogueManager.displaySettings == null || DialogueManager.displaySettings.subtitleSettings == null) return true; if (string.Equals(arg, "true", StringComparison.OrdinalIgnoreCase)) { savedContinueButtonMode = DialogueManager.displaySettings.subtitleSettings.continueButton; DialogueManager.displaySettings.subtitleSettings.continueButton = DisplaySettings.SubtitleSettings.ContinueButtonMode.Always; } else if (string.Equals(arg, "false", StringComparison.OrdinalIgnoreCase)) { savedContinueButtonMode = DialogueManager.displaySettings.subtitleSettings.continueButton; DialogueManager.displaySettings.subtitleSettings.continueButton = DisplaySettings.SubtitleSettings.ContinueButtonMode.Never; } else if (string.Equals(arg, "original", StringComparison.OrdinalIgnoreCase)) { if (DialogueDebug.logInfo) Debug.Log(string.Format("{0}: Sequencer: SetContinueMode({1}): Restoring original mode {2}", new System.Object[] { DialogueDebug.Prefix, arg, savedContinueButtonMode })); DialogueManager.displaySettings.subtitleSettings.continueButton = savedContinueButtonMode; } else { if (DialogueDebug.logWarnings) Debug.LogWarning(string.Format("{0}: Sequencer: SetContinueMode(true|false|original) requires a true/false/original parameter", new System.Object[] { DialogueDebug.Prefix })); return true; } if (DialogueManager.conversationView != null) { DialogueManager.conversationView.displaySettings.conversationOverrideSettings.continueButton = DialogueManager.displaySettings.subtitleSettings.continueButton; DialogueManager.conversationView.SetupContinueButton(); } return true; } } /// <summary> /// Handles "Continue()", which simulates a continue button click. /// </summary> /// <returns></returns> private bool HandleContinueInternally() { if (DialogueDebug.logInfo) Debug.Log(string.Format("{0}: Sequencer: Continue()", new System.Object[] { DialogueDebug.Prefix })); DialogueManager.instance.BroadcastMessage("OnConversationContinueAll", SendMessageOptions.DontRequireReceiver); return true; } /// <summary> /// Handles "SetVariable(variableName, value)". /// Thanks to Darkkingdom for this sequencer command! /// </summary> private bool HandleSetVariableInternally(string commandName, string[] args) { if (args == null || args.Length < 2) { if (DialogueDebug.logWarnings) Debug.LogWarning(string.Format("{0}: Sequencer: SetVariable(variableName, value) requires two parameters", new System.Object[] { DialogueDebug.Prefix })); } else { var variableName = SequencerTools.GetParameter(args, 0); var variableValue = SequencerTools.GetParameter(args, 1); if (DialogueDebug.logInfo) Debug.Log(string.Format("{0}: Sequencer: SetVariable({1}, {2})", new System.Object[] { DialogueDebug.Prefix, variableName, variableValue })); bool boolValue; float floatValue; if (bool.TryParse(variableValue, out boolValue)) { DialogueLua.SetVariable(variableName, boolValue); } else if (float.TryParse(variableValue, System.Globalization.NumberStyles.Float, System.Globalization.CultureInfo.InvariantCulture, out floatValue)) { DialogueLua.SetVariable(variableName, floatValue); } else { DialogueLua.SetVariable(variableName, variableValue); } } return true; } /// <summary> /// Handles the "ShowAlert([duration])" action. /// /// Arguments: /// -# (Optional) Duration. /// </summary> private bool HandleShowAlertInternally(string commandName, string[] args) { bool hasDuration = ((args.Length > 0) && !string.IsNullOrEmpty(args[0])); float duration = hasDuration ? SequencerTools.GetParameterAsFloat(args, 0) : 0; if (DialogueDebug.logInfo) { if (hasDuration) { Debug.Log(string.Format("{0}: Sequencer: ShowAlert({1})", new System.Object[] { DialogueDebug.Prefix, duration })); } else { Debug.Log(string.Format("{0}: Sequencer: ShowAlert()", new System.Object[] { DialogueDebug.Prefix })); } } try { string message = Lua.Run("return Variable['Alert']").asString; if (!string.IsNullOrEmpty(message)) { Lua.Run("Variable['Alert'] = ''"); if (hasDuration) { DialogueManager.ShowAlert(message, duration); } else { DialogueManager.ShowAlert(message); } } } catch (Exception) { } return true; } /// <summary> /// Handles the "UpdateTracker()" command. /// </summary> private bool HandleUpdateTrackerInternally() { if (DialogueDebug.logInfo) Debug.Log(string.Format("{0}: Sequencer: UpdateTracker()", new System.Object[] { DialogueDebug.Prefix })); DialogueManager.SendUpdateTracker(); return true; } private bool HandleRandomizeNextEntryInternally() { if (DialogueDebug.logInfo) Debug.Log(string.Format("{0}: Sequencer: RandomizeNextEntry()", new System.Object[] { DialogueDebug.Prefix })); if (DialogueManager.conversationController != null) DialogueManager.conversationController.randomizeNextEntry = true; return true; } } }
50.369683
282
0.550362
[ "MIT" ]
lilbonito/hammer_bar
Assets/Plugins/Pixel Crushers/Dialogue System/Scripts/MVC/Sequencer/Sequencer.cs
130,256
C#
namespace Lab3 { partial class Form8 { /// <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.label1 = new System.Windows.Forms.Label(); this.textBox1 = new System.Windows.Forms.TextBox(); this.button1 = new System.Windows.Forms.Button(); this.SuspendLayout(); // // label1 // this.label1.AutoSize = true; this.label1.Location = new System.Drawing.Point(57, 26); this.label1.Name = "label1"; this.label1.Size = new System.Drawing.Size(158, 13); this.label1.TabIndex = 0; this.label1.Text = "Enter number betwwen 1 to 100"; // // textBox1 // this.textBox1.Location = new System.Drawing.Point(60, 64); this.textBox1.Name = "textBox1"; this.textBox1.Size = new System.Drawing.Size(155, 20); this.textBox1.TabIndex = 1; // // button1 // this.button1.Location = new System.Drawing.Point(140, 113); this.button1.Name = "button1"; this.button1.Size = new System.Drawing.Size(75, 23); this.button1.TabIndex = 2; this.button1.Text = "button1"; this.button1.UseVisualStyleBackColor = true; this.button1.Click += new System.EventHandler(this.button1_Click); // // Form8 // this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.ClientSize = new System.Drawing.Size(800, 450); this.Controls.Add(this.button1); this.Controls.Add(this.textBox1); this.Controls.Add(this.label1); this.Name = "Form8"; this.Text = "Form8"; this.ResumeLayout(false); this.PerformLayout(); } #endregion private System.Windows.Forms.Label label1; private System.Windows.Forms.TextBox textBox1; private System.Windows.Forms.Button button1; } }
35.819277
107
0.544904
[ "MIT" ]
BorisLechev/-University
C#/Windows Forms/Lab3/Lab3/Form8.Designer.cs
2,975
C#
// PreregisterOperation using ClubPenguin.Net.Client; using ClubPenguin.Net.Client.Mappers; using ClubPenguin.Net.Domain; using hg.ApiWebKit.core.attributes; using hg.ApiWebKit.mappers; using System; [HttpBasicAuthorization("cp-api-username", "cp-api-password")] [HttpPOST] [HttpPath("cp-api-base-uri", "/player/v1/preregistration")] [HttpAccept("application/json")] public class PreregisterOperation : CPAPIHttpOperation { [HttpQueryString("clientId")] public string ClientID; [HttpResponseJsonBody] public MigrationData ResponseBody; public PreregisterOperation(string clientId) { ClientID = clientId; } protected override void PerformOfflineAction(OfflineDatabase offlineDatabase, IOfflineDefinitionLoader offlineDefinitions) { throw new NotImplementedException(); } }
25.483871
123
0.801266
[ "MIT" ]
smdx24/CPI-Source-Code
ClubPenguin.Net.Client/PreregisterOperation.cs
790
C#
using System.Windows.Controls; namespace Speckle.DesktopUI.Streams.Dialogs.FilterViews { public partial class ParameterFilterView : UserControl { public ParameterFilterView() { InitializeComponent(); } } }
16.642857
56
0.72103
[ "Apache-2.0" ]
ENAC-CNPA/speckle-sharp
DesktopUI/DesktopUI/Streams/Dialogs/FilterViews/PropertyFilterView.xaml.cs
235
C#
using System; using System.Diagnostics; using System.IO; using System.Net; using System.Net.Sockets; using UnityEditor; using UnityEngine; namespace UnityEditor.CacheServerTests { internal class LocalCacheServer : ScriptableSingleton<LocalCacheServer> { [SerializeField] public string m_path; [SerializeField] public int m_port; [SerializeField] public int m_pid = -1; private void Create(int port, ulong size, string cachePath) { var nodeExecutable = Utils.Paths.Combine(EditorApplication.applicationContentsPath, "Tools", "nodejs"); nodeExecutable = Application.platform == RuntimePlatform.WindowsEditor ? Utils.Paths.Combine(nodeExecutable, "node.exe") : Utils.Paths.Combine(nodeExecutable, "bin", "node"); if (!Directory.Exists(cachePath)) Directory.CreateDirectory(cachePath); m_path = cachePath; var cacheServerJs = Utils.Paths.Combine(EditorApplication.applicationContentsPath, "Tools", "CacheServer", "main.js"); var processStartInfo = new ProcessStartInfo(nodeExecutable) { Arguments = "\"" + cacheServerJs + "\"" + " --port " + port + " --path \"" + m_path + "\" --nolegacy" + " --monitor-parent-process " + Process.GetCurrentProcess().Id // node.js has issues running on windows with stdout not redirected. // so we silence logging to avoid that. And also to avoid CacheServer // spamming the editor logs on OS X. + " --silent" + " --size " + size, UseShellExecute = false, CreateNoWindow = true }; var p = new Process {StartInfo = processStartInfo}; p.Start(); m_port = port; m_pid = p.Id; Save(true); } public static string CachePath { get { return instance.m_path; } } public static int Port { get { return instance.m_port; } } public static void Setup(ulong size, string cachePath) { Kill(); instance.Create(GetRandomUnusedPort(), size, cachePath); WaitForServerToComeAlive(instance.m_port); } public static void Kill() { if (instance.m_pid == -1) return; try { var p = Process.GetProcessById(instance.m_pid); p.Kill(); instance.m_pid = -1; } catch { // if we could not get a process, there is non alive. continue. } } public static void Clear() { Kill(); if (Directory.Exists(instance.m_path)) Directory.Delete(instance.m_path, true); } private static void WaitForServerToComeAlive(int port) { var start = DateTime.Now; var maximum = start.AddSeconds(5); while (DateTime.Now < maximum) { if (!PingHost("localhost", port, 10)) continue; Console.WriteLine("Server Came alive after {0} ms", (DateTime.Now - start).TotalMilliseconds); break; } } private static int GetRandomUnusedPort() { var listener = new TcpListener(IPAddress.Any, 0); listener.Start(); var port = ((IPEndPoint)listener.LocalEndpoint).Port; listener.Stop(); return port; } private static bool PingHost(string host, int port, int timeout) { try { using (var client = new TcpClient()) { var result = client.BeginConnect(host, port, null, null); result.AsyncWaitHandle.WaitOne(TimeSpan.FromMilliseconds(timeout)); return client.Connected; } } catch { return false; } } } }
32.313433
130
0.509931
[ "Apache-2.0" ]
GDIVX/QophProject
MVP/Library/PackageCache/[email protected]/Tests/Editor/CacheServer/LocalCacheServer.cs
4,332
C#
 using System.Reflection; using System.Runtime.InteropServices; [assembly: ComVisible(false)] [assembly: Guid("c6dd02fe-9e84-4cdc-a7f0-8517953f5750")]
21.857143
56
0.79085
[ "MIT" ]
TANZAME/ServiceStack.Redis.Cluster
ServiceStack.Redis.Cluster/Properties/AssemblyInfo.cs
155
C#
namespace CloudinaryDotNet.Test { public class TestConstants { public const string CloudName = "testcloud"; public const string DefaultApiKey = "1234"; public const string DefaultApiSecret = "abcd"; public const string DefaultRootPath = "http://res.cloudinary.com/testcloud/"; public const string DefaultVideoUpPath = DefaultRootPath + "video/upload/"; public const string DefaultImageUpPath = DefaultRootPath + "image/upload/"; public const string DefaultImageFetchPath = DefaultRootPath + "image/fetch/"; } }
41.428571
85
0.698276
[ "MIT" ]
jordansjones/CloudinaryDotNet
Shared.Tests/Constants.cs
582
C#
using System.ComponentModel.DataAnnotations; namespace CloudABISSampleWebApp.Models.MatchingServer.Models.Request { /// <summary> /// Register/Update/Verify API Request Model /// </summary> public class BiometricGenericRequest { /// <summary> /// Client-specific key provided by the vendor. /// </summary> [Required(ErrorMessage = "Client Key Is Required")] [DataType(DataType.Text)] [StringLength(50, ErrorMessage = "The {0} must be at least (6) and at most (50) characters long.", MinimumLength = 6)] public string ClientKey { get; set; } /// <summary> /// This is will help you to trace your request full-cycle later. You can put on the request body or the server will be generated and returns with the API response. /// </summary> [DataType(DataType.Text)] [StringLength(32, ErrorMessage = "The {0} must be at least (4) and at most (32) characters long.", MinimumLength = 4)] public string SequenceNo { get; set; } /// <summary> /// The unique identifier (Member ID) of the biometric enrollment that the requested operation will be performed on. /// </summary> public string RegistrationID { get; set; } /// <summary> /// The biometric images with supported engine's images. /// The images data should be a base64 encoded string of the original face/fingerprint/iris image. /// The number of face images might be 1 to 3. When use only one image, use the Position=1. /// The number of finger print images might be 1 to 10. The images position would be 1-10. /// The number of iris images might be 1 to 2. The images position would be 1, 2. /// Supported image formats: JPG, BMP, PNG, WSQ /// </summary> [DataType(DataType.Text)] //[Required(ErrorMessage = "Images Is Required")] public BiometricImages Images { get; set; } = null; } }
49.725
172
0.638512
[ "Apache-2.0" ]
kernello/cloudabisv12-csharp-web-sample
CloudABISSampleWebApp/Models/MatchingServer/Models/Request/BiometricGenericRequest.cs
1,991
C#
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; using System.ServiceModel; using Client.BankServiceReference; namespace Client { public partial class Form1 : Form { BankClient proxy; int userNum = -1; public Form1() { InitializeComponent(); } private void button1_Click(object sender, EventArgs e) { if (int.TryParse(textBox1.Text, out int initialMoney)) userNum = proxy.CreateAccount(initialMoney); } private void button2_Click(object sender, EventArgs e) { if(userNum != -1 && int.TryParse(textBox2.Text, out int money)) proxy.Withdraw(money, userNum); } private void button3_Click(object sender, EventArgs e) { if (userNum != -1) textBox3.Text = proxy.GetAccountInfo(userNum).ToString(); } private void Form1_Load(object sender, EventArgs e) { proxy = new BankClient(new InstanceContext(new ClientCallback() {form=this })); } private void textBox2_TextChanged(object sender, EventArgs e) { } private void textBox1_TextChanged(object sender, EventArgs e) { } } }
23.627451
82
0.73112
[ "MIT" ]
Team-on/works
0_homeworks/C#/9 wcf/4/Bank/Client/Form1.cs
1,207
C#
using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Linq; using System.Threading.Tasks; namespace mymgm.Models.AccountViewModels { public class ResetPasswordViewModel { [Required] [EmailAddress] public string Email { get; set; } [Required] [StringLength(100, ErrorMessage = "The {0} must be at least {2} and at max {1} characters long.", MinimumLength = 6)] [DataType(DataType.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; } } }
29.714286
125
0.659856
[ "MIT" ]
elijahlofgren/mymgm
Models/AccountViewModels/ResetPasswordViewModel.cs
832
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.Lighthouse.V20200324.Models { using Newtonsoft.Json; using System.Collections.Generic; using TencentCloud.Common; public class InstanceTrafficPackage : AbstractModel { /// <summary> /// 实例ID。 /// </summary> [JsonProperty("InstanceId")] public string InstanceId{ get; set; } /// <summary> /// 流量包详情列表。 /// </summary> [JsonProperty("TrafficPackageSet")] public TrafficPackage[] TrafficPackageSet{ 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 + "InstanceId", this.InstanceId); this.SetParamArrayObj(map, prefix + "TrafficPackageSet.", this.TrafficPackageSet); } } }
30.843137
94
0.649078
[ "Apache-2.0" ]
TencentCloud/tencentcloud-sdk-dotnet
TencentCloud/Lighthouse/V20200324/Models/InstanceTrafficPackage.cs
1,595
C#
using System; using Newtonsoft.Json; using Primary.Serialization; namespace Primary.Data.Orders { /// <summary> /// Has all the order information, plus the current state of the order. /// </summary> public class OrderStatus : Order { [JsonProperty("orderId")] public string Id { get; set; } public class AccountId { [JsonProperty("id")] public string Id { get; set; } } [JsonProperty("accountId")] public AccountId Account { get; set; } [JsonProperty("execId")] public string ExecutionId { get; set; } [JsonProperty("transactTime")] [JsonConverter(typeof(DateTimeJsonDeserializer))] public DateTime TransactionTime { get; set; } [JsonProperty("avgPx")] public decimal AveragePrice { get; set; } [JsonProperty("lastPx")] public decimal LastPrice { get; set; } /// <summary>Quantity affected in the last operation.</summary> [JsonProperty("lastQty")] public uint LastQuantity { get; set; } /// <summary>Total quantity affected on the order.</summary> [JsonProperty("cumQty")] public uint CumulativeQuantity { get; set; } /// <summary>How much quantity is left on the order.</summary> [JsonProperty("leavesQty")] public uint LeavesQuantity { get; set; } /// <summary>Order status.</summary> [JsonProperty("status")] public Status Status { get; set; } /// <summary>More information about the order status.</summary> [JsonProperty("text")] public string StatusText { get; set; } } }
30.224138
76
0.575014
[ "MIT" ]
naicigam/Primary.Net
Primary/Data/Orders/OrderStatus.cs
1,755
C#
namespace uTinyRipper.Classes.Shaders { public struct SamplerParameter : IAssetReadable { public SamplerParameter(uint sampler, int bindPoint) { Sampler = sampler; BindPoint = bindPoint; } public void Read(AssetReader reader) { Sampler = reader.ReadUInt32(); BindPoint = reader.ReadInt32(); } public uint Sampler { get; set; } public int BindPoint { get; set; } } }
19.047619
54
0.695
[ "MIT" ]
Bluscream/UtinyRipper
uTinyRipperCore/Parser/Classes/Shader/Parameters/SamplerParameter.cs
402
C#
using EF6AspNetWebApi.Data; using LinqKit; using System; using System.Collections.Generic; using System.Linq; using System.Linq.Expressions; using System.Text; using System.Threading.Tasks; namespace EF6AspNetWebApi.Blogs.Posts { public class PostSummaryViewModel { public int Id { get; set; } public string Title { get; set; } public DateTimeOffset Created { get; set; } public static Expression<Func<Post, PostSummaryViewModel>> Map() { return i => new PostSummaryViewModel { Id = i.PostId, Title = i.Title, Created = i.DateCreated }; } public ViewModelToEntity<Post> ToEntityConverter() { return new ViewModelToEntity<Post>( (Id != default, i => i.PostId == Id), (!string.IsNullOrEmpty(Title), i => i.Title == Title), (Created != default, i => i.DateCreated == Created) ); } } public class PostViewModel : PostSummaryViewModel { public BlogSummaryViewModel Blog { get; set; } public string Content { get; set; } public PostSummaryViewModel UpdatedPost { get; set; } public DateTimeOffset? UpdatedAsOfDate { get; set; } public new static Expression<Func<Post, PostViewModel>> Map() { var blogMap = BlogSummaryViewModel.Map(); var postMap = PostSummaryViewModel.Map(); return i => new PostViewModel { Id = i.PostId, Title = i.Title, Created = i.DateCreated, Blog = blogMap.Invoke(i.Blog), Content = i.Content, UpdatedPost = (i.UpdatedPostId == null) ? null : postMap.Invoke(i.UpdatedPost), UpdatedAsOfDate = i.UpdatedAsOfDate }; } } }
30.0625
95
0.557173
[ "MIT" ]
jayoungers/PatchMap
Examples/EF6AspNetWebApi/EF6AspNetWebApi/Blogs/Posts/PostViewModel.cs
1,926
C#
/*----------------------------------------------------------------------- Copyright (c) Microsoft Corporation. Licensed under the MIT license. -----------------------------------------------------------------------*/ using AdsGoFast.Models.Options; using AdsGoFast.SqlServer; using AdsGoFast.TaskMetaData; using Cronos; using Microsoft.Azure.WebJobs; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Options; using Newtonsoft.Json; using Newtonsoft.Json.Linq; using System; using System.Collections.Generic; using System.Data; using System.Data.SqlClient; using System.Linq; using System.Threading.Tasks; namespace AdsGoFast { public class PrepareFrameworkTasksTimerTrigger { private readonly IOptions<ApplicationOptions> _appOptions; public PrepareFrameworkTasksTimerTrigger(IOptions<ApplicationOptions> appOptions) { _appOptions = appOptions; } [FunctionName("PrepareFrameworkTasksTimerTrigger")] public async Task Run([TimerTrigger("0 */2 * * * *")] TimerInfo myTimer, ILogger log, ExecutionContext context) { Guid ExecutionId = context.InvocationId; if (_appOptions.Value.TimerTriggers.EnablePrepareFrameworkTasks) { using (FrameworkRunner FR = new FrameworkRunner(log, ExecutionId)) { FrameworkRunner.FrameworkRunnerWorker worker = PrepareFrameworkTasks.PrepareFrameworkTasksCore; FrameworkRunner.FrameworkRunnerResult result = FR.Invoke("PrepareFrameworkTasksHttpTrigger", worker); } } } } public static class PrepareFrameworkTasks { public static dynamic PrepareFrameworkTasksCore(Logging logging) { TaskMetaDataDatabase TMD = new TaskMetaDataDatabase(); TMD.ExecuteSql(string.Format("Insert into Execution values ('{0}', '{1}', '{2}')", logging.DefaultActivityLogItem.ExecutionUid, DateTimeOffset.Now.ToString("u"), DateTimeOffset.Now.AddYears(999).ToString("u"))); //Check status of running pipelines and calculate available "slots" based on max concurrency settings short _FrameworkWideMaxConcurrency = Shared._ApplicationOptions.FrameworkWideMaxConcurrency; //ToDo: Write Pipelines that need to be checked to Queue for now I have just reduced to only those tasks that have been running for longer than x minutes. //CheckLongRunningPipelines(logging); //Get Count of All runnning pipelines directly from the database short _RunnningPipelines = CountRunnningPipelines(logging); short _AvailableConcurrencySlots = (short)(_FrameworkWideMaxConcurrency - _RunnningPipelines); //Generate new task instances based on task master and schedules CreateTaskInstance(logging); //Is there is Available Slots Proceed if (_AvailableConcurrencySlots > 0) { List<AdsGoFast.TaskMetaData.TaskGroup> _TaskGroups = TaskGroupsStatic.GetActive(); if (_TaskGroups.Count > 0) { short _ConcurrencySlotsAllocated = 0; short _DefaultTasksPerGroup = 0; short _DistributionLoopCounter = 1; //Distribute Concurrency Slots while (_AvailableConcurrencySlots > 0) { DistributeConcurrencySlots(ref _TaskGroups, ref _DefaultTasksPerGroup, ref _ConcurrencySlotsAllocated, ref _AvailableConcurrencySlots, _DistributionLoopCounter); _DistributionLoopCounter += 1; } Table TempTarget = new Table { Schema = "dbo", Name = "#TempGroups" + logging.DefaultActivityLogItem.ExecutionUid.ToString() }; SqlConnection _con = TMD.GetSqlConnection(); TMD.BulkInsert(_TaskGroups.ToDataTable(), TempTarget, true, _con); Dictionary<string, string> _params = new Dictionary<string, string> { { "TempTable", TempTarget.QuotedSchemaAndName() } }; string _sql = GenerateSQLStatementTemplates.GetSQL(System.IO.Path.Combine(Shared._ApplicationBasePath, Shared._ApplicationOptions.LocalPaths.SQLTemplateLocation), "UpdateTaskInstancesWithTaskRunner", _params); TMD.ExecuteSql(_sql, _con); } } return new { }; } public static void DistributeConcurrencySlots(ref List<AdsGoFast.TaskMetaData.TaskGroup> _TaskGroups, ref short _DefaultTasksPerGroup, ref short _ConcurrencySlotsAllocated, ref short _AvailableConcurrencySlots, short DistributionLoopCount) { short TaskGroupLoopCount = 1; short MaxTaskGroupIndex = 32767; //Ensure that we have at least one concurrency slot per group if (_TaskGroups.Count > _AvailableConcurrencySlots) { MaxTaskGroupIndex = _AvailableConcurrencySlots; _DefaultTasksPerGroup = 1; //List<AdsGoFast.TaskMetaData.TaskGroup> _NewTaskGroups = _TaskGroups.Take<AdsGoFast.TaskMetaData.TaskGroup>(_AvailableConcurrencySlots).ToList(); //_TaskGroups = _NewTaskGroups; } else { _DefaultTasksPerGroup = (short)Math.Floor((decimal)(_AvailableConcurrencySlots / _TaskGroups.Count)); } foreach (TaskGroup _TaskGroup in _TaskGroups) { if (DistributionLoopCount == 1) { _TaskGroup.TasksUnAllocated = _TaskGroup.TaskCount; } if (_TaskGroup.TasksUnAllocated < _DefaultTasksPerGroup) { _ConcurrencySlotsAllocated += _TaskGroup.TaskCount; _AvailableConcurrencySlots -= _TaskGroup.TaskCount; _TaskGroup.ConcurrencySlotsAllocated += _TaskGroup.TaskCount; _TaskGroup.TasksUnAllocated -= _TaskGroup.TaskCount; } else { _ConcurrencySlotsAllocated += _DefaultTasksPerGroup; _AvailableConcurrencySlots -= _DefaultTasksPerGroup; _TaskGroup.ConcurrencySlotsAllocated += _DefaultTasksPerGroup; _TaskGroup.TasksUnAllocated -= _DefaultTasksPerGroup; } TaskGroupLoopCount += 1; //Break the foreach if we have hit the max if (TaskGroupLoopCount >= MaxTaskGroupIndex) { break; } } } public static void CreateTaskInstance(Logging logging) { logging.LogInformation("Create ScheduleInstance called."); TaskMetaDataDatabase TMD = new TaskMetaDataDatabase(); DateTimeOffset _date = DateTimeOffset.Now; DataTable dtScheduleInstance = new DataTable(); dtScheduleInstance.Columns.Add(new DataColumn("ScheduleMasterId", typeof(long))); dtScheduleInstance.Columns.Add(new DataColumn("ScheduledDateUtc", typeof(DateTime))); dtScheduleInstance.Columns.Add(new DataColumn("ScheduledDateTimeOffset", typeof(DateTimeOffset))); dtScheduleInstance.Columns.Add(new DataColumn("ActiveYN", typeof(bool))); dynamic resScheduleInstance = TMD.GetSqlConnection().QueryWithRetry(@" Select SM.ScheduleMasterId, SM.ScheduleCronExpression, Coalesce(SI.MaxScheduledDateTimeOffset,cast('1900-01-01' as datetimeoffset)) as MaxScheduledDateTimeOffset from ScheduleMaster SM join ( Select distinct ScheduleMasterId from TaskMaster TM where TM.ActiveYN = 1) TM on TM.ScheduleMasterId = SM.ScheduleMasterId left outer join ( Select ScheduleMasterId, Max(ScheduledDateTimeOffset) MaxScheduledDateTimeOffset From ScheduleInstance Where ActiveYN = 1 Group By ScheduleMasterId ) SI on SM.ScheduleMasterId = SI.ScheduleMasterId Where SM.ActiveYN = 1"); foreach (dynamic _row in resScheduleInstance) { DateTimeOffset? nextUtc; if (_row.ScheduleCronExpression.ToString() == "N/A") { nextUtc = DateTime.UtcNow.AddMinutes(-1); } else { CronExpression _cronExpression = CronExpression.Parse(_row.ScheduleCronExpression.ToString(), CronFormat.IncludeSeconds); nextUtc = _cronExpression.GetNextOccurrence(_row.MaxScheduledDateTimeOffset, TimeZoneInfo.Utc); } if (nextUtc?.DateTime <= DateTime.UtcNow) { DataRow dr = dtScheduleInstance.NewRow(); dr["ScheduleMasterId"] = _row.ScheduleMasterId; dr["ScheduledDateUtc"] = _date.Date; dr["ScheduledDateTimeOffset"] = _date; dr["ActiveYN"] = true; dtScheduleInstance.Rows.Add(dr); } } //Persist TEMP ScheduleInstance SqlConnection _con = TMD.GetSqlConnection(); Table tmpScheduleInstanceTargetTable = new Table { Name = "#Temp" + Guid.NewGuid().ToString() }; TMD.BulkInsert(dtScheduleInstance, tmpScheduleInstanceTargetTable, true, _con); //Create TaskInstance logging.LogInformation("Create TaskInstance called."); DataTable dtTaskInstance = new DataTable(); dtTaskInstance.Columns.Add(new DataColumn("ExecutionUid", typeof(Guid))); dtTaskInstance.Columns.Add(new DataColumn("TaskMasterId", typeof(long))); dtTaskInstance.Columns.Add(new DataColumn("ScheduleInstanceId", typeof(long))); dtTaskInstance.Columns.Add(new DataColumn("ADFPipeline", typeof(string))); dtTaskInstance.Columns.Add(new DataColumn("TaskInstanceJson", typeof(string))); dtTaskInstance.Columns.Add(new DataColumn("LastExecutionStatus", typeof(string))); dtTaskInstance.Columns.Add(new DataColumn("ActiveYN", typeof(bool))); //DataTable dtTaskInstanceErrors = new DataTable(); //dtTaskInstance.Columns.Add(new DataColumn("TaskMasterId", typeof(long))); //dtTaskInstance.Columns.Add(new DataColumn("ErrorMessage", typeof(string))); dynamic resTaskInstance = TMD.GetSqlConnection().QueryWithRetry(@"Exec dbo.GetTaskMaster"); DataTable dtTaskTypeMapping = GetTaskTypeMapping(logging); foreach (dynamic _row in resTaskInstance) { DataRow drTaskInstance = dtTaskInstance.NewRow(); //DataRow drTaskInstanceErrors = dtTaskInstance.NewRow(); logging.DefaultActivityLogItem.TaskInstanceId = _row.TaskInstanceId; logging.DefaultActivityLogItem.TaskMasterId = _row.TaskMasterId; string InstanceGenerationErrorMessage = ""; try { dynamic sourceSystemJson = JsonConvert.DeserializeObject(_row.SourceSystemJSON); dynamic taskMasterJson = JsonConvert.DeserializeObject(_row.TaskMasterJSON); dynamic targetSystemJson = JsonConvert.DeserializeObject(_row.TargetSystemJSON); string _ADFPipeline = GetTaskTypeMappingName(logging, _row.TaskExecutionType.ToString(), dtTaskTypeMapping, _row.TaskTypeId, _row.SourceSystemType.ToString(), taskMasterJson?.Source.Type.ToString(), _row.TargetSystemType.ToString(), taskMasterJson?.Target.Type.ToString(), _row.TaskDatafactoryIR); drTaskInstance["TaskMasterId"] = _row.TaskMasterId ?? DBNull.Value; //drTaskInstanceErrors["TaskMasterId"] = _row.TaskMasterId ?? DBNull.Value; //drTaskInstanceErrors["ErrorMessage"] = ""; drTaskInstance["ScheduleInstanceId"] = 0;//_row.ScheduleInstanceId == null ? DBNull.Value : _row.ScheduleInstanceId; drTaskInstance["ExecutionUid"] = logging.DefaultActivityLogItem.ExecutionUid; drTaskInstance["ADFPipeline"] = _ADFPipeline; drTaskInstance["LastExecutionStatus"] = "Untried"; drTaskInstance["ActiveYN"] = true; JObject Root = new JObject(); if (_row.SourceSystemType == "ADLS" || _row.SourceSystemType == "Azure Blob") { if (taskMasterJson?.Source.Type.ToString() != "Filelist") { Root["SourceRelativePath"] = TaskInstancesStatic.TransformRelativePath(JObject.Parse(_row.TaskMasterJSON)["Source"]["RelativePath"].ToString(), _date.DateTime); } } if (_row.TargetSystemType == "ADLS" || _row.TargetSystemType == "Azure Blob") { if (JObject.Parse(_row.TaskMasterJSON)["Target"]["RelativePath"] != null) { Root["TargetRelativePath"] = TaskInstancesStatic.TransformRelativePath(JObject.Parse(_row.TaskMasterJSON)["Target"]["RelativePath"].ToString(), _date.DateTime); } } if (JObject.Parse(_row.TaskMasterJSON)["Source"]["IncrementalType"] == "Watermark") { Root["IncrementalField"] = _row.TaskMasterWaterMarkColumn; Root["IncrementalColumnType"] = _row.TaskMasterWaterMarkColumnType; if (_row.TaskMasterWaterMarkColumnType == "DateTime") { Root["IncrementalValue"] = _row.TaskMasterWaterMark_DateTime ?? "1900-01-01"; } else if (_row.TaskMasterWaterMarkColumnType == "BigInt") { Root["IncrementalValue"] = _row.TaskMasterWaterMark_BigInt ?? -1; } if ((Root["IncrementalField"] == null) || (Root["IncrementalField"].ToString() == "")) { InstanceGenerationErrorMessage += string.Format("TaskMasterId '{0}' has an IncrementalType of Watermark but does not have any entry in the TaskWatermark table. ", logging.DefaultActivityLogItem.TaskInstanceId); } } if (Root == null) { drTaskInstance["TaskInstanceJson"] = DBNull.Value; } else { drTaskInstance["TaskInstanceJson"] = Root; } if (String.IsNullOrEmpty(InstanceGenerationErrorMessage)) { dtTaskInstance.Rows.Add(drTaskInstance); } else { throw new Exception(InstanceGenerationErrorMessage); } } catch (Exception e) { logging.LogErrors(new Exception(string.Format("Failed to create new task instances for TaskMasterId '{0}'.", logging.DefaultActivityLogItem.TaskInstanceId))); logging.LogErrors(e); } } //Persist TMP TaskInstance Table tmpTaskInstanceTargetTable = new Table { Name = "#Temp" + Guid.NewGuid().ToString() }; TMD.BulkInsert(dtTaskInstance, tmpTaskInstanceTargetTable, true, _con); Dictionary<string, string> SqlParams = new Dictionary<string, string> { { "tmpScheduleInstance", tmpScheduleInstanceTargetTable.QuotedSchemaAndName() }, { "tmpTaskInstance", tmpTaskInstanceTargetTable.QuotedSchemaAndName() } }; string InsertSQL = GenerateSQLStatementTemplates.GetSQL(System.IO.Path.Combine(Shared._ApplicationBasePath, Shared._ApplicationOptions.LocalPaths.SQLTemplateLocation), "InsertScheduleInstance_TaskInstance", SqlParams); _con.ExecuteWithRetry(InsertSQL); //PersistErrors //if (dtTaskInstanceErrors.Rows.Count > 0) //{ // Table tmpTaskInstanceErrorsTargetTable = new Table // { // Name = "#TempErrors" + Guid.NewGuid().ToString() // }; // TMD.BulkInsert(dtTaskInstanceErrors, tmpTaskInstanceErrorsTargetTable, true, _con); // Dictionary<string, string> SqlParamsTIErrors = new Dictionary<string, string> // { // { "tmpTaskInstanceErrors", tmpTaskInstanceErrorsTargetTable.QuotedSchemaAndName() } // }; // string InsertSQLTIErrors = GenerateSQLStatementTemplates.GetSQL(System.IO.Path.Combine(Shared._ApplicationBasePath, Shared._ApplicationOptions.LocalPaths.SQLTemplateLocation), "InsertTaskInstanceErrors", SqlParamsTIErrors); // _con.ExecuteWithRetry(InsertSQLTIErrors); //} _con.Close(); } public static short CountRunnningPipelines(Logging logging) { short _ActivePipelines = ActivePipelines.CountActivePipelines(logging); return _ActivePipelines; } /// <summary> /// Checks for long running pipelines and updates their status in the database /// </summary> /// <param name="logging"></param> /// <returns></returns> public static short CheckLongRunningPipelines(Logging logging) { dynamic _ActivePipelines = ActivePipelines.GetLongRunningPipelines(logging); short RunningPipelines = 0; short FinishedPipelines = 0; DataTable dt = new DataTable(); dt.Columns.Add(new DataColumn("TaskInstanceId", typeof(string))); dt.Columns.Add(new DataColumn("ExecutionUid", typeof(Guid))); dt.Columns.Add(new DataColumn("PipelineName", typeof(string))); dt.Columns.Add(new DataColumn("DatafactorySubscriptionUid", typeof(Guid))); dt.Columns.Add(new DataColumn("DatafactoryResourceGroup", typeof(string))); dt.Columns.Add(new DataColumn("DatafactoryName", typeof(string))); dt.Columns.Add(new DataColumn("RunUid", typeof(Guid))); dt.Columns.Add(new DataColumn("Status", typeof(string))); dt.Columns.Add(new DataColumn("SimpleStatus", typeof(string))); //Check Each Running Pipeline foreach (dynamic _Pipeline in _ActivePipelines) { dynamic _PipelineStatus = CheckPipelineStatus.CheckPipelineStatusMethod(_Pipeline.DatafactorySubscriptionUid.ToString(), _Pipeline.DatafactoryResourceGroup.ToString(), _Pipeline.DatafactoryName.ToString(), _Pipeline.PipelineName.ToString(), _Pipeline.AdfRunUid.ToString(), logging); if (_PipelineStatus["SimpleStatus"].ToString() == "Runnning") { RunningPipelines += 1; } if (_PipelineStatus["SimpleStatus"].ToString() == "Done") { FinishedPipelines += 1; } DataRow dr = dt.NewRow(); dr["TaskInstanceId"] = _Pipeline.TaskInstanceId; dr["ExecutionUid"] = _Pipeline.ExecutionUid; dr["DatafactorySubscriptionUid"] = _Pipeline.DatafactorySubscriptionUid; dr["DatafactoryResourceGroup"] = _Pipeline.DatafactoryResourceGroup; dr["DatafactoryName"] = _Pipeline.DatafactoryName; dr["Status"] = _PipelineStatus["Status"]; dr["SimpleStatus"] = _PipelineStatus["SimpleStatus"]; dr["RunUid"] = (Guid)_PipelineStatus["RunId"]; dr["PipelineName"] = _PipelineStatus["PipelineName"]; dt.Rows.Add(dr); } string TempTableName = "#Temp" + Guid.NewGuid().ToString(); TaskMetaDataDatabase TMD = new TaskMetaDataDatabase(); //Todo: Update both the TaskInstanceExecution and the TaskInstance; TMD.AutoBulkInsertAndMerge(dt, TempTableName, "TaskInstanceExecution"); return RunningPipelines; } public static DataTable GetTaskTypeMapping(Logging logging) { logging.LogDebug("Load TaskTypeMapping called."); TaskMetaDataDatabase TMD = new TaskMetaDataDatabase(); dynamic resTaskTypeMapping = TMD.GetSqlConnection().QueryWithRetry(@"select * from [dbo].[TaskTypeMapping] Where ActiveYN = 1"); DataTable dtTaskTypeMapping = new DataTable(); dtTaskTypeMapping.Columns.Add(new DataColumn("TaskTypeId", typeof(int))); dtTaskTypeMapping.Columns.Add(new DataColumn("MappingType", typeof(string))); dtTaskTypeMapping.Columns.Add(new DataColumn("MappingName", typeof(string))); dtTaskTypeMapping.Columns.Add(new DataColumn("SourceSystemType", typeof(string))); dtTaskTypeMapping.Columns.Add(new DataColumn("SourceType", typeof(string))); dtTaskTypeMapping.Columns.Add(new DataColumn("TargetSystemType", typeof(string))); dtTaskTypeMapping.Columns.Add(new DataColumn("TargetType", typeof(string))); dtTaskTypeMapping.Columns.Add(new DataColumn("TaskDatafactoryIR", typeof(string))); foreach (dynamic _row in resTaskTypeMapping) { DataRow dr = dtTaskTypeMapping.NewRow(); dr["TaskTypeId"] = _row.TaskTypeId; dr["MappingType"] = _row.MappingType; dr["MappingName"] = _row.MappingName; dr["SourceSystemType"] = _row.SourceSystemType; dr["SourceType"] = _row.SourceType; dr["TargetSystemType"] = _row.TargetSystemType; dr["TargetType"] = _row.TargetType; dr["TaskDatafactoryIR"] = _row.TaskDatafactoryIR; dtTaskTypeMapping.Rows.Add(dr); } logging.LogDebug("Load TaskTypeMapping complete."); return dtTaskTypeMapping; } public static string GetTaskTypeMappingName(Logging logging, String MappingType, DataTable dt, int TaskTypeId, string SourceSystemType, string SourceType, string TargetSystemType, string TargetType, string TaskDatafactoryIR) { logging.LogDebug("Get TaskTypeMappingName called."); string _ex = string.Format("MappingType = '{6}' and SourceSystemType = '{0}' and SourceType = '{1}' and TargetSystemType = '{2}' and TargetType = '{3}' and TaskDatafactoryIR = '{4}' and TaskTypeId = {5}", SourceSystemType, SourceType, TargetSystemType, TargetType, TaskDatafactoryIR, TaskTypeId, MappingType); DataRow[] foundRows = dt.Select(_ex); if (foundRows.Count() > 1 || foundRows.Count() == 0) { throw new System.ArgumentException(string.Format("Invalid TypeMapping for SourceSystemType = '{0}' and SourceType = '{1}' and TargetSystemType = '{2}' and TargetType = '{3}' and TaskDatafactoryIR = '{4}'. Mapping returned: {5}", SourceSystemType, SourceType, TargetSystemType, TargetType, TaskDatafactoryIR, foundRows.Count())); } string TypeName = foundRows[0]["MappingName"].ToString(); logging.LogDebug("Get TaskTypeMappingName complete."); return TypeName; } } }
48.949495
344
0.600124
[ "MIT" ]
LeighS/azure-data-services-go-fast-codebase
solution/FunctionApp/PrepareFrameworkTasks.cs
24,230
C#