content
stringlengths
5
1.04M
avg_line_length
float64
1.75
12.9k
max_line_length
int64
2
244k
alphanum_fraction
float64
0
0.98
licenses
list
repository_name
stringlengths
7
92
path
stringlengths
3
249
size
int64
5
1.04M
lang
stringclasses
2 values
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Identity; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.RazorPages; using Microsoft.Extensions.Logging; namespace SGFR_Web.Areas.Identity.Pages.Account.Manage { public class ResetAuthenticatorModel : PageModel { UserManager<IdentityUser> _userManager; private readonly SignInManager<IdentityUser> _signInManager; ILogger<ResetAuthenticatorModel> _logger; public ResetAuthenticatorModel( UserManager<IdentityUser> userManager, SignInManager<IdentityUser> signInManager, ILogger<ResetAuthenticatorModel> logger) { _userManager = userManager; _signInManager = signInManager; _logger = logger; } [TempData] public string StatusMessage { get; set; } public async Task<IActionResult> OnGet() { var user = await _userManager.GetUserAsync(User); if (user == null) { return NotFound($"Unable to load user with ID '{_userManager.GetUserId(User)}'."); } return Page(); } public async Task<IActionResult> OnPostAsync() { var user = await _userManager.GetUserAsync(User); if (user == null) { return NotFound($"Unable to load user with ID '{_userManager.GetUserId(User)}'."); } await _userManager.SetTwoFactorEnabledAsync(user, false); await _userManager.ResetAuthenticatorKeyAsync(user); _logger.LogInformation("User with ID '{UserId}' has reset their authentication app key.", user.Id); await _signInManager.RefreshSignInAsync(user); StatusMessage = "Your authenticator app key has been reset, you will need to configure your authenticator app using the new key."; return RedirectToPage("./EnableAuthenticator"); } } }
34.416667
142
0.641162
[ "MIT" ]
PauloGaldino/SGFR_Identity
src/SGFR_Web/Areas/Identity/Pages/Account/Manage/ResetAuthenticator.cshtml.cs
2,067
C#
using System; using System.Net; using System.Runtime.Serialization; using Bytewizer.Backblaze.Models; namespace Bytewizer.Backblaze { /// <summary> /// The exception thrown when an error occurs during client operations. /// </summary> [Serializable] public class ApiException : Exception { /// <summary> /// Get the http response status code. /// </summary> public HttpStatusCode StatusCode { get; private set; } /// <summary> /// Get error information related to request failures. /// </summary> public ErrorResponse Error { get; private set; } /// <summary> /// Initializes a new instance of the <see cref="ApiException"/> class. /// </summary> public ApiException() {} /// <summary> /// Initializes a new instance of the <see cref="ApiException"/> class /// with a specified error message. /// </summary> /// <param name="message">The error message that explains the reason for the exception.</param> public ApiException(string message) : base(message) {} /// <summary> /// Initializes a new instance of the <see cref="ApiException"/> class /// with a specified error message and a reference to the inner exception that is the cause of this exception. /// </summary> /// <param name="message">The error message that explains the reason for the exception.</param> /// <param name="innerException">The exception that is the cause of the current exception. If the <paramref name="innerException" /> parameter /// is not a null reference, the current exception is raised in a catch block that handles the inner exception. </param> public ApiException(string message, Exception innerException) : base(message, innerException) {} /// <summary> /// Initializes a new instance of the <see cref="ApiException"/> class /// with a specified http status code. /// </summary> /// <param name="statusCode">The http status code.</param> public ApiException(HttpStatusCode statusCode) : base($"Backblaze B2 Cloud Storage responded with the following: httpcode={statusCode.ToString().ToLower()}") { StatusCode = statusCode; } /// <summary> /// Initializes a new instance of the <see cref="ApiException"/> class /// with a specified http status code and error message. /// </summary> /// <param name="statusCode">The http status code.</param> /// <param name="message">The error message that explains the reason for the exception.</param> public ApiException(HttpStatusCode statusCode, string message) : base($"Backblaze API server responded with the following: httpcode={statusCode.ToString().ToLower()}, message:{message}") { StatusCode = statusCode; } /// <summary> /// Initializes a new instance of the <see cref="ApiException"/> class /// with a specified http status code and error message. /// </summary> /// <param name="statusCode">The http status code.</param> /// <param name="error">The server error that explains the reason for the exception.</param> public ApiException(HttpStatusCode statusCode, ErrorResponse error) : base($"Backblaze API server responded with the following error: httpcode={statusCode.ToString().ToLower()}, status={error.Status.ToLower()}, code={error.Code.ToLower()}, message={error.Message.ToLower()}") { StatusCode = statusCode; Error = error; } /// <summary> /// Initializes a new instance of the <see cref="ApiException"/> class /// with serialized data. /// </summary> /// <param name="info">The object that holds the serialized object data. </param> /// <param name="context">The contextual information about the source or destination. </param> protected ApiException(SerializationInfo info, StreamingContext context) : base(info, context) {} } }
43.244898
219
0.62152
[ "MIT" ]
microcompiler/backblaze
src/Client/Exceptions/ApiException.cs
4,240
C#
using BusinessLayer.Concrete; using DataAccessLayer.EntityFremawork; using Microsoft.AspNetCore.Mvc; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace HealthProject.ViewComponents.Blog { public class BlogLast3Post: ViewComponent { BlogManeger bm = new BlogManeger(new EfBlogDal()); public IViewComponentResult Invoke() { var values = bm.GetListBlogLast3(); return View(values); } } }
24.333333
58
0.702544
[ "Apache-2.0" ]
OzkanBahrianil/HealthProject
ViewComponents/Blog/BlogLast3Post.cs
513
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/OAIdl.h in the Windows SDK for Windows 10.0.19041.0 // Original source is Copyright © Microsoft. All rights reserved. using System.Runtime.InteropServices; namespace TerraFX.Interop { public partial struct SAFEARRAYUNION { [NativeTypeName("ULONG")] public uint sfType; [NativeTypeName("union __MIDL_IOleAutomationTypes_0001")] public _u_e__Union u; [StructLayout(LayoutKind.Explicit)] public partial struct _u_e__Union { [FieldOffset(0)] public SAFEARR_BSTR BstrStr; [FieldOffset(0)] public SAFEARR_UNKNOWN UnknownStr; [FieldOffset(0)] public SAFEARR_DISPATCH DispatchStr; [FieldOffset(0)] public SAFEARR_VARIANT VariantStr; [FieldOffset(0)] public SAFEARR_BRECORD RecordStr; [FieldOffset(0)] public SAFEARR_HAVEIID HaveIidStr; [FieldOffset(0)] public BYTE_SIZEDARR ByteStr; [FieldOffset(0)] public WORD_SIZEDARR WordStr; [FieldOffset(0)] public DWORD_SIZEDARR LongStr; [FieldOffset(0)] public HYPER_SIZEDARR HyperStr; } } }
26.773585
145
0.618746
[ "MIT" ]
Ethereal77/terrafx.interop.windows
sources/Interop/Windows/um/OAIdl/SAFEARRAYUNION.cs
1,421
C#
namespace Firebend.AutoCrud.Io.Interfaces { public interface IEntityExportMapper<in TEntity, out TOut> where TEntity: class where TOut: class { TOut Map(TEntity entity); } public abstract class DefaultEntityExportMapper<T> : IEntityExportMapper<T, T> where T : class { public T Map(T entity) { return entity; } } }
23.470588
98
0.611529
[ "MIT" ]
d2eason/auto-crud
Firebend.AutoCrud/Firebend.AutoCrud.Io/Interfaces/IEntityExportMapper.cs
399
C#
namespace UniModules.UniGameFlow.Nodes.Runtime.States { using System; using System.Diagnostics; using Cysharp.Threading.Tasks; using global::UniCore.Runtime.ProfilerTools; using global::UniModules.GameFlow.Runtime.Attributes; using global::UniModules.GameFlow.Runtime.Core; using global::UniModules.GameFlow.Runtime.Interfaces; using UniCore.Runtime.Attributes; using UniGame.Context.SerializableContext.Runtime.Abstract; using UniGame.Context.SerializableContext.Runtime.States; using UniGame.Core.Runtime.DataFlow.Interfaces; using UniGame.Core.Runtime.Interfaces; using UniModules.UniCore.Runtime.Rx.Extensions; using UniRx; using UnityEngine; [HideNode] [Serializable] public abstract class AsyncStateUniNode : UniNode, IAsyncContextState, IAsyncStateCommand<IContext, AsyncStatus>, IAsyncCompletion<AsyncStatus, IContext>, IAsyncEndPoint<IContext>, IAsyncRollback<IContext>, IStateCancellation { #region inspector [ReadOnlyValue] [SerializeField] protected bool _isStateActive; #endregion [Port] public object input; #region public properties #endregion #region private fields private AsyncContextStateProxy _asyncStateProxy; private IStateToken _token; private IPortValue _inputPort; #endregion public bool IsStateActive => _isStateActive; public IStateToken Token => _token; #region public methods public async UniTask<AsyncStatus> ExecuteAsync(IContext value) => await _asyncStateProxy.ExecuteAsync(value); public async UniTask ExitAsync() { _isStateActive = false; _token = null; await _asyncStateProxy.ExitAsync(); } public void StopState() => ExitAsync(); #region custom execution handlers public virtual UniTask<AsyncStatus> ExecuteStateAsync(IContext value) => UniTask.FromResult(AsyncStatus.Succeeded); public virtual UniTask CompleteAsync(AsyncStatus value, IContext data, ILifeTime lifeTime) => UniTask.FromResult(UniTask.CompletedTask); public virtual UniTask ExitAsync(IContext data) => UniTask.FromResult(UniTask.CompletedTask); public virtual UniTask Rollback(IContext source) => UniTask.FromResult(UniTask.CompletedTask); #endregion #endregion protected void PublishToken(INodePort port) { if (!_isStateActive || _token == null) { GameLog.LogWarning($"{ItemName} Try to Publish Token in inactive state"); return; } port.Value.Publish(_token); } protected sealed override UniTask OnExecute() { if (!Application.isPlaying) return UniTask.CompletedTask; _isStateActive = false; _asyncStateProxy = new AsyncContextStateProxy(this, this, this, this); _inputPort = GetPortValue(nameof(input)); LifeTime.AddCleanUpAction(() => _asyncStateProxy.ExitAsync()); LogNodeExecutionState(); //get all actual stat tokens and try to run state _inputPort.Receive<IStateToken>(). Where(x => _isStateActive == false). Select(async x => await OwnToken(x)). Subscribe(). AddTo(LifeTime); return UniTask.CompletedTask; } [Conditional("UNITY_EDITOR")] private void LogNodeExecutionState() { _asyncStateProxy.Value .Do(x => GameLog.Log($"STATE NODE {ItemName} ID {Id} STATUS : {x}")) .Subscribe() .AddTo(LifeTime); } private async UniTask OwnToken(IStateToken token) { var result = token.TakeOwnership(this); _token = result ? token : null; _isStateActive = result; if (_token == null) return; await ExecuteAsync(_token.Context); } } }
30.55
144
0.610007
[ "MIT" ]
UniGameTeam/UniGame.GameFlow
Runtime/Nodes/States/AsyncStateUniNode.cs
4,279
C#
namespace CS203_CALLBACK_API_DEMO { partial class TagKillForm { /// <summary> /// Required designer variable. /// </summary> private System.ComponentModel.IContainer components = null; /// <summary> /// Clean up any resources being used. /// </summary> /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param> protected override void Dispose(bool disposing) { if (disposing && (components != null)) { components.Dispose(); } base.Dispose(disposing); } #region Windows Form Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { this.panel1 = new System.Windows.Forms.Panel(); this.linkLabel1 = new System.Windows.Forms.LinkLabel(); this.label1 = new System.Windows.Forms.Label(); this.lk_epc = new System.Windows.Forms.LinkLabel(); this.label3 = new System.Windows.Forms.Label(); this.btn_kill = new System.Windows.Forms.Button(); this.btn_exit = new System.Windows.Forms.Button(); this.resultForm1 = new CS203_CALLBACK_API_DEMO.ResultForm(); this.tb_kill_password = new Custom.Control.HexOnlyTextbox(); this.label4 = new System.Windows.Forms.Label(); this.cb_extCmd = new System.Windows.Forms.ComboBox(); this.panel1.SuspendLayout(); this.SuspendLayout(); // // panel1 // this.panel1.BackColor = System.Drawing.Color.Red; this.panel1.Controls.Add(this.linkLabel1); this.panel1.Controls.Add(this.label1); this.panel1.Location = new System.Drawing.Point(3, 34); this.panel1.Name = "panel1"; this.panel1.Size = new System.Drawing.Size(314, 65); this.panel1.TabIndex = 13; // // linkLabel1 // this.linkLabel1.Font = new System.Drawing.Font("Tahoma", 10F, ((System.Drawing.FontStyle)((System.Drawing.FontStyle.Bold | System.Drawing.FontStyle.Underline)))); this.linkLabel1.ForeColor = System.Drawing.Color.White; this.linkLabel1.Location = new System.Drawing.Point(7, 33); this.linkLabel1.Name = "linkLabel1"; this.linkLabel1.Size = new System.Drawing.Size(304, 20); this.linkLabel1.TabIndex = 1; this.linkLabel1.TabStop = true; this.linkLabel1.Text = "Tag will be destoryed permanently. "; this.linkLabel1.TextAlign = System.Drawing.ContentAlignment.TopCenter; // // label1 // this.label1.Font = new System.Drawing.Font("Tahoma", 16F, System.Drawing.FontStyle.Bold); this.label1.ForeColor = System.Drawing.Color.White; this.label1.Location = new System.Drawing.Point(0, 0); this.label1.Name = "label1"; this.label1.Size = new System.Drawing.Size(311, 33); this.label1.TabIndex = 2; this.label1.Text = "Warning :"; // // lk_epc // this.lk_epc.Font = new System.Drawing.Font("Tahoma", 12F, System.Drawing.FontStyle.Underline); this.lk_epc.Location = new System.Drawing.Point(10, 11); this.lk_epc.Name = "lk_epc"; this.lk_epc.Size = new System.Drawing.Size(304, 20); this.lk_epc.TabIndex = 1; this.lk_epc.TabStop = true; this.lk_epc.Text = "Click here to select a tag to destroy."; this.lk_epc.TextAlign = System.Drawing.ContentAlignment.TopCenter; this.lk_epc.LinkClicked += new System.Windows.Forms.LinkLabelLinkClickedEventHandler(this.lk_epc_LinkClicked); this.lk_epc.Click += new System.EventHandler(this.lk_epc_Click); // // label3 // this.label3.Location = new System.Drawing.Point(10, 150); this.label3.Name = "label3"; this.label3.Size = new System.Drawing.Size(129, 20); this.label3.TabIndex = 11; this.label3.Text = "Kill password :"; this.label3.TextAlign = System.Drawing.ContentAlignment.TopRight; // // btn_kill // this.btn_kill.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(0)))), ((int)(((byte)(192)))), ((int)(((byte)(0))))); this.btn_kill.Font = new System.Drawing.Font("Tahoma", 16F); this.btn_kill.Location = new System.Drawing.Point(10, 198); this.btn_kill.Name = "btn_kill"; this.btn_kill.Size = new System.Drawing.Size(107, 39); this.btn_kill.TabIndex = 5; this.btn_kill.Text = "Kill Tag"; this.btn_kill.UseVisualStyleBackColor = false; this.btn_kill.Click += new System.EventHandler(this.btn_kill_Click); // // btn_exit // this.btn_exit.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(255)))), ((int)(((byte)(192)))), ((int)(((byte)(192))))); this.btn_exit.Location = new System.Drawing.Point(245, 207); this.btn_exit.Name = "btn_exit"; this.btn_exit.Size = new System.Drawing.Size(72, 20); this.btn_exit.TabIndex = 6; this.btn_exit.Text = "Exit"; this.btn_exit.UseVisualStyleBackColor = false; this.btn_exit.Click += new System.EventHandler(this.btn_exit_Click); // // resultForm1 // this.resultForm1.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(192)))), ((int)(((byte)(255)))), ((int)(((byte)(192))))); this.resultForm1.Location = new System.Drawing.Point(82, 70); this.resultForm1.Name = "resultForm1"; this.resultForm1.Size = new System.Drawing.Size(150, 66); this.resultForm1.TabIndex = 10; this.resultForm1.Visible = false; // // tb_kill_password // this.tb_kill_password.BackColor = System.Drawing.Color.LightPink; this.tb_kill_password.BackgroundText = null; this.tb_kill_password.FontColor = System.Drawing.Color.Black; this.tb_kill_password.ForeColor = System.Drawing.Color.Black; this.tb_kill_password.Location = new System.Drawing.Point(145, 150); this.tb_kill_password.MaxLength = 8; this.tb_kill_password.Name = "tb_kill_password"; this.tb_kill_password.PaddingZero = true; this.tb_kill_password.Size = new System.Drawing.Size(100, 22); this.tb_kill_password.TabIndex = 4; this.tb_kill_password.Text = "00000000"; // // label4 // this.label4.Location = new System.Drawing.Point(56, 179); this.label4.Name = "label4"; this.label4.Size = new System.Drawing.Size(83, 23); this.label4.TabIndex = 14; this.label4.Text = "ExtCommand"; this.label4.TextAlign = System.Drawing.ContentAlignment.MiddleRight; // // cb_extCmd // this.cb_extCmd.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList; this.cb_extCmd.FormattingEnabled = true; this.cb_extCmd.Items.AddRange(new object[] { "Tag Kill", "Disable Permalock", "Disable User Memory", "Unlock all banks"}); this.cb_extCmd.Location = new System.Drawing.Point(145, 181); this.cb_extCmd.Name = "cb_extCmd"; this.cb_extCmd.Size = new System.Drawing.Size(100, 20); this.cb_extCmd.TabIndex = 15; // // TagKillForm // this.AutoScaleDimensions = new System.Drawing.SizeF(96F, 96F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Dpi; this.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(192)))), ((int)(((byte)(255)))), ((int)(((byte)(192))))); this.ClientSize = new System.Drawing.Size(320, 240); this.ControlBox = false; this.Controls.Add(this.btn_kill); this.Controls.Add(this.cb_extCmd); this.Controls.Add(this.resultForm1); this.Controls.Add(this.label4); this.Controls.Add(this.btn_exit); this.Controls.Add(this.tb_kill_password); this.Controls.Add(this.label3); this.Controls.Add(this.lk_epc); this.Controls.Add(this.panel1); this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedSingle; this.Name = "TagKillForm"; this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen; this.Text = "TagKillForm"; this.Load += new System.EventHandler(this.TagKillForm_Load); this.Closing += new System.ComponentModel.CancelEventHandler(this.TagKillForm_Closing); this.panel1.ResumeLayout(false); this.ResumeLayout(false); this.PerformLayout(); } #endregion private System.Windows.Forms.Panel panel1; private System.Windows.Forms.LinkLabel linkLabel1; private System.Windows.Forms.Label label1; private System.Windows.Forms.LinkLabel lk_epc; private System.Windows.Forms.Label label3; private Custom.Control.HexOnlyTextbox tb_kill_password; private System.Windows.Forms.Button btn_kill; private System.Windows.Forms.Button btn_exit; private ResultForm resultForm1; private System.Windows.Forms.Label label4; private System.Windows.Forms.ComboBox cb_extCmd; } }
47.848341
174
0.58746
[ "MIT" ]
cslrfid/CSL-Callback-Unified-SDK-App
CSL RFID Demo Apps/Source/CS Native Demo XP/TagKillForm.designer.cs
10,096
C#
namespace qnote { partial class SignIn { /// <summary> /// Required designer variable. /// </summary> private System.ComponentModel.IContainer components = null; /// <summary> /// Clean up any resources being used. /// </summary> /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param> protected override void Dispose(bool disposing) { if (disposing && (components != null)) { components.Dispose(); } base.Dispose(disposing); } #region Windows Form Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { this.label9 = new System.Windows.Forms.Label(); this.label2 = new System.Windows.Forms.Label(); this.label1 = new System.Windows.Forms.Label(); this.textBox3 = new System.Windows.Forms.TextBox(); this.textBox2 = new System.Windows.Forms.TextBox(); this.label5 = new System.Windows.Forms.Label(); this.label4 = new System.Windows.Forms.Label(); this.button1 = new System.Windows.Forms.Button(); this.button2 = new System.Windows.Forms.Button(); this.SuspendLayout(); // // label9 // this.label9.BackColor = System.Drawing.SystemColors.Highlight; this.label9.Location = new System.Drawing.Point(13, 55); this.label9.Name = "label9"; this.label9.Size = new System.Drawing.Size(240, 1); this.label9.TabIndex = 22; // // label2 // this.label2.AutoSize = true; this.label2.Font = new System.Drawing.Font("Copperplate Gothic Light", 8.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.label2.Location = new System.Drawing.Point(14, 34); this.label2.Name = "label2"; this.label2.Size = new System.Drawing.Size(209, 12); this.label2.TabIndex = 21; this.label2.Text = "Want to sign in fill out this form!"; // // label1 // this.label1.AutoSize = true; this.label1.Font = new System.Drawing.Font("Copperplate Gothic Light", 15F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.label1.Location = new System.Drawing.Point(12, 9); this.label1.Name = "label1"; this.label1.Size = new System.Drawing.Size(82, 21); this.label1.TabIndex = 20; this.label1.Text = "Sign in"; this.label1.Click += new System.EventHandler(this.label1_Click); // // textBox3 // this.textBox3.Location = new System.Drawing.Point(16, 132); this.textBox3.Name = "textBox3"; this.textBox3.PasswordChar = '*'; this.textBox3.Size = new System.Drawing.Size(238, 20); this.textBox3.TabIndex = 29; this.textBox3.UseSystemPasswordChar = true; // // textBox2 // this.textBox2.Location = new System.Drawing.Point(16, 89); this.textBox2.Name = "textBox2"; this.textBox2.Size = new System.Drawing.Size(238, 20); this.textBox2.TabIndex = 30; // // label5 // this.label5.AutoSize = true; this.label5.Font = new System.Drawing.Font("Copperplate Gothic Light", 12F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.label5.Location = new System.Drawing.Point(13, 112); this.label5.Name = "label5"; this.label5.Size = new System.Drawing.Size(97, 17); this.label5.TabIndex = 25; this.label5.Text = "Password"; // // label4 // this.label4.AutoSize = true; this.label4.Font = new System.Drawing.Font("Copperplate Gothic Light", 12F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.label4.Location = new System.Drawing.Point(12, 69); this.label4.Name = "label4"; this.label4.Size = new System.Drawing.Size(94, 17); this.label4.TabIndex = 26; this.label4.Text = "Username"; // // button1 // this.button1.Font = new System.Drawing.Font("Copperplate Gothic Light", 8.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.button1.Location = new System.Drawing.Point(137, 158); this.button1.Name = "button1"; this.button1.Size = new System.Drawing.Size(116, 32); this.button1.TabIndex = 31; this.button1.Text = "OK"; this.button1.UseVisualStyleBackColor = true; this.button1.Click += new System.EventHandler(this.button1_Click); // // button2 // this.button2.Font = new System.Drawing.Font("Copperplate Gothic Light", 8.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.button2.Location = new System.Drawing.Point(16, 158); this.button2.Name = "button2"; this.button2.Size = new System.Drawing.Size(116, 32); this.button2.TabIndex = 31; this.button2.Text = "Sign up"; this.button2.UseVisualStyleBackColor = true; this.button2.Click += new System.EventHandler(this.button2_Click); // // SignIn // this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.ClientSize = new System.Drawing.Size(269, 199); this.Controls.Add(this.button2); this.Controls.Add(this.button1); this.Controls.Add(this.textBox3); this.Controls.Add(this.textBox2); this.Controls.Add(this.label5); this.Controls.Add(this.label4); this.Controls.Add(this.label9); this.Controls.Add(this.label2); this.Controls.Add(this.label1); this.Name = "SignIn"; this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen; this.Text = "SignIn"; this.ResumeLayout(false); this.PerformLayout(); } #endregion private System.Windows.Forms.Label label9; private System.Windows.Forms.Label label2; private System.Windows.Forms.Label label1; private System.Windows.Forms.TextBox textBox3; private System.Windows.Forms.TextBox textBox2; private System.Windows.Forms.Label label5; private System.Windows.Forms.Label label4; private System.Windows.Forms.Button button1; private System.Windows.Forms.Button button2; } }
45.128834
173
0.574225
[ "Apache-2.0" ]
maxcriser/CSharpLanguage
qnote/qnote/SignIn.Designer.cs
7,358
C#
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; namespace OneTimePassword.Mvc.Controllers { public class HomeController : Controller { public ActionResult Index() { return View(); } public ActionResult About() { ViewBag.Message = "Your application description page."; return View(); } public ActionResult Contact() { ViewBag.Message = "Your contact page."; return View(); } } }
20.5
68
0.541463
[ "MIT" ]
thiagosatoshi/OneTimePassword
OneTimePassword/OneTimePassword.Mvc/Controllers/HomeController.cs
617
C#
using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Http; using System.Threading.Tasks; using Microsoft.Extensions.DependencyInjection; using Microsoft.AspNetCore; namespace HelloWorldWithMiddleware { public class Startup { public void Configure(IApplicationBuilder app) { app.Map("/hello", (IApplicationBuilder pp) => { //nested app.Map("/world", (IApplicationBuilder ppa) => ppa.Run(context => context.Response.WriteAsync($"Path: {context.Request.Path} - Path Base: {context.Request.PathBase}"))); pp.Run(context => context.Response.WriteAsync($"Path: {context.Request.Path} - Path Base: {context.Request.PathBase}")); }); app.Run(context => { context.Response.Headers.Add("content-type", "text/html"); return context.Response.WriteAsync(@" <a href=""/hello"">/hello</a> <a href=""/hello/world"">/hello/world</a> "); }); } } public class Program { public static void Main(string[] args) { CreateWebHostBuilder(args).Build().Run(); } public static IWebHostBuilder CreateWebHostBuilder(string[] args) => WebHost.CreateDefaultBuilder(args) .UseStartup<Startup>() .UseEnvironment("Development"); } }
34.022222
123
0.564337
[ "MIT" ]
AdrienTorris/practical-aspnetcore
projects/middleware-5/src/Program.cs
1,531
C#
namespace StockSharp.Algo.Storages { using System; using System.Collections; using System.Collections.Generic; using System.Linq; using StockSharp.Messages; /// <summary> /// The market data storage, saving data in the cache-storage. /// </summary> /// <typeparam name="TData">Market data type.</typeparam> public class CacheableMarketDataStorage<TData> : IMarketDataStorage<TData> { private readonly IMarketDataStorage<TData> _cacheStorage; private readonly IMarketDataStorage<TData> _sourceStorage; /// <summary> /// Initializes a new instance of the <see cref="CacheableMarketDataStorage{TData}"/>. /// </summary> /// <param name="sourceStorage">The initial storage of market-data.</param> /// <param name="cacheStorage">The cache-storage of market-data.</param> public CacheableMarketDataStorage(IMarketDataStorage<TData> sourceStorage, IMarketDataStorage<TData> cacheStorage) { _sourceStorage = sourceStorage ?? throw new ArgumentNullException(nameof(sourceStorage)); _cacheStorage = cacheStorage ?? throw new ArgumentNullException(nameof(cacheStorage)); } IEnumerable<DateTime> IMarketDataStorage.Dates => _sourceStorage.Dates; Type IMarketDataStorage.DataType => _sourceStorage.DataType; SecurityId IMarketDataStorage.SecurityId => _sourceStorage.SecurityId; object IMarketDataStorage.Arg => _sourceStorage.Arg; IMarketDataStorageDrive IMarketDataStorage.Drive => _sourceStorage.Drive; bool IMarketDataStorage.AppendOnlyNew { get => _sourceStorage.AppendOnlyNew; set => _sourceStorage.AppendOnlyNew = value; } int IMarketDataStorage.Save(IEnumerable data) => ((IMarketDataStorage<TData>)this).Save(data); void IMarketDataStorage.Delete(IEnumerable data) => ((IMarketDataStorage<TData>)this).Delete(data); void IMarketDataStorage.Delete(DateTime date) => ((IMarketDataStorage<TData>)this).Delete(date); IEnumerable IMarketDataStorage.Load(DateTime date) => ((IMarketDataStorage<TData>)this).Load(date); IMarketDataSerializer IMarketDataStorage.Serializer => ((IMarketDataStorage<TData>)this).Serializer; IEnumerable<TData> IMarketDataStorage<TData>.Load(DateTime date) { if (_cacheStorage.Dates.Contains(date)) return _cacheStorage.Load(date); var data = _sourceStorage.Load(date); _cacheStorage.Save(data); return data; } IMarketDataSerializer<TData> IMarketDataStorage<TData>.Serializer => _sourceStorage.Serializer; int IMarketDataStorage<TData>.Save(IEnumerable<TData> data) { _cacheStorage.Save(data); return _sourceStorage.Save(data); } void IMarketDataStorage<TData>.Delete(IEnumerable<TData> data) { _cacheStorage.Delete(data); _sourceStorage.Delete(data); } IMarketDataMetaInfo IMarketDataStorage.GetMetaInfo(DateTime date) { if (_cacheStorage.Dates.Contains(date)) return _cacheStorage.GetMetaInfo(date); return _sourceStorage.GetMetaInfo(date); } } }
33.215909
116
0.765994
[ "Apache-2.0" ]
CB-Creates/StockSharp
Algo/Storages/CacheableMarketDataStorage.cs
2,923
C#
using System; public static class ResistorColorTrio { private const int KiloOhms = 1_000; private static readonly string[] AllColors = new[] { "black", "brown", "red", "orange", "yellow", "green", "blue", "violet", "grey", "white" }; public static string Label(string[] colors) => $"{(GetValue(colors) is int _value && _value >= KiloOhms ? _value / KiloOhms : _value)} " + GetUnit(_value); private static int GetValue(string[] colors) => ((ResistorValue(colors[0]) * 10) + ResistorValue(colors[1])) * (int)Math.Pow(10, ResistorValue(colors[2])); private static string GetUnit(int value) => (value >= KiloOhms ? "kilo" : "") + "ohms"; private static int ResistorValue(string color) => Array.IndexOf(AllColors, color); }
62
159
0.670699
[ "MIT" ]
18-F-cali/csharp
exercises/practice/resistor-color-trio/.meta/Example.cs
744
C#
using System.Xml; using Microsoft.Xna.Framework.Content.Pipeline; namespace TmxContentPipeline { [ContentImporter(".tmx", DisplayName = "TMX Importer", DefaultProcessor = "TmxProcessor")] public class TmxImporter : ContentImporter<XmlDocument> { public override XmlDocument Import(string filename, ContentImporterContext context) { XmlDocument doc = new XmlDocument(); doc.Load(filename); return doc; } } }
25.117647
91
0.758782
[ "MIT" ]
antonyoung/Breaker
src/TmxContentPipeline/src/TmxImporter.cs
427
C#
//----------------------------------------------------------------------- // <auto-generated /> //----------------------------------------------------------------------- using System; using System.Collections.Generic; using System.Text; using FlubuCore.Context; using FlubuCore.Tasks; using FlubuCore.Tasks.Process; namespace FlubuCore.Tasks.Docker.Manifest { public partial class DockerManifestAnnotateTask : ExternalProcessTaskBase<int, DockerManifestAnnotateTask> { private string _manifest_list; private string _manifest; public DockerManifestAnnotateTask(string manifest_list, string manifest) { ExecutablePath = "docker"; WithArguments("manifest annotate"); _manifest_list = manifest_list; _manifest = manifest; } protected override string Description { get; set; } /// <summary> /// Set architecture /// </summary> public DockerManifestAnnotateTask Arch(string arch) { WithArgumentsValueRequired("arch", arch.ToString()); return this; } /// <summary> /// Set operating system /// </summary> public DockerManifestAnnotateTask Os(string os) { WithArgumentsValueRequired("os", os.ToString()); return this; } /// <summary> /// Set operating system feature /// </summary> public DockerManifestAnnotateTask OsFeatures(string osFeatures) { WithArgumentsValueRequired("os-features", osFeatures.ToString()); return this; } /// <summary> /// Set architecture variant /// </summary> public DockerManifestAnnotateTask Variant(string variant) { WithArgumentsValueRequired("variant", variant.ToString()); return this; } protected override int DoExecute(ITaskContextInternal context) { WithArguments(_manifest_list); WithArguments(_manifest); return base.DoExecute(context); } } }
27.881579
111
0.566777
[ "BSD-2-Clause" ]
0xflotus/FlubuCore
FlubuCore/Tasks/Docker/Manifest/DockerManifestAnnotateTask.cs
2,119
C#
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("Per-Pixel Lighting")] [assembly: AssemblyProduct("Per-Pixel Lighting")] [assembly: AssemblyDescription("This sample shows how to apply specular lighting and calculate lighting per-pixel.")] [assembly: AssemblyCompany("Microsoft Corporation")] [assembly: AssemblyCopyright("Copyright © Microsoft 2008")] [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("D8FF1BC1-AA98-4dce-BB0A-CD9C6C70FD77")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // [assembly: AssemblyVersion("1.0.0.0")]
38.787879
117
0.760938
[ "MIT" ]
SimonDarksideJ/XNAGameStudio
Samples/PerPixelLightingSample_4_0/PerPixelLighting/Properties/AssemblyInfo.cs
1,283
C#
using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Options; using Minio.Exceptions; using Newtonsoft.Json; using Orleans.Runtime; using Orleans.Serialization; using Orleans.Storage; using System; using System.IO; using System.Text; using System.Threading; using System.Threading.Tasks; namespace Orleans.Persistence.Minio.Storage { public partial class MinioGrainStorage : IGrainStorage, ILifecycleParticipant<ISiloLifecycle> { private readonly string _name; private readonly string _container; private readonly ILogger<MinioGrainStorage> _logger; private readonly IMinioStorage _storage; private readonly IGrainFactory _grainFactory; private readonly ITypeResolver _typeResolver; private JsonSerializerSettings _jsonSettings; public MinioGrainStorage(string name, string container, IMinioStorage storage, ILogger<MinioGrainStorage> logger, IGrainFactory grainFactory, ITypeResolver typeResolver) { _name = name; _container = container; _logger = logger; _storage = storage; _grainFactory = grainFactory; _typeResolver = typeResolver; } public async Task ClearStateAsync(string grainType, GrainReference grainReference, IGrainState grainState) { string blobName = GetBlobNameString(grainType, grainReference); try { _logger.LogTrace("Clearing: GrainType={0} Grainid={1} ETag={2} to BlobName={3} in Container={4}", grainType, grainReference, grainState.ETag, blobName, _container); await _storage.DeleteBlob(_container, blobName); grainState.ETag = null; _logger.LogTrace("Cleared: GrainType={0} Grainid={1} ETag={2} to BlobName={3} in Container={4}", grainType, grainReference, grainState.ETag, blobName, _container); } catch (Exception ex) { _logger.LogError(ex, "Error clearing: GrainType={0} Grainid={1} ETag={2} BlobName={3} in Container={4} Exception={5}", grainType, grainReference, grainState.ETag, blobName, _container, ex.Message); throw; } } public async Task ReadStateAsync(string grainType, GrainReference grainReference, IGrainState grainState) { string blobName = GetBlobNameString(grainType, grainReference); try { _logger.LogTrace("Reading: GrainType={0} Grainid={1} ETag={2} to BlobName={3} in Container={4}", grainType, grainReference, grainState.ETag, blobName, _container); GrainStateRecord record; try { using (var blob = await _storage.ReadBlob(_container, blobName)) using (var stream = new MemoryStream()) { await blob.CopyToAsync(stream); record = ConvertFromStorageFormat(stream.ToArray()); } } catch (BucketNotFoundException ex) { _logger.LogTrace("ContainerNotFound reading: GrainType={0} Grainid={1} ETag={2} to BlobName={3} in Container={4} Exception={5}", grainType, grainReference, grainState.ETag, blobName, _container, ex.message); return; } catch (ObjectNotFoundException ex) { _logger.LogTrace("BlobNotFound reading: GrainType={0} Grainid={1} ETag={2} to BlobName={3} in Container={4} Exception={5}", grainType, grainReference, grainState.ETag, blobName, _container, ex.message); return; } grainState.State = record.State; grainState.ETag = record.ETag.ToString(); _logger.LogTrace("Read: GrainType={0} Grainid={1} ETag={2} to BlobName={3} in Container={4}", grainType, grainReference, grainState.ETag, blobName, _container); } catch (Exception ex) { _logger.LogError(ex, "Error reading: GrainType={0} Grainid={1} ETag={2} from BlobName={3} in Container={4} Exception={5}", grainType, grainReference, grainState.ETag, blobName, _container, ex.Message); throw; } } public async Task WriteStateAsync(string grainType, GrainReference grainReference, IGrainState grainState) { string blobName = GetBlobNameString(grainType, grainReference); int newETag = string.IsNullOrEmpty(grainState.ETag) ? 0 : Int32.Parse(grainState.ETag) + 1; try { _logger.LogTrace("Writing: GrainType={0} Grainid={1} ETag={2} to BlobName={3} in Container={4}", grainType, grainReference, grainState.ETag, blobName, _container); var record = new GrainStateRecord { ETag = newETag, State = grainState.State }; using (var stream = new MemoryStream(ConvertToStorageFormat(record))) { await _storage.UploadBlob(_container, blobName, stream, contentType: "application/json"); } grainState.ETag = newETag.ToString(); _logger.LogTrace("Wrote: GrainType={0} Grainid={1} ETag={2} to BlobName={3} in Container={4}", grainType, grainReference, grainState.ETag, blobName, _container); } catch (Exception ex) { _logger.LogError(ex, "Error writing: GrainType={0} Grainid={1} ETag={2} from BlobName={3} in Container={4} Exception={5}", grainType, grainReference, grainState.ETag, blobName, _container, ex.Message); throw; } } private string GetBlobNameString(string grainType, GrainReference grainReference) { return $"{grainType}-{grainReference.ToKeyString()}"; } private byte[] ConvertToStorageFormat(object record) { var data = JsonConvert.SerializeObject(record, _jsonSettings); return Encoding.UTF8.GetBytes(data); } private GrainStateRecord ConvertFromStorageFormat(byte[] content) { var json = Encoding.UTF8.GetString(content); var record = JsonConvert.DeserializeObject<GrainStateRecord>(json, _jsonSettings); return record; } private async Task Init(CancellationToken ct) { _jsonSettings = OrleansJsonSerializer.UpdateSerializerSettings(OrleansJsonSerializer.GetDefaultSerializerSettings(_typeResolver, _grainFactory), false, false, null); if (!await _storage.ContainerExits(_container)) { await _storage.CreateContainerAsync(_container); } } public void Participate(ISiloLifecycle lifecycle) { lifecycle.Subscribe(OptionFormattingUtilities.Name<MinioGrainStorage>(_name), ServiceLifecycleStage.ApplicationServices, Init); } } public static class MinioGrainStorageFactory { public static IGrainStorage Create(IServiceProvider services, string name) { IOptionsSnapshot<MinioGrainStorageOptions> optionsSnapshot = services.GetRequiredService<IOptionsSnapshot<MinioGrainStorageOptions>>(); var options = optionsSnapshot.Get(name); IMinioStorage storage = ActivatorUtilities.CreateInstance<MinioStorage>(services, options.AccessKey, options.SecretKey, options.Endpoint); return ActivatorUtilities.CreateInstance<MinioGrainStorage>(services, name, options.Container, storage); } } }
42.125654
177
0.608998
[ "MIT" ]
Kimserey/Orleans.Persistence.Minio
Orleans.Persistence.Minio/Storage/MinioGrainStorage.cs
8,048
C#
using Common.Core.Helpers; using Xunit; namespace Common.Core.Tests.Helpers { public class MessageTest { [Theory] [InlineData(Messages.Body, "Body")] [InlineData(Messages.Method, "Method")] [InlineData(Messages.TraceIdentifier, "Trace Identifier")] [InlineData(Messages.Url, "Url")] [InlineData(Messages.DateTimeYearRange1To9999, "The year should be in the range 1 to 9999")] [InlineData(Messages.DateTimeWeekNumberRange1To9999, "The week number must not shift the year beyond 1 year to 9999 years")] public void Messages_String_ReturnTrue(string input, string expected) { Assert.Equal(expected, input); } } }
34.095238
132
0.670391
[ "Apache-2.0" ]
b-a-x/Common
test/Common.Core.Tests/Helpers/MessageTest.cs
718
C#
using Alabo.Web.Mvc.Attributes; using System.ComponentModel.DataAnnotations; namespace Alabo.App.Share.TaskExecutes.Domain.Enums { /// <summary> /// 封顶方式 /// </summary> [ClassProperty(Name = "封顶方式")] public enum LimitType { /// <summary> /// 不封顶 /// </summary> [LabelCssClass(BadgeColorCalss.Success)] [Display(Name = "不封顶")] NoMaxValue = 1, /// <summary> /// 封顶但无时间限制 /// </summary> [LabelCssClass(BadgeColorCalss.Success)] [Display(Name = "封顶但无时间限制")] MaxValueNoTimeLimit = 2, /// <summary> /// 按天封顶 /// </summary> [LabelCssClass(BadgeColorCalss.Success)] [Display(Name = "按天封顶")] MaxValueByDay = 3, /// <summary> /// 按周封顶 /// </summary> [LabelCssClass(BadgeColorCalss.Success)] [Display(Name = "按周封顶")] MaxValueByWeek = 4, /// <summary> /// 按月封顶 /// </summary> [LabelCssClass(BadgeColorCalss.Success)] [Display(Name = "按月封顶")] MaxValueByMonth = 5, /// <summary> /// 按季度封顶 /// </summary> [LabelCssClass(BadgeColorCalss.Success)] [Display(Name = "按季度封顶")] MaxValueByQuarter = 6, /// <summary> /// 按年封顶 /// </summary> [LabelCssClass(BadgeColorCalss.Success)] [Display(Name = "按年封顶")] MaxValueByYear = 7 } }
24.754098
51
0.504636
[ "MIT" ]
tongxin3267/alabo
src/03.app/01-Alabo.App.Share/TaskExecutes/Domain/Enums/LimitType.cs
1,656
C#
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("Math Patato")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("Math Patato")] [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("1747eab4-fc6e-4dca-b496-b84c8d5ca83f")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
37.567568
84
0.746043
[ "MIT" ]
zrusev/SoftUni_2016
04. C# Advanced - May 2017/01. Stacks and Queues/01. Stacks and Queues - Lab/06. Math Patato/Math Patato/Math Patato/Properties/AssemblyInfo.cs
1,393
C#
using PLControls.FormsPlugin; using PLControls.FormsPlugin.iOS; using UIKit; using Xamarin.Forms; using Xamarin.Forms.Platform.iOS; [assembly: ExportRenderer(typeof(JustifiedLabel), typeof(JustifiedLabelRenderer))] namespace PLControls.FormsPlugin.iOS { public class JustifiedLabelRenderer : LabelRenderer { protected override void OnElementChanged(ElementChangedEventArgs<Label> e) { base.OnElementChanged(e); if (Control != null) { Control.TextAlignment = UITextAlignment.Justified; } } } }
27.045455
82
0.677311
[ "MIT" ]
processim-labs/PLControls
src/PLControls/iOS/JustifiedLabelRenderer.ios.cs
597
C#
using Kudu.Contracts; using Kudu.Contracts.Jobs; using Kudu.Contracts.Tracing; using Kudu.Core.Hooks; using Kudu.Core.Infrastructure; using Kudu.Core.Jobs; using Kudu.Core.Tracing; using Kudu.Services.Arm; using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Net; using System.Net.Http; using System.Net.Http.Headers; using System.Threading.Tasks; using System.Web.Http; namespace Kudu.Services.Jobs { [ArmControllerConfiguration] public class JobsController : ApiController { private readonly ITracer _tracer; private readonly ITriggeredJobsManager _triggeredJobsManager; private readonly IContinuousJobsManager _continuousJobsManager; public JobsController(ITriggeredJobsManager triggeredJobsManager, IContinuousJobsManager continuousJobsManager, ITracer tracer) { _triggeredJobsManager = triggeredJobsManager; _continuousJobsManager = continuousJobsManager; _tracer = tracer; } [HttpGet] public HttpResponseMessage ListAllJobs() { IEnumerable<ContinuousJob> continuousJobs = _continuousJobsManager.ListJobs(forceRefreshCache: false); IEnumerable<TriggeredJob> triggeredJobs = _triggeredJobsManager.ListJobs(forceRefreshCache: false); var allJobs = triggeredJobs.OfType<JobBase>().Union(continuousJobs); return ListJobsResponseBasedOnETag(allJobs); } [HttpGet] public HttpResponseMessage ListContinuousJobs() { IEnumerable<ContinuousJob> continuousJobs = _continuousJobsManager.ListJobs(forceRefreshCache: false); return ListJobsResponseBasedOnETag(continuousJobs); } [HttpGet] public HttpResponseMessage GetContinuousJob(string jobName) { ContinuousJob continuousJob = _continuousJobsManager.GetJob(jobName); if (continuousJob != null) { return Request.CreateResponse(HttpStatusCode.OK, ArmUtils.AddEnvelopeOnArmRequest(continuousJob, Request)); } return Request.CreateResponse(HttpStatusCode.NotFound); } [HttpPost] public HttpResponseMessage EnableContinuousJob(string jobName) { try { _continuousJobsManager.EnableJob(jobName); return Request.CreateResponse(HttpStatusCode.OK); } catch (JobNotFoundException) { return Request.CreateResponse(HttpStatusCode.NotFound); } } [HttpPost] public HttpResponseMessage DisableContinuousJob(string jobName) { try { _continuousJobsManager.DisableJob(jobName); return Request.CreateResponse(HttpStatusCode.OK); } catch (JobNotFoundException) { return Request.CreateResponse(HttpStatusCode.NotFound); } } [HttpGet] public HttpResponseMessage GetContinuousJobSettings(string jobName) { return GetJobSettings(jobName, _continuousJobsManager); } [HttpPut] public HttpResponseMessage SetContinuousJobSettings(string jobName, JobSettings jobSettings) { return SetJobSettings(jobName, jobSettings, _continuousJobsManager); } [HttpGet] public HttpResponseMessage ListTriggeredJobs() { IEnumerable<TriggeredJob> triggeredJobs = _triggeredJobsManager.ListJobs(forceRefreshCache: false); return ListJobsResponseBasedOnETag(triggeredJobs); } [HttpGet] public HttpResponseMessage ListTriggeredJobsInSwaggerFormat() { IEnumerable<TriggeredJob> triggeredJobs = _triggeredJobsManager.ListJobs(forceRefreshCache: false); SwaggerApiDef responseSwagger = new SwaggerApiDef(triggeredJobs); return Request.CreateResponse(responseSwagger); } [HttpGet] public HttpResponseMessage GetTriggeredJob(string jobName) { TriggeredJob triggeredJob = _triggeredJobsManager.GetJob(jobName); if (triggeredJob != null) { return Request.CreateResponse(HttpStatusCode.OK, ArmUtils.AddEnvelopeOnArmRequest(triggeredJob, Request)); } return Request.CreateResponse(HttpStatusCode.NotFound); } [HttpGet] public HttpResponseMessage GetTriggeredJobHistory(string jobName) { string etag = GetRequestETag(); string currentETag; TriggeredJobHistory history = _triggeredJobsManager.GetJobHistory(jobName, etag, out currentETag); if (history == null && currentETag == null) { return Request.CreateResponse(HttpStatusCode.NotFound); } HttpResponseMessage response; if (etag == currentETag) { response = Request.CreateResponse(HttpStatusCode.NotModified); } else { object triggeredJobHistoryResponse = history != null && ArmUtils.IsArmRequest(Request) ? ArmUtils.AddEnvelopeOnArmRequest(history.TriggeredJobRuns, Request) : history; response = Request.CreateResponse(HttpStatusCode.OK, triggeredJobHistoryResponse); } response.Headers.ETag = new EntityTagHeaderValue(currentETag); return response; } [HttpGet] public HttpResponseMessage GetTriggeredJobRun(string jobName, string runId) { TriggeredJobRun triggeredJobRun = _triggeredJobsManager.GetJobRun(jobName, runId); if (triggeredJobRun != null) { return Request.CreateResponse(HttpStatusCode.OK, ArmUtils.AddEnvelopeOnArmRequest(triggeredJobRun, Request)); } return Request.CreateResponse(HttpStatusCode.NotFound); } [HttpPost] public HttpResponseMessage InvokeTriggeredJob(string jobName, string arguments = null) { try { Uri runUri = _triggeredJobsManager.InvokeTriggeredJob(jobName, arguments, "External - " + Request.Headers.UserAgent); // Return a 200 in the ARM case, otherwise a 202 can cause it to poll on /run, which we don't support // For non-ARM, stay with the 202 to reduce potential impact of change var response = Request.CreateResponse(ArmUtils.IsArmRequest(Request) ? HttpStatusCode.OK : HttpStatusCode.Accepted); // Add the run uri in the location so caller can get status on the running job response.Headers.Add("Location", runUri.AbsoluteUri); return response; } catch (JobNotFoundException) { return Request.CreateResponse(HttpStatusCode.NotFound); } catch (ConflictException) { return CreateErrorResponse(HttpStatusCode.Conflict, Resources.Error_WebJobAlreadyRunning); } catch (WebJobsStoppedException) { return CreateErrorResponse(HttpStatusCode.Conflict, Resources.Error_WebJobsStopped); } catch { if (FileSystemHelpers.IsFileSystemReadOnly()) { // return 503 to ask caller to retry, since ReadOnly file system should be temporary return Request.CreateResponse(HttpStatusCode.ServiceUnavailable); } throw; } } [HttpPut] public Task<HttpResponseMessage> CreateContinuousJob(string jobName) { return CreateJob(jobName, _continuousJobsManager); } [HttpPut] public HttpResponseMessage CreateContinuousJobArm(string jobName, ArmEntry<ContinuousJob> armContinuousJob) { return SetJobSettings(jobName, armContinuousJob.Properties.Settings, _continuousJobsManager); } [HttpDelete] public HttpResponseMessage RemoveContinuousJob(string jobName) { return RemoveJob(jobName, _continuousJobsManager); } [HttpPut] public Task<HttpResponseMessage> CreateTriggeredJob(string jobName) { return CreateJob(jobName, _triggeredJobsManager); } [HttpPut] public HttpResponseMessage CreateTriggeredJobArm(string jobName, ArmEntry<TriggeredJob> armTriggeredJob) { return SetJobSettings(jobName, armTriggeredJob.Properties.Settings, _triggeredJobsManager); } [HttpDelete] public HttpResponseMessage RemoveTriggeredJob(string jobName) { return RemoveJob(jobName, _triggeredJobsManager); } [HttpGet] public HttpResponseMessage GetTriggeredJobSettings(string jobName) { return GetJobSettings(jobName, _triggeredJobsManager); } [HttpPut] public HttpResponseMessage SetTriggeredJobSettings(string jobName, JobSettings jobSettings) { return SetJobSettings(jobName, jobSettings, _triggeredJobsManager); } [AcceptVerbs("GET", "HEAD", "PUT", "POST", "DELETE", "PATCH")] public async Task<HttpResponseMessage> RequestPassthrough(string jobName, string path) { try { return await _continuousJobsManager.HandleRequest(jobName, path, Request); } catch(Exception e) { _tracer.TraceError(e); return Request.CreateErrorResponse(HttpStatusCode.NotFound, e); } } private HttpResponseMessage ListJobsResponseBasedOnETag(IEnumerable<JobBase> jobs) { string etag = GetRequestETag(); string currentETag = "\"" + HashHelpers.CalculateCompositeHash(jobs.ToArray()).ToString("x") + "\""; HttpResponseMessage response; if (etag == currentETag) { response = Request.CreateResponse(HttpStatusCode.NotModified); } else { response = Request.CreateResponse(HttpStatusCode.OK, ArmUtils.AddEnvelopeOnArmRequest(jobs, Request)); } response.Headers.ETag = new EntityTagHeaderValue(currentETag); return response; } private string GetRequestETag() { return Request.Headers.IfNoneMatch.Select(header => header.Tag).FirstOrDefault(); } private HttpResponseMessage RemoveJob<TJob>(string jobName, IJobsManager<TJob> jobsManager) where TJob : JobBase, new() { jobsManager.DeleteJob(jobName); return Request.CreateResponse(HttpStatusCode.OK); } private async Task<HttpResponseMessage> CreateJob<TJob>(string jobName, IJobsManager<TJob> jobsManager) where TJob : JobBase, new() { TJob job = null; string errorMessage = null; HttpStatusCode errorStatusCode; // Get the script file name from the content disposition header string scriptFileName = null; HttpContent content = Request.Content; if (content.Headers != null && content.Headers.ContentDisposition != null) { scriptFileName = content.Headers.ContentDisposition.FileName; } if (String.IsNullOrEmpty(scriptFileName)) { return CreateErrorResponse(HttpStatusCode.BadRequest, Resources.Error_MissingContentDispositionHeader); } // Clean the file name from quotes and directories scriptFileName = scriptFileName.Trim('"'); scriptFileName = Path.GetFileName(scriptFileName); Stream fileStream = await content.ReadAsStreamAsync(); try { // Upload as a zip if content type is of a zipped file if (content.Headers.ContentType != null && String.Equals(content.Headers.ContentType.MediaType, "application/zip", StringComparison.OrdinalIgnoreCase)) { job = jobsManager.CreateOrReplaceJobFromZipStream(fileStream, jobName); } else { job = jobsManager.CreateOrReplaceJobFromFileStream(fileStream, jobName, scriptFileName); } errorMessage = job.Error; errorStatusCode = HttpStatusCode.BadRequest; } catch (ConflictException) { return CreateErrorResponse(HttpStatusCode.Conflict, Resources.Error_WebJobAlreadyExists); } catch (Exception ex) { errorMessage = ex.Message; errorStatusCode = HttpStatusCode.InternalServerError; _tracer.TraceError(ex); } // On error, delete job (if exists) if (errorMessage != null) { jobsManager.DeleteJob(jobName); return CreateErrorResponse(errorStatusCode, errorMessage); } return Request.CreateResponse(job); } private HttpResponseMessage GetJobSettings<TJob>(string jobName, IJobsManager<TJob> jobsManager) where TJob : JobBase, new() { try { JobSettings jobSettings = jobsManager.GetJobSettings(jobName); return Request.CreateResponse(HttpStatusCode.OK, jobSettings); } catch (JobNotFoundException) { return Request.CreateResponse(HttpStatusCode.NotFound); } } private HttpResponseMessage SetJobSettings<TJob>(string jobName, JobSettings jobSettings, IJobsManager<TJob> jobsManager) where TJob : JobBase, new() { try { jobsManager.SetJobSettings(jobName, jobSettings); return Request.CreateResponse(HttpStatusCode.OK); } catch (JobNotFoundException) { return Request.CreateResponse(HttpStatusCode.NotFound); } } private HttpResponseMessage CreateErrorResponse(HttpStatusCode errorStatusCode, string errorMessage) { HttpResponseMessage response = Request.CreateResponse(errorStatusCode); response.Content = new StringContent(errorMessage); return response; } } }
36.62716
157
0.617298
[ "Apache-2.0" ]
DiogenesPolanco/kudu
Kudu.Services/Jobs/JobsController.cs
14,836
C#
using MixERP.Net.Common.Helpers; using MixERP.Net.Framework; using MixERP.Net.i18n.Resources; using System.Diagnostics.CodeAnalysis; namespace MixERP.Net.Entities.Helpers { public static class TransactionBookHelper { public static string GetBookAcronym(TranBook book, SubTranBook subBook) { if (book == TranBook.Sales) { if (subBook == SubTranBook.Delivery) { return ConfigurationHelper.GetParameter("SalesDeliveryAcronym"); } if (subBook == SubTranBook.Direct) { return ConfigurationHelper.GetParameter("SalesDirectAcronym"); } if (subBook == SubTranBook.Invoice) { return ConfigurationHelper.GetParameter("SalesInvoiceAcronym"); } if (subBook == SubTranBook.Order) { return ConfigurationHelper.GetParameter("SalesOrderAcronym"); } if (subBook == SubTranBook.Quotation) { return ConfigurationHelper.GetParameter("SalesQuotationAcronym"); } if (subBook == SubTranBook.Receipt) { return ConfigurationHelper.GetParameter("SalesReceiptAcronym"); } if (subBook == SubTranBook.Return) { return ConfigurationHelper.GetParameter("SaleReturnAcronym"); } } if (book == TranBook.Purchase) { if (subBook == SubTranBook.Direct) { return ConfigurationHelper.GetParameter("PurchaseDirectAcronym"); } if (subBook == SubTranBook.Order) { return ConfigurationHelper.GetParameter("PurchaseOrderAcronym"); } if (subBook == SubTranBook.Payment) { return ConfigurationHelper.GetParameter("PurchasePaymentAcronym"); } if (subBook == SubTranBook.Receipt) { return ConfigurationHelper.GetParameter("PurchaseGRNAcronym"); } if (subBook == SubTranBook.Return) { return ConfigurationHelper.GetParameter("PurchaseReturnAcronym"); } } return string.Empty; } [SuppressMessage("Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity")] public static string GetInvariantTransactionBookName(TranBook book, SubTranBook subBook) { string bookName = string.Empty; if (book == TranBook.Sales) { switch (subBook) { case SubTranBook.Delivery: bookName = "Sales.Delivery"; break; case SubTranBook.Direct: bookName = "Sales.Direct"; break; case SubTranBook.Invoice: bookName = "Sales.Invoice"; break; case SubTranBook.Order: bookName = "Sales.Order"; break; case SubTranBook.Payment: throw new MixERPException(Warnings.InvalidSubTranBookSalesPayment); case SubTranBook.Quotation: bookName = "Sales.Quotation"; break; case SubTranBook.Receipt: bookName = "Sales.Receipt"; break; case SubTranBook.Return: bookName = "Sales.Return"; break; case SubTranBook.Transfer: throw new MixERPException(Warnings.InvalidSubTranBookSalesTransfer); case SubTranBook.Suspense: throw new MixERPException(Warnings.InvalidSubTranBookSalesSuspense); } } if (book == TranBook.Purchase) { switch (subBook) { case SubTranBook.Delivery: throw new MixERPException(Warnings.InvalidSubTranBookPurchaseDelivery); case SubTranBook.Direct: bookName = "Purchase.Direct"; break; case SubTranBook.Invoice: bookName = "Purchase.Invoice"; break; case SubTranBook.Order: bookName = "Purchase.Order"; break; case SubTranBook.Payment: bookName = "Purchase.Payment"; break; case SubTranBook.Quotation: throw new MixERPException(Warnings.InvalidSubTranBookPurchaseQuotation); case SubTranBook.Receipt: bookName = "Purchase.Receipt"; //Also known as GRN break; case SubTranBook.Return: bookName = "Purchase.Return"; break; case SubTranBook.Transfer: throw new MixERPException(Warnings.InvalidSubTranBookPurchaseTransfer); case SubTranBook.Suspense: throw new MixERPException(Warnings.InvalidSubTranBookPurchaseSuspense); } } if (book == TranBook.Inventory) { switch (subBook) { case SubTranBook.Delivery: throw new MixERPException(Warnings.InvalidSubTranBookInventoryDelivery); case SubTranBook.Direct: throw new MixERPException(Warnings.InvalidSubTranBookInventoryDirect); case SubTranBook.Invoice: throw new MixERPException(Warnings.InvalidSubTranBookInventoryInvoice); case SubTranBook.Order: throw new MixERPException(Warnings.InvalidSubTranBookInventoryOrder); case SubTranBook.Payment: throw new MixERPException(Warnings.InvalidSubTranBookInventoryPayment); case SubTranBook.Quotation: throw new MixERPException(Warnings.InvalidSubTranBookInventoryQuotation); case SubTranBook.Receipt: throw new MixERPException(Warnings.InvalidSubTranBookInventoryReceipt); case SubTranBook.Return: throw new MixERPException(Warnings.InvalidSubTranBookInventoryReturn); case SubTranBook.Transfer: bookName = "Inventory.Transfer"; break; case SubTranBook.Suspense: bookName = "Inventory.Suspense"; break; } } return bookName; } } }
37.368687
97
0.490337
[ "MPL-2.0" ]
asine/mixerp
src/Libraries/Entities/MixERP.Net.Entities/Helpers/TransactionBookHelper.cs
7,401
C#
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("12. FallingRocksVersion2")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("12. FallingRocksVersion2")] [assembly: AssemblyCopyright("Copyright © 2012")] [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("19b2638a-adff-4386-b2cb-7fa371dc1d9c")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
38.405405
84
0.746657
[ "MIT" ]
vladislav-karamfilov/TelerikAcademy
C# Projects/Homework-ConsoleInputOutput/12. FallingRocksVersion2/Properties/AssemblyInfo.cs
1,424
C#
namespace OEmbed.Test { public class BasicTests { [Fact] public async void NotFoundRequestWithCacheTest() { var provider = new CoubProvider(); var consumer = TestHelpers.BuildConsumer(new[] { provider }, withCache: true); var result = await consumer.RequestAsync<Video>("https://coub.com/view/ut4ws6a3dsSfefsd"); Assert.Null(result); } [Fact] public async void NotFoundRequestWithoutCacheTest() { var provider = new CoubProvider(); var consumer = TestHelpers.BuildConsumer(new[] { provider }, withCache: false); var result = await consumer.RequestAsync<Video>("https://coub.com/view/ut4ws6a3dsSfefsd"); Assert.Null(result); } } }
29.888889
102
0.597274
[ "MIT" ]
hey-red/OEmbed
OEmbed.Test/BasicTests.cs
809
C#
namespace Logger.Loggers { using Contracts; public class LogFile : ILogFile { public string Size { get; private set; } public void Write(string message) { for (int i = 0; i < message.Length; i++) { if ((message[i] >= 'a' && message[i] <= 'z') || (message[i] >= 'A' && message[i] <= 'Z')) { this.Size += message[i]; } } // this.Size += message.Where(char.IsLetter).Sum(ch => ch); } } }
25.090909
105
0.425725
[ "MIT" ]
MiroslavaPetrova/SoftUni-Solutions
CSharp OOP Advanced/01.SOLID/Logger/Loggers/LogFile.cs
554
C#
#if !NO_CRYPTO using System; using System.Security.Cryptography; using SharpCompress.Converters; namespace SharpCompress.Common.Zip { internal class WinzipAesEncryptionData { private const int RFC2898_ITERATIONS = 1000; private readonly byte[] _salt; private readonly WinzipAesKeySize _keySize; private readonly byte[] _passwordVerifyValue; private readonly string _password; private byte[] _generatedVerifyValue; internal WinzipAesEncryptionData(WinzipAesKeySize keySize, byte[] salt, byte[] passwordVerifyValue, string password) { this._keySize = keySize; this._salt = salt; this._passwordVerifyValue = passwordVerifyValue; this._password = password; Initialize(); } internal byte[] IvBytes { get; set; } internal byte[] KeyBytes { get; set; } private int KeySizeInBytes { get { return KeyLengthInBytes(_keySize); } } internal static int KeyLengthInBytes(WinzipAesKeySize keySize) { switch (keySize) { case WinzipAesKeySize.KeySize128: return 16; case WinzipAesKeySize.KeySize192: return 24; case WinzipAesKeySize.KeySize256: return 32; } throw new InvalidOperationException(); } private void Initialize() { var rfc2898 = new Rfc2898DeriveBytes(_password, _salt, RFC2898_ITERATIONS); KeyBytes = rfc2898.GetBytes(KeySizeInBytes); // 16 or 24 or 32 ??? IvBytes = rfc2898.GetBytes(KeySizeInBytes); _generatedVerifyValue = rfc2898.GetBytes(2); short verify = DataConverter.LittleEndian.GetInt16(_passwordVerifyValue, 0); if (_password != null) { short generated = DataConverter.LittleEndian.GetInt16(_generatedVerifyValue, 0); if (verify != generated) { throw new InvalidFormatException("bad password"); } } } } } #endif
28.582278
107
0.573074
[ "MIT" ]
13xforever/sharpcompress
src/SharpCompress/Common/Zip/WinzipAesEncryptionData.cs
2,258
C#
using Microsoft.AspNetCore.Http; using System; using System.ComponentModel; using System.Net; using System.Runtime.Serialization; namespace EasyOC { /// <summary> /// 自定义友好异常类 /// </summary> public class AppFriendlyException : Exception { /// <summary> /// 构造函数 /// </summary> public AppFriendlyException() : base() { } public AppFriendlyException(HttpStatusCode simpleError, object message = null) : base() { if (message == null) { message = simpleError.ToDescriptionOrString(); } switch (simpleError) { case HttpStatusCode.Unauthorized: ErrorMessage = message; ErrorCode = StatusCodes.Status403Forbidden; break; case HttpStatusCode.NotFound: ErrorMessage = message; ErrorCode = StatusCodes.Status404NotFound; break; default: ErrorMessage = message; break; } } /// <summary> /// 构造函数 /// </summary> /// <param name="message"></param> /// <param name="errorCode"></param> public AppFriendlyException(string message, int errorCode) : base(message) { ErrorMessage = message; ErrorCode = errorCode; } public AppFriendlyException(object message, int errorCode) : base(message.ToString()) { ErrorMessage = message; ErrorCode = errorCode; } /// <summary> /// 构造函数 /// </summary> /// <param name="message"></param> /// <param name="errorCode"></param> /// <param name="innerException"></param> public AppFriendlyException(string message, int errorCode, Exception innerException) : base(message, innerException) { ErrorMessage = message; ErrorCode = errorCode; } /// <summary> /// 构造函数 /// </summary> /// <param name="info"></param> /// <param name="context"></param> public AppFriendlyException(SerializationInfo info, StreamingContext context) : base(info, context) { } /// <summary> /// 错误码 /// </summary> public object ErrorCode { get; set; } /// <summary> /// 错误消息(支持 Object 对象) /// </summary> public object ErrorMessage { get; set; } /// <summary> /// 状态码 <see cref="StatusCodes"/> /// </summary> public int StatusCode { get; set; } = StatusCodes.Status500InternalServerError; /// <summary> /// 是否是数据验证异常 /// </summary> public bool ValidationException { get; set; } = false; } public enum SimpleError { [Description("Permission denied.")] PermissionDenied, [Description("Resource not found.")] ResourceNotFound, } }
27.810811
124
0.515711
[ "Apache-2.0" ]
EasyOC/EasyOC
src/Core/EasyOC.Core/ResultWaper/FriendlyException/AppFriendlyException.cs
3,187
C#
namespace LateBindingHelper { /// <summary> /// Provides an interface for specifying a method to invoke on a type /// </summary> public interface IMethodCall { /// <summary> /// Sets the Method name to be invoked /// </summary> /// <param name="methodName">String with the name of the method to be invoked</param> /// <returns> /// An <see cref="IMethodOperations"/> that will establish the parameters to /// add to this method invocation, and also will allow to perform the method real invocation. /// </returns> IMethodOperations Method(string methodName); } }
37.611111
102
0.604136
[ "MIT" ]
rickyah/DynoBind
projects/Core/IMethodCall.cs
677
C#
//------------------------------------------------------------------------------ // <auto-generated> // このコードはツールによって生成されました。 // ランタイム バージョン:2.0.50727.8009 // // このファイルへの変更は、以下の状況下で不正な動作の原因になったり、 // コードが再生成されるときに損失したりします。 // </auto-generated> //------------------------------------------------------------------------------ namespace MsgPack.Serialization.GeneratedSerializers.MapBased { [System.CodeDom.Compiler.GeneratedCodeAttribute("MsgPack.Serialization.CodeDomSerializers.CodeDomSerializerBuilder", "0.6.0.0")] [System.Diagnostics.DebuggerNonUserCodeAttribute()] public class MsgPack_Serialization_PolymorphicMemberTypeKnownType_PrimitiveReadOnlyFieldAndConstructorAsObjectSerializer : MsgPack.Serialization.MessagePackSerializer<MsgPack.Serialization.PolymorphicMemberTypeKnownType_PrimitiveReadOnlyFieldAndConstructorAsObject> { private MsgPack.Serialization.MessagePackSerializer<string> _serializer0; private MsgPack.Serialization.MessagePackSerializer<object> _serializer1; public MsgPack_Serialization_PolymorphicMemberTypeKnownType_PrimitiveReadOnlyFieldAndConstructorAsObjectSerializer(MsgPack.Serialization.SerializationContext context) : base(context) { MsgPack.Serialization.PolymorphismSchema schema0 = default(MsgPack.Serialization.PolymorphismSchema); schema0 = null; this._serializer0 = context.GetSerializer<string>(schema0); MsgPack.Serialization.PolymorphismSchema schema1 = default(MsgPack.Serialization.PolymorphismSchema); schema1 = null; this._serializer1 = context.GetSerializer<object>(schema1); } protected internal override void PackToCore(MsgPack.Packer packer, MsgPack.Serialization.PolymorphicMemberTypeKnownType_PrimitiveReadOnlyFieldAndConstructorAsObject objectTree) { packer.PackMapHeader(1); this._serializer0.PackTo(packer, "Primitive"); this._serializer1.PackTo(packer, objectTree.Primitive); } protected internal override MsgPack.Serialization.PolymorphicMemberTypeKnownType_PrimitiveReadOnlyFieldAndConstructorAsObject UnpackFromCore(MsgPack.Unpacker unpacker) { MsgPack.Serialization.PolymorphicMemberTypeKnownType_PrimitiveReadOnlyFieldAndConstructorAsObject result = default(MsgPack.Serialization.PolymorphicMemberTypeKnownType_PrimitiveReadOnlyFieldAndConstructorAsObject); if (unpacker.IsArrayHeader) { int unpacked = default(int); int itemsCount = default(int); itemsCount = MsgPack.Serialization.UnpackHelpers.GetItemsCount(unpacker); object ctorArg0 = default(object); ctorArg0 = null; object nullable = default(object); if ((unpacked < itemsCount)) { if ((unpacker.Read() == false)) { throw MsgPack.Serialization.SerializationExceptions.NewMissingItem(0); } if (((unpacker.IsArrayHeader == false) && (unpacker.IsMapHeader == false))) { nullable = this._serializer1.UnpackFrom(unpacker); } else { MsgPack.Unpacker disposable = default(MsgPack.Unpacker); disposable = unpacker.ReadSubtree(); try { nullable = this._serializer1.UnpackFrom(disposable); } finally { if (((disposable == null) == false)) { disposable.Dispose(); } } } } if (((nullable == null) == false)) { ctorArg0 = nullable; } unpacked = (unpacked + 1); result = new MsgPack.Serialization.PolymorphicMemberTypeKnownType_PrimitiveReadOnlyFieldAndConstructorAsObject(ctorArg0); } else { int itemsCount0 = default(int); itemsCount0 = MsgPack.Serialization.UnpackHelpers.GetItemsCount(unpacker); object ctorArg00 = default(object); ctorArg00 = null; for (int i = 0; (i < itemsCount0); i = (i + 1)) { string key = default(string); string nullable0 = default(string); nullable0 = MsgPack.Serialization.UnpackHelpers.UnpackStringValue(unpacker, typeof(MsgPack.Serialization.PolymorphicMemberTypeKnownType_PrimitiveReadOnlyFieldAndConstructorAsObject), "MemberName"); if (((nullable0 == null) == false)) { key = nullable0; } else { throw MsgPack.Serialization.SerializationExceptions.NewNullIsProhibited("MemberName"); } if ((key == "Primitive")) { object nullable1 = default(object); if ((unpacker.Read() == false)) { throw MsgPack.Serialization.SerializationExceptions.NewMissingItem(i); } if (((unpacker.IsArrayHeader == false) && (unpacker.IsMapHeader == false))) { nullable1 = this._serializer1.UnpackFrom(unpacker); } else { MsgPack.Unpacker disposable0 = default(MsgPack.Unpacker); disposable0 = unpacker.ReadSubtree(); try { nullable1 = this._serializer1.UnpackFrom(disposable0); } finally { if (((disposable0 == null) == false)) { disposable0.Dispose(); } } } if (((nullable1 == null) == false)) { ctorArg00 = nullable1; } } else { unpacker.Skip(); } } result = new MsgPack.Serialization.PolymorphicMemberTypeKnownType_PrimitiveReadOnlyFieldAndConstructorAsObject(ctorArg00); } return result; } private static T @__Conditional<T>(bool condition, T whenTrue, T whenFalse) { if (condition) { return whenTrue; } else { return whenFalse; } } } }
51.23741
271
0.522466
[ "Apache-2.0" ]
sosan/msgpack-cli
test/MsgPack.UnitTest.Net35/gen/map/MsgPack_Serialization_PolymorphicMemberTypeKnownType_PrimitiveReadOnlyFieldAndConstructorAsObjectSerializer.cs
7,296
C#
// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Net; using System.Security.Authentication; using System.Security.Cryptography.X509Certificates; using System.Threading.Tasks; using Microsoft.AspNetCore; using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.Server.Kestrel.Https; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.Logging; namespace mvc { public class Program { public static void Main(string[] args) { if (args.Length != 7) { System.Console.WriteLine("Required: <CertificatePath> <CertificatePassword> <HTTPPortNumber> <HTTPSPortNumberTls12> <HTTPSPortNumberTls11> <HTTPSPortNumberTls> <HTTPSPortNumberTls12>"); Environment.Exit(1); } BuildWebHost(args).Run(); } public static IWebHost BuildWebHost(string[] args) => WebHost.CreateDefaultBuilder() .UseStartup<Startup>().UseKestrel(options => { options.AllowSynchronousIO = true; options.Listen(IPAddress.Loopback, int.Parse(args[2])); options.Listen(IPAddress.Loopback, int.Parse(args[3]), listenOptions => { var certificate = new X509Certificate2(args[0], args[1]); HttpsConnectionAdapterOptions httpsOption = new HttpsConnectionAdapterOptions(); httpsOption.SslProtocols = SslProtocols.Tls12; httpsOption.ClientCertificateMode = ClientCertificateMode.AllowCertificate; httpsOption.ClientCertificateValidation = (inCertificate, inChain, inPolicy) => { return true; }; httpsOption.CheckCertificateRevocation = false; httpsOption.ServerCertificate = certificate; listenOptions.UseHttps(httpsOption); }); options.Listen(IPAddress.Loopback, int.Parse(args[4]), listenOptions => { var certificate = new X509Certificate2(args[0], args[1]); HttpsConnectionAdapterOptions httpsOption = new HttpsConnectionAdapterOptions(); httpsOption.SslProtocols = SslProtocols.Tls11; httpsOption.ClientCertificateMode = ClientCertificateMode.AllowCertificate; httpsOption.ClientCertificateValidation = (inCertificate, inChain, inPolicy) => { return true; }; httpsOption.CheckCertificateRevocation = false; httpsOption.ServerCertificate = certificate; listenOptions.UseHttps(httpsOption); }); options.Listen(IPAddress.Loopback, int.Parse(args[5]), listenOptions => { var certificate = new X509Certificate2(args[0], args[1]); HttpsConnectionAdapterOptions httpsOption = new HttpsConnectionAdapterOptions(); httpsOption.SslProtocols = SslProtocols.Tls; httpsOption.ClientCertificateMode = ClientCertificateMode.AllowCertificate; httpsOption.ClientCertificateValidation = (inCertificate, inChain, inPolicy) => { return true; }; httpsOption.CheckCertificateRevocation = false; httpsOption.ServerCertificate = certificate; listenOptions.UseHttps(httpsOption); }); options.Listen(IPAddress.Loopback, int.Parse(args[6]), listenOptions => { var certificate = new X509Certificate2(args[0], args[1]); HttpsConnectionAdapterOptions httpsOption = new HttpsConnectionAdapterOptions(); httpsOption.SslProtocols = SslProtocols.Tls13; httpsOption.ClientCertificateMode = ClientCertificateMode.AllowCertificate; httpsOption.ClientCertificateValidation = (inCertificate, inChain, inPolicy) => { return true; }; httpsOption.CheckCertificateRevocation = false; httpsOption.ServerCertificate = certificate; listenOptions.UseHttps(httpsOption); }); }) .Build(); } }
52.252874
201
0.599648
[ "MIT" ]
2bon/PowerShell
test/tools/WebListener/Program.cs
4,546
C#
// *** WARNING: this file was generated by the Pulumi Terraform Bridge (tfgen) Tool. *** // *** Do not edit by hand unless you're certain you know what you are doing! *** using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Threading.Tasks; using Pulumi.Serialization; namespace Pulumi.Aws.Waf { /// <summary> /// Provides a WAF SQL Injection Match Set Resource /// /// ## Example Usage /// /// ```csharp /// using Pulumi; /// using Aws = Pulumi.Aws; /// /// class MyStack : Stack /// { /// public MyStack() /// { /// var sqlInjectionMatchSet = new Aws.Waf.SqlInjectionMatchSet("sqlInjectionMatchSet", new Aws.Waf.SqlInjectionMatchSetArgs /// { /// SqlInjectionMatchTuples = /// { /// new Aws.Waf.Inputs.SqlInjectionMatchSetSqlInjectionMatchTupleArgs /// { /// FieldToMatch = new Aws.Waf.Inputs.SqlInjectionMatchSetSqlInjectionMatchTupleFieldToMatchArgs /// { /// Type = "QUERY_STRING", /// }, /// TextTransformation = "URL_DECODE", /// }, /// }, /// }); /// } /// /// } /// ``` /// /// ## Import /// /// AWS WAF SQL Injection Match Set can be imported using their ID, e.g., /// /// ```sh /// $ pulumi import aws:waf/sqlInjectionMatchSet:SqlInjectionMatchSet example a1b2c3d4-d5f6-7777-8888-9999aaaabbbbcccc /// ``` /// </summary> [AwsResourceType("aws:waf/sqlInjectionMatchSet:SqlInjectionMatchSet")] public partial class SqlInjectionMatchSet : Pulumi.CustomResource { /// <summary> /// The name or description of the SQL Injection Match Set. /// </summary> [Output("name")] public Output<string> Name { get; private set; } = null!; /// <summary> /// The parts of web requests that you want AWS WAF to inspect for malicious SQL code and, if you want AWS WAF to inspect a header, the name of the header. /// </summary> [Output("sqlInjectionMatchTuples")] public Output<ImmutableArray<Outputs.SqlInjectionMatchSetSqlInjectionMatchTuple>> SqlInjectionMatchTuples { get; private set; } = null!; /// <summary> /// Create a SqlInjectionMatchSet resource with the given unique name, arguments, and options. /// </summary> /// /// <param name="name">The unique name of the resource</param> /// <param name="args">The arguments used to populate this resource's properties</param> /// <param name="options">A bag of options that control this resource's behavior</param> public SqlInjectionMatchSet(string name, SqlInjectionMatchSetArgs? args = null, CustomResourceOptions? options = null) : base("aws:waf/sqlInjectionMatchSet:SqlInjectionMatchSet", name, args ?? new SqlInjectionMatchSetArgs(), MakeResourceOptions(options, "")) { } private SqlInjectionMatchSet(string name, Input<string> id, SqlInjectionMatchSetState? state = null, CustomResourceOptions? options = null) : base("aws:waf/sqlInjectionMatchSet:SqlInjectionMatchSet", name, state, MakeResourceOptions(options, id)) { } private static CustomResourceOptions MakeResourceOptions(CustomResourceOptions? options, Input<string>? id) { var defaultOptions = new CustomResourceOptions { Version = Utilities.Version, }; var merged = CustomResourceOptions.Merge(defaultOptions, options); // Override the ID if one was specified for consistency with other language SDKs. merged.Id = id ?? merged.Id; return merged; } /// <summary> /// Get an existing SqlInjectionMatchSet resource's state with the given name, ID, and optional extra /// properties used to qualify the lookup. /// </summary> /// /// <param name="name">The unique name of the resulting resource.</param> /// <param name="id">The unique provider ID of the resource to lookup.</param> /// <param name="state">Any extra arguments used during the lookup.</param> /// <param name="options">A bag of options that control this resource's behavior</param> public static SqlInjectionMatchSet Get(string name, Input<string> id, SqlInjectionMatchSetState? state = null, CustomResourceOptions? options = null) { return new SqlInjectionMatchSet(name, id, state, options); } } public sealed class SqlInjectionMatchSetArgs : Pulumi.ResourceArgs { /// <summary> /// The name or description of the SQL Injection Match Set. /// </summary> [Input("name")] public Input<string>? Name { get; set; } [Input("sqlInjectionMatchTuples")] private InputList<Inputs.SqlInjectionMatchSetSqlInjectionMatchTupleArgs>? _sqlInjectionMatchTuples; /// <summary> /// The parts of web requests that you want AWS WAF to inspect for malicious SQL code and, if you want AWS WAF to inspect a header, the name of the header. /// </summary> public InputList<Inputs.SqlInjectionMatchSetSqlInjectionMatchTupleArgs> SqlInjectionMatchTuples { get => _sqlInjectionMatchTuples ?? (_sqlInjectionMatchTuples = new InputList<Inputs.SqlInjectionMatchSetSqlInjectionMatchTupleArgs>()); set => _sqlInjectionMatchTuples = value; } public SqlInjectionMatchSetArgs() { } } public sealed class SqlInjectionMatchSetState : Pulumi.ResourceArgs { /// <summary> /// The name or description of the SQL Injection Match Set. /// </summary> [Input("name")] public Input<string>? Name { get; set; } [Input("sqlInjectionMatchTuples")] private InputList<Inputs.SqlInjectionMatchSetSqlInjectionMatchTupleGetArgs>? _sqlInjectionMatchTuples; /// <summary> /// The parts of web requests that you want AWS WAF to inspect for malicious SQL code and, if you want AWS WAF to inspect a header, the name of the header. /// </summary> public InputList<Inputs.SqlInjectionMatchSetSqlInjectionMatchTupleGetArgs> SqlInjectionMatchTuples { get => _sqlInjectionMatchTuples ?? (_sqlInjectionMatchTuples = new InputList<Inputs.SqlInjectionMatchSetSqlInjectionMatchTupleGetArgs>()); set => _sqlInjectionMatchTuples = value; } public SqlInjectionMatchSetState() { } } }
42.391304
163
0.622125
[ "ECL-2.0", "Apache-2.0" ]
RafalSumislawski/pulumi-aws
sdk/dotnet/Waf/SqlInjectionMatchSet.cs
6,825
C#
using System.Collections.Generic; #pragma warning disable 1591 namespace Simple.OData.Client { public class ReferenceLink { public string LinkName { get; set; } public object LinkData { get; set; } public string ContentId { get; set; } } public class EntryDetails { private readonly IDictionary<string, object> _properties = new Dictionary<string, object>(); private readonly IDictionary<string, List<ReferenceLink>> _links = new Dictionary<string, List<ReferenceLink>>(); public IDictionary<string, object> Properties { get { return _properties; } } public IDictionary<string, List<ReferenceLink>> Links { get { return _links; } } public bool HasOpenTypeProperties { get; set; } public void AddProperty(string propertyName, object propertyValue) { _properties.Add(propertyName, propertyValue); } public void AddLink(string linkName, object linkData, string contentId = null) { if (!_links.TryGetValue(linkName, out var links)) { links = new List<ReferenceLink>(); _links.Add(linkName, links); } links.Add(new ReferenceLink() { LinkName = linkName, LinkData = linkData, ContentId = contentId }); } } }
33.45
121
0.632287
[ "MIT" ]
3-PRO/Simple.OData.Client
src/Simple.OData.Client.Core/EntryDetails.cs
1,340
C#
/******************************************************************************* * * Copyright (c) {2003-2019} Murex S.A.S. and its affiliates. * All rights reserved. This program and the accompanying materials * are made available under the terms of the MIT License * which accompanies this distribution, and is available at * https://opensource.org/licenses/MIT * *******************************************************************************/ namespace Application.Domain.Book { public enum Genre { HorrorFiction, Thriller, DarkFantasy, Mystery, AdventureFiction, NonFiction, Romance } }
27.875
81
0.500747
[ "MIT" ]
PrivateCodeRetreat2/mikado-testbuilders-kata
csharp/Application/Domain/Book/Genre.cs
669
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Threading; using BuildCaddyShared; namespace TestSuite { class Program { public class ServerListener : INetworkServerListener { public void OnPeerConnect() { } public void OnPeerDisconnect() { } public void OnPeerReceive( Message message ) { Console.WriteLine( "[RECV] " + message.GetOperation() + " " + message.GetMessage() ); } } static void Main(string[] args) { if ( args.Length == 0 ) { return; } if ( args[0].CompareTo( "server" ) == 0 ) { NetworkServer server = new NetworkServer(); server.Start( 25001, 2, "BuildCaddyTest"); if ( server.Active == false ) { Console.WriteLine("Server failed to start..."); } Console.WriteLine( "Press any key to stop..." ); while( !Console.KeyAvailable ) { server.Update(); Thread.Sleep( 100 ); } server.Stop(); return; } if ( args[0].CompareTo( "client" ) == 0 ) { NetworkClient client = new NetworkClient(); client.Connect( "127.0.0.1", 25001, "BuildCaddyTest" ); Console.WriteLine( "Press any key to quit..." ); while( !Console.KeyAvailable ) { client.Update(); Thread.Sleep( 100 ); } client.Stop(); return; } if ( args[0].CompareTo( "supervisor" ) == 0 ) { NetworkServer server = new NetworkServer(); server.Start( 25001, 2, "BuildCaddyTest"); if ( server.Active == false ) { Console.WriteLine("Server failed to start..."); } ServerListener listener = new ServerListener(); server.SetListener( listener ); Console.WriteLine( "Press any key to stop..." ); while( !Console.KeyAvailable ) { server.Update(); Thread.Sleep( 100 ); } server.Stop(); return; } } } }
18.715686
89
0.59979
[ "MIT" ]
bargle/BuildCaddy
TestSuite/Program.cs
1,911
C#
using System.Collections.Generic; using Obvs.Types; namespace Obvs.Integrations.Slack.Messages { public class GetSlackUsersResponse : IResponse, ISlackIntegrationMessage { public string RequestId { get; set; } public string RequesterId { get; set; } public List<User> Users { get; set; } public GetSlackUsersResponse() { Users = new List<User>(); } public class User { public string Id { get; set; } public string Name { get; set; } } } }
24.391304
76
0.582888
[ "MIT" ]
SpocWeb/Obvs
Obvs.Integrations.Slack/Messages/GetSlackUsersResponse.cs
561
C#
using MediatR; namespace Advertising.Application.Queries { public interface IQuery<out TResult> : IRequest<TResult> { } }
15.111111
60
0.705882
[ "MIT" ]
burakkirbag/advertising-api
src/Advertising.Common/Application/Queries/IQuery.cs
138
C#
using System; using Sitecore.Configuration; namespace Sitecore.React { public static class Constants { public const string ExtensionsAssemblyFileName = "Sitecore.Pathfinder.Checker.dll"; public const string SafeProjectUniqueIdRegex = @"[^a-zA-Z0-9_\.]"; public static readonly char[] Comma = { ',' }; } public struct SitecoreCustomCache { public static string CacheName = "Sitecore.React.CustomCache"; public static bool Enabled => bool.Parse(Settings.GetSetting("Sitecore.React.CustomCache.Enabled", "true")); public static long CacheSize => StringUtil.ParseSizeString(Settings.GetSetting("Sitecore.React.CustomCache.MaxSize", "10MB")); } }
25.962963
134
0.717546
[ "MIT" ]
Aceik/sitecore.react
src/Sitecore.React/Constants.cs
703
C#
using System; using System.Collections.Generic; using Foundation; using Plugin.Toast.IOS; using UIKit; using UserNotifications; namespace Plugin.Toast { public static partial class Platform { /// <summary> /// You must call this function if you want to receive an event received at application startup. /// Place call inside FinishedLaunching function. /// </summary> /// <param name="app"></param> /// <param name="options"></param> public static void OnActivated(UIApplication app, NSDictionary options) { UNUserNotificationCenter.Current.Delegate = new TemproraryNotificationCenterDelegate(AddPendingEvent); } } }
29.791667
114
0.672727
[ "MIT" ]
anton-yashin/Plugin.Toast
src/Plugin.Toast/Platform.ios.cs
717
C#
namespace AutoRest.CSharp.LoadBalanced.Json { public delegate bool TryParser<in TSource, TTarget>(TSource source, out TTarget target); }
35.25
92
0.787234
[ "MIT" ]
agoda-com/autorest
src/generator/AutoRest.CSharp.LoadBalanced.Json/TryParser.cs
143
C#
using System; using System.Collections.Generic; using System.Text; namespace StrykerDG.FarmForge.Actors.Units.Messages { public class AskToDeleteUnitType { public int UnitTypeId { get; private set; } public AskToDeleteUnitType(int id) { UnitTypeId = id; } } }
18.764706
51
0.642633
[ "MIT" ]
StrykerDG/StrykerDG.FarmForge
StrykerDG.FarmForge.Actors/Units/Messages/AskToDeleteUnitType.cs
321
C#
using System; using System.Text; using Bing.Data.Queries; using Bing.Data.Queries.Conditions; using Bing.Tests.Samples; using Xunit; namespace Bing.Tests.Datas.Queries.Criterias { /// <summary> /// 测试日期范围过滤条件 - 包含时间 /// </summary> public class DateTimeSegmentCriteriaTest { /// <summary> /// 最小日期 /// </summary> private readonly DateTime? _min; /// <summary> /// 最大日期 /// </summary> private readonly DateTime? _max; /// <summary> /// 测试初始化 /// </summary> public DateTimeSegmentCriteriaTest() { _min = DateTime.Parse("2000-1-1 10:10:10"); _max = DateTime.Parse("2000-1-2 10:10:10"); } /// <summary> /// 测试 - 获取查询条件 /// </summary> [Fact] public void Test_GetPredicate() { var result = new StringBuilder(); result.Append("t => ((t.DateValue >= Convert(Parse(\"2000/1/1 10:10:10\"), DateTime))"); result.Append(" AndAlso (t.DateValue <= Convert(Parse(\"2000/1/2 10:10:10\"), DateTime)))"); var criteria = new DateTimeSegmentCondition<AggregateRootSample, DateTime>(t => t.DateValue, _min, _max); Assert.Equal(result.ToString(), criteria.GetCondition().ToString()); result = new StringBuilder(); result.Append("t => ((t.NullableDateValue >= Convert(Parse(\"2000/1/1 10:10:10\"), Nullable`1))"); result.Append(" AndAlso (t.NullableDateValue <= Convert(Parse(\"2000/1/2 10:10:10\"), Nullable`1)))"); var criteria2 = new DateTimeSegmentCondition<AggregateRootSample, DateTime?>(t => t.NullableDateValue, _min, _max); Assert.Equal(result.ToString(), criteria2.GetCondition().ToString()); } /// <summary> /// 测试 - 获取查询条件 - 设置边界 /// </summary> [Fact] public void Test_GetPredicate_Boundary() { var result = new StringBuilder(); result.Append("t => ((t.DateValue > Convert(Parse(\"2000/1/1 10:10:10\"), DateTime))"); result.Append(" AndAlso (t.DateValue < Convert(Parse(\"2000/1/2 10:10:10\"), DateTime)))"); var criteria = new DateTimeSegmentCondition<AggregateRootSample, DateTime>(t => t.DateValue, _min, _max, Boundary.Neither); Assert.Equal(result.ToString(), criteria.GetCondition().ToString()); result = new StringBuilder(); result.Append("t => ((t.DateValue >= Convert(Parse(\"2000/1/1 10:10:10\"), DateTime))"); result.Append(" AndAlso (t.DateValue < Convert(Parse(\"2000/1/2 10:10:10\"), DateTime)))"); criteria = new DateTimeSegmentCondition<AggregateRootSample, DateTime>(t => t.DateValue, _min, _max, Boundary.Left); Assert.Equal(result.ToString(), criteria.GetCondition().ToString()); result = new StringBuilder(); result.Append("t => ((t.NullableDateValue > Convert(Parse(\"2000/1/1 10:10:10\"), Nullable`1))"); result.Append(" AndAlso (t.NullableDateValue <= Convert(Parse(\"2000/1/2 10:10:10\"), Nullable`1)))"); var criteria2 = new DateTimeSegmentCondition<AggregateRootSample, DateTime?>(t => t.NullableDateValue, _min, _max, Boundary.Right); Assert.Equal(result.ToString(), criteria2.GetCondition().ToString()); result = new StringBuilder(); result.Append("t => ((t.NullableDateValue >= Convert(Parse(\"2000/1/1 10:10:10\"), Nullable`1))"); result.Append(" AndAlso (t.NullableDateValue <= Convert(Parse(\"2000/1/2 10:10:10\"), Nullable`1)))"); criteria2 = new DateTimeSegmentCondition<AggregateRootSample, DateTime?>(t => t.NullableDateValue, _min, _max, Boundary.Both); Assert.Equal(result.ToString(), criteria2.GetCondition().ToString()); } } }
46.380952
143
0.594713
[ "MIT" ]
bing-framework/Bing.NetCode
framework/tests/Bing.Tests/Datas/Queries/Criterias/DateTimeSegmentCriteriaTest.cs
3,992
C#
using System.ComponentModel.Composition; using Microsoft.VisualStudio.Text; using Microsoft.VisualStudio.Text.Tagging; using Microsoft.VisualStudio.Utilities; namespace PackageSecurity { [Export(typeof(ITaggerProvider))] [ContentType("json")] [TagType(typeof(AlertTag))] class AlertTaggerProvider : ITaggerProvider { [Import] private ITextDocumentFactoryService DocumentService { get; set; } public ITagger<T> CreateTagger<T>(ITextBuffer buffer) where T : ITag { ITextDocument doc; if (!DocumentService.TryGetTextDocument(buffer, out doc) || !doc.IsFileSupported()) return null; PackageSecurityPackage.LoadPackage(); return new AlertTagger() as ITagger<T>; //return buffer.Properties.GetOrCreateSingletonProperty(() => new AlertTagger()) as ITagger<T>; } } }
29.225806
107
0.669978
[ "Apache-2.0" ]
madskristensen/PackageSecurity
src/Tagger/AlertTaggerProvider.cs
908
C#
namespace ytSendMail { partial class frmConfig { /// <summary> /// 必需的设计器变量。 /// </summary> private System.ComponentModel.IContainer components = null; /// <summary> /// 清理所有正在使用的资源。 /// </summary> /// <param name="disposing">如果应释放托管资源,为 true;否则为 false。</param> protected override void Dispose(bool disposing) { if (disposing && (components != null)) { components.Dispose(); } base.Dispose(disposing); } #region Windows 窗体设计器生成的代码 /// <summary> /// 设计器支持所需的方法 - 不要 /// 使用代码编辑器修改此方法的内容。 /// </summary> private void InitializeComponent() { System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(frmConfig)); this.label1 = new System.Windows.Forms.Label(); this.label2 = new System.Windows.Forms.Label(); this.label3 = new System.Windows.Forms.Label(); this.label4 = new System.Windows.Forms.Label(); this.groupBox1 = new System.Windows.Forms.GroupBox(); this.txtServerIP = new System.Windows.Forms.TextBox(); this.txtExitPwd = new System.Windows.Forms.TextBox(); this.txtRowCount = new System.Windows.Forms.TextBox(); this.txtLogCount = new System.Windows.Forms.TextBox(); this.btnOK = new System.Windows.Forms.Button(); this.btnCancel = new System.Windows.Forms.Button(); this.groupBox1.SuspendLayout(); this.SuspendLayout(); // // label1 // this.label1.AutoSize = true; this.label1.Location = new System.Drawing.Point(25, 28); this.label1.Name = "label1"; this.label1.Size = new System.Drawing.Size(101, 12); this.label1.TabIndex = 0; this.label1.Text = "日志显示最大行数"; // // label2 // this.label2.AutoSize = true; this.label2.Location = new System.Drawing.Point(25, 55); this.label2.Name = "label2"; this.label2.Size = new System.Drawing.Size(101, 12); this.label2.TabIndex = 1; this.label2.Text = "每次提取记录条数"; // // label3 // this.label3.AutoSize = true; this.label3.Location = new System.Drawing.Point(73, 85); this.label3.Name = "label3"; this.label3.Size = new System.Drawing.Size(53, 12); this.label3.TabIndex = 2; this.label3.Text = "退出口令"; // // label4 // this.label4.AutoSize = true; this.label4.Location = new System.Drawing.Point(25, 114); this.label4.Name = "label4"; this.label4.Size = new System.Drawing.Size(101, 12); this.label4.TabIndex = 3; this.label4.Text = "数据库连接字符串"; // // groupBox1 // this.groupBox1.Controls.Add(this.txtServerIP); this.groupBox1.Controls.Add(this.txtExitPwd); this.groupBox1.Controls.Add(this.txtRowCount); this.groupBox1.Controls.Add(this.label4); this.groupBox1.Controls.Add(this.txtLogCount); this.groupBox1.Controls.Add(this.label1); this.groupBox1.Controls.Add(this.label2); this.groupBox1.Controls.Add(this.label3); this.groupBox1.Location = new System.Drawing.Point(12, 12); this.groupBox1.Name = "groupBox1"; this.groupBox1.Size = new System.Drawing.Size(283, 145); this.groupBox1.TabIndex = 4; this.groupBox1.TabStop = false; // // txtServerIP // this.txtServerIP.Location = new System.Drawing.Point(132, 108); this.txtServerIP.Name = "txtServerIP"; this.txtServerIP.Size = new System.Drawing.Size(128, 21); this.txtServerIP.TabIndex = 4; // // txtExitPwd // this.txtExitPwd.Location = new System.Drawing.Point(132, 78); this.txtExitPwd.Name = "txtExitPwd"; this.txtExitPwd.Size = new System.Drawing.Size(128, 21); this.txtExitPwd.TabIndex = 3; // // txtRowCount // this.txtRowCount.Location = new System.Drawing.Point(132, 49); this.txtRowCount.Name = "txtRowCount"; this.txtRowCount.Size = new System.Drawing.Size(128, 21); this.txtRowCount.TabIndex = 2; // // txtLogCount // this.txtLogCount.Location = new System.Drawing.Point(132, 20); this.txtLogCount.Name = "txtLogCount"; this.txtLogCount.Size = new System.Drawing.Size(128, 21); this.txtLogCount.TabIndex = 1; // // btnOK // this.btnOK.Location = new System.Drawing.Point(68, 168); this.btnOK.Name = "btnOK"; this.btnOK.Size = new System.Drawing.Size(75, 23); this.btnOK.TabIndex = 5; this.btnOK.Text = "确定"; this.btnOK.UseVisualStyleBackColor = true; this.btnOK.Click += new System.EventHandler(this.btnOK_Click); // // btnCancel // this.btnCancel.DialogResult = System.Windows.Forms.DialogResult.Cancel; this.btnCancel.Location = new System.Drawing.Point(168, 168); this.btnCancel.Name = "btnCancel"; this.btnCancel.Size = new System.Drawing.Size(75, 23); this.btnCancel.TabIndex = 6; this.btnCancel.Text = "取消"; this.btnCancel.UseVisualStyleBackColor = true; // // frmConfig // this.AcceptButton = this.btnOK; this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 12F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.CancelButton = this.btnCancel; this.ClientSize = new System.Drawing.Size(308, 201); this.Controls.Add(this.btnCancel); this.Controls.Add(this.btnOK); this.Controls.Add(this.groupBox1); this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedSingle; this.Icon = ((System.Drawing.Icon)(resources.GetObject("$this.Icon"))); this.MaximizeBox = false; this.MinimizeBox = false; this.Name = "frmConfig"; this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen; this.Text = "配置"; this.Load += new System.EventHandler(this.frmConfig_Load); this.groupBox1.ResumeLayout(false); this.groupBox1.PerformLayout(); this.ResumeLayout(false); } #endregion private System.Windows.Forms.Label label1; private System.Windows.Forms.Label label2; private System.Windows.Forms.Label label3; private System.Windows.Forms.Label label4; private System.Windows.Forms.GroupBox groupBox1; private System.Windows.Forms.TextBox txtExitPwd; private System.Windows.Forms.TextBox txtRowCount; private System.Windows.Forms.TextBox txtLogCount; private System.Windows.Forms.TextBox txtServerIP; private System.Windows.Forms.Button btnOK; private System.Windows.Forms.Button btnCancel; } }
41.706522
141
0.563331
[ "MIT" ]
callbin/SendEmail
ytSendMail/frmConfig.Designer.cs
7,894
C#
using System.Collections; using System.Collections.ObjectModel; using WALauncher.Utils; namespace WALauncher.ViewModels.WapkgObjects { public class PackageGroup : ViewModelBase { public string Name { get; } public ObservableCollection<AvailablePackage> Packages { get; } public PackageGroup(string name) { Name = name; Packages = new ObservableCollection<AvailablePackage>(); } public void Push(IEnumerable pkgs) { if(pkgs == null) { return; } Packages.Clear(); foreach (var x in pkgs) { var pkg = x as AvailablePackage; if (pkg != null) { Packages.Add(pkg); } } } } }
23.189189
71
0.501166
[ "Apache-2.0" ]
MEDVEDx64/WALauncher
WALauncher/ViewModels/WapkgObjects/PackageGroup.cs
860
C#
using Order.Infrastructure.Enumaration; namespace Order.Domain.Enums { public class CourierTypeEnum: Enumaration { public static readonly CourierTypeEnum CarCourier = new CourierTypeEnum(1, "CarCourier"); public static readonly CourierTypeEnum MotorCourier = new CourierTypeEnum(2, "MotorCourier"); private CourierTypeEnum(int id, string name) : base(id, name) { } public static CourierTypeEnum Create(int id) { return id switch { 1 => CourierTypeEnum.CarCourier, 2 => CourierTypeEnum.MotorCourier, _ => CourierTypeEnum.CarCourier }; } public CourierTypeEnum() { } } }
32.086957
101
0.608401
[ "MIT" ]
MrBugra/EventSourcing.Order
Order.Domain/Enums/CourierTypeEnum.cs
740
C#
using HavenSoft.HexManiac.Core.Models; using HavenSoft.HexManiac.Core.Models.Runs; using HavenSoft.HexManiac.Core.Models.Runs.Factory; using HavenSoft.HexManiac.Core.ViewModels.DataFormats; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using System.Windows.Input; namespace HavenSoft.HexManiac.Core.ViewModels.Tools { public abstract class StreamElementViewModel : ViewModelCore, IStreamArrayElementViewModel { public ViewPort ViewPort { get; } public IDataModel Model { get; } public int Start { get; protected set; } public string RunFormat { get; protected set; } private bool visible = true; public bool Visible { get => visible; set => Set(ref visible, value); } public ICommand Undo { get; } public ICommand Redo { get; } #region IStreamArrayElementViewModel Properties public bool ShowContent => UsageCount != 0; private int usageCount; public int UsageCount { get => usageCount; set { if (!TryUpdate(ref usageCount, value)) return; NotifyPropertyChanged(nameof(ShowContent)); NotifyPropertyChanged(nameof(CanRepoint)); NotifyPropertyChanged(nameof(CanRepointAll)); NotifyPropertyChanged(nameof(HasMultipleUses)); NotifyPropertyChanged(nameof(CanCreateNew)); repoint.CanExecuteChanged.Invoke(repoint, EventArgs.Empty); createNew.CanExecuteChanged.Invoke(createNew, EventArgs.Empty); } } public bool HasMultipleUses => UsageCount > 1; public bool CanRepoint => !CanCreateNew && (UsageCount > 1 || DataIsValidButNoRun || DataIsNotValid); public bool CanRepointAll => UsageCount > 2; public bool DataIsValidButNoRun { get { var destination = Model.ReadPointer(Start); if (destination < 0 || destination >= Model.Count) return false; var run = Model.GetNextRun(destination); if (run.Start == destination) return false; run = new NoInfoRun(destination, new SortedSpan<int>(Start)); var error = FormatRunFactory.GetStrategy(RunFormat).TryParseData(Model, string.Empty, destination, ref run); return !error.HasError; } } public bool DataIsNotValid { get { var destination = Model.ReadPointer(Start); if (destination < 0 || destination >= Model.Count) return true; var run = Model.GetNextRun(destination); if (run.Start != destination) return true; using (ModelCacheScope.CreateScope(Model)) { var error = FormatRunFactory.GetStrategy(RunFormat).TryParseData(Model, string.Empty, destination, ref run); return error.HasError; } } } public IReadOnlyList<AutocompleteItem> GetAutoCompleteOptions(string line, int caretLineIndex, int caretCharacterIndex) { var destination = Model.ReadPointer(Start); if (Model.GetNextRun(destination) is IStreamRun streamRun) { var options = streamRun.GetAutoCompleteOptions(line, caretLineIndex, caretCharacterIndex); if (options != null && options.Count > 0) ZIndex = 1; return options; } else { return new List<AutocompleteItem>(); } } public void ClearAutocomplete() => ZIndex = 0; private readonly StubCommand repoint = new StubCommand(); public ICommand Repoint => repoint; private readonly StubCommand repointAll = new StubCommand(); public ICommand RepointAll => repointAll; public bool CanCreateNew => UsageCount == 0; private readonly StubCommand createNew = new StubCommand(); public ICommand CreateNew => createNew; public bool IsInError => !string.IsNullOrEmpty(ErrorText); private string errorText; public string ErrorText { get => errorText; set => TryUpdate(ref errorText, value); } private int zIndex; public int ZIndex { get => zIndex; private set => Set(ref zIndex, value); } private EventHandler<(int originalStart, int newStart)> dataMoved; public event EventHandler<(int originalStart, int newStart)> DataMoved { add => dataMoved += value; remove => dataMoved -= value; } protected void RaiseDataMoved(int originalStart, int newStart) => dataMoved?.Invoke(this, (originalStart, newStart)); private EventHandler dataChanged; public event EventHandler DataChanged { add => dataChanged += value; remove => dataChanged -= value; } protected void RaiseDataChanged() => dataChanged?.Invoke(this, EventArgs.Empty); #endregion public StreamElementViewModel(ViewPort viewPort, string runFormat, int start) { ViewPort = viewPort; Model = viewPort.Model; Start = start; RunFormat = runFormat; Undo = ViewPort.Undo; Redo = ViewPort.Redo; repoint.CanExecute = arg => CanRepoint; repoint.Execute = ExecuteRepoint; repointAll.CanExecute = arg => CanRepointAll; repointAll.Execute = ExecuteRepointAll; createNew.CanExecute = arg => CanCreateNew; createNew.Execute = ExecuteCreateNew; // by the time we get this far, we're nearly guaranteed that this will be a IStreamRun. // if it's not an IStreamRun, it's because the pointer in the array doesn't actually point to a valid stream. // (It might point to an IPagedRun or some other stream-like element.) // at which point, we don't want to display any content. var destination = Model.ReadPointer(Start); if (destination == Pointer.NULL) { UsageCount = 0; } else { var run = Model.GetNextRun(destination) as IStreamRun; UsageCount = run?.PointerSources?.Count ?? 0; } } #region TryCopy // if the source of the copy attempt is a datachange that I triggered myself, then ignore the copy and keep the same contents. private bool overrideCopyAttempt; public bool TryCopy(IArrayElementViewModel other) { if (!(other is StreamElementViewModel that)) return false; if (overrideCopyAttempt) return true; if (!TryCopy(that)) return false; UsageCount = that.UsageCount; ErrorText = that.ErrorText; dataMoved = that.dataMoved; dataChanged = that.dataChanged; Start = that.Start; RunFormat = that.RunFormat; Visible = other.Visible; NotifyPropertyChanged(nameof(CanRepoint)); NotifyPropertyChanged(nameof(CanRepointAll)); repoint.RaiseCanExecuteChanged(); NotifyPropertyChanged(nameof(DataIsValidButNoRun)); return true; } protected IDisposable PreventSelfCopy() { overrideCopyAttempt = true; return new StubDisposable { Dispose = () => overrideCopyAttempt = false }; } protected abstract bool TryCopy(StreamElementViewModel other); #endregion private void ExecuteRepoint(object arg) { ViewPort.RepointToNewCopy(Start); ViewPort.Refresh(); UsageCount = 1; dataChanged?.Invoke(this, EventArgs.Empty); } private void ExecuteRepointAll(object arg) { var destination = Model.ReadPointer(Start); var sources = Model.GetNextRun(destination).PointerSources.Skip(1).ToList(); RepointAllAsync(sources).ContinueWith(completedTask => { ViewPort.ClearProgress(); ViewPort.Refresh(); UsageCount = 1; dataChanged?.Invoke(this, EventArgs.Empty); }, TaskContinuationOptions.ExecuteSynchronously); } private async Task<ErrorInfo> RepointAllAsync(IReadOnlyList<int> sources) { var buffer = ViewPort.Model.FreeSpaceBuffer; ViewPort.Model.FreeSpaceBuffer = 0; var groupSize = Math.Max(1, sources.Count / 100); for (int i = 0; i < sources.Count; i++) { ViewPort.RepointToNewCopy(sources[i]); if (i % groupSize == 0) { await ViewPort.UpdateProgress((i + 1) / (double)sources.Count); } } ViewPort.Model.FreeSpaceBuffer = buffer; return ErrorInfo.NoError; } private void ExecuteCreateNew(object arg) { ViewPort.RepointToNewCopy(Start); ViewPort.Refresh(); UsageCount = 1; dataChanged?.Invoke(this, EventArgs.Empty); } } }
38.855856
137
0.645259
[ "MIT" ]
haven1433/HexManiacAdvance
src/HexManiac.Core/ViewModels/Tools/StreamElementViewModel.cs
8,628
C#
using NUnit.Framework; namespace Mirage { [TestFixture] public class ExponentialMovingAverageTest { [Test] public void TestInitial() { var ema = new ExponentialMovingAverage(10); ema.Add(3); Assert.That(ema.Value, Is.EqualTo(3)); Assert.That(ema.Var, Is.EqualTo(0)); } [Test] public void TestMovingAverage() { var ema = new ExponentialMovingAverage(10); ema.Add(5); ema.Add(6); Assert.That(ema.Value, Is.EqualTo(5.1818).Within(0.0001f)); Assert.That(ema.Var, Is.EqualTo(0.1487).Within(0.0001f)); } [Test] public void TestVar() { var ema = new ExponentialMovingAverage(10); ema.Add(5); ema.Add(6); ema.Add(7); Assert.That(ema.Var, Is.EqualTo(0.6134).Within(0.0001f)); } } }
21.863636
71
0.509356
[ "MIT" ]
HeadClot/Mirage
Assets/Tests/Editor/ExponentialMovingAverageTest.cs
962
C#
//------------------------------------------------------------------------------ // <自动生成> // 此代码由工具生成。 // // 对此文件的更改可能导致不正确的行为,如果 // 重新生成代码,则所做更改将丢失。 // </自动生成> //------------------------------------------------------------------------------ namespace YanZhiwei.JavaScript.Utilities { public partial class JsDemo { /// <summary> /// form1 控件。 /// </summary> /// <remarks> /// 自动生成的字段。 /// 若要进行修改,请将字段声明从设计器文件移到代码隐藏文件。 /// </remarks> protected global::System.Web.UI.HtmlControls.HtmlForm form1; } }
24.16
81
0.379139
[ "MIT" ]
wind2006/DotNet.Utilities
YanZhiwei.JavaScript.Utilities/JsDemo.aspx.designer.cs
790
C#
/* MIT License Copyright (c) 2019: Francesco Dettori, Jacopo Frasson, Riccardo Lombardi, Michele Maione Author: Francesco Dettori 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.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.SceneManagement; using UnityEngine.UI; public class ArrowPanelOnSpline : PausableMonoBehaviour { public Sprite imageToShow; Image container; Dictionary<GameObject, Transform> playerUIArrows = new Dictionary<GameObject, Transform>(); private void Start() { foreach (var root in SceneManager.GetActiveScene().GetRootGameObjects()) if (root.name.Equals("UI")) for (int i = 0; i < root.transform.childCount; i++) { var c = root.transform.GetChild(i); if (c.CompareTag("PlayerCanvas") && c.gameObject.activeSelf) { var lapManager = c.gameObject.GetComponent<LapManager>(); var arrow = GB.FindTransformInChildWithName(c, "Arrow"); playerUIArrows.Add(lapManager.player, arrow); } } } private void OnTriggerEnter(Collider co) { /*if (co.CompareTag("Player")) { var player = co.transform.root.gameObject; if (playerUIArrows.ContainsKey(player)) { var arrow = playerUIArrows[player]; container = arrow.GetComponent<Image>(); container.sprite = imageToShow; container.enabled = true; StartCoroutine(compareImage()); } }*/ } IEnumerator compareImage() { yield return new WaitForSeconds(2); container.enabled = false; } }
43.4
559
0.663949
[ "MIT" ]
FraDetto/BeStrong-BeTheLas
Project/BeStrongBeTheLast/Assets/Scripts/Global/ArrowPanelOnSpline.cs
2,823
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 bqStart.Data; #nullable disable namespace bqStart.Data.Migrations { [DbContext(typeof(MainDataContext))] [Migration("20220105123524_AddOrderData01")] partial class AddOrderData01 { protected override void BuildTargetModel(ModelBuilder modelBuilder) { #pragma warning disable 612, 618 modelBuilder .HasAnnotation("ProductVersion", "6.0.0") .HasAnnotation("Relational:MaxIdentifierLength", 128); SqlServerModelBuilderExtensions.UseIdentityColumns(modelBuilder, 1L, 1); modelBuilder.Entity("BinaryQuest.Framework.Core.Data.SettingKey", b => { b.Property<string>("Key") .HasColumnType("nvarchar(450)"); b.Property<string>("DisplayName") .IsRequired() .HasMaxLength(50) .HasColumnType("nvarchar(50)"); b.Property<Guid>("SystemSettingId") .HasColumnType("uniqueidentifier"); b.Property<string>("Value") .IsRequired() .HasColumnType("nvarchar(max)"); b.HasKey("Key"); b.HasIndex("SystemSettingId"); b.ToTable("SettingKeys"); }); modelBuilder.Entity("BinaryQuest.Framework.Core.Data.SystemSetting", b => { b.Property<Guid>("Id") .HasColumnType("uniqueidentifier"); b.Property<bool>("IsActive") .HasColumnType("bit"); b.Property<string>("SettingsName") .IsRequired() .HasMaxLength(50) .HasColumnType("nvarchar(50)"); b.HasKey("Id"); b.ToTable("SystemSettings"); }); modelBuilder.Entity("bqStart.Data.ApplicationUser", b => { b.Property<string>("Id") .HasColumnType("nvarchar(450)"); b.Property<int>("AccessFailedCount") .HasColumnType("int"); b.Property<string>("ConcurrencyStamp") .IsConcurrencyToken() .HasColumnType("nvarchar(max)"); b.Property<string>("Email") .HasMaxLength(256) .HasColumnType("nvarchar(256)"); b.Property<bool>("EmailConfirmed") .HasColumnType("bit"); b.Property<string>("FirstName") .IsRequired() .HasMaxLength(255) .HasColumnType("nvarchar(255)"); b.Property<string>("LastName") .IsRequired() .HasMaxLength(255) .HasColumnType("nvarchar(255)"); b.Property<bool>("LockoutEnabled") .HasColumnType("bit"); b.Property<DateTimeOffset?>("LockoutEnd") .HasColumnType("datetimeoffset"); b.Property<string>("NormalizedEmail") .HasMaxLength(256) .HasColumnType("nvarchar(256)"); b.Property<string>("NormalizedUserName") .HasMaxLength(256) .HasColumnType("nvarchar(256)"); b.Property<string>("PasswordHash") .HasColumnType("nvarchar(max)"); b.Property<string>("PhoneNumber") .HasColumnType("nvarchar(max)"); b.Property<bool>("PhoneNumberConfirmed") .HasColumnType("bit"); b.Property<string>("SecurityStamp") .HasColumnType("nvarchar(max)"); b.Property<string>("TimeZoneId") .HasMaxLength(100) .HasColumnType("nvarchar(100)"); b.Property<bool>("TwoFactorEnabled") .HasColumnType("bit"); b.Property<string>("UserName") .HasMaxLength(256) .HasColumnType("nvarchar(256)"); b.HasKey("Id"); b.HasIndex("NormalizedEmail") .HasDatabaseName("EmailIndex"); b.HasIndex("NormalizedUserName") .IsUnique() .HasDatabaseName("UserNameIndex") .HasFilter("[NormalizedUserName] IS NOT NULL"); b.ToTable("AspNetUsers", (string)null); }); modelBuilder.Entity("bqStart.Data.Department", b => { b.Property<int>("Id") .ValueGeneratedOnAdd() .HasColumnType("int"); SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property<int>("Id"), 1L, 1); b.Property<string>("CreatedBy") .HasMaxLength(256) .HasColumnType("nvarchar(256)"); b.Property<DateTime?>("CreatedOn") .HasColumnType("datetime2"); b.Property<string>("DepartmentName") .IsRequired() .HasMaxLength(150) .HasColumnType("nvarchar(150)"); b.Property<string>("ModifiedBy") .HasMaxLength(256) .HasColumnType("nvarchar(256)"); b.Property<DateTime?>("ModifiedOn") .HasColumnType("datetime2"); b.HasKey("Id"); b.ToTable("Departments"); }); modelBuilder.Entity("bqStart.Data.ExampleClass", b => { b.Property<int>("Id") .ValueGeneratedOnAdd() .HasColumnType("int"); SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property<int>("Id"), 1L, 1); b.Property<DateTime?>("ClassDate") .HasColumnType("datetime2"); b.Property<string>("ClassName") .IsRequired() .HasMaxLength(200) .HasColumnType("nvarchar(200)"); b.Property<string>("CreatedBy") .HasMaxLength(256) .HasColumnType("nvarchar(256)"); b.Property<DateTime?>("CreatedOn") .HasColumnType("datetime2"); b.Property<int>("DepartmentId") .HasColumnType("int"); b.Property<bool>("IsActive") .HasColumnType("bit"); b.Property<string>("ModifiedBy") .HasMaxLength(256) .HasColumnType("nvarchar(256)"); b.Property<DateTime?>("ModifiedOn") .HasColumnType("datetime2"); b.HasKey("Id"); b.HasIndex("DepartmentId"); b.ToTable("ExampleClasses"); }); modelBuilder.Entity("bqStart.Data.Order", b => { b.Property<int>("Id") .ValueGeneratedOnAdd() .HasColumnType("int"); SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property<int>("Id"), 1L, 1); b.Property<string>("CreatedBy") .HasMaxLength(256) .HasColumnType("nvarchar(256)"); b.Property<DateTime?>("CreatedOn") .HasColumnType("datetime2"); b.Property<string>("CustomerName") .IsRequired() .HasColumnType("nvarchar(max)"); b.Property<string>("ModifiedBy") .HasMaxLength(256) .HasColumnType("nvarchar(256)"); b.Property<DateTime?>("ModifiedOn") .HasColumnType("datetime2"); b.Property<int>("OrderDate") .HasColumnType("int"); b.Property<int>("Total") .HasColumnType("int"); b.HasKey("Id"); b.ToTable("Orders"); }); modelBuilder.Entity("bqStart.Data.OrderDetail", b => { b.Property<int>("Id") .ValueGeneratedOnAdd() .HasColumnType("int"); SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property<int>("Id"), 1L, 1); b.Property<string>("CreatedBy") .HasMaxLength(256) .HasColumnType("nvarchar(256)"); b.Property<DateTime?>("CreatedOn") .HasColumnType("datetime2"); b.Property<string>("ModifiedBy") .HasMaxLength(256) .HasColumnType("nvarchar(256)"); b.Property<DateTime?>("ModifiedOn") .HasColumnType("datetime2"); b.Property<int>("OrderId") .HasColumnType("int"); b.Property<int>("Price") .HasColumnType("int"); b.Property<int>("Qty") .HasColumnType("int"); b.HasKey("Id"); b.HasIndex("OrderId"); b.ToTable("OrderDetails"); }); modelBuilder.Entity("Duende.IdentityServer.EntityFramework.Entities.DeviceFlowCodes", b => { b.Property<string>("UserCode") .HasMaxLength(200) .HasColumnType("nvarchar(200)"); b.Property<string>("ClientId") .IsRequired() .HasMaxLength(200) .HasColumnType("nvarchar(200)"); b.Property<DateTime>("CreationTime") .HasColumnType("datetime2"); b.Property<string>("Data") .IsRequired() .HasMaxLength(50000) .HasColumnType("nvarchar(max)"); b.Property<string>("Description") .HasMaxLength(200) .HasColumnType("nvarchar(200)"); b.Property<string>("DeviceCode") .IsRequired() .HasMaxLength(200) .HasColumnType("nvarchar(200)"); b.Property<DateTime?>("Expiration") .IsRequired() .HasColumnType("datetime2"); b.Property<string>("SessionId") .HasMaxLength(100) .HasColumnType("nvarchar(100)"); b.Property<string>("SubjectId") .HasMaxLength(200) .HasColumnType("nvarchar(200)"); b.HasKey("UserCode"); b.HasIndex("DeviceCode") .IsUnique(); b.HasIndex("Expiration"); b.ToTable("DeviceCodes", (string)null); }); modelBuilder.Entity("Duende.IdentityServer.EntityFramework.Entities.Key", b => { b.Property<string>("Id") .HasColumnType("nvarchar(450)"); b.Property<string>("Algorithm") .IsRequired() .HasMaxLength(100) .HasColumnType("nvarchar(100)"); b.Property<DateTime>("Created") .HasColumnType("datetime2"); b.Property<string>("Data") .IsRequired() .HasColumnType("nvarchar(max)"); b.Property<bool>("DataProtected") .HasColumnType("bit"); b.Property<bool>("IsX509Certificate") .HasColumnType("bit"); b.Property<string>("Use") .HasColumnType("nvarchar(450)"); b.Property<int>("Version") .HasColumnType("int"); b.HasKey("Id"); b.HasIndex("Use"); b.ToTable("Keys"); }); modelBuilder.Entity("Duende.IdentityServer.EntityFramework.Entities.PersistedGrant", b => { b.Property<string>("Key") .HasMaxLength(200) .HasColumnType("nvarchar(200)"); b.Property<string>("ClientId") .IsRequired() .HasMaxLength(200) .HasColumnType("nvarchar(200)"); b.Property<DateTime?>("ConsumedTime") .HasColumnType("datetime2"); b.Property<DateTime>("CreationTime") .HasColumnType("datetime2"); b.Property<string>("Data") .IsRequired() .HasMaxLength(50000) .HasColumnType("nvarchar(max)"); b.Property<string>("Description") .HasMaxLength(200) .HasColumnType("nvarchar(200)"); b.Property<DateTime?>("Expiration") .HasColumnType("datetime2"); b.Property<string>("SessionId") .HasMaxLength(100) .HasColumnType("nvarchar(100)"); b.Property<string>("SubjectId") .HasMaxLength(200) .HasColumnType("nvarchar(200)"); b.Property<string>("Type") .IsRequired() .HasMaxLength(50) .HasColumnType("nvarchar(50)"); b.HasKey("Key"); b.HasIndex("ConsumedTime"); b.HasIndex("Expiration"); b.HasIndex("SubjectId", "ClientId", "Type"); b.HasIndex("SubjectId", "SessionId", "Type"); b.ToTable("PersistedGrants", (string)null); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRole", b => { b.Property<string>("Id") .HasColumnType("nvarchar(450)"); b.Property<string>("ConcurrencyStamp") .IsConcurrencyToken() .HasColumnType("nvarchar(max)"); b.Property<string>("Name") .HasMaxLength(256) .HasColumnType("nvarchar(256)"); b.Property<string>("NormalizedName") .HasMaxLength(256) .HasColumnType("nvarchar(256)"); b.HasKey("Id"); b.HasIndex("NormalizedName") .IsUnique() .HasDatabaseName("RoleNameIndex") .HasFilter("[NormalizedName] IS NOT NULL"); b.ToTable("AspNetRoles", (string)null); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRoleClaim<string>", b => { b.Property<int>("Id") .ValueGeneratedOnAdd() .HasColumnType("int"); SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property<int>("Id"), 1L, 1); b.Property<string>("ClaimType") .HasColumnType("nvarchar(max)"); b.Property<string>("ClaimValue") .HasColumnType("nvarchar(max)"); b.Property<string>("RoleId") .IsRequired() .HasColumnType("nvarchar(450)"); b.HasKey("Id"); b.HasIndex("RoleId"); b.ToTable("AspNetRoleClaims", (string)null); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserClaim<string>", b => { b.Property<int>("Id") .ValueGeneratedOnAdd() .HasColumnType("int"); SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property<int>("Id"), 1L, 1); b.Property<string>("ClaimType") .HasColumnType("nvarchar(max)"); b.Property<string>("ClaimValue") .HasColumnType("nvarchar(max)"); b.Property<string>("UserId") .IsRequired() .HasColumnType("nvarchar(450)"); b.HasKey("Id"); b.HasIndex("UserId"); b.ToTable("AspNetUserClaims", (string)null); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserLogin<string>", b => { b.Property<string>("LoginProvider") .HasMaxLength(128) .HasColumnType("nvarchar(128)"); b.Property<string>("ProviderKey") .HasMaxLength(128) .HasColumnType("nvarchar(128)"); b.Property<string>("ProviderDisplayName") .HasColumnType("nvarchar(max)"); b.Property<string>("UserId") .IsRequired() .HasColumnType("nvarchar(450)"); b.HasKey("LoginProvider", "ProviderKey"); b.HasIndex("UserId"); b.ToTable("AspNetUserLogins", (string)null); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserRole<string>", b => { b.Property<string>("UserId") .HasColumnType("nvarchar(450)"); b.Property<string>("RoleId") .HasColumnType("nvarchar(450)"); b.HasKey("UserId", "RoleId"); b.HasIndex("RoleId"); b.ToTable("AspNetUserRoles", (string)null); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserToken<string>", b => { b.Property<string>("UserId") .HasColumnType("nvarchar(450)"); b.Property<string>("LoginProvider") .HasMaxLength(128) .HasColumnType("nvarchar(128)"); b.Property<string>("Name") .HasMaxLength(128) .HasColumnType("nvarchar(128)"); b.Property<string>("Value") .HasColumnType("nvarchar(max)"); b.HasKey("UserId", "LoginProvider", "Name"); b.ToTable("AspNetUserTokens", (string)null); }); modelBuilder.Entity("BinaryQuest.Framework.Core.Data.SettingKey", b => { b.HasOne("BinaryQuest.Framework.Core.Data.SystemSetting", "SystemSetting") .WithMany("Settings") .HasForeignKey("SystemSettingId") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); b.Navigation("SystemSetting"); }); modelBuilder.Entity("bqStart.Data.ExampleClass", b => { b.HasOne("bqStart.Data.Department", "Department") .WithMany() .HasForeignKey("DepartmentId") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); b.Navigation("Department"); }); modelBuilder.Entity("bqStart.Data.OrderDetail", b => { b.HasOne("bqStart.Data.Order", "Order") .WithMany("Details") .HasForeignKey("OrderId") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); b.Navigation("Order"); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRoleClaim<string>", b => { b.HasOne("Microsoft.AspNetCore.Identity.IdentityRole", null) .WithMany() .HasForeignKey("RoleId") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserClaim<string>", b => { b.HasOne("bqStart.Data.ApplicationUser", null) .WithMany() .HasForeignKey("UserId") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserLogin<string>", b => { b.HasOne("bqStart.Data.ApplicationUser", null) .WithMany() .HasForeignKey("UserId") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserRole<string>", b => { b.HasOne("Microsoft.AspNetCore.Identity.IdentityRole", null) .WithMany() .HasForeignKey("RoleId") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); b.HasOne("bqStart.Data.ApplicationUser", null) .WithMany() .HasForeignKey("UserId") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserToken<string>", b => { b.HasOne("bqStart.Data.ApplicationUser", null) .WithMany() .HasForeignKey("UserId") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); }); modelBuilder.Entity("BinaryQuest.Framework.Core.Data.SystemSetting", b => { b.Navigation("Settings"); }); modelBuilder.Entity("bqStart.Data.Order", b => { b.Navigation("Details"); }); #pragma warning restore 612, 618 } } }
35.967311
103
0.437288
[ "MIT" ]
binaryquest/bqstart
aspnet/src/bqStart/bqStart.Data/Migrations/20220105123524_AddOrderData01.Designer.cs
24,208
C#
using System.IO; using System.Threading.Tasks; namespace RIAppDemo.BLL.Utils { public class FileContent : IDataContent { private readonly string _filePath; public FileContent(string filePath) { _filePath = filePath; } public string FilePath => _filePath; public async Task CopyToAsync(Stream stream, int bufferSize = 131072) { using (FileStream fileStream = File.OpenRead(FilePath)) { await fileStream.CopyToAsync(stream); } } public void CleanUp() { if (File.Exists(FilePath)) { File.Delete(FilePath); } } } }
21.558824
77
0.537517
[ "MIT" ]
BBGONE/JRIApp
DEMOS/RIAppDemoMVC/RIApp.BLL/Utils/FileContent.cs
735
C#
#pragma checksum "E:\.NETProjeto\CadastroAluno\CadatroAluno\Views\Cursos\Details.cshtml" "{ff1816ec-aa5e-4d10-87f7-6f4963833460}" "d14d7ac8390b49bf232da431a759387876bb43cb" // <auto-generated/> #pragma warning disable 1591 [assembly: global::Microsoft.AspNetCore.Razor.Hosting.RazorCompiledItemAttribute(typeof(AspNetCore.Views_Cursos_Details), @"mvc.1.0.view", @"/Views/Cursos/Details.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 "E:\.NETProjeto\CadastroAluno\CadatroAluno\Views\_ViewImports.cshtml" using CadastroAluno; #line default #line hidden #nullable disable #nullable restore #line 2 "E:\.NETProjeto\CadastroAluno\CadatroAluno\Views\_ViewImports.cshtml" using CadastroAluno.Models; #line default #line hidden #nullable disable [global::Microsoft.AspNetCore.Razor.Hosting.RazorSourceChecksumAttribute(@"SHA1", @"d14d7ac8390b49bf232da431a759387876bb43cb", @"/Views/Cursos/Details.cshtml")] [global::Microsoft.AspNetCore.Razor.Hosting.RazorSourceChecksumAttribute(@"SHA1", @"976b5366458955880b0be78d61783b37b307cd3f", @"/Views/_ViewImports.cshtml")] #nullable restore public class Views_Cursos_Details : global::Microsoft.AspNetCore.Mvc.Razor.RazorPage<CadastroAluno.Models.Curso> #nullable disable { private static readonly global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute __tagHelperAttribute_0 = new global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute("asp-action", "Edit", global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes); private static readonly global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute __tagHelperAttribute_1 = new global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute("asp-action", "Index", global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes); #line hidden #pragma warning disable 0649 private global::Microsoft.AspNetCore.Razor.Runtime.TagHelpers.TagHelperExecutionContext __tagHelperExecutionContext; #pragma warning restore 0649 private global::Microsoft.AspNetCore.Razor.Runtime.TagHelpers.TagHelperRunner __tagHelperRunner = new global::Microsoft.AspNetCore.Razor.Runtime.TagHelpers.TagHelperRunner(); #pragma warning disable 0169 private string __tagHelperStringValueBuffer; #pragma warning restore 0169 private global::Microsoft.AspNetCore.Razor.Runtime.TagHelpers.TagHelperScopeManager __backed__tagHelperScopeManager = null; private global::Microsoft.AspNetCore.Razor.Runtime.TagHelpers.TagHelperScopeManager __tagHelperScopeManager { get { if (__backed__tagHelperScopeManager == null) { __backed__tagHelperScopeManager = new global::Microsoft.AspNetCore.Razor.Runtime.TagHelpers.TagHelperScopeManager(StartTagHelperWritingScope, EndTagHelperWritingScope); } return __backed__tagHelperScopeManager; } } private global::Microsoft.AspNetCore.Mvc.TagHelpers.AnchorTagHelper __Microsoft_AspNetCore_Mvc_TagHelpers_AnchorTagHelper; #pragma warning disable 1998 public async override global::System.Threading.Tasks.Task ExecuteAsync() { WriteLiteral("\n"); #nullable restore #line 3 "E:\.NETProjeto\CadastroAluno\CadatroAluno\Views\Cursos\Details.cshtml" ViewData["Title"] = "Detalhes"; #line default #line hidden #nullable disable WriteLiteral("\n<h1>Details</h1>\n\n<div>\n <h4>Curso</h4>\n <hr />\n <dl class=\"row\">\n <dt class = \"col-sm-2\">\n "); #nullable restore #line 14 "E:\.NETProjeto\CadastroAluno\CadatroAluno\Views\Cursos\Details.cshtml" Write(Html.DisplayNameFor(model => model.NomeDoCurso)); #line default #line hidden #nullable disable WriteLiteral("\n </dt>\n <dd class = \"col-sm-10\">\n "); #nullable restore #line 17 "E:\.NETProjeto\CadastroAluno\CadatroAluno\Views\Cursos\Details.cshtml" Write(Html.DisplayFor(model => model.NomeDoCurso)); #line default #line hidden #nullable disable WriteLiteral("\n </dd>\n <dt class = \"col-sm-2\">\n "); #nullable restore #line 20 "E:\.NETProjeto\CadastroAluno\CadatroAluno\Views\Cursos\Details.cshtml" Write(Html.DisplayNameFor(model => model.DiciplinasDoCurso)); #line default #line hidden #nullable disable WriteLiteral("\n </dt>\n <dd class = \"col-sm-10\">\n "); #nullable restore #line 23 "E:\.NETProjeto\CadastroAluno\CadatroAluno\Views\Cursos\Details.cshtml" Write(Html.DisplayFor(model => model.DiciplinasDoCurso)); #line default #line hidden #nullable disable WriteLiteral("\n </dd>\n </dl>\n</div>\n<div>\n "); __tagHelperExecutionContext = __tagHelperScopeManager.Begin("a", global::Microsoft.AspNetCore.Razor.TagHelpers.TagMode.StartTagAndEndTag, "d14d7ac8390b49bf232da431a759387876bb43cb5294", async() => { WriteLiteral("Edit"); } ); __Microsoft_AspNetCore_Mvc_TagHelpers_AnchorTagHelper = CreateTagHelper<global::Microsoft.AspNetCore.Mvc.TagHelpers.AnchorTagHelper>(); __tagHelperExecutionContext.Add(__Microsoft_AspNetCore_Mvc_TagHelpers_AnchorTagHelper); __Microsoft_AspNetCore_Mvc_TagHelpers_AnchorTagHelper.Action = (string)__tagHelperAttribute_0.Value; __tagHelperExecutionContext.AddTagHelperAttribute(__tagHelperAttribute_0); if (__Microsoft_AspNetCore_Mvc_TagHelpers_AnchorTagHelper.RouteValues == null) { throw new InvalidOperationException(InvalidTagHelperIndexerAssignment("asp-route-id", "Microsoft.AspNetCore.Mvc.TagHelpers.AnchorTagHelper", "RouteValues")); } BeginWriteTagHelperAttribute(); #nullable restore #line 28 "E:\.NETProjeto\CadastroAluno\CadatroAluno\Views\Cursos\Details.cshtml" WriteLiteral(Model.Id); #line default #line hidden #nullable disable __tagHelperStringValueBuffer = EndWriteTagHelperAttribute(); __Microsoft_AspNetCore_Mvc_TagHelpers_AnchorTagHelper.RouteValues["id"] = __tagHelperStringValueBuffer; __tagHelperExecutionContext.AddTagHelperAttribute("asp-route-id", __Microsoft_AspNetCore_Mvc_TagHelpers_AnchorTagHelper.RouteValues["id"], global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes); await __tagHelperRunner.RunAsync(__tagHelperExecutionContext); if (!__tagHelperExecutionContext.Output.IsContentModified) { await __tagHelperExecutionContext.SetOutputContentAsync(); } Write(__tagHelperExecutionContext.Output); __tagHelperExecutionContext = __tagHelperScopeManager.End(); WriteLiteral(" |\n "); __tagHelperExecutionContext = __tagHelperScopeManager.Begin("a", global::Microsoft.AspNetCore.Razor.TagHelpers.TagMode.StartTagAndEndTag, "d14d7ac8390b49bf232da431a759387876bb43cb7424", async() => { WriteLiteral("Voltar"); } ); __Microsoft_AspNetCore_Mvc_TagHelpers_AnchorTagHelper = CreateTagHelper<global::Microsoft.AspNetCore.Mvc.TagHelpers.AnchorTagHelper>(); __tagHelperExecutionContext.Add(__Microsoft_AspNetCore_Mvc_TagHelpers_AnchorTagHelper); __Microsoft_AspNetCore_Mvc_TagHelpers_AnchorTagHelper.Action = (string)__tagHelperAttribute_1.Value; __tagHelperExecutionContext.AddTagHelperAttribute(__tagHelperAttribute_1); await __tagHelperRunner.RunAsync(__tagHelperExecutionContext); if (!__tagHelperExecutionContext.Output.IsContentModified) { await __tagHelperExecutionContext.SetOutputContentAsync(); } Write(__tagHelperExecutionContext.Output); __tagHelperExecutionContext = __tagHelperScopeManager.End(); WriteLiteral("\n</div>\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<CadastroAluno.Models.Curso> Html { get; private set; } = default!; #nullable disable } } #pragma warning restore 1591
55.457143
298
0.723751
[ "MIT" ]
Josyas/CadastroAluno
CadatroAluno/obj/Debug/net5.0/Razor/Views/Cursos/Details.cshtml.g.cs
9,705
C#
// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. #nullable enable using System; using System.Collections.Generic; using System.ComponentModel; using System.Threading; using System.Threading.Tasks; using Microsoft.Azure.Quantum.Authentication; using Microsoft.Jupyter.Core; namespace Microsoft.Quantum.IQSharp.AzureClient { /// <summary> /// List of arguments for the event that is triggered when the user tries /// to connect to an Azure Quantum Workspace /// </summary> public class ConnectToWorkspaceEventArgs : EventArgs { /// <summary> /// Default contructor. /// </summary> /// <param name="status">The status of the connection after calling Connect</param> /// <param name="error">If an error happen, the error code.</param> /// <param name="location">Location of the workspace connecting to.</param> /// <param name="useCustomStorage">True if the user provides a custom storage connection.</param> /// <param name="credentialType">The type of credentials used to authenticate with Azure.</param> /// <param name="duration">How long the action took.</param> public ConnectToWorkspaceEventArgs(ExecuteStatus status, AzureClientError? error, string location, bool useCustomStorage, CredentialType credentialType, TimeSpan duration) { this.Status = status; this.Error = error; this.Location =location; this.UseCustomStorage = useCustomStorage; this.CredentialType = credentialType; this.Duration = duration; } /// <summary> /// The connection status. Can be "success" or "error" /// </summary> public ExecuteStatus Status { get; } /// <summary> /// If an error happened during connection, the error code. /// Otherwise, <c>null</c>. /// </summary> public AzureClientError? Error { get; } /// <summary> /// The region (location) we tried to connect to. /// </summary> public string Location { get; } /// <summary> /// True if the user provides a custom storage connection. /// </summary> public bool UseCustomStorage { get; } /// <summary> /// The type of credentials used to authenticate with Azure. /// </summary> public CredentialType CredentialType { get; } /// <summary> /// The total time it took to connect. /// </summary> public TimeSpan Duration { get; } } /// <summary> /// This service is capable of connecting to Azure Quantum workspaces /// and submitting jobs. /// </summary> public interface IAzureClient { /// <summary> /// This event is triggered when a user connects to an Azure Quantum Workspace. /// </summary> event EventHandler<ConnectToWorkspaceEventArgs> ConnectToWorkspace; /// <summary> /// Connects to the specified Azure Quantum workspace, first logging into Azure if necessary. /// </summary> /// <returns> /// The list of execution targets available in the Azure Quantum workspace. /// </returns> public Task<ExecutionResult> ConnectAsync(IChannel channel, string subscriptionId, string resourceGroupName, string workspaceName, string storageAccountConnectionString, string location, CredentialType credentialType, CancellationToken? cancellationToken = null); /// <summary> /// Gets the current connection status to an Azure Quantum workspace. /// </summary> /// <returns> /// The list of execution targets available in the Azure Quantum workspace, /// or an error if the Azure Quantum workspace connection has not yet been created. /// </returns> public Task<ExecutionResult> GetConnectionStatusAsync(IChannel channel, CancellationToken? token); /// <summary> /// Submits the specified Q# operation as a job to the currently active target. /// </summary> /// <returns> /// Details of the submitted job, or an error if submission failed. /// </returns> public Task<ExecutionResult> SubmitJobAsync(IChannel channel, AzureSubmissionContext submissionContext, CancellationToken? token); /// <summary> /// Executes the specified Q# operation as a job to the currently active target /// and waits for execution to complete before returning. /// </summary> /// <returns> /// The result of the executed job, or an error if execution failed. /// </returns> public Task<ExecutionResult> ExecuteJobAsync(IChannel channel, AzureSubmissionContext submissionContext, CancellationToken? token); /// <summary> /// Sets the specified target for job submission. /// </summary> /// <returns> /// Success if the target is valid, or an error if the target cannot be set. /// </returns> public Task<ExecutionResult> SetActiveTargetAsync(IChannel channel, string targetId, CancellationToken? token); /// <summary> /// Gets the currently specified target for job submission. /// </summary> /// <returns> /// The target ID. /// </returns> public Task<ExecutionResult> GetActiveTargetAsync(IChannel channel, CancellationToken? token); /// <summary> /// Gets the result of a specified job. /// </summary> /// <returns> /// The job result corresponding to the given job ID, /// or for the most recently-submitted job if no job ID is provided. /// </returns> public Task<ExecutionResult> GetJobResultAsync(IChannel channel, string jobId, CancellationToken? token); /// <summary> /// Gets the status of a specified job. /// </summary> /// <returns> /// The job status corresponding to the given job ID, /// or for the most recently-submitted job if no job ID is provided. /// </returns> public Task<ExecutionResult> GetJobStatusAsync(IChannel channel, string jobId, CancellationToken? token); /// <summary> /// Gets a list of all jobs in the current Azure Quantum workspace. /// </summary> /// <returns> /// A list of all jobs in the current workspace, optionally filtered /// to jobs with fields containing <c>filter</c> using a case-insensitive /// comparison. /// </returns> public Task<ExecutionResult> GetJobListAsync(IChannel channel, string filter, int? count, CancellationToken? token); /// <summary> /// Gets a list of all jobs in the current Azure Quantum workspace. /// </summary> /// <returns> /// A list of all jobs in the current workspace, optionally filtered /// to jobs with fields containing <c>filter</c> using a case-insensitive /// comparison. /// </returns> public Task<ExecutionResult> GetQuotaListAsync(IChannel channel, CancellationToken? token); /// <summary> /// Returns a string indicating the current target ID if one is /// set, or <c>null</c> if no target is set. /// </summary> string? ActiveTargetId { get; } /// <summary> /// Returns the active workspace connected to this client, or /// <c>null</c> if none is set. /// </summary> Microsoft.Azure.Quantum.IWorkspace? ActiveWorkspace { get; } } }
40.139896
179
0.618433
[ "MIT" ]
Bradben/iqsharp
src/AzureClient/IAzureClient.cs
7,749
C#
// // Trimmer Framework for Unity // https://sttz.ch/trimmer // #if !NO_TRIMMER || UNITY_EDITOR using System; using System.Collections.Generic; using System.Linq; using UnityEngine; using sttz.Trimmer.Extensions; using System.Text; using System.Text.RegularExpressions; namespace sttz.Trimmer { // TODO: Way to clean up store from old nodes /// <summary> /// Unity compatible store of nested string key/value pairs. /// </summary> /// <remarks> /// The ValueStore is used to serialize the nested Option values in /// Unity using its `ISerializationCallbackReceiver` callbacks. /// </remarks> [Serializable] public class ValueStore : ISerializationCallbackReceiver { /// <summary> /// Named value node with optional variants and children. /// </summary> [Serializable] public class Node { [SerializeField] internal string name; [SerializeField] internal string value = string.Empty; [NonSerialized] internal List<Node> variants; [NonSerialized] internal List<Node> children; /// <summary> /// Used for compatibility with Unity's serialization. /// </summary> [SerializeField] internal int numVariants; /// <summary> /// Used for compatibility with Unity's serialization. /// </summary> [SerializeField] internal int numChildren; /// <summary> /// Flag to track if store needs to be saved. /// </summary> [NonSerialized] internal bool isDirty; /// <summary> /// Name of the node, variant parameter for variant nodes /// and child name for child nodes. /// </summary> public string Name { get { return name; } set { if (this.name == value) return; this.name = value; isDirty = true; } } /// <summary> /// The value (if any) of the node. /// </summary> public string Value { get { return value; } set { if (this.value == value) return; this.value = value; isDirty = true; } } /// <summary> /// Enumerate the node's variants. /// </summary> public IEnumerable<Node> Variants { get { if (variants != null) { return variants; } else { return Enumerable.Empty<Node>(); } } } /// <summary> /// Number of variants in this node. /// </summary> public int VariantCount { get { if (variants != null) { return variants.Count; } else { return 0; } } } /// <summary> /// Look up a variant node by name. /// </summary> public Node GetVariant(string name) { if (variants == null || string.IsNullOrEmpty(name)) return null; foreach (var variant in variants) { if (variant.name.EqualsIgnoringCase(name)) { return variant; } } return null; } /// <summary> /// Look up a variant node by name, create it if it doesn't exist. /// </summary> public Node GetOrCreateVariant(string name) { var variant = GetVariant(name); if (variant == null) variant = AddVariant(name, string.Empty); return variant; } /// <summary> /// Add a new variant node. /// </summary> public Node AddVariant(string name, string value) { var node = new Node(); node.name = name; node.value = value; if (variants == null) variants = new List<Node>(); variants.Add(node); isDirty = true; return node; } /// <summary> /// Remove a variant node. /// </summary> public void RemoveVariant(string name) { if (variants == null) return; for (int i = 0; i < variants.Count; i++) { if (variants[i].name.EqualsIgnoringCase(name)) { variants.RemoveAt(i); isDirty = true; return; } } } /// <summary> /// Remove a variant node. /// </summary> public void RemoveVariant(int index) { if (variants == null) return; variants.RemoveAt(index); isDirty = true; } /// <summary> /// Remove all variant nodes. /// </summary> public void ClearVariants() { if (variants != null) { variants.Clear(); } } /// <summary> /// Set variants parameters to a sequential index, /// assigned based on natural sort order of existing /// parameters. /// </summary> public void NumberVariantsSequentially() { var comparer = NumericStringComparer.Instance; variants.Sort((a, b) => comparer.Compare(a.name, b.name)); for (int i = 0; i < variants.Count; i++) { variants[i].name = i.ToString(); } } /// <summary> /// Enumerate the node's children. /// </summary> public IEnumerable<Node> Children { get { if (children != null) { return children; } else { return Enumerable.Empty<Node>(); } } } /// <summary> /// Number of children in this node. /// </summary> public int ChildCount { get { if (children != null) { return children.Count; } else { return 0; } } } /// <summary> /// Look up a child node by name. /// </summary> public Node GetChild(string name) { if (children == null || string.IsNullOrEmpty(name)) return null; foreach (var child in children) { if (child.name.EqualsIgnoringCase(name)) { return child; } } return null; } /// <summary> /// Look up a child node by name, create it if it doesn't exist. /// </summary> public Node GetOrCreateChild(string name) { var child = GetChild(name); if (child == null) child = AddChild(name, string.Empty); return child; } /// <summary> /// Add a new child node. /// </summary> public Node AddChild(string name, string value) { var node = new Node(); node.name = name; node.value = value; if (children == null) children = new List<Node>(); children.Add(node); isDirty = true; return node; } /// <summary> /// Remove a child node. /// </summary> public void RemoveChild(string name) { if (children == null) return; for (int i = 0; i < children.Count; i++) { if (children[i].name.EqualsIgnoringCase(name)) { children.RemoveAt(i); isDirty = true; return; } } } /// <summary> /// Remove all child nodes. /// </summary> public void ClearChildren() { if (children != null) { children.Clear(); } } /// <summary> /// Create a clone of this node, with all its variants and children. /// </summary> public virtual Node Clone() { return Clone<Node>(); } /// <summary> /// Clone method to be used by subclasses for overriding. /// </summary> protected T Clone<T>() where T : Node, new() { var clone = new T() { name = name, value = value, numChildren = numChildren, numVariants = numVariants }; if (variants != null) { clone.variants = new List<Node>(variants.Count); foreach (var variant in variants) { clone.variants.Add(variant.Clone()); } } if (children != null) { clone.children = new List<Node>(children.Count); foreach (var child in children) { clone.children.Add(child.Clone()); } } return clone; } override public string ToString() { return string.Format( "[Node {0} = {1}, children = {2}, variants = {3}, isDirty = {4}]", name, value, ChildCount, VariantCount, isDirty ); } } /// <summary> /// Root named value node that has additional fields that only /// apply to the root nodes. /// </summary> [Serializable] public class RootNode : Node { #if UNITY_EDITOR [SerializeField] internal OptionInclusion inclusion; /// <summary> /// Wether the option should be included in builds. /// </summary> public OptionInclusion Inclusion { get { return inclusion; } set { if (inclusion == value) return; inclusion = value; isDirty = true; } } #endif public override Node Clone() { var clone = Clone<RootNode>(); #if UNITY_EDITOR clone.inclusion = inclusion; #endif return clone; } override public string ToString() { #if UNITY_EDITOR return string.Format( "[RootNode {0} = {1}, children = {2}, variants = {3}, isDirty = {4}, inclusion = {5}]", name, value, ChildCount, VariantCount, isDirty, inclusion ); #else return string.Format( "[RootNode {0} = {1}, children = {2}, variants = {3}, isDirty = {4}]", name, value, ChildCount, VariantCount, isDirty ); #endif } } /// <summary> /// Root nodes by name. /// </summary> [NonSerialized] List<RootNode> nodes; /// <summary> /// Track if the store roots have been changed. /// </summary> [NonSerialized] bool isDirty; /// <summary> /// Check if the store has been modified and optionally /// reset the modification state. /// </summary> public bool IsDirty(bool clear = false) { var anyDirty = isDirty; if (!clear && anyDirty) return true; else if (clear) isDirty = false; foreach (var root in Roots) { anyDirty |= IsDirtyRecursive(root, clear); if (!clear && anyDirty) return true; } return anyDirty; } bool IsDirtyRecursive(Node node, bool clear = false) { var anyDirty = node.isDirty; if (!clear && anyDirty) return true; else if (clear) node.isDirty = false; foreach (var variant in node.Variants) { anyDirty |= IsDirtyRecursive(variant, clear); if (!clear && anyDirty) return true; } foreach (var child in node.Children) { anyDirty |= IsDirtyRecursive(child, clear); if (!clear && anyDirty) return true; } return anyDirty; } /// <summary> /// Enumerate the root nodes in this store. /// </summary> public IEnumerable<RootNode> Roots { get { if (nodes != null) { return nodes; } else { return Enumerable.Empty<RootNode>(); } } } /// <summary> /// Number of root nodes in this store. /// </summary> public int RootCount { get { if (nodes != null) { return nodes.Count; } else { return 0; } } } /// <summary> /// Get a root node by name. /// </summary> public RootNode GetRoot(string name) { if (nodes == null || string.IsNullOrEmpty(name)) return null; foreach (var node in nodes) { if (node.name.EqualsIgnoringCase(name)) { return node; } } return null; } /// <summary> /// Get a root node by name, create it if it doesn't exist. /// </summary> public RootNode GetOrCreateRoot(string name) { var root = GetRoot(name); if (root == null) { root = AddRoot(name, string.Empty); } return root; } /// <summary> /// Add a new root node. /// </summary> public RootNode AddRoot(string name, string value) { var node = new RootNode(); node.name = name; node.value = value; if (nodes == null) nodes = new List<RootNode>(); nodes.Add(node); isDirty = true; return node; } /// <summary> /// Remove a root node. /// </summary> public void RemoveRoot(string name) { if (nodes == null) return; for (int i = 0; i < nodes.Count; i++) { if (nodes[i].name.EqualsIgnoringCase(name)) { nodes.RemoveAt(i); isDirty = true; return; } } } /// <summary> /// Removes all content form the store. /// </summary> public void Clear() { if (nodes == null) return; nodes.Clear(); } /// <summary> /// Create a clone of the current store. /// </summary> public ValueStore Clone() { var clone = new ValueStore(); clone.nodes = new List<RootNode>(nodes.Count); foreach (var node in nodes) { clone.nodes.Add((RootNode)node.Clone()); } return clone; } // -------- Unity Serialization -------- [SerializeField] List<RootNode> serializedRootNodes; [SerializeField] List<Node> serializedNodes; [SerializeField] int numNodes; /// <summary> /// Unity doesn't support serialization of types that contain themselves, /// like in this case <c>Node</c> that contains lists of <c>Node</c>. /// To enable this we don't serialize the nested lists but instead just /// the size of the lists (i.e. Node.numVariants and Node.numChildren) /// and then use <c>ISerializationCallbackReceiver</c> to flatten and /// unpack the tree before and after Unity serializes it. /// /// We process the nodes in the same order flattening and unpacking them /// and that allows us to get away with just serializing the list lengths. /// </summary> void ISerializationCallbackReceiver.OnBeforeSerialize() { serializedRootNodes = new List<RootNode>(); serializedNodes = new List<Node>(); if (nodes == null) return; numNodes = nodes.Count; serializedRootNodes.AddRange(nodes.Select(n => (RootNode)n.Clone())); for (int i = 0; i < numNodes; i++) { FlattenNode(serializedRootNodes[i], serializedNodes); } } void FlattenNode(Node node, List<Node> appendTo) { if (node.variants == null) { node.numVariants = 0; } else { node.numVariants = node.variants.Count; appendTo.AddRange(node.variants); foreach (var variant in node.variants) { FlattenNode(variant, appendTo); } node.variants = null; } if (node.children == null) { node.numChildren = 0; } else { node.numChildren = node.children.Count; appendTo.AddRange(node.children); foreach (var child in node.children) { FlattenNode(child, appendTo); } node.children = null; } } void ISerializationCallbackReceiver.OnAfterDeserialize() { nodes = new List<RootNode>(); if (serializedRootNodes == null) return; int offset = 0; for (int i = 0; i < serializedRootNodes.Count; i++) { nodes.Add((RootNode)serializedRootNodes[i].Clone()); UnpackNode(nodes[i], serializedNodes, ref offset); } } void UnpackNode(Node node, List<Node> takeFrom, ref int offset) { if (node.numVariants > 0) { node.variants = takeFrom.Skip(offset).Take(node.numVariants).Select(n => n.Clone()).ToList(); offset += node.numVariants; foreach (var variant in node.variants) { UnpackNode(variant, takeFrom, ref offset); } } if (node.numChildren > 0) { node.children = takeFrom.Skip(offset).Take(node.numChildren).Select( n => n.Clone()).ToList(); offset += node.numChildren; foreach (var children in node.children) { UnpackNode(children, takeFrom, ref offset); } } } } /// <summary> /// Helper methods to save a <see cref="ValueStore"/> to an Ini file and loading it back again. /// </summary> /// <remarks> /// The ini file supports comments on lines starting with "#" or "//" but not /// trailing comments. Categories are not supported. /// /// Each line assigns a value to an Option. The name part in front of the equal /// sign can contain child names separated by a dot and variant parameters /// enclosed with square brackets. Variant parameters must be quoted with double /// quotes if they contain square brackets (and double quotes then escaped). /// /// The value after the equal sign will be trimmed. It can be quoted with double /// quotes to retain the white space. /// </remarks> public static class IniAdapter { // -------- Ini Serialization -------- /// <summary> /// Save the content of this value store as a Ini file formatted string. /// </summary> public static string Save(ValueStore store) { var output = new StringBuilder(); foreach (var node in store.Roots) { SaveIniRecursive(output, "", node, false); } return output.ToString(); } static void SaveIniRecursive(StringBuilder output, string path, ValueStore.Node node, bool isVariantChild) { if (!isVariantChild) { path += node.name; } else { path += "[" + QuoteParameterIfNeeded(node.name) + "]"; } if (!string.IsNullOrEmpty(node.value)) { output.Append(path); output.Append(" = "); output.Append(QuoteValueIfNeeded(node.value)); output.Append("\n"); } if (node.VariantCount > 0) { foreach (var variant in node.variants) { SaveIniRecursive(output, path, variant, true); } } if (node.ChildCount > 0) { var childPath = path + "."; foreach (var child in node.children) { SaveIniRecursive(output, childPath, child, false); } } } /// <summary> /// Quote a parameter if it contains square brackets or /// return it as-is otherwise. /// </summary> public static string QuoteParameterIfNeeded(string parameter) { if (parameter.IndexOf('[') < 0 && parameter.IndexOf(']') < 0) { return parameter; } return '"' + parameter.Replace("\\", "\\\\").Replace("\"", "\\\"") + '"'; } /// <summary> /// Quote a value if it contains leading or trailing whitespace or /// return it as-is otherwise. /// </summary> public static string QuoteValueIfNeeded(string value) { if (value.Trim() == value) { return value; } return '"' + value.Replace("\\", "\\\\").Replace("\"", "\\\"") + '"'; } // ------ Ini Deserialization ------ /// <summary> /// Load the values in an Ini file into this value store instance, /// replacing the value store's contents. /// </summary> public static void Load(ValueStore store, string content) { // TODO: More input validation var lines = content.Split('\n'); foreach (var line in lines) { if (commentedLineRegex.IsMatch(line) || line.Trim().Length == 0) continue; var match = LineRegex.Match(line); if (!match.Success) { Debug.LogWarning("Failed to read line in Ini file: " + line); continue; } // Groups: // 1 = Regular Name // 2 = Child name // 3 = Quoted Parameter // 4 = Unquoted Parameter // 5 = Quoted Value // 6 = Unquoted Value var rootCapture = match.Groups[1]; var rootNode = store.GetOrCreateRoot(rootCapture.Value); var node = GetNodeRecursive(rootNode, match, rootCapture.Index + rootCapture.Length - 1); var isQuoted = true; var valueCapture = match.Groups[5]; if (!valueCapture.Success) { isQuoted = false; valueCapture = match.Groups[6]; } node.value = ProcessQuotedString(valueCapture.Value, isQuoted); } } /// <summary> /// Regex fragment matching identifiers based on valid C# identifiers. /// L = All letter characters (upper, lower, title, modifier and other) /// Nl = Number, Letter, Mn = Mark, Nonspacing, Mc = Mark, Combining /// Nd = Number, Decimal Digit, Pc = Punctuation, Connector, Cf = Other, Format /// Note that C# disallows leading numbers but this regex matches them. /// </summary> const string IdentifierRegex = @"([\p{L}|\p{Nl}|\p{Mn}|\p{Mc}|\p{Nd}|\p{Pc}|\p{Cf}]+)"; /// <summary> /// Regex fragment matching an optionally quoted string containing escape sequences. /// E.g. Unquoted String, "Quoted String", "Quoted with \"Escaped\" Quotes", "Quoted Double Escape \\" /// </summary> const string QuotedStringRegex = @" (?: # Group to make quotes optional ""( # Opening quote (?: [^""\\] # Anything but "" or \ | \\. # Or any escaped character )* )"" # Ending quote | (.*?) # Anything unqutoed ) "; /// <summary> /// Regex fragment matching the name part of a ini line. /// </summary> const string IniNameRegex = @" \s* # Any leading whitespce " + IdentifierRegex + @" # The name of the root option (?: # Start of name part \." + IdentifierRegex + @" # A child name starting with . | \[ " + QuotedStringRegex + @" \] # Or a paramter in [] )* \s* # Any trailing whitespace "; /// <summary> /// Regex matching only the name part of an ini line. /// </summary> public static readonly Regex NameRegex = new Regex( "^" + IniNameRegex, RegexOptions.IgnorePatternWhitespace ); /// <summary> /// Regex matching a line in a Ini file. /// </summary> public static readonly Regex LineRegex = new Regex(@" ^" + IniNameRegex + @" # Name part =\s* # Assignment = " + QuotedStringRegex + @" # Value part \s*$ # Any trailing whitespace ", RegexOptions.IgnorePatternWhitespace); /// <summary> /// Regex matching a comment line starting with # or // /// </summary> static readonly Regex commentedLineRegex = new Regex(@"^\s*(?:#|//)"); /// <summary> /// Find the next capture in the match and return the group index /// or <c>-1</c> if no capture was found. /// </summary> static int FindNextCapture(Match match, int startIndex, out Capture capture) { capture = null; var index = -1; for (int i = 0; i < match.Groups.Count; i++) { foreach (Capture candidate in match.Groups[i].Captures) { if (candidate.Index >= startIndex) { if (capture == null || candidate.Index < capture.Index) { capture = candidate; index = i; } else { break; } } } } return index; } static ValueStore.Node GetNodeRecursive(ValueStore.Node current, Match match, int index) { Capture next; var groupIndex = FindNextCapture(match, index, out next); if (groupIndex < 0) { Debug.LogWarning("Unexpected end of captures in match: " + match); return current; } else if (groupIndex == 2) { var child = current.GetOrCreateChild(next.Value); return GetNodeRecursive(child, match, next.Index + next.Length); } else if (groupIndex == 3 || groupIndex == 4) { var isQuoted = (groupIndex == 3); var variant = current.GetOrCreateVariant(ProcessQuotedString(next.Value, isQuoted)); return GetNodeRecursive(variant, match, next.Index + next.Length); } else { return current; } } static string ProcessQuotedString(string input, bool isQuoted) { if (!isQuoted) { return input; } else { return input.Replace("\\\"", "\"").Replace("\\\\", "\\"); } } // ------ Helpers ------ /// <summary> /// Take the name part of an ini line and convert it to a option path /// that then can be used with <see cref="RuntimeProfile.GetOption(string)"/>. /// </summary> public static string NameToPath(string name) { var match = NameRegex.Match(name); if (!match.Success) return null; var rootCapture = match.Groups[1]; return GetPathRecursive(rootCapture.Value, match, rootCapture.Index + rootCapture.Length - 1); } static string GetPathRecursive(string path, Match match, int index) { Capture next; var groupIndex = FindNextCapture(match, index, out next); if (groupIndex == 2) { return GetPathRecursive(path + "/" + next.Value, match, next.Index + next.Length); } else if (groupIndex == 3 || groupIndex == 4) { var name = ProcessQuotedString(next.Value, groupIndex == 3); return GetPathRecursive(path + ":" + name, match, next.Index + next.Length); } else { return path; } } /// <summary> /// Get the value part of an ini line, unquoting where necessary. /// </summary> public static string GetValue(string iniLine) { var match = LineRegex.Match(iniLine); if (!match.Success) return null; var isQuoted = true; var valueCapture = match.Groups[5]; if (!valueCapture.Success) { isQuoted = false; valueCapture = match.Groups[6]; } return ProcessQuotedString(valueCapture.Value, isQuoted); } } } #endif
28.978439
110
0.507812
[ "MIT" ]
JesseTG/trimmer
Base/ValueStore.cs
28,225
C#
using System; using Microsoft.EntityFrameworkCore.Metadata; using Microsoft.EntityFrameworkCore.Migrations; namespace Liu.Infra.CrossCutting.Identity.Data.Migrations { public partial class CreateIdentitySchema : Migration { protected override void Up(MigrationBuilder migrationBuilder) { migrationBuilder.CreateTable( name: "AspNetRoles", columns: table => new { Id = table.Column<string>(nullable: false), ConcurrencyStamp = table.Column<string>(nullable: true), Name = table.Column<string>(maxLength: 256, nullable: true), NormalizedName = table.Column<string>(maxLength: 256, nullable: true) }, constraints: table => { table.PrimaryKey("PK_AspNetRoles", x => x.Id); }); migrationBuilder.CreateTable( name: "AspNetUserTokens", columns: table => new { UserId = table.Column<string>(nullable: false), LoginProvider = table.Column<string>(nullable: false), Name = table.Column<string>(nullable: false), Value = table.Column<string>(nullable: true) }, constraints: table => { table.PrimaryKey("PK_AspNetUserTokens", x => new { x.UserId, x.LoginProvider, x.Name }); }); migrationBuilder.CreateTable( name: "AspNetUsers", columns: table => new { Id = table.Column<string>(nullable: false), AccessFailedCount = table.Column<int>(nullable: false), ConcurrencyStamp = table.Column<string>(nullable: true), Email = table.Column<string>(maxLength: 256, nullable: true), EmailConfirmed = table.Column<bool>(nullable: false), LockoutEnabled = table.Column<bool>(nullable: false), LockoutEnd = table.Column<DateTimeOffset>(nullable: true), NormalizedEmail = table.Column<string>(maxLength: 256, nullable: true), NormalizedUserName = table.Column<string>(maxLength: 256, nullable: true), PasswordHash = table.Column<string>(nullable: true), PhoneNumber = table.Column<string>(nullable: true), PhoneNumberConfirmed = table.Column<bool>(nullable: false), SecurityStamp = table.Column<string>(nullable: true), TwoFactorEnabled = table.Column<bool>(nullable: false), UserName = table.Column<string>(maxLength: 256, nullable: true) }, constraints: table => { table.PrimaryKey("PK_AspNetUsers", x => x.Id); }); migrationBuilder.CreateTable( name: "AspNetRoleClaims", columns: table => new { Id = table.Column<int>(nullable: false) .Annotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn), ClaimType = table.Column<string>(nullable: true), ClaimValue = table.Column<string>(nullable: true), RoleId = table.Column<string>(nullable: false) }, constraints: table => { table.PrimaryKey("PK_AspNetRoleClaims", x => x.Id); table.ForeignKey( name: "FK_AspNetRoleClaims_AspNetRoles_RoleId", column: x => x.RoleId, principalTable: "AspNetRoles", principalColumn: "Id", onDelete: ReferentialAction.Cascade); }); migrationBuilder.CreateTable( name: "AspNetUserClaims", columns: table => new { Id = table.Column<int>(nullable: false) .Annotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn), ClaimType = table.Column<string>(nullable: true), ClaimValue = table.Column<string>(nullable: true), UserId = table.Column<string>(nullable: false) }, constraints: table => { table.PrimaryKey("PK_AspNetUserClaims", x => x.Id); table.ForeignKey( name: "FK_AspNetUserClaims_AspNetUsers_UserId", column: x => x.UserId, principalTable: "AspNetUsers", principalColumn: "Id", onDelete: ReferentialAction.Cascade); }); migrationBuilder.CreateTable( name: "AspNetUserLogins", columns: table => new { LoginProvider = table.Column<string>(nullable: false), ProviderKey = table.Column<string>(nullable: false), ProviderDisplayName = table.Column<string>(nullable: true), UserId = table.Column<string>(nullable: false) }, constraints: table => { table.PrimaryKey("PK_AspNetUserLogins", x => new { x.LoginProvider, x.ProviderKey }); table.ForeignKey( name: "FK_AspNetUserLogins_AspNetUsers_UserId", column: x => x.UserId, principalTable: "AspNetUsers", principalColumn: "Id", onDelete: ReferentialAction.Cascade); }); migrationBuilder.CreateTable( name: "AspNetUserRoles", columns: table => new { UserId = table.Column<string>(nullable: false), RoleId = table.Column<string>(nullable: false) }, constraints: table => { table.PrimaryKey("PK_AspNetUserRoles", x => new { x.UserId, x.RoleId }); table.ForeignKey( name: "FK_AspNetUserRoles_AspNetRoles_RoleId", column: x => x.RoleId, principalTable: "AspNetRoles", principalColumn: "Id", onDelete: ReferentialAction.Cascade); table.ForeignKey( name: "FK_AspNetUserRoles_AspNetUsers_UserId", column: x => x.UserId, principalTable: "AspNetUsers", principalColumn: "Id", onDelete: ReferentialAction.Cascade); }); migrationBuilder.CreateIndex( name: "RoleNameIndex", table: "AspNetRoles", column: "NormalizedName"); migrationBuilder.CreateIndex( name: "IX_AspNetRoleClaims_RoleId", table: "AspNetRoleClaims", column: "RoleId"); migrationBuilder.CreateIndex( name: "IX_AspNetUserClaims_UserId", table: "AspNetUserClaims", column: "UserId"); migrationBuilder.CreateIndex( name: "IX_AspNetUserLogins_UserId", table: "AspNetUserLogins", column: "UserId"); migrationBuilder.CreateIndex( name: "IX_AspNetUserRoles_RoleId", table: "AspNetUserRoles", column: "RoleId"); migrationBuilder.CreateIndex( name: "IX_AspNetUserRoles_UserId", table: "AspNetUserRoles", column: "UserId"); migrationBuilder.CreateIndex( name: "EmailIndex", table: "AspNetUsers", column: "NormalizedEmail"); migrationBuilder.CreateIndex( name: "UserNameIndex", table: "AspNetUsers", column: "NormalizedUserName", unique: true); } protected override void Down(MigrationBuilder migrationBuilder) { migrationBuilder.DropTable( name: "AspNetRoleClaims"); migrationBuilder.DropTable( name: "AspNetUserClaims"); migrationBuilder.DropTable( name: "AspNetUserLogins"); migrationBuilder.DropTable( name: "AspNetUserRoles"); migrationBuilder.DropTable( name: "AspNetUserTokens"); migrationBuilder.DropTable( name: "AspNetRoles"); migrationBuilder.DropTable( name: "AspNetUsers"); } } }
42.313364
122
0.499564
[ "MIT" ]
faugusto90/LiuProject
src/Liu.Infra.CrossCutting.Identity/Data/Migrations/00000000000000_CreateIdentitySchema.cs
9,184
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 ds-2015-04-16.normal.json service model. */ using System; using System.Collections.Generic; using System.Text; using System.Collections; using System.Threading; using System.Threading.Tasks; using Amazon.Runtime; namespace Amazon.DirectoryService.Model { /// <summary> /// Base class for DescribeDomainControllers paginators. /// </summary> internal sealed partial class DescribeDomainControllersPaginator : IPaginator<DescribeDomainControllersResponse>, IDescribeDomainControllersPaginator { private readonly IAmazonDirectoryService _client; private readonly DescribeDomainControllersRequest _request; private int _isPaginatorInUse = 0; /// <summary> /// Enumerable containing all full responses for the operation /// </summary> public IPaginatedEnumerable<DescribeDomainControllersResponse> Responses => new PaginatedResponse<DescribeDomainControllersResponse>(this); internal DescribeDomainControllersPaginator(IAmazonDirectoryService client, DescribeDomainControllersRequest request) { this._client = client; this._request = request; } #if BCL IEnumerable<DescribeDomainControllersResponse> IPaginator<DescribeDomainControllersResponse>.Paginate() { if (Interlocked.Exchange(ref _isPaginatorInUse, 1) != 0) { throw new System.InvalidOperationException("Paginator has already been consumed and cannot be reused. Please create a new instance."); } PaginatorUtils.SetUserAgentAdditionOnRequest(_request); var nextToken = _request.NextToken; DescribeDomainControllersResponse response; do { _request.NextToken = nextToken; response = _client.DescribeDomainControllers(_request); nextToken = response.NextToken; yield return response; } while (!string.IsNullOrEmpty(nextToken)); } #endif #if AWS_ASYNC_ENUMERABLES_API async IAsyncEnumerable<DescribeDomainControllersResponse> IPaginator<DescribeDomainControllersResponse>.PaginateAsync(CancellationToken cancellationToken = default) { if (Interlocked.Exchange(ref _isPaginatorInUse, 1) != 0) { throw new System.InvalidOperationException("Paginator has already been consumed and cannot be reused. Please create a new instance."); } PaginatorUtils.SetUserAgentAdditionOnRequest(_request); var nextToken = _request.NextToken; DescribeDomainControllersResponse response; do { _request.NextToken = nextToken; response = await _client.DescribeDomainControllersAsync(_request, cancellationToken).ConfigureAwait(false); nextToken = response.NextToken; cancellationToken.ThrowIfCancellationRequested(); yield return response; } while (!string.IsNullOrEmpty(nextToken)); } #endif } } #endif
40.817204
172
0.683351
[ "Apache-2.0" ]
PureKrome/aws-sdk-net
sdk/src/Services/DirectoryService/Generated/Model/_bcl45+netstandard/DescribeDomainControllersPaginator.cs
3,796
C#
using System.Collections; using System.Collections.Generic; using System.Linq; using ClForms.Elements; namespace ClForms.Common { /// <summary> /// Represents the collection of items in a <see cref="ListView"/> control /// </summary> public class ListViewItemCollection<T>: IList<T> { private readonly ListView<T> owner; private readonly List<T> items; internal ListViewItemCollection(ListView<T> owner) { this.owner = owner; items = new List<T>(); } /// <inheritdoc /> public IEnumerator<T> GetEnumerator() => items.GetEnumerator(); /// <inheritdoc /> IEnumerator IEnumerable.GetEnumerator() => GetEnumerator(); /// <inheritdoc /> public void Add(T item) { items.Add(item); owner.InvalidateVisualIfItemVisible(Count - 1, 1, ListViewItemCollectionAction.Add); } /// <inheritdoc cref="List{T}.AddRange"/> public void AddRange(IEnumerable<T> item) { var count = item.Count(); items.AddRange(item); owner.InvalidateVisualIfItemVisible(Count - count, count, ListViewItemCollectionAction.Add); } /// <inheritdoc /> public void Clear() { items.Clear(); owner.ClearItemsInternal(); } /// <inheritdoc /> public bool Contains(T item) => items.Contains(item); /// <inheritdoc /> public void CopyTo(T[] array, int arrayIndex) => items.CopyTo(array, arrayIndex); /// <inheritdoc /> public bool Remove(T item) { owner.InvalidateVisualIfItemVisible(IndexOf(item), 1, ListViewItemCollectionAction.Remove); return items.Remove(item); } /// <inheritdoc /> public int Count => items.Count; /// <inheritdoc /> public bool IsReadOnly { get; } = false; /// <inheritdoc /> public int IndexOf(T item) => items.IndexOf(item); /// <inheritdoc /> public void Insert(int index, T item) { items.Insert(index, item); owner.InvalidateVisualIfItemVisible(index, 1, ListViewItemCollectionAction.Add); } /// <inheritdoc /> public void RemoveAt(int index) { items.RemoveAt(index); owner.InvalidateVisualIfItemVisible(index, 1, ListViewItemCollectionAction.Remove); } /// <inheritdoc /> public T this[int index] { get => items[index]; set => items[index] = value; } } internal enum ListViewItemCollectionAction { Add, Remove, } }
27.44
104
0.562318
[ "Apache-2.0" ]
Ahatornn/clforms
ClForms/Common/ListViewItemCollection.cs
2,744
C#
// Copyright Information // ================================== // EntityFrameworkCore - EfCoreBasics - VIndividualCustomer.cs // All samples copyright Philip Japikse // http://www.skimedic.com 2020/04/08 // See License.txt for more information // ================================== using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; namespace EfCoreBasics.Entities { public partial class VIndividualCustomer { [Column("BusinessEntityID")] public int BusinessEntityId { get; set; } [StringLength(8)] public string Title { get; set; } [Required] [StringLength(50)] public string FirstName { get; set; } [StringLength(50)] public string MiddleName { get; set; } [Required] [StringLength(50)] public string LastName { get; set; } [StringLength(10)] public string Suffix { get; set; } [StringLength(25)] public string PhoneNumber { get; set; } [StringLength(50)] public string PhoneNumberType { get; set; } [StringLength(50)] public string EmailAddress { get; set; } public int EmailPromotion { get; set; } [Required] [StringLength(50)] public string AddressType { get; set; } [Required] [StringLength(60)] public string AddressLine1 { get; set; } [StringLength(60)] public string AddressLine2 { get; set; } [Required] [StringLength(30)] public string City { get; set; } [Required] [StringLength(50)] public string StateProvinceName { get; set; } [Required] [StringLength(15)] public string PostalCode { get; set; } [Required] [StringLength(50)] public string CountryRegionName { get; set; } [Column(TypeName = "xml")] public string Demographics { get; set; } } }
33.851852
83
0.647702
[ "BSD-3-Clause", "MIT" ]
MalikWaseemJaved/presentations
.NETCore/EFCoreSamples/EfCoreBasics/Entities/VIndividualCustomer.cs
1,830
C#
using System; using System.Text.RegularExpressions; namespace Microsoft.Recognizers.Text.DateTime { public interface ICJKSetExtractorConfiguration : IDateTimeOptionsConfiguration { Regex LastRegex { get; } Regex EachPrefixRegex { get; } Regex EachUnitRegex { get; } Regex UnitRegex { get; } Regex EachDayRegex { get; } IDateTimeExtractor DurationExtractor { get; } IDateTimeExtractor TimeExtractor { get; } IDateTimeExtractor DateExtractor { get; } IDateTimeExtractor DateTimeExtractor { get; } IDateTimeExtractor DatePeriodExtractor { get; } IDateTimeExtractor TimePeriodExtractor { get; } IDateTimeExtractor DateTimePeriodExtractor { get; } } }
23.96875
82
0.683181
[ "MIT" ]
QPC-database/Recognizers-Text
.NET/Microsoft.Recognizers.Text.DateTime/Extractors/CJK/ICJKSetExtractorConfiguration.cs
769
C#
using System; using Microsoft.VisualStudio.TestTools.UnitTesting; using System.IO; using WalkMatrix; using WalkMatrix.MatrixGenerator; namespace WalkMatrix.Tests { [TestClass] public class TestMatrixGenerator { [TestMethod] public void MatrixGeneratorGetNextDirectionShouldSwitchDirectionCorrectly() { Direction dir = Direction.DownRight; for (int i = 0; i < 7; i++) { dir = Generator.GetNextDirection(dir); } Assert.AreEqual(Direction.Right, dir); } [TestMethod] public void MatrixGeneratorCheckIfFreeNeighbourCellExistsShouldWorkIfFreeNeighbourCellExists() { var arr = new int[,] { {1,1,1,1,1}, {1,0,1,1,1}, {1,0,1,1,1} }; var matrix = new Matrix(3, 5); matrix.MatrixArray = arr; var position = new Position(0, 0); var cellExist = matrix.CheckIfAnyNeighbourCellContainsValue(position, 0); Assert.IsTrue(cellExist); } [TestMethod] public void MatrixGeneratorCheckIfFreeNeighbourCellExistsShouldWorkIfFreeNeighbourCellExistsAndPositionIsAtTheBorderOfMatrix() { var arr = new int[,] { {1,1,1,1,1}, {1,0,1,1,1}, {1,0,1,1,1} }; var matrix = new Matrix(3, 5); matrix.MatrixArray = arr; var position = new Position(2, 1); var cellExist = matrix.CheckIfAnyNeighbourCellContainsValue(position, 0); Assert.IsTrue(cellExist); } [TestMethod] public void MatrixGeneratorCheckIfFreeNeighbourCellExistsShouldWorkIfFreeNeighbourCellDeosNotExists() { var arr = new int[,] { {1,1,1,1,1}, {1,0,1,1,1}, {1,1,1,1,1} }; var matrix = new Matrix(3, 5); matrix.MatrixArray = arr; var position = new Position(2, 3); var cellExist = matrix.CheckIfAnyNeighbourCellContainsValue(position, 0); Assert.IsFalse(cellExist); } [TestMethod] public void MatrixGeneratorCheckIfFreeNeighbourCellExistsShouldWorkIfFreeNeighbourCellDeosNotExistsAndPositionIsAtTheBorder() { var arr = new int[,] { {1,1,1,1,1}, {1,0,1,1,1}, {1,1,1,1,1} }; var matrix = new Matrix(3, 5); matrix.MatrixArray = arr; var position = new Position(0, 4); var cellExist = matrix.CheckIfAnyNeighbourCellContainsValue(position, 0); Assert.IsFalse(cellExist); } [TestMethod] public void MatrixGeneratorFindFirstFreeCellShouldWorkWhenFreeCellExists() { var arr = new int[,] { {1,1,1,1,1}, {1,0,1,1,1}, {1,1,0,1,1} }; var matrix = new Matrix(3, 5); matrix.MatrixArray = arr; var position = matrix.FindFirstCellPositionWithValue(0); Assert.AreEqual(1, position.Row); Assert.AreEqual(1, position.Col); } [TestMethod] public void MatrixGeneratorFindFirstFreeCellShouldWorkWhenFreeCellDoesNotExist() { var arr = new int[,] { {1,1,1,1,1}, {1,1,1,1,1}, {1,1,1,1,1} }; var matrix = new Matrix(3, 5); matrix.MatrixArray = arr; var position = matrix.FindFirstCellPositionWithValue(0); Assert.AreEqual(null, position); } [TestMethod] public void IsPositionValidShouldReturnTrueOnValidPosition() { var arr = new int[,] { {1,1,1,1,0}, {1,1,1,1,1}, {1,1,1,0,0} }; var matrix = new Matrix(3, 5); matrix.MatrixArray = arr; var position = new Position(0, 4); Assert.IsTrue(matrix.IsPositionValid(position), "0 4"); position = new Position(2, 4); Assert.IsTrue(matrix.IsPositionValid(position), "2 4"); position = new Position(2, 3); Assert.IsTrue(matrix.IsPositionValid(position), "2 3"); } [TestMethod] public void IsPositionValidShouldReturnFalseOnInvalidPosition() { var arr = new int[,] { {1,1,1,1,1}, {1,1,1,1,1}, {1,1,1,1,1} }; var matrix = new Matrix(3, 5); matrix.MatrixArray = arr; var position = new Position(-2, 4); Assert.IsFalse(matrix.IsPositionValid(position)); position = new Position(2, -5); Assert.IsFalse(matrix.IsPositionValid(position)); position = new Position(-1, 3); Assert.IsFalse(matrix.IsPositionValid(position)); } } }
32.304348
134
0.512209
[ "MIT" ]
todorm85/TelerikAcademy
Courses/Programming/High Quality Code/Homework/13. Refactoring/MatrixWalk/Matrix.Tests/TestMatrixGenerator.cs
5,203
C#
using Microsoft.AspNetCore.SignalR; using System; namespace SignalR.Modules { /// <summary> /// A base class for a SignalR Module hub. /// </summary> public abstract class ModuleHub<T> : ModuleHub where T : class { private bool _disposed; private IHubCallerClients<T> _clients = default!; /// <summary> /// Gets or sets an object that can be used to invoke methods on the clients connected to this hub. /// </summary> public new IHubCallerClients<T> Clients { get { CheckDisposed(); return _clients; } set { CheckDisposed(); _clients = value; } } /// <summary> /// Releases all resources currently used by this <see cref="Hub"/> instance. /// </summary> /// <param name="disposing"><c>true</c> if this method is being invoked by the <see cref="Dispose()"/> method, /// otherwise <c>false</c>.</param> protected override void Dispose(bool disposing) { if (_disposed) { return; } _disposed = true; } private void CheckDisposed() { if (_disposed) { throw new ObjectDisposedException(GetType().Name); } } } }
25.385965
118
0.494817
[ "MIT" ]
berhir/SignalR.Modules
src/SignalR.Modules/ModuleHub{T}.cs
1,447
C#
using CodeGen.Core; namespace CodeGen.Parsing.Ast.Expressions { public class ExpressionNode : Expression { public Expression[] Operands { get; } public ExpressionNode(string operatorName, params Expression[] operands) : this(operatorName) { Operands = operands; } public ExpressionNode(string operatorName) : base(new Reference()) { OperatorName = operatorName; } public string OperatorName { get; } public bool IsUnary => Operands.Length == 1; public override void Accept(ICodeUnitVisitor unitVisitor) { unitVisitor.Visit(this); } } }
25.481481
101
0.606105
[ "MIT" ]
SuperJMN/CodeGeneration
CodeGen.Parsing/Ast/Expressions/ExpressionNode.cs
690
C#
using System; using System.Collections.Generic; namespace RefinId.Specs { public class TestStorage : ILongIdStorage { private List<long> _values; public TestStorage(params long[] values) { _values = new List<long>(values); } public List<long> Values { get { return _values; } } public List<long> GetLastValues(bool requestFromRealTables = false) { return new List<long>(_values); } public void SaveLastValues(IEnumerable<long> values, bool removeUnusedRows = true) { _values = new List<long>(values); } public void SaveLastValue(long value) { SaveLastValues(new[] { value }); } public TableCommandBuilder Builder { get { throw new NotImplementedException(); } } } }
17.926829
69
0.688435
[ "MIT" ]
OlegAxenow/refinid
Refinid.Specs/TestStorage.cs
737
C#
// // Copyright (C) 2004 Novell, Inc (http://www.novell.com) // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // using System; namespace System.Runtime.InteropServices { #if NET_2_0 [ComVisible(true)] #endif [AttributeUsage (AttributeTargets.Parameter, Inherited=false)] public sealed class OptionalAttribute : Attribute { public OptionalAttribute () { } } }
38.864865
74
0.737135
[ "MIT" ]
GrapeCity/pagefx
mono/mcs/class/corlib/System.Runtime.InteropServices/OptionalAttribute.cs
1,438
C#
namespace WorQLess.Models { public interface IWorQLessWorkflow { IWorkflowContainer WorkflowContainer { get; set; } } }
19.857143
58
0.690647
[ "MIT" ]
fabiohvp/WorQLess.Net
Models/IWorQLessWorkflow.cs
139
C#
using System; namespace SampleAspNetWithEfCore.Dtos { public class PingDto { public PingDto(bool useUtc, string messageSuffix) { IsUtc = useUtc; Now = useUtc ? DateTime.UtcNow : DateTime.Now; Message = "Server is alive!" + messageSuffix; } public bool IsUtc { get; set; } public DateTime Now { get; } public string Message { get; } } }
22.894737
58
0.567816
[ "MIT" ]
lucas-zimerman/sample-ef-core-in-asp-net-core
SampleAspNetWithEfCore/Dtos/PingDto.cs
437
C#
// (c) www.click2wait.net using System; using System.Text; using System.Linq; using UnityEngine; using Mirror; using click2wait; namespace click2wait { [System.Serializable] public abstract partial class EntityManager : PropertyManager { // assign // cmd assign // unassign // cmd unassign // ----------------------------------------------------------------------- ACTIONS public abstract bool CanEntryAction(int index); [Command] public abstract void CmdCancelEntryAction(int index); [Server] protected abstract void CancelEntryAction(int index); // ----------------------------------------------------------------------- UPGRADE public abstract bool CanUpgradeEntry(int index); [Command] public abstract void CmdUpgradeEntry(int index); [Server] protected abstract void UpgradeEntry(int index); } }
19.130435
84
0.590909
[ "MIT" ]
Ghetaldus/click2wait-browser-game-style-engine
Scripts/Managers/_Abstract/EntityManager.cs
882
C#
// Copyright (c) Microsoft. All rights reserved. namespace Microsoft.Azure.Devices.Edge.Hub.Core.Test { using System; using System.Collections.Generic; using System.Text; using System.Threading.Tasks; using Microsoft.Azure.Devices.Edge.Hub.Core.Cloud; using Microsoft.Azure.Devices.Edge.Hub.Core.Device; using Microsoft.Azure.Devices.Edge.Hub.Core.Identity; using Microsoft.Azure.Devices.Edge.Util; using Microsoft.Azure.Devices.Edge.Util.Test.Common; using Moq; using Xunit; [Unit] public class DeviceMessageHandlerTest { [Fact] public async Task ForwardsGetTwinOperationToEdgeHub() { var edgeHub = new Mock<IEdgeHub>(); var connMgr = Mock.Of<IConnectionManager>(); var identity = Mock.Of<IDeviceIdentity>(i => i.Id == "d1"); var cloudProxy = Mock.Of<ICloudProxy>(); var deviceProxy = new Mock<IDeviceProxy>(); IMessage actualMessage = null; deviceProxy.Setup(d => d.SendTwinUpdate(It.IsAny<IMessage>())) .Callback<IMessage>(m => actualMessage = m) .Returns(Task.CompletedTask); IMessage expectedMessage = new EdgeMessage.Builder(new byte[0]).Build(); edgeHub.Setup(e => e.GetTwinAsync(It.IsAny<string>())).Returns(Task.FromResult(expectedMessage)); Mock.Get(connMgr).Setup(c => c.GetCloudConnection(It.IsAny<string>())).Returns(Task.FromResult(Option.Some(cloudProxy))); var listener = new DeviceMessageHandler(identity, edgeHub.Object, connMgr); listener.BindDeviceProxy(deviceProxy.Object); await listener.SendGetTwinRequest("cid"); edgeHub.Verify(x => x.GetTwinAsync(identity.Id), Times.Once); Assert.Same(expectedMessage, actualMessage); } [Fact] public async Task ProcessMessageBatchAsync_RouteAsyncTest() { var cloudProxy = Mock.Of<ICloudProxy>(); var connectionManager = Mock.Of<IConnectionManager>(); var edgeHub = Mock.Of<IEdgeHub>(); var identity = Mock.Of<IDeviceIdentity>(); var messages = new List<IMessage>(); messages.Add(Mock.Of<IMessage>()); messages.Add(Mock.Of<IMessage>()); Mock.Get(connectionManager).Setup(c => c.GetCloudConnection(It.IsAny<string>())).Returns(Task.FromResult(Option.Some(cloudProxy))); var deviceListener = new DeviceMessageHandler(identity, edgeHub, connectionManager); await deviceListener.ProcessDeviceMessageBatchAsync(messages); Mock.Get(edgeHub).Verify(eh => eh.ProcessDeviceMessageBatch(identity, It.IsAny<IEnumerable<IMessage>>()), Times.Once()); } [Fact] public async Task ProcessFeedbackMessageAsync_RouteAsyncTest() { var cloudProxy = Mock.Of<ICloudProxy>(); var connectionManager = Mock.Of<IConnectionManager>(); var edgeHub = Mock.Of<IEdgeHub>(); var identity = Mock.Of<IDeviceIdentity>(); string messageId = "messageId"; var status = FeedbackStatus.Complete; Mock.Get(connectionManager).Setup(c => c.GetCloudConnection(It.IsAny<string>())).Returns(Task.FromResult(Option.Some(cloudProxy))); var deviceListener = new DeviceMessageHandler(identity, edgeHub, connectionManager); await deviceListener.ProcessMessageFeedbackAsync(messageId, status); Mock.Get(cloudProxy).Verify(cp => cp.SendFeedbackMessageAsync(messageId, status), Times.Once()); } [Fact] public async Task ForwardsTwinPatchOperationToTheCloudProxy() { var connMgr = Mock.Of<IConnectionManager>(); var identity = Mock.Of<IModuleIdentity>(m => m.DeviceId == "device1" && m.ModuleId == "module1" && m.Id == "device1/module1"); var cloudProxy = Mock.Of<ICloudProxy>(); IMessage receivedMessage = null; var edgeHub = new Mock<IEdgeHub>(); edgeHub.Setup(e => e.UpdateReportedPropertiesAsync(It.IsAny<IIdentity>(), It.IsAny<IMessage>())) .Callback<IIdentity, IMessage>((id, m) => receivedMessage = m) .Returns(Task.CompletedTask); Mock.Get(connMgr).Setup(c => c.GetCloudConnection(It.IsAny<string>())).Returns(Task.FromResult(Option.Some(cloudProxy))); var listener = new DeviceMessageHandler(identity, edgeHub.Object, connMgr); var underlyingDeviceProxy = new Mock<IDeviceProxy>(); bool updateSent = false; underlyingDeviceProxy.Setup(d => d.SendTwinUpdate(It.IsAny<IMessage>())) .Callback(() => updateSent = true) .Returns(Task.CompletedTask); listener.BindDeviceProxy(underlyingDeviceProxy.Object); IMessage message = new EdgeMessage.Builder(Encoding.UTF8.GetBytes("don't care")).Build(); await listener.UpdateReportedPropertiesAsync(message, Guid.NewGuid().ToString()); edgeHub.VerifyAll(); Assert.True(updateSent); Assert.NotNull(receivedMessage); Assert.Equal(Constants.TwinChangeNotificationMessageSchema, receivedMessage.SystemProperties[SystemProperties.MessageSchema]); Assert.Equal(Constants.TwinChangeNotificationMessageType, receivedMessage.SystemProperties[SystemProperties.MessageType]); Assert.Equal("device1", receivedMessage.SystemProperties[SystemProperties.ConnectionDeviceId]); Assert.Equal("module1", receivedMessage.SystemProperties[SystemProperties.ConnectionModuleId]); Assert.True(receivedMessage.SystemProperties.ContainsKey(SystemProperties.EnqueuedTime)); } [Fact] public async Task InvokeMethodTest() { DeviceMessageHandler deviceMessageHandler = this.GetDeviceMessageHandler(); var methodRequest = new DirectMethodRequest("device10", "shutdown", null, TimeSpan.FromSeconds(2), TimeSpan.FromMilliseconds(10)); Task<DirectMethodResponse> responseTask = deviceMessageHandler.InvokeMethodAsync(methodRequest); Assert.False(responseTask.IsCompleted); IMessage message = new EdgeMessage.Builder(new byte[0]).Build(); message.Properties[SystemProperties.CorrelationId] = methodRequest.CorrelationId; message.Properties[SystemProperties.StatusCode] = "200"; await deviceMessageHandler.ProcessMethodResponseAsync(message); Assert.True(responseTask.IsCompleted); Assert.Equal(methodRequest.CorrelationId, responseTask.Result.CorrelationId); Assert.Equal(200, responseTask.Result.Status); } [Fact] public async Task InvokeMethodTimeoutTest() { DeviceMessageHandler deviceMessageHandler = this.GetDeviceMessageHandler(); var methodRequest = new DirectMethodRequest("device10", "shutdown", null, TimeSpan.FromSeconds(2), TimeSpan.FromMilliseconds(10)); Task<DirectMethodResponse> responseTask = deviceMessageHandler.InvokeMethodAsync(methodRequest); Assert.False(responseTask.IsCompleted); await Task.Delay(TimeSpan.FromSeconds(5)); Assert.True(responseTask.IsCompleted); Assert.NotNull(responseTask.Result); Assert.Null(responseTask.Result.Data); } [Fact] public async Task InvokedMethodMismatchedResponseTest() { DeviceMessageHandler deviceMessageHandler = this.GetDeviceMessageHandler(); var methodRequest = new DirectMethodRequest("device10", "shutdown", null, TimeSpan.FromSeconds(2), TimeSpan.FromMilliseconds(10)); Task<DirectMethodResponse> responseTask = deviceMessageHandler.InvokeMethodAsync(methodRequest); Assert.False(responseTask.IsCompleted); IMessage message = new EdgeMessage.Builder(new byte[0]).Build(); message.Properties[SystemProperties.CorrelationId] = methodRequest.CorrelationId + 1; message.Properties[SystemProperties.StatusCode] = "200"; await deviceMessageHandler.ProcessMethodResponseAsync(message); Assert.False(responseTask.IsCompleted); } [Fact] public async Task MessageCompletionTest() { var connMgr = new Mock<IConnectionManager>(); connMgr.Setup(c => c.AddDeviceConnection(It.IsAny<IIdentity>(), It.IsAny<IDeviceProxy>())); var identity = Mock.Of<IModuleIdentity>(m => m.DeviceId == "device1" && m.ModuleId == "module1" && m.Id == "device1/module1"); var cloudProxy = new Mock<ICloudProxy>(); var edgeHub = Mock.Of<IEdgeHub>(); var underlyingDeviceProxy = new Mock<IDeviceProxy>(); IMessage receivedMessage = null; underlyingDeviceProxy.Setup(d => d.SendMessageAsync(It.IsAny<IMessage>(), It.IsAny<string>())) .Callback<IMessage, string>((m, s) => receivedMessage = m) .Returns(Task.CompletedTask); connMgr.Setup(c => c.GetCloudConnection(It.IsAny<string>())).Returns(Task.FromResult(Option.Some(cloudProxy.Object))); var deviceMessageHandler = new DeviceMessageHandler(identity, edgeHub, connMgr.Object); deviceMessageHandler.BindDeviceProxy(underlyingDeviceProxy.Object); IMessage message = new EdgeMessage.Builder(new byte[0]).Build(); Task sendMessageTask = deviceMessageHandler.SendMessageAsync(message, "input1"); Assert.False(sendMessageTask.IsCompleted); string messageId = receivedMessage.SystemProperties[SystemProperties.LockToken]; await deviceMessageHandler.ProcessMessageFeedbackAsync(messageId, FeedbackStatus.Complete); Assert.True(sendMessageTask.IsCompleted); Assert.False(sendMessageTask.IsFaulted); } [Fact] public async Task MessageCompletionTimeoutTest() { var connMgr = new Mock<IConnectionManager>(); connMgr.Setup(c => c.AddDeviceConnection(It.IsAny<IIdentity>(), It.IsAny<IDeviceProxy>())); var identity = Mock.Of<IModuleIdentity>(m => m.DeviceId == "device1" && m.ModuleId == "module1" && m.Id == "device1/module1"); var cloudProxy = new Mock<ICloudProxy>(); var edgeHub = Mock.Of<IEdgeHub>(); var underlyingDeviceProxy = new Mock<IDeviceProxy>(); underlyingDeviceProxy.Setup(d => d.SendMessageAsync(It.IsAny<IMessage>(), It.IsAny<string>())) .Returns(Task.CompletedTask); connMgr.Setup(c => c.GetCloudConnection(It.IsAny<string>())).Returns(Task.FromResult(Option.Some(cloudProxy.Object))); var deviceMessageHandler = new DeviceMessageHandler(identity, edgeHub, connMgr.Object); deviceMessageHandler.BindDeviceProxy(underlyingDeviceProxy.Object); IMessage message = new EdgeMessage.Builder(new byte[0]).Build(); Task sendMessageTask = deviceMessageHandler.SendMessageAsync(message, "input1"); Assert.False(sendMessageTask.IsCompleted); await Assert.ThrowsAsync<TimeoutException>(async () => await sendMessageTask); } [Fact] public async Task MessageCompletionMismatchedResponseTest() { var connMgr = new Mock<IConnectionManager>(); connMgr.Setup(c => c.AddDeviceConnection(It.IsAny<IIdentity>(), It.IsAny<IDeviceProxy>())); var identity = Mock.Of<IModuleIdentity>(m => m.DeviceId == "device1" && m.ModuleId == "module1" && m.Id == "device1/module1"); var cloudProxy = new Mock<ICloudProxy>(); var edgeHub = Mock.Of<IEdgeHub>(); var underlyingDeviceProxy = new Mock<IDeviceProxy>(); underlyingDeviceProxy.Setup(d => d.SendMessageAsync(It.IsAny<IMessage>(), It.IsAny<string>())) .Returns(Task.CompletedTask); connMgr.Setup(c => c.GetCloudConnection(It.IsAny<string>())).Returns(Task.FromResult(Option.Some(cloudProxy.Object))); var deviceMessageHandler = new DeviceMessageHandler(identity, edgeHub, connMgr.Object); deviceMessageHandler.BindDeviceProxy(underlyingDeviceProxy.Object); IMessage message = new EdgeMessage.Builder(new byte[0]).Build(); Task sendMessageTask = deviceMessageHandler.SendMessageAsync(message, "input1"); Assert.False(sendMessageTask.IsCompleted); await deviceMessageHandler.ProcessMessageFeedbackAsync(Guid.NewGuid().ToString(), FeedbackStatus.Complete); Assert.False(sendMessageTask.IsCompleted); } [Fact] public async Task X509DeviceCanSendMessageTest() { var connMgr = new Mock<IConnectionManager>(); connMgr.Setup(c => c.AddDeviceConnection(It.IsAny<IIdentity>(), It.IsAny<IDeviceProxy>())); var identity = Mock.Of<IModuleIdentity>(m => m.DeviceId == "device1" && m.ModuleId == "module1" && m.Id == "device1/module1"); var edgeHub = Mock.Of<IEdgeHub>(); Option<ICloudProxy> cloudProxy = Option.None<ICloudProxy>(); bool messageReceived = false; string lockToken = null; var underlyingDeviceProxy = new Mock<IDeviceProxy>(); underlyingDeviceProxy.Setup(d => d.SendMessageAsync(It.IsAny<IMessage>(), It.IsAny<string>())) .Callback<IMessage, string>( (m, i) => { messageReceived = true; lockToken = m.SystemProperties[SystemProperties.LockToken]; }) .Returns(Task.CompletedTask); connMgr.Setup(c => c.GetCloudConnection(It.IsAny<string>())).Returns(Task.FromResult(cloudProxy)); var deviceMessageHandler = new DeviceMessageHandler(identity, edgeHub, connMgr.Object); deviceMessageHandler.BindDeviceProxy(underlyingDeviceProxy.Object); IMessage message = new EdgeMessage.Builder(new byte[0]).Build(); // send message to x509 device Task sendMessageTask = deviceMessageHandler.SendMessageAsync(message, "input1"); await deviceMessageHandler.ProcessMessageFeedbackAsync(lockToken, FeedbackStatus.Complete); Assert.True(messageReceived); Assert.True(sendMessageTask.IsCompletedSuccessfully); } [Fact] public async Task ProcessDesiredPropertiesUpdateSubscription() { // Arrange var edgeHub = new Mock<IEdgeHub>(); edgeHub.Setup(e => e.AddSubscription("d1", DeviceSubscription.DesiredPropertyUpdates)).Returns(Task.CompletedTask); var connMgr = Mock.Of<IConnectionManager>(); var identity = Mock.Of<IDeviceIdentity>(i => i.Id == "d1"); var deviceProxy = new Mock<IDeviceProxy>(); IMessage sentMessage = null; deviceProxy.Setup(d => d.SendTwinUpdate(It.IsAny<IMessage>())) .Callback<IMessage>(m => sentMessage = m) .Returns(Task.CompletedTask); var listener = new DeviceMessageHandler(identity, edgeHub.Object, connMgr); listener.BindDeviceProxy(deviceProxy.Object); string correlationId = Guid.NewGuid().ToString(); // Act await listener.AddDesiredPropertyUpdatesSubscription(correlationId); // Assert Assert.NotNull(sentMessage); Assert.Equal(correlationId, sentMessage.SystemProperties[SystemProperties.CorrelationId]); Assert.Equal("200", sentMessage.SystemProperties[SystemProperties.StatusCode]); edgeHub.VerifyAll(); } [Fact] public async Task ProcessRemoveDesiredPropertiesUpdateSubscription() { // Arrange var edgeHub = new Mock<IEdgeHub>(); edgeHub.Setup(e => e.RemoveSubscription("d1", DeviceSubscription.DesiredPropertyUpdates)) .Returns(Task.CompletedTask); var connMgr = Mock.Of<IConnectionManager>(); var identity = Mock.Of<IDeviceIdentity>(i => i.Id == "d1"); var deviceProxy = new Mock<IDeviceProxy>(); IMessage sentMessage = null; deviceProxy.Setup(d => d.SendTwinUpdate(It.IsAny<IMessage>())) .Callback<IMessage>(m => sentMessage = m) .Returns(Task.CompletedTask); var listener = new DeviceMessageHandler(identity, edgeHub.Object, connMgr); listener.BindDeviceProxy(deviceProxy.Object); string correlationId = Guid.NewGuid().ToString(); // Act await listener.RemoveDesiredPropertyUpdatesSubscription(correlationId); // Assert Assert.NotNull(sentMessage); Assert.Equal(correlationId, sentMessage.SystemProperties[SystemProperties.CorrelationId]); Assert.Equal("200", sentMessage.SystemProperties[SystemProperties.StatusCode]); edgeHub.VerifyAll(); } DeviceMessageHandler GetDeviceMessageHandler() { var identity = Mock.Of<IModuleIdentity>(m => m.DeviceId == "device1" && m.ModuleId == "module1" && m.Id == "device1/module1"); var cloudProxy = new Mock<ICloudProxy>(); var edgeHub = Mock.Of<IEdgeHub>(); var underlyingDeviceProxy = new Mock<IDeviceProxy>(); underlyingDeviceProxy.Setup(d => d.InvokeMethodAsync(It.IsAny<DirectMethodRequest>())).ReturnsAsync(default(DirectMethodResponse)); underlyingDeviceProxy.Setup(d => d.SendC2DMessageAsync(It.IsAny<IMessage>())).Returns(Task.CompletedTask); var connMgr = new Mock<IConnectionManager>(); connMgr.Setup(c => c.AddDeviceConnection(It.IsAny<IIdentity>(), It.IsAny<IDeviceProxy>())); connMgr.Setup(c => c.GetCloudConnection(It.IsAny<string>())).Returns(Task.FromResult(Option.Some(cloudProxy.Object))); var deviceMessageHandler = new DeviceMessageHandler(identity, edgeHub, connMgr.Object); deviceMessageHandler.BindDeviceProxy(underlyingDeviceProxy.Object); return deviceMessageHandler; } } }
54.238938
143
0.651275
[ "MIT" ]
CIPop/iotedge
edge-hub/test/Microsoft.Azure.Devices.Edge.Hub.Core.Test/DeviceMessageHandlerTest.cs
18,387
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Xamarin.Forms; using Xamarin.Forms.Xaml; namespace BikeDataProject.App.Views { [XamlCompilation(XamlCompilationOptions.Compile)] public partial class TrackingPage : ContentPage { public TrackingPage() { InitializeComponent(); } } }
20.4
53
0.703431
[ "MIT" ]
bikedataproject/app
src/BikeDataProject.App/Views/TrackingPage.xaml.cs
410
C#
using System.Reflection; using System.Runtime.CompilerServices; // Information about this assembly is defined by the following attributes. // Change them to the values specific to your project. [assembly: AssemblyTitle("ImageModeration")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Sailr Solutions Ltd")] [assembly: AssemblyProduct("")] [assembly: AssemblyCopyright("")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // The assembly version has the format "{Major}.{Minor}.{Build}.{Revision}". // The form "{Major}.{Minor}.*" will automatically update the build and revision, // and "{Major}.{Minor}.{Build}.*" will update just the revision. [assembly: AssemblyVersion("1.0.*")] // The following attributes are used to specify the signing key for the assembly, // if desired. See the Mono documentation for more information about signing. //[assembly: AssemblyDelaySign(false)] //[assembly: AssemblyKeyFile("")]
37.037037
82
0.746
[ "MIT" ]
PacktPublishing/Implementing-Azure-Cognitive-Services-for-Language
Section 4/4.5/after/ImageModeration/ImageModeration/Properties/AssemblyInfo.cs
1,002
C#
using UnityEngine; using System.Collections; public class CustomObject { static public GameObject CreateObject(string type = "GameObject", Obj.Colour color = Obj.Colour.WHITE) { GameObject obj = new GameObject(type); obj.AddComponent<MeshFilter>();//.mesh = (Mesh) typeof(CustomMesh).GetMethod(type).Invoke(null, null); //CustomMesh.CurveWall(); obj.AddComponent<MeshRenderer>().material = Game.BaseMaterial; obj.GetComponent<Renderer>().material.color = Game.GetColor(color); return obj; //type.GetMethod("Join").Invoke(null, new object[]{node.ChildNodes[i], obj}); } static public GameObject CreateBlockRoom() { GameObject room = BlockRoom.Create(); return room; } static public GameObject CreatePrimitive(PrimitiveType type, bool collision = true, bool twoSideMesh = false) { GameObject obj = GameObject.CreatePrimitive(type); if(type == PrimitiveType.Sphere) { obj.GetComponent<MeshFilter>().mesh = OctahedronSphereCreator.Create(5, 0.5f); } else if(type == PrimitiveType.Quad && twoSideMesh) { Mesh mesh = obj.GetComponent<MeshFilter>().mesh; //int[] tris = new int[mesh.triangles.Length * 2]; string s = ""; foreach(int i in mesh.triangles) s += i.ToString() + " "; int[] tris = new int[] { 0, 1, 2, 1, 0, 3, 2, 1, 0, 3, 0, 1 }; //Debug.LogWarning(s); /*for(int i=0; i<mesh.triangles.Length*2; ++i) { // 0 1 2 3 4 5 6 7 8 9 if(i >= mesh.triangles.Length) { if(i%3 == 0) { tris[i] = mesh.triangles[i - mesh.triangles.Length + 1]; } else if((i-1)%3 == 0) { tris[i] = mesh.triangles[i - mesh.triangles.Length - 1]; } } else { tris[i] = mesh.triangles[i]; } }*/ mesh.triangles = tris; } obj.GetComponent<Renderer>().material = Game.BaseMaterial; if(!collision) { Object.Destroy(obj.GetComponent<Collider>()); } return obj; } static public GameObject CreateAtom(int eCount) { float coreSize = 0.4f; GameObject atom, core; GameObject[] e = new GameObject[eCount]; atom = new GameObject("Atom"); core = CustomObject.CreatePrimitive(PrimitiveType.Sphere); core.transform.localScale = Vector3.one*coreSize; Object.Destroy(core.GetComponent<Collider>()); core.GetComponent<Renderer>().material = Ball.whiteBall; core.transform.parent = atom.transform; for(int i=0; i<eCount; ++i) { GameObject tmp = CustomObject.CreatePrimitive(PrimitiveType.Sphere); e[i] = new GameObject("Electron"); Object.Destroy(tmp.GetComponent<Collider>()); tmp.transform.localScale = Vector3.one*0.05f; tmp.transform.parent = e[i].transform; tmp.transform.localPosition = Vector3.up*coreSize/2f + Vector3.up * Random.value * 0.6f; e[i].transform.transform.parent = atom.transform; e[i].transform.localRotation = Random.rotationUniform; tmp.GetComponent<Renderer>().material = Ball.blackBall; e[i].AddComponent<Animation>().wrapMode = WrapMode.Loop; float timeForAnimation = 2f; Quaternion start = e[i].transform.localRotation;//Quaternion.Euler(new Vector3(90, 0, 0)); Quaternion qua = Quaternion.Euler(e[i].transform.localEulerAngles + new Vector3(0, 180, 0));//Quaternion.Euler(new Vector3(90, 180, 0));//Quaternion.Euler(new Vector3(90, 180, 0)); Quaternion qua2 = Quaternion.Euler(e[i].transform.localEulerAngles + new Vector3(0, 360, 0));//Quaternion.Euler(new Vector3(90, 360, 0)); AnimationCurve curveX = new AnimationCurve(new Keyframe(0, start.x), new Keyframe(timeForAnimation/2f, qua.x), new Keyframe(timeForAnimation, qua2.x)); AnimationCurve curveY = new AnimationCurve(new Keyframe(0, start.y), new Keyframe(timeForAnimation/2f, qua.y), new Keyframe(timeForAnimation, qua2.y)); AnimationCurve curveZ = new AnimationCurve(new Keyframe(0, start.z), new Keyframe(timeForAnimation/2f, qua.z), new Keyframe(timeForAnimation, qua2.z)); AnimationCurve curveW = new AnimationCurve(new Keyframe(0, start.w), new Keyframe(timeForAnimation/2f, qua.w), new Keyframe(timeForAnimation, qua2.w)); curveX.SmoothTangents(0, 0); curveX.SmoothTangents(1, 0); curveX.SmoothTangents(2, 0); curveY.SmoothTangents(0, 0); curveY.SmoothTangents(1, 0); curveY.SmoothTangents(2, 0); curveZ.SmoothTangents(0, 0); curveZ.SmoothTangents(1, 0); curveZ.SmoothTangents(2, 0); curveW.SmoothTangents(0, 0); curveW.SmoothTangents(1, 0); curveW.SmoothTangents(2, 0); AnimationClip clip = new AnimationClip(); clip.legacy = true; clip.SetCurve("", typeof(Transform), "localRotation.x", curveX); clip.SetCurve("", typeof(Transform), "localRotation.y", curveY); clip.SetCurve("", typeof(Transform), "localRotation.z", curveZ); clip.SetCurve("", typeof(Transform), "localRotation.w", curveW); clip.EnsureQuaternionContinuity(); e[i].GetComponent<Animation>().AddClip(clip, "anim"); e[i].GetComponent<Animation>().Play("anim"); } return atom; } static public Switcher CreateSwitcher() { GameObject obj = new GameObject("Switcher"); Switcher switcher = obj.AddComponent<Switcher>(); switcher.Init(); return switcher; } static public GameObject ArrowForGravityGun(float radius = 0.5f, float D = 1f, int vertsCount = 25) { GameObject arrow = CreateObject("GravityGunArrow", Obj.Colour.BLACK); arrow.GetComponent<MeshFilter>().mesh = CustomMesh.ArrowForGravityGun(radius, D, vertsCount); return arrow; } static public GameObject Exit() { GameObject exit = new GameObject("Exit"), ptr = CustomObject.Pointer(); float height = 1.6f, width = 1, thick = 0.08f, doorHeight = width*0.25f; GameObject[] lines = new GameObject[8]; lines[0] = Word.I__(height/2f - doorHeight, thick); lines[7] = Word.I__(height/2f - doorHeight, thick); lines[1] = Word.I__(height, thick); lines[2] = Word.I__(height, thick); lines[3] = Word.I__(width, thick); lines[4] = Word.I__(width - doorHeight, thick); //lines[4] = Word.I__(width, thick); lines[5] = Word.I__(width/4f * Mathf.Sqrt(2), thick); lines[6] = Word.I__(width/4f * Mathf.Sqrt(2), thick); foreach(GameObject obj in lines) { obj.transform.parent = exit.transform; } ptr.transform.parent = exit.transform; ptr.transform.localScale = Vector3.one * 0.3f; ptr.transform.localPosition = Vector3.right * (-0.5f); lines[0].transform.localPosition = new Vector3(-width/2f, 0, -height/2f); lines[0].transform.localEulerAngles = new Vector3(0, -90, 0); lines[7].transform.localPosition = new Vector3(-width/2f, 0, doorHeight); lines[7].transform.localEulerAngles = new Vector3(0, -90, 0); lines[1].transform.localPosition = new Vector3(width/2f, 0, -height/2f); lines[1].transform.localEulerAngles = new Vector3(0, -90, 0); lines[2].transform.localPosition = new Vector3(width/2f - doorHeight, 0, -height/2f - doorHeight); lines[2].transform.localEulerAngles = new Vector3(0, -90, 0); lines[3].transform.localPosition = new Vector3(-width/2f, 0, height/2f - thick/2f); lines[4].transform.localPosition = new Vector3(-width/2f, 0, -height/2f + thick/2f); lines[5].transform.localPosition = new Vector3(width/2f - thick/9f, 0, height/2f - thick/2.6f); lines[5].transform.localEulerAngles = new Vector3(0, 135, 0); lines[6].transform.localPosition = new Vector3(width/2f + thick/9f, 0, -height/2f + thick/2.6f); lines[6].transform.localEulerAngles = new Vector3(0, 135, 0); return exit; } static public GameObject AnimationCube(Vector3 size, Obj.Colour color = Obj.Colour.WHITE) { GameObject cube = new GameObject("CustomCube"); GameObject qb = CustomObject.CreatePrimitive(PrimitiveType.Cube); qb.name = "QB"; qb.transform.localScale = size; qb.GetComponent<Renderer>().material.color = Game.GetColor(color); Color c = Game.GetColor( Game.ReverseColor(color) ); GameObject[] edge = new GameObject[12]; for(int i=0; i<edge.Length; ++i) { edge[i] = new GameObject(i.ToString()); GameObject edgeChild = CustomObject.CreatePrimitive(PrimitiveType.Cube, false); edgeChild.transform.parent = edge[i].transform; edgeChild.GetComponent<Renderer>().material.color = c; edge[i].name = i.ToString(); edge[i].transform.parent = cube.transform; Vector3 tmp = Vector3.one * Line.height; tmp[i/4] = size[i/4]; edge[i].transform.localScale = tmp; tmp = Vector3.zero; int ind1 = i/4 == 0 ? 1 : 0; int ind2 = i/4 != 2 ? 2 : 1; //int ind3 = (ind1==0 && ind2==1) ? 2 : ( (ind1==0 && ind2==2) ? 1 : 0 ); //Debug.Log(i.ToString() + "__" + ((2 * (int)(i/2))).ToString()); tmp[ind1] = size[ind1]/2f * ((2 * (int)(i/2))%4==0 ? 1 : -1); tmp[ind2] = size[ind2]/2f * (i%2==0 ? 1 : -1); tmp[i/4] = size[i/4] * 0.5f; edge[i].transform.localPosition = tmp; Vector3 childPosition = Vector3.zero; childPosition[i/4] = -0.5f; edgeChild.transform.localPosition = childPosition; edge[i].AddComponent<Animation>(); /*Vector3 zeroScale = edge[i].transform.localScale; zeroScale[i/4] = 0; Vector3 oneScale = edge[i].transform.localScale; oneScale[i/4] = 1f; AnimationClip clip = Game.CreateAnimationClip(Game.AnimationClipType.SCALE, zeroScale, oneScale, Game.drawTime); edge[i].AddComponent<Animation>().AddClip(clip, "Draw");*/ } qb.transform.parent = cube.transform; return cube; } static public GameObject Cube(Vector3 size, Obj.Colour color = Obj.Colour.WHITE) { GameObject cube = new GameObject("CustomCube"); GameObject qb = CustomObject.CreatePrimitive(PrimitiveType.Cube); qb.name = "QB"; qb.transform.localScale = size; qb.GetComponent<Renderer>().material.color = Game.GetColor(color); Color c = Game.GetColor( Game.ReverseColor(color) ); GameObject[] edge = new GameObject[12]; for(int i=0; i<edge.Length; ++i) { edge[i] = CustomObject.CreatePrimitive(PrimitiveType.Cube, false); edge[i].GetComponent<Renderer>().material.color = c; edge[i].name = i.ToString(); edge[i].transform.parent = cube.transform; Vector3 tmp = Vector3.one * (Line.height);// * 3.8f); tmp[i/4] = size[i/4]; edge[i].transform.localScale = tmp; tmp = Vector3.zero; int ind1 = i/4 == 0 ? 1 : 0; int ind2 = i/4 != 2 ? 2 : 1; //Debug.Log(i.ToString() + "__" + ((2 * (int)(i/2))).ToString()); tmp[ind1] = size[ind1]/2f * ((2 * (int)(i/2))%4==0 ? 1 : -1); //2.3 tmp[ind2] = size[ind2]/2f * (i%2==0 ? 1 : -1); edge[i].transform.localPosition = tmp; } qb.transform.parent = cube.transform; return cube; } static public GameObject CreateSingleBubble(float radius, Obj.Colour color, float beginTime = 0.0f, float endTime = 1.5f, float scale = 1f, float beginScale = 0f) { GameObject circle = CustomObject.Circle(radius, color); //circle.GetComponent<Renderer> ().material.renderQueue -= 1; AnimationClip clip = new AnimationClip(); clip.legacy = true; AnimationCurve curve = new AnimationCurve(new Keyframe(beginTime, beginScale), new Keyframe(endTime, scale)); clip.SetCurve("", typeof(Transform), "localScale.x", curve); clip.SetCurve("", typeof(Transform), "localScale.y", curve); clip.SetCurve("", typeof(Transform), "localScale.z", curve); Animation anim = circle.AddComponent<Animation>(); anim.AddClip(clip, "Draw"); AnimationCurve curve2 = new AnimationCurve(new Keyframe(beginTime, scale), new Keyframe(endTime, beginScale)); AnimationClip clip2 = new AnimationClip(); clip2.legacy = true; clip2.SetCurve("", typeof(Transform), "localScale.x", curve2); clip2.SetCurve("", typeof(Transform), "localScale.y", curve2); clip2.SetCurve("", typeof(Transform), "localScale.z", curve2); anim.AddClip(clip2, "Hide"); return circle; } static public GameObject CreateBubbles(int minCount, int maxCount, Vector2 size, Obj.Colour color, int renderQueue = 0) { int circleCount = UnityEngine.Random.Range(minCount, maxCount); GameObject circleParent = new GameObject("CircleParent"); GameObject[] circle = new GameObject[circleCount]; float minX = -size.x*0.5f; float maxX = -minX; float minZ = -size.y*0.5f; float maxZ = -minZ; for(int i=0; i<circleCount; ++i) { //float area = size.x * size.y; circle[i] = CustomObject.Circle(i==0 ? size.x*0.7f : UnityEngine.Random.Range(size.x/35f, size.x/2f), color); //size.x/35f, size.x/2f), color); Game.SetRenderQueue(circle[i], renderQueue); //circle[i].GetComponent<Renderer>().material.renderQueue -= 1; circle[i].transform.parent = circleParent.transform; if(i != 0 ) circle[i].transform.localPosition = new Vector3(UnityEngine.Random.Range(minX, maxX), 0, UnityEngine.Random.Range(minZ, maxZ)); AnimationClip clip = new AnimationClip(); clip.legacy = true; AnimationCurve curve = new AnimationCurve(new Keyframe(i==0 ? Game.drawTime/4f : 0, 0), new Keyframe(Game.drawTime + Game.drawTime*(i==0?0.5f:0.25f), circle[i].transform.localScale.x)); clip.SetCurve("", typeof(Transform), "localScale.x", curve); clip.SetCurve("", typeof(Transform), "localScale.y", curve); clip.SetCurve("", typeof(Transform), "localScale.z", curve); Animation anim = circle[i].AddComponent<Animation>(); anim.AddClip(clip, "Draw"); anim.Play("Draw"); //curve[0] = new AnimationCurve(new Keyframe(), new Keyframe); } //circleParent.transform.localEulerAngles += Vector3.right * 90f; //circleParent.transform.position = door.transform.position; //circleParent.transform.parent = Level.current.transform; return circleParent; } static public GameObject Pointer() { GameObject pointer = CreateObject("Pointer", Obj.Colour.BLACK); pointer.GetComponent<MeshFilter>().mesh = CustomMesh.Pointer(); return pointer; } static public GameObject Circle(float radius = 0.5f, Obj.Colour color = Obj.Colour.WHITE, bool withCollider = false, int vertsCount = 50) { GameObject obj = new GameObject("Circle"); obj.AddComponent<MeshFilter>().mesh = CustomMesh.Circle(vertsCount); obj.AddComponent<MeshRenderer> ().material = Game.BaseMaterial; obj.GetComponent<Renderer>().material.color = Game.GetColor(color); if(withCollider) obj.AddComponent<BoxCollider>(); obj.transform.localScale *= (radius*2f); return obj; } static public GameObject Semiircle(Obj.Colour color = Obj.Colour.WHITE, bool withCollider = false, int vertsCount = 25) { GameObject obj = new GameObject("Semicircle"); obj.AddComponent<MeshFilter>().mesh = CustomMesh.Semicircle(vertsCount); obj.AddComponent<MeshRenderer>().material = Game.BaseMaterial; obj.GetComponent<Renderer>().material.color = Game.GetColor(color); if(withCollider) obj.AddComponent<BoxCollider>(); return obj; } static public GameObject SettingsButton() { float radius = 0.2f; GameObject border, circle; GameObject[] dot = new GameObject[3]; border = CircleBorder(radius, Obj.Colour.BLACK, 0.01f); circle = Circle(radius, Obj.Colour.WHITE); circle.name = "Button"; //circle.transform.localScale *= (radius*2f); border.transform.parent = circle.transform; border.transform.localPosition = Vector3.up*0.002f; for(int i=0; i<dot.Length; ++i) { dot[i] = Circle(radius/6f, Obj.Colour.BLACK); Vector3 pos = Vector3.up*0.001f; pos.x = (i-1) * radius/2f; dot[i].transform.localPosition = pos; dot[i].transform.parent = circle.transform; } return circle; } static public GameObject Arrow() { GameObject button; //border = CircleBorder(radius, Obj.Colour.WHITE, 0.01f); button = new GameObject();//Circle(radius, Obj.Colour.BLACK); button.name = "Button"; //circle.transform.localScale *= (radius*2f); //border.transform.parent = circle.transform; GameObject arrow = Word.GetGameObject(CustomMesh.ShortPointer(), Obj.Colour.BLACK); arrow.transform.parent = button.transform; arrow.transform.localScale = new Vector3 (-0.5f, 1, -0.04f);//*1.5f; //arrow.transform.localPosition = new Vector3(0.15f, 0.001f, 0); arrow.transform.localEulerAngles = new Vector3 (0, 90f, 90f); if(arrow.GetComponent<Renderer>() != null) { arrow.GetComponent<Renderer>().material.renderQueue = 3000; //text.GetComponent<Renderer>().material = materialForMask; } if(arrow.GetComponent<Renderer>() != null) { arrow.GetComponent<Renderer>().material.shader = Shader.Find("InverseColor"); arrow.GetComponent<Renderer>().material.color = Game.White; } return button; } static public GameObject ArrowButton() { GameObject button; //border = CircleBorder(radius, Obj.Colour.WHITE, 0.01f); button = new GameObject();//Circle(radius, Obj.Colour.BLACK); button.name = "Button"; //circle.transform.localScale *= (radius*2f); //border.transform.parent = circle.transform; GameObject arrow = Word.GetGameObject(CustomMesh.ShortPointer(), Obj.Colour.WHITE); arrow.transform.parent = button.transform; arrow.transform.localScale = new Vector3(-1.2f, 1, -0.25f); arrow.transform.localPosition = new Vector3(0.15f, 0.001f, 0); //button.AddComponent<BoxCollider>(); return button; } static public GameObject ExitButton() { float radius = 0.2f; GameObject border, circle; //GameObject[] dot = new GameObject[3]; border = CircleBorder(radius, Obj.Colour.BLACK, 0.01f); circle = Circle(radius, Obj.Colour.WHITE); circle.name = "Button"; //circle.transform.localScale *= (radius*2f); border.transform.parent = circle.transform; border.transform.localPosition = Vector3.up*0.002f; GameObject exit = Exit(); exit.transform.parent = circle.transform; exit.transform.localScale = new Vector3(-0.38f, 0.4f, -0.38f); exit.transform.localPosition = new Vector3(-0.015f, 0.001f, 0); /*for(int i=0; i<dot.Length; ++i) { dot[i] = Circle(radius/6f, Obj.Colour.BLACK); Vector3 pos = Vector3.up*0.001f; pos.x = (i-1) * radius/2f; dot[i].transform.localPosition = pos; dot[i].transform.parent = circle.transform; }*/ return circle; } static public GameObject CircleBorder(float radius, Obj.Colour color = Obj.Colour.WHITE, float thick = 0.02f, int vertsCount = 50) { GameObject border = CreateObject("CircleBorder", color); border.GetComponent<MeshFilter>().mesh = CustomMesh.CircleBorder(radius, thick, vertsCount); //border.transform.localScale *= (radius*2f); return border; } static public GameObject SemiircleBorder(float radius, Obj.Colour color = Obj.Colour.WHITE, float thick = 0.02f) { GameObject border = CreateObject("SemircleBorder", color); border.GetComponent<MeshFilter>().mesh = CustomMesh.SemicircleBorder(radius, thick*50f); //border.transform.localScale *= (radius*2f); return border; } static public GameObject Hill(float length, float radius, Obj.Colour color = Obj.Colour.WHITE, int vertsCount = 25) { GameObject hill = new GameObject("Hill"); GameObject wall = CreateObject("CurveWall", color); //wall.tag = "Side"; wall.GetComponent<MeshFilter>().mesh = CustomMesh.CurveWall(vertsCount, 90, radius, true); wall.transform.parent = hill.transform; wall.transform.localScale = new Vector3(1, length, 1); wall.AddComponent<CapsuleCollider>().center = Vector3.zero; wall.layer = LayerMask.NameToLayer("Hill"); float thick = 0.02f; GameObject border = SemiircleBorder(radius + thick/2f, Game.ReverseColor(color), thick); border.transform.parent = hill.transform; GameObject border2 = SemiircleBorder(radius + thick/2f, Game.ReverseColor(color), thick); border2.transform.parent = hill.transform; border.transform.localPosition = new Vector3(0, -length/2f, 0); border2.transform.localPosition = new Vector3(0, length/2f, 0); border2.transform.localScale = new Vector3(1, -1, 1); hill.transform.localEulerAngles = new Vector3(-90, -90, 0); wall.GetComponent<Renderer>().enabled = false; return hill; } static public GameObject SemicircleRoom(Vector3 size, Obj.Colour color = Obj.Colour.WHITE, int vertsCount = 25) { GameObject up = Semiircle(color, true), down = Semiircle(color, true); GameObject wall, upBorder, downBorder, semicircleRoom = new GameObject("SemicircleRoom"); up.transform.localPosition = Vector3.up/2f; down.transform.localPosition = -Vector3.up/2f; up.transform.localEulerAngles = Vector3.forward * 180f; up.transform.parent = down.transform.parent = semicircleRoom.transform; wall = CreateObject("CurveWall", color); wall.tag = "Side"; wall.GetComponent<MeshFilter>().mesh = CustomMesh.CurveWall(vertsCount); wall.transform.parent = semicircleRoom.transform; wall.AddComponent<MeshCollider>(); //obj.AddComponent<BoxCollider>(); downBorder = CreateObject("SemicircleBorder", Game.ReverseColor(color)); upBorder = CreateObject("SemicircleBorder", Game.ReverseColor(color)); downBorder.GetComponent<MeshFilter>().mesh = CustomMesh.SemicircleBorder(0.5f, size.x); upBorder.GetComponent<MeshFilter>().mesh = CustomMesh.SemicircleBorder(0.5f, size.x); upBorder.transform.localEulerAngles = Vector3.forward * 180f; upBorder.transform.localPosition = Vector3.up/2f; downBorder.transform.localPosition = -Vector3.up/2f; upBorder.transform.parent = downBorder.transform.parent = semicircleRoom.transform; /*upBorder_ = CreateObject("CurveWall", Obj.Colour.BLACK); downBorder_ = CreateObject("CurveWall", Obj.Colour.BLACK); upBorder_.transform.localPosition = Vector3.up/2f; downBorder_.transform.localPosition = -Vector3.up/2f;*/ GameObject b1 = CreateObject("Border", Game.ReverseColor(color)); b1.GetComponent<MeshFilter>().mesh = CustomMesh.CurveWall(vertsCount); b1.transform.localScale = new Vector3(1f, Line.height/size.y, 1f); b1.transform.localPosition = -Vector3.up/2f + Vector3.up*(Line.height/size.y/2f) - Vector3.forward*0.0001f; GameObject b2 = CreateObject("Border", Game.ReverseColor(color)); b2.GetComponent<MeshFilter>().mesh = CustomMesh.CurveWall(vertsCount); b2.transform.localScale = new Vector3(1f, Line.height/size.y, 1f); b2.transform.localPosition = Vector3.up/2f - Vector3.up*(Line.height/size.y/2f) - Vector3.forward*0.0001f; b1.transform.parent = b2.transform.parent = semicircleRoom.transform; semicircleRoom.transform.localScale = size; return semicircleRoom; } }
33.943598
307
0.695918
[ "MIT" ]
NikolaySkakun/coloristique-origins
Assets/Scripts/Utilities/CustomObject.cs
22,269
C#
using System; using WinReform.Domain.WinApi; using WinReform.Domain.Windows; using Xunit; namespace WinReform.Domain.Tests.Windows { /// <summary> /// Tests for the <see cref="Window"/> /// </summary> public class WindowTests { #region Equals Tests [Fact] public void Equals_EqualWindow_ShouldReturnTrue() { // Prepare var window1 = new Window { Id = 1, WindowHandle = (IntPtr)1, Description = "Window", Dimensions = new Rect() }; var window2 = new Window { Id = 1, WindowHandle = (IntPtr)1, Description = "Window", Dimensions = new Rect() }; // Act // Assert Assert.True(window1.Equals(window2)); } [Fact] public void Equals_UnEqualWindow_ShouldReturnFalse() { // Prepare var window1 = new Window { Id = 1, WindowHandle = (IntPtr)1, Description = "Window1", Dimensions = new Rect() }; var window2 = new Window { Id = 2, WindowHandle = (IntPtr)2, Description = "Window2", Dimensions = new Rect() }; // Act // Assert Assert.False(window1.Equals(window2)); } [Fact] public void Equals_InvalidType_ShouldReturnFalse() { // Prepare var window1 = new Window { Id = 1, WindowHandle = (IntPtr)1, Description = "Window", Dimensions = new Rect() }; // Act // Assert Assert.False(window1.Equals("Invalid Type")); } #endregion Equals Tests #region CompareTo Tests [Fact] public void CompareTo_EqualId_ShouldReturnZero() { // Prepare var window1 = new Window { Id = 1, WindowHandle = (IntPtr)1, Description = "Window1", Dimensions = new Rect() }; var window2 = new Window { Id = 1, WindowHandle = (IntPtr)2, Description = "Window2", Dimensions = new Rect() }; // Act // Assert Assert.True(window1.CompareTo(window2) == 0); } [Fact] public void CompareTo_UnEqualId_ShouldReturnNegativeOne() { // Prepare var window1 = new Window { Id = 1, WindowHandle = (IntPtr)1, Description = "Window1", Dimensions = new Rect() }; var window2 = new Window { Id = 2, WindowHandle = (IntPtr)2, Description = "Window2", Dimensions = new Rect() }; // Act // Assert Assert.True(window1.CompareTo(window2) == -1); } [Fact] public void CompareTo_NullInstances_ShouldReturnNegativeOne() { // Prepare var window1 = new Window { Id = 1, WindowHandle = (IntPtr)1, Description = "Window1", Dimensions = new Rect() }; // Act // Assert Assert.True(window1.CompareTo(null) == -1); } #endregion CompareTo Tests } }
30.112245
124
0.547272
[ "Apache-2.0" ]
AKruimink/WinReform
src/Tests/WinReform.Domain.Tests/Windows/WindowTests.cs
2,953
C#
using Job.Notification.Contracts; namespace JobService { public interface IClientNotificationService { void JobNotification(string clientId, int jobId, JobStatus status); } }
17.25
75
0.700483
[ "MIT" ]
nrawat207/SignalR-NotificationService-WPF
src/SignalR-NotificationService-WPF/JobService/Infrastructure/IClientNotificationService.cs
209
C#
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Text; using System.Windows.Forms; using System.Reflection; namespace BlogDownloader { public partial class frmAbout : Form { public frmAbout() { InitializeComponent(); } private void button1_Click(object sender, EventArgs e) { this.Dispose(); } private void linkLabel2_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e) { System.Diagnostics.Process.Start("http://www.douyuehan.com"); } private void frmAbout_Load(object sender, EventArgs e) { } } }
21.351351
92
0.593671
[ "Apache-2.0" ]
songboriceboy/SimpleFrameWork
BlogDownloader/frmAbout.cs
790
C#
namespace SKIT.FlurlHttpClient.Wechat.Api.Models { /// <summary> /// <para>表示 [POST] /componenttcb/dbimport 接口的响应。</para> /// </summary> public class ComponentTcbDbImportResponse : WechatApiResponse { /// <summary> /// 获取或设置导入任务 ID。 /// </summary> [Newtonsoft.Json.JsonProperty("job_id")] [System.Text.Json.Serialization.JsonPropertyName("job_id")] public int JobId { get; set; } } }
28.5625
67
0.608315
[ "MIT" ]
OrchesAdam/DotNetCore.SKIT.FlurlHttpClient.Wechat
src/SKIT.FlurlHttpClient.Wechat.Api/Models/ComponentTcb/Database/ComponentTcbDbImportResponse.cs
495
C#
using Auth0.ManagementApi.Models; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace AgoraAcademy.AgoraEgo.Server.Interfaces { /// <summary> /// 在Auth0 内的登录用API的所有可用用户身份获取 /// </summary> public interface IAvailableRoleGetterService { /// <summary> /// 获取可用用户身份 /// </summary> /// <returns>可用用户身份</returns> Task<Role[]> GetAvailableRoles(); } }
22.190476
49
0.648069
[ "Apache-2.0" ]
AgoraAcademy/Agora_E-go
Server/Interfaces/IAvailableRoleGetterService.cs
530
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.WebPubSub.Cmdlets { using static Microsoft.Azure.PowerShell.Cmdlets.WebPubSub.Runtime.Extensions; using System; /// <summary>Operation to update an exiting resource.</summary> /// <remarks> /// [OpenAPI] Update=>PATCH:"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.SignalRService/WebPubSub/{resourceName}" /// </remarks> [global::System.Management.Automation.Cmdlet(global::System.Management.Automation.VerbsData.Update, @"AzWebPubSub_UpdateViaIdentityExpanded", SupportsShouldProcess = true)] [global::System.Management.Automation.OutputType(typeof(Microsoft.Azure.PowerShell.Cmdlets.WebPubSub.Models.Api20211001.IWebPubSubResource))] [global::Microsoft.Azure.PowerShell.Cmdlets.WebPubSub.Description(@"Operation to update an exiting resource.")] [global::Microsoft.Azure.PowerShell.Cmdlets.WebPubSub.Generated] public partial class UpdateAzWebPubSub_UpdateViaIdentityExpanded : global::System.Management.Automation.PSCmdlet, Microsoft.Azure.PowerShell.Cmdlets.WebPubSub.Runtime.IEventListener { /// <summary>A unique id generatd for the this cmdlet when it is instantiated.</summary> private string __correlationId = System.Guid.NewGuid().ToString(); /// <summary>A copy of the Invocation Info (necessary to allow asJob to clone this cmdlet)</summary> private global::System.Management.Automation.InvocationInfo __invocationInfo; /// <summary>A unique id generatd for the this cmdlet when ProcessRecord() is called.</summary> private string __processRecordId; /// <summary> /// The <see cref="global::System.Threading.CancellationTokenSource" /> for this operation. /// </summary> private global::System.Threading.CancellationTokenSource _cancellationTokenSource = new global::System.Threading.CancellationTokenSource(); /// <summary>when specified, runs this cmdlet as a PowerShell job</summary> [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Run the command as a job")] [global::Microsoft.Azure.PowerShell.Cmdlets.WebPubSub.Category(global::Microsoft.Azure.PowerShell.Cmdlets.WebPubSub.ParameterCategory.Runtime)] public global::System.Management.Automation.SwitchParameter AsJob { get; set; } /// <summary>Wait for .NET debugger to attach</summary> [global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "Wait for .NET debugger to attach")] [global::Microsoft.Azure.PowerShell.Cmdlets.WebPubSub.Category(global::Microsoft.Azure.PowerShell.Cmdlets.WebPubSub.ParameterCategory.Runtime)] public global::System.Management.Automation.SwitchParameter Break { get; set; } /// <summary>The reference to the client API class.</summary> public Microsoft.Azure.PowerShell.Cmdlets.WebPubSub.WebPubSub Client => Microsoft.Azure.PowerShell.Cmdlets.WebPubSub.Module.Instance.ClientAPI; /// <summary> /// The credentials, account, tenant, and subscription used for communication with Azure /// </summary> [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "The credentials, account, tenant, and subscription used for communication with Azure.")] [global::System.Management.Automation.ValidateNotNull] [global::System.Management.Automation.Alias("AzureRMContext", "AzureCredential")] [global::Microsoft.Azure.PowerShell.Cmdlets.WebPubSub.Category(global::Microsoft.Azure.PowerShell.Cmdlets.WebPubSub.ParameterCategory.Azure)] public global::System.Management.Automation.PSObject DefaultProfile { get; set; } /// <summary> /// DisableLocalAuthEnable or disable aad authWhen set as true, connection with AuthType=aad won't work. /// </summary> [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "DisableLocalAuthEnable or disable aad authWhen set as true, connection with AuthType=aad won't work.")] [global::Microsoft.Azure.PowerShell.Cmdlets.WebPubSub.Category(global::Microsoft.Azure.PowerShell.Cmdlets.WebPubSub.ParameterCategory.Body)] [Microsoft.Azure.PowerShell.Cmdlets.WebPubSub.Runtime.Info( Required = false, ReadOnly = false, Description = @"DisableLocalAuthEnable or disable aad authWhen set as true, connection with AuthType=aad won't work.", SerializedName = @"disableAadAuth", PossibleTypes = new [] { typeof(global::System.Management.Automation.SwitchParameter) })] public global::System.Management.Automation.SwitchParameter DisableAadAuth { get => ParametersBody.DisableAadAuth ?? default(global::System.Management.Automation.SwitchParameter); set => ParametersBody.DisableAadAuth = value; } /// <summary> /// DisableLocalAuthEnable or disable local auth with AccessKeyWhen set as true, connection with AccessKey=xxx won't work. /// </summary> [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "DisableLocalAuthEnable or disable local auth with AccessKeyWhen set as true, connection with AccessKey=xxx won't work.")] [global::Microsoft.Azure.PowerShell.Cmdlets.WebPubSub.Category(global::Microsoft.Azure.PowerShell.Cmdlets.WebPubSub.ParameterCategory.Body)] [Microsoft.Azure.PowerShell.Cmdlets.WebPubSub.Runtime.Info( Required = false, ReadOnly = false, Description = @"DisableLocalAuthEnable or disable local auth with AccessKeyWhen set as true, connection with AccessKey=xxx won't work.", SerializedName = @"disableLocalAuth", PossibleTypes = new [] { typeof(global::System.Management.Automation.SwitchParameter) })] public global::System.Management.Automation.SwitchParameter DisableLocalAuth { get => ParametersBody.DisableLocalAuth ?? default(global::System.Management.Automation.SwitchParameter); set => ParametersBody.DisableLocalAuth = value; } /// <summary>Request client certificate during TLS handshake if enabled</summary> [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Request client certificate during TLS handshake if enabled")] [global::Microsoft.Azure.PowerShell.Cmdlets.WebPubSub.Category(global::Microsoft.Azure.PowerShell.Cmdlets.WebPubSub.ParameterCategory.Body)] [Microsoft.Azure.PowerShell.Cmdlets.WebPubSub.Runtime.Info( Required = false, ReadOnly = false, Description = @"Request client certificate during TLS handshake if enabled", SerializedName = @"clientCertEnabled", PossibleTypes = new [] { typeof(global::System.Management.Automation.SwitchParameter) })] public global::System.Management.Automation.SwitchParameter EnableTlsClientCert { get => ParametersBody.EnableTlsClientCert ?? default(global::System.Management.Automation.SwitchParameter); set => ParametersBody.EnableTlsClientCert = value; } /// <summary>SendAsync Pipeline Steps to be appended to the front of the pipeline</summary> [global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "SendAsync Pipeline Steps to be appended to the front of the pipeline")] [global::System.Management.Automation.ValidateNotNull] [global::Microsoft.Azure.PowerShell.Cmdlets.WebPubSub.Category(global::Microsoft.Azure.PowerShell.Cmdlets.WebPubSub.ParameterCategory.Runtime)] public Microsoft.Azure.PowerShell.Cmdlets.WebPubSub.Runtime.SendAsyncStep[] HttpPipelineAppend { get; set; } /// <summary>SendAsync Pipeline Steps to be prepended to the front of the pipeline</summary> [global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "SendAsync Pipeline Steps to be prepended to the front of the pipeline")] [global::System.Management.Automation.ValidateNotNull] [global::Microsoft.Azure.PowerShell.Cmdlets.WebPubSub.Category(global::Microsoft.Azure.PowerShell.Cmdlets.WebPubSub.ParameterCategory.Runtime)] public Microsoft.Azure.PowerShell.Cmdlets.WebPubSub.Runtime.SendAsyncStep[] HttpPipelinePrepend { get; set; } /// <summary>Represent the identity type: systemAssigned, userAssigned, None</summary> [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Represent the identity type: systemAssigned, userAssigned, None")] [global::Microsoft.Azure.PowerShell.Cmdlets.WebPubSub.Category(global::Microsoft.Azure.PowerShell.Cmdlets.WebPubSub.ParameterCategory.Body)] [Microsoft.Azure.PowerShell.Cmdlets.WebPubSub.Runtime.Info( Required = false, ReadOnly = false, Description = @"Represent the identity type: systemAssigned, userAssigned, None", SerializedName = @"type", PossibleTypes = new [] { typeof(Microsoft.Azure.PowerShell.Cmdlets.WebPubSub.Support.ManagedIdentityType) })] [global::System.Management.Automation.ArgumentCompleter(typeof(Microsoft.Azure.PowerShell.Cmdlets.WebPubSub.Support.ManagedIdentityType))] public Microsoft.Azure.PowerShell.Cmdlets.WebPubSub.Support.ManagedIdentityType IdentityType { get => ParametersBody.IdentityType ?? ((Microsoft.Azure.PowerShell.Cmdlets.WebPubSub.Support.ManagedIdentityType)""); set => ParametersBody.IdentityType = value; } /// <summary>Backing field for <see cref="InputObject" /> property.</summary> private Microsoft.Azure.PowerShell.Cmdlets.WebPubSub.Models.IWebPubSubIdentity _inputObject; /// <summary>Identity Parameter</summary> [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "Identity Parameter", ValueFromPipeline = true)] [global::Microsoft.Azure.PowerShell.Cmdlets.WebPubSub.Category(global::Microsoft.Azure.PowerShell.Cmdlets.WebPubSub.ParameterCategory.Path)] public Microsoft.Azure.PowerShell.Cmdlets.WebPubSub.Models.IWebPubSubIdentity InputObject { get => this._inputObject; set => this._inputObject = value; } /// <summary>Accessor for our copy of the InvocationInfo.</summary> public global::System.Management.Automation.InvocationInfo InvocationInformation { get => __invocationInfo = __invocationInfo ?? this.MyInvocation ; set { __invocationInfo = value; } } /// <summary>Gets or sets the list of category configurations.</summary> [global::System.Management.Automation.AllowEmptyCollection] [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Gets or sets the list of category configurations.")] [global::Microsoft.Azure.PowerShell.Cmdlets.WebPubSub.Category(global::Microsoft.Azure.PowerShell.Cmdlets.WebPubSub.ParameterCategory.Body)] [Microsoft.Azure.PowerShell.Cmdlets.WebPubSub.Runtime.Info( Required = false, ReadOnly = false, Description = @"Gets or sets the list of category configurations.", SerializedName = @"categories", PossibleTypes = new [] { typeof(Microsoft.Azure.PowerShell.Cmdlets.WebPubSub.Models.Api20211001.ILiveTraceCategory) })] public Microsoft.Azure.PowerShell.Cmdlets.WebPubSub.Models.Api20211001.ILiveTraceCategory[] LiveTraceCategory { get => ParametersBody.LiveTraceCategory ?? null /* arrayOf */; set => ParametersBody.LiveTraceCategory = value; } /// <summary> /// Indicates whether or not enable live trace.When it's set to true, live trace client can connect to the service.Otherwise, /// live trace client can't connect to the service, so that you are unable to receive any log, no matter what you configure /// in "categories".Available values: true, false.Case insensitive. /// </summary> [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Indicates whether or not enable live trace.When it's set to true, live trace client can connect to the service.Otherwise, live trace client can't connect to the service, so that you are unable to receive any log, no matter what you configure in \"categories\".Available values: true, false.Case insensitive.")] [global::Microsoft.Azure.PowerShell.Cmdlets.WebPubSub.Category(global::Microsoft.Azure.PowerShell.Cmdlets.WebPubSub.ParameterCategory.Body)] [Microsoft.Azure.PowerShell.Cmdlets.WebPubSub.Runtime.Info( Required = false, ReadOnly = false, Description = @"Indicates whether or not enable live trace.When it's set to true, live trace client can connect to the service.Otherwise, live trace client can't connect to the service, so that you are unable to receive any log, no matter what you configure in ""categories"".Available values: true, false.Case insensitive.", SerializedName = @"enabled", PossibleTypes = new [] { typeof(string) })] public string LiveTraceEnabled { get => ParametersBody.LiveTraceEnabled ?? null; set => ParametersBody.LiveTraceEnabled = value; } /// <summary> /// The GEO location of the resource. e.g. West US | East US | North Central US | South Central US. /// </summary> [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "The GEO location of the resource. e.g. West US | East US | North Central US | South Central US.")] [global::Microsoft.Azure.PowerShell.Cmdlets.WebPubSub.Category(global::Microsoft.Azure.PowerShell.Cmdlets.WebPubSub.ParameterCategory.Body)] [Microsoft.Azure.PowerShell.Cmdlets.WebPubSub.Runtime.Info( Required = false, ReadOnly = false, Description = @"The GEO location of the resource. e.g. West US | East US | North Central US | South Central US.", SerializedName = @"location", PossibleTypes = new [] { typeof(string) })] [global::Microsoft.Azure.PowerShell.Cmdlets.WebPubSub.DoNotExport] public string Location { get => ParametersBody.Location ?? null; set => ParametersBody.Location = value; } /// <summary> /// <see cref="IEventListener" /> cancellation delegate. Stops the cmdlet when called. /// </summary> global::System.Action Microsoft.Azure.PowerShell.Cmdlets.WebPubSub.Runtime.IEventListener.Cancel => _cancellationTokenSource.Cancel; /// <summary><see cref="IEventListener" /> cancellation token.</summary> global::System.Threading.CancellationToken Microsoft.Azure.PowerShell.Cmdlets.WebPubSub.Runtime.IEventListener.Token => _cancellationTokenSource.Token; /// <summary>Default action when no other rule matches</summary> [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Default action when no other rule matches")] [global::Microsoft.Azure.PowerShell.Cmdlets.WebPubSub.Category(global::Microsoft.Azure.PowerShell.Cmdlets.WebPubSub.ParameterCategory.Body)] [Microsoft.Azure.PowerShell.Cmdlets.WebPubSub.Runtime.Info( Required = false, ReadOnly = false, Description = @"Default action when no other rule matches", SerializedName = @"defaultAction", PossibleTypes = new [] { typeof(Microsoft.Azure.PowerShell.Cmdlets.WebPubSub.Support.AclAction) })] [global::System.Management.Automation.ArgumentCompleter(typeof(Microsoft.Azure.PowerShell.Cmdlets.WebPubSub.Support.AclAction))] public Microsoft.Azure.PowerShell.Cmdlets.WebPubSub.Support.AclAction NetworkAcLDefaultAction { get => ParametersBody.NetworkAcLDefaultAction ?? ((Microsoft.Azure.PowerShell.Cmdlets.WebPubSub.Support.AclAction)""); set => ParametersBody.NetworkAcLDefaultAction = value; } /// <summary> /// when specified, will make the remote call, and return an AsyncOperationResponse, letting the remote operation continue /// asynchronously. /// </summary> [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Run the command asynchronously")] [global::Microsoft.Azure.PowerShell.Cmdlets.WebPubSub.Category(global::Microsoft.Azure.PowerShell.Cmdlets.WebPubSub.ParameterCategory.Runtime)] public global::System.Management.Automation.SwitchParameter NoWait { get; set; } /// <summary>Backing field for <see cref="ParametersBody" /> property.</summary> private Microsoft.Azure.PowerShell.Cmdlets.WebPubSub.Models.Api20211001.IWebPubSubResource _parametersBody= new Microsoft.Azure.PowerShell.Cmdlets.WebPubSub.Models.Api20211001.WebPubSubResource(); /// <summary>A class represent a resource.</summary> private Microsoft.Azure.PowerShell.Cmdlets.WebPubSub.Models.Api20211001.IWebPubSubResource ParametersBody { get => this._parametersBody; set => this._parametersBody = value; } /// <summary> /// The instance of the <see cref="Microsoft.Azure.PowerShell.Cmdlets.WebPubSub.Runtime.HttpPipeline" /> that the remote call will use. /// </summary> private Microsoft.Azure.PowerShell.Cmdlets.WebPubSub.Runtime.HttpPipeline Pipeline { get; set; } /// <summary>ACLs for requests from private endpoints</summary> [global::System.Management.Automation.AllowEmptyCollection] [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "ACLs for requests from private endpoints")] [global::Microsoft.Azure.PowerShell.Cmdlets.WebPubSub.Category(global::Microsoft.Azure.PowerShell.Cmdlets.WebPubSub.ParameterCategory.Body)] [Microsoft.Azure.PowerShell.Cmdlets.WebPubSub.Runtime.Info( Required = false, ReadOnly = false, Description = @"ACLs for requests from private endpoints", SerializedName = @"privateEndpoints", PossibleTypes = new [] { typeof(Microsoft.Azure.PowerShell.Cmdlets.WebPubSub.Models.Api20211001.IPrivateEndpointAcl) })] public Microsoft.Azure.PowerShell.Cmdlets.WebPubSub.Models.Api20211001.IPrivateEndpointAcl[] PrivateEndpointAcl { get => ParametersBody.PrivateEndpointAcl ?? null /* arrayOf */; set => ParametersBody.PrivateEndpointAcl = value; } /// <summary>The URI for the proxy server to use</summary> [global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "The URI for the proxy server to use")] [global::Microsoft.Azure.PowerShell.Cmdlets.WebPubSub.Category(global::Microsoft.Azure.PowerShell.Cmdlets.WebPubSub.ParameterCategory.Runtime)] public global::System.Uri Proxy { get; set; } /// <summary>Credentials for a proxy server to use for the remote call</summary> [global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "Credentials for a proxy server to use for the remote call")] [global::System.Management.Automation.ValidateNotNull] [global::Microsoft.Azure.PowerShell.Cmdlets.WebPubSub.Category(global::Microsoft.Azure.PowerShell.Cmdlets.WebPubSub.ParameterCategory.Runtime)] public global::System.Management.Automation.PSCredential ProxyCredential { get; set; } /// <summary>Use the default credentials for the proxy</summary> [global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "Use the default credentials for the proxy")] [global::Microsoft.Azure.PowerShell.Cmdlets.WebPubSub.Category(global::Microsoft.Azure.PowerShell.Cmdlets.WebPubSub.ParameterCategory.Runtime)] public global::System.Management.Automation.SwitchParameter ProxyUseDefaultCredentials { get; set; } /// <summary> /// Enable or disable public network access. Default to "Enabled".When it's Enabled, network ACLs still apply.When it's Disabled, /// public network access is always disabled no matter what you set in network ACLs. /// </summary> [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Enable or disable public network access. Default to \"Enabled\".When it's Enabled, network ACLs still apply.When it's Disabled, public network access is always disabled no matter what you set in network ACLs.")] [global::Microsoft.Azure.PowerShell.Cmdlets.WebPubSub.Category(global::Microsoft.Azure.PowerShell.Cmdlets.WebPubSub.ParameterCategory.Body)] [Microsoft.Azure.PowerShell.Cmdlets.WebPubSub.Runtime.Info( Required = false, ReadOnly = false, Description = @"Enable or disable public network access. Default to ""Enabled"".When it's Enabled, network ACLs still apply.When it's Disabled, public network access is always disabled no matter what you set in network ACLs.", SerializedName = @"publicNetworkAccess", PossibleTypes = new [] { typeof(string) })] public string PublicNetworkAccess { get => ParametersBody.PublicNetworkAccess ?? null; set => ParametersBody.PublicNetworkAccess = value; } /// <summary> /// Allowed request types. The value can be one or more of: ClientConnection, ServerConnection, RESTAPI. /// </summary> [global::System.Management.Automation.AllowEmptyCollection] [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Allowed request types. The value can be one or more of: ClientConnection, ServerConnection, RESTAPI.")] [global::Microsoft.Azure.PowerShell.Cmdlets.WebPubSub.Category(global::Microsoft.Azure.PowerShell.Cmdlets.WebPubSub.ParameterCategory.Body)] [Microsoft.Azure.PowerShell.Cmdlets.WebPubSub.Runtime.Info( Required = false, ReadOnly = false, Description = @"Allowed request types. The value can be one or more of: ClientConnection, ServerConnection, RESTAPI.", SerializedName = @"allow", PossibleTypes = new [] { typeof(Microsoft.Azure.PowerShell.Cmdlets.WebPubSub.Support.WebPubSubRequestType) })] [global::System.Management.Automation.ArgumentCompleter(typeof(Microsoft.Azure.PowerShell.Cmdlets.WebPubSub.Support.WebPubSubRequestType))] public Microsoft.Azure.PowerShell.Cmdlets.WebPubSub.Support.WebPubSubRequestType[] PublicNetworkAllow { get => ParametersBody.PublicNetworkAllow ?? null /* arrayOf */; set => ParametersBody.PublicNetworkAllow = value; } /// <summary> /// Denied request types. The value can be one or more of: ClientConnection, ServerConnection, RESTAPI. /// </summary> [global::System.Management.Automation.AllowEmptyCollection] [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Denied request types. The value can be one or more of: ClientConnection, ServerConnection, RESTAPI.")] [global::Microsoft.Azure.PowerShell.Cmdlets.WebPubSub.Category(global::Microsoft.Azure.PowerShell.Cmdlets.WebPubSub.ParameterCategory.Body)] [Microsoft.Azure.PowerShell.Cmdlets.WebPubSub.Runtime.Info( Required = false, ReadOnly = false, Description = @"Denied request types. The value can be one or more of: ClientConnection, ServerConnection, RESTAPI.", SerializedName = @"deny", PossibleTypes = new [] { typeof(Microsoft.Azure.PowerShell.Cmdlets.WebPubSub.Support.WebPubSubRequestType) })] [global::System.Management.Automation.ArgumentCompleter(typeof(Microsoft.Azure.PowerShell.Cmdlets.WebPubSub.Support.WebPubSubRequestType))] public Microsoft.Azure.PowerShell.Cmdlets.WebPubSub.Support.WebPubSubRequestType[] PublicNetworkDeny { get => ParametersBody.PublicNetworkDeny ?? null /* arrayOf */; set => ParametersBody.PublicNetworkDeny = value; } /// <summary>Gets or sets the list of category configurations.</summary> [global::System.Management.Automation.AllowEmptyCollection] [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Gets or sets the list of category configurations.")] [global::Microsoft.Azure.PowerShell.Cmdlets.WebPubSub.Category(global::Microsoft.Azure.PowerShell.Cmdlets.WebPubSub.ParameterCategory.Body)] [Microsoft.Azure.PowerShell.Cmdlets.WebPubSub.Runtime.Info( Required = false, ReadOnly = false, Description = @"Gets or sets the list of category configurations.", SerializedName = @"categories", PossibleTypes = new [] { typeof(Microsoft.Azure.PowerShell.Cmdlets.WebPubSub.Models.Api20211001.IResourceLogCategory) })] public Microsoft.Azure.PowerShell.Cmdlets.WebPubSub.Models.Api20211001.IResourceLogCategory[] ResourceLogCategory { get => ParametersBody.ResourceLogCategory ?? null /* arrayOf */; set => ParametersBody.ResourceLogCategory = value; } /// <summary> /// Optional, integer. The unit count of the resource. 1 by default.If present, following values are allowed: Free: 1 Standard: /// 1,2,5,10,20,50,100 /// </summary> [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Optional, integer. The unit count of the resource. 1 by default.If present, following values are allowed: Free: 1 Standard: 1,2,5,10,20,50,100")] [global::Microsoft.Azure.PowerShell.Cmdlets.WebPubSub.Category(global::Microsoft.Azure.PowerShell.Cmdlets.WebPubSub.ParameterCategory.Body)] [Microsoft.Azure.PowerShell.Cmdlets.WebPubSub.Runtime.Info( Required = false, ReadOnly = false, Description = @"Optional, integer. The unit count of the resource. 1 by default.If present, following values are allowed: Free: 1 Standard: 1,2,5,10,20,50,100", SerializedName = @"capacity", PossibleTypes = new [] { typeof(int) })] public int SkuCapacity { get => ParametersBody.SkuCapacity ?? default(int); set => ParametersBody.SkuCapacity = value; } /// <summary>The name of the SKU. Required.Allowed values: Standard_S1, Free_F1</summary> [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "The name of the SKU. Required.Allowed values: Standard_S1, Free_F1")] [global::Microsoft.Azure.PowerShell.Cmdlets.WebPubSub.Category(global::Microsoft.Azure.PowerShell.Cmdlets.WebPubSub.ParameterCategory.Body)] [Microsoft.Azure.PowerShell.Cmdlets.WebPubSub.Runtime.Info( Required = false, ReadOnly = false, Description = @"The name of the SKU. Required.Allowed values: Standard_S1, Free_F1", SerializedName = @"name", PossibleTypes = new [] { typeof(string) })] public string SkuName { get => ParametersBody.SkuName ?? null; set => ParametersBody.SkuName = value; } /// <summary> /// Optional tier of this particular SKU. 'Standard' or 'Free'. `Basic` is deprecated, use `Standard` instead. /// </summary> [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Optional tier of this particular SKU. 'Standard' or 'Free'. `Basic` is deprecated, use `Standard` instead.")] [global::Microsoft.Azure.PowerShell.Cmdlets.WebPubSub.Category(global::Microsoft.Azure.PowerShell.Cmdlets.WebPubSub.ParameterCategory.Body)] [Microsoft.Azure.PowerShell.Cmdlets.WebPubSub.Runtime.Info( Required = false, ReadOnly = false, Description = @"Optional tier of this particular SKU. 'Standard' or 'Free'. `Basic` is deprecated, use `Standard` instead.", SerializedName = @"tier", PossibleTypes = new [] { typeof(Microsoft.Azure.PowerShell.Cmdlets.WebPubSub.Support.WebPubSubSkuTier) })] [global::System.Management.Automation.ArgumentCompleter(typeof(Microsoft.Azure.PowerShell.Cmdlets.WebPubSub.Support.WebPubSubSkuTier))] public Microsoft.Azure.PowerShell.Cmdlets.WebPubSub.Support.WebPubSubSkuTier SkuTier { get => ParametersBody.SkuTier ?? ((Microsoft.Azure.PowerShell.Cmdlets.WebPubSub.Support.WebPubSubSkuTier)""); set => ParametersBody.SkuTier = value; } /// <summary> /// Tags of the service which is a list of key value pairs that describe the resource. /// </summary> [global::Microsoft.Azure.PowerShell.Cmdlets.WebPubSub.ExportAs(typeof(global::System.Collections.Hashtable))] [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Tags of the service which is a list of key value pairs that describe the resource.")] [global::Microsoft.Azure.PowerShell.Cmdlets.WebPubSub.Category(global::Microsoft.Azure.PowerShell.Cmdlets.WebPubSub.ParameterCategory.Body)] [Microsoft.Azure.PowerShell.Cmdlets.WebPubSub.Runtime.Info( Required = false, ReadOnly = false, Description = @"Tags of the service which is a list of key value pairs that describe the resource.", SerializedName = @"tags", PossibleTypes = new [] { typeof(Microsoft.Azure.PowerShell.Cmdlets.WebPubSub.Models.Api20211001.ITrackedResourceTags) })] public Microsoft.Azure.PowerShell.Cmdlets.WebPubSub.Models.Api20211001.ITrackedResourceTags Tag { get => ParametersBody.Tag ?? null /* object */; set => ParametersBody.Tag = value; } /// <summary>Get or set the user assigned identities</summary> [global::Microsoft.Azure.PowerShell.Cmdlets.WebPubSub.ExportAs(typeof(global::System.Collections.Hashtable))] [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Get or set the user assigned identities")] [global::Microsoft.Azure.PowerShell.Cmdlets.WebPubSub.Category(global::Microsoft.Azure.PowerShell.Cmdlets.WebPubSub.ParameterCategory.Body)] [Microsoft.Azure.PowerShell.Cmdlets.WebPubSub.Runtime.Info( Required = false, ReadOnly = false, Description = @"Get or set the user assigned identities", SerializedName = @"userAssignedIdentities", PossibleTypes = new [] { typeof(Microsoft.Azure.PowerShell.Cmdlets.WebPubSub.Models.Api20211001.IManagedIdentityUserAssignedIdentities) })] public Microsoft.Azure.PowerShell.Cmdlets.WebPubSub.Models.Api20211001.IManagedIdentityUserAssignedIdentities UserAssignedIdentity { get => ParametersBody.UserAssignedIdentity ?? null /* object */; set => ParametersBody.UserAssignedIdentity = value; } /// <summary> /// <c>overrideOnDefault</c> will be called before the regular onDefault has been processed, allowing customization of what /// happens on that response. Implement this method in a partial class to enable this behavior /// </summary> /// <param name="responseMessage">the raw response message as an global::System.Net.Http.HttpResponseMessage.</param> /// <param name="response">the body result as a <see cref="Microsoft.Azure.PowerShell.Cmdlets.WebPubSub.Models.Api20.IErrorResponse" /// /> from the remote call</param> /// <param name="returnNow">/// Determines if the rest of the onDefault method should be processed, or if the method should /// return immediately (set to true to skip further processing )</param> partial void overrideOnDefault(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task<Microsoft.Azure.PowerShell.Cmdlets.WebPubSub.Models.Api20.IErrorResponse> response, ref global::System.Threading.Tasks.Task<bool> returnNow); /// <summary> /// <c>overrideOnOk</c> will be called before the regular onOk has been processed, allowing customization of what happens /// on that response. Implement this method in a partial class to enable this behavior /// </summary> /// <param name="responseMessage">the raw response message as an global::System.Net.Http.HttpResponseMessage.</param> /// <param name="response">the body result as a <see cref="Microsoft.Azure.PowerShell.Cmdlets.WebPubSub.Models.Api20211001.IWebPubSubResource" /// /> from the remote call</param> /// <param name="returnNow">/// Determines if the rest of the onOk method should be processed, or if the method should return /// immediately (set to true to skip further processing )</param> partial void overrideOnOk(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task<Microsoft.Azure.PowerShell.Cmdlets.WebPubSub.Models.Api20211001.IWebPubSubResource> response, ref global::System.Threading.Tasks.Task<bool> returnNow); /// <summary> /// (overrides the default BeginProcessing method in global::System.Management.Automation.PSCmdlet) /// </summary> protected override void BeginProcessing() { Module.Instance.SetProxyConfiguration(Proxy, ProxyCredential, ProxyUseDefaultCredentials); if (Break) { Microsoft.Azure.PowerShell.Cmdlets.WebPubSub.Runtime.AttachDebugger.Break(); } ((Microsoft.Azure.PowerShell.Cmdlets.WebPubSub.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.WebPubSub.Runtime.Events.CmdletBeginProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.WebPubSub.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } } /// <summary>Creates a duplicate instance of this cmdlet (via JSON serialization).</summary> /// <returns>a duplicate instance of UpdateAzWebPubSub_UpdateViaIdentityExpanded</returns> public Microsoft.Azure.PowerShell.Cmdlets.WebPubSub.Cmdlets.UpdateAzWebPubSub_UpdateViaIdentityExpanded Clone() { var clone = new UpdateAzWebPubSub_UpdateViaIdentityExpanded(); clone.__correlationId = this.__correlationId; clone.__processRecordId = this.__processRecordId; clone.DefaultProfile = this.DefaultProfile; clone.InvocationInformation = this.InvocationInformation; clone.Proxy = this.Proxy; clone.Pipeline = this.Pipeline; clone.AsJob = this.AsJob; clone.Break = this.Break; clone.ProxyCredential = this.ProxyCredential; clone.ProxyUseDefaultCredentials = this.ProxyUseDefaultCredentials; clone.HttpPipelinePrepend = this.HttpPipelinePrepend; clone.HttpPipelineAppend = this.HttpPipelineAppend; clone.ParametersBody = this.ParametersBody; return clone; } /// <summary>Performs clean-up after the command execution</summary> protected override void EndProcessing() { ((Microsoft.Azure.PowerShell.Cmdlets.WebPubSub.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.WebPubSub.Runtime.Events.CmdletEndProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.WebPubSub.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } } /// <summary>Handles/Dispatches events during the call to the REST service.</summary> /// <param name="id">The message id</param> /// <param name="token">The message cancellation token. When this call is cancelled, this should be <c>true</c></param> /// <param name="messageData">Detailed message data for the message event.</param> /// <returns> /// A <see cref="global::System.Threading.Tasks.Task" /> that will be complete when handling of the message is completed. /// </returns> async global::System.Threading.Tasks.Task Microsoft.Azure.PowerShell.Cmdlets.WebPubSub.Runtime.IEventListener.Signal(string id, global::System.Threading.CancellationToken token, global::System.Func<Microsoft.Azure.PowerShell.Cmdlets.WebPubSub.Runtime.EventData> messageData) { using( NoSynchronizationContext ) { if (token.IsCancellationRequested) { return ; } switch ( id ) { case Microsoft.Azure.PowerShell.Cmdlets.WebPubSub.Runtime.Events.Verbose: { WriteVerbose($"{(messageData().Message ?? global::System.String.Empty)}"); return ; } case Microsoft.Azure.PowerShell.Cmdlets.WebPubSub.Runtime.Events.Warning: { WriteWarning($"{(messageData().Message ?? global::System.String.Empty)}"); return ; } case Microsoft.Azure.PowerShell.Cmdlets.WebPubSub.Runtime.Events.Information: { // When an operation supports asjob, Information messages must go thru verbose. WriteVerbose($"INFORMATION: {(messageData().Message ?? global::System.String.Empty)}"); return ; } case Microsoft.Azure.PowerShell.Cmdlets.WebPubSub.Runtime.Events.Debug: { WriteDebug($"{(messageData().Message ?? global::System.String.Empty)}"); return ; } case Microsoft.Azure.PowerShell.Cmdlets.WebPubSub.Runtime.Events.Error: { WriteError(new global::System.Management.Automation.ErrorRecord( new global::System.Exception(messageData().Message), string.Empty, global::System.Management.Automation.ErrorCategory.NotSpecified, null ) ); return ; } case Microsoft.Azure.PowerShell.Cmdlets.WebPubSub.Runtime.Events.DelayBeforePolling: { if (true == MyInvocation?.BoundParameters?.ContainsKey("NoWait")) { var data = messageData(); if (data.ResponseMessage is System.Net.Http.HttpResponseMessage response) { var asyncOperation = response.GetFirstHeader(@"Azure-AsyncOperation"); var location = response.GetFirstHeader(@"Location"); var uri = global::System.String.IsNullOrEmpty(asyncOperation) ? global::System.String.IsNullOrEmpty(location) ? response.RequestMessage.RequestUri.AbsoluteUri : location : asyncOperation; WriteObject(new Microsoft.Azure.PowerShell.Cmdlets.WebPubSub.Runtime.PowerShell.AsyncOperationResponse { Target = uri }); // do nothing more. data.Cancel(); return; } } break; } } await Microsoft.Azure.PowerShell.Cmdlets.WebPubSub.Module.Instance.Signal(id, token, messageData, (i,t,m) => ((Microsoft.Azure.PowerShell.Cmdlets.WebPubSub.Runtime.IEventListener)this).Signal(i,t,()=> Microsoft.Azure.PowerShell.Cmdlets.WebPubSub.Runtime.EventDataConverter.ConvertFrom( m() ) as Microsoft.Azure.PowerShell.Cmdlets.WebPubSub.Runtime.EventData ), InvocationInformation, this.ParameterSetName, __correlationId, __processRecordId, null ); if (token.IsCancellationRequested) { return ; } WriteDebug($"{id}: {(messageData().Message ?? global::System.String.Empty)}"); } } /// <summary>Performs execution of the command.</summary> protected override void ProcessRecord() { ((Microsoft.Azure.PowerShell.Cmdlets.WebPubSub.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.WebPubSub.Runtime.Events.CmdletProcessRecordStart).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.WebPubSub.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } __processRecordId = System.Guid.NewGuid().ToString(); try { // work if (ShouldProcess($"Call remote 'WebPubSubUpdate' operation")) { if (true == MyInvocation?.BoundParameters?.ContainsKey("AsJob")) { var instance = this.Clone(); var job = new Microsoft.Azure.PowerShell.Cmdlets.WebPubSub.Runtime.PowerShell.AsyncJob(instance, this.MyInvocation.Line, this.MyInvocation.MyCommand.Name, this._cancellationTokenSource.Token, this._cancellationTokenSource.Cancel); JobRepository.Add(job); var task = instance.ProcessRecordAsync(); job.Monitor(task); WriteObject(job); } else { using( var asyncCommandRuntime = new Microsoft.Azure.PowerShell.Cmdlets.WebPubSub.Runtime.PowerShell.AsyncCommandRuntime(this, ((Microsoft.Azure.PowerShell.Cmdlets.WebPubSub.Runtime.IEventListener)this).Token) ) { asyncCommandRuntime.Wait( ProcessRecordAsync(),((Microsoft.Azure.PowerShell.Cmdlets.WebPubSub.Runtime.IEventListener)this).Token); } } } } catch (global::System.AggregateException aggregateException) { // unroll the inner exceptions to get the root cause foreach( var innerException in aggregateException.Flatten().InnerExceptions ) { ((Microsoft.Azure.PowerShell.Cmdlets.WebPubSub.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.WebPubSub.Runtime.Events.CmdletException, $"{innerException.GetType().Name} - {innerException.Message} : {innerException.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.WebPubSub.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } // Write exception out to error channel. WriteError( new global::System.Management.Automation.ErrorRecord(innerException,string.Empty, global::System.Management.Automation.ErrorCategory.NotSpecified, null) ); } } catch (global::System.Exception exception) when ((exception as System.Management.Automation.PipelineStoppedException)== null || (exception as System.Management.Automation.PipelineStoppedException).InnerException != null) { ((Microsoft.Azure.PowerShell.Cmdlets.WebPubSub.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.WebPubSub.Runtime.Events.CmdletException, $"{exception.GetType().Name} - {exception.Message} : {exception.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.WebPubSub.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } // Write exception out to error channel. WriteError( new global::System.Management.Automation.ErrorRecord(exception,string.Empty, global::System.Management.Automation.ErrorCategory.NotSpecified, null) ); } finally { ((Microsoft.Azure.PowerShell.Cmdlets.WebPubSub.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.WebPubSub.Runtime.Events.CmdletProcessRecordEnd).Wait(); } } /// <summary>Performs execution of the command, working asynchronously if required.</summary> /// <returns> /// A <see cref="global::System.Threading.Tasks.Task" /> that will be complete when handling of the method is completed. /// </returns> protected async global::System.Threading.Tasks.Task ProcessRecordAsync() { using( NoSynchronizationContext ) { await ((Microsoft.Azure.PowerShell.Cmdlets.WebPubSub.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.WebPubSub.Runtime.Events.CmdletProcessRecordAsyncStart); if( ((Microsoft.Azure.PowerShell.Cmdlets.WebPubSub.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } await ((Microsoft.Azure.PowerShell.Cmdlets.WebPubSub.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.WebPubSub.Runtime.Events.CmdletGetPipeline); if( ((Microsoft.Azure.PowerShell.Cmdlets.WebPubSub.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } Pipeline = Microsoft.Azure.PowerShell.Cmdlets.WebPubSub.Module.Instance.CreatePipeline(InvocationInformation, __correlationId, __processRecordId, this.ParameterSetName); if (null != HttpPipelinePrepend) { Pipeline.Prepend((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.WebPubSub.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelinePrepend) ?? HttpPipelinePrepend); } if (null != HttpPipelineAppend) { Pipeline.Append((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.WebPubSub.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelineAppend) ?? HttpPipelineAppend); } // get the client instance try { await ((Microsoft.Azure.PowerShell.Cmdlets.WebPubSub.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.WebPubSub.Runtime.Events.CmdletBeforeAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.WebPubSub.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } if (InputObject?.Id != null) { await this.Client.WebPubSubUpdateViaIdentity(InputObject.Id, ParametersBody, onOk, onDefault, this, Pipeline); } else { // try to call with PATH parameters from Input Object if (null == InputObject.SubscriptionId) { ThrowTerminatingError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception("InputObject has null value for InputObject.SubscriptionId"),string.Empty, global::System.Management.Automation.ErrorCategory.InvalidArgument, InputObject) ); } if (null == InputObject.ResourceGroupName) { ThrowTerminatingError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception("InputObject has null value for InputObject.ResourceGroupName"),string.Empty, global::System.Management.Automation.ErrorCategory.InvalidArgument, InputObject) ); } if (null == InputObject.ResourceName) { ThrowTerminatingError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception("InputObject has null value for InputObject.ResourceName"),string.Empty, global::System.Management.Automation.ErrorCategory.InvalidArgument, InputObject) ); } await this.Client.WebPubSubUpdate(InputObject.SubscriptionId ?? null, InputObject.ResourceGroupName ?? null, InputObject.ResourceName ?? null, ParametersBody, onOk, onDefault, this, Pipeline); } await ((Microsoft.Azure.PowerShell.Cmdlets.WebPubSub.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.WebPubSub.Runtime.Events.CmdletAfterAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.WebPubSub.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } } catch (Microsoft.Azure.PowerShell.Cmdlets.WebPubSub.Runtime.UndeclaredResponseException urexception) { WriteError(new global::System.Management.Automation.ErrorRecord(urexception, urexception.StatusCode.ToString(), global::System.Management.Automation.ErrorCategory.InvalidOperation, new { body=ParametersBody}) { ErrorDetails = new global::System.Management.Automation.ErrorDetails(urexception.Message) { RecommendedAction = urexception.Action } }); } finally { await ((Microsoft.Azure.PowerShell.Cmdlets.WebPubSub.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.WebPubSub.Runtime.Events.CmdletProcessRecordAsyncEnd); } } } /// <summary>Interrupts currently running code within the command.</summary> protected override void StopProcessing() { ((Microsoft.Azure.PowerShell.Cmdlets.WebPubSub.Runtime.IEventListener)this).Cancel(); base.StopProcessing(); } /// <summary> /// Intializes a new instance of the <see cref="UpdateAzWebPubSub_UpdateViaIdentityExpanded" /> cmdlet class. /// </summary> public UpdateAzWebPubSub_UpdateViaIdentityExpanded() { } /// <summary> /// a delegate that is called when the remote service returns default (any response code not handled elsewhere). /// </summary> /// <param name="responseMessage">the raw response message as an global::System.Net.Http.HttpResponseMessage.</param> /// <param name="response">the body result as a <see cref="Microsoft.Azure.PowerShell.Cmdlets.WebPubSub.Models.Api20.IErrorResponse" /// /> from the remote call</param> /// <returns> /// A <see cref="global::System.Threading.Tasks.Task" /> that will be complete when handling of the method is completed. /// </returns> private async global::System.Threading.Tasks.Task onDefault(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task<Microsoft.Azure.PowerShell.Cmdlets.WebPubSub.Models.Api20.IErrorResponse> response) { using( NoSynchronizationContext ) { var _returnNow = global::System.Threading.Tasks.Task<bool>.FromResult(false); overrideOnDefault(responseMessage, response, ref _returnNow); // if overrideOnDefault has returned true, then return right away. if ((null != _returnNow && await _returnNow)) { return ; } // Error Response : default var code = (await response)?.Code; var message = (await response)?.Message; if ((null == code || null == message)) { // Unrecognized Response. Create an error record based on what we have. var ex = new Microsoft.Azure.PowerShell.Cmdlets.WebPubSub.Runtime.RestException<Microsoft.Azure.PowerShell.Cmdlets.WebPubSub.Models.Api20.IErrorResponse>(responseMessage, await response); WriteError( new global::System.Management.Automation.ErrorRecord(ex, ex.Code, global::System.Management.Automation.ErrorCategory.InvalidOperation, new { body=ParametersBody }) { ErrorDetails = new global::System.Management.Automation.ErrorDetails(ex.Message) { RecommendedAction = ex.Action } }); } else { WriteError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception($"[{code}] : {message}"), code?.ToString(), global::System.Management.Automation.ErrorCategory.InvalidOperation, new { body=ParametersBody }) { ErrorDetails = new global::System.Management.Automation.ErrorDetails(message) { RecommendedAction = global::System.String.Empty } }); } } } /// <summary>a delegate that is called when the remote service returns 200 (OK).</summary> /// <param name="responseMessage">the raw response message as an global::System.Net.Http.HttpResponseMessage.</param> /// <param name="response">the body result as a <see cref="Microsoft.Azure.PowerShell.Cmdlets.WebPubSub.Models.Api20211001.IWebPubSubResource" /// /> from the remote call</param> /// <returns> /// A <see cref="global::System.Threading.Tasks.Task" /> that will be complete when handling of the method is completed. /// </returns> private async global::System.Threading.Tasks.Task onOk(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task<Microsoft.Azure.PowerShell.Cmdlets.WebPubSub.Models.Api20211001.IWebPubSubResource> response) { using( NoSynchronizationContext ) { var _returnNow = global::System.Threading.Tasks.Task<bool>.FromResult(false); overrideOnOk(responseMessage, response, ref _returnNow); // if overrideOnOk has returned true, then return right away. if ((null != _returnNow && await _returnNow)) { return ; } // onOk - response for 200 / application/json // (await response) // should be Microsoft.Azure.PowerShell.Cmdlets.WebPubSub.Models.Api20211001.IWebPubSubResource WriteObject((await response)); } } } }
79.444606
467
0.682783
[ "MIT" ]
Agazoth/azure-powershell
src/SignalR/SignalR.Autorest/generated/cmdlets/UpdateAzWebPubSub_UpdateViaIdentityExpanded.cs
53,814
C#
namespace CoinMonitoringPortalApi.Business.Database.Enums { public enum ExchangeTypeEnum: short { Cex = 1, Poloniex = 2 } }
14.666667
58
0.734848
[ "MIT" ]
VytautasBoznis/CoinMonitoringApi
CoinMonitoringPortalApi.Business/Database/Enums/ExchangeTypeEnum.cs
134
C#
using System.Collections; using System.Collections.Generic; using UnityEngine; public class SkyBoxScript : MonoBehaviour { public Material SkyBox1; public Material SkyBox2; void Start() { RenderSettings.skybox = SkyBox1; } // Update is called once per frame void Update() { if(Input.GetKeyDown("3")) { RenderSettings.skybox = SkyBox1; DynamicGI.UpdateEnvironment(); } else if (Input.GetKeyDown("4")) { RenderSettings.skybox = SkyBox2; DynamicGI.UpdateEnvironment(); } if(Input.GetKeyDown("5")) { RenderSettings.fog = !RenderSettings.fog; } } }
19.864865
53
0.564626
[ "Apache-2.0" ]
rockchik/Bouncy
Assets/Scripts/SkyBoxScript.cs
737
C#
using ApprovalTests.Namers.StackTraceParsers; namespace ApprovalTests.StackTraceParsers { public class XUnitTheoryStackTraceParser : AttributeStackTraceParser { public const string TheoryAttribute = "Xunit.Extensions.TheoryAttribute"; public override string ForTestingFramework { get { return "xUnit.extensions"; } } protected override string GetAttributeType() { return TheoryAttribute; } } }
23
76
0.750572
[ "Apache-2.0" ]
GeertvanHorrik/ApprovalTests.Net
ApprovalTests/Namers/UnitTestFrameworks/XUnitTheoryStackTraceParser.cs
419
C#
namespace MediaManager_Client { partial class MediaPlayer { /// <summary> /// Required designer variable. /// </summary> private System.ComponentModel.IContainer components = null; /// <summary> /// Clean up any resources being used. /// </summary> /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param> protected override void Dispose(bool disposing) { if (disposing && (components != null)) { components.Dispose(); } base.Dispose(disposing); } #region Windows Form Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { this.components = new System.ComponentModel.Container(); System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(MediaPlayer)); this.CommandPanel = new System.Windows.Forms.Panel(); this.label1 = new System.Windows.Forms.Label(); this.pictureBox1 = new System.Windows.Forms.PictureBox(); this.SnapshotButton = new System.Windows.Forms.Button(); this.FullScreenButton = new System.Windows.Forms.Button(); this.SpeedTrackBar = new System.Windows.Forms.TrackBar(); this.VolumeTrackBar = new System.Windows.Forms.TrackBar(); this.ForwardButton = new System.Windows.Forms.Button(); this.StopButton = new System.Windows.Forms.Button(); this.BackButton = new System.Windows.Forms.Button(); this.PlayPauseButton = new System.Windows.Forms.Button(); this.ControlImageList = new System.Windows.Forms.ImageList(this.components); this.label2 = new System.Windows.Forms.Label(); this.TimeTrackBar = new System.Windows.Forms.TrackBar(); this.TimePanel = new System.Windows.Forms.Panel(); this.TotalRemainingTimeLabel = new System.Windows.Forms.Label(); this.ElapsedTimeLabel = new System.Windows.Forms.Label(); this.toolTip1 = new System.Windows.Forms.ToolTip(this.components); this.PictureScreen = new System.Windows.Forms.Panel(); this.CommandPanel.SuspendLayout(); ((System.ComponentModel.ISupportInitialize)(this.pictureBox1)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.SpeedTrackBar)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.VolumeTrackBar)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.TimeTrackBar)).BeginInit(); this.TimePanel.SuspendLayout(); this.SuspendLayout(); // // CommandPanel // this.CommandPanel.Controls.Add(this.label1); this.CommandPanel.Controls.Add(this.pictureBox1); this.CommandPanel.Controls.Add(this.SnapshotButton); this.CommandPanel.Controls.Add(this.FullScreenButton); this.CommandPanel.Controls.Add(this.SpeedTrackBar); this.CommandPanel.Controls.Add(this.VolumeTrackBar); this.CommandPanel.Controls.Add(this.ForwardButton); this.CommandPanel.Controls.Add(this.StopButton); this.CommandPanel.Controls.Add(this.BackButton); this.CommandPanel.Controls.Add(this.PlayPauseButton); this.CommandPanel.Dock = System.Windows.Forms.DockStyle.Bottom; this.CommandPanel.Location = new System.Drawing.Point(0, 331); this.CommandPanel.Name = "CommandPanel"; this.CommandPanel.Size = new System.Drawing.Size(528, 34); this.CommandPanel.TabIndex = 7; // // label1 // this.label1.Location = new System.Drawing.Point(415, 18); this.label1.Name = "label1"; this.label1.Size = new System.Drawing.Size(35, 13); this.label1.TabIndex = 18; this.label1.Text = "0%"; // // pictureBox1 // this.pictureBox1.Location = new System.Drawing.Point(395, 7); this.pictureBox1.Name = "pictureBox1"; this.pictureBox1.Size = new System.Drawing.Size(14, 14); this.pictureBox1.TabIndex = 17; this.pictureBox1.TabStop = false; // // SnapshotButton // this.SnapshotButton.Location = new System.Drawing.Point(172, 3); this.SnapshotButton.Name = "SnapshotButton"; this.SnapshotButton.Size = new System.Drawing.Size(28, 26); this.SnapshotButton.TabIndex = 16; this.SnapshotButton.TabStop = false; this.toolTip1.SetToolTip(this.SnapshotButton, "Take a snapshot"); this.SnapshotButton.UseVisualStyleBackColor = true; this.SnapshotButton.Click += new System.EventHandler(this.SnapshotButton_Click); this.SnapshotButton.MouseLeave += new System.EventHandler(this.SnapshotButton_MouseLeave); // // FullScreenButton // this.FullScreenButton.Location = new System.Drawing.Point(137, 3); this.FullScreenButton.Name = "FullScreenButton"; this.FullScreenButton.Size = new System.Drawing.Size(28, 26); this.FullScreenButton.TabIndex = 12; this.FullScreenButton.TabStop = false; this.toolTip1.SetToolTip(this.FullScreenButton, "Toggle fullscreen view"); this.FullScreenButton.UseVisualStyleBackColor = true; this.FullScreenButton.Click += new System.EventHandler(this.FullScreenButton_Click); this.FullScreenButton.MouseLeave += new System.EventHandler(this.FullScreenButton_MouseLeave); // // SpeedTrackBar // this.SpeedTrackBar.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right))); this.SpeedTrackBar.AutoSize = false; this.SpeedTrackBar.LargeChange = 1; this.SpeedTrackBar.Location = new System.Drawing.Point(256, 3); this.SpeedTrackBar.Maximum = 4; this.SpeedTrackBar.Name = "SpeedTrackBar"; this.SpeedTrackBar.Size = new System.Drawing.Size(118, 28); this.SpeedTrackBar.TabIndex = 13; this.SpeedTrackBar.TabStop = false; this.toolTip1.SetToolTip(this.SpeedTrackBar, "Current play back speed: 1.00x"); this.SpeedTrackBar.Value = 2; // // VolumeTrackBar // this.VolumeTrackBar.AutoSize = false; this.VolumeTrackBar.LargeChange = 1; this.VolumeTrackBar.Location = new System.Drawing.Point(407, 3); this.VolumeTrackBar.Maximum = 100; this.VolumeTrackBar.Name = "VolumeTrackBar"; this.VolumeTrackBar.Size = new System.Drawing.Size(118, 28); this.VolumeTrackBar.TabIndex = 15; this.VolumeTrackBar.TabStop = false; this.VolumeTrackBar.TickStyle = System.Windows.Forms.TickStyle.None; this.toolTip1.SetToolTip(this.VolumeTrackBar, "Current volume: 75%"); this.VolumeTrackBar.Value = 75; this.VolumeTrackBar.Scroll += new System.EventHandler(this.VolumeTrackBar_Scroll); // // ForwardButton // this.ForwardButton.ImageKey = "(none)"; this.ForwardButton.Location = new System.Drawing.Point(102, 3); this.ForwardButton.Name = "ForwardButton"; this.ForwardButton.Size = new System.Drawing.Size(28, 26); this.ForwardButton.TabIndex = 11; this.ForwardButton.TabStop = false; this.toolTip1.SetToolTip(this.ForwardButton, "Jump to next media"); this.ForwardButton.UseVisualStyleBackColor = true; this.ForwardButton.Click += new System.EventHandler(this.ForwardButton_Click); this.ForwardButton.MouseLeave += new System.EventHandler(this.ForwardButton_MouseLeave); // // StopButton // this.StopButton.ImageKey = "(none)"; this.StopButton.Location = new System.Drawing.Point(71, 3); this.StopButton.Name = "StopButton"; this.StopButton.Size = new System.Drawing.Size(28, 26); this.StopButton.TabIndex = 10; this.StopButton.TabStop = false; this.toolTip1.SetToolTip(this.StopButton, "Stop playback"); this.StopButton.UseVisualStyleBackColor = true; this.StopButton.Click += new System.EventHandler(this.StopButton_Click); this.StopButton.MouseLeave += new System.EventHandler(this.StopButton_MouseLeave); // // BackButton // this.BackButton.ImageKey = "vlc_preivous.png"; this.BackButton.Location = new System.Drawing.Point(40, 3); this.BackButton.Name = "BackButton"; this.BackButton.Size = new System.Drawing.Size(28, 26); this.BackButton.TabIndex = 9; this.BackButton.TabStop = false; this.toolTip1.SetToolTip(this.BackButton, "Jump to previous media"); this.BackButton.UseVisualStyleBackColor = true; this.BackButton.Click += new System.EventHandler(this.BackButton_Click); this.BackButton.MouseLeave += new System.EventHandler(this.BackButton_MouseLeave); // // PlayPauseButton // this.PlayPauseButton.BackgroundImageLayout = System.Windows.Forms.ImageLayout.Center; this.PlayPauseButton.ImageKey = "vlc_play.png"; this.PlayPauseButton.Location = new System.Drawing.Point(5, 3); this.PlayPauseButton.Name = "PlayPauseButton"; this.PlayPauseButton.Size = new System.Drawing.Size(28, 26); this.PlayPauseButton.TabIndex = 8; this.PlayPauseButton.TabStop = false; this.PlayPauseButton.TextAlign = System.Drawing.ContentAlignment.MiddleRight; this.toolTip1.SetToolTip(this.PlayPauseButton, "Play "); this.PlayPauseButton.UseVisualStyleBackColor = true; this.PlayPauseButton.Click += new System.EventHandler(this.PlayPauseButton_Click); this.PlayPauseButton.MouseLeave += new System.EventHandler(this.PlayPauseButton_MouseLeave); // // ControlImageList // this.ControlImageList.ImageStream = ((System.Windows.Forms.ImageListStreamer)(resources.GetObject("ControlImageList.ImageStream"))); this.ControlImageList.TransparentColor = System.Drawing.Color.Transparent; this.ControlImageList.Images.SetKeyName(0, "vlc_de_fullscreen.png"); this.ControlImageList.Images.SetKeyName(1, "vlc_fullscreen.png"); this.ControlImageList.Images.SetKeyName(2, "vlc_next.png"); this.ControlImageList.Images.SetKeyName(3, "vlc_play.png"); this.ControlImageList.Images.SetKeyName(4, "vlc_preivous.png"); this.ControlImageList.Images.SetKeyName(5, "vlc_snapshot.png"); this.ControlImageList.Images.SetKeyName(6, "vlc_stop.png"); this.ControlImageList.Images.SetKeyName(7, "volume_down.png"); this.ControlImageList.Images.SetKeyName(8, "volume_up.png"); // // label2 // this.label2.BorderStyle = System.Windows.Forms.BorderStyle.Fixed3D; this.label2.Dock = System.Windows.Forms.DockStyle.Bottom; this.label2.FlatStyle = System.Windows.Forms.FlatStyle.System; this.label2.Location = new System.Drawing.Point(0, 329); this.label2.Name = "label2"; this.label2.Size = new System.Drawing.Size(528, 2); this.label2.TabIndex = 6; this.label2.Text = "label2"; // // TimeTrackBar // this.TimeTrackBar.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this.TimeTrackBar.AutoSize = false; this.TimeTrackBar.LargeChange = 35; this.TimeTrackBar.Location = new System.Drawing.Point(55, 0); this.TimeTrackBar.Maximum = 1000; this.TimeTrackBar.Name = "TimeTrackBar"; this.TimeTrackBar.Size = new System.Drawing.Size(417, 23); this.TimeTrackBar.TabIndex = 4; this.TimeTrackBar.TabStop = false; this.TimeTrackBar.TickStyle = System.Windows.Forms.TickStyle.None; // // TimePanel // this.TimePanel.Controls.Add(this.TotalRemainingTimeLabel); this.TimePanel.Controls.Add(this.ElapsedTimeLabel); this.TimePanel.Controls.Add(this.TimeTrackBar); this.TimePanel.Dock = System.Windows.Forms.DockStyle.Bottom; this.TimePanel.Location = new System.Drawing.Point(0, 306); this.TimePanel.Name = "TimePanel"; this.TimePanel.Size = new System.Drawing.Size(528, 23); this.TimePanel.TabIndex = 2; // // TotalRemainingTimeLabel // this.TotalRemainingTimeLabel.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right))); this.TotalRemainingTimeLabel.AutoSize = true; this.TotalRemainingTimeLabel.Location = new System.Drawing.Point(476, 3); this.TotalRemainingTimeLabel.Name = "TotalRemainingTimeLabel"; this.TotalRemainingTimeLabel.Size = new System.Drawing.Size(49, 15); this.TotalRemainingTimeLabel.TabIndex = 5; this.TotalRemainingTimeLabel.Text = "00:00:00"; this.toolTip1.SetToolTip(this.TotalRemainingTimeLabel, "Total/Remaining time\r\nClick to toggle between total and remaining time"); this.TotalRemainingTimeLabel.Click += new System.EventHandler(this.TotalRemainingTimeLabel_Click); // // ElapsedTimeLabel // this.ElapsedTimeLabel.AutoSize = true; this.ElapsedTimeLabel.Location = new System.Drawing.Point(3, 3); this.ElapsedTimeLabel.Name = "ElapsedTimeLabel"; this.ElapsedTimeLabel.Size = new System.Drawing.Size(49, 15); this.ElapsedTimeLabel.TabIndex = 3; this.ElapsedTimeLabel.Text = "00:00:00"; this.toolTip1.SetToolTip(this.ElapsedTimeLabel, "Elapsed time"); // // PictureScreen // this.PictureScreen.BackColor = System.Drawing.SystemColors.WindowText; this.PictureScreen.BackgroundImageLayout = System.Windows.Forms.ImageLayout.Center; this.PictureScreen.Dock = System.Windows.Forms.DockStyle.Fill; this.PictureScreen.Location = new System.Drawing.Point(0, 0); this.PictureScreen.Name = "PictureScreen"; this.PictureScreen.Size = new System.Drawing.Size(528, 306); this.PictureScreen.TabIndex = 0; this.PictureScreen.DoubleClick += new System.EventHandler(this.PictureScreen_DoubleClick); // // MediaPlayer // this.AutoScaleDimensions = new System.Drawing.SizeF(7F, 15F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.ClientSize = new System.Drawing.Size(528, 365); this.Controls.Add(this.PictureScreen); this.Controls.Add(this.TimePanel); this.Controls.Add(this.label2); this.Controls.Add(this.CommandPanel); this.Font = new System.Drawing.Font("Segoe UI", 9F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.MinimizeBox = false; this.MinimumSize = new System.Drawing.Size(500, 101); this.Name = "MediaPlayer"; this.ShowIcon = false; this.ShowInTaskbar = false; this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen; this.Load += new System.EventHandler(this.MediaPlayer_Load); this.CommandPanel.ResumeLayout(false); ((System.ComponentModel.ISupportInitialize)(this.pictureBox1)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.SpeedTrackBar)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.VolumeTrackBar)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.TimeTrackBar)).EndInit(); this.TimePanel.ResumeLayout(false); this.TimePanel.PerformLayout(); this.ResumeLayout(false); } #endregion private System.Windows.Forms.Panel CommandPanel; private System.Windows.Forms.Label label2; private System.Windows.Forms.TrackBar TimeTrackBar; private System.Windows.Forms.Button ForwardButton; private System.Windows.Forms.Button StopButton; private System.Windows.Forms.Button BackButton; private System.Windows.Forms.Button PlayPauseButton; private System.Windows.Forms.Panel TimePanel; private System.Windows.Forms.Label TotalRemainingTimeLabel; private System.Windows.Forms.Label ElapsedTimeLabel; private System.Windows.Forms.TrackBar VolumeTrackBar; private System.Windows.Forms.TrackBar SpeedTrackBar; private System.Windows.Forms.ToolTip toolTip1; private System.Windows.Forms.Button FullScreenButton; private System.Windows.Forms.Panel PictureScreen; private System.Windows.Forms.Button SnapshotButton; private System.Windows.Forms.ImageList ControlImageList; private System.Windows.Forms.PictureBox pictureBox1; private System.Windows.Forms.Label label1; } }
55.994012
172
0.623463
[ "MIT" ]
Adrianvdh/Prepril-Remote
Plugins/MediaManager/MediaManager.Client/MediaPlayer.designer.cs
18,704
C#
using System; using System.Collections.Generic; using System.ComponentModel; using System.Linq; using System.Linq.Expressions; using System.Reflection; using System.Text.RegularExpressions; using System.Threading.Tasks; using Customer.API.Infrastructure.Contexts; using Customer.API.Models; using Microsoft.EntityFrameworkCore; using Newtonsoft.Json; using Newtonsoft.Json.Serialization; namespace Customer.API.Infrastructure.Utils { public class TestA { public string Foo { get; set; } } public class PropertyIgnoreSerializerContractResolver : DefaultContractResolver { private readonly Dictionary<Type, HashSet<string>> _ignores; public PropertyIgnoreSerializerContractResolver () { _ignores = new Dictionary<Type, HashSet<string>> (); } public void IgnoreProperty (Type type, params string[] jsonPropertyNames) { if (!_ignores.ContainsKey (type)) _ignores[type] = new HashSet<string> (); foreach (var prop in jsonPropertyNames) _ignores[type].Add (prop); } protected override JsonProperty CreateProperty (MemberInfo member, MemberSerialization memberSerialization) { var property = base.CreateProperty (member, memberSerialization); if (IsIgnored (property.DeclaringType, property.PropertyName)) { property.ShouldSerialize = i => false; property.Ignored = true; } return property; } private bool IsIgnored (Type type, string jsonPropertyName) { if (!_ignores.ContainsKey (type)) return false; return _ignores[type].Contains (jsonPropertyName); } } public static class APIUtils { public static string UpperFirstLetter (this string value) { return value[0].ToString ().ToUpperInvariant () + value.Substring (1, value.Length - 1); } public static string LowerFirstLetter (this string value) { return value[0].ToString ().ToLowerInvariant () + value.Substring (1, value.Length - 1); } private static MethodInfo GetMethodInfo<T1, T2> (Func<T1, T2> f, T1 unused1) { return f.Method; } private static MethodInfo GetMethodInfo<T1, T2, T3> (Func<T1, T2, T3> f, T1 unused1, T2 unused2) { return f.Method; } private static MethodInfo GetMethodInfo<T1, T2, T3, T4> (Func<T1, T2, T3, T4> f, T1 unused1, T2 unused2, T3 unused3) { return f.Method; } private static MethodInfo GetMethodInfo<T1, T2, T3, T4, T5> (Func<T1, T2, T3, T4, T5> f, T1 unused1, T2 unused2, T3 unused3, T4 unused4) { return f.Method; } private static MethodInfo GetMethodInfo<T1, T2, T3, T4, T5, T6> (Func<T1, T2, T3, T4, T5, T6> f, T1 unused1, T2 unused2, T3 unused3, T4 unused4, T5 unused5) { return f.Method; } private static MethodInfo GetMethodInfo<T1, T2, T3, T4, T5, T6, T7> (Func<T1, T2, T3, T4, T5, T6, T7> f, T1 unused1, T2 unused2, T3 unused3, T4 unused4, T5 unused5, T6 unused6) { return f.Method; } public static IQueryable<TEntity> DynamicTake<TEntity> (this IQueryable<TEntity> query, int? limit) { if (limit == null) { return query; } Expression queryExpr = query.Expression; queryExpr = Expression.Call ( null, GetMethodInfo (Queryable.Take, query, limit.Value), new Expression[] { query.Expression, Expression.Constant (limit.Value) } ); return query.Provider.CreateQuery<TEntity> (queryExpr); } public static IQueryable<TEntity> DynamicSkip<TEntity> (this IQueryable<TEntity> query, int? offset) { if (offset == null) { return query; } Expression queryExpr = query.Expression; queryExpr = Expression.Call ( null, GetMethodInfo (Queryable.Skip, query, offset.Value), new Expression[] { query.Expression, Expression.Constant (offset.Value) } ); return query.Provider.CreateQuery<TEntity> (queryExpr); } public static IQueryable<dynamic> DynamicSelect<TEntity> (this IQueryable<TEntity> query, String fields) { if (string.IsNullOrWhiteSpace (fields)) { return (IQueryable<dynamic>) query; } string[] fieldArray = fields.Split (","); Expression queryExpr = query.Expression; Func<TEntity, dynamic> selectorFunc = (element) => { dynamic filteredObject = new System.Dynamic.ExpandoObject (); for (int i = 0; i < fieldArray.Length; i++) { ((IDictionary<String, Object>) filteredObject) [fieldArray[i].LowerFirstLetter ()] = query.ElementType.GetProperty (fieldArray[i].UpperFirstLetter ()).GetValue (element, null); } return filteredObject; }; Expression<Func<TEntity, dynamic>> selector = x => selectorFunc (x); queryExpr = Expression.Call ( null, GetMethodInfo (Queryable.Select, query, selector), new Expression[] { query.Expression, Expression.Quote (selector) } ); return query.Provider.CreateQuery<dynamic> (queryExpr); } public static IQueryable<TEntity> DynamicWhere<TEntity> (this IQueryable<TEntity> query, String searches) { if (string.IsNullOrWhiteSpace (searches)) { return query; } string[] searchArray = searches.Split (","); Expression queryExpr = query.Expression; ParameterExpression parameter = Expression.Parameter (query.ElementType, "p"); Expression predicateBody = null; for (int i = 0; i < searchArray.Length; i++) { string searchValue = string.Empty; string searchField = string.Empty; string searchExpression = string.Empty; searchField = Regex.Split (searchArray[i], "\\[.*]") [0].UpperFirstLetter (); searchValue = Regex.Split (searchArray[i], "\\[.*]") [1]; searchExpression = Regex.Replace (searchArray[i].Substring (searchField.Length, searchArray[i].IndexOf (searchValue) - searchField.Length), "[\\[\\]]", ""); PropertyInfo property = query.ElementType.GetProperty (searchField); Expression left = Expression.Property (parameter, property); TypeConverter typeConverter = TypeDescriptor.GetConverter (property.PropertyType); object searchValueTyped = typeConverter.ConvertFromString (searchValue); Expression right = Expression.Constant (searchValueTyped, property.PropertyType); Expression expression = null; switch (searchExpression) { case "=": expression = Expression.Equal (left, right); break; case "!=": expression = Expression.NotEqual (left, right); break; case ">=": expression = Expression.GreaterThanOrEqual (left, right); break; case "<=": expression = Expression.LessThanOrEqual (left, right); break; case ">": expression = Expression.GreaterThan (left, right); break; case "<": expression = Expression.LessThan (left, right); break; case "%": case "!%": case "^%": case "%^": case "!^%": case "!%^": expression = GetLikeExpressions (parameter, property, searchValue, searchExpression); break; default: throw new Exception ("Undefined search parameter"); } if (predicateBody == null) { predicateBody = expression; } else { predicateBody = Expression.And (predicateBody, expression); } } queryExpr = Expression.Call ( typeof (Queryable), "Where", new Type[] { query.ElementType }, queryExpr, Expression.Quote (Expression.Lambda (predicateBody, parameter)) ); return query.Provider.CreateQuery<TEntity> (queryExpr); } private static Expression GetLikeExpressions (ParameterExpression parameter, PropertyInfo property, string searchValue, string searchExpression) { Expression expression = null; MemberExpression memberExpression = Expression.MakeMemberAccess (parameter, property); ConstantExpression c = Expression.Constant (searchValue, typeof (string)); MethodInfo mi = null; var toString = typeof (Object).GetMethod ("ToString"); var toStringValue = Expression.Call (memberExpression, toString); switch (searchExpression) { case "%": mi = typeof (string).GetMethod ("Contains", new Type[] { typeof (string) }); expression = Expression.Call (toStringValue, mi, c); break; case "!%": mi = typeof (string).GetMethod ("Contains", new Type[] { typeof (string) }); expression = Expression.Call (toStringValue, mi, c); expression = Expression.Not (expression); break; case "^%": mi = typeof (string).GetMethod ("StartsWith", new Type[] { typeof (string) }); expression = Expression.Call (toStringValue, mi, c); break; case "%^": mi = typeof (string).GetMethod ("EndsWith", new Type[] { typeof (string) }); expression = Expression.Call (toStringValue, mi, c); break; case "!^%": mi = typeof (string).GetMethod ("StartsWith", new Type[] { typeof (string) }); expression = Expression.Call (toStringValue, mi, c); expression = Expression.Not (expression); break; case "!%^": mi = typeof (string).GetMethod ("EndsWith", new Type[] { typeof (string) }); expression = Expression.Call (toStringValue, mi, c); expression = Expression.Not (expression); break; } return expression; } public static IQueryable<TEntity> DynamicOrder<TEntity> (this IQueryable<TEntity> query, String sorts) { if (string.IsNullOrWhiteSpace (sorts)) { return query; } string[] sortArray = sorts.Split (","); Expression queryExpr = query.Expression; for (int i = 0; i < sortArray.Length; i++) { string sortDirection = string.Empty; string sortField = string.Empty; if (sortArray[i][0] == '+') { sortDirection = i == 0 ? "OrderBy" : "ThenBy"; } else if (sortArray[i][0] == '-') { sortDirection = i == 0 ? "OrderByDescending" : "ThenByDescending"; } else { //TODO throw undefined order error; } //TODO check validation sortField = sortArray[i].Substring (1, sortArray[i].Length - 1).UpperFirstLetter (); ParameterExpression parameter = Expression.Parameter (query.ElementType, "p"); PropertyInfo property = query.ElementType.GetProperty (sortField); MemberExpression propertyAccess = Expression.MakeMemberAccess (parameter, property); queryExpr = Expression.Call ( typeof (Queryable), sortDirection, new Type[] { query.ElementType, property.PropertyType }, queryExpr, Expression.Quote (Expression.Lambda (propertyAccess, parameter)) ); } return query.Provider.CreateQuery<TEntity> (queryExpr); } } }
41.574675
196
0.549473
[ "MIT" ]
onur-ozel/o-bank
services/Customer.API/Infrastructure/Utils/APIUtils.cs
12,805
C#
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Diagnostics; namespace System.DirectoryServices.AccountManagement { internal class EmptySet : BookmarkableResultSet { internal EmptySet() { // Nothing to do } internal override object CurrentAsPrincipal { get { Debug.Fail("EmptySet.CurrentAsPrincipal: Shouldn't be here"); return null; } } internal override bool MoveNext() { // Mimic an empty set return false; } internal override void Reset() { // Nothing to do } internal override ResultSetBookmark BookmarkAndReset() { return new EmptySetBookmark(); } internal override void RestoreBookmark(ResultSetBookmark bookmark) { // Nothing to do } } internal class EmptySetBookmark : ResultSetBookmark { } }
23.076923
77
0.575
[ "MIT" ]
Mattlk13/corefx
src/System.DirectoryServices.AccountManagement/src/System/DirectoryServices/AccountManagement/EmptySet.cs
1,200
C#
using ObrasBibliotecariasApp.DataAccess; using ObrasBibliotecariasApp.Interfaces; using ObrasBibliotecariasApp.Models; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.HttpsPolicy; using Microsoft.AspNetCore.SpaServices.AngularCli; using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Hosting; namespace ObrasBibliotecariasApp { 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.AddTransient<IAuthor, AuthorDataAccessLayer>(); services.AddDbContext<myDBContext>(options => options.UseSqlServer(Configuration["ConnectionStrings:DefaultConnection"])); services.AddMvc(options => options.EnableEndpointRouting = false); // In production, the Angular files will be served from this directory services.AddSpaStaticFiles(configuration => { configuration.RootPath = "ClientApp/dist"; }); } // 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(); } else { app.UseExceptionHandler("/Error"); // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts. app.UseHsts(); } app.UseHttpsRedirection(); app.UseStaticFiles(); app.UseSpaStaticFiles(); app.UseMvc(routes => { routes.MapRoute( name: "default", template: "{controller}/{action=Index}/{id?}"); }); app.UseSpa(spa => { // To learn more about options for serving an Angular SPA from ASP.NET Core, // see https://go.microsoft.com/fwlink/?linkid=864501 spa.Options.SourcePath = "ClientApp"; if (env.IsDevelopment()) { spa.UseAngularCliServer(npmScript: "start"); } }); } } }
34.43038
143
0.607721
[ "Unlicense" ]
marcelomsr/obras-bibliograficas
ObrasBibliograficas/ObrasBibliotecariasApp/Startup.cs
2,720
C#
using System; using System.Collections.Generic; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; using System.IO; using System.Threading; using System.Globalization; using System.Runtime.InteropServices; using System.Text.RegularExpressions; using System.Diagnostics; using System.Drawing.Text; using OpenTK; using OpenTK.Graphics.OpenGL; using static AssetStudio.Studio; using static AssetStudio.Importer; namespace AssetStudio { partial class AssetStudioForm : Form { private AssetPreloadData lastSelectedItem; private AssetPreloadData lastLoadedAsset; private FMOD.System system; private FMOD.Sound sound; private FMOD.Channel channel; private FMOD.SoundGroup masterSoundGroup; private FMOD.MODE loopMode = FMOD.MODE.LOOP_OFF; private uint FMODlenms; private float FMODVolume = 0.8f; private Bitmap imageTexture; #region OpenTK private int pgmID, pgmColorID, pgmBlackID; private int attributeVertexPosition; private int attributeNormalDirection; private int attributeVertexColor; private int uniformModelMatrix; private int uniformViewMatrix; private int vao; private Vector3[] vertexData; private Vector3[] normalData; private Vector3[] normal2Data; private Vector4[] colorData; private Matrix4 modelMatrixData; private Matrix4 viewMatrixData; private int[] indiceData; private int wireFrameMode; private int shadeMode; private int normalMode; #endregion //asset list sorting helpers private int firstSortColumn = -1; private int secondSortColumn; private bool reverseSort; private bool enableFiltering; //tree search private int nextGObject; private List<GameObject> treeSrcResults = new List<GameObject>(); [DllImport("gdi32.dll")] private static extern IntPtr AddFontMemResourceEx(IntPtr pbFont, uint cbFont, IntPtr pdv, [In] ref uint pcFonts); private void loadFile_Click(object sender, EventArgs e) { if (openFileDialog1.ShowDialog() == DialogResult.OK) { resetForm(); ThreadPool.QueueUserWorkItem(state => { mainPath = Path.GetDirectoryName(openFileDialog1.FileNames[0]); MergeSplitAssets(mainPath); var readFile = ProcessingSplitFiles(openFileDialog1.FileNames.ToList()); foreach (var i in readFile) { importFiles.Add(i); importFilesHash.Add(Path.GetFileName(i).ToUpper()); } SetProgressBarValue(0); SetProgressBarMaximum(importFiles.Count); //use a for loop because list size can change for (int f = 0; f < importFiles.Count; f++) { LoadFile(importFiles[f]); ProgressBarPerformStep(); } importFilesHash.Clear(); assetsfileListHash.Clear(); BuildAssetStrucutres(); }); } } private void loadFolder_Click(object sender, EventArgs e) { var openFolderDialog1 = new OpenFolderDialog(); if (openFolderDialog1.ShowDialog(this) == DialogResult.OK) { resetForm(); ThreadPool.QueueUserWorkItem(state => { mainPath = openFolderDialog1.Folder; MergeSplitAssets(mainPath); var files = Directory.GetFiles(mainPath, "*.*", SearchOption.AllDirectories).ToList(); var readFile = ProcessingSplitFiles(files); foreach (var i in readFile) { importFiles.Add(i); importFilesHash.Add(Path.GetFileName(i)); } SetProgressBarValue(0); SetProgressBarMaximum(importFiles.Count); //use a for loop because list size can change for (int f = 0; f < importFiles.Count; f++) { LoadFile(importFiles[f]); ProgressBarPerformStep(); } importFilesHash.Clear(); assetsfileListHash.Clear(); BuildAssetStrucutres(); }); } } private void extractFileToolStripMenuItem_Click(object sender, EventArgs e) { var openBundleDialog = new OpenFileDialog { Filter = "All types|*.*", FilterIndex = 1, RestoreDirectory = true, Multiselect = true }; if (openBundleDialog.ShowDialog() == DialogResult.OK) { progressBar1.Value = 0; progressBar1.Maximum = openBundleDialog.FileNames.Length; ExtractFile(openBundleDialog.FileNames); } } private void extractFolderToolStripMenuItem_Click(object sender, EventArgs e) { var openFolderDialog1 = new OpenFolderDialog(); if (openFolderDialog1.ShowDialog(this) == DialogResult.OK) { var files = Directory.GetFiles(openFolderDialog1.Folder, "*.*", SearchOption.AllDirectories); progressBar1.Value = 0; progressBar1.Maximum = files.Length; ExtractFile(files); } } private void BuildAssetStrucutres() { if (assetsfileList.Count == 0) { StatusStripUpdate("No file was loaded."); return; } BuildAssetStructures(!dontLoadAssetsMenuItem.Checked, displayAll.Checked, !dontBuildHierarchyMenuItem.Checked, buildClassStructuresMenuItem.Checked, displayOriginalName.Checked, out var fileNodes); BeginInvoke(new Action(() => { if (!string.IsNullOrEmpty(productName)) { Text = $"AssetStudio - {productName} - {assetsfileList[0].m_Version} - {assetsfileList[0].platformStr}"; } else if (assetsfileList.Count > 0) { Text = $"AssetStudio - no productName - {assetsfileList[0].m_Version} - {assetsfileList[0].platformStr}"; } if (!dontLoadAssetsMenuItem.Checked) { assetListView.VirtualListSize = visibleAssets.Count; //will only work if ListView is visible resizeAssetListColumns(); } if (!dontBuildHierarchyMenuItem.Checked) { sceneTreeView.BeginUpdate(); sceneTreeView.Nodes.AddRange(fileNodes.ToArray()); foreach (TreeNode node in sceneTreeView.Nodes) { node.HideCheckBox(); } sceneTreeView.EndUpdate(); } if (buildClassStructuresMenuItem.Checked) { classesListView.BeginUpdate(); foreach (var version in AllClassStructures) { ListViewGroup versionGroup = new ListViewGroup(version.Key); classesListView.Groups.Add(versionGroup); foreach (var uclass in version.Value) { uclass.Value.Group = versionGroup; classesListView.Items.Add(uclass.Value); } } classesListView.EndUpdate(); } var types = exportableAssets.Select(x => x.Type).Distinct().ToArray(); foreach (var type in types) { var typeItem = new ToolStripMenuItem { CheckOnClick = true, Name = type.ToString(), Size = new Size(180, 22), Text = type.ToString() }; typeItem.Click += typeToolStripMenuItem_Click; showTypeToolStripMenuItem.DropDownItems.Add(typeItem); } allToolStripMenuItem.Checked = true; StatusStripUpdate($"Finished loading {assetsfileList.Count} files with {assetListView.Items.Count} exportable assets."); treeSearch.Select(); })); } private void typeToolStripMenuItem_Click(object sender, EventArgs e) { var typeItem = (ToolStripMenuItem)sender; if (typeItem != allToolStripMenuItem) { allToolStripMenuItem.Checked = false; } else if (allToolStripMenuItem.Checked) { for (var i = 1; i < showTypeToolStripMenuItem.DropDownItems.Count; i++) { var item = (ToolStripMenuItem)showTypeToolStripMenuItem.DropDownItems[i]; item.Checked = false; } } FilterAssetList(); } private void AssetStudioForm_KeyDown(object sender, KeyEventArgs e) { if (e.Control && e.Alt && e.KeyCode == Keys.D) { debugMenuItem.Visible = !debugMenuItem.Visible; buildClassStructuresMenuItem.Checked = debugMenuItem.Visible; dontLoadAssetsMenuItem.Checked = debugMenuItem.Visible; dontBuildHierarchyMenuItem.Checked = debugMenuItem.Visible; if (tabControl1.TabPages.Contains(tabPage3)) { tabControl1.TabPages.Remove(tabPage3); } else { tabControl1.TabPages.Add(tabPage3); } } if (glControl1.Visible) { switch (e.KeyCode) { case Keys.D: // --> Right if (e.Shift) //Move { viewMatrixData *= Matrix4.CreateTranslation(0.1f, 0, 0); } else //Rotate { viewMatrixData *= Matrix4.CreateRotationY(0.1f); } glControl1.Invalidate(); break; case Keys.A: // <-- Left if (e.Shift) //Move { viewMatrixData *= Matrix4.CreateTranslation(-0.1f, 0, 0); } else //Rotate { viewMatrixData *= Matrix4.CreateRotationY(-0.1f); } glControl1.Invalidate(); break; case Keys.W: // Up if (e.Control) //Toggle WireFrame { wireFrameMode = (wireFrameMode + 1) % 3; glControl1.Invalidate(); } else if (e.Shift) //Move { viewMatrixData *= Matrix4.CreateTranslation(0, 0.1f, 0); } else //Rotate { viewMatrixData *= Matrix4.CreateRotationX(0.1f); } glControl1.Invalidate(); break; case Keys.S: // Down if (e.Control) //Toggle Shade { shadeMode = (shadeMode + 1) % 2; glControl1.Invalidate(); } else if (e.Shift) //Move { viewMatrixData *= Matrix4.CreateTranslation(0, -0.1f, 0); } else //Rotate { viewMatrixData *= Matrix4.CreateRotationX(-0.1f); } glControl1.Invalidate(); break; case Keys.Q: // Zoom Out viewMatrixData *= Matrix4.CreateScale(0.9f); glControl1.Invalidate(); break; case Keys.E: // Zoom In viewMatrixData *= Matrix4.CreateScale(1.1f); glControl1.Invalidate(); break; } // Normal mode if (e.Control && e.KeyCode == Keys.N) { normalMode = (normalMode + 1) % 2; createVAO(); glControl1.Invalidate(); } // Toggle Timer if (e.KeyCode == Keys.T) { timerOpenTK.Enabled = !timerOpenTK.Enabled; } } } private void dontLoadAssetsMenuItem_CheckedChanged(object sender, EventArgs e) { if (dontLoadAssetsMenuItem.Checked) { dontBuildHierarchyMenuItem.Checked = true; dontBuildHierarchyMenuItem.Enabled = false; } else { dontBuildHierarchyMenuItem.Enabled = true; } } private void exportClassStructuresMenuItem_Click(object sender, EventArgs e) { if (AllClassStructures.Count > 0) { var saveFolderDialog1 = new OpenFolderDialog(); if (saveFolderDialog1.ShowDialog(this) == DialogResult.OK) { progressBar1.Value = 0; progressBar1.Maximum = AllClassStructures.Count; var savePath = saveFolderDialog1.Folder; foreach (var version in AllClassStructures) { if (version.Value.Count > 0) { string versionPath = savePath + "\\" + version.Key; Directory.CreateDirectory(versionPath); foreach (var uclass in version.Value) { string saveFile = $"{versionPath}\\{uclass.Key} {uclass.Value.Text}.txt"; using (StreamWriter TXTwriter = new StreamWriter(saveFile)) { TXTwriter.Write(uclass.Value.ToString()); } } } progressBar1.PerformStep(); } StatusStripUpdate("Finished exporting class structures"); progressBar1.Value = 0; } } } private void enablePreview_Check(object sender, EventArgs e) { if (lastLoadedAsset != null) { switch (lastLoadedAsset.Type) { case ClassIDReference.Texture2D: case ClassIDReference.Sprite: { if (enablePreview.Checked && imageTexture != null) { previewPanel.BackgroundImage = imageTexture; } else { previewPanel.BackgroundImage = Properties.Resources.preview; previewPanel.BackgroundImageLayout = ImageLayout.Center; } } break; case ClassIDReference.Shader: case ClassIDReference.TextAsset: case ClassIDReference.MonoBehaviour: textPreviewBox.Visible = !textPreviewBox.Visible; break; case ClassIDReference.Font: fontPreviewBox.Visible = !fontPreviewBox.Visible; break; case ClassIDReference.AudioClip: { FMODpanel.Visible = !FMODpanel.Visible; if (sound != null && channel != null) { var result = channel.isPlaying(out var playing); if (result == FMOD.RESULT.OK && playing) { result = channel.stop(); FMODreset(); } } else if (FMODpanel.Visible) { PreviewAsset(lastLoadedAsset); } break; } } } else if (lastSelectedItem != null && enablePreview.Checked) { lastLoadedAsset = lastSelectedItem; PreviewAsset(lastLoadedAsset); } Properties.Settings.Default["enablePreview"] = enablePreview.Checked; Properties.Settings.Default.Save(); } private void displayAssetInfo_Check(object sender, EventArgs e) { if (displayInfo.Checked && assetInfoLabel.Text != null) { assetInfoLabel.Visible = true; } else { assetInfoLabel.Visible = false; } Properties.Settings.Default["displayInfo"] = displayInfo.Checked; Properties.Settings.Default.Save(); } private void MenuItem_CheckedChanged(object sender, EventArgs e) { Properties.Settings.Default[((ToolStripMenuItem)sender).Name] = ((ToolStripMenuItem)sender).Checked; Properties.Settings.Default.Save(); } private void assetGroupOptions_SelectedIndexChanged(object sender, EventArgs e) { Properties.Settings.Default["assetGroupOption"] = ((ToolStripComboBox)sender).SelectedIndex; Properties.Settings.Default.Save(); } private void showExpOpt_Click(object sender, EventArgs e) { ExportOptions exportOpt = new ExportOptions(); exportOpt.ShowDialog(); } private void assetListView_RetrieveVirtualItem(object sender, RetrieveVirtualItemEventArgs e) { e.Item = visibleAssets[e.ItemIndex]; } private void tabPageSelected(object sender, TabControlEventArgs e) { switch (e.TabPageIndex) { case 0: treeSearch.Select(); break; case 1: resizeAssetListColumns(); //required because the ListView is not visible on app launch classPreviewPanel.Visible = false; previewPanel.Visible = true; listSearch.Select(); break; case 2: previewPanel.Visible = false; classPreviewPanel.Visible = true; break; } } private void treeSearch_Enter(object sender, EventArgs e) { if (treeSearch.Text == " Search ") { treeSearch.Text = ""; treeSearch.ForeColor = SystemColors.WindowText; } } private void treeSearch_Leave(object sender, EventArgs e) { if (treeSearch.Text == "") { treeSearch.Text = " Search "; treeSearch.ForeColor = SystemColors.GrayText; } } private void treeSearch_TextChanged(object sender, EventArgs e) { treeSrcResults.Clear(); nextGObject = 0; } private void treeSearch_KeyDown(object sender, KeyEventArgs e) { if (e.KeyCode == Keys.Enter) { if (treeSrcResults.Count == 0) { foreach (var aFile in assetsfileList) { foreach (var gObject in aFile.GameObjectList.Values) { if (gObject.Text.IndexOf(treeSearch.Text, StringComparison.CurrentCultureIgnoreCase) >= 0) { treeSrcResults.Add(gObject); } } } } if (treeSrcResults.Count > 0) { if (nextGObject >= treeSrcResults.Count) { nextGObject = 0; } treeSrcResults[nextGObject].EnsureVisible(); sceneTreeView.SelectedNode = treeSrcResults[nextGObject]; nextGObject++; } } } private void sceneTreeView_AfterCheck(object sender, TreeViewEventArgs e) { foreach (GameObject childNode in e.Node.Nodes) { childNode.Checked = e.Node.Checked; } } private void resizeAssetListColumns() { assetListView.AutoResizeColumn(1, ColumnHeaderAutoResizeStyle.HeaderSize); assetListView.AutoResizeColumn(1, ColumnHeaderAutoResizeStyle.ColumnContent); assetListView.AutoResizeColumn(2, ColumnHeaderAutoResizeStyle.HeaderSize); assetListView.AutoResizeColumn(2, ColumnHeaderAutoResizeStyle.ColumnContent); var vscrollwidth = SystemInformation.VerticalScrollBarWidth; var hasvscroll = (visibleAssets.Count / (float)assetListView.Height) > 0.0567f; columnHeaderName.Width = assetListView.Width - columnHeaderType.Width - columnHeaderSize.Width - (hasvscroll ? (5 + vscrollwidth) : 5); } private void tabPage2_Resize(object sender, EventArgs e) { resizeAssetListColumns(); } private void listSearch_Enter(object sender, EventArgs e) { if (listSearch.Text == " Filter ") { listSearch.Text = ""; listSearch.ForeColor = SystemColors.WindowText; enableFiltering = true; } } private void listSearch_Leave(object sender, EventArgs e) { if (listSearch.Text == "") { enableFiltering = false; listSearch.Text = " Filter "; listSearch.ForeColor = SystemColors.GrayText; } } private void ListSearchTextChanged(object sender, EventArgs e) { if (enableFiltering) { FilterAssetList(); } } private void assetListView_ColumnClick(object sender, ColumnClickEventArgs e) { if (firstSortColumn != e.Column) { //sorting column has been changed reverseSort = false; secondSortColumn = firstSortColumn; } else { reverseSort = !reverseSort; } firstSortColumn = e.Column; assetListView.BeginUpdate(); assetListView.SelectedIndices.Clear(); switch (e.Column) { case 0: visibleAssets.Sort(delegate (AssetPreloadData a, AssetPreloadData b) { int xdiff = reverseSort ? b.Text.CompareTo(a.Text) : a.Text.CompareTo(b.Text); if (xdiff != 0) return xdiff; return secondSortColumn == 1 ? a.TypeString.CompareTo(b.TypeString) : a.fullSize.CompareTo(b.fullSize); }); break; case 1: visibleAssets.Sort(delegate (AssetPreloadData a, AssetPreloadData b) { int xdiff = reverseSort ? b.TypeString.CompareTo(a.TypeString) : a.TypeString.CompareTo(b.TypeString); if (xdiff != 0) return xdiff; return secondSortColumn == 2 ? a.fullSize.CompareTo(b.fullSize) : a.Text.CompareTo(b.Text); }); break; case 2: visibleAssets.Sort(delegate (AssetPreloadData a, AssetPreloadData b) { int xdiff = reverseSort ? b.fullSize.CompareTo(a.fullSize) : a.fullSize.CompareTo(b.fullSize); if (xdiff != 0) return xdiff; return secondSortColumn == 1 ? a.TypeString.CompareTo(b.TypeString) : a.Text.CompareTo(b.Text); }); break; } assetListView.EndUpdate(); resizeAssetListColumns(); } private void selectAsset(object sender, ListViewItemSelectionChangedEventArgs e) { previewPanel.BackgroundImage = Properties.Resources.preview; previewPanel.BackgroundImageLayout = ImageLayout.Center; assetInfoLabel.Visible = false; assetInfoLabel.Text = null; textPreviewBox.Visible = false; fontPreviewBox.Visible = false; FMODpanel.Visible = false; glControl1.Visible = false; lastLoadedAsset = null; StatusStripUpdate(""); FMODreset(); lastSelectedItem = (AssetPreloadData)e.Item; if (e.IsSelected) { if (enablePreview.Checked) { lastLoadedAsset = lastSelectedItem; PreviewAsset(lastLoadedAsset); } if (displayInfo.Checked && assetInfoLabel.Text != null)//only display the label if asset has info text { assetInfoLabel.Text = lastSelectedItem.InfoText; assetInfoLabel.Visible = true; } } } private void classesListView_ItemSelectionChanged(object sender, ListViewItemSelectionChangedEventArgs e) { if (e.IsSelected) { classTextBox.Text = ((ClassStruct)classesListView.SelectedItems[0]).ToString(); } } private void PreviewAsset(AssetPreloadData asset) { switch (asset.Type) { case ClassIDReference.Texture2D: { imageTexture?.Dispose(); var m_Texture2D = new Texture2DConverter(new Texture2D(asset, true)); imageTexture = m_Texture2D.ConvertToBitmap(true); if (imageTexture != null) { previewPanel.BackgroundImage = imageTexture; if (imageTexture.Width > previewPanel.Width || imageTexture.Height > previewPanel.Height) previewPanel.BackgroundImageLayout = ImageLayout.Zoom; else previewPanel.BackgroundImageLayout = ImageLayout.Center; } else { StatusStripUpdate("Unsupported image for preview"); } break; } case ClassIDReference.AudioClip: { AudioClip m_AudioClip = new AudioClip(asset, true); if (m_AudioClip.m_AudioData == null) break; FMOD.CREATESOUNDEXINFO exinfo = new FMOD.CREATESOUNDEXINFO(); exinfo.cbsize = Marshal.SizeOf(exinfo); exinfo.length = (uint)m_AudioClip.m_Size; var result = system.createSound(m_AudioClip.m_AudioData, FMOD.MODE.OPENMEMORY | loopMode, ref exinfo, out sound); if (ERRCHECK(result)) { break; } result = sound.getSubSound(0, out var subsound); if (result == FMOD.RESULT.OK) { sound = subsound; } result = sound.getLength(out FMODlenms, FMOD.TIMEUNIT.MS); if (ERRCHECK(result)) { break; } result = system.playSound(sound, null, true, out channel); if (ERRCHECK(result)) { break; } FMODpanel.Visible = true; result = channel.getFrequency(out var frequency); if (ERRCHECK(result)) { break; } FMODinfoLabel.Text = frequency + " Hz"; FMODtimerLabel.Text = $"0:0.0 / {FMODlenms / 1000 / 60}:{FMODlenms / 1000 % 60}.{FMODlenms / 10 % 100}"; break; } case ClassIDReference.Shader: { Shader m_TextAsset = new Shader(asset, true); string m_Script_Text = Encoding.UTF8.GetString(m_TextAsset.m_Script); m_Script_Text = Regex.Replace(m_Script_Text, "(?<!\r)\n", "\r\n"); m_Script_Text = m_Script_Text.Replace("\0", "\\0"); textPreviewBox.Text = m_Script_Text; textPreviewBox.Visible = true; break; } case ClassIDReference.TextAsset: { TextAsset m_TextAsset = new TextAsset(asset, true); string m_Script_Text = Encoding.UTF8.GetString(m_TextAsset.m_Script); m_Script_Text = Regex.Replace(m_Script_Text, "(?<!\r)\n", "\r\n"); textPreviewBox.Text = m_Script_Text; textPreviewBox.Visible = true; break; } case ClassIDReference.MonoBehaviour: { MonoBehaviour m_MonoBehaviour = new MonoBehaviour(asset, true); textPreviewBox.Text = m_MonoBehaviour.serializedText; textPreviewBox.Visible = true; break; } case ClassIDReference.Font: { UFont m_Font = new UFont(asset, true); if (m_Font.m_FontData != null) { IntPtr data = Marshal.AllocCoTaskMem(m_Font.m_FontData.Length); Marshal.Copy(m_Font.m_FontData, 0, data, m_Font.m_FontData.Length); // We HAVE to do this to register the font to the system (Weird .NET bug !) uint cFonts = 0; var re = AddFontMemResourceEx(data, (uint)m_Font.m_FontData.Length, IntPtr.Zero, ref cFonts); if (re != IntPtr.Zero) { using (var pfc = new PrivateFontCollection()) { pfc.AddMemoryFont(data, m_Font.m_FontData.Length); Marshal.FreeCoTaskMem(data); if (pfc.Families.Length > 0) { fontPreviewBox.SelectionStart = 0; fontPreviewBox.SelectionLength = 80; fontPreviewBox.SelectionFont = new Font(pfc.Families[0], 16, FontStyle.Regular); fontPreviewBox.SelectionStart = 81; fontPreviewBox.SelectionLength = 56; fontPreviewBox.SelectionFont = new Font(pfc.Families[0], 12, FontStyle.Regular); fontPreviewBox.SelectionStart = 138; fontPreviewBox.SelectionLength = 56; fontPreviewBox.SelectionFont = new Font(pfc.Families[0], 18, FontStyle.Regular); fontPreviewBox.SelectionStart = 195; fontPreviewBox.SelectionLength = 56; fontPreviewBox.SelectionFont = new Font(pfc.Families[0], 24, FontStyle.Regular); fontPreviewBox.SelectionStart = 252; fontPreviewBox.SelectionLength = 56; fontPreviewBox.SelectionFont = new Font(pfc.Families[0], 36, FontStyle.Regular); fontPreviewBox.SelectionStart = 309; fontPreviewBox.SelectionLength = 56; fontPreviewBox.SelectionFont = new Font(pfc.Families[0], 48, FontStyle.Regular); fontPreviewBox.SelectionStart = 366; fontPreviewBox.SelectionLength = 56; fontPreviewBox.SelectionFont = new Font(pfc.Families[0], 60, FontStyle.Regular); fontPreviewBox.SelectionStart = 423; fontPreviewBox.SelectionLength = 55; fontPreviewBox.SelectionFont = new Font(pfc.Families[0], 72, FontStyle.Regular); fontPreviewBox.Visible = true; } } break; } } StatusStripUpdate("Unsupported font for preview. Try to export."); break; } case ClassIDReference.Mesh: { var m_Mesh = new Mesh(asset, true); if (m_Mesh.m_VertexCount > 0) { viewMatrixData = Matrix4.CreateRotationY(-(float)Math.PI / 4) * Matrix4.CreateRotationX(-(float)Math.PI / 6); #region Vertices if (m_Mesh.m_Vertices == null || m_Mesh.m_Vertices.Length == 0) { StatusStripUpdate("Mesh can't be previewed."); return; } int count = 3; if (m_Mesh.m_Vertices.Length == m_Mesh.m_VertexCount * 4) { count = 4; } vertexData = new Vector3[m_Mesh.m_VertexCount]; // Calculate Bounding float[] min = new float[3]; float[] max = new float[3]; for (int i = 0; i < 3; i++) { min[i] = m_Mesh.m_Vertices[i]; max[i] = m_Mesh.m_Vertices[i]; } for (int v = 0; v < m_Mesh.m_VertexCount; v++) { for (int i = 0; i < 3; i++) { min[i] = Math.Min(min[i], m_Mesh.m_Vertices[v * count + i]); max[i] = Math.Max(max[i], m_Mesh.m_Vertices[v * count + i]); } vertexData[v] = new Vector3( m_Mesh.m_Vertices[v * count], m_Mesh.m_Vertices[v * count + 1], m_Mesh.m_Vertices[v * count + 2]); } // Calculate modelMatrix Vector3 dist = Vector3.One, offset = Vector3.Zero; for (int i = 0; i < 3; i++) { dist[i] = max[i] - min[i]; offset[i] = (max[i] + min[i]) / 2; } float d = Math.Max(1e-5f, dist.Length); modelMatrixData = Matrix4.CreateTranslation(-offset) * Matrix4.CreateScale(2f / d); #endregion #region Indicies indiceData = new int[m_Mesh.m_Indices.Count]; for (int i = 0; i < m_Mesh.m_Indices.Count; i = i + 3) { indiceData[i] = (int)m_Mesh.m_Indices[i]; indiceData[i + 1] = (int)m_Mesh.m_Indices[i + 1]; indiceData[i + 2] = (int)m_Mesh.m_Indices[i + 2]; } #endregion #region Normals if (m_Mesh.m_Normals != null && m_Mesh.m_Normals.Length > 0) { if (m_Mesh.m_Normals.Length == m_Mesh.m_VertexCount * 3) count = 3; else if (m_Mesh.m_Normals.Length == m_Mesh.m_VertexCount * 4) count = 4; normalData = new Vector3[m_Mesh.m_VertexCount]; for (int n = 0; n < m_Mesh.m_VertexCount; n++) { normalData[n] = new Vector3( m_Mesh.m_Normals[n * count], m_Mesh.m_Normals[n * count + 1], m_Mesh.m_Normals[n * count + 2]); } } else normalData = null; // calculate normal by ourself normal2Data = new Vector3[m_Mesh.m_VertexCount]; int[] normalCalculatedCount = new int[m_Mesh.m_VertexCount]; for (int i = 0; i < m_Mesh.m_VertexCount; i++) { normal2Data[i] = Vector3.Zero; normalCalculatedCount[i] = 0; } for (int i = 0; i < m_Mesh.m_Indices.Count; i = i + 3) { Vector3 dir1 = vertexData[indiceData[i + 1]] - vertexData[indiceData[i]]; Vector3 dir2 = vertexData[indiceData[i + 2]] - vertexData[indiceData[i]]; Vector3 normal = Vector3.Cross(dir1, dir2); normal.Normalize(); for (int j = 0; j < 3; j++) { normal2Data[indiceData[i + j]] += normal; normalCalculatedCount[indiceData[i + j]]++; } } for (int i = 0; i < m_Mesh.m_VertexCount; i++) { if (normalCalculatedCount[i] == 0) normal2Data[i] = new Vector3(0, 1, 0); else normal2Data[i] /= normalCalculatedCount[i]; } #endregion #region Colors if (m_Mesh.m_Colors != null && m_Mesh.m_Colors.Length == m_Mesh.m_VertexCount * 3) { colorData = new Vector4[m_Mesh.m_VertexCount]; for (int c = 0; c < m_Mesh.m_VertexCount; c++) { colorData[c] = new Vector4( m_Mesh.m_Colors[c * 3], m_Mesh.m_Colors[c * 3 + 1], m_Mesh.m_Colors[c * 3 + 2], 1.0f); } } else if (m_Mesh.m_Colors != null && m_Mesh.m_Colors.Length == m_Mesh.m_VertexCount * 4) { colorData = new Vector4[m_Mesh.m_VertexCount]; for (int c = 0; c < m_Mesh.m_VertexCount; c++) { colorData[c] = new Vector4( m_Mesh.m_Colors[c * 4], m_Mesh.m_Colors[c * 4 + 1], m_Mesh.m_Colors[c * 4 + 2], m_Mesh.m_Colors[c * 4 + 3]); } } else { colorData = new Vector4[m_Mesh.m_VertexCount]; for (int c = 0; c < m_Mesh.m_VertexCount; c++) { colorData[c] = new Vector4(0.5f, 0.5f, 0.5f, 1.0f); } } #endregion glControl1.Visible = true; createVAO(); } StatusStripUpdate("Using OpenGL Version: " + GL.GetString(StringName.Version) + "\n" + "'T'=Start/Stop Rotation | 'WASD'=Manual Rotate | 'Shift WASD'=Move | 'Q/E'=Zoom \n" + "'Ctrl W'=Wireframe | 'Ctrl S'=Shade | 'Ctrl N'=ReNormal "); } break; case ClassIDReference.VideoClip: case ClassIDReference.MovieTexture: { StatusStripUpdate("Only supported export."); break; } case ClassIDReference.Sprite: { imageTexture?.Dispose(); imageTexture = SpriteHelper.GetImageFromSprite(asset); if (imageTexture != null) { previewPanel.BackgroundImage = imageTexture; if (imageTexture.Width > previewPanel.Width || imageTexture.Height > previewPanel.Height) previewPanel.BackgroundImageLayout = ImageLayout.Zoom; else previewPanel.BackgroundImageLayout = ImageLayout.Center; } else { StatusStripUpdate("Unsupported sprite for preview."); } break; } case ClassIDReference.Animator: { StatusStripUpdate("Can be exported to FBX file."); break; } case ClassIDReference.AnimationClip: { StatusStripUpdate("Can be exported with Animator or objects"); break; } default: { var str = asset.GetClassString(); if (str != null) { textPreviewBox.Text = str; textPreviewBox.Visible = true; } else StatusStripUpdate("Only supported export the raw file."); break; } } } private void FMODinit() { FMODreset(); var result = FMOD.Factory.System_Create(out system); if (ERRCHECK(result)) { return; } result = system.getVersion(out var version); ERRCHECK(result); if (version < FMOD.VERSION.number) { MessageBox.Show($"Error! You are using an old version of FMOD {version:X}. This program requires {FMOD.VERSION.number:X}."); Application.Exit(); } result = system.init(1, FMOD.INITFLAGS.NORMAL, IntPtr.Zero); if (ERRCHECK(result)) { return; } result = system.getMasterSoundGroup(out masterSoundGroup); if (ERRCHECK(result)) { return; } result = masterSoundGroup.setVolume(FMODVolume); if (ERRCHECK(result)) { return; } } private void FMODreset() { timer.Stop(); FMODprogressBar.Value = 0; FMODtimerLabel.Text = "0:00.0 / 0:00.0"; FMODstatusLabel.Text = "Stopped"; FMODinfoLabel.Text = ""; if (sound != null && sound.isValid()) { var result = sound.release(); ERRCHECK(result); sound = null; } } private void FMODplayButton_Click(object sender, EventArgs e) { if (sound != null && channel != null) { timer.Start(); var result = channel.isPlaying(out var playing); if ((result != FMOD.RESULT.OK) && (result != FMOD.RESULT.ERR_INVALID_HANDLE)) { if (ERRCHECK(result)) { return; } } if (playing) { result = channel.stop(); if (ERRCHECK(result)) { return; } result = system.playSound(sound, null, false, out channel); if (ERRCHECK(result)) { return; } FMODpauseButton.Text = "Pause"; } else { result = system.playSound(sound, null, false, out channel); if (ERRCHECK(result)) { return; } FMODstatusLabel.Text = "Playing"; if (FMODprogressBar.Value > 0) { uint newms = FMODlenms / 1000 * (uint)FMODprogressBar.Value; result = channel.setPosition(newms, FMOD.TIMEUNIT.MS); if ((result != FMOD.RESULT.OK) && (result != FMOD.RESULT.ERR_INVALID_HANDLE)) { if (ERRCHECK(result)) { return; } } } } } } private void FMODpauseButton_Click(object sender, EventArgs e) { if (sound != null && channel != null) { var result = channel.isPlaying(out var playing); if ((result != FMOD.RESULT.OK) && (result != FMOD.RESULT.ERR_INVALID_HANDLE)) { if (ERRCHECK(result)) { return; } } if (playing) { result = channel.getPaused(out var paused); if (ERRCHECK(result)) { return; } result = channel.setPaused(!paused); if (ERRCHECK(result)) { return; } if (paused) { FMODstatusLabel.Text = "Playing"; FMODpauseButton.Text = "Pause"; timer.Start(); } else { FMODstatusLabel.Text = "Paused"; FMODpauseButton.Text = "Resume"; timer.Stop(); } } } } private void FMODstopButton_Click(object sender, EventArgs e) { if (channel != null) { var result = channel.isPlaying(out var playing); if ((result != FMOD.RESULT.OK) && (result != FMOD.RESULT.ERR_INVALID_HANDLE)) { if (ERRCHECK(result)) { return; } } if (playing) { result = channel.stop(); if (ERRCHECK(result)) { return; } //channel = null; //don't FMODreset, it will nullify the sound timer.Stop(); FMODprogressBar.Value = 0; FMODtimerLabel.Text = "0:00.0 / 0:00.0"; FMODstatusLabel.Text = "Stopped"; FMODpauseButton.Text = "Pause"; } } } private void FMODloopButton_CheckedChanged(object sender, EventArgs e) { FMOD.RESULT result; loopMode = FMODloopButton.Checked ? FMOD.MODE.LOOP_NORMAL : FMOD.MODE.LOOP_OFF; if (sound != null) { result = sound.setMode(loopMode); if (ERRCHECK(result)) { return; } } if (channel != null) { result = channel.isPlaying(out var playing); if ((result != FMOD.RESULT.OK) && (result != FMOD.RESULT.ERR_INVALID_HANDLE)) { if (ERRCHECK(result)) { return; } } result = channel.getPaused(out var paused); if ((result != FMOD.RESULT.OK) && (result != FMOD.RESULT.ERR_INVALID_HANDLE)) { if (ERRCHECK(result)) { return; } } if (playing || paused) { result = channel.setMode(loopMode); if (ERRCHECK(result)) { return; } } } } private void FMODvolumeBar_ValueChanged(object sender, EventArgs e) { FMODVolume = Convert.ToSingle(FMODvolumeBar.Value) / 10; var result = masterSoundGroup.setVolume(FMODVolume); if (ERRCHECK(result)) { return; } } private void FMODprogressBar_Scroll(object sender, EventArgs e) { if (channel != null) { uint newms = FMODlenms / 1000 * (uint)FMODprogressBar.Value; FMODtimerLabel.Text = $"{newms / 1000 / 60}:{newms / 1000 % 60}.{newms / 10 % 100}/{FMODlenms / 1000 / 60}:{FMODlenms / 1000 % 60}.{FMODlenms / 10 % 100}"; } } private void FMODprogressBar_MouseDown(object sender, MouseEventArgs e) { timer.Stop(); } private void FMODprogressBar_MouseUp(object sender, MouseEventArgs e) { if (channel != null) { uint newms = FMODlenms / 1000 * (uint)FMODprogressBar.Value; var result = channel.setPosition(newms, FMOD.TIMEUNIT.MS); if ((result != FMOD.RESULT.OK) && (result != FMOD.RESULT.ERR_INVALID_HANDLE)) { if (ERRCHECK(result)) { return; } } result = channel.isPlaying(out var playing); if ((result != FMOD.RESULT.OK) && (result != FMOD.RESULT.ERR_INVALID_HANDLE)) { if (ERRCHECK(result)) { return; } } if (playing) { timer.Start(); } } } private void timer_Tick(object sender, EventArgs e) { uint ms = 0; bool playing = false; bool paused = false; if (channel != null) { var result = channel.getPosition(out ms, FMOD.TIMEUNIT.MS); if ((result != FMOD.RESULT.OK) && (result != FMOD.RESULT.ERR_INVALID_HANDLE)) { ERRCHECK(result); } result = channel.isPlaying(out playing); if ((result != FMOD.RESULT.OK) && (result != FMOD.RESULT.ERR_INVALID_HANDLE)) { ERRCHECK(result); } result = channel.getPaused(out paused); if ((result != FMOD.RESULT.OK) && (result != FMOD.RESULT.ERR_INVALID_HANDLE)) { ERRCHECK(result); } } FMODtimerLabel.Text = $"{ms / 1000 / 60}:{ms / 1000 % 60}.{ms / 10 % 100} / {FMODlenms / 1000 / 60}:{FMODlenms / 1000 % 60}.{FMODlenms / 10 % 100}"; FMODprogressBar.Value = (int)(ms * 1000 / FMODlenms); FMODstatusLabel.Text = paused ? "Paused " : playing ? "Playing" : "Stopped"; if (system != null && channel != null) { system.update(); } } private bool ERRCHECK(FMOD.RESULT result) { if (result != FMOD.RESULT.OK) { FMODreset(); StatusStripUpdate($"FMOD error! {result} - {FMOD.Error.String(result)}"); return true; } return false; } private void exportallobjectssplitToolStripMenuItem_Click(object sender, EventArgs e) { if (sceneTreeView.Nodes.Count > 0) { var saveFolderDialog1 = new OpenFolderDialog(); if (saveFolderDialog1.ShowDialog(this) == DialogResult.OK) { var savePath = saveFolderDialog1.Folder + "\\"; progressBar1.Value = 0; progressBar1.Maximum = sceneTreeView.Nodes.Cast<TreeNode>().Sum(x => x.Nodes.Count); ExportSplitObjects(savePath, sceneTreeView.Nodes); } } else { StatusStripUpdate("No Objects available for export"); } } private void ExportObjects_Click(object sender, EventArgs e) { if (sceneTreeView.Nodes.Count > 0) { var exportAll = ((ToolStripItem)sender).Name == "exportallobjectsMenuItem"; saveFileDialog1.FileName = productName + DateTime.Now.ToString("_yy_MM_dd__HH_mm_ss"); if (saveFileDialog1.ShowDialog() == DialogResult.OK) { var gameObjects = new List<GameObject>(); foreach (var assetsFile in assetsfileList) { foreach (var m_GameObject in assetsFile.GameObjectList.Values) { if (m_GameObject.Checked || exportAll) { gameObjects.Add(m_GameObject); } } } progressBar1.Value = 0; progressBar1.Maximum = 1; if (gameObjects.Count == 0) { progressBar1.PerformStep(); toolStripStatusLabel1.Text = "Nothing exported."; return; } toolStripStatusLabel1.Text = $"Exporting {Path.GetFileName(saveFileDialog1.FileName)}"; FBXExporter.WriteFBX(saveFileDialog1.FileName, gameObjects); toolStripStatusLabel1.Text = $"Finished exporting {Path.GetFileName(saveFileDialog1.FileName)}"; progressBar1.PerformStep(); if (openAfterExport.Checked && File.Exists(saveFileDialog1.FileName)) { Process.Start(Path.GetDirectoryName(saveFileDialog1.FileName)); } } } else { toolStripStatusLabel1.Text = "No Objects available for export"; } } private void ExportAssets_Click(object sender, EventArgs e) { if (exportableAssets.Count > 0) { var saveFolderDialog1 = new OpenFolderDialog(); if (saveFolderDialog1.ShowDialog(this) == DialogResult.OK) { timer.Stop(); List<AssetPreloadData> toExportAssets = null; switch (((ToolStripItem)sender).Name) { case "exportAllAssetsMenuItem": toExportAssets = exportableAssets; break; case "exportFilteredAssetsMenuItem": toExportAssets = visibleAssets; break; case "exportSelectedAssetsMenuItem": toExportAssets = new List<AssetPreloadData>(assetListView.SelectedIndices.Count); foreach (int i in assetListView.SelectedIndices) { toExportAssets.Add((AssetPreloadData)assetListView.Items[i]); } break; } ExportAssets(saveFolderDialog1.Folder, toExportAssets, assetGroupOptions.SelectedIndex, openAfterExport.Checked); } } else { StatusStripUpdate("No exportable assets loaded"); } } private void SetProgressBarValue(int value) { if (InvokeRequired) { BeginInvoke(new Action(() => { progressBar1.Value = value; })); } else { progressBar1.Value = value; } } private void SetProgressBarMaximum(int value) { if (InvokeRequired) { BeginInvoke(new Action(() => { progressBar1.Maximum = value; })); } else { progressBar1.Maximum = value; } } private void ProgressBarPerformStep() { if (InvokeRequired) { BeginInvoke(new Action(() => { progressBar1.PerformStep(); })); } else { progressBar1.PerformStep(); } } private void StatusStripUpdate(string statusText) { if (InvokeRequired) { BeginInvoke(new Action(() => { toolStripStatusLabel1.Text = statusText; })); } else { toolStripStatusLabel1.Text = statusText; } } private void ProgressBarMaximumAdd(int value) { if (InvokeRequired) { BeginInvoke(new Action(() => { progressBar1.Maximum += value; })); } else { progressBar1.Maximum += value; } } public AssetStudioForm() { Thread.CurrentThread.CurrentCulture = new CultureInfo("en-US"); InitializeComponent(); displayOriginalName.Checked = (bool)Properties.Settings.Default["displayOriginalName"]; displayAll.Checked = (bool)Properties.Settings.Default["displayAll"]; displayInfo.Checked = (bool)Properties.Settings.Default["displayInfo"]; enablePreview.Checked = (bool)Properties.Settings.Default["enablePreview"]; openAfterExport.Checked = (bool)Properties.Settings.Default["openAfterExport"]; assetGroupOptions.SelectedIndex = (int)Properties.Settings.Default["assetGroupOption"]; FMODinit(); //UI Studio.SetProgressBarValue = SetProgressBarValue; Studio.SetProgressBarMaximum = SetProgressBarMaximum; Studio.ProgressBarPerformStep = ProgressBarPerformStep; Studio.StatusStripUpdate = StatusStripUpdate; Studio.ProgressBarMaximumAdd = ProgressBarMaximumAdd; } private void timerOpenTK_Tick(object sender, EventArgs e) { if (glControl1.Visible) { viewMatrixData *= Matrix4.CreateRotationY(-0.1f); glControl1.Invalidate(); } } private void initOpenTK() { GL.Viewport(0, 0, glControl1.ClientSize.Width, glControl1.ClientSize.Height); GL.ClearColor(Color.CadetBlue); pgmID = GL.CreateProgram(); loadShader("vs", ShaderType.VertexShader, pgmID, out int vsID); loadShader("fs", ShaderType.FragmentShader, pgmID, out int fsID); GL.LinkProgram(pgmID); pgmColorID = GL.CreateProgram(); loadShader("vs", ShaderType.VertexShader, pgmColorID, out vsID); loadShader("fsColor", ShaderType.FragmentShader, pgmColorID, out fsID); GL.LinkProgram(pgmColorID); pgmBlackID = GL.CreateProgram(); loadShader("vs", ShaderType.VertexShader, pgmBlackID, out vsID); loadShader("fsBlack", ShaderType.FragmentShader, pgmBlackID, out fsID); GL.LinkProgram(pgmBlackID); attributeVertexPosition = GL.GetAttribLocation(pgmID, "vertexPosition"); attributeNormalDirection = GL.GetAttribLocation(pgmID, "normalDirection"); attributeVertexColor = GL.GetAttribLocation(pgmColorID, "vertexColor"); uniformModelMatrix = GL.GetUniformLocation(pgmID, "modelMatrix"); uniformViewMatrix = GL.GetUniformLocation(pgmID, "viewMatrix"); glControl1.Visible = false; } private void loadShader(string filename, ShaderType type, int program, out int address) { address = GL.CreateShader(type); var str = (string)Properties.Resources.ResourceManager.GetObject(filename); GL.ShaderSource(address, str); GL.CompileShader(address); GL.AttachShader(program, address); GL.DeleteShader(address); } private void createVBO(out int vboAddress, Vector3[] data, int address) { GL.GenBuffers(1, out vboAddress); GL.BindBuffer(BufferTarget.ArrayBuffer, vboAddress); GL.BufferData(BufferTarget.ArrayBuffer, (IntPtr)(data.Length * Vector3.SizeInBytes), data, BufferUsageHint.StaticDraw); GL.VertexAttribPointer(address, 3, VertexAttribPointerType.Float, false, 0, 0); GL.EnableVertexAttribArray(address); } private void createVBO(out int vboAddress, Vector4[] data, int address) { GL.GenBuffers(1, out vboAddress); GL.BindBuffer(BufferTarget.ArrayBuffer, vboAddress); GL.BufferData(BufferTarget.ArrayBuffer, (IntPtr)(data.Length * Vector4.SizeInBytes), data, BufferUsageHint.StaticDraw); GL.VertexAttribPointer(address, 4, VertexAttribPointerType.Float, false, 0, 0); GL.EnableVertexAttribArray(address); } private void createVBO(out int vboAddress, Matrix4 data, int address) { GL.GenBuffers(1, out vboAddress); GL.UniformMatrix4(address, false, ref data); } private void createEBO(out int address, int[] data) { GL.GenBuffers(1, out address); GL.BindBuffer(BufferTarget.ElementArrayBuffer, address); GL.BufferData(BufferTarget.ElementArrayBuffer, (IntPtr)(data.Length * sizeof(int)), data, BufferUsageHint.StaticDraw); } private void createVAO() { timerOpenTK.Stop(); GL.DeleteVertexArray(vao); GL.GenVertexArrays(1, out vao); GL.BindVertexArray(vao); createVBO(out var vboPositions, vertexData, attributeVertexPosition); if (normalMode == 0) { createVBO(out var vboNormals, normal2Data, attributeNormalDirection); } else { if (normalData != null) createVBO(out var vboNormals, normalData, attributeNormalDirection); } createVBO(out var vboColors, colorData, attributeVertexColor); createVBO(out var vboModelMatrix, modelMatrixData, uniformModelMatrix); createVBO(out var vboViewMatrix, viewMatrixData, uniformViewMatrix); createEBO(out var eboElements, indiceData); GL.BindBuffer(BufferTarget.ArrayBuffer, 0); GL.BindVertexArray(0); } protected override void OnLoad(EventArgs e) { base.OnLoad(e); initOpenTK(); } private void glControl1_Paint(object sender, PaintEventArgs e) { glControl1.MakeCurrent(); GL.Clear(ClearBufferMask.ColorBufferBit | ClearBufferMask.DepthBufferBit); GL.Enable(EnableCap.DepthTest); GL.DepthFunc(DepthFunction.Lequal); GL.BindVertexArray(vao); if (wireFrameMode == 0 || wireFrameMode == 2) { GL.UseProgram(shadeMode == 0 ? pgmID : pgmColorID); GL.UniformMatrix4(uniformModelMatrix, false, ref modelMatrixData); GL.UniformMatrix4(uniformViewMatrix, false, ref viewMatrixData); GL.PolygonMode(MaterialFace.FrontAndBack, PolygonMode.Fill); GL.DrawElements(BeginMode.Triangles, indiceData.Length, DrawElementsType.UnsignedInt, 0); } //Wireframe if (wireFrameMode == 1 || wireFrameMode == 2) { GL.Enable(EnableCap.PolygonOffsetLine); GL.PolygonOffset(-1, -1); GL.UseProgram(pgmBlackID); GL.UniformMatrix4(uniformModelMatrix, false, ref modelMatrixData); GL.UniformMatrix4(uniformViewMatrix, false, ref viewMatrixData); GL.PolygonMode(MaterialFace.FrontAndBack, PolygonMode.Line); GL.DrawElements(BeginMode.Triangles, indiceData.Length, DrawElementsType.UnsignedInt, 0); GL.Disable(EnableCap.PolygonOffsetLine); } GL.BindVertexArray(0); GL.Flush(); glControl1.SwapBuffers(); } private void glControl1_MouseWheel(object sender, MouseEventArgs e) { if (glControl1.Visible) { viewMatrixData *= Matrix4.CreateScale(1 + e.Delta / 1000f); glControl1.Invalidate(); } } private void resetForm() { Text = "AssetStudio"; importFiles.Clear(); foreach (var assetsFile in assetsfileList) { assetsFile.reader.Dispose(); } assetsfileList.Clear(); exportableAssets.Clear(); visibleAssets.Clear(); foreach (var resourceFileReader in resourceFileReaders) { resourceFileReader.Value.Dispose(); } resourceFileReaders.Clear(); sharedFileIndex.Clear(); productName = ""; sceneTreeView.Nodes.Clear(); assetListView.VirtualListSize = 0; assetListView.Items.Clear(); classesListView.Items.Clear(); classesListView.Groups.Clear(); previewPanel.BackgroundImage = Properties.Resources.preview; previewPanel.BackgroundImageLayout = ImageLayout.Center; assetInfoLabel.Visible = false; assetInfoLabel.Text = null; textPreviewBox.Visible = false; fontPreviewBox.Visible = false; glControl1.Visible = false; lastSelectedItem = null; lastLoadedAsset = null; firstSortColumn = -1; secondSortColumn = 0; reverseSort = false; enableFiltering = false; listSearch.Text = " Filter "; var count = showTypeToolStripMenuItem.DropDownItems.Count; for (var i = 1; i < count; i++) { showTypeToolStripMenuItem.DropDownItems.RemoveAt(1); } FMODreset(); } private void assetListView_MouseClick(object sender, MouseEventArgs e) { if (e.Button == MouseButtons.Right && assetListView.SelectedIndices.Count > 0) { jumpToSceneHierarchyToolStripMenuItem.Visible = false; showOriginalFileToolStripMenuItem.Visible = false; exportAnimatorwithselectedAnimationClipMenuItem.Visible = false; exportobjectswithselectedAnimationClipMenuItem.Visible = false; if (assetListView.SelectedIndices.Count == 1) { jumpToSceneHierarchyToolStripMenuItem.Visible = true; showOriginalFileToolStripMenuItem.Visible = true; } if (assetListView.SelectedIndices.Count >= 1) { var selectedAssets = GetSelectedAssets(); if (selectedAssets.Any(x => x.Type == ClassIDReference.Animator) && selectedAssets.Any(x => x.Type == ClassIDReference.AnimationClip)) { exportAnimatorwithselectedAnimationClipMenuItem.Visible = true; } else if (selectedAssets.All(x => x.Type == ClassIDReference.AnimationClip)) { exportobjectswithselectedAnimationClipMenuItem.Visible = true; } } contextMenuStrip1.Show(assetListView, e.X, e.Y); } } private void exportSelectedAssetsToolStripMenuItem_Click(object sender, EventArgs e) { var saveFolderDialog1 = new OpenFolderDialog(); if (saveFolderDialog1.ShowDialog(this) == DialogResult.OK) { timer.Stop(); ExportAssets(saveFolderDialog1.Folder, GetSelectedAssets(), assetGroupOptions.SelectedIndex, openAfterExport.Checked); } } private void showOriginalFileToolStripMenuItem_Click(object sender, EventArgs e) { var selectasset = (AssetPreloadData)assetListView.Items[assetListView.SelectedIndices[0]]; var args = $"/select, {selectasset.sourceFile.parentPath ?? selectasset.sourceFile.filePath}"; var pfi = new ProcessStartInfo("explorer.exe", args); Process.Start(pfi); } private void exportAnimatorwithAnimationClipMenuItem_Click(object sender, EventArgs e) { AssetPreloadData animator = null; List<AssetPreloadData> animationList = new List<AssetPreloadData>(); var selectedAssets = GetSelectedAssets(); foreach (var assetPreloadData in selectedAssets) { if (assetPreloadData.Type == ClassIDReference.Animator) { animator = assetPreloadData; } else if (assetPreloadData.Type == ClassIDReference.AnimationClip) { animationList.Add(assetPreloadData); } } if (animator != null) { var saveFolderDialog1 = new OpenFolderDialog(); if (saveFolderDialog1.ShowDialog(this) == DialogResult.OK) { var exportPath = saveFolderDialog1.Folder + "\\Animator\\"; progressBar1.Value = 0; progressBar1.Maximum = 1; ExportAnimatorWithAnimationClip(animator, animationList, exportPath); } } } private void exportSelectedObjectsToolStripMenuItem_Click(object sender, EventArgs e) { if (sceneTreeView.Nodes.Count > 0) { var saveFolderDialog1 = new OpenFolderDialog(); if (saveFolderDialog1.ShowDialog(this) == DialogResult.OK) { var exportPath = saveFolderDialog1.Folder + "\\GameObject\\"; ExportObjectsWithAnimationClip(exportPath, sceneTreeView.Nodes); } } else { StatusStripUpdate("No Objects available for export"); } } private void exportObjectswithAnimationClipMenuItem_Click(object sender, EventArgs e) { if (sceneTreeView.Nodes.Count > 0) { var saveFolderDialog1 = new OpenFolderDialog(); if (saveFolderDialog1.ShowDialog(this) == DialogResult.OK) { var exportPath = saveFolderDialog1.Folder + "\\GameObject\\"; ExportObjectsWithAnimationClip(exportPath, sceneTreeView.Nodes, GetSelectedAssets()); } } else { StatusStripUpdate("No Objects available for export"); } } private void jumpToSceneHierarchyToolStripMenuItem_Click(object sender, EventArgs e) { var selectasset = (AssetPreloadData)assetListView.Items[assetListView.SelectedIndices[0]]; if (selectasset.gameObject != null) { sceneTreeView.SelectedNode = selectasset.gameObject; tabControl1.SelectedTab = tabPage1; } } private void exportAllObjectssplitToolStripMenuItem1_Click(object sender, EventArgs e) { if (sceneTreeView.Nodes.Count > 0) { var saveFolderDialog1 = new OpenFolderDialog(); if (saveFolderDialog1.ShowDialog(this) == DialogResult.OK) { var savePath = saveFolderDialog1.Folder + "\\"; progressBar1.Value = 0; progressBar1.Maximum = sceneTreeView.Nodes.Cast<TreeNode>().Sum(x => x.Nodes.Count); ; ExportSplitObjects(savePath, sceneTreeView.Nodes, true); } } else { StatusStripUpdate("No Objects available for export"); } } private List<AssetPreloadData> GetSelectedAssets() { var selectedAssets = new List<AssetPreloadData>(); foreach (int index in assetListView.SelectedIndices) { selectedAssets.Add((AssetPreloadData)assetListView.Items[index]); } return selectedAssets; } private void FilterAssetList() { assetListView.BeginUpdate(); assetListView.SelectedIndices.Clear(); var show = new List<ClassIDReference>(); if (!allToolStripMenuItem.Checked) { for (var i = 1; i < showTypeToolStripMenuItem.DropDownItems.Count; i++) { var item = (ToolStripMenuItem)showTypeToolStripMenuItem.DropDownItems[i]; if (item.Checked) { show.Add((ClassIDReference)Enum.Parse(typeof(ClassIDReference), item.Text)); } } visibleAssets = exportableAssets.FindAll(x => show.Contains(x.Type)); } else { visibleAssets = exportableAssets; } if (listSearch.Text != " Filter ") { visibleAssets = visibleAssets.FindAll(x => x.Text.IndexOf(listSearch.Text, StringComparison.CurrentCultureIgnoreCase) >= 0); } assetListView.VirtualListSize = visibleAssets.Count; assetListView.EndUpdate(); } } }
41.602242
171
0.471709
[ "MIT" ]
TSelman61/AssetStudio
AssetStudio/AssetStudioForm.cs
77,923
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using APIMonLib; using APIMonShared; using System.Diagnostics; using EasyHook; using CPN; using System.Runtime.Remoting; using AliasProcessCreationFlags = APIMonLib.Hooks.kernel32.dll.Kernel32Support.ProcessCreationFlags; namespace APIMon { class MessageServer { private String ChannelName = null; private static MessageServer _instance = null; public static MessageServer instance { get { if (_instance == null) _instance = new MessageServer(); return _instance; } } private MessageServer() { } /// <summary> /// Returns path to the directory where main module of the program (the file from which process was started) is located /// </summary> /// <returns></returns> public string getMainModuleDirectory() { string main_module_path = Process.GetCurrentProcess().MainModule.FileName; string main_module_name = Process.GetCurrentProcess().MainModule.ModuleName; main_module_path = main_module_path.Replace(main_module_name, ""); return main_module_path; } #region CallBacks for remote hooking /// <summary> /// This method accepts transfer unti and dispatches it through ApiDispatcher /// which transfers it to appropriate places in CPNet /// </summary> /// <param name="tu"></param> private void receiveTransferUnit(TransferUnit tu) { try { ApiDispatcher.dispatchToken(new Token(tu)); } catch (Exception e) { Console.WriteLine(e); } } /// <summary> /// Receives remote text message and prints it immediately /// </summary> /// <param name="message"></param> private void receiveTextMessage(String message) { Console.WriteLine(message); } /// <summary> /// Receives remote exception and prints it /// </summary> /// <param name="ex"></param> private void receiveException(RemoteHookingException ex) { //TODO Do something with remote excpetion. Probably shutdown remote hook Console.WriteLine("------------------------------Remote Exception--------------------------------"); Console.WriteLine(ex); Console.WriteLine("-----------------------End of Remote Exception--------------------------------"); } /// <summary> /// This method is actually designed for remote system. It returns API calls that should be intercepted by remote system /// </summary> /// <returns></returns> private APIFullName[] getListOfInterceptedApiCalls() { return ApiDispatcher.getListOfApiCalls(); } /// <summary> /// This method connects defined here callback functions as delegates to TransferUnitReceiverEvents /// </summary> private void attachCallbacks() { TransferUnitReceiver.instance.addTransferUnitReceiver(new TransferUnitReceiver.ReceiveTransferUnit(receiveTransferUnit)); TransferUnitReceiver.instance.addTextMessageReceiver(new TransferUnitReceiver.ReceiveTextMessage(receiveTextMessage)); TransferUnitReceiver.instance.addExceptionReceiver(new TransferUnitReceiver.ReceiveRemoteHookingException(receiveException)); TransferUnitReceiver.instance.addGetApiCallsToInterceptReceiver(new TransferUnitReceiver.ReceiveGetApiCallsToIntercept(getListOfInterceptedApiCalls)); } public void waitForTheEndOfProcessing() { TransferUnitReceiver.instance.waitForAllTransferUnitsGetProcessed(); } #endregion public void initEnvironment() { //RemoteHooking.ExecuteAsService<Object>("Config.Register", new Object[] { "A FileMon like demo application.", // "FileMon.exe", // "FileMonInject.dll", // "native_class_library.dll" }); Config.Register( "A FileMon like demo application.", "APIMon.exe", "APIMonInject.dll", "AlmostNativeHooks.dll", //"msvcm90d.dll", //"msvcp90d.dll", //"msvcr90d.dll", "APIMonLib.dll" ); attachCallbacks(); RemoteHooking.IpcCreateServer<ChannelReceiverStsukoProxy>(ref ChannelName, WellKnownObjectMode.SingleCall); } /// <summary> /// Must be called before shutting down. /// Closes remote connections. /// </summary> public void closeEnvironment() { TransferUnitReceiver.instance.stopReceiver(); } /// <summary> /// Injects hooking library into started processes. /// </summary> /// <param name="process_names">array of process names to watch w/o .exe extention(e.g. msimn, Test_Files_Handles)</param> /// <param name="as_service">set this parameter to true for injecting from service. Needed for hooking services</param> /// <param name="path_to_library_for_injection">Path to library for injection. Library should be located on local disk. Can be null for as_service=false</param> public void watchProcesses(string[] process_names, bool as_service, string path_to_library_for_injection) { foreach (String process_name in process_names) { foreach (Process p in Process.GetProcessesByName(process_name)) { try { if (as_service) { injectLibraryAsService(p, path_to_library_for_injection); } else { injectLibrary(p); } } catch (Exception e) { Console.WriteLine("\n\nException while processing PID=" + p.Id + " -------------------------------------\n"); Console.WriteLine("-------------------------------------------------------------------------------------\n"); Console.WriteLine(e); } } } } public void injectLibrary(Process p) { MessageFromInjector message = new MessageFromInjector(); message.channel_name = ChannelName; List<int> thread_ids = new List<int>(); foreach (ProcessThread t in p.Threads) { thread_ids.Add(t.Id); } message.thread_ids = thread_ids.ToArray(); RemoteHooking.Inject(p.Id, "APIMonInject.dll", null, message); } public void injectLibrary(Process p, int TID) { MessageFromInjector message = new MessageFromInjector(); message.channel_name = ChannelName; List<int> thread_ids = new List<int>(); foreach (ProcessThread t in p.Threads) { thread_ids.Add(t.Id); } message.thread_ids = thread_ids.ToArray(); RemoteHooking.Inject(p.Id, (Int32)TID, "APIMonInject.dll", null, message); } private void injectLibraryAsService(Process p, string library_location) { MessageFromInjector message = new MessageFromInjector(); message.channel_name = ChannelName; List<int> thread_ids = new List<int>(); foreach (ProcessThread t in p.Threads) { thread_ids.Add(t.Id); } message.thread_ids = thread_ids.ToArray(); Console.WriteLine("Injecting through service"); RemoteHooking.ExecuteAsService<RemoteHooking>("Inject", new Object[] { p.Id, library_location, null, message }); } ///// <summary> ///// Starts process and injects library with redirection of standard input, output and error to handles provided ///// </summary> ///// <param name="what_to_start"></param> ///// <param name="command_line_parameters"></param> ///// <returns>process ID of newly created process</returns> //public Process startProcessAndInject(string what_to_start, string command_line_parameters, IntPtr stdIn, IntPtr stdOut, IntPtr stdErr) //{ // int process_id; // MessageFromInjector message = new MessageFromInjector(); // message.channel_name = ChannelName; // RemoteHooking.CreateAndInjectEx(what_to_start, command_line_parameters, getMainModuleDirectory() + "APIMonInject.dll", null, out process_id, // stdIn, stdOut, stdErr, message); // return System.Diagnostics.Process.GetProcessById(process_id); //} /// <summary> /// Starts process and injects library /// </summary> /// <param name="what_to_start"></param> /// <param name="command_line_parameters"></param> /// <returns>process ID of newly created process</returns> public Process startProcessAndInject(ProgramStartDescription tp) { int process_id; MessageFromInjector message = new MessageFromInjector(); message.channel_name = ChannelName; RemoteHooking.CreateAndInject(tp.image_path, tp.command_line, (int)AliasProcessCreationFlags.CREATE_NEW_CONSOLE, getMainModuleDirectory() + "APIMonInject.dll", null, out process_id, message); return System.Diagnostics.Process.GetProcessById(process_id); //Process notePad = new Process(); //notePad.StartInfo.FileName = tp.image_path; //notePad.StartInfo.Arguments = tp.command_line; //notePad.Start(); //return notePad; } /// <summary> /// Waits for process to exit in time specified otherwise kills it. This method blocks for at most ime specified. /// </summary> /// <param name="p">which process to wait</param> /// <param name="time_in_sec">how much time to wait for process exit</param> /// <returns>true when process exited itself. False when process was killed due to timeout</returns> public bool waitForProcessToEnd(Process p, int time_in_sec) { if (!p.WaitForExit(time_in_sec * 1000)) { killProcess(p); return false; } else { return true; } } //public void setExitHandler(Process p, EventHandler eh){ // p.EnableRaisingEvents = true; // p.Exited+=eh; //} private const int MAX_TRIES_TO_KILL = 5; private void killProcess(Process p) { int tries_to_kill = MAX_TRIES_TO_KILL; bool successful_kill = false; while ((--tries_to_kill >= 0)&&(!p.HasExited)) { try { p.Kill(); successful_kill = true; break; } catch (System.ComponentModel.Win32Exception) { Console.WriteLine("Failed to stop process"); Console.WriteLine("Will retry for " + tries_to_kill + " times."); System.Threading.Thread.Sleep(1000); } catch (Exception) { Console.WriteLine("Looks like process has exited"); break; } } if (p.HasExited) { Console.WriteLine("Process exited"); } else { if (!successful_kill) throw new Exception("Couldn't stop process "); else Console.WriteLine("Process was killed but not exited yet."); } } } }
39.242812
195
0.561345
[ "Apache-2.0" ]
850i/APIMon
APIMon/MessageServer.cs
12,285
C#
namespace Ultrasound { /// <summary> /// Родительский класс от которого наследуются все препятствия в мире. /// </summary> class Obstacle { /// <summary> /// Позиция в мире по X. /// </summary> protected int PosX; /// <summary> /// Отправка информации об самом объекте Environment-у. /// </summary> /// <param name="obstacle">Вид препятствия.</param> /// <param name="x">Позиция по X.</param> public void SignUp(Obstacle obstacle) { Environment environment = Environment.GetInstance(); environment.Initialize(obstacle, obstacle.PosX); } } }
26.461538
74
0.55814
[ "MIT" ]
Rinkton/ultrasound-project
UltrasoundTheProgram/Ultrasound/Obstacle.cs
817
C#
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ /* * Do not modify this file. This file is generated from the rds-2014-10-31.normal.json service model. */ using System; using System.Collections.Generic; using System.Globalization; using System.IO; using System.Net; using System.Text; using System.Xml.Serialization; using Amazon.RDS.Model; using Amazon.Runtime; using Amazon.Runtime.Internal; using Amazon.Runtime.Internal.Transform; using Amazon.Runtime.Internal.Util; namespace Amazon.RDS.Model.Internal.MarshallTransformations { /// <summary> /// Response Unmarshaller for DeleteDBSecurityGroup operation /// </summary> public class DeleteDBSecurityGroupResponseUnmarshaller : XmlResponseUnmarshaller { /// <summary> /// Unmarshaller the response from the service to the response class. /// </summary> /// <param name="context"></param> /// <returns></returns> public override AmazonWebServiceResponse Unmarshall(XmlUnmarshallerContext context) { DeleteDBSecurityGroupResponse response = new DeleteDBSecurityGroupResponse(); context.Read(); int targetDepth = context.CurrentDepth; while (context.ReadAtDepth(targetDepth)) { if (context.IsStartElement) { if(context.TestExpression("DeleteDBSecurityGroupResult", 2)) { UnmarshallResult(context, response); continue; } if (context.TestExpression("ResponseMetadata", 2)) { response.ResponseMetadata = ResponseMetadataUnmarshaller.Instance.Unmarshall(context); } } } return response; } [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA1801:ReviewUnusedParameters", MessageId="response")] private static void UnmarshallResult(XmlUnmarshallerContext context, DeleteDBSecurityGroupResponse response) { int originalDepth = context.CurrentDepth; int targetDepth = originalDepth + 1; if (context.IsStartOfDocument) targetDepth += 2; while (context.ReadAtDepth(originalDepth)) { if (context.IsStartElement || context.IsAttribute) { } } return; } /// <summary> /// Unmarshaller error response to exception. /// </summary> /// <param name="context"></param> /// <param name="innerException"></param> /// <param name="statusCode"></param> /// <returns></returns> public override AmazonServiceException UnmarshallException(XmlUnmarshallerContext context, Exception innerException, HttpStatusCode statusCode) { ErrorResponse errorResponse = ErrorResponseUnmarshaller.GetInstance().Unmarshall(context); errorResponse.InnerException = innerException; errorResponse.StatusCode = statusCode; var responseBodyBytes = context.GetResponseBodyBytes(); using (var streamCopy = new MemoryStream(responseBodyBytes)) using (var contextCopy = new XmlUnmarshallerContext(streamCopy, false, null)) { if (errorResponse.Code != null && errorResponse.Code.Equals("DBSecurityGroupNotFound")) { return DBSecurityGroupNotFoundExceptionUnmarshaller.Instance.Unmarshall(contextCopy, errorResponse); } if (errorResponse.Code != null && errorResponse.Code.Equals("InvalidDBSecurityGroupState")) { return InvalidDBSecurityGroupStateExceptionUnmarshaller.Instance.Unmarshall(contextCopy, errorResponse); } } return new AmazonRDSException(errorResponse.Message, innerException, errorResponse.Type, errorResponse.Code, errorResponse.RequestId, statusCode); } private static DeleteDBSecurityGroupResponseUnmarshaller _instance = new DeleteDBSecurityGroupResponseUnmarshaller(); internal static DeleteDBSecurityGroupResponseUnmarshaller GetInstance() { return _instance; } /// <summary> /// Gets the singleton. /// </summary> public static DeleteDBSecurityGroupResponseUnmarshaller Instance { get { return _instance; } } } }
37.7
158
0.615574
[ "Apache-2.0" ]
ChristopherButtars/aws-sdk-net
sdk/src/Services/RDS/Generated/Model/Internal/MarshallTransformations/DeleteDBSecurityGroupResponseUnmarshaller.cs
5,278
C#
using System.Collections; using System.Collections.Generic; using UnityEngine; using System; using System.Linq; using UnityEngine.Networking; using Object = UnityEngine.Object; using System.Text; using System.Text.RegularExpressions; namespace Mobcast.Coffee.AssetSystem { #if UNITY_EDITOR public class EditorOption : UnityEditor.ScriptableSingleton<EditorOption> { public enum Mode { None, Simulation, LocalServer, StreamingAssets, } public Mode mode = Mode.Simulation; public int localServerProcessId = 0; } #endif public class AssetManager : MonoSingleton<AssetManager> { public const string kLog = "[AssetManager] "; #if UNITY_STANDALONE_OSX public const string Platform = "OSX"; #elif UNITY_STANDALONE_WIN public const string Platform = "Windows"; #elif UNITY_ANDROID public const string Platform = "Android"; #elif UNITY_IOS || UNITY_IPHONE public const string Platform = "iOS"; #elif UNITY_WEBGL public const string Platform = "WebGL"; #else public const string Platform = "Unknown"; #endif /// <summary> /// AssetBundleManifest object which can be used to load the dependecies /// and check suitable assetBundle variants. /// </summary> public static AssetBundleManifest manifest { set; get; } /// <summary> /// The base downloading url which is used to generate the full /// downloading url with the assetBundle names. /// </summary> public static string patchServerURL { get; set; } public static bool ready { get; protected set; } static bool patchRestored { get; set; } public static Patch patch { get; private set; } public Patch storedPatch { get { return JsonUtility.FromJson<Patch>(PlayerPrefs.GetString("AssetManager_StoredPatch", "{}")); } set { PlayerPrefs.SetString("AssetManager_StoredPatch", JsonUtility.ToJson(value)); } } public static Dictionary<string, AssetBundle> m_LoadedAssetBundles = new Dictionary<string, AssetBundle>(); public static List<AssetOperation> m_InProgressOperations = new List<AssetOperation>(); public static Dictionary<string, UnityEngine.Object> m_RuntimeCache = new Dictionary<string, UnityEngine.Object>(); public static Dictionary<string, HashSet<string>> m_Depended = new Dictionary<string, HashSet<string>>(); static readonly HashSet<string> m_Unloadable = new HashSet<string>(); public static StringBuilder errorLog = new StringBuilder(); public static PatchHistory history = new PatchHistory(); public static readonly Hash128 MAX_HASH = new Hash128(uint.MaxValue, uint.MaxValue, uint.MaxValue, uint.MaxValue); #if UNITY_EDITOR public static bool isLocalServerMode { get { return EditorOption.instance.mode == EditorOption.Mode.LocalServer; } } public static bool isSimulationMode { get { return EditorOption.instance.mode == EditorOption.Mode.Simulation; } } public static bool isStreamingAssetsMode { get { return EditorOption.instance.mode == EditorOption.Mode.StreamingAssets; } } #else public static bool isLocalServerMode { get { return false; } } public static bool isSimulationMode { get { return false; } } public static bool isStreamingAssetsMode { get; set; } #endif #if UNITY_ANDROID && !UNITY_EDITOR public static string streamingAssetsAssetBundlePath { get{ return System.IO.Path.Combine(Application.streamingAssetsPath, "AssetBundles/"); } } #else public static string streamingAssetsAssetBundlePath { get { return "file://" + System.IO.Path.Combine(Application.streamingAssetsPath, "AssetBundles/"); } } #endif static string Dump(IEnumerable<string> self, string sep = ", ") { int sepLength = sep.Length; return !self.Any() ? "" : self.Aggregate(new StringBuilder(), (a, b) => a.Append(b + sep), x => x.Remove(x.Length - sepLength, sepLength).ToString()); } public override string ToString() { var assetbundleNames = AssetManager.manifest ? AssetManager.manifest.GetAllAssetBundles() : new string[0]; var downloadedCount = AssetManager.manifest ? assetbundleNames.Count(x => Caching.IsVersionCached(x, AssetManager.manifest.GetAssetBundleHash(x))) : 0; var depend = Dump(m_Depended.Select(x => x.Key + " = " + Dump(x.Value)), "\n"); return string.Format("{0}\nパッチサーバーURL : {6}\n現在のパッチ : {7}\nディスク使用量 : {1}\nランタイムキャッシュ : {2}\nロード済みアセットバンドル : {3}\nダウンロード済みアセットバンドル{4}/{5}\nアセットバンドル依存関係{8}", kLog, Caching.spaceOccupied, AssetManager.m_RuntimeCache.Count, AssetManager.m_LoadedAssetBundles.Count, downloadedCount, assetbundleNames.Length, patchServerURL, patch, depend ); } protected virtual IEnumerator Start() { Application.logMessageReceived += (condition, stackTrace, type) => { if (type != LogType.Log && type != LogType.Warning && condition.StartsWith(kLog)) errorLog.AppendLine(condition); }; ready = false; yield return new WaitUntil(() => Caching.ready); // パッチリストア. 最後に利用したパッチのマニフェストファイルがダウンロード済みであれば、そのパッチ(=マニフェスト)を復元. // Is the last used patch cached? patchRestored = false; patch = storedPatch; if (Caching.IsVersionCached(Platform, Hash128.Parse(patch.commitHash))) { Debug.LogFormat("{0}最後に利用したパッチ [{1}] を復元します.", kLog, patch); yield return StartCoroutine(SetPatch(patch)); Debug.LogFormat("{0}パッチ [{1}] を復元しました", kLog, patch); } else { Debug.LogWarningFormat("{0}マニフェストがキャッシュにありません.\n最後に利用したパッチ [{1}] は復元されず、アセットバンドルキャッシュはクリアされます.", kLog, patch); ClearCachedAssetBundleAll(); } patchRestored = true; if (isStreamingAssetsMode) { patchServerURL = streamingAssetsAssetBundlePath; Debug.LogWarningFormat("{0}StreamingAssetsモードに設定します\n{1}", kLog, patchServerURL); yield return SetPatch(new Patch() { comment = "StreamingAssetsMode", commitHash = MAX_HASH.ToString() }); } #if UNITY_EDITOR else if (isSimulationMode) { patchServerURL = "SimulationMode/"; Debug.LogWarningFormat("{0}シミュレーションモードに設定します", kLog); } else if (isLocalServerMode) { patchServerURL = "http://localhost:7888/"; Debug.LogWarningFormat("{0}ローカルサーバーモードに設定します\n{1}", kLog, patchServerURL); yield return SetPatch(new Patch() { comment = "LocalServerMode", commitHash = MAX_HASH.ToString() }); } #endif ready = true; Debug.LogFormat("{0}準備完了", kLog); yield break; } /// <summary> /// Sets base downloading URL to a web URL. The directory pointed to by this URL /// on the web-server should have the same structure as the AssetBundles directory /// in the demo project root. /// </summary> public static void SetPatchServerURL(string url) { if (!url.EndsWith("/")) url += "/"; patchServerURL = url; Debug.LogFormat("{0}パッチサーバーURLを設定しました : {1}", kLog, patchServerURL); } void Update() { // 実行中のオペレーションを全て更新処理する. // Update all in progress operations for (int i = 0; i < m_InProgressOperations.Count;) { var operation = m_InProgressOperations[i]; if (operation.deferred && i == 0) { Debug.LogFormat("{0}オペレーション遅延解除 : {1}", kLog, operation.id); operation.deferred = false; } if (operation.deferred || operation.Update()) { i++; } else { // オペレーション完了. 終了コールバックを実行. // The operation is completed. m_InProgressOperations.RemoveAt(i); operation.OnComplete(); if (!string.IsNullOrEmpty(operation.error)) { errorLog.AppendLine(operation.error); } } } //アンロード可能なアセットバンドルをアンロード // Unload unused asset bundles. if (0 < m_Unloadable.Count) { var array = m_Unloadable.ToArray(); m_Unloadable.Clear(); foreach (var assetBundleName in array) UnloadAssetBundleInternal(assetBundleName); } } public static bool TryGetBundle(string name, out AssetBundle bundle) { bundle = null; // 依存しているアセットバンドルを全てロード済みか. // TODO: cache dependancy! // Loaded all dependancy. if (!manifest || manifest.GetAllDependencies(name).All(m_LoadedAssetBundles.ContainsKey)) { // 自分自身をロード済みか. // Loaded itself. return m_LoadedAssetBundles.TryGetValue(name, out bundle); } return false; } /// <summary> /// Preloads the asset bundle. /// </summary> /// <returns>The asset bundle.</returns> public static BundlePreLoadOperation PreDownload(Func<string, bool> predicate, Action onComplete) { #if UNITY_EDITOR if (isSimulationMode) { Debug.LogErrorFormat("{0}事前ダウンロード スキップ : シミュレーションモード中は無視されます", kLog); var dummyOperation = new BundlePreLoadOperation(m_InProgressOperations.OfType<BundleLoadOperation>().ToList()); m_InProgressOperations.Add(dummyOperation); return dummyOperation; } #endif if (!manifest) { Debug.LogErrorFormat("{0}事前ダウンロード 失敗 : マニフェストがロードされていません", kLog); return null; } IEnumerable<string> bundleNames = predicate != null ? manifest.GetAllAssetBundles().Where(predicate) : manifest.GetAllAssetBundles(); foreach (var name in bundleNames) { var hash = manifest.GetAssetBundleHash(name); bool cached = Caching.IsVersionCached(name, hash); if (!cached) { LoadAssetBundle(name, false); } } var list = m_InProgressOperations.OfType<BundleLoadOperation>().ToList(); var operation = new BundlePreLoadOperation(list); Debug.LogFormat("{0}事前ダウンロード 開始 : {1}件", kLog, list.Count); if (onComplete != null) operation.onComplete += onComplete; m_InProgressOperations.Add(operation); return operation; } /// <summary> /// Preloads the asset bundle. /// </summary> /// <returns>The asset bundle.</returns> public static BundlePreLoadOperation PreDownload() { return PreDownload(null, null); } // Starts the download of the asset bundle identified by the given name, and asset bundles // that this asset bundle depends on. static public BundleLoadOperation LoadAssetBundle(string assetBundleName) { return LoadAssetBundle(assetBundleName, false); } // Starts the download of the asset bundle identified by the given name, and asset bundles // that this asset bundle depends on. static protected BundleLoadOperation LoadAssetBundle(string assetBundleName, bool isLoadingAssetBundleManifest) { string operationId = BundleLoadOperation.GetId(assetBundleName); #if UNITY_EDITOR if (isSimulationMode && !isLoadingAssetBundleManifest) { return new BundleLoadOperation(assetBundleName); } #endif // Already loaded. AssetBundle bundle = null; m_LoadedAssetBundles.TryGetValue(assetBundleName, out bundle); if (bundle != null) { Debug.LogFormat("{0}アセットバンドルロード 成功:{1} はロード済みです.", kLog, assetBundleName); return new BundleLoadOperation(assetBundleName); } m_LoadedAssetBundles.Remove(assetBundleName); // Search same operation in progress to merge load complete callbacks. // Check if the assetBundle has already been processed. BundleLoadOperation op; foreach (var progressOperation in m_InProgressOperations) { op = progressOperation as BundleLoadOperation; if (op != null && op.id == operationId) { return op; } } if (!isLoadingAssetBundleManifest) { if (!manifest) { Debug.LogErrorFormat("{0}アセットバンドルロード 失敗 : マニフェストがロードされていません", kLog); return null; } foreach (var dependency in manifest.GetAllDependencies(assetBundleName)) { AddDepend(dependency, assetBundleName); LoadAssetBundle(dependency, false); } } Debug.LogFormat("{0}アセットバンドルロード バンドルロードオペレーション {1} を作成", kLog, assetBundleName); op = new BundleLoadOperation(assetBundleName, () => GetAssetBundleRequest(assetBundleName, isLoadingAssetBundleManifest)); op.deferred = isLoadingAssetBundleManifest; m_InProgressOperations.Add(op); return op; } protected static UnityWebRequest GetAssetBundleRequest(string assetBundleName, bool isLoadingAssetBundleManifest) { string url; if (string.IsNullOrEmpty(patchServerURL)) { url = "file://" + Platform + "/" + assetBundleName; } else if (string.IsNullOrEmpty(patch.commitHash) || isLocalServerMode || isStreamingAssetsMode) { url = patchServerURL + Platform + "/" + assetBundleName; } else { url = patchServerURL + patch.commitHash + "/" + Platform + "/" + assetBundleName; } Hash128 hash = isLoadingAssetBundleManifest ? Hash128.Parse(patch.commitHash) : manifest.GetAssetBundleHash(assetBundleName); bool forceDownload = (!hash.isValid || hash == MAX_HASH) && patchRestored; Debug.LogFormat("{0}アセットバンドル {1} のロードリクエスト生成(Hash:{2}, DL済み:{3}, 強制DL:{4})\n{5}" , kLog , assetBundleName , hash.ToString().Substring(0, 4) , Caching.IsVersionCached(assetBundleName, hash) , forceDownload , url ); // パッチリストア済みかつハッシュ値が0または最大の場合、キャッシュからロードされず、常にダウンロードされます. // If the hash value is 0, the manifest will be not loaded from the cache and will be always downloaded. return forceDownload ? UnityWebRequest.GetAssetBundle(url) : UnityWebRequest.GetAssetBundle(url, hash, 0); } /// <summary> /// アンロードする /// </summary> /// <param name="assetBundleName">Asset bundle name.</param> static protected void UnloadAssetBundleInternal(string assetBundleName, bool checkDependancy = true) { if (checkDependancy && manifest) { foreach (var dependency in manifest.GetAllDependencies(assetBundleName)) { SubDepend(dependency, assetBundleName); } } m_Depended.Remove(assetBundleName); AssetBundle bundle; m_LoadedAssetBundles.TryGetValue(assetBundleName, out bundle); m_LoadedAssetBundles.Remove(assetBundleName); if (bundle) { bundle.Unload(!checkDependancy); Debug.LogFormat("{0}アセットバンドルのアンロード 成功 : {1}", kLog, assetBundleName); } } static Regex s_RegAb = new Regex("^ab://(.*)/(.*)$"); /// <summary> /// Starts a load operation for an asset from Resources. /// </summary> static public AssetLoadOperation LoadAssetAsync<T>(string assetName, System.Action<T> onLoad = null) where T : UnityEngine.Object { if (assetName.StartsWith("ab://")) { var match = s_RegAb.Match(assetName); return LoadAssetAsync(match.Groups[1].Value, match.Groups[2].Value, typeof(T), obj => onLoad(obj as T)); } return onLoad != null ? LoadAssetAsync("", assetName, typeof(T), obj => onLoad(obj as T)) : LoadAssetAsync("", assetName, typeof(T)); } /// <summary> /// Starts a load operation for an asset from Resources. /// </summary> static public AssetLoadOperation LoadAssetAsync(string assetName, System.Type type, System.Action<UnityEngine.Object> onLoad = null) { if (assetName.StartsWith("ab://")) { var match = s_RegAb.Match(assetName); return LoadAssetAsync(match.Groups[1].Value, match.Groups[2].Value, type, onLoad); } return onLoad != null ? LoadAssetAsync("", assetName, type, onLoad) : LoadAssetAsync("", assetName, type); } /// <summary> /// Starts a load operation for an asset from the given asset bundle. /// </summary> static public AssetLoadOperation LoadAssetAsync<T>(string assetBundleName, string assetName, System.Action<T> onLoad = null) where T : UnityEngine.Object { return onLoad != null ? LoadAssetAsync(assetBundleName, assetName, typeof(T), obj => onLoad(obj as T)) : LoadAssetAsync(assetBundleName, assetName, typeof(T)); } /// <summary> /// Starts a load operation for an asset from the given asset bundle. /// </summary> static public AssetLoadOperation LoadAssetAsync(string assetBundleName, string assetName, System.Type type, System.Action<UnityEngine.Object> onLoad = null) { if (type != typeof(AssetBundleManifest)) { assetBundleName = assetBundleName.ToLower(); } string operationId = AssetLoadOperation.GetId(assetBundleName, assetName, type); // Operation has not been cached. Need load the assetbundle. bool hasRuntimeCache = m_RuntimeCache.ContainsKey(operationId) && m_RuntimeCache[operationId]; if (!string.IsNullOrEmpty(assetBundleName) && !hasRuntimeCache) LoadAssetBundle(assetBundleName, type == typeof(AssetBundleManifest)); // Search same operation in progress to merge load complete callbacks. AssetLoadOperation operation = null; foreach (var progressOperation in m_InProgressOperations) { var op = progressOperation as AssetLoadOperation; if (op != null && op.id == operationId) { operation = op; break; } } // When no same operation in progress, create new operation. if (operation == null) { operation = new AssetLoadOperation(assetBundleName, assetName, type); operation.onComplete += () => { var obj = operation.GetAsset<Object>(); if (obj && instance.ValidRuntimeCache(operationId, type)) { Debug.LogFormat("{0}ランタイムキャッシュに追加\n{1}", kLog, operationId); AssetManager.m_RuntimeCache[operationId] = obj; } else { Debug.LogWarningFormat("{0}ランタイムキャッシュから除外\n{1}", kLog, operationId); } }; m_InProgressOperations.Add(operation); } // Add load complete callback. if (onLoad != null) { operation.onComplete += () => { var obj = operation.GetAsset<Object>(); Debug.LogFormat("{0}ロード完了(成功:{2})\n{1}", kLog, operationId, obj != null); onLoad(obj); }; } return operation; } /// <summary> /// Update manifest. /// Compare manifests and delete old cached bundles. /// Starts download of manifest asset bundle. /// Returns the manifest asset bundle downolad operation object. /// </summary> /// <param name="newManifest">Asset bundle manifest.</param> static void SetManifest(AssetBundleManifest newManifest) { if (!newManifest) { Debug.LogErrorFormat("{0}マニフェスト更新 失敗 : {1}", kLog, patch); return; } var oldManifest = AssetManager.manifest; AssetManager.manifest = newManifest; if (oldManifest) { var oldBundles = new HashSet<string>(oldManifest.GetAllAssetBundles()); var newBundles = new HashSet<string>(newManifest.GetAllAssetBundles()); // 新規 var sb = new StringBuilder(); var array = newBundles.Except(oldBundles).ToArray(); sb.AppendFormat("[Added] {0}\n", array.Length); foreach (var bundleName in array) sb.AppendFormat(" > {0} ({1})\n", bundleName, newManifest.GetAssetBundleHash(bundleName).ToString().Substring(0, 4)); // 削除 array = oldBundles.Except(newBundles).ToArray(); sb.AppendFormat("\n[Deleted : キャッシュは削除されます] {0}\n", array.Length); foreach (var bundleName in array) sb.AppendFormat(" > {0} ({1})\n", bundleName, oldManifest.GetAssetBundleHash(bundleName).ToString().Substring(0, 4)); // 更新 array = oldBundles .Intersect(newBundles) .Select(name => new { name = name, oldHash = oldManifest.GetAssetBundleHash(name), newHash = newManifest.GetAssetBundleHash(name), }) .Where(x => x.oldHash != x.newHash) .Select(x => string.Format("{0} ({1} -> {2})", x.name, x.oldHash.ToString().Substring(0, 4), x.newHash.ToString().Substring(0, 4))) .ToArray(); sb.AppendFormat("\n[Updated : 古いキャッシュは削除されます] {0}\n", array.Length); foreach (var bundleName in array) sb.AppendLine(" > " + bundleName); #if UNITY_2017_1_OR_NEWER // 削除 foreach (var name in oldBundles.Except(newBundles)) { UnloadAssetBundleInternal(name); Caching.ClearAllCachedVersions(name); Debug.LogFormat("{0}キャッシュ削除 : {1}", kLog, name); } // 更新 foreach (var name in newBundles) { UnloadAssetBundleInternal(name); Caching.ClearOtherCachedVersions(name, newManifest.GetAssetBundleHash(name)); Debug.LogFormat("{0}キャッシュ削除 : {1}", kLog, name); } #else foreach (var name in oldBundles.Where(newBundles.Contains)) { var oldHash = oldManifest.GetAssetBundleHash(name); var newHash = newManifest.GetAssetBundleHash(name); // The bundle has removed or changed. Need to delete cached bundle. if (oldHash != newHash) { UnloadAssetBundleInternal(name); if (Caching.IsVersionCached(name, oldHash)) { Debug.LogFormat("{0}キャッシュ削除 : {1}({2})", kLog, name, oldHash.ToString().Substring(0, 4)); var request = UnityWebRequest.GetAssetBundle(name, oldHash, uint.MaxValue); request.Send(); request.Abort(); } } } #endif Debug.LogFormat("{0}マニフェスト更新 完了 : {2}\n変更は以下の通りです:\n{1}", kLog, sb, patch); } else { var newBundles = newManifest.GetAllAssetBundles(); // 新規 var sb = new StringBuilder(); sb.AppendFormat("[Added] {0}\n", newBundles.Length); foreach (var bundleName in newBundles) sb.AppendFormat(" > {0} ({1})\n", bundleName, newManifest.GetAssetBundleHash(bundleName).ToString().Substring(0, 4)); Debug.LogFormat("{0}マニフェスト更新 完了 : {2}\n変更は以下の通りです:\n{1}", kLog, sb, patch); } instance.storedPatch = patch; } /// <summary> /// Starts download of manifest asset bundle. /// Returns the manifest asset bundle downolad operation object. /// </summary> /// <param name="hash">Hash for manifest.</param> /// <param name="onComplete">callback.</param> static public AssetLoadOperation SetPatch(Patch patchHash) { patch = patchHash; return SetPatch(); } /// <summary> /// Starts download of manifest asset bundle. /// Returns the manifest asset bundle downolad operation object. /// </summary> /// <param name="hash">Hash for manifest.</param> /// <param name="onComplete">callback.</param> static public AssetLoadOperation SetPatch() { Debug.LogFormat("{0}パッチを更新します : {1}", kLog, patch); ClearRuntimeCacheAll(); ClearOperationsAll(); UnloadAssetbundlesAll(); #if UNITY_EDITOR if (isSimulationMode && ready) return null; #endif return LoadAssetAsync<AssetBundleManifest>(Platform, "assetbundlemanifest", SetManifest); } static public AssetLoadOperation SetPatchLatest(string url) { if (isStreamingAssetsMode || isSimulationMode || isLocalServerMode) { Debug.LogWarningFormat("{0}現在のモードでは、最新パッチが存在しません", kLog); return null; } Debug.LogFormat("{0}最新のパッチに更新します : {1}", kLog, patch); ClearRuntimeCacheAll(); ClearOperationsAll(); UnloadAssetbundlesAll(); #if UNITY_EDITOR if (isSimulationMode && ready) return null; #endif UpdatePatchList(url, his => patch = his.latestPatch); return LoadAssetAsync<AssetBundleManifest>(Platform, "assetbundlemanifest", SetManifest); } static public AssetLoadOperation UpdatePatchList(string url, Action<PatchHistory> onComplete = null) { if (isStreamingAssetsMode || isSimulationMode || isLocalServerMode) { Debug.LogWarningFormat("{0}現在のモードでは、パッチリストが存在しません", kLog); return null; } Debug.LogFormat("{0}パッチリストの更新 開始 : {1}", kLog, url); return LoadAssetAsync<PlainObject>(url, txt => { history = new PatchHistory(); try { JsonUtility.FromJsonOverwrite(txt ? txt.text : "{}", history); } catch (Exception e) { Debug.LogException(e); Debug.LogErrorFormat("{0}パッチリストの更新 失敗 : {1}", kLog, e.Message); } if (onComplete != null) { onComplete(history); } Debug.LogFormat("{0}パッチリストの更新 完了(最新パッチ:{1})", kLog, history.latestPatch); }); } /// <summary> /// Delete all cached asset bundle. /// </summary> static public void ClearCachedAssetBundleAll() { Debug.LogFormat("{0}アセットバンドルキャッシュをすべて削除", kLog); #if UNITY_2017_1_OR_NEWER Caching.ClearCache(); #else Caching.CleanCache(); #endif if (!manifest) return; foreach (var bundleName in manifest.GetAllAssetBundles()) { var hash = manifest.GetAssetBundleHash(bundleName); UnloadAssetBundleInternal(bundleName); if (Caching.IsVersionCached(bundleName, hash)) { Debug.LogFormat("{0}キャッシュ削除 : {1}({2})", kLog, bundleName, hash.ToString().Substring(0, 4)); #if UNITY_2017_1_OR_NEWER Caching.ClearAllCachedVersions(bundleName); #else var request = UnityWebRequest.GetAssetBundle(bundleName, hash, uint.MaxValue); request.Send(); request.Abort(); #endif } } } /// <summary> /// Unloads the assetbundle all. /// </summary> static void UnloadAssetbundlesAll() { foreach (var assetBundleName in new List<string>(m_LoadedAssetBundles.Keys)) UnloadAssetBundleInternal(assetBundleName, false); m_LoadedAssetBundles.Clear(); m_Depended.Clear(); } /// <summary> /// Clears the runtime cache. /// </summary> public static void ClearRuntimeCacheAll() { Debug.LogFormat("{0}ランタイムキャッシュを削除 : {1}件", kLog, m_RuntimeCache.Count); m_RuntimeCache.Clear(); } /// <summary> /// Clears the runtime cache. /// </summary> public static void ClearRuntimeCacheAll(Predicate<string> predicate) { ClearRuntimeCacheAll(m_RuntimeCache.Where(x => predicate(x.Key)).Select(x => x.Key).ToArray()); } /// <summary> /// Clears the runtime cache. /// </summary> public static void ClearRuntimeCacheAll(Predicate<Object> predicate) { ClearRuntimeCacheAll(m_RuntimeCache.Where(x => predicate(x.Value)).Select(x => x.Key).ToArray()); } /// <summary> /// Clears the runtime cache. /// </summary> public static void ClearRuntimeCacheAll(IEnumerable<string> ids) { Debug.LogFormat("{0}ランタイムキャッシュを削除 : {1}件", kLog, ids.Count()); foreach (var id in ids) { m_RuntimeCache.Remove(id); } } /// <summary> /// Clears the operations. /// </summary> static void ClearOperationsAll() { m_InProgressOperations.ForEach(op => op.OnCancel()); m_InProgressOperations.Clear(); } /// <summary> /// Clear all. /// </summary> public static void ClearAll() { errorLog.Length = 0; ClearRuntimeCacheAll(); ClearOperationsAll(); UnloadAssetbundlesAll(); ClearCachedAssetBundleAll(); Resources.UnloadUnusedAssets(); } public static void AddDepend(string assetBundleName, string dependedId) { if (string.IsNullOrEmpty(assetBundleName)) return; Debug.LogFormat("{0} アセットバンドル依存関係の追加\n{1} <- {2}", kLog, assetBundleName, dependedId); HashSet<string> depended; if (!m_Depended.TryGetValue(assetBundleName, out depended)) { if (string.IsNullOrEmpty(dependedId)) { m_Unloadable.Add(assetBundleName); return; } depended = new HashSet<string>(); m_Depended.Add(assetBundleName, depended); } if (!string.IsNullOrEmpty(dependedId)) depended.Add(dependedId); UpdateDepend(assetBundleName, depended); } public static void SubDepend(string assetBundleName, string dependedId) { if (string.IsNullOrEmpty(assetBundleName)) return; Debug.LogFormat("{0} アセットバンドル依存関係の解除\n{1} <- {2}", kLog, assetBundleName, dependedId); HashSet<string> depended; if (m_Depended.TryGetValue(assetBundleName, out depended)) { if (!string.IsNullOrEmpty(dependedId)) depended.Remove(dependedId); } UpdateDepend(assetBundleName, depended); } static void UpdateDepend(string assetBundleName, HashSet<string> depended) { if (depended != null && 0 < depended.Count) { // Debug.LogFormat("{0} 依存関係の更新: 依存関係があるため、 {1} はアンロードできません. {2}", kLog, assetBundleName, Dump(depended)); m_Unloadable.Remove(assetBundleName); } else if (instance.ValidBundleKeepLoaded(assetBundleName)) { // Debug.LogFormat("{0} 依存関係の更新: ValidBundleKeepLoaded により、 {1} はアンロードできません.", kLog, assetBundleName); m_Unloadable.Remove(assetBundleName); } else { Debug.LogFormat("{0} アセットバンドル依存関係の更新\n{1} のアンロードを許可します. 次のUpdate時にアンロードされます.", kLog, assetBundleName); m_Unloadable.Add(assetBundleName); m_Depended.Remove(assetBundleName); } } /// <summary> /// オブジェクトをランタイムキャッシュに含めるかどうかを判定します. /// このメソッドがtrueを返す時のみ、オブジェクトはランタイムキャッシュされます. /// 引数idはオブジェクトアドレスです. /// Resourcesからロードした場合: resources://<アセット名> /// アセットバンドルからロードした場合: ab://<アセットバンドル名>/<アセット名> /// webからロードした場合: https://リソースアドレス /// </summary> protected virtual bool ValidRuntimeCache(string id, Type type) { return type != typeof(AssetBundleManifest) && type != typeof(PlainObject); } /// <summary> /// アセットバンドルをオンメモリ上にキープし続けるかどうかを判定します. /// </summary> /// <param name="bundleName">Bundle name.</param> protected virtual bool ValidBundleKeepLoaded(string bundleName) { return bundleName.StartsWith("shared_"); } public static SceneLoadOperation LoadSceneAsync(string assetBundleName, string levelName, bool isAdditive, Action onComplete = null) { string operationId = SceneLoadOperation.GetId(assetBundleName, levelName); // Search same operation in progress to merge load complete callbacks. SceneLoadOperation operation = null; foreach (var progressOperation in m_InProgressOperations) { var op = progressOperation as SceneLoadOperation; if (op != null && op.id == operationId) { operation = op; break; } } // When no same operation in progress, create new operation. if (operation == null) { operation = new SceneLoadOperation(assetBundleName, levelName, isAdditive); operation.onComplete += () => Debug.LogFormat("{0}シーンロード完了: {1}", kLog, operationId); m_InProgressOperations.Add(operation); } // Add load complete callback. if (onComplete != null) { operation.onComplete += onComplete; } return operation; } } }
30.948312
217
0.691673
[ "MIT" ]
mob-sakai/AssetSystem
Assets/Mobcast/Coffee/AssetSystem/AssetManager.cs
31,823
C#
using FluentValidation; using Nop.Core.Domain.Topics; using Nop.Data; using Nop.Services.Localization; using Nop.Web.Areas.Admin.Models.Templates; using Nop.Web.Framework.Validators; namespace Nop.Web.Areas.Admin.Validators.Templates { public partial class TopicTemplateValidator : BaseNopValidator<TopicTemplateModel> { public TopicTemplateValidator(ILocalizationService localizationService, INopDataProvider dataProvider) { RuleFor(x => x.Name).NotEmpty().WithMessageAwait(localizationService.GetResourceAsync("Admin.System.Templates.Topic.Name.Required")); RuleFor(x => x.ViewPath).NotEmpty().WithMessageAwait(localizationService.GetResourceAsync("Admin.System.Templates.Topic.ViewPath.Required")); SetDatabaseValidationRules<TopicTemplate>(dataProvider); } } }
41.95
153
0.764005
[ "CC0-1.0" ]
peterthomet/BioPuur
nopCommerce 4.4/src/Presentation/Nop.Web/Areas/Admin/Validators/Templates/TopicTemplateValidator.cs
841
C#
/* ======================================================================= Copyright 2017 Technische Universitaet Darmstadt, Fachgebiet fuer Stroemungsdynamik (chair of fluid dynamics) Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ using System; using System.Collections.Generic; using System.Text; using System.Runtime.InteropServices; using System.IO; using System.Reflection; using ilPSP.Utils; using ilPSP.Tracing; using System.Linq; namespace ilPSP.LinSolvers.monkey.CUDA { /// <summary> /// a monkey device that uses CUDA /// </summary> /// <remarks> /// All objects /// (matrices: <see cref="CudaMatrix"/> and derivatives, vectors: <see cref="CudaVector"/>) are created within /// this CUDA context, and therefore, (methods of these objects) must be called from the same thread. <br/> /// Using multiple <see cref="CudaDevice"/>-objects in one thread is neither tested nor supported. /// </remarks> public class CudaDevice : Device { private CudaEnviroment m_Env; /// <summary> /// CUDA Environment (use which GPU on which MPI process, ...); /// </summary> public CudaEnviroment Env { get { return m_Env; } } /// <summary> /// ctor /// </summary> /// <param name="cuEnv">Distribution of processes and CUDA devices</param> public CudaDevice(CudaEnviroment cuEnv) { m_Env = cuEnv; } /// <summary> /// /// </summary> public override VectorBase CreateVector(IPartitioning p) { if (p.IsMutable) throw new NotSupportedException(); return new CudaVector(p,m_Env); } /// <summary> /// see <see cref="Device.CreateMatrix(MsrMatrix,MatrixType)"/>; /// </summary> public override MatrixBase CreateMatrix(MsrMatrix M, MatrixType matType) { using (var f = new FuncTrace()) { f.Info("desired matrix type: " + matType); switch (matType) { case MatrixType.CCBCSR: return new CudaCCBCSRMatrix(M, this.Env); case MatrixType.CSR: return new CudaCSRMatrix(M, this.Env); case MatrixType.ELLPACK: return new CudaELLPACKmodMatrix(M, this.Env); case MatrixType.Auto: case MatrixType.ELLPACKcache: return new CudaELLPACKcacheMatrix(M, this.Env); default: throw new NotImplementedException(); } } } /// <summary> /// see <see cref="Device.CreateVector{T}(IPartitioning,T,out bool)"/> /// </summary> public override VectorBase CreateVector<T>(IPartitioning p, T content, out bool shallowInit) { double[] vals = null; if (typeof(T).Equals(typeof(double[]))) { shallowInit = true; vals = content as double[]; } else { shallowInit = false; vals = content.ToArray(); } return new CudaVector(p, vals, m_Env); } } }
36.009346
116
0.559304
[ "Apache-2.0" ]
FDYdarmstadt/BoSSS
src/ilPSP/layer_1.2-ilPSP/ilPSP.LinSolvers.monkey/CudaDevice.cs
3,749
C#
using System; using Microsoft.VisualStudio.TestTools.UnitTesting; using zxMode = com.google.zxing.qrcode.decoder.Mode; namespace Custom.Calculation.QrCode.Encoding.Tests { using Custom.Algebra.QrCode.Encoding; using Custom.Algebra.QrCode.Encoding.DataEncodation; using Custom.Algebra.QrCode.Encoding.DataEncodation.InputRecognition; using TestAttribute = NUnit.Framework.TestAttribute; using TestCaseAttribute = NUnit.Framework.TestCaseAttribute; using TestFixtureAttribute = NUnit.Framework.TestFixtureAttribute; [TestClass, TestFixture] public class ModeAutoSelectTest { [TestCase("15097435193480", "", (int)(Mode.Numeric))] [TestCase("35980SDLFKWETLKD", "", (int)(Mode.Alphanumeric))] [TestCase("r3546rraaaaÁÁÒÒÂÂöö", QRCodeConstantVariable.DefaultEncoding, (int)(Mode.EightBitByte))] [TestCase("r3546rraaaaククククララララウウウ", "shift_jis", (int)(Mode.EightBitByte))] [TestCase("r3546rraaaaรรฝฝฝฝรสสสสสรร", "windows-874", (int)(Mode.EightBitByte))] [TestCase("ヲヲヲヲヲンンンンン絞絞絞裁裁裁裁冊冊冊", QRCodeConstantVariable.UTF8Encoding, (int)(Mode.EightBitByte))] [TestCase("絞絞絞裁裁裁裁冊冊冊", "", (int)(Mode.Kanji))] [TestCase("123sad絞絞絞裁裁裁裁冊冊冊", QRCodeConstantVariable.UTF8Encoding, (int)(Mode.EightBitByte))] [TestCase("123sadััััใใใ์์์", "windows-874", (int)(Mode.EightBitByte))] [TestCase("ヲヲヲヲヲンンンンン◌ัใใใ◌์◌์◌ンンンÑÑå", QRCodeConstantVariable.UTF8Encoding, (int)(Mode.EightBitByte))] [TestCase("r3546สสสส์์แแแ์", "windows-874", (int)(Mode.EightBitByte))] [TestCase("ヲヲヲヲヲンンンンンÑÑÑååสสส◌์◌์แแแ", QRCodeConstantVariable.UTF8Encoding, (int)(Mode.EightBitByte))] [TestCase("r3546ลลธธธลๆๆๆๆๆ", "windows-874", (int)(Mode.EightBitByte))] [TestCase("ヲヲヲヲヲンンンンンd◌ั◌ลๆๆๆๆ", QRCodeConstantVariable.UTF8Encoding, (int)(Mode.EightBitByte))] [TestCase("r3546rraaaaêêêêêýýýýýýþþþþ", QRCodeConstantVariable.DefaultEncoding, (int)(Mode.EightBitByte))] [TestCase("ヲヲヲヲヲンンンンンaaa¶¶¶ååaaaรรฝฝ", QRCodeConstantVariable.UTF8Encoding, (int)(Mode.EightBitByte))] [TestCase("r3546rraaaa¶¶¶ååÑÑÑÑåååå¶¶¶", QRCodeConstantVariable.DefaultEncoding, (int)(Mode.EightBitByte))] [TestCase("ヲヲヲヲヲンンンンンÑÑåååå¶¶¶ฝรสสส", QRCodeConstantVariable.UTF8Encoding, (int)(Mode.EightBitByte))] [TestCase("r3546rraaaaÆÆÆÆÔÔÔÔØØØÔÔÆÆ", QRCodeConstantVariable.DefaultEncoding, (int)(Mode.EightBitByte))] [TestCase("ヲヲヲヲヲンンンンンสสส◌์◌์", QRCodeConstantVariable.UTF8Encoding, (int)(Mode.EightBitByte))] public void AutoSelectTestTwo(string content, string expectEncodingName, int expectMode) { RecognitionStruct structValue = InputRecognise.Recognise(content); if(structValue.Mode != (Mode)expectMode) Assert.Fail("Mode return as {0}. But it should be {1}", structValue.Mode, (Mode)expectMode); if(structValue.Mode == Mode.EightBitByte) { if(structValue.EncodingName != expectEncodingName) Assert.Fail("Encoding Name return as {0}. But it should be {1}", structValue.EncodingName, expectEncodingName); } } } }
53.035088
118
0.74264
[ "Apache-2.0" ]
InnPad/Formall.NET
Formall.MySql/branches/WebSiteWithPresentation/QrCode.Tests/ModeAutoSelectTest.cs
3,507
C#
using XUCore.Template.EasyFreeSql.Core; using XUCore.Template.EasyFreeSql.Persistence.Entities.User; namespace XUCore.Template.EasyFreeSql.Applaction.User.Role { /// <summary> /// 角色 /// </summary> public class RoleDto : DtoBase<RoleEntity> { /// <summary> /// 角色名 /// </summary> public string Name { get; set; } } }
22.058824
60
0.610667
[ "MIT" ]
xuyiazl/XUCore.Template
XUCore.Template.EasyFreeSql/Content/XUCore.Template.EasyFreeSql/XUCore.Template.EasyFreeSql.Applaction/AppServices/User/Role/Dtos/RoleDto.cs
387
C#
// *** WARNING: this file was generated by the Pulumi Terraform Bridge (tfgen) Tool. *** // *** Do not edit by hand unless you're certain you know what you are doing! *** using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Threading.Tasks; using Pulumi.Serialization; namespace Pulumi.Aws.WafV2.Inputs { public sealed class WebAclRuleStatementRateBasedStatementScopeDownStatementOrStatementStatementSizeConstraintStatementFieldToMatchAllQueryArgumentsGetArgs : Pulumi.ResourceArgs { public WebAclRuleStatementRateBasedStatementScopeDownStatementOrStatementStatementSizeConstraintStatementFieldToMatchAllQueryArgumentsGetArgs() { } } }
35.95
180
0.799722
[ "ECL-2.0", "Apache-2.0" ]
Otanikotani/pulumi-aws
sdk/dotnet/WafV2/Inputs/WebAclRuleStatementRateBasedStatementScopeDownStatementOrStatementStatementSizeConstraintStatementFieldToMatchAllQueryArgumentsGetArgs.cs
719
C#
using System.Windows; using System.Windows.Controls; using RevitLookupWpf.ViewModel; namespace RevitLookupWpf.Controls { public class BreadCrumNavigation:StackPanel { public LookupViewModel RootContext { get { return (LookupViewModel)GetValue(RootContextProperty); } set { SetValue(RootContextProperty, value); } } // Using a DependencyProperty as the backing store for RootContext. This enables animation, styling, binding, etc... public static readonly DependencyProperty RootContextProperty = DependencyProperty.Register("RootContext", typeof(LookupViewModel), typeof(BreadCrumNavigation), new PropertyMetadata(null,RootContextChangedCallback)); private static void RootContextChangedCallback(DependencyObject d, DependencyPropertyChangedEventArgs e) { var bread = (BreadCrumNavigation)d; bread.OnRootContextChanged((LookupViewModel)e.OldValue, (LookupViewModel)e.NewValue); } private void OnRootContextChanged(LookupViewModel oldValue, LookupViewModel newValue) { if (newValue != null) { Children.Clear(); } else if(oldValue != newValue) { var current = newValue; while (current != null) { DataTemplate data; Children.Add(new Button() { Content = current.Name }); current = current.Next; } } } public LookupViewModel SelectedContext { get { return (LookupViewModel)GetValue(SelectedContextProperty); } set { SetValue(SelectedContextProperty, value); } } // Using a DependencyProperty as the backing store for SelectedContext. This enables animation, styling, binding, etc... public static readonly DependencyProperty SelectedContextProperty = DependencyProperty.Register("SelectedContext", typeof(LookupViewModel), typeof(BreadCrumNavigation), new PropertyMetadata(null,SelectedContextChangedCallback)); private static void SelectedContextChangedCallback(DependencyObject d, DependencyPropertyChangedEventArgs e) { } } }
37.390625
172
0.625157
[ "MIT" ]
weianweigan/RevitLookupWpf
RevitLookup/Controls/BreadCrumNavigation.cs
2,395
C#
using System; using System.Runtime.InteropServices; using LibHac.Common; using LibHac.Diag; namespace LibHac.Util { public enum CharacterEncodingResult { Success = 0, InsufficientLength = 1, InvalidFormat = 2 } public static class CharacterEncoding { private static ReadOnlySpan<sbyte> Utf8NBytesInnerTable => new sbyte[] { -1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 4, 4, 4, 4, 4, 4, 4, 4, 5, 5, 5, 5, 6, 6, 7, 8 }; private static ReadOnlySpan<sbyte> Utf8NBytesTable => Utf8NBytesInnerTable.Slice(1); private static CharacterEncodingResult ConvertStringUtf8ToUtf16Impl(out int codeUnitsWritten, out int codeUnitsRead, Span<ushort> destination, ReadOnlySpan<byte> source) { if (source.Length == 0) { codeUnitsWritten = 0; codeUnitsRead = 0; return CharacterEncodingResult.Success; } ReadOnlySpan<byte> src = source; Span<ushort> dst = destination; while (src.Length > 0) { int codePointBytes = Utf8NBytesTable[src[0]]; if (src.Length < codePointBytes) goto ReturnInvalidFormat; if (dst.Length == 0) goto ReturnInsufficientLength; uint codePoint; switch (codePointBytes) { case 1: dst[0] = src[0]; src = src.Slice(1); dst = dst.Slice(1); break; case 2: // Check if the encoding is overlong if ((src[0] & 0x1E) == 0) goto ReturnInvalidFormat; if ((src[1] & 0xC0) != 0x80) goto ReturnInvalidFormat; codePoint = ((src[0] & 0x1Fu) << 6) | ((src[1] & 0x3Fu) << 0); dst[0] = (ushort)codePoint; src = src.Slice(2); dst = dst.Slice(1); break; case 3: if ((src[1] & 0xC0) != 0x80) goto ReturnInvalidFormat; if ((src[2] & 0xC0) != 0x80) goto ReturnInvalidFormat; codePoint = ((src[0] & 0xFu) << 12) | ((src[1] & 0x3Fu) << 6) | ((src[2] & 0x3Fu) << 0); // Check if the encoding is overlong if ((codePoint & 0xF800) == 0) goto ReturnInvalidFormat; // Check if the code point is in the range reserved for UTF-16 surrogates if ((codePoint & 0xF800) == 0xD800) goto ReturnInvalidFormat; dst[0] = (ushort)codePoint; src = src.Slice(3); dst = dst.Slice(1); break; case 4: if ((src[1] & 0xC0) != 0x80) goto ReturnInvalidFormat; if ((src[2] & 0xC0) != 0x80) goto ReturnInvalidFormat; if ((src[3] & 0xC0) != 0x80) goto ReturnInvalidFormat; codePoint = ((src[0] & 7u) << 18) | ((src[1] & 0x3Fu) << 12) | ((src[2] & 0x3Fu) << 6) | ((src[3] & 0x3Fu) << 0); // Check if the code point is outside the range of valid code points if (codePoint < 0x10000 || codePoint >= 0x110000) goto ReturnInvalidFormat; // Make sure we have enough space left in the destination if (dst.Length == 1) goto ReturnInsufficientLength; ushort highSurrogate = (ushort)((codePoint - 0x10000) / 0x400 + 0xD800); ushort lowSurrogate = (ushort)((codePoint - 0x10000) % 0x400 + 0xDC00); dst[0] = highSurrogate; dst[1] = lowSurrogate; src = src.Slice(4); dst = dst.Slice(2); break; default: goto ReturnInvalidFormat; } } codeUnitsWritten = destination.Length - dst.Length; codeUnitsRead = source.Length - src.Length; return CharacterEncodingResult.Success; ReturnInvalidFormat: codeUnitsWritten = destination.Length - dst.Length; codeUnitsRead = source.Length - src.Length; return CharacterEncodingResult.InvalidFormat; ReturnInsufficientLength: codeUnitsWritten = destination.Length - dst.Length; codeUnitsRead = source.Length - src.Length; return CharacterEncodingResult.InsufficientLength; } private static CharacterEncodingResult ConvertStringUtf16ToUtf8Impl(out int codeUnitsWritten, out int codeUnitsRead, Span<byte> destination, ReadOnlySpan<ushort> source) { if (source.Length == 0) { codeUnitsWritten = 0; codeUnitsRead = 0; return CharacterEncodingResult.Success; } ReadOnlySpan<ushort> src = source; Span<byte> dst = destination; while (src.Length > 0) { ushort codeUnit1 = src[0]; if (codeUnit1 < 0x80) { if (dst.Length < 1) goto ReturnInsufficientLength; dst[0] = (byte)codeUnit1; src = src.Slice(1); dst = dst.Slice(1); } else if ((codeUnit1 & 0xF800) == 0) { if (dst.Length < 2) goto ReturnInsufficientLength; dst[0] = (byte)(0xC0 | (codeUnit1 >> 6) & 0x1F); dst[1] = (byte)(0x80 | codeUnit1 & 0x3F); src = src.Slice(1); dst = dst.Slice(2); } else if (codeUnit1 < 0xD800 || codeUnit1 >= 0xE000) { if (dst.Length < 3) goto ReturnInsufficientLength; dst[0] = (byte)(0xE0 | (codeUnit1 >> 12) & 0xF); dst[1] = (byte)(0x80 | (codeUnit1 >> 6) & 0x3F); dst[2] = (byte)(0x80 | codeUnit1 & 0x3F); src = src.Slice(1); dst = dst.Slice(3); } else { uint utf32; if (source.Length == 1) { // If the code unit is a high surrogate if ((codeUnit1 & 0xF800) == 0xD800 && (codeUnit1 & 0x400) == 0) { if (dst.Length < 1) goto ReturnInsufficientLength; // We have the first half of a surrogate pair. Get the code point as if the low surrogate // were 0xDC00, effectively ignoring it. The first byte of the UTF-8-encoded code point does not // ever depend on the low surrogate, so we can write what the first byte would be. // The second byte doesn't ever depend on the low surrogate either, so I don't know why Nintendo // doesn't write that one too. I'll admit I'm not even sure why they write the first byte. This // reasoning is simply my best guess. const int codeUnit2 = 0xDC00; utf32 = ((codeUnit1 - 0xD800u) << 10) + codeUnit2 + 0x2400; dst[0] = (byte)(0xF0 | (utf32 >> 18)); dst = dst.Slice(1); } goto ReturnInvalidFormat; } int codeUnitsUsed = ConvertCharacterUtf16ToUtf32(out utf32, codeUnit1, src[1]); if (codeUnitsUsed < 0) { if (codeUnitsUsed == -2 && dst.Length > 0) { // We have an unpaired surrogate. Output the first UTF-8 code unit of the code point // ConvertCharacterUtf16ToUtf32 gave us. Nintendo's reason for doing this is unclear. dst[0] = (byte)(0xF0 | (utf32 >> 18)); dst = dst.Slice(1); } goto ReturnInvalidFormat; } if (dst.Length < 4) goto ReturnInsufficientLength; dst[0] = (byte)(0xF0 | (utf32 >> 18)); dst[1] = (byte)(0x80 | (utf32 >> 12) & 0x3F); dst[2] = (byte)(0x80 | (utf32 >> 6) & 0x3F); dst[3] = (byte)(0x80 | (utf32 >> 0) & 0x3F); src = src.Slice(2); dst = dst.Slice(4); } } codeUnitsWritten = destination.Length - dst.Length; codeUnitsRead = source.Length - src.Length; return CharacterEncodingResult.Success; ReturnInvalidFormat: codeUnitsWritten = destination.Length - dst.Length; codeUnitsRead = source.Length - src.Length; return CharacterEncodingResult.InvalidFormat; ReturnInsufficientLength: codeUnitsWritten = destination.Length - dst.Length; codeUnitsRead = source.Length - src.Length; return CharacterEncodingResult.InsufficientLength; } private static CharacterEncodingResult ConvertStringUtf8ToUtf32Impl(out int codeUnitsWritten, out int codeUnitsRead, Span<uint> destination, ReadOnlySpan<byte> source) { if (source.Length == 0) { codeUnitsWritten = 0; codeUnitsRead = 0; return CharacterEncodingResult.Success; } ReadOnlySpan<byte> src = source; Span<uint> dst = destination; while (src.Length > 0) { int codePointBytes = Utf8NBytesTable[src[0]]; if (src.Length < codePointBytes) goto ReturnInvalidFormat; if (dst.Length == 0) goto ReturnInsufficientLength; uint codePoint; switch (codePointBytes) { case 1: dst[0] = src[0]; src = src.Slice(1); dst = dst.Slice(1); break; case 2: // Check if the encoding is overlong if ((src[0] & 0x1E) == 0) goto ReturnInvalidFormat; if (Utf8NBytesTable[src[1]] != 0) goto ReturnInvalidFormat; codePoint = ((src[0] & 0x1Fu) << 6) | ((src[1] & 0x3Fu) << 0); dst[0] = codePoint; src = src.Slice(2); dst = dst.Slice(1); break; case 3: if (Utf8NBytesTable[src[1]] != 0) goto ReturnInvalidFormat; if (Utf8NBytesTable[src[2]] != 0) goto ReturnInvalidFormat; codePoint = ((src[0] & 0xFu) << 12) | ((src[1] & 0x3Fu) << 6) | ((src[2] & 0x3Fu) << 0); // Check if the encoding is overlong if ((codePoint & 0xF800) == 0) goto ReturnInvalidFormat; // Check if the code point is in the range reserved for UTF-16 surrogates if ((codePoint & 0xF800) == 0xD800) goto ReturnInvalidFormat; dst[0] = codePoint; src = src.Slice(3); dst = dst.Slice(1); break; case 4: if (Utf8NBytesTable[src[1]] != 0) goto ReturnInvalidFormat; if (Utf8NBytesTable[src[2]] != 0) goto ReturnInvalidFormat; if (Utf8NBytesTable[src[3]] != 0) goto ReturnInvalidFormat; codePoint = ((src[0] & 7u) << 18) | ((src[1] & 0x3Fu) << 12) | ((src[2] & 0x3Fu) << 6) | ((src[3] & 0x3Fu) << 0); // Check if the code point is outside the range of valid code points if (codePoint < 0x10000 || codePoint >= 0x110000) goto ReturnInvalidFormat; dst[0] = codePoint; src = src.Slice(4); dst = dst.Slice(1); break; default: goto ReturnInvalidFormat; } } codeUnitsWritten = destination.Length - dst.Length; codeUnitsRead = source.Length - src.Length; return CharacterEncodingResult.Success; ReturnInvalidFormat: codeUnitsWritten = destination.Length - dst.Length; codeUnitsRead = source.Length - src.Length; return CharacterEncodingResult.InvalidFormat; ReturnInsufficientLength: codeUnitsWritten = destination.Length - dst.Length; codeUnitsRead = source.Length - src.Length; return CharacterEncodingResult.InsufficientLength; } private static CharacterEncodingResult ConvertStringUtf32ToUtf8Impl(out int codeUnitsWritten, out int codeUnitsRead, Span<byte> destination, ReadOnlySpan<uint> source) { if (source.Length == 0) { codeUnitsWritten = 0; codeUnitsRead = 0; return CharacterEncodingResult.Success; } ReadOnlySpan<uint> src = source; Span<byte> dst = destination; while ((uint)src.Length > 0) { uint codePoint = src[0]; if (codePoint < 0x80) { if (dst.Length < 1) goto ReturnInsufficientLength; dst[0] = (byte)codePoint; dst = dst.Slice(1); } else if (codePoint < 0x800) { if (dst.Length < 2) goto ReturnInsufficientLength; dst[0] = (byte)(0xC0 | codePoint >> 6); dst[1] = (byte)(0x80 | codePoint & 0x3F); dst = dst.Slice(2); } else if (codePoint < 0x10000) { if (codePoint >= 0xD800 && codePoint <= 0xDFFF) goto ReturnInvalidFormat; if (dst.Length < 3) goto ReturnInsufficientLength; dst[0] = (byte)(0xE0 | (codePoint >> 12) & 0xF); dst[1] = (byte)(0x80 | (codePoint >> 6) & 0x3F); dst[2] = (byte)(0x80 | (codePoint >> 0) & 0x3F); dst = dst.Slice(3); } else if (codePoint < 0x110000) { if (dst.Length < 4) goto ReturnInsufficientLength; dst[0] = (byte)(0xF0 | codePoint >> 18); dst[1] = (byte)(0x80 | (codePoint >> 12) & 0x3F); dst[2] = (byte)(0x80 | (codePoint >> 6) & 0x3F); dst[3] = (byte)(0x80 | (codePoint >> 0) & 0x3F); dst = dst.Slice(4); } else { goto ReturnInvalidFormat; } src = src.Slice(1); } codeUnitsWritten = destination.Length - dst.Length; codeUnitsRead = source.Length - src.Length; return CharacterEncodingResult.Success; ReturnInvalidFormat: codeUnitsWritten = destination.Length - dst.Length; codeUnitsRead = source.Length - src.Length; return CharacterEncodingResult.InvalidFormat; ReturnInsufficientLength: codeUnitsWritten = destination.Length - dst.Length; codeUnitsRead = source.Length - src.Length; return CharacterEncodingResult.InsufficientLength; } private static int ConvertCharacterUtf16ToUtf32(out uint outUtf32, ushort codeUnit1, ushort codeUnit2) { UnsafeHelpers.SkipParamInit(out outUtf32); // If the first code unit isn't a surrogate, simply copy it to the output if ((codeUnit1 & 0xF800) != 0xD800) { outUtf32 = codeUnit1; return 1; } // Make sure the high surrogate isn't in the range of low surrogate values if ((codeUnit1 & 0x400) != 0) return -1; // We still output a code point value if we have an unpaired high surrogate. // Nintendo's reason for doing this is unclear. outUtf32 = ((codeUnit1 - 0xD800u) << 10) + codeUnit2 + 0x2400; // Make sure the low surrogate is in the range of low surrogate values if ((codeUnit2 & 0xFC00) != 0xDC00) return -2; return 2; } private static int GetLengthOfUtf16(ReadOnlySpan<ushort> source) { for (int i = 0; i < source.Length; i++) { if (source[i] == 0) return i; } return source.Length; } private static int GetLengthOfUtf32(ReadOnlySpan<uint> source) { for (int i = 0; i < source.Length; i++) { if (source[i] == 0) return i; } return source.Length; } public static CharacterEncodingResult ConvertStringUtf8ToUtf16Native(Span<ushort> destination, ReadOnlySpan<byte> source, int sourceLength) { Assert.SdkRequires(0 <= sourceLength, $"{nameof(sourceLength)} must not be negative."); Assert.SdkRequires(sourceLength <= source.Length); return ConvertStringUtf8ToUtf16Impl(out _, out _, destination, source.Slice(0, sourceLength)); } public static CharacterEncodingResult ConvertStringUtf8ToUtf16Native(Span<char> destination, ReadOnlySpan<byte> source, int sourceLength) { return ConvertStringUtf8ToUtf16Native(MemoryMarshal.Cast<char, ushort>(destination), source, sourceLength); } public static CharacterEncodingResult ConvertStringUtf8ToUtf16Native(Span<ushort> destination, ReadOnlySpan<byte> source) { int length = StringUtils.GetLength(source); Assert.SdkAssert(0 <= length); CharacterEncodingResult result = ConvertStringUtf8ToUtf16Impl(out int writtenCount, out _, destination.Slice(0, destination.Length - 1), source.Slice(0, length)); if (result == CharacterEncodingResult.Success) destination[writtenCount] = 0; return result; } public static CharacterEncodingResult ConvertStringUtf8ToUtf16Native(Span<char> destination, ReadOnlySpan<byte> source) { return ConvertStringUtf8ToUtf16Native(MemoryMarshal.Cast<char, ushort>(destination), source); } public static CharacterEncodingResult ConvertStringUtf16NativeToUtf8(Span<byte> destination, ReadOnlySpan<ushort> source, int sourceLength) { Assert.SdkRequires(0 <= sourceLength, $"{nameof(sourceLength)} must not be negative."); Assert.SdkRequires(sourceLength <= source.Length); return ConvertStringUtf16ToUtf8Impl(out _, out _, destination, source.Slice(0, sourceLength)); } public static CharacterEncodingResult ConvertStringUtf16NativeToUtf8(Span<byte> destination, ReadOnlySpan<char> source, int sourceLength) { return ConvertStringUtf16NativeToUtf8(destination, MemoryMarshal.Cast<char, ushort>(source), sourceLength); } public static CharacterEncodingResult ConvertStringUtf16NativeToUtf8(Span<byte> destination, ReadOnlySpan<ushort> source) { int length = GetLengthOfUtf16(source); Assert.SdkAssert(0 <= length); CharacterEncodingResult result = ConvertStringUtf16ToUtf8Impl(out int writtenCount, out _, destination.Slice(0, destination.Length - 1), source.Slice(0, length)); if (result == CharacterEncodingResult.Success) destination[writtenCount] = 0; return result; } public static CharacterEncodingResult ConvertStringUtf16NativeToUtf8(Span<byte> destination, ReadOnlySpan<char> source) { return ConvertStringUtf16NativeToUtf8(destination, MemoryMarshal.Cast<char, ushort>(source)); } public static CharacterEncodingResult GetLengthOfConvertedStringUtf8ToUtf16Native(out int length, ReadOnlySpan<byte> source, int sourceLength) { UnsafeHelpers.SkipParamInit(out length); Span<ushort> buffer = stackalloc ushort[0x20]; Assert.SdkRequires(0 <= sourceLength, $"{nameof(sourceLength)} must not be negative."); Assert.SdkRequires(sourceLength <= source.Length); int totalLength = 0; source = source.Slice(0, sourceLength); while (source.Length > 0) { CharacterEncodingResult result = ConvertStringUtf8ToUtf16Impl(out int writtenCount, out int readCount, buffer, source); if (result == CharacterEncodingResult.InvalidFormat) return CharacterEncodingResult.InvalidFormat; totalLength += writtenCount; source = source.Slice(readCount); } Assert.SdkAssert(0 <= totalLength); length = totalLength; return CharacterEncodingResult.Success; } public static CharacterEncodingResult GetLengthOfConvertedStringUtf8ToUtf16Native(out int length, ReadOnlySpan<byte> source) { int sourceLength = StringUtils.GetLength(source); Assert.SdkAssert(0 <= sourceLength); return GetLengthOfConvertedStringUtf8ToUtf16Native(out length, source, sourceLength); } public static CharacterEncodingResult GetLengthOfConvertedStringUtf16NativeToUtf8(out int length, ReadOnlySpan<ushort> source, int sourceLength) { UnsafeHelpers.SkipParamInit(out length); Span<byte> buffer = stackalloc byte[0x20]; Assert.SdkRequires(0 <= sourceLength, $"{nameof(sourceLength)} must not be negative."); Assert.SdkRequires(sourceLength <= source.Length); int totalLength = 0; source = source.Slice(0, sourceLength); while (source.Length > 0) { CharacterEncodingResult result = ConvertStringUtf16ToUtf8Impl(out int writtenCount, out int readCount, buffer, source); if (result == CharacterEncodingResult.InvalidFormat) return CharacterEncodingResult.InvalidFormat; totalLength += writtenCount; source = source.Slice(readCount); } Assert.SdkAssert(0 <= totalLength); length = totalLength; return CharacterEncodingResult.Success; } public static CharacterEncodingResult GetLengthOfConvertedStringUtf16NativeToUtf8(out int length, ReadOnlySpan<char> source, int sourceLength) { return GetLengthOfConvertedStringUtf16NativeToUtf8(out length, MemoryMarshal.Cast<char, ushort>(source), sourceLength); } public static CharacterEncodingResult GetLengthOfConvertedStringUtf16NativeToUtf8(out int length, ReadOnlySpan<ushort> source) { int sourceLength = GetLengthOfUtf16(source); Assert.SdkAssert(0 <= sourceLength); return GetLengthOfConvertedStringUtf16NativeToUtf8(out length, source, sourceLength); } public static CharacterEncodingResult GetLengthOfConvertedStringUtf16NativeToUtf8(out int length, ReadOnlySpan<char> source) { return GetLengthOfConvertedStringUtf16NativeToUtf8(out length, MemoryMarshal.Cast<char, ushort>(source)); } public static CharacterEncodingResult ConvertStringUtf8ToUtf32(Span<uint> destination, ReadOnlySpan<byte> source, int sourceLength) { Assert.SdkRequires(0 <= sourceLength, $"{nameof(sourceLength)} must not be negative."); Assert.SdkRequires(sourceLength <= source.Length); return ConvertStringUtf8ToUtf32Impl(out _, out _, destination, source.Slice(0, sourceLength)); } public static CharacterEncodingResult ConvertStringUtf8ToUtf32(Span<uint> destination, ReadOnlySpan<byte> source) { int sourceLength = StringUtils.GetLength(source); Assert.SdkAssert(0 <= sourceLength); CharacterEncodingResult result = ConvertStringUtf8ToUtf32Impl(out int writtenCount, out _, destination.Slice(0, destination.Length - 1), source.Slice(0, sourceLength)); if (result == CharacterEncodingResult.Success) destination[writtenCount] = 0; return result; } public static CharacterEncodingResult ConvertStringUtf32ToUtf8(Span<byte> destination, ReadOnlySpan<uint> source, int sourceLength) { Assert.SdkRequires(0 <= sourceLength, $"{nameof(sourceLength)} must not be negative."); Assert.SdkRequires(sourceLength <= source.Length); return ConvertStringUtf32ToUtf8Impl(out _, out _, destination, source.Slice(0, sourceLength)); } public static CharacterEncodingResult ConvertStringUtf32ToUtf8(Span<byte> destination, ReadOnlySpan<uint> source) { int sourceLength = GetLengthOfUtf32(source); Assert.SdkAssert(0 <= sourceLength); CharacterEncodingResult result = ConvertStringUtf32ToUtf8Impl(out int writtenCount, out _, destination.Slice(0, destination.Length - 1), source.Slice(0, sourceLength)); if (result == CharacterEncodingResult.Success) destination[writtenCount] = 0; return result; } public static CharacterEncodingResult GetLengthOfConvertedStringUtf8ToUtf32(out int length, ReadOnlySpan<byte> source, int sourceLength) { UnsafeHelpers.SkipParamInit(out length); Span<uint> buffer = stackalloc uint[0x20]; Assert.SdkRequires(0 <= sourceLength, $"{nameof(sourceLength)} must not be negative."); Assert.SdkRequires(sourceLength <= source.Length); int totalLength = 0; source = source.Slice(0, sourceLength); while (source.Length > 0) { CharacterEncodingResult result = ConvertStringUtf8ToUtf32Impl(out int writtenCount, out int readCount, buffer, source); if (result == CharacterEncodingResult.InvalidFormat) return CharacterEncodingResult.InvalidFormat; totalLength += writtenCount; source = source.Slice(readCount); } Assert.SdkAssert(0 <= totalLength); length = totalLength; return CharacterEncodingResult.Success; } public static CharacterEncodingResult GetLengthOfConvertedStringUtf8ToUtf32(out int length, ReadOnlySpan<byte> source) { int sourceLength = StringUtils.GetLength(source); Assert.SdkAssert(0 <= sourceLength); return GetLengthOfConvertedStringUtf8ToUtf32(out length, source, sourceLength); } public static CharacterEncodingResult GetLengthOfConvertedStringUtf32ToUtf8(out int length, ReadOnlySpan<uint> source, int sourceLength) { UnsafeHelpers.SkipParamInit(out length); Span<byte> buffer = stackalloc byte[0x20]; Assert.SdkRequires(0 <= sourceLength, $"{nameof(sourceLength)} must not be negative."); Assert.SdkRequires(sourceLength <= source.Length); int totalLength = 0; source = source.Slice(0, sourceLength); while (source.Length > 0) { CharacterEncodingResult result = ConvertStringUtf32ToUtf8Impl(out int writtenCount, out int readCount, buffer, source); if (result == CharacterEncodingResult.InvalidFormat) return CharacterEncodingResult.InvalidFormat; totalLength += writtenCount; source = source.Slice(readCount); } Assert.SdkAssert(0 <= totalLength); length = totalLength; return CharacterEncodingResult.Success; } public static CharacterEncodingResult GetLengthOfConvertedStringUtf32ToUtf8(out int length, ReadOnlySpan<uint> source) { int sourceLength = GetLengthOfUtf32(source); Assert.SdkAssert(0 <= sourceLength); return GetLengthOfConvertedStringUtf32ToUtf8(out length, source, sourceLength); } public static CharacterEncodingResult ConvertCharacterUtf8ToUtf16Native(Span<ushort> destination, ReadOnlySpan<byte> source) { if (destination.Length < 2) return CharacterEncodingResult.InsufficientLength; if (source.Length < 1) return CharacterEncodingResult.InvalidFormat; Span<byte> bufferSrc = stackalloc byte[5]; Span<ushort> bufferDst = stackalloc ushort[3]; bufferSrc[0] = source[0]; bufferSrc[1] = 0; bufferSrc[2] = 0; bufferSrc[3] = 0; bufferSrc[4] = 0; // Read more code units if needed if (source[0] >= 0xC2 && source[0] < 0xE0) { if (source.Length < 2) return CharacterEncodingResult.InvalidFormat; bufferSrc[1] = source[1]; } else if (source[0] >= 0xE0 && source[0] < 0xF0) { if (source.Length < 3) return CharacterEncodingResult.InvalidFormat; bufferSrc[1] = source[1]; bufferSrc[2] = source[2]; } else if (source[0] >= 0xF0 && source[0] < 0xF8) { if (source.Length < 4) return CharacterEncodingResult.InvalidFormat; bufferSrc[1] = source[1]; bufferSrc[2] = source[2]; bufferSrc[3] = source[3]; } bufferDst.Clear(); CharacterEncodingResult result = ConvertStringUtf8ToUtf16Native(bufferDst, bufferSrc); destination[0] = bufferDst[0]; destination[1] = bufferDst[1]; return result; } public static CharacterEncodingResult ConvertCharacterUtf8ToUtf16Native(Span<char> destination, ReadOnlySpan<byte> source) { return ConvertCharacterUtf8ToUtf16Native(MemoryMarshal.Cast<char, ushort>(destination), source); } public static CharacterEncodingResult ConvertCharacterUtf16NativeToUtf8(Span<byte> destination, ReadOnlySpan<ushort> source) { if (destination.Length < 4) return CharacterEncodingResult.InsufficientLength; if (source.Length < 1) return CharacterEncodingResult.InvalidFormat; Span<ushort> bufferSrc = stackalloc ushort[3]; Span<byte> bufferDst = stackalloc byte[5]; bufferSrc[0] = source[0]; bufferSrc[1] = 0; bufferSrc[2] = 0; // Read more code units if needed if (source[0] >= 0xD800 && source[0] < 0xE000) { if (source.Length < 2) return CharacterEncodingResult.InvalidFormat; bufferSrc[1] = source[1]; } bufferDst.Clear(); CharacterEncodingResult result = ConvertStringUtf16NativeToUtf8(bufferDst, bufferSrc); destination[0] = bufferDst[0]; destination[1] = bufferDst[1]; destination[2] = bufferDst[2]; destination[3] = bufferDst[3]; return result; } public static CharacterEncodingResult ConvertCharacterUtf16NativeToUtf8(Span<byte> destination, ReadOnlySpan<char> source) { return ConvertCharacterUtf16NativeToUtf8(destination, MemoryMarshal.Cast<char, ushort>(source)); } public static CharacterEncodingResult ConvertCharacterUtf8ToUtf32(out uint destination, ReadOnlySpan<byte> source) { UnsafeHelpers.SkipParamInit(out destination); if (source.Length < 1) return CharacterEncodingResult.InvalidFormat; switch (Utf8NBytesTable[source[0]]) { case 1: destination = source[0]; return CharacterEncodingResult.Success; case 2: if (source.Length < 2) break; if ((source[0] & 0x1E) == 0) break; if (Utf8NBytesTable[source[1]] != 0) break; destination = ((source[0] & 0x1Fu) << 6) | ((source[1] & 0x3Fu) << 0); return CharacterEncodingResult.Success; case 3: if (source.Length < 3) break; if (Utf8NBytesTable[source[1]] != 0 || Utf8NBytesTable[source[2]] != 0) break; uint codePoint3 = ((source[0] & 0xFu) << 12) | ((source[1] & 0x3Fu) << 6) | ((source[2] & 0x3Fu) << 0); if ((codePoint3 & 0xF800) == 0 || (codePoint3 & 0xF800) == 0xD800) break; destination = codePoint3; return CharacterEncodingResult.Success; case 4: if (source.Length < 4) break; if (Utf8NBytesTable[source[1]] != 0 || Utf8NBytesTable[source[2]] != 0 || Utf8NBytesTable[source[3]] != 0) break; uint codePoint4 = ((source[0] & 7u) << 18) | ((source[1] & 0x3Fu) << 12) | ((source[2] & 0x3Fu) << 6) | ((source[3] & 0x3Fu) << 0); if (codePoint4 < 0x10000 || codePoint4 >= 0x110000) break; destination = codePoint4; return CharacterEncodingResult.Success; } return CharacterEncodingResult.InvalidFormat; } public static CharacterEncodingResult ConvertCharacterUtf32ToUtf8(Span<byte> destination, uint source) { if (destination.Length < 4) return CharacterEncodingResult.InsufficientLength; destination[0] = 0; destination[1] = 0; destination[2] = 0; destination[3] = 0; if (source < 0x80) { destination[0] = (byte)source; } else if (source < 0x800) { destination[0] = (byte)(0xC0 | source >> 6); destination[1] = (byte)(0x80 | (source & 0x3F)); } else if (source < 0x10000) { if (source >= 0xD800 && source <= 0xDFFF) return CharacterEncodingResult.InvalidFormat; destination[0] = (byte)(0xE0 | (source >> 12) & 0xF); destination[1] = (byte)(0x80 | (source >> 6) & 0x3F); destination[2] = (byte)(0x80 | (source >> 0) & 0x3F); } else if (source < 0x110000) { destination[0] = (byte)(0xF0 | (source >> 18)); destination[1] = (byte)(0x80 | (source >> 12) & 0x3F); destination[2] = (byte)(0x80 | (source >> 6) & 0x3F); destination[3] = (byte)(0x80 | (source >> 0) & 0x3F); } else { return CharacterEncodingResult.InvalidFormat; } return CharacterEncodingResult.Success; } public static CharacterEncodingResult PickOutCharacterFromUtf8String(Span<byte> destinationChar, ref ReadOnlySpan<byte> source) { Assert.SdkRequires(destinationChar.Length >= 4); Assert.SdkRequires(source.Length >= 1); Assert.SdkRequires(source[0] != 0); ReadOnlySpan<byte> str = source; if (destinationChar.Length < 4) return CharacterEncodingResult.InsufficientLength; if (str.Length < 1) return CharacterEncodingResult.InvalidFormat; destinationChar[0] = 0; destinationChar[1] = 0; destinationChar[2] = 0; destinationChar[3] = 0; uint codePoint = str[0]; switch (Utf8NBytesTable[(int)codePoint]) { case 1: destinationChar[0] = str[0]; source = str.Slice(1); break; case 2: if (str.Length < 2) return CharacterEncodingResult.InvalidFormat; if ((str[0] & 0x1E) == 0 || Utf8NBytesTable[str[1]] != 0) return CharacterEncodingResult.InvalidFormat; destinationChar[0] = str[0]; destinationChar[1] = str[1]; source = str.Slice(2); break; case 3: if (str.Length < 3) return CharacterEncodingResult.InvalidFormat; if (Utf8NBytesTable[str[1]] != 0 || Utf8NBytesTable[str[2]] != 0) return CharacterEncodingResult.InvalidFormat; codePoint = ((str[0] & 0xFu) << 12) | ((str[1] & 0x3Fu) << 6) | ((str[2] & 0x3Fu) << 0); if ((codePoint & 0xF800) == 0 || (codePoint & 0xF800) == 0xD800) return CharacterEncodingResult.InvalidFormat; destinationChar[0] = str[0]; destinationChar[1] = str[1]; destinationChar[2] = str[2]; source = str.Slice(3); break; case 4: if (str.Length < 4) return CharacterEncodingResult.InvalidFormat; if (Utf8NBytesTable[str[1]] != 0 || Utf8NBytesTable[str[2]] != 0 || Utf8NBytesTable[str[3]] != 0) return CharacterEncodingResult.InvalidFormat; codePoint = ((str[0] & 7u) << 18) | ((str[1] & 0x3Fu) << 12) | ((str[2] & 0x3Fu) << 6) | ((str[3] & 0x3Fu) << 0); if (codePoint < 0x10000 || codePoint >= 0x110000) return CharacterEncodingResult.InvalidFormat; destinationChar[0] = str[0]; destinationChar[1] = str[1]; destinationChar[2] = str[2]; destinationChar[3] = str[3]; source = str.Slice(4); break; default: return CharacterEncodingResult.InvalidFormat; } return CharacterEncodingResult.Success; } } }
39.250899
152
0.490984
[ "BSD-3-Clause" ]
Thealexbarney/LibHac
src/LibHac/Util/CharacterEncoding.cs
43,649
C#
// // C4PredictiveQuery_defs.cs // // Copyright (c) 2019 Couchbase, Inc All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // using System; using System.Linq; using System.Runtime.InteropServices; using System.Threading; using LiteCore.Util; namespace LiteCore.Interop { internal unsafe partial struct C4PredictiveModel { public void* context; public IntPtr prediction; public IntPtr unregistered; } }
26.135135
75
0.73423
[ "Apache-2.0" ]
kokoska69/couchbase-lite-net
src/LiteCore/src/LiteCore.Shared/Interop/C4PredictiveQuery_defs.cs
967
C#
using System; using System.Collections.Generic; using System.Windows; namespace ReactNative.DevSupport { /// <summary> /// The content dialog for red box exception display. /// </summary> sealed partial class RedBoxDialog : Window { #region Private Fields private readonly Action _onClick; #endregion #region Properties /// <summary> /// The error cookie. /// </summary> public int ErrorCookie { get; set; } /// <summary> /// The message. /// </summary> public string Message { get; set; } /// <summary> /// The stack trace. /// </summary> public IList<IStackFrame> StackTrace { get; set; } = new List<IStackFrame>(); #endregion #region Constructor(s) /// <summary> /// Instantiates the <see cref="RedBoxDialog"/>. /// </summary> /// <param name="onClick"> /// Action to take when primary button is clicked. /// </param> public RedBoxDialog(Action onClick) { InitializeComponent(); this.DataContext = this; _onClick = onClick; } #endregion #region Event Handlers private void OnReloadButtonClicked(object sender, RoutedEventArgs e) { if (_onClick != null) { _onClick(); } else { this.Close(); } } private void OnCloseButtonClicked(object sender, RoutedEventArgs e) { this.Close(); } #endregion } }
21.538462
85
0.509524
[ "MIT" ]
Shadyzpop/react-native-windows-compiled
ReactWindows/ReactNative.Net46/DevSupport/RedBoxDialog.xaml.cs
1,682
C#
namespace Machete.X12Schema.V5010 { using X12; public interface Loop0320_204 : X12Layout { SegmentList<L5> DescriptionMarksAndNumbers { get; } Segment<AT8> ShipmentWeightPackagingAndQuantityData { get; } LayoutList<Loop0325_1_204> Loop0325_1 { get; } SegmentList<L11> BusinessInstructionsAndReferenceNumber { get; } SegmentList<MEA> Measurements { get; } SegmentList<PER> AdministrativeCommunicationsContact { get; } Segment<L4> Measurement { get; } LayoutList<Loop0325_2_204> Loop0325_2 { get; } } }
26.12
72
0.612557
[ "Apache-2.0" ]
ahives/Machete
src/Machete.X12Schema/V5010/Layouts/Loop0320_204.cs
653
C#
using HarmonyLib; using RimWorld; using RimWorld.Planet; using System; using System.Collections.Generic; using System.Linq; using System.Reflection; using System.Reflection.Emit; using System.Text; using UnityEngine; using Verse; using Verse.AI; using Verse.Sound; namespace ZombieLand { public class BombVest : Apparel { } public class TankySuit : Apparel { } public class StickyGoo : Filth { } [StaticConstructorOnStartup] static class Patches { static readonly List<string> errors = new List<string>(); static Patches() { var harmony = new Harmony("net.pardeike.zombieland"); errors = new List<string>(); try { harmony.PatchAll(); } catch (Exception ex) { var error = ex.ToString(); Log.Error(error); var idx = error.IndexOf("\n at"); if (idx > 0) errors.Insert(0, error.Substring(0, idx)); } // prepare Twinkie LongEventHandler.QueueLongEvent(() => { Tools.EnableTwinkie(false); }, "", true, null); // patches for Combat Extended (need to run late or else statics in those classes are not set yet) LongEventHandler.ExecuteWhenFinished(() => { Projectile_Launch_Patch.PatchCombatExtended(harmony); ArmorUtility_GetPostArmorDamage_Patch.PatchCombatExtended(harmony); AlienTools.Init(); }); // for debugging // //DebugRimworldMethodCalls((Type type) => //{ // if (type.Name.Contains("AttackTarget")) return true; // if (type.Name.Contains("_AI")) return true; // if (type.Name.Contains("Reachability")) return true; // return false; //}); } static void Error(string error) { errors.Add(error); Log.Error(error); } [HarmonyPatch(typeof(MainMenuDrawer))] [HarmonyPatch(nameof(MainMenuDrawer.Init))] static class MainMenuDrawer_Init_Patch { static void Postfix() { if (errors.Any()) { LongEventHandler.ExecuteWhenFinished(() => { var message = errors.Join(error => error, "\n\n"); errors.Clear(); if (Find.WindowStack != null) Find.WindowStack.Add(new Dialog_ErrorMessage($"Zombieland encountered an unexpected error and might not work as expected. Either RimWorld has been updated or you have a mod conflict:\n\n{message}")); }); } } } // used to prevent zombies from being counted as hostiles // both in map exist and for danger music // static readonly Dictionary<Map, HashSet<IAttackTarget>> playerHostilesWithoutZombies = new Dictionary<Map, HashSet<IAttackTarget>>(); // patch for debugging: show pheromone grid as overlay // [HarmonyPatch(typeof(SelectionDrawer))] [HarmonyPatch(nameof(SelectionDrawer.DrawSelectionOverlays))] static class SelectionDrawer_DrawSelectionOverlays_Patch { static readonly float pawnAltitude = Altitudes.AltitudeFor(AltitudeLayer.Pawn - 1); static void Postfix() { if (Constants.DEBUGGRID == false || DebugViewSettings.drawDoorsDebug == false) return; // debug zombie counts Find.CurrentMap.GetGrid().IterateCells((x, z, cell) => { var pos = new Vector3(x, pawnAltitude, z); if (cell.zombieCount > 1) { var a = Math.Min(0.9f, 0.2f * (cell.zombieCount - 1)); Tools.DebugPosition(pos, new Color(0f, 0f, 1f, a)); } }); // debug timestamps var fadeOff = Tools.PheromoneFadeoff(); var now = Tools.Ticks(); Find.CurrentMap.GetGrid().IterateCells((x, z, cell) => { var pos = new Vector3(x, pawnAltitude, z); var diff = now - cell.timestamp; if (diff >= -fadeOff && diff < 0) { var a = GenMath.LerpDouble(-fadeOff, 0, 0.8f, 0.5f, diff); Tools.DebugPosition(pos, new Color(1f, 1f, 0f, a)); } else if (diff < fadeOff) { var a = GenMath.LerpDouble(0, fadeOff, 0.5f, 0.0f, diff); Tools.DebugPosition(pos, new Color(1f, 0f, 0f, a)); } }); } } // patch for debugging: show zombie avoidance grid // [HarmonyPatch(typeof(MapInterface))] [HarmonyPatch(nameof(MapInterface.MapInterfaceUpdate))] class MapInterface_MapInterfaceUpdate_Patch { static void Postfix() { // var m = DebugSolidColorMats.MaterialOf(Color.magenta); // Tools.PlayerReachableRegions(Find.CurrentMap).SelectMany(r => r.Cells).Do(c => CellRenderer.RenderSpot(c.ToVector3Shifted(), m, 0.25f)); if (Constants.DEBUGGRID == false || DebugViewSettings.writePathCosts == false) return; if (Tools.ShouldAvoidZombies() == false) return; var map = Find.CurrentMap; var tickManager = map.GetComponent<TickManager>(); if (tickManager == null) return; var avoidGrid = tickManager.avoidGrid; var currentViewRect = Find.CameraDriver.CurrentViewRect; _ = currentViewRect.ClipInsideMap(map); foreach (var c in currentViewRect) { var cost = avoidGrid.GetCosts()[c.x + c.z * map.Size.x]; if (cost > 0) Tools.DebugPosition(c.ToVector3(), new Color(1f, 0f, 0f, GenMath.LerpDouble(0, 10000, 0.4f, 1f, cost))); } } } // patch for debugging: show zombie pathing grid around the mouse // [HarmonyPatch(typeof(MapInterface))] [HarmonyPatch(nameof(MapInterface.MapInterfaceOnGUI_AfterMainTabs))] class MapInterface_MapInterfaceOnGUI_AfterMainTabs_Patch { static void Postfix() { if (Constants.DEBUGGRID == false || DebugViewSettings.writeBeauty == false) return; if (Event.current.type != EventType.Repaint) return; var map = Find.CurrentMap; if (map == null) return; var grid = map.GetGrid(); var basePos = UI.MouseCell(); var info = ZombieWanderer.GetMapInfo(map); var ignoreBuildings = Input.GetKey(KeyCode.LeftShift) || Input.GetKey(KeyCode.RightShift); Tools.GetCircle(4).Select(vec => vec + basePos).Do(cell => { var labelVec = GenMapUI.LabelDrawPosFor(cell); var newPos = info.GetParent(cell, ignoreBuildings); if (newPos.IsValid == false) { GenMapUI.DrawThingLabel(labelVec, "⁜", Color.red); return; } var d = newPos - cell; var n = (d.x + 1) + (d.z + 1) * 3; var arrow = "↙↓↘←◌→↖↑↗".Substring(n, 1); GenMapUI.DrawThingLabel(labelVec, arrow, ignoreBuildings ? Color.yellow : Color.white); }); } } // patch to show zombieland version and total number of zombies // [HarmonyPatch(typeof(GlobalControlsUtility))] [HarmonyPatch(nameof(GlobalControlsUtility.DoDate))] class GlobalControlsUtility_DoDate_Patch { static Color percentageBackground = new Color(1, 1, 1, 0.1f); static void Postfix(float leftX, float width, ref float curBaseY) { var map = Find.CurrentMap; if (map == null) return; // current zombie count + mouseover: version var tickManager = map.GetComponent<TickManager>(); if (tickManager == null) return; var count = tickManager.ZombieCount(); var rightMargin = 7f; if (count > 0) { var zombieCountString = count + " Zombies"; var zlRect = new Rect(leftX, curBaseY - 24f, width, 24f); Text.Font = GameFont.Small; var len = Text.CalcSize(zombieCountString); zlRect.xMin = zlRect.xMax - Math.Min(leftX, len.x + rightMargin); GUI.BeginGroup(zlRect); Text.Anchor = TextAnchor.UpperRight; var rect = zlRect.AtZero(); rect.xMax -= rightMargin; var percentRect = rect; percentRect.width *= ZombieTicker.PercentTicking; percentRect.xMin -= 2; percentRect.xMax += 2; percentRect.yMax -= 3; Widgets.DrawRectFast(percentRect, percentageBackground); Widgets.Label(rect, zombieCountString); Text.Anchor = TextAnchor.UpperLeft; GUI.EndGroup(); TooltipHandler.TipRegion(zlRect, new TipSignal(delegate { var currentVersion = Assembly.GetExecutingAssembly().GetName().Version; return $"Zombieland v{currentVersion.ToString(4)}"; }, 99799)); if (Mouse.IsOver(zlRect) && tickManager.allZombiesCached.Count <= 100) tickManager.allZombiesCached.Do(zombie => TargetHighlighter.Highlight(new GlobalTargetInfo(zombie), true, false, false)); curBaseY -= zlRect.height; } // current threat count + mouseover: forecast if (ZombieSettings.Values.useDynamicThreatLevel) { static string Format(float min, float max) { var n1 = Mathf.FloorToInt(min * 100); var n2 = Mathf.FloorToInt(max * 100); if (n1 == n2) return string.Format("{0:D0}%", n1) + " " + "ThreatLevel".Translate(); return string.Format("{0:D0}-{1:D0}%", n1, n2) + " " + "ThreatLevel".Translate(); } var zombieWeather = map.GetComponent<ZombieWeather>(); var (min, max) = zombieWeather.GetFactorRangeFor(); var zombieWeatherString = Format(min, max); var zlRect = new Rect(leftX, curBaseY - 24f, width, 24f); Text.Font = GameFont.Small; var len = Text.CalcSize(zombieWeatherString); zlRect.xMin = zlRect.xMax - Math.Min(leftX, len.x + rightMargin); var over = Mouse.IsOver(zlRect); if (over) { var r = zlRect; r.xMin -= 10; Widgets.DrawHighlight(r); } GUI.BeginGroup(zlRect); Text.Anchor = TextAnchor.UpperRight; var rect = zlRect.AtZero(); rect.xMax -= rightMargin; Widgets.Label(rect, zombieWeatherString); Text.Anchor = TextAnchor.UpperLeft; GUI.EndGroup(); if (over) { var winWidth = 720; var winHeight = 320; var bgRect = new Rect(zlRect.xMin - 10 - winWidth, zlRect.yMax - winHeight, winWidth, winHeight); Find.WindowStack.ImmediateWindow(564534346, bgRect, WindowLayer.Super, ZombieWeather.GeneateTooltipDrawer(bgRect.AtZero()), false, false, 1f); } curBaseY -= zlRect.height; } } } // custom ticking // [HarmonyPatch(typeof(Verse.TickManager))] [HarmonyPatch(nameof(Verse.TickManager.TickManagerUpdate))] static class Verse_TickManager_TickManagerUpdate_Patch { static void Prefix(Verse.TickManager __instance) { _ = ZombieWanderer.processor.MoveNext(); if (Find.TickManager.Paused) return; ZombieTicker.zombiesTicked = 0; ZombieTicker.managers = Find.Maps.Select(map => map.GetComponent<TickManager>()).OfType<TickManager>(); var curTimePerTick = __instance.CurTimePerTick; var realTimeToTickThrough = __instance.realTimeToTickThrough; if (Mathf.Abs(Time.deltaTime - curTimePerTick) < curTimePerTick * 0.1f) realTimeToTickThrough += curTimePerTick; else realTimeToTickThrough += Time.deltaTime; var n1 = realTimeToTickThrough / curTimePerTick; var n2 = __instance.TickRateMultiplier * 2f; var loopEstimate = Mathf.FloorToInt(Mathf.Min(n1, n2)); ZombieTicker.maxTicking = Mathf.FloorToInt(loopEstimate * ZombieTicker.managers.Sum(tm => tm.allZombiesCached.Count(zombie => zombie.Spawned && zombie.Dead == false))); ZombieTicker.currentTicking = Mathf.FloorToInt(ZombieTicker.maxTicking * ZombieTicker.PercentTicking); } static void Postfix(Verse.TickManager __instance) { if (__instance.Paused) return; var ticked = ZombieTicker.zombiesTicked; var current = ZombieTicker.currentTicking; var newPercentZombiesTicked = ticked == 0 || current == 0 ? 1f : ticked / (float)current; if (ticked > current - 100) newPercentZombiesTicked = Math.Min(1f, newPercentZombiesTicked + 0.5f); ZombieTicker.PercentTicking = newPercentZombiesTicked; } } [HarmonyPatch(typeof(Verse.TickManager))] [HarmonyPatch(nameof(Verse.TickManager.DoSingleTick))] static class TickManager_DoSingleTick_Patch { static IEnumerable<CodeInstruction> Transpiler(IEnumerable<CodeInstruction> instructions) { foreach (var instruction in instructions) { if (instruction.opcode == OpCodes.Ret) yield return CodeInstruction.Call(() => ZombieTicker.DoSingleTick()); yield return instruction; } } } [HarmonyPatch(typeof(Verse.TickManager))] [HarmonyPatch(nameof(Verse.TickManager.NothingHappeningInGame))] static class Verse_TickManager_NothingHappeningInGame_Patch { static void Postfix(ref bool __result) { if (__result == false) return; __result = ZombieGenerator.ZombiesSpawning == 0; } } // patch to have zombies not being mothballed // [HarmonyPatch(typeof(RimWorld.Planet.WorldPawns))] [HarmonyPatch(nameof(RimWorld.Planet.WorldPawns.ShouldMothball))] static class WorldPawns_ShouldMothball_Patch { static bool Prefix(Pawn p, ref bool __result) { if (p is Zombie zombie) { __result = false; return false; } return true; } } // patch to control if raiders and animals see zombies as hostile // [HarmonyPatch(typeof(GenHostility))] [HarmonyPatch(nameof(GenHostility.HostileTo))] [HarmonyPatch(new Type[] { typeof(Thing), typeof(Thing) })] static class GenHostility_HostileTo_Thing_Thing_Patch { static void Postfix(Thing a, Thing b, ref bool __result) { if (!(a is Pawn pawn) || pawn.IsColonist || (pawn is Zombie) || !(b is Zombie zombie)) return; if (Tools.HasInfectionState(pawn, InfectionState.BittenInfectable, InfectionState.Infected)) __result = false; else __result = Tools.IsHostileToZombies(pawn); } } [HarmonyPatch(typeof(GenHostility))] [HarmonyPatch(nameof(GenHostility.HostileTo))] [HarmonyPatch(new Type[] { typeof(Thing), typeof(Faction) })] static class GenHostility_HostileTo_Thing_Faction_Patch { static void Postfix(Thing t, Faction fac, ref bool __result) { if (fac == null) return; if (fac.def != ZombieDefOf.Zombies) return; if (!(t is Pawn pawn)) return; if (pawn is Zombie) return; // jobs != null test is a workaround for a NRE in RW triggered by carried slaves being dropped if (pawn.jobs != null && pawn.IsColonist) return; __result = Tools.IsHostileToZombies(pawn); } } // patch to make raiders choose zombies less likely as a target // and to prefer non-downed zombies from downed one as targets // [HarmonyPatch(typeof(AttackTargetFinder))] [HarmonyPatch(nameof(AttackTargetFinder.GetAvailableShootingTargetsByScore))] static class AttackTargetFinder_GetAvailableShootingTargetsByScore_Patch { static void Prefix(List<IAttackTarget> rawTargets, IAttackTargetSearcher searcher, Verb verb) { if (searcher == null || verb == null) return; if (verb.CanHarmElectricZombies()) return; _ = rawTargets.RemoveAll(t => t.Thing is Zombie zombie && zombie.IsActiveElectric && zombie.Downed == false); } static void Postfix(List<Pair<IAttackTarget, float>> __result) { if (__result.Any(pair => pair.first is Zombie zombie && zombie.health.Downed == false)) _ = __result.RemoveAll(pair => pair.first is Zombie zombie && (zombie.health.Downed || zombie.ropedBy != null)); } } [HarmonyPatch(typeof(AttackTargetFinder))] [HarmonyPatch(nameof(AttackTargetFinder.BestAttackTarget))] static class AttackTargetFinder_BestAttackTarget_Patch { static void Prefix(ref Predicate<Thing> validator, IAttackTargetSearcher searcher) { if (validator == null || searcher == null) return; var verb = searcher.CurrentEffectiveVerb; if (verb == null) return; var oldValidator = validator; // make ranged weapons (i.e. turrets) ignore electrical or roped zombies if (!(searcher is Pawn attacker)) { if (verb.CanHarmElectricZombies()) return; validator = (Thing t) => { if (t is Zombie zombie && (zombie.IsActiveElectric || zombie.ropedBy != null)) return false; return oldValidator(t); }; return; } // attacker is zombie? use default if (attacker is Zombie) return; // attacker is colonist? if (attacker.IsColonist) { validator = (Thing t) => { if (t is Zombie zombie && zombie.ropedBy == attacker) return false; return oldValidator(t); }; return; } // attacker is animal if (attacker.RaceProps.Animal) { validator = (Thing t) => { if (t is Zombie) return ZombieSettings.Values.animalsAttackZombies; return oldValidator(t); }; return; } // attacker is friendly // (disabled because the postfix deals with that) // // if (attacker.Faction.HostileTo(Faction.OfPlayer) == false) // return (IAttackTarget t) => (t.Thing is Zombie) ? false : validator(t); // attacker is enemy validator = (Thing t) => { if (t is Zombie zombie) { if (ZombieSettings.Values.enemiesAttackZombies == false) return false; if (zombie.IsActiveElectric && zombie.Downed == false) if (verb.GetDamageDef().isRanged) return false; var distanceToTarget = (float)(attacker.Position - zombie.Position).LengthHorizontalSquared; if (zombie.health.Downed && distanceToTarget <= 9) return true; if (zombie.state != ZombieState.Tracking) return false; var attackDistance = verb == null ? 1f : verb.verbProps.range * verb.verbProps.range; var zombieAvoidRadius = Tools.ZombieAvoidRadius(zombie, true); if (attackDistance < zombieAvoidRadius && distanceToTarget >= zombieAvoidRadius) return false; if (distanceToTarget > attackDistance) return false; } return oldValidator(t); }; } static void Postfix(ref IAttackTarget __result, TargetScanFlags flags, Predicate<Thing> validator, IAttackTargetSearcher searcher) { var thing = __result as Thing; if (thing == null) { // fix only friendlies Thing attacker = searcher as Pawn; if (attacker == null) attacker = searcher.Thing; if (attacker != null && attacker.Faction.HostileTo(Faction.OfPlayer) == false) { var verb = searcher.CurrentEffectiveVerb; if (verb != null) { var props = verb.verbProps; var canHarmElectricZombies = verb.CanHarmElectricZombies(); if (props.IsMeleeAttack == false && props.range > 0) { // TODO // the following can be improved by choosing targets that // are not too close. unsolved problem: we do not know how // to relocate shooters yet // var maxDownedRangeSquared = 6 * 6; var maxRangeSquared = (int)(props.range * props.range); var tickManager = attacker.Map.GetComponent<TickManager>(); var pos = attacker.Position; int zombiePrioritySorter(Zombie zombie) { var score = maxRangeSquared - pos.DistanceToSquared(zombie.Position); if (zombie.IsSuicideBomber) score += 30; if (zombie.IsTanky) score += 20; if (zombie.isDarkSlimer) score += 15; if (zombie.isToxicSplasher) score += 10; if (zombie.story.bodyType == BodyTypeDefOf.Thin) score += 5; if (zombie.state == ZombieState.Tracking) score += 5; return -score; } var losFlags = TargetScanFlags.NeedLOSToPawns | TargetScanFlags.NeedLOSToAll; __result = tickManager.allZombiesCached .Where(zombie => { if (zombie.state == ZombieState.Emerging || zombie.ropedBy != null) return false; if (canHarmElectricZombies == false && zombie.IsActiveElectric && zombie.Downed == false) return false; var d = pos.DistanceToSquared(zombie.Position); var dn = zombie.health.Downed; if (dn && (d > maxDownedRangeSquared || ZombieSettings.Values.doubleTapRequired == false)) return false; if (dn == false && d > maxRangeSquared) return false; if (verb.CanHitTargetFrom(pos, zombie) == false) return false; if ((flags & losFlags) != 0 && attacker.CanSee(zombie, null) == false) return false; return true; }) .OrderBy(zombiePrioritySorter).FirstOrDefault(); return; } } } } if (validator != null && thing != null && validator(thing) == false) __result = null; } } [HarmonyPatch(typeof(AttackTargetFinder))] [HarmonyPatch(nameof(AttackTargetFinder.GetShootingTargetScore))] static class AttackTargetFinder_GetShootingTargetScore_Patch { static bool Prefix(IAttackTarget target, IAttackTargetSearcher searcher, Verb verb, ref float __result) { if (!(searcher?.Thing is Pawn pawn) || verb == null || verb.IsMeleeAttack) return true; if (!(target is Zombie zombie) || (zombie.health.Downed && ZombieSettings.Values.doubleTapRequired == false)) return true; var distance = (zombie.Position - pawn.Position).LengthHorizontal; var weaponRange = verb.verbProps.range; if (distance > weaponRange) return true; __result = 120f * (weaponRange - distance) / weaponRange; if (zombie.IsSuicideBomber) __result += 12f; if (zombie.isToxicSplasher) __result += 6f; if (zombie.story.bodyType == BodyTypeDefOf.Thin) __result += 3f; return false; } } // patch so other zombies do not affect goodwill of other factions // [HarmonyPatch(typeof(Faction))] [HarmonyPatch(nameof(Faction.TryAffectGoodwillWith))] static class Faction_TryAffectGoodwillWith_Patch { static bool Prefix(ref bool __result, Faction __instance, Faction other) { if (__instance.def == ZombieDefOf.Zombies || other.def == ZombieDefOf.Zombies) { __result = false; return false; } return true; } } // patch to make downed zombies as easy to kill as standing // [HarmonyPatch(typeof(Projectile))] [HarmonyPatch(nameof(Projectile.ImpactSomething))] static class Projectile_ImpactSomething_Patch { static PawnPosture GetPostureFix(Pawn p) { if (p is Zombie) return PawnPosture.Standing; // fake standing return p.GetPosture(); } static bool RandChance(float chance, Pawn pawn) { return Rand.Chance(pawn is Zombie ? Math.Min(1f, chance * 2f) : chance); } static IEnumerable<CodeInstruction> Transpiler(IEnumerable<CodeInstruction> instructions) { var m_GetPosture = SymbolExtensions.GetMethodInfo(() => PawnUtility.GetPosture(null)); var m_Chance = SymbolExtensions.GetMethodInfo(() => Rand.Chance(0f)); var list = instructions.ToList(); CodeInstruction lastPawnInstruction = null; var len = list.Count; for (var i = 0; i < len; i++) { if (list[i].Calls(m_GetPosture)) { list[i].opcode = OpCodes.Call; list[i].operand = SymbolExtensions.GetMethodInfo(() => GetPostureFix(null)); lastPawnInstruction = list[i - 1]; } if (list[i].Calls(m_Chance)) { list.Insert(i, lastPawnInstruction); i++; len++; list[i].opcode = OpCodes.Call; list[i].operand = SymbolExtensions.GetMethodInfo(() => RandChance(0f, null)); } } return list.AsEnumerable(); } } // patch to remove the constant danger music because of the constant thread of zombies // [HarmonyPatch(typeof(AttackTargetsCache))] [HarmonyPatch(nameof(AttackTargetsCache.RegisterTarget))] static class AttackTargetsCache_RegisterTarget_Patch { static void Postfix(IAttackTarget target) { var thing = target.Thing; if (thing == null || thing is Zombie) return; if (thing.HostileTo(Faction.OfPlayer) == false) return; var map = thing.Map; if (map == null) return; if (playerHostilesWithoutZombies.ContainsKey(map) == false) playerHostilesWithoutZombies.Add(map, new HashSet<IAttackTarget>()); _ = playerHostilesWithoutZombies[map].Add(target); } } // [HarmonyPatch(typeof(AttackTargetsCache))] [HarmonyPatch(nameof(AttackTargetsCache.DeregisterTarget))] static class AttackTargetsCache_DeregisterTarget_Patch { static void Postfix(IAttackTarget target) { var thing = target.Thing; if (thing == null || thing is Zombie) return; var map = thing.Map; if (map == null) return; if (playerHostilesWithoutZombies.ContainsKey(map)) _ = playerHostilesWithoutZombies[map].Remove(target); } } // [HarmonyPatch(typeof(MusicManagerPlay))] [HarmonyPatch(nameof(MusicManagerPlay.DangerMusicMode), MethodType.Getter)] static class MusicManagerPlay_DangerMusicMode_Patch { static int lastUpdateTick; static StoryDanger dangerRatingInt = StoryDanger.None; // TODO: the following is ugly since we copy original code (ugh!) // The solution is to add method IL copying to Harmony ... // Until then: this stays // [HarmonyPriority(Priority.First)] static bool Prefix(ref bool __result) { var maps = Find.Maps; for (var i = 0; i < maps.Count; i++) { var map = maps[i]; if (map.IsPlayerHome) { if (Find.TickManager.TicksGame > lastUpdateTick + 101) { var hostiles = playerHostilesWithoutZombies.ContainsKey(map) ? playerHostilesWithoutZombies[map] : new HashSet<IAttackTarget>(); var num = hostiles.Count(GenHostility.IsActiveThreatToPlayer); if (num == 0) dangerRatingInt = StoryDanger.None; else if (num <= Mathf.CeilToInt(map.mapPawns.FreeColonistsSpawnedCount * 0.5f)) dangerRatingInt = StoryDanger.Low; else { dangerRatingInt = StoryDanger.Low; var lastColonistHarmedTick = map.dangerWatcher.lastColonistHarmedTick; if (lastColonistHarmedTick > Find.TickManager.TicksGame - 900) dangerRatingInt = StoryDanger.High; else { foreach (var current in map.lordManager.lords) { if (current.CurLordToil is LordToil_AssaultColony) { dangerRatingInt = StoryDanger.High; break; } } } } lastUpdateTick = Find.TickManager.TicksGame; } } } __result = dangerRatingInt == StoryDanger.High; return false; } } // make zombies not affect overall danger rating // [HarmonyPatch(typeof(DangerWatcher))] [HarmonyPatch(nameof(DangerWatcher.AffectsStoryDanger))] static class DangerWatcher_AffectsStoryDanger_Patch { [HarmonyPriority(Priority.First)] static bool Prefix(IAttackTarget t, ref bool __result) { if (t is Zombie) { __result = false; return false; } return true; } } // patch to increase hit chance for shooting at zombies // [HarmonyPatch(typeof(Verb_LaunchProjectile))] [HarmonyPatch(nameof(Verb_LaunchProjectile.TryCastShot))] static class Verb_LaunchProjectile_TryCastShot_Patch { static bool SkipMissingShotsAtZombies(Verb verb, LocalTargetInfo currentTarget) { // difficulty Intense or worse will trigger default behavior if (Tools.Difficulty() >= 1.5f) return false; // only for colonists if (!(verb.caster is Pawn colonist) || colonist.Faction != Faction.OfPlayer) return false; // shooting zombies var zombie = currentTarget.HasThing ? currentTarget.Thing as Zombie : null; if (zombie == null) return false; // max 15 cells awaw if ((zombie.Position - colonist.Position).LengthHorizontalSquared > 225) return false; // with line of sight if (!(verb is Verb_LaunchProjectile shot) || shot.verbProps.requireLineOfSight == false) return false; // skip miss calculations return Rand.Chance(Constants.COLONISTS_HIT_ZOMBIES_CHANCE); } [HarmonyPriority(Priority.First)] static IEnumerable<CodeInstruction> Transpiler(IEnumerable<CodeInstruction> instructions, ILGenerator generator) { var m_SkipMissingShotsAtZombies = SymbolExtensions.GetMethodInfo(() => SkipMissingShotsAtZombies(null, null)); var p_forcedMissRadius = AccessTools.DeclaredPropertyGetter(typeof(VerbProperties), nameof(VerbProperties.ForcedMissRadius)); var f_canHitNonTargetPawnsNow = AccessTools.DeclaredField(typeof(Verb), "canHitNonTargetPawnsNow"); var f_currentTarget = typeof(Verb).Field("currentTarget"); var skipLabel = generator.DefineLabel(); var inList = instructions.ToList(); var idx1 = inList.FirstIndexOf(instr => instr.Calls(p_forcedMissRadius)); if (idx1 > 0 && idx1 < inList.Count()) { var jumpToIndex = -1; for (var i = inList.Count - 1; i >= 3; i--) { if (inList[i].LoadsField(f_canHitNonTargetPawnsNow) == false) continue; i -= 3; if (inList[i].LoadsConstant(1)) { jumpToIndex = i; break; } } if (jumpToIndex >= 0) { inList[jumpToIndex].labels.Add(skipLabel); idx1 -= 2; inList.Insert(idx1++, new CodeInstruction(OpCodes.Ldarg_0)); inList.Insert(idx1++, new CodeInstruction(OpCodes.Ldarg_0)); inList.Insert(idx1++, new CodeInstruction(OpCodes.Ldfld, f_currentTarget)); inList.Insert(idx1++, new CodeInstruction(OpCodes.Call, m_SkipMissingShotsAtZombies)); inList.Insert(idx1++, new CodeInstruction(OpCodes.Brtrue, skipLabel)); } else Error("No ldfld canHitNonTargetPawnsNow prefixed by ldc.i4.1;stloc.s;ldarg.0 in Verb_LaunchProjectile.TryCastShot"); } else Error("No ldfld forcedMissRadius in Verb_LaunchProjectile.TryCastShot"); foreach (var instruction in inList) yield return instruction; } } // patch to remove zombies from hostile count so it does not // alter game logic (for example when a caravan leaves an enemy base) // [HarmonyPatch(typeof(GenHostility))] [HarmonyPatch(nameof(GenHostility.IsActiveThreatTo))] [HarmonyPatch(new Type[] { typeof(IAttackTarget), typeof(Faction) })] static class GenHostility_IsActiveThreat_Patch { [HarmonyPriority(Priority.First)] static bool Prefix(ref bool __result, IAttackTarget target) { if (target is Zombie) { __result = false; return false; } return true; } } // patch to not allow some jobs on zombies // [HarmonyPatch(typeof(Pawn_JobTracker))] [HarmonyPatch(nameof(Pawn_JobTracker.StartJob))] static class Pawn_JobTracker_StartJob_Patch { static readonly HashSet<JobDef> allowedJobs = new HashSet<JobDef>() { CustomDefs.Stumble, CustomDefs.Sabotage, DefDatabase<JobDef>.GetNamed("ExtractZombieSerum"), DefDatabase<JobDef>.GetNamed("DoubleTap"), JobDefOf.Goto, JobDefOf.Wait, JobDefOf.Wait_MaintainPosture, JobDefOf.AttackMelee, JobDefOf.AttackStatic }; static bool Prefix(Job newJob, Pawn ___pawn, ref int ___jobsGivenThisTick, ref string ___jobsGivenThisTickTextual, ref bool ___startingNewJob) { if ((___pawn is Zombie) == false) return true; if (allowedJobs.Contains(newJob.def)) return true; ___jobsGivenThisTick = 0; ___jobsGivenThisTickTextual = ""; ___startingNewJob = false; ___pawn.ClearReservationsForJob(newJob); Log.Warning($"Zombies cannot do job {newJob.def.defName}"); return false; } } // make static attacks on doors stop when door is open // [HarmonyPatch] static class JobDriver_AttackStatic_MakeNewToils_b__1_Patch { static AccessTools.FieldRef<object, JobDriver_AttackStatic> _this; static MethodBase TargetMethod() { var method = typeof(JobDriver_AttackStatic).InnerMethodsStartingWith("<MakeNewToils>b__1").First(); if (method != null) { var f_this = AccessTools.GetDeclaredFields(method.DeclaringType).First(); _this = AccessTools.FieldRefAccess<object, JobDriver_AttackStatic>(f_this); } else Error($"Cannot find field Verse.AI.JobDriver_AttackStatic.*.<MakeNewToils>b__1"); return method; } static bool Prefix(object __instance) { var me = _this(__instance); if (me.TargetA.HasThing && me.TargetThingA is Building_Door door && door.Open) { me.EndJobWith(JobCondition.Incompletable); return false; } return true; } } // hide zombie bite when electrifier/albino zombie wants to melee // [HarmonyPatch(typeof(Pawn_MeleeVerbs))] [HarmonyPatch(nameof(Pawn_MeleeVerbs.GetUpdatedAvailableVerbsList))] static class Pawn_MeleeVerbs_GetUpdatedAvailableVerbsList_Patch { static void Postfix(List<VerbEntry> __result, Pawn ___pawn) { if (___pawn is Zombie zombie && (zombie.isElectrifier || zombie.isAlbino)) _ = __result.RemoveAll(entry => entry.verb.GetDamageDef() == Tools.ZombieBiteDamageDef); } } // apply electrical damage when electrifier zombies melee // [HarmonyPatch(typeof(Verb_MeleeAttackDamage))] [HarmonyPatch(nameof(Verb_MeleeAttackDamage.DamageInfosToApply))] static class Pawn_MeleeVerbs_ChooseMeleeVerb_Patch { static void ElectricalDamage(Zombie zombie, Pawn pawn, ref DamageInfo damageInfo) { if (zombie == null || zombie.IsActiveElectric == false) return; if (pawn?.Map == null || pawn.apparel == null) return; var apparel = pawn.apparel.WornApparel; var smokepopBelt = apparel.OfType<SmokepopBelt>().FirstOrDefault(); if (smokepopBelt != null) { damageInfo = new DamageInfo(Tools.ElectricalShockDamageDef, 1f, 0f, -1f, zombie, null, Tools.ElectricalFieldThingDef); zombie.ElectrifyAnimation(); return; } var shieldBelt = apparel.OfType<ShieldBelt>().FirstOrDefault(); if (shieldBelt != null) { if (shieldBelt.Energy > 0) damageInfo = new DamageInfo(DamageDefOf.EMP, 1f, 0f, -1f, zombie, null, Tools.ElectricalFieldThingDef); else shieldBelt.Destroy(); FleckMaker.Static(pawn.TrueCenter(), pawn.Map, FleckDefOf.ExplosionFlash, 12f); FleckMaker.ThrowDustPuff(pawn.TrueCenter(), pawn.Map, Rand.Range(0.8f, 1.2f)); zombie.ElectrifyAnimation(); return; } var sensitiveStuff = apparel.Cast<Thing>(); if (pawn.equipment != null) sensitiveStuff = sensitiveStuff .Union(pawn.equipment.AllEquipmentListForReading.Cast<Thing>()); if (pawn.inventory != null) sensitiveStuff = sensitiveStuff .Union(pawn.inventory.GetDirectlyHeldThings()); var success = sensitiveStuff .Where(thing => { if (thing?.def?.costList == null) return false; return thing.def.costList.Any(cost => cost.thingDef == ThingDefOf.ComponentIndustrial || cost.thingDef == ThingDefOf.ComponentSpacer); }) .TryRandomElement(out var stuff); if (success && stuff != null) { var amount = 2f * Tools.Difficulty(); var damage = new DamageInfo(DamageDefOf.Deterioration, amount); _ = stuff.TakeDamage(damage); FleckMaker.Static(pawn.TrueCenter(), pawn.Map, FleckDefOf.ExplosionFlash, 12f); FleckMaker.ThrowDustPuff(pawn.TrueCenter(), pawn.Map, Rand.Range(0.8f, 1.2f)); zombie.ElectrifyAnimation(); } } static IEnumerable<DamageInfo> Postfix(IEnumerable<DamageInfo> results, LocalTargetInfo target, Thing ___caster) { if (target.Thing is Pawn pawn) if (___caster is Zombie zombie) { foreach (var result in results) { var def = result.Def; var damage = result; if (def.isRanged == false && def.isExplosive == false && target.HasThing) ElectricalDamage(zombie, pawn, ref damage); yield return damage; } yield break; } foreach (var result in results) yield return result; } } // patch to reduce revenge by animals // [HarmonyPatch(typeof(PawnUtility))] [HarmonyPatch(nameof(PawnUtility.GetManhunterOnDamageChance))] [HarmonyPatch(new Type[] { typeof(Pawn), typeof(float), typeof(Thing) })] static class PawnUtility_GetManhunterOnDamageChance_Patch { static void Postfix(ref float __result, Thing instigator) { if (ZombieSettings.Values.zombiesCauseManhuntingResponse == false) __result = 0; else if (instigator is Zombie) __result /= 20; } } // patch to let predators prefer humans for zombies // [HarmonyPatch(typeof(FoodUtility))] [HarmonyPatch(nameof(FoodUtility.GetPreyScoreFor))] static class FoodUtility_GetPreyScoreFor_Patch { static void Postfix(Pawn prey, ref float __result) { if (prey is Zombie) { if (ZombieSettings.Values.animalsAttackZombies) __result -= 70f; else __result -= 10000f; } } } [HarmonyPatch(typeof(PathFinder))] [HarmonyPatch(nameof(PathFinder.FindPath))] [HarmonyPatch(new Type[] { typeof(IntVec3), typeof(LocalTargetInfo), typeof(TraverseParms), typeof(PathEndMode), typeof(PathFinderCostTuning) })] public static class PathFinder_FindPath_Patch { public static Dictionary<Map, TickManager> tickManagerCache = new Dictionary<Map, TickManager>(); // infected colonists will still path so exclude them from this check // by returning 0 - currently disabled because it does cost too much static int GetZombieCosts(Pawn pawn, int idx) { if (pawn == null) return 0; if (Tools.ShouldAvoidZombies(pawn) == false) return 0; var map = pawn.Map; if (map == null) return 0; if (tickManagerCache.TryGetValue(map, out var tickManager) == false) { tickManager = map.GetComponent<TickManager>(); if (tickManager == null) return 0; tickManagerCache[map] = tickManager; } if (tickManager.avoidGrid == null) return 0; return tickManager.avoidGrid.GetCosts()[idx]; } static readonly MethodInfo m_CellToIndex_int_int = AccessTools.Method(typeof(CellIndices), nameof(CellIndices.CellToIndex), new Type[] { typeof(int), typeof(int) }); static readonly FieldInfo f_TraverseParms_pawn = AccessTools.Field(typeof(TraverseParms), nameof(TraverseParms.pawn)); static readonly MethodInfo m_GetExtraCosts = SymbolExtensions.GetMethodInfo(() => GetZombieCosts(null, 0)); static IEnumerable<CodeInstruction> Transpiler(IEnumerable<CodeInstruction> instructions, MethodBase original) { var list = instructions.ToList(); while (true) { var t_PathFinderNodeFast = AccessTools.Inner(typeof(PathFinder), "PathFinderNodeFast"); var f_knownCost = AccessTools.Field(t_PathFinderNodeFast, "knownCost"); if (f_knownCost == null) { Error($"Cannot find field Verse.AI.PathFinder.PathFinderNodeFast.knownCost"); break; } var idx = list.FirstIndexOf(ins => ins.Calls(m_CellToIndex_int_int)); if (idx < 0 || idx >= list.Count() || list[idx + 1].opcode != OpCodes.Stloc_S) { Error($"Cannot find CellToIndex(n,n)/Stloc_S in {original.FullDescription()}"); break; } var gridIdx = list[idx + 1].operand; var insertLoc = list.FirstIndexOf(ins => ins.opcode == OpCodes.Ldfld && (FieldInfo)ins.operand == f_knownCost); while (insertLoc >= 0 && insertLoc < list.Count) { if (list[insertLoc].opcode == OpCodes.Add) break; insertLoc++; } if (insertLoc < 0 || insertLoc >= list.Count()) { Error($"Cannot find Ldfld knownCost ... Add in {original.FullDescription()}"); break; } var traverseParmsIdx = original.GetParameters().FirstIndexOf(info => info.ParameterType == typeof(TraverseParms)) + 1; list.Insert(insertLoc++, new CodeInstruction(OpCodes.Add)); list.Insert(insertLoc++, new CodeInstruction(OpCodes.Ldarga_S, traverseParmsIdx)); list.Insert(insertLoc++, new CodeInstruction(OpCodes.Ldfld, f_TraverseParms_pawn)); list.Insert(insertLoc++, new CodeInstruction(OpCodes.Ldloc_S, gridIdx)); list.Insert(insertLoc++, new CodeInstruction(OpCodes.Call, m_GetExtraCosts)); break; } foreach (var instr in list) yield return instr; } } [HarmonyPatch(typeof(Pawn_PathFollower))] [HarmonyPatch(nameof(Pawn_PathFollower.NeedNewPath))] static class Pawn_PathFollower_NeedNewPath_Patch { static readonly MethodInfo m_ShouldCollideWithPawns = SymbolExtensions.GetMethodInfo(() => PawnUtility.ShouldCollideWithPawns(null)); static bool ZombieInPath(Pawn_PathFollower __instance, Pawn pawn) { if (Tools.ShouldAvoidZombies(pawn) == false) return false; if (pawn.RaceProps.Humanlike == false) return false; if (pawn.RaceProps.IsFlesh == false) return false; if (AlienTools.IsFleshPawn(pawn) == false) return false; var path = __instance.curPath; if (path.NodesLeftCount < 5) return false; var lookAhead = path.Peek(4); var destination = path.LastNode; if ((lookAhead - destination).LengthHorizontalSquared < 25) return false; var map = pawn.Map; var tickManager = map.GetComponent<TickManager>(); if (tickManager == null) return false; var costs = tickManager.avoidGrid.GetCosts(); var zombieDanger = costs[lookAhead.x + lookAhead.z * map.Size.x]; return (zombieDanger > 0); } static IEnumerable<CodeInstruction> Transpiler(IEnumerable<CodeInstruction> instructions, ILGenerator generator) { var list = instructions.ToList(); var idx = list.FirstIndexOf(code => code.Calls(m_ShouldCollideWithPawns)) - 1; if (idx > 0 && idx < list.Count()) { if (list[idx].opcode == OpCodes.Ldfld) { var jump = generator.DefineLabel(); // here we should have a Ldarg_0 but original code has one with a label on it so we reuse it list.Insert(idx++, new CodeInstruction(OpCodes.Ldarg_0)); list.Insert(idx++, new CodeInstruction(OpCodes.Ldfld, typeof(Pawn_PathFollower).Field("pawn"))); list.Insert(idx++, new CodeInstruction(OpCodes.Call, SymbolExtensions.GetMethodInfo(() => ZombieInPath(null, null)))); list.Insert(idx++, new CodeInstruction(OpCodes.Brfalse, jump)); list.Insert(idx++, new CodeInstruction(OpCodes.Ldc_I4_1)); list.Insert(idx++, new CodeInstruction(OpCodes.Ret)); list.Insert(idx++, new CodeInstruction(OpCodes.Ldarg_0) { labels = new List<Label>() { jump } }); // add the missing Ldarg_0 from original code here } else Error("Cannot find Ldfld one instruction before " + m_ShouldCollideWithPawns + " in Pawn_PathFollower.NeedNewPath"); } else Error("Cannot find " + m_ShouldCollideWithPawns + " in Pawn_PathFollower.NeedNewPath"); foreach (var instr in list) yield return instr; } } // do not open doors when not drafted and they are marked by the avoid grid // [HarmonyPatch] static class Building_Door_PawnCanOpen_Patch { static void Postfix(Building_Door __instance, Pawn p, ref bool __result) { if (__result == false) return; if (p == null || p.Map == null || p.Drafted || __instance == null) return; if (__instance.FreePassage) return; if (p.CurJob?.playerForced ?? false) return; if (Tools.ShouldAvoidZombies(p) == false) return; var map = p.Map; var tickManager = map.GetComponent<TickManager>(); if (tickManager == null) return; var avoidGrid = tickManager.avoidGrid; if (avoidGrid == null) return; var size = __instance.def.size; if (size.x == 1 && size.z == 1) { if (avoidGrid.ShouldAvoid(map, __instance.Position)) __result = false; } else { var cells = __instance.OccupiedRect().Cells; if (cells.Any(cell => avoidGrid.ShouldAvoid(map, cell))) __result = false; } } static IEnumerable<MethodBase> TargetMethods() { return GenTypes.AllSubclasses(typeof(Building_Door)) .Union(new List<Type>() { typeof(Building_Door) }) .Select(type => type.GetMethod("PawnCanOpen", AccessTools.all | BindingFlags.DeclaredOnly)) .Where(method => method != null) .Cast<MethodBase>(); } } // patch to make zombie not auto-close doors // [HarmonyPatch(typeof(Building_Door))] [HarmonyPatch(nameof(Building_Door.Tick))] static class Building_Door_Tick_Patch { static bool CellContains(ThingGrid instance, IntVec3 c, ThingCategory cat) { var zombie = instance.ThingAt<Zombie>(c); if (zombie != null && zombie.isAlbino) return false; return instance.CellContains(c, cat); } static IEnumerable<CodeInstruction> Transpiler(IEnumerable<CodeInstruction> instructions) { var from = SymbolExtensions.GetMethodInfo(() => new ThingGrid(null).CellContains(default, default(ThingCategory))); var to = SymbolExtensions.GetMethodInfo(() => CellContains(null, default, default)); return Transpilers.MethodReplacer(instructions, from, to); } } // [HarmonyPatch(typeof(Building_Door))] [HarmonyPatch(nameof(Building_Door.StartManualCloseBy))] static class Building_Door_StartManualCloseBy_Patch { static bool Prefix(Pawn closer) { return !(closer is Zombie zombie); } } // patch to stop jobs when zombies have to be avoided // [HarmonyPatch(typeof(JobDriver))] [HarmonyPatch(nameof(JobDriver.DriverTick))] static class JobDriver_DriverTick_Patch { static void Postfix(JobDriver __instance, Pawn ___pawn) { if (___pawn is Zombie || ___pawn.Map == null || ___pawn.IsColonist == false) return; // could also check ___pawn.health.capacities.CapableOf(PawnCapacityDefOf.Moving) but it's expensive // and Pawn_HealthTracker.ShouldBeDowned checks it too if (___pawn.health.Downed || ___pawn.InMentalState || ___pawn.Drafted) return; if (__instance.job == null || __instance.job.playerForced || Tools.ShouldAvoidZombies(___pawn) == false) return; var tickManager = ___pawn.Map.GetComponent<TickManager>(); if (tickManager == null) return; var avoidGrid = tickManager.avoidGrid; if (avoidGrid == null) return; if (avoidGrid.InAvoidDanger(___pawn) == false) return; var jobDef = __instance.job.def; if (false || jobDef == JobDefOf.ExtinguishSelf || jobDef == JobDefOf.Flee || jobDef == JobDefOf.FleeAndCower || jobDef == JobDefOf.Vomit ) return; var pos = ___pawn.Position; var map = ___pawn.Map; var safeDestinations = new List<IntVec3>(); map.floodFiller.FloodFill(pos, (IntVec3 cell) => { if (cell.x == pos.x && cell.z == pos.z) return true; if (cell.Walkable(map) == false) return false; if (cell.GetEdifice(map) is Building_Door building_Door && building_Door.CanPhysicallyPass(___pawn) == false) return false; return PawnUtility.AnyPawnBlockingPathAt(cell, ___pawn, true, false, false) == false; }, (IntVec3 cell) => { if (cell.Standable(map) && avoidGrid.ShouldAvoid(map, cell) == false) safeDestinations.Add(cell); return false; }, 64, false, null); if (safeDestinations.Count > 0) { safeDestinations.SortByDescending(dest => (pos - dest).LengthHorizontalSquared); var destination = safeDestinations.First(); if (destination.IsValid) { var flee = JobMaker.MakeJob(JobDefOf.Flee, destination); flee.playerForced = true; ___pawn.jobs.ClearQueuedJobs(); ___pawn.jobs.StartJob(flee, JobCondition.Incompletable, null); } } } } [HarmonyPatch(typeof(JobGiver_ConfigurableHostilityResponse))] [HarmonyPatch(nameof(JobGiver_ConfigurableHostilityResponse.TryGetAttackNearbyEnemyJob))] static class JobGiver_ConfigurableHostilityResponse_TryGetAttackNearbyEnemyJob_Patch { static bool Prefix(Pawn pawn, ref Job __result) { if (pawn.CurJobDef == JobDefOf.Flee && pawn.CurJob.playerForced) { __result = null; return false; } return true; } public static bool MyCanReachImmediate(Pawn pawn, LocalTargetInfo target, PathEndMode peMode) { if (target.Thing is Zombie zombie) if (zombie.IsActiveElectric) return true; return pawn.CanReachImmediate(target, peMode); } static IEnumerable<CodeInstruction> Transpiler(IEnumerable<CodeInstruction> instructions) { var m_CanReachImmediate = SymbolExtensions.GetMethodInfo(() => ReachabilityImmediate.CanReachImmediate(null, default, default)); var m_MyCanReachImmediate = SymbolExtensions.GetMethodInfo(() => MyCanReachImmediate(null, default, default)); return Transpilers.MethodReplacer(instructions, m_CanReachImmediate, m_MyCanReachImmediate); } } [HarmonyPatch(typeof(DangerUtility))] [HarmonyPatch(nameof(DangerUtility.GetDangerFor))] static class DangerUtility_GetDangerFor_Patch { static void Postfix(IntVec3 c, Pawn p, Map map, ref Danger __result) { if (p is Zombie || p.IsColonist == false || Tools.ShouldAvoidZombies(p) == false) return; if (p.CurJob?.playerForced ?? false) return; var avoidGrid = map.GetComponent<TickManager>()?.avoidGrid; if (avoidGrid == null) return; if (avoidGrid.ShouldAvoid(map, c)) __result = Danger.Deadly; } } [HarmonyPatch] static class WorkGiver_Scanner_HasJobOnCell_Patches { static bool ShouldAvoid(Pawn pawn, IntVec3 cell, bool forced) { if (forced || pawn.IsColonist == false) return false; if (Tools.ShouldAvoidZombies(pawn) == false) return false; var tickManager = pawn.Map?.GetComponent<TickManager>(); if (tickManager == null) return false; return tickManager.avoidGrid.ShouldAvoid(pawn.Map, cell); } static IEnumerable<CodeInstruction> Transpiler(IEnumerable<CodeInstruction> instructions, ILGenerator generator) { var label = generator.DefineLabel(); yield return new CodeInstruction(OpCodes.Ldarg_1); yield return new CodeInstruction(OpCodes.Ldarg_2); yield return new CodeInstruction(OpCodes.Ldarg_3); yield return new CodeInstruction(OpCodes.Call, SymbolExtensions.GetMethodInfo(() => ShouldAvoid(null, default, false))); yield return new CodeInstruction(OpCodes.Brfalse, label); yield return new CodeInstruction(OpCodes.Ldc_I4_0); yield return new CodeInstruction(OpCodes.Ret); var list = instructions.ToList(); list[0].labels.Add(label); foreach (var instruction in list) yield return instruction; } static IEnumerable<MethodBase> TargetMethods() { return GenTypes.AllSubclasses(typeof(WorkGiver_Scanner)) .Select(type => type.GetMethod("HasJobOnCell", AccessTools.all | BindingFlags.DeclaredOnly)) .Where(method => method != null) .Cast<MethodBase>(); } } [HarmonyPatch] static class WorkGiver_Scanner_JobOnCell_Patches { static bool ShouldAvoid(Pawn pawn, IntVec3 cell, bool forced) { if (forced || pawn.IsColonist == false) return false; if (Tools.ShouldAvoidZombies(pawn) == false) return false; var tickManager = pawn.Map?.GetComponent<TickManager>(); if (tickManager == null) return false; return tickManager.avoidGrid.ShouldAvoid(pawn.Map, cell); } static IEnumerable<CodeInstruction> Transpiler(IEnumerable<CodeInstruction> instructions, ILGenerator generator) { var label = generator.DefineLabel(); yield return new CodeInstruction(OpCodes.Ldarg_1); yield return new CodeInstruction(OpCodes.Ldarg_2); yield return new CodeInstruction(OpCodes.Ldarg_3); yield return new CodeInstruction(OpCodes.Call, SymbolExtensions.GetMethodInfo(() => ShouldAvoid(null, default, false))); yield return new CodeInstruction(OpCodes.Brfalse, label); yield return new CodeInstruction(OpCodes.Ldnull); yield return new CodeInstruction(OpCodes.Ret); var list = instructions.ToList(); list[0].labels.Add(label); foreach (var instruction in list) yield return instruction; } static IEnumerable<MethodBase> TargetMethods() { return GenTypes.AllSubclasses(typeof(WorkGiver_Scanner)) .Select(type => type.GetMethod(nameof(WorkGiver_Scanner.JobOnCell), AccessTools.all | BindingFlags.DeclaredOnly)) .Where(method => method != null) .Cast<MethodBase>(); } } [HarmonyPatch] static class WorkGiver_Scanner_HasJobOnThing_Patches { static bool ShouldAvoid(Pawn pawn, Thing thing, bool forced) { if (forced || pawn.IsColonist == false) return false; if (Tools.ShouldAvoidZombies(pawn) == false) return false; var tickManager = pawn.Map?.GetComponent<TickManager>(); if (tickManager == null) return false; return tickManager.avoidGrid.ShouldAvoid(thing.Map, thing.Position); } static IEnumerable<CodeInstruction> Transpiler(IEnumerable<CodeInstruction> instructions, ILGenerator generator) { var label = generator.DefineLabel(); yield return new CodeInstruction(OpCodes.Ldarg_1); yield return new CodeInstruction(OpCodes.Ldarg_2); yield return new CodeInstruction(OpCodes.Ldarg_3); yield return new CodeInstruction(OpCodes.Call, SymbolExtensions.GetMethodInfo(() => ShouldAvoid(null, null, false))); yield return new CodeInstruction(OpCodes.Brfalse, label); yield return new CodeInstruction(OpCodes.Ldc_I4_0); yield return new CodeInstruction(OpCodes.Ret); var list = instructions.ToList(); list[0].labels.Add(label); foreach (var instruction in list) yield return instruction; } static IEnumerable<MethodBase> TargetMethods() { return GenTypes.AllSubclasses(typeof(WorkGiver_Scanner)) .Select(type => type.GetMethod(nameof(WorkGiver_Scanner.HasJobOnThing), AccessTools.all | BindingFlags.DeclaredOnly)) .Where(method => method != null) .Cast<MethodBase>(); } } [HarmonyPatch] static class WorkGiver_Scanner_JobOnThing_Patches { static bool ShouldAvoid(Pawn pawn, Thing thing, bool forced) { if (forced || pawn.IsColonist == false) return false; if (Tools.ShouldAvoidZombies(pawn) == false) return false; var tickManager = pawn.Map?.GetComponent<TickManager>(); if (tickManager == null) return false; return tickManager.avoidGrid.ShouldAvoid(thing.Map, thing.Position); } static IEnumerable<CodeInstruction> Transpiler(IEnumerable<CodeInstruction> instructions, ILGenerator generator) { var label = generator.DefineLabel(); yield return new CodeInstruction(OpCodes.Ldarg_1); yield return new CodeInstruction(OpCodes.Ldarg_2); yield return new CodeInstruction(OpCodes.Ldarg_3); yield return new CodeInstruction(OpCodes.Call, SymbolExtensions.GetMethodInfo(() => ShouldAvoid(null, null, false))); yield return new CodeInstruction(OpCodes.Brfalse, label); yield return new CodeInstruction(OpCodes.Ldnull); yield return new CodeInstruction(OpCodes.Ret); var list = instructions.ToList(); list[0].labels.Add(label); foreach (var instruction in list) yield return instruction; } static IEnumerable<MethodBase> TargetMethods() { return GenTypes.AllSubclasses(typeof(WorkGiver_Scanner)) .Select(type => type.GetMethod(nameof(WorkGiver_Scanner.JobOnThing), AccessTools.all | BindingFlags.DeclaredOnly)) .Where(method => method != null) .Cast<MethodBase>(); } } // patch to remove log error "xxx pathing to destroyed thing (zombie)" // [HarmonyPatch(typeof(Pawn_PathFollower))] [HarmonyPatch(nameof(Pawn_PathFollower.StartPath))] static class Pawn_PathFollower_StartPath_Patch { static bool ThingDestroyedAndNotZombie(LocalTargetInfo info) { return info.ThingDestroyed && (info.Thing is Zombie) == false; } static PawnPosture GetPawnPosture(Pawn pawn) { if (pawn is Zombie zombie && zombie.health.Downed) return PawnPosture.LayingOnGroundNormal; return PawnPosture.Standing; } static IEnumerable<CodeInstruction> Transpiler(IEnumerable<CodeInstruction> instructions) { var from = typeof(LocalTargetInfo).PropertyGetter(nameof(LocalTargetInfo.ThingDestroyed)); var to = SymbolExtensions.GetMethodInfo(() => ThingDestroyedAndNotZombie(null)); var list = Tools.DownedReplacer(instructions).ToList(); var i = list.FirstIndexOf(instr => instr.Calls(from)); if (i < 0 || i >= list.Count()) { Error("Cannot find " + from.FullDescription() + " in Pawn_PathFollower.StartPath"); return list.AsEnumerable(); } list[i - 1].opcode = OpCodes.Ldarg_1; list[i].operand = to; i = list.FindLastIndex(instr => instr.LoadsConstant(0)); list.RemoveAt(i); list.InsertRange(i, new CodeInstruction[] { new CodeInstruction(OpCodes.Ldarg_0), new CodeInstruction(OpCodes.Ldfld, typeof(Pawn_PathFollower).Field("pawn")), new CodeInstruction(OpCodes.Call, SymbolExtensions.GetMethodInfo(() => GetPawnPosture(null))) }); return list.AsEnumerable(); } } // patch to add a pheromone info section to the rimworld cell inspector // [HarmonyPatch(typeof(EditWindow_DebugInspector))] [HarmonyPatch(nameof(EditWindow_DebugInspector.CurrentDebugString))] static class EditWindow_DebugInspector_CurrentDebugString_Patch { static int[] colonyPoints = new int[3]; static int colonyPointsCounter = 0; static void DebugGrid(StringBuilder builder) { if (Current.Game == null) return; var map = Current.Game.CurrentMap; if (map == null) return; var pos = UI.MouseCell(); var tickManager = map.GetComponent<TickManager>(); if (tickManager == null) return; if (colonyPointsCounter-- < 0) { colonyPointsCounter = 60; colonyPoints = Tools.ColonyPoints(); } var maxCount = tickManager.GetMaxZombieCount(); var threatLevel = ZombieWeather.GetThreatLevel(map); var realCount = Mathf.FloorToInt(maxCount * threatLevel); _ = builder.AppendLine("---"); _ = builder.AppendLine($"Center of Interest: {tickManager.centerOfInterest.x}/{tickManager.centerOfInterest.z}"); _ = builder.AppendLine($"Colonist points: {colonyPoints[0]}"); _ = builder.AppendLine($"Weapon points: {colonyPoints[1]}"); _ = builder.AppendLine($"Defense points: {colonyPoints[2]}"); _ = builder.AppendLine($"Max zombie count: {maxCount}"); if (ZombieSettings.Values.useDynamicThreatLevel) _ = builder.AppendLine($"Zombie threat level: {Mathf.FloorToInt(10000 * threatLevel) / 100f}%"); else _ = builder.AppendLine("Zombie threat level off"); _ = builder.AppendLine($"Total zombie count: {tickManager.ZombieCount()} out of {realCount}"); _ = builder.AppendLine(""); AccessTools.GetFieldNames(typeof(IncidentParameters)).Do(name => { var value = Traverse.Create(tickManager.incidentInfo.parameters).Field(name).GetValue(); _ = builder.AppendLine($"{name}: {value}"); }); _ = builder.AppendLine(""); if (pos.InBounds(map) == false) return; if (Tools.ShouldAvoidZombies()) { var avoidGrid = map.GetComponent<TickManager>().avoidGrid; _ = builder.AppendLine($"Avoid cost: {avoidGrid.GetCosts()[pos.x + pos.z * map.Size.x]}"); } var info = ZombieWanderer.GetMapInfo(map); _ = builder.AppendLine($"Parent normal: {info.GetParent(pos, false)}"); _ = builder.AppendLine($"Parent via doors: {info.GetParent(pos, true)}"); _ = builder.AppendLine($"Parent raw: {info.GetDirectDebug(pos)}"); var cell = map.GetGrid().GetPheromone(pos, false); if (cell != null) { var realZombieCount = pos.GetThingList(map).OfType<Zombie>().Count(); var sb = new StringBuilder(); _ = sb.Append($"Zombie grid: {cell.zombieCount} zombies"); if (cell.zombieCount != realZombieCount) _ = sb.Append($" (real {realZombieCount})"); _ = builder.AppendLine(sb.ToString()); var now = Tools.Ticks(); var tdiff = (cell.timestamp - now).ToString(); if (tdiff.StartsWith("-")) tdiff = tdiff.ReplaceFirst("-", "- "); else tdiff = "+ " + tdiff; _ = builder.AppendLine($"Pheromone timestamp {cell.timestamp} = {now} {tdiff}"); } else _ = builder.AppendLine($"{pos.x} {pos.z}: empty"); var pathing = map.GetComponent<TickManager>()?.zombiePathing; if (pathing != null && pos.InBounds(map)) { var wrong = pathing.backpointingRegions.Count != pathing.backpointingRegionsIndices.Count; _ = builder.AppendLine($"Smart wandering seeds: {pathing.backpointingRegions.Count(br => br.parentIdx == -1)}"); _ = builder.AppendLine($"Smart wandering regions: {pathing.backpointingRegions.Count} {(wrong ? " [count wrong]" : "")}"); var from = IntVec3.Invalid; var region = map.regionGrid.GetRegionAt_NoRebuild_InvalidAllowed(pos); _ = builder.AppendLine($"Smart wandering region id: {region?.id.ToString() ?? "null"}"); if (region != null) { if (pathing.backpointingRegionsIndices.TryGetValue(region, out var idx)) from = pathing.backpointingRegions[idx].cell; else idx = -1; _ = builder.AppendLine($"Smart wandering index: {idx}"); } var destination = pathing.GetWanderDestination(pos); var fromStr = from.IsValid ? from.ToString() : "null"; var destStr = destination.IsValid ? destination.ToString() : "null"; _ = builder.AppendLine($"Smart wandering {fromStr} -> {destStr}"); } var gridSum = GenAdj.AdjacentCellsAndInside.Select(vec => pos + vec) .Where(c => c.InBounds(map)) .Select(c => map.GetGrid().GetZombieCount(c)) .Sum(); var realSum = GenAdj.AdjacentCellsAndInside.Select(vec => pos + vec) .Where(c => c.InBounds(map)) .Select(c => map.thingGrid.ThingsListAtFast(c).OfType<Zombie>().Count()) .Sum(); _ = builder.AppendLine($"Rage factor: grid={gridSum}, real={realSum}"); map.thingGrid.ThingsListAtFast(pos).OfType<Zombie>().Do(zombie => { var currPos = zombie.Position; var gotoPos = zombie.pather.Moving ? zombie.pather.Destination.Cell : IntVec3.Invalid; var wanderTo = zombie.wanderDestination; var sb = new StringBuilder(); _ = sb.Append($"Zombie {zombie.Name.ToStringShort} at {currPos.x},{currPos.z}"); _ = sb.Append($", {zombie.state.ToString().ToLower()}"); if (zombie.raging > 0) _ = sb.Append($", raging[{zombie.raging - GenTicks.TicksAbs}] "); _ = sb.Append($", going to {gotoPos.x},{gotoPos.z}"); _ = sb.Append($" (wander dest {wanderTo.x},{wanderTo.z})"); _ = builder.AppendLine(sb.ToString()); }); } static bool Prefix(ref string __result) { if (Current.Game == null) { __result = ""; return false; } return true; } static IEnumerable<CodeInstruction> Transpiler(IEnumerable<CodeInstruction> instructions) { var list = instructions.ToList(); var m_ToString = AccessTools.Method(typeof(object), "ToString"); var idx = list.FindLastIndex(instr => instr.Calls(m_ToString)); if (idx > 0) { list.Insert(idx++, new CodeInstruction(OpCodes.Call, SymbolExtensions.GetMethodInfo(() => DebugGrid(null)))); list.Insert(idx++, list[idx - 3].Clone()); } else Error("Unexpected code in patch " + MethodBase.GetCurrentMethod().DeclaringType); return list.AsEnumerable(); } } // patch to add our actions to the debug action menu // [HarmonyPatch(typeof(DebugWindowsOpener))] [HarmonyPatch(nameof(DebugWindowsOpener.ToggleDebugActionsMenu))] static class DebugWindowsOpener_ToggleDebugActionsMenu_Patch { [HarmonyPriority(Priority.First)] static IEnumerable<CodeInstruction> Transpiler(IEnumerable<CodeInstruction> instructions) { var from = AccessTools.Constructor(typeof(Dialog_DebugActionsMenu)); var to = AccessTools.Constructor(typeof(Dialog_ZombieDebugActionMenu)); return instructions.MethodReplacer(from, to); } } // patch for adding zombie faction to existing games // [HarmonyPatch(typeof(FactionManager))] [HarmonyPatch(nameof(FactionManager.ExposeData))] static class FactionManager_ExposeData_Patch { static void Postfix(List<Faction> ___allFactions) { if (Scribe.mode == LoadSaveMode.Saving) return; if (___allFactions == null) return; var factionDefs = ___allFactions.Select(f => f.def).ToList(); if (factionDefs.Contains(ZombieDefOf.Zombies) == false) { var parms = new FactionGeneratorParms(ZombieDefOf.Zombies); var zombies = FactionGenerator.NewGeneratedFaction(parms); foreach (var faction in ___allFactions) { var rel1 = new FactionRelation() { other = faction, baseGoodwill = 0, kind = FactionRelationKind.Hostile }; zombies.relations.Add(rel1); var rel2 = new FactionRelation() { other = zombies, baseGoodwill = 0, kind = FactionRelationKind.Hostile }; faction.relations.Add(rel2); } ___allFactions.Add(zombies); } } } // patch for detecting if a pawn enters a new cell // [HarmonyPatch(typeof(Thing))] [HarmonyPatch(nameof(Thing.Position), MethodType.Setter)] static class Thing_Position_Patch { static readonly MentalStateDef def1 = MentalStateDefOf.Manhunter; static readonly MentalStateDef def2 = MentalStateDefOf.ManhunterPermanent; static readonly ThingDef stickyGooDef = ThingDef.Named("StickyGoo"); static void Prefix(Thing __instance, IntVec3 value) { if (!(__instance is Pawn pawn)) return; var map = pawn.Map; if (map == null) return; var pos = pawn.Position; if (pos == value) return; if (pawn is Zombie zombie) { var grid = map.GetGrid(); // tanky zombies leave pherome trace too so other zombies follow // if (zombie.IsTanky) { var fadeOff = Tools.PheromoneFadeoff(); var now = Tools.Ticks(); var radius = Constants.TANKY_PHEROMONE_RADIUS; var dx = pos.x - value.x; var dz = pos.z - value.z; var r2 = radius * radius; Tools.GetCircle(radius).Do(vec => { var vx = Math.Sign(vec.x); var vz = Math.Sign(vec.z); var vlen = vec.LengthHorizontalSquared; if ((vx == 0 || vx == dx) && (vz == 0 || vz == dz) && vlen > 1f) { var offset = GenMath.LerpDouble(0f, r2, fadeOff / 8f, fadeOff / 4f, vlen); grid.BumpTimestamp(value + vec, now - (long)offset); } }); } else { var newCell = grid.GetPheromone(value, false); if (newCell != null && newCell.zombieCount > 0) { newCell.timestamp -= newCell.zombieCount * Constants.ZOMBIE_CLOGGING_FACTOR; var notOlderThan = Tools.Ticks() - Tools.PheromoneFadeoff(); newCell.timestamp = Math.Max(newCell.timestamp, notOlderThan); } } // dark slimers leave dark slime behind them // if (zombie.isDarkSlimer) _ = FilthMaker.TryMakeFilth(value, map, ThingDef.Named("TarSlime"), zombie.Name.ToStringShort, 1); return; } // manhunting will always trigger senses // if (pawn.MentalState == null || (pawn.MentalState.def != def1 && pawn.MentalState.def != def2)) { if (ZombieSettings.Values.attackMode == AttackMode.OnlyHumans) if (pawn.RaceProps.Humanlike == false || pawn.RaceProps.IsFlesh == false || AlienTools.IsFleshPawn(pawn) == false) return; if (ZombieSettings.Values.attackMode == AttackMode.OnlyColonists) if (pawn.IsColonist == false) return; } // apply toxic splatter damage var toxity = 0.05f * pawn.GetStatValue(StatDefOf.ToxicSensitivity, true); if (toxity > 0f) { pawn.Position.GetThingList(pawn.Map).Where(thing => thing.def == stickyGooDef).Do(thing => { HealthUtility.AdjustSeverity(pawn, HediffDefOf.ToxicBuildup, toxity); }); } // leave pheromone trail if (Tools.HasInfectionState(pawn, InfectionState.Infecting) == false) { var now = Tools.Ticks(); var radius = Tools.RadiusForPawn(pawn); var grid = pawn.Map.GetGrid(); Tools.GetCircle(radius).Do(vec => grid.BumpTimestamp(value + vec, now - (long)(2f * vec.LengthHorizontal))); } } } // turrets consume less steam // [HarmonyPatch(typeof(CompRefuelable))] [HarmonyPatch(nameof(CompRefuelable.ConsumeFuel))] public static class CompRefuelable_ConsumeFuel_Patch { static void Prefix(CompRefuelable __instance, ref float amount) { if (!(__instance.parent is Building_Turret turret)) return; amount -= amount * ZombieSettings.Values.reducedTurretConsumption; } } // downed zombies only scratch feet parts // [HarmonyPatch(typeof(DamageWorker_Scratch))] [HarmonyPatch(nameof(DamageWorker_Scratch.ChooseHitPart))] public static class DamageWorker_Scratch_ChooseHitPart_Patch { static void Prefix(ref DamageInfo dinfo) { if (!(dinfo.Instigator is Zombie zombie) || zombie.health.Downed == false) return; dinfo.SetBodyRegion(BodyPartHeight.Bottom, BodyPartDepth.Outside); } } [HarmonyPatch(typeof(DamageWorker_Bite))] [HarmonyPatch(nameof(DamageWorker_Bite.ChooseHitPart))] public static class DamageWorker_Bite_ChooseHitPart_Patch { static void Prefix(ref DamageInfo dinfo) { if (!(dinfo.Instigator is Zombie zombie) || zombie.health.Downed == false) return; dinfo.SetBodyRegion(BodyPartHeight.Bottom, BodyPartDepth.Outside); } } // patch to make infected colonists have no needs // [HarmonyPatch(typeof(Need))] [HarmonyPatch(nameof(Need.CurLevel), MethodType.Setter)] public static class Need_CurLevel_Patch { // this is set periodically from Alerts.Alert_ZombieInfection public static HashSet<Pawn> infectedColonists = new HashSet<Pawn>(); static bool ShouldBeAverageNeed(Pawn pawn) { return infectedColonists.Contains(pawn); } [HarmonyPriority(Priority.First)] static IEnumerable<CodeInstruction> Transpiler(ILGenerator il, IEnumerable<CodeInstruction> instructions) { var average = il.DeclareLocal(typeof(float)); var originalStart = il.DefineLabel(); yield return new CodeInstruction(OpCodes.Ldarg_1); yield return new CodeInstruction(OpCodes.Stloc, average); yield return new CodeInstruction(OpCodes.Ldarg_0); yield return new CodeInstruction(OpCodes.Ldfld, typeof(Need).Field("pawn")); yield return new CodeInstruction(OpCodes.Call, SymbolExtensions.GetMethodInfo(() => ShouldBeAverageNeed(null))); yield return new CodeInstruction(OpCodes.Brfalse, originalStart); yield return new CodeInstruction(OpCodes.Ldc_R4, 0.5f); yield return new CodeInstruction(OpCodes.Stloc, average); var found = false; var firstTime = true; foreach (var instruction in instructions) { if (firstTime) instruction.labels.Add(originalStart); if (instruction.IsLdarg(1)) { instruction.opcode = OpCodes.Ldloc; instruction.operand = average; found = true; } yield return instruction; firstTime = false; } if (!found) Error("Unexpected code in patch " + MethodBase.GetCurrentMethod().DeclaringType); } } // patch to make infected colonists have no mental breaks // [HarmonyPatch(typeof(MentalStateHandler))] [HarmonyPatch(nameof(MentalStateHandler.TryStartMentalState))] static class MentalStateHandler_TryStartMentalState_Patch { static bool NoMentalState(Pawn pawn) { return Need_CurLevel_Patch.infectedColonists.Contains(pawn); } [HarmonyPriority(Priority.First)] static IEnumerable<CodeInstruction> Transpiler(ILGenerator il, IEnumerable<CodeInstruction> instructions) { var originalStart = il.DefineLabel(); yield return new CodeInstruction(OpCodes.Ldarg_0); yield return new CodeInstruction(OpCodes.Ldfld, typeof(MentalStateHandler).Field("pawn")); yield return new CodeInstruction(OpCodes.Call, SymbolExtensions.GetMethodInfo(() => NoMentalState(null))); yield return new CodeInstruction(OpCodes.Brfalse, originalStart); yield return new CodeInstruction(OpCodes.Ldc_I4_0); yield return new CodeInstruction(OpCodes.Ret); var firstTime = true; foreach (var instruction in instructions) { if (firstTime) instruction.labels.Add(originalStart); yield return instruction; firstTime = false; } } } // patch to make infected colonists feel no pain // [HarmonyPatch(typeof(HediffSet))] [HarmonyPatch(nameof(HediffSet.PainTotal), MethodType.Getter)] static class HediffSet_CalculatePain_Patch { static bool Prefix(HediffSet __instance, ref float __result) { if (Need_CurLevel_Patch.infectedColonists.Contains(__instance.pawn)) { __result = 0f; return false; } return true; } } // patch to make infected colonists have full capacity // [HarmonyPatch(typeof(PawnCapacitiesHandler))] [HarmonyPatch(nameof(PawnCapacitiesHandler.GetLevel))] static class PawnCapacitiesHandler_GetLevel_Patch { static bool FullLevel(Pawn pawn) { if (pawn.health.Dead) return false; return Need_CurLevel_Patch.infectedColonists.Contains(pawn); } [HarmonyPriority(Priority.First)] static IEnumerable<CodeInstruction> Transpiler(ILGenerator il, IEnumerable<CodeInstruction> instructions) { var originalStart = il.DefineLabel(); yield return new CodeInstruction(OpCodes.Ldarg_0); yield return new CodeInstruction(OpCodes.Ldfld, typeof(PawnCapacitiesHandler).Field("pawn")); yield return new CodeInstruction(OpCodes.Call, SymbolExtensions.GetMethodInfo(() => FullLevel(null))); yield return new CodeInstruction(OpCodes.Brfalse, originalStart); yield return new CodeInstruction(OpCodes.Ldc_R4, 1f); yield return new CodeInstruction(OpCodes.Ret); var firstTime = true; foreach (var instruction in instructions) { if (firstTime) instruction.labels.Add(originalStart); yield return instruction; firstTime = false; } } } // patch to reduce instant zombie infections for pawns in incidents // [HarmonyPatch(typeof(IncidentWorker))] [HarmonyPatch(nameof(IncidentWorker.TryExecute))] static class IncidentWorker_TryExecute_Patch { static void Postfix(IncidentParms parms) { if (parms.pawnGroups == null) return; var f = GenMath.LerpDoubleClamped(0, 5, 100, 0, Tools.Difficulty()); parms.pawnGroups.Keys.DoIf(_ => Rand.Chance(f), pawn => pawn.health.hediffSet .GetHediffs<Hediff_Injury_ZombieBite>() .Do(bite => { bite.mayBecomeZombieWhenDead = false; var tendDuration = bite.TryGetComp<HediffComp_Zombie_TendDuration>(); tendDuration?.ZombieInfector.MakeHarmless(); }) ); } } // patch to allow spawning zombie raids with debug tools // [HarmonyPatch(typeof(IncidentWorker_Raid))] [HarmonyPatch(nameof(IncidentWorker_Raid.TryExecuteWorker))] static class IncidentWorker_Raid_TryExecuteWorker_Patch { [HarmonyPriority(Priority.First)] static bool Prefix(ref bool __result, IncidentParms parms) { if (parms?.faction?.def != ZombieDefOf.Zombies) return true; var oldMode = ZombieSettings.Values.spawnHowType; ZombieSettings.Values.spawnHowType = parms.raidArrivalMode.walkIn ? SpawnHowType.FromTheEdges : SpawnHowType.AllOverTheMap; _ = ZombiesRising.TryExecute(Find.CurrentMap, Mathf.FloorToInt(parms.points), parms.spawnCenter, false, false); ZombieSettings.Values.spawnHowType = oldMode; __result = false; return false; } } // patch to let incidents spawn infected [HarmonyPatch(typeof(PawnGroupKindWorker))] [HarmonyPatch(nameof(PawnGroupKindWorker.GeneratePawns))] [HarmonyPatch(new[] { typeof(PawnGroupMakerParms), typeof(PawnGroupMaker), typeof(bool) })] static class IncidentWorker_Patches { static void Postfix(List<Pawn> __result) { if (__result == null || Rand.Chance(ZombieSettings.Values.infectedRaidsChance) == false) return; __result.DoIf(pawn => pawn.RaceProps.Humanlike, Tools.AddZombieInfection); } } // patch to allow spawning zombies with debug tools // [HarmonyPatch(typeof(PawnGenerator))] [HarmonyPatch(nameof(PawnGenerator.GenerateNewPawnInternal))] static class PawnGenerator_GenerateNewPawnInternal_Patch { [HarmonyPriority(Priority.First)] static bool Prefix(ref PawnGenerationRequest request, ref Pawn __result) { if (request.Faction?.def != ZombieDefOf.Zombies) return true; Zombie zombie = null; var map = Find.CurrentMap; var it = ZombieGenerator.SpawnZombieIterativ(map.Center, map, ZombieType.Random, z => zombie = z); while (it.MoveNext()) ; __result = zombie; return false; } } // patches to disallow interacting with zombies or zombiecorpses // [HarmonyPatch(typeof(WorkGiver_Haul))] [HarmonyPatch(nameof(WorkGiver_Haul.JobOnThing))] static class WorkGiver_Haul_JobOnThing_Patch { [HarmonyPriority(Priority.First)] static bool Prefix(Thing t, bool forced, ref Job __result) { if (forced) return true; if (t is ZombieCorpse corpse) { __result = null; return false; } return true; } } [HarmonyPatch(typeof(ReservationManager))] [HarmonyPatch(nameof(ReservationManager.CanReserve))] static class ReservationManager_CanReserve_Patch { [HarmonyPriority(Priority.First)] static bool Prefix(LocalTargetInfo target, ref bool __result) { if (target.HasThing && target.Thing is Zombie zombie && zombie.wasMapPawnBefore == false) { __result = false; return false; } return true; } } [HarmonyPatch(typeof(ReservationManager))] [HarmonyPatch(nameof(ReservationManager.Reserve))] static class ReservationManager_Reserve_Patch { [HarmonyPriority(Priority.First)] static bool Prefix(LocalTargetInfo target, ref bool __result) { if (target.HasThing) { //if (target.Thing is Zombie || target.Thing is ZombieCorpse) if (target.Thing is Zombie) { __result = false; return false; } } return true; } } // patch so you cannot strip zombies // [HarmonyPatch(typeof(Pawn))] [HarmonyPatch(nameof(Pawn.AnythingToStrip))] static class Pawn_AnythingToStrip_Patch { [HarmonyPriority(Priority.First)] static bool Prefix(Pawn __instance, ref bool __result) { if (__instance is Zombie) { __result = false; return false; } return true; } } // patch to not show forbidden red cross icon on zombies // [HarmonyPatch(typeof(ForbidUtility))] [HarmonyPatch(nameof(ForbidUtility.IsForbidden))] [HarmonyPatch(new Type[] { typeof(Thing), typeof(Faction) })] static class ForbidUtility_IsForbidden_Patch { [HarmonyPriority(Priority.First)] static bool Prefix(Thing t, ref bool __result) { //if (t is Zombie || t is ZombieCorpse) if (t is Zombie) { __result = true; return false; } return true; } } // patch to hide zombie names // [HarmonyPatch(typeof(GenMapUI))] [HarmonyPatch(nameof(GenMapUI.DrawPawnLabel))] [HarmonyPatch(new Type[] { typeof(Pawn), typeof(Vector2), typeof(float), typeof(float), typeof(Dictionary<string, string>), typeof(GameFont), typeof(bool), typeof(bool) })] [StaticConstructorOnStartup] static class GenMapUI_DrawPawnLabel_Patch { static bool Prefix(Pawn pawn) { if (!(pawn is Zombie zombie)) return true; return zombie.wasMapPawnBefore; } } // patch to fix null exceptions for zombie panels // [HarmonyPatch(typeof(MainTabWindow_Inspect))] [HarmonyPatch(nameof(MainTabWindow_Inspect.CurTabs), MethodType.Getter)] static class MainTabWindow_Inspect_CurTabs_Patch { static void Postfix(ref IEnumerable<InspectTabBase> __result) { if (__result == null) __result = new List<InspectTabBase>(); } } // patch to make zombies appear to be never "down" if self-healing is on // to get original state, use pawn.health.Downed instead // [HarmonyPatch(typeof(Pawn))] [HarmonyPatch(nameof(Pawn.Downed), MethodType.Getter)] static class Pawn_Downed_Patch { [HarmonyPriority(Priority.First)] static bool Prefix(Pawn __instance, ref bool __result) { if (ZombieSettings.Values.doubleTapRequired == false) return true; if (!(__instance is Zombie zombie)) return true; __result = false; return false; } } // patch to keep shooting even if a zombie is down (only if self-healing is on) // [HarmonyPatch(typeof(Pawn))] [HarmonyPatch(nameof(Pawn.ThreatDisabled))] static class Pawn_ThreatDisabled_Patch { [HarmonyPriority(Priority.First)] static bool Prefix(Pawn __instance, ref bool __result) { if (!(__instance is Zombie zombie)) return true; __result = !zombie.Spawned; return false; } } [HarmonyPatch] static class Toils_Combat_FollowAndMeleeAttack_KillIncappedTarget_Patch { static bool IncappedTargetCheck(Job curJob, Pawn target) { if (target is Zombie) return true; return curJob.killIncappedTarget; } static MethodBase TargetMethod() { return typeof(Toils_Combat).InnerMethodsStartingWith("<FollowAndMeleeAttack>b__0").First(); } [HarmonyPriority(Priority.First)] static IEnumerable<CodeInstruction> Transpiler(IEnumerable<CodeInstruction> instructions) { var m_get_Downed = typeof(Pawn).PropertyGetter(nameof(Pawn.Downed)); var f_killIncappedTarget = typeof(Job).Field(nameof(Job.killIncappedTarget)); var found1 = false; var found2 = false; CodeInstruction last = null; CodeInstruction localPawnInstruction = null; foreach (var instruction in instructions) { if (instruction.Calls(m_get_Downed)) { localPawnInstruction = new CodeInstruction(last); found1 = true; } if (instruction.LoadsField(f_killIncappedTarget) && localPawnInstruction != null) { yield return localPawnInstruction; instruction.opcode = OpCodes.Call; instruction.operand = SymbolExtensions.GetMethodInfo(() => IncappedTargetCheck(null, null)); found2 = true; } yield return instruction; last = instruction; } if (!found1 || !found2) Error("Unexpected code in patch " + MethodBase.GetCurrentMethod().DeclaringType); } } [HarmonyPatch(typeof(Stance_Warmup))] [HarmonyPatch(nameof(Stance_Warmup.StanceTick))] static class Stance_Warmup_StanceTick_Patch { [HarmonyPriority(Priority.First)] static IEnumerable<CodeInstruction> Transpiler(IEnumerable<CodeInstruction> instructions) { return Tools.DownedReplacer(instructions); } } [HarmonyPatch] static class Toils_Jump_JumpIfTargetDownedDistant_Patch { static IEnumerable<MethodBase> TargetMethods() { var m_Downed = AccessTools.PropertyGetter(typeof(Pawn), nameof(Pawn.Downed)); return typeof(Toils_Jump) .InnerMethodsStartingWith("<JumpIfTargetDowned>") .Where(method => PatchProcessor.GetCurrentInstructions(method).Any(code => code.Calls(m_Downed))); } [HarmonyPriority(Priority.First)] static IEnumerable<CodeInstruction> Transpiler(IEnumerable<CodeInstruction> instructions) { return Tools.DownedReplacer(instructions); } } [HarmonyPatch(typeof(Pawn_MindState))] [HarmonyPatch(nameof(Pawn_MindState.MeleeThreatStillThreat), MethodType.Getter)] static class Pawn_MindState_MeleeThreatStillThreat_Patch { [HarmonyPriority(Priority.First)] static IEnumerable<CodeInstruction> Transpiler(IEnumerable<CodeInstruction> instructions) { return Tools.DownedReplacer(instructions); } } [HarmonyPatch(typeof(JobDriver_Wait))] [HarmonyPatch(nameof(JobDriver_Wait.CheckForAutoAttack))] static class JobDriver_Wait_CheckForAutoAttack_Patch { [HarmonyPriority(Priority.First)] static IEnumerable<CodeInstruction> Transpiler(IEnumerable<CodeInstruction> instructions) { return Tools.DownedReplacer(instructions, 1); } } [HarmonyPatch] static class JobDriver_AttackStatic_TickAction_Patch { static IEnumerable<MethodBase> TargetMethods() { var m_Downed = AccessTools.PropertyGetter(typeof(Pawn), nameof(Pawn.Downed)); return typeof(JobDriver_AttackStatic) .InnerMethodsStartingWith("*") .Where(method => PatchProcessor.GetCurrentInstructions(method).Any(code => code.Calls(m_Downed))); } [HarmonyPriority(Priority.First)] static IEnumerable<CodeInstruction> Transpiler(IEnumerable<CodeInstruction> instructions) { return Tools.DownedReplacer(instructions); } } [HarmonyPatch(typeof(TargetingParameters))] [HarmonyPatch(nameof(TargetingParameters.CanTarget))] static class TargetingParameters_CanTarget_Patch { [HarmonyPriority(Priority.First)] static IEnumerable<CodeInstruction> Transpiler(IEnumerable<CodeInstruction> instructions) { return Tools.DownedReplacer(instructions); } } // makes downed zombie crawl rotated to their destination // [HarmonyPatch(typeof(PawnDownedWiggler))] [HarmonyPatch(nameof(PawnDownedWiggler.WigglerTick))] static class PawnDownedWiggler_WigglerTick_Patch { static void Postfix(PawnDownedWiggler __instance, Pawn ___pawn) { if (!(___pawn is Zombie zombie) || zombie.health.Downed == false) return; var vec = ___pawn.pather.Destination.Cell - ___pawn.Position; var pos = ___pawn.DrawPos; __instance.downedAngle = vec.AngleFlat + 15f * Mathf.Sin(6f * pos.x) * Mathf.Cos(6f * pos.z); } } [HarmonyPatch(typeof(PawnRenderer))] [HarmonyPatch(nameof(PawnRenderer.BodyAngle))] static class PawnRenderer_BodyAngle_Patch { static bool Prefix(Pawn ___pawn, PawnDownedWiggler ___wiggler, ref float __result) { if (___pawn is Zombie zombie && zombie.health.Downed) { var angle = ___wiggler.downedAngle + 360; if (zombie.currentDownedAngle == -1) zombie.currentDownedAngle = angle; zombie.currentDownedAngle = (zombie.currentDownedAngle * 15 + angle) / 16; __result = zombie.currentDownedAngle; return false; } return true; } } [HarmonyPatch(typeof(Root_Play))] [HarmonyPatch(nameof(Root_Play.Update))] static class Root_Play_Update_Patch { static void Postfix() { var map = Find.CurrentMap; if (map == null) return; var tickManager = map.GetComponent<TickManager>(); if (tickManager == null) return; tickManager.UpdateElectricalHumming(); } } [HarmonyPatch(typeof(PawnRenderer))] [HarmonyPatch(nameof(PawnRenderer.RenderPawnAt))] [HarmonyPatch(new Type[] { typeof(Vector3), typeof(Rot4?), typeof(bool) })] static class PawnRenderer_RenderPawnAt_Patch { static readonly float moteAltitute = Altitudes.AltitudeFor(AltitudeLayer.MoteOverhead); static Vector3 leftEyeOffset = new Vector3(-0.092f, 0f, -0.08f); static Vector3 rightEyeOffset = new Vector3(0.092f, 0f, -0.08f); static Vector3 toxicAuraOffset = new Vector3(0f, 0f, 0.1f); const float leanAngle = 15f; static readonly Color white50 = new Color(1f, 1f, 1f, 0.5f); static readonly Mesh bodyMesh = MeshPool.GridPlane(new Vector2(1.5f, 1.5f)); static readonly Mesh bodyMesh_flipped = MeshPool.GridPlaneFlip(new Vector2(1.5f, 1.5f)); static readonly Mesh headMesh = MeshPool.GridPlane(new Vector2(1.5f, 1.5f)); static readonly Mesh headMesh_flipped = MeshPool.GridPlaneFlip(new Vector2(1.5f, 1.5f)); static readonly Mesh shieldMesh = MeshPool.GridPlane(new Vector2(2f, 2f)); static readonly Mesh shieldMesh_flipped = MeshPool.GridPlaneFlip(new Vector2(2f, 2f)); [HarmonyPriority(Priority.First)] static bool Prefix(PawnRenderer __instance, Vector3 drawLoc) { if (!(__instance.graphics.pawn is Zombie zombie)) return true; if (zombie.needsGraphics) { var tickManager = zombie.Map?.GetComponent<TickManager>(); if (tickManager != null) tickManager.AllZombies().DoIf(z => z.needsGraphics, z => { z.needsGraphics = false; ZombieGenerator.AssignNewGraphics(z); }); else { zombie.needsGraphics = false; ZombieGenerator.AssignNewGraphics(zombie); } } if (zombie.state == ZombieState.Emerging) { zombie.Render(__instance, drawLoc); return false; } return true; } [HarmonyPriority(Priority.First)] static IEnumerable<CodeInstruction> Transpiler(IEnumerable<CodeInstruction> instructions) { var list = instructions.ToList(); var ret = list.Last(); if (ret.opcode != OpCodes.Ret) Error("Expected ret in PawnRenderer.RenderPawnAt"); ret.opcode = OpCodes.Ldarg_0; list.Add(new CodeInstruction(OpCodes.Ldarg_1)); list.Add(CodeInstruction.Call(() => RenderExtras(null, Vector3.zero))); list.Add(new CodeInstruction(OpCodes.Ret)); return list.AsEnumerable(); } [HarmonyPriority(Priority.First)] static void Postfix(PawnRenderer __instance, Vector3 drawLoc) { if (!(__instance.graphics.pawn is Zombie zombie)) return; if (zombie.isAlbino && zombie.scream > 0) { var f1 = zombie.scream / 400f; var f2 = Mathf.Sin(Mathf.PI * f1); var f3 = Math.Max(0, Mathf.Sin(Mathf.PI * f1 * 1.5f)); var mat = new Material(Constants.SCREAM) { color = new Color(1f, 1f, 1f, f2) }; var size = f1 * 4f; var center = drawLoc + new Vector3(0, 0.1f, 0.25f); GraphicToolbox.DrawScaledMesh(Constants.screamMesh, mat, center, Quaternion.identity, size, size); mat = new Material(Constants.SCREAMSHADOW) { color = new Color(1f, 1f, 1f, f3) }; var q = Quaternion.AngleAxis(f2 * 360f, Vector3.up); GraphicToolbox.DrawScaledMesh(MeshPool.plane20, mat, center, q, 1.5f, 1.5f); } var lowConsciousness = zombie.consciousness <= Constants.MIN_CONSCIOUSNESS; if ((zombie.paralyzedUntil > 0 || lowConsciousness) && zombie.GetPosture() == PawnPosture.Standing) { var confLoc = drawLoc + new Vector3(0, moteAltitute / 2, 0.75f); if (zombie.Rotation == Rot4.West) confLoc.x -= 0.09f; if (zombie.Rotation == Rot4.East) confLoc.x += 0.09f; var t = GenTicks.TicksAbs; var n = t % 12; if (n > 6) n = 12 - n; var scale = 1f; var ticks = GenTicks.TicksAbs; if (zombie.paralyzedUntil > ticks) scale = Mathf.Clamp((zombie.paralyzedUntil - ticks) / (float)(GenDate.TicksPerHour / 4), 0, 1); GraphicToolbox.DrawScaledMesh(MeshPool.plane05, Constants.CONFUSED[n], confLoc, Quaternion.Euler(0, t, 0), scale, scale); } if (zombie.ropedBy != null && zombie.Spawned && zombie.Dead == false) { var f = zombie.RopingFactorTo(zombie.ropedBy); var n = f <= 0.5f ? 2 : (f <= 0.8f ? 1 : 0); var mat = Constants.RopeLineMat[n]; GenDraw.DrawLineBetween(zombie.DrawPos.Yto0(), zombie.ropedBy.DrawPos.Yto0(), AltitudeLayer.PawnRope.AltitudeFor(), mat, 0.2f); } } // we don't use a postfix so that someone that patches and skips RenderPawnAt will also skip RenderExtras static void RenderExtras(PawnRenderer renderer, Vector3 drawLoc) { if (!(renderer.graphics.pawn is Zombie zombie)) return; if (zombie.state == ZombieState.Emerging || zombie.GetPosture() != PawnPosture.Standing) return; // general zombie drawing Verse.TickManager tm = null; var orientation = zombie.Rotation; if (zombie.IsSuicideBomber) { tm = Find.TickManager; var currentTick = tm.TicksAbs; var interval = (int)zombie.bombTickingInterval; if (currentTick >= zombie.lastBombTick + interval) zombie.lastBombTick = currentTick; else if (currentTick <= zombie.lastBombTick + interval / 2) { if (zombie.state != ZombieState.Emerging) { var bombLightLoc = drawLoc + new Vector3(0, 0.1f, -0.2f); var scale = 1f; if (orientation == Rot4.South || orientation == Rot4.North) bombLightLoc.z += 0.05f; if (orientation == Rot4.North) { bombLightLoc.y -= 0.1f; scale = 1.5f; } if (orientation == Rot4.West) { bombLightLoc.x -= 0.25f; bombLightLoc.z -= 0.05f; } if (orientation == Rot4.East) { bombLightLoc.x += 0.25f; bombLightLoc.z -= 0.05f; } GraphicToolbox.DrawScaledMesh(MeshPool.plane10, Constants.BOMB_LIGHT, bombLightLoc, Quaternion.identity, scale, scale); } } } if (zombie.isHealer && zombie.state != ZombieState.Emerging && zombie.healInfo.Count > 0) { var i = 0; var isNotPaused = Find.TickManager.Paused == false; while (i < zombie.healInfo.Count) { // healing: |0%..100%.............0%| // being healed: |0%...........100%...........0%| // info.step: |0 40 80 120| var info = zombie.healInfo[i]; var healTarget = info.pawn; var healingIndex = (int)GenMath.LerpDoubleClamped(0, 80, Constants.healingMaterials.Length - 1, 0, info.step); var beingHealedIndex = (int)GenMath.LerpDoubleClamped(40, 120, 0, 9, info.step); if (beingHealedIndex >= Constants.BEING_HEALED.Length) beingHealedIndex = 9 - beingHealedIndex; var mat = Constants.healingMaterials[healingIndex]; var size = (zombie.DrawPos - healTarget.DrawPos).MagnitudeHorizontal() / 2 + 0.2f; GraphicToolbox.DrawScaledMesh(Constants.healMesh, mat, drawLoc, Quaternion.identity, size, size); float angle = healTarget.drawer.renderer.BodyAngle(); if (healTarget.Rotation == Rot4.West) angle -= leanAngle; if (healTarget.Rotation == Rot4.East) angle += leanAngle; var quat = Quaternion.AngleAxis(angle, Vector3.up); GraphicToolbox.DrawScaledMesh(MeshPool.plane20, Constants.BEING_HEALED[beingHealedIndex], healTarget.DrawPos + toxicAuraOffset, quat, 1.5f, 1.5f); if (info.step == 120) zombie.healInfo.RemoveAt(i); else { if (isNotPaused) info.step++; i++; } } } var location = drawLoc; location.y += Altitudes.AltInc / 2f; if (orientation == Rot4.North) location.y += Altitudes.AltInc / 12f; if (zombie.hasTankySuit > 0f && zombie.hasTankySuit <= 1f) { var n = (int)(zombie.hasTankySuit * 4f + 0.5f); var pos = location; var f = 25f * (zombie.pather.nextCellCostLeft / zombie.pather.nextCellCostTotal); pos.z += (Mathf.Max(0.5f, Mathf.Cos(f)) - 0.7f) / 20f; if (orientation == Rot4.South || orientation == Rot4.North) { var rot = Quaternion.identity; var frontBack = (int)(orientation == Rot4.South ? FacingIndex.South : FacingIndex.North); GraphicToolbox.DrawScaledMesh(bodyMesh, Constants.TANKYSUITS[frontBack][n], pos, rot, 1f, 1f); } else { var rot = Quaternion.identity; var mesh = orientation == Rot4.West ? bodyMesh_flipped : bodyMesh; GraphicToolbox.DrawScaledMesh(mesh, Constants.TANKYSUITS[(int)FacingIndex.East][n], pos, rot, 1f, 1f); } } if (zombie.hasTankyHelmet > 0f && zombie.hasTankyHelmet <= 1f) { var n = (int)(zombie.hasTankyHelmet * 4f + 0.5f); var headOffset = zombie.Drawer.renderer.BaseHeadOffsetAt(orientation); headOffset.y += Altitudes.AltInc / 2f; var pos = location; var f = 25f * (zombie.pather.nextCellCostLeft / zombie.pather.nextCellCostTotal); pos.z += (Mathf.Max(0.5f, Mathf.Cos(f + 0.8f)) - 0.7f) / 20f; if (orientation == Rot4.South || orientation == Rot4.North) { var rot = Quaternion.identity; var frontBack = (int)(orientation == Rot4.South ? FacingIndex.South : FacingIndex.North); GraphicToolbox.DrawScaledMesh(headMesh, Constants.TANKYHELMETS[frontBack][n], pos + headOffset, rot, 1f, 1f); } else { var rot = Quaternion.identity; var mesh = orientation == Rot4.West ? headMesh_flipped : headMesh; GraphicToolbox.DrawScaledMesh(mesh, Constants.TANKYHELMETS[(int)FacingIndex.East][n], pos + headOffset, rot, 1f, 1f); } } if (zombie.hasTankyShield > 0f && zombie.hasTankyShield <= 1f) { var n = (int)(zombie.hasTankyShield * 4f + 0.5f); var f = Mathf.PI * 4f * (zombie.pather.nextCellCostLeft / zombie.pather.nextCellCostTotal); if (orientation == Rot4.South || orientation == Rot4.North) { var x = Mathf.Sin(f) * 0.03f; var dx = x + (orientation == Rot4.South ? 0.2f : -0.2f); var dy = orientation == Rot4.South ? 0.2f : -0.2f; var dz = Mathf.Abs(Mathf.Cos(f) * 0.05f) + (orientation == Rot4.South ? -0.2f : 0.2f); var rot = Quaternion.Euler(0f, x * 100f, 0f); var mesh = orientation == Rot4.South ? shieldMesh : shieldMesh_flipped; GraphicToolbox.DrawScaledMesh(mesh, Constants.TANKYSHIELDS[(int)FacingIndex.South][n], drawLoc + new Vector3(dx, dy, dz), rot, 0.52f, 0.52f); } else { var dx = orientation == Rot4.West ? -0.45f : 0.45f; var dy = 0.3f; var dz = Mathf.Abs(Mathf.Cos(f) * 0.05f); var rot = Quaternion.Euler(0f, dx * 22f, 0f); var mesh = orientation == Rot4.West ? shieldMesh_flipped : shieldMesh; GraphicToolbox.DrawScaledMesh(mesh, Constants.TANKYSHIELDS[(int)FacingIndex.East][n], drawLoc + new Vector3(dx, dy, dz), rot, 0.62f, 0.62f); } } if (zombie.isToxicSplasher) { float angle = zombie.drawer.renderer.BodyAngle(); if (zombie.Rotation == Rot4.West) angle -= leanAngle; if (zombie.Rotation == Rot4.East) angle += leanAngle; var quat = Quaternion.AngleAxis(angle, Vector3.up); var idx = ((Find.TickManager.TicksGame + zombie.thingIDNumber) / 10) % 8; if (idx >= 5) idx = 8 - idx; GraphicToolbox.DrawScaledMesh(MeshPool.plane20, Constants.TOXIC_AURAS[idx], drawLoc + toxicAuraOffset, quat, 1f, 1f); } if (zombie.isMiner) { var headOffset = zombie.Drawer.renderer.BaseHeadOffsetAt(orientation); headOffset.y += Altitudes.AltInc / 2f; var pos = location; var f = 25f * (zombie.pather.nextCellCostLeft / zombie.pather.nextCellCostTotal); pos.z += (Mathf.Max(0.5f, Mathf.Cos(f + 0.8f)) - 0.7f) / 20f; var helmetWiggleAngle = orientation == Rot4.South || orientation == Rot4.North ? 0f : (Mathf.Sin(f) + Mathf.Cos(f + zombie.HashOffset())) * 3f; if (orientation == Rot4.West) helmetWiggleAngle += 5f; if (orientation == Rot4.East) helmetWiggleAngle -= 5f; var rot = Quaternion.AngleAxis(helmetWiggleAngle, Vector3.up); GraphicToolbox.DrawScaledMesh(headMesh, Constants.MINERHELMET[orientation.AsInt][0], pos + headOffset, rot, 1f, 1f); } if (zombie.IsActiveElectric && zombie.health.Downed == false) { tm ??= Find.TickManager; var flicker = (tm.TicksAbs / (2 + zombie.thingIDNumber % 2) + zombie.thingIDNumber) % 3; if (flicker != 0 || tm.Paused) { var glowLoc = drawLoc; glowLoc.y -= Altitudes.AltInc / 2f; var mesh = MeshPool.humanlikeBodySet.MeshAt(orientation); var glowingMaterials = Constants.ELECTRIC_GLOWING[zombie.story.bodyType]; var idx = orientation == Rot4.East || orientation == Rot4.West ? 0 : (orientation == Rot4.North ? 1 : 2); GraphicToolbox.DrawScaledMesh(mesh, glowingMaterials[idx], glowLoc, Quaternion.identity, 1f, 1f); } // stage: 0 2 4 6 8 10 12 14 16 18 // shine: x - x x x x x - x - // arc : - - - x - x - - - - // new : x zombie.electricCounter--; if (zombie.electricCounter <= 0) { var stage = -zombie.electricCounter; if (stage == 0) { var info = SoundInfo.InMap(zombie); CustomDefs.ElectricShock.PlayOneShot(info); } if (stage == 0 || (stage >= 4 && stage <= 12) || stage == 16) { var behind = drawLoc; behind.x += 0.25f; behind.y -= 0.5f; //GraphicToolbox.DrawScaledMesh(MeshPool.plane20, Constants.ELECTRIC_SHINE, behind, quat, 1f, 1f); } if (stage == 6 || stage == 7 || stage == 10 || stage == 11) { if (Rand.Chance(0.1f)) zombie.electricAngle = Rand.RangeInclusive(0, 359); var quat = Quaternion.Euler(0, zombie.electricAngle, 0); var idx = Rand.RangeInclusive(0, 3); GraphicToolbox.DrawScaledMesh(MeshPool.plane20, Constants.ELECTRIC_ARCS[idx], drawLoc, quat, 1.5f, 1.5f); } if (stage >= 18) { zombie.electricCounter = Rand.RangeInclusive(60, 180); if (Find.TickManager.Paused) zombie.electricCounter += Rand.RangeInclusive(300, 600); zombie.electricAngle = Rand.RangeInclusive(0, 359); } } if (zombie.absorbAttack.Count > 0) { var pair = zombie.absorbAttack.Pop(); var idx = pair.Value; if (idx >= 0) { var facing = pair.Key; var center = drawLoc + Quaternion.AngleAxis(facing + 225f, Vector3.up) * new Vector3(-0.4f, 0, 0.4f); var quat = Quaternion.AngleAxis(facing + 225f, Vector3.up); GraphicToolbox.DrawScaledMesh(MeshPool.plane14, Constants.ELECTRIC_ABSORB[idx], center, quat, 1f, 1f); Tools.PlayAbsorb(zombie); } else if (idx == -2) { for (var facing = 0; facing < 360; facing += 90) { var center = drawLoc + Quaternion.AngleAxis(facing + 225f, Vector3.up) * new Vector3(-0.4f, 0, 0.4f); var quat = Quaternion.AngleAxis(facing + 225f, Vector3.up); GraphicToolbox.DrawScaledMesh(MeshPool.plane14, Constants.ELECTRIC_ABSORB[Rand.RangeInclusive(0, 3)], center, quat, 1f, 1f); } Tools.PlayAbsorb(zombie); } } } if (zombie.raging == 0 && zombie.isAlbino == false) return; // raging zombies and albino eyes drawing drawLoc.y = moteAltitute; var quickHeadCenter = drawLoc + new Vector3(0, 0, 0.35f); if (Find.CameraDriver.CurrentZoom <= CameraZoomRange.Middle) { tm ??= Find.TickManager; var blinkPeriod = 60 + zombie.thingIDNumber % 180; // between 2-5s var eyesOpen = (tm.TicksAbs % blinkPeriod) > 3; if (eyesOpen || tm.CurTimeSpeed == TimeSpeed.Paused) { // the following constant comes from PawnRenderer.RenderPawnInternal var loc = drawLoc + renderer.BaseHeadOffsetAt(orientation) + new Vector3(0, 0.0281250011f, 0); // not clear why 75 but it seems to fit var eyeX = zombie.sideEyeOffset.x / 75f; var eyeZ = zombie.sideEyeOffset.z / 75f; var eyeScale = zombie.isAlbino ? 0.25f : 0.5f; var eyeMat = zombie.isAlbino ? new Material(Constants.RAGE_EYE) { color = white50 } : Constants.RAGE_EYE; if (orientation == Rot4.West) GraphicToolbox.DrawScaledMesh(MeshPool.plane05, Constants.RAGE_EYE, loc + new Vector3(-eyeX, 0, eyeZ), Quaternion.identity, eyeScale, eyeScale); else if (orientation == Rot4.East) GraphicToolbox.DrawScaledMesh(MeshPool.plane05, Constants.RAGE_EYE, loc + new Vector3(eyeX, 0, eyeZ), Quaternion.identity, eyeScale, eyeScale); if (orientation == Rot4.South) { GraphicToolbox.DrawScaledMesh(MeshPool.plane05, Constants.RAGE_EYE, quickHeadCenter + leftEyeOffset, Quaternion.identity, eyeScale, eyeScale); GraphicToolbox.DrawScaledMesh(MeshPool.plane05, Constants.RAGE_EYE, quickHeadCenter + rightEyeOffset, Quaternion.identity, eyeScale, eyeScale); } } } if (orientation == Rot4.West) quickHeadCenter.x -= 0.09f; if (orientation == Rot4.East) quickHeadCenter.x += 0.09f; if (zombie.isAlbino == false) GraphicToolbox.DrawScaledMesh(MeshPool.plane20, Constants.RAGE_AURAS[Find.CameraDriver.CurrentZoom], quickHeadCenter, Quaternion.identity, 1f, 1f); } } // patch to exclude any zombieland apparel from being used at all // (we fake our own apparel via the patch below) // [HarmonyPatch] static class PawnApparelGenerator_PossibleApparelSet_PairOverlapsAnything_Patch { static MethodBase TargetMethod() { var inner = AccessTools.Inner(typeof(PawnApparelGenerator), "PossibleApparelSet"); return AccessTools.Method(inner, "PairOverlapsAnything"); } [HarmonyPriority(Priority.First)] static bool Prefix(ThingStuffPair pair, ref bool __result) { if (pair.thing?.IsZombieDef() ?? false) { __result = true; return false; } if (pair.stuff?.IsZombieDef() ?? false) { __result = true; return false; } return true; } } // patch for giving zombies accessories like bomb vests or tanky suits // [HarmonyPatch(typeof(PawnGraphicSet))] [HarmonyPatch(nameof(PawnGraphicSet.ResolveApparelGraphics))] static class PawnGraphicSet_ResolveApparelGraphics_Patch { static ThingDef bombVestApparelDef; [HarmonyPriority(Priority.Last)] static void Postfix(PawnGraphicSet __instance) { if (!(__instance.pawn is Zombie zombie)) return; if (zombie.IsSuicideBomber) { if (bombVestApparelDef == null) bombVestApparelDef = ThingDef.Named("Apparel_BombVest"); var apparel = new Apparel() { def = bombVestApparelDef }; if (__instance.apparelGraphics.Any(a => a.sourceApparel.def == bombVestApparelDef) == false) if (ApparelGraphicRecordGetter.TryGetGraphicApparel(apparel, BodyTypeDefOf.Hulk, out var record)) __instance.apparelGraphics.Add(record); } } } // patch to inform zombie generator that apparel texture could not load [HarmonyPatch(typeof(Graphic_Multi))] [HarmonyPatch(nameof(Graphic_Multi.Init))] public static class Graphic_Multi_Init_Patch { public static bool suppressError = false; public static bool textureError = false; static void Error(string text) { textureError = true; if (suppressError == false) Error(text); } [HarmonyPriority(Priority.First)] static IEnumerable<CodeInstruction> Transpiler(IEnumerable<CodeInstruction> instructions) { var m1 = SymbolExtensions.GetMethodInfo(() => Error("")); var m2 = SymbolExtensions.GetMethodInfo(() => Error("")); return Transpilers.MethodReplacer(instructions, m1, m2); } } // patch for reducing the warmup smash time for raging zombies // [HarmonyPatch(typeof(Verb))] [HarmonyPatch(nameof(Verb.TryStartCastOn))] [HarmonyPatch(new Type[] { typeof(LocalTargetInfo), typeof(LocalTargetInfo), typeof(bool), typeof(bool), typeof(bool) })] static class Verb_TryStartCastOn_Patch { static int ModifyTicks(float seconds, Verb verb) { var ticks = seconds.SecondsToTicks(); if (verb?.caster is Zombie zombie && (zombie.raging > 0 || zombie.wasMapPawnBefore)) { var grid = zombie.Map.GetGrid(); var count = grid.GetZombieCount(zombie.Position); if (count > 0) ticks /= count; } return ticks; } [HarmonyPriority(Priority.Last)] static IEnumerable<CodeInstruction> Transpiler(IEnumerable<CodeInstruction> instructions) { var m_SecondsToTicks = SymbolExtensions.GetMethodInfo(() => GenTicks.SecondsToTicks(0f)); var found = false; foreach (var instruction in instructions) { if (instruction.Calls(m_SecondsToTicks)) { yield return new CodeInstruction(OpCodes.Ldarg_0); instruction.opcode = OpCodes.Call; instruction.operand = SymbolExtensions.GetMethodInfo(() => ModifyTicks(0, null)); found = true; } yield return instruction; } if (!found) Error("Unexpected code in patch " + MethodBase.GetCurrentMethod().DeclaringType); } } // patch for variable zombie stats (speed, pain, melee, dodge) // [HarmonyPatch(typeof(StatExtension))] [HarmonyPatch(nameof(StatExtension.GetStatValue))] static class StatExtension_GetStatValue_Patch { static readonly float defaultHumanMoveSpeed = ThingDefOf.Human.statBases.First(mod => mod.stat == StatDefOf.MoveSpeed).value; [HarmonyPriority(Priority.First)] static bool Prefix(Thing thing, StatDef stat, ref float __result) { if (!(thing is Zombie zombie)) return true; if (stat == StatDefOf.PainShockThreshold) { if (zombie.wasMapPawnBefore) { __result = 4000f; return false; } if (zombie.raging > 0) { __result = 1000f; return false; } if (zombie.hasTankyShield != -1f || zombie.hasTankyHelmet != -1f || zombie.hasTankySuit != -1f) { __result = 5000f; return false; } var bodyType = zombie.story.bodyType; if (bodyType == BodyTypeDefOf.Thin) { __result = 0.1f; return false; } if (bodyType == BodyTypeDefOf.Hulk) { __result = 0.8f; return false; } else if (bodyType == BodyTypeDefOf.Fat) { __result = 10f; return false; } __result = 0.8f; return false; } if (stat == StatDefOf.MeleeHitChance) { if (zombie.wasMapPawnBefore) { __result = 1f; return false; } if (zombie.health.Downed) { __result = 0.1f; return false; } if (zombie.hasTankyShield != -1f) { __result = 1.0f; return false; } if (zombie.hasTankyHelmet != -1f || zombie.hasTankySuit != -1f) { __result = 0.9f; return false; } if (zombie.story.bodyType == BodyTypeDefOf.Fat) { __result = 0.8f; return false; } if (zombie.state == ZombieState.Tracking || zombie.raging > 0) __result = Constants.ZOMBIE_HIT_CHANCE_TRACKING; else __result = Constants.ZOMBIE_HIT_CHANCE_IDLE; return false; } if (stat == StatDefOf.MeleeDodgeChance) { if (zombie.wasMapPawnBefore) { __result = 0.9f; return false; } if (zombie.isAlbino) __result = 0f; else __result = 0.02f; return false; } if (stat == StatDefOf.MoveSpeed) { var tm = Find.TickManager; var multiplier = defaultHumanMoveSpeed / ZombieTicker.PercentTicking; if (zombie.health.Downed) { __result = 0.004f * tm.TickRateMultiplier; return false; } if (zombie.IsTanky) { __result = 0.004f * multiplier * tm.TickRateMultiplier; return false; } var albinoSpeed = 1f; if (zombie.isAlbino) { var albinoPos = zombie.Position; var colonists = zombie.Map.mapPawns.FreeColonistsAndPrisonersSpawned; var minDistSquared = colonists.Any() ? colonists.Min(colonist => colonist.Position.DistanceToSquared(albinoPos)) : 450; albinoSpeed = GenMath.LerpDoubleClamped(36, 900, 5f, 1f, minDistSquared); } float speed; if (albinoSpeed > 1f || zombie.state == ZombieState.Tracking || zombie.raging > 0 || zombie.wasMapPawnBefore) speed = ZombieSettings.Values.moveSpeedTracking; else speed = ZombieSettings.Values.moveSpeedIdle; var factor = 1f; var bodyType = zombie.story.bodyType; if (bodyType == BodyTypeDefOf.Thin) factor = 0.8f; else if (bodyType == BodyTypeDefOf.Hulk) factor = 0.8f; else if (bodyType == BodyTypeDefOf.Fat) factor = 0.7f; __result = speed * factor * multiplier * albinoSpeed; if (zombie.wasMapPawnBefore) __result *= 2f; if (zombie.isDarkSlimer) __result /= 1.5f; if (zombie.isHealer) __result *= 0.9f; return false; } if (zombie.hasTankySuit != -1f || zombie.hasTankyHelmet != -1f) { if (stat == StatDefOf.ComfyTemperatureMin) { __result = -999; return false; } if (stat == StatDefOf.ComfyTemperatureMax) { __result = 999f; return false; } } return true; } } // patch for variable zombie damage factor // [HarmonyPatch(typeof(VerbProperties))] [HarmonyPatch(nameof(VerbProperties.GetDamageFactorFor), typeof(Tool), typeof(Pawn), typeof(HediffComp_VerbGiver))] static class Verb_GetDamageFactorFor_Patch { static void Postfix(Pawn attacker, ref float __result) { if (!(attacker is Zombie zombie)) return; if (zombie.hasTankyShield > 0f || zombie.hasTankyHelmet > 0f || zombie.hasTankySuit > 0f) { var val = 0f; if (zombie.hasTankyShield > 0f) val += 30f; if (zombie.hasTankyHelmet > 0f) val += 10f; if (zombie.hasTankySuit > 0f) val += 20f; __result *= val; return; } var settings = ZombieSettings.Values.damageFactor; var bodyType = zombie.story.bodyType; if (bodyType == BodyTypeDefOf.Thin) __result *= 0.5f * settings; else if (bodyType == BodyTypeDefOf.Hulk) __result *= 3f * settings; else if (bodyType == BodyTypeDefOf.Fat) __result *= 4f * settings; if (zombie.wasMapPawnBefore) __result *= 5f; } } // patch for zombies rotting regardless of temperature // [HarmonyPatch(typeof(Thing))] [HarmonyPatch(nameof(Thing.AmbientTemperature), MethodType.Getter)] static class Thing_AmbientTemperature_Patch { [HarmonyPriority(Priority.First)] static bool Prefix(Thing __instance, ref float __result) { if (__instance is Zombie || __instance is ZombieCorpse) { __result = 21f; // fake normal conditions return false; } return true; } } // add start/stop extracting zombie serum gizmo // [HarmonyPatch(typeof(PriorityWork))] [HarmonyPatch(nameof(PriorityWork.GetGizmos))] [StaticConstructorOnStartup] static class PriorityWork_GetGizmos_Patch { static IEnumerable<Gizmo> Postfix(IEnumerable<Gizmo> gizmos, Pawn ___pawn) { foreach (var gizmo in gizmos) yield return gizmo; if (ZombieSettings.Values.betterZombieAvoidance) yield return Gizmos.ZombieAvoidance(___pawn); if (ZombieSettings.Values.corpsesExtractAmount > 0) yield return Gizmos.ExtractSerum(___pawn); if (ZombieSettings.Values.hoursAfterDeathToBecomeZombie > 0) yield return Gizmos.DoubleTap(___pawn); } } // patch to forbid zombie extract and use our zombie serum in the right order with medicine // - first use medicine to tend all wounds by excluding serum // - then allow serum and let it automatically execute operation bills // [HarmonyPatch(typeof(HealthAIUtility))] [HarmonyPatch(nameof(HealthAIUtility.FindBestMedicine))] static class HealthAIUtility_FindBestMedicine_Patch { static bool Prefix(Pawn healer, Pawn patient, ref Thing __result) { if (patient.playerSettings == null || patient.playerSettings.medCare <= MedicalCareCategory.NoMeds) return true; var useSerum = Medicine.GetMedicineCountToFullyHeal(patient) <= 0; bool validator(Thing m) { return !m.IsForbidden(healer) && patient.playerSettings.medCare.AllowsMedicine(m.def) && healer.CanReserve(m, 10, 1, null, false); } float priorityGetter(Thing t) { if (t.def.thingClass == typeof(ZombieSerum)) return useSerum ? 1000 * t.def.costList[1].count : -10000; return t.def.GetStatValueAbstract(StatDefOf.MedicalPotency, null); } var position = patient.Position; var map = patient.Map; var searchSet = patient.Map.listerThings .ThingsInGroup(ThingRequestGroup.Medicine) .Where(t => t.def.thingClass != typeof(ZombieExtract)); if (useSerum == false) searchSet = searchSet.Where(t => t.def.thingClass != typeof(ZombieSerum)); var traverseParams = TraverseParms.For(healer, Danger.Deadly, TraverseMode.ByPawn, false); __result = GenClosest.ClosestThing_Global_Reachable(position, map, searchSet, PathEndMode.ClosestTouch, traverseParams, 9999f, validator, priorityGetter); return false; } } // patch to set zombie bite injuries as non natural healing to avoid // the healing cross mote // [HarmonyPatch(typeof(HediffUtility))] [HarmonyPatch(nameof(HediffUtility.CanHealNaturally))] static class HediffUtility_CanHealNaturally_Patch { [HarmonyPriority(Priority.First)] static bool Prefix(Hediff_Injury hd, ref bool __result) { if (hd is Hediff_Injury_ZombieBite zombieBite && zombieBite.pawn.RaceProps.Humanlike && zombieBite.pawn.RaceProps.IsFlesh && AlienTools.IsFleshPawn(zombieBite.pawn)) { var tendDuration = zombieBite.TendDuration; if (tendDuration != null) { var state = tendDuration.GetInfectionState(); __result = (state != InfectionState.BittenNotVisible && state < InfectionState.BittenInfectable); return false; } } return true; } } // patch to allow amputation of biten body parts // [HarmonyPatch(typeof(Recipe_RemoveBodyPart))] [HarmonyPatch(nameof(Recipe_RemoveBodyPart.GetPartsToApplyOn))] static class Recipe_RemoveBodyPart_GetPartsToApplyOn_Patch { [HarmonyPriority(Priority.Last)] static IEnumerable<BodyPartRecord> Postfix(IEnumerable<BodyPartRecord> parts, Pawn pawn, RecipeDef recipe) { foreach (var part in parts) yield return part; if (recipe != RecipeDefOf.RemoveBodyPart) yield break; var bites = pawn.health.hediffSet.GetHediffs<Hediff_Injury_ZombieBite>().Select(bite => bite.Part); foreach (var bite in bites) yield return bite; } } // patch to keep zombie bite injuries even after tending if they have to stay around // [HarmonyPatch(typeof(Hediff))] [HarmonyPatch(nameof(Hediff.ShouldRemove), MethodType.Getter)] static class Hediff_ShouldRemove_Patch { [HarmonyPriority(Priority.Last)] static void Postfix(Hediff __instance, ref bool __result) { if (__result == false) return; // do not remove our zombie hediffs from dead pawns if (__instance.pawn != null && __instance.pawn.Dead && __instance.def.IsZombieHediff()) { __result = false; return; } if (__instance is Hediff_Injury_ZombieBite zombieBite && zombieBite.pawn.RaceProps.Humanlike && zombieBite.pawn.RaceProps.IsFlesh && AlienTools.IsFleshPawn(zombieBite.pawn)) { var tendDuration = zombieBite.TendDuration; if (tendDuration != null) { var state = tendDuration.GetInfectionState(); if (state == InfectionState.BittenNotVisible || state >= InfectionState.BittenInfectable) __result = false; } } } } // patch for making burning zombies keep their fire (even when it rains) // [HarmonyPatch(typeof(Fire))] [HarmonyPatch(nameof(Fire.VulnerableToRain))] static class Fire_VulnerableToRain_Patch { static void Postfix(Fire __instance, ref bool __result) { if (__result == false) return; if (__instance.parent is Zombie zombie && ZombieSettings.Values.zombiesBurnLonger && Rand.Chance(0.2f)) __result = false; } } // patch for making zombies burn slower // [HarmonyPatch(typeof(Fire))] [HarmonyPatch(nameof(Fire.DoFireDamage))] static class Fire_DoFireDamage_Patch { static int FireDamagePatch(float f, Pawn pawn) { var num = GenMath.RoundRandom(f); if (ZombieSettings.Values.zombiesBurnLonger == false) return num; if (!(pawn is Zombie zombie)) return num; return Math.Max(2, num / 2); } static IEnumerable<CodeInstruction> Transpiler(IEnumerable<CodeInstruction> instructions) { var m_RoundRandom = SymbolExtensions.GetMethodInfo(() => GenMath.RoundRandom(0f)); var m_FireDamagePatch = SymbolExtensions.GetMethodInfo(() => FireDamagePatch(0f, null)); var list = instructions.ToList(); var idx = list.FirstIndexOf(code => code.Calls(m_RoundRandom)); if (idx > 0 && idx < list.Count()) { list[idx].opcode = OpCodes.Ldarg_1; // first argument of instance method list[idx].operand = null; list.Insert(idx + 1, new CodeInstruction(OpCodes.Call, m_FireDamagePatch)); } else Error("Unexpected code in patch " + MethodBase.GetCurrentMethod().DeclaringType); return list.AsEnumerable(); } } // patch for excluding burning zombies from total fire count // [HarmonyPatch(typeof(FireWatcher))] [HarmonyPatch(nameof(FireWatcher.UpdateObservations))] static class FireWatcher_UpdateObservations_Patch { static IEnumerable<CodeInstruction> Transpiler(ILGenerator generator, IEnumerable<CodeInstruction> instructions) { var found1 = false; var found2 = false; var n = 0; var label = generator.DefineLabel(); foreach (var instruction in instructions) { yield return instruction; if (instruction.opcode == OpCodes.Stloc_2) { yield return new CodeInstruction(OpCodes.Ldloc_2); yield return new CodeInstruction(OpCodes.Ldfld, typeof(AttachableThing).Field(nameof(AttachableThing.parent))); yield return new CodeInstruction(OpCodes.Isinst, typeof(Zombie)); yield return new CodeInstruction(OpCodes.Brtrue, label); found1 = true; } if (n >= 0 && instruction.opcode == OpCodes.Add) n++; if (instruction.opcode == OpCodes.Ldloc_1 && n == 2) { instruction.labels.Add(label); n = -1; found2 = true; } } if (!found1 || !found2) Error("Unexpected code in patch " + MethodBase.GetCurrentMethod().DeclaringType); } } // patch to prevent errors in combat log // [HarmonyPatch(typeof(DamageWorker.DamageResult))] [HarmonyPatch(nameof(DamageWorker.DamageResult.AssociateWithLog))] public static class DamageWorker_DamageResult_AssociateWithLog_Patch { static bool Prefix(DamageWorker.DamageResult __instance) { return !(__instance.hitThing is Zombie zombie); } } // patch to prevent errors for empty corpses (seems like a bug in rimworld) // [HarmonyPatch(typeof(Alert_ColonistLeftUnburied))] [HarmonyPatch(nameof(Alert_ColonistLeftUnburied.IsCorpseOfColonist))] public static class Alert_ColonistLeftUnburied_IsCorpseOfColonist_Patch { static bool Prefix(Corpse corpse, ref bool __result) { if (corpse?.InnerPawn == null) { __result = false; return false; } return true; } } // patch to make zombies in tar smoke un-hitable // [HarmonyPatch(typeof(Verb))] [HarmonyPatch(nameof(Verb.CanHitTargetFrom))] static class ShotReport_HitReportFor_Patch { [HarmonyPriority(Priority.First)] static bool Prefix(Verb __instance, LocalTargetInfo targ, ref bool __result) { if (__instance.IsMeleeAttack) return true; var thing = targ.Thing; var map = thing?.Map; if (map == null) return true; if (thing.Position.GetGas(map)?.def != CustomDefs.TarSmoke) return true; __result = false; return false; } } // patch to make tar smoke really affect hit chance a lot // [HarmonyPatch(typeof(ShotReport))] [HarmonyPatch(nameof(ShotReport.AimOnTargetChance_StandardTarget), MethodType.Getter)] public static class ShotReport_AimOnTargetChance_StandardTarget_Patch { public static bool Prefix(ref float __result, ThingDef ___coveringGas) { if (___coveringGas != CustomDefs.TarSmoke) return true; __result = 0f; return false; } } // patch to deactivate electrical zombies with emp // [HarmonyPatch(typeof(StunHandler))] [HarmonyPatch(nameof(StunHandler.Notify_DamageApplied))] static class DamageFlasher_Notify_DamageApplied_Patch { [HarmonyPriority(Priority.First)] static void Prefix(StunHandler __instance, DamageInfo dinfo) { if (dinfo.Def != DamageDefOf.EMP && dinfo.Def != DamageDefOf.Stun) return; if (__instance.parent is Zombie zombie && zombie.Downed == false && zombie.Dead == false) if (zombie.IsActiveElectric) zombie.DisableElectric((int)(dinfo.Amount * 60)); } } // patch to remove non-melee damage from electrifier zombies // [HarmonyPatch(typeof(DamageWorker_AddInjury))] [HarmonyPatch(nameof(DamageWorker_AddInjury.ApplyDamageToPart))] public static class DamageWorker_AddInjury_ApplyDamageToPart_Patch { static bool Prefix(ref DamageInfo dinfo, Pawn pawn) { if (!(pawn is Zombie zombie)) return true; if (zombie.health.Downed) return true; if (zombie.wasMapPawnBefore) { dinfo.SetAllowDamagePropagation(false); dinfo.SetInstantPermanentInjury(false); dinfo.SetAmount(dinfo.Amount / 1.5f); return true; } var def = dinfo.Def; if (zombie.isAlbino) return def.isExplosive || Rand.Chance(0.5f); if (zombie.isDarkSlimer) { var pos = zombie.Position; var map = zombie.Map; if (map != null && pos.GetGas(map) == null) { var difficulty = Tools.Difficulty(); var alpha = GenMath.LerpDoubleClamped(0, 5, 0.25f, 1f, difficulty); var min = GenMath.LerpDoubleClamped(0, 5, 2, 60, difficulty); var max = GenMath.LerpDoubleClamped(0, 5, min, 90, difficulty); CustomDefs.TarSmoke.graphicData.color = new Color(0, 0, 0, alpha); CustomDefs.TarSmoke.gas.expireSeconds = new FloatRange(min, max); GenExplosion.DoExplosion(pos, map, 1 + difficulty, DamageDefOf.Smoke, null, (int)(50 * difficulty), -1f, CustomDefs.TarSmokePop, null, null, null, CustomDefs.TarSmoke, 1f, 1, false, null, 0f, 1, 0f, false, null, null); } } if (zombie.IsActiveElectric) { if (def.isRanged == false || (def.isRanged && def.isExplosive)) return true; var indices = new List<int>() { 0, 1, 2, 3 }; indices.Shuffle(); for (var i = 0; i < Rand.RangeInclusive(1, 4); i++) { zombie.absorbAttack.Add(new KeyValuePair<float, int>(dinfo.Angle, i)); if (Rand.Chance(0.9f)) zombie.absorbAttack.Add(new KeyValuePair<float, int>(0f, -1)); } return false; } return true; } } // patch to prevent damage if zombie has armor // [HarmonyPatch(typeof(ArmorUtility))] [HarmonyPatch(nameof(ArmorUtility.GetPostArmorDamage))] public static class ArmorUtility_GetPostArmorDamage_Patch { static void ApplyDamage(ref float armor, ref float amount, float reducer) { var damage = amount / reducer; if (armor >= damage) { armor -= damage; amount = 0f; return; } amount = (damage - armor) * reducer; armor = -1f; } [HarmonyPriority(Priority.First)] static bool Prefix(Pawn pawn, ref float amount, BodyPartRecord part, float armorPenetration, out bool deflectedByMetalArmor, out bool diminishedByMetalArmor, ref float __result) { deflectedByMetalArmor = false; diminishedByMetalArmor = false; if (!(pawn is Zombie zombie)) return true; var penetration = Math.Max(armorPenetration - 0.25f, 0f); amount *= (1f + 2 * penetration); var skip = false; var difficulty = Tools.Difficulty(); if (amount > 0f && zombie.hasTankyShield > 0f) { ApplyDamage(ref zombie.hasTankyShield, ref amount, 1f + difficulty * 100f); diminishedByMetalArmor |= zombie.hasTankyShield > 0f; __result = -1f; skip = true; } var fakeHeadShot = (zombie.hasTankySuit <= 0f && Rand.Chance(0.25f)); if (part.groups.Contains(BodyPartGroupDefOf.FullHead) || fakeHeadShot) { if (amount > 0f && zombie.hasTankyHelmet > 0f) { ApplyDamage(ref zombie.hasTankyHelmet, ref amount, 1f + difficulty * 10f); diminishedByMetalArmor |= zombie.hasTankyHelmet > 0f; __result = -1f; skip = true; } } if (amount > 0f && zombie.hasTankySuit > 0f) { ApplyDamage(ref zombie.hasTankySuit, ref amount, 1f + difficulty * 50f); diminishedByMetalArmor |= zombie.hasTankySuit > 0f; __result = -1f; skip = true; } deflectedByMetalArmor = amount == 0f; if (diminishedByMetalArmor) Tools.PlayTink(zombie); // still a tough zombie even if we hit the body but some armor is left if (amount > 0f && (zombie.hasTankyHelmet > 0f || zombie.hasTankySuit > 0f)) { var toughnessLevel = Tools.Difficulty() / 2; amount = (amount + toughnessLevel) / (toughnessLevel + 1); } return skip == false; } static bool GetAfterArmorDamagePrefix(ref DamageInfo originalDinfo, Pawn pawn, BodyPartRecord hitPart, out bool shieldAbsorbed, ref DamageInfo __result) { __result = originalDinfo; var dinfo = new DamageInfo(originalDinfo); var dmgAmount = dinfo.Amount; shieldAbsorbed = false; if (pawn == null || hitPart == null) return true; var prefixResult = 0f; var result = Prefix(pawn, ref dmgAmount, hitPart, dinfo.ArmorPenetrationInt, out var deflect, out var diminish, ref prefixResult); if (result && originalDinfo.Instigator != null) return (pawn.Spawned && pawn.Dead == false && pawn.Destroyed == false && originalDinfo.Instigator.Spawned && originalDinfo.Instigator.Destroyed == false); dinfo.SetAmount(dmgAmount); originalDinfo = dinfo; __result = dinfo; shieldAbsorbed = deflect || diminish; return false; } // called from Main public static void PatchCombatExtended(Harmony harmony) { var t_ArmorUtilityCE = AccessTools.TypeByName("CombatExtended.ArmorUtilityCE"); if (t_ArmorUtilityCE == null) return; var boolRef = typeof(bool).MakeByRefType(); var argumentTypes = new Type[] { typeof(DamageInfo), typeof(Pawn), typeof(BodyPartRecord), boolRef, boolRef, boolRef }; var m_GetAfterArmorDamage = AccessTools.Method(t_ArmorUtilityCE, "GetAfterArmorDamage", argumentTypes); if (m_GetAfterArmorDamage == null) { Error("Combat Extended installed, but method ArmorUtilityCE.GetAfterArmorDamage not found"); return; } var prefix = new HarmonyMethod(typeof(ArmorUtility_GetPostArmorDamage_Patch).GetMethod(nameof(GetAfterArmorDamagePrefix), AccessTools.all)); _ = harmony.Patch(m_GetAfterArmorDamage, prefix); } } [HarmonyPatch] class Harmony_DamageWorker_AddInjury_ApplyDamageToPart_ArmorReroute_Patch { static bool Prepare() { return TargetMethod() != null; } static MethodInfo TargetMethod() { return AccessTools.Method("CombatExtended.Harmony.Harmony_DamageWorker_AddInjury_ApplyDamageToPart:ArmorReroute"); } static bool Prefix(ref DamageInfo dinfo) { return dinfo.Def != DamageDefOf.SurgicalCut; } } // patch for not slowing down time if pawn attacks a zombie // [HarmonyPatch(typeof(Verb))] [HarmonyPatch(nameof(Verb.CausesTimeSlowdown))] class Verb_CausesTimeSlowdown_Patch { static void Postfix(Verb __instance, ref bool __result, LocalTargetInfo castTarg) { if (__result == false || castTarg == null || castTarg.HasThing == false || __instance.caster is Zombie) return; if (!(castTarg.Thing is Zombie zombie)) return; var dist = __instance.caster.Position.DistanceToSquared(zombie.Position); if (dist >= Constants.HUMAN_PHEROMONE_RADIUS * Constants.HUMAN_PHEROMONE_RADIUS) __result = false; } } // patch to exclude electric zombies from ranged combat // [HarmonyPatch(typeof(Pawn))] [HarmonyPatch(nameof(Pawn.TryGetAttackVerb))] static class Pawn_TryGetAttackVerb_Patch { [HarmonyPriority(Priority.First)] static bool Prefix(Pawn __instance, Thing target, ref Verb __result) { if (!(target is Zombie zombie) || zombie.IsActiveElectric == false) return true; if (__instance.equipment?.Primary != null && __instance.equipment.PrimaryEq.PrimaryVerb.targetParams.canTargetLocations) return true; __result = __instance.meleeVerbs.TryGetMeleeVerb(target); return false; } } // patch for simpler attack verb handling on zombies (story work tab confict) // [HarmonyPatch(typeof(Pawn))] [HarmonyPatch(nameof(Pawn.TryStartAttack))] static class Pawn_TryStartAttack_Patch { [HarmonyPriority(Priority.First)] static bool Prefix(Pawn __instance, LocalTargetInfo targ, ref bool __result) { if ((__instance is Zombie) == false) return true; var verb = __instance.TryGetAttackVerb(targ.Thing); __result = verb != null && verb.TryStartCastOn(targ, false, true); return false; } } // patch to handle various things when someone dies // [HarmonyPatch(typeof(Pawn))] [HarmonyPatch(nameof(Pawn.Kill))] static class Pawn_Kill_Patch { [HarmonyPriority(Priority.First)] static void Prefix(Pawn __instance) { // remove current job of zombie immediately when killed if (__instance is Zombie zombie) { if (zombie.jobs != null && zombie.CurJob != null) zombie.jobs.EndCurrentJob(JobCondition.InterruptForced, false); Tools.DropLoot(zombie); return; } var pawn = __instance; if (pawn.RaceProps.Humanlike) { var hediffSet = pawn.health.hediffSet; // flag zombie bites to be infectious when pawn dies hediffSet .GetHediffs<Hediff_Injury_ZombieBite>() .Where(zombieBite => zombieBite.TendDuration.InfectionStateBetween(InfectionState.BittenInfectable, InfectionState.Infected)) .Do(zombieBite => zombieBite.mayBecomeZombieWhenDead = true); // if death means becoming a zombie, install zombie infection if (ZombieSettings.Values.hoursAfterDeathToBecomeZombie > -1) { var brain = hediffSet.GetBrain(); if (brain != null) { var hediff = HediffMaker.MakeHediff(CustomDefs.ZombieInfection, pawn, brain) as Hediff_ZombieInfection; hediff.InitializeExpiringDate(); hediffSet.AddDirect(hediff, null, null); } } } ColonistSettings.Values.RemoveColonist(pawn); } } // patch headshot to kill zombies right away // [HarmonyPatch(typeof(DamageWorker_AddInjury))] [HarmonyPatch(nameof(DamageWorker_AddInjury.IsHeadshot))] static class DamageWorker_AddInjury_IsHeadshot_Patch { static void Postfix(Pawn pawn, bool __result) { if (__result == false) return; if (pawn is Zombie zombie) zombie.state = ZombieState.ShouldDie; } } // [HarmonyPatch(typeof(HediffSet))] [HarmonyPatch(nameof(HediffSet.AddDirect))] static class HediffSet_AddDirect_Patch { static void Postfix(Pawn ___pawn, Hediff hediff) { if (!(___pawn is Zombie zombie)) return; if (hediff?.Part != null && hediff.Part.def.tags.Contains(BodyPartTagDefOf.ConsciousnessSource)) zombie.state = ZombieState.ShouldDie; } } // simplify fire lookup by updating isOnFire on zombies // [HarmonyPatch(typeof(CompAttachBase))] [HarmonyPatch(nameof(CompAttachBase.AddAttachment))] static class CompAttachBase_AddAttachment_Patch { static void Postfix(AttachableThing t, ThingWithComps ___parent) { if (t.def != ThingDefOf.Fire) return; if (___parent is Zombie zombie) zombie.isOnFire = true; } } // [HarmonyPatch(typeof(CompAttachBase))] [HarmonyPatch(nameof(CompAttachBase.RemoveAttachment))] static class CompAttachBase_RemoveAttachment_Patch { static void Postfix(AttachableThing t, ThingWithComps ___parent, List<AttachableThing> ___attachments) { if (t.def != ThingDefOf.Fire) return; if (___parent is Zombie zombie) zombie.isOnFire = ___attachments.Any(a => a.def == ThingDefOf.Fire); } } // patch for disallowing social interaction with zombies // [HarmonyPatch(typeof(RelationsUtility))] [HarmonyPatch(nameof(RelationsUtility.HasAnySocialMemoryWith))] static class RelationsUtility_HasAnySocialMemoryWith_Patch { [HarmonyPriority(Priority.First)] static bool Prefix(Pawn p, Pawn otherPawn, ref bool __result) { if (p is Zombie || otherPawn is Zombie) { __result = false; return false; } return true; } } [HarmonyPatch(typeof(Pawn_RelationsTracker))] [HarmonyPatch(nameof(Pawn_RelationsTracker.OpinionOf))] static class Pawn_RelationsTracker_OpinionOf_Patch { static IEnumerable<CodeInstruction> Transpiler(ILGenerator generator, IEnumerable<CodeInstruction> instructions) { var returnZeroLabel = generator.DefineLabel(); yield return new CodeInstruction(OpCodes.Ldarg_0); yield return new CodeInstruction(OpCodes.Ldfld, typeof(Pawn_RelationsTracker).Field("pawn")); yield return new CodeInstruction(OpCodes.Isinst, typeof(Zombie)); yield return new CodeInstruction(OpCodes.Brtrue_S, returnZeroLabel); yield return new CodeInstruction(OpCodes.Ldarg_1); yield return new CodeInstruction(OpCodes.Isinst, typeof(Zombie)); yield return new CodeInstruction(OpCodes.Brtrue_S, returnZeroLabel); foreach (var instruction in instructions) yield return instruction; yield return new CodeInstruction(OpCodes.Ldc_I4_0) { labels = new List<Label> { returnZeroLabel } }; yield return new CodeInstruction(OpCodes.Ret); } } [HarmonyPatch(typeof(RelationsUtility))] [HarmonyPatch(nameof(RelationsUtility.PawnsKnowEachOther))] static class RelationsUtility_PawnsKnowEachOther_Patch { [HarmonyPriority(Priority.First)] static bool Prefix(Pawn p1, Pawn p2, ref bool __result) { if (p1 is Zombie || p2 is Zombie) { __result = false; return false; } return true; } } [HarmonyPatch(typeof(ThoughtHandler))] [HarmonyPatch(nameof(ThoughtHandler.GetSocialThoughts))] [HarmonyPatch(new Type[] { typeof(Pawn), typeof(List<ISocialThought>) })] static class ThoughtHandler_GetSocialThoughts_Patch { [HarmonyPriority(Priority.First)] static bool Prefix(ThoughtHandler __instance, Pawn otherPawn, List<ISocialThought> outThoughts) { if (otherPawn is Zombie || __instance.pawn is Zombie) { outThoughts.Clear(); return false; } return true; } } [HarmonyPatch(typeof(SituationalThoughtHandler))] [HarmonyPatch(nameof(SituationalThoughtHandler.AppendSocialThoughts))] static class SituationalThoughtHandler_AppendSocialThoughts_Patch { [HarmonyPriority(Priority.First)] static bool Prefix(SituationalThoughtHandler __instance, Pawn otherPawn) { return !(otherPawn is Zombie || __instance.pawn is Zombie); } } [HarmonyPatch(typeof(Corpse))] [HarmonyPatch(nameof(Corpse.GiveObservedThought))] static class Corpse_GiveObservedThought_Patch { [HarmonyPriority(Priority.First)] static bool Prefix(Corpse __instance) { return !(__instance is ZombieCorpse); } } [HarmonyPatch(typeof(Corpse))] [HarmonyPatch(nameof(Corpse.GiveObservedHistoryEvent))] static class Corpse_GiveObservedHistoryEvent_Patch { [HarmonyPriority(Priority.First)] static bool Prefix(Corpse __instance) { return !(__instance is ZombieCorpse); } } // patch for disallowing thoughts on zombies // [HarmonyPatch(typeof(ThoughtUtility))] [HarmonyPatch(nameof(ThoughtUtility.CanGetThought))] static class ThoughtUtility_CanGetThought_Patch { [HarmonyPriority(Priority.First)] static bool Prefix(Pawn pawn, ref bool __result) { if (pawn is Zombie) { __result = false; return false; } return true; } } // patch for not forbidding zombie corpses // [HarmonyPatch(typeof(ForbidUtility))] [HarmonyPatch(nameof(ForbidUtility.SetForbiddenIfOutsideHomeArea))] static class ForbidUtility_SetForbiddenIfOutsideHomeArea_Patch { [HarmonyPriority(Priority.First)] static bool Prefix(Thing t) { return (t as ZombieCorpse == null); } } // patches to prevent interaction with zombies // [HarmonyPatch(typeof(Pawn_InteractionsTracker))] [HarmonyPatch(nameof(Pawn_InteractionsTracker.TryInteractWith))] static class Pawn_InteractionsTracker_TryInteractWith_Patch { static IEnumerable<CodeInstruction> Transpiler(ILGenerator generator, MethodBase method, IEnumerable<CodeInstruction> instructions) { var conditions = new List<CodeInstruction>(); conditions.AddRange(Tools.NotZombieInstructions(generator, method)); conditions.AddRange(Tools.NotZombieInstructions(generator, method, "recipient")); var transpiler = Tools.GenerateReplacementCallTranspiler(conditions); return transpiler(generator, instructions); } } [HarmonyPatch(typeof(Pawn_InteractionsTracker))] [HarmonyPatch(nameof(Pawn_InteractionsTracker.InteractionsTrackerTick))] static class Pawn_InteractionsTracker_InteractionsTrackerTick_Patch { static IEnumerable<CodeInstruction> Transpiler(ILGenerator generator, MethodBase method, IEnumerable<CodeInstruction> instructions) { var conditions = Tools.NotZombieInstructions(generator, method); var transpiler = Tools.GenerateReplacementCallTranspiler(conditions); return transpiler(generator, instructions); } } // patch to colorize the label of zombies that were colonists // [HarmonyPatch(typeof(PawnNameColorUtility))] [HarmonyPatch(nameof(PawnNameColorUtility.PawnNameColorOf))] static class PawnNameColorUtility_PawnNameColorOf_Patch { static Color zombieLabelColor = new Color(0.7f, 1f, 0.7f); [HarmonyPriority(Priority.First)] static bool Prefix(Pawn pawn, ref Color __result) { if (pawn is Zombie zombie && zombie.wasMapPawnBefore) { __result = zombieLabelColor; return false; } return true; } } // allow clicks on zombies that were colonists // [HarmonyPatch(typeof(ThingSelectionUtility))] [HarmonyPatch(nameof(ThingSelectionUtility.SelectableByMapClick))] static class ThingSelectionUtility_SelectableByMapClick_Patch { [HarmonyPriority(Priority.First)] static bool Prefix(Thing t, ref bool __result) { if (t is Zombie zombie && zombie.wasMapPawnBefore) { __result = true; return false; } return true; } } // patch for a custom zombie corpse class // [HarmonyPatch(typeof(ThingMaker))] [HarmonyPatch(nameof(ThingMaker.MakeThing))] static class ThingMaker_MakeThing_Patch { static void Prefix(ThingDef def) { if (def == null || def.IsCorpse == false) return; if (def.ingestible == null) return; if (def.ingestible.sourceDef is ThingDef_Zombie) { def.selectable = false; def.neverMultiSelect = true; def.drawGUIOverlay = false; def.hasTooltip = false; def.hideAtSnowDepth = 99f; def.inspectorTabs = new List<Type>(); def.passability = Traversability.Standable; def.stackLimit = 1; def.thingClass = typeof(ZombieCorpse); } } } // patch to make zombies always awake // [HarmonyPatch(typeof(PawnCapacitiesHandler))] [HarmonyPatch(nameof(PawnCapacitiesHandler.CanBeAwake), MethodType.Getter)] static class PawnCapacitiesHandler_CanBeAwake_Patch { static void Postfix(Pawn ___pawn, ref bool __result) { if (___pawn is Zombie) __result = true; } } // patch to handle targets downed so that we update our grid // [HarmonyPatch(typeof(Pawn_HealthTracker))] [HarmonyPatch(nameof(Pawn_HealthTracker.MakeDowned))] static class Pawn_HealthTracker_MakeDowned_Patch { static void Postfix(Pawn ___pawn) { if (___pawn is Zombie) return; if (___pawn == null || ___pawn.Map == null) return; var grid = ___pawn.Map.GetGrid(); if (Constants.KILL_CIRCLE_RADIUS_MULTIPLIER > 0) { var timestamp = grid.GetTimestamp(___pawn.Position); if (timestamp > 0) { var radius = Tools.RadiusForPawn(___pawn) * Constants.KILL_CIRCLE_RADIUS_MULTIPLIER; radius /= ZombieSettings.Values.zombieInstinct.HalfToDoubleValue(); Tools.GetCircle(radius).Do(vec => { var pos = ___pawn.Position + vec; var cell = grid.GetPheromone(pos, false); if (cell != null && cell.timestamp > 0 && cell.timestamp <= timestamp) cell.timestamp = 0; }); } } grid.SetTimestamp(___pawn.Position, 0); } } // patch to update twinkie graphics // [HarmonyPatch(typeof(Game))] [HarmonyPatch(nameof(Game.FinalizeInit))] static class Game_FinalizeInit_Patch { static void Postfix() { Tools.EnableTwinkie(ZombieSettings.Values.replaceTwinkie); } } // patches to update our zombie count grid // [HarmonyPatch(typeof(Map))] [HarmonyPatch(nameof(Map.FinalizeLoading))] static class Map_FinalizeLoading_Patch { static void Prefix(Map __instance) { var grid = __instance.GetGrid(); grid.IterateCellsQuick(cell => cell.zombieCount = 0); } } // patches to clean up after us // [HarmonyPatch(typeof(Root))] [HarmonyPatch(nameof(Root.Shutdown))] static class Root_Shutdown_Patch { static void Prefix() { Tools.avoider.running = false; // var maps = Find.Maps; // if (maps != null) // foreach (var map in maps) // map?.GetComponent<TickManager>()?.MapRemoved(); // // MemoryUtility.ClearAllMapsAndWorld(); } } // convert dying infected pawns when they start rotting // [HarmonyPatch(typeof(Corpse))] [HarmonyPatch(nameof(Corpse.RotStageChanged))] static class Corpse_RotStageChanged_Patch { static void Postfix(Corpse __instance) { var pawn = __instance.InnerPawn; if (pawn == null || pawn is Zombie || pawn.health == null || pawn.RaceProps.Humanlike == false) return; var rotStage = __instance.GetRotStage(); if (rotStage == RotStage.Fresh) return; var hasBrain = pawn.health.hediffSet.GetBrain() != null; if (hasBrain == false) return; var shouldBecomeZombie = pawn.health.hediffSet .GetHediffs<Hediff_Injury_ZombieBite>() .Any(zombieByte => zombieByte.TendDuration.InfectionStateBetween(InfectionState.BittenInfectable, InfectionState.Infected)); if (shouldBecomeZombie) { var map = ThingOwnerUtility.GetRootMap(__instance); if (map != null) Tools.QueueConvertToZombie(__instance, map); } } } [HarmonyPatch(typeof(Corpse))] [HarmonyPatch(nameof(Corpse.TickRare))] static class Corpse_TickRare_Patch { static void Postfix(Corpse __instance) { var pawn = __instance.InnerPawn; if (pawn == null || pawn is Zombie || pawn.health == null || pawn.RaceProps.Humanlike == false) return; var hasBrain = pawn.health.hediffSet.GetBrain() != null; if (hasBrain == false) return; var ticks = GenTicks.TicksGame; var shouldBecomeZombie = pawn.health.hediffSet .GetHediffs<Hediff_ZombieInfection>() .Any(infection => ticks > infection.ticksWhenBecomingZombie); if (shouldBecomeZombie) { var map = ThingOwnerUtility.GetRootMap(__instance); if (map != null) Tools.QueueConvertToZombie(__instance, map); } } } // show infection on dead pawns // [HarmonyPatch(typeof(HealthCardUtility))] [HarmonyPatch(nameof(HealthCardUtility.DrawOverviewTab))] static class HealthCardUtility_DrawOverviewTab_Patch { static void Postfix(Pawn pawn, Rect leftRect, ref float __result) { if (pawn == null || pawn.health == null) return; if (pawn.health.hediffSet.GetBrain() == null) return; if (pawn.Dead) { if (pawn.health.hediffSet.GetHediffs<Hediff_Injury_ZombieBite>() .All(zombieByte => zombieByte.mayBecomeZombieWhenDead == false)) return; } else { if (Tools.HasInfectionState(pawn, InfectionState.BittenInfectable, InfectionState.Infected) == false) return; } __result += 15f; GUI.color = Color.red; var text = "BodyIsInfectedLabel".Translate(); var textHeight = Text.CalcHeight(text, leftRect.width); Widgets.Label(new Rect(0f, __result, leftRect.width, textHeight), text); TooltipHandler.TipRegion(new Rect(0f, __result, leftRect.width, textHeight), "BodyIsInfectedTooltip".Translate()); __result += textHeight; GUI.color = Color.white; } } // patch to handle targets deaths so that we update our grid // [HarmonyPatch(typeof(PawnComponentsUtility))] [HarmonyPatch(nameof(PawnComponentsUtility.RemoveComponentsOnKilled))] static class PawnComponentsUtility_RemoveComponentsOnKilled_Patch { static void Postfix(Pawn pawn) { if (pawn is Zombie || pawn.Map == null) return; if (Constants.KILL_CIRCLE_RADIUS_MULTIPLIER > 0) { var grid = pawn.Map.GetGrid(); var timestamp = grid.GetTimestamp(pawn.Position); var radius = Tools.RadiusForPawn(pawn) * Constants.KILL_CIRCLE_RADIUS_MULTIPLIER; radius /= ZombieSettings.Values.zombieInstinct.HalfToDoubleValue(); Tools.GetCircle(radius).Do(vec => { var pos = pawn.Position + vec; var cell = grid.GetPheromone(pos, false); if (cell != null && cell.timestamp > 0 && cell.timestamp <= timestamp) grid.SetTimestamp(pos, 0); }); } } } // patch to prevent thoughts on zombies // [HarmonyPatch(typeof(PawnDiedOrDownedThoughtsUtility))] [HarmonyPatch(nameof(PawnDiedOrDownedThoughtsUtility.TryGiveThoughts))] [HarmonyPatch(new Type[] { typeof(Pawn), typeof(DamageInfo?), typeof(PawnDiedOrDownedThoughtsKind) })] static class PawnDiedOrDownedThoughtsUtility_TryGiveThoughts_Patch { [HarmonyPriority(Priority.First)] static bool Prefix(Pawn victim) { return !(victim is Zombie); } } // patch to remove immunity ticks on zombies // [HarmonyPatch(typeof(ImmunityHandler))] [HarmonyPatch(nameof(ImmunityHandler.ImmunityHandlerTick))] static class ImmunityHandler_ImmunityHandlerTick_Patch { [HarmonyPriority(Priority.First)] static bool Prefix(ImmunityHandler __instance) { return !(__instance.pawn is Zombie); } } // patch to trigger on gun shots // [HarmonyPatch(typeof(Projectile))] [HarmonyPatch(nameof(Projectile.Launch))] [HarmonyPatch(new Type[] { typeof(Thing), typeof(Vector3), typeof(LocalTargetInfo), typeof(LocalTargetInfo), typeof(ProjectileHitFlags), typeof(bool), typeof(Thing), typeof(ThingDef) })] public static class Projectile_Launch_Patch { static void Postfix(Thing launcher, Vector3 origin, LocalTargetInfo usedTarget) { if (!(launcher is Pawn pawn) || pawn.Map == null) return; var noiseScale = 1f; if (pawn.equipment?.PrimaryEq?.PrimaryVerb?.verbProps != null) noiseScale = pawn.equipment.PrimaryEq.PrimaryVerb.verbProps.muzzleFlashScale / Constants.BASE_MUZZLE_FLASH_VALUE; var now = Tools.Ticks(); var pos = origin.ToIntVec3(); var magnitude = usedTarget == null ? (Constants.MIN_WEAPON_RANGE + Constants.MAX_WEAPON_RANGE) / 2 : (usedTarget.CenterVector3 - origin).magnitude * noiseScale * Math.Min(1f, ZombieSettings.Values.zombieInstinct.HalfToDoubleValue()); var radius = Tools.Boxed(magnitude, Constants.MIN_WEAPON_RANGE, Constants.MAX_WEAPON_RANGE); var grid = pawn.Map.GetGrid(); Tools.GetCircle(radius).Do(vec => grid.BumpTimestamp(pos + vec, now - vec.LengthHorizontalSquared)); } static float GetDistanceTraveled(float velocity, float angle, float shotHeight) { if (shotHeight < 0.001f) return (velocity * velocity / 9.8f) * Mathf.Sin(2f * angle); var velsin = velocity * Mathf.Sin(angle); return ((velocity * Mathf.Cos(angle)) / 9.8f) * (velsin + Mathf.Sqrt(velsin * velsin + 2f * 9.8f * shotHeight)); } static void PostfixCombatExtended(Thing launcher, Vector2 origin, float shotAngle, float shotHeight, float shotSpeed) { if (!(launcher is Pawn pawn)) return; if (launcher.Map == null) return; var noiseScale = 1f; if (pawn.equipment?.PrimaryEq?.PrimaryVerb?.verbProps != null) noiseScale = pawn.equipment.PrimaryEq.PrimaryVerb.verbProps.muzzleFlashScale / Constants.BASE_MUZZLE_FLASH_VALUE; var now = Tools.Ticks(); var pos = new IntVec3(origin); var delta = GetDistanceTraveled(shotSpeed, shotAngle, shotHeight); var magnitude = noiseScale * delta * Math.Min(1f, ZombieSettings.Values.zombieInstinct.HalfToDoubleValue()); var radius = Tools.Boxed(magnitude, Constants.MIN_WEAPON_RANGE, Constants.MAX_WEAPON_RANGE); var grid = launcher.Map.GetGrid(); Tools.GetCircle(radius).Do(vec => grid.BumpTimestamp(pos + vec, now - vec.LengthHorizontalSquared)); } // called from Main // public static void PatchCombatExtended(Harmony harmony) { // do not throw or error if this type does not exist // it only exists if CombatExtended is loaded (optional) // var t_ProjectileCE = AccessTools.TypeByName("CombatExtended.ProjectileCE"); if (t_ProjectileCE == null) return; var originalMethodInfo = AccessTools.Method(t_ProjectileCE, "Launch", new Type[] { typeof(Thing), typeof(Vector2), typeof(float), typeof(float), typeof(float), typeof(float), typeof(Thing) }); if (originalMethodInfo == null) { Error("Combat Extended installed, but method ProjectileCE.Launch not found"); return; } var postfix = new HarmonyMethod(SymbolExtensions.GetMethodInfo(() => PostfixCombatExtended(null, Vector2.zero, 0, 0, 0))); _ = harmony.Patch(originalMethodInfo, null, postfix); } } // patch to allow zombies to occupy the same spot without collision // [HarmonyPatch(typeof(Pawn_PathFollower))] [HarmonyPatch(nameof(Pawn_PathFollower.WillCollideWithPawnOnNextPathCell))] static class Pawn_PathFollower_WillCollideWithPawnOnNextPathCell_Patch { [HarmonyPriority(Priority.First)] static bool Prefix(Pawn ___pawn, ref bool __result) { if (___pawn is Zombie) { __result = false; return false; } return true; } } // [HarmonyPatch(typeof(PawnCollisionTweenerUtility))] [HarmonyPatch(nameof(PawnCollisionTweenerUtility.PawnCollisionPosOffsetFor))] static class PawnCollisionTweenerUtility_PawnCollisionPosOffsetFor_Patch { [HarmonyPriority(Priority.First)] static bool Prefix(Pawn pawn, ref Vector3 __result) { if (!(pawn is Zombie)) return true; __result = Vector3.zero; return false; } } // patches so that zombies do not have needs // [HarmonyPatch(typeof(Pawn_NeedsTracker))] [HarmonyPatch(nameof(Pawn_NeedsTracker.AllNeeds), MethodType.Getter)] static class Pawn_NeedsTracker_AllNeeds_Patch { static List<Need> Replacement() { return new List<Need>(); } static IEnumerable<CodeInstruction> Transpiler(ILGenerator generator, MethodBase method, IEnumerable<CodeInstruction> instructions) { var conditions = Tools.NotZombieInstructions(generator, method); var replacement = SymbolExtensions.GetMethodInfo(() => Replacement()); var transpiler = Tools.GenerateReplacementCallTranspiler(conditions, method, replacement); return transpiler(generator, instructions); } } [HarmonyPatch(typeof(Pawn_NeedsTracker))] [HarmonyPatch(nameof(Pawn_NeedsTracker.AddOrRemoveNeedsAsAppropriate))] static class Pawn_NeedsTracker_AddOrRemoveNeedsAsAppropriate_Patch { static IEnumerable<CodeInstruction> Transpiler(ILGenerator generator, MethodBase method, IEnumerable<CodeInstruction> instructions) { var conditions = Tools.NotZombieInstructions(generator, method); var transpiler = Tools.GenerateReplacementCallTranspiler(conditions, method); return transpiler(generator, instructions); } } // patches so zombies don't use clamors at all // [HarmonyPatch(typeof(GenClamor))] [HarmonyPatch(nameof(GenClamor.DoClamor))] [HarmonyPatch(new[] { typeof(Thing), typeof(IntVec3), typeof(float), typeof(ClamorDef) })] static class GenClamor_DoClamor_Patch { [HarmonyPriority(Priority.First)] static bool Prefix(Thing source) { return (source is Zombie) == false; } } [HarmonyPatch(typeof(Pawn))] [HarmonyPatch(nameof(Pawn.HearClamor))] static class Pawn_HearClamor_Patch { [HarmonyPriority(Priority.First)] static bool Prefix(Thing source) { return (source is Zombie) == false; } } // patches so that zombies have no records // [HarmonyPatch] static class Pawn_RecordsTracker_Increment_Patch { static IEnumerable<MethodBase> TargetMethods() { var type = typeof(Pawn_RecordsTracker); yield return AccessTools.Method(type, nameof(Pawn_RecordsTracker.AddTo)); yield return AccessTools.Method(type, nameof(Pawn_RecordsTracker.RecordsTickUpdate)); yield return AccessTools.Method(type, nameof(Pawn_RecordsTracker.Increment)); } static IEnumerable<CodeInstruction> Transpiler(ILGenerator generator, MethodBase method, IEnumerable<CodeInstruction> instructions) { var conditions = Tools.NotZombieInstructions(generator, method); var transpiler = Tools.GenerateReplacementCallTranspiler(conditions, method); return transpiler(generator, instructions); } } [HarmonyPatch(typeof(Pawn_RecordsTracker))] [HarmonyPatch(nameof(Pawn_RecordsTracker.GetValue))] static class Pawn_RecordsTracker_GetValue_Patch { static bool Prefix(Pawn ___pawn, ref float __result) { if (___pawn is Zombie) { __result = 0; return false; } return true; } } [HarmonyPatch(typeof(Pawn_RecordsTracker))] [HarmonyPatch(nameof(Pawn_RecordsTracker.GetAsInt))] static class Pawn_RecordsTracker_GetAsInt_Patch { static bool Prefix(Pawn ___pawn, ref int __result) { if (___pawn is Zombie) { __result = 0; return false; } return true; } } // patch so zombies get less move cost from tar slime // [HarmonyPatch(typeof(Pawn_PathFollower))] [HarmonyPatch(nameof(Pawn_PathFollower.CostToMoveIntoCell))] [HarmonyPatch(new[] { typeof(Pawn), typeof(IntVec3) })] static class Pawn_PathFollower_CostToMoveIntoCell_Patch { static void Postfix(Pawn pawn, IntVec3 c, ref int __result) { if ((pawn is Zombie) == false) return; if (__result < 450) return; if (pawn.Map.thingGrid.ThingAt<TarSlime>(c) != null) __result = 100; } } // patch so zombies do not bleed // [HarmonyPatch(typeof(Pawn_HealthTracker))] [HarmonyPatch(nameof(Pawn_HealthTracker.DropBloodFilth))] static class Pawn_HealthTracker_DropBloodFilth_Patch { static bool SkipDropBlood(Pawn pawn) { if (!(pawn is Zombie zombie)) return false; if (ZombieSettings.Values.zombiesDropBlood == false) return true; if (zombie.hasTankyShield > 0 || zombie.hasTankySuit > 0) return true; return false; } static IEnumerable<CodeInstruction> Transpiler(IEnumerable<CodeInstruction> instructions, ILGenerator generator) { var jump = generator.DefineLabel(); yield return new CodeInstruction(OpCodes.Ldarg_0); yield return new CodeInstruction(OpCodes.Ldfld, typeof(Pawn_HealthTracker).Field("pawn")); yield return new CodeInstruction(OpCodes.Call, SymbolExtensions.GetMethodInfo(() => SkipDropBlood(null))); yield return new CodeInstruction(OpCodes.Brfalse, jump); yield return new CodeInstruction(OpCodes.Ret); var list = instructions.ToList(); list[0].labels.Add(jump); foreach (var instr in list) yield return instr; } } // patch to insert our settings page // [HarmonyPatch(typeof(Scenario))] [HarmonyPatch(nameof(Scenario.GetFirstConfigPage))] static class Scenario_GetFirstConfigPage_Patch { static IEnumerable<CodeInstruction> Transpiler(IEnumerable<CodeInstruction> instructions) { var found = false; foreach (var instruction in instructions) { var constructorInfo = instruction.operand as ConstructorInfo; var constructorName = constructorInfo?.DeclaringType.Name ?? ""; if (constructorName == "Page_SelectLandingSite" || constructorName == "Page_SelectStartingSite") { yield return new CodeInstruction(OpCodes.Newobj, AccessTools.Constructor(typeof(SettingsDialog))); yield return new CodeInstruction(OpCodes.Callvirt, AccessTools.Method(typeof(List<Page>), nameof(List<Page>.Add))); yield return new CodeInstruction(OpCodes.Ldloc_0); found = true; } yield return instruction; } if (!found) Error("Unexpected code in patch " + MethodBase.GetCurrentMethod().DeclaringType); } } // set hostility response to attack as default // [HarmonyPatch(typeof(Game))] [HarmonyPatch(nameof(Game.InitNewGame))] class Game_InitNewGame_Patch { static void Postfix() { Find.CurrentMap?.mapPawns.FreeColonists .Do(pawn => pawn.playerSettings.hostilityResponse = HostilityResponseMode.Attack); } } // suppress memories of zombie violence // [HarmonyPatch(typeof(Pawn_HealthTracker))] [HarmonyPatch(nameof(Pawn_HealthTracker.PreApplyDamage))] static class Pawn_HealthTracker_PreApplyDamage_Patch { static IEnumerable<CodeInstruction> Transpiler(IEnumerable<CodeInstruction> instructions, ILGenerator generator) { var m_TryGainMemory = typeof(MemoryThoughtHandler).MethodNamed(nameof(MemoryThoughtHandler.TryGainMemory), new Type[] { typeof(ThoughtDef), typeof(Pawn), typeof(Precept) }); var f_pawn = typeof(Pawn_HealthTracker).Field("pawn"); var found1 = false; var found2 = false; var list = instructions.ToList(); var jumpIndex = list.FirstIndexOf(instr => instr.Calls(m_TryGainMemory)) + 1; if (jumpIndex > 0 && jumpIndex < list.Count()) { var skipLabel = generator.DefineLabel(); list[jumpIndex].labels.Add(skipLabel); found1 = true; for (var i = jumpIndex; i >= 0; i--) if (list[i].IsLdarg(0)) { var j = i; list.Insert(j++, new CodeInstruction(OpCodes.Ldarg_0)); list.Insert(j++, new CodeInstruction(OpCodes.Ldfld, f_pawn)); list.Insert(j++, new CodeInstruction(OpCodes.Isinst, typeof(Zombie))); list.Insert(j++, new CodeInstruction(OpCodes.Brtrue_S, skipLabel)); found2 = true; break; } } foreach (var instruction in list) yield return instruction; if (!found1 || !found2) Error("Unexpected code in patch " + MethodBase.GetCurrentMethod().DeclaringType); } } // patch to add our settings to the main bottom-right menu // [HarmonyPatch(typeof(MainTabWindow_Menu))] [HarmonyPatch(nameof(MainTabWindow_Menu.RequestedTabSize), MethodType.Getter)] static class MainTabWindow_Menu_RequestedTabSize_Path { static void Postfix(ref Vector2 __result) { __result.y += MainMenuDrawer_DoMainMenuControls_Path.addedHeight; } } [HarmonyPatch(typeof(MainTabWindow_Menu))] [HarmonyPatch(nameof(MainTabWindow_Menu.DoWindowContents))] static class MainTabWindow_Menu_DoWindowContents_Path { static void Prefix(ref Rect rect) { rect.height += MainMenuDrawer_DoMainMenuControls_Path.addedHeight; } } [HarmonyPatch(typeof(Widgets))] [HarmonyPatch(nameof(Widgets.ButtonTextWorker))] static class Widgets_ButtonText_Path { static void NewDrawAtlas(Rect rect, Texture2D atlas, string label) { Widgets.DrawAtlas(rect, atlas); if (label == "Zombieland") { var texture = Tools.GetZombieButtonBackground(); GUI.DrawTexture(rect, texture, ScaleMode.StretchToFill, true, 0f); } } static IEnumerable<CodeInstruction> Transpiler(IEnumerable<CodeInstruction> instructions) { var from = typeof(Widgets).MethodNamed(nameof(Widgets.DrawAtlas), new Type[] { typeof(Rect), typeof(Texture2D) }); var to = SymbolExtensions.GetMethodInfo(() => NewDrawAtlas(Rect.zero, null, null)); var found = false; foreach (var instruction in instructions) { if (instruction.Calls(from)) { instruction.operand = to; yield return new CodeInstruction(OpCodes.Ldarg_1); found = true; } yield return instruction; } if (!found) Error("Unexpected code in patch " + MethodBase.GetCurrentMethod().DeclaringType); } } [HarmonyPatch(typeof(MainMenuDrawer))] [HarmonyPatch(nameof(MainMenuDrawer.DoMainMenuControls))] static class MainMenuDrawer_DoMainMenuControls_Path { // called from MainTabWindow_Menu_RequestedTabSize_Path public static float addedHeight = 45f + 7f; // default height ListableOption + OptionListingUtility.DrawOptionListing spacing static readonly MethodInfo[] patchMethods = new MethodInfo[] { SymbolExtensions.GetMethodInfo(() => DrawOptionListingPatch1(Rect.zero, null)), SymbolExtensions.GetMethodInfo(() => DrawOptionListingPatch2(Rect.zero, null)) }; static float DrawOptionListingPatch1(Rect rect, List<ListableOption> optList) { if (Current.ProgramState == ProgramState.Playing) { var label = "Options".Translate(); var idx = optList.FirstIndexOf(opt => opt.label == label); if (idx > 0 && idx < optList.Count()) optList.Insert(idx, new ListableOption("Zombieland", delegate { MainMenuDrawer.CloseMainTab(); var dialog = new Dialog_ModSettings(); var me = LoadedModManager.GetMod<ZombielandMod>(); dialog.selMod = me; Find.WindowStack.Add(dialog); }, null)); } return OptionListingUtility.DrawOptionListing(rect, optList); } static float DrawOptionListingPatch2(Rect rect, List<ListableOption> optList) { if (Current.ProgramState == ProgramState.Playing) { var item = new ListableOption_WebLink("Brrainz", "http://patreon.com/pardeike", Tools.GetMenuIcon()); optList.Add(item); } return OptionListingUtility.DrawOptionListing(rect, optList); } static IEnumerable<CodeInstruction> Transpiler(IEnumerable<CodeInstruction> instructions) { var m_DrawOptionListing = SymbolExtensions.GetMethodInfo(() => OptionListingUtility.DrawOptionListing(Rect.zero, null)); var counter = 0; foreach (var instruction in instructions) { if (instruction.Calls(m_DrawOptionListing)) instruction.operand = patchMethods[counter++]; yield return instruction; } if (counter != 2) Error("Unexpected code in patch " + MethodBase.GetCurrentMethod().DeclaringType); } } // update zombie pathing // [HarmonyPatch(typeof(RegionAndRoomUpdater))] [HarmonyPatch(nameof(RegionAndRoomUpdater.CreateOrUpdateRooms))] static class RegionAndRoomUpdater_CreateOrUpdateRooms_Patch { static void Postfix(Map ___map) { ___map.GetComponent<TickManager>()?.zombiePathing?.UpdateRegions(); } } // adding roping job // [HarmonyPatch(typeof(FloatMenuMakerMap))] [HarmonyPatch(nameof(FloatMenuMakerMap.AddDraftedOrders))] static class FloatMenuMakerMap_AddHumanlikeOrders_Patch { static void Postfix(Vector3 clickPos, Pawn pawn, List<FloatMenuOption> opts) { var ropableZombie = pawn.Map.GetComponent<TickManager>().GetRopableZombie(clickPos); if (ropableZombie != null) { void job() => pawn.jobs.StartJob(new Job(CustomDefs.RopeZombie, ropableZombie), JobCondition.InterruptForced, null, true); opts.Add(new FloatMenuOption($"RopeZombie".Translate(), job)); } } } } }
33.406187
237
0.690105
[ "MIT" ]
X-EcutiOnner/Zombieland
Source/Patches.cs
165,249
C#