content
stringlengths
5
1.04M
avg_line_length
float64
1.75
12.9k
max_line_length
int64
2
244k
alphanum_fraction
float64
0
0.98
licenses
list
repository_name
stringlengths
7
92
path
stringlengths
3
249
size
int64
5
1.04M
lang
stringclasses
2 values
using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; namespace FastReportCore.MVC.Models { [Table("orderdetails")] public partial class Orderdetails { public long Id { get; set; } [Column("OrderID", TypeName = "INTEGER KEY")] public int? OrderId { get; set; } [Column("ProductID", TypeName = "INTEGER KEY")] public int? ProductId { get; set; } [Column(TypeName = "decimal (10, 0)")] public decimal? UnitPrice { get; set; } public short? Quantity { get; set; } [Column(TypeName = "float")] public float? Discount { get; set; } } }
31.304348
55
0.630556
[ "MIT" ]
8VAid8/FastReport
Demos/Core/FastReportCore.MVC/Models/Orderdetails.cs
722
C#
using System.Collections; using System.Collections.Generic; using UnityEngine; public class BrownPlatform : MonoBehaviour { Animator animator; // Start is called before the first frame update void Start() { animator = gameObject.GetComponent<Animator>(); } // Update is called once per frame void Update() { } private void OnTriggerEnter2D(Collider2D collider) { if (!collider.isTrigger) { GetComponent<Collider2D>().enabled = false; animator.SetBool("broken", true); } } }
17.5
55
0.611765
[ "MIT" ]
TheMagnat/Doodle-Jump
Unity/DoodleJumpGM/Assets/Scripts/BrownPlatform.cs
595
C#
using Arragro.Common.BusinessRules; using Arragro.Common.Repository; using System.Linq; namespace Arragro.Common.ServiceBase { public abstract class Service<TRepository, TModel, TKeyType> : BusinessRulesBase<TRepository, TModel, TKeyType> where TModel : class where TRepository : IRepository<TModel, TKeyType> { public Service(TRepository repository) : base(repository) { } public TModel Find(TKeyType id) { return Repository.Find(id); } protected abstract void ValidateModelRules(TModel model); public abstract TModel InsertOrUpdate(TModel model); public void ValidateModel(TModel model) { RulesException.ErrorsForValidationResults(ValidateModelProperties(model)); ValidateModelRules(model); if (RulesException.Errors.Any()) throw RulesException; } public TModel ValidateAndInsertOrUpdate(TModel model) { ValidateModel(model); return InsertOrUpdate(model); } } }
28.076923
115
0.646575
[ "BSD-3-Clause" ]
Arragro/Arragro
src/Arragro.Common/ServiceBase/Service.cs
1,097
C#
// <auto-generated /> using System; using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Infrastructure; using Microsoft.EntityFrameworkCore.Metadata; using Microsoft.EntityFrameworkCore.Migrations; using Microsoft.EntityFrameworkCore.Storage.ValueConversion; using SoftJail.Data; namespace SoftJail.Migrations { [DbContext(typeof(SoftJailDbContext))] [Migration("20191205084427_Initial")] partial class Initial { protected override void BuildTargetModel(ModelBuilder modelBuilder) { #pragma warning disable 612, 618 modelBuilder .HasAnnotation("ProductVersion", "2.2.0-rtm-35687") .HasAnnotation("Relational:MaxIdentifierLength", 128) .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); modelBuilder.Entity("SoftJail.Data.Models.Cell", b => { b.Property<int>("Id") .ValueGeneratedOnAdd() .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); b.Property<int>("CellNumber"); b.Property<int>("DepartmentId"); b.Property<bool>("HasWindow"); b.HasKey("Id"); b.HasIndex("DepartmentId"); b.ToTable("Cells"); }); modelBuilder.Entity("SoftJail.Data.Models.Department", b => { b.Property<int>("Id") .ValueGeneratedOnAdd() .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); b.Property<string>("Name") .IsRequired() .HasMaxLength(25); b.HasKey("Id"); b.ToTable("Departments"); }); modelBuilder.Entity("SoftJail.Data.Models.Mail", b => { b.Property<int>("Id") .ValueGeneratedOnAdd() .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); b.Property<string>("Address") .IsRequired(); b.Property<string>("Description") .IsRequired(); b.Property<int>("PrisonerId"); b.Property<string>("Sender") .IsRequired(); b.HasKey("Id"); b.HasIndex("PrisonerId"); b.ToTable("Mails"); }); modelBuilder.Entity("SoftJail.Data.Models.Officer", b => { b.Property<int>("Id") .ValueGeneratedOnAdd() .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); b.Property<int?>("DepartmentId"); b.Property<string>("FullName") .IsRequired() .HasMaxLength(30); b.Property<int>("Position"); b.Property<decimal>("Salary"); b.Property<int>("Weapon"); b.HasKey("Id"); b.HasIndex("DepartmentId"); b.ToTable("Officers"); }); modelBuilder.Entity("SoftJail.Data.Models.OfficerPrisoner", b => { b.Property<int>("OfficerId"); b.Property<int>("PrisonerId"); b.HasKey("OfficerId", "PrisonerId"); b.HasIndex("PrisonerId"); b.ToTable("OfficersPrisoners"); }); modelBuilder.Entity("SoftJail.Data.Models.Prisoner", b => { b.Property<int>("Id") .ValueGeneratedOnAdd() .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); b.Property<int>("Age"); b.Property<decimal?>("Bail"); b.Property<int?>("CellId"); b.Property<string>("FullName") .IsRequired() .HasMaxLength(20); b.Property<DateTime>("IncarcerationDate"); b.Property<string>("Nickname") .IsRequired(); b.Property<DateTime?>("ReleaseDate"); b.HasKey("Id"); b.HasIndex("CellId"); b.ToTable("Prisoners"); }); modelBuilder.Entity("SoftJail.Data.Models.Cell", b => { b.HasOne("SoftJail.Data.Models.Department", "Department") .WithMany("Cells") .HasForeignKey("DepartmentId") .OnDelete(DeleteBehavior.Cascade); }); modelBuilder.Entity("SoftJail.Data.Models.Mail", b => { b.HasOne("SoftJail.Data.Models.Prisoner", "Prisoner") .WithMany("Mails") .HasForeignKey("PrisonerId") .OnDelete(DeleteBehavior.Cascade); }); modelBuilder.Entity("SoftJail.Data.Models.Officer", b => { b.HasOne("SoftJail.Data.Models.Department", "Department") .WithMany() .HasForeignKey("DepartmentId"); }); modelBuilder.Entity("SoftJail.Data.Models.OfficerPrisoner", b => { b.HasOne("SoftJail.Data.Models.Officer", "Officer") .WithMany("OfficerPrisoners") .HasForeignKey("OfficerId") .OnDelete(DeleteBehavior.Cascade); b.HasOne("SoftJail.Data.Models.Prisoner", "Prisoner") .WithMany("PrisonerOfficers") .HasForeignKey("PrisonerId") .OnDelete(DeleteBehavior.Cascade); }); modelBuilder.Entity("SoftJail.Data.Models.Prisoner", b => { b.HasOne("SoftJail.Data.Models.Cell", "Cell") .WithMany("Prisoners") .HasForeignKey("CellId"); }); #pragma warning restore 612, 618 } } }
34.403061
125
0.481536
[ "Apache-2.0" ]
KostadinovK/CSharp-DB
02-Entity Framework Core/13-Past Exams/Exam 12.08.2018/SoftJail/Migrations/20191205084427_Initial.Designer.cs
6,745
C#
#pragma checksum "..\..\MainWindow.xaml" "{8829d00f-11b8-4213-878b-770e8597ac16}" "87F72F0F8B2C4F3FA76FEB8F4AF6FF2927740B032E0B288EE768E3671819B7FA" //------------------------------------------------------------------------------ // <auto-generated> // Ce code a été généré par un outil. // Version du runtime :4.0.30319.42000 // // Les modifications apportées à ce fichier peuvent provoquer un comportement incorrect et seront perdues si // le code est régénéré. // </auto-generated> //------------------------------------------------------------------------------ using MediaPlayer; using System; using System.Diagnostics; using System.Windows; using System.Windows.Automation; using System.Windows.Controls; using System.Windows.Controls.Primitives; using System.Windows.Data; using System.Windows.Documents; using System.Windows.Ink; using System.Windows.Input; using System.Windows.Markup; using System.Windows.Media; using System.Windows.Media.Animation; using System.Windows.Media.Effects; using System.Windows.Media.Imaging; using System.Windows.Media.Media3D; using System.Windows.Media.TextFormatting; using System.Windows.Navigation; using System.Windows.Shapes; using System.Windows.Shell; namespace MediaPlayer { /// <summary> /// MainWindow /// </summary> public partial class MainWindow : System.Windows.Window, System.Windows.Markup.IComponentConnector { #line 24 "..\..\MainWindow.xaml" [System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1823:AvoidUnusedPrivateFields")] internal System.Windows.Controls.ComboBox cboxVideosList; #line default #line hidden #line 27 "..\..\MainWindow.xaml" [System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1823:AvoidUnusedPrivateFields")] internal System.Windows.Controls.MediaElement myMediaPlayer; #line default #line hidden #line 33 "..\..\MainWindow.xaml" [System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1823:AvoidUnusedPrivateFields")] internal System.Windows.Controls.Primitives.ScrollBar sbarPosition; #line default #line hidden #line 45 "..\..\MainWindow.xaml" [System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1823:AvoidUnusedPrivateFields")] internal System.Windows.Controls.Button btnPlay; #line default #line hidden #line 48 "..\..\MainWindow.xaml" [System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1823:AvoidUnusedPrivateFields")] internal System.Windows.Controls.Button btnPause; #line default #line hidden #line 51 "..\..\MainWindow.xaml" [System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1823:AvoidUnusedPrivateFields")] internal System.Windows.Controls.Button btnStop; #line default #line hidden #line 54 "..\..\MainWindow.xaml" [System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1823:AvoidUnusedPrivateFields")] internal System.Windows.Controls.Button btnRestart; #line default #line hidden #line 58 "..\..\MainWindow.xaml" [System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1823:AvoidUnusedPrivateFields")] internal System.Windows.Controls.Button btnPrevious; #line default #line hidden #line 61 "..\..\MainWindow.xaml" [System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1823:AvoidUnusedPrivateFields")] internal System.Windows.Controls.Button btnNext; #line default #line hidden #line 67 "..\..\MainWindow.xaml" [System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1823:AvoidUnusedPrivateFields")] internal System.Windows.Controls.Button btnSlower; #line default #line hidden #line 70 "..\..\MainWindow.xaml" [System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1823:AvoidUnusedPrivateFields")] internal System.Windows.Controls.Label SpeedRatio; #line default #line hidden #line 71 "..\..\MainWindow.xaml" [System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1823:AvoidUnusedPrivateFields")] internal System.Windows.Controls.Button btnFaster; #line default #line hidden #line 76 "..\..\MainWindow.xaml" [System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1823:AvoidUnusedPrivateFields")] internal System.Windows.Controls.TextBox txtPosition; #line default #line hidden #line 79 "..\..\MainWindow.xaml" [System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1823:AvoidUnusedPrivateFields")] internal System.Windows.Controls.Button btnSetPosition; #line default #line hidden private bool _contentLoaded; /// <summary> /// InitializeComponent /// </summary> [System.Diagnostics.DebuggerNonUserCodeAttribute()] [System.CodeDom.Compiler.GeneratedCodeAttribute("PresentationBuildTasks", "4.0.0.0")] public void InitializeComponent() { if (_contentLoaded) { return; } _contentLoaded = true; System.Uri resourceLocater = new System.Uri("/MediaPlayer;component/mainwindow.xaml", System.UriKind.Relative); #line 1 "..\..\MainWindow.xaml" System.Windows.Application.LoadComponent(this, resourceLocater); #line default #line hidden } [System.Diagnostics.DebuggerNonUserCodeAttribute()] [System.CodeDom.Compiler.GeneratedCodeAttribute("PresentationBuildTasks", "4.0.0.0")] [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] [System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Design", "CA1033:InterfaceMethodsShouldBeCallableByChildTypes")] [System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity")] [System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1800:DoNotCastUnnecessarily")] void System.Windows.Markup.IComponentConnector.Connect(int connectionId, object target) { switch (connectionId) { case 1: #line 7 "..\..\MainWindow.xaml" ((MediaPlayer.MainWindow)(target)).Loaded += new System.Windows.RoutedEventHandler(this.Window_Loaded); #line default #line hidden return; case 2: this.cboxVideosList = ((System.Windows.Controls.ComboBox)(target)); return; case 3: this.myMediaPlayer = ((System.Windows.Controls.MediaElement)(target)); #line 29 "..\..\MainWindow.xaml" this.myMediaPlayer.MediaOpened += new System.Windows.RoutedEventHandler(this.Player_MediaOpened); #line default #line hidden return; case 4: this.sbarPosition = ((System.Windows.Controls.Primitives.ScrollBar)(target)); return; case 5: this.btnPlay = ((System.Windows.Controls.Button)(target)); #line 45 "..\..\MainWindow.xaml" this.btnPlay.Click += new System.Windows.RoutedEventHandler(this.btnPlay_Click); #line default #line hidden return; case 6: this.btnPause = ((System.Windows.Controls.Button)(target)); #line 48 "..\..\MainWindow.xaml" this.btnPause.Click += new System.Windows.RoutedEventHandler(this.btnPause_Click); #line default #line hidden return; case 7: this.btnStop = ((System.Windows.Controls.Button)(target)); #line 51 "..\..\MainWindow.xaml" this.btnStop.Click += new System.Windows.RoutedEventHandler(this.btnStop_Click); #line default #line hidden return; case 8: this.btnRestart = ((System.Windows.Controls.Button)(target)); #line 54 "..\..\MainWindow.xaml" this.btnRestart.Click += new System.Windows.RoutedEventHandler(this.btnRestart_Click); #line default #line hidden return; case 9: this.btnPrevious = ((System.Windows.Controls.Button)(target)); #line 58 "..\..\MainWindow.xaml" this.btnPrevious.Click += new System.Windows.RoutedEventHandler(this.btnPrevious_Click); #line default #line hidden return; case 10: this.btnNext = ((System.Windows.Controls.Button)(target)); #line 61 "..\..\MainWindow.xaml" this.btnNext.Click += new System.Windows.RoutedEventHandler(this.btnNext_Click); #line default #line hidden return; case 11: this.btnSlower = ((System.Windows.Controls.Button)(target)); #line 67 "..\..\MainWindow.xaml" this.btnSlower.Click += new System.Windows.RoutedEventHandler(this.btnSlower_Click); #line default #line hidden return; case 12: this.SpeedRatio = ((System.Windows.Controls.Label)(target)); return; case 13: this.btnFaster = ((System.Windows.Controls.Button)(target)); #line 71 "..\..\MainWindow.xaml" this.btnFaster.Click += new System.Windows.RoutedEventHandler(this.btnFaster_Click); #line default #line hidden return; case 14: this.txtPosition = ((System.Windows.Controls.TextBox)(target)); return; case 15: this.btnSetPosition = ((System.Windows.Controls.Button)(target)); #line 79 "..\..\MainWindow.xaml" this.btnSetPosition.Click += new System.Windows.RoutedEventHandler(this.btnSetPosition_Click); #line default #line hidden return; } this._contentLoaded = true; } } }
38.79402
150
0.584482
[ "MIT" ]
Axel82/MediaPlayer
MediaPlayer/MediaPlayer/obj/Debug/MainWindow.g.cs
11,690
C#
namespace AgileObjects.ReadableExpressions.Translations { using System; using System.Linq; using System.Reflection; using Interfaces; #if NET35 using Microsoft.Scripting.Ast; #else using System.Linq.Expressions; #endif using NetStandardPolyfills; internal static class TypeEqualTranslation { private static readonly MethodInfo _reduceTypeEqualMethod; static TypeEqualTranslation() { try { _reduceTypeEqualMethod = typeof(TypeBinaryExpression) .GetNonPublicInstanceMethods("ReduceTypeEqual") .FirstOrDefault(); } catch { // Unable to find or access ReduceTypeEqual - ignore } } public static ITranslation For(TypeBinaryExpression typeBinary, ITranslationContext context) { ITranslation operandTranslation; if (_reduceTypeEqualMethod != null) { try { // TypeEqual '123 TypeEqual int' is reduced to a Block with the Expressions '123' and 'true', // 'o TypeEqual string' is reduced to (o != null) && (o is string): var reducedTypeBinary = (Expression)_reduceTypeEqualMethod.Invoke(typeBinary, null); operandTranslation = context.GetTranslationFor(reducedTypeBinary); if (operandTranslation.NodeType == ExpressionType.Block) { operandTranslation = ((BlockTranslation)operandTranslation).WithoutTermination(); } return operandTranslation.WithTypes(ExpressionType.TypeEqual, typeof(bool)); } catch { // Unable to invoke the non-public ReduceTypeEqual method - ignore } } operandTranslation = context.GetTranslationFor(typeBinary.Expression); var typeNameTranslation = context.GetTranslationFor(typeBinary.TypeOperand); if (typeBinary.TypeOperand.IsClass()) { return CastTranslation.For(typeBinary, context); } return new TypeOfTranslation(operandTranslation, typeNameTranslation); } private class TypeOfTranslation : ITranslation { private const string _typeOf = " TypeOf typeof("; private readonly ITranslation _operandTranslation; private readonly ITranslation _typeNameTranslation; public TypeOfTranslation(ITranslation operandTranslation, ITranslation typeNameTranslation) { _operandTranslation = operandTranslation; _typeNameTranslation = typeNameTranslation; EstimatedSize = GetEstimatedSize(); } private int GetEstimatedSize() { var estimatedSize = _operandTranslation.EstimatedSize + _typeNameTranslation.EstimatedSize; estimatedSize += _typeOf.Length + 2; // <- +2 for parentheses return estimatedSize; } public ExpressionType NodeType => ExpressionType.TypeEqual; public Type Type => typeof(bool); public int EstimatedSize { get; } public void WriteTo(TranslationBuffer buffer) { _operandTranslation.WriteTo(buffer); buffer.WriteToTranslation(_typeOf); _typeNameTranslation.WriteTo(buffer); buffer.WriteToTranslation(')'); } } } }
34.247706
113
0.577284
[ "MIT" ]
rikimaru0345/ReadableExpressions
ReadableExpressions/Translations/TypeEqualTranslation.cs
3,735
C#
using System; using System.Collections.Generic; using System.Text; namespace BreakinIn.Messages { class PlusWho : AbstractMessage { public override string _Name { get => "+who"; } public string I { get; set; } public string N { get; set; } public string M { get; set; } public string F { get; set; } = ""; public string A { get; set; } public string S { get; set; } = ""; public string X { get; set; } public string R { get; set; } //room public string RI { get; set; } //room id public string RF { get; set; } = "C"; public string RT { get; set; } = "1"; } }
27.958333
55
0.540984
[ "Apache-2.0" ]
Blayer98/Breakin-In
BreakinIn/Messages/PlusWho.cs
673
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: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("DotNetCSS.Tests")] [assembly: AssemblyTrademark("")] // 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("2f5163cb-b410-402a-85d8-448f8125c5fa")]
41.25
84
0.781818
[ "MIT" ]
grapoza/DotNetCSS
src/DotNetCSS.Tests/Properties/AssemblyInfo.cs
827
C#
using Jw.Winform.Ctrls; using System; using System.Collections.Generic; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace Jw.Winform.Forms { public class JwNotify { private static JwNotify manager = null; private Dictionary<string, JwNotifyForm> _Forms = new Dictionary<string, JwNotifyForm>(); private JwNotify() { } static JwNotify() { manager = new JwNotify(); } public static void Info(string message, bool autoClose =true, int delay = 5000, bool closeable = false) { manager.Show(message, ThemeType.Info, "icon-info-fill", closeable, autoClose, delay); } public static void Error(string message, bool autoClose = true, int delay = 5000, bool closeable = false) { manager.Show(message, ThemeType.Danger, "op2-reeor", closeable, autoClose, delay); } public static void Succ(string message, bool autoClose = true, int delay = 5000, bool closeable = false) { manager.Show(message, ThemeType.Success, "op2-succ", closeable, autoClose, delay); } public static void Warning(string message, bool autoClose = true, int delay = 5000, bool closeable = false) { manager.Show(message, ThemeType.Warning, "icon-warning-fill", closeable, autoClose, delay); } public string Show(string message, ThemeType theme, string icon, bool closeable, bool autoClose, int delay) { var fnotify = new JwNotifyForm { ShowCloseButton = closeable, Message = message, MessageIcon = icon, Theme = theme, AutoClose = autoClose, CloseDelay = delay, StartPosition = System.Windows.Forms.FormStartPosition.Manual }; fnotify.FormClosed += FNotifyFormClosed; _Forms.Add(fnotify.Uuid, fnotify); var screen = Screen.FromPoint(new Point(Cursor.Position.X, Cursor.Position.Y)); var x = screen.WorkingArea.X + screen.WorkingArea.Width - fnotify.Width; var y = screen.WorkingArea.Y + screen.WorkingArea.Height - fnotify.Height; fnotify.Location = new Point(x, y); fnotify.Show(); return fnotify.Uuid; } private void FNotifyFormClosed(object sender, System.Windows.Forms.FormClosedEventArgs e) { if (!(sender is JwNotifyForm)) return; var uuid = ((JwNotifyForm)sender).Uuid; if(_Forms.ContainsKey(uuid)) { _Forms.Remove(uuid); } } } }
38.873239
115
0.602899
[ "MIT" ]
wuqinchao/JwControls
Jw.Winform.Forms/JwNotify/JwNotify.cs
2,762
C#
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.DataProtection; using Microsoft.AspNetCore.Mvc; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Localization; using Microsoft.Extensions.Logging; using OrchardCore.Data; using OrchardCore.Email; using OrchardCore.Environment.Shell; using OrchardCore.Modules; using OrchardCore.Recipes.Models; using OrchardCore.Setup.Services; using OrchardCore.Setup.ViewModels; namespace OrchardCore.Setup.Controllers { public class SetupController : Controller { private readonly ISetupService _setupService; private readonly ShellSettings _shellSettings; private readonly IShellHost _shellHost; private readonly IEnumerable<DatabaseProvider> _databaseProviders; private readonly IClock _clock; private readonly ILogger _logger; private readonly IStringLocalizer S; private readonly IEmailAddressValidator _emailAddressValidator; public SetupController( ILogger<SetupController> logger, IClock clock, ISetupService setupService, ShellSettings shellSettings, IEnumerable<DatabaseProvider> databaseProviders, IShellHost shellHost, IStringLocalizer<SetupController> localizer, IEmailAddressValidator emailAddressValidator) { _logger = logger; _clock = clock; _shellHost = shellHost; _setupService = setupService; _shellSettings = shellSettings; _databaseProviders = databaseProviders; S = localizer; _emailAddressValidator = emailAddressValidator; } public async Task<ActionResult> Index(string token) { var recipes = await _setupService.GetSetupRecipesAsync(); var defaultRecipe = recipes.FirstOrDefault(x => x.Tags.Contains("default")) ?? recipes.FirstOrDefault(); if (!string.IsNullOrWhiteSpace(_shellSettings["Secret"])) { if (string.IsNullOrEmpty(token) || !await IsTokenValid(token)) { _logger.LogWarning("An attempt to access '{TenantName}' without providing a secret was made", _shellSettings.Name); return StatusCode(404); } } var model = new SetupViewModel { DatabaseProviders = _databaseProviders, Recipes = recipes, RecipeName = defaultRecipe?.Name, Secret = token }; CopyShellSettingsValues(model); if (!String.IsNullOrEmpty(_shellSettings["TablePrefix"])) { model.DatabaseConfigurationPreset = true; model.TablePrefix = _shellSettings["TablePrefix"]; } return View(model); } [HttpPost, ActionName("Index")] public async Task<ActionResult> IndexPOST(SetupViewModel model) { if (!string.IsNullOrWhiteSpace(_shellSettings["Secret"])) { if (string.IsNullOrEmpty(model.Secret) || !await IsTokenValid(model.Secret)) { _logger.LogWarning("An attempt to access '{TenantName}' without providing a valid secret was made", _shellSettings.Name); return StatusCode(404); } } model.DatabaseProviders = _databaseProviders; model.Recipes = await _setupService.GetSetupRecipesAsync(); var selectedProvider = model.DatabaseProviders.FirstOrDefault(x => x.Value == model.DatabaseProvider); if (!model.DatabaseConfigurationPreset) { if (selectedProvider != null && selectedProvider.HasConnectionString && String.IsNullOrWhiteSpace(model.ConnectionString)) { ModelState.AddModelError(nameof(model.ConnectionString), S["The connection string is mandatory for this provider."]); } } if (String.IsNullOrEmpty(model.Password)) { ModelState.AddModelError(nameof(model.Password), S["The password is required."]); } if (model.Password != model.PasswordConfirmation) { ModelState.AddModelError(nameof(model.PasswordConfirmation), S["The password confirmation doesn't match the password."]); } RecipeDescriptor selectedRecipe = null; if (!string.IsNullOrEmpty(_shellSettings["RecipeName"])) { selectedRecipe = model.Recipes.FirstOrDefault(x => x.Name == _shellSettings["RecipeName"]); if (selectedRecipe == null) { ModelState.AddModelError(nameof(model.RecipeName), S["Invalid recipe."]); } } else if (String.IsNullOrEmpty(model.RecipeName) || (selectedRecipe = model.Recipes.FirstOrDefault(x => x.Name == model.RecipeName)) == null) { ModelState.AddModelError(nameof(model.RecipeName), S["Invalid recipe."]); } if (!_emailAddressValidator.Validate(model.Email)) { ModelState.AddModelError(nameof(model.Email), S["Invalid email."]); } if (!ModelState.IsValid) { CopyShellSettingsValues(model); return View(model); } var setupContext = new SetupContext { ShellSettings = _shellSettings, SiteName = model.SiteName, EnabledFeatures = null, // default list, AdminUsername = model.UserName, AdminEmail = model.Email, AdminPassword = model.Password, Errors = new Dictionary<string, string>(), Recipe = selectedRecipe, SiteTimeZone = model.SiteTimeZone }; if (!string.IsNullOrEmpty(_shellSettings["ConnectionString"])) { setupContext.DatabaseProvider = _shellSettings["DatabaseProvider"]; setupContext.DatabaseConnectionString = _shellSettings["ConnectionString"]; setupContext.DatabaseTablePrefix = _shellSettings["TablePrefix"]; } else { setupContext.DatabaseProvider = model.DatabaseProvider; setupContext.DatabaseConnectionString = model.ConnectionString; setupContext.DatabaseTablePrefix = model.TablePrefix; } var executionId = await _setupService.SetupAsync(setupContext); // Check if a component in the Setup failed if (setupContext.Errors.Any()) { foreach (var error in setupContext.Errors) { ModelState.AddModelError(error.Key, error.Value); } return View(model); } return Redirect("~/"); } private void CopyShellSettingsValues(SetupViewModel model) { if (!String.IsNullOrEmpty(_shellSettings["ConnectionString"])) { model.DatabaseConfigurationPreset = true; model.ConnectionString = _shellSettings["ConnectionString"]; } if (!String.IsNullOrEmpty(_shellSettings["RecipeName"])) { model.RecipeNamePreset = true; model.RecipeName = _shellSettings["RecipeName"]; } if (!String.IsNullOrEmpty(_shellSettings["DatabaseProvider"])) { model.DatabaseConfigurationPreset = true; model.DatabaseProvider = _shellSettings["DatabaseProvider"]; } else { model.DatabaseProvider = model.DatabaseProviders.FirstOrDefault(p => p.IsDefault)?.Value; } if (!String.IsNullOrEmpty(_shellSettings["Description"])) { model.Description = _shellSettings["Description"]; } } private async Task<bool> IsTokenValid(string token) { try { var result = false; var shellScope = await _shellHost.GetScopeAsync(ShellHelper.DefaultShellName); await shellScope.UsingAsync(scope => { var dataProtectionProvider = scope.ServiceProvider.GetRequiredService<IDataProtectionProvider>(); var dataProtector = dataProtectionProvider.CreateProtector("Tokens").ToTimeLimitedDataProtector(); var tokenValue = dataProtector.Unprotect(token, out var expiration); if (_clock.UtcNow < expiration.ToUniversalTime()) { if (_shellSettings["Secret"] == tokenValue) { result = true; } } return Task.CompletedTask; }); return result; } catch (Exception ex) { _logger.LogError(ex, "Error in decrypting the token"); } return false; } } }
37.501976
152
0.574831
[ "BSD-3-Clause" ]
ArieGato/OrchardCore
src/OrchardCore.Modules/OrchardCore.Setup/Controllers/SetupController.cs
9,488
C#
using System; using System.Collections.Generic; namespace ApartmentsLilly.Server.Infrastructure.Extensions { public static class EnumExtensions { public static List<EnumValue> GetValues<T>() { var values = new List<EnumValue>(); foreach (var itemType in Enum.GetValues(typeof(T))) { values.Add(new EnumValue() { Name = Enum.GetName(typeof(T), itemType), Value = (int)itemType }); } return values; } public class EnumValue { public string Name { get; set; } public int Value { get; set; } } } }
24.333333
63
0.50137
[ "MIT" ]
yotkoKanchev/ApartmentsLilly
Server/ApartmentsLilly.Server/Infrastructure/Extensions/EnumExtensions.cs
732
C#
namespace VTMap.Core.Primitives { /// <summary> /// Context for which the style should be evaluated /// </summary> public class EvaluationContext { public float? Zoom { get; set; } public float Scale { get; set; } public TagsCollection Tags { get; set; } public EvaluationContext(float? zoom, float scale = 1, TagsCollection tags = null) { Zoom = zoom; Scale = scale; Tags = tags; } public override bool Equals(object other) => other is EvaluationContext context && Equals(context); public bool Equals(EvaluationContext context) { return context != null && context.Zoom == Zoom && context.Scale == Scale && ((context.Tags == null && Tags == null) || context.Tags.Equals(Tags)); } } }
29.034483
158
0.577197
[ "MIT" ]
charlenni/VTMap
Source/VTMap.Core/Primitives/EvaluationContext.cs
844
C#
// Copyright 2021 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. // Generated code. DO NOT EDIT! namespace Google.Cloud.Spanner.V1.Snippets { using Google.Api.Gax.Grpc; using Google.Cloud.Spanner.V1; using Google.Protobuf; using System.Threading.Tasks; public sealed partial class GeneratedSpannerClientStandaloneSnippets { /// <summary>Snippet for StreamingRead</summary> /// <remarks> /// This snippet has been automatically generated for illustrative purposes only. /// It may require modifications to work in your environment. /// </remarks> public async Task StreamingReadRequestObject() { // Create client SpannerClient spannerClient = SpannerClient.Create(); // Initialize request argument(s) ReadRequest request = new ReadRequest { SessionAsSessionName = SessionName.FromProjectInstanceDatabaseSession("[PROJECT]", "[INSTANCE]", "[DATABASE]", "[SESSION]"), Transaction = new TransactionSelector(), Table = "", Index = "", Columns = { "", }, KeySet = new KeySet(), Limit = 0L, ResumeToken = ByteString.Empty, PartitionToken = ByteString.Empty, RequestOptions = new RequestOptions(), }; // Make the request, returning a streaming response SpannerClient.StreamingReadStream response = spannerClient.StreamingRead(request); // Read streaming responses from server until complete // Note that C# 8 code can use await foreach AsyncResponseStream<PartialResultSet> responseStream = response.GetResponseStream(); while (await responseStream.MoveNextAsync()) { PartialResultSet responseItem = responseStream.Current; // Do something with streamed response } // The response stream has completed } } }
40.484375
140
0.632188
[ "Apache-2.0" ]
googleapis/googleapis-gen
google/spanner/v1/google-cloud-spanner-v1-csharp/Google.Cloud.Spanner.V1.StandaloneSnippets/SpannerClient.StreamingReadRequestObjectSnippet.g.cs
2,591
C#
using System; using NUnit.Framework; namespace PostalCodes.UnitTests { internal class IsoCountryCodeValidatorTests { private static readonly IIsoCountryCodeValidator IsoValidator = new IsoCountryCodeValidator(); [Test] public void Validate_ValidCountryCode_ReturnsTrue() { Assert.IsTrue(IsoValidator.Validate("US")); } [Test] [TestCase(null)] [TestCase("ZZ")] [TestCase("FFF")] public void Validate_InvalidCountryCode_ReturnsFalse(string countryCode) { Assert.IsFalse(IsoValidator.Validate(countryCode)); } [Test] [TestCase("US", "US")] [TestCase(" US", "US")] [TestCase("US ", "US")] [TestCase(" US ", "US")] [TestCase("us", "US")] public void GetNormalizedCountryCode_ReturnsValidCountryCode(string input, string output) { Assert.AreEqual(output, IsoValidator.GetNormalizedCountryCode(input)); } [Test] [TestCase(null, "Country code must not be null.")] public void GetNormalizedCountryCode_NullCountryCode_ThrowsArgumentException(string input, string output) { Assert.Throws<ArgumentException>(() => IsoValidator.GetNormalizedCountryCode(input), output); } [Test] [TestCase("", "Country code must contain exactly two characters.")] [TestCase("U", "Country code must contain exactly two characters.")] [TestCase("USA", "Country code must contain exactly two characters.")] public void GetNormalizedCountryCode_InvalidNumberOfChars_ThrowsArgumentException(string input, string output) { Assert.Throws<ArgumentException>(() => IsoValidator.GetNormalizedCountryCode(input), output); } [Test] [TestCase("UK", "GB")] [TestCase("AN", "CW")] public void GetNormalizedCountryCode_NonStandardCountryCode_ReturnsIsoCountryCode(string input, string output) { Assert.AreEqual(output, IsoValidator.GetNormalizedCountryCode(input)); } } }
35.934426
119
0.62135
[ "Apache-2.0" ]
twiho2/PostalCodes.Net
src/PostalCodes.UnitTests/IsoCountryCodeValidatorTests.cs
2,134
C#
using HK.Nanka.RobotSystems; using UnityEngine; using UnityEngine.Assertions; namespace HK.Nanka { public sealed class GameController : MonoBehaviour { [SerializeField] private ItemSpecs itemSpecs; [SerializeField] private Recipes recipes; [SerializeField] private RobotController robotController; public static GameController Instance { private set; get; } public Player Player { private set; get; } public ItemSpecs ItemSpecs { get { return this.itemSpecs; } } public Recipes Recipes { get { return this.recipes; } } public RobotController RobotController { get { return this.robotController; } } void Awake() { Assert.IsNull(Instance); Instance = this; this.Player = new Player(); this.ItemSpecs.Initialize(); } } }
23.947368
87
0.617582
[ "MIT" ]
hiroki-kitahara/Nanka
Assets/Scripts/System/GameController.cs
912
C#
// Copyright (c) Josef Pihrt. All rights reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System.Collections.Generic; #pragma warning disable RCS1016, RCS1067, RCS1095, RCS1163 namespace Roslynator.CSharp.Analyzers.Test { internal static class FormatInitializerWithSingleExpressionOnSingleLine { private class Entity { public string Name { get; set; } public int Value { get; set; } } public static void Foo() { var entity = new Entity() { Name = "Name" }; var dic = new Dictionary<int, string>() { { 0, "0" } }; var dic2 = new Dictionary<int, string>() { [0] = "0" }; var entities = new Entity[] { new Entity() { Name = new string('a', 1) } }; var items = new List<string>() { { null } }; // n var entity2 = new Entity() { Name = "Name", Value = 0 }; var entity3 = new Entity() { Name = "Name" }; var entity4 = new Entity() { // abc Name = "Name" }; } } }
22.637681
160
0.40589
[ "Apache-2.0" ]
TechnoridersForks/Roslynator
source/Test/AnalyzersTest/FormatInitializerWithSingleExpressionOnSingleLine.cs
1,564
C#
using System; using System.Data.SQLite; using System.Reflection; using System.Text; namespace InfrastructureLayer.DataAccess { public class WolSqliteDatabase { public SQLiteConnection Connection { private set; get; } public string FilePath { get; private set; } public bool Valid { get; private set; } public WolSqliteDatabase(string filePath) { Valid = false; FilePath = filePath; Connection = new SQLiteConnection(PrepareConnectrionString()); //We need to check if database exists. Database doesn't exits if (!System.IO.File.Exists(filePath)) CreateDatabase(); VerifyDatabase(); } private string PrepareConnectrionString() { StringBuilder connectionString = new StringBuilder(); connectionString.Append("Data Source="); connectionString.Append(FilePath); connectionString.Append(";Version=3;"); return connectionString.ToString(); } private string PrepareConnectrionString(string path) { StringBuilder connectionString = new StringBuilder(); connectionString.Append("Data Source="); connectionString.Append(path); connectionString.Append(";Version=3;"); return connectionString.ToString(); } public void CreateDatabase() { CreateDatabaseFile(); GenerateDatabaseStructure(); } public void ImportDatabase(string sourcePath) { SQLiteConnection sourceDatabase = new SQLiteConnection(PrepareConnectrionString(sourcePath)); try { this.Connection.Open(); sourceDatabase.Open(); sourceDatabase.BackupDatabase(this.Connection, "main", "main", -1, null, 0); } catch (Exception ex) { } finally { this.Connection.Close(); sourceDatabase.Close(); } } public void ExportDatabase(string destinationPath) { SQLiteConnection destinationDatabase = new SQLiteConnection(PrepareConnectrionString(destinationPath)); try { this.Connection.Open(); destinationDatabase.Open(); this.Connection.BackupDatabase(destinationDatabase, "main", "main", -1, null, 0); } catch (Exception e) { //return false; } finally { this.Connection.Close(); destinationDatabase.Close(); } } private void CreateDatabaseFile() { SQLiteConnection.CreateFile(FilePath); } public void GenerateDatabaseStructure() { try { string appVersion = Assembly.GetExecutingAssembly().GetName().Version.ToString(); string dbVersion = Assembly.GetExecutingAssembly().GetName().Version.Major.ToString(); string createdAt = DateTime.Now.ToString(); string query = $"INSERT INTO 'Info' ('Attribute','Value') VALUES ('AppVersion', '{appVersion}');" + $"INSERT INTO 'Info' ('Attribute','Value') VALUES ('CreatedAt','{createdAt}');"; Connection.Open(); SQLiteCommand cmd = new SQLiteCommand(InfrastructureLayer.Properties.InfrastructureResource.create_db_1, Connection); SQLiteCommand cmd1 = new SQLiteCommand(query, Connection); cmd.ExecuteNonQuery(); cmd1.ExecuteNonQuery(); } catch (Exception e) { } finally { Connection.Close(); } } private void VerifyDatabase() { try { string sql = "SELECT Value FROM Info WHERE Attribute == 'AppVersion'"; Connection.Open(); SQLiteCommand cmd = new SQLiteCommand(sql, Connection); var reader = cmd.ExecuteScalar(); Version version = Version.Parse(reader.ToString()); Valid = version.Major == Assembly.GetExecutingAssembly().GetName().Version.Major; } catch (Exception e) { Valid = false; } finally { Connection.Close(); } } } }
29.515723
133
0.528873
[ "MIT" ]
nski27/WOLsignal
src/InfrastructureLayer/DataAccess/WolSqliteDatabase.cs
4,695
C#
// <auto-generated /> using System; using evitoriav2.EntityFrameworkCore; using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Infrastructure; using Microsoft.EntityFrameworkCore.Metadata; using Microsoft.EntityFrameworkCore.Storage.ValueConversion; namespace evitoriav2.Migrations { [DbContext(typeof(evitoriav2DbContext))] partial class evitoriav2DbContextModelSnapshot : ModelSnapshot { protected override void BuildModel(ModelBuilder modelBuilder) { #pragma warning disable 612, 618 modelBuilder .UseIdentityColumns() .HasAnnotation("Relational:MaxIdentifierLength", 128) .HasAnnotation("ProductVersion", "5.0.3"); modelBuilder.Entity("Abp.Application.Editions.Edition", b => { b.Property<int>("Id") .ValueGeneratedOnAdd() .HasColumnType("int") .UseIdentityColumn(); b.Property<DateTime>("CreationTime") .HasColumnType("datetime2"); b.Property<long?>("CreatorUserId") .HasColumnType("bigint"); b.Property<long?>("DeleterUserId") .HasColumnType("bigint"); b.Property<DateTime?>("DeletionTime") .HasColumnType("datetime2"); b.Property<string>("DisplayName") .IsRequired() .HasMaxLength(64) .HasColumnType("nvarchar(64)"); b.Property<bool>("IsDeleted") .HasColumnType("bit"); b.Property<DateTime?>("LastModificationTime") .HasColumnType("datetime2"); b.Property<long?>("LastModifierUserId") .HasColumnType("bigint"); b.Property<string>("Name") .IsRequired() .HasMaxLength(32) .HasColumnType("nvarchar(32)"); b.HasKey("Id"); b.ToTable("AbpEditions"); }); modelBuilder.Entity("Abp.Application.Features.FeatureSetting", b => { b.Property<long>("Id") .ValueGeneratedOnAdd() .HasColumnType("bigint") .UseIdentityColumn(); b.Property<DateTime>("CreationTime") .HasColumnType("datetime2"); b.Property<long?>("CreatorUserId") .HasColumnType("bigint"); b.Property<string>("Discriminator") .IsRequired() .HasColumnType("nvarchar(max)"); b.Property<string>("Name") .IsRequired() .HasMaxLength(128) .HasColumnType("nvarchar(128)"); b.Property<int?>("TenantId") .HasColumnType("int"); b.Property<string>("Value") .IsRequired() .HasMaxLength(2000) .HasColumnType("nvarchar(2000)"); b.HasKey("Id"); b.ToTable("AbpFeatures"); b.HasDiscriminator<string>("Discriminator").HasValue("FeatureSetting"); }); modelBuilder.Entity("Abp.Auditing.AuditLog", b => { b.Property<long>("Id") .ValueGeneratedOnAdd() .HasColumnType("bigint") .UseIdentityColumn(); b.Property<string>("BrowserInfo") .HasMaxLength(512) .HasColumnType("nvarchar(512)"); b.Property<string>("ClientIpAddress") .HasMaxLength(64) .HasColumnType("nvarchar(64)"); b.Property<string>("ClientName") .HasMaxLength(128) .HasColumnType("nvarchar(128)"); b.Property<string>("CustomData") .HasMaxLength(2000) .HasColumnType("nvarchar(2000)"); b.Property<string>("Exception") .HasMaxLength(2000) .HasColumnType("nvarchar(2000)"); b.Property<string>("ExceptionMessage") .HasMaxLength(1024) .HasColumnType("nvarchar(1024)"); b.Property<int>("ExecutionDuration") .HasColumnType("int"); b.Property<DateTime>("ExecutionTime") .HasColumnType("datetime2"); b.Property<int?>("ImpersonatorTenantId") .HasColumnType("int"); b.Property<long?>("ImpersonatorUserId") .HasColumnType("bigint"); b.Property<string>("MethodName") .HasMaxLength(256) .HasColumnType("nvarchar(256)"); b.Property<string>("Parameters") .HasMaxLength(1024) .HasColumnType("nvarchar(1024)"); b.Property<string>("ReturnValue") .HasColumnType("nvarchar(max)"); b.Property<string>("ServiceName") .HasMaxLength(256) .HasColumnType("nvarchar(256)"); b.Property<int?>("TenantId") .HasColumnType("int"); b.Property<long?>("UserId") .HasColumnType("bigint"); b.HasKey("Id"); b.HasIndex("TenantId", "ExecutionDuration"); b.HasIndex("TenantId", "ExecutionTime"); b.HasIndex("TenantId", "UserId"); b.ToTable("AbpAuditLogs"); }); modelBuilder.Entity("Abp.Authorization.PermissionSetting", b => { b.Property<long>("Id") .ValueGeneratedOnAdd() .HasColumnType("bigint") .UseIdentityColumn(); b.Property<DateTime>("CreationTime") .HasColumnType("datetime2"); b.Property<long?>("CreatorUserId") .HasColumnType("bigint"); b.Property<string>("Discriminator") .IsRequired() .HasColumnType("nvarchar(max)"); b.Property<bool>("IsGranted") .HasColumnType("bit"); b.Property<string>("Name") .IsRequired() .HasMaxLength(128) .HasColumnType("nvarchar(128)"); b.Property<int?>("TenantId") .HasColumnType("int"); b.HasKey("Id"); b.HasIndex("TenantId", "Name"); b.ToTable("AbpPermissions"); b.HasDiscriminator<string>("Discriminator").HasValue("PermissionSetting"); }); modelBuilder.Entity("Abp.Authorization.Roles.RoleClaim", b => { b.Property<long>("Id") .ValueGeneratedOnAdd() .HasColumnType("bigint") .UseIdentityColumn(); b.Property<string>("ClaimType") .HasMaxLength(256) .HasColumnType("nvarchar(256)"); b.Property<string>("ClaimValue") .HasColumnType("nvarchar(max)"); b.Property<DateTime>("CreationTime") .HasColumnType("datetime2"); b.Property<long?>("CreatorUserId") .HasColumnType("bigint"); b.Property<int>("RoleId") .HasColumnType("int"); b.Property<int?>("TenantId") .HasColumnType("int"); b.HasKey("Id"); b.HasIndex("RoleId"); b.HasIndex("TenantId", "ClaimType"); b.ToTable("AbpRoleClaims"); }); modelBuilder.Entity("Abp.Authorization.Users.UserAccount", b => { b.Property<long>("Id") .ValueGeneratedOnAdd() .HasColumnType("bigint") .UseIdentityColumn(); b.Property<DateTime>("CreationTime") .HasColumnType("datetime2"); b.Property<long?>("CreatorUserId") .HasColumnType("bigint"); b.Property<long?>("DeleterUserId") .HasColumnType("bigint"); b.Property<DateTime?>("DeletionTime") .HasColumnType("datetime2"); b.Property<string>("EmailAddress") .HasMaxLength(256) .HasColumnType("nvarchar(256)"); b.Property<bool>("IsDeleted") .HasColumnType("bit"); b.Property<DateTime?>("LastModificationTime") .HasColumnType("datetime2"); b.Property<long?>("LastModifierUserId") .HasColumnType("bigint"); b.Property<int?>("TenantId") .HasColumnType("int"); b.Property<long>("UserId") .HasColumnType("bigint"); b.Property<long?>("UserLinkId") .HasColumnType("bigint"); b.Property<string>("UserName") .HasMaxLength(256) .HasColumnType("nvarchar(256)"); b.HasKey("Id"); b.HasIndex("EmailAddress"); b.HasIndex("UserName"); b.HasIndex("TenantId", "EmailAddress"); b.HasIndex("TenantId", "UserId"); b.HasIndex("TenantId", "UserName"); b.ToTable("AbpUserAccounts"); }); modelBuilder.Entity("Abp.Authorization.Users.UserClaim", b => { b.Property<long>("Id") .ValueGeneratedOnAdd() .HasColumnType("bigint") .UseIdentityColumn(); b.Property<string>("ClaimType") .HasMaxLength(256) .HasColumnType("nvarchar(256)"); b.Property<string>("ClaimValue") .HasColumnType("nvarchar(max)"); b.Property<DateTime>("CreationTime") .HasColumnType("datetime2"); b.Property<long?>("CreatorUserId") .HasColumnType("bigint"); b.Property<int?>("TenantId") .HasColumnType("int"); b.Property<long>("UserId") .HasColumnType("bigint"); b.HasKey("Id"); b.HasIndex("UserId"); b.HasIndex("TenantId", "ClaimType"); b.ToTable("AbpUserClaims"); }); modelBuilder.Entity("Abp.Authorization.Users.UserLogin", b => { b.Property<long>("Id") .ValueGeneratedOnAdd() .HasColumnType("bigint") .UseIdentityColumn(); b.Property<string>("LoginProvider") .IsRequired() .HasMaxLength(128) .HasColumnType("nvarchar(128)"); b.Property<string>("ProviderKey") .IsRequired() .HasMaxLength(256) .HasColumnType("nvarchar(256)"); b.Property<int?>("TenantId") .HasColumnType("int"); b.Property<long>("UserId") .HasColumnType("bigint"); b.HasKey("Id"); b.HasIndex("UserId"); b.HasIndex("ProviderKey", "TenantId") .IsUnique() .HasFilter("[TenantId] IS NOT NULL"); b.HasIndex("TenantId", "UserId"); b.HasIndex("TenantId", "LoginProvider", "ProviderKey"); b.ToTable("AbpUserLogins"); }); modelBuilder.Entity("Abp.Authorization.Users.UserLoginAttempt", b => { b.Property<long>("Id") .ValueGeneratedOnAdd() .HasColumnType("bigint") .UseIdentityColumn(); b.Property<string>("BrowserInfo") .HasMaxLength(512) .HasColumnType("nvarchar(512)"); b.Property<string>("ClientIpAddress") .HasMaxLength(64) .HasColumnType("nvarchar(64)"); b.Property<string>("ClientName") .HasMaxLength(128) .HasColumnType("nvarchar(128)"); b.Property<DateTime>("CreationTime") .HasColumnType("datetime2"); b.Property<byte>("Result") .HasColumnType("tinyint"); b.Property<string>("TenancyName") .HasMaxLength(64) .HasColumnType("nvarchar(64)"); b.Property<int?>("TenantId") .HasColumnType("int"); b.Property<long?>("UserId") .HasColumnType("bigint"); b.Property<string>("UserNameOrEmailAddress") .HasMaxLength(256) .HasColumnType("nvarchar(256)"); b.HasKey("Id"); b.HasIndex("UserId", "TenantId"); b.HasIndex("TenancyName", "UserNameOrEmailAddress", "Result"); b.ToTable("AbpUserLoginAttempts"); }); modelBuilder.Entity("Abp.Authorization.Users.UserOrganizationUnit", b => { b.Property<long>("Id") .ValueGeneratedOnAdd() .HasColumnType("bigint") .UseIdentityColumn(); b.Property<DateTime>("CreationTime") .HasColumnType("datetime2"); b.Property<long?>("CreatorUserId") .HasColumnType("bigint"); b.Property<bool>("IsDeleted") .HasColumnType("bit"); b.Property<long>("OrganizationUnitId") .HasColumnType("bigint"); b.Property<int?>("TenantId") .HasColumnType("int"); b.Property<long>("UserId") .HasColumnType("bigint"); b.HasKey("Id"); b.HasIndex("TenantId", "OrganizationUnitId"); b.HasIndex("TenantId", "UserId"); b.ToTable("AbpUserOrganizationUnits"); }); modelBuilder.Entity("Abp.Authorization.Users.UserRole", b => { b.Property<long>("Id") .ValueGeneratedOnAdd() .HasColumnType("bigint") .UseIdentityColumn(); b.Property<DateTime>("CreationTime") .HasColumnType("datetime2"); b.Property<long?>("CreatorUserId") .HasColumnType("bigint"); b.Property<int>("RoleId") .HasColumnType("int"); b.Property<int?>("TenantId") .HasColumnType("int"); b.Property<long>("UserId") .HasColumnType("bigint"); b.HasKey("Id"); b.HasIndex("UserId"); b.HasIndex("TenantId", "RoleId"); b.HasIndex("TenantId", "UserId"); b.ToTable("AbpUserRoles"); }); modelBuilder.Entity("Abp.Authorization.Users.UserToken", b => { b.Property<long>("Id") .ValueGeneratedOnAdd() .HasColumnType("bigint") .UseIdentityColumn(); b.Property<DateTime?>("ExpireDate") .HasColumnType("datetime2"); b.Property<string>("LoginProvider") .HasMaxLength(128) .HasColumnType("nvarchar(128)"); b.Property<string>("Name") .HasMaxLength(128) .HasColumnType("nvarchar(128)"); b.Property<int?>("TenantId") .HasColumnType("int"); b.Property<long>("UserId") .HasColumnType("bigint"); b.Property<string>("Value") .HasMaxLength(512) .HasColumnType("nvarchar(512)"); b.HasKey("Id"); b.HasIndex("UserId"); b.HasIndex("TenantId", "UserId"); b.ToTable("AbpUserTokens"); }); modelBuilder.Entity("Abp.BackgroundJobs.BackgroundJobInfo", b => { b.Property<long>("Id") .ValueGeneratedOnAdd() .HasColumnType("bigint") .UseIdentityColumn(); b.Property<DateTime>("CreationTime") .HasColumnType("datetime2"); b.Property<long?>("CreatorUserId") .HasColumnType("bigint"); b.Property<bool>("IsAbandoned") .HasColumnType("bit"); b.Property<string>("JobArgs") .IsRequired() .HasMaxLength(1048576) .HasColumnType("nvarchar(max)"); b.Property<string>("JobType") .IsRequired() .HasMaxLength(512) .HasColumnType("nvarchar(512)"); b.Property<DateTime?>("LastTryTime") .HasColumnType("datetime2"); b.Property<DateTime>("NextTryTime") .HasColumnType("datetime2"); b.Property<byte>("Priority") .HasColumnType("tinyint"); b.Property<short>("TryCount") .HasColumnType("smallint"); b.HasKey("Id"); b.HasIndex("IsAbandoned", "NextTryTime"); b.ToTable("AbpBackgroundJobs"); }); modelBuilder.Entity("Abp.Configuration.Setting", b => { b.Property<long>("Id") .ValueGeneratedOnAdd() .HasColumnType("bigint") .UseIdentityColumn(); b.Property<DateTime>("CreationTime") .HasColumnType("datetime2"); b.Property<long?>("CreatorUserId") .HasColumnType("bigint"); b.Property<DateTime?>("LastModificationTime") .HasColumnType("datetime2"); b.Property<long?>("LastModifierUserId") .HasColumnType("bigint"); b.Property<string>("Name") .IsRequired() .HasMaxLength(256) .HasColumnType("nvarchar(256)"); b.Property<int?>("TenantId") .HasColumnType("int"); b.Property<long?>("UserId") .HasColumnType("bigint"); b.Property<string>("Value") .HasColumnType("nvarchar(max)"); b.HasKey("Id"); b.HasIndex("UserId"); b.HasIndex("TenantId", "Name", "UserId") .IsUnique(); b.ToTable("AbpSettings"); }); modelBuilder.Entity("Abp.DynamicEntityProperties.DynamicEntityProperty", b => { b.Property<int>("Id") .ValueGeneratedOnAdd() .HasColumnType("int") .UseIdentityColumn(); b.Property<int>("DynamicPropertyId") .HasColumnType("int"); b.Property<string>("EntityFullName") .HasMaxLength(256) .HasColumnType("nvarchar(256)"); b.Property<int?>("TenantId") .HasColumnType("int"); b.HasKey("Id"); b.HasIndex("DynamicPropertyId"); b.HasIndex("EntityFullName", "DynamicPropertyId", "TenantId") .IsUnique() .HasFilter("[EntityFullName] IS NOT NULL AND [TenantId] IS NOT NULL"); b.ToTable("AbpDynamicEntityProperties"); }); modelBuilder.Entity("Abp.DynamicEntityProperties.DynamicEntityPropertyValue", b => { b.Property<long>("Id") .ValueGeneratedOnAdd() .HasColumnType("bigint") .UseIdentityColumn(); b.Property<int>("DynamicEntityPropertyId") .HasColumnType("int"); b.Property<string>("EntityId") .HasColumnType("nvarchar(max)"); b.Property<int?>("TenantId") .HasColumnType("int"); b.Property<string>("Value") .IsRequired() .HasColumnType("nvarchar(max)"); b.HasKey("Id"); b.HasIndex("DynamicEntityPropertyId"); b.ToTable("AbpDynamicEntityPropertyValues"); }); modelBuilder.Entity("Abp.DynamicEntityProperties.DynamicProperty", b => { b.Property<int>("Id") .ValueGeneratedOnAdd() .HasColumnType("int") .UseIdentityColumn(); b.Property<string>("DisplayName") .HasColumnType("nvarchar(max)"); b.Property<string>("InputType") .HasColumnType("nvarchar(max)"); b.Property<string>("Permission") .HasColumnType("nvarchar(max)"); b.Property<string>("PropertyName") .HasMaxLength(256) .HasColumnType("nvarchar(256)"); b.Property<int?>("TenantId") .HasColumnType("int"); b.HasKey("Id"); b.HasIndex("PropertyName", "TenantId") .IsUnique() .HasFilter("[PropertyName] IS NOT NULL AND [TenantId] IS NOT NULL"); b.ToTable("AbpDynamicProperties"); }); modelBuilder.Entity("Abp.DynamicEntityProperties.DynamicPropertyValue", b => { b.Property<long>("Id") .ValueGeneratedOnAdd() .HasColumnType("bigint") .UseIdentityColumn(); b.Property<int>("DynamicPropertyId") .HasColumnType("int"); b.Property<int?>("TenantId") .HasColumnType("int"); b.Property<string>("Value") .IsRequired() .HasColumnType("nvarchar(max)"); b.HasKey("Id"); b.HasIndex("DynamicPropertyId"); b.ToTable("AbpDynamicPropertyValues"); }); modelBuilder.Entity("Abp.EntityHistory.EntityChange", b => { b.Property<long>("Id") .ValueGeneratedOnAdd() .HasColumnType("bigint") .UseIdentityColumn(); b.Property<DateTime>("ChangeTime") .HasColumnType("datetime2"); b.Property<byte>("ChangeType") .HasColumnType("tinyint"); b.Property<long>("EntityChangeSetId") .HasColumnType("bigint"); b.Property<string>("EntityId") .HasMaxLength(48) .HasColumnType("nvarchar(48)"); b.Property<string>("EntityTypeFullName") .HasMaxLength(192) .HasColumnType("nvarchar(192)"); b.Property<int?>("TenantId") .HasColumnType("int"); b.HasKey("Id"); b.HasIndex("EntityChangeSetId"); b.HasIndex("EntityTypeFullName", "EntityId"); b.ToTable("AbpEntityChanges"); }); modelBuilder.Entity("Abp.EntityHistory.EntityChangeSet", b => { b.Property<long>("Id") .ValueGeneratedOnAdd() .HasColumnType("bigint") .UseIdentityColumn(); b.Property<string>("BrowserInfo") .HasMaxLength(512) .HasColumnType("nvarchar(512)"); b.Property<string>("ClientIpAddress") .HasMaxLength(64) .HasColumnType("nvarchar(64)"); b.Property<string>("ClientName") .HasMaxLength(128) .HasColumnType("nvarchar(128)"); b.Property<DateTime>("CreationTime") .HasColumnType("datetime2"); b.Property<string>("ExtensionData") .HasColumnType("nvarchar(max)"); b.Property<int?>("ImpersonatorTenantId") .HasColumnType("int"); b.Property<long?>("ImpersonatorUserId") .HasColumnType("bigint"); b.Property<string>("Reason") .HasMaxLength(256) .HasColumnType("nvarchar(256)"); b.Property<int?>("TenantId") .HasColumnType("int"); b.Property<long?>("UserId") .HasColumnType("bigint"); b.HasKey("Id"); b.HasIndex("TenantId", "CreationTime"); b.HasIndex("TenantId", "Reason"); b.HasIndex("TenantId", "UserId"); b.ToTable("AbpEntityChangeSets"); }); modelBuilder.Entity("Abp.EntityHistory.EntityPropertyChange", b => { b.Property<long>("Id") .ValueGeneratedOnAdd() .HasColumnType("bigint") .UseIdentityColumn(); b.Property<long>("EntityChangeId") .HasColumnType("bigint"); b.Property<string>("NewValue") .HasMaxLength(512) .HasColumnType("nvarchar(512)"); b.Property<string>("NewValueHash") .HasColumnType("nvarchar(max)"); b.Property<string>("OriginalValue") .HasMaxLength(512) .HasColumnType("nvarchar(512)"); b.Property<string>("OriginalValueHash") .HasColumnType("nvarchar(max)"); b.Property<string>("PropertyName") .HasMaxLength(96) .HasColumnType("nvarchar(96)"); b.Property<string>("PropertyTypeFullName") .HasMaxLength(192) .HasColumnType("nvarchar(192)"); b.Property<int?>("TenantId") .HasColumnType("int"); b.HasKey("Id"); b.HasIndex("EntityChangeId"); b.ToTable("AbpEntityPropertyChanges"); }); modelBuilder.Entity("Abp.Localization.ApplicationLanguage", b => { b.Property<int>("Id") .ValueGeneratedOnAdd() .HasColumnType("int") .UseIdentityColumn(); b.Property<DateTime>("CreationTime") .HasColumnType("datetime2"); b.Property<long?>("CreatorUserId") .HasColumnType("bigint"); b.Property<long?>("DeleterUserId") .HasColumnType("bigint"); b.Property<DateTime?>("DeletionTime") .HasColumnType("datetime2"); b.Property<string>("DisplayName") .IsRequired() .HasMaxLength(64) .HasColumnType("nvarchar(64)"); b.Property<string>("Icon") .HasMaxLength(128) .HasColumnType("nvarchar(128)"); b.Property<bool>("IsDeleted") .HasColumnType("bit"); b.Property<bool>("IsDisabled") .HasColumnType("bit"); b.Property<DateTime?>("LastModificationTime") .HasColumnType("datetime2"); b.Property<long?>("LastModifierUserId") .HasColumnType("bigint"); b.Property<string>("Name") .IsRequired() .HasMaxLength(128) .HasColumnType("nvarchar(128)"); b.Property<int?>("TenantId") .HasColumnType("int"); b.HasKey("Id"); b.HasIndex("TenantId", "Name"); b.ToTable("AbpLanguages"); }); modelBuilder.Entity("Abp.Localization.ApplicationLanguageText", b => { b.Property<long>("Id") .ValueGeneratedOnAdd() .HasColumnType("bigint") .UseIdentityColumn(); b.Property<DateTime>("CreationTime") .HasColumnType("datetime2"); b.Property<long?>("CreatorUserId") .HasColumnType("bigint"); b.Property<string>("Key") .IsRequired() .HasMaxLength(256) .HasColumnType("nvarchar(256)"); b.Property<string>("LanguageName") .IsRequired() .HasMaxLength(128) .HasColumnType("nvarchar(128)"); b.Property<DateTime?>("LastModificationTime") .HasColumnType("datetime2"); b.Property<long?>("LastModifierUserId") .HasColumnType("bigint"); b.Property<string>("Source") .IsRequired() .HasMaxLength(128) .HasColumnType("nvarchar(128)"); b.Property<int?>("TenantId") .HasColumnType("int"); b.Property<string>("Value") .IsRequired() .HasMaxLength(67108864) .HasColumnType("nvarchar(max)"); b.HasKey("Id"); b.HasIndex("TenantId", "Source", "LanguageName", "Key"); b.ToTable("AbpLanguageTexts"); }); modelBuilder.Entity("Abp.Notifications.NotificationInfo", b => { b.Property<Guid>("Id") .ValueGeneratedOnAdd() .HasColumnType("uniqueidentifier"); b.Property<DateTime>("CreationTime") .HasColumnType("datetime2"); b.Property<long?>("CreatorUserId") .HasColumnType("bigint"); b.Property<string>("Data") .HasMaxLength(1048576) .HasColumnType("nvarchar(max)"); b.Property<string>("DataTypeName") .HasMaxLength(512) .HasColumnType("nvarchar(512)"); b.Property<string>("EntityId") .HasMaxLength(96) .HasColumnType("nvarchar(96)"); b.Property<string>("EntityTypeAssemblyQualifiedName") .HasMaxLength(512) .HasColumnType("nvarchar(512)"); b.Property<string>("EntityTypeName") .HasMaxLength(250) .HasColumnType("nvarchar(250)"); b.Property<string>("ExcludedUserIds") .HasMaxLength(131072) .HasColumnType("nvarchar(max)"); b.Property<string>("NotificationName") .IsRequired() .HasMaxLength(96) .HasColumnType("nvarchar(96)"); b.Property<byte>("Severity") .HasColumnType("tinyint"); b.Property<string>("TenantIds") .HasMaxLength(131072) .HasColumnType("nvarchar(max)"); b.Property<string>("UserIds") .HasMaxLength(131072) .HasColumnType("nvarchar(max)"); b.HasKey("Id"); b.ToTable("AbpNotifications"); }); modelBuilder.Entity("Abp.Notifications.NotificationSubscriptionInfo", b => { b.Property<Guid>("Id") .ValueGeneratedOnAdd() .HasColumnType("uniqueidentifier"); b.Property<DateTime>("CreationTime") .HasColumnType("datetime2"); b.Property<long?>("CreatorUserId") .HasColumnType("bigint"); b.Property<string>("EntityId") .HasMaxLength(96) .HasColumnType("nvarchar(96)"); b.Property<string>("EntityTypeAssemblyQualifiedName") .HasMaxLength(512) .HasColumnType("nvarchar(512)"); b.Property<string>("EntityTypeName") .HasMaxLength(250) .HasColumnType("nvarchar(250)"); b.Property<string>("NotificationName") .HasMaxLength(96) .HasColumnType("nvarchar(96)"); b.Property<int?>("TenantId") .HasColumnType("int"); b.Property<long>("UserId") .HasColumnType("bigint"); b.HasKey("Id"); b.HasIndex("NotificationName", "EntityTypeName", "EntityId", "UserId"); b.HasIndex("TenantId", "NotificationName", "EntityTypeName", "EntityId", "UserId"); b.ToTable("AbpNotificationSubscriptions"); }); modelBuilder.Entity("Abp.Notifications.TenantNotificationInfo", b => { b.Property<Guid>("Id") .ValueGeneratedOnAdd() .HasColumnType("uniqueidentifier"); b.Property<DateTime>("CreationTime") .HasColumnType("datetime2"); b.Property<long?>("CreatorUserId") .HasColumnType("bigint"); b.Property<string>("Data") .HasMaxLength(1048576) .HasColumnType("nvarchar(max)"); b.Property<string>("DataTypeName") .HasMaxLength(512) .HasColumnType("nvarchar(512)"); b.Property<string>("EntityId") .HasMaxLength(96) .HasColumnType("nvarchar(96)"); b.Property<string>("EntityTypeAssemblyQualifiedName") .HasMaxLength(512) .HasColumnType("nvarchar(512)"); b.Property<string>("EntityTypeName") .HasMaxLength(250) .HasColumnType("nvarchar(250)"); b.Property<string>("NotificationName") .IsRequired() .HasMaxLength(96) .HasColumnType("nvarchar(96)"); b.Property<byte>("Severity") .HasColumnType("tinyint"); b.Property<int?>("TenantId") .HasColumnType("int"); b.HasKey("Id"); b.HasIndex("TenantId"); b.ToTable("AbpTenantNotifications"); }); modelBuilder.Entity("Abp.Notifications.UserNotificationInfo", b => { b.Property<Guid>("Id") .ValueGeneratedOnAdd() .HasColumnType("uniqueidentifier"); b.Property<DateTime>("CreationTime") .HasColumnType("datetime2"); b.Property<int>("State") .HasColumnType("int"); b.Property<int?>("TenantId") .HasColumnType("int"); b.Property<Guid>("TenantNotificationId") .HasColumnType("uniqueidentifier"); b.Property<long>("UserId") .HasColumnType("bigint"); b.HasKey("Id"); b.HasIndex("UserId", "State", "CreationTime"); b.ToTable("AbpUserNotifications"); }); modelBuilder.Entity("Abp.Organizations.OrganizationUnit", b => { b.Property<long>("Id") .ValueGeneratedOnAdd() .HasColumnType("bigint") .UseIdentityColumn(); b.Property<string>("Code") .IsRequired() .HasMaxLength(95) .HasColumnType("nvarchar(95)"); b.Property<DateTime>("CreationTime") .HasColumnType("datetime2"); b.Property<long?>("CreatorUserId") .HasColumnType("bigint"); b.Property<long?>("DeleterUserId") .HasColumnType("bigint"); b.Property<DateTime?>("DeletionTime") .HasColumnType("datetime2"); b.Property<string>("DisplayName") .IsRequired() .HasMaxLength(128) .HasColumnType("nvarchar(128)"); b.Property<bool>("IsDeleted") .HasColumnType("bit"); b.Property<DateTime?>("LastModificationTime") .HasColumnType("datetime2"); b.Property<long?>("LastModifierUserId") .HasColumnType("bigint"); b.Property<long?>("ParentId") .HasColumnType("bigint"); b.Property<int?>("TenantId") .HasColumnType("int"); b.HasKey("Id"); b.HasIndex("ParentId"); b.HasIndex("TenantId", "Code"); b.ToTable("AbpOrganizationUnits"); }); modelBuilder.Entity("Abp.Organizations.OrganizationUnitRole", b => { b.Property<long>("Id") .ValueGeneratedOnAdd() .HasColumnType("bigint") .UseIdentityColumn(); b.Property<DateTime>("CreationTime") .HasColumnType("datetime2"); b.Property<long?>("CreatorUserId") .HasColumnType("bigint"); b.Property<bool>("IsDeleted") .HasColumnType("bit"); b.Property<long>("OrganizationUnitId") .HasColumnType("bigint"); b.Property<int>("RoleId") .HasColumnType("int"); b.Property<int?>("TenantId") .HasColumnType("int"); b.HasKey("Id"); b.HasIndex("TenantId", "OrganizationUnitId"); b.HasIndex("TenantId", "RoleId"); b.ToTable("AbpOrganizationUnitRoles"); }); modelBuilder.Entity("Abp.Webhooks.WebhookEvent", b => { b.Property<Guid>("Id") .ValueGeneratedOnAdd() .HasColumnType("uniqueidentifier"); b.Property<DateTime>("CreationTime") .HasColumnType("datetime2"); b.Property<string>("Data") .HasColumnType("nvarchar(max)"); b.Property<DateTime?>("DeletionTime") .HasColumnType("datetime2"); b.Property<bool>("IsDeleted") .HasColumnType("bit"); b.Property<int?>("TenantId") .HasColumnType("int"); b.Property<string>("WebhookName") .IsRequired() .HasColumnType("nvarchar(max)"); b.HasKey("Id"); b.ToTable("AbpWebhookEvents"); }); modelBuilder.Entity("Abp.Webhooks.WebhookSendAttempt", b => { b.Property<Guid>("Id") .ValueGeneratedOnAdd() .HasColumnType("uniqueidentifier"); b.Property<DateTime>("CreationTime") .HasColumnType("datetime2"); b.Property<DateTime?>("LastModificationTime") .HasColumnType("datetime2"); b.Property<string>("Response") .HasColumnType("nvarchar(max)"); b.Property<int?>("ResponseStatusCode") .HasColumnType("int"); b.Property<int?>("TenantId") .HasColumnType("int"); b.Property<Guid>("WebhookEventId") .HasColumnType("uniqueidentifier"); b.Property<Guid>("WebhookSubscriptionId") .HasColumnType("uniqueidentifier"); b.HasKey("Id"); b.HasIndex("WebhookEventId"); b.ToTable("AbpWebhookSendAttempts"); }); modelBuilder.Entity("Abp.Webhooks.WebhookSubscriptionInfo", b => { b.Property<Guid>("Id") .ValueGeneratedOnAdd() .HasColumnType("uniqueidentifier"); b.Property<DateTime>("CreationTime") .HasColumnType("datetime2"); b.Property<long?>("CreatorUserId") .HasColumnType("bigint"); b.Property<string>("Headers") .HasColumnType("nvarchar(max)"); b.Property<bool>("IsActive") .HasColumnType("bit"); b.Property<string>("Secret") .IsRequired() .HasColumnType("nvarchar(max)"); b.Property<int?>("TenantId") .HasColumnType("int"); b.Property<string>("WebhookUri") .IsRequired() .HasColumnType("nvarchar(max)"); b.Property<string>("Webhooks") .HasColumnType("nvarchar(max)"); b.HasKey("Id"); b.ToTable("AbpWebhookSubscriptions"); }); modelBuilder.Entity("evitoriav2.Authorization.Roles.Role", b => { b.Property<int>("Id") .ValueGeneratedOnAdd() .HasColumnType("int") .UseIdentityColumn(); b.Property<string>("ConcurrencyStamp") .IsConcurrencyToken() .HasMaxLength(128) .HasColumnType("nvarchar(128)"); b.Property<DateTime>("CreationTime") .HasColumnType("datetime2"); b.Property<long?>("CreatorUserId") .HasColumnType("bigint"); b.Property<long?>("DeleterUserId") .HasColumnType("bigint"); b.Property<DateTime?>("DeletionTime") .HasColumnType("datetime2"); b.Property<string>("Description") .HasMaxLength(5000) .HasColumnType("nvarchar(max)"); b.Property<string>("DisplayName") .IsRequired() .HasMaxLength(64) .HasColumnType("nvarchar(64)"); b.Property<bool>("IsDefault") .HasColumnType("bit"); b.Property<bool>("IsDeleted") .HasColumnType("bit"); b.Property<bool>("IsStatic") .HasColumnType("bit"); b.Property<DateTime?>("LastModificationTime") .HasColumnType("datetime2"); b.Property<long?>("LastModifierUserId") .HasColumnType("bigint"); b.Property<string>("Name") .IsRequired() .HasMaxLength(32) .HasColumnType("nvarchar(32)"); b.Property<string>("NormalizedName") .IsRequired() .HasMaxLength(32) .HasColumnType("nvarchar(32)"); b.Property<int?>("TenantId") .HasColumnType("int"); b.HasKey("Id"); b.HasIndex("CreatorUserId"); b.HasIndex("DeleterUserId"); b.HasIndex("LastModifierUserId"); b.HasIndex("TenantId", "NormalizedName"); b.ToTable("AbpRoles"); }); modelBuilder.Entity("evitoriav2.Authorization.Users.User", b => { b.Property<long>("Id") .ValueGeneratedOnAdd() .HasColumnType("bigint") .UseIdentityColumn(); b.Property<int>("AccessFailedCount") .HasColumnType("int"); b.Property<string>("AuthenticationSource") .HasMaxLength(64) .HasColumnType("nvarchar(64)"); b.Property<string>("ConcurrencyStamp") .IsConcurrencyToken() .HasMaxLength(128) .HasColumnType("nvarchar(128)"); b.Property<DateTime>("CreationTime") .HasColumnType("datetime2"); b.Property<long?>("CreatorUserId") .HasColumnType("bigint"); b.Property<long?>("DeleterUserId") .HasColumnType("bigint"); b.Property<DateTime?>("DeletionTime") .HasColumnType("datetime2"); b.Property<string>("EmailAddress") .IsRequired() .HasMaxLength(256) .HasColumnType("nvarchar(256)"); b.Property<string>("EmailConfirmationCode") .HasMaxLength(328) .HasColumnType("nvarchar(328)"); b.Property<bool>("IsActive") .HasColumnType("bit"); b.Property<bool>("IsDeleted") .HasColumnType("bit"); b.Property<bool>("IsEmailConfirmed") .HasColumnType("bit"); b.Property<bool>("IsLockoutEnabled") .HasColumnType("bit"); b.Property<bool>("IsPhoneNumberConfirmed") .HasColumnType("bit"); b.Property<bool>("IsTwoFactorEnabled") .HasColumnType("bit"); b.Property<DateTime?>("LastModificationTime") .HasColumnType("datetime2"); b.Property<long?>("LastModifierUserId") .HasColumnType("bigint"); b.Property<DateTime?>("LockoutEndDateUtc") .HasColumnType("datetime2"); b.Property<string>("Name") .IsRequired() .HasMaxLength(64) .HasColumnType("nvarchar(64)"); b.Property<string>("NormalizedEmailAddress") .IsRequired() .HasMaxLength(256) .HasColumnType("nvarchar(256)"); b.Property<string>("NormalizedUserName") .IsRequired() .HasMaxLength(256) .HasColumnType("nvarchar(256)"); b.Property<string>("Password") .IsRequired() .HasMaxLength(128) .HasColumnType("nvarchar(128)"); b.Property<string>("PasswordResetCode") .HasMaxLength(328) .HasColumnType("nvarchar(328)"); b.Property<string>("PhoneNumber") .HasMaxLength(32) .HasColumnType("nvarchar(32)"); b.Property<string>("SecurityStamp") .HasMaxLength(128) .HasColumnType("nvarchar(128)"); b.Property<string>("Surname") .IsRequired() .HasMaxLength(64) .HasColumnType("nvarchar(64)"); b.Property<int?>("TenantId") .HasColumnType("int"); b.Property<string>("UserName") .IsRequired() .HasMaxLength(256) .HasColumnType("nvarchar(256)"); b.HasKey("Id"); b.HasIndex("CreatorUserId"); b.HasIndex("DeleterUserId"); b.HasIndex("LastModifierUserId"); b.HasIndex("TenantId", "NormalizedEmailAddress"); b.HasIndex("TenantId", "NormalizedUserName"); b.ToTable("AbpUsers"); }); modelBuilder.Entity("evitoriav2.MultiTenancy.Tenant", b => { b.Property<int>("Id") .ValueGeneratedOnAdd() .HasColumnType("int") .UseIdentityColumn(); b.Property<string>("ConnectionString") .HasMaxLength(1024) .HasColumnType("nvarchar(1024)"); b.Property<DateTime>("CreationTime") .HasColumnType("datetime2"); b.Property<long?>("CreatorUserId") .HasColumnType("bigint"); b.Property<long?>("DeleterUserId") .HasColumnType("bigint"); b.Property<DateTime?>("DeletionTime") .HasColumnType("datetime2"); b.Property<int?>("EditionId") .HasColumnType("int"); b.Property<bool>("IsActive") .HasColumnType("bit"); b.Property<bool>("IsDeleted") .HasColumnType("bit"); b.Property<DateTime?>("LastModificationTime") .HasColumnType("datetime2"); b.Property<long?>("LastModifierUserId") .HasColumnType("bigint"); b.Property<string>("Name") .IsRequired() .HasMaxLength(128) .HasColumnType("nvarchar(128)"); b.Property<string>("TenancyName") .IsRequired() .HasMaxLength(64) .HasColumnType("nvarchar(64)"); b.HasKey("Id"); b.HasIndex("CreatorUserId"); b.HasIndex("DeleterUserId"); b.HasIndex("EditionId"); b.HasIndex("LastModifierUserId"); b.HasIndex("TenancyName"); b.ToTable("AbpTenants"); }); modelBuilder.Entity("Abp.Application.Features.EditionFeatureSetting", b => { b.HasBaseType("Abp.Application.Features.FeatureSetting"); b.Property<int>("EditionId") .HasColumnType("int"); b.HasIndex("EditionId", "Name"); b.ToTable("AbpFeatures"); b.HasDiscriminator().HasValue("EditionFeatureSetting"); }); modelBuilder.Entity("Abp.MultiTenancy.TenantFeatureSetting", b => { b.HasBaseType("Abp.Application.Features.FeatureSetting"); b.HasIndex("TenantId", "Name"); b.ToTable("AbpFeatures"); b.HasDiscriminator().HasValue("TenantFeatureSetting"); }); modelBuilder.Entity("Abp.Authorization.Roles.RolePermissionSetting", b => { b.HasBaseType("Abp.Authorization.PermissionSetting"); b.Property<int>("RoleId") .HasColumnType("int"); b.HasIndex("RoleId"); b.ToTable("AbpPermissions"); b.HasDiscriminator().HasValue("RolePermissionSetting"); }); modelBuilder.Entity("Abp.Authorization.Users.UserPermissionSetting", b => { b.HasBaseType("Abp.Authorization.PermissionSetting"); b.Property<long>("UserId") .HasColumnType("bigint"); b.HasIndex("UserId"); b.ToTable("AbpPermissions"); b.HasDiscriminator().HasValue("UserPermissionSetting"); }); modelBuilder.Entity("Abp.Authorization.Roles.RoleClaim", b => { b.HasOne("evitoriav2.Authorization.Roles.Role", null) .WithMany("Claims") .HasForeignKey("RoleId") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); }); modelBuilder.Entity("Abp.Authorization.Users.UserClaim", b => { b.HasOne("evitoriav2.Authorization.Users.User", null) .WithMany("Claims") .HasForeignKey("UserId") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); }); modelBuilder.Entity("Abp.Authorization.Users.UserLogin", b => { b.HasOne("evitoriav2.Authorization.Users.User", null) .WithMany("Logins") .HasForeignKey("UserId") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); }); modelBuilder.Entity("Abp.Authorization.Users.UserRole", b => { b.HasOne("evitoriav2.Authorization.Users.User", null) .WithMany("Roles") .HasForeignKey("UserId") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); }); modelBuilder.Entity("Abp.Authorization.Users.UserToken", b => { b.HasOne("evitoriav2.Authorization.Users.User", null) .WithMany("Tokens") .HasForeignKey("UserId") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); }); modelBuilder.Entity("Abp.Configuration.Setting", b => { b.HasOne("evitoriav2.Authorization.Users.User", null) .WithMany("Settings") .HasForeignKey("UserId"); }); modelBuilder.Entity("Abp.DynamicEntityProperties.DynamicEntityProperty", b => { b.HasOne("Abp.DynamicEntityProperties.DynamicProperty", "DynamicProperty") .WithMany() .HasForeignKey("DynamicPropertyId") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); b.Navigation("DynamicProperty"); }); modelBuilder.Entity("Abp.DynamicEntityProperties.DynamicEntityPropertyValue", b => { b.HasOne("Abp.DynamicEntityProperties.DynamicEntityProperty", "DynamicEntityProperty") .WithMany() .HasForeignKey("DynamicEntityPropertyId") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); b.Navigation("DynamicEntityProperty"); }); modelBuilder.Entity("Abp.DynamicEntityProperties.DynamicPropertyValue", b => { b.HasOne("Abp.DynamicEntityProperties.DynamicProperty", "DynamicProperty") .WithMany("DynamicPropertyValues") .HasForeignKey("DynamicPropertyId") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); b.Navigation("DynamicProperty"); }); modelBuilder.Entity("Abp.EntityHistory.EntityChange", b => { b.HasOne("Abp.EntityHistory.EntityChangeSet", null) .WithMany("EntityChanges") .HasForeignKey("EntityChangeSetId") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); }); modelBuilder.Entity("Abp.EntityHistory.EntityPropertyChange", b => { b.HasOne("Abp.EntityHistory.EntityChange", null) .WithMany("PropertyChanges") .HasForeignKey("EntityChangeId") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); }); modelBuilder.Entity("Abp.Organizations.OrganizationUnit", b => { b.HasOne("Abp.Organizations.OrganizationUnit", "Parent") .WithMany("Children") .HasForeignKey("ParentId"); b.Navigation("Parent"); }); modelBuilder.Entity("Abp.Webhooks.WebhookSendAttempt", b => { b.HasOne("Abp.Webhooks.WebhookEvent", "WebhookEvent") .WithMany() .HasForeignKey("WebhookEventId") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); b.Navigation("WebhookEvent"); }); modelBuilder.Entity("evitoriav2.Authorization.Roles.Role", b => { b.HasOne("evitoriav2.Authorization.Users.User", "CreatorUser") .WithMany() .HasForeignKey("CreatorUserId"); b.HasOne("evitoriav2.Authorization.Users.User", "DeleterUser") .WithMany() .HasForeignKey("DeleterUserId"); b.HasOne("evitoriav2.Authorization.Users.User", "LastModifierUser") .WithMany() .HasForeignKey("LastModifierUserId"); b.Navigation("CreatorUser"); b.Navigation("DeleterUser"); b.Navigation("LastModifierUser"); }); modelBuilder.Entity("evitoriav2.Authorization.Users.User", b => { b.HasOne("evitoriav2.Authorization.Users.User", "CreatorUser") .WithMany() .HasForeignKey("CreatorUserId"); b.HasOne("evitoriav2.Authorization.Users.User", "DeleterUser") .WithMany() .HasForeignKey("DeleterUserId"); b.HasOne("evitoriav2.Authorization.Users.User", "LastModifierUser") .WithMany() .HasForeignKey("LastModifierUserId"); b.Navigation("CreatorUser"); b.Navigation("DeleterUser"); b.Navigation("LastModifierUser"); }); modelBuilder.Entity("evitoriav2.MultiTenancy.Tenant", b => { b.HasOne("evitoriav2.Authorization.Users.User", "CreatorUser") .WithMany() .HasForeignKey("CreatorUserId"); b.HasOne("evitoriav2.Authorization.Users.User", "DeleterUser") .WithMany() .HasForeignKey("DeleterUserId"); b.HasOne("Abp.Application.Editions.Edition", "Edition") .WithMany() .HasForeignKey("EditionId"); b.HasOne("evitoriav2.Authorization.Users.User", "LastModifierUser") .WithMany() .HasForeignKey("LastModifierUserId"); b.Navigation("CreatorUser"); b.Navigation("DeleterUser"); b.Navigation("Edition"); b.Navigation("LastModifierUser"); }); modelBuilder.Entity("Abp.Application.Features.EditionFeatureSetting", b => { b.HasOne("Abp.Application.Editions.Edition", "Edition") .WithMany() .HasForeignKey("EditionId") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); b.Navigation("Edition"); }); modelBuilder.Entity("Abp.Authorization.Roles.RolePermissionSetting", b => { b.HasOne("evitoriav2.Authorization.Roles.Role", null) .WithMany("Permissions") .HasForeignKey("RoleId") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); }); modelBuilder.Entity("Abp.Authorization.Users.UserPermissionSetting", b => { b.HasOne("evitoriav2.Authorization.Users.User", null) .WithMany("Permissions") .HasForeignKey("UserId") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); }); modelBuilder.Entity("Abp.DynamicEntityProperties.DynamicProperty", b => { b.Navigation("DynamicPropertyValues"); }); modelBuilder.Entity("Abp.EntityHistory.EntityChange", b => { b.Navigation("PropertyChanges"); }); modelBuilder.Entity("Abp.EntityHistory.EntityChangeSet", b => { b.Navigation("EntityChanges"); }); modelBuilder.Entity("Abp.Organizations.OrganizationUnit", b => { b.Navigation("Children"); }); modelBuilder.Entity("evitoriav2.Authorization.Roles.Role", b => { b.Navigation("Claims"); b.Navigation("Permissions"); }); modelBuilder.Entity("evitoriav2.Authorization.Users.User", b => { b.Navigation("Claims"); b.Navigation("Logins"); b.Navigation("Permissions"); b.Navigation("Roles"); b.Navigation("Settings"); b.Navigation("Tokens"); }); #pragma warning restore 612, 618 } } }
35.515658
106
0.429491
[ "MIT" ]
ntgentil/evitoria
aspnet-core/src/evitoriav2.EntityFrameworkCore/Migrations/evitoriav2DbContextModelSnapshot.cs
68,050
C#
using System; using System.IO; using System.Text; using Xunit; namespace GildedRoseKata { public class CharacterizationTest { [Fact] public void DoesWhatItDoes() { var sb = new StringBuilder(); Console.SetOut(new StringWriter(sb)); Console.SetIn(new StringReader("a\n")); Program.Main(new string[] { }); var output = sb.ToString(); var expectedOutput = File.ReadAllText("CharacterizationTest.txt"); Assert.Equal(expectedOutput.Trim(), output.Trim()); } } }
23.56
78
0.584041
[ "MIT" ]
vaughn-bloomerang/GildedRoseStarter
GildedRoseKata/CharacterizationTest.cs
591
C#
using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Options; using Plus.Data; using System; using System.Collections.Generic; namespace Plus.EntityFrameworkCore.DependencyInjection { public static class DbContextOptionsFactory { public static DbContextOptions<TDbContext> Create<TDbContext>(IServiceProvider serviceProvider) where TDbContext : PlusDbContext<TDbContext> { var creationContext = GetCreationContext<TDbContext>(serviceProvider); var context = new PlusDbContextConfigurationContext<TDbContext>( creationContext.ConnectionString, serviceProvider, creationContext.ConnectionStringName, creationContext.ExistingConnection ); var options = GetDbContextOptions<TDbContext>(serviceProvider); PreConfigure(options, context); Configure(options, context); return context.DbContextOptions.Options; } private static void PreConfigure<TDbContext>( PlusDbContextOptions options, PlusDbContextConfigurationContext<TDbContext> context) where TDbContext : PlusDbContext<TDbContext> { foreach (var defaultPreConfigureAction in options.DefaultPreConfigureActions) { defaultPreConfigureAction.Invoke(context); } var preConfigureActions = options.PreConfigureActions.GetOrDefault(typeof(TDbContext)); if (!preConfigureActions.IsNullOrEmpty()) { foreach (var preConfigureAction in preConfigureActions) { ((Action<PlusDbContextConfigurationContext<TDbContext>>)preConfigureAction).Invoke(context); } } } private static void Configure<TDbContext>( PlusDbContextOptions options, PlusDbContextConfigurationContext<TDbContext> context) where TDbContext : PlusDbContext<TDbContext> { var configureAction = options.ConfigureActions.GetOrDefault(typeof(TDbContext)); if (configureAction != null) { ((Action<PlusDbContextConfigurationContext<TDbContext>>)configureAction).Invoke(context); } else if (options.DefaultConfigureAction != null) { options.DefaultConfigureAction.Invoke(context); } else { throw new PlusException( $"No configuration found for {typeof(DbContext).AssemblyQualifiedName}! Use services.Configure<PlusDbContextOptions>(...) to configure it."); } } private static PlusDbContextOptions GetDbContextOptions<TDbContext>(IServiceProvider serviceProvider) where TDbContext : PlusDbContext<TDbContext> { return serviceProvider.GetRequiredService<IOptions<PlusDbContextOptions>>().Value; } private static DbContextCreationContext GetCreationContext<TDbContext>(IServiceProvider serviceProvider) where TDbContext : PlusDbContext<TDbContext> { var context = DbContextCreationContext.Current; if (context != null) { return context; } var connectionStringName = ConnectionStringNameAttribute.GetConnStringName<TDbContext>(); var connectionString = serviceProvider.GetRequiredService<IConnectionStringResolver>().Resolve(connectionStringName); return new DbContextCreationContext( connectionStringName, connectionString ); } } }
39.092784
161
0.642669
[ "MIT" ]
Meowv/Plus.Core
Plus.Core/Plus/EntityFrameworkCore/DependencyInjection/DbContextOptionsFactory.cs
3,792
C#
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the MIT license. See License.txt in the project root for license information. namespace System.Data.Entity.Core.Mapping { // This file contains an enum for the errors generated by StorageMappingItemCollection // There is almost a one-to-one correspondence between these error codes // and the resource strings - so if you need more insight into what the // error code means, please see the code that uses the particular enum // AND the corresponding resource string // error numbers end up being hard coded in test cases; they can be removed, but should not be changed. // reusing error numbers is probably OK, but not recommended. // // The acceptable range for this enum is // 2000 - 2999 // // The Range 10,000-15,000 is reserved for tools // internal enum MappingErrorCode { // <summary> // StorageMappingErrorBase // </summary> Value = 2000, // <summary> // Invalid Content // </summary> InvalidContent = Value + 1, // <summary> // Unresolvable Entity Container Name // </summary> InvalidEntityContainer = Value + 2, // <summary> // Unresolvable Entity Set Name // </summary> InvalidEntitySet = Value + 3, // <summary> // Unresolvable Entity Type Name // </summary> InvalidEntityType = Value + 4, // <summary> // Unresolvable Association Set Name // </summary> InvalidAssociationSet = Value + 5, // <summary> // Unresolvable Association Type Name // </summary> InvalidAssociationType = Value + 6, // <summary> // Unresolvable Table Name // </summary> InvalidTable = Value + 7, // <summary> // Unresolvable Complex Type Name // </summary> InvalidComplexType = Value + 8, // <summary> // Unresolvable Edm Member Name // </summary> InvalidEdmMember = Value + 9, // <summary> // Unresolvable Storage Member Name // </summary> InvalidStorageMember = Value + 10, // <summary> // TableMappingFragment element expected // </summary> TableMappingFragmentExpected = Value + 11, // <summary> // SetMappingFragment element expected // </summary> SetMappingExpected = Value + 12, // Unused: 13 // <summary> // Duplicate Set Map // </summary> DuplicateSetMapping = Value + 14, // <summary> // Duplicate Type Map // </summary> DuplicateTypeMapping = Value + 15, // <summary> // Condition Error // </summary> ConditionError = Value + 16, // Unused: 17 // <summary> // Root Mapping Element missing // </summary> RootMappingElementMissing = Value + 18, // <summary> // Incompatible member map // </summary> IncompatibleMemberMapping = Value + 19, // Unused: 20 // Unused: 21 // Unused: 22 // <summary> // Invalid Enum Value // </summary> InvalidEnumValue = Value + 23, // <summary> // Xml Schema Validation error // </summary> XmlSchemaParsingError = Value + 24, // <summary> // Xml Schema Validation error // </summary> XmlSchemaValidationError = Value + 25, // <summary> // Ambiguous Modification Function Mapping For AssociationSet // </summary> AmbiguousModificationFunctionMappingForAssociationSet = Value + 26, // <summary> // Missing Set Closure In Modification Function Mapping // </summary> MissingSetClosureInModificationFunctionMapping = Value + 27, // <summary> // Missing Modification Function Mapping For Entity Type // </summary> MissingModificationFunctionMappingForEntityType = Value + 28, // <summary> // Invalid Table Name Attribute With Modification Function Mapping // </summary> InvalidTableNameAttributeWithModificationFunctionMapping = Value + 29, // <summary> // Invalid Modification Function Mapping For Multiple Types // </summary> InvalidModificationFunctionMappingForMultipleTypes = Value + 30, // <summary> // Ambiguous Result Binding In Modification Function Mapping // </summary> AmbiguousResultBindingInModificationFunctionMapping = Value + 31, // <summary> // Invalid Association Set Role In Modification Function Mapping // </summary> InvalidAssociationSetRoleInModificationFunctionMapping = Value + 32, // <summary> // Invalid Association Set Cardinality In Modification Function Mapping // </summary> InvalidAssociationSetCardinalityInModificationFunctionMapping = Value + 33, // <summary> // Redundant Entity Type Mapping In Modification Function Mapping // </summary> RedundantEntityTypeMappingInModificationFunctionMapping = Value + 34, // <summary> // Missing Version In Modification Function Mapping // </summary> MissingVersionInModificationFunctionMapping = Value + 35, // <summary> // Invalid Version In Modification Function Mapping // </summary> InvalidVersionInModificationFunctionMapping = Value + 36, // <summary> // Invalid Parameter In Modification Function Mapping // </summary> InvalidParameterInModificationFunctionMapping = Value + 37, // <summary> // Parameter Bound Twice In Modification Function Mapping // </summary> ParameterBoundTwiceInModificationFunctionMapping = Value + 38, // <summary> // Same CSpace member mapped to multiple SSpace members with different types // </summary> CSpaceMemberMappedToMultipleSSpaceMemberWithDifferentTypes = Value + 39, // <summary> // No store type found for the given CSpace type (these error message is for primitive type with no facets) // </summary> NoEquivalentStorePrimitiveTypeFound = Value + 40, // <summary> // No Store type found for the given CSpace type with the given set of facets // </summary> NoEquivalentStorePrimitiveTypeWithFacetsFound = Value + 41, // <summary> // While mapping functions, if the property type is not compatible with the function parameter // </summary> InvalidModificationFunctionMappingPropertyParameterTypeMismatch = Value + 42, // <summary> // While mapping functions, if more than one end of association is mapped // </summary> InvalidModificationFunctionMappingMultipleEndsOfAssociationMapped = Value + 43, // <summary> // While mapping functions, if we find an unknown function // </summary> InvalidModificationFunctionMappingUnknownFunction = Value + 44, // <summary> // While mapping functions, if we find an ambiguous function // </summary> InvalidModificationFunctionMappingAmbiguousFunction = Value + 45, // <summary> // While mapping functions, if we find an invalid function // </summary> InvalidModificationFunctionMappingNotValidFunction = Value + 46, // <summary> // While mapping functions, if we find an invalid function parameter // </summary> InvalidModificationFunctionMappingNotValidFunctionParameter = Value + 47, // <summary> // Association set function mappings are not consistently defined for different operations // </summary> InvalidModificationFunctionMappingAssociationSetNotMappedForOperation = Value + 48, // <summary> // Entity type function mapping includes association end but the type is not part of the association // </summary> InvalidModificationFunctionMappingAssociationEndMappingInvalidForEntityType = Value + 49, // <summary> // Function import mapping references non-existent store function // </summary> MappingFunctionImportStoreFunctionDoesNotExist = Value + 50, // <summary> // Function import mapping references store function with overloads (overload resolution is not possible) // </summary> MappingFunctionImportStoreFunctionAmbiguous = Value + 51, // <summary> // Function import mapping reference non-existent import // </summary> MappingFunctionImportFunctionImportDoesNotExist = Value + 52, // <summary> // Function import mapping is mapped in several locations // </summary> MappingFunctionImportFunctionImportMappedMultipleTimes = Value + 53, // <summary> // Attempting to map non-composable function import to a composable function. // </summary> MappingFunctionImportTargetFunctionMustBeNonComposable = Value + 54, // <summary> // No parameter on import side corresponding to target parameter // </summary> MappingFunctionImportTargetParameterHasNoCorrespondingImportParameter = Value + 55, // <summary> // No parameter on target side corresponding to import parameter // </summary> MappingFunctionImportImportParameterHasNoCorrespondingTargetParameter = Value + 56, // <summary> // Parameter directions are different // </summary> MappingFunctionImportIncompatibleParameterMode = Value + 57, // <summary> // Parameter types are different // </summary> MappingFunctionImportIncompatibleParameterType = Value + 58, // <summary> // Rows affected parameter does not exist on mapped function // </summary> MappingFunctionImportRowsAffectedParameterDoesNotExist = Value + 59, // <summary> // Rows affected parameter does not Int32 // </summary> MappingFunctionImportRowsAffectedParameterHasWrongType = Value + 60, // <summary> // Rows affected does not have 'out' mode // </summary> MappingFunctionImportRowsAffectedParameterHasWrongMode = Value + 61, // <summary> // Empty Container Mapping // </summary> EmptyContainerMapping = Value + 62, // <summary> // Empty Set Mapping // </summary> EmptySetMapping = Value + 63, // <summary> // Both TableName Attribute on Set Mapping and QueryView specified // </summary> TableNameAttributeWithQueryView = Value + 64, // <summary> // Empty Query View // </summary> EmptyQueryView = Value + 65, // <summary> // Both Query View and Property Maps specified for EntitySet // </summary> PropertyMapsWithQueryView = Value + 66, // <summary> // Some sets in the graph missing Query Views // </summary> MissingSetClosureInQueryViews = Value + 67, // <summary> // Invalid Query View // </summary> InvalidQueryView = Value + 68, // <summary> // Invalid result type for query view // </summary> InvalidQueryViewResultType = Value + 69, // <summary> // Item with same name exists both in CSpace and SSpace // </summary> ItemWithSameNameExistsBothInCSpaceAndSSpace = Value + 70, // <summary> // Unsupported expression kind in query view // </summary> MappingUnsupportedExpressionKindQueryView = Value + 71, // <summary> // Non S-space target in query view // </summary> MappingUnsupportedScanTargetQueryView = Value + 72, // <summary> // Non structural property referenced in query view // </summary> MappingUnsupportedPropertyKindQueryView = Value + 73, // <summary> // Initialization non-target type in query view // </summary> MappingUnsupportedInitializationQueryView = Value + 74, // <summary> // EntityType mapping for non-entity set function // </summary> MappingFunctionImportEntityTypeMappingForFunctionNotReturningEntitySet = Value + 75, // <summary> // FunctionImport ambiguous type mappings // </summary> MappingFunctionImportAmbiguousTypeConditions = Value + 76, // MappingFunctionMultipleTypeConditionsForOneColumn = Value + 77, // <summary> // Abstract type being mapped explicitly - not supported. // </summary> MappingOfAbstractType = Value + 78, // <summary> // Storage EntityContainer Name mismatch while specifying partial mapping // </summary> StorageEntityContainerNameMismatchWhileSpecifyingPartialMapping = Value + 79, // <summary> // TypeName attribute specified for First QueryView // </summary> TypeNameForFirstQueryView = Value + 80, // <summary> // No TypeName attribute is specified for type-specific QueryViews // </summary> NoTypeNameForTypeSpecificQueryView = Value + 81, // <summary> // Multiple (optype/oftypeonly) QueryViews have been defined for the same EntitySet/EntityType // </summary> QueryViewExistsForEntitySetAndType = Value + 82, // <summary> // TypeName Contains Multiple Types For QueryView // </summary> TypeNameContainsMultipleTypesForQueryView = Value + 83, // <summary> // IsTypeOf QueryView is specified for base type // </summary> IsTypeOfQueryViewForBaseType = Value + 84, // <summary> // ScalarProperty Element contains invalid type // </summary> InvalidTypeInScalarProperty = Value + 85, // <summary> // Already Mapped Storage Container // </summary> AlreadyMappedStorageEntityContainer = Value + 86, // <summary> // No query view is allowed at compile time in EntityContainerMapping // </summary> UnsupportedQueryViewInEntityContainerMapping = Value + 87, // <summary> // EntityContainerMapping only contains query view // </summary> MappingAllQueryViewAtCompileTime = Value + 88, // <summary> // No views can be generated since all of the EntityContainerMapping contain query view // </summary> MappingNoViewsCanBeGenerated = Value + 89, // <summary> // The store provider returns null EdmType for the given targetParameter's type // </summary> MappingStoreProviderReturnsNullEdmType = Value + 90, // MappingFunctionImportInvalidMemberName = Value + 91, // <summary> // Multiple mappings of the same Member or Property inside the same mapping fragment. // </summary> DuplicateMemberMapping = Value + 92, // <summary> // Entity type mapping for a function import that does not return a collection of entity type. // </summary> MappingFunctionImportUnexpectedEntityTypeMapping = Value + 93, // <summary> // Complex type mapping for a function import that does not return a collection of complex type. // </summary> MappingFunctionImportUnexpectedComplexTypeMapping = Value + 94, // <summary> // Distinct flag can only be placed in a container that is not read-write // </summary> DistinctFragmentInReadWriteContainer = Value + 96, // <summary> // The EntitySet used in creating the Ref and the EntitySet declared in AssociationSetEnd do not match // </summary> EntitySetMismatchOnAssociationSetEnd = Value + 97, // <summary> // FKs not permitted for function association ends. // </summary> InvalidModificationFunctionMappingAssociationEndForeignKey = Value + 98, // EdmItemCollectionVersionIncompatible = Value + 98, // StoreItemCollectionVersionIncompatible = Value + 99, // <summary> // Cannot load different version of schemas in the same ItemCollection // </summary> CannotLoadDifferentVersionOfSchemaInTheSameItemCollection = Value + 100, MappingDifferentMappingEdmStoreVersion = Value + 101, MappingDifferentEdmStoreVersion = Value + 102, // <summary> // All function imports must be mapped. // </summary> UnmappedFunctionImport = Value + 103, // <summary> // Invalid function import result mapping: return type property not mapped. // </summary> MappingFunctionImportReturnTypePropertyNotMapped = Value + 104, // AmbiguousFunction = Value + 105, // <summary> // Unresolvable Type Name // </summary> InvalidType = Value + 106, // FunctionResultMappingTypeMismatch = Value + 107, // <summary> // TVF expected on the store side. // </summary> MappingFunctionImportTVFExpected = Value + 108, // <summary> // Collection(Scalar) function import return type is not compatible with the TVF column type. // </summary> MappingFunctionImportScalarMappingTypeMismatch = Value + 109, // <summary> // Collection(Scalar) function import must be mapped to a TVF returning a single column. // </summary> MappingFunctionImportScalarMappingToMulticolumnTVF = Value + 110, // <summary> // Attempting to map composable function import to a non-composable function. // </summary> MappingFunctionImportTargetFunctionMustBeComposable = Value + 111, // <summary> // Non-s-space function call in query view. // </summary> UnsupportedFunctionCallInQueryView = Value + 112, // <summary> // Invalid function result mapping: result mapping count doesn't match result type count. // </summary> FunctionResultMappingCountMismatch = Value + 113, // <summary> // The key properties of all entity types returned by the function import must be mapped to the same non-nullable columns returned by the storage function. // </summary> MappingFunctionImportCannotInferTargetFunctionKeys = Value + 114, } }
35.011152
163
0.622478
[ "MIT" ]
dotnet/ef6tools
src/EntityFramework/Core/Mapping/MappingErrorCode.cs
18,836
C#
// Copyright (c) .NET Foundation. All rights reserved. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Linq.Expressions; using System.Reflection; using Microsoft.EntityFrameworkCore.Diagnostics; using Microsoft.EntityFrameworkCore.Infrastructure; using Microsoft.EntityFrameworkCore.Internal; using Microsoft.EntityFrameworkCore.Metadata; using Microsoft.EntityFrameworkCore.Utilities; using CA = System.Diagnostics.CodeAnalysis; #nullable enable namespace Microsoft.EntityFrameworkCore.Query.Internal { public partial class NavigationExpandingExpressionVisitor { /// <summary> /// Expands navigations in the given tree for given source. /// Optionally also expands navigations for includes. /// </summary> private class ExpandingExpressionVisitor : ExpressionVisitor { private static readonly MethodInfo _objectEqualsMethodInfo = typeof(object).GetRequiredRuntimeMethod(nameof(object.Equals), new[] { typeof(object), typeof(object) }); private readonly NavigationExpandingExpressionVisitor _navigationExpandingExpressionVisitor; private readonly NavigationExpansionExpression _source; public ExpandingExpressionVisitor( NavigationExpandingExpressionVisitor navigationExpandingExpressionVisitor, NavigationExpansionExpression source) { _navigationExpandingExpressionVisitor = navigationExpandingExpressionVisitor; _source = source; Model = navigationExpandingExpressionVisitor._queryCompilationContext.Model; } public Expression Expand(Expression expression, bool applyIncludes = false) { expression = Visit(expression); if (applyIncludes) { expression = new IncludeExpandingExpressionVisitor(_navigationExpandingExpressionVisitor, _source) .Visit(expression); } return expression; } protected IModel Model { get; } protected override Expression VisitExtension(Expression expression) { Check.NotNull(expression, nameof(expression)); switch (expression) { case NavigationExpansionExpression _: case NavigationTreeExpression _: return expression; default: return base.VisitExtension(expression); } } protected override Expression VisitMember(MemberExpression memberExpression) { Check.NotNull(memberExpression, nameof(memberExpression)); var innerExpression = Visit(memberExpression.Expression); return TryExpandNavigation(innerExpression, MemberIdentity.Create(memberExpression.Member)) ?? memberExpression.Update(innerExpression); } protected override Expression VisitMethodCall(MethodCallExpression methodCallExpression) { Check.NotNull(methodCallExpression, nameof(methodCallExpression)); if (methodCallExpression.TryGetEFPropertyArguments(out var source, out var navigationName)) { source = Visit(source); return TryExpandNavigation(source, MemberIdentity.Create(navigationName)) // TODO-Nullable bug ?? methodCallExpression.Update(null!, new[] { source, methodCallExpression.Arguments[1] }); } if (methodCallExpression.TryGetIndexerArguments(Model, out source, out navigationName)) { source = Visit(source); return TryExpandNavigation(source, MemberIdentity.Create(navigationName)) ?? methodCallExpression.Update(source, new[] { methodCallExpression.Arguments[0] }); } return base.VisitMethodCall(methodCallExpression); } private Expression? TryExpandNavigation(Expression? root, MemberIdentity memberIdentity) { if (root == null) { return null; } var innerExpression = root.UnwrapTypeConversion(out var convertedType); if (UnwrapEntityReference(innerExpression) is EntityReference entityReference) { var entityType = entityReference.EntityType; if (convertedType != null) { entityType = entityType.GetAllBaseTypes().Concat(entityType.GetDerivedTypesInclusive()) .FirstOrDefault(et => et.ClrType == convertedType); if (entityType == null) { return null; } } var navigation = memberIdentity.MemberInfo != null ? entityType.FindNavigation(memberIdentity.MemberInfo) : entityType.FindNavigation(memberIdentity.Name!); if (navigation != null) { return ExpandNavigation(root, entityReference, navigation, convertedType != null); } var skipNavigation = memberIdentity.MemberInfo != null ? entityType.FindSkipNavigation(memberIdentity.MemberInfo) : memberIdentity.Name is not null ? entityType.FindSkipNavigation(memberIdentity.Name) : null; if (skipNavigation != null) { return ExpandSkipNavigation(root, entityReference, skipNavigation, convertedType != null); } } return null; } protected Expression ExpandNavigation( Expression root, EntityReference entityReference, INavigation navigation, bool derivedTypeConversion) { var targetType = navigation.TargetEntityType; if (targetType.IsOwned()) { if (entityReference.ForeignKeyExpansionMap.TryGetValue( (navigation.ForeignKey, navigation.IsOnDependent), out var ownedExpansion)) { return ownedExpansion; } var ownedEntityReference = new EntityReference(targetType); _navigationExpandingExpressionVisitor.PopulateEagerLoadedNavigations(ownedEntityReference.IncludePaths); ownedEntityReference.MarkAsOptional(); if (entityReference.IncludePaths.TryGetValue(navigation, out var includePath)) { ownedEntityReference.IncludePaths.Merge(includePath); } ownedExpansion = new OwnedNavigationReference(root, navigation, ownedEntityReference); if (navigation.IsCollection) { var elementType = ownedExpansion.Type.GetSequenceType(); var subquery = Expression.Call( QueryableMethods.AsQueryable.MakeGenericMethod(elementType), ownedExpansion); return new MaterializeCollectionNavigationExpression(subquery, navigation); } entityReference.ForeignKeyExpansionMap[(navigation.ForeignKey, navigation.IsOnDependent)] = ownedExpansion; return ownedExpansion; } var expansion = ExpandForeignKey( root, entityReference, navigation.ForeignKey, navigation.IsOnDependent, derivedTypeConversion); return navigation.IsCollection ? new MaterializeCollectionNavigationExpression(expansion, navigation) : expansion; } protected Expression ExpandSkipNavigation( Expression root, EntityReference entityReference, ISkipNavigation navigation, bool derivedTypeConversion) { var inverseNavigation = navigation.Inverse; var includeTree = entityReference.IncludePaths.TryGetValue(navigation, out var tree) ? tree : null; var primaryExpansion = ExpandForeignKey( root, entityReference, navigation.ForeignKey, navigation.IsOnDependent, derivedTypeConversion); Expression secondaryExpansion; if (navigation.ForeignKey.IsUnique || navigation.IsOnDependent) { // First pseudo-navigation is a reference // ExpandFK handles both collection & reference navigation for second psuedo-navigation // Value known to be non-null secondaryExpansion = ExpandForeignKey( primaryExpansion, UnwrapEntityReference(primaryExpansion)!, inverseNavigation.ForeignKey, !inverseNavigation.IsOnDependent, derivedTypeConversion: false); } else { var secondaryForeignKey = inverseNavigation.ForeignKey; // First psuedo-navigation is a collection if (secondaryForeignKey.IsUnique || !inverseNavigation.IsOnDependent) { // Second psuedo-navigation is a reference var secondTargetType = navigation.TargetEntityType; var innerQueryable = new QueryRootExpression(secondTargetType); var innerSource = (NavigationExpansionExpression)_navigationExpandingExpressionVisitor.Visit(innerQueryable); if (includeTree != null) { // Value known to be non-null UnwrapEntityReference(innerSource.PendingSelector)!.IncludePaths.Merge(includeTree); } var sourceElementType = primaryExpansion.Type.GetSequenceType(); var outerKeyparameter = Expression.Parameter(sourceElementType); var outerKey = outerKeyparameter.CreateKeyValuesExpression( !inverseNavigation.IsOnDependent ? secondaryForeignKey.Properties : secondaryForeignKey.PrincipalKey.Properties, makeNullable: true); var outerKeySelector = Expression.Lambda(outerKey, outerKeyparameter); var innerSourceElementType = innerSource.Type.GetSequenceType(); var innerKeyParameter = Expression.Parameter(innerSourceElementType); var innerKey = innerKeyParameter.CreateKeyValuesExpression( !inverseNavigation.IsOnDependent ? secondaryForeignKey.PrincipalKey.Properties : secondaryForeignKey.Properties, makeNullable: true); var innerKeySelector = Expression.Lambda(innerKey, innerKeyParameter); var resultSelector = Expression.Lambda(innerKeyParameter, outerKeyparameter, innerKeyParameter); var innerJoin = !inverseNavigation.IsOnDependent && secondaryForeignKey.IsRequired; secondaryExpansion = Expression.Call( (innerJoin ? QueryableMethods.Join : QueryableExtensions.LeftJoinMethodInfo).MakeGenericMethod( sourceElementType, innerSourceElementType, outerKeySelector.ReturnType, resultSelector.ReturnType), primaryExpansion, innerSource, Expression.Quote(outerKeySelector), Expression.Quote(innerKeySelector), Expression.Quote(resultSelector)); } else { // Second psuedo-navigation is a collection var secondTargetType = navigation.TargetEntityType; var innerQueryable = new QueryRootExpression(secondTargetType); var innerSource = (NavigationExpansionExpression)_navigationExpandingExpressionVisitor.Visit(innerQueryable); if (includeTree != null) { // Value known to be non-null UnwrapEntityReference(innerSource.PendingSelector)!.IncludePaths.Merge(includeTree); } var sourceElementType = primaryExpansion.Type.GetSequenceType(); var outersourceParameter = Expression.Parameter(sourceElementType); var outerKey = outersourceParameter.CreateKeyValuesExpression( !inverseNavigation.IsOnDependent ? secondaryForeignKey.Properties : secondaryForeignKey.PrincipalKey.Properties, makeNullable: true); var innerSourceElementType = innerSource.Type.GetSequenceType(); var innerSourceParameter = Expression.Parameter(innerSourceElementType); var innerKey = innerSourceParameter.CreateKeyValuesExpression( !inverseNavigation.IsOnDependent ? secondaryForeignKey.PrincipalKey.Properties : secondaryForeignKey.Properties, makeNullable: true); // Selector body is IQueryable, we need to adjust the type to IEnumerable, to match the SelectMany signature // therefore the delegate type is specified explicitly var selectorLambdaType = typeof(Func<,>).MakeGenericType( sourceElementType, typeof(IEnumerable<>).MakeGenericType(innerSourceElementType)); var selector = Expression.Lambda( selectorLambdaType, Expression.Call( QueryableMethods.Where.MakeGenericMethod(innerSourceElementType), innerSource, Expression.Quote(Expression.Lambda(Expression.Equal(outerKey, innerKey), innerSourceParameter))), outersourceParameter); secondaryExpansion = Expression.Call( QueryableMethods.SelectManyWithoutCollectionSelector.MakeGenericMethod( sourceElementType, innerSourceElementType), primaryExpansion, Expression.Quote(selector)); } } return navigation.IsCollection ? new MaterializeCollectionNavigationExpression(secondaryExpansion, navigation) : secondaryExpansion; } private Expression ExpandForeignKey( Expression root, EntityReference entityReference, IForeignKey foreignKey, bool onDependent, bool derivedTypeConversion) { if (entityReference.ForeignKeyExpansionMap.TryGetValue((foreignKey, onDependent), out var expansion)) { return expansion; } var collection = !foreignKey.IsUnique && !onDependent; var targetType = onDependent ? foreignKey.PrincipalEntityType : foreignKey.DeclaringEntityType; Debug.Assert(!targetType.IsOwned(), "Owned entity expanding foreign key."); var innerQueryable = new QueryRootExpression(targetType); var innerSource = (NavigationExpansionExpression)_navigationExpandingExpressionVisitor.Visit(innerQueryable); // We detect and copy over include for navigation being expanded automatically var navigation = onDependent ? foreignKey.DependentToPrincipal : foreignKey.PrincipalToDependent; // Value known to be non-null var innerEntityReference = UnwrapEntityReference(innerSource.PendingSelector)!; if (navigation != null && entityReference.IncludePaths.TryGetValue(navigation, out var includeTree)) { { innerEntityReference.IncludePaths.Merge(includeTree); } } var innerSourceSequenceType = innerSource.Type.GetSequenceType(); var innerParameter = Expression.Parameter(innerSourceSequenceType, "i"); Expression outerKey; if (root is NavigationExpansionExpression innerNavigationExpansionExpression && innerNavigationExpansionExpression.CardinalityReducingGenericMethodInfo != null) { // This is FirstOrDefault ending so we need to push down properties. var temporaryParameter = Expression.Parameter(root.Type); var temporaryKey = temporaryParameter.CreateKeyValuesExpression( onDependent ? foreignKey.Properties : foreignKey.PrincipalKey.Properties, makeNullable: true); var newSelector = ReplacingExpressionVisitor.Replace( temporaryParameter, innerNavigationExpansionExpression.PendingSelector, temporaryKey); innerNavigationExpansionExpression.ApplySelector(newSelector); outerKey = innerNavigationExpansionExpression; } else { outerKey = root.CreateKeyValuesExpression( onDependent ? foreignKey.Properties : foreignKey.PrincipalKey.Properties, makeNullable: true); } var innerKey = innerParameter.CreateKeyValuesExpression( onDependent ? foreignKey.PrincipalKey.Properties : foreignKey.Properties, makeNullable: true); if (outerKey.Type != innerKey.Type) { if (!outerKey.Type.IsNullableType()) { outerKey = Expression.Convert(outerKey, outerKey.Type.MakeNullable()); } if (!innerKey.Type.IsNullableType()) { innerKey = Expression.Convert(innerKey, innerKey.Type.MakeNullable()); } } if (collection) { // This is intentionally deferred to be applied to innerSource.Source // Since outerKey's reference could change if a reference navigation is expanded afterwards var predicateBody = Expression.AndAlso( outerKey is NewArrayExpression newArrayExpression ? newArrayExpression.Expressions .Select( e => { var left = (e as UnaryExpression)?.Operand ?? e; return Expression.NotEqual(left, Expression.Constant(null, left.Type)); }) .Aggregate((l, r) => Expression.AndAlso(l, r)) : Expression.NotEqual(outerKey, Expression.Constant(null, outerKey.Type)), Expression.Call(_objectEqualsMethodInfo, AddConvertToObject(outerKey), AddConvertToObject(innerKey))); // Caller should take care of wrapping MaterializeCollectionNavigation return Expression.Call( QueryableMethods.Where.MakeGenericMethod(innerSourceSequenceType), innerSource, Expression.Quote( Expression.Lambda( predicateBody, innerParameter))); } var outerKeySelector = _navigationExpandingExpressionVisitor.GenerateLambda( outerKey, _source.CurrentParameter); var innerKeySelector = _navigationExpandingExpressionVisitor.ProcessLambdaExpression( innerSource, Expression.Lambda(innerKey, innerParameter)); var resultSelectorOuterParameter = Expression.Parameter(_source.SourceElementType, "o"); var resultSelectorInnerParameter = Expression.Parameter(innerSource.SourceElementType, "i"); var resultType = TransparentIdentifierFactory.Create(_source.SourceElementType, innerSource.SourceElementType); var transparentIdentifierOuterMemberInfo = resultType.GetTypeInfo().GetRequiredDeclaredField("Outer"); var transparentIdentifierInnerMemberInfo = resultType.GetTypeInfo().GetRequiredDeclaredField("Inner"); var resultSelector = Expression.Lambda( Expression.New( resultType.GetConstructors().Single(), new[] { resultSelectorOuterParameter, resultSelectorInnerParameter }, transparentIdentifierOuterMemberInfo, transparentIdentifierInnerMemberInfo), resultSelectorOuterParameter, resultSelectorInnerParameter); var innerJoin = !entityReference.IsOptional && !derivedTypeConversion && onDependent && foreignKey.IsRequired; if (!innerJoin) { innerEntityReference.MarkAsOptional(); } _source.UpdateSource( Expression.Call( (innerJoin ? QueryableMethods.Join : QueryableExtensions.LeftJoinMethodInfo).MakeGenericMethod( _source.SourceElementType, innerSource.SourceElementType, outerKeySelector.ReturnType, resultSelector.ReturnType), _source.Source, innerSource.Source, Expression.Quote(outerKeySelector), Expression.Quote(innerKeySelector), Expression.Quote(resultSelector))); entityReference.ForeignKeyExpansionMap[(foreignKey, onDependent)] = innerSource.PendingSelector; _source.UpdateCurrentTree(new NavigationTreeNode(_source.CurrentTree, innerSource.CurrentTree)); return innerSource.PendingSelector; } private static Expression AddConvertToObject(Expression expression) => expression.Type.IsValueType ? Expression.Convert(expression, typeof(object)) : expression; } /// <summary> /// Expands an include tree. This is separate and needed because we may need to reconstruct parts of /// <see cref="NewExpression" /> to apply includes. /// </summary> private sealed class IncludeExpandingExpressionVisitor : ExpandingExpressionVisitor { private static readonly MethodInfo _fetchJoinEntityMethodInfo = typeof(IncludeExpandingExpressionVisitor).GetRequiredDeclaredMethod(nameof(FetchJoinEntity)); private readonly bool _queryStateManager; private readonly bool _ignoreAutoIncludes; private readonly IDiagnosticsLogger<DbLoggerCategory.Query> _logger; public IncludeExpandingExpressionVisitor( NavigationExpandingExpressionVisitor navigationExpandingExpressionVisitor, NavigationExpansionExpression source) : base(navigationExpandingExpressionVisitor, source) { _logger = navigationExpandingExpressionVisitor._queryCompilationContext.Logger; _queryStateManager = navigationExpandingExpressionVisitor._queryCompilationContext.QueryTrackingBehavior == QueryTrackingBehavior.TrackAll || navigationExpandingExpressionVisitor._queryCompilationContext.QueryTrackingBehavior == QueryTrackingBehavior.NoTrackingWithIdentityResolution; _ignoreAutoIncludes = navigationExpandingExpressionVisitor._queryCompilationContext.IgnoreAutoIncludes; } protected override Expression VisitExtension(Expression extensionExpression) { Check.NotNull(extensionExpression, nameof(extensionExpression)); switch (extensionExpression) { case NavigationTreeExpression navigationTreeExpression: if (navigationTreeExpression.Value is EntityReference entityReference) { return ExpandInclude(navigationTreeExpression, entityReference); } if (navigationTreeExpression.Value is NewExpression newExpression) { if (ReconstructAnonymousType(navigationTreeExpression, newExpression, out var replacement)) { return replacement; } } break; case OwnedNavigationReference ownedNavigationReference: return ExpandInclude(ownedNavigationReference, ownedNavigationReference.EntityReference); case MaterializeCollectionNavigationExpression _: return extensionExpression; } return base.VisitExtension(extensionExpression); } protected override Expression VisitMember(MemberExpression memberExpression) { Check.NotNull(memberExpression, nameof(memberExpression)); if (memberExpression.Expression != null) { var innerExpression = memberExpression.Expression.UnwrapTypeConversion(out var convertedType); if (UnwrapEntityReference(innerExpression) is EntityReference entityReference) { // If it is mapped property then, it would get converted to a column so we don't need to expand includes. var entityType = entityReference.EntityType; if (convertedType != null) { entityType = entityType.GetAllBaseTypes().Concat(entityType.GetDerivedTypesInclusive()) .FirstOrDefault(et => et.ClrType == convertedType); if (entityType == null) { return base.VisitMember(memberExpression); } } var property = entityType.FindProperty(memberExpression.Member); if (property != null) { return memberExpression; } } } return base.VisitMember(memberExpression); } protected override Expression VisitMethodCall(MethodCallExpression methodCallExpression) { Check.NotNull(methodCallExpression, nameof(methodCallExpression)); if (methodCallExpression.TryGetEFPropertyArguments(out _, out _)) { // If it is EF.Property then, it would get converted to a column or throw // so we don't need to expand includes. return methodCallExpression; } if (methodCallExpression.TryGetIndexerArguments(Model, out var source, out var propertyName)) { if (UnwrapEntityReference(source) is EntityReference entityReferece) { // If it is mapped property then, it would get converted to a column so we don't need to expand includes. var property = entityReferece.EntityType.FindProperty(propertyName); if (property != null) { return methodCallExpression; } } } return base.VisitMethodCall(methodCallExpression); } protected override Expression VisitNew(NewExpression newExpression) { Check.NotNull(newExpression, nameof(newExpression)); var arguments = new Expression[newExpression.Arguments.Count]; for (var i = 0; i < newExpression.Arguments.Count; i++) { var argument = newExpression.Arguments[i]; arguments[i] = argument is EntityReference entityReference ? ExpandInclude(argument, entityReference) : Visit(argument); } return newExpression.Update(arguments); } private bool ReconstructAnonymousType( Expression currentRoot, NewExpression newExpression, [CA.NotNullWhen(true)] out Expression? replacement) { replacement = null; var changed = false; if (newExpression.Arguments.Count > 0 && newExpression.Members == null) { return changed; } var arguments = new Expression[newExpression.Arguments.Count]; for (var i = 0; i < newExpression.Arguments.Count; i++) { var argument = newExpression.Arguments[i]; var newRoot = Expression.MakeMemberAccess(currentRoot, newExpression.Members![i]); if (argument is EntityReference entityReference) { changed = true; arguments[i] = ExpandInclude(newRoot, entityReference); } else if (argument is NewExpression innerNewExpression) { if (ReconstructAnonymousType(newRoot, innerNewExpression, out var innerReplacement)) { changed = true; arguments[i] = innerReplacement; } else { arguments[i] = newRoot; } } else { arguments[i] = newRoot; } } if (changed) { replacement = newExpression.Update(arguments); } return changed; } private Expression ExpandInclude(Expression root, EntityReference entityReference) { if (!_queryStateManager) { VerifyNoCycles(entityReference.IncludePaths); } return ExpandIncludesHelper(root, entityReference, previousNavigation: null); } private void VerifyNoCycles(IncludeTreeNode includeTreeNode) { foreach (var keyValuePair in includeTreeNode) { var navigation = keyValuePair.Key; var referenceIncludeTreeNode = keyValuePair.Value; var inverseNavigation = navigation.Inverse; if (inverseNavigation != null && referenceIncludeTreeNode.ContainsKey(inverseNavigation)) { throw new InvalidOperationException(CoreStrings.IncludeWithCycle(navigation.Name, inverseNavigation.Name)); } VerifyNoCycles(referenceIncludeTreeNode); } } private Expression ExpandIncludesHelper(Expression root, EntityReference entityReference, INavigationBase? previousNavigation) { var result = root; var convertedRoot = root; foreach (var kvp in entityReference.IncludePaths) { var navigationBase = kvp.Key; if (!navigationBase.IsCollection && previousNavigation?.Inverse == navigationBase) { continue; } var converted = false; if (entityReference.EntityType != navigationBase.DeclaringEntityType && entityReference.EntityType.IsAssignableFrom(navigationBase.DeclaringEntityType)) { converted = true; convertedRoot = Expression.Convert(root, navigationBase.DeclaringEntityType.ClrType!); } var included = navigationBase switch { INavigation navigation => ExpandNavigation(convertedRoot, entityReference, navigation, converted), ISkipNavigation skipNavigation => ExpandSkipNavigation(convertedRoot, entityReference, skipNavigation, converted), _ => throw new InvalidOperationException(CoreStrings.UnhandledNavigationBase(navigationBase.GetType())), }; _logger.NavigationBaseIncluded(navigationBase); // Collection will expand it's includes when reducing the navigationExpansionExpression if (!navigationBase.IsCollection) { // Value known to be non-null included = ExpandIncludesHelper(included, UnwrapEntityReference(included)!, navigationBase); } else { var materializeCollectionNavigation = (MaterializeCollectionNavigationExpression)included; var subquery = materializeCollectionNavigation.Subquery; if (!_ignoreAutoIncludes && navigationBase is INavigation && navigationBase.Inverse != null && subquery is MethodCallExpression subqueryMethodCallExpression && subqueryMethodCallExpression.Method.IsGenericMethod) { EntityReference? innerEntityReference = null; if (subqueryMethodCallExpression.Method.GetGenericMethodDefinition() == QueryableMethods.Where && subqueryMethodCallExpression.Arguments[0] is NavigationExpansionExpression navigationExpansionExpression) { innerEntityReference = UnwrapEntityReference(navigationExpansionExpression.CurrentTree); } else if (subqueryMethodCallExpression.Method.GetGenericMethodDefinition() == QueryableMethods.AsQueryable) { innerEntityReference = UnwrapEntityReference(subqueryMethodCallExpression.Arguments[0]); } if (innerEntityReference != null) { innerEntityReference.IncludePaths.Remove(navigationBase.Inverse); } } var filterExpression = entityReference.IncludePaths[navigationBase].FilterExpression; if (_queryStateManager && navigationBase is ISkipNavigation && subquery is MethodCallExpression joinMethodCallExpression && joinMethodCallExpression.Method.IsGenericMethod && joinMethodCallExpression.Method.GetGenericMethodDefinition() == QueryableMethods.Join && joinMethodCallExpression.Arguments[4] is UnaryExpression unaryExpression && unaryExpression.NodeType == ExpressionType.Quote && unaryExpression.Operand is LambdaExpression resultSelectorLambda && resultSelectorLambda.Body == resultSelectorLambda.Parameters[1]) { var joinParameter = resultSelectorLambda.Parameters[0]; var targetParameter = resultSelectorLambda.Parameters[1]; if (filterExpression == null) { var newResultSelector = Expression.Quote( Expression.Lambda( Expression.Call( _fetchJoinEntityMethodInfo.MakeGenericMethod(joinParameter.Type, targetParameter.Type), joinParameter, targetParameter), joinParameter, targetParameter)); subquery = joinMethodCallExpression.Update( // TODO-Nullable bug null!, joinMethodCallExpression.Arguments.Take(4).Append(newResultSelector)); } else { var resultType = TransparentIdentifierFactory.Create(joinParameter.Type, targetParameter.Type); var transparentIdentifierOuterMemberInfo = resultType.GetTypeInfo().GetRequiredDeclaredField("Outer"); var transparentIdentifierInnerMemberInfo = resultType.GetTypeInfo().GetRequiredDeclaredField("Inner"); var newResultSelector = Expression.Quote( Expression.Lambda( Expression.New( resultType.GetConstructors().Single(), new[] { joinParameter, targetParameter }, transparentIdentifierOuterMemberInfo, transparentIdentifierInnerMemberInfo), joinParameter, targetParameter)); var joinTypeParameters = joinMethodCallExpression.Method.GetGenericArguments(); joinTypeParameters[3] = resultType; subquery = Expression.Call( QueryableMethods.Join.MakeGenericMethod(joinTypeParameters), joinMethodCallExpression.Arguments.Take(4).Append(newResultSelector)); var transparentIdentifierParameter = Expression.Parameter(resultType); var transparentIdentifierInnerAccessor = Expression.MakeMemberAccess( transparentIdentifierParameter, transparentIdentifierInnerMemberInfo); subquery = RemapFilterExpressionForJoinEntity( filterExpression.Parameters[0], filterExpression.Body, subquery, transparentIdentifierParameter, transparentIdentifierInnerAccessor); var selector = Expression.Quote( Expression.Lambda( Expression.Call( _fetchJoinEntityMethodInfo.MakeGenericMethod(joinParameter.Type, targetParameter.Type), Expression.MakeMemberAccess( transparentIdentifierParameter, transparentIdentifierOuterMemberInfo), transparentIdentifierInnerAccessor), transparentIdentifierParameter)); subquery = Expression.Call( QueryableMethods.Select.MakeGenericMethod(resultType, targetParameter.Type), subquery, selector); } included = materializeCollectionNavigation.Update(subquery); } else if (filterExpression != null) { subquery = ReplacingExpressionVisitor.Replace(filterExpression.Parameters[0], subquery, filterExpression.Body); included = materializeCollectionNavigation.Update(subquery); } } #pragma warning disable EF1001 // Internal EF Core API usage. result = new IncludeExpression(result, included, navigationBase, kvp.Value.SetLoaded); #pragma warning restore EF1001 // Internal EF Core API usage. } return result; } #pragma warning disable IDE0060 // Remove unused parameter private static TTarget FetchJoinEntity<TJoin, TTarget>(TJoin joinEntity, TTarget targetEntity) => targetEntity; #pragma warning restore IDE0060 // Remove unused parameter private static Expression RemapFilterExpressionForJoinEntity( ParameterExpression filterParameter, Expression filterExpressionBody, Expression subquery, ParameterExpression transparentIdentifierParameter, Expression transparentIdentifierInnerAccessor) { if (filterExpressionBody == filterParameter) { return subquery; } var methodCallExpression = (MethodCallExpression)filterExpressionBody; var arguments = methodCallExpression.Arguments.ToArray(); arguments[0] = RemapFilterExpressionForJoinEntity( filterParameter, arguments[0], subquery, transparentIdentifierParameter, transparentIdentifierInnerAccessor); var genericParameters = methodCallExpression.Method.GetGenericArguments(); genericParameters[0] = transparentIdentifierParameter.Type; var method = methodCallExpression.Method.GetGenericMethodDefinition().MakeGenericMethod(genericParameters); if (arguments.Length == 2 && arguments[1].GetLambdaOrNull() is LambdaExpression lambdaExpression) { arguments[1] = Expression.Quote( Expression.Lambda( ReplacingExpressionVisitor.Replace( lambdaExpression.Parameters[0], transparentIdentifierInnerAccessor, lambdaExpression.Body), transparentIdentifierParameter)); } return Expression.Call(method, arguments); } } /// <summary> /// <see cref="NavigationExpansionExpression" /> remembers the pending selector so we don't expand /// navigations unless we need to. This visitor applies them when we need to. /// </summary> private sealed class PendingSelectorExpandingExpressionVisitor : ExpressionVisitor { private readonly NavigationExpandingExpressionVisitor _visitor; private readonly bool _applyIncludes; public PendingSelectorExpandingExpressionVisitor( NavigationExpandingExpressionVisitor visitor, bool applyIncludes = false) { _visitor = visitor; _applyIncludes = applyIncludes; } [return: CA.NotNullIfNotNull("expression")] public override Expression? Visit(Expression? expression) { if (expression is NavigationExpansionExpression navigationExpansionExpression) { _visitor.ApplyPendingOrderings(navigationExpansionExpression); var pendingSelector = new ExpandingExpressionVisitor(_visitor, navigationExpansionExpression) .Expand(navigationExpansionExpression.PendingSelector, _applyIncludes); pendingSelector = _visitor._subqueryMemberPushdownExpressionVisitor.Visit(pendingSelector); pendingSelector = _visitor.Visit(pendingSelector); pendingSelector = Visit(pendingSelector); navigationExpansionExpression.ApplySelector(pendingSelector); return navigationExpansionExpression; } return base.Visit(expression); } } /// <summary> /// Removes custom expressions from tree and converts it to LINQ again. /// </summary> private sealed class ReducingExpressionVisitor : ExpressionVisitor { [return: CA.NotNullIfNotNull("expression")] public override Expression? Visit(Expression? expression) { switch (expression) { case NavigationTreeExpression navigationTreeExpression: return navigationTreeExpression.GetExpression(); case NavigationExpansionExpression navigationExpansionExpression: { var pendingSelector = Visit(navigationExpansionExpression.PendingSelector); Expression result; var source = Visit(navigationExpansionExpression.Source); if (pendingSelector == navigationExpansionExpression.CurrentParameter) { // identity projection result = source; } else { var selectorLambda = Expression.Lambda(pendingSelector, navigationExpansionExpression.CurrentParameter); result = Expression.Call( QueryableMethods.Select.MakeGenericMethod( navigationExpansionExpression.SourceElementType, selectorLambda.ReturnType), source, Expression.Quote(selectorLambda)); } if (navigationExpansionExpression.CardinalityReducingGenericMethodInfo != null) { result = Expression.Call( navigationExpansionExpression.CardinalityReducingGenericMethodInfo.MakeGenericMethod( result.Type.GetSequenceType()), result); } return result; } case OwnedNavigationReference ownedNavigationReference: return Visit(ownedNavigationReference.Parent).CreateEFPropertyExpression(ownedNavigationReference.Navigation); case IncludeExpression includeExpression: var entityExpression = Visit(includeExpression.EntityExpression); var navigationExpression = ReplacingExpressionVisitor.Replace( includeExpression.EntityExpression, entityExpression, includeExpression.NavigationExpression); navigationExpression = Visit(navigationExpression); return includeExpression.Update(entityExpression, navigationExpression); default: return base.Visit(expression); } } } /// <summary> /// Marks <see cref="EntityReference" /> as nullable when coming from a left join. /// Nullability is required to figure out if the navigation from this entity should be a left join or /// an inner join. /// </summary> private sealed class EntityReferenceOptionalMarkingExpressionVisitor : ExpressionVisitor { [return: CA.NotNullIfNotNull("expression")] public override Expression? Visit(Expression? expression) { if (expression is EntityReference entityReference) { entityReference.MarkAsOptional(); return entityReference; } return base.Visit(expression); } } /// <summary> /// Allows self reference of query root inside query filters/defining queries. /// </summary> private sealed class SelfReferenceEntityQueryableRewritingExpressionVisitor : ExpressionVisitor { private readonly NavigationExpandingExpressionVisitor _navigationExpandingExpressionVisitor; private readonly IEntityType _entityType; public SelfReferenceEntityQueryableRewritingExpressionVisitor( NavigationExpandingExpressionVisitor navigationExpandingExpressionVisitor, IEntityType entityType) { _navigationExpandingExpressionVisitor = navigationExpandingExpressionVisitor; _entityType = entityType; } protected override Expression VisitExtension(Expression extensionExpression) { Check.NotNull(extensionExpression, nameof(extensionExpression)); return extensionExpression is QueryRootExpression queryRootExpression && queryRootExpression.EntityType == _entityType ? _navigationExpandingExpressionVisitor.CreateNavigationExpansionExpression(queryRootExpression, _entityType) : base.VisitExtension(extensionExpression); } } private sealed class RemoveRedundantNavigationComparisonExpressionVisitor : ExpressionVisitor { private readonly IDiagnosticsLogger<DbLoggerCategory.Query> _logger; public RemoveRedundantNavigationComparisonExpressionVisitor(IDiagnosticsLogger<DbLoggerCategory.Query> logger) { _logger = logger; } protected override Expression VisitBinary(BinaryExpression binaryExpression) => (binaryExpression.NodeType == ExpressionType.Equal || binaryExpression.NodeType == ExpressionType.NotEqual) && TryRemoveNavigationComparison( binaryExpression.NodeType, binaryExpression.Left, binaryExpression.Right, out var result) ? result : base.VisitBinary(binaryExpression); protected override Expression VisitMethodCall(MethodCallExpression methodCallExpression) { var method = methodCallExpression.Method; if (method.Name == nameof(object.Equals) && methodCallExpression.Object != null && methodCallExpression.Arguments.Count == 1 && TryRemoveNavigationComparison( ExpressionType.Equal, methodCallExpression.Object, methodCallExpression.Arguments[0], out var result)) { return result; } if (method.Name == nameof(object.Equals) && methodCallExpression.Object == null && methodCallExpression.Arguments.Count == 2 && TryRemoveNavigationComparison( ExpressionType.Equal, methodCallExpression.Arguments[0], methodCallExpression.Arguments[1], out result)) { return result; } return base.VisitMethodCall(methodCallExpression); } private bool TryRemoveNavigationComparison( ExpressionType nodeType, Expression left, Expression right, [CA.NotNullWhen(true)] out Expression? result) { result = null; var leftNavigationData = ProcessNavigationPath(left) as NavigationDataExpression; var rightNavigationData = ProcessNavigationPath(right) as NavigationDataExpression; if (leftNavigationData == null && rightNavigationData == null) { return false; } if (left.IsNullConstantExpression() || right.IsNullConstantExpression()) { NavigationDataExpression nonNullNavigationData = left.IsNullConstantExpression() ? rightNavigationData! : leftNavigationData!; if (nonNullNavigationData.Navigation?.IsCollection == true) { _logger.PossibleUnintendedCollectionNavigationNullComparisonWarning(nonNullNavigationData.Navigation); // Inner would be non-null when navigation is non-null result = Expression.MakeBinary( nodeType, nonNullNavigationData.Inner!.Current, Expression.Constant(null, nonNullNavigationData.Inner.Type)); return true; } } else if (leftNavigationData != null && rightNavigationData != null) { if (leftNavigationData.Navigation?.IsCollection == true) { if (leftNavigationData.Navigation == rightNavigationData.Navigation) { _logger.PossibleUnintendedReferenceComparisonWarning(leftNavigationData.Current, rightNavigationData.Current); // Inner would be non-null when navigation is non-null result = Expression.MakeBinary(nodeType, leftNavigationData.Inner!.Current, rightNavigationData.Inner!.Current); } else { result = Expression.Constant(nodeType == ExpressionType.NotEqual); } return true; } } return false; } private Expression ProcessNavigationPath(Expression expression) { switch (expression) { case MemberExpression memberExpression when memberExpression.Expression != null: var innerExpression = ProcessNavigationPath(memberExpression.Expression); if (innerExpression is NavigationDataExpression navigationDataExpression && navigationDataExpression.EntityType != null) { var navigation = navigationDataExpression.EntityType.FindNavigation(memberExpression.Member); if (navigation != null) { return new NavigationDataExpression(expression, navigationDataExpression, navigation); } } return expression; case MethodCallExpression methodCallExpression when methodCallExpression.TryGetEFPropertyArguments(out var source, out var navigationName): return expression; default: var convertlessExpression = expression.UnwrapTypeConversion(out var convertedType); if (UnwrapEntityReference(convertlessExpression) is EntityReference entityReference) { var entityType = entityReference.EntityType; if (convertedType != null) { entityType = entityType.GetAllBaseTypes().Concat(entityType.GetDerivedTypesInclusive()) .FirstOrDefault(et => et.ClrType == convertedType); if (entityType == null) { return expression; } } return new NavigationDataExpression(expression, entityType); } return expression; } } private sealed class NavigationDataExpression : Expression { public NavigationDataExpression(Expression current, IEntityType entityType) { Navigation = default; Current = current; EntityType = entityType; } public NavigationDataExpression(Expression current, NavigationDataExpression inner, INavigation navigation) { Current = current; Inner = inner; Navigation = navigation; if (!navigation.IsCollection) { EntityType = navigation.TargetEntityType; } } public override Type Type => Current.Type; public override ExpressionType NodeType => ExpressionType.Extension; public INavigation? Navigation { get; } public Expression Current { get; } public NavigationDataExpression? Inner { get; } public IEntityType? EntityType { get; } } } } }
49.632653
140
0.540855
[ "Apache-2.0" ]
FriendsTmCo/efcore
src/EFCore/Query/Internal/NavigationExpandingExpressionVisitor.ExpressionVisitors.cs
60,800
C#
using JT808.Protocol.Enums; using JT808.Protocol.Extensions; using JT808.Protocol.Formatters; using JT808.Protocol.Interfaces; using JT808.Protocol.MessagePack; using System; using System.Buffers.Binary; using System.Collections.Generic; using System.Text; using System.Text.Json; namespace JT808.Protocol.MessageBody.CarDVR { /// <summary> /// 采集指定的参数修改记录 /// 返回:符合条件的参数修改记录 /// </summary> public class JT808_CarDVR_Up_0x14 : JT808CarDVRUpBodies, IJT808MessagePackFormatter<JT808_CarDVR_Up_0x14>, IJT808Analyze { /// <summary> /// 0x14 /// </summary> public override byte CommandId => JT808CarDVRCommandID.采集指定的参数修改记录.ToByteValue(); /// <summary> /// 请求发送指定的时间范围内 N 个单位数据块的数据(N≥1) /// </summary> public List<JT808_CarDVR_Up_0x14_ParameterModify> JT808_CarDVR_Up_0x14_ParameterModifys { get; set; } /// <summary> /// 符合条件的参数修改记录 /// </summary> public override string Description => "符合条件的参数修改记录"; /// <summary> /// /// </summary> /// <param name="reader"></param> /// <param name="writer"></param> /// <param name="config"></param> public void Analyze(ref JT808MessagePackReader reader, Utf8JsonWriter writer, IJT808Config config) { writer.WriteStartArray("请求发送指定的时间范围内 N 个单位数据块的数据"); var count = (reader.ReadCurrentRemainContentLength() - 1) / 7;//记录块个数, -1 去掉校验位 for (int i = 0; i < count; i++) { JT808_CarDVR_Up_0x14_ParameterModify jT808_CarDVR_Up_0x14_ParameterModify = new JT808_CarDVR_Up_0x14_ParameterModify(); writer.WriteStartObject(); writer.WriteStartObject($"指定的结束时间之前最近的第{i+1}条参数修改记录"); var hex = reader.ReadVirtualArray(6); jT808_CarDVR_Up_0x14_ParameterModify.EventTime = reader.ReadDateTime_yyMMddHHmmss(); writer.WriteString($"[{hex.ToArray().ToHexString()}]事件发生时间", jT808_CarDVR_Up_0x14_ParameterModify.EventTime); jT808_CarDVR_Up_0x14_ParameterModify.EventType = reader.ReadByte(); writer.WriteString($"[{ jT808_CarDVR_Up_0x14_ParameterModify.EventType.ReadNumber()}]事件类型", ((JT808CarDVRCommandID)jT808_CarDVR_Up_0x14_ParameterModify.EventType).ToString()); writer.WriteEndObject(); writer.WriteEndObject(); } writer.WriteEndArray(); } /// <summary> /// /// </summary> /// <param name="writer"></param> /// <param name="value"></param> /// <param name="config"></param> public void Serialize(ref JT808MessagePackWriter writer, JT808_CarDVR_Up_0x14 value, IJT808Config config) { foreach (var parameterModify in value.JT808_CarDVR_Up_0x14_ParameterModifys) { writer.WriteDateTime_yyMMddHHmmss(parameterModify.EventTime); writer.WriteByte(parameterModify.EventType); } } /// <summary> /// /// </summary> /// <param name="reader"></param> /// <param name="config"></param> /// <returns></returns> public JT808_CarDVR_Up_0x14 Deserialize(ref JT808MessagePackReader reader, IJT808Config config) { JT808_CarDVR_Up_0x14 value = new JT808_CarDVR_Up_0x14(); value.JT808_CarDVR_Up_0x14_ParameterModifys = new List<JT808_CarDVR_Up_0x14_ParameterModify>(); var count = (reader.ReadCurrentRemainContentLength() - 1) / 7;//记录块个数, -1 去掉校验位 for (int i = 0; i < count; i++) { JT808_CarDVR_Up_0x14_ParameterModify jT808_CarDVR_Up_0x14_ParameterModify = new JT808_CarDVR_Up_0x14_ParameterModify(); jT808_CarDVR_Up_0x14_ParameterModify.EventTime = reader.ReadDateTime_yyMMddHHmmss(); jT808_CarDVR_Up_0x14_ParameterModify.EventType = reader.ReadByte(); value.JT808_CarDVR_Up_0x14_ParameterModifys.Add(jT808_CarDVR_Up_0x14_ParameterModify); } return value; } } /// <summary> /// 单位参数修改记录数据块格式 /// </summary> public class JT808_CarDVR_Up_0x14_ParameterModify { /// <summary> /// 事件发生时间 /// </summary> public DateTime EventTime { get; set; } /// <summary> /// 事件类型 /// </summary> public byte EventType { get; set; } } }
42.046729
192
0.623916
[ "MIT" ]
DonPangPang/JT808
src/JT808.Protocol/MessageBody/CarDVR/JT808_CarDVR_Up_0x14.cs
4,853
C#
using System; using System.Collections.Generic; using System.IO; using System.Net; using MiscUtil.Conversion; namespace BitTorent { public enum TrackerEvent { Started, Paused, Stopped } public class Tracker { public event EventHandler<List<IPEndPoint>> PeerListUpdated; public string Address { get; private set; } private DateTime LastPeerRequest { get; set; } = DateTime.MinValue; private TimeSpan PeerRequestInterval { get; set; } = TimeSpan.FromMinutes(30); private HttpWebRequest _httpWebRequest; public Tracker(string address) { Address = address; } #region Announcing public void Update(Torrent torrent, TrackerEvent ev, string id, int port) { // wait until after request interval has elapsed before asking for new peers if (ev == TrackerEvent.Started && DateTime.UtcNow < LastPeerRequest.Add(PeerRequestInterval)) return; LastPeerRequest = DateTime.UtcNow; string url = $"{Address}?info_hash={torrent.UrlSafeStringInfohash}&peer_id={id}&port={port}&uploaded={torrent.Uploaded}&downloaded={torrent.Downloaded}&left={torrent.Left}&event={Enum.GetName(typeof(TrackerEvent), ev)?.ToLower()}&compact=1"; Request(url); } private void Request( string url ) { _httpWebRequest = (HttpWebRequest)WebRequest.Create(url); _httpWebRequest.BeginGetResponse(HandleResponse, null); } private void HandleResponse(IAsyncResult result) { byte[] data; using (HttpWebResponse response = (HttpWebResponse)_httpWebRequest.EndGetResponse(result)) { if (response.StatusCode != HttpStatusCode.OK) { Console.WriteLine("error reaching tracker " + this + ": " + response.StatusCode + " " + response.StatusDescription); return; } using (Stream stream = response.GetResponseStream()) { data = new byte[response.ContentLength]; stream?.Read(data, 0, Convert.ToInt32(response.ContentLength)); } } Dictionary<string,object> info = BenCoding.Decode(data) as Dictionary<string,object>; if (info == null) { Console.WriteLine("unable to decode tracker announce response"); return; } PeerRequestInterval = TimeSpan.FromSeconds((long)info["interval"]); byte[] peerInfo = (byte[])info["peers"]; List<IPEndPoint> peers = new List<IPEndPoint>(); for (int i = 0; i < peerInfo.Length/6; i++) { int offset = i * 6; string address = peerInfo[offset] + "." + peerInfo[offset+1] + "." + peerInfo[offset+2] + "." + peerInfo[offset+3]; int port = EndianBitConverter.Big.ToChar(peerInfo, offset + 4); peers.Add(new IPEndPoint(IPAddress.Parse(address), port)); } var handler = PeerListUpdated; handler?.Invoke(this, peers); } public void ResetLastRequest() { LastPeerRequest = DateTime.MinValue; } #endregion #region Helper public override string ToString() { return $"[Tracker: {Address}]"; } #endregion } }
31.649123
244
0.560698
[ "MIT" ]
LightOstrich/bittorent-research
Torrent/ConsoleApp1/BitTorrent/Tracker.cs
3,608
C#
using System.Reflection; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("ConsoleApplication2")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("ConsoleApplication2")] [assembly: AssemblyCopyright("Copyright © 2017")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("958655f8-c87c-4107-81a9-a14a80a5c571")] // 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")]
35.25641
84
0.742545
[ "Apache-2.0" ]
GallantChar/minecraft-worldedit-bedrock
src/WorldEdit/Properties/AssemblyInfo.cs
1,378
C#
// Copyright © Tanner Gooding and Contributors. Licensed under the MIT License (MIT). See License.md in the repository root for more information. // Ported from um/d2d1_1.h in the Windows SDK for Windows 10.0.19041.0 // Original source is Copyright © Microsoft. All rights reserved. using System; using System.Runtime.InteropServices; namespace TerraFX.Interop { public static unsafe partial class Windows { [DllImport("d2d1", ExactSpelling = true)] [return: NativeTypeName("HRESULT")] public static extern int D2D1CreateDevice([NativeTypeName("IDXGIDevice *")] IDXGIDevice* dxgiDevice, [NativeTypeName("const D2D1_CREATION_PROPERTIES *")] D2D1_CREATION_PROPERTIES* creationProperties, [NativeTypeName("ID2D1Device **")] ID2D1Device** d2dDevice); [DllImport("d2d1", ExactSpelling = true)] [return: NativeTypeName("HRESULT")] public static extern int D2D1CreateDeviceContext([NativeTypeName("IDXGISurface *")] IDXGISurface* dxgiSurface, [NativeTypeName("const D2D1_CREATION_PROPERTIES *")] D2D1_CREATION_PROPERTIES* creationProperties, [NativeTypeName("ID2D1DeviceContext **")] ID2D1DeviceContext** d2dDeviceContext); [DllImport("d2d1", ExactSpelling = true)] [return: NativeTypeName("D2D1_COLOR_F")] public static extern DXGI_RGBA D2D1ConvertColorSpace(D2D1_COLOR_SPACE sourceColorSpace, D2D1_COLOR_SPACE destinationColorSpace, [NativeTypeName("const D2D1_COLOR_F *")] DXGI_RGBA* color); [DllImport("d2d1", ExactSpelling = true)] public static extern void D2D1SinCos([NativeTypeName("FLOAT")] float angle, [NativeTypeName("FLOAT *")] float* s, [NativeTypeName("FLOAT *")] float* c); [DllImport("d2d1", ExactSpelling = true)] [return: NativeTypeName("FLOAT")] public static extern float D2D1Tan([NativeTypeName("FLOAT")] float angle); [DllImport("d2d1", ExactSpelling = true)] [return: NativeTypeName("FLOAT")] public static extern float D2D1Vec3Length([NativeTypeName("FLOAT")] float x, [NativeTypeName("FLOAT")] float y, [NativeTypeName("FLOAT")] float z); [NativeTypeName("#define D2D1_INVALID_PROPERTY_INDEX UINT_MAX")] public const uint D2D1_INVALID_PROPERTY_INDEX = 0xffffffff; public static readonly Guid IID_ID2D1GdiMetafileSink = new Guid(0x82237326, 0x8111, 0x4F7C, 0xBC, 0xF4, 0xB5, 0xC1, 0x17, 0x55, 0x64, 0xFE); public static readonly Guid IID_ID2D1GdiMetafile = new Guid(0x2F543DC3, 0xCFC1, 0x4211, 0x86, 0x4F, 0xCF, 0xD9, 0x1C, 0x6F, 0x33, 0x95); public static readonly Guid IID_ID2D1CommandSink = new Guid(0x54D7898A, 0xA061, 0x40A7, 0xBE, 0xC7, 0xE4, 0x65, 0xBC, 0xBA, 0x2C, 0x4F); public static readonly Guid IID_ID2D1CommandList = new Guid(0xB4F34A19, 0x2383, 0x4D76, 0x94, 0xF6, 0xEC, 0x34, 0x36, 0x57, 0xC3, 0xDC); public static readonly Guid IID_ID2D1PrintControl = new Guid(0x2C1D867D, 0xC290, 0x41C8, 0xAE, 0x7E, 0x34, 0xA9, 0x87, 0x02, 0xE9, 0xA5); public static readonly Guid IID_ID2D1ImageBrush = new Guid(0xFE9E984D, 0x3F95, 0x407C, 0xB5, 0xDB, 0xCB, 0x94, 0xD4, 0xE8, 0xF8, 0x7C); public static readonly Guid IID_ID2D1BitmapBrush1 = new Guid(0x41343A53, 0xE41A, 0x49A2, 0x91, 0xCD, 0x21, 0x79, 0x3B, 0xBB, 0x62, 0xE5); public static readonly Guid IID_ID2D1StrokeStyle1 = new Guid(0x10A72A66, 0xE91C, 0x43F4, 0x99, 0x3F, 0xDD, 0xF4, 0xB8, 0x2B, 0x0B, 0x4A); public static readonly Guid IID_ID2D1PathGeometry1 = new Guid(0x62BAA2D2, 0xAB54, 0x41B7, 0xB8, 0x72, 0x78, 0x7E, 0x01, 0x06, 0xA4, 0x21); public static readonly Guid IID_ID2D1Properties = new Guid(0x483473D7, 0xCD46, 0x4F9D, 0x9D, 0x3A, 0x31, 0x12, 0xAA, 0x80, 0x15, 0x9D); public static readonly Guid IID_ID2D1Effect = new Guid(0x28211A43, 0x7D89, 0x476F, 0x81, 0x81, 0x2D, 0x61, 0x59, 0xB2, 0x20, 0xAD); public static readonly Guid IID_ID2D1Bitmap1 = new Guid(0xA898A84C, 0x3873, 0x4588, 0xB0, 0x8B, 0xEB, 0xBF, 0x97, 0x8D, 0xF0, 0x41); public static readonly Guid IID_ID2D1ColorContext = new Guid(0x1C4820BB, 0x5771, 0x4518, 0xA5, 0x81, 0x2F, 0xE4, 0xDD, 0x0E, 0xC6, 0x57); public static readonly Guid IID_ID2D1GradientStopCollection1 = new Guid(0xAE1572F4, 0x5DD0, 0x4777, 0x99, 0x8B, 0x92, 0x79, 0x47, 0x2A, 0xE6, 0x3B); public static readonly Guid IID_ID2D1DrawingStateBlock1 = new Guid(0x689F1F85, 0xC72E, 0x4E33, 0x8F, 0x19, 0x85, 0x75, 0x4E, 0xFD, 0x5A, 0xCE); public static readonly Guid IID_ID2D1DeviceContext = new Guid(0xE8F7FE7A, 0x191C, 0x466D, 0xAD, 0x95, 0x97, 0x56, 0x78, 0xBD, 0xA9, 0x98); public static readonly Guid IID_ID2D1Device = new Guid(0x47DD575D, 0xAC05, 0x4CDD, 0x80, 0x49, 0x9B, 0x02, 0xCD, 0x16, 0xF4, 0x4C); public static readonly Guid IID_ID2D1Factory1 = new Guid(0xBB12D362, 0xDAEE, 0x4B9A, 0xAA, 0x1D, 0x14, 0xBA, 0x40, 0x1C, 0xFA, 0x1F); public static readonly Guid IID_ID2D1Multithread = new Guid(0x31E6E7BC, 0xE0FF, 0x4D46, 0x8C, 0x64, 0xA0, 0xA8, 0xC4, 0x1C, 0x15, 0xD3); } }
64.692308
299
0.724138
[ "MIT" ]
Ethereal77/terrafx.interop.windows
sources/Interop/Windows/um/d2d1_1/Windows.cs
5,048
C#
// Copyright (c) Six Labors and contributors. // Licensed under the GNU Affero General Public License, Version 3. using System; using SixLabors.ImageSharp.Processing; namespace SixLabors.ImageSharp { /// <summary> /// Adds extensions that allow the processing of images to the <see cref="Image{TPixel}"/> type. /// </summary> public static class GraphicOptionsDefaultsExtensions { /// <summary> /// Sets the default options against the image processing context. /// </summary> /// <param name="context">The image processing context to store default against.</param> /// <param name="optionsBuilder">The action to update instance of the default options used.</param> /// <returns>The passed in <paramref name="context"/> to allow chaining.</returns> public static IImageProcessingContext SetGraphicsOptions(this IImageProcessingContext context, Action<GraphicsOptions> optionsBuilder) { var cloned = context.GetGraphicsOptions().DeepClone(); optionsBuilder(cloned); context.Properties[typeof(GraphicsOptions)] = cloned; return context; } /// <summary> /// Sets the default options against the configuration. /// </summary> /// <param name="configuration">The configuration to store default against.</param> /// <param name="optionsBuilder">The default options to use.</param> public static void SetGraphicsOptions(this Configuration configuration, Action<GraphicsOptions> optionsBuilder) { var cloned = configuration.GetGraphicsOptions().DeepClone(); optionsBuilder(cloned); configuration.Properties[typeof(GraphicsOptions)] = cloned; } /// <summary> /// Sets the default options against the image processing context. /// </summary> /// <param name="context">The image processing context to store default against.</param> /// <param name="options">The default options to use.</param> /// <returns>The passed in <paramref name="context"/> to allow chaining.</returns> public static IImageProcessingContext SetGraphicsOptions(this IImageProcessingContext context, GraphicsOptions options) { context.Properties[typeof(GraphicsOptions)] = options; return context; } /// <summary> /// Sets the default options against the configuration. /// </summary> /// <param name="configuration">The configuration to store default against.</param> /// <param name="options">The default options to use.</param> public static void SetGraphicsOptions(this Configuration configuration, GraphicsOptions options) { configuration.Properties[typeof(GraphicsOptions)] = options; } /// <summary> /// Gets the default options against the image processing context. /// </summary> /// <param name="context">The image processing context to retrieve defaults from.</param> /// <returns>The globaly configued default options.</returns> public static GraphicsOptions GetGraphicsOptions(this IImageProcessingContext context) { if (context.Properties.TryGetValue(typeof(GraphicsOptions), out var options) && options is GraphicsOptions go) { return go; } var configOptions = context.Configuration.GetGraphicsOptions(); // do not cache the fall back to config into the the processing context // in case someone want to change the value on the config and expects it re trflow thru return configOptions; } /// <summary> /// Gets the default options against the image processing context. /// </summary> /// <param name="configuration">The configuration to retrieve defaults from.</param> /// <returns>The globaly configued default options.</returns> public static GraphicsOptions GetGraphicsOptions(this Configuration configuration) { if (configuration.Properties.TryGetValue(typeof(GraphicsOptions), out var options) && options is GraphicsOptions go) { return go; } var configOptions = new GraphicsOptions(); // capture the fallback so the same instance will always be returned in case its mutated configuration.Properties[typeof(GraphicsOptions)] = configOptions; return configOptions; } } }
45.613861
142
0.650098
[ "Apache-2.0" ]
fahadabdulaziz/ImageSharp
src/ImageSharp/GraphicOptionsDefaultsExtensions.cs
4,607
C#
using System; using System.Collections.Generic; using JetBrains.Annotations; using JetBrains.Collections.Viewable; using JetBrains.Diagnostics; using JetBrains.Lifetimes; using JetBrains.Rd.Base; namespace JetBrains.Rd.Impl { public class Protocol : IProtocol { public static readonly ILog Logger = Log.GetLog("protocol"); public static readonly ILog InitLogger = Logger.GetSublogger("INIT"); public static LogWithLevel? InitTrace = InitLogger.Trace(); /// <summary> /// Should match textual RdId of protocol intern root in Kotlin/js/cpp counterpart /// </summary> const string ProtocolInternRootRdId = "ProtocolInternRoot"; const string ContextHandlerRdId = "ProtocolContextHandler"; /// <summary> /// Should match whatever is in rd-gen for ProtocolInternScope /// </summary> const string ProtocolInternScopeStringId = "Protocol"; public Protocol([NotNull] string name, [NotNull] ISerializers serializers, [NotNull] IIdentities identities, [NotNull] IScheduler scheduler, [NotNull] IWire wire, Lifetime lifetime, params RdContextBase[] initialContexts) : this(name, serializers, identities, scheduler, wire, lifetime, null, null, initialContexts) { } internal Protocol([NotNull] string name, [NotNull] ISerializers serializers, [NotNull] IIdentities identities, [NotNull] IScheduler scheduler, [NotNull] IWire wire, Lifetime lifetime, SerializationCtx? serializationCtx = null, [CanBeNull] ProtocolContexts parentContexts = null, params RdContextBase[] initialContexts) { Name = name ?? throw new ArgumentNullException(nameof(name)); Location = new RName(name); Serializers = serializers ?? throw new ArgumentNullException(nameof(serializers)); Identities = identities ?? throw new ArgumentNullException(nameof(identities)); Scheduler = scheduler ?? throw new ArgumentNullException(nameof(scheduler)); Wire = wire ?? throw new ArgumentNullException(nameof(wire)); SerializationContext = serializationCtx ?? new SerializationCtx(this, new Dictionary<string, IInternRoot<object>>() {{ProtocolInternScopeStringId, CreateProtocolInternRoot(lifetime)}}); Contexts = parentContexts ?? new ProtocolContexts(SerializationContext); wire.Contexts = Contexts; if (serializationCtx == null) SerializationContext.InternRoots[ProtocolInternScopeStringId].Bind(lifetime, this, ProtocolInternRootRdId); foreach (var rdContextBase in initialContexts) rdContextBase.RegisterOn(Contexts); if (parentContexts == null) BindContexts(lifetime); OutOfSyncModels = new ViewableSet<RdExtBase>(); } private InternRoot<object> CreateProtocolInternRoot(Lifetime lifetime) { var root = new InternRoot<object>(); root.RdId = RdId.Nil.Mix(ProtocolInternRootRdId); return root; } private void BindContexts(Lifetime lifetime) { Contexts.RdId = RdId.Nil.Mix(ContextHandlerRdId); Scheduler.InvokeOrQueue(() => { if (!lifetime.IsAlive) return; Contexts.Bind(lifetime, this, ContextHandlerRdId); }); } public string Name { get; } public IWire Wire { get; } public ISerializers Serializers { get; } public IIdentities Identities { get; } public IScheduler Scheduler { get; } public SerializationCtx SerializationContext { get; } public ViewableSet<RdExtBase> OutOfSyncModels { get; } public ProtocolContexts Contexts { get; } [PublicAPI] public bool ThrowErrorOnOutOfSyncModels = true; public RName Location { get; } IProtocol IRdDynamic.Proto => this; } }
40.472527
191
0.71735
[ "Apache-2.0" ]
denis417/rd
rd-net/RdFramework/Impl/Protocol.cs
3,683
C#
using ContosoUniversity.Models; using System.Data.Entity; using System.Data.Entity.ModelConfiguration.Conventions; namespace ContosoUniversity.DAL { public partial class SchoolDbContext //SchoolDbContext2.cs { protected override void OnModelCreating(DbModelBuilder modelBuilder) { modelBuilder.Conventions.Remove<PluralizingTableNameConvention>(); modelBuilder.Entity<Course>() .HasMany(c => c.Instructors).WithMany(i => i.Courses) .Map(t => t.MapLeftKey("CourseID") .MapRightKey("InstructorID") .ToTable("CourseInstructor")); modelBuilder.Entity<Instructor>() .HasOptional(i => i.OfficeAssignment) .WithRequired(o => o.Instructor); } } }
32.92
78
0.620899
[ "MIT" ]
bgoodearl/ContosoUniversity_dnc31_MVC
ContosoUniversity.DAL/SchoolDbContext2.cs
825
C#
using Chloe; using Chloe.Core; using Chloe.Descriptors; using Chloe.Infrastructure; using Chloe.SqlServer; using Chloe.Reflection; using System; using System.Collections.Generic; using System.Data; using System.Linq; using System.Linq.Expressions; using System.Text; using System.Threading.Tasks; using Chloe.SqlServer.DDL; using Chloe.DDL; namespace ChloeDemo { class MsSqlDemo : DemoBase { public MsSqlDemo() { DbConfiguration.UseTypeBuilders(typeof(TestEntityMap)); } protected override IDbContext CreateDbContext() { MsSqlContext dbContext = new MsSqlContext("Data Source = .;Initial Catalog = Chloe;Integrated Security = SSPI;"); dbContext.PagingMode = PagingMode.OFFSET_FETCH; return dbContext; } public override void InitDatabase() { new SqlServerTableGenerator(this.DbContext).CreateTables(TableCreateMode.CreateNew); } public override void Method() { IQuery<Person> q = this.DbContext.Query<Person>(); var space = new char[] { ' ' }; DateTime startTime = DateTime.Now; DateTime endTime = DateTime.Now.AddDays(1); q.Select(a => new { Id = a.Id, //CustomFunction = DbFunctions.MyFunction(a.Id), //自定义函数 String_Length = (int?)a.Name.Length,//LEN([Person].[Name]) Substring = a.Name.Substring(0),//SUBSTRING([Person].[Name],0 + 1,LEN([Person].[Name])) Substring1 = a.Name.Substring(1),//SUBSTRING([Person].[Name],1 + 1,LEN([Person].[Name])) Substring1_2 = a.Name.Substring(1, 2),//SUBSTRING([Person].[Name],1 + 1,2) ToLower = a.Name.ToLower(),//LOWER([Person].[Name]) ToUpper = a.Name.ToUpper(),//UPPER([Person].[Name]) IsNullOrEmpty = string.IsNullOrEmpty(a.Name),//too long Contains = (bool?)a.Name.Contains("s"),// Trim = a.Name.Trim(),//RTRIM(LTRIM([Person].[Name])) TrimStart = a.Name.TrimStart(space),//LTRIM([Person].[Name]) TrimEnd = a.Name.TrimEnd(space),//RTRIM([Person].[Name]) StartsWith = (bool?)a.Name.StartsWith("s"),// EndsWith = (bool?)a.Name.EndsWith("s"),// Replace = a.Name.Replace("l", "L"), 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 /* No longer support method 'DateTime.Subtract(DateTime d)', instead of using 'Sql.DiffXX' */ //SubtractTotalDays = endTime.Subtract(startTime).TotalDays,//CAST(DATEDIFF(DAY,@P_0,@P_1) //SubtractTotalHours = endTime.Subtract(startTime).TotalHours,//CAST(DATEDIFF(HOUR,@P_0,@P_1) //SubtractTotalMinutes = endTime.Subtract(startTime).TotalMinutes,//CAST(DATEDIFF(MINUTE,@P_0,@P_1) //SubtractTotalSeconds = endTime.Subtract(startTime).TotalSeconds,//CAST(DATEDIFF(SECOND,@P_0,@P_1) //SubtractTotalMilliseconds = endTime.Subtract(startTime).TotalMilliseconds,//CAST(DATEDIFF(MILLISECOND,@P_0,@P_1) AddYears = startTime.AddYears(1),//DATEADD(YEAR,1,@P_0) AddMonths = startTime.AddMonths(1),//DATEADD(MONTH,1,@P_0) AddDays = startTime.AddDays(1),//DATEADD(DAY,1,@P_0) AddHours = startTime.AddHours(1),//DATEADD(HOUR,1,@P_0) AddMinutes = startTime.AddMinutes(2),//DATEADD(MINUTE,2,@P_0) AddSeconds = startTime.AddSeconds(120),//DATEADD(SECOND,120,@P_0) AddMilliseconds = startTime.AddMilliseconds(20000),//DATEADD(MILLISECOND,20000,@P_0) Now = DateTime.Now,//GETDATE() UtcNow = DateTime.UtcNow,//GETUTCDATE() Today = DateTime.Today,//CAST(GETDATE() AS DATE) Date = DateTime.Now.Date,//CAST(GETDATE() AS DATE) Year = DateTime.Now.Year,//DATEPART(YEAR,GETDATE()) Month = DateTime.Now.Month,//DATEPART(MONTH,GETDATE()) Day = DateTime.Now.Day,//DATEPART(DAY,GETDATE()) Hour = DateTime.Now.Hour,//DATEPART(HOUR,GETDATE()) Minute = DateTime.Now.Minute,//DATEPART(MINUTE,GETDATE()) Second = DateTime.Now.Second,//DATEPART(SECOND,GETDATE()) Millisecond = DateTime.Now.Millisecond,//DATEPART(MILLISECOND,GETDATE()) DayOfWeek = DateTime.Now.DayOfWeek,//(DATEPART(WEEKDAY,GETDATE()) - 1) Int_Parse = int.Parse("1"),//CAST(N'1' AS INT) Int16_Parse = Int16.Parse("11"),//CAST(N'11' AS SMALLINT) Long_Parse = long.Parse("2"),//CAST(N'2' AS BIGINT) Double_Parse = double.Parse("3"),//CAST(N'3' AS FLOAT) Float_Parse = float.Parse("4"),//CAST(N'4' AS REAL) //Decimal_Parse = decimal.Parse("5"),//CAST(N'5' AS DECIMAL) ps: 'Decimal.Parse(string s)' is not supported now,because we don't know the precision and scale information. Guid_Parse = Guid.Parse("D544BC4C-739E-4CD3-A3D3-7BF803FCE179"),//CAST(N'D544BC4C-739E-4CD3-A3D3-7BF803FCE179' AS UNIQUEIDENTIFIER) AS [Guid_Parse] Bool_Parse = bool.Parse("1"),//CASE WHEN CAST(N'1' AS BIT) = CAST(1 AS BIT) THEN CAST(1 AS BIT) WHEN NOT (CAST(N'1' AS BIT) = CAST(1 AS BIT)) THEN CAST(0 AS BIT) ELSE NULL END AS [Bool_Parse] DateTime_Parse = DateTime.Parse("1992-1-16"),//CAST(N'1992-1-16' AS DATETIME) AS [DateTime_Parse] B = a.Age == null ? false : a.Age > 1, //三元表达式 CaseWhen = Case.When(a.Id > 100).Then(1).Else(0) //case when }).ToList(); ConsoleHelper.WriteLineAndReadKey(); } } }
52.99187
207
0.59911
[ "MIT" ]
shuxinqin/Chloe
src/ChloeDemo/MsSqlDemo.cs
6,540
C#
// Copyright (c) 2015 - 2019 Doozy Entertainment. All Rights Reserved. // This code can only be used under the standard Unity Asset Store End User License Agreement // A Copy of the EULA APPENDIX 1 is available at http://unity3d.com/company/legal/as_terms using System; using UnityEngine; namespace Doozy.Editor { public static partial class DGUI { public static class Tab { public enum Direction { ToRight, ToBottom, ToLeft, ToTop } public static GUIStyle GetStyle(Direction direction, bool selectedStyle = false) { switch (direction) { case Direction.ToRight: break; case Direction.ToBottom: break; case Direction.ToLeft: break; case Direction.ToTop: return Styles.GetStyle(selectedStyle ? Styles.StyleName.TabToTopSelected : Styles.StyleName.TabToTop); default: throw new ArgumentOutOfRangeException("direction", direction, null); } return null; } public static bool Draw(string label, bool isSelected = false, Direction direction = Direction.ToTop, params GUILayoutOption[] options) { bool result = GUILayout.Button(label, GetStyle(direction, isSelected), options); return result; } } } }
34.727273
147
0.563482
[ "MIT" ]
Galaxyben/FixMeArmor
Assets/Doozy/Editor/GUI/Scripts/DGUI/Tab.cs
1,528
C#
using System.Collections.Generic; using System.Globalization; using System.IO; using System.IO.Compression; using System.Linq; using System.Text; using System.Xml; using System.Xml.Linq; using BlackOps2SoundStudio.Properties; #if BUILD_XML using System.IO; using System.Xml; using System.Linq; #endif #if BUILD_BO3 using System.IO; using System.Xml; using System.Linq; #endif namespace BlackOps2SoundStudio.Format { static class SndAliasNameDatabase { public static Dictionary<int, string> Names { get; set; } static SndAliasNameDatabase() { XDocument document; using (var ms = new MemoryStream(Resources.Names)) using (var deflate = new DeflateStream(ms, CompressionMode.Decompress)) { using (var reader = new XmlTextReader(deflate)) document = XDocument.Load(reader); } Names = new Dictionary<int, string>(); var entries = document.Element("Entries"); if (entries == null) return; foreach (var desc in entries.Elements("Entry")) { var hash = desc.Attribute("Hash"); var path = desc.Attribute("Path"); if (hash == null || path == null) continue; Names[int.Parse(hash.Value, NumberStyles.HexNumber)] = path.Value; } } #if BUILD_BO3 public static void BuildBO3() { const string gamePath = @"I:\Call.of.Duty.Black.Ops.III.Beta.SteamEarlyAccess-Fisher\Call of Duty Black Ops III Beta\zone\snd"; foreach (var sabl in Directory.GetFiles(gamePath, "*.sabl", SearchOption.AllDirectories)) { var sndBank = SndAliasBankReader.Read(sabl); sndBank.Dispose(); } foreach (var sabs in Directory.GetFiles(gamePath, "*.sabs", SearchOption.AllDirectories)) { var sndBank = SndAliasBankReader.Read(sabs); sndBank.Dispose(); } var document = new XDocument( new XElement("Entries", Names.Select(kvp => new XElement("Entry", new XAttribute("Hash", kvp.Key), new XAttribute("Path", kvp.Value))))); using (var writer = XmlWriter.Create("Names.xml", new XmlWriterSettings { Indent = true })) document.WriteTo(writer); } #endif #if BUILD_XML public static void BuildXML() { if (!Directory.Exists("Identifiers")) return; var dict = new Dictionary<string, string>(); foreach (var kvp in Names) dict.Add(kvp.Key.ToString("X8"), kvp.Value); foreach (var file in Directory.GetFiles("Identifiers")) { var lines = File.ReadAllLines(file); foreach (var line in lines) { if (string.IsNullOrEmpty(line)) continue; var split = line.Split('-'); if (split.Length != 2) continue; dict[split[0]] = split[1]; } } var document = new XDocument( new XElement("Entries", dict.Select(kvp => new XElement("Entry", new XAttribute("Hash", kvp.Key), new XAttribute("Path", kvp.Value))))); using (var writer = XmlWriter.Create("Names.xml", new XmlWriterSettings { Indent = true })) document.WriteTo(writer); using (var stream = File.OpenRead("Names.xml")) using (var outStream = File.Create("Names.deflate")) using (var deflate = new DeflateStream(outStream, CompressionMode.Compress)) stream.CopyTo(deflate); } #endif } }
32.081967
139
0.547266
[ "MIT" ]
master131/Black-Ops-II-Sound-Studio
Format/SndAliasNameDatabase.cs
3,916
C#
using System; using System.IO; using UnityEngine; public class KGFDocumentation : global::UnityEngine.MonoBehaviour { public void OpenDocumentation() { string text = global::UnityEngine.Application.dataPath; text = global::System.IO.Path.Combine(text, "kolmich"); text = global::System.IO.Path.Combine(text, "documentation"); text = global::System.IO.Path.Combine(text, "files"); text += global::System.IO.Path.DirectorySeparatorChar; text += "documentation.html"; text.Replace('/', global::System.IO.Path.DirectorySeparatorChar); global::UnityEngine.Application.OpenURL("file://" + text); } }
32.368421
67
0.736585
[ "CC0-1.0" ]
FreyaFreed/mordheim
Assembly-CSharp/KGFDocumentation.cs
617
C#
using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Hosting; namespace GeneratorUtils.Samples.Api { public class Startup { public Startup(IConfiguration configuration) { Configuration = configuration; } public IConfiguration Configuration { get; } #pragma warning disable CA1822 // Mark members as static // This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { services.AddControllers(); services.AddSwaggerDocument(); } #pragma warning restore CA1822 // Mark members as static #pragma warning disable CA1822 // Mark members as static // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IWebHostEnvironment env) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); app.UseOpenApi(); app.UseSwaggerUi3(); } app.UseHttpsRedirection(); app.UseRouting(); app.UseAuthorization(); app.UseEndpoints(endpoints => endpoints.MapControllers()); } #pragma warning restore CA1822 // Mark members as static } }
28.754717
106
0.653543
[ "MIT" ]
KuraiAndras/GeneratorUtils
samples/GeneratorUtils.Samples.Api/Startup.cs
1,526
C#
/****************************************************************************** * Spine Runtimes License Agreement * Last updated May 1, 2019. Replaces all prior versions. * * Copyright (c) 2013-2019, Esoteric Software LLC * * Integration of the Spine Runtimes into software or otherwise creating * derivative works of the Spine Runtimes is permitted under the terms and * conditions of Section 2 of the Spine Editor License Agreement: * http://esotericsoftware.com/spine-editor-license * * Otherwise, it is permitted to integrate the Spine Runtimes into software * or otherwise create derivative works of the Spine Runtimes (collectively, * "Products"), provided that each user of the Products must obtain their own * Spine Editor license and redistribution of the Products in any form must * include this license and copyright notice. * * THIS SOFTWARE IS PROVIDED BY ESOTERIC SOFTWARE LLC "AS IS" AND ANY EXPRESS * OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN * NO EVENT SHALL ESOTERIC SOFTWARE LLC BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES, BUSINESS * INTERRUPTION, OR LOSS OF USE, DATA, OR PROFITS) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. *****************************************************************************/ using UnityEngine; using System.Collections.Generic; namespace Spine.Unity.Modules.AttachmentTools { public static class AttachmentRegionExtensions { #region GetRegion /// <summary> /// Tries to get the region (image) of a renderable attachment. If the attachment is not renderable, it returns null.</summary> public static AtlasRegion GetRegion (this Attachment attachment) { var renderableAttachment = attachment as IHasRendererObject; if (renderableAttachment != null) return renderableAttachment.RendererObject as AtlasRegion; return null; } /// <summary>Gets the region (image) of a RegionAttachment</summary> public static AtlasRegion GetRegion (this RegionAttachment regionAttachment) { return regionAttachment.RendererObject as AtlasRegion; } /// <summary>Gets the region (image) of a MeshAttachment</summary> public static AtlasRegion GetRegion (this MeshAttachment meshAttachment) { return meshAttachment.RendererObject as AtlasRegion; } #endregion #region SetRegion /// <summary> /// Tries to set the region (image) of a renderable attachment. If the attachment is not renderable, nothing is applied.</summary> public static void SetRegion (this Attachment attachment, AtlasRegion region, bool updateOffset = true) { var regionAttachment = attachment as RegionAttachment; if (regionAttachment != null) regionAttachment.SetRegion(region, updateOffset); var meshAttachment = attachment as MeshAttachment; if (meshAttachment != null) meshAttachment.SetRegion(region, updateOffset); } /// <summary>Sets the region (image) of a RegionAttachment</summary> public static void SetRegion (this RegionAttachment attachment, AtlasRegion region, bool updateOffset = true) { if (region == null) throw new System.ArgumentNullException("region"); // (AtlasAttachmentLoader.cs) attachment.RendererObject = region; attachment.SetUVs(region.u, region.v, region.u2, region.v2, region.rotate); attachment.regionOffsetX = region.offsetX; attachment.regionOffsetY = region.offsetY; attachment.regionWidth = region.width; attachment.regionHeight = region.height; attachment.regionOriginalWidth = region.originalWidth; attachment.regionOriginalHeight = region.originalHeight; if (updateOffset) attachment.UpdateOffset(); } /// <summary>Sets the region (image) of a MeshAttachment</summary> public static void SetRegion (this MeshAttachment attachment, AtlasRegion region, bool updateUVs = true) { if (region == null) throw new System.ArgumentNullException("region"); // (AtlasAttachmentLoader.cs) attachment.RendererObject = region; attachment.RegionU = region.u; attachment.RegionV = region.v; attachment.RegionU2 = region.u2; attachment.RegionV2 = region.v2; attachment.RegionRotate = region.rotate; attachment.regionOffsetX = region.offsetX; attachment.regionOffsetY = region.offsetY; attachment.regionWidth = region.width; attachment.regionHeight = region.height; attachment.regionOriginalWidth = region.originalWidth; attachment.regionOriginalHeight = region.originalHeight; if (updateUVs) attachment.UpdateUVs(); } #endregion #region Runtime RegionAttachments /// <summary> /// Creates a RegionAttachment based on a sprite. This method creates a real, usable AtlasRegion. That AtlasRegion uses a new AtlasPage with the Material provided./// </summary> public static RegionAttachment ToRegionAttachment (this Sprite sprite, Material material, float rotation = 0f) { return sprite.ToRegionAttachment(material.ToSpineAtlasPage(), rotation); } /// <summary> /// Creates a RegionAttachment based on a sprite. This method creates a real, usable AtlasRegion. That AtlasRegion uses the AtlasPage provided./// </summary> public static RegionAttachment ToRegionAttachment (this Sprite sprite, AtlasPage page, float rotation = 0f) { if (sprite == null) throw new System.ArgumentNullException("sprite"); if (page == null) throw new System.ArgumentNullException("page"); var region = sprite.ToAtlasRegion(page); var unitsPerPixel = 1f / sprite.pixelsPerUnit; return region.ToRegionAttachment(sprite.name, unitsPerPixel, rotation); } /// <summary> /// Creates a Spine.AtlasRegion that uses a premultiplied alpha duplicate texture of the Sprite's texture data. Returns a RegionAttachment that uses it. Use this if you plan to use a premultiply alpha shader such as "Spine/Skeleton"</summary> public static RegionAttachment ToRegionAttachmentPMAClone (this Sprite sprite, Shader shader, TextureFormat textureFormat = AtlasUtilities.SpineTextureFormat, bool mipmaps = AtlasUtilities.UseMipMaps, Material materialPropertySource = null, float rotation = 0f) { if (sprite == null) throw new System.ArgumentNullException("sprite"); if (shader == null) throw new System.ArgumentNullException("shader"); var region = sprite.ToAtlasRegionPMAClone(shader, textureFormat, mipmaps, materialPropertySource); var unitsPerPixel = 1f / sprite.pixelsPerUnit; return region.ToRegionAttachment(sprite.name, unitsPerPixel, rotation); } public static RegionAttachment ToRegionAttachmentPMAClone (this Sprite sprite, Material materialPropertySource, TextureFormat textureFormat = AtlasUtilities.SpineTextureFormat, bool mipmaps = AtlasUtilities.UseMipMaps, float rotation = 0f) { return sprite.ToRegionAttachmentPMAClone(materialPropertySource.shader, textureFormat, mipmaps, materialPropertySource, rotation); } /// <summary> /// Creates a new RegionAttachment from a given AtlasRegion.</summary> public static RegionAttachment ToRegionAttachment (this AtlasRegion region, string attachmentName, float scale = 0.01f, float rotation = 0f) { if (string.IsNullOrEmpty(attachmentName)) throw new System.ArgumentException("attachmentName can't be null or empty.", "attachmentName"); if (region == null) throw new System.ArgumentNullException("region"); // (AtlasAttachmentLoader.cs) var attachment = new RegionAttachment(attachmentName); attachment.RendererObject = region; attachment.SetUVs(region.u, region.v, region.u2, region.v2, region.rotate); attachment.regionOffsetX = region.offsetX; attachment.regionOffsetY = region.offsetY; attachment.regionWidth = region.width; attachment.regionHeight = region.height; attachment.regionOriginalWidth = region.originalWidth; attachment.regionOriginalHeight = region.originalHeight; attachment.Path = region.name; attachment.scaleX = 1; attachment.scaleY = 1; attachment.rotation = rotation; attachment.r = 1; attachment.g = 1; attachment.b = 1; attachment.a = 1; // pass OriginalWidth and OriginalHeight because UpdateOffset uses it in its calculation. attachment.width = attachment.regionOriginalWidth * scale; attachment.height = attachment.regionOriginalHeight * scale; attachment.SetColor(Color.white); attachment.UpdateOffset(); return attachment; } /// <summary> Sets the scale. Call regionAttachment.UpdateOffset to apply the change.</summary> public static void SetScale (this RegionAttachment regionAttachment, Vector2 scale) { regionAttachment.scaleX = scale.x; regionAttachment.scaleY = scale.y; } /// <summary> Sets the scale. Call regionAttachment.UpdateOffset to apply the change.</summary> public static void SetScale (this RegionAttachment regionAttachment, float x, float y) { regionAttachment.scaleX = x; regionAttachment.scaleY = y; } /// <summary> Sets the position offset. Call regionAttachment.UpdateOffset to apply the change.</summary> public static void SetPositionOffset (this RegionAttachment regionAttachment, Vector2 offset) { regionAttachment.x = offset.x; regionAttachment.y = offset.y; } /// <summary> Sets the position offset. Call regionAttachment.UpdateOffset to apply the change.</summary> public static void SetPositionOffset (this RegionAttachment regionAttachment, float x, float y) { regionAttachment.x = x; regionAttachment.y = y; } /// <summary> Sets the rotation. Call regionAttachment.UpdateOffset to apply the change.</summary> public static void SetRotation (this RegionAttachment regionAttachment, float rotation) { regionAttachment.rotation = rotation; } #endregion } public static class AtlasUtilities { internal const TextureFormat SpineTextureFormat = TextureFormat.RGBA32; internal const float DefaultMipmapBias = -0.5f; internal const bool UseMipMaps = false; internal const float DefaultScale = 0.01f; const int NonrenderingRegion = -1; public static AtlasRegion ToAtlasRegion (this Texture2D t, Material materialPropertySource, float scale = DefaultScale) { return t.ToAtlasRegion(materialPropertySource.shader, scale, materialPropertySource); } public static AtlasRegion ToAtlasRegion (this Texture2D t, Shader shader, float scale = DefaultScale, Material materialPropertySource = null) { var material = new Material(shader); if (materialPropertySource != null) { material.CopyPropertiesFromMaterial(materialPropertySource); material.shaderKeywords = materialPropertySource.shaderKeywords; } material.mainTexture = t; var page = material.ToSpineAtlasPage(); float width = t.width; float height = t.height; var region = new AtlasRegion(); region.name = t.name; region.index = -1; region.rotate = false; // World space units Vector2 boundsMin = Vector2.zero, boundsMax = new Vector2(width, height) * scale; // Texture space/pixel units region.width = (int)width; region.originalWidth = (int)width; region.height = (int)height; region.originalHeight = (int)height; region.offsetX = width * (0.5f - InverseLerp(boundsMin.x, boundsMax.x, 0)); region.offsetY = height * (0.5f - InverseLerp(boundsMin.y, boundsMax.y, 0)); // Use the full area of the texture. region.u = 0; region.v = 1; region.u2 = 1; region.v2 = 0; region.x = 0; region.y = 0; region.page = page; return region; } /// <summary> /// Creates a Spine.AtlasRegion that uses a premultiplied alpha duplicate of the Sprite's texture data.</summary> public static AtlasRegion ToAtlasRegionPMAClone (this Texture2D t, Material materialPropertySource, TextureFormat textureFormat = SpineTextureFormat, bool mipmaps = UseMipMaps) { return t.ToAtlasRegionPMAClone(materialPropertySource.shader, textureFormat, mipmaps, materialPropertySource); } /// <summary> /// Creates a Spine.AtlasRegion that uses a premultiplied alpha duplicate of the Sprite's texture data.</summary> public static AtlasRegion ToAtlasRegionPMAClone (this Texture2D t, Shader shader, TextureFormat textureFormat = SpineTextureFormat, bool mipmaps = UseMipMaps, Material materialPropertySource = null) { var material = new Material(shader); if (materialPropertySource != null) { material.CopyPropertiesFromMaterial(materialPropertySource); material.shaderKeywords = materialPropertySource.shaderKeywords; } var newTexture = t.GetClone(textureFormat, mipmaps); newTexture.ApplyPMA(true); newTexture.name = t.name + "-pma-"; material.name = t.name + shader.name; material.mainTexture = newTexture; var page = material.ToSpineAtlasPage(); var region = newTexture.ToAtlasRegion(shader); region.page = page; return region; } /// <summary> /// Creates a new Spine.AtlasPage from a UnityEngine.Material. If the material has a preassigned texture, the page width and height will be set.</summary> public static AtlasPage ToSpineAtlasPage (this Material m) { var newPage = new AtlasPage { rendererObject = m, name = m.name }; var t = m.mainTexture; if (t != null) { newPage.width = t.width; newPage.height = t.height; } return newPage; } /// <summary> /// Creates a Spine.AtlasRegion from a UnityEngine.Sprite.</summary> public static AtlasRegion ToAtlasRegion (this Sprite s, AtlasPage page) { if (page == null) throw new System.ArgumentNullException("page", "page cannot be null. AtlasPage determines which texture region belongs and how it should be rendered. You can use material.ToSpineAtlasPage() to get a shareable AtlasPage from a Material, or use the sprite.ToAtlasRegion(material) overload."); var region = s.ToAtlasRegion(); region.page = page; return region; } /// <summary> /// Creates a Spine.AtlasRegion from a UnityEngine.Sprite. This creates a new AtlasPage object for every AtlasRegion you create. You can centralize Material control by creating a shared atlas page using Material.ToSpineAtlasPage and using the sprite.ToAtlasRegion(AtlasPage) overload.</summary> public static AtlasRegion ToAtlasRegion (this Sprite s, Material material) { var region = s.ToAtlasRegion(); region.page = material.ToSpineAtlasPage(); return region; } public static AtlasRegion ToAtlasRegionPMAClone (this Sprite s, Material materialPropertySource, TextureFormat textureFormat = SpineTextureFormat, bool mipmaps = UseMipMaps) { return s.ToAtlasRegionPMAClone(materialPropertySource.shader, textureFormat, mipmaps, materialPropertySource); } /// <summary> /// Creates a Spine.AtlasRegion that uses a premultiplied alpha duplicate of the Sprite's texture data.</summary> public static AtlasRegion ToAtlasRegionPMAClone (this Sprite s, Shader shader, TextureFormat textureFormat = SpineTextureFormat, bool mipmaps = UseMipMaps, Material materialPropertySource = null) { var material = new Material(shader); if (materialPropertySource != null) { material.CopyPropertiesFromMaterial(materialPropertySource); material.shaderKeywords = materialPropertySource.shaderKeywords; } var tex = s.ToTexture(textureFormat, mipmaps); tex.ApplyPMA(true); tex.name = s.name + "-pma-"; material.name = tex.name + shader.name; material.mainTexture = tex; var page = material.ToSpineAtlasPage(); var region = s.ToAtlasRegion(true); region.page = page; return region; } internal static AtlasRegion ToAtlasRegion (this Sprite s, bool isolatedTexture = false) { var region = new AtlasRegion(); region.name = s.name; region.index = -1; region.rotate = s.packed && s.packingRotation != SpritePackingRotation.None; // World space units Bounds bounds = s.bounds; Vector2 boundsMin = bounds.min, boundsMax = bounds.max; // Texture space/pixel units Rect spineRect = s.rect.SpineUnityFlipRect(s.texture.height); region.width = (int)spineRect.width; region.originalWidth = (int)spineRect.width; region.height = (int)spineRect.height; region.originalHeight = (int)spineRect.height; region.offsetX = spineRect.width * (0.5f - InverseLerp(boundsMin.x, boundsMax.x, 0)); region.offsetY = spineRect.height * (0.5f - InverseLerp(boundsMin.y, boundsMax.y, 0)); if (isolatedTexture) { region.u = 0; region.v = 1; region.u2 = 1; region.v2 = 0; region.x = 0; region.y = 0; } else { Texture2D tex = s.texture; Rect uvRect = TextureRectToUVRect(s.textureRect, tex.width, tex.height); region.u = uvRect.xMin; region.v = uvRect.yMax; region.u2 = uvRect.xMax; region.v2 = uvRect.yMin; region.x = (int)spineRect.x; region.y = (int)spineRect.y; } return region; } #region Runtime Repacking /// <summary> /// Fills the outputAttachments list with new attachment objects based on the attachments in sourceAttachments, but mapped to a new single texture using the same material.</summary> /// <param name="sourceAttachments">The list of attachments to be repacked.</param> /// <param name = "outputAttachments">The List(Attachment) to populate with the newly created Attachment objects.</param> /// /// <param name="materialPropertySource">May be null. If no Material property source is provided, no special </param> public static void GetRepackedAttachments (List<Attachment> sourceAttachments, List<Attachment> outputAttachments, Material materialPropertySource, out Material outputMaterial, out Texture2D outputTexture, int maxAtlasSize = 1024, int padding = 2, TextureFormat textureFormat = SpineTextureFormat, bool mipmaps = UseMipMaps, string newAssetName = "Repacked Attachments", bool clearCache = false, bool useOriginalNonrenderables = true) { if (sourceAttachments == null) throw new System.ArgumentNullException("sourceAttachments"); if (outputAttachments == null) throw new System.ArgumentNullException("outputAttachments"); // Use these to detect and use shared regions. var existingRegions = new Dictionary<AtlasRegion, int>(); var regionIndexes = new List<int>(); var texturesToPack = new List<Texture2D>(); var originalRegions = new List<AtlasRegion>(); outputAttachments.Clear(); outputAttachments.AddRange(sourceAttachments); int newRegionIndex = 0; for (int i = 0, n = sourceAttachments.Count; i < n; i++) { var originalAttachment = sourceAttachments[i]; if (IsRenderable(originalAttachment)) { var newAttachment = originalAttachment.GetClone(true); var region = newAttachment.GetRegion(); int existingIndex; if (existingRegions.TryGetValue(region, out existingIndex)) { regionIndexes.Add(existingIndex); // Store the region index for the eventual new attachment. } else { originalRegions.Add(region); texturesToPack.Add(region.ToTexture()); // Add the texture to the PackTextures argument existingRegions.Add(region, newRegionIndex); // Add the region to the dictionary of known regions regionIndexes.Add(newRegionIndex); // Store the region index for the eventual new attachment. newRegionIndex++; } outputAttachments[i] = newAttachment; } else { outputAttachments[i] = useOriginalNonrenderables ? originalAttachment : originalAttachment.GetClone(true); regionIndexes.Add(NonrenderingRegion); // Output attachments pairs with regionIndexes list 1:1. Pad with a sentinel if the attachment doesn't have a region. } } // Fill a new texture with the collected attachment textures. var newTexture = new Texture2D(maxAtlasSize, maxAtlasSize, textureFormat, mipmaps); newTexture.mipMapBias = AtlasUtilities.DefaultMipmapBias; newTexture.name = newAssetName; // Copy settings if (texturesToPack.Count > 0) { newTexture.anisoLevel = texturesToPack[0].anisoLevel; } var rects = newTexture.PackTextures(texturesToPack.ToArray(), padding, maxAtlasSize); // Rehydrate the repacked textures as a Material, Spine atlas and Spine.AtlasAttachments Shader shader = materialPropertySource == null ? Shader.Find("Spine/Skeleton") : materialPropertySource.shader; var newMaterial = new Material(shader); if (materialPropertySource != null) { newMaterial.CopyPropertiesFromMaterial(materialPropertySource); newMaterial.shaderKeywords = materialPropertySource.shaderKeywords; } newMaterial.name = newAssetName; newMaterial.mainTexture = newTexture; var page = newMaterial.ToSpineAtlasPage(); page.name = newAssetName; var repackedRegions = new List<AtlasRegion>(); for (int i = 0, n = originalRegions.Count; i < n; i++) { var oldRegion = originalRegions[i]; var newRegion = UVRectToAtlasRegion(rects[i], oldRegion.name, page, oldRegion.offsetX, oldRegion.offsetY, oldRegion.rotate); repackedRegions.Add(newRegion); } // Map the cloned attachments to the repacked atlas. for (int i = 0, n = outputAttachments.Count; i < n; i++) { var a = outputAttachments[i]; if (IsRenderable(a)) a.SetRegion(repackedRegions[regionIndexes[i]]); } // Clean up. if (clearCache) AtlasUtilities.ClearCache(); outputTexture = newTexture; outputMaterial = newMaterial; } /// <summary> /// Creates and populates a duplicate skin with cloned attachments that are backed by a new packed texture atlas comprised of all the regions from the original skin.</summary> /// <remarks>GetRepackedSkin is an expensive operation, preferably call it at level load time. No Spine.Atlas object is created so there is no way to find AtlasRegions except through the Attachments using them.</remarks> public static Skin GetRepackedSkin (this Skin o, string newName, Material materialPropertySource, out Material outputMaterial, out Texture2D outputTexture, int maxAtlasSize = 1024, int padding = 2, TextureFormat textureFormat = SpineTextureFormat, bool mipmaps = UseMipMaps, bool useOriginalNonrenderables = true) { return GetRepackedSkin(o, newName, materialPropertySource.shader, out outputMaterial, out outputTexture, maxAtlasSize, padding, textureFormat, mipmaps, materialPropertySource, useOriginalNonrenderables); } /// <summary> /// Creates and populates a duplicate skin with cloned attachments that are backed by a new packed texture atlas comprised of all the regions from the original skin.</summary> /// <remarks>GetRepackedSkin is an expensive operation, preferably call it at level load time. No Spine.Atlas object is created so there is no way to find AtlasRegions except through the Attachments using them.</remarks> public static Skin GetRepackedSkin (this Skin o, string newName, Shader shader, out Material outputMaterial, out Texture2D outputTexture, int maxAtlasSize = 1024, int padding = 2, TextureFormat textureFormat = SpineTextureFormat, bool mipmaps = UseMipMaps, Material materialPropertySource = null, bool clearCache = false, bool useOriginalNonrenderables = true) { if (o == null) throw new System.NullReferenceException("Skin was null"); var skinAttachments = o.Attachments; var newSkin = new Skin(newName); // Use these to detect and use shared regions. var existingRegions = new Dictionary<AtlasRegion, int>(); var regionIndexes = new List<int>(); // Collect all textures from the attachments of the original skin. var repackedAttachments = new List<Attachment>(); var texturesToPack = new List<Texture2D>(); var originalRegions = new List<AtlasRegion>(); int newRegionIndex = 0; foreach (var skinEntry in skinAttachments) { var originalKey = skinEntry.Key; var originalAttachment = skinEntry.Value; Attachment newAttachment; if (IsRenderable(originalAttachment)) { newAttachment = originalAttachment.GetClone(true); var region = newAttachment.GetRegion(); int existingIndex; if (existingRegions.TryGetValue(region, out existingIndex)) { regionIndexes.Add(existingIndex); // Store the region index for the eventual new attachment. } else { originalRegions.Add(region); texturesToPack.Add(region.ToTexture()); // Add the texture to the PackTextures argument existingRegions.Add(region, newRegionIndex); // Add the region to the dictionary of known regions regionIndexes.Add(newRegionIndex); // Store the region index for the eventual new attachment. newRegionIndex++; } repackedAttachments.Add(newAttachment); newSkin.AddAttachment(originalKey.slotIndex, originalKey.name, newAttachment); } else { newSkin.AddAttachment(originalKey.slotIndex, originalKey.name, useOriginalNonrenderables ? originalAttachment : originalAttachment.GetClone(true)); } } // Fill a new texture with the collected attachment textures. var newTexture = new Texture2D(maxAtlasSize, maxAtlasSize, textureFormat, mipmaps); newTexture.mipMapBias = AtlasUtilities.DefaultMipmapBias; newTexture.anisoLevel = texturesToPack[0].anisoLevel; newTexture.name = newName; var rects = newTexture.PackTextures(texturesToPack.ToArray(), padding, maxAtlasSize); // Rehydrate the repacked textures as a Material, Spine atlas and Spine.AtlasAttachments var newMaterial = new Material(shader); if (materialPropertySource != null) { newMaterial.CopyPropertiesFromMaterial(materialPropertySource); newMaterial.shaderKeywords = materialPropertySource.shaderKeywords; } newMaterial.name = newName; newMaterial.mainTexture = newTexture; var page = newMaterial.ToSpineAtlasPage(); page.name = newName; var repackedRegions = new List<AtlasRegion>(); for (int i = 0, n = originalRegions.Count; i < n; i++) { var oldRegion = originalRegions[i]; var newRegion = UVRectToAtlasRegion(rects[i], oldRegion.name, page, oldRegion.offsetX, oldRegion.offsetY, oldRegion.rotate); repackedRegions.Add(newRegion); } // Map the cloned attachments to the repacked atlas. for (int i = 0, n = repackedAttachments.Count; i < n; i++) { var a = repackedAttachments[i]; if (IsRenderable(a)) a.SetRegion(repackedRegions[regionIndexes[i]]); } // Clean up. if (clearCache) AtlasUtilities.ClearCache(); outputTexture = newTexture; outputMaterial = newMaterial; return newSkin; } public static Sprite ToSprite (this AtlasRegion ar, float pixelsPerUnit = 100) { return Sprite.Create(ar.GetMainTexture(), ar.GetUnityRect(), new Vector2(0.5f, 0.5f), pixelsPerUnit); } static Dictionary<AtlasRegion, Texture2D> CachedRegionTextures = new Dictionary<AtlasRegion, Texture2D>(); static List<Texture2D> CachedRegionTexturesList = new List<Texture2D>(); public static void ClearCache () { foreach (var t in CachedRegionTexturesList) { UnityEngine.Object.Destroy(t); } CachedRegionTextures.Clear(); CachedRegionTexturesList.Clear(); } /// <summary>Creates a new Texture2D object based on an AtlasRegion. /// If applyImmediately is true, Texture2D.Apply is called immediately after the Texture2D is filled with data.</summary> public static Texture2D ToTexture (this AtlasRegion ar, TextureFormat textureFormat = SpineTextureFormat, bool mipmaps = UseMipMaps) { Texture2D output; CachedRegionTextures.TryGetValue(ar, out output); if (output == null) { Texture2D sourceTexture = ar.GetMainTexture(); Rect r = ar.GetUnityRect(sourceTexture.height); int width = (int)r.width; int height = (int)r.height; output = new Texture2D(width, height, textureFormat, mipmaps) { name = ar.name }; AtlasUtilities.CopyTexture(sourceTexture, r, output); CachedRegionTextures.Add(ar, output); CachedRegionTexturesList.Add(output); } return output; } static Texture2D ToTexture (this Sprite s, TextureFormat textureFormat = SpineTextureFormat, bool mipmaps = UseMipMaps) { var spriteTexture = s.texture; var r = s.textureRect; var newTexture = new Texture2D((int)r.width, (int)r.height, textureFormat, mipmaps); AtlasUtilities.CopyTexture(spriteTexture, r, newTexture); return newTexture; } static Texture2D GetClone (this Texture2D t, TextureFormat textureFormat = SpineTextureFormat, bool mipmaps = UseMipMaps) { var newTexture = new Texture2D((int)t.width, (int)t.height, textureFormat, mipmaps); AtlasUtilities.CopyTexture(t, new Rect(0, 0, t.width, t.height), newTexture); return newTexture; } static void CopyTexture (Texture2D source, Rect sourceRect, Texture2D destination) { if (SystemInfo.copyTextureSupport == UnityEngine.Rendering.CopyTextureSupport.None) { // GetPixels fallback for old devices. Color[] pixelBuffer = source.GetPixels((int)sourceRect.x, (int)sourceRect.y, (int)sourceRect.width, (int)sourceRect.height); destination.SetPixels(pixelBuffer); destination.Apply(); } else { Graphics.CopyTexture(source, 0, 0, (int)sourceRect.x, (int)sourceRect.y, (int)sourceRect.width, (int)sourceRect.height, destination, 0, 0, 0, 0); } } static bool IsRenderable (Attachment a) { return a is IHasRendererObject; } /// <summary> /// Get a rect with flipped Y so that a Spine atlas rect gets converted to a Unity Sprite rect and vice versa.</summary> static Rect SpineUnityFlipRect (this Rect rect, int textureHeight) { rect.y = textureHeight - rect.y - rect.height; return rect; } /// <summary> /// Gets the Rect of an AtlasRegion according to Unity texture coordinates (x-right, y-up). /// This overload relies on region.page.height being correctly set.</summary> static Rect GetUnityRect (this AtlasRegion region) { return region.GetSpineAtlasRect().SpineUnityFlipRect(region.page.height); } /// <summary> /// Gets the Rect of an AtlasRegion according to Unity texture coordinates (x-right, y-up).</summary> static Rect GetUnityRect (this AtlasRegion region, int textureHeight) { return region.GetSpineAtlasRect().SpineUnityFlipRect(textureHeight); } /// <summary> /// Returns a Rect of the AtlasRegion according to Spine texture coordinates. (x-right, y-down)</summary> static Rect GetSpineAtlasRect (this AtlasRegion region, bool includeRotate = true) { if (includeRotate && region.rotate) return new Rect(region.x, region.y, region.height, region.width); else return new Rect(region.x, region.y, region.width, region.height); } /// <summary> /// Denormalize a uvRect into a texture-space Rect.</summary> static Rect UVRectToTextureRect (Rect uvRect, int texWidth, int texHeight) { uvRect.x *= texWidth; uvRect.width *= texWidth; uvRect.y *= texHeight; uvRect.height *= texHeight; return uvRect; } /// <summary> /// Normalize a texture Rect into UV coordinates.</summary> static Rect TextureRectToUVRect (Rect textureRect, int texWidth, int texHeight) { textureRect.x = Mathf.InverseLerp(0, texWidth, textureRect.x); textureRect.y = Mathf.InverseLerp(0, texHeight, textureRect.y); textureRect.width = Mathf.InverseLerp(0, texWidth, textureRect.width); textureRect.height = Mathf.InverseLerp(0, texHeight, textureRect.height); return textureRect; } /// <summary> /// Creates a new Spine AtlasRegion according to a Unity UV Rect (x-right, y-up, uv-normalized).</summary> static AtlasRegion UVRectToAtlasRegion (Rect uvRect, string name, AtlasPage page, float offsetX, float offsetY, bool rotate) { var tr = UVRectToTextureRect(uvRect, page.width, page.height); var rr = tr.SpineUnityFlipRect(page.height); int x = (int)rr.x, y = (int)rr.y; int w, h; if (rotate) { w = (int)rr.height; h = (int)rr.width; } else { w = (int)rr.width; h = (int)rr.height; } return new AtlasRegion { page = page, name = name, u = uvRect.xMin, u2 = uvRect.xMax, v = uvRect.yMax, v2 = uvRect.yMin, index = -1, width = w, originalWidth = w, height = h, originalHeight = h, offsetX = offsetX, offsetY = offsetY, x = x, y = y, rotate = rotate }; } /// <summary> /// Convenience method for getting the main texture of the material of the page of the region.</summary> static Texture2D GetMainTexture (this AtlasRegion region) { var material = (region.page.rendererObject as Material); return material.mainTexture as Texture2D; } static void ApplyPMA (this Texture2D texture, bool applyImmediately = true) { var pixels = texture.GetPixels(); for (int i = 0, n = pixels.Length; i < n; i++) { Color p = pixels[i]; float a = p.a; p.r = p.r * a; p.g = p.g * a; p.b = p.b * a; pixels[i] = p; } texture.SetPixels(pixels); if (applyImmediately) texture.Apply(); } #endregion static float InverseLerp (float a, float b, float value) { return (value - a) / (b - a); } } public static class SkinUtilities { #region Skeleton Skin Extensions /// <summary> /// Convenience method for duplicating a skeleton's current active skin so changes to it will not affect other skeleton instances. .</summary> public static Skin UnshareSkin (this Skeleton skeleton, bool includeDefaultSkin, bool unshareAttachments, AnimationState state = null) { // 1. Copy the current skin and set the skeleton's skin to the new one. var newSkin = skeleton.GetClonedSkin("cloned skin", includeDefaultSkin, unshareAttachments, true); skeleton.SetSkin(newSkin); // 2. Apply correct attachments: skeleton.SetToSetupPose + animationState.Apply if (state != null) { skeleton.SetToSetupPose(); state.Apply(skeleton); } // 3. Return unshared skin. return newSkin; } public static Skin GetClonedSkin (this Skeleton skeleton, string newSkinName, bool includeDefaultSkin = false, bool cloneAttachments = false, bool cloneMeshesAsLinked = true) { var newSkin = new Skin(newSkinName); // may have null name. Harmless. var defaultSkin = skeleton.data.DefaultSkin; var activeSkin = skeleton.skin; if (includeDefaultSkin) defaultSkin.CopyTo(newSkin, true, cloneAttachments, cloneMeshesAsLinked); if (activeSkin != null) activeSkin.CopyTo(newSkin, true, cloneAttachments, cloneMeshesAsLinked); return newSkin; } #endregion /// <summary> /// Gets a shallow copy of the skin. The cloned skin's attachments are shared with the original skin.</summary> public static Skin GetClone (this Skin original) { var newSkin = new Skin(original.name + " clone"); var newSkinAttachments = newSkin.Attachments; foreach (var a in original.Attachments) newSkinAttachments[a.Key] = a.Value; return newSkin; } /// <summary>Adds an attachment to the skin for the specified slot index and name. If the name already exists for the slot, the previous value is replaced.</summary> public static void SetAttachment (this Skin skin, string slotName, string keyName, Attachment attachment, Skeleton skeleton) { int slotIndex = skeleton.FindSlotIndex(slotName); if (skeleton == null) throw new System.ArgumentNullException("skeleton", "skeleton cannot be null."); if (slotIndex == -1) throw new System.ArgumentException(string.Format("Slot '{0}' does not exist in skeleton.", slotName), "slotName"); skin.AddAttachment(slotIndex, keyName, attachment); } /// <summary>Adds skin items from another skin. For items that already exist, the previous values are replaced.</summary> public static void AddAttachments (this Skin skin, Skin otherSkin) { if (otherSkin == null) return; otherSkin.CopyTo(skin, true, false); } /// <summary>Gets an attachment from the skin for the specified slot index and name.</summary> public static Attachment GetAttachment (this Skin skin, string slotName, string keyName, Skeleton skeleton) { int slotIndex = skeleton.FindSlotIndex(slotName); if (skeleton == null) throw new System.ArgumentNullException("skeleton", "skeleton cannot be null."); if (slotIndex == -1) throw new System.ArgumentException(string.Format("Slot '{0}' does not exist in skeleton.", slotName), "slotName"); return skin.GetAttachment(slotIndex, keyName); } /// <summary>Adds an attachment to the skin for the specified slot index and name. If the name already exists for the slot, the previous value is replaced.</summary> public static void SetAttachment (this Skin skin, int slotIndex, string keyName, Attachment attachment) { skin.AddAttachment(slotIndex, keyName, attachment); } public static void RemoveAttachment (this Skin skin, string slotName, string keyName, SkeletonData skeletonData) { int slotIndex = skeletonData.FindSlotIndex(slotName); if (skeletonData == null) throw new System.ArgumentNullException("skeletonData", "skeletonData cannot be null."); if (slotIndex == -1) throw new System.ArgumentException(string.Format("Slot '{0}' does not exist in skeleton.", slotName), "slotName"); skin.RemoveAttachment(slotIndex, keyName); } public static void Clear (this Skin skin) { skin.Attachments.Clear(); } //[System.Obsolete] public static void Append (this Skin destination, Skin source) { source.CopyTo(destination, true, false); } public static void CopyTo (this Skin source, Skin destination, bool overwrite, bool cloneAttachments, bool cloneMeshesAsLinked = true) { var sourceAttachments = source.Attachments; var destinationAttachments = destination.Attachments; if (cloneAttachments) { if (overwrite) { foreach (var e in sourceAttachments) destinationAttachments[e.Key] = e.Value.GetClone(cloneMeshesAsLinked); } else { foreach (var e in sourceAttachments) { if (destinationAttachments.ContainsKey(e.Key)) continue; destinationAttachments.Add(e.Key, e.Value.GetClone(cloneMeshesAsLinked)); } } } else { if (overwrite) { foreach (var e in sourceAttachments) destinationAttachments[e.Key] = e.Value; } else { foreach (var e in sourceAttachments) { if (destinationAttachments.ContainsKey(e.Key)) continue; destinationAttachments.Add(e.Key, e.Value); } } } } } public static class AttachmentCloneExtensions { /// <summary> /// Clones the attachment.</summary> public static Attachment GetClone (this Attachment o, bool cloneMeshesAsLinked) { var regionAttachment = o as RegionAttachment; if (regionAttachment != null) return regionAttachment.GetClone(); var meshAttachment = o as MeshAttachment; if (meshAttachment != null) return cloneMeshesAsLinked ? meshAttachment.GetLinkedClone() : meshAttachment.GetClone(); var boundingBoxAttachment = o as BoundingBoxAttachment; if (boundingBoxAttachment != null) return boundingBoxAttachment.GetClone(); var pathAttachment = o as PathAttachment; if (pathAttachment != null) return pathAttachment.GetClone(); var pointAttachment = o as PointAttachment; if (pointAttachment != null) return pointAttachment.GetClone(); var clippingAttachment = o as ClippingAttachment; if (clippingAttachment != null) return clippingAttachment.GetClone(); return null; } public static RegionAttachment GetClone (this RegionAttachment o) { return new RegionAttachment(o.Name) { x = o.x, y = o.y, rotation = o.rotation, scaleX = o.scaleX, scaleY = o.scaleY, width = o.width, height = o.height, r = o.r, g = o.g, b = o.b, a = o.a, Path = o.Path, RendererObject = o.RendererObject, regionOffsetX = o.regionOffsetX, regionOffsetY = o.regionOffsetY, regionWidth = o.regionWidth, regionHeight = o.regionHeight, regionOriginalWidth = o.regionOriginalWidth, regionOriginalHeight = o.regionOriginalHeight, uvs = o.uvs.Clone() as float[], offset = o.offset.Clone() as float[] }; } public static ClippingAttachment GetClone (this ClippingAttachment o) { var ca = new ClippingAttachment(o.Name) { endSlot = o.endSlot }; CloneVertexAttachment(o, ca); return ca; } public static PointAttachment GetClone (this PointAttachment o) { var pa = new PointAttachment(o.Name) { rotation = o.rotation, x = o.x, y = o.y }; return pa; } public static BoundingBoxAttachment GetClone (this BoundingBoxAttachment o) { var ba = new BoundingBoxAttachment(o.Name); CloneVertexAttachment(o, ba); return ba; } public static MeshAttachment GetLinkedClone (this MeshAttachment o, bool inheritDeform = true) { return o.GetLinkedMesh(o.Name, o.RendererObject as AtlasRegion, inheritDeform, copyOriginalProperties: true); } /// <summary> /// Returns a clone of the MeshAttachment. This will cause Deform animations to stop working unless you explicity set the .parentMesh to the original.</summary> public static MeshAttachment GetClone (this MeshAttachment o) { var ma = new MeshAttachment(o.Name) { r = o.r, g = o.g, b = o.b, a = o.a, inheritDeform = o.inheritDeform, Path = o.Path, RendererObject = o.RendererObject, regionOffsetX = o.regionOffsetX, regionOffsetY = o.regionOffsetY, regionWidth = o.regionWidth, regionHeight = o.regionHeight, regionOriginalWidth = o.regionOriginalWidth, regionOriginalHeight = o.regionOriginalHeight, RegionU = o.RegionU, RegionV = o.RegionV, RegionU2 = o.RegionU2, RegionV2 = o.RegionV2, RegionRotate = o.RegionRotate, uvs = o.uvs.Clone() as float[] }; // Linked mesh if (o.ParentMesh != null) { // bones, vertices, worldVerticesLength, regionUVs, triangles, HullLength, Edges, Width, Height ma.ParentMesh = o.ParentMesh; } else { CloneVertexAttachment(o, ma); // bones, vertices, worldVerticesLength ma.regionUVs = o.regionUVs.Clone() as float[]; ma.triangles = o.triangles.Clone() as int[]; ma.hulllength = o.hulllength; // Nonessential. ma.Edges = (o.Edges == null) ? null : o.Edges.Clone() as int[]; // Allow absence of Edges array when nonessential data is not exported. ma.Width = o.Width; ma.Height = o.Height; } return ma; } public static PathAttachment GetClone (this PathAttachment o) { var newPathAttachment = new PathAttachment(o.Name) { lengths = o.lengths.Clone() as float[], closed = o.closed, constantSpeed = o.constantSpeed }; CloneVertexAttachment(o, newPathAttachment); return newPathAttachment; } static void CloneVertexAttachment (VertexAttachment src, VertexAttachment dest) { dest.worldVerticesLength = src.worldVerticesLength; if (src.bones != null) dest.bones = src.bones.Clone() as int[]; if (src.vertices != null) dest.vertices = src.vertices.Clone() as float[]; } #region Runtime Linked MeshAttachments /// <summary> /// Returns a new linked mesh linked to this MeshAttachment. It will be mapped to the AtlasRegion provided.</summary> public static MeshAttachment GetLinkedMesh (this MeshAttachment o, string newLinkedMeshName, AtlasRegion region, bool inheritDeform = true, bool copyOriginalProperties = false) { //if (string.IsNullOrEmpty(attachmentName)) throw new System.ArgumentException("attachmentName cannot be null or empty", "attachmentName"); if (region == null) throw new System.ArgumentNullException("region"); // If parentMesh is a linked mesh, create a link to its parent. Preserves Deform animations. if (o.ParentMesh != null) o = o.ParentMesh; // 1. NewMeshAttachment (AtlasAttachmentLoader.cs) var mesh = new MeshAttachment(newLinkedMeshName); mesh.SetRegion(region, false); // 2. (SkeletonJson.cs::ReadAttachment. case: LinkedMesh) mesh.Path = newLinkedMeshName; if (copyOriginalProperties) { mesh.r = o.r; mesh.g = o.g; mesh.b = o.b; mesh.a = o.a; } else { mesh.r = 1f; mesh.g = 1f; mesh.b = 1f; mesh.a = 1f; } //mesh.ParentMesh property call below sets mesh.Width and mesh.Height // 3. Link mesh with parent. (SkeletonJson.cs) mesh.inheritDeform = inheritDeform; mesh.ParentMesh = o; mesh.UpdateUVs(); return mesh; } /// <summary> /// Returns a new linked mesh linked to this MeshAttachment. It will be mapped to an AtlasRegion generated from a Sprite. The AtlasRegion will be mapped to a new Material based on the shader. /// For better caching and batching, use GetLinkedMesh(string, AtlasRegion, bool)</summary> public static MeshAttachment GetLinkedMesh (this MeshAttachment o, Sprite sprite, Shader shader, bool inheritDeform = true, Material materialPropertySource = null) { var m = new Material(shader); if (materialPropertySource != null) { m.CopyPropertiesFromMaterial(materialPropertySource); m.shaderKeywords = materialPropertySource.shaderKeywords; } return o.GetLinkedMesh(sprite.name, sprite.ToAtlasRegion(), inheritDeform); } /// <summary> /// Returns a new linked mesh linked to this MeshAttachment. It will be mapped to an AtlasRegion generated from a Sprite. The AtlasRegion will be mapped to a new Material based on the shader. /// For better caching and batching, use GetLinkedMesh(string, AtlasRegion, bool)</summary> public static MeshAttachment GetLinkedMesh (this MeshAttachment o, Sprite sprite, Material materialPropertySource, bool inheritDeform = true) { return o.GetLinkedMesh(sprite, materialPropertySource.shader, inheritDeform, materialPropertySource); } #endregion #region RemappedClone Convenience Methods /// <summary> /// Gets a clone of the attachment remapped with a sprite image.</summary> /// <returns>The remapped clone.</returns> /// <param name="o">The original attachment.</param> /// <param name="sprite">The sprite whose texture to use.</param> /// <param name="sourceMaterial">The source material used to copy the shader and material properties from.</param> /// <param name="premultiplyAlpha">If <c>true</c>, a premultiply alpha clone of the original texture will be created.</param> /// <param name="cloneMeshAsLinked">If <c>true</c> MeshAttachments will be cloned as linked meshes and will inherit animation from the original attachment.</param> /// <param name="useOriginalRegionSize">If <c>true</c> the size of the original attachment will be followed, instead of using the Sprite size.</param> public static Attachment GetRemappedClone (this Attachment o, Sprite sprite, Material sourceMaterial, bool premultiplyAlpha = true, bool cloneMeshAsLinked = true, bool useOriginalRegionSize = false) { var atlasRegion = premultiplyAlpha ? sprite.ToAtlasRegionPMAClone(sourceMaterial) : sprite.ToAtlasRegion(new Material(sourceMaterial) { mainTexture = sprite.texture } ); return o.GetRemappedClone(atlasRegion, cloneMeshAsLinked, useOriginalRegionSize, 1f/sprite.pixelsPerUnit); } /// <summary> /// Gets a clone of the attachment remapped with an atlasRegion image.</summary> /// <returns>The remapped clone.</returns> /// <param name="o">The original attachment.</param> /// <param name="atlasRegion">Atlas region.</param> /// <param name="cloneMeshAsLinked">If <c>true</c> MeshAttachments will be cloned as linked meshes and will inherit animation from the original attachment.</param> /// <param name="useOriginalRegionSize">If <c>true</c> the size of the original attachment will be followed, instead of using the Sprite size.</param> /// <param name="scale">Unity units per pixel scale used to scale the atlas region size when not using the original region size.</param> public static Attachment GetRemappedClone (this Attachment o, AtlasRegion atlasRegion, bool cloneMeshAsLinked = true, bool useOriginalRegionSize = false, float scale = 0.01f) { var regionAttachment = o as RegionAttachment; if (regionAttachment != null) { RegionAttachment newAttachment = regionAttachment.GetClone(); newAttachment.SetRegion(atlasRegion, false); if (!useOriginalRegionSize) { newAttachment.width = atlasRegion.width * scale; newAttachment.height = atlasRegion.height * scale; } newAttachment.UpdateOffset(); return newAttachment; } else { var meshAttachment = o as MeshAttachment; if (meshAttachment != null) { MeshAttachment newAttachment = cloneMeshAsLinked ? meshAttachment.GetLinkedClone(cloneMeshAsLinked) : meshAttachment.GetClone(); newAttachment.SetRegion(atlasRegion); return newAttachment; } } return o.GetClone(true); // Non-renderable Attachments will return as normal cloned attachments. } #endregion } }
42.903169
438
0.730395
[ "MIT" ]
daonq/unity_game
Assets/Spine/Runtime/spine-unity/Modules/AttachmentTools/AttachmentTools.cs
48,738
C#
using Marten.Services; using Marten.Testing.Documents; using Marten.Testing.Harness; using Xunit; namespace DocumentDbTests.Bugs { public class Bug_237_duplicate_indexing_Tests: BugIntegrationContext { [Fact] public void save() { StoreOptions(_ => { _.Schema.For<Issue>() .Duplicate(x => x.AssigneeId) .ForeignKey<User>(x => x.AssigneeId); }); theSession.Store(new Issue()); theSession.SaveChanges(); } } }
21.615385
72
0.551601
[ "MIT" ]
Rob89/marten
src/DocumentDbTests/Bugs/Bug_237_duplicate_indexing_Tests.cs
562
C#
using System.Threading.Tasks; using Disqord.Gateway.Api; using Disqord.Gateway.Api.Models; namespace Disqord.Gateway.Default.Dispatcher { public class MessageReactionAddHandler : Handler<MessageReactionAddJsonModel, ReactionAddedEventArgs> { public override ValueTask<ReactionAddedEventArgs> HandleDispatchAsync(IGatewayApiClient shard, MessageReactionAddJsonModel model) { CachedUserMessage message; IMember member = null; if (CacheProvider.TryGetMessages(model.ChannelId, out var messageCache)) { message = messageCache.GetValueOrDefault(model.MessageId); message?.Update(model); } else { message = null; } if (model.GuildId.HasValue) { member = Dispatcher.GetOrAddMember(model.GuildId.Value, model.Member.Value); if (member == null) member = new TransientMember(Client, model.GuildId.Value, model.Member.Value); } var e = new ReactionAddedEventArgs(model.UserId, model.ChannelId, model.MessageId, message, model.GuildId.GetValueOrNullable(), member, Emoji.Create(model.Emoji)); return new(e); } } }
38.057143
176
0.60961
[ "MIT" ]
Neuheit/Diqnod
src/Disqord.Gateway/Default/Dispatcher/Dispatches/Reaction/MESSAGE_REACTION_ADD.cs
1,334
C#
using BPP.Core.Models; using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Metadata.Builders; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace BPP.Data.Seeds { class ProductSeed : IEntityTypeConfiguration<Product> { private readonly int[] _ids; public ProductSeed(int[] ids) { _ids = ids; } public void Configure(EntityTypeBuilder<Product> builder) { builder.HasData( new Product { Id = 1, Name = "Trampet", Price = 120.50m, Stock = 20, IsActive = true, CategoryId = _ids[1] }, new Product { Id = 2, Name = "Klasık Gıtar", Price = 220.50m, Stock = 15, IsActive = false, CategoryId = _ids[0] }, new Product { Id = 3, Name = "Elektro Gıtar", Price = 137.53m, Stock = 10, IsActive = true, CategoryId = _ids[0] }, new Product { Id = 4, Name = "Baglama", Price = 99.50m, Stock = 20, IsActive = true, CategoryId = _ids[0] }, new Product { Id = 5, Name = "Blok Flut", Price = 15.50m, Stock = 20, IsActive = true, CategoryId = _ids[2] } ); } } }
38.34375
131
0.597392
[ "MIT" ]
tunahanaydinoglu/BPPattern-Core5-API
BPP.Data/Seeds/ProductSeed.cs
1,232
C#
// This file is part of YamlDotNet - A .NET library for YAML. // Copyright (c) Antoine Aubry and contributors // Permission is hereby granted, free of charge, to any person obtaining a copy of // this software and associated documentation files (the "Software"), to deal in // the Software without restriction, including without limitation the rights to // use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies // of the Software, and to permit persons to whom the Software is furnished to do // so, subject to the following conditions: // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. using System; using System.Collections; using System.Collections.Generic; using System.Globalization; using System.Linq; using System.Reflection; using System.Text.RegularExpressions; namespace YamlDotNet { #if (NETSTANDARD1_3 || UNITY) internal static class StandardRegexOptions { public const RegexOptions Compiled = RegexOptions.None; } #else internal static class StandardRegexOptions { public const RegexOptions Compiled = RegexOptions.Compiled; } #endif #if NETSTANDARD1_3 internal static class ReflectionExtensions { public static Type BaseType(this Type type) { return type.GetTypeInfo().BaseType; } public static bool IsValueType(this Type type) { return type.GetTypeInfo().IsValueType; } public static bool IsGenericType(this Type type) { return type.GetTypeInfo().IsGenericType; } public static bool IsInterface(this Type type) { return type.GetTypeInfo().IsInterface; } public static bool IsEnum(this Type type) { return type.GetTypeInfo().IsEnum; } /// <summary> /// Determines whether the specified type has a default constructor. /// </summary> /// <param name="type">The type.</param> /// <returns> /// <c>true</c> if the type has a default constructor; otherwise, <c>false</c>. /// </returns> public static bool HasDefaultConstructor(this Type type) { var typeInfo = type.GetTypeInfo(); return typeInfo.IsValueType || typeInfo.DeclaredConstructors .Any(c => c.IsPublic && !c.IsStatic && c.GetParameters().Length == 0); } public static bool IsAssignableFrom(this Type type, Type source) { return type.IsAssignableFrom(source.GetTypeInfo()); } public static bool IsAssignableFrom(this Type type, TypeInfo source) { return type.GetTypeInfo().IsAssignableFrom(source); } public static TypeCode GetTypeCode(this Type type) { bool isEnum = type.IsEnum(); if (isEnum) { type = Enum.GetUnderlyingType(type); } if (type == typeof(bool)) { return TypeCode.Boolean; } else if (type == typeof(char)) { return TypeCode.Char; } else if (type == typeof(sbyte)) { return TypeCode.SByte; } else if (type == typeof(byte)) { return TypeCode.Byte; } else if (type == typeof(short)) { return TypeCode.Int16; } else if (type == typeof(ushort)) { return TypeCode.UInt16; } else if (type == typeof(int)) { return TypeCode.Int32; } else if (type == typeof(uint)) { return TypeCode.UInt32; } else if (type == typeof(long)) { return TypeCode.Int64; } else if (type == typeof(ulong)) { return TypeCode.UInt64; } else if (type == typeof(float)) { return TypeCode.Single; } else if (type == typeof(double)) { return TypeCode.Double; } else if (type == typeof(decimal)) { return TypeCode.Decimal; } else if (type == typeof(DateTime)) { return TypeCode.DateTime; } else if (type == typeof(String)) { return TypeCode.String; } else { return TypeCode.Object; } } public static bool IsDbNull(this object value) { return value?.GetType()?.FullName == "System.DBNull"; } public static Type[] GetGenericArguments(this Type type) { return type.GetTypeInfo().GenericTypeArguments; } public static PropertyInfo GetPublicProperty(this Type type, string name) { return type.GetRuntimeProperty(name); } public static IEnumerable<PropertyInfo> GetPublicProperties(this Type type) { var instancePublic = new Func<PropertyInfo, bool>( p => !p.GetMethod.IsStatic && p.GetMethod.IsPublic); return type.IsInterface() ? (new Type[] { type }) .Concat(type.GetInterfaces()) .SelectMany(i => i.GetRuntimeProperties().Where(instancePublic)) : type.GetRuntimeProperties().Where(instancePublic); } public static IEnumerable<MethodInfo> GetPublicStaticMethods(this Type type) { return type.GetRuntimeMethods() .Where(m => m.IsPublic && m.IsStatic); } public static MethodInfo GetPublicStaticMethod(this Type type, string name, params Type[] parameterTypes) { return type.GetRuntimeMethods() .FirstOrDefault(m => { if (m.IsPublic && m.IsStatic && m.Name.Equals(name)) { var parameters = m.GetParameters(); return parameters.Length == parameterTypes.Length && parameters.Zip(parameterTypes, (pi, pt) => pi.ParameterType == pt).All(r => r); } return false; }); } public static MethodInfo GetPublicInstanceMethod(this Type type, string name) { return type.GetRuntimeMethods() .FirstOrDefault(m => m.IsPublic && !m.IsStatic && m.Name.Equals(name)); } public static MethodInfo GetGetMethod(this PropertyInfo property) { return property.GetMethod; } public static MethodInfo GetSetMethod(this PropertyInfo property) { return property.SetMethod; } public static IEnumerable<Type> GetInterfaces(this Type type) { return type.GetTypeInfo().ImplementedInterfaces; } public static Exception Unwrap(this TargetInvocationException ex) { return ex.InnerException; } public static bool IsInstanceOf(this Type type, object o) { return o.GetType() == type || o.GetType().GetTypeInfo().IsSubclassOf(type); } } internal sealed class CultureInfoAdapter : CultureInfo { private readonly IFormatProvider _provider; public CultureInfoAdapter(CultureInfo baseCulture, IFormatProvider provider) : base(baseCulture.Name) { _provider = provider; } public override object GetFormat(Type formatType) { return _provider.GetFormat(formatType); } } #else internal static class ReflectionExtensions { public static Type BaseType(this Type type) { return type.BaseType; } public static bool IsValueType(this Type type) { return type.IsValueType; } public static bool IsGenericType(this Type type) { return type.IsGenericType; } public static bool IsInterface(this Type type) { return type.IsInterface; } public static bool IsEnum(this Type type) { return type.IsEnum; } public static bool IsDbNull(this object value) { return value is DBNull; } /// <summary> /// Determines whether the specified type has a default constructor. /// </summary> /// <param name="type">The type.</param> /// <returns> /// <c>true</c> if the type has a default constructor; otherwise, <c>false</c>. /// </returns> public static bool HasDefaultConstructor(this Type type) { return type.IsValueType || type.GetConstructor(BindingFlags.Public | BindingFlags.Instance, null, Type.EmptyTypes, null) != null; } public static TypeCode GetTypeCode(this Type type) { return Type.GetTypeCode(type); } public static PropertyInfo GetPublicProperty(this Type type, string name) { return type.GetProperty(name); } public static IEnumerable<PropertyInfo> GetPublicProperties(this Type type) { var instancePublic = BindingFlags.Instance | BindingFlags.Public; return type.IsInterface ? (new Type[] { type }) .Concat(type.GetInterfaces()) .SelectMany(i => i.GetProperties(instancePublic)) : type.GetProperties(instancePublic); } public static IEnumerable<MethodInfo> GetPublicStaticMethods(this Type type) { return type.GetMethods(BindingFlags.Static | BindingFlags.Public); } public static MethodInfo GetPublicStaticMethod(this Type type, string name, params Type[] parameterTypes) { return type.GetMethod(name, BindingFlags.Public | BindingFlags.Static, null, parameterTypes, null); } public static MethodInfo GetPublicInstanceMethod(this Type type, string name) { return type.GetMethod(name, BindingFlags.Public | BindingFlags.Instance); } private static readonly FieldInfo remoteStackTraceField = typeof(Exception) .GetField("_remoteStackTraceString", BindingFlags.Instance | BindingFlags.NonPublic); public static Exception Unwrap(this TargetInvocationException ex) { var result = ex.InnerException; if (remoteStackTraceField != null) { remoteStackTraceField.SetValue(ex.InnerException, ex.InnerException.StackTrace + "\r\n"); } return result; } public static bool IsInstanceOf(this Type type, object o) { return type.IsInstanceOfType(o); } } internal sealed class CultureInfoAdapter : CultureInfo { private readonly IFormatProvider _provider; public CultureInfoAdapter(CultureInfo baseCulture, IFormatProvider provider) : base(baseCulture.LCID) { _provider = provider; } public override object GetFormat(Type formatType) { return _provider.GetFormat(formatType); } } #endif #if UNITY internal static class PropertyInfoExtensions { public static object ReadValue(this PropertyInfo property, object target) { return property.GetGetMethod().Invoke(target, null); } } #else internal static class PropertyInfoExtensions { public static object ReadValue(this PropertyInfo property, object target) { return property.GetValue(target, null); } } #endif } #if NET20 namespace System.Runtime.CompilerServices { [AttributeUsage(AttributeTargets.Assembly | AttributeTargets.Class | AttributeTargets.Method)] internal sealed class ExtensionAttribute : Attribute { } } namespace YamlDotNet // To allow these to be public without clashing with the standard ones on platforms > 2.0 { public delegate TResult Func<TArg, TResult>(TArg arg); public delegate TResult Func<TArg1, TArg2, TResult>(TArg1 arg1, TArg2 arg2); public delegate TResult Func<TArg1, TArg2, TArg3, TResult>(TArg1 arg1, TArg2 arg2, TArg3 arg3); } namespace System.Linq.Expressions { // Do not remove. // Avoids code breaking on .NET 2.0 due to using System.Linq.Expressions. } namespace System.Linq { using YamlDotNet; internal static class Enumerable { public static List<T> ToList<T>(this IEnumerable<T> sequence) { return new List<T>(sequence); } public static T[] ToArray<T>(this IEnumerable<T> sequence) { return sequence.ToList().ToArray(); } public static IEnumerable<T> OrderBy<T, TKey>(this IEnumerable<T> sequence, Func<T, TKey> orderBy) { var comparer = Comparer<TKey>.Default; var list = sequence.ToList(); list.Sort((a, b) => comparer.Compare(orderBy(a), orderBy(b))); return list; } public static IEnumerable<T> Empty<T>() { yield break; } public static IEnumerable<T> Where<T>(this IEnumerable<T> sequence, Func<T, bool> predicate) { foreach (var item in sequence) { if (predicate(item)) { yield return item; } } } public static IEnumerable<T2> Select<T1, T2>(this IEnumerable<T1> sequence, Func<T1, T2> selector) { foreach (var item in sequence) { yield return selector(item); } } public static IEnumerable<T> OfType<T>(this IEnumerable sequence) { foreach (var item in sequence) { if (item is T) { yield return (T)item; } } } public static IEnumerable<T2> SelectMany<T1, T2>(this IEnumerable<T1> sequence, Func<T1, IEnumerable<T2>> selector) { foreach (var item in sequence) { foreach (var subitem in selector(item)) { yield return subitem; } } } public static T First<T>(this IEnumerable<T> sequence) { foreach (var item in sequence) { return item; } throw new InvalidOperationException(); } public static T FirstOrDefault<T>(this IEnumerable<T> sequence) { foreach (var item in sequence) { return item; } return default(T); } public static T SingleOrDefault<T>(this IEnumerable<T> sequence) { using (var enumerator = sequence.GetEnumerator()) { if (!enumerator.MoveNext()) { return default(T); } var result = enumerator.Current; if (enumerator.MoveNext()) { throw new InvalidOperationException(); } return result; } } public static T Single<T>(this IEnumerable<T> sequence) { using (var enumerator = sequence.GetEnumerator()) { if (!enumerator.MoveNext()) { throw new InvalidOperationException(); } var result = enumerator.Current; if (enumerator.MoveNext()) { throw new InvalidOperationException(); } return result; } } public static T FirstOrDefault<T>(this IEnumerable<T> sequence, Func<T, bool> predicate) { return sequence.Where(predicate).FirstOrDefault(); } public static IEnumerable<T> Concat<T>(this IEnumerable<T> first, IEnumerable<T> second) { foreach (var item in first) { yield return item; } foreach (var item in second) { yield return item; } } public static IEnumerable<T> Skip<T>(this IEnumerable<T> sequence, int skipCount) { foreach (var item in sequence) { if (skipCount <= 0) { yield return item; } else { --skipCount; } } } public static IEnumerable<T> SkipWhile<T>(this IEnumerable<T> sequence, Func<T, bool> predicate) { var skip = true; foreach (var item in sequence) { skip = skip && predicate(item); if (!skip) { yield return item; } } } public static IEnumerable<T> TakeWhile<T>(this IEnumerable<T> sequence, Func<T, bool> predicate) { var take = true; foreach (var item in sequence) { take = take && predicate(item); if (take) { yield return item; } } } public static IEnumerable<T> DefaultIfEmpty<T>(this IEnumerable<T> sequence, T defaultValue) { var isEmpty = true; foreach (var item in sequence) { yield return item; isEmpty = false; } if (isEmpty) { yield return defaultValue; } } public static bool Any<T>(this IEnumerable<T> sequence) { foreach (var item in sequence) { return true; } return false; } public static bool Any<T>(this IEnumerable<T> sequence, Func<T, bool> predicate) { return sequence.Where(predicate).Any(); } public static bool Contains<T>(this IEnumerable<T> sequence, T value) { foreach (var item in sequence) { if (item.Equals(value)) { return true; } } return false; } public static TSource Aggregate<TSource>(this IEnumerable<TSource> source, Func<TSource, TSource, TSource> func) { using (var enumerator = source.GetEnumerator()) { if (!enumerator.MoveNext()) { throw new InvalidOperationException(); } var accumulator = enumerator.Current; while (enumerator.MoveNext()) { accumulator = func(accumulator, enumerator.Current); } return accumulator; } } public static TAccumulate Aggregate<TSource, TAccumulate>(this IEnumerable<TSource> source, TAccumulate seed, Func<TAccumulate, TSource, TAccumulate> func) { var accumulator = seed; foreach (var item in source) { accumulator = func(accumulator, item); } return accumulator; } } } namespace System.Collections.Generic { internal class HashSet<T> : IEnumerable<T> { private readonly Dictionary<T, object> items = new Dictionary<T, object>(); public bool Add(T value) { if (Contains(value)) { return false; } else { items.Add(value, null); return true; } } public bool Contains(T value) { return items.ContainsKey(value); } public void Clear() { items.Clear(); } public IEnumerator<T> GetEnumerator() { return items.Keys.GetEnumerator(); } IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); } } } #endif #if UNITY namespace System.Runtime.Versioning { // Unity uses the net40 target, because that simplifies the project configuration. // But in practice it targets framework 3.5, which does not have the TargetFrameworkAttribute // that is added to the generated AssemblyInfo. [AttributeUsage(AttributeTargets.Assembly, AllowMultiple = false, Inherited = false)] internal sealed class TargetFrameworkAttribute : Attribute { public string FrameworkName { get; set; } public string FrameworkDisplayName { get; set; } public TargetFrameworkAttribute(string frameworkName) { FrameworkName = frameworkName; } } } #endif
30.254446
163
0.540423
[ "BSD-2-Clause" ]
ostadnik/evdEn
Yaml/Helpers/Portability.cs
22,118
C#
using System.Collections; using System.Collections.Generic; using UnityEngine; namespace MacKay.Game { public class CelestialSatellite : CelestialObjects { [SerializeField] private bool isTidalLocked; [SerializeField] private GameObject parentCelestailObject; } }
22
54
0.717532
[ "MIT" ]
mikebmac/VR-Local-Solar-System-for-Master-s-Thesis
Scripts/Runtime/Objects/CelestialSatellite.cs
308
C#
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Duende.IdentityServer.Events; using Duende.IdentityServer.Extensions; using Duende.IdentityServer.Models; using Duende.IdentityServer.Services; using Duende.IdentityServer.Validation; using IdentityModel; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.RazorPages; using Microsoft.Extensions.Logging; namespace Duente.Pages.Consent; [Authorize] [SecurityHeadersAttribute] public class Index : PageModel { private readonly IIdentityServerInteractionService _interaction; private readonly IEventService _events; private readonly ILogger<Index> _logger; public Index( IIdentityServerInteractionService interaction, IEventService events, ILogger<Index> logger) { _interaction = interaction; _events = events; _logger = logger; } public ViewModel View { get; set; } [BindProperty] public InputModel Input { get; set; } public async Task<IActionResult> OnGet(string returnUrl) { View = await BuildViewModelAsync(returnUrl); if (View == null) { return RedirectToPage("/Error/Index"); } Input = new InputModel { ReturnUrl = returnUrl, }; return Page(); } public async Task<IActionResult> OnPost() { // validate return url is still valid var request = await _interaction.GetAuthorizationContextAsync(Input.ReturnUrl); if (request == null) return RedirectToPage("/Error/Index"); ConsentResponse grantedConsent = null; // user clicked 'no' - send back the standard 'access_denied' response if (Input?.Button == "no") { grantedConsent = new ConsentResponse { Error = AuthorizationError.AccessDenied }; // emit event await _events.RaiseAsync(new ConsentDeniedEvent(User.GetSubjectId(), request.Client.ClientId, request.ValidatedResources.RawScopeValues)); } // user clicked 'yes' - validate the data else if (Input?.Button == "yes") { // if the user consented to some scope, build the response model if (Input.ScopesConsented != null && Input.ScopesConsented.Any()) { var scopes = Input.ScopesConsented; if (ConsentOptions.EnableOfflineAccess == false) { scopes = scopes.Where(x => x != Duende.IdentityServer.IdentityServerConstants.StandardScopes.OfflineAccess); } grantedConsent = new ConsentResponse { RememberConsent = Input.RememberConsent, ScopesValuesConsented = scopes.ToArray(), Description = Input.Description }; // emit event await _events.RaiseAsync(new ConsentGrantedEvent(User.GetSubjectId(), request.Client.ClientId, request.ValidatedResources.RawScopeValues, grantedConsent.ScopesValuesConsented, grantedConsent.RememberConsent)); } else { ModelState.AddModelError("", ConsentOptions.MustChooseOneErrorMessage); } } else { ModelState.AddModelError("", ConsentOptions.InvalidSelectionErrorMessage); } if (grantedConsent != null) { // communicate outcome of consent back to identityserver await _interaction.GrantConsentAsync(request, grantedConsent); // redirect back to authorization endpoint if (request.IsNativeClient() == true) { // The client is native, so this change in how to // return the response is for better UX for the end user. return this.LoadingPage(Input.ReturnUrl); } return Redirect(Input.ReturnUrl); } // we need to redisplay the consent UI View = await BuildViewModelAsync(Input.ReturnUrl, Input); return Page(); } private async Task<ViewModel> BuildViewModelAsync(string returnUrl, InputModel model = null) { var request = await _interaction.GetAuthorizationContextAsync(returnUrl); if (request != null) { return CreateConsentViewModel(model, returnUrl, request); } else { _logger.LogError("No consent request matching request: {0}", returnUrl); } return null; } private ViewModel CreateConsentViewModel( InputModel model, string returnUrl, AuthorizationRequest request) { var vm = new ViewModel { ClientName = request.Client.ClientName ?? request.Client.ClientId, ClientUrl = request.Client.ClientUri, ClientLogoUrl = request.Client.LogoUri, AllowRememberConsent = request.Client.AllowRememberConsent }; vm.IdentityScopes = request.ValidatedResources.Resources.IdentityResources .Select(x => CreateScopeViewModel(x, model?.ScopesConsented == null || model.ScopesConsented?.Contains(x.Name) == true)) .ToArray(); var resourceIndicators = request.Parameters.GetValues(OidcConstants.AuthorizeRequest.Resource) ?? Enumerable.Empty<string>(); var apiResources = request.ValidatedResources.Resources.ApiResources.Where(x => resourceIndicators.Contains(x.Name)); var apiScopes = new List<ScopeViewModel>(); foreach (var parsedScope in request.ValidatedResources.ParsedScopes) { var apiScope = request.ValidatedResources.Resources.FindApiScope(parsedScope.ParsedName); if (apiScope != null) { var scopeVm = CreateScopeViewModel(parsedScope, apiScope, model == null || model.ScopesConsented?.Contains(parsedScope.RawValue) == true); scopeVm.Resources = apiResources.Where(x => x.Scopes.Contains(parsedScope.ParsedName)) .Select(x => new ResourceViewModel { Name = x.Name, DisplayName = x.DisplayName ?? x.Name, }).ToArray(); apiScopes.Add(scopeVm); } } if (ConsentOptions.EnableOfflineAccess && request.ValidatedResources.Resources.OfflineAccess) { apiScopes.Add(GetOfflineAccessScope(model == null || model.ScopesConsented?.Contains(Duende.IdentityServer.IdentityServerConstants.StandardScopes.OfflineAccess) == true)); } vm.ApiScopes = apiScopes; return vm; } private ScopeViewModel CreateScopeViewModel(IdentityResource identity, bool check) { return new ScopeViewModel { Name = identity.Name, Value = identity.Name, DisplayName = identity.DisplayName ?? identity.Name, Description = identity.Description, Emphasize = identity.Emphasize, Required = identity.Required, Checked = check || identity.Required }; } public ScopeViewModel CreateScopeViewModel(ParsedScopeValue parsedScopeValue, ApiScope apiScope, bool check) { var displayName = apiScope.DisplayName ?? apiScope.Name; if (!String.IsNullOrWhiteSpace(parsedScopeValue.ParsedParameter)) { displayName += ":" + parsedScopeValue.ParsedParameter; } return new ScopeViewModel { Name = parsedScopeValue.ParsedName, Value = parsedScopeValue.RawValue, DisplayName = displayName, Description = apiScope.Description, Emphasize = apiScope.Emphasize, Required = apiScope.Required, Checked = check || apiScope.Required }; } private ScopeViewModel GetOfflineAccessScope(bool check) { return new ScopeViewModel { Value = Duende.IdentityServer.IdentityServerConstants.StandardScopes.OfflineAccess, DisplayName = ConsentOptions.OfflineAccessDisplayName, Description = ConsentOptions.OfflineAccessDescription, Emphasize = true, Checked = check }; } }
36.633188
225
0.627727
[ "Apache-2.0" ]
onassisb/microservices-dotnet6
GeekShooping/Duente/Pages/Consent/Index.cshtml.cs
8,389
C#
using System; using System.Collections.Generic; using System.Linq; using Foundation; using UIKit; namespace WikiHeroApp.iOS { public class Application { // This is the main entry point of the application. static void Main(string[] args) { // if you want to use a different Application Delegate class from "AppDelegate" // you can specify it here. UIApplication.Main(args, null, "AppDelegate"); } } }
23
91
0.63354
[ "MIT" ]
RafaelFernandez0512/WikiHeroApp
WikiHeroApp/WikiHeroApp.iOS/Main.cs
485
C#
using System.Collections; using System.Collections.Generic; using UnityEngine; public class EnemyAttackRanged : FSMState, IGameEntity { [SerializeField] [Range(0f, 2f)] private float minReactionTime = 1f; [SerializeField] [Range(0f, 5f)] private float maxReactionTime = 2f; [SerializeField] private EnemyFlee stateChase; [SerializeField] private GameObject projectilePrefab; [SerializeField] private Transform objSpawnPos; [SerializeField] [Range(0f, 30f)] private float ChaseDistance = 5f; [SerializeField] private SoundPacket shootingSound; private GameObject target; private Transform projectilesRoot; private string pg = "Player"; private float reactionTime; private GameManager gameManager; private void OnValidate() { this.stateChase = this.GetComponent<EnemyFlee>(); } private void Update() { target = GameObject.FindGameObjectWithTag(pg); var pos = this.transform.position; var targetPos = this.target.transform.position; var dir = Vector3.Distance(pos, targetPos); this.reactionTime -= Time.deltaTime; if (this.reactionTime <= 0f) { this.Attack(); if(dir < ChaseDistance) { this.fsm.ChangeState(this.stateChase); return; } ReAttack(); } } public override void OnStateEnter() { base.OnStateEnter(); this.reactionTime = Random.Range(this.minReactionTime, this.maxReactionTime); } public void ReAttack() { this.reactionTime = Random.Range(this.minReactionTime, this.maxReactionTime); } public void SetProjectilesRoot(Transform root) { this.projectilesRoot = root; } public override string ToString() { return "ATTACK"; } private void Attack() { gameManager.PlaySound(shootingSound); GameObject proj = Instantiate(projectilePrefab, objSpawnPos.position, objSpawnPos.rotation, null); proj.transform.parent = projectilesRoot; proj.GetComponent<ProjectileController>().SetTeam(Team.Enemy); } public void Init(GameManager gameManager) { this.gameManager = gameManager; } }
19.68932
100
0.733235
[ "MIT" ]
Bobbsify/Blade-Dancer
Assets/Scripts/AI/Mobs/EnemyAttackRanged.cs
2,030
C#
/* © Siemens AG, 2017-2018 Author: Dr. Martin Bischoff (martin.bischoff@siemens.com) Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at <http://www.apache.org/licenses/LICENSE-2.0>. Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ using System; using WebSocketSharp; namespace RosSharp.RosBridgeClient.Protocols { public class WebSocketSharpProtocol: IProtocol { public event EventHandler OnReceive; public event EventHandler OnConnected; public event EventHandler OnClosed; public event EventHandler OnError; private WebSocket WebSocket; public WebSocketSharpProtocol(string url) { WebSocket = new WebSocket(url); WebSocket.OnMessage += Receive; WebSocket.OnClose += Closed; WebSocket.OnOpen += Connected; } public void Connect() { WebSocket.ConnectAsync(); } public void Close() { WebSocket.CloseAsync(); } public bool IsAlive() { return WebSocket.IsAlive; } public void Send(byte[] data) { WebSocket.SendAsync(data, null); } private void Receive(object sender, WebSocketSharp.MessageEventArgs e) { OnReceive?.Invoke(sender, new MessageEventArgs(e.RawData)); } private void Closed(object sender, EventArgs e) { OnClosed?.Invoke(sender, e); } private void Connected(object sender, EventArgs e) { OnConnected?.Invoke(sender, e); } } }
26.842105
78
0.622549
[ "Apache-2.0" ]
forbiddenname/ros-sharp
Libraries/RosBridgeClient/Protocols/WebSocketSharpProtocol.cs
2,043
C#
using System; using System.Collections.Generic; using System.Text; using System.Web.UI; using System.Web.UI.HtmlControls; using System.Web.UI.WebControls; using System.Web.UI.WebControls.WebParts; using umbraco.BusinessLogic; using umbraco.editorControls; namespace umbraco.editorControls.relatedlinks { [Obsolete("IDataType and all other references to the legacy property editors are no longer used this will be removed from the codebase in future versions")] public class RelatedLinksPrevalueEditor : System.Web.UI.WebControls.PlaceHolder, umbraco.interfaces.IDataPrevalue { #region IDataPrevalue Members // referenced datatype private umbraco.cms.businesslogic.datatype.BaseDataType _datatype; //private DropDownList _dropdownlist; //private CheckBox _showUrls; public RelatedLinksPrevalueEditor(umbraco.cms.businesslogic.datatype.BaseDataType DataType) { _datatype = DataType; setupChildControls(); } private void setupChildControls() { //_dropdownlist = new DropDownList(); //_dropdownlist.ID = "dbtype"; ////_dropdownlist.Items.Add(DBTypes.Date.ToString()); ////_dropdownlist.Items.Add(DBTypes.Integer.ToString()); //_dropdownlist.Items.Add(DBTypes.Ntext.ToString()); //_dropdownlist.Items.Add(DBTypes.Nvarchar.ToString()); ////_checkboxShowGrandChildren = new CheckBox(); ////_checkboxShowGrandChildren.ID = "showurls"; //Controls.Add(_dropdownlist); //Controls.Add(_showUrls); } public Control Editor { get { return this; } } protected override void OnLoad(EventArgs e) { base.OnLoad(e); //if (!Page.IsPostBack) //{ // string[] config = Configuration.Split("|".ToCharArray()); // if (config.Length > 1) // { // //_showUrls.Checked = Convert.ToBoolean(config[0]); // } // _dropdownlist.SelectedValue = _datatype.DBType.ToString(); //} } public void Save() { _datatype.DBType = (umbraco.cms.businesslogic.datatype.DBTypes)Enum.Parse(typeof(umbraco.cms.businesslogic.datatype.DBTypes), DBTypes.Ntext.ToString(), true); } protected override void Render(HtmlTextWriter writer) { //writer.WriteLine("<table>"); //writer.WriteLine("<tr><th>Database datatype:</th><td>"); //_dropdownlist.RenderControl(writer); //writer.Write("</td></tr>"); //writer.Write("</table>"); } public string Configuration { get { return ""; } } #endregion } }
29.394231
171
0.561662
[ "MIT" ]
Abhith/Umbraco-CMS
src/umbraco.editorControls/relatedlinks/RelatedLinksPrevalueEditor.cs
3,059
C#
// Copyright 2022 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. // Generated code. DO NOT EDIT! namespace Google.Cloud.VMMigration.V1.Snippets { // [START vmmigration_v1_generated_VmMigration_DeleteUtilizationReport_async_flattened_resourceNames] using Google.Cloud.VMMigration.V1; using Google.LongRunning; using Google.Protobuf.WellKnownTypes; using System.Threading.Tasks; public sealed partial class GeneratedVmMigrationClientSnippets { /// <summary>Snippet for DeleteUtilizationReportAsync</summary> /// <remarks> /// This snippet has been automatically generated for illustrative purposes only. /// It may require modifications to work in your environment. /// </remarks> public async Task DeleteUtilizationReportResourceNamesAsync() { // Create client VmMigrationClient vmMigrationClient = await VmMigrationClient.CreateAsync(); // Initialize request argument(s) UtilizationReportName name = UtilizationReportName.FromProjectLocationSourceUtilizationReport("[PROJECT]", "[LOCATION]", "[SOURCE]", "[UTILIZATION_REPORT]"); // Make the request Operation<Empty, OperationMetadata> response = await vmMigrationClient.DeleteUtilizationReportAsync(name); // Poll until the returned long-running operation is complete Operation<Empty, OperationMetadata> completedResponse = await response.PollUntilCompletedAsync(); // Retrieve the operation result Empty result = completedResponse.Result; // Or get the name of the operation string operationName = response.Name; // This name can be stored, then the long-running operation retrieved later by name Operation<Empty, OperationMetadata> retrievedResponse = await vmMigrationClient.PollOnceDeleteUtilizationReportAsync(operationName); // Check if the retrieved long-running operation has completed if (retrievedResponse.IsCompleted) { // If it has completed, then access the result Empty retrievedResult = retrievedResponse.Result; } } } // [END vmmigration_v1_generated_VmMigration_DeleteUtilizationReport_async_flattened_resourceNames] }
47.7
169
0.708595
[ "Apache-2.0" ]
AlexandrTrf/google-cloud-dotnet
apis/Google.Cloud.VMMigration.V1/Google.Cloud.VMMigration.V1.GeneratedSnippets/VmMigrationClient.DeleteUtilizationReportResourceNamesAsyncSnippet.g.cs
2,862
C#
using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.Configuration; using WebApi.Entities; namespace WebApi.Helpers { public class DataContext : DbContext { protected readonly IConfiguration Configuration; public DataContext(IConfiguration configuration) { Configuration = configuration; } protected override void OnConfiguring(DbContextOptionsBuilder options) { // in memory database used for simplicity, change to a real db for production applications options.UseInMemoryDatabase("TestDb"); } public DbSet<User> Users { get; set; } } }
27.666667
102
0.679217
[ "MIT" ]
cornflourblue/dotnet-5-crud-api
Helpers/DataContext.cs
664
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Amazon.EC2.Model; namespace CloudStudio.SharedLibrary.Services.AWSServices { /// <summary> /// Response for detaching volumes from instances. /// </summary> public class DetachVolumeResponse : AbstractResponse { } }
19.736842
58
0.712
[ "Apache-2.0" ]
jzonthemtn/cloud-studio
Cloud Studio Shared Library/Services/AWSServices/DetachVolumeResponse.cs
377
C#
namespace Microsoft.TemplateEngine.Core.UnitTests { public class EncodingTests { } }
14.857143
51
0.663462
[ "MIT" ]
ChadNedzlek/templating
test/Microsoft.TemplateEngine.Core.UnitTests/EncodingTests.cs
100
C#
using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; using System.Linq; using System.Web; namespace IdentitySample.Models { [Table("Multa")] public class Multa { [Key] [Display(Name = "Código")] public int Id { get; set; } [Display(Name = "Valor da Multa")] public decimal Valor { get; set; } [Display(Name = "Status do Pagamento")] [Required(ErrorMessage = "Campo Obrigatório | Favor selecionar o status atual do pagamento")] public string StatusPagamento { get; set; } [Display(Name = "Motivo da Multa")] [Required(ErrorMessage = "Campo Obrigatório | Favor selecionar o motivoda da cobrança da multa")] public string MotivoMulta { get; set; } [Display(Name = "Observação")] public string Observacao { get; set; } [Display(Name = "Livro")] [Required(ErrorMessage = "Campo Obrigatório | Favor selecionar o Livro")] public int LivroId { get; set; } [ForeignKey("LivroId")] public Livro Livro { get; set; } [Required(ErrorMessage = "Campo Obrigatório | Favor selecionar o Livro")] public string Leitor { get; set; } } }
31.560976
105
0.636012
[ "MIT" ]
RodrigoErnandes/TCC
IdentitySample/Models/Multa.cs
1,304
C#
using HITUOISR.Toolkit.PluginBase; using System; namespace HITUOISR.Toolkit.SimpleHost.PluginTools { /// <summary> /// 插件构造器。 /// </summary> public interface IPluginBuilder { /// <summary> /// 添加插件搜索模式。 /// </summary> /// <param name="pattern">插件搜索模式。</param> IPluginBuilder AddSearchPattern(string pattern); /// <summary> /// 添加插件搜索路径。 /// </summary> /// <param name="path">插件搜索路径。</param> IPluginBuilder AddSearchPath(string path); /// <summary> /// 添加插件。 /// </summary> /// <param name="plugin">插件。</param> IPluginBuilder AddPlugin(IPlugin plugin); /// <summary> /// 构造插件和插件管理器。 /// </summary> /// <param name="builder">关联的主机构造器。</param> /// <returns>插件管理器工厂方法。</returns> Func<IServiceProvider, IPluginManager> Build(IHostBuilder builder); } }
25.513514
75
0.549788
[ "MIT" ]
HIT-UOI-SR/HITUOISR.Toolkit
HITUOISR.Toolkit.SimpleHost/src/PluginTools/IPluginBuilder.cs
1,098
C#
using UnityEngine; using System.Collections; public class Car : MonoBehaviour, ICar { public WheelCollider[] wheelColliders; public Transform[] wheelMeshes; public float maxTorque = 50f; public float maxSpeed = 10f; public Transform centrOfMass; public float requestTorque = 0f; public float requestBrake = 0f; public float requestSteering = 0f; public Vector3 acceleration = Vector3.zero; public Vector3 prevVel = Vector3.zero; public Vector3 startPos; public Quaternion startRot; private Quaternion rotation = Quaternion.identity; private Quaternion gyro = Quaternion.identity; public float length = 1.7f; Rigidbody rb; //for logging public float lastSteer = 0.0f; public float lastAccel = 0.0f; //when the car is doing multiple things, we sometimes want to sort out parts of the training //use this label to pull partial training samples from a run public string activity = "keep_lane"; public float maxSteer = 16.0f; //name of the last object we hit. public string last_collision = "none"; // used by race manager to keep cars at the starting line. public bool blockControls = false; // Use this for initialization void Awake () { rb = GetComponent<Rigidbody>(); if(rb && centrOfMass) { rb.centerOfMass = centrOfMass.localPosition; } requestTorque = 0f; requestSteering = 0f; SavePosRot(); //maxSteer = PlayerPrefs.GetFloat("max_steer", 16.0f); } public void SavePosRot() { startPos = transform.position; startRot = transform.rotation; } public void RestorePosRot() { Set(startPos, startRot); } public void RequestThrottle(float val) { requestTorque = val; requestBrake = 0f; //Debug.Log("request throttle: " + val); } public void SetMaxSteering(float val) { maxSteer = val; PlayerPrefs.SetFloat("max_steer", maxSteer); PlayerPrefs.Save(); } public float GetMaxSteering() { return maxSteer; } public void RequestSteering(float val) { requestSteering = Mathf.Clamp(val, -maxSteer, maxSteer); //Debug.Log("request steering: " + val); } public void Set(Vector3 pos, Quaternion rot) { rb.position = pos; rb.rotation = rot; //just setting it once doesn't seem to work. Try setting it multiple times.. StartCoroutine(KeepSetting(pos, rot, 1)); } IEnumerator KeepSetting(Vector3 pos, Quaternion rot, int numIter) { while(numIter > 0) { rb.isKinematic = true; yield return new WaitForFixedUpdate(); rb.position = pos; rb.rotation = rot; transform.position = pos; transform.rotation = rot; numIter--; rb.isKinematic = false; } } public float GetSteering() { return requestSteering; } public float GetThrottle() { return requestTorque; } public float GetFootBrake() { return requestBrake; } public float GetHandBrake() { return 0.0f; } public Vector3 GetVelocity() { return rb.velocity; } public Vector3 GetAccel() { return acceleration; } public Quaternion GetGyro() { return gyro; } public float GetOrient () { Vector3 dir = transform.forward; return Mathf.Atan2( dir.z, dir.x); } public Transform GetTransform() { return this.transform; } public bool IsStill() { return rb.IsSleeping(); } public void RequestFootBrake(float val) { requestBrake = val; } public void RequestHandBrake(float val) { //todo } // Update is called once per frame void Update () { UpdateWheelPositions(); } public string GetActivity() { return activity; } public void SetActivity(string act) { activity = act; } void FixedUpdate() { if(blockControls) { requestSteering = 0.0f; requestTorque = 0.0f; } lastSteer = requestSteering; lastAccel = requestTorque; float throttle = requestTorque * maxTorque; float steerAngle = requestSteering; float brake = requestBrake; //front two tires. wheelColliders[2].steerAngle = steerAngle; wheelColliders[3].steerAngle = steerAngle; //four wheel drive at the moment foreach(WheelCollider wc in wheelColliders) { if(rb.velocity.magnitude < maxSpeed) { wc.motorTorque = throttle; } else { wc.motorTorque = 0.0f; } wc.brakeTorque = 400f * brake; } acceleration = rb.velocity - prevVel; gyro = rb.rotation * Quaternion.Inverse(rotation); rotation = rb.rotation; } void FlipUpright() { Quaternion rot = Quaternion.Euler(180f, 0f, 0f); this.transform.rotation = transform.rotation * rot; transform.position = transform.position + Vector3.up * 2; } void UpdateWheelPositions() { Quaternion rot; Vector3 pos; for(int i = 0; i < wheelColliders.Length; i++) { WheelCollider wc = wheelColliders[i]; Transform tm = wheelMeshes[i]; wc.GetWorldPose(out pos, out rot); tm.position = pos; tm.rotation = rot; } } //get the name of the last object we collided with public string GetLastCollision() { return last_collision; } public void SetLastCollision(string col_name) { last_collision = col_name; } public void ClearLastCollision() { last_collision = "none"; } void OnCollisionEnter(Collision col) { SetLastCollision(col.gameObject.name); } }
17.828179
93
0.69121
[ "BSD-3-Clause" ]
helios57/sdsandbox
sdsim/Assets/Scripts/Car.cs
5,188
C#
//------------------------------------------------------------------------------ // <auto-generated /> // // This file was automatically generated by SWIG (http://www.swig.org). // Version 3.0.10 // // Do not make changes to this file unless you know what you are doing--modify // the SWIG interface file instead. //------------------------------------------------------------------------------ namespace HoloToolkit.Sharing { public class DiscoveryClientListener : Listener { private global::System.Runtime.InteropServices.HandleRef swigCPtr; internal DiscoveryClientListener(global::System.IntPtr cPtr, bool cMemoryOwn) : base(SharingClientPINVOKE.DiscoveryClientListener_SWIGUpcast(cPtr), cMemoryOwn) { swigCPtr = new global::System.Runtime.InteropServices.HandleRef(this, cPtr); } internal static global::System.Runtime.InteropServices.HandleRef getCPtr(DiscoveryClientListener obj) { return (obj == null) ? new global::System.Runtime.InteropServices.HandleRef(null, global::System.IntPtr.Zero) : obj.swigCPtr; } ~DiscoveryClientListener() { Dispose(); } public override void Dispose() { lock(this) { if (swigCPtr.Handle != global::System.IntPtr.Zero) { if (swigCMemOwn) { swigCMemOwn = false; SharingClientPINVOKE.delete_DiscoveryClientListener(swigCPtr); } swigCPtr = new global::System.Runtime.InteropServices.HandleRef(null, global::System.IntPtr.Zero); } global::System.GC.SuppressFinalize(this); base.Dispose(); } } public virtual void OnRemoteSystemDiscovered(DiscoveredSystem remoteSystem) { if (SwigDerivedClassHasMethod("OnRemoteSystemDiscovered", swigMethodTypes0)) SharingClientPINVOKE.DiscoveryClientListener_OnRemoteSystemDiscoveredSwigExplicitDiscoveryClientListener(swigCPtr, DiscoveredSystem.getCPtr(remoteSystem)); else SharingClientPINVOKE.DiscoveryClientListener_OnRemoteSystemDiscovered(swigCPtr, DiscoveredSystem.getCPtr(remoteSystem)); } public virtual void OnRemoteSystemLost(DiscoveredSystem remoteSystem) { if (SwigDerivedClassHasMethod("OnRemoteSystemLost", swigMethodTypes1)) SharingClientPINVOKE.DiscoveryClientListener_OnRemoteSystemLostSwigExplicitDiscoveryClientListener(swigCPtr, DiscoveredSystem.getCPtr(remoteSystem)); else SharingClientPINVOKE.DiscoveryClientListener_OnRemoteSystemLost(swigCPtr, DiscoveredSystem.getCPtr(remoteSystem)); } public DiscoveryClientListener() : this(SharingClientPINVOKE.new_DiscoveryClientListener(), true) { SwigDirectorConnect(); } private void SwigDirectorConnect() { if (SwigDerivedClassHasMethod("OnRemoteSystemDiscovered", swigMethodTypes0)) swigDelegate0 = new SwigDelegateDiscoveryClientListener_0(SwigDirectorOnRemoteSystemDiscovered); if (SwigDerivedClassHasMethod("OnRemoteSystemLost", swigMethodTypes1)) swigDelegate1 = new SwigDelegateDiscoveryClientListener_1(SwigDirectorOnRemoteSystemLost); SharingClientPINVOKE.DiscoveryClientListener_director_connect(swigCPtr, swigDelegate0, swigDelegate1); } private bool SwigDerivedClassHasMethod(string methodName, global::System.Type[] methodTypes) { global::System.Reflection.MethodInfo methodInfo = this.GetType().GetMethod(methodName, global::System.Reflection.BindingFlags.Public | global::System.Reflection.BindingFlags.NonPublic | global::System.Reflection.BindingFlags.Instance, null, methodTypes, null); bool hasDerivedMethod = methodInfo.DeclaringType.IsSubclassOf(typeof(DiscoveryClientListener)); return hasDerivedMethod; } private void SwigDirectorOnRemoteSystemDiscovered(global::System.IntPtr remoteSystem) { OnRemoteSystemDiscovered((remoteSystem == global::System.IntPtr.Zero) ? null : new DiscoveredSystem(remoteSystem, true)); } private void SwigDirectorOnRemoteSystemLost(global::System.IntPtr remoteSystem) { OnRemoteSystemLost((remoteSystem == global::System.IntPtr.Zero) ? null : new DiscoveredSystem(remoteSystem, true)); } public delegate void SwigDelegateDiscoveryClientListener_0(global::System.IntPtr remoteSystem); public delegate void SwigDelegateDiscoveryClientListener_1(global::System.IntPtr remoteSystem); private SwigDelegateDiscoveryClientListener_0 swigDelegate0; private SwigDelegateDiscoveryClientListener_1 swigDelegate1; private static global::System.Type[] swigMethodTypes0 = new global::System.Type[] { typeof(DiscoveredSystem) }; private static global::System.Type[] swigMethodTypes1 = new global::System.Type[] { typeof(DiscoveredSystem) }; } }
53.114943
363
0.7533
[ "MIT" ]
4dpocket/Unitytest1
DesignLabs_Unity/Assets/HoloToolkit/Sharing/Scripts/SDK/DiscoveryClientListener.cs
4,621
C#
/* ==================================================================== Licensed to the Apache Software Foundation (ASF) Under one or more contributor license agreements. See the NOTICE file distributed with this work for Additional information regarding copyright ownership. The ASF licenses this file to You Under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed Under the License is distributed on an "AS Is" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations Under the License. ==================================================================== */ namespace NPOI.HSSF.Record { using System; using System.Text; /** * Title: Header Record * Description: Specifies a header for a sheet * REFERENCE: PG 321 Microsoft Excel 97 Developer's Kit (ISBN: 1-57231-498-2) * @author Andrew C. Oliver (acoliver at apache dot org) * @author Shawn Laubach (slaubach at apache dot org) Modified 3/14/02 * @author Jason Height (jheight at chariot dot net dot au) * @version 2.0-pre */ public class HeaderRecord : HeaderFooterBase { public const short sid = 0x14; public HeaderRecord(String text):base(text) { } /** * Constructs an Header record and Sets its fields appropriately. * @param in the RecordInputstream to Read the record from */ public HeaderRecord(RecordInputStream in1):base(in1) { } public override String ToString() { StringBuilder buffer = new StringBuilder(); buffer.Append("[HEADER]\n"); buffer.Append(" .header = ").Append(Text) .Append("\n"); buffer.Append("[/HEADER]\n"); return buffer.ToString(); } public override short Sid { get { return sid; } } public override Object Clone() { return new HeaderRecord(this.Text); } } }
32.394737
83
0.569456
[ "Apache-2.0" ]
sunshinele/npoi
main/HSSF/Record/HeaderRecord.cs
2,462
C#
#pragma warning disable 108 // new keyword hiding #pragma warning disable 114 // new keyword hiding namespace Windows.Data.Xml.Dom { #if __ANDROID__ || __IOS__ || NET46 || __WASM__ [global::Uno.NotImplemented] #endif public partial class XmlAttribute : global::Windows.Data.Xml.Dom.IXmlNode,global::Windows.Data.Xml.Dom.IXmlNodeSerializer,global::Windows.Data.Xml.Dom.IXmlNodeSelector { #if __ANDROID__ || __IOS__ || NET46 || __WASM__ [global::Uno.NotImplemented] public string Value { get { throw new global::System.NotImplementedException("The member string XmlAttribute.Value is not implemented in Uno."); } set { global::Windows.Foundation.Metadata.ApiInformation.TryRaiseNotImplemented("Windows.Data.Xml.Dom.XmlAttribute", "string XmlAttribute.Value"); } } #endif #if __ANDROID__ || __IOS__ || NET46 || __WASM__ [global::Uno.NotImplemented] public bool Specified { get { throw new global::System.NotImplementedException("The member bool XmlAttribute.Specified is not implemented in Uno."); } } #endif #if __ANDROID__ || __IOS__ || NET46 || __WASM__ [global::Uno.NotImplemented] public string Name { get { throw new global::System.NotImplementedException("The member string XmlAttribute.Name is not implemented in Uno."); } } #endif #if __ANDROID__ || __IOS__ || NET46 || __WASM__ [global::Uno.NotImplemented] public object Prefix { get { throw new global::System.NotImplementedException("The member object XmlAttribute.Prefix is not implemented in Uno."); } set { global::Windows.Foundation.Metadata.ApiInformation.TryRaiseNotImplemented("Windows.Data.Xml.Dom.XmlAttribute", "object XmlAttribute.Prefix"); } } #endif #if __ANDROID__ || __IOS__ || NET46 || __WASM__ [global::Uno.NotImplemented] public object NodeValue { get { throw new global::System.NotImplementedException("The member object XmlAttribute.NodeValue is not implemented in Uno."); } set { global::Windows.Foundation.Metadata.ApiInformation.TryRaiseNotImplemented("Windows.Data.Xml.Dom.XmlAttribute", "object XmlAttribute.NodeValue"); } } #endif #if __ANDROID__ || __IOS__ || NET46 || __WASM__ [global::Uno.NotImplemented] public global::Windows.Data.Xml.Dom.IXmlNode FirstChild { get { throw new global::System.NotImplementedException("The member IXmlNode XmlAttribute.FirstChild is not implemented in Uno."); } } #endif #if __ANDROID__ || __IOS__ || NET46 || __WASM__ [global::Uno.NotImplemented] public global::Windows.Data.Xml.Dom.IXmlNode LastChild { get { throw new global::System.NotImplementedException("The member IXmlNode XmlAttribute.LastChild is not implemented in Uno."); } } #endif #if __ANDROID__ || __IOS__ || NET46 || __WASM__ [global::Uno.NotImplemented] public object LocalName { get { throw new global::System.NotImplementedException("The member object XmlAttribute.LocalName is not implemented in Uno."); } } #endif #if __ANDROID__ || __IOS__ || NET46 || __WASM__ [global::Uno.NotImplemented] public object NamespaceUri { get { throw new global::System.NotImplementedException("The member object XmlAttribute.NamespaceUri is not implemented in Uno."); } } #endif #if __ANDROID__ || __IOS__ || NET46 || __WASM__ [global::Uno.NotImplemented] public global::Windows.Data.Xml.Dom.IXmlNode NextSibling { get { throw new global::System.NotImplementedException("The member IXmlNode XmlAttribute.NextSibling is not implemented in Uno."); } } #endif #if __ANDROID__ || __IOS__ || NET46 || __WASM__ [global::Uno.NotImplemented] public string NodeName { get { throw new global::System.NotImplementedException("The member string XmlAttribute.NodeName is not implemented in Uno."); } } #endif #if __ANDROID__ || __IOS__ || NET46 || __WASM__ [global::Uno.NotImplemented] public global::Windows.Data.Xml.Dom.NodeType NodeType { get { throw new global::System.NotImplementedException("The member NodeType XmlAttribute.NodeType is not implemented in Uno."); } } #endif #if __ANDROID__ || __IOS__ || NET46 || __WASM__ [global::Uno.NotImplemented] public global::Windows.Data.Xml.Dom.XmlNamedNodeMap Attributes { get { throw new global::System.NotImplementedException("The member XmlNamedNodeMap XmlAttribute.Attributes is not implemented in Uno."); } } #endif #if __ANDROID__ || __IOS__ || NET46 || __WASM__ [global::Uno.NotImplemented] public global::Windows.Data.Xml.Dom.XmlDocument OwnerDocument { get { throw new global::System.NotImplementedException("The member XmlDocument XmlAttribute.OwnerDocument is not implemented in Uno."); } } #endif #if __ANDROID__ || __IOS__ || NET46 || __WASM__ [global::Uno.NotImplemented] public global::Windows.Data.Xml.Dom.XmlNodeList ChildNodes { get { throw new global::System.NotImplementedException("The member XmlNodeList XmlAttribute.ChildNodes is not implemented in Uno."); } } #endif #if __ANDROID__ || __IOS__ || NET46 || __WASM__ [global::Uno.NotImplemented] public global::Windows.Data.Xml.Dom.IXmlNode ParentNode { get { throw new global::System.NotImplementedException("The member IXmlNode XmlAttribute.ParentNode is not implemented in Uno."); } } #endif #if __ANDROID__ || __IOS__ || NET46 || __WASM__ [global::Uno.NotImplemented] public global::Windows.Data.Xml.Dom.IXmlNode PreviousSibling { get { throw new global::System.NotImplementedException("The member IXmlNode XmlAttribute.PreviousSibling is not implemented in Uno."); } } #endif #if __ANDROID__ || __IOS__ || NET46 || __WASM__ [global::Uno.NotImplemented] public string InnerText { get { throw new global::System.NotImplementedException("The member string XmlAttribute.InnerText is not implemented in Uno."); } set { global::Windows.Foundation.Metadata.ApiInformation.TryRaiseNotImplemented("Windows.Data.Xml.Dom.XmlAttribute", "string XmlAttribute.InnerText"); } } #endif // Forced skipping of method Windows.Data.Xml.Dom.XmlAttribute.Name.get // Forced skipping of method Windows.Data.Xml.Dom.XmlAttribute.Specified.get // Forced skipping of method Windows.Data.Xml.Dom.XmlAttribute.Value.get // Forced skipping of method Windows.Data.Xml.Dom.XmlAttribute.Value.set // Forced skipping of method Windows.Data.Xml.Dom.XmlAttribute.NodeValue.get // Forced skipping of method Windows.Data.Xml.Dom.XmlAttribute.NodeValue.set // Forced skipping of method Windows.Data.Xml.Dom.XmlAttribute.NodeType.get // Forced skipping of method Windows.Data.Xml.Dom.XmlAttribute.NodeName.get // Forced skipping of method Windows.Data.Xml.Dom.XmlAttribute.ParentNode.get // Forced skipping of method Windows.Data.Xml.Dom.XmlAttribute.ChildNodes.get // Forced skipping of method Windows.Data.Xml.Dom.XmlAttribute.FirstChild.get // Forced skipping of method Windows.Data.Xml.Dom.XmlAttribute.LastChild.get // Forced skipping of method Windows.Data.Xml.Dom.XmlAttribute.PreviousSibling.get // Forced skipping of method Windows.Data.Xml.Dom.XmlAttribute.NextSibling.get // Forced skipping of method Windows.Data.Xml.Dom.XmlAttribute.Attributes.get #if __ANDROID__ || __IOS__ || NET46 || __WASM__ [global::Uno.NotImplemented] public bool HasChildNodes() { throw new global::System.NotImplementedException("The member bool XmlAttribute.HasChildNodes() is not implemented in Uno."); } #endif // Forced skipping of method Windows.Data.Xml.Dom.XmlAttribute.OwnerDocument.get #if __ANDROID__ || __IOS__ || NET46 || __WASM__ [global::Uno.NotImplemented] public global::Windows.Data.Xml.Dom.IXmlNode InsertBefore( global::Windows.Data.Xml.Dom.IXmlNode newChild, global::Windows.Data.Xml.Dom.IXmlNode referenceChild) { throw new global::System.NotImplementedException("The member IXmlNode XmlAttribute.InsertBefore(IXmlNode newChild, IXmlNode referenceChild) is not implemented in Uno."); } #endif #if __ANDROID__ || __IOS__ || NET46 || __WASM__ [global::Uno.NotImplemented] public global::Windows.Data.Xml.Dom.IXmlNode ReplaceChild( global::Windows.Data.Xml.Dom.IXmlNode newChild, global::Windows.Data.Xml.Dom.IXmlNode referenceChild) { throw new global::System.NotImplementedException("The member IXmlNode XmlAttribute.ReplaceChild(IXmlNode newChild, IXmlNode referenceChild) is not implemented in Uno."); } #endif #if __ANDROID__ || __IOS__ || NET46 || __WASM__ [global::Uno.NotImplemented] public global::Windows.Data.Xml.Dom.IXmlNode RemoveChild( global::Windows.Data.Xml.Dom.IXmlNode childNode) { throw new global::System.NotImplementedException("The member IXmlNode XmlAttribute.RemoveChild(IXmlNode childNode) is not implemented in Uno."); } #endif #if __ANDROID__ || __IOS__ || NET46 || __WASM__ [global::Uno.NotImplemented] public global::Windows.Data.Xml.Dom.IXmlNode AppendChild( global::Windows.Data.Xml.Dom.IXmlNode newChild) { throw new global::System.NotImplementedException("The member IXmlNode XmlAttribute.AppendChild(IXmlNode newChild) is not implemented in Uno."); } #endif #if __ANDROID__ || __IOS__ || NET46 || __WASM__ [global::Uno.NotImplemented] public global::Windows.Data.Xml.Dom.IXmlNode CloneNode( bool deep) { throw new global::System.NotImplementedException("The member IXmlNode XmlAttribute.CloneNode(bool deep) is not implemented in Uno."); } #endif // Forced skipping of method Windows.Data.Xml.Dom.XmlAttribute.NamespaceUri.get // Forced skipping of method Windows.Data.Xml.Dom.XmlAttribute.LocalName.get // Forced skipping of method Windows.Data.Xml.Dom.XmlAttribute.Prefix.get #if __ANDROID__ || __IOS__ || NET46 || __WASM__ [global::Uno.NotImplemented] public void Normalize() { global::Windows.Foundation.Metadata.ApiInformation.TryRaiseNotImplemented("Windows.Data.Xml.Dom.XmlAttribute", "void XmlAttribute.Normalize()"); } #endif // Forced skipping of method Windows.Data.Xml.Dom.XmlAttribute.Prefix.set #if __ANDROID__ || __IOS__ || NET46 || __WASM__ [global::Uno.NotImplemented] public global::Windows.Data.Xml.Dom.IXmlNode SelectSingleNode( string xpath) { throw new global::System.NotImplementedException("The member IXmlNode XmlAttribute.SelectSingleNode(string xpath) is not implemented in Uno."); } #endif #if __ANDROID__ || __IOS__ || NET46 || __WASM__ [global::Uno.NotImplemented] public global::Windows.Data.Xml.Dom.XmlNodeList SelectNodes( string xpath) { throw new global::System.NotImplementedException("The member XmlNodeList XmlAttribute.SelectNodes(string xpath) is not implemented in Uno."); } #endif #if __ANDROID__ || __IOS__ || NET46 || __WASM__ [global::Uno.NotImplemented] public global::Windows.Data.Xml.Dom.IXmlNode SelectSingleNodeNS( string xpath, object namespaces) { throw new global::System.NotImplementedException("The member IXmlNode XmlAttribute.SelectSingleNodeNS(string xpath, object namespaces) is not implemented in Uno."); } #endif #if __ANDROID__ || __IOS__ || NET46 || __WASM__ [global::Uno.NotImplemented] public global::Windows.Data.Xml.Dom.XmlNodeList SelectNodesNS( string xpath, object namespaces) { throw new global::System.NotImplementedException("The member XmlNodeList XmlAttribute.SelectNodesNS(string xpath, object namespaces) is not implemented in Uno."); } #endif #if __ANDROID__ || __IOS__ || NET46 || __WASM__ [global::Uno.NotImplemented] public string GetXml() { throw new global::System.NotImplementedException("The member string XmlAttribute.GetXml() is not implemented in Uno."); } #endif // Forced skipping of method Windows.Data.Xml.Dom.XmlAttribute.InnerText.get // Forced skipping of method Windows.Data.Xml.Dom.XmlAttribute.InnerText.set // Processing: Windows.Data.Xml.Dom.IXmlNode // Processing: Windows.Data.Xml.Dom.IXmlNodeSelector // Processing: Windows.Data.Xml.Dom.IXmlNodeSerializer } }
38.255521
172
0.738765
[ "Apache-2.0" ]
nv-ksavaria/Uno
src/Uno.UWP/Generated/3.0.0.0/Windows.Data.Xml.Dom/XmlAttribute.cs
12,127
C#
using System; using System.Collections.Generic; using System.Linq; using System.Web; namespace ManageNotification.Models { public class SearchHuyenEntity { public string Tinh_Id{ get; set; } } }
18.916667
43
0.682819
[ "Apache-2.0" ]
kakada/epihack-vn-notification
ManageNotification/ManageNotification/Models/SearchHuyenEntity.cs
229
C#
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System; using Microsoft.EntityFrameworkCore.Diagnostics; using Xunit; namespace Microsoft.EntityFrameworkCore { public class SqlServerDatabaseFacadeTest { [ConditionalFact] public void IsSqlServer_when_using_OnConfiguring() { using var context = new SqlServerOnConfiguringContext(); Assert.True(context.Database.IsSqlServer()); } [ConditionalFact] public void IsSqlServer_in_OnModelCreating_when_using_OnConfiguring() { using var context = new SqlServerOnModelContext(); var _ = context.Model; // Trigger context initialization Assert.True(context.IsSqlServerSet); } [ConditionalFact] public void IsRelational_in_OnModelCreating_when_using_OnConfiguring() { using var context = new RelationalOnModelContext(); var _ = context.Model; // Trigger context initialization Assert.True(context.IsSqlServerSet); } [ConditionalFact] public void IsSqlServer_in_constructor_when_using_OnConfiguring() { using var context = new SqlServerConstructorContext(); var _ = context.Model; // Trigger context initialization Assert.True(context.IsSqlServerSet); } [ConditionalFact] public void Cannot_use_IsSqlServer_in_OnConfiguring() { using var context = new SqlServerUseInOnConfiguringContext(); Assert.Equal( CoreStrings.RecursiveOnConfiguring, Assert.Throws<InvalidOperationException>( () => { var _ = context.Model; // Trigger context initialization }).Message); } [ConditionalFact] public void IsSqlServer_when_using_constructor() { using var context = new ProviderContext( new DbContextOptionsBuilder() .UseInternalServiceProvider(SqlServerFixture.DefaultServiceProvider) .UseSqlServer("Database=Maltesers").Options); Assert.True(context.Database.IsSqlServer()); } [ConditionalFact] public void IsSqlServer_in_OnModelCreating_when_using_constructor() { using var context = new ProviderOnModelContext( new DbContextOptionsBuilder() .UseInternalServiceProvider(SqlServerFixture.DefaultServiceProvider) .UseSqlServer("Database=Maltesers").Options); var _ = context.Model; // Trigger context initialization Assert.True(context.IsSqlServerSet); } [ConditionalFact] public void IsSqlServer_in_constructor_when_using_constructor() { using var context = new ProviderConstructorContext( new DbContextOptionsBuilder() .UseInternalServiceProvider(SqlServerFixture.DefaultServiceProvider) .UseSqlServer("Database=Maltesers").Options); var _ = context.Model; // Trigger context initialization Assert.True(context.IsSqlServerSet); } [ConditionalFact] public void Cannot_use_IsSqlServer_in_OnConfiguring_with_constructor() { using var context = new ProviderUseInOnConfiguringContext( new DbContextOptionsBuilder() .UseInternalServiceProvider(SqlServerFixture.DefaultServiceProvider) .UseSqlServer("Database=Maltesers").Options); Assert.Equal( CoreStrings.RecursiveOnConfiguring, Assert.Throws<InvalidOperationException>( () => { var _ = context.Model; // Trigger context initialization }).Message); } [ConditionalFact] public void Not_IsSqlServer_when_using_different_provider() { using var context = new ProviderContext( new DbContextOptionsBuilder() .UseInternalServiceProvider(InMemoryFixture.DefaultServiceProvider) .UseInMemoryDatabase("Maltesers").Options); Assert.False(context.Database.IsSqlServer()); } private class ProviderContext : DbContext { protected ProviderContext() { } public ProviderContext(DbContextOptions options) : base(options) { } public bool? IsSqlServerSet { get; protected set; } } private class SqlServerOnConfiguringContext : ProviderContext { protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) => optionsBuilder .UseInternalServiceProvider(SqlServerFixture.DefaultServiceProvider) .UseSqlServer("Database=Maltesers"); } private class SqlServerOnModelContext : SqlServerOnConfiguringContext { protected override void OnModelCreating(ModelBuilder modelBuilder) => IsSqlServerSet = Database.IsSqlServer(); } private class RelationalOnModelContext : SqlServerOnConfiguringContext { protected override void OnModelCreating(ModelBuilder modelBuilder) => IsSqlServerSet = Database.IsRelational(); } private class SqlServerConstructorContext : SqlServerOnConfiguringContext { public SqlServerConstructorContext() => IsSqlServerSet = Database.IsSqlServer(); } private class SqlServerUseInOnConfiguringContext : SqlServerOnConfiguringContext { protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) { base.OnConfiguring(optionsBuilder); IsSqlServerSet = Database.IsSqlServer(); } } private class ProviderOnModelContext : ProviderContext { public ProviderOnModelContext(DbContextOptions options) : base(options) { } protected override void OnModelCreating(ModelBuilder modelBuilder) => IsSqlServerSet = Database.IsSqlServer(); } private class ProviderConstructorContext : ProviderContext { public ProviderConstructorContext(DbContextOptions options) : base(options) => IsSqlServerSet = Database.IsSqlServer(); } private class ProviderUseInOnConfiguringContext : ProviderContext { public ProviderUseInOnConfiguringContext(DbContextOptions options) : base(options) { } protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) => IsSqlServerSet = Database.IsSqlServer(); } } }
37.06701
89
0.613823
[ "MIT" ]
CameronAavik/efcore
test/EFCore.SqlServer.Tests/SqlServerDatabaseFacadeTest.cs
7,191
C#
using System.Threading.Tasks; using NServiceBus; using NServiceBus.Persistence.ServiceFabric; [ServiceFabricSaga(CollectionName = "candidate-votes")] public class CandidateVotesSaga : Saga<CandidateVotesSaga.CandidateVoteData>, IAmStartedByMessages<VotePlaced>, IHandleMessages<CloseElection>, IHandleMessages<TrackZipCodeReply> { protected override void ConfigureHowToFindSaga(SagaPropertyMapper<CandidateVoteData> mapper) { mapper.ConfigureMapping<VotePlaced>(m => m.Candidate) .ToSaga(s => s.Candidate); mapper.ConfigureMapping<CloseElection>(m => m.Candidate) .ToSaga(s => s.Candidate); } public Task Handle(VotePlaced message, IMessageHandlerContext context) { if (!Data.Started) { Data.Candidate = message.Candidate; Data.Started = true; } Data.Count++; var trackZipCode = new TrackZipCode { ZipCode = message.ZipCode }; return context.Send(trackZipCode); } public Task Handle(CloseElection message, IMessageHandlerContext context) { var reportVotes = new ReportVotes { Candidate = Data.Candidate, NumberOfVotes = Data.Count }; MarkAsComplete(); return context.SendLocal(reportVotes); } public Task Handle(TrackZipCodeReply message, IMessageHandlerContext context) { Logger.Log($"##### CandidateVote saga for {Data.Candidate} got reply for zip code '{message.ZipCode}' tracking with current count of {message.CurrentCount}"); return Task.CompletedTask; } public class CandidateVoteData : ContainSagaData { public bool Started { get; set; } public string Candidate { get; set; } public int Count { get; set; } } }
31.096774
167
0.626037
[ "Apache-2.0" ]
Cogax/docs.particular.net
samples/azure/azure-service-fabric-routing/Core_7/CandidateVoteCount/CandidateVotesSaga.cs
1,869
C#
using System; using System.Globalization; namespace CacheManager.Core.Logging { #pragma warning disable CS1591 // Missing XML comment for publicly visible type or member public static class LoggerExtensions { //// Critical public static void LogCritical(this ILogger logger, string message, params object[] args) { if (logger == null) { throw new ArgumentNullException(nameof(logger)); } logger.Log(LogLevel.Critical, 0, new FormatMessage(message, args), null); } public static void LogCritical(this ILogger logger, int eventId, string message, params object[] args) { if (logger == null) { throw new ArgumentNullException(nameof(logger)); } logger.Log(LogLevel.Critical, eventId, new FormatMessage(message, args), null); } public static void LogCritical(this ILogger logger, Exception exception, string message, params object[] args) { if (logger == null) { throw new ArgumentNullException(nameof(logger)); } logger.Log(LogLevel.Critical, 0, new FormatMessage(message, args), exception); } public static void LogCritical(this ILogger logger, int eventId, Exception exception, string message, params object[] args) { if (logger == null) { throw new ArgumentNullException(nameof(logger)); } logger.Log(LogLevel.Critical, eventId, new FormatMessage(message, args), exception); } //// DEBUG public static void LogDebug(this ILogger logger, string message, params object[] args) { if (logger == null) { throw new ArgumentNullException(nameof(logger)); } logger.Log(LogLevel.Debug, 0, new FormatMessage(message, args), null); } public static void LogDebug(this ILogger logger, int eventId, string message, params object[] args) { if (logger == null) { throw new ArgumentNullException(nameof(logger)); } logger.Log(LogLevel.Debug, eventId, new FormatMessage(message, args), null); } public static void LogDebug(this ILogger logger, Exception exception, string message, params object[] args) { if (logger == null) { throw new ArgumentNullException(nameof(logger)); } logger.Log(LogLevel.Debug, 0, new FormatMessage(message, args), exception); } public static void LogDebug(this ILogger logger, int eventId, Exception exception, string message, params object[] args) { if (logger == null) { throw new ArgumentNullException(nameof(logger)); } logger.Log(LogLevel.Debug, eventId, new FormatMessage(message, args), exception); } //// Error public static void LogError(this ILogger logger, string message, params object[] args) { if (logger == null) { throw new ArgumentNullException(nameof(logger)); } logger.Log(LogLevel.Error, 0, new FormatMessage(message, args), null); } public static void LogError(this ILogger logger, int eventId, string message, params object[] args) { if (logger == null) { throw new ArgumentNullException(nameof(logger)); } logger.Log(LogLevel.Error, eventId, new FormatMessage(message, args), null); } public static void LogError(this ILogger logger, Exception exception, string message, params object[] args) { if (logger == null) { throw new ArgumentNullException(nameof(logger)); } logger.Log(LogLevel.Error, 0, new FormatMessage(message, args), exception); } public static void LogError(this ILogger logger, int eventId, Exception exception, string message, params object[] args) { if (logger == null) { throw new ArgumentNullException(nameof(logger)); } logger.Log(LogLevel.Error, eventId, new FormatMessage(message, args), exception); } //// Information public static void LogInfo(this ILogger logger, string message, params object[] args) { if (logger == null) { throw new ArgumentNullException(nameof(logger)); } logger.Log(LogLevel.Information, 0, new FormatMessage(message, args), null); } public static void LogInfo(this ILogger logger, int eventId, string message, params object[] args) { if (logger == null) { throw new ArgumentNullException(nameof(logger)); } logger.Log(LogLevel.Information, eventId, new FormatMessage(message, args), null); } public static void LogInfo(this ILogger logger, Exception exception, string message, params object[] args) { if (logger == null) { throw new ArgumentNullException(nameof(logger)); } logger.Log(LogLevel.Information, 0, new FormatMessage(message, args), exception); } public static void LogInfo(this ILogger logger, int eventId, Exception exception, string message, params object[] args) { if (logger == null) { throw new ArgumentNullException(nameof(logger)); } logger.Log(LogLevel.Information, eventId, new FormatMessage(message, args), exception); } //// Trace public static void LogTrace(this ILogger logger, string message, params object[] args) { if (logger == null) { throw new ArgumentNullException(nameof(logger)); } logger.Log(LogLevel.Trace, 0, new FormatMessage(message, args), null); } public static void LogTrace(this ILogger logger, int eventId, string message, params object[] args) { if (logger == null) { throw new ArgumentNullException(nameof(logger)); } logger.Log(LogLevel.Trace, eventId, new FormatMessage(message, args), null); } public static void LogTrace(this ILogger logger, Exception exception, string message, params object[] args) { if (logger == null) { throw new ArgumentNullException(nameof(logger)); } logger.Log(LogLevel.Trace, 0, new FormatMessage(message, args), exception); } public static void LogTrace(this ILogger logger, int eventId, Exception exception, string message, params object[] args) { if (logger == null) { throw new ArgumentNullException(nameof(logger)); } logger.Log(LogLevel.Trace, eventId, new FormatMessage(message, args), exception); } //// Warning public static void LogWarn(this ILogger logger, string message, params object[] args) { if (logger == null) { throw new ArgumentNullException(nameof(logger)); } logger.Log(LogLevel.Warning, 0, new FormatMessage(message, args), null); } public static void LogWarn(this ILogger logger, int eventId, string message, params object[] args) { if (logger == null) { throw new ArgumentNullException(nameof(logger)); } logger.Log(LogLevel.Warning, eventId, new FormatMessage(message, args), null); } public static void LogWarn(this ILogger logger, Exception exception, string message, params object[] args) { if (logger == null) { throw new ArgumentNullException(nameof(logger)); } logger.Log(LogLevel.Warning, 0, new FormatMessage(message, args), exception); } public static void LogWarn(this ILogger logger, int eventId, Exception exception, string message, params object[] args) { if (logger == null) { throw new ArgumentNullException(nameof(logger)); } logger.Log(LogLevel.Warning, eventId, new FormatMessage(message, args), exception); } private class FormatMessage { private readonly string format; private readonly object[] args; public FormatMessage(string format, params object[] args) { this.format = format; this.args = args; } public override string ToString() { if (this.args == null || this.args.Length == 0) { return this.format; } return string.Format(CultureInfo.CurrentCulture, this.format, this.args); } } } #pragma warning restore CS1591 // Missing XML comment for publicly visible type or member }
33.295775
131
0.564404
[ "ECL-2.0", "Apache-2.0" ]
Arch/CacheManager
src/CacheManager.Core/Logging/LoggerExtensions.cs
9,458
C#
// Copyright 2022 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. // Generated code. DO NOT EDIT! namespace Google.Cloud.AIPlatform.V1.Snippets { // [START aiplatform_v1_generated_MetadataService_DeleteArtifact_async_flattened_resourceNames] using Google.Cloud.AIPlatform.V1; using Google.LongRunning; using Google.Protobuf.WellKnownTypes; using System.Threading.Tasks; public sealed partial class GeneratedMetadataServiceClientSnippets { /// <summary>Snippet for DeleteArtifactAsync</summary> /// <remarks> /// This snippet has been automatically generated for illustrative purposes only. /// It may require modifications to work in your environment. /// </remarks> public async Task DeleteArtifactResourceNamesAsync() { // Create client MetadataServiceClient metadataServiceClient = await MetadataServiceClient.CreateAsync(); // Initialize request argument(s) ArtifactName name = ArtifactName.FromProjectLocationMetadataStoreArtifact("[PROJECT]", "[LOCATION]", "[METADATA_STORE]", "[ARTIFACT]"); // Make the request Operation<Empty, DeleteOperationMetadata> response = await metadataServiceClient.DeleteArtifactAsync(name); // Poll until the returned long-running operation is complete Operation<Empty, DeleteOperationMetadata> completedResponse = await response.PollUntilCompletedAsync(); // Retrieve the operation result Empty result = completedResponse.Result; // Or get the name of the operation string operationName = response.Name; // This name can be stored, then the long-running operation retrieved later by name Operation<Empty, DeleteOperationMetadata> retrievedResponse = await metadataServiceClient.PollOnceDeleteArtifactAsync(operationName); // Check if the retrieved long-running operation has completed if (retrievedResponse.IsCompleted) { // If it has completed, then access the result Empty retrievedResult = retrievedResponse.Result; } } } // [END aiplatform_v1_generated_MetadataService_DeleteArtifact_async_flattened_resourceNames] }
47.2
147
0.705508
[ "Apache-2.0" ]
AlexandrTrf/google-cloud-dotnet
apis/Google.Cloud.AIPlatform.V1/Google.Cloud.AIPlatform.V1.GeneratedSnippets/MetadataServiceClient.DeleteArtifactResourceNamesAsyncSnippet.g.cs
2,832
C#
// Decompiled with JetBrains decompiler // Type: SynapseGaming.LightingSystem.Core.IPreferences // Assembly: SynapseGaming-SunBurn-Pro, Version=1.3.2.8, Culture=neutral, PublicKeyToken=c23c60523565dbfd // MVID: A5F03349-72AC-4BAA-AEEE-9AB9B77E0A39 // Assembly location: C:\Projects\BlackBox\StarDrive\SynapseGaming-SunBurn-Pro.dll namespace SynapseGaming.LightingSystem.Core { /// <summary> /// Interface that provides a base for all objects that load and save user preference. /// </summary> public interface IPreferences { /// <summary>Loads user preference from a file.</summary> /// <param name="filename"></param> void LoadFromFile(string filename); /// <summary>Saves user preference to a file.</summary> /// <param name="filename"></param> void SaveToFile(string filename); } }
36.782609
106
0.712766
[ "MIT" ]
UnGaucho/StarDrive
SynapseGaming-SunBurn-Pro/SynapseGaming/LightingSystem/Core/IPreferences.cs
848
C#
using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.Mvc.Formatters; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Redmanmale.TelegramToRss.DAL; namespace Redmanmale.TelegramToRss { public class Startup { public Startup(IConfiguration configuration) { Configuration = configuration; } public IConfiguration Configuration { get; } // This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { services.AddMvc(o => o.OutputFormatters.Add(new XmlDataContractSerializerOutputFormatter())); services.AddSingleton<IStorage, Storage>(s => ConfigurationManager.CreateStorage(Configuration)); } // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IHostingEnvironment env) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } app.UseMvc(); } } }
32.710526
109
0.678198
[ "MIT" ]
redmanmale/TelegramToRss
TelegramToRss/Startup.cs
1,245
C#
using System; using System.Runtime.InteropServices; namespace OBSMidiRemote.Lib.PureMidi.Data { [StructLayout(LayoutKind.Sequential)] internal struct MidiHeader { public IntPtr data; public int bufferLength; public int bytesRecorded; public int user; public int flags; public IntPtr next; public int reserved; public int offset; [MarshalAs(UnmanagedType.ByValArray, SizeConst=4)] public int[] reservedArray; } }
23.227273
58
0.655577
[ "Apache-2.0" ]
TechFactoryHU/OBSMidiRemote
OBSMidiRemote/Lib/PureMidi/Data/MidiHeader.cs
513
C#
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using BootShop_2019.Models.Services; using BootShop_2019.Models.ViewModels; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc; namespace BootProduct_2019.Controllers { public class ProductController : Controller { private ProductService _productService; public ProductController(ProductService productService) { _productService = productService; } // GET: Product public ActionResult Index() { var model = _productService.GetProducts(); return View(model); } // GET: Product/Details/5 public ActionResult Details(int id) { try { var model = _productService.GetProductDetails(id); return View(model); } catch { return RedirectToAction(nameof(Index)); } } // GET: Product/Create public ActionResult Create() { var model = _productService.Create(); return View(model); } // POST: Product/Create [HttpPost] [ValidateAntiForgeryToken] public ActionResult Create(ProductViewModel model) { try { bool result = _productService.AddProduct(model); if (result) { return RedirectToAction(nameof(Index)); } throw new Exception(); } catch { ModelState.AddModelError(string.Empty, "Ooops! Something went wrong!"); return View(); } } // GET: Product/Edit/5 public ActionResult Edit(int id) { try { var model = _productService.GetProductDetails(id); return View(model); } catch { return RedirectToAction(nameof(Index)); } } // POST: Product/Edit/5 [HttpPost] [ValidateAntiForgeryToken] public ActionResult Edit(int id, ProductViewModel model) { try { bool result = _productService.UpdateProduct(model); if (result) { return RedirectToAction(nameof(Index)); } throw new Exception(); } catch { ModelState.AddModelError(string.Empty, "Ooops! Something went wrong!"); return View(); } } // GET: Product/Delete/5 public ActionResult Delete(int id) { try { var model = _productService.GetProductDetails(id); return View(model); } catch { return RedirectToAction(nameof(Index)); } } // POST: Product/Delete/5 [HttpPost] [ValidateAntiForgeryToken] public ActionResult Delete(int id, ProductViewModel model) { try { bool result = _productService.DeleteProduct(id); if (result) { return RedirectToAction(nameof(Index)); } throw new Exception(); } catch { ModelState.AddModelError(string.Empty, "Ooops! Something went wrong!"); return View(); } } } }
25.216216
87
0.482047
[ "MIT" ]
koninlord/BootShop-Web
BootShop_2019/Controllers/ProductController.cs
3,734
C#
namespace OnlyT.AnalogueClock { // ReSharper disable UnusedMember.Global using System; using System.ComponentModel; using System.Globalization; using System.Threading.Tasks; using System.Windows; using System.Windows.Controls; using System.Windows.Media; using System.Windows.Media.Effects; using System.Windows.Shapes; using System.Windows.Threading; public class ClockControl : Control { public static readonly DependencyProperty DigitalTimeFormatShowLeadingZeroProperty = DependencyProperty.Register( "DigitalTimeFormatShowLeadingZero", typeof(bool), typeof(ClockControl), new FrameworkPropertyMetadata(DigitalTimeFormatShowLeadingZeroPropertyChanged)); public static readonly DependencyProperty DigitalTimeFormat24HoursProperty = DependencyProperty.Register( "DigitalTimeFormat24Hours", typeof(bool), typeof(ClockControl), new FrameworkPropertyMetadata(DigitalTimeFormat24HoursPropertyChanged)); public static readonly DependencyProperty DigitalTimeFormatAMPMProperty = DependencyProperty.Register( "DigitalTimeFormatAMPM", typeof(bool), typeof(ClockControl), new FrameworkPropertyMetadata(DigitalTimeFormatAMPMPropertyChanged)); public static readonly DependencyProperty IsRunningProperty = DependencyProperty.Register( "IsRunning", typeof(bool), typeof(ClockControl), new FrameworkPropertyMetadata(IsRunningPropertyChanged)); public static readonly DependencyProperty CurrentTimeHrMinProperty = DependencyProperty.Register( "CurrentTimeHrMin", typeof(string), typeof(ClockControl)); public static readonly DependencyProperty CurrentTimeSecProperty = DependencyProperty.Register( "CurrentTimeSec", typeof(string), typeof(ClockControl)); public static readonly DependencyProperty DurationSectorProperty = DependencyProperty.Register( "DurationSector", typeof(DurationSector), typeof(ClockControl), new FrameworkPropertyMetadata(DurationSectorPropertyChanged)); private const double HourHandDropShadowOpacity = 1.0; private const double MinuteHandDropShadowOpacity = 0.4; private const double SecondHandDropShadowOpacity = 0.3; private static readonly double ClockRadius = 250; private static readonly double SectorRadius = 230; private static readonly Point ClockOrigin = new Point(ClockRadius, ClockRadius); private static readonly TimeSpan TimerInterval = TimeSpan.FromMilliseconds(100); private static readonly TimeSpan AnimationTimerInterval = TimeSpan.FromMilliseconds(20); private static readonly double AngleTolerance = 0.75; private readonly DispatcherTimer _timer; private readonly DispatcherTimer _animationTimer; private AnglesOfHands _animationTargetAngles; private AnglesOfHands _animationCurrentAngles; private bool _showElapsedSector; private Line _minuteHand; private Line _hourHand; private Line _secondHand; private Path _sectorPath1; private Path _sectorPath2; private Path _sectorPath3; private bool _digitalFormatLeadingZero; private bool _digitalFormat24Hours; private bool _digitalFormatAMPM; static ClockControl() { DefaultStyleKeyProperty.OverrideMetadata( typeof(ClockControl), new FrameworkPropertyMetadata(typeof(ClockControl))); } public ClockControl() { var isInDesignMode = DesignerProperties.GetIsInDesignMode(this); _showElapsedSector = true; _timer = new DispatcherTimer(DispatcherPriority.Render) { Interval = TimerInterval }; _timer.Tick += TimerCallback; _animationTimer = new DispatcherTimer(DispatcherPriority.Render) { Interval = AnimationTimerInterval }; _animationTimer.Tick += AnimationCallback; if (isInDesignMode) { CurrentTimeHrMin = "3:50"; CurrentTimeSec = "20"; } } public bool DigitalTimeFormat24Hours { // ReSharper disable once PossibleNullReferenceException get => (bool)GetValue(DigitalTimeFormat24HoursProperty); set => SetValue(DigitalTimeFormat24HoursProperty, value); } public bool DigitalTimeFormatAMPM { // ReSharper disable once PossibleNullReferenceException get => (bool)GetValue(DigitalTimeFormatAMPMProperty); set => SetValue(DigitalTimeFormatAMPMProperty, value); } public bool IsRunning { // ReSharper disable once PossibleNullReferenceException get => (bool)GetValue(IsRunningProperty); set => SetValue(IsRunningProperty, value); } public DurationSector DurationSector { get => (DurationSector)GetValue(DurationSectorProperty); set => SetValue(DurationSectorProperty, value); } public bool DigitalTimeFormatShowLeadingZero { // ReSharper disable once PossibleNullReferenceException get => (bool)GetValue(DigitalTimeFormatShowLeadingZeroProperty); set => SetValue(DigitalTimeFormatShowLeadingZeroProperty, value); } public string CurrentTimeHrMin { // ReSharper disable once PossibleNullReferenceException // ReSharper disable once UnusedMember.Local get => (string)GetValue(CurrentTimeHrMinProperty); private set => SetValue(CurrentTimeHrMinProperty, value); } public string CurrentTimeSec { // ReSharper disable once PossibleNullReferenceException // ReSharper disable once UnusedMember.Local get => (string)GetValue(CurrentTimeSecProperty); private set => SetValue(CurrentTimeSecProperty, value); } public override void OnApplyTemplate() { base.OnApplyTemplate(); GetElementRefs(); if (GetTemplateChild("ClockCanvas") is Canvas cc) { GenerateHourMarkers(cc); GenerateHourNumbers(cc); } } private static void DigitalTimeFormatShowLeadingZeroPropertyChanged( DependencyObject d, DependencyPropertyChangedEventArgs e) { var c = (ClockControl)d; c._digitalFormatLeadingZero = (bool)e.NewValue; } private static void DigitalTimeFormat24HoursPropertyChanged( DependencyObject d, DependencyPropertyChangedEventArgs e) { var c = (ClockControl)d; c._digitalFormat24Hours = (bool)e.NewValue; } private static void DigitalTimeFormatAMPMPropertyChanged( DependencyObject d, DependencyPropertyChangedEventArgs e) { var c = (ClockControl)d; c._digitalFormatAMPM = (bool)e.NewValue; } private static void IsRunningPropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) { var b = (bool)e.NewValue; var c = (ClockControl)d; if (b) { c.StartupAnimation(); } else { c._timer.IsEnabled = false; } } private static void DurationSectorPropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) { var sector = (DurationSector)e.NewValue; var c = (ClockControl)d; if (sector == null) { c._sectorPath1.Data = null; c._sectorPath2.Data = null; c._sectorPath3.Data = null; } else { bool delay = e.OldValue == null; if (delay) { // the first time we display the sector we delay it for aesthetics // (so it doesn't appear just as the clock is fading out) Task.Delay(1000).ContinueWith(t => { c.Dispatcher.Invoke(() => { DrawSector(c, sector); }); }); } else { DrawSector(c, sector); } } } private static void DrawSector(ClockControl c, DurationSector sector) { // we may have 1, 2 or 3 sectors to draw... // green sector... if (!sector.IsOvertime) { DrawSector(c._sectorPath1, sector.StartAngle, sector.EndAngle, IsLargeArc(sector.StartAngle, sector.EndAngle)); } c.ShowElapsedSector = sector.ShowElapsedSector; // light green sector... DrawSector(c._sectorPath2, sector.StartAngle, sector.CurrentAngle, IsLargeArc(sector.StartAngle, sector.CurrentAngle)); if (sector.IsOvertime) { // red sector... DrawSector(c._sectorPath3, sector.EndAngle, sector.CurrentAngle, IsLargeArc(sector.EndAngle, sector.CurrentAngle)); } } private static bool IsLargeArc(double startAngle, double endAngle) { if (endAngle < startAngle) { return (360 - startAngle + endAngle) > 180; } return endAngle - startAngle >= 180.0; } private static void DrawSector(Path sectorPath, double startAngle, double endAngle, bool isLargeArc) { var startPoint = PointOnCircle(SectorRadius, startAngle, ClockOrigin); var endPoint = PointOnCircle(SectorRadius, endAngle, ClockOrigin); string largeArc = isLargeArc ? "1" : "0"; // use InvariantCulture to ensure that decimal separator is '.' sectorPath.Data = Geometry.Parse($"M{ClockRadius.ToString(CultureInfo.InvariantCulture)},{ClockRadius.ToString(CultureInfo.InvariantCulture)} L{startPoint.X.ToString(CultureInfo.InvariantCulture)},{startPoint.Y.ToString(CultureInfo.InvariantCulture)} A{SectorRadius.ToString(CultureInfo.InvariantCulture)},{SectorRadius.ToString(CultureInfo.InvariantCulture)} 0 {largeArc} 1 {endPoint.X.ToString(CultureInfo.InvariantCulture)},{endPoint.Y.ToString(CultureInfo.InvariantCulture)} z"); } private static Point PointOnCircle(double radius, double angleInDegrees, Point origin) { // NB - angleInDegrees is from 12 o'clock rather than from 3 o'clock var x = (radius * Math.Cos((angleInDegrees - 90) * Math.PI / 180F)) + origin.X; var y = (radius * Math.Sin((angleInDegrees - 90) * Math.PI / 180F)) + origin.Y; return new Point(x, y); } private double CalculateAngleSeconds(DateTime dt) { return dt.Second * 6; } private double CalculateAngleMinutes(DateTime dt) { return (dt.Minute * 6) + (dt.Second * 0.1) + (dt.Millisecond * 0.0001); } private double CalculateAngleHours(DateTime dt) { var hr = dt.Hour >= 12 ? dt.Hour - 12 : dt.Hour; return (hr * 30) + (((double)dt.Minute / 60) * 30); } private void PositionClockHand(Line hand, double angle, double shadowOpacity) { ((DropShadowEffect)hand.Effect).Opacity = shadowOpacity; ((DropShadowEffect)hand.Effect).Direction = angle; hand.RenderTransform = new RotateTransform(angle, ClockRadius, ClockRadius); } private void TimerCallback(object sender, EventArgs eventArgs) { var now = DateTime.Now; PositionClockHand(_secondHand, CalculateAngleSeconds(now), SecondHandDropShadowOpacity); PositionClockHand(_minuteHand, CalculateAngleMinutes(now), MinuteHandDropShadowOpacity); PositionClockHand(_hourHand, CalculateAngleHours(now), HourHandDropShadowOpacity); CurrentTimeHrMin = FormatTimeOfDayHoursAndMins(now); CurrentTimeSec = FormatTimeOfDaySeconds(now); } private string FormatTimeOfDayHoursAndMins(DateTime dt) { int hours = _digitalFormat24Hours ? dt.Hour : dt.Hour > 12 ? dt.Hour - 12 : dt.Hour; var ampm = GetAmPmPostfix(dt); if (_digitalFormatLeadingZero) { return $"{hours:D2}:{dt.Minute:D2}{ampm}"; } return $"{hours}:{dt.Minute:D2}{ampm}"; } private string GetAmPmPostfix(DateTime dt) { if (!_digitalFormatAMPM) { return string.Empty; } var ampm = dt.ToString("tt"); if (string.IsNullOrEmpty(ampm)) { return string.Empty; } return $" {ampm}"; } private string FormatTimeOfDaySeconds(DateTime dt) { return _digitalFormatAMPM ? string.Empty : dt.Second.ToString("D2"); } private void StartupAnimation() { _animationTargetAngles = GenerateTargetAngles(); _animationCurrentAngles = new AnglesOfHands { HoursAngle = 0.0, MinutesAngle = 0.0, SecondsAngle = 0.0 }; _animationTimer.Start(); } private AnglesOfHands GenerateTargetAngles() { DateTime targetTime = DateTime.Now; return new AnglesOfHands { SecondsAngle = CalculateAngleSeconds(targetTime), MinutesAngle = CalculateAngleMinutes(targetTime), HoursAngle = CalculateAngleHours(targetTime) }; } private void AnimationCallback(object sender, EventArgs eventArgs) { ((DispatcherTimer)sender).Stop(); _animationCurrentAngles.SecondsAngle = AnimateHand( _secondHand, _animationCurrentAngles.SecondsAngle, _animationTargetAngles.SecondsAngle, SecondHandDropShadowOpacity); _animationCurrentAngles.MinutesAngle = AnimateHand( _minuteHand, _animationCurrentAngles.MinutesAngle, _animationTargetAngles.MinutesAngle, MinuteHandDropShadowOpacity); _animationCurrentAngles.HoursAngle = AnimateHand( _hourHand, _animationCurrentAngles.HoursAngle, _animationTargetAngles.HoursAngle, HourHandDropShadowOpacity); if (AnimationShouldContinue()) { ((DispatcherTimer)sender).Start(); } else { _timer.Start(); } } private double AnimateHand(Line hand, double currentAngle, double targetAngle, double shadowOpacity) { if (Math.Abs(currentAngle - targetAngle) > AngleTolerance) { double delta = (targetAngle - currentAngle) / 5; currentAngle += delta; PositionClockHand(hand, currentAngle, shadowOpacity); } return currentAngle; } private bool AnimationShouldContinue() { return Math.Abs(_animationCurrentAngles.SecondsAngle - _animationTargetAngles.SecondsAngle) > AngleTolerance || Math.Abs(_animationCurrentAngles.MinutesAngle - _animationTargetAngles.MinutesAngle) > AngleTolerance || Math.Abs(_animationCurrentAngles.HoursAngle - _animationTargetAngles.HoursAngle) > AngleTolerance; } private TextBlock CreateHourNumberTextBlock(int hour) { return new TextBlock { Text = hour.ToString(), FontSize = 36, VerticalAlignment = VerticalAlignment.Center, HorizontalAlignment = HorizontalAlignment.Center, FontWeight = FontWeights.Bold, Foreground = Brushes.DarkSlateBlue }; } private void GenerateHourNumbers(Canvas canvas) { double clockRadius = canvas.Width / 2; double centrePointRadius = clockRadius - 50; double borderSize = 80; for (int n = 0; n < 12; ++n) { var angle = n * 30; var pt = PointOnCircle(centrePointRadius, angle, ClockOrigin); var hour = n == 0 ? 12 : n; var t = CreateHourNumberTextBlock(hour); var b = new Border { Width = borderSize, Height = borderSize, Child = t }; canvas.Children.Add(b); Canvas.SetLeft(b, pt.X - (borderSize / 2)); Canvas.SetTop(b, pt.Y - (borderSize / 2)); } } private void GenerateHourMarkers(Canvas canvas) { var angle = 0; for (var n = 0; n < 4; ++n) { var line = CreateMajorHourMarker(); line.RenderTransform = new RotateTransform(angle += 90, ClockRadius, ClockRadius); canvas.Children.Add(line); } for (var n = 0; n < 12; ++n) { if (n % 3 > 0) { var line = CreateMinorHourMarker(); line.RenderTransform = new RotateTransform(angle, ClockRadius, ClockRadius); canvas.Children.Add(line); } angle += 30; } for (var n = 0; n < 60; ++n) { if (n % 5 > 0) { var line = CreateMinuteMarker(); line.RenderTransform = new RotateTransform(angle, ClockRadius, ClockRadius); canvas.Children.Add(line); } angle += 6; } } private Line CreateMajorHourMarker() { return new Line { Stroke = Brushes.Black, StrokeThickness = 7, X1 = ClockRadius, Y1 = 19, X2 = ClockRadius, Y2 = 27 }; } private Line CreateMinorHourMarker() { return new Line { Stroke = Brushes.Black, StrokeThickness = 3, X1 = ClockRadius, Y1 = 19, X2 = ClockRadius, Y2 = 25 }; } private Line CreateMinuteMarker() { return new Line { Stroke = Brushes.Black, StrokeThickness = 1, X1 = ClockRadius, Y1 = 19, X2 = ClockRadius, Y2 = 25 }; } private void GetElementRefs() { if (GetTemplateChild("MinuteHand") is Line line1) { _minuteHand = line1; _minuteHand.Effect = new DropShadowEffect { Color = Colors.DarkGray, BlurRadius = 5, ShadowDepth = 3, Opacity = MinuteHandDropShadowOpacity }; } if (GetTemplateChild("HourHand") is Line line2) { _hourHand = line2; _hourHand.Effect = new DropShadowEffect { Color = Colors.DarkGray, BlurRadius = 5, ShadowDepth = 3, Opacity = HourHandDropShadowOpacity }; } if (GetTemplateChild("SecondHand") is Line line3) { _secondHand = line3; _secondHand.Effect = new DropShadowEffect { Color = Colors.DarkGray, BlurRadius = 1.2, ShadowDepth = 3, Opacity = SecondHandDropShadowOpacity }; } if (GetTemplateChild("SectorPath1") is Path sectorPath1) { _sectorPath1 = sectorPath1; } if (GetTemplateChild("SectorPath2") is Path sectorPath2) { _sectorPath2 = sectorPath2; } if (GetTemplateChild("SectorPath3") is Path sectorPath3) { _sectorPath3 = sectorPath3; } } private bool ShowElapsedSector { get => _showElapsedSector; set { if (_showElapsedSector != value) { _showElapsedSector = value; if (_showElapsedSector) { _sectorPath2.Fill = new SolidColorBrush(Color.FromRgb(230, 255, 230)); _sectorPath2.StrokeThickness = 1; } else { _sectorPath2.Fill = Brushes.White; _sectorPath2.StrokeThickness = 0; } } } } } }
34.687011
495
0.550011
[ "MIT" ]
diagdave1/OnlyT-1
OnlyT.AnalogueClock/ClockControl.cs
22,167
C#
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for license information. // Code generated by Microsoft (R) AutoRest Code Generator. // Changes may cause incorrect behavior and will be lost if the code is regenerated. namespace Microsoft.Azure.PowerShell.Cmdlets.Functions.Models.Api20190801 { using Microsoft.Azure.PowerShell.Cmdlets.Functions.Runtime.PowerShell; /// <summary> /// A PowerShell PSTypeConverter to support converting to an instance of <see cref="MigrateMySqlStatus" /> /// </summary> public partial class MigrateMySqlStatusTypeConverter : global::System.Management.Automation.PSTypeConverter { /// <summary> /// Determines if the converter can convert the <see cref="sourceValue"/> parameter to the <see cref="destinationType" /> /// parameter. /// </summary> /// <param name="sourceValue">the <see cref="System.Object"/> to convert from</param> /// <param name="destinationType">the <see cref="System.Type" /> to convert to</param> /// <returns> /// <c>true</c> if the converter can convert the <see cref="sourceValue"/> parameter to the <see cref="destinationType" /> /// parameter, otherwise <c>false</c>. /// </returns> public override bool CanConvertFrom(object sourceValue, global::System.Type destinationType) => CanConvertFrom(sourceValue); /// <summary> /// Determines if the converter can convert the <see cref="sourceValue"/> parameter to the <see cref="destinationType" /> /// parameter. /// </summary> /// <param name="sourceValue">the <see cref="System.Object" /> instance to check if it can be converted to the <see cref="MigrateMySqlStatus" /// /> type.</param> /// <returns> /// <c>true</c> if the instance could be converted to a <see cref="MigrateMySqlStatus" /> type, otherwise <c>false</c> /// </returns> public static bool CanConvertFrom(dynamic sourceValue) { if (null == sourceValue) { return true; } global::System.Type type = sourceValue.GetType(); if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) { // we say yest to PSObjects return true; } if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) { // we say yest to Hashtables/dictionaries return true; } try { if (null != sourceValue.ToJsonString()) { return true; } } catch { // Not one of our objects } try { string text = sourceValue.ToString()?.Trim(); return true == text?.StartsWith("{") && true == text?.EndsWith("}") && Microsoft.Azure.PowerShell.Cmdlets.Functions.Runtime.Json.JsonNode.Parse(text).Type == Microsoft.Azure.PowerShell.Cmdlets.Functions.Runtime.Json.JsonType.Object; } catch { // Doesn't look like it can be treated as JSON } return false; } /// <summary> /// Determines if the <see cref="sourceValue" /> parameter can be converted to the <see cref="destinationType" /> parameter /// </summary> /// <param name="sourceValue">the <see cref="System.Object"/> to convert from</param> /// <param name="destinationType">the <see cref="System.Type" /> to convert to</param> /// <returns> /// <c>true</c> if the converter can convert the <see cref="sourceValue" /> parameter to the <see cref="destinationType" /> /// parameter, otherwise <c>false</c> /// </returns> public override bool CanConvertTo(object sourceValue, global::System.Type destinationType) => false; /// <summary> /// Converts the <see cref="sourceValue" /> parameter to the <see cref="destinationType" /> parameter using <see cref="formatProvider" /// /> and <see cref="ignoreCase" /> /// </summary> /// <param name="sourceValue">the <see cref="System.Object"/> to convert from</param> /// <param name="destinationType">the <see cref="System.Type" /> to convert to</param> /// <param name="formatProvider">not used by this TypeConverter.</param> /// <param name="ignoreCase">when set to <c>true</c>, will ignore the case when converting.</param> /// <returns> /// an instance of <see cref="MigrateMySqlStatus" />, or <c>null</c> if there is no suitable conversion. /// </returns> public override object ConvertFrom(object sourceValue, global::System.Type destinationType, global::System.IFormatProvider formatProvider, bool ignoreCase) => ConvertFrom(sourceValue); /// <summary> /// Converts the <see cref="sourceValue" /> parameter to the <see cref="destinationType" /> parameter using <see cref="formatProvider" /// /> and <see cref="ignoreCase" /> /// </summary> /// <param name="sourceValue">the value to convert into an instance of <see cref="MigrateMySqlStatus" />.</param> /// <returns> /// an instance of <see cref="MigrateMySqlStatus" />, or <c>null</c> if there is no suitable conversion. /// </returns> public static Microsoft.Azure.PowerShell.Cmdlets.Functions.Models.Api20190801.IMigrateMySqlStatus ConvertFrom(dynamic sourceValue) { if (null == sourceValue) { return null; } global::System.Type type = sourceValue.GetType(); if (typeof(Microsoft.Azure.PowerShell.Cmdlets.Functions.Models.Api20190801.IMigrateMySqlStatus).IsAssignableFrom(type)) { return sourceValue; } try { return MigrateMySqlStatus.FromJsonString(typeof(string) == sourceValue.GetType() ? sourceValue : sourceValue.ToJsonString());; } catch { // Unable to use JSON pattern } if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) { return MigrateMySqlStatus.DeserializeFromPSObject(sourceValue); } if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) { return MigrateMySqlStatus.DeserializeFromDictionary(sourceValue); } return null; } /// <summary>NotImplemented -- this will return <c>null</c></summary> /// <param name="sourceValue">the <see cref="System.Object"/> to convert from</param> /// <param name="destinationType">the <see cref="System.Type" /> to convert to</param> /// <param name="formatProvider">not used by this TypeConverter.</param> /// <param name="ignoreCase">when set to <c>true</c>, will ignore the case when converting.</param> /// <returns>will always return <c>null</c>.</returns> public override object ConvertTo(object sourceValue, global::System.Type destinationType, global::System.IFormatProvider formatProvider, bool ignoreCase) => null; } }
51.918367
249
0.591064
[ "MIT" ]
Agazoth/azure-powershell
src/Functions/generated/api/Models/Api20190801/MigrateMySqlStatus.TypeConverter.cs
7,486
C#
// Copyright (c) Microsoft Corporation // All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); you may not // use this file except in compliance with the License. You may obtain a copy // of the License at http://www.apache.org/licenses/LICENSE-2.0 // // THIS CODE IS PROVIDED *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY // KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED // WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, // MERCHANTABLITY OR NON-INFRINGEMENT. // // See the Apache Version 2.0 License for specific language governing // permissions and limitations under the License. namespace Microsoft.HBase.Client.Tests.Utilities { using Microsoft.VisualStudio.TestTools.UnitTesting; /// <summary> /// Provides common services for BDD-style (context/specification) unit tests. /// Serves as an adapter between the MSTest framework and our BDD-style tests. /// </summary> //// Borrowed from the blog of SaintGimp (with permission). [TestClass] public abstract class ContextSpecification : TestBase { /// <summary> /// Sets up the environment for a specification context. /// </summary> protected virtual void Context() { } /// <summary> /// Acts on the context to create the observable condition. /// </summary> protected virtual void BecauseOf() { } /// <inheritdoc/> [TestInitialize] public override void TestInitialize() { base.TestInitialize(); Context(); BecauseOf(); } } }
32.113208
84
0.650999
[ "Apache-2.0" ]
Tchami/hbase-sdk-for-net
Microsoft.HBase.Client.Tests/Utilities/ContextSpecification.cs
1,704
C#
// SPDX-FileCopyrightText: 2021 smdn <smdn@smdn.jp> // SPDX-License-Identifier: MIT using System; using System.Buffers; using System.Runtime.CompilerServices; namespace Smdn.Formats; public static class Hexadecimal { private const string UpperCaseHexCharsInString = "0123456789ABCDEF"; private const string LowerCaseHexCharsInString = "0123456789abcdef"; private static readonly ReadOnlyMemory<byte> upperCaseHexOctets = new byte[] { 0x30, 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, 0x38, 0x39, 0x41, 0x42, 0x43, 0x44, 0x45, 0x46, }; public static ReadOnlySpan<byte> UpperCaseHexOctets => upperCaseHexOctets.Span; private static readonly ReadOnlyMemory<byte> lowerCaseHexOctets = new byte[] { 0x30, 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, 0x38, 0x39, 0x61, 0x62, 0x63, 0x64, 0x65, 0x66, }; public static ReadOnlySpan<byte> LowerCaseHexOctets => lowerCaseHexOctets.Span; public static ReadOnlySpan<char> UpperCaseHexChars => UpperCaseHexCharsInString.AsSpan(); public static ReadOnlySpan<char> LowerCaseHexChars => LowerCaseHexCharsInString.AsSpan(); public static string ToUpperCaseString(ReadOnlySpan<byte> dataSequence) { #if false && SYSTEM_STRING_CREATE // XXX: string.Create does not accept ReadOnlySpan<T>, dotnet/runtime#30175 return string.Create( dataSequence.Length * 2, dataSequence, static (destination, sequence) => TryEncodeUpperCase(sequence, destination, out _) ); #else char[] destination = null; try { var length = dataSequence.Length * 2; destination = ArrayPool<char>.Shared.Rent(length); TryEncodeUpperCase(dataSequence, destination.AsSpan(0, length), out _); #if NETSTANDARD2_1_OR_GREATER || NET5_0_OR_GREATER return new string(destination.AsSpan(0, length)); #else return new string(destination, 0, length); #endif } finally { if (destination is not null) ArrayPool<char>.Shared.Return(destination); } #endif } public static string ToLowerCaseString(ReadOnlySpan<byte> dataSequence) { #if false && SYSTEM_STRING_CREATE // XXX: string.Create does not accept ReadOnlySpan<T>, dotnet/runtime#30175 return string.Create( dataSequence.Length * 2, dataSequence, static (destination, sequence) => TryEncodeLowerCase(sequence, destination, out _) ); #else char[] destination = null; try { var length = dataSequence.Length * 2; destination = ArrayPool<char>.Shared.Rent(length); TryEncodeLowerCase(dataSequence, destination.AsSpan(0, length), out _); #if NETSTANDARD2_1_OR_GREATER || NET5_0_OR_GREATER return new string(destination.AsSpan(0, length)); #else return new string(destination, 0, length); #endif } finally { if (destination is not null) ArrayPool<char>.Shared.Return(destination); } #endif } public static bool TryEncodeUpperCase(ReadOnlySpan<byte> dataSequence, Span<byte> destination, out int bytesEncoded) => TryEncode(dataSequence, destination, UpperCaseHexOctets, out bytesEncoded); public static bool TryEncodeLowerCase(ReadOnlySpan<byte> dataSequence, Span<byte> destination, out int bytesEncoded) => TryEncode(dataSequence, destination, LowerCaseHexOctets, out bytesEncoded); public static bool TryEncodeUpperCase(ReadOnlySpan<byte> dataSequence, Span<char> destination, out int charsEncoded) => TryEncode(dataSequence, destination, UpperCaseHexChars, out charsEncoded); public static bool TryEncodeLowerCase(ReadOnlySpan<byte> dataSequence, Span<char> destination, out int charsEncoded) => TryEncode(dataSequence, destination, LowerCaseHexChars, out charsEncoded); internal static bool TryEncode<T>(ReadOnlySpan<byte> dataSequence, Span<T> destination, ReadOnlySpan<T> hex, out int lengthEncoded) { lengthEncoded = 0; if (dataSequence.IsEmpty) return true; if (destination.Length < dataSequence.Length * 2) return false; // destination to short while (!dataSequence.IsEmpty) { if (!TryEncode(dataSequence[0], destination, hex, out var len)) return false; lengthEncoded += len; dataSequence = dataSequence.Slice(1); destination = destination.Slice(2); } return true; } public static bool TryEncodeUpperCase(byte data, Span<byte> destination, out int bytesEncoded) => TryEncode(data, destination, UpperCaseHexOctets, out bytesEncoded); public static bool TryEncodeLowerCase(byte data, Span<byte> destination, out int bytesEncoded) => TryEncode(data, destination, LowerCaseHexOctets, out bytesEncoded); public static bool TryEncodeUpperCase(byte data, Span<char> destination, out int charsEncoded) => TryEncode(data, destination, UpperCaseHexChars, out charsEncoded); public static bool TryEncodeLowerCase(byte data, Span<char> destination, out int charsEncoded) => TryEncode(data, destination, LowerCaseHexChars, out charsEncoded); [MethodImpl(MethodImplOptions.AggressiveInlining)] internal static bool TryEncode<T>(byte data, Span<T> destination, ReadOnlySpan<T> hex, out int lengthEncoded) { lengthEncoded = default; if (destination.Length < 2) return false; destination[lengthEncoded++] = hex[data >> 4]; destination[lengthEncoded++] = hex[data & 0xf]; return true; } public static bool TryDecodeUpperCase(ReadOnlySpan<char> upperCaseDataSequence, Span<byte> destination, out int decodedLength) => TryDecode(upperCaseDataSequence, destination, allowUpperCase: true, allowLowerCase: false, out decodedLength); public static bool TryDecodeLowerCase(ReadOnlySpan<char> lowerCaseDataSequence, Span<byte> destination, out int decodedLength) => TryDecode(lowerCaseDataSequence, destination, allowUpperCase: false, allowLowerCase: true, out decodedLength); public static bool TryDecode(ReadOnlySpan<char> dataSequence, Span<byte> destination, out int decodedLength) => TryDecode(dataSequence, destination, allowUpperCase: true, allowLowerCase: true, out decodedLength); internal static bool TryDecode(ReadOnlySpan<char> dataSequence, Span<byte> destination, bool allowUpperCase, bool allowLowerCase, out int decodedLength) { decodedLength = 0; if (dataSequence.IsEmpty) return true; var length = dataSequence.Length; if ((length & 0x1) != 0) return false; // incorrect form length >>= 1; if (destination.Length < length) return false; // destination too short for (var i = 0; i < length; i++) { if (!TryDecode(dataSequence.Slice(0, 2), allowUpperCase, allowLowerCase, out byte decodedData)) return false; destination[i] = decodedData; dataSequence = dataSequence.Slice(2); decodedLength++; } return true; } public static bool TryDecodeUpperCase(ReadOnlySpan<byte> upperCaseData, out byte decodedData) => TryDecode(upperCaseData, allowUpperCase: true, allowLowerCase: false, out decodedData); public static bool TryDecodeLowerCase(ReadOnlySpan<byte> lowerCaseData, out byte decodedData) => TryDecode(lowerCaseData, allowUpperCase: false, allowLowerCase: true, out decodedData); public static bool TryDecode(ReadOnlySpan<byte> data, out byte decodedData) => TryDecode(data, allowUpperCase: true, allowLowerCase: true, out decodedData); [MethodImpl(MethodImplOptions.AggressiveInlining)] internal static bool TryDecode(ReadOnlySpan<byte> data, bool allowUpperCase, bool allowLowerCase, out byte decodedData) { decodedData = 0; if (data.Length < 2) return false; if (!TryDecodeValue(data[0], allowUpperCase, allowLowerCase, out var high)) return false; if (!TryDecodeValue(data[1], allowUpperCase, allowLowerCase, out var low)) return false; decodedData = (byte)((high << 4) | low); return true; } public static bool TryDecodeUpperCase(ReadOnlySpan<char> upperCaseData, out byte decodedData) => TryDecode(upperCaseData, allowUpperCase: true, allowLowerCase: false, out decodedData); public static bool TryDecodeLowerCase(ReadOnlySpan<char> lowerCaseData, out byte decodedData) => TryDecode(lowerCaseData, allowUpperCase: false, allowLowerCase: true, out decodedData); public static bool TryDecode(ReadOnlySpan<char> data, out byte decodedData) => TryDecode(data, allowUpperCase: true, allowLowerCase: true, out decodedData); [MethodImpl(MethodImplOptions.AggressiveInlining)] internal static bool TryDecode(ReadOnlySpan<char> data, bool allowUpperCase, bool allowLowerCase, out byte decodedData) { decodedData = 0; if (data.Length < 2) return false; if (!TryDecodeValue(data[0], allowUpperCase, allowLowerCase, out var high)) return false; if (!TryDecodeValue(data[1], allowUpperCase, allowLowerCase, out var low)) return false; decodedData = (byte)((high << 4) | low); return true; } public static bool TryDecodeUpperCaseValue(byte upperCaseData, out byte decodedValue) => TryDecodeValue(upperCaseData, allowUpperCase: true, allowLowerCase: false, out decodedValue); public static bool TryDecodeLowerCaseValue(byte lowerCaseData, out byte decodedValue) => TryDecodeValue(lowerCaseData, allowUpperCase: false, allowLowerCase: true, out decodedValue); public static bool TryDecodeValue(byte data, out byte decodedValue) => TryDecodeValue(data, allowUpperCase: true, allowLowerCase: true, out decodedValue); [MethodImpl(MethodImplOptions.AggressiveInlining)] internal static bool TryDecodeValue(byte data, bool allowUpperCase, bool allowLowerCase, out byte decodedValue) { if (data is >= 0x30 and <= 0x39) { // '0' 0x30 to '9' 0x39 decodedValue = (byte)(data - 0x30); return true; } else if (allowUpperCase && 0x41 <= data && data <= 0x46) { // 'A' 0x41 to 'F' 0x46 decodedValue = (byte)(data - 0x37); return true; } else if (allowLowerCase && 0x61 <= data && data <= 0x66) { // 'a' 0x61 to 'f' 0x66 decodedValue = (byte)(data - 0x57); return true; } else { decodedValue = default; return false; } } public static bool TryDecodeUpperCaseValue(char upperCaseData, out byte decodedValue) => TryDecodeValue(upperCaseData, allowUpperCase: true, allowLowerCase: false, out decodedValue); public static bool TryDecodeLowerCaseValue(char lowerCaseData, out byte decodedValue) => TryDecodeValue(lowerCaseData, allowUpperCase: false, allowLowerCase: true, out decodedValue); public static bool TryDecodeValue(char data, out byte decodedValue) => TryDecodeValue(data, allowUpperCase: true, allowLowerCase: true, out decodedValue); [MethodImpl(MethodImplOptions.AggressiveInlining)] internal static bool TryDecodeValue(char data, bool allowUpperCase, bool allowLowerCase, out byte decodedValue) { if (data is >= (char)0x30 and <= (char)0x39) { // '0' 0x30 to '9' 0x39 decodedValue = (byte)(data - 0x30); return true; } else if (allowUpperCase && 0x41 <= data && data <= 0x46) { // 'A' 0x41 to 'F' 0x46 decodedValue = (byte)(data - 0x37); return true; } else if (allowLowerCase && 0x61 <= data && data <= 0x66) { // 'a' 0x61 to 'f' 0x66 decodedValue = (byte)(data - 0x57); return true; } else { decodedValue = default; return false; } } }
36.970779
154
0.721437
[ "MIT" ]
smdn/Smdn.Fundamentals
src/Smdn.Fundamental.PrintableEncoding.Hexadecimal/Smdn.Formats/Hexadecimal.cs
11,387
C#
// Copyright 2015-2020 Serilog Contributors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. using System; using System.IO; using System.Text; namespace Serilog.Sinks.Http.Private.Durable { public class BookmarkFile : IDisposable { private static readonly Encoding Encoding = new UTF8Encoding(encoderShouldEmitUTF8Identifier: false); private readonly FileStream fileStream; public BookmarkFile(string bookmarkFileName) { if (bookmarkFileName == null) throw new ArgumentNullException(nameof(bookmarkFileName)); fileStream = System.IO.File.Open( bookmarkFileName, FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.Read); } public void TryReadBookmark(out long nextLineBeginsAtOffset, out string currentFile) { nextLineBeginsAtOffset = 0; currentFile = null; if (fileStream.Length != 0) { // Important not to dispose this StreamReader as the stream must remain open var reader = new StreamReader(fileStream, Encoding, false, 128); var bookmark = reader.ReadLine(); if (bookmark != null) { fileStream.Position = 0; var parts = bookmark.Split( new[] { ":::" }, StringSplitOptions.RemoveEmptyEntries); if (parts.Length == 2) { nextLineBeginsAtOffset = long.Parse(parts[0]); currentFile = parts[1]; } } } } public void WriteBookmark(long nextLineBeginsAtOffset, string currentFile) { using var writer = new StreamWriter(fileStream, Encoding); writer.WriteLine("{0}:::{1}", nextLineBeginsAtOffset, currentFile); } public void Dispose() => fileStream?.Dispose(); } }
34.24
109
0.5919
[ "Apache-2.0" ]
vaibhavepatel/serilog-sinks-http
src/Serilog.Sinks.Http/Sinks/Http/Private/Durable/BookmarkFile.cs
2,570
C#
using System; using System.Collections.Generic; using System.Text; namespace System.Net.Http.Json { public sealed partial class JsonContent : System.Net.Http.HttpContent { protected override System.Threading.Tasks.Task SerializeToStreamAsync(System.IO.Stream stream, System.Net.TransportContext? context, System.Threading.CancellationToken cancellationToken) { throw null; } } }
33.416667
210
0.780549
[ "MIT" ]
06needhamt/runtime
src/libraries/System.Net.Http.Json/ref/System.Net.Http.Json.netcoreapp.cs
403
C#
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; public class size : MonoBehaviour { private ParticleSystem ps; public float hSliderValue = 1.0F; public Slider particle_size; void Start() { ps = GetComponent<ParticleSystem>(); } void Update() { var main = ps.main; main.startSize = particle_size.value; } void OnGUI() { //hSliderValue = GUI.HorizontalSlider(new Rect(25, 45, 100, 30), hSliderValue, 0.0F, 10.0F); } }
19.137931
100
0.636036
[ "MIT" ]
Gonzo717/A-Random-Act-Generative-Graphics
Generative Graphics/Assets/scripts/size.cs
557
C#
namespace MovieCatalogAspNetCore.Data.Seeding { using System; using System.Collections.Generic; using System.Threading.Tasks; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; public class ApplicationDbContextSeeder : ISeeder { public async Task SeedAsync(ApplicationDbContext dbContext, IServiceProvider serviceProvider) { if (dbContext == null) { throw new ArgumentNullException(nameof(dbContext)); } if (serviceProvider == null) { throw new ArgumentNullException(nameof(serviceProvider)); } var logger = serviceProvider.GetService<ILoggerFactory>().CreateLogger(typeof(ApplicationDbContextSeeder)); var seeders = new List<ISeeder> { new RolesSeeder(), new SettingsSeeder(), }; foreach (var seeder in seeders) { await seeder.SeedAsync(dbContext, serviceProvider); await dbContext.SaveChangesAsync(); logger.LogInformation($"Seeder {seeder.GetType().Name} done."); } } } }
31.585366
119
0.565251
[ "MIT" ]
d1ma1/Movie-Catalog-AspNet-Core
Data/MovieCatalogAspNetCore.Data/Seeding/ApplicationDbContextSeeder.cs
1,297
C#
// Copyright 2017-2020 Elringus (Artyom Sovetnikov). All Rights Reserved. using System.Collections.Generic; using System.Linq; using UnityEditor; using UnityEditor.Experimental.GraphView; using UnityEditor.UIElements; using UnityEngine; using UnityEngine.UIElements; namespace Naninovel { /// <summary> /// Allows working with visual representation of multiple <see cref="Script"/> assets and their relations. /// </summary> public class ScriptGraphView : GraphView { public const string ProgressBarTitle = "Generating Script Graph"; public static StyleSheet StyleSheet { get; } public static StyleSheet CustomStyleSheet { get; private set; } private readonly ScriptsConfiguration config; private readonly ScriptGraphState state; private readonly List<Script> scripts; private readonly List<ScriptGraphNode> scriptNodes = new List<ScriptGraphNode>(); static ScriptGraphView () { var styleSheetPath = PathUtils.AbsoluteToAssetPath(PathUtils.Combine(PackagePath.EditorResourcesPath, "ScriptGraph.uss")); StyleSheet = AssetDatabase.LoadAssetAtPath<StyleSheet>(styleSheetPath); } public ScriptGraphView (ScriptsConfiguration config, ScriptGraphState state, List<Script> scripts) { this.config = config; this.scripts = scripts; this.state = state; CustomStyleSheet = config.GraphCustomStyleSheet; styleSheets.Add(StyleSheet); if (CustomStyleSheet != null) styleSheets.Add(CustomStyleSheet); this.AddManipulator(new ContentDragger()); this.AddManipulator(new SelectionDragger()); this.AddManipulator(new RectangleSelector()); var grid = new GridBackground(); Insert(0, grid); grid.StretchToParentSize(); var minimap = new MiniMap(); minimap.anchored = true; minimap.SetPosition(new Rect(10, 30, 200, 140)); minimap.visible = false; Add(minimap); var toolbar = new Toolbar(); Add(toolbar); var rebuildButton = new Button(RebuildGraph); rebuildButton.text = "Rebuild Graph"; toolbar.Add(rebuildButton); var alignButton = new Button(AutoAlign); alignButton.text = "Auto Align"; toolbar.Add(alignButton); var minimapToggle = new Toggle(); minimapToggle.label = "Show Minimap"; minimapToggle.RegisterValueChangedCallback(evt => minimap.visible = evt.newValue); toolbar.Add(minimapToggle); var saveButton = new Button(SerializeState); saveButton.text = "Save"; toolbar.Add(saveButton); SetupZoom(ContentZoomer.DefaultMinScale, ContentZoomer.DefaultMaxScale); RebuildGraph(); } public override List<Port> GetCompatiblePorts (Port startPort, NodeAdapter nodeAdapter) => ports.ToList(); public void SerializeState () { state.NodesState.Clear(); foreach (var node in scriptNodes) if (ObjectUtils.IsValid(node.Script)) state.NodesState.Add(new ScriptGraphState.NodeState { ScriptName = node.Script.Name, Position = node.GetPosition() }); EditorUtility.SetDirty(state); AssetDatabase.SaveAssets(); } private void RebuildGraph () { scriptNodes.ForEach(RemoveElement); scriptNodes.Clear(); edges.ForEach(RemoveElement); // Generate one node per script asset. for (int i = 0; i < scripts.Count; i++) { var script = scripts[i]; // Discard deleted script assets. if (!ObjectUtils.IsValid(script)) continue; var progress = i / (float)scripts.Count; EditorUtility.DisplayProgressBar(ProgressBarTitle, $"Building `{script.Name}` node...", progress); var node = new ScriptGraphNode(config, script, scripts); scriptNodes.Add(node); AddElement(node); if (state.NodesState.Exists(s => s.ScriptName == script.Name)) { var nodeState = state.NodesState.First(s => s.ScriptName == script.Name); node.SetPosition(nodeState.Position); } } // Generate connections between nodes. for (int i = 0; i < scriptNodes.Count; i++) { var node = scriptNodes[i]; var progress = i / (float)scripts.Count; EditorUtility.DisplayProgressBar(ProgressBarTitle, "Connecting nodes...", progress); foreach (var data in node.OutputPorts) { var gotoNode = scriptNodes.FirstOrDefault(n => n.Script.Name == data.ScriptName); if (gotoNode is null) continue; gotoNode.InputPorts.TryGetValue(data.Label, out var gotoPort); if (gotoPort is null) continue; var edge = data.Port.ConnectTo(gotoPort); edge.capabilities = Capabilities.Ascendable | Capabilities.Selectable; edge.edgeControl.interceptWidth = 0; AddElement(edge); } } // Refresh nodes representation. foreach (var node in scriptNodes) { node.RefreshPorts(); node.RefreshExpandedState(); } EditorUtility.ClearProgressBar(); if (state.NodesState.Count == 0) // Auto align on first run. EditorApplication.delayCall += AutoAlign; } private void AutoAlign () { if (scriptNodes.Count == 0) return; if (float.IsNaN(scriptNodes.First().resolvedStyle.width)) // Layout not ready. { EditorApplication.delayCall += AutoAlign; return; } var orphans = scriptNodes.Where(n => !n.InputPorts.Any(p => p.Value.connections.Any(c => c.output.node != c.input.node)) && !n.OutputPorts.Any(p => p.Port.connections.Any(c => c.output.node != c.input.node))).ToList(); var nodes = scriptNodes.Except(orphans).TopologicalOrder(n => n.GetConnectedNodes(), false); var prevPos = Vector2.zero; foreach (var orphan in orphans) { var rect = orphan.GetPosition(); var pos = new Vector2(0, prevPos.y + config.GraphAutoAlignPadding.y * 2); orphan.SetPosition(new Rect(pos, rect.size)); prevPos = new Vector2(0, pos.y + orphan.resolvedStyle.height); } var maxOrphanWidth = orphans.Count > 0 ? orphans.Max(n => n.resolvedStyle.width) + config.GraphAutoAlignPadding.x : 0; prevPos = new Vector2(maxOrphanWidth, 0); foreach (var node in nodes) { var rect = node.GetPosition(); var pos = new Vector2(prevPos.x + config.GraphAutoAlignPadding.x * 2, 0); node.SetPosition(new Rect(pos, rect.size)); prevPos = new Vector2(pos.x + node.resolvedStyle.width, 0); } } } }
39.225131
138
0.577549
[ "MIT" ]
BSK-Baesick/Partita
Assets/Naninovel/Editor/ScriptGraph/ScriptGraphView.cs
7,494
C#
using System; using System.Linq; using System.IO; using System.Text; using System.Collections; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Runtime.Serialization; using Newtonsoft.Json; using Newtonsoft.Json.Converters; using PureCloudPlatform.Client.V2.Client; namespace PureCloudPlatform.Client.V2.Model { /// <summary> /// UserState /// </summary> [DataContract] public partial class UserState : IEquatable<UserState> { /// <summary> /// User's current state. /// </summary> /// <value>User's current state.</value> [JsonConverter(typeof(UpgradeSdkEnumConverter))] public enum StateEnum { /// <summary> /// Your SDK version is out of date and an unknown enum value was encountered. /// Please upgrade the SDK using the command "Upgrade-Package PureCloudApiSdk" /// in the Package Manager Console /// </summary> [EnumMember(Value = "OUTDATED_SDK_VERSION")] OutdatedSdkVersion, /// <summary> /// Enum Active for "active" /// </summary> [EnumMember(Value = "active")] Active, /// <summary> /// Enum Inactive for "inactive" /// </summary> [EnumMember(Value = "inactive")] Inactive, /// <summary> /// Enum Deleted for "deleted" /// </summary> [EnumMember(Value = "deleted")] Deleted } /// <summary> /// Reason for a change in the user's state. /// </summary> /// <value>Reason for a change in the user's state.</value> [JsonConverter(typeof(UpgradeSdkEnumConverter))] public enum StateChangeReasonEnum { /// <summary> /// Your SDK version is out of date and an unknown enum value was encountered. /// Please upgrade the SDK using the command "Upgrade-Package PureCloudApiSdk" /// in the Package Manager Console /// </summary> [EnumMember(Value = "OUTDATED_SDK_VERSION")] OutdatedSdkVersion, /// <summary> /// Enum Voluntary for "Voluntary" /// </summary> [EnumMember(Value = "Voluntary")] Voluntary, /// <summary> /// Enum Seasonal for "Seasonal" /// </summary> [EnumMember(Value = "Seasonal")] Seasonal, /// <summary> /// Enum Leave for "Leave" /// </summary> [EnumMember(Value = "Leave")] Leave, /// <summary> /// Enum Performance for "Performance" /// </summary> [EnumMember(Value = "Performance")] Performance, /// <summary> /// Enum Conduct for "Conduct" /// </summary> [EnumMember(Value = "Conduct")] Conduct, /// <summary> /// Enum Unknown for "Unknown" /// </summary> [EnumMember(Value = "Unknown")] Unknown } /// <summary> /// User's current state. /// </summary> /// <value>User's current state.</value> [DataMember(Name="state", EmitDefaultValue=false)] public StateEnum? State { get; set; } /// <summary> /// Reason for a change in the user's state. /// </summary> /// <value>Reason for a change in the user's state.</value> [DataMember(Name="stateChangeReason", EmitDefaultValue=false)] public StateChangeReasonEnum? StateChangeReason { get; set; } /// <summary> /// Initializes a new instance of the <see cref="UserState" /> class. /// </summary> /// <param name="State">User&#39;s current state..</param> /// <param name="Version">Version of this user..</param> /// <param name="StateChangeReason">Reason for a change in the user&#39;s state..</param> public UserState(StateEnum? State = null, int? Version = null, StateChangeReasonEnum? StateChangeReason = null) { this.State = State; this.Version = Version; this.StateChangeReason = StateChangeReason; } /// <summary> /// Version of this user. /// </summary> /// <value>Version of this user.</value> [DataMember(Name="version", EmitDefaultValue=false)] public int? Version { get; set; } /// <summary> /// Date that the state was last changed. Date time is represented as an ISO-8601 string. For example: yyyy-MM-ddTHH:mm:ss[.mmm]Z /// </summary> /// <value>Date that the state was last changed. Date time is represented as an ISO-8601 string. For example: yyyy-MM-ddTHH:mm:ss[.mmm]Z</value> [DataMember(Name="stateChangeDate", EmitDefaultValue=false)] public DateTime? StateChangeDate { get; private set; } /// <summary> /// Returns the string presentation of the object /// </summary> /// <returns>String presentation of the object</returns> public override string ToString() { var sb = new StringBuilder(); sb.Append("class UserState {\n"); sb.Append(" State: ").Append(State).Append("\n"); sb.Append(" Version: ").Append(Version).Append("\n"); sb.Append(" StateChangeReason: ").Append(StateChangeReason).Append("\n"); sb.Append(" StateChangeDate: ").Append(StateChangeDate).Append("\n"); sb.Append("}\n"); return sb.ToString(); } /// <summary> /// Returns the JSON string presentation of the object /// </summary> /// <returns>JSON string presentation of the object</returns> public string ToJson() { return JsonConvert.SerializeObject(this, new JsonSerializerSettings { MetadataPropertyHandling = MetadataPropertyHandling.Ignore, Formatting = Formatting.Indented }); } /// <summary> /// Returns true if objects are equal /// </summary> /// <param name="obj">Object to be compared</param> /// <returns>Boolean</returns> public override bool Equals(object obj) { // credit: http://stackoverflow.com/a/10454552/677735 return this.Equals(obj as UserState); } /// <summary> /// Returns true if UserState instances are equal /// </summary> /// <param name="other">Instance of UserState to be compared</param> /// <returns>Boolean</returns> public bool Equals(UserState other) { // credit: http://stackoverflow.com/a/10454552/677735 if (other == null) return false; return true && ( this.State == other.State || this.State != null && this.State.Equals(other.State) ) && ( this.Version == other.Version || this.Version != null && this.Version.Equals(other.Version) ) && ( this.StateChangeReason == other.StateChangeReason || this.StateChangeReason != null && this.StateChangeReason.Equals(other.StateChangeReason) ) && ( this.StateChangeDate == other.StateChangeDate || this.StateChangeDate != null && this.StateChangeDate.Equals(other.StateChangeDate) ); } /// <summary> /// Gets the hash code /// </summary> /// <returns>Hash code</returns> public override int GetHashCode() { // credit: http://stackoverflow.com/a/263416/677735 unchecked // Overflow is fine, just wrap { int hash = 41; // Suitable nullity checks etc, of course :) if (this.State != null) hash = hash * 59 + this.State.GetHashCode(); if (this.Version != null) hash = hash * 59 + this.Version.GetHashCode(); if (this.StateChangeReason != null) hash = hash * 59 + this.StateChangeReason.GetHashCode(); if (this.StateChangeDate != null) hash = hash * 59 + this.StateChangeDate.GetHashCode(); return hash; } } } }
32.800699
152
0.492485
[ "MIT" ]
MyPureCloud/platform-client-sdk-dotnet
build/src/PureCloudPlatform.Client.V2/Model/UserState.cs
9,381
C#
using System.Linq; namespace RayCarrot.RCP.Metro { /// <summary> /// View model for a file extension selection dialog /// </summary> public class FileExtensionSelectionDialogViewModel : UserInputViewModel { /// <summary> /// Default constructor /// </summary> /// <param name="fileFormats">The available file formats</param> /// <param name="header">The header to display</param> public FileExtensionSelectionDialogViewModel(string[] fileFormats, string header) { // Set properties FileFormats = fileFormats; Header = header; SelectedFileFormat = FileFormats.First(); // Set the default title Title = Resources.Archive_FileExtensionSelectionHeader; } /// <summary> /// The header to display /// </summary> public string Header { get; } /// <summary> /// The available file formats /// </summary> public string[] FileFormats { get; } /// <summary> /// The selected file format /// </summary> public string SelectedFileFormat { get; set; } } }
29.341463
89
0.571904
[ "MIT" ]
RayCarrot/RayCarrot.RCP.Metro
src/RayCarrot.RCP.Metro/UI/Dialogs/FileExtensionSelection/FileExtensionSelectionDialogViewModel.cs
1,205
C#
namespace BreakPoint.Models.ViewModels.ManageViewModels { public class TwoFactorAuthenticationViewModel { public bool HasAuthenticator { get; set; } public int RecoveryCodesLeft { get; set; } public bool Is2faEnabled { get; set; } } }
22.833333
56
0.678832
[ "MIT" ]
StoychoMihaylov/BreakPoint_APS.NET_Core_MVC
BreakPoint.Models/ViewModels/ManageViewModels/TwoFactorAuthenticationViewModel.cs
276
C#
// Copyright © 2010 onwards, Andrew Whewell // All rights reserved. // // Redistribution and use of this software in source and binary forms, with or without modification, are permitted provided that the following conditions are met: // * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. // * Neither the name of the author nor the names of the program's contributors may be used to endorse or promote products derived from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHORS OF THE SOFTWARE BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. using System; using System.Collections.Generic; using System.Linq; using System.Text; using InterfaceFactory; using Microsoft.VisualStudio.TestTools.UnitTesting; using Moq; using Test.Framework; using VirtualRadar.Interface.Presenter; using VirtualRadar.Interface.StandingData; using VirtualRadar.Interface.View; using VirtualRadar.Localisation; namespace Test.VirtualRadar.Library.Presenter { [TestClass] public class DownloadDataPresenterTests { #region TestContext, Fields, TestInitialise public TestContext TestContext { get; set; } private IClassFactory _ClassFactorySnapshot; private IDownloadDataPresenter _Presenter; private Mock<IDownloadDataView> _View; private Mock<IStandingDataManager> _StandingDataManager; private Mock<IStandingDataUpdater> _StandingDataUpdater; [TestInitialize] public void TestInitialise() { _ClassFactorySnapshot = Factory.TakeSnapshot(); _StandingDataManager = TestUtilities.CreateMockSingleton<IStandingDataManager>(); _StandingDataUpdater = TestUtilities.CreateMockImplementation<IStandingDataUpdater>(); _Presenter = Factory.Resolve<IDownloadDataPresenter>(); _View = new Mock<IDownloadDataView>() { DefaultValue = DefaultValue.Mock }.SetupAllProperties(); } [TestCleanup] public void TestCleanup() { Factory.RestoreSnapshot(_ClassFactorySnapshot); } #endregion #region Initialise [TestMethod] public void DownloadDataPresenter_Initialise_Sets_Initial_Status() { _StandingDataManager.Setup(s => s.RouteStatus).Returns("The route status"); _Presenter.Initialise(_View.Object); Assert.AreEqual("The route status", _View.Object.Status); } #endregion #region DownloadButtonClicked [TestMethod] public void DownloadDataPresenter_DownloadButtonClicked_Instantiates_Updater_And_Calls_It() { _Presenter.Initialise(_View.Object); _View.Raise(v => v.DownloadButtonClicked += null, EventArgs.Empty); _StandingDataUpdater.Verify(u => u.Update(), Times.Once()); } [TestMethod] public void DownloadDataPresenter_DownloadButtonClicked_Reloads_Data_After_Update_Has_Finished() { _StandingDataManager.Setup(m => m.Load()).Callback(() => { _StandingDataUpdater.Verify(u => u.Update(), Times.Once()); }); _Presenter.Initialise(_View.Object); _View.Raise(v => v.DownloadButtonClicked += null, EventArgs.Empty); _StandingDataManager.Verify(m => m.Load(), Times.Once()); } [TestMethod] public void DownloadDataPresenter_DownloadButtonClicked_Sets_View_Status_Before_Update() { _StandingDataUpdater.Setup(u => u.Update()).Callback(() => { Assert.AreEqual(Strings.DownloadingPleaseWait, _View.Object.Status); }); _Presenter.Initialise(_View.Object); _View.Raise(v => v.DownloadButtonClicked += null, EventArgs.Empty); } [TestMethod] public void DownloadDataPresenter_DownloadButtonClicked_Sets_View_Status_After_Load() { _StandingDataManager.Setup(m => m.Load()).Callback(() => { _StandingDataManager.Setup(m => m.RouteStatus).Returns("New status"); }); _Presenter.Initialise(_View.Object); _View.Raise(v => v.DownloadButtonClicked += null, EventArgs.Empty); Assert.AreEqual("New status", _View.Object.Status); } [TestMethod] public void DownloadDataPresenter_DownloadButtonClicked_Indicates_To_User_That_UI_Will_Be_Unresponsive() { var busyState = new Object(); _View.Setup(v => v.ShowBusy(It.IsAny<bool>(), It.IsAny<object>())).Returns((bool busy, object state) => { return busyState; }).Callback((bool busy, object state) => { if(busy) _StandingDataUpdater.Verify(u => u.Update(), Times.Never()); if(!busy) _StandingDataUpdater.Verify(u => u.Update(), Times.Once()); }); _Presenter.Initialise(_View.Object); _View.Raise(v => v.DownloadButtonClicked += null, EventArgs.Empty); _View.Verify(v => v.ShowBusy(It.IsAny<bool>(), It.IsAny<object>()), Times.Exactly(2)); _View.Verify(v => v.ShowBusy(true, null), Times.Once()); _View.Verify(v => v.ShowBusy(false, busyState), Times.Once()); } [TestMethod] public void DownloadDataPresenter_DownloadButtonClicked_Restores_Busy_Indicator_Even_If_Downloader_Throws() { _StandingDataUpdater.Setup(u => u.Update()).Callback(() => { throw new InvalidOperationException(); }); _Presenter.Initialise(_View.Object); try { _View.Raise(v => v.DownloadButtonClicked += null, EventArgs.Empty); } catch { } _View.Verify(v => v.ShowBusy(It.IsAny<bool>(), It.IsAny<object>()), Times.Exactly(2)); } #endregion } }
46.878378
750
0.662871
[ "BSD-3-Clause" ]
AlexAX135/vrs
Test/Test.VirtualRadar.Library/Presenter/DownloadDataPresenterTests.cs
6,941
C#
using System; using System.Collections.Generic; using System.IO; using System.Threading.Tasks; using RestSharp; namespace PillowSharp.Helper { public static class MimeMapping { private static Dictionary<string,string> mappings = new Dictionary<string,string> (); static MimeMapping() { mappings.Add(".323", "text/h323"); mappings.Add(".aaf", "application/octet-stream"); mappings.Add(".aca", "application/octet-stream"); mappings.Add(".accdb", "application/msaccess"); mappings.Add(".accde", "application/msaccess"); mappings.Add(".accdt", "application/msaccess"); mappings.Add(".acx", "application/internet-property-stream"); mappings.Add(".afm", "application/octet-stream"); mappings.Add(".ai", "application/postscript"); mappings.Add(".aif", "audio/x-aiff"); mappings.Add(".aifc", "audio/aiff"); mappings.Add(".aiff", "audio/aiff"); mappings.Add(".application", "application/x-ms-application"); mappings.Add(".art", "image/x-jg"); mappings.Add(".asd", "application/octet-stream"); mappings.Add(".asf", "video/x-ms-asf"); mappings.Add(".asi", "application/octet-stream"); mappings.Add(".asm", "text/plain"); mappings.Add(".asr", "video/x-ms-asf"); mappings.Add(".asx", "video/x-ms-asf"); mappings.Add(".atom", "application/atom+xml"); mappings.Add(".au", "audio/basic"); mappings.Add(".avi", "video/x-msvideo"); mappings.Add(".axs", "application/olescript"); mappings.Add(".bas", "text/plain"); mappings.Add(".bcpio", "application/x-bcpio"); mappings.Add(".bin", "application/octet-stream"); mappings.Add(".bmp", "image/bmp"); mappings.Add(".c", "text/plain"); mappings.Add(".cab", "application/octet-stream"); mappings.Add(".calx", "application/vnd.ms-office.calx"); mappings.Add(".cat", "application/vnd.ms-pki.seccat"); mappings.Add(".cdf", "application/x-cdf"); mappings.Add(".chm", "application/octet-stream"); mappings.Add(".class", "application/x-java-applet"); mappings.Add(".clp", "application/x-msclip"); mappings.Add(".cmx", "image/x-cmx"); mappings.Add(".cnf", "text/plain"); mappings.Add(".cod", "image/cis-cod"); mappings.Add(".cpio", "application/x-cpio"); mappings.Add(".cpp", "text/plain"); mappings.Add(".crd", "application/x-mscardfile"); mappings.Add(".crl", "application/pkix-crl"); mappings.Add(".crt", "application/x-x509-ca-cert"); mappings.Add(".csh", "application/x-csh"); mappings.Add(".css", "text/css"); mappings.Add(".csv", "application/octet-stream"); mappings.Add(".cur", "application/octet-stream"); mappings.Add(".dcr", "application/x-director"); mappings.Add(".deploy", "application/octet-stream"); mappings.Add(".der", "application/x-x509-ca-cert"); mappings.Add(".dib", "image/bmp"); mappings.Add(".dir", "application/x-director"); mappings.Add(".disco", "text/xml"); mappings.Add(".dll", "application/x-msdownload"); mappings.Add(".dll.config", "text/xml"); mappings.Add(".dlm", "text/dlm"); mappings.Add(".doc", "application/msword"); mappings.Add(".docm", "application/vnd.ms-word.document.macroEnabled.12"); mappings.Add(".docx", "application/vnd.openxmlformats-officedocument.wordprocessingml.document"); mappings.Add(".dot", "application/msword"); mappings.Add(".dotm", "application/vnd.ms-word.template.macroEnabled.12"); mappings.Add(".dotx", "application/vnd.openxmlformats-officedocument.wordprocessingml.template"); mappings.Add(".dsp", "application/octet-stream"); mappings.Add(".dtd", "text/xml"); mappings.Add(".dvi", "application/x-dvi"); mappings.Add(".dwf", "drawing/x-dwf"); mappings.Add(".dwp", "application/octet-stream"); mappings.Add(".dxr", "application/x-director"); mappings.Add(".eml", "message/rfc822"); mappings.Add(".emz", "application/octet-stream"); mappings.Add(".eot", "application/octet-stream"); mappings.Add(".eps", "application/postscript"); mappings.Add(".etx", "text/x-setext"); mappings.Add(".evy", "application/envoy"); mappings.Add(".exe", "application/octet-stream"); mappings.Add(".exe.config", "text/xml"); mappings.Add(".fdf", "application/vnd.fdf"); mappings.Add(".fif", "application/fractals"); mappings.Add(".fla", "application/octet-stream"); mappings.Add(".flr", "x-world/x-vrml"); mappings.Add(".flv", "video/x-flv"); mappings.Add(".gif", "image/gif"); mappings.Add(".gtar", "application/x-gtar"); mappings.Add(".gz", "application/x-gzip"); mappings.Add(".h", "text/plain"); mappings.Add(".hdf", "application/x-hdf"); mappings.Add(".hdml", "text/x-hdml"); mappings.Add(".hhc", "application/x-oleobject"); mappings.Add(".hhk", "application/octet-stream"); mappings.Add(".hhp", "application/octet-stream"); mappings.Add(".hlp", "application/winhlp"); mappings.Add(".hqx", "application/mac-binhex40"); mappings.Add(".hta", "application/hta"); mappings.Add(".htc", "text/x-component"); mappings.Add(".htm", "text/html"); mappings.Add(".html", "text/html"); mappings.Add(".htt", "text/webviewhtml"); mappings.Add(".hxt", "text/html"); mappings.Add(".ico", "image/x-icon"); mappings.Add(".ics", "application/octet-stream"); mappings.Add(".ief", "image/ief"); mappings.Add(".iii", "application/x-iphone"); mappings.Add(".inf", "application/octet-stream"); mappings.Add(".ins", "application/x-internet-signup"); mappings.Add(".isp", "application/x-internet-signup"); mappings.Add(".IVF", "video/x-ivf"); mappings.Add(".jar", "application/java-archive"); mappings.Add(".java", "application/octet-stream"); mappings.Add(".jck", "application/liquidmotion"); mappings.Add(".jcz", "application/liquidmotion"); mappings.Add(".jfif", "image/pjpeg"); mappings.Add(".jpb", "application/octet-stream"); mappings.Add(".jpe", "image/jpeg"); mappings.Add(".jpeg", "image/jpeg"); mappings.Add(".jpg", "image/jpeg"); mappings.Add(".js", "application/x-javascript"); mappings.Add(".jsx", "text/jscript"); mappings.Add(".latex", "application/x-latex"); mappings.Add(".lit", "application/x-ms-reader"); mappings.Add(".lpk", "application/octet-stream"); mappings.Add(".lsf", "video/x-la-asf"); mappings.Add(".lsx", "video/x-la-asf"); mappings.Add(".lzh", "application/octet-stream"); mappings.Add(".m13", "application/x-msmediaview"); mappings.Add(".m14", "application/x-msmediaview"); mappings.Add(".m1v", "video/mpeg"); mappings.Add(".m3u", "audio/x-mpegurl"); mappings.Add(".man", "application/x-troff-man"); mappings.Add(".manifest", "application/x-ms-manifest"); mappings.Add(".map", "text/plain"); mappings.Add(".mdb", "application/x-msaccess"); mappings.Add(".mdp", "application/octet-stream"); mappings.Add(".me", "application/x-troff-me"); mappings.Add(".mht", "message/rfc822"); mappings.Add(".mhtml", "message/rfc822"); mappings.Add(".mid", "audio/mid"); mappings.Add(".midi", "audio/mid"); mappings.Add(".mix", "application/octet-stream"); mappings.Add(".mmf", "application/x-smaf"); mappings.Add(".mno", "text/xml"); mappings.Add(".mny", "application/x-msmoney"); mappings.Add(".mov", "video/quicktime"); mappings.Add(".movie", "video/x-sgi-movie"); mappings.Add(".mp2", "video/mpeg"); mappings.Add(".mp3", "audio/mpeg"); mappings.Add(".mpa", "video/mpeg"); mappings.Add(".mpe", "video/mpeg"); mappings.Add(".mpeg", "video/mpeg"); mappings.Add(".mpg", "video/mpeg"); mappings.Add(".mpp", "application/vnd.ms-project"); mappings.Add(".mpv2", "video/mpeg"); mappings.Add(".ms", "application/x-troff-ms"); mappings.Add(".msi", "application/octet-stream"); mappings.Add(".mso", "application/octet-stream"); mappings.Add(".mvb", "application/x-msmediaview"); mappings.Add(".mvc", "application/x-miva-compiled"); mappings.Add(".nc", "application/x-netcdf"); mappings.Add(".nsc", "video/x-ms-asf"); mappings.Add(".nws", "message/rfc822"); mappings.Add(".ocx", "application/octet-stream"); mappings.Add(".oda", "application/oda"); mappings.Add(".odc", "text/x-ms-odc"); mappings.Add(".ods", "application/oleobject"); mappings.Add(".one", "application/onenote"); mappings.Add(".onea", "application/onenote"); mappings.Add(".onetoc", "application/onenote"); mappings.Add(".onetoc2", "application/onenote"); mappings.Add(".onetmp", "application/onenote"); mappings.Add(".onepkg", "application/onenote"); mappings.Add(".osdx", "application/opensearchdescription+xml"); mappings.Add(".p10", "application/pkcs10"); mappings.Add(".p12", "application/x-pkcs12"); mappings.Add(".p7b", "application/x-pkcs7-certificates"); mappings.Add(".p7c", "application/pkcs7-mime"); mappings.Add(".p7m", "application/pkcs7-mime"); mappings.Add(".p7r", "application/x-pkcs7-certreqresp"); mappings.Add(".p7s", "application/pkcs7-signature"); mappings.Add(".pbm", "image/x-portable-bitmap"); mappings.Add(".pcx", "application/octet-stream"); mappings.Add(".pcz", "application/octet-stream"); mappings.Add(".pdf", "application/pdf"); mappings.Add(".pfb", "application/octet-stream"); mappings.Add(".pfm", "application/octet-stream"); mappings.Add(".pfx", "application/x-pkcs12"); mappings.Add(".pgm", "image/x-portable-graymap"); mappings.Add(".pko", "application/vnd.ms-pki.pko"); mappings.Add(".pma", "application/x-perfmon"); mappings.Add(".pmc", "application/x-perfmon"); mappings.Add(".pml", "application/x-perfmon"); mappings.Add(".pmr", "application/x-perfmon"); mappings.Add(".pmw", "application/x-perfmon"); mappings.Add(".png", "image/png"); mappings.Add(".pnm", "image/x-portable-anymap"); mappings.Add(".pnz", "image/png"); mappings.Add(".pot", "application/vnd.ms-powerpoint"); mappings.Add(".potm", "application/vnd.ms-powerpoint.template.macroEnabled.12"); mappings.Add(".potx", "application/vnd.openxmlformats-officedocument.presentationml.template"); mappings.Add(".ppam", "application/vnd.ms-powerpoint.addin.macroEnabled.12"); mappings.Add(".ppm", "image/x-portable-pixmap"); mappings.Add(".pps", "application/vnd.ms-powerpoint"); mappings.Add(".ppsm", "application/vnd.ms-powerpoint.slideshow.macroEnabled.12"); mappings.Add(".ppsx", "application/vnd.openxmlformats-officedocument.presentationml.slideshow"); mappings.Add(".ppt", "application/vnd.ms-powerpoint"); mappings.Add(".pptm", "application/vnd.ms-powerpoint.presentation.macroEnabled.12"); mappings.Add(".pptx", "application/vnd.openxmlformats-officedocument.presentationml.presentation"); mappings.Add(".prf", "application/pics-rules"); mappings.Add(".prm", "application/octet-stream"); mappings.Add(".prx", "application/octet-stream"); mappings.Add(".ps", "application/postscript"); mappings.Add(".psd", "application/octet-stream"); mappings.Add(".psm", "application/octet-stream"); mappings.Add(".psp", "application/octet-stream"); mappings.Add(".pub", "application/x-mspublisher"); mappings.Add(".qt", "video/quicktime"); mappings.Add(".qtl", "application/x-quicktimeplayer"); mappings.Add(".qxd", "application/octet-stream"); mappings.Add(".ra", "audio/x-pn-realaudio"); mappings.Add(".ram", "audio/x-pn-realaudio"); mappings.Add(".rar", "application/octet-stream"); mappings.Add(".ras", "image/x-cmu-raster"); mappings.Add(".rf", "image/vnd.rn-realflash"); mappings.Add(".rgb", "image/x-rgb"); mappings.Add(".rm", "application/vnd.rn-realmedia"); mappings.Add(".rmi", "audio/mid"); mappings.Add(".roff", "application/x-troff"); mappings.Add(".rpm", "audio/x-pn-realaudio-plugin"); mappings.Add(".rtf", "application/rtf"); mappings.Add(".rtx", "text/richtext"); mappings.Add(".scd", "application/x-msschedule"); mappings.Add(".sct", "text/scriptlet"); mappings.Add(".sea", "application/octet-stream"); mappings.Add(".setpay", "application/set-payment-initiation"); mappings.Add(".setreg", "application/set-registration-initiation"); mappings.Add(".sgml", "text/sgml"); mappings.Add(".sh", "application/x-sh"); mappings.Add(".shar", "application/x-shar"); mappings.Add(".sit", "application/x-stuffit"); mappings.Add(".sldm", "application/vnd.ms-powerpoint.slide.macroEnabled.12"); mappings.Add(".sldx", "application/vnd.openxmlformats-officedocument.presentationml.slide"); mappings.Add(".smd", "audio/x-smd"); mappings.Add(".smi", "application/octet-stream"); mappings.Add(".smx", "audio/x-smd"); mappings.Add(".smz", "audio/x-smd"); mappings.Add(".snd", "audio/basic"); mappings.Add(".snp", "application/octet-stream"); mappings.Add(".spc", "application/x-pkcs7-certificates"); mappings.Add(".spl", "application/futuresplash"); mappings.Add(".src", "application/x-wais-source"); mappings.Add(".ssm", "application/streamingmedia"); mappings.Add(".sst", "application/vnd.ms-pki.certstore"); mappings.Add(".stl", "application/vnd.ms-pki.stl"); mappings.Add(".sv4cpio", "application/x-sv4cpio"); mappings.Add(".sv4crc", "application/x-sv4crc"); mappings.Add(".swf", "application/x-shockwave-flash"); mappings.Add(".t", "application/x-troff"); mappings.Add(".tar", "application/x-tar"); mappings.Add(".tcl", "application/x-tcl"); mappings.Add(".tex", "application/x-tex"); mappings.Add(".texi", "application/x-texinfo"); mappings.Add(".texinfo", "application/x-texinfo"); mappings.Add(".tgz", "application/x-compressed"); mappings.Add(".thmx", "application/vnd.ms-officetheme"); mappings.Add(".thn", "application/octet-stream"); mappings.Add(".tif", "image/tiff"); mappings.Add(".tiff", "image/tiff"); mappings.Add(".toc", "application/octet-stream"); mappings.Add(".tr", "application/x-troff"); mappings.Add(".trm", "application/x-msterminal"); mappings.Add(".tsv", "text/tab-separated-values"); mappings.Add(".ttf", "application/octet-stream"); mappings.Add(".txt", "text/plain"); mappings.Add(".u32", "application/octet-stream"); mappings.Add(".uls", "text/iuls"); mappings.Add(".ustar", "application/x-ustar"); mappings.Add(".vbs", "text/vbscript"); mappings.Add(".vcf", "text/x-vcard"); mappings.Add(".vcs", "text/plain"); mappings.Add(".vdx", "application/vnd.ms-visio.viewer"); mappings.Add(".vml", "text/xml"); mappings.Add(".vsd", "application/vnd.visio"); mappings.Add(".vss", "application/vnd.visio"); mappings.Add(".vst", "application/vnd.visio"); mappings.Add(".vsto", "application/x-ms-vsto"); mappings.Add(".vsw", "application/vnd.visio"); mappings.Add(".vsx", "application/vnd.visio"); mappings.Add(".vtx", "application/vnd.visio"); mappings.Add(".wav", "audio/wav"); mappings.Add(".wax", "audio/x-ms-wax"); mappings.Add(".wbmp", "image/vnd.wap.wbmp"); mappings.Add(".wcm", "application/vnd.ms-works"); mappings.Add(".wdb", "application/vnd.ms-works"); mappings.Add(".wks", "application/vnd.ms-works"); mappings.Add(".wm", "video/x-ms-wm"); mappings.Add(".wma", "audio/x-ms-wma"); mappings.Add(".wmd", "application/x-ms-wmd"); mappings.Add(".wmf", "application/x-msmetafile"); mappings.Add(".wml", "text/vnd.wap.wml"); mappings.Add(".wmlc", "application/vnd.wap.wmlc"); mappings.Add(".wmls", "text/vnd.wap.wmlscript"); mappings.Add(".wmlsc", "application/vnd.wap.wmlscriptc"); mappings.Add(".wmp", "video/x-ms-wmp"); mappings.Add(".wmv", "video/x-ms-wmv"); mappings.Add(".wmx", "video/x-ms-wmx"); mappings.Add(".wmz", "application/x-ms-wmz"); mappings.Add(".wps", "application/vnd.ms-works"); mappings.Add(".wri", "application/x-mswrite"); mappings.Add(".wrl", "x-world/x-vrml"); mappings.Add(".wrz", "x-world/x-vrml"); mappings.Add(".wsdl", "text/xml"); mappings.Add(".wvx", "video/x-ms-wvx"); mappings.Add(".x", "application/directx"); mappings.Add(".xaf", "x-world/x-vrml"); mappings.Add(".xaml", "application/xaml+xml"); mappings.Add(".xap", "application/x-silverlight-app"); mappings.Add(".xbap", "application/x-ms-xbap"); mappings.Add(".xbm", "image/x-xbitmap"); mappings.Add(".xdr", "text/plain"); mappings.Add(".xla", "application/vnd.ms-excel"); mappings.Add(".xlam", "application/vnd.ms-excel.addin.macroEnabled.12"); mappings.Add(".xlc", "application/vnd.ms-excel"); mappings.Add(".xlm", "application/vnd.ms-excel"); mappings.Add(".xls", "application/vnd.ms-excel"); mappings.Add(".xlsb", "application/vnd.ms-excel.sheet.binary.macroEnabled.12"); mappings.Add(".xlsm", "application/vnd.ms-excel.sheet.macroEnabled.12"); mappings.Add(".xlsx", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"); mappings.Add(".xlt", "application/vnd.ms-excel"); mappings.Add(".xltm", "application/vnd.ms-excel.template.macroEnabled.12"); mappings.Add(".xltx", "application/vnd.openxmlformats-officedocument.spreadsheetml.template"); mappings.Add(".xlw", "application/vnd.ms-excel"); mappings.Add(".xml", "text/xml"); mappings.Add(".xof", "x-world/x-vrml"); mappings.Add(".xpm", "image/x-xpixmap"); mappings.Add(".xps", "application/vnd.ms-xpsdocument"); mappings.Add(".xsd", "text/xml"); mappings.Add(".xsf", "text/xml"); mappings.Add(".xsl", "text/xml"); mappings.Add(".xslt", "text/xml"); mappings.Add(".xsn", "application/octet-stream"); mappings.Add(".xtp", "application/octet-stream"); mappings.Add(".xwd", "image/x-xwindowdump"); mappings.Add(".z", "application/x-compress"); mappings.Add(".zip", "application/x-zip-compressed"); } public static string GetMimeType(string FilePath,string Default="text/xml") { var ending = Path.GetExtension(FilePath).ToLower(); if(!mappings.ContainsKey(ending)) return Default; else return mappings[ending]; } } }
60.427419
115
0.526313
[ "Apache-2.0" ]
Dev-Owl/pillowsharp
src/libary/Helper/MimeMapping.cs
22,479
C#
using System.Collections; using System.Collections.Generic; using UnityEngine; public class FoundationColumn : Column { [SerializeField] private Card.CardSuit suit = Card.CardSuit.SPADES; public override bool CanAddTo(Card card) { if (_cards.Count <= 0 && card.Suit == suit && card.Rank == Card.CardRank.ACE) { return true; } if (card.Rank == _cards[_cards.Count - 1].Rank + 1 && card.Suit == suit) { return true; } return false; } }
22.25
85
0.588015
[ "MIT" ]
Nova-Victoriae/Chet-and-Josh-Play-Solitaire
Chet and Josh Play Solitaire/Assets/Scripts/FoundationColumn.cs
534
C#
using System; using System.Globalization; using Newtonsoft.Json.Linq; using Ripple.Core.Binary; namespace Ripple.Core.Types { public abstract class Uint<T> : ISerializedType where T: struct, IConvertible { public readonly T Value; protected Uint(T value) { Value = value; } public void ToBytes(IBytesSink sink) => sink.Put(ToBytes()); public virtual JToken ToJson() => Convert.ToUInt32(Value); public override string ToString() { return Value.ToString(CultureInfo.InvariantCulture); } public abstract byte[] ToBytes(); } }
25.64
81
0.630265
[ "ISC" ]
CASL-AE/ripple-netcore
src/Ripple.Core/Types/Uint.cs
641
C#
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; using HProject.Application; using HProject.Infrastructure; using Microsoft.AspNet.Identity; using HProject.Domain; using System.Security.Principal; namespace HProject.Controllers { public class HomeController : Controller { private ILogger _logger; private HProjectDbContext _context; public HomeController(ILogger logger, HProjectDbContext hProjectDbContext) { this._logger = logger; this._context = hProjectDbContext; } // GET: Home [Authorize] public ActionResult Index() { return View(); } [Authorize] [ChildActionOnly] public ActionResult Menu() { List<HProject.Application.Menu> menuList = new List<HProject.Application.Menu>(); ProduceMenu menu = new ProduceMenu(); IPrincipal User = HttpContext.User; if (User.IsInRole("Admin")) { menuList = menu.GetAdminMenu(); } else { menuList = menu.GetUserMenu(); } return PartialView(menuList); } } }
24.207547
93
0.587685
[ "MIT" ]
airfoot/HProject
HProject/Controllers/HomeController.cs
1,285
C#
using System.Collections; using DCL; using DCL.Helpers; using NUnit.Framework; using UnityEngine.TestTools; public class WithPbrMaterial_SceneMetricsCounterShould : IntegrationTestSuite_SceneMetricsCounter { [UnityTest] public IEnumerator NotCountWhenAttachedToIgnoredEntities() { var material = CreatePBRMaterial("", "", "", ""); var shape = CreatePlane(); var entity = CreateEntityWithTransform(); DataStore.i.sceneWorldObjects.AddExcludedOwner(scene.sceneData.id, entity.entityId); TestUtils.SharedComponentAttach(shape, entity); TestUtils.SharedComponentAttach(material, entity); yield return material.routine; Assert.That( scene.metricsCounter.currentCount.entities, Is.EqualTo(0) ); Assert.That( scene.metricsCounter.currentCount.materials, Is.EqualTo(0) ); DataStore.i.sceneWorldObjects.RemoveExcludedOwner(scene.sceneData.id, entity.entityId); } [UnityTest] public IEnumerator CountWhenAdded() { var material = CreatePBRMaterial("", "", "", ""); var shape = CreatePlane(); var entity = CreateEntityWithTransform(); TestUtils.SharedComponentAttach(shape, entity); TestUtils.SharedComponentAttach(material, entity); yield return material.routine; Assert.That( scene.metricsCounter.currentCount.materials, Is.EqualTo(1) ); Assert.That( scene.metricsCounter.currentCount.bodies, Is.EqualTo(1) ); Assert.That( scene.metricsCounter.currentCount.entities, Is.EqualTo(1) ); } [UnityTest] public IEnumerator CountWhenRemoved() { var material = CreatePBRMaterial("", "", "", ""); var shape = CreatePlane(); var entity = CreateEntityWithTransform(); TestUtils.SharedComponentAttach(shape, entity); TestUtils.SharedComponentAttach(material, entity); yield return material.routine; material.Dispose(); shape.Dispose(); Assert.That( scene.metricsCounter.currentCount.materials, Is.EqualTo(0) ); Assert.That( scene.metricsCounter.currentCount.bodies, Is.EqualTo(0) ); Assert.That( scene.metricsCounter.currentCount.entities, Is.EqualTo(0) ); } [UnityTest] public IEnumerator NotCountWhenNoShapeIsPresent() { var material1 = CreatePBRMaterial("", "", "", ""); yield return material1.routine; Assert.That( scene.metricsCounter.currentCount.materials, Is.EqualTo(0) ); } }
33.026316
97
0.684861
[ "Apache-2.0" ]
CarlosPolygonalMind/unity-renderer
unity-renderer/Assets/Scripts/MainScripts/DCL/WorldRuntime/Tests/WithPbrMaterial_SceneMetricsCounterShould.cs
2,512
C#
using System; using System.Collections.Generic; using System.Linq; using RimWorld; using AbilityUser; using Verse; using UnityEngine; namespace TorannMagic { public class Verb_CureDisease : Verb_UseAbility { private int verVal; private int pwrVal; private float arcaneDmg = 1f; protected override bool TryCastShot() { Pawn caster = base.CasterPawn; Pawn pawn = this.currentTarget.Thing as Pawn; CompAbilityUserMagic comp = caster.TryGetComp<CompAbilityUserMagic>(); pwrVal = TM_Calc.GetSkillPowerLevel(caster, this.Ability.Def as TMAbilityDef); verVal = TM_Calc.GetSkillVersatilityLevel(caster, this.Ability.Def as TMAbilityDef); //MagicPowerSkill pwr = comp.MagicData.MagicPowerSkill_CureDisease.FirstOrDefault((MagicPowerSkill x) => x.label == "TM_CureDisease_pwr"); //MagicPowerSkill ver = comp.MagicData.MagicPowerSkill_CureDisease.FirstOrDefault((MagicPowerSkill x) => x.label == "TM_CureDisease_ver"); //verVal = ver.level; //pwrVal = pwr.level; //this.arcaneDmg = caster.GetComp<CompAbilityUserMagic>().arcaneDmg; //if (caster.story.traits.HasTrait(TorannMagicDefOf.Faceless)) //{ // MightPowerSkill mpwr = caster.GetComp<CompAbilityUserMight>().MightData.MightPowerSkill_Mimic.FirstOrDefault((MightPowerSkill x) => x.label == "TM_Mimic_pwr"); // MightPowerSkill mver = caster.GetComp<CompAbilityUserMight>().MightData.MightPowerSkill_Mimic.FirstOrDefault((MightPowerSkill x) => x.label == "TM_Mimic_ver"); // pwrVal = mpwr.level; // verVal = mver.level; //} bool flag = pawn != null; if (flag) { int num = 1; float sevAdjustment = 0; if (pwrVal >= 2) { //apply immunity buff, 60k ticks in a day if (pwrVal == 3) { HealthUtility.AdjustSeverity(pawn, TorannMagicDefOf.TM_DiseaseImmunity2HD, 5); pawn.health.hediffSet.GetFirstHediffOfDef(TorannMagicDefOf.TM_DiseaseImmunity2HD).TryGetComp<HediffComp_DiseaseImmunity>().verVal = verVal; } else { HealthUtility.AdjustSeverity(pawn, TorannMagicDefOf.TM_DiseaseImmunityHD, 3); } } if (pwrVal >= 1) { sevAdjustment = 5; } else { sevAdjustment = (Rand.Range(0f, 1f) * this.arcaneDmg); } if(sevAdjustment >= .25f) { bool success = false; using (IEnumerator<Hediff> enumerator = pawn.health.hediffSet.GetHediffs<Hediff>().GetEnumerator()) { while (enumerator.MoveNext()) { Hediff rec = enumerator.Current; bool flag2 = num > 0; if (TM_Data.AddictionList().Contains(rec.def)) { List<TMDefs.TM_CategoryHediff> diseaseList = HediffCategoryList.Named("TM_Category_Hediffs").diseases; foreach (TMDefs.TM_CategoryHediff chd in diseaseList) { if (chd.hediffDefname.Contains(rec.def.defName)) { if (comp != null && chd.requiredSkillName != "TM_Purify_ver") { pwrVal = comp.MagicData.AllMagicPowerSkills.FirstOrDefault((MagicPowerSkill x) => x.label == chd.powerSkillName).level; verVal = comp.MagicData.AllMagicPowerSkills.FirstOrDefault((MagicPowerSkill x) => x.label == chd.requiredSkillName).level; } if (verVal >= chd.requiredSkillLevel) { if (chd.removeOnCure) { if (Rand.Chance((chd.chanceToRemove + (chd.powerSkillAdjustment * pwrVal)) * arcaneDmg)) { pawn.health.RemoveHediff(rec); if (chd.replacementHediffDefname != "") { HealthUtility.AdjustSeverity(pawn, HediffDef.Named(chd.replacementHediffDefname), chd.replacementHediffSeverity); } success = true; num--; } else { MoteMaker.ThrowText(pawn.DrawPos, pawn.Map, "Failed to remove " + rec.Label + " ..."); } break; } else { if (((rec.Severity - (chd.severityReduction + (chd.powerSkillAdjustment * pwrVal)) * arcaneDmg <= 0))) { if (chd.replacementHediffDefname != "") { HealthUtility.AdjustSeverity(pawn, HediffDef.Named(chd.replacementHediffDefname), chd.replacementHediffSeverity); } success = true; } rec.Severity -= ((chd.severityReduction + (chd.powerSkillAdjustment * pwrVal)) * arcaneDmg); num--; break; } } } } } else { if (rec.def.defName == "WoundInfection" || rec.def.defName.Contains("Flu") || rec.def.defName == "Animal_Flu" || rec.def.defName.Contains("Infection")) { //rec.Severity -= sevAdjustment; pawn.health.RemoveHediff(rec); success = true; } if (verVal >= 1 && (rec.def.defName == "GutWorms" || rec.def == HediffDefOf.Malaria || rec.def == HediffDefOf.FoodPoisoning)) { //rec.Severity -= sevAdjustment; pawn.health.RemoveHediff(rec); success = true; } if (verVal >= 2 && (rec.def.defName == "SleepingSickness" || rec.def.defName == "MuscleParasites") || rec.def == HediffDefOf.Scaria) { //rec.Severity -= sevAdjustment; pawn.health.RemoveHediff(rec); success = true; } if (verVal == 3 && (rec.def.makesSickThought && rec.def.isBad)) { //rec.Severity -= sevAdjustment; if (rec.def.defName == "BloodRot") { rec.Severity = 0.01f; MoteMaker.ThrowText(pawn.DrawPos, pawn.Map, "Tended Blood Rot", -1f); rec.Tended(1f, 1f); TM_MoteMaker.ThrowRegenMote(pawn.Position.ToVector3(), pawn.Map, 1.5f); return false; } else if (rec.def.defName == "Abasia") { //do nothing } else { pawn.health.RemoveHediff(rec); success = true; } } } if(success) { break; } } } if (success == true) { TM_MoteMaker.ThrowRegenMote(pawn.Position.ToVector3(), pawn.Map, 1.5f); MoteMaker.ThrowText(pawn.DrawPos, pawn.Map, "Cure Disease" + ": " + StringsToTranslate.AU_CastSuccess, -1f); } else { Messages.Message("TM_CureDiseaseTypeFail".Translate(), MessageTypeDefOf.NegativeEvent); MoteMaker.ThrowText(pawn.DrawPos, pawn.Map, "Cure Disease" + ": " + StringsToTranslate.AU_CastFailure, -1f); } } else { MoteMaker.ThrowText(pawn.DrawPos, pawn.Map, "Cure Disease" + ": " + StringsToTranslate.AU_CastFailure, -1f); } } return false; } } }
54.697436
188
0.379617
[ "BSD-3-Clause" ]
Sn1p3rr3c0n/RWoM
RimWorldOfMagic/RimWorldOfMagic/Verb_CureDisease.cs
10,668
C#
// ------------------------------------------------------------------------------ // <auto-generated> // Generated by Xsd2Code. Version 3.4.0.18239 Microsoft Reciprocal License (Ms-RL) // <NameSpace>Mim.V6301</NameSpace><Collection>Array</Collection><codeType>CSharp</codeType><EnableDataBinding>False</EnableDataBinding><EnableLazyLoading>False</EnableLazyLoading><TrackingChangesEnable>False</TrackingChangesEnable><GenTrackingClasses>False</GenTrackingClasses><HidePrivateFieldInIDE>False</HidePrivateFieldInIDE><EnableSummaryComment>True</EnableSummaryComment><VirtualProp>False</VirtualProp><IncludeSerializeMethod>True</IncludeSerializeMethod><UseBaseClass>False</UseBaseClass><GenBaseClass>False</GenBaseClass><GenerateCloneMethod>True</GenerateCloneMethod><GenerateDataContracts>False</GenerateDataContracts><CodeBaseTag>Net35</CodeBaseTag><SerializeMethodName>Serialize</SerializeMethodName><DeserializeMethodName>Deserialize</DeserializeMethodName><SaveToFileMethodName>SaveToFile</SaveToFileMethodName><LoadFromFileMethodName>LoadFromFile</LoadFromFileMethodName><GenerateXMLAttributes>True</GenerateXMLAttributes><OrderXMLAttrib>False</OrderXMLAttrib><EnableEncoding>False</EnableEncoding><AutomaticProperties>False</AutomaticProperties><GenerateShouldSerialize>False</GenerateShouldSerialize><DisableDebug>False</DisableDebug><PropNameSpecified>Default</PropNameSpecified><Encoder>UTF8</Encoder><CustomUsings></CustomUsings><ExcludeIncludedTypes>True</ExcludeIncludedTypes><EnableInitializeFields>False</EnableInitializeFields> // </auto-generated> // ------------------------------------------------------------------------------ namespace Mim.V6301 { using System; using System.Diagnostics; using System.Xml.Serialization; using System.Collections; using System.Xml.Schema; using System.ComponentModel; using System.IO; using System.Text; [System.CodeDom.Compiler.GeneratedCodeAttribute("Xsd2Code", "3.4.0.18239")] [System.SerializableAttribute()] [System.Xml.Serialization.XmlTypeAttribute(AnonymousType=true, Namespace="urn:hl7-org:v3")] public enum POII_MT000001UK01PertinentInformation6TemplateIdExtension { /// <remarks/> [System.Xml.Serialization.XmlEnumAttribute("CSAB_RM-NPfITUK10.sourceOf2")] CSAB_RMNPfITUK10sourceOf2, } }
84
1,358
0.757228
[ "MIT" ]
Kusnaditjung/MimDms
src/Mim.V6301/Generated/POII_MT000001UK01PertinentInformation6TemplateIdExtension.cs
2,352
C#
// Copyright (c) Microsoft Corporation. // Licensed under the MIT license. namespace Microsoft.Bing.Commerce.Connectors.Core.Serializers { using System.Collections.Generic; using Microsoft.Bing.Commerce.Connectors.Core.Config; /// <summary> /// A utility to serialize the batch of records in the one of select format. /// </summary> public class FormatSerializer : IPushSerializer<IDictionary<string, object>> { private static readonly Dictionary<Format, IPushSerializer<IDictionary<string, object>>> serializerMap = new Dictionary<Format, IPushSerializer<IDictionary<string, object>>>() { { Format.JsonArray, new JsonArraySerializer() }, { Format.NDJson, new NDJsonSerializer() }, { Format.Csv, new CSVSerializer() }, { Format.Tsv, new TSVSerializer() } }; private readonly IPushSerializer<IDictionary<string, object>> activeSerializer; /// <summary> /// Initializes a new instance of the <see cref="FormatSerializer"/> class. /// </summary> /// <param name="serializerFormat">The selected format to intialize the object with.</param> public FormatSerializer(Format serializerFormat) { this.activeSerializer = serializerMap[serializerFormat]; } /// <summary> /// Gets the number of characters added to any number of serialized records in order to complete the batch. /// </summary> public uint OverheadSize => this.activeSerializer.OverheadSize; /// <summary> /// Gets the number of characters added as an overhaed to one serialized record in order to be able to concatenate it with other serialized records. /// </summary> public uint RecordOverheadSize => this.activeSerializer.RecordOverheadSize; /// <summary> /// Uses the selected serializer to serialize a batch of record objects in Comma-Separated Values format. /// </summary> /// <param name="records">the records to be serialized.</param> /// <returns>The batch of objects serialized as string.</returns> public string Serialize(IEnumerable<IDictionary<string, object>> records) { return this.activeSerializer.Serialize(records); } /// <summary> /// uses the selectd serializer to serializes a single record object in Comma-Separated Values format. /// </summary> /// <param name="record">The record object to be serialized</param> /// <returns>The object serialized as string in Csv format.</returns> public string Serialize(IDictionary<string, object> record) { return this.activeSerializer.Serialize(record); } } }
44.384615
158
0.633276
[ "MIT" ]
microsoft/bing-commerce-connectors
src/Core/Serializers/FormatSerializer.cs
2,887
C#
 namespace GMap.NET.MapProviders { using System; using GMap.NET.Projections; using System.Security.Cryptography; using System.Diagnostics; using System.Net; using System.IO; using System.Text.RegularExpressions; using System.Threading; using GMap.NET.Internals; using System.Collections.Generic; using System.Globalization; using System.Xml; using System.Text; public abstract class GoogleMapProviderBase : GMapProvider, RoutingProvider, GeocodingProvider, DirectionsProvider { public GoogleMapProviderBase() { MaxZoom = null; RefererUrl = string.Format("http://maps.{0}/", Server); Copyright = string.Format("©{0} Google - Map data ©{0} Tele Atlas, Imagery ©{0} TerraMetrics", DateTime.Today.Year); } public readonly string ServerAPIs /* ;}~~ */ = Stuff.GString(/*{^_^}*/"9gERyvblybF8iMuCt/LD6w=="/*d{'_'}b*/); public readonly string Server /* ;}~~~~ */ = Stuff.GString(/*{^_^}*/"gosr2U13BoS+bXaIxt6XWg=="/*d{'_'}b*/); public readonly string ServerChina /* ;}~ */ = Stuff.GString(/*{^_^}*/"gosr2U13BoTEJoJJuO25gQ=="/*d{'_'}b*/); public readonly string ServerKorea /* ;}~~ */ = Stuff.GString(/*{^_^}*/"8ZVBOEsBinzi+zmP7y7pPA=="/*d{'_'}b*/); public readonly string ServerKoreaKr /* ;}~ */ = Stuff.GString(/*{^_^}*/"gosr2U13BoQyz1gkC4QLfg=="/*d{'_'}b*/); public string SecureWord = "Galileo"; /// <summary> /// API generated using http://greatmaps.codeplex.com/ /// from http://tinyurl.com/3q6zhcw /// </summary> //public string APIKey = @"ABQIAAAAWaQgWiEBF3lW97ifKnAczhRAzBk5Igf8Z5n2W3hNnMT0j2TikxTLtVIGU7hCLLHMAuAMt-BO5UrEWA"; #region GMapProvider Members public override Guid Id { get { throw new NotImplementedException(); } } public override string Name { get { throw new NotImplementedException(); } } public override PureProjection Projection { get { return MercatorProjection.Instance; } } GMapProvider [] overlays; public override GMapProvider [] Overlays { get { if (overlays == null) { overlays = new GMapProvider [] { this }; } return overlays; } } public override PureImage GetTileImage(GPoint pos, int zoom) { throw new NotImplementedException(); } #endregion public bool TryCorrectVersion = true; static bool init = false; public override void OnInitialized() { if (!init && TryCorrectVersion) { string url = string.Format("http://maps.{0}", Server); try { string html = GMaps.Instance.UseUrlCache ? Cache.Instance.GetContent(url, CacheType.UrlCache, TimeSpan.FromHours(8)) : string.Empty; if (string.IsNullOrEmpty(html)) { html = GetContentUsingHttp(url); if (!string.IsNullOrEmpty(html)) { if (GMaps.Instance.UseUrlCache) { Cache.Instance.SaveContent(url, CacheType.UrlCache, html); } } } if (!string.IsNullOrEmpty(html)) { #region -- match versions -- Regex reg = new Regex(string.Format("\"*https?://mt\\D?\\d.{0}/vt/lyrs=m@(\\d*)", Server), RegexOptions.IgnoreCase); Match mat = reg.Match(html); if (mat.Success) { GroupCollection gc = mat.Groups; int count = gc.Count; if (count > 0) { string ver = string.Format("m@{0}", gc [1].Value); string old = GMapProviders.GoogleMap.Version; GMapProviders.GoogleMap.Version = ver; GMapProviders.GoogleChinaMap.Version = ver; #if DEBUG Debug.WriteLine("GMapProviders.GoogleMap.Version: " + ver + ", " + (ver == old ? "OK" : "old: " + old + ", consider updating source")); if (Debugger.IsAttached && ver != old) { Thread.Sleep(1111); } #endif } } reg = new Regex(string.Format("\"*https?://mt\\D?\\d.{0}/vt/lyrs=h@(\\d*)", Server), RegexOptions.IgnoreCase); mat = reg.Match(html); if (mat.Success) { GroupCollection gc = mat.Groups; int count = gc.Count; if (count > 0) { string ver = string.Format("h@{0}", gc [1].Value); string old = GMapProviders.GoogleHybridMap.Version; GMapProviders.GoogleHybridMap.Version = ver; GMapProviders.GoogleChinaHybridMap.Version = ver; #if DEBUG Debug.WriteLine("GMapProviders.GoogleHybridMap.Version: " + ver + ", " + (ver == old ? "OK" : "old: " + old + ", consider updating source")); if (Debugger.IsAttached && ver != old) { Thread.Sleep(1111); } #endif } } reg = new Regex(string.Format("\"*https?://khm\\D?\\d.{0}/kh/v=(\\d*)", Server), RegexOptions.IgnoreCase); mat = reg.Match(html); if (mat.Success) { GroupCollection gc = mat.Groups; int count = gc.Count; if (count > 0) { string ver = gc [1].Value; string old = GMapProviders.GoogleSatelliteMap.Version; GMapProviders.GoogleSatelliteMap.Version = ver; GMapProviders.GoogleKoreaSatelliteMap.Version = ver; GMapProviders.GoogleChinaSatelliteMap.Version = "s@" + ver; #if DEBUG Debug.WriteLine("GMapProviders.GoogleSatelliteMap.Version: " + ver + ", " + (ver == old ? "OK" : "old: " + old + ", consider updating source")); if (Debugger.IsAttached && ver != old) { Thread.Sleep(1111); } #endif } } reg = new Regex(string.Format("\"*https?://mt\\D?\\d.{0}/vt/lyrs=t@(\\d*),r@(\\d*)", Server), RegexOptions.IgnoreCase); mat = reg.Match(html); if (mat.Success) { GroupCollection gc = mat.Groups; int count = gc.Count; if (count > 1) { string ver = string.Format("t@{0},r@{1}", gc [1].Value, gc [2].Value); string old = GMapProviders.GoogleTerrainMap.Version; GMapProviders.GoogleTerrainMap.Version = ver; GMapProviders.GoogleChinaTerrainMap.Version = ver; #if DEBUG Debug.WriteLine("GMapProviders.GoogleTerrainMap.Version: " + ver + ", " + (ver == old ? "OK" : "old: " + old + ", consider updating source")); if (Debugger.IsAttached && ver != old) { Thread.Sleep(1111); } #endif } } #endregion } init = true; // try it only once } catch (Exception ex) { Debug.WriteLine("TryCorrectGoogleVersions failed: " + ex.ToString()); } } } internal void GetSecureWords(GPoint pos, out string sec1, out string sec2) { sec1 = string.Empty; // after &x=... sec2 = string.Empty; // after &zoom=... int seclen = (int)((pos.X * 3) + pos.Y) % 8; sec2 = SecureWord.Substring(0, seclen); if (pos.Y >= 10000 && pos.Y < 100000) { sec1 = Sec1; } } static readonly string Sec1 = "&s="; #region RoutingProvider Members public MapRoute GetRoute(PointLatLng start, PointLatLng end, bool avoidHighways, bool walkingMode, int Zoom) { string tooltip; int numLevels; int zoomFactor; MapRoute ret = null; List<PointLatLng> points = GetRoutePoints(MakeRouteUrl(start, end, LanguageStr, avoidHighways, walkingMode), Zoom, out tooltip, out numLevels, out zoomFactor); if (points != null) { ret = new MapRoute(points, tooltip); } return ret; } public MapRoute GetRoute(string start, string end, bool avoidHighways, bool walkingMode, int Zoom) { string tooltip; int numLevels; int zoomFactor; MapRoute ret = null; List<PointLatLng> points = GetRoutePoints(MakeRouteUrl(start, end, LanguageStr, avoidHighways, walkingMode), Zoom, out tooltip, out numLevels, out zoomFactor); if (points != null) { ret = new MapRoute(points, tooltip); } return ret; } #region -- internals -- string MakeRouteUrl(PointLatLng start, PointLatLng end, string language, bool avoidHighways, bool walkingMode) { string opt = walkingMode ? WalkingStr : (avoidHighways ? RouteWithoutHighwaysStr : RouteStr); return string.Format(CultureInfo.InvariantCulture, RouteUrlFormatPointLatLng, language, opt, start.Lat, start.Lng, end.Lat, end.Lng, Server); } string MakeRouteUrl(string start, string end, string language, bool avoidHighways, bool walkingMode) { string opt = walkingMode ? WalkingStr : (avoidHighways ? RouteWithoutHighwaysStr : RouteStr); return string.Format(RouteUrlFormatStr, language, opt, start.Replace(' ', '+'), end.Replace(' ', '+'), Server); } List<PointLatLng> GetRoutePoints(string url, int zoom, out string tooltipHtml, out int numLevel, out int zoomFactor) { List<PointLatLng> points = null; tooltipHtml = string.Empty; numLevel = -1; zoomFactor = -1; try { string route = GMaps.Instance.UseRouteCache ? Cache.Instance.GetContent(url, CacheType.RouteCache) : string.Empty; if (string.IsNullOrEmpty(route)) { route = GetContentUsingHttp(url); if (!string.IsNullOrEmpty(route)) { if (GMaps.Instance.UseRouteCache) { Cache.Instance.SaveContent(url, CacheType.RouteCache, route); } } } // parse values if (!string.IsNullOrEmpty(route)) { //{ //tooltipHtml:" (300\x26#160;km / 2 valandos 59 min.)", //polylines: //[{ // id:"route0", // points:"cy~rIcvp`ClJ~v@jHpu@N|BB~A?tA_@`J@nAJrB|AhEf@h@~@^pANh@Mr@a@`@_@x@cBPk@ZiBHeDQ{C]wAc@mAqCeEoA_C{@_Cy@iDoEaW}AsJcJ}t@iWowB{C_Vyw@gvGyTyjBu@gHwDoZ{W_zBsX}~BiA_MmAyOcAwOs@yNy@eTk@mVUmTE}PJ_W`@cVd@cQ`@}KjA_V`AeOn@oItAkOdAaKfBaOhDiVbD}RpBuKtEkTtP}q@fr@ypCfCmK|CmNvEqVvCuQ`BgLnAmJ`CgTpA_N~@sLlBwYh@yLp@cSj@e]zFkzKHaVViSf@wZjFwqBt@{Wr@qS`AaUjAgStBkYrEwe@xIuw@`Gmj@rFok@~BkYtCy_@|KccBvBgZjC}[tD__@pDaYjB_MpBuLhGi[fC}KfFcSnEkObFgOrFkOzEoLt[ys@tJeUlIsSbKqXtFiPfKi]rG_W|CiNhDkPfDuQlDoShEuXrEy[nOgiAxF{`@|DoVzFk[fDwPlXupA~CoPfDuQxGcd@l@yEdH{r@xDam@`AiWz@mYtAq~@p@uqAfAqx@|@kZxA}^lBq\\|Be\\lAaO~Dm`@|Gsj@tS_~AhCyUrCeZrByWv@uLlUiyDpA}NdHkn@pGmb@LkAtAoIjDqR`I{`@`BcH|I_b@zJcd@lKig@\\_CbBaIlJ}g@lIoj@pAuJtFoh@~Eqs@hDmv@h@qOfF{jBn@gSxCio@dAuQn@gIVoBjAiOlCqWbCiT`PekAzKiu@~EgYfIya@fA{ExGwWnDkMdHiU|G}R`HgQhRsa@hW}g@jVsg@|a@cbAbJkUxKoYxLa_@`IiZzHu[`DoOXsBhBuJbCwNdBaL`EkYvAwM`CeVtEwj@nDqj@BkAnB{YpGgeAn@eJ`CmYvEid@tBkQpGkd@rE}UxB}JdJo_@nDcNfSan@nS}j@lCeIvDsMbC{J|CyNbAwFfCgPz@uGvBiSdD}`@rFon@nKaqAxDmc@xBuT|Fqc@nC_PrEcUtC_MpFcT`GqQxJmXfXwq@jQgh@hBeGhG_U|BaK|G}[nRikAzIam@tDsYfE}^v@_MbAwKn@oIr@yLrBub@jAoa@b@sRdDmjBx@aZdA}XnAqVpAgTlAqPn@oGvFye@dCeRzGwb@xT_}A`BcPrAoOvCad@jAmXv@eV`BieA~@a[fBg_@`CiZ~A_OhHqk@hHcn@tEwe@rDub@nBoW~@sN|BeZnAgMvDm\\hFs^hSigArFaY`Gc\\`C}OhD}YfByQdAaNbAkOtOu~Cn@wKz@uLfCeY|CkW~B}OhCmO|AcI~A_IvDoPpEyPdImWrDuKnL_YjI{Ptl@qfAle@u|@xI}PbImQvFwMbGgOxFkOpdAosCdD_KxGsU|E}RxFcXhCwNjDwTvBiPfBqOrAyMfBcTxAaVhAwVrCy_Al@iPt@_OtA}Q`AuJ`AgIzAkK`EoUtBsJhCaKxCaKdDaKhQeg@jGiRfGaSrFyR`HsWvL}f@xp@grC`Sq|@pEsVdAoGjF{XlkAgwHxHgj@|Jex@fg@qlEjQs{AdHwh@zDkVhEkVzI_e@v}AgzHpK_l@tE}YtEy[rC}TpFme@jg@cpEbF{d@~BoXfBqUbAyOx@yN|Ao]bAo[tIazC`@iLb@aJ~AkWbBgRdBgPjA{IdCePlAmHfBmJdCiL~CuM|DoNxhDezKdDkLvBoInFqVbCuMxBqNnAeJ~CwXdBoSb^crElFsl@`Dy[zDu^xBiRzc@aaE|Fsd@vCkShDmTpG}^lD}QzDoR|zAcdHvIob@dKoj@jDmSlKiq@xVacBhEqXnBqL|Ga^zJke@`y@ktD~Mop@tP}_AdOg`AtCiQxCyOlDkPfDoN`GiTfGkRjEwLvEsL|HkQtEkJdE{HrwAkaCrT{a@rpDiuHtE_KvLuV|{AwaDzAqCb@mAf{Ac`D~FqL~y@_fBlNmZbGaNtF}Mpn@s~AlYss@dFgK|DoGhBoCrDuE~AcBtGaGnByAnDwBnCwAfDwAnFaBjGkA~[{E`iEkn@pQaDvIwBnIiCl\\qLn}J{pDhMcGrFcDhGeEvoDehC|AsArCwChBaC`C_EzC_HbBcFd@uB`@qAn@gDdB}Kz@}Hn@iPjByx@jDcvAj@}RDsEn@yTv@a]VcPtEamFBcHT_LNkEdAiShDsi@`GudAbFgx@`@iKdP}yFhBgs@p@yRjCo_AJwCXeEb@uEz@_H|@yEnBqHrCiIpAmE`o@qhBxC_IjIuVdIcXh{AgmG`i@_{BfCuLrhAssGfFeXxbBklInCsN|_AoiGpGs_@pl@w}Czy@_kEvG{]h}@ieFbQehAdHye@lPagA|Eu\\tAmI|CwWjn@mwGj@eH|]azFl@kPjAqd@jJe|DlD}vAxAeh@@eBvVk}JzIkqDfE_aBfA{YbBk[zp@e}LhAaObCeUlAuIzAeJrb@q`CjCcOnAaIpBwOtBkTjDsg@~AiPvBwOlAcH|AkIlCkLlYudApDoN`BgHhBaJvAeIvAqJbAuHrBqQbAsLx@oL`MwrCXkFr@uJh@{FhBsOvXwoB|EqVdBmHxC}KtCcJtDgKjDoIxE}JdHcMdCuDdIoKlmB}|BjJuMfFgIlE{HlEyIdEeJ~FaOvCgInCuI`EmN`J}]rEsP`EuMzCoIxGwPpi@cnAhGgPzCiJvFmRrEwQbDyOtCoPbDwTxDq\\rAsK`BgLhB{KxBoLfCgLjDqKdBqEfEkJtSy^`EcJnDuJjAwDrCeK\\}AjCaNr@qEjAaJtNaqAdCqQ`BsItS}bAbQs{@|Kor@xBmKz}@}uDze@{zAjk@}fBjTsq@r@uCd@aDFyCIwCWcCY}Aq_@w|A{AwF_DyHgHwOgu@m_BSb@nFhL", // levels:"B?@?????@?@???A???@?@????@??@????????@????@???A????@????@??@???@??@???A???@??@???A??@???@????A??@???@??@????@??@???@????@???@??A@?@???@????A????@??@?@???@???????@??@?@????@????@?A??@???@????@??@?A??????@???????@??A???@??@???@??@????@??@?@?????@?@?A?@????@???@??@??@????@?@??@?@??@??????@???@?@????@???B???@??@??????@??@???A?????@????@???A??@??????@??@??A?@???@???@??A????@???@???@????A????@@??A???@???@??@??A????@??????@??@???@???B????@?@????????@????@????A?????@????@??A???@???@???B???@?????@???@????@????@???A???????@??A@??@?@??@@?????A?@@????????@??@?A????@?????@???@???@???@???@?@?A???@??@?@??@???@?????@???A??@???????@????@???@????@????@@???A????@?@??@?B", // numLevels:4, // zoomFactor:16 //}] //} #region -- title -- int tooltipEnd = 0; { int x = route.IndexOf("tooltipHtml:") + 13; if (x >= 13) { tooltipEnd = route.IndexOf("\"", x + 1); if (tooltipEnd > 0) { int l = tooltipEnd - x; if (l > 0) { tooltipHtml = route.Substring(x, l).Replace(@"\x26#160;", " "); } } } } #endregion #region -- points -- int pointsEnd = 0; { int x = route.IndexOf("points:", tooltipEnd >= 0 ? tooltipEnd : 0) + 8; if (x >= 8) { pointsEnd = route.IndexOf("\"", x + 1); if (pointsEnd > 0) { int l = pointsEnd - x; if (l > 0) { /* while(l % 5 != 0) { l--; } */ points = new List<PointLatLng>(); DecodePointsInto(points, route.Substring(x, l)); } } } } #endregion #region -- levels -- string levels = string.Empty; int levelsEnd = 0; { int x = route.IndexOf("levels:", pointsEnd >= 0 ? pointsEnd : 0) + 8; if (x >= 8) { levelsEnd = route.IndexOf("\"", x + 1); if (levelsEnd > 0) { int l = levelsEnd - x; if (l > 0) { levels = route.Substring(x, l); } } } } #endregion #region -- numLevel -- int numLevelsEnd = 0; { int x = route.IndexOf("numLevels:", levelsEnd >= 0 ? levelsEnd : 0) + 10; if (x >= 10) { numLevelsEnd = route.IndexOf(",", x); if (numLevelsEnd > 0) { int l = numLevelsEnd - x; if (l > 0) { numLevel = int.Parse(route.Substring(x, l)); } } } } #endregion #region -- zoomFactor -- { int x = route.IndexOf("zoomFactor:", numLevelsEnd >= 0 ? numLevelsEnd : 0) + 11; if (x >= 11) { int end = route.IndexOf("}", x); if (end > 0) { int l = end - x; if (l > 0) { zoomFactor = int.Parse(route.Substring(x, l)); } } } } #endregion #region -- trim point overload -- if (points != null && numLevel > 0 && !string.IsNullOrEmpty(levels)) { if (points.Count - levels.Length > 0) { points.RemoveRange(levels.Length, points.Count - levels.Length); } //http://facstaff.unca.edu/mcmcclur/GoogleMaps/EncodePolyline/description.html // string allZlevels = "TSRPONMLKJIHGFEDCBA@?"; if (numLevel > allZlevels.Length) { numLevel = allZlevels.Length; } // used letters in levels string string pLevels = allZlevels.Substring(allZlevels.Length - numLevel); // remove useless points at zoom { List<PointLatLng> removedPoints = new List<PointLatLng>(); for (int i = 0; i < levels.Length; i++) { int zi = pLevels.IndexOf(levels [i]); if (zi > 0) { if (zi * numLevel > zoom) { removedPoints.Add(points [i]); } } } foreach (var v in removedPoints) { points.Remove(v); } removedPoints.Clear(); removedPoints = null; } } #endregion } } catch (Exception ex) { points = null; Debug.WriteLine("GetRoutePoints: " + ex); } return points; } static readonly string RouteUrlFormatPointLatLng = "http://maps.{6}/maps?f=q&output=dragdir&doflg=p&hl={0}{1}&q=&saddr=@{2},{3}&daddr=@{4},{5}"; static readonly string RouteUrlFormatStr = "http://maps.{4}/maps?f=q&output=dragdir&doflg=p&hl={0}{1}&q=&saddr=@{2}&daddr=@{3}"; static readonly string WalkingStr = "&mra=ls&dirflg=w"; static readonly string RouteWithoutHighwaysStr = "&mra=ls&dirflg=dh"; static readonly string RouteStr = "&mra=ls&dirflg=d"; #endregion #endregion #region GeocodingProvider Members public GeoCoderStatusCode GetPoints(string keywords, out List<PointLatLng> pointList) { return GetLatLngFromGeocoderUrl(MakeGeocoderUrl(keywords, LanguageStr), out pointList); } public PointLatLng? GetPoint(string keywords, out GeoCoderStatusCode status) { List<PointLatLng> pointList; status = GetPoints(keywords, out pointList); return pointList != null && pointList.Count > 0 ? pointList [0] : (PointLatLng?)null; } /// <summary> /// NotImplemented /// </summary> /// <param name="placemark"></param> /// <param name="pointList"></param> /// <returns></returns> public GeoCoderStatusCode GetPoints(Placemark placemark, out List<PointLatLng> pointList) { throw new NotImplementedException("use GetPoints(string keywords..."); } /// <summary> /// NotImplemented /// </summary> /// <param name="placemark"></param> /// <param name="status"></param> /// <returns></returns> public PointLatLng? GetPoint(Placemark placemark, out GeoCoderStatusCode status) { throw new NotImplementedException("use GetPoint(string keywords..."); } public GeoCoderStatusCode GetPlacemarks(PointLatLng location, out List<Placemark> placemarkList) { return GetPlacemarkFromReverseGeocoderUrl(MakeReverseGeocoderUrl(location, LanguageStr), out placemarkList); } public Placemark? GetPlacemark(PointLatLng location, out GeoCoderStatusCode status) { List<Placemark> pointList; status = GetPlacemarks(location, out pointList); return pointList != null && pointList.Count > 0 ? pointList [0] : (Placemark?)null; } #region -- internals -- // The Coogle Geocoding API: http://tinyurl.com/cdlj889 string MakeGeocoderUrl(string keywords, string language) { return string.Format(CultureInfo.InvariantCulture, GeocoderUrlFormat, ServerAPIs, keywords.Replace(' ', '+'), language); } string MakeReverseGeocoderUrl(PointLatLng pt, string language) { return string.Format(CultureInfo.InvariantCulture, ReverseGeocoderUrlFormat, ServerAPIs, pt.Lat, pt.Lng, language); } GeoCoderStatusCode GetLatLngFromGeocoderUrl(string url, out List<PointLatLng> pointList) { var status = GeoCoderStatusCode.Unknow; pointList = null; try { string geo = GMaps.Instance.UseGeocoderCache ? Cache.Instance.GetContent(url, CacheType.GeocoderCache) : string.Empty; bool cache = false; if (string.IsNullOrEmpty(geo)) { geo = GetContentUsingHttp(url); if (!string.IsNullOrEmpty(geo)) { cache = true; } } if (!string.IsNullOrEmpty(geo)) { if (geo.StartsWith("<?xml")) { #region -- xml response -- //<?xml version="1.0" encoding="UTF-8"?> //<GeocodeResponse> // <status>OK</status> // <result> // <type>locality</type> // <type>political</type> // <formatted_address>Vilnius, Lithuania</formatted_address> // <address_component> // <long_name>Vilnius</long_name> // <short_name>Vilnius</short_name> // <type>locality</type> // <type>political</type> // </address_component> // <address_component> // <long_name>Vilniaus miesto savivaldyb??</long_name> // <short_name>Vilniaus m. sav.</short_name> // <type>administrative_area_level_2</type> // <type>political</type> // </address_component> // <address_component> // <long_name>Vilnius County</long_name> // <short_name>Vilnius County</short_name> // <type>administrative_area_level_1</type> // <type>political</type> // </address_component> // <address_component> // <long_name>Lithuania</long_name> // <short_name>LT</short_name> // <type>country</type> // <type>political</type> // </address_component> // <geometry> // <location> // <lat>54.6871555</lat> // <lng>25.2796514</lng> // </location> // <location_type>APPROXIMATE</location_type> // <viewport> // <southwest> // <lat>54.5677980</lat> // <lng>25.0243760</lng> // </southwest> // <northeast> // <lat>54.8325440</lat> // <lng>25.4814883</lng> // </northeast> // </viewport> // <bounds> // <southwest> // <lat>54.5677980</lat> // <lng>25.0243760</lng> // </southwest> // <northeast> // <lat>54.8325440</lat> // <lng>25.4814883</lng> // </northeast> // </bounds> // </geometry> // </result> // <result> // <type>airport</type> // <type>transit_station</type> // <type>establishment</type> // <formatted_address>Vilnius International Airport (VNO), 10A, Vilnius, Lithuania</formatted_address> // <address_component> // <long_name>Vilnius International Airport</long_name> // <short_name>Vilnius International Airport</short_name> // <type>establishment</type> // </address_component> // <address_component> // <long_name>10A</long_name> // <short_name>10A</short_name> // <type>street_number</type> // </address_component> // <address_component> // <long_name>Vilnius</long_name> // <short_name>Vilnius</short_name> // <type>locality</type> // <type>political</type> // </address_component> // <address_component> // <long_name>Vilniaus miesto savivaldyb??</long_name> // <short_name>Vilniaus m. sav.</short_name> // <type>administrative_area_level_2</type> // <type>political</type> // </address_component> // <address_component> // <long_name>Vilnius County</long_name> // <short_name>Vilnius County</short_name> // <type>administrative_area_level_1</type> // <type>political</type> // </address_component> // <address_component> // <long_name>Lithuania</long_name> // <short_name>LT</short_name> // <type>country</type> // <type>political</type> // </address_component> // <geometry> // <location> // <lat>54.6369440</lat> // <lng>25.2877780</lng> // </location> // <location_type>APPROXIMATE</location_type> // <viewport> // <southwest> // <lat>54.6158331</lat> // <lng>25.2723832</lng> // </southwest> // <northeast> // <lat>54.6538331</lat> // <lng>25.3034219</lng> // </northeast> // </viewport> // <bounds> // <southwest> // <lat>54.6158331</lat> // <lng>25.2723832</lng> // </southwest> // <northeast> // <lat>54.6538331</lat> // <lng>25.3034219</lng> // </northeast> // </bounds> // </geometry> // </result> //</GeocodeResponse> #endregion XmlDocument doc = new XmlDocument(); doc.LoadXml(geo); XmlNode nn = doc.SelectSingleNode("//status"); if (nn != null) { if (nn.InnerText != "OK") { Debug.WriteLine("GetLatLngFromGeocoderUrl: " + nn.InnerText); } else { status = GeoCoderStatusCode.G_GEO_SUCCESS; if (cache && GMaps.Instance.UseGeocoderCache) { Cache.Instance.SaveContent(url, CacheType.GeocoderCache, geo); } pointList = new List<PointLatLng>(); XmlNodeList l = doc.SelectNodes("//result"); if (l != null) { foreach (XmlNode n in l) { nn = n.SelectSingleNode("geometry/location/lat"); if (nn != null) { double lat = double.Parse(nn.InnerText, CultureInfo.InvariantCulture); nn = n.SelectSingleNode("geometry/location/lng"); if (nn != null) { double lng = double.Parse(nn.InnerText, CultureInfo.InvariantCulture); pointList.Add(new PointLatLng(lat, lng)); } } } } } } } } } catch (Exception ex) { status = GeoCoderStatusCode.ExceptionInCode; Debug.WriteLine("GetLatLngFromGeocoderUrl: " + ex); } return status; } GeoCoderStatusCode GetPlacemarkFromReverseGeocoderUrl(string url, out List<Placemark> placemarkList) { GeoCoderStatusCode status = GeoCoderStatusCode.Unknow; placemarkList = null; try { string reverse = GMaps.Instance.UsePlacemarkCache ? Cache.Instance.GetContent(url, CacheType.PlacemarkCache) : string.Empty; bool cache = false; if (string.IsNullOrEmpty(reverse)) { reverse = GetContentUsingHttp(url); if (!string.IsNullOrEmpty(reverse)) { cache = true; } } if (!string.IsNullOrEmpty(reverse)) { if (reverse.StartsWith("<?xml")) { #region -- xml response -- //<?xml version="1.0" encoding="UTF-8"?> //<GeocodeResponse> // <status>OK</status> // <result> // <type>street_address</type> // <formatted_address>Tuskul??n?? gatv?? 2, Vilnius 09213, Lithuania</formatted_address> // <address_component> // <long_name>2</long_name> // <short_name>2</short_name> // <type>street_number</type> // </address_component> // <address_component> // <long_name>Tuskul??n?? gatv??</long_name> // <short_name>Tuskul??n?? g.</short_name> // <type>route</type> // </address_component> // <address_component> // <long_name>Vilnius</long_name> // <short_name>Vilnius</short_name> // <type>locality</type> // <type>political</type> // </address_component> // <address_component> // <long_name>Vilniaus miesto savivaldyb??</long_name> // <short_name>Vilniaus m. sav.</short_name> // <type>administrative_area_level_2</type> // <type>political</type> // </address_component> // <address_component> // <long_name>Vilnius County</long_name> // <short_name>Vilnius County</short_name> // <type>administrative_area_level_1</type> // <type>political</type> // </address_component> // <address_component> // <long_name>Lithuania</long_name> // <short_name>LT</short_name> // <type>country</type> // <type>political</type> // </address_component> // <address_component> // <long_name>09213</long_name> // <short_name>09213</short_name> // <type>postal_code</type> // </address_component> // <geometry> // <location> // <lat>54.6963339</lat> // <lng>25.2968939</lng> // </location> // <location_type>ROOFTOP</location_type> // <viewport> // <southwest> // <lat>54.6949849</lat> // <lng>25.2955449</lng> // </southwest> // <northeast> // <lat>54.6976829</lat> // <lng>25.2982429</lng> // </northeast> // </viewport> // </geometry> // </result> // <result> // <type>postal_code</type> // <formatted_address>Vilnius 09213, Lithuania</formatted_address> // <address_component> // <long_name>09213</long_name> // <short_name>09213</short_name> // <type>postal_code</type> // </address_component> // <address_component> // <long_name>Vilnius</long_name> // <short_name>Vilnius</short_name> // <type>locality</type> // <type>political</type> // </address_component> // <address_component> // <long_name>Vilniaus miesto savivaldyb??</long_name> // <short_name>Vilniaus m. sav.</short_name> // <type>administrative_area_level_2</type> // <type>political</type> // </address_component> // <address_component> // <long_name>Vilnius County</long_name> // <short_name>Vilnius County</short_name> // <type>administrative_area_level_1</type> // <type>political</type> // </address_component> // <address_component> // <long_name>Lithuania</long_name> // <short_name>LT</short_name> // <type>country</type> // <type>political</type> // </address_component> // <geometry> // <location> // <lat>54.6963032</lat> // <lng>25.2967390</lng> // </location> // <location_type>APPROXIMATE</location_type> // <viewport> // <southwest> // <lat>54.6950889</lat> // <lng>25.2958851</lng> // </southwest> // <northeast> // <lat>54.6977869</lat> // <lng>25.2985830</lng> // </northeast> // </viewport> // <bounds> // <southwest> // <lat>54.6956179</lat> // <lng>25.2958871</lng> // </southwest> // <northeast> // <lat>54.6972579</lat> // <lng>25.2985810</lng> // </northeast> // </bounds> // </geometry> // </result> // <result> // <type>neighborhood</type> // <type>political</type> // <formatted_address>??irm??nai, Vilnius, Lithuania</formatted_address> // <address_component> // <long_name>??irm??nai</long_name> // <short_name>??irm??nai</short_name> // <type>neighborhood</type> // <type>political</type> // </address_component> // <address_component> // <long_name>Vilnius</long_name> // <short_name>Vilnius</short_name> // <type>locality</type> // <type>political</type> // </address_component> // <address_component> // <long_name>Vilniaus miesto savivaldyb??</long_name> // <short_name>Vilniaus m. sav.</short_name> // <type>administrative_area_level_2</type> // <type>political</type> // </address_component> // <address_component> // <long_name>Vilnius County</long_name> // <short_name>Vilnius County</short_name> // <type>administrative_area_level_1</type> // <type>political</type> // </address_component> // <address_component> // <long_name>Lithuania</long_name> // <short_name>LT</short_name> // <type>country</type> // <type>political</type> // </address_component> // <geometry> // <location> // <lat>54.7117424</lat> // <lng>25.2974345</lng> // </location> // <location_type>APPROXIMATE</location_type> // <viewport> // <southwest> // <lat>54.6888939</lat> // <lng>25.2838700</lng> // </southwest> // <northeast> // <lat>54.7304441</lat> // <lng>25.3133630</lng> // </northeast> // </viewport> // <bounds> // <southwest> // <lat>54.6888939</lat> // <lng>25.2838700</lng> // </southwest> // <northeast> // <lat>54.7304441</lat> // <lng>25.3133630</lng> // </northeast> // </bounds> // </geometry> // </result> // <result> // <type>administrative_area_level_3</type> // <type>political</type> // <formatted_address>??irm??n?? seni??nija, Lithuania</formatted_address> // <address_component> // <long_name>??irm??n?? seni??nija</long_name> // <short_name>??irm??n?? sen.</short_name> // <type>administrative_area_level_3</type> // <type>political</type> // </address_component> // <address_component> // <long_name>Vilniaus miesto savivaldyb??</long_name> // <short_name>Vilniaus m. sav.</short_name> // <type>administrative_area_level_2</type> // <type>political</type> // </address_component> // <address_component> // <long_name>Vilnius County</long_name> // <short_name>Vilnius County</short_name> // <type>administrative_area_level_1</type> // <type>political</type> // </address_component> // <address_component> // <long_name>Lithuania</long_name> // <short_name>LT</short_name> // <type>country</type> // <type>political</type> // </address_component> // <geometry> // <location> // <lat>54.7117424</lat> // <lng>25.2974345</lng> // </location> // <location_type>APPROXIMATE</location_type> // <viewport> // <southwest> // <lat>54.6892135</lat> // <lng>25.2837150</lng> // </southwest> // <northeast> // <lat>54.7305878</lat> // <lng>25.3135630</lng> // </northeast> // </viewport> // <bounds> // <southwest> // <lat>54.6892135</lat> // <lng>25.2837150</lng> // </southwest> // <northeast> // <lat>54.7305878</lat> // <lng>25.3135630</lng> // </northeast> // </bounds> // </geometry> // </result> // <result> // <type>locality</type> // <type>political</type> // <formatted_address>Vilnius, Lithuania</formatted_address> // <address_component> // <long_name>Vilnius</long_name> // <short_name>Vilnius</short_name> // <type>locality</type> // <type>political</type> // </address_component> // <address_component> // <long_name>Vilniaus miesto savivaldyb??</long_name> // <short_name>Vilniaus m. sav.</short_name> // <type>administrative_area_level_2</type> // <type>political</type> // </address_component> // <address_component> // <long_name>Vilnius County</long_name> // <short_name>Vilnius County</short_name> // <type>administrative_area_level_1</type> // <type>political</type> // </address_component> // <address_component> // <long_name>Lithuania</long_name> // <short_name>LT</short_name> // <type>country</type> // <type>political</type> // </address_component> // <geometry> // <location> // <lat>54.6871555</lat> // <lng>25.2796514</lng> // </location> // <location_type>APPROXIMATE</location_type> // <viewport> // <southwest> // <lat>54.5677980</lat> // <lng>25.0243760</lng> // </southwest> // <northeast> // <lat>54.8325440</lat> // <lng>25.4814883</lng> // </northeast> // </viewport> // <bounds> // <southwest> // <lat>54.5677980</lat> // <lng>25.0243760</lng> // </southwest> // <northeast> // <lat>54.8325440</lat> // <lng>25.4814883</lng> // </northeast> // </bounds> // </geometry> // </result> // <result> // <type>administrative_area_level_2</type> // <type>political</type> // <formatted_address>Vilniaus miesto savivaldyb??, Lithuania</formatted_address> // <address_component> // <long_name>Vilniaus miesto savivaldyb??</long_name> // <short_name>Vilniaus m. sav.</short_name> // <type>administrative_area_level_2</type> // <type>political</type> // </address_component> // <address_component> // <long_name>Vilnius County</long_name> // <short_name>Vilnius County</short_name> // <type>administrative_area_level_1</type> // <type>political</type> // </address_component> // <address_component> // <long_name>Lithuania</long_name> // <short_name>LT</short_name> // <type>country</type> // <type>political</type> // </address_component> // <geometry> // <location> // <lat>54.6759715</lat> // <lng>25.2867413</lng> // </location> // <location_type>APPROXIMATE</location_type> // <viewport> // <southwest> // <lat>54.5677980</lat> // <lng>25.0243760</lng> // </southwest> // <northeast> // <lat>54.8325440</lat> // <lng>25.4814883</lng> // </northeast> // </viewport> // <bounds> // <southwest> // <lat>54.5677980</lat> // <lng>25.0243760</lng> // </southwest> // <northeast> // <lat>54.8325440</lat> // <lng>25.4814883</lng> // </northeast> // </bounds> // </geometry> // </result> // <result> // <type>administrative_area_level_1</type> // <type>political</type> // <formatted_address>Vilnius County, Lithuania</formatted_address> // <address_component> // <long_name>Vilnius County</long_name> // <short_name>Vilnius County</short_name> // <type>administrative_area_level_1</type> // <type>political</type> // </address_component> // <address_component> // <long_name>Lithuania</long_name> // <short_name>LT</short_name> // <type>country</type> // <type>political</type> // </address_component> // <geometry> // <location> // <lat>54.8086502</lat> // <lng>25.2182138</lng> // </location> // <location_type>APPROXIMATE</location_type> // <viewport> // <southwest> // <lat>54.1276599</lat> // <lng>24.3863751</lng> // </southwest> // <northeast> // <lat>55.5174369</lat> // <lng>26.7602130</lng> // </northeast> // </viewport> // <bounds> // <southwest> // <lat>54.1276599</lat> // <lng>24.3863751</lng> // </southwest> // <northeast> // <lat>55.5174369</lat> // <lng>26.7602130</lng> // </northeast> // </bounds> // </geometry> // </result> // <result> // <type>country</type> // <type>political</type> // <formatted_address>Lithuania</formatted_address> // <address_component> // <long_name>Lithuania</long_name> // <short_name>LT</short_name> // <type>country</type> // <type>political</type> // </address_component> // <geometry> // <location> // <lat>55.1694380</lat> // <lng>23.8812750</lng> // </location> // <location_type>APPROXIMATE</location_type> // <viewport> // <southwest> // <lat>53.8968787</lat> // <lng>20.9543679</lng> // </southwest> // <northeast> // <lat>56.4503209</lat> // <lng>26.8355913</lng> // </northeast> // </viewport> // <bounds> // <southwest> // <lat>53.8968787</lat> // <lng>20.9543679</lng> // </southwest> // <northeast> // <lat>56.4503209</lat> // <lng>26.8355913</lng> // </northeast> // </bounds> // </geometry> // </result> //</GeocodeResponse> #endregion XmlDocument doc = new XmlDocument(); doc.LoadXml(reverse); XmlNode nn = doc.SelectSingleNode("//status"); if (nn != null) { if (nn.InnerText != "OK") { Debug.WriteLine("GetPlacemarkFromReverseGeocoderUrl: " + nn.InnerText); } else { status = GeoCoderStatusCode.G_GEO_SUCCESS; if (cache && GMaps.Instance.UsePlacemarkCache) { Cache.Instance.SaveContent(url, CacheType.PlacemarkCache, reverse); } placemarkList = new List<Placemark>(); #region -- placemarks -- XmlNodeList l = doc.SelectNodes("//result"); if (l != null) { foreach (XmlNode n in l) { Debug.WriteLine("---------------------"); nn = n.SelectSingleNode("formatted_address"); if (nn != null) { var ret = new Placemark(nn.InnerText); Debug.WriteLine("formatted_address: [" + nn.InnerText + "]"); nn = n.SelectSingleNode("type"); if (nn != null) { Debug.WriteLine("type: " + nn.InnerText); } // TODO: fill Placemark details XmlNodeList acl = n.SelectNodes("address_component"); foreach (XmlNode ac in acl) { nn = ac.SelectSingleNode("type"); if (nn != null) { var type = nn.InnerText; Debug.Write(" - [" + type + "], "); nn = ac.SelectSingleNode("long_name"); if (nn != null) { Debug.WriteLine("long_name: [" + nn.InnerText + "]"); switch (type) { case "street_address": { ret.StreetNumber = nn.InnerText; } break; case "route": { ret.ThoroughfareName = nn.InnerText; } break; case "postal_code": { ret.PostalCodeNumber = nn.InnerText; } break; case "country": { ret.CountryName = nn.InnerText; } break; case "locality": { ret.LocalityName = nn.InnerText; } break; case "administrative_area_level_2": { ret.DistrictName = nn.InnerText; } break; case "administrative_area_level_1": { ret.AdministrativeAreaName = nn.InnerText; } break; case "administrative_area_level_3": { ret.SubAdministrativeAreaName = nn.InnerText; } break; case "neighborhood": { ret.Neighborhood = nn.InnerText; } break; } } } } placemarkList.Add(ret); } } } #endregion } } #endregion } } } catch (Exception ex) { status = GeoCoderStatusCode.ExceptionInCode; placemarkList = null; Debug.WriteLine("GetPlacemarkReverseGeocoderUrl: " + ex.ToString()); } return status; } static readonly string ReverseGeocoderUrlFormat = "http://maps.{0}/maps/api/geocode/xml?latlng={1},{2}&language={3}&sensor=false"; static readonly string GeocoderUrlFormat = "http://maps.{0}/maps/api/geocode/xml?address={1}&language={2}&sensor=false"; #endregion #region DirectionsProvider Members public DirectionsStatusCode GetDirections(out GDirections direction, PointLatLng start, PointLatLng end, bool avoidHighways, bool avoidTolls, bool walkingMode, bool sensor, bool metric) { return GetDirectionsUrl(MakeDirectionsUrl(start, end, LanguageStr, avoidHighways, avoidTolls, walkingMode, sensor, metric), out direction); } public DirectionsStatusCode GetDirections(out GDirections direction, string start, string end, bool avoidHighways, bool avoidTolls, bool walkingMode, bool sensor, bool metric) { return GetDirectionsUrl(MakeDirectionsUrl(start, end, LanguageStr, avoidHighways, avoidTolls, walkingMode, sensor, metric), out direction); } /// <summary> /// NotImplemented /// </summary> /// <param name="status"></param> /// <param name="start"></param> /// <param name="end"></param> /// <param name="avoidHighways"></param> /// <param name="avoidTolls"></param> /// <param name="walkingMode"></param> /// <param name="sensor"></param> /// <param name="metric"></param> /// <returns></returns> public IEnumerable<GDirections> GetDirections(out DirectionsStatusCode status, string start, string end, bool avoidHighways, bool avoidTolls, bool walkingMode, bool sensor, bool metric) { // TODO: add alternative directions throw new NotImplementedException(); } /// <summary> /// NotImplemented /// </summary> /// <param name="status"></param> /// <param name="start"></param> /// <param name="end"></param> /// <param name="avoidHighways"></param> /// <param name="avoidTolls"></param> /// <param name="walkingMode"></param> /// <param name="sensor"></param> /// <param name="metric"></param> /// <returns></returns> public IEnumerable<GDirections> GetDirections(out DirectionsStatusCode status, PointLatLng start, PointLatLng end, bool avoidHighways, bool avoidTolls, bool walkingMode, bool sensor, bool metric) { // TODO: add alternative directions throw new NotImplementedException(); } public DirectionsStatusCode GetDirections(out GDirections direction, PointLatLng start, IEnumerable<PointLatLng> wayPoints, bool avoidHighways, bool avoidTolls, bool walkingMode, bool sensor, bool metric) { return GetDirectionsUrl(MakeDirectionsUrl(start, wayPoints, LanguageStr, avoidHighways, avoidTolls, walkingMode, sensor, metric), out direction); } public DirectionsStatusCode GetDirections(out GDirections direction, string start, IEnumerable<string> wayPoints, bool avoidHighways, bool avoidTolls, bool walkingMode, bool sensor, bool metric) { return GetDirectionsUrl(MakeDirectionsUrl(start, wayPoints, LanguageStr, avoidHighways, avoidTolls, walkingMode, sensor, metric), out direction); } #region -- internals -- // The Coogle Directions API: http://tinyurl.com/6vv4cac string MakeDirectionsUrl(PointLatLng start, PointLatLng end, string language, bool avoidHighways, bool avoidTolls, bool walkingMode, bool sensor, bool metric) { string av = (avoidHighways ? "&avoid=highways" : string.Empty) + (avoidTolls ? "&avoid=tolls" : string.Empty); // 6 string mt = "&units=" + (metric ? "metric" : "imperial"); // 7 string wk = "&mode=" + (walkingMode ? "walking" : "driving"); // 8 return string.Format(CultureInfo.InvariantCulture, DirectionUrlFormatPoint, start.Lat, start.Lng, end.Lat, end.Lng, sensor.ToString().ToLower(), language, av, mt, wk, ServerAPIs); } string MakeDirectionsUrl(string start, string end, string language, bool avoidHighways, bool walkingMode, bool avoidTolls, bool sensor, bool metric) { string av = (avoidHighways ? "&avoid=highways" : string.Empty) + (avoidTolls ? "&avoid=tolls" : string.Empty); // 4 string mt = "&units=" + (metric ? "metric" : "imperial"); // 5 string wk = "&mode=" + (walkingMode ? "walking" : "driving"); // 6 return string.Format(DirectionUrlFormatStr, start.Replace(' ', '+'), end.Replace(' ', '+'), sensor.ToString().ToLower(), language, av, mt, wk, ServerAPIs); } string MakeDirectionsUrl(PointLatLng start, IEnumerable<PointLatLng> wayPoints, string language, bool avoidHighways, bool avoidTolls, bool walkingMode, bool sensor, bool metric) { string av = (avoidHighways ? "&avoid=highways" : string.Empty) + (avoidTolls ? "&avoid=tolls" : string.Empty); // 6 string mt = "&units=" + (metric ? "metric" : "imperial"); // 7 string wk = "&mode=" + (walkingMode ? "walking" : "driving"); // 8 string wpLatLng = string.Empty; int i = 0; foreach (var wp in wayPoints) { wpLatLng += string.Format(CultureInfo.InvariantCulture, i++ == 0 ? "{0},{1}" : "|{0},{1}", wp.Lat, wp.Lng); } return string.Format(CultureInfo.InvariantCulture, DirectionUrlFormatWaypoint, start.Lat, start.Lng, wpLatLng, sensor.ToString().ToLower(), language, av, mt, wk, ServerAPIs); } string MakeDirectionsUrl(string start, IEnumerable<string> wayPoints, string language, bool avoidHighways, bool avoidTolls, bool walkingMode, bool sensor, bool metric) { string av = (avoidHighways ? "&avoid=highways" : string.Empty) + (avoidTolls ? "&avoid=tolls" : string.Empty); // 6 string mt = "&units=" + (metric ? "metric" : "imperial"); // 7 string wk = "&mode=" + (walkingMode ? "walking" : "driving"); // 8 string wpLatLng = string.Empty; int i = 0; foreach (var wp in wayPoints) { wpLatLng += string.Format(CultureInfo.InvariantCulture, i++ == 0 ? "{0}" : "|{0}", wp.Replace(' ', '+')); } return string.Format(CultureInfo.InvariantCulture, DirectionUrlFormatWaypointStr, start.Replace(' ', '+'), wpLatLng, sensor.ToString().ToLower(), language, av, mt, wk, ServerAPIs); } DirectionsStatusCode GetDirectionsUrl(string url, out GDirections direction) { DirectionsStatusCode ret = DirectionsStatusCode.UNKNOWN_ERROR; direction = null; try { string kml = GMaps.Instance.UseDirectionsCache ? Cache.Instance.GetContent(url, CacheType.DirectionsCache) : string.Empty; bool cache = false; if (string.IsNullOrEmpty(kml)) { kml = GetContentUsingHttp(url); if (!string.IsNullOrEmpty(kml)) { cache = true; } } if (!string.IsNullOrEmpty(kml)) { #region -- kml response -- //<?xml version="1.0" encoding="UTF-8"?> //<DirectionsResponse> // <status>OK</status> // <route> // <summary>A1/E85</summary> // <leg> // <step> // <travel_mode>DRIVING</travel_mode> // <start_location> // <lat>54.6893800</lat> // <lng>25.2800500</lng> // </start_location> // <end_location> // <lat>54.6907800</lat> // <lng>25.2798000</lng> // </end_location> // <polyline> // <points>soxlIiohyCYLkCJ}@Vs@?</points> // </polyline> // <duration> // <value>32</value> // <text>1 min</text> // </duration> // <html_instructions>Head &lt;b&gt;north&lt;/b&gt; on &lt;b&gt;Vilniaus gatvė&lt;/b&gt; toward &lt;b&gt;Tilto gatvė&lt;/b&gt;</html_instructions> // <distance> // <value>157</value> // <text>0.2 km</text> // </distance> // </step> // <step> // <travel_mode>DRIVING</travel_mode> // <start_location> // <lat>54.6907800</lat> // <lng>25.2798000</lng> // </start_location> // <end_location> // <lat>54.6942500</lat> // <lng>25.2621300</lng> // </end_location> // <polyline> // <points>kxxlIwmhyCmApUF`@GvAYpD{@dGcCjIoIvOuAhDwAtEa@vBUnDAhB?~AThDRxAh@hBtAdC</points> // </polyline> // <duration> // <value>133</value> // <text>2 mins</text> // </duration> // <html_instructions>Turn &lt;b&gt;left&lt;/b&gt; onto &lt;b&gt;A. Goštauto gatvė&lt;/b&gt;</html_instructions> // <distance> // <value>1326</value> // <text>1.3 km</text> // </distance> // </step> // <step> // <travel_mode>DRIVING</travel_mode> // <start_location> // <lat>54.6942500</lat> // <lng>25.2621300</lng> // </start_location> // <end_location> // <lat>54.6681200</lat> // <lng>25.2377500</lng> // </end_location> // <polyline> // <points>anylIi_eyC`AwD~@oBLKr@K`U|FdF|@`J^~E[j@Lh@\hB~Bn@tBZhBLrC?zIJ~DzA~OVrELlG^lDdAtDh@hAfApA`EzCvAp@jUpIpAl@bBpAdBpBxA|BdLpV`BxClAbBhBlBbChBpBhAdAXjBHlE_@t@?|@Lt@X</points> // </polyline> // <duration> // <value>277</value> // <text>5 mins</text> // </duration> // <html_instructions>Turn &lt;b&gt;left&lt;/b&gt; to merge onto &lt;b&gt;Geležinio Vilko gatvė&lt;/b&gt;</html_instructions> // <distance> // <value>3806</value> // <text>3.8 km</text> // </distance> // </step> // <step> // <travel_mode>DRIVING</travel_mode> // <start_location> // <lat>54.6681200</lat> // <lng>25.2377500</lng> // </start_location> // <end_location> // <lat>54.6584100</lat> // <lng>25.1411300</lng> // </end_location> // <polyline> // <points>wjtlI}f`yC~FhBlFr@jD|A~EbC~VjNxBbBdA`BnvA|zCba@l`Bt@tDTbBJpBBfBMvDaAzF}bBjiF{HnXiHxZ</points> // </polyline> // <duration> // <value>539</value> // <text>9 mins</text> // </duration> // <html_instructions>Continue onto &lt;b&gt;Savanorių prospektas&lt;/b&gt;</html_instructions> // <distance> // <value>8465</value> // <text>8.5 km</text> // </distance> // </step> // <step> // <travel_mode>DRIVING</travel_mode> // <start_location> // <lat>54.6584100</lat> // <lng>25.1411300</lng> // </start_location> // <end_location> // <lat>54.9358200</lat> // <lng>23.9260000</lng> // </end_location> // <polyline> // <points>anrlIakmxCiq@|qCuBbLcK~n@wUrkAcPnw@gCnPoQt}AoB`MuAdHmAdFoCtJqClImBxE{DrIkQ|ZcEvIkDzIcDhKyBxJ{EdXuCtS_G`g@mF|\eF`WyDhOiE~NiErMaGpOoj@ppAoE|K_EzKeDtKkEnOsLnd@mDzLgI~U{FrNsEvJoEtI_FpI{J`O_EjFooBf_C{GdJ_FjIsH`OoFhMwH`UcDtL{CzMeDlQmAzHuU~bBiArIwApNaBfWaLfiCoBpYsDf\qChR_FlVqEpQ_ZbfA}CfN{A~HwCtRiAfKmBlVwBx[gBfRcBxMaLdp@sXrzAaE~UqCzRyC`[_q@z|LgC|e@m@vNqp@b}WuLraFo@jPaS~bDmJryAeo@v|G}CnWsm@~`EoKvo@kv@lkEkqBrlKwBvLkNj|@cu@`~EgCnNuiBpcJakAx|GyB`KqdC~fKoIfYicAxtCiDrLu@hDyBjQm@xKoGdxBmQhoGuUn|Dc@nJ[`OW|VaEn|Ee@`X</points> // </polyline> // <duration> // <value>3506</value> // <text>58 mins</text> // </duration> // <html_instructions>Continue onto &lt;b&gt;A1/E85&lt;/b&gt;</html_instructions> // <distance> // <value>85824</value> // <text>85.8 km</text> // </distance> // </step> // <step> // <travel_mode>DRIVING</travel_mode> // <start_location> // <lat>54.9358200</lat> // <lng>23.9260000</lng> // </start_location> // <end_location> // <lat>54.9376500</lat> // <lng>23.9195600</lng> // </end_location> // <polyline> // <points>{shnIo``qCQ^MnD[lBgA`DqBdEu@xB}@zJCjB</points> // </polyline> // <duration> // <value>39</value> // <text>1 min</text> // </duration> // <html_instructions>Take the exit toward &lt;b&gt;Senamiestis/Aleksotas&lt;/b&gt;</html_instructions> // <distance> // <value>476</value> // <text>0.5 km</text> // </distance> // </step> // <step> // <travel_mode>DRIVING</travel_mode> // <start_location> // <lat>54.9376500</lat> // <lng>23.9195600</lng> // </start_location> // <end_location> // <lat>54.9361300</lat> // <lng>23.9189700</lng> // </end_location> // <polyline> // <points>i_inIgx~pCnHtB</points> // </polyline> // <duration> // <value>28</value> // <text>1 min</text> // </duration> // <html_instructions>Turn &lt;b&gt;left&lt;/b&gt; onto &lt;b&gt;Kleboniškio gatvė&lt;/b&gt;</html_instructions> // <distance> // <value>173</value> // <text>0.2 km</text> // </distance> // </step> // <step> // <travel_mode>DRIVING</travel_mode> // <start_location> // <lat>54.9361300</lat> // <lng>23.9189700</lng> // </start_location> // <end_location> // <lat>54.9018900</lat> // <lng>23.8937000</lng> // </end_location> // <polyline> // <points>yuhnIqt~pCvAb@JLrOvExSdHvDdAv`@pIpHnAdl@hLdB`@nDvAtEjDdCvCjLzOvAzBhC`GpHfRbQd^`JpMPt@ClA</points> // </polyline> // <duration> // <value>412</value> // <text>7 mins</text> // </duration> // <html_instructions>Continue onto &lt;b&gt;Jonavos gatvė&lt;/b&gt;</html_instructions> // <distance> // <value>4302</value> // <text>4.3 km</text> // </distance> // </step> // <step> // <travel_mode>DRIVING</travel_mode> // <start_location> // <lat>54.9018900</lat> // <lng>23.8937000</lng> // </start_location> // <end_location> // <lat>54.8985600</lat> // <lng>23.8933400</lng> // </end_location> // <polyline> // <points>y_bnIsvypCMf@FnARlAf@zAl@^v@EZ_@pAe@x@k@xBPpA@pAQNSf@oB</points> // </polyline> // <duration> // <value>69</value> // <text>1 min</text> // </duration> // <html_instructions>At the roundabout, take the &lt;b&gt;3rd&lt;/b&gt; exit and stay on &lt;b&gt;Jonavos gatvė&lt;/b&gt;</html_instructions> // <distance> // <value>478</value> // <text>0.5 km</text> // </distance> // </step> // <step> // <travel_mode>DRIVING</travel_mode> // <start_location> // <lat>54.8985600</lat> // <lng>23.8933400</lng> // </start_location> // <end_location> // <lat>54.8968500</lat> // <lng>23.8930000</lng> // </end_location> // <polyline> // <points>_kanIktypCbEx@pCH</points> // </polyline> // <duration> // <value>38</value> // <text>1 min</text> // </duration> // <html_instructions>Turn &lt;b&gt;right&lt;/b&gt; onto &lt;b&gt;A. Mapu gatvė&lt;/b&gt;&lt;div style=&quot;font-size:0.9em&quot;&gt;Destination will be on the right&lt;/div&gt;</html_instructions> // <distance> // <value>192</value> // <text>0.2 km</text> // </distance> // </step> // <duration> // <value>5073</value> // <text>1 hour 25 mins</text> // </duration> // <distance> // <value>105199</value> // <text>105 km</text> // </distance> // <start_location> // <lat>54.6893800</lat> // <lng>25.2800500</lng> // </start_location> // <end_location> // <lat>54.8968500</lat> // <lng>23.8930000</lng> // </end_location> // <start_address>Vilnius, Lithuania</start_address> // <end_address>Kaunas, Lithuania</end_address> // </leg> // <copyrights>Map data ©2011 Tele Atlas</copyrights> // <overview_polyline> // <points>soxlIiohyCYL}Fb@mApUF`@GvAYpD{@dGcCjIoIvOwBpFy@xC]jBSxCC~E^~Er@lCtAdC`AwD~@oB`AW`U|FdF|@`J^~E[tAj@hB~BjA~ELrCJzOzA~Od@`N^lDdAtDt@xAjAnApDlCbXbKpAl@bBpAdBpBxA|BdLpV`BxCvDpEbChBpBhAdAXjBHbG_@|@LtHbClFr@jK`F~VjNxBbB`@h@rwAt|Cba@l`BjAxGNxEMvDaAzF}bBjiFcFbQ_y@|gD{CxMeBnJcK~n@wh@dkCkAlIoQt}AeEfV}EzQqClImBxE{DrIkQ|ZcEvIkDzIcDhKyBxJ{EdXuCtS_G`g@mF|\eF`WyDhOiE~NiErMaGpOoj@ppAoE|K_EzKeDtKmXzbAgI~U{FrNsEvJoLfT{J`O_EjFooBf_C{GdJkLtSwI`SyClI}CrJcDtL{CzMeDlQcXzlBiArIwApNaBfWaLfiCoBpYsDf\qChR_FlVqEpQ_ZbfAyFfXwCtRiAfKeFfs@gBfRcBxMaLdp@sXrzAaE~UqCzRyC`[_q@z|LuDtu@qp@b}WuLraFo@jPo^r}Faq@pfHaBtMsm@~`EoKvo@kv@lkEcuBjzKkNj|@cu@`~EgCnNuiBpcJakAx|GyB`KqdC~fKoIfYidAbwCoD|MeAbHcA|Im@xK}YnhKyV~gEs@~f@aEn|Ee@`XQ^MnD[lBoF`N}@zJCjBfKxCJLdj@bQv`@pIpHnAdl@hLdB`@nDvAtEjDdCvCbOvSzLhZbQd^`JpMPt@QtBFnAz@hDl@^j@?f@e@pAe@x@k@xBPfCEf@Uj@wBbEx@pCH</points> // </overview_polyline> // <bounds> // <southwest> // <lat>54.6389500</lat> // <lng>23.8920900</lng> // </southwest> // <northeast> // <lat>54.9376500</lat> // <lng>25.2800500</lng> // </northeast> // </bounds> // </route> //</DirectionsResponse> #endregion XmlDocument doc = new XmlDocument(); doc.LoadXml(kml); XmlNode nn = doc.SelectSingleNode("/DirectionsResponse/status"); if (nn != null) { ret = (DirectionsStatusCode)Enum.Parse(typeof(DirectionsStatusCode), nn.InnerText, false); if (ret == DirectionsStatusCode.OK) { if (cache && GMaps.Instance.UseDirectionsCache) { Cache.Instance.SaveContent(url, CacheType.DirectionsCache, kml); } direction = new GDirections(); nn = doc.SelectSingleNode("/DirectionsResponse/route/summary"); if (nn != null) { direction.Summary = nn.InnerText; Debug.WriteLine("summary: " + direction.Summary); } nn = doc.SelectSingleNode("/DirectionsResponse/route/leg/duration"); if (nn != null) { var t = nn.SelectSingleNode("text"); if (t != null) { direction.Duration = t.InnerText; Debug.WriteLine("duration: " + direction.Duration); } t = nn.SelectSingleNode("value"); if (t != null) { if (!string.IsNullOrEmpty(t.InnerText)) { direction.DurationValue = uint.Parse(t.InnerText); Debug.WriteLine("value: " + direction.DurationValue); } } } nn = doc.SelectSingleNode("/DirectionsResponse/route/leg/distance"); if (nn != null) { var t = nn.SelectSingleNode("text"); if (t != null) { direction.Distance = t.InnerText; Debug.WriteLine("distance: " + direction.Distance); } t = nn.SelectSingleNode("value"); if (t != null) { if (!string.IsNullOrEmpty(t.InnerText)) { direction.DistanceValue = uint.Parse(t.InnerText); Debug.WriteLine("value: " + direction.DistanceValue); } } } nn = doc.SelectSingleNode("/DirectionsResponse/route/leg/start_location"); if (nn != null) { var pt = nn.SelectSingleNode("lat"); if (pt != null) { direction.StartLocation.Lat = double.Parse(pt.InnerText, CultureInfo.InvariantCulture); } pt = nn.SelectSingleNode("lng"); if (pt != null) { direction.StartLocation.Lng = double.Parse(pt.InnerText, CultureInfo.InvariantCulture); } } nn = doc.SelectSingleNode("/DirectionsResponse/route/leg/end_location"); if (nn != null) { var pt = nn.SelectSingleNode("lat"); if (pt != null) { direction.EndLocation.Lat = double.Parse(pt.InnerText, CultureInfo.InvariantCulture); } pt = nn.SelectSingleNode("lng"); if (pt != null) { direction.EndLocation.Lng = double.Parse(pt.InnerText, CultureInfo.InvariantCulture); } } nn = doc.SelectSingleNode("/DirectionsResponse/route/leg/start_address"); if (nn != null) { direction.StartAddress = nn.InnerText; Debug.WriteLine("start_address: " + direction.StartAddress); } nn = doc.SelectSingleNode("/DirectionsResponse/route/leg/end_address"); if (nn != null) { direction.EndAddress = nn.InnerText; Debug.WriteLine("end_address: " + direction.EndAddress); } nn = doc.SelectSingleNode("/DirectionsResponse/route/copyrights"); if (nn != null) { direction.Copyrights = nn.InnerText; Debug.WriteLine("copyrights: " + direction.Copyrights); } nn = doc.SelectSingleNode("/DirectionsResponse/route/overview_polyline/points"); if (nn != null) { direction.Route = new List<PointLatLng>(); DecodePointsInto(direction.Route, nn.InnerText); } XmlNodeList steps = doc.SelectNodes("/DirectionsResponse/route/leg/step"); if (steps != null) { if (steps.Count > 0) { direction.Steps = new List<GDirectionStep>(); } foreach (XmlNode s in steps) { GDirectionStep step = new GDirectionStep(); Debug.WriteLine("----------------------"); nn = s.SelectSingleNode("travel_mode"); if (nn != null) { step.TravelMode = nn.InnerText; Debug.WriteLine("travel_mode: " + step.TravelMode); } nn = s.SelectSingleNode("start_location"); if (nn != null) { var pt = nn.SelectSingleNode("lat"); if (pt != null) { step.StartLocation.Lat = double.Parse(pt.InnerText, CultureInfo.InvariantCulture); } pt = nn.SelectSingleNode("lng"); if (pt != null) { step.StartLocation.Lng = double.Parse(pt.InnerText, CultureInfo.InvariantCulture); } } nn = s.SelectSingleNode("end_location"); if (nn != null) { var pt = nn.SelectSingleNode("lat"); if (pt != null) { step.EndLocation.Lat = double.Parse(pt.InnerText, CultureInfo.InvariantCulture); } pt = nn.SelectSingleNode("lng"); if (pt != null) { step.EndLocation.Lng = double.Parse(pt.InnerText, CultureInfo.InvariantCulture); } } nn = s.SelectSingleNode("duration"); if (nn != null) { nn = nn.SelectSingleNode("text"); if (nn != null) { step.Duration = nn.InnerText; Debug.WriteLine("duration: " + step.Duration); } } nn = s.SelectSingleNode("distance"); if (nn != null) { nn = nn.SelectSingleNode("text"); if (nn != null) { step.Distance = nn.InnerText; Debug.WriteLine("distance: " + step.Distance); } } nn = s.SelectSingleNode("html_instructions"); if (nn != null) { step.HtmlInstructions = nn.InnerText; Debug.WriteLine("html_instructions: " + step.HtmlInstructions); } nn = s.SelectSingleNode("polyline"); if (nn != null) { nn = nn.SelectSingleNode("points"); if (nn != null) { step.Points = new List<PointLatLng>(); DecodePointsInto(step.Points, nn.InnerText); } } direction.Steps.Add(step); } } } } } } catch (Exception ex) { direction = null; ret = DirectionsStatusCode.ExceptionInCode; Debug.WriteLine("GetDirectionsUrl: " + ex); } return ret; } static void DecodePointsInto(List<PointLatLng> list, string encodedPoints) { // http://tinyurl.com/3ds3scr // http://code.server.com/apis/maps/documentation/polylinealgorithm.html // string encoded = encodedPoints.Replace("\\\\", "\\"); { int len = encoded.Length; int index = 0; double dlat = 0; double dlng = 0; while (index < len) { int b; int shift = 0; int result = 0; do { b = encoded [index++] - 63; result |= (b & 0x1f) << shift; shift += 5; } while (b >= 0x20 && index < len); dlat += ((result & 1) == 1 ? ~(result >> 1) : (result >> 1)); shift = 0; result = 0; if (index < len) { do { b = encoded [index++] - 63; result |= (b & 0x1f) << shift; shift += 5; } while (b >= 0x20 && index < len); dlng += ((result & 1) == 1 ? ~(result >> 1) : (result >> 1)); list.Add(new PointLatLng(dlat * 1e-5, dlng * 1e-5)); } } } } static readonly string DirectionUrlFormatStr = "http://maps.{7}/maps/api/directions/xml?origin={0}&destination={1}&sensor={2}&language={3}{4}{5}{6}"; static readonly string DirectionUrlFormatPoint = "http://maps.{9}/maps/api/directions/xml?origin={0},{1}&destination={2},{3}&sensor={4}&language={5}{6}{7}{8}"; static readonly string DirectionUrlFormatWaypoint = "http://maps.{8}/maps/api/directions/xml?origin={0},{1}&waypoints={2}&sensor={3}&language={4}{5}{6}{7}"; static readonly string DirectionUrlFormatWaypointStr = "http://maps.{7}/maps/api/directions/xml?origin={0}&waypoints={1}&sensor={2}&language={3}{4}{5}{6}"; #endregion #endregion } /// <summary> /// GoogleMap provider /// </summary> public class GoogleMapProvider : GoogleMapProviderBase { public static readonly GoogleMapProvider Instance; GoogleMapProvider() { } static GoogleMapProvider() { Instance = new GoogleMapProvider(); } public string Version = "m@249000000"; #region GMapProvider Members readonly Guid id = new Guid("D7287DA0-A7FF-405F-8166-B6BAF26D066C"); public override Guid Id { get { return id; } } readonly string name = "GoogleMap"; public override string Name { get { return name; } } public override PureImage GetTileImage(GPoint pos, int zoom) { string url = MakeTileImageUrl(pos, zoom, LanguageStr); return GetTileImageUsingHttp(url); } #endregion string MakeTileImageUrl(GPoint pos, int zoom, string language) { string sec1 = string.Empty; // after &x=... string sec2 = string.Empty; // after &zoom=... GetSecureWords(pos, out sec1, out sec2); return string.Format(UrlFormat, UrlFormatServer, GetServerNum(pos, 4), UrlFormatRequest, Version, language, pos.X, sec1, pos.Y, zoom, sec2, Server); } static readonly string UrlFormatServer = "mt"; static readonly string UrlFormatRequest = "vt"; static readonly string UrlFormat = "http://{0}{1}.{10}/{2}/lyrs={3}&hl={4}&x={5}{6}&y={7}&z={8}&s={9}"; } }
49.039206
2,873
0.385827
[ "MIT" ]
azprofe/marianMaps
mapas/lib/GMap.NET.Core/GMap.NET.MapProviders/Google/GoogleMapProvider.cs
103,834
C#
using Microsoft.Data.SqlClient; public class TestBase : IDisposable { public TestBase() { SqlConnection = Connection.OpenConnection(); } public SqlConnection SqlConnection; public virtual void Dispose() { SqlConnection?.Dispose(); } }
15.944444
52
0.641115
[ "MIT" ]
NServiceBusExtensions/NServiceBus.SqlNative
src/SqlServer.Native.Tests/TestHelpers/TestBase.cs
289
C#
using System.Collections; using System.Collections.Generic; using UnityEngine; public enum AnimTriggers { Idle, Happy, Angry, Sit}; public class PikachuController : MonoBehaviour { [SerializeField] private Animator m_PikachuAnimator; [SerializeField] private PikachuFacialExpressionController m_PikachuFacialExpressionControllerScript; public void GetHappy(){ m_PikachuAnimator.SetTrigger(AnimTriggers.Happy.ToString()); m_PikachuFacialExpressionControllerScript.SetHappyFacialExpression(); m_PikachuFacialExpressionControllerScript.StopBlinking(); } public void GetAngry(){ m_PikachuAnimator.SetTrigger(AnimTriggers.Angry.ToString()); m_PikachuFacialExpressionControllerScript.SetAngryFacialExpression(); m_PikachuFacialExpressionControllerScript.StartAngryBlinking(); } public void Idle(){ m_PikachuAnimator.SetTrigger(AnimTriggers.Idle.ToString()); m_PikachuFacialExpressionControllerScript.SetNormalFacialExpression(); m_PikachuFacialExpressionControllerScript.StartNormalBlinking(); } public void Sit(){ m_PikachuAnimator.SetTrigger(AnimTriggers.Sit.ToString()); m_PikachuFacialExpressionControllerScript.SetNormalFacialExpression(); m_PikachuFacialExpressionControllerScript.StartNormalBlinking(); } }
36.648649
88
0.774336
[ "MIT" ]
hferoze/Unity-Projects
Pikachu/Assets/Scripts/PikachuController.cs
1,358
C#
#pragma checksum "D:\Kurslar\ASP.NET_MVC_CORE\FullStackDotNetCore-Lessons\DbFirst\DbFirst\Views\Home\Privacy.cshtml" "{ff1816ec-aa5e-4d10-87f7-6f4963833460}" "d8ddb6bffa5a9b264bf8f89038bf03c234083fd3" // <auto-generated/> #pragma warning disable 1591 [assembly: global::Microsoft.AspNetCore.Razor.Hosting.RazorCompiledItemAttribute(typeof(AspNetCore.Views_Home_Privacy), @"mvc.1.0.view", @"/Views/Home/Privacy.cshtml")] namespace AspNetCore { #line hidden using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.Rendering; using Microsoft.AspNetCore.Mvc.ViewFeatures; #nullable restore #line 1 "D:\Kurslar\ASP.NET_MVC_CORE\FullStackDotNetCore-Lessons\DbFirst\DbFirst\Views\_ViewImports.cshtml" using DbFirst; #line default #line hidden #nullable disable #nullable restore #line 2 "D:\Kurslar\ASP.NET_MVC_CORE\FullStackDotNetCore-Lessons\DbFirst\DbFirst\Views\_ViewImports.cshtml" using DbFirst.Models; #line default #line hidden #nullable disable [global::Microsoft.AspNetCore.Razor.Hosting.RazorSourceChecksumAttribute(@"SHA1", @"d8ddb6bffa5a9b264bf8f89038bf03c234083fd3", @"/Views/Home/Privacy.cshtml")] [global::Microsoft.AspNetCore.Razor.Hosting.RazorSourceChecksumAttribute(@"SHA1", @"ea3803ee4b1fa1696ead876a73023493de43bdb6", @"/Views/_ViewImports.cshtml")] #nullable restore public class Views_Home_Privacy : global::Microsoft.AspNetCore.Mvc.Razor.RazorPage<dynamic> #nullable disable { #pragma warning disable 1998 public async override global::System.Threading.Tasks.Task ExecuteAsync() { #nullable restore #line 1 "D:\Kurslar\ASP.NET_MVC_CORE\FullStackDotNetCore-Lessons\DbFirst\DbFirst\Views\Home\Privacy.cshtml" ViewData["Title"] = "Privacy Policy"; #line default #line hidden #nullable disable WriteLiteral("<h1>"); #nullable restore #line 4 "D:\Kurslar\ASP.NET_MVC_CORE\FullStackDotNetCore-Lessons\DbFirst\DbFirst\Views\Home\Privacy.cshtml" Write(ViewData["Title"]); #line default #line hidden #nullable disable WriteLiteral("</h1>\r\n\r\n<p>Use this page to detail your site\'s privacy policy.</p>\r\n"); } #pragma warning restore 1998 #nullable restore [global::Microsoft.AspNetCore.Mvc.Razor.Internal.RazorInjectAttribute] public global::Microsoft.AspNetCore.Mvc.ViewFeatures.IModelExpressionProvider ModelExpressionProvider { get; private set; } = default!; #nullable disable #nullable restore [global::Microsoft.AspNetCore.Mvc.Razor.Internal.RazorInjectAttribute] public global::Microsoft.AspNetCore.Mvc.IUrlHelper Url { get; private set; } = default!; #nullable disable #nullable restore [global::Microsoft.AspNetCore.Mvc.Razor.Internal.RazorInjectAttribute] public global::Microsoft.AspNetCore.Mvc.IViewComponentHelper Component { get; private set; } = default!; #nullable disable #nullable restore [global::Microsoft.AspNetCore.Mvc.Razor.Internal.RazorInjectAttribute] public global::Microsoft.AspNetCore.Mvc.Rendering.IJsonHelper Json { get; private set; } = default!; #nullable disable #nullable restore [global::Microsoft.AspNetCore.Mvc.Razor.Internal.RazorInjectAttribute] public global::Microsoft.AspNetCore.Mvc.Rendering.IHtmlHelper<dynamic> Html { get; private set; } = default!; #nullable disable } } #pragma warning restore 1591
45.4875
201
0.730146
[ "MIT" ]
firatalcin/CSharp-.NetCore-Works
FullStackDotNetCore-Lessons/DbFirst/DbFirst/obj/Debug/net5.0/Razor/Views/Home/Privacy.cshtml.g.cs
3,639
C#
using System.IO; using System.Runtime.Serialization; using GameEstate.Red.Formats.Red.CR2W.Reflection; using FastMember; using static GameEstate.Red.Formats.Red.Records.Enums; namespace GameEstate.Red.Formats.Red.Types { [DataContract(Namespace = "")] [REDMeta] public class CAIArachasDEBUGLogic : CAIMonsterCombatLogic { public CAIArachasDEBUGLogic(CR2WFile cr2w, CVariable parent, string name) : base(cr2w, parent, name){ } public static new CVariable Create(CR2WFile cr2w, CVariable parent, string name) => new CAIArachasDEBUGLogic(cr2w, parent, name); public override void Read(BinaryReader file, uint size) => base.Read(file, size); public override void Write(BinaryWriter file) => base.Write(file); } }
32.565217
132
0.751669
[ "MIT" ]
bclnet/GameEstate
src/Estates/Red/GameEstate.Red.Format/Red/W3/RTTIConvert/CAIArachasDEBUGLogic.cs
749
C#
 using UnityEngine; [RequireComponent(typeof(BoxCollider2D))] public class logic_swipe : MonoBehaviour { // Settings public float minSwipeMovement; private Vector2 swipeStartPos = Vector2.zero; private BoxCollider2D _collison; private Camera _camera; private float tapCD; public void Awake() { this._camera = GameObject.Find("Camera").GetComponent<Camera>(); this._collison = GetComponent<BoxCollider2D>(); } // Update is called once per frame public void FixedUpdate() { // If there is no target, ignore if (Input.touches.Length <= 0) return; foreach (var touch in Input.touches) { TouchPhase phase = touch.phase; if (phase == TouchPhase.Began) { swipeStartPos = touch.position; tapCD = Time.time; } else if (phase == TouchPhase.Moved) { // Calculate the distance float Xdiff = touch.position.x - swipeStartPos.x; swipeStartPos = touch.position; Vector2 diff = new Vector2(Xdiff, 0); if (diff.magnitude < minSwipeMovement) return; Vector3 wp = this._camera.ScreenToWorldPoint(touch.position); if (!_collison.OverlapPoint(wp)) return; // We only care about the up and down swipe if (diff.y != 0) { gameObject.SendMessage("OnSwipeY", diff.y, SendMessageOptions.DontRequireReceiver); } if (diff.x != 0) { gameObject.SendMessage("OnSwipeX", diff.x, SendMessageOptions.DontRequireReceiver); } } } } }
29.580645
103
0.537077
[ "Apache-2.0" ]
edunad/tempus
Assets/Scripts/Entities/logic_swipe.cs
1,836
C#
using System; using Avalonia.Controls; using Avalonia.Controls.Primitives; using Avalonia.Controls.Shapes; using Avalonia.Styling; using DataBox.Primitives; namespace DataBox; public class DataBoxRow : ListBoxItem, IStyleable { private Rectangle? _bottomGridLine; Type IStyleable.StyleKey => typeof(DataBoxRow); internal DataBox? DataBox { get; set; } internal DataBoxCellsPresenter? CellsPresenter { get; set; } protected override void OnApplyTemplate(TemplateAppliedEventArgs e) { base.OnApplyTemplate(e); _bottomGridLine = e.NameScope.Find<Rectangle>("PART_BottomGridLine"); InvalidateBottomGridLine(); CellsPresenter = e.NameScope.Find<DataBoxCellsPresenter>("PART_CellsPresenter"); if (CellsPresenter is { }) { CellsPresenter.DataBox = DataBox; CellsPresenter.Attach(); } } private void InvalidateBottomGridLine() { if (_bottomGridLine is { } && DataBox is { }) { bool newVisibility = DataBox.GridLinesVisibility == DataBoxGridLinesVisibility.Horizontal || DataBox.GridLinesVisibility == DataBoxGridLinesVisibility.All; if (newVisibility != _bottomGridLine.IsVisible) { _bottomGridLine.IsVisible = newVisibility; } _bottomGridLine.Fill = DataBox.HorizontalGridLinesBrush; } } }
27.185185
88
0.650545
[ "MIT" ]
wieslawsoltes/CellPanelDemo
src/DataBox/DataBoxRow.cs
1,468
C#
using System; using System.Collections.Generic; using static DR.Networking.Configuration; namespace DR.Networking.Core.Extensions { internal static class List { /// <summary> /// Find an uri in the SiteSpecific list. /// </summary> /// <param name="list">List containing the sites you want to ratelimit</param> /// <param name="target">The uri you want to find from the list</param> /// <returns> /// <description>(bool, SiteSpecific)</description> /// <list type="number"> /// <item> /// <description>Bool. Indicates if an item that has the target Uri was found in the list</description> /// </item> /// <item> /// <description>SiteSpecific. If item that contains target Uri is found return it</description> /// </item> /// </list> /// </returns> internal static (bool, SiteSpecific) FindUri(this List<SiteSpecific> list, Uri target) { SiteSpecific findPage = list.Find(e => e._uri == target); if (findPage == null) { SiteSpecific findDomain = list.Find(r => r._uri.AbsoluteUri == target.AbsoluteUri); if (findDomain == null) { return (false, null); } else { return (true, findDomain); } } else { return (true, findPage); } } } }
32.270833
117
0.511298
[ "Apache-2.0" ]
DatReki/DR.Networking
DR.Networking/Core/Extensions/List.cs
1,551
C#
/* * Copyright 2010-2014 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ /* * Do not modify this file. This file is generated from the appsync-2017-07-25.normal.json service model. */ using System; using Amazon.Runtime; using Amazon.Util.Internal; namespace Amazon.AppSync { /// <summary> /// Configuration for accessing Amazon AppSync service /// </summary> public partial class AmazonAppSyncConfig : ClientConfig { private static readonly string UserAgentString = InternalSDKUtils.BuildUserAgentString("3.3.103.6"); private string _userAgent = UserAgentString; /// <summary> /// Default constructor /// </summary> public AmazonAppSyncConfig() { this.AuthenticationServiceName = "appsync"; } /// <summary> /// The constant used to lookup in the region hash the endpoint. /// </summary> public override string RegionEndpointServiceName { get { return "appsync"; } } /// <summary> /// Gets the ServiceVersion property. /// </summary> public override string ServiceVersion { get { return "2017-07-25"; } } /// <summary> /// Gets the value of UserAgent property. /// </summary> public override string UserAgent { get { return _userAgent; } } } }
26.025
105
0.585495
[ "Apache-2.0" ]
damianh/aws-sdk-net
sdk/src/Services/AppSync/Generated/AmazonAppSyncConfig.cs
2,082
C#
#if !NETSTANDARD13 /* * 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 rekognition-2016-06-27.normal.json service model. */ using Amazon.Runtime; namespace Amazon.Rekognition.Model { /// <summary> /// Paginator for the ListCollections operation ///</summary> public interface IListCollectionsPaginator { /// <summary> /// Enumerable containing all full responses for the operation /// </summary> IPaginatedEnumerable<ListCollectionsResponse> Responses { get; } /// <summary> /// Enumerable containing all of the CollectionIds /// </summary> IPaginatedEnumerable<string> CollectionIds { get; } } } #endif
33.075
110
0.66969
[ "Apache-2.0" ]
philasmar/aws-sdk-net
sdk/src/Services/Rekognition/Generated/Model/_bcl45+netstandard/IListCollectionsPaginator.cs
1,323
C#
// *************************************************************************** // This is free and unencumbered software released into the public domain. // // Anyone is free to copy, modify, publish, use, compile, sell, or // distribute this software, either in source code form or as a compiled // binary, for any purpose, commercial or non-commercial, and by any // means. // // In jurisdictions that recognize copyright laws, the author or authors // of this software dedicate any and all copyright interest in the // software to the public domain. We make this dedication for the benefit // of the public at large and to the detriment of our heirs and // successors. We intend this dedication to be an overt act of // relinquishment in perpetuity of all present and future rights to this // software under copyright law. // // 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 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. // // For more information, please refer to <http://unlicense.org> // *************************************************************************** using NexusClient.Converters; using NexusClient.HandlerGroups; namespace NexusClient.Nexus.Apis { public class HandlerTargetApi<TCnv, TSer, TDes, TDto> : TargetApi<TCnv, TSer, TDes, TDto> where TCnv : IConverter<TDto> where TSer : IMessageSer<TDto> where TDes : IMessageDes<TDto> where TDto : IMessageDto { protected HandlerGroup<TCnv, TSer, TDes, TDto> HandlerGroup { get; set; } internal HandlerTargetApi(Nexus<TCnv, TSer, TDes, TDto> nexus, HandlerGroup<TCnv, TSer, TDes, TDto> handlerGroup) : base(nexus) { HandlerGroup = handlerGroup; } public MessageApi<TCnv, TSer, TDes, TDto> ToAll() { return To(HandlerGroup.Participants); } public MessageApi<TCnv, TSer, TDes, TDto> ToAllExcept(params string[] userIds) { return ToAllExcept(HandlerGroup.Participants, userIds); } public MessageApi<TCnv, TSer, TDes, TDto> ToOthers() { return ToOthers(HandlerGroup.Participants); } public MessageApi<TCnv, TSer, TDes, TDto> ToOthersExcept(params string[] userIds) { return ToOthersExcept(HandlerGroup.Participants, userIds); } } }
37.776119
90
0.697748
[ "Unlicense" ]
UnterrainerInformatik/Nexus
NexusClient/NexusClient/Nexus/Apis/HanderTargetApi.cs
2,533
C#
using System; using System.Collections.Generic; using System.IO; using System.Runtime.Serialization; using System.ServiceModel.Channels; using System.Xml; using System.Xml.Serialization; namespace SoapCore { public class ServiceBodyWriter : BodyWriter { private readonly SoapSerializer _serializer; private readonly string _serviceNamespace; private readonly string _envelopeName; private readonly string _resultName; private readonly object _result; private readonly Dictionary<string, object> _outResults; public ServiceBodyWriter(SoapSerializer serializer, string serviceNamespace, string envelopeName, string resultName, object result, Dictionary<string, object> outResults) : base(isBuffered: true) { _serializer = serializer; _serviceNamespace = serviceNamespace; _envelopeName = envelopeName; _resultName = resultName; _result = result; _outResults = outResults; } protected override void OnWriteBodyContents(XmlDictionaryWriter writer) { writer.WriteStartElement(_envelopeName, _serviceNamespace); if (_outResults != null) { foreach (var outResult in _outResults) { string value; if (outResult.Value is Guid) value = outResult.Value.ToString(); else if (outResult.Value is bool) value = outResult.Value.ToString().ToLower(); else if (outResult.Value is string) value = SecurityElement.Escape(outResult.Value.ToString()); else if (outResult.Value is Enum) value = outResult.Value.ToString(); else if (outResult.Value == null) value = null; else //for complex types { using (var ms = new MemoryStream()) using (var stream = new BufferedStream(ms)) { new XmlSerializer(outResult.Value.GetType(), _serviceNamespace).Serialize(ms, outResult.Value); stream.Position = 0; using (var reader = XmlReader.Create(stream)) { reader.MoveToContent(); value = reader.ReadInnerXml(); } } } if (value != null) writer.WriteRaw(string.Format("<{0}>{1}</{0}>", outResult.Key, value)); } } if (_result != null) { switch (_serializer) { case SoapSerializer.XmlSerializer: { // see https://referencesource.microsoft.com/System.Xml/System/Xml/Serialization/XmlSerializer.cs.html#c97688a6c07294d5 var serializer = new XmlSerializer(_result.GetType(), null, new Type[0], new XmlRootAttribute(_resultName), _serviceNamespace); serializer.Serialize(writer, _result); } break; case SoapSerializer.DataContractSerializer: { var serializer = new DataContractSerializer(_result.GetType(), _resultName, _serviceNamespace); serializer.WriteObject(writer, _result); } break; default: throw new NotImplementedException(); } } writer.WriteEndElement(); } } }
30.617021
197
0.695969
[ "MIT" ]
gktech/SoapCore
src/SoapCore/ServiceBodyWriter.cs
2,880
C#
/* * Copyright 2010-2014 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ /* * Do not modify this file. This file is generated from the sagemaker-2017-07-24.normal.json service model. */ using System; using System.Collections.Generic; using System.Xml.Serialization; using System.Text; using System.IO; using Amazon.Runtime; using Amazon.Runtime.Internal; namespace Amazon.SageMaker.Model { /// <summary> /// Specifies weight and capacity values for a production variant. /// </summary> public partial class DesiredWeightAndCapacity { private int? _desiredInstanceCount; private float? _desiredWeight; private string _variantName; /// <summary> /// Gets and sets the property DesiredInstanceCount. /// <para> /// The variant's capacity. /// </para> /// </summary> [AWSProperty(Min=1)] public int DesiredInstanceCount { get { return this._desiredInstanceCount.GetValueOrDefault(); } set { this._desiredInstanceCount = value; } } // Check to see if DesiredInstanceCount property is set internal bool IsSetDesiredInstanceCount() { return this._desiredInstanceCount.HasValue; } /// <summary> /// Gets and sets the property DesiredWeight. /// <para> /// The variant's weight. /// </para> /// </summary> [AWSProperty(Min=0)] public float DesiredWeight { get { return this._desiredWeight.GetValueOrDefault(); } set { this._desiredWeight = value; } } // Check to see if DesiredWeight property is set internal bool IsSetDesiredWeight() { return this._desiredWeight.HasValue; } /// <summary> /// Gets and sets the property VariantName. /// <para> /// The name of the variant to update. /// </para> /// </summary> [AWSProperty(Required=true, Max=63)] public string VariantName { get { return this._variantName; } set { this._variantName = value; } } // Check to see if VariantName property is set internal bool IsSetVariantName() { return this._variantName != null; } } }
29.721649
107
0.610128
[ "Apache-2.0" ]
FoxBearBear/aws-sdk-net
sdk/src/Services/SageMaker/Generated/Model/DesiredWeightAndCapacity.cs
2,883
C#
#if REACTIVE_VARIABLE_RX_ENABLED using UniRx; #endif using System; using UnityEngine.Assertions; // ReSharper disable once CheckNamespace namespace STRV.Variables { /// Generic base variable reference that all other variable references inherit /// Can (should) only be used for getting values, not setting them public abstract class Reference<T> : IObservable<T> { public bool UseConstant = true; public T ConstantValue; public virtual Variable<T> Variable { get { return null; } } public Reference() { } public Reference(T value): this() { UseConstant = true; ConstantValue = value; } #if REACTIVE_VARIABLE_RX_ENABLED public IObservable<T> AsObservable() { Assert.IsTrue(UseConstant || Variable != null, "Using variable value with no variable assigned"); return UseConstant ? Observable.Return(ConstantValue) : Variable.AsObservable(); } #else public Action<T> OnValueChanged { get { if (UseConstant) { return new Action<T>(_ => { }); } else { return Variable.OnValueChanged; } } set { if (!UseConstant) { Variable.OnValueChanged = value; } } } #endif public T Value { get { return UseConstant ? ConstantValue : Variable.CurrentValue;; } } public static implicit operator T(Reference<T> reference) { return reference.Value; } public IDisposable Subscribe(IObserver<T> observer) { return AsObservable().Subscribe(observer); } } }
25.728395
109
0.485125
[ "MIT" ]
strvcom/rxscriptablevariables-unity
Source/Variables/Reference.cs
2,086
C#
using NUnit.Framework; using Swagger.Net.Dummy.Controllers; using System.Linq; namespace Swagger.Net.Tests.Swagger { [TestFixture] public class SchemaTestsWithCustomAuthorizeAttribute : SwaggerTestBase { public SchemaTestsWithCustomAuthorizeAttribute() : base("swagger/docs/{apiVersion}") {} [Test] public void It_adds_security_to_protected_operations() { SetUpDefaultRouteFor<ProtectedResourcesController>(); SetUpDefaultRouteFor<ProtectedWithCustomAttributeResourcesController>(); SetUpHandler(c => { c.ApiKey("apiKey", "header", "API Key Authentication"); }); var swagger = GetContent<SwaggerDocument>(TEMP_URI.DOCS); var paths = swagger.paths.ToArray(); Assert.IsNotNull(paths[0].Value.get.security); Assert.IsNotNull(paths[1].Value.get.security); } } }
29.53125
95
0.646561
[ "BSD-3-Clause" ]
SiCoe/Swagger-Net
Tests/Swagger.Net.Tests/Swagger/SchemaTestsWithCustomAuthorizeAttribute.cs
947
C#