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
// Copyright (c) .NET Foundation. All rights reserved. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using System.Security.Claims; namespace Microsoft.AspNetCore.Authentication { /// <summary> /// Contains user identity information as well as additional authentication state. /// </summary> public class AuthenticationTicket { /// <summary> /// Initializes a new instance of the <see cref="AuthenticationTicket"/> class /// </summary> /// <param name="principal">the <see cref="ClaimsPrincipal"/> that represents the authenticated user.</param> /// <param name="properties">additional properties that can be consumed by the user or runtime.</param> /// <param name="authenticationScheme">the authentication middleware that was responsible for this ticket.</param> public AuthenticationTicket(ClaimsPrincipal principal, AuthenticationProperties? properties, string? authenticationScheme) { if (principal == null) { throw new ArgumentNullException(nameof(principal)); } AuthenticationScheme = authenticationScheme; Principal = principal; Properties = properties ?? new AuthenticationProperties(); } /// <summary> /// Initializes a new instance of the <see cref="AuthenticationTicket"/> class /// </summary> /// <param name="principal">the <see cref="ClaimsPrincipal"/> that represents the authenticated user.</param> /// <param name="authenticationScheme">the authentication middleware that was responsible for this ticket.</param> public AuthenticationTicket(ClaimsPrincipal principal, string authenticationScheme) : this(principal, properties: null, authenticationScheme: authenticationScheme) { } /// <summary> /// Gets the authentication type. /// </summary> public string? AuthenticationScheme { get; private set; } /// <summary> /// Gets the claims-principal with authenticated user identities. /// </summary> public ClaimsPrincipal Principal { get; private set; } /// <summary> /// Additional state values for the authentication session. /// </summary> public AuthenticationProperties Properties { get; private set; } /// <summary> /// Returns a copy of the ticket. /// Note: the claims principal will be cloned by calling Clone() on each of the Identities. /// </summary> /// <returns>A copy of the ticket</returns> public AuthenticationTicket Clone() { var principal = new ClaimsPrincipal(); foreach (var identity in Principal.Identities) { principal.AddIdentity(identity.Clone()); } return new AuthenticationTicket(principal, Properties.Clone(), AuthenticationScheme); } } }
42.5
130
0.641176
[ "Apache-2.0" ]
Blubern/AspNetCore
src/Http/Authentication.Abstractions/src/AuthenticationTicket.cs
3,060
C#
using CakeMail.RestClient.Exceptions; using Shouldly; using System; using Xunit; namespace CakeMail.RestClient.UnitTests.Exceptions { public class CakeMailPostExceptionTests { [Fact] public void CakeMailPostException_Constructor_with_message_and_postdata_and_diagnostic() { // Arrange var message = "This is a dummy message"; var postData = "This is a sample"; var diagnosticLog = "This is the diagnostic log"; // Act var exception = new CakeMailPostException(message, postData, diagnosticLog); // Assert exception.Message.ShouldBe(message); exception.PostData.ShouldBe(postData); exception.DiagnosticLog.ShouldBe(diagnosticLog); exception.InnerException.ShouldBeNull(); } [Fact] public void CakeMailPostException_Constructor_with_message_and_postdata_and_diagnostic_and_innerexception() { // Arrange var message = "This is a dummy message"; var postData = "This is a sample"; var diagnosticLog = "This is the diagnostic log"; var innerException = new Exception("Testing"); // Act var exception = new CakeMailPostException(message, postData, diagnosticLog, innerException); // Assert exception.Message.ShouldBe(message); exception.PostData.ShouldBe(postData); exception.DiagnosticLog.ShouldBe(diagnosticLog); exception.InnerException.ShouldNotBeNull(); exception.InnerException.Message.ShouldBe(innerException.Message); } } }
29.040816
109
0.761068
[ "MIT" ]
Jericho/CakeMail.RestClient
Source/CakeMail.RestClient.UnitTests/Exceptions/CakeMailPostExceptionTests.cs
1,423
C#
// <auto-generated /> using System; using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Infrastructure; using Microsoft.EntityFrameworkCore.Migrations; using Microsoft.EntityFrameworkCore.Storage.ValueConversion; using MyWallWebAPI; namespace MyWallWebAPI.Migrations { [DbContext(typeof(MySQLContext))] [Migration("20210727182455_Authentication")] partial class Authentication { protected override void BuildTargetModel(ModelBuilder modelBuilder) { #pragma warning disable 612, 618 modelBuilder .HasAnnotation("Relational:MaxIdentifierLength", 64) .HasAnnotation("ProductVersion", "5.0.8"); modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRole", b => { b.Property<string>("Id") .HasColumnType("varchar(255)"); b.Property<string>("ConcurrencyStamp") .IsConcurrencyToken() .HasColumnType("longtext"); b.Property<string>("Discriminator") .IsRequired() .HasColumnType("longtext"); b.Property<string>("Name") .HasMaxLength(256) .HasColumnType("varchar(256)"); b.Property<string>("NormalizedName") .HasMaxLength(256) .HasColumnType("varchar(256)"); b.HasKey("Id"); b.HasIndex("NormalizedName") .IsUnique() .HasDatabaseName("RoleNameIndex"); b.ToTable("AspNetRoles"); b.HasDiscriminator<string>("Discriminator").HasValue("IdentityRole"); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRoleClaim<string>", b => { b.Property<int>("Id") .ValueGeneratedOnAdd() .HasColumnType("int"); b.Property<string>("ClaimType") .HasColumnType("longtext"); b.Property<string>("ClaimValue") .HasColumnType("longtext"); b.Property<string>("RoleId") .IsRequired() .HasColumnType("varchar(255)"); b.HasKey("Id"); b.HasIndex("RoleId"); b.ToTable("AspNetRoleClaims"); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserClaim<string>", b => { b.Property<int>("Id") .ValueGeneratedOnAdd() .HasColumnType("int"); b.Property<string>("ClaimType") .HasColumnType("longtext"); b.Property<string>("ClaimValue") .HasColumnType("longtext"); b.Property<string>("UserId") .IsRequired() .HasColumnType("varchar(255)"); b.HasKey("Id"); b.HasIndex("UserId"); b.ToTable("AspNetUserClaims"); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserLogin<string>", b => { b.Property<string>("LoginProvider") .HasColumnType("varchar(255)"); b.Property<string>("ProviderKey") .HasColumnType("varchar(255)"); b.Property<string>("ProviderDisplayName") .HasColumnType("longtext"); b.Property<string>("UserId") .IsRequired() .HasColumnType("varchar(255)"); b.HasKey("LoginProvider", "ProviderKey"); b.HasIndex("UserId"); b.ToTable("AspNetUserLogins"); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserRole<string>", b => { b.Property<string>("UserId") .HasColumnType("varchar(255)"); b.Property<string>("RoleId") .HasColumnType("varchar(255)"); b.HasKey("UserId", "RoleId"); b.HasIndex("RoleId"); b.ToTable("AspNetUserRoles"); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserToken<string>", b => { b.Property<string>("UserId") .HasColumnType("varchar(255)"); b.Property<string>("LoginProvider") .HasColumnType("varchar(255)"); b.Property<string>("Name") .HasColumnType("varchar(255)"); b.Property<string>("Value") .HasColumnType("longtext"); b.HasKey("UserId", "LoginProvider", "Name"); b.ToTable("AspNetUserTokens"); }); modelBuilder.Entity("MyWallWebAPI.Domain.Models.ApplicationUser", b => { b.Property<string>("Id") .HasColumnType("varchar(255)"); b.Property<int>("AccessFailedCount") .HasColumnType("int"); b.Property<string>("ConcurrencyStamp") .IsConcurrencyToken() .HasColumnType("longtext"); b.Property<string>("Email") .HasMaxLength(256) .HasColumnType("varchar(256)"); b.Property<bool>("EmailConfirmed") .HasColumnType("tinyint(1)"); b.Property<bool>("LockoutEnabled") .HasColumnType("tinyint(1)"); b.Property<DateTimeOffset?>("LockoutEnd") .HasColumnType("datetime(6)"); b.Property<string>("NormalizedEmail") .HasMaxLength(256) .HasColumnType("varchar(256)"); b.Property<string>("NormalizedUserName") .HasMaxLength(256) .HasColumnType("varchar(256)"); b.Property<string>("PasswordHash") .HasColumnType("longtext"); b.Property<string>("PhoneNumber") .HasColumnType("longtext"); b.Property<bool>("PhoneNumberConfirmed") .HasColumnType("tinyint(1)"); b.Property<string>("SecurityStamp") .HasColumnType("longtext"); b.Property<bool>("TwoFactorEnabled") .HasColumnType("tinyint(1)"); b.Property<string>("UserName") .HasMaxLength(256) .HasColumnType("varchar(256)"); b.HasKey("Id"); b.HasIndex("NormalizedEmail") .HasDatabaseName("EmailIndex"); b.HasIndex("NormalizedUserName") .IsUnique() .HasDatabaseName("UserNameIndex"); b.ToTable("AspNetUsers"); }); modelBuilder.Entity("MyWallWebAPI.Post", b => { b.Property<int>("Id") .ValueGeneratedOnAdd() .HasColumnType("int"); b.Property<string>("Conteudo") .HasColumnType("longtext"); b.Property<DateTime>("Data") .HasColumnType("datetime(6)"); b.Property<string>("Titulo") .HasColumnType("longtext"); b.HasKey("Id"); b.ToTable("Post"); }); modelBuilder.Entity("MyWallWebAPI.Domain.Models.ApplicationRole", b => { b.HasBaseType("Microsoft.AspNetCore.Identity.IdentityRole"); b.HasDiscriminator().HasValue("ApplicationRole"); }); 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("MyWallWebAPI.Domain.Models.ApplicationUser", null) .WithMany() .HasForeignKey("UserId") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserLogin<string>", b => { b.HasOne("MyWallWebAPI.Domain.Models.ApplicationUser", null) .WithMany() .HasForeignKey("UserId") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserRole<string>", b => { b.HasOne("Microsoft.AspNetCore.Identity.IdentityRole", null) .WithMany() .HasForeignKey("RoleId") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); b.HasOne("MyWallWebAPI.Domain.Models.ApplicationUser", null) .WithMany() .HasForeignKey("UserId") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserToken<string>", b => { b.HasOne("MyWallWebAPI.Domain.Models.ApplicationUser", null) .WithMany() .HasForeignKey("UserId") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); }); #pragma warning restore 612, 618 } } }
35.986711
95
0.457072
[ "MIT" ]
kazuuu/curso-dotnet-core-web-api
MyWallWebAPI/MyWallWebAPI/Migrations/20210727182455_Authentication.Designer.cs
10,834
C#
using System.ComponentModel.DataAnnotations; using Domain.Base; using Newtonsoft.Json; namespace Domain.Entities { public class Booking : BaseEntity { [Required(ErrorMessage = "Inmate is a required field")] public Inmate Inmate { get; set; } [Required(ErrorMessage = "BookingAgency is a required field")] public string BookingAgency { get; set; } [Required(ErrorMessage = "BookingType is a required field")] public string BookingType { get; set; } public override string ToString() { return JsonConvert.SerializeObject(this); } } }
25.545455
64
0.731317
[ "MIT" ]
c1kad14/cosmos-api
CosmosAPI/Domain/Entities/Booking.cs
564
C#
using System.Collections.Generic; using ProSuite.Commons.Essentials.Assertions; namespace ProSuite.QA.Container.TestContainer { public class BaseRowComparer : IEqualityComparer<BaseRow> { public bool Equals(BaseRow x, BaseRow y) { // Assumption : // x.Feature.Table = y.Feature.Table if (x == y) { return true; } if (x.OID != y.OID) { return false; } if (x.UniqueId != null && y.UniqueId != null) { return x.UniqueId.Id == y.UniqueId.Id; } if (x.Table != null && x.Table.HasOID) { return true; } if (! x.Extent.Equals(y.Extent)) { return false; } return CompareObjectIds(x, y); } // compare integer fields, which include also ObjectID fields private static bool CompareObjectIds(BaseRow x, BaseRow y) { int oidCount = x.OidList.Count; if (oidCount != y.OidList.Count) { return false; } for (var oidIndex = 0; oidIndex < oidCount; oidIndex++) { if (x.OidList[oidIndex] != y.OidList[oidIndex]) { return false; } } // --> all ObjectID fields are equal return true; } public int GetHashCode(BaseRow obj) { if (obj.UniqueId?.Id != null) { return obj.UniqueId.Id; } int oid = obj.OID; Assert.True(oid >= 0, "negative OID, but no assigned UniqueId"); return oid; } } }
17.441558
67
0.611318
[ "MIT" ]
ProSuite/ProSuite
src/ProSuite.QA.Container/TestContainer/BaseRowComparer.cs
1,343
C#
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.IO; using System.Linq; using System.Text; using System.Threading; using System.Threading.Tasks; using System.Windows.Forms; namespace CountLines { public partial class MainWindow : Form { /// <summary> /// the dialog to choose the root (project) dir /// </summary> private readonly OpenFileDialog _dialog = new OpenFileDialog(); /// <summary> /// the cancellation token source to cancel the run /// </summary> private CancellationTokenSource _cancelToken = new CancellationTokenSource(); /// <summary> /// the result for the current run /// </summary> private static CountLinesResult _currentResult; /// <summary> /// the total files to scan (for the current run) /// </summary> private static long _totalFilesToScan = 0; public MainWindow() { InitializeComponent(); _dialog.Multiselect = false; _dialog.RestoreDirectory = true; _dialog.Title = @"Choose file in target directory"; btnCancel.Enabled = false; //btnPause.Enabled = false; tbIgnoreList.AllowDrop = true; tbIgnoreList.DragEnter += (sender, args) => { if (args.Data.GetDataPresent(DataFormats.FileDrop)) { args.Effect = DragDropEffects.Link; } }; tbIgnoreList.DragDrop += (sender, args) => { if (args.Data.GetDataPresent(DataFormats.FileDrop)) { var paths = (string[]) args.Data.GetData(DataFormats.FileDrop); foreach (var path in paths) { var fileInfo = new FileInfo(path); if (fileInfo.Exists) { //it's a file tbIgnoreList.AppendText(Environment.NewLine + fileInfo.FullName); } var dirInfo = new DirectoryInfo(path); if (dirInfo.Exists) { //it's a dir tbIgnoreList.AppendText(Environment.NewLine + fileInfo.FullName); } } FormatIgnoreList(); } }; } /// <summary> /// formats the ignore list entries /// removes duplicate entries /// </summary> private void FormatIgnoreList() { string[] lines = tbIgnoreList.Lines; var dict = new HashSet<string>(); foreach (var line in lines) { if (String.IsNullOrWhiteSpace(line)) continue; dict.Add(line.Trim()); } tbIgnoreList.Lines = dict.ToArray(); } private async void btnStart_Click(object sender, EventArgs e) { rbAllLines.Enabled = false; rbIgnoreEmptyLines.Enabled = false; rbIgnoreEmptyOrWhitespaceLines.Enabled = false; _currentResult = new CountLinesResult(); lbInfo.Text = ""; numIgnoreRules.Text = ""; _totalFilesToScan = 0; progBar.Value = 0; tbFoundFiles.Clear(); bool ignoreEmptyLines = rbIgnoreEmptyLines.Checked; bool ignoreEmptyorWhitespaceLines = rbIgnoreEmptyOrWhitespaceLines.Checked; if (String.IsNullOrWhiteSpace(tbRootDir.Text)) return; //get the root directory var rootDir = new DirectoryInfo(tbRootDir.Text.Trim()); if (!rootDir.Exists) { MessageBox.Show(@"Root directory path is not a directory"); ResetButtons(); return; } //get extensions var extensions = tbExtensions.Text.Split(new char[] {','}, StringSplitOptions.RemoveEmptyEntries).ToList(); if (extensions.Count == 0) { MessageBox.Show(@"No extensions provided"); ResetButtons(); return; } //get files and directories to ignore var ignoreList = new HashSet<string>(tbIgnoreList.Lines); //also add the ignore files lines if (string.IsNullOrEmpty(tbIgnoreFileConfig.Text) == false) { var ignoreFileInfo = new FileInfo(tbIgnoreFileConfig.Text); if (!ignoreFileInfo.Exists) { MessageBox.Show(@"Ignore file not found"); ResetButtons(); return; } var additionalRules = File.ReadAllLines(ignoreFileInfo.FullName).ToList(); additionalRules.ForEach(rule => ignoreList.Add(rule)); } var filesToIgnore = new List<FileInfo>(); var directoriesToIgnore = new List<DirectoryInfo>(); foreach (var ignoreItem in ignoreList) { if (ignoreItem.Trim().StartsWith("#")) continue; var infoDir = new DirectoryInfo(ignoreItem.Trim()); var infoFile = new FileInfo(ignoreItem.Trim()); if (!infoDir.Exists && !infoFile.Exists) { //maybe relative path?? infoDir = new DirectoryInfo(Path.Combine(rootDir.FullName, ignoreItem.Trim())); infoFile = new FileInfo(Path.Combine(rootDir.FullName, ignoreItem.Trim())); if (!infoDir.Exists && !infoFile.Exists) { MessageBox.Show(ignoreItem + " is not a directory or file"); ResetButtons(); return; } } if (infoDir.Exists) { directoriesToIgnore.Add(infoDir); } else if (infoFile.Exists) { filesToIgnore.Add(infoFile); } } numIgnoreRules.Text = "Ignore rules: " + (directoriesToIgnore.Count + filesToIgnore.Count); //btnPause.Enabled = true; btnCancel.Enabled = true; btnStart.Enabled = false; this._cancelToken = new CancellationTokenSource(); //cancelToken.Token.Register(ResetButtons); try { await this.CountFiles(rootDir, extensions.Select(p => "." + p).ToList(), filesToIgnore.Select(p => p.FullName).ToList(), directoriesToIgnore.Select(p => p.FullName).ToList() ); } catch (Exception) { //task was cancelled lbInfo.Text = "Was cancelled!"; ResetButtons(); return; } //set total files lbTotalFiles.Text = 0 + " / " + _totalFilesToScan; await this.Scan(rootDir, extensions.Select(p => "." + p).ToList(), filesToIgnore.Select(p => p.FullName).ToList(), directoriesToIgnore.Select(p => p.FullName).ToList(), ignoreEmptyLines, ignoreEmptyorWhitespaceLines ); lbTotalLines.Text = _currentResult.Lines.ToString(); if (_cancelToken.IsCancellationRequested) { lbInfo.Text = "Was cancelled!"; } else { lbInfo.Text = "Finished"; } ResetButtons(); } private void ResetButtons() { //btnPause.Enabled = false; btnCancel.Enabled = false; btnStart.Enabled = true; rbAllLines.Enabled = true; rbIgnoreEmptyLines.Enabled = true; rbIgnoreEmptyOrWhitespaceLines.Enabled = true; } private void btnCancel_Click(object sender, EventArgs e) { this._cancelToken.Cancel(); } private void btnRootDir_Click(object sender, EventArgs e) { var result = _dialog.ShowDialog(); if (result != DialogResult.OK) return; var info = new FileInfo(_dialog.FileName); if (!info.Exists) return; tbRootDir.Text = info.DirectoryName; } private void btnChooseIgnoreFile_Click(object sender, EventArgs e) { var result = _dialog.ShowDialog(); if (result != DialogResult.OK) return; var info = new FileInfo(_dialog.FileName); if (!info.Exists) return; tbIgnoreFileConfig.Text = info.FullName; } /// <summary> /// displays the new statistics /// </summary> /// <param name="fileFullPath">the full path of the current file</param> private void ReportProgress(string fileFullPath) { if (lbTotalLines.InvokeRequired) { Action invokeAction = () => { progBar.Value = (int) ((_currentResult.Files*100)/_totalFilesToScan); lbTotalFiles.Text = _currentResult.Files + " / " + _totalFilesToScan; lbTotalLines.Text = _currentResult.Lines.ToString(); tbFoundFiles.AppendText(Environment.NewLine + fileFullPath); }; this.Invoke(invokeAction); } } /// <summary> /// counts the files that will be scanned for lines /// </summary> /// <param name="rootDir">the root dir to start</param> /// <param name="extensions">the extensions for the files to scan (whitelist)</param> /// <param name="filesToignore">the files to ignore</param> /// <param name="directoriesToIgnore">the directories to ignore</param> /// <returns>the task</returns> private async Task CountFiles(DirectoryInfo rootDir, List<string> extensions, List<string> filesToignore, List<string> directoriesToIgnore) { await Task.Run(async () => { foreach (var fileInfo in rootDir.EnumerateFiles()) { //is the file ignored? if (filesToignore.Contains(fileInfo.FullName)) continue; //ensure the file extension is in the extensions list if (extensions.Contains(fileInfo.Extension) == false) continue; //scan file for lines _totalFilesToScan++; if (_cancelToken.Token.IsCancellationRequested) { _cancelToken.Token.ThrowIfCancellationRequested(); } } foreach (var directoryInfo in rootDir.EnumerateDirectories()) { //is the directory ignored? if (directoriesToIgnore.Contains(directoryInfo.FullName)) continue; await this.CountFiles( directoryInfo, extensions, filesToignore, directoriesToIgnore); } }, _cancelToken.Token); } /// <summary> /// scans/counts the lines of every file in the given root directory /// only if the file extensions is in the extensions list and /// only if the file is NOT in the ignore list /// also scans sub directories (only if the sub directory is NOT in the ignore list) /// </summary> /// <param name="rootDir">the root dir</param> /// <param name="extensions">the extensions</param> /// <param name="filesToignore">the files to ignore</param> /// <param name="directoriesToIgnore">the sub directories to ignore</param> /// <returns></returns> private async Task Scan(DirectoryInfo rootDir, List<string> extensions, List<string> filesToignore, List<string> directoriesToIgnore, bool ignoreEmptyLines, bool ignoreEmptyorWhitespaceLines) { await Task.Run(async () => { foreach (var fileInfo in rootDir.EnumerateFiles()) { //Thread.Sleep(1000); //is the file ignored? if (filesToignore.Contains(fileInfo.FullName)) continue; //ensure the file extension is in the extensions list if (extensions.Contains(fileInfo.Extension) == false) continue; int lines = 0; if (ignoreEmptyLines) { lines = File.ReadLines(fileInfo.FullName).Where(p => !string.IsNullOrEmpty(p)).Count(); } else if (ignoreEmptyorWhitespaceLines) { lines = File.ReadLines(fileInfo.FullName).Where(p => !string.IsNullOrWhiteSpace(p)).Count(); } else { lines = File.ReadLines(fileInfo.FullName).Count(); } _currentResult.Lines += lines; _currentResult.Files += 1; ReportProgress(fileInfo.FullName + "(" + lines + ")"); if (_cancelToken.Token.IsCancellationRequested) { return; } } foreach (var directoryInfo in rootDir.EnumerateDirectories()) { //is the directory ignored? if (directoriesToIgnore.Contains(directoryInfo.FullName)) continue; await this.Scan(directoryInfo, extensions, filesToignore, directoriesToIgnore, ignoreEmptyLines, ignoreEmptyorWhitespaceLines); } }, _cancelToken.Token); } } struct CountLinesResult { /// <summary> /// the amount of found files /// </summary> public long Files { get; set; } /// <summary> /// the amount of found lines /// </summary> public long Lines { get; set; } } }
33.350797
147
0.511919
[ "MIT" ]
janisdd/countlines
Form1.cs
14,643
C#
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; using TeleSharp.TL; namespace TeleSharp.TL { [TLObject(-373312269)] public class TLInputMediaPhoto : TLAbsInputMedia { public override int Constructor { get { return -373312269; } } public TLAbsInputPhoto Id { get; set; } public string Caption { get; set; } public void ComputeFlags() { } public override void DeserializeBody(BinaryReader br) { this.Id = (TLAbsInputPhoto)ObjectUtils.DeserializeObject(br); this.Caption = StringUtil.Deserialize(br); } public override void SerializeBody(BinaryWriter bw) { bw.Write(this.Constructor); ObjectUtils.SerializeObject(this.Id, bw); StringUtil.Serialize(this.Caption, bw); } } }
21.804348
73
0.589232
[ "MIT" ]
slctr/Men.Telegram.ClientApi
Men.Telegram.ClientApi/TL/TL/TLInputMediaPhoto.cs
1,003
C#
using JetBrains.Annotations; using UnityEngine; [RequireComponent(typeof(Rigidbody))] public class AvoidCollisions : MonoBehaviour { public float ResponseRate = 1; public bool SpeedScaling; private Rigidbody _rigidbody; [UsedImplicitly] private void Start () { this.AssignComponent(out _rigidbody); } [UsedImplicitly] private void OnTriggerStay(Collider other) { var otherPoint = _rigidbody.ClosestPointOnBounds(other.transform.position); var direction = (transform.position - otherPoint).normalized; var speed = SpeedScaling ? _rigidbody.velocity.magnitude : 1; _rigidbody.AddForce(direction * ResponseRate * speed); } }
26.916667
77
0.77709
[ "MIT" ]
kroltan/ld39
Assets/Scripts/AvoidCollisions.cs
648
C#
using System; using System.Collections; using System.Collections.Generic; using System.Globalization; using System.IO; using System.Linq; using System.Text; using System.Text.RegularExpressions; using Microsoft.Crm.Sdk.Messages; using Microsoft.Xrm.Sdk; using Microsoft.Xrm.Sdk.Messages; using Microsoft.Xrm.Sdk.Metadata; using Microsoft.Xrm.Sdk.Query; using Xrm.Oss.FluentQuery; using static Xrm.Oss.XTL.Interpreter.XTLInterpreter; namespace Xrm.Oss.XTL.Interpreter { #pragma warning disable S1104 // Fields should not have public accessibility public static class FunctionHandlers { private static ConfigHandler GetConfig(List<ValueExpression> parameters) { return new ConfigHandler((Dictionary<string, object>) parameters.LastOrDefault(p => p?.Value is Dictionary<string, object>)?.Value ?? new Dictionary<string, object>()); } public static FunctionHandler Not = (primary, service, tracing, organizationConfig, parameters) => { var target = parameters.FirstOrDefault(); var result = !CheckedCast<bool>(target?.Value, "Not expects a boolean input, consider using one of the Is methods"); return new ValueExpression(result.ToString(CultureInfo.InvariantCulture), result); }; public static FunctionHandler First = (primary, service, tracing, organizationConfig, parameters) => { if (parameters.Count != 1) { throw new InvalidPluginExecutionException("First expects a list as only parameter!"); } var firstParam = CheckedCast<List<ValueExpression>>(parameters.FirstOrDefault().Value, string.Empty, false)?.Select(v => v?.Value).ToList(); var entityCollection = CheckedCast<EntityCollection>(parameters.FirstOrDefault().Value, string.Empty, false)?.Entities.ToList(); if (firstParam == null && entityCollection == null) { throw new InvalidPluginExecutionException("First expects a list or EntityCollection as input"); } return new ValueExpression(string.Empty, firstParam?.FirstOrDefault() ?? entityCollection?.FirstOrDefault()); }; public static FunctionHandler Last = (primary, service, tracing, organizationConfig, parameters) => { if (parameters.Count != 1) { throw new InvalidPluginExecutionException("Last expects a list as only parameter!"); } var firstParam = CheckedCast<List<ValueExpression>>(parameters.FirstOrDefault().Value, string.Empty, false)?.Select(v => v?.Value).ToList(); var entityCollection = CheckedCast<EntityCollection>(parameters.FirstOrDefault().Value, string.Empty, false)?.Entities.ToList(); if (firstParam == null && entityCollection == null) { throw new InvalidPluginExecutionException("Last expects a list or EntityCollection as input"); } return new ValueExpression(string.Empty, firstParam?.LastOrDefault() ?? entityCollection?.LastOrDefault()); }; public static FunctionHandler IsLess = (primary, service, tracing, organizationConfig, parameters) => { bool result = Compare(parameters) < 0; return new ValueExpression(result.ToString(CultureInfo.InvariantCulture), result); }; public static FunctionHandler IsLessEqual = (primary, service, tracing, organizationConfig, parameters) => { bool result = Compare(parameters) <= 0; return new ValueExpression(result.ToString(CultureInfo.InvariantCulture), result); }; public static FunctionHandler IsGreater = (primary, service, tracing, organizationConfig, parameters) => { bool result = Compare(parameters) > 0; return new ValueExpression(result.ToString(CultureInfo.InvariantCulture), result); }; public static FunctionHandler IsGreaterEqual = (primary, service, tracing, organizationConfig, parameters) => { bool result = Compare(parameters) >= 0; return new ValueExpression(result.ToString(CultureInfo.InvariantCulture), result); }; private static int Compare(List<ValueExpression> parameters) { if (parameters.Count != 2) { throw new InvalidPluginExecutionException("IsLess expects exactly 2 parameters!"); } var actual = CheckedCast<IComparable>(parameters[0].Value, "Actual value is not comparable"); var expected = CheckedCast<IComparable>(parameters[1].Value, "Expected value is not comparable"); // Negative: actual is less than expected, 0: equal, 1: actual is greater than expected return actual.CompareTo(expected); } public static FunctionHandler IsEqual = (primary, service, tracing, organizationConfig, parameters) => { if (parameters.Count != 2) { throw new InvalidPluginExecutionException("IsEqual expects exactly 2 parameters!"); } var expected = parameters[0]; var actual = parameters[1]; var tempGuid = Guid.Empty; var falseReturn = new ValueExpression(bool.FalseString, false); var trueReturn = new ValueExpression(bool.TrueString, true); if (expected.Value == null && actual.Value == null) { return trueReturn; } if (expected.Value == null && actual.Value != null) { return falseReturn; } if (expected.Value != null && actual.Value == null) { return falseReturn; } if (new[] { expected.Value, actual.Value }.All(v => v is int || v is OptionSetValue)) { var values = new[] { expected.Value, actual.Value } .Select(v => v is OptionSetValue ? ((OptionSetValue)v).Value : (int)v) .ToList(); var optionSetResult = values[0].Equals(values[1]); return new ValueExpression(optionSetResult.ToString(CultureInfo.InvariantCulture), optionSetResult); } else if (new[] { expected.Value, actual.Value }.All(v => v is Guid || (v is string && Guid.TryParse((string) v, out tempGuid)) || v is EntityReference || v is Entity)) { var values = new[] { expected.Value, actual.Value } .Select(v => { if (v is Guid) { return (Guid) v; } if (v is string) { return tempGuid; } if (v is EntityReference) { return ((EntityReference) v).Id; } if (v is Entity) { return ((Entity) v).Id; } return Guid.Empty; }) .ToList(); var guidResult = values[0].Equals(values[1]); return new ValueExpression(guidResult.ToString(CultureInfo.InvariantCulture), guidResult); } else { var result = expected.Value.Equals(actual.Value); return new ValueExpression(result.ToString(CultureInfo.InvariantCulture), result); } }; public static FunctionHandler And = (primary, service, tracing, organizationConfig, parameters) => { if (parameters.Count < 2) { throw new InvalidPluginExecutionException("And expects at least 2 conditions!"); } if (parameters.Any(p => !(p.Value is bool))) { throw new InvalidPluginExecutionException("And: All conditions must be booleans!"); } if (parameters.All(p => (bool)p.Value)) { return new ValueExpression(bool.TrueString, true); } return new ValueExpression(bool.FalseString, false); }; public static FunctionHandler Or = (primary, service, tracing, organizationConfig, parameters) => { if (parameters.Count < 2) { throw new InvalidPluginExecutionException("Or expects at least 2 conditions!"); } if (parameters.Any(p => !(p.Value is bool))) { throw new InvalidPluginExecutionException("Or: All conditions must be booleans!"); } if (parameters.Any(p => (bool)p.Value)) { return new ValueExpression(bool.TrueString, true); } return new ValueExpression(bool.FalseString, false); }; public static FunctionHandler IsNull = (primary, service, tracing, organizationConfig, parameters) => { var target = parameters.FirstOrDefault(); if (target.Value == null) { return new ValueExpression(bool.TrueString, true); } return new ValueExpression(bool.FalseString, false); }; public static FunctionHandler If = (primary, service, tracing, organizationConfig, parameters) => { if (parameters.Count != 3) { throw new InvalidPluginExecutionException("If-Then-Else expects exactly three parameters: Condition, True-Action, False-Action"); } var condition = CheckedCast<bool>(parameters[0]?.Value, "If condition must be a boolean!"); var trueAction = parameters[1]; var falseAction = parameters[2]; if (condition) { tracing.Trace("Executing true condition"); return new ValueExpression(new Lazy<ValueExpression>(() => trueAction)); } tracing.Trace("Executing false condition"); return new ValueExpression(new Lazy<ValueExpression>(() => falseAction)); }; public static FunctionHandler GetPrimaryRecord = (primary, service, tracing, organizationConfig, parameters) => { if (primary == null) { return new ValueExpression(null); } return new ValueExpression(string.Empty, primary); }; public static FunctionHandler GetRecordUrl = (primary, service, tracing, organizationConfig, parameters) => { if (organizationConfig == null || string.IsNullOrEmpty(organizationConfig.OrganizationUrl)) { throw new InvalidPluginExecutionException("GetRecordUrl can't find the Organization Url inside the plugin step secure configuration. Please add it."); } if (!parameters.All(p => p.Value is EntityReference || p.Value is Entity || p.Value is Dictionary<string, object> || p.Value == null)) { throw new InvalidPluginExecutionException("Only Entity Reference and Entity ValueExpressions are supported in GetRecordUrl"); } var refs = parameters.Where(p => p != null && !(p?.Value is Dictionary<string, object>)).Select(e => { var entityReference = e.Value as EntityReference; if (entityReference != null) { return new { Id = entityReference.Id, LogicalName = entityReference.LogicalName }; } var entity = e.Value as Entity; return new { Id = entity.Id, LogicalName = entity.LogicalName }; }); var organizationUrl = organizationConfig.OrganizationUrl.EndsWith("/") ? organizationConfig.OrganizationUrl : organizationConfig.OrganizationUrl + "/"; var config = GetConfig(parameters); var linkText = config.GetValue<string>("linkText", "linkText must be a string"); var appId = config.GetValue<string>("appId", "appId must be a string"); var urls = string.Join(Environment.NewLine, refs.Select(e => { var url = $"{organizationUrl}main.aspx?etn={e.LogicalName}&id={e.Id}&newWindow=true&pagetype=entityrecord{(string.IsNullOrEmpty(appId) ? string.Empty : $"&appid={appId}")}"; return $"<a href=\"{url}\">{(string.IsNullOrEmpty(linkText) ? url : linkText)}</a>"; })); return new ValueExpression(urls, urls); }; public static FunctionHandler GetOrganizationUrl = (primary, service, tracing, organizationConfig, parameters) => { if (organizationConfig == null || string.IsNullOrEmpty(organizationConfig.OrganizationUrl)) { throw new InvalidPluginExecutionException("GetOrganizationUrl can't find the Organization Url inside the plugin step secure configuration. Please add it."); } var config = GetConfig(parameters); var linkText = config.GetValue<string>("linkText", "linkText must be a string", string.Empty); var urlSuffix = config.GetValue<string>("urlSuffix", "urlSuffix must be a string", string.Empty); var asHtml = config.GetValue<bool>("asHtml", "asHtml must be a boolean"); if (asHtml) { var url = $"{organizationConfig.OrganizationUrl}{urlSuffix}"; var href = $"<a href=\"{url}\">{(string.IsNullOrEmpty(linkText) ? url : linkText)}</a>"; return new ValueExpression(href, href); } else { return new ValueExpression(organizationConfig.OrganizationUrl, organizationConfig.OrganizationUrl); } }; public static FunctionHandler Union = (primary, service, tracing, organizationConfig, parameters) => { if (parameters.Count < 2) { throw new InvalidPluginExecutionException("Union function needs at least two parameters: Arrays to union"); } var union = parameters.Select(p => { if (p == null) { return null; } return p.Value as List<ValueExpression>; }) .Where(p => p != null) .SelectMany(p => p) .ToList(); return new ValueExpression(null, union); }; public static FunctionHandler Map = (primary, service, tracing, organizationConfig, parameters) => { if (parameters.Count < 2) { throw new InvalidPluginExecutionException("Map function needs at least an array with data and a function for mutating the data"); } var config = GetConfig(parameters); var values = parameters[0].Value as List<ValueExpression>; if (!(values is IEnumerable)) { throw new InvalidPluginExecutionException("Map needs an array as first parameter."); } var lambda = parameters[1].Value as Func<List<ValueExpression>, ValueExpression>; if (lambda == null) { throw new InvalidPluginExecutionException("Lambda function must be a proper arrow function"); } return new ValueExpression(null, values.Select(v => lambda(new List<ValueExpression> { v })).ToList()); }; public static FunctionHandler Sort = (primary, service, tracing, organizationConfig, parameters) => { if (parameters.Count < 1) { throw new InvalidPluginExecutionException("Sort function needs at least an array to sort and optionally a property for sorting"); } var config = GetConfig(parameters); var values = parameters[0].Value as List<ValueExpression>; if (!(values is IEnumerable)) { throw new InvalidPluginExecutionException("Sort needs an array as first parameter."); } var descending = config.GetValue<bool>("descending", "descending must be a bool"); var property = config.GetValue<string>("property", "property must be a string"); if (string.IsNullOrEmpty(property)) { if (descending) { return new ValueExpression(null, values.OrderByDescending(v => v.Value).ToList()); } else { return new ValueExpression(null, values.OrderBy(v => v.Value).ToList()); } } else { if (descending) { return new ValueExpression(null, values.OrderByDescending(v => (v.Value as Entity)?.GetAttributeValue<object>(property)).ToList()); } else { return new ValueExpression(null, values.OrderBy(v => (v.Value as Entity)?.GetAttributeValue<object>(property)).ToList()); } } }; private static Func<string, IOrganizationService, Dictionary<string, string>> RetrieveColumnNames = (entityName, service) => { return ((RetrieveEntityResponse)service.Execute(new RetrieveEntityRequest { EntityFilters = EntityFilters.Attributes, LogicalName = entityName, RetrieveAsIfPublished = false })) .EntityMetadata .Attributes .ToDictionary(a => a.LogicalName, a => a?.DisplayName?.UserLocalizedLabel?.Label ?? a.LogicalName); }; public static FunctionHandler RenderRecordTable = (primary, service, tracing, organizationConfig, parameters) => { tracing.Trace("Parsing parameters"); if (parameters.Count < 3) { throw new InvalidPluginExecutionException("RecordTable needs at least 3 parameters: Entities, entity name, add url boolean, display columns as separate string constants"); } var records = CheckedCast<List<ValueExpression>>(parameters[0].Value, "RecordTable requires the first parameter to be a list of entities") .Select(p => (p as ValueExpression)?.Value) .Cast<Entity>() .ToList(); tracing.Trace($"Records: {records.Count}"); // We need the entity name although it should be set in the record. If no records are passed, we would fail to display the grid with proper columns otherwise var entityName = CheckedCast<string>(parameters[1]?.Value, "Second parameter of the RecordTable function needs to be the entity name as string"); if (string.IsNullOrEmpty(entityName)) { throw new InvalidPluginExecutionException("Second parameter of the RecordTable function needs to be the entity name as string"); } // We need the column names explicitly, since CRM does not return new ValueExpression(null)-valued columns, so that we can't rely on the column union of all records. In addition to that, the order can be set this way var displayColumns = CheckedCast<List<ValueExpression>>(parameters[2]?.Value, "List of column names for record table must be an array expression") .Select(p => p.Value) .Select(p => p is Dictionary<string, object> ? (Dictionary<string, object>) p : new Dictionary<string, object> { { "name", p } }) .ToList(); tracing.Trace("Retrieving column names"); var columnNames = RetrieveColumnNames(entityName, service); tracing.Trace($"Column names done"); var config = GetConfig(parameters); var addRecordUrl = config.GetValue<bool>("addRecordUrl", "When setting addRecordUrl, value must be a boolean"); var tableStyle = config.GetValue("tableStyle", "tableStyle must be a string!", string.Empty); if (!string.IsNullOrEmpty(tableStyle)) { tableStyle = $" style=\"{tableStyle}\""; } var tableHeadStyle = config.GetValue("headerStyle", "headerStyle must be a string!", @"border:1px solid black;text-align:left;padding:1px 15px 1px 5px;"); var tableDataStyle = config.GetValue("dataStyle", "dataStyle must be a string!", @"border:1px solid black;padding:1px 15px 1px 5px;"); var evenDataStyle = config.GetValue<string>("evenDataStyle", "evenDataStyle must be a string!"); var unevenDataStyle = config.GetValue<string>("unevenDataStyle", "unevenDataStyle must be a string!"); tracing.Trace("Parsed parameters"); // Create table header var stringBuilder = new StringBuilder($"<table{tableStyle}>\n<tr>"); foreach (var column in displayColumns) { var name = string.Empty; var columnName = column.ContainsKey("name") ? column["name"] as string : string.Empty; if (columnName.Contains(":")) { name = columnName.Substring(columnName.IndexOf(':') + 1); } else { name = columnNames.ContainsKey(columnName) ? columnNames[columnName] : columnName; } if (column.ContainsKey("label")) { name = column["label"] as string; } if (column.ContainsKey("style")) { if (!column.ContainsKey("mergeStyle") || (bool) column["mergeStyle"]) { stringBuilder.AppendLine($"<th style=\"{tableHeadStyle}{column["style"]}\">{name}</th>"); } else { stringBuilder.AppendLine($"<th style=\"{column["style"]}\">{name}</th>"); } } else { stringBuilder.AppendLine($"<th style=\"{tableHeadStyle}\">{name}</th>"); } } // Add column for url if wanted if (addRecordUrl) { stringBuilder.AppendLine($"<th style=\"{tableHeadStyle}\">URL</th>"); } stringBuilder.AppendLine("</tr>"); if (records != null) { for (var i = 0; i < records.Count; i++) { var record = records[i]; var isEven = i % 2 == 0; var lineStyle = (isEven ? evenDataStyle : unevenDataStyle) ?? tableDataStyle; stringBuilder.AppendLine("<tr>"); foreach (var column in displayColumns) { var columnName = column.ContainsKey("name") ? column["name"] as string : string.Empty; columnName = columnName.Contains(":") ? columnName.Substring(0, columnName.IndexOf(':')) : columnName; var renderFunction = column.ContainsKey("renderFunction") ? column["renderFunction"] as Func<List<ValueExpression>, ValueExpression> : null; var entityConfig = column.ContainsKey("nameByEntity") ? column["nameByEntity"] as Dictionary<string, object> : null; if (entityConfig != null && entityConfig.ContainsKey(record.LogicalName)) { columnName = entityConfig[record.LogicalName] as string; } var staticValues = column.ContainsKey("staticValueByEntity") ? column["staticValueByEntity"] as Dictionary<string, object> : null; string value; if (staticValues != null && staticValues.ContainsKey(record.LogicalName)) { value = staticValues[record.LogicalName] as string; } else if (renderFunction != null) { var rowRecord = new ValueExpression(null, record); var rowColumnName = new ValueExpression(columnName, columnName); value = renderFunction(new List<ValueExpression> { rowRecord, rowColumnName })?.Text; } else { value = PropertyStringifier.Stringify(columnName, record, service, config); } if (column.ContainsKey("style")) { if (!column.ContainsKey("mergeStyle") || (bool)column["mergeStyle"]) { stringBuilder.AppendLine($"<td style=\"{lineStyle}{column["style"]}\">{value}</td>"); } else { stringBuilder.AppendLine($"<td style=\"{column["style"]}\">{value}</td>"); } } else { stringBuilder.AppendLine($"<td style=\"{lineStyle}\">{value}</td>"); } } if (addRecordUrl) { stringBuilder.AppendLine($"<td style=\"{lineStyle}\">{GetRecordUrl(primary, service, tracing, organizationConfig, new List<ValueExpression> { new ValueExpression(string.Empty, record), new ValueExpression(string.Empty, config.Dictionary) }).Value}</td>"); } stringBuilder.AppendLine("</tr>"); } } stringBuilder.AppendLine("</table>"); var table = stringBuilder.ToString(); return new ValueExpression(table, table); }; public static FunctionHandler Fetch = (primary, service, tracing, organizationConfig, parameters) => { if (parameters.Count < 1) { throw new InvalidPluginExecutionException("Fetch needs at least one parameter: Fetch XML."); } var fetch = parameters[0].Value as string; if (string.IsNullOrEmpty(fetch)) { throw new InvalidPluginExecutionException("First parameter of Fetch function needs to be a fetchXml string"); } var references = new List<object> { primary.Id }; if (parameters.Count > 1) { if (!(parameters[1].Value is List<ValueExpression>)) { throw new InvalidPluginExecutionException("Fetch parameters must be an array expression"); } var @params = parameters[1].Value as List<ValueExpression>; if (@params is IEnumerable) { foreach (var item in @params) { var reference = item.Value as EntityReference; if (reference != null) { references.Add(reference.Id); continue; } var entity = item.Value as Entity; if (entity != null) { references.Add(entity.Id); continue; } var optionSet = item.Value as OptionSetValue; if (optionSet != null) { references.Add(optionSet.Value); continue; } references.Add(item.Value); } } } var records = new List<object>(); var query = fetch; if (primary != null) { query = query.Replace("{0}", references[0].ToString()); } tracing.Trace("Replacing references"); var referenceRegex = new Regex("{([0-9]+)}", RegexOptions.Compiled | RegexOptions.CultureInvariant); query = referenceRegex.Replace(query, match => { var capture = match.Groups[1].Value; var referenceNumber = int.Parse(capture); if (referenceNumber >= references.Count) { throw new InvalidPluginExecutionException($"You tried using reference {referenceNumber} in fetch, but there are less reference inputs than that. Please check your reference number or your reference input array."); } return references[referenceNumber]?.ToString(); }); tracing.Trace("References replaced"); tracing.Trace($"Executing fetch: {query}"); records.AddRange(service.RetrieveMultiple(new FetchExpression(query)).Entities); return new ValueExpression(string.Empty, records.Select(r => new ValueExpression(string.Empty, r)).ToList()); }; public static FunctionHandler GetValue = (primary, service, tracing, organizationConfig, parameters) => { if (primary == null) { return new ValueExpression(null); } var field = parameters.FirstOrDefault()?.Text; if (string.IsNullOrEmpty(field)) { throw new InvalidPluginExecutionException("First parameter of Value function needs to be the field name as string"); } var target = primary; var config = GetConfig(parameters); if (config.Contains("explicitTarget")) { if (config.IsSet("explicitTarget")) { var explicitTarget = config.GetValue<Entity>("explicitTarget", "explicitTarget must be an entity!"); target = explicitTarget; } else { return new ValueExpression(string.Empty, string.Empty); } } if (field == null) { throw new InvalidPluginExecutionException("Value requires a field target string as input"); } return DataRetriever.ResolveTokenValue(field, target, service, config); }; public static FunctionHandler Join = (primary, service, tracing, organizationConfig, parameters) => { if (parameters.Count < 2) { throw new InvalidPluginExecutionException("Join function needs at lease two parameters: Separator and an array of values to concatenate"); } var separator = parameters.FirstOrDefault()?.Text; if (string.IsNullOrEmpty(separator)) { throw new InvalidPluginExecutionException("First parameter of Join function needs to be the separator string"); } var values = parameters[1].Value as List<ValueExpression>; if (!(values is IEnumerable)) { throw new InvalidPluginExecutionException("The values parameter needs to be an enumerable, please wrap them using an Array expression."); } var config = GetConfig(parameters); var removeEmptyEntries = false; if (parameters.Count > 2 && parameters[2].Value is bool) { removeEmptyEntries = (bool) parameters[2].Value; } var valuesToConcatenate = values .Where(v => !removeEmptyEntries || !string.IsNullOrEmpty(v.Text)) .Select(v => v.Text); var joined = string.Join(separator, valuesToConcatenate); return new ValueExpression(joined, joined); }; public static FunctionHandler NewLine = (primary, service, tracing, organizationConfig, parameters) => { return new ValueExpression(Environment.NewLine, Environment.NewLine); }; public static FunctionHandler Concat = (primary, service, tracing, organizationConfig, parameters) => { var text = ""; foreach (var parameter in parameters) { text += parameter.Text; } return new ValueExpression(text, text); }; private static T CheckedCast<T>(object input, string errorMessage, bool failOnError = true) { var value = input; if (input is Money) { value = (input as Money).Value; } if (input is OptionSetValue) { value = (input as OptionSetValue).Value; } if (!(value is T)) { if (failOnError) { throw new InvalidPluginExecutionException(errorMessage); } return default(T); } return (T)value; } public static FunctionHandler Substring = (primary, service, tracing, organizationConfig, parameters) => { if (parameters.Count < 2) { throw new InvalidPluginExecutionException("Substring expects at least two parameters: text, start index and optionally a length"); } var text = parameters[0].Text; var startIndex = CheckedCast<int>(parameters[1].Value, "Start index parameter must be an int!"); var length = -1; if (parameters.Count > 2) { length = CheckedCast<int>(parameters[2].Value, "Length parameter must be an int!"); } var subString = length > -1 ? text.Substring(startIndex, length) : text.Substring(startIndex); return new ValueExpression(subString, subString); }; public static FunctionHandler IndexOf = (primary, service, tracing, organizationConfig, parameters) => { if (parameters.Count < 2) { throw new InvalidPluginExecutionException("IndexOf needs a source string and a string to search for"); } var value = CheckedCast<string>(parameters[0].Value, "Source must be a string"); var searchText = CheckedCast<string>(parameters[1].Value, "Search text must be a string"); var config = GetConfig(parameters); var ignoreCase = config.GetValue<bool>("ignoreCase", "ignoreCase must be a boolean!"); var index = value.IndexOf(searchText, ignoreCase ? StringComparison.InvariantCultureIgnoreCase : StringComparison.InvariantCulture); return new ValueExpression(index.ToString(), index); }; public static FunctionHandler Replace = (primary, service, tracing, organizationConfig, parameters) => { if (parameters.Count < 3) { throw new InvalidPluginExecutionException("Replace expects three parameters: text input, regex pattern, regex replacement"); } var input = parameters[0].Text; var pattern = parameters[1].Text; var replacement = parameters[2].Text; var replaced = Regex.Replace(input, pattern, replacement); return new ValueExpression(replaced, replaced); }; public static FunctionHandler Array = (primary, service, tracing, organizationConfig, parameters) => { return new ValueExpression(string.Join(", ", parameters.Select(p => p.Text)), parameters); }; public static FunctionHandler DateTimeNow = (primary, service, tracing, organizationConfig, parameters) => { var date = DateTime.Now; return new ValueExpression(date.ToString("o", CultureInfo.InvariantCulture), date); }; public static FunctionHandler DateTimeUtcNow = (primary, service, tracing, organizationConfig, parameters) => { var date = DateTime.UtcNow; return new ValueExpression(date.ToString("o", CultureInfo.InvariantCulture), date); }; public static FunctionHandler Static = (primary, service, tracing, organizationConfig, parameters) => { if (parameters.Count < 1) { throw new InvalidOperationException("You have to pass a static value"); } var parameter = parameters[0]; return new ValueExpression(parameter.Text, parameter.Value); }; public static FunctionHandler DateToString = (primary, service, tracing, organizationConfig, parameters) => { if (parameters.Count < 1) { throw new Exception("No date to stringify"); } var date = CheckedCast<DateTime>(parameters[0].Value, "You need to pass a date"); var config = GetConfig(parameters); var format = config.GetValue<string>("format", "format must be a string!"); if (!string.IsNullOrEmpty(format)) { return new ValueExpression(date.ToString(format), date.ToString(format)); } return new ValueExpression(date.ToString(CultureInfo.InvariantCulture), date.ToString(CultureInfo.InvariantCulture)); }; public static FunctionHandler Format = (primary, service, tracing, organizationConfig, parameters) => { if (parameters.Count < 2) { throw new InvalidPluginExecutionException("Format needs a value to format and a config for defining further options"); } var value = parameters[0].Value; var config = GetConfig(parameters); var format = config.GetValue<string>("format", "format must be a string!"); var knownTypes = new Dictionary<Type, Func<object, ValueExpression>> { { typeof(Money), (obj) => { var val = obj as Money; var formatted = string.Format(CultureInfo.InvariantCulture, format, val.Value); return new ValueExpression( formatted, formatted ); } } }; if(knownTypes.ContainsKey(value.GetType())) { return knownTypes[value.GetType()](value); } else { var formatted = string.Format(CultureInfo.InvariantCulture, format, value); return new ValueExpression(formatted, formatted); } }; private static Entity FetchSnippetByUniqueName(string uniqueName, IOrganizationService service) { var fetch = $@"<fetch no-lock=""true""> <entity name=""oss_xtlsnippet""> <attribute name=""oss_xtlexpression"" /> <attribute name=""oss_containsplaintext"" /> <filter operator=""and""> <condition attribute=""oss_uniquename"" operator=""eq"" value=""{uniqueName}"" /> </filter> </entity> </fetch>"; var snippet = service.RetrieveMultiple(new FetchExpression(fetch)) .Entities .FirstOrDefault(); return snippet; } private static Entity FetchSnippet(string name, string filter, Entity primary, OrganizationConfig organizationConfig, IOrganizationService service, ITracingService tracing) { var uniqueNameSnippet = FetchSnippetByUniqueName(name, service); if (uniqueNameSnippet != null) { tracing.Trace("Found snippet by unique name"); return uniqueNameSnippet; } if (!string.IsNullOrEmpty(filter)) { tracing.Trace("Processing tokens in custom snippet filter"); } var fetch = $@"<fetch no-lock=""true""> <entity name=""oss_xtlsnippet""> <attribute name=""oss_xtlexpression"" /> <attribute name=""oss_containsplaintext"" /> <filter operator=""and""> <condition attribute=""oss_name"" operator=""eq"" value=""{name}"" /> { (!string.IsNullOrEmpty(filter) ? TokenMatcher.ProcessTokens(filter, primary, organizationConfig, service, tracing) : string.Empty) } </filter> </entity> </fetch>"; if (!string.IsNullOrEmpty(filter)) { tracing.Trace("Done processing tokens in custom snippet filter"); } var snippet = service.RetrieveMultiple(new FetchExpression(fetch)) .Entities .FirstOrDefault(); return snippet; } public static FunctionHandler Snippet = (primary, service, tracing, organizationConfig, parameters) => { if (parameters.Count < 1) { throw new InvalidPluginExecutionException("Snippet needs at least a name as first parameter and optionally a config for defining further options"); } var name = CheckedCast<string>(parameters[0].Value, "Name must be a string!"); var config = GetConfig(parameters); var filter = config?.GetValue<string>("filter", "filter must be a string containing your fetchXml filter, which may contain XTL expressions on its own"); var snippet = FetchSnippet(name, filter, primary, organizationConfig, service, tracing); if (snippet == null) { tracing.Trace("Failed to find a snippet matching the input"); return new ValueExpression(string.Empty, null); } var containsPlainText = snippet.GetAttributeValue<bool>("oss_containsplaintext"); var value = snippet.GetAttributeValue<string>("oss_xtlexpression"); // Wrap it in ${{ ... }} block var processedValue = containsPlainText ? value : $"${{{{ {value} }}}}"; tracing.Trace("Processing snippet tokens"); var result = TokenMatcher.ProcessTokens(processedValue, primary, organizationConfig, service, tracing); tracing.Trace("Done processing snippet tokens"); return new ValueExpression(result, result); }; public static FunctionHandler ConvertDateTime = (primary, service, tracing, organizationConfig, parameters) => { if (parameters.Count < 2) { throw new InvalidPluginExecutionException("Convert DateTime needs a DateTime and a config for defining further options"); } var date = CheckedCast<DateTime>(parameters[0].Value, "You need to pass a date"); var config = GetConfig(parameters); var timeZoneId = config.GetValue<string>("timeZoneId", "timeZoneId must be a string"); var userId = config.GetValue<EntityReference>("userId", "userId must be an EntityReference"); if (userId == null && string.IsNullOrEmpty(timeZoneId)) { throw new InvalidPluginExecutionException("You need to either set a userId for converting to a user's configured timezone, or pass a timeZoneId"); } if (userId != null) { var userSettings = service.Retrieve("usersettings", userId.Id, new ColumnSet("timezonecode")); var timeZoneCode = userSettings.GetAttributeValue<int>("timezonecode"); timeZoneId = service.Query("timezonedefinition") .IncludeColumns("standardname") .Where(e => e .Attribute(a => a .Named("timezonecode") .Is(ConditionOperator.Equal) .To(timeZoneCode) ) ) .Retrieve() .FirstOrDefault() ?.GetAttributeValue<string>("standardname"); } if (string.IsNullOrEmpty(timeZoneId)) { throw new InvalidPluginExecutionException("Failed to retrieve timeZoneId, can't convert datetime"); } var timeZone = TimeZoneInfo.FindSystemTimeZoneById(timeZoneId); var localTime = TimeZoneInfo.ConvertTime(date, timeZone); var text = localTime.ToString(config.GetValue<string>("format", "format must be a string", "g"), CultureInfo.InvariantCulture); return new ValueExpression(text, localTime); }; public static FunctionHandler RetrieveAudit = (primary, service, tracing, organizationConfig, parameters) => { var firstParam = parameters.FirstOrDefault()?.Value; var reference = (firstParam as Entity)?.ToEntityReference() ?? firstParam as EntityReference; var config = GetConfig(parameters); if (firstParam != null && reference == null) { throw new InvalidPluginExecutionException("RetrieveAudit: First Parameter must be an Entity or EntityReference"); } if (reference == null) { return new ValueExpression(string.Empty, null); } var field = CheckedCast<string>(parameters[1]?.Value, "RetrieveAudit: fieldName must be a string"); var request = new RetrieveRecordChangeHistoryRequest { Target = reference }; var audit = service.Execute(request) as RetrieveRecordChangeHistoryResponse; var auditValue = audit.AuditDetailCollection.AuditDetails.Select(d => { var detail = d as AttributeAuditDetail; if (detail == null) { return null; } var oldValue = detail.OldValue.GetAttributeValue<object>(field); return Tuple.Create(PropertyStringifier.Stringify(field, detail.OldValue, service, config), oldValue); }) .FirstOrDefault(t => t != null); return new ValueExpression(auditValue?.Item1 ?? string.Empty, auditValue?.Item2); }; public static FunctionHandler GetRecordId = (primary, service, tracing, organizationConfig, parameters) => { var firstParam = parameters.FirstOrDefault()?.Value; var reference = (firstParam as Entity)?.ToEntityReference() ?? firstParam as EntityReference; var config = GetConfig(parameters); if (firstParam != null && reference == null) { throw new InvalidPluginExecutionException("RecordId: First Parameter must be an Entity or EntityReference"); } if (reference == null) { return new ValueExpression(string.Empty, null); } var textValue = reference.Id.ToString(config.GetValue<string>("format", "format must be a string", "D")); return new ValueExpression(textValue, reference.Id); }; public static FunctionHandler GetRecordLogicalName = (primary, service, tracing, organizationConfig, parameters) => { var firstParam = parameters.FirstOrDefault()?.Value; var reference = (firstParam as Entity)?.ToEntityReference() ?? firstParam as EntityReference; if (firstParam != null && reference == null) { throw new InvalidPluginExecutionException("RecordLogicalName: First Parameter must be an Entity or EntityReference"); } if (reference == null) { return new ValueExpression(string.Empty, null); } return new ValueExpression(reference.LogicalName, reference.LogicalName); }; } } #pragma warning restore S1104 // Fields should not have public accessibility
41.489848
279
0.555392
[ "MIT" ]
Andrea-Bosca/Xrm-Templating-Language
src/lib/Xrm.Oss.XTL.Interpreter/FunctionHandlers.cs
49,043
C#
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; public class ButtonBack : MonoBehaviour { public Button mButton; // Use this for initialization void Start() { //获取回退按钮 Button btn = mButton.GetComponent<Button>(); //给回退按钮绑定监听器,点击时执行TaskOnClick方法 btn.onClick.AddListener(TaskOnClick); } void TaskOnClick() { //加载菜单场景 Application.LoadLevel(0); } }
17.321429
52
0.645361
[ "Apache-2.0" ]
Edward7Zhang/Unity3D_AR_Pokemon
Assets/Scripts/ButtonBack.cs
547
C#
class RecentItemQueue<T> where T : class { private readonly int _size; private int _head; private int _tail; private readonly T[] _content; public RecentItemQueue(int size) { _head = -1; _tail = -1; _size = size; _content = new T[size]; } public IReadOnlyList<T> GetItems() { // the latest item (last in) will be in the first place of output list List<T> items = new List<T>(); if (_head == -1) { return items; } int index = _head; for (int i = 0; i < _size; i++) { if (index == -1) { index = _size - 1; } if (_content[index] != null) { items.Add(_content[index]); } index--; } return items; } public void SetItem(T item) { // inital case if (_head == -1) { _head = 0; _tail = 1; _content[_head] = item; return; } if (Contains(item, out int target)) { // when item is in content T targetItem = _content[target]; while (target != _head) { if (target + 1 == _size) { _content[target] = _content[0]; target = 0; continue; } _content[target] = _content[target + 1]; target++; } _content[_head] = targetItem; return; } // when item is not in content _content[_tail] = item; _tail++; if (_tail == _size) { _tail = 0; } _head++; if (_head == _size) { _head = 0; } } private bool Contains(T item, out int location) { int index = _head; location = -1; while (index != _tail) { if (_content[index] != null && item.Equals(_content[index])) { location = index; return true; } index--; if (index == -1) { index = _size - 1; } } return false; } }
22.809917
82
0.337319
[ "BSD-3-Clause" ]
wooly905/RecentItemQueue
RecentItemQueue.cs
2,760
C#
using UnityEngine; using System.Collections; public class InputManagerScript : MonoBehaviour { private GameManagerScript _gameManager; private MoveTokensScript _moveManager; private GameObject _selected = null; public virtual void Start () { _moveManager = GetComponent<MoveTokensScript>(); _gameManager = GetComponent<GameManagerScript>(); } public virtual void SelectToken(){ if (Input.GetMouseButtonDown(0)){ Vector3 mousePos = Camera.main.ScreenToWorldPoint(Input.mousePosition); Collider2D collider = Physics2D.OverlapPoint(mousePos); if(collider != null){ if(_selected == null){ _selected = collider.gameObject; } else { Vector2 pos1 = _gameManager.GetPositionOfTokenInGrid(_selected); Vector2 pos2 = _gameManager.GetPositionOfTokenInGrid(collider.gameObject); if(Mathf.Abs((pos1.x - pos2.x) + (pos1.y - pos2.y)) == 1){ _moveManager.SetupTokenExchange(_selected, pos1, collider.gameObject, pos2, true); } _selected = null; } } } } public int CommentFunc(int x, int y){ return x - y; } }
25.833333
88
0.715207
[ "Unlicense" ]
connorcarson/CodeLab2_Carson
W2_CARSON/Assets/Scripts/InputManagerScript.cs
1,087
C#
// <auto-generated> // Code generated by Microsoft (R) AutoRest Code Generator. // Changes may cause incorrect behavior and will be lost if the code is // regenerated. // </auto-generated> namespace IL.Library.Amazon.SPAPI.Finances.Models { using Newtonsoft.Json; using System.Linq; /// <summary> /// A currency type and amount. /// </summary> public partial class Currency { /// <summary> /// Initializes a new instance of the Currency class. /// </summary> public Currency() { CustomInit(); } /// <summary> /// Initializes a new instance of the Currency class. /// </summary> /// <param name="currencyCode">The three-digit currency code in ISO /// 4217 format.</param> /// <param name="currencyAmount">The monetary value.</param> public Currency(string currencyCode = default(string), double? currencyAmount = default(double?)) { CurrencyCode = currencyCode; CurrencyAmount = currencyAmount; CustomInit(); } /// <summary> /// An initialization method that performs custom operations like setting defaults /// </summary> partial void CustomInit(); /// <summary> /// Gets or sets the three-digit currency code in ISO 4217 format. /// </summary> [JsonProperty(PropertyName = "CurrencyCode")] public string CurrencyCode { get; set; } /// <summary> /// Gets or sets the monetary value. /// </summary> [JsonProperty(PropertyName = "CurrencyAmount")] public double? CurrencyAmount { get; set; } } }
30.052632
105
0.587274
[ "Apache-2.0" ]
InventoryLab/selling-partner-api-models
clients/IL/Finances/Models/Currency.cs
1,713
C#
using System; using System.Net.Http; using System.Threading; using System.Threading.Tasks; using EventStore.Client; using EventStore.Client.Streams; namespace subscribing_to_streams { class Program { static async Task Main(string[] args) { using var client = new EventStoreClient( EventStoreClientSettings.Create("esdb://admin:changeit@localhost:2113?TlsVerifyCert=false") ); await SubscribeToStream(client); await SubscribeToAll(client); await OverridingUserCredentials(client); } private static async Task SubscribeToStream(EventStoreClient client) { #region subscribe-to-stream await client.SubscribeToStreamAsync("some-stream", async (subscription, evnt, cancellationToken) => { Console.WriteLine($"Received event {evnt.OriginalEventNumber}@{evnt.OriginalStreamId}"); await HandleEvent(evnt); }); #endregion subscribe-to-stream #region subscribe-to-stream-from-position await client.SubscribeToStreamAsync( "some-stream", StreamPosition.FromInt64(20), EventAppeared); #endregion subscribe-to-stream-from-position #region subscribe-to-stream-live await client.SubscribeToStreamAsync( "some-stream", StreamPosition.End, EventAppeared); #endregion subscribe-to-stream-live #region subscribe-to-stream-resolving-linktos await client.SubscribeToStreamAsync( "$et-myEventType", StreamPosition.Start, EventAppeared, resolveLinkTos: true); #endregion subscribe-to-stream-resolving-linktos #region subscribe-to-stream-subscription-dropped var checkpoint = StreamPosition.Start; await client.SubscribeToStreamAsync( "some-stream", checkpoint, eventAppeared: async (subscription, evnt, cancellationToken) => { await HandleEvent(evnt); checkpoint = evnt.OriginalEventNumber; }, subscriptionDropped: ((subscription, reason, exception) => { Console.WriteLine($"Subscription was dropped due to {reason}. {exception}"); if (reason != SubscriptionDroppedReason.Disposed) { // Resubscribe if the client didn't stop the subscription Resubscribe(checkpoint); } })); #endregion subscribe-to-stream-subscription-dropped } private static async Task SubscribeToAll(EventStoreClient client) { #region subscribe-to-all await client.SubscribeToAllAsync( async (subscription, evnt, cancellationToken) => { Console.WriteLine($"Received event {evnt.OriginalEventNumber}@{evnt.OriginalStreamId}"); await HandleEvent(evnt); }); #endregion subscribe-to-all #region subscribe-to-all-from-position await client.SubscribeToAllAsync( new Position(1056, 1056), EventAppeared); #endregion subscribe-to-all-from-position #region subscribe-to-all-live await client.SubscribeToAllAsync( Position.End, EventAppeared); #endregion subscribe-to-all-live #region subscribe-to-all-subscription-dropped var checkpoint = Position.Start; await client.SubscribeToAllAsync( checkpoint, eventAppeared: async (subscription, evnt, cancellationToken) => { await HandleEvent(evnt); checkpoint = evnt.OriginalPosition.Value; }, subscriptionDropped: ((subscription, reason, exception) => { Console.WriteLine($"Subscription was dropped due to {reason}. {exception}"); if (reason != SubscriptionDroppedReason.Disposed) { // Resubscribe if the client didn't stop the subscription Resubscribe(checkpoint); } })); #endregion subscribe-to-all-subscription-dropped } private static async Task SubscribeToFiltered(EventStoreClient client) { #region stream-prefix-filtered-subscription var prefixStreamFilter = new SubscriptionFilterOptions(StreamFilter.Prefix("test-", "other-")); await client.SubscribeToAllAsync( EventAppeared, filterOptions: prefixStreamFilter); #endregion stream-prefix-filtered-subscription #region stream-regex-filtered-subscription var regexStreamFilter = StreamFilter.RegularExpression(@"/invoice-\d\d\d/g"); #endregion stream-regex-filtered-subscription } private static async Task OverridingUserCredentials(EventStoreClient client) { #region overriding-user-credentials await client.SubscribeToAllAsync( EventAppeared, userCredentials: new UserCredentials("admin", "changeit")); #endregion overriding-user-credentials } private static Task EventAppeared(StreamSubscription subscription, ResolvedEvent evnt, CancellationToken cancellationToken) { return Task.CompletedTask; } private static void SubscriptionDropped(StreamSubscription subscription, SubscriptionDroppedReason reason, Exception ex) { } private static Task HandleEvent(ResolvedEvent evnt) { return Task.CompletedTask; } private static void Resubscribe(StreamPosition checkpoint) { } private static void Resubscribe(Position checkpoint) { } } }
33.414966
108
0.742467
[ "Apache-2.0" ]
CodingBrushUp/EventStore-Client-Dotnet
samples/subscribing-to-streams/Program.cs
4,914
C#
using System; using System.Threading.Tasks; using Etg.Yams.Client; using System.IO; namespace GracefullShutdownProcess { internal class Program { public static void Main(string[] args) { Run(args).Wait(); } private static async Task Run(string[] args) { Console.WriteLine("args " + string.Join(" ", args)); int shutdownDelay = 1000 * Convert.ToInt32(args[2]); var yamsClientConfig = new YamsClientConfigBuilder(args).Build(); var yamsClientFactory = new YamsClientFactory(); Console.WriteLine("Initializing..."); IYamsClient yamsClient = yamsClientFactory.CreateYamsClient(yamsClientConfig); await yamsClient.Connect(); Console.WriteLine("Initialization done!"); bool exitMessageReceived = false; yamsClient.ExitMessageReceived += (sender, eventArgs) => { Console.WriteLine("Exit message received!"); exitMessageReceived = true; }; File.WriteAllText($"GracefulShutdownApp.exe.out", $"GracefulShutdownApp.exe {args[0]} {args[1]}"); while (!exitMessageReceived) { await Task.Delay(100); Console.WriteLine("Doing work"); } await Task.Delay(shutdownDelay); Console.WriteLine("Exiting.."); } } }
30.87234
110
0.576154
[ "MIT" ]
Bhaskers-Blu-Org2/Yams
test/GracefullShutdownProcess/Program.cs
1,453
C#
using System; using System.Text; using UnityEngine; namespace MelonLoader.MelonStartScreen { internal class GifDecoder : IDisposable { public string Version; public ushort Width; public ushort Height; public Color32 BackgroundColour; //------------------------------------------------------------------------------ // GIF format enums private enum ImageFlag { Interlaced = 0x40, ColourTable = 0x80, TableSizeMask = 0x07, BitDepthMask = 0x70, } private enum Block { Image = 0x2C, Extension = 0x21, End = 0x3B } private enum Extension { GraphicControl = 0xF9, Comments = 0xFE, PlainText = 0x01, ApplicationData = 0xFF } private enum Disposal { None = 0x00, DoNotDispose = 0x04, RestoreBackground = 0x08, ReturnToPrevious = 0x0C } private enum ControlFlags { HasTransparency = 0x01, DisposalMask = 0x0C } //------------------------------------------------------------------------------ private const uint NoCode = 0xFFFF; private const ushort NoTransparency = 0xFFFF; // input stream to decode private byte[] Input; private int D; // colour table private Color32[] GlobalColourTable; private Color32[] LocalColourTable; private Color32[] ActiveColourTable; private ushort TransparentIndex; // current image private Image Image = new Image(); private ushort ImageLeft; private ushort ImageTop; private ushort ImageWidth; private ushort ImageHeight; private Color32[] Output; private Color32[] PreviousImage; private readonly int[] Pow2 = { 1, 2, 4, 8, 16, 32, 64, 128, 256, 512, 1024, 2048, 4096 }; //------------------------------------------------------------------------------ // ctor public GifDecoder(byte[] data) : this() => Load(data); public GifDecoder Load(byte[] data) { Input = data; D = 0; GlobalColourTable = new Color32[256]; LocalColourTable = new Color32[256]; TransparentIndex = NoTransparency; Output = null; PreviousImage = null; Image.Delay = 0; return this; } //------------------------------------------------------------------------------ // reading data utility functions private byte ReadByte() => Input[D++]; private ushort ReadUInt16() => (ushort)(Input[D++] | Input[D++] << 8); //------------------------------------------------------------------------------ private void ReadHeader() { if (Input == null || Input.Length <= 12) throw new Exception("Invalid data"); // signature Version = Encoding.ASCII.GetString(Input, 0, 6); D = 6; if (Version != "GIF87a" && Version != "GIF89a") { throw new Exception("Unsupported GIF version"); } // read header Width = ReadUInt16(); Height = ReadUInt16(); Image.Width = Width; Image.Height = Height; var flags = (ImageFlag)ReadByte(); var bgIndex = ReadByte(); // background colour ReadByte(); // aspect ratio if (flags.HasFlag(ImageFlag.ColourTable)) ReadColourTable(GlobalColourTable, flags); BackgroundColour = GlobalColourTable[bgIndex]; } //------------------------------------------------------------------------------ public Image NextImage() { // if at start of data, read header if (D == 0) ReadHeader(); // read blocks until we find an image block while (true) { var block = (Block)ReadByte(); switch (block) { case Block.Image: { // return the image if we got one var img = ReadImageBlock(); if (img != null) return img; } break; case Block.Extension: { var ext = (Extension)ReadByte(); if (ext == Extension.GraphicControl) ReadControlBlock(); else SkipBlocks(); } break; case Block.End: { // end block - stop! return null; } default: { throw new Exception("Unexpected block type"); } } } } //------------------------------------------------------------------------------ private Color32[] ReadColourTable(Color32[] colourTable, ImageFlag flags) { var tableSize = Pow2[(int)(flags & ImageFlag.TableSizeMask) + 1]; for (var i = 0; i < tableSize; i++) { colourTable[i] = new Color32( Input[D++], Input[D++], Input[D++], 0xFF ); } return colourTable; } //------------------------------------------------------------------------------ private void SkipBlocks() { var blockSize = Input[D++]; while (blockSize != 0x00) { D += blockSize; blockSize = Input[D++]; } } //------------------------------------------------------------------------------ private void ReadControlBlock() { // read block ReadByte(); // block size (0x04) var flags = (ControlFlags)ReadByte(); // flags Image.Delay = ReadUInt16() * 10; // delay (1/100th -> milliseconds) var transparentColour = ReadByte(); // transparent colour ReadByte(); // terminator (0x00) // has transparent colour? if (flags.HasFlag(ControlFlags.HasTransparency)) TransparentIndex = transparentColour; else TransparentIndex = NoTransparency; // dispose of current image switch ((Disposal)(flags & ControlFlags.DisposalMask)) { default: case Disposal.None: case Disposal.DoNotDispose: // remember current image in case we need to "return to previous" PreviousImage = Output; break; case Disposal.RestoreBackground: // empty image - don't track Output = new Color32[Width * Height]; break; case Disposal.ReturnToPrevious: // return to previous image Output = new Color32[Width * Height]; if (PreviousImage != null) Array.Copy(PreviousImage, Output, Output.Length); break; } } //------------------------------------------------------------------------------ private Image ReadImageBlock() { // read image block header ImageLeft = ReadUInt16(); ImageTop = ReadUInt16(); ImageWidth = ReadUInt16(); ImageHeight = ReadUInt16(); var flags = (ImageFlag)ReadByte(); // bad image if we don't have any dimensions if (ImageWidth == 0 || ImageHeight == 0) return null; // read colour table if (flags.HasFlag(ImageFlag.ColourTable)) ActiveColourTable = ReadColourTable(LocalColourTable, flags); else ActiveColourTable = GlobalColourTable; if (Output == null) { Output = new Color32[Width * Height]; PreviousImage = Output; } // read image data DecompressLZW(); // deinterlace if (flags.HasFlag(ImageFlag.Interlaced)) Deinterlace(); // return image Image.RawImage = Output; return Image; } //------------------------------------------------------------------------------ // decode interlaced images private void Deinterlace() { var numRows = Output.Length / Width; var writePos = Output.Length - Width; // NB: work backwards due to Y-coord flip var input = Output; Output = new Color32[Output.Length]; for (var row = 0; row < numRows; row++) { int copyRow; // every 8th row starting at 0 if (row % 8 == 0) { copyRow = row / 8; } // every 8th row starting at 4 else if ((row + 4) % 8 == 0) { var o = numRows / 8; copyRow = o + (row - 4) / 8; } // every 4th row starting at 2 else if ((row + 2) % 4 == 0) { var o = numRows / 4; copyRow = o + (row - 2) / 4; } // every 2nd row starting at 1 else // if( ( r + 1 ) % 2 == 0 ) { var o = numRows / 2; copyRow = o + (row - 1) / 2; } Array.Copy(input, (numRows - copyRow - 1) * Width, Output, writePos, Width); writePos -= Width; } } //------------------------------------------------------------------------------ // dispose isn't needed for the safe implementation but keep here for interface parity public GifDecoder() { } public void Dispose() { Dispose(true); } protected virtual void Dispose(bool disposing) { } private int[] Indices = new int[4096]; private ushort[] Codes = new ushort[128 * 1024]; private uint[] CurBlock = new uint[64]; private void DecompressLZW() { // output write position int row = (Height - ImageTop - 1) * Width; // reverse rows for unity texture coords int col = ImageLeft; int rightEdge = ImageLeft + ImageWidth; // setup codes int minimumCodeSize = Input[D++]; if (minimumCodeSize > 11) minimumCodeSize = 11; var codeSize = minimumCodeSize + 1; var nextSize = Pow2[codeSize]; var maximumCodeSize = Pow2[minimumCodeSize]; var clearCode = maximumCodeSize; var endCode = maximumCodeSize + 1; // initialise buffers var codesEnd = 0; var numCodes = maximumCodeSize + 2; for (ushort i = 0; i < numCodes; i++) { Indices[i] = codesEnd; Codes[codesEnd++] = 1; // length Codes[codesEnd++] = i; // code } // LZW decode loop uint previousCode = NoCode; // last code processed uint mask = (uint)(nextSize - 1); // mask out code bits uint shiftRegister = 0; // shift register holds the bytes coming in from the input stream, we shift down by the number of bits int bitsAvailable = 0; // number of bits available to read in the shift register int bytesAvailable = 0; // number of bytes left in current block int blockPos = 0; while (true) { // get next code uint curCode = shiftRegister & mask; if (bitsAvailable >= codeSize) { bitsAvailable -= codeSize; shiftRegister >>= codeSize; } else { // reload shift register // if start of new block if (bytesAvailable <= 0) { // read blocksize bytesAvailable = Input[D++]; // exit if end of stream if (bytesAvailable == 0) return; // read block CurBlock[(bytesAvailable - 1) / 4] = 0; // zero last entry Buffer.BlockCopy(Input, D, CurBlock, 0, bytesAvailable); blockPos = 0; D += bytesAvailable; } // load shift register shiftRegister = CurBlock[blockPos++]; int newBits = bytesAvailable >= 4 ? 32 : bytesAvailable * 8; bytesAvailable -= 4; // read remaining bits if (bitsAvailable > 0) { var bitsRemaining = codeSize - bitsAvailable; curCode |= (shiftRegister << bitsAvailable) & mask; shiftRegister >>= bitsRemaining; bitsAvailable = newBits - bitsRemaining; } else { curCode = shiftRegister & mask; shiftRegister >>= codeSize; bitsAvailable = newBits - codeSize; } } // process code if (curCode == clearCode) { // reset codes codeSize = minimumCodeSize + 1; nextSize = Pow2[codeSize]; numCodes = maximumCodeSize + 2; // reset buffer write pos codesEnd = numCodes * 2; // clear previous code previousCode = NoCode; mask = (uint)(nextSize - 1); continue; } else if (curCode == endCode) { // stop break; } bool plusOne = false; int codePos = 0; if (curCode < numCodes) { // write existing code codePos = Indices[curCode]; } else if (previousCode != NoCode) { // write previous code codePos = Indices[previousCode]; plusOne = true; } else continue; // output colours var codeLength = Codes[codePos++]; var newCode = Codes[codePos]; for (int i = 0; i < codeLength; i++) { var code = Codes[codePos++]; if (code != TransparentIndex && col < Width) { Output[row + col] = ActiveColourTable[code]; } if (++col == rightEdge) { col = ImageLeft; row -= Width; if (row < 0) { SkipBlocks(); return; } } } if (plusOne) { if (newCode != TransparentIndex && col < Width) Output[row + col] = ActiveColourTable[newCode]; if (++col == rightEdge) { col = ImageLeft; row -= Width; if (row < 0) break; } } // create new code if (previousCode != NoCode && numCodes != Indices.Length) { // get previous code from buffer codePos = Indices[previousCode]; codeLength = Codes[codePos++]; // resize buffer if required (should be rare) if (codesEnd + codeLength + 1 >= Codes.Length) Array.Resize(ref Codes, Codes.Length * 2); // add new code Indices[numCodes++] = codesEnd; Codes[codesEnd++] = (ushort)(codeLength + 1); // copy previous code sequence var stop = codesEnd + codeLength; while (codesEnd < stop) Codes[codesEnd++] = Codes[codePos++]; // append new code Codes[codesEnd++] = newCode; } // increase code size? if (numCodes >= nextSize && codeSize < 12) { nextSize = Pow2[++codeSize]; mask = (uint)(nextSize - 1); } // remember last code processed previousCode = curCode; } // skip any remaining blocks SkipBlocks(); } public static string Ident() { var v = "1.1"; var e = BitConverter.IsLittleEndian ? "L" : "B"; var b = "M"; var s = "S"; var n = "2.0"; return $"{v} {e}{s}{b} {n}"; } } }
29.660287
138
0.395548
[ "Apache-2.0" ]
TrevTV/MelonLoader
MelonStartScreen/mgGif/GifDecoder.cs
18,599
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("07_04_Even Powers of 2")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("07_04_Even Powers of 2")] [assembly: AssemblyCopyright("Copyright © 2016")] [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("2233e738-e7b5-4708-83d3-f073f9270c5d")] // 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.297297
84
0.744531
[ "MIT" ]
akkirilov/ProgrammingFundamentalsHomeworks
00_ProgrammingBasics/Homeworks/07_AdvancedLoops/07_04_Even Powers of 2/Properties/AssemblyInfo.cs
1,420
C#
// Copyright (c) 2021 EPAM Systems // // 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 Epam.FixAntenna.NetCore.Common; using Epam.FixAntenna.NetCore.Common.Logging; using Epam.FixAntenna.NetCore.Common.ResourceLoading; using NUnit.Framework; namespace Epam.FixAntenna.Validation.Tests.Engine.Validation.Test { [TestFixture] internal class Validate44DataTest : GenericValidationTestStub { [TearDown] public virtual void After() { Assert.IsTrue(Errors.IsEmpty, Errors.Errors.ToReadableString()); } private static readonly ILog Log = LogFactory.GetLog(typeof(Validate44DataTest)); private const bool ErrorShouldOccur = false; public override FixInfo GetFixInfo() { return new FixInfo(FixVersion.Fix44); } [Test] [TestCaseSource(nameof(GetResourcePaths), new object[] { "fixdatafix44" })] public virtual void ValidateAutoData(string resourceName) { using (var data = ResourceLoader.DefaultLoader.LoadResource(resourceName)) { Validate(data, ErrorShouldOccur); Log.Info("Passed " + resourceName); } } [Test] [TestCaseSource(nameof(GetResourcePaths), new object[] { "FIX44." })] public virtual void ValidateCustomData(string resourceName) { using (var data = ResourceLoader.DefaultLoader.LoadResource(resourceName)) { Validate(data, ErrorShouldOccur); Log.Info("Passed " + resourceName); } } } }
30.934426
83
0.744038
[ "Apache-2.0" ]
epam/fix-antenna-net-core
Tests/Validation.Tests/Engine/Validation/Test/Validate44DataTest.cs
1,889
C#
// ==++== // // Copyright (c) Microsoft Corporation. All rights reserved. // // ==--== /*============================================================================= ** ** Class: ManifestResourceInfo ** ** <OWNER>[....]</OWNER> ** ** ** Purpose: For info regarding a manifest resource's topology. ** ** =============================================================================*/ namespace System.Reflection { using System; [System.Runtime.InteropServices.ComVisible(true)] public class ManifestResourceInfo { private Assembly _containingAssembly; private String _containingFileName; private ResourceLocation _resourceLocation; public ManifestResourceInfo(Assembly containingAssembly, String containingFileName, ResourceLocation resourceLocation) { _containingAssembly = containingAssembly; _containingFileName = containingFileName; _resourceLocation = resourceLocation; } public virtual Assembly ReferencedAssembly { get { return _containingAssembly; } } public virtual String FileName { get { return _containingFileName; } } public virtual ResourceLocation ResourceLocation { get { return _resourceLocation; } } } // The ResourceLocation is a combination of these flags, set or not. // Linked means not Embedded. [Serializable] [Flags] [System.Runtime.InteropServices.ComVisible(true)] public enum ResourceLocation { Embedded = 0x1, ContainedInAnotherAssembly = 0x2, ContainedInManifestFile = 0x4 } }
26.228571
79
0.533769
[ "Apache-2.0" ]
295007712/295007712.github.io
sourceCode/dotNet4.6/ndp/clr/src/BCL/system/reflection/manifestresourceinfo.cs
1,836
C#
// Code generated by Microsoft (R) AutoRest Code Generator 1.0.1.0 // Changes may cause incorrect behavior and will be lost if the code is // regenerated. namespace ApplicationGateway.Models { /// <summary> /// Defines values for VirtualNetworkGatewayType. /// </summary> public static class VirtualNetworkGatewayType { public const string Vpn = "Vpn"; public const string ExpressRoute = "ExpressRoute"; } }
26.470588
71
0.691111
[ "MIT" ]
bloudraak/autorest
Samples/test/end-to-end/network/Client/Models/VirtualNetworkGatewayType.cs
450
C#
using System.Collections.Generic; using Umbraco.Core.Models; namespace Umbraco.Core.Persistence.Repositories { internal interface IMacroRepository : IRepositoryQueryable<int, IMacro> { //IEnumerable<IMacro> GetAll(params string[] aliases); } }
23.166667
76
0.71223
[ "MIT" ]
AdrianJMartin/Umbraco-CMS
src/Umbraco.Core/Persistence/Repositories/Interfaces/IMacroRepository.cs
280
C#
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace driver { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void Form1_Load(object sender, EventArgs e) { //this.WindowState = FormWindowState.Minimized; hhgate.CustomServer.BeginServer(); } protected override void WndProc(ref Message m) { switch (m.Msg) { case 0x4e: case 0xd: case 0xe: case 0x14: base.WndProc(ref m); break; case 0x84://鼠标点任意位置后可以拖动窗体 this.DefWndProc(ref m); if (m.Result.ToInt32() == 0x01) { m.Result = new IntPtr(0x02); } break; case 0xA3://禁止双击最大化 break; default: base.WndProc(ref m); break; } } public static string publicKey_NoComp =""; public static byte[] privateKey; public static byte[] publicKey; public static string address =""; private void buttonWif_Click(object sender, EventArgs e) { //导入WIF try { var txt = this.textWIF.Text; var bytes_PrivateKey = NEO.AllianceOfThinWallet.Cryptography.Helper.GetPrivateKeyFromWIF(txt); var bytes_PublicKey = NEO.AllianceOfThinWallet.Cryptography.Helper.GetPublicKeyFromPrivateKey(bytes_PrivateKey); publicKey_NoComp = NEO.AllianceOfThinWallet.Cryptography.Helper.Bytes2HexString(NEO.AllianceOfThinWallet.Cryptography.Helper.GetPublicKeyFromPrivateKey_NoComp(bytes_PrivateKey)); var bytes_PublicKeyHash = NEO.AllianceOfThinWallet.Cryptography.Helper.GetPublicKeyHash(bytes_PublicKey); address = NEO.AllianceOfThinWallet.Cryptography.Helper.GetAddressFromPublicKey(bytes_PublicKey); privateKey = bytes_PrivateKey; publicKey = bytes_PublicKey; } catch { address = ""; MessageBox.Show("导入WIF错误"); } this.labelWif.Visible = false; this.textWIF.Visible = false; this.buttonWif.Visible = false; this.labelAccount.Text = address; } private void textWIF_TextChanged(object sender, EventArgs e) { } } }
32.488372
194
0.550107
[ "MIT" ]
NewEconoLab/NeoDun
驱动程序与钱包/neoHardWallet/driver/Form1.cs
2,850
C#
using System; using System.IO; using System.Threading.Tasks; using DryIoc; namespace MediatR.Examples.DryIoc { class Program { static Task Main() { var writer = new WrappingWriter(Console.Out); var mediator = BuildMediator(writer); return Runner.Run(mediator, writer, "DryIoc"); } private static IMediator BuildMediator(WrappingWriter writer) { var container = new Container(); container.RegisterDelegate<ServiceFactory>(r => r.Resolve); container.UseInstance<TextWriter>(writer); //Pipeline works out of the box here container.RegisterMany(new[] { typeof(IMediator).GetAssembly(), typeof(Ping).GetAssembly() }, Registrator.Interfaces); return container.Resolve<IMediator>(); } } }
25.969697
130
0.619603
[ "Apache-2.0" ]
ArnaudB88/MediatR
samples/MediatR.Examples.DryIoc/Program.cs
857
C#
using System.Collections.Generic; using Horizon.Payment.Alipay.Response; namespace Horizon.Payment.Alipay.Request { /// <summary> /// alipay.open.mini.morpho.appgray.cancel /// </summary> public class AlipayOpenMiniMorphoAppgrayCancelRequest : IAlipayRequest<AlipayOpenMiniMorphoAppgrayCancelResponse> { /// <summary> /// 取消灰度 /// </summary> public string BizContent { get; set; } #region IAlipayRequest Members private bool needEncrypt = false; private string apiVersion = "1.0"; private string terminalType; private string terminalInfo; private string prodCode; private string notifyUrl; private string returnUrl; private AlipayObject bizModel; public void SetNeedEncrypt(bool needEncrypt) { this.needEncrypt = needEncrypt; } public bool GetNeedEncrypt() { return needEncrypt; } public void SetNotifyUrl(string notifyUrl) { this.notifyUrl = notifyUrl; } public string GetNotifyUrl() { return notifyUrl; } public void SetReturnUrl(string returnUrl) { this.returnUrl = returnUrl; } public string GetReturnUrl() { return returnUrl; } public void SetTerminalType(string terminalType) { this.terminalType = terminalType; } public string GetTerminalType() { return terminalType; } public void SetTerminalInfo(string terminalInfo) { this.terminalInfo = terminalInfo; } public string GetTerminalInfo() { return terminalInfo; } public void SetProdCode(string prodCode) { this.prodCode = prodCode; } public string GetProdCode() { return prodCode; } public string GetApiName() { return "alipay.open.mini.morpho.appgray.cancel"; } public void SetApiVersion(string apiVersion) { this.apiVersion = apiVersion; } public string GetApiVersion() { return apiVersion; } public IDictionary<string, string> GetParameters() { var parameters = new AlipayDictionary { { "biz_content", BizContent } }; return parameters; } public AlipayObject GetBizModel() { return bizModel; } public void SetBizModel(AlipayObject bizModel) { this.bizModel = bizModel; } #endregion } }
22.629032
117
0.546329
[ "Apache-2.0" ]
bluexray/Horizon.Sample
Horizon.Payment.Alipay/Request/AlipayOpenMiniMorphoAppgrayCancelRequest.cs
2,816
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("eldenringsavebackup")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("eldenringsavebackup")] [assembly: AssemblyCopyright("Copyright © 2022")] [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("a2297230-7053-4416-b8bb-150bbb17da7e")] // 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
84
0.750356
[ "MIT" ]
thomasgraham18/eldenring-savebackupandload
eldenringsavebackup/Properties/AssemblyInfo.cs
1,409
C#
using System; using System.Collections.Generic; using System.Linq; using System.Web; using FluentValidation; using server.Model.Account; using server.Constants; namespace server.Model.Validators.Account_Validator { /// <summary> /// Validates the security questions and answers based on business rules /// </summary> public class SecurityQuestionValidator : AbstractValidator<List<SecurityQuestion>> { public SecurityQuestionValidator() { When(SecurityQuestions => SecurityQuestions != null, () => { RuleFor(SecurityQuestions => SecurityQuestions.Count).Must(SecurityQuestionCount => SecurityQuestionCount == 3).WithMessage(AccountConstants.QUESTION_AMOUNT_ERROR); RuleFor(SecurityQuestions => SecurityQuestions).Must(CheckAnswers).WithMessage(AccountConstants.ANSWER_INVALID_ERROR); }); } /// <summary> /// Checks user input of the answers to the security questions /// </summary> /// <param name="securityQuestions"></param> /// <returns> status of the validation of the answers </returns> public bool CheckAnswers(List<SecurityQuestion> securityQuestions) { foreach (SecurityQuestion question in securityQuestions) { if (question.Answer == null || question.Answer.Equals("") || question.Answer.Length > 150) { return false; } } return true; } } }
36.023256
180
0.631375
[ "MIT" ]
apham42/WhatFits
server/server/Business Logic/Validators/Account Validator/SecurityQuestionValidator.cs
1,551
C#
using System.Collections; using System.Collections.Generic; using UnityEngine; public class ParticleCollision : MonoBehaviour { public ParticleSystem part; public List<ParticleCollisionEvent> collisionEvents; void Start() { part = GetComponent<ParticleSystem>(); collisionEvents = new List<ParticleCollisionEvent>(); } float getMultiplier() { Debug.Log(part.name); if(part.name == "ChargedBeamParticle"){ return 10; } if(part.name == "MissleParticle"){ return 20; } return 1; } private void OnParticleCollision(GameObject other) { int numCollisionEvents = part.GetCollisionEvents(other, collisionEvents); if (numCollisionEvents > 0 && other.CompareTag("Interactable")) { if(other.GetComponent<Rigidbody>() != null) { Vector3 pos = collisionEvents[0].intersection; Vector3 force = collisionEvents[0].velocity * 10 * getMultiplier(); other.GetComponent<Rigidbody>().AddForceAtPosition(force, pos); } } } }
25.711111
83
0.605877
[ "MIT" ]
LucasMW/MetroidPrime-Hud
Assets/Scripts/ParticleCollision.cs
1,159
C#
using System; using System.Xml.Serialization; using System.Collections.Generic; namespace Aop.Api.Response { /// <summary> /// KoubeiMarketingCampaignRetailDmQueryResponse. /// </summary> public class KoubeiMarketingCampaignRetailDmQueryResponse : AopResponse { /// <summary> /// 第三方详情页链接:该商品/活动的详细介绍,注意:该字段需要过风控校验,不得传入敏感链接 /// </summary> [XmlElement("action_url")] public string ActionUrl { get; set; } /// <summary> /// 促销结束时间,用于产品详情展示,格式为:2017-02-07 11:11:11。 /// </summary> [XmlElement("activity_end_time")] public string ActivityEndTime { get; set; } /// <summary> /// 促销开始时间,在产品详情中展示,格式为:2017-02-01 11:11:11。 /// </summary> [XmlElement("activity_start_time")] public string ActivityStartTime { get; set; } /// <summary> /// 简要的促销说明,用于对促销的内容进行直接明了的说明(如会员价:10元)。 /// </summary> [XmlElement("brief")] public string Brief { get; set; } /// <summary> /// 活动的结束时间(下架时间) /// </summary> [XmlElement("campaign_end_time")] public string CampaignEndTime { get; set; } /// <summary> /// 活动类型:该活动是属于单品优惠,还是全场活动,单品优惠 SINGLE,全场优惠UNIVERSAL /// </summary> [XmlElement("campaign_type")] public string CampaignType { get; set; } /// <summary> /// 优惠类型,全场优惠传入枚举值 比如:DISCOUNT(折扣),OFF(立减),CARD(集点),VOUCHER(代金),REDEMPTION(换购),EXCHANGE(兑换),GIFT(买赠),OTHERS(其他) /// </summary> [XmlElement("coupon_type")] public string CouponType { get; set; } /// <summary> /// 活动文案,主要涉及(活动时间、参与方式、活动力度),最多不得超过1024个字 /// </summary> [XmlElement("description")] public string Description { get; set; } /// <summary> /// 扩展备用信息,一些其他信息存入该字段 /// </summary> [XmlElement("ext_info")] public string ExtInfo { get; set; } /// <summary> /// 图片url,该图片id只有一个,由Isv传入,(通过alipay.offline.material.image.upload 接口上传视频/图片获取的资源id /// </summary> [XmlElement("image_id")] public string ImageId { get; set; } /// <summary> /// 品牌:该商品属于哪个牌子/该活动属于哪个商家(比如 海飞丝,统一,徐福记,立白......) /// </summary> [XmlElement("item_brand")] public string ItemBrand { get; set; } /// <summary> /// 该商品/活动所属类别(吃的:食品 面膜:个人洗护 拖把:家庭清洁) /// </summary> [XmlElement("item_category")] public string ItemCategory { get; set; } /// <summary> /// 商品编码,SKU或店内码 /// </summary> [XmlElement("item_code")] public string ItemCode { get; set; } /// <summary> /// 商品名称,单品优惠时传入商品名称;全场活动时传入活动名称,注意:该字段需要过风控校验,不得传入敏感词 /// </summary> [XmlElement("item_name")] public string ItemName { get; set; } /// <summary> /// 该商品/活动,是否是会员专享的,TRUE表示会员专享,会显示会员标识,FALSE表示非会员专享 /// </summary> [XmlElement("member_only")] public string MemberOnly { get; set; } /// <summary> /// 适用外部门店id,传入该优惠适用口碑门店id,可以传入多个值,列表类型 /// </summary> [XmlArray("shop_ids")] [XmlArrayItem("string")] public List<string> ShopIds { get; set; } /// <summary> /// 店铺DM活动的状态信息(INIT:初始状态,ONLINE:上架状态,OFFLINE:下架状态) /// </summary> [XmlElement("status")] public string Status { get; set; } /// <summary> /// 4:3缩略图url,用于产品在店铺页简单规范的展示。 /// </summary> [XmlElement("thumbnail_image_id")] public string ThumbnailImageId { get; set; } } }
30.983607
121
0.532011
[ "Apache-2.0" ]
554393109/alipay-sdk-net-all
AlipaySDKNet.Standard/Response/KoubeiMarketingCampaignRetailDmQueryResponse.cs
4,810
C#
using System; using System.Collections.Generic; using System.Text; namespace Microsoft.VisualStudio.Utilities { /// <summary> /// Defines a feature which may be disabled using <see cref="IFeatureService"/> and grouped using <see cref="BaseDefinitionAttribute"/> /// </summary> /// <remarks> /// Because you cannot subclass this type, you can use the [Export] attribute with no type. /// </remarks> /// <example> /// [Export] /// [Name(nameof(MyFeature))] // required /// [BaseDefinition(PredefinedEditorFeatureNames.Popup)] // zero or more BaseDefinitions are allowed /// public FeatureDefinition MyFeature; /// </example> public sealed class FeatureDefinition { } }
31.913043
139
0.668937
[ "MIT" ]
AmadeusW/vs-editor-api
src/Editor/Core/Def/Features/FeatureDefinition.cs
736
C#
 using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; namespace EPiServer.Reference.Commerce.Site.Infrastructure { public class SiteViewEngine : RazorViewEngine { private static readonly string[] AdditionalPartialViewFormats = new[] { ViewTemplateModelRegistrator.BlockFolder + "{0}.cshtml", ViewTemplateModelRegistrator.PagePartialsFolder + "{0}.cshtml" }; public SiteViewEngine() { PartialViewLocationFormats = PartialViewLocationFormats.Union(AdditionalPartialViewFormats).ToArray(); } } }
27.875
114
0.669656
[ "Apache-2.0" ]
huyphan2/episerver-team-01
Sources/EPiServer.Reference.Commerce.Site/Infrastructure/SiteViewEngine.cs
671
C#
using GraphQL; using GraphQL.EntityFramework; [GraphQLMetadata(nameof(MappingChild))] public class MappingChildGraph : EfObjectGraphType<MappingContext, MappingChild> { public MappingChildGraph(IEfGraphQLService<MappingContext> graphQlService) : base(graphQlService) { AutoMap(); } }
24.384615
80
0.744479
[ "MIT" ]
Intecpsp/GraphQL.EntityFramework
src/Tests/Mapping/MappingChildGraph.cs
319
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("SortEvenNumbers")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("SortEvenNumbers")] [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("ecb86afb-2b2b-410e-a3c6-d184ec3f40ee")] // 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.783784
84
0.748927
[ "MIT" ]
varbanov88/C-Advanced
FunctionalProgramming/SortEvenNumbers/Properties/AssemblyInfo.cs
1,401
C#
using UnityEngine; public class LevelManager : MonoBehaviour { public Levels[] levels; public Transform[] lanes; private ObjectPool glassPool; private ObjectPool polePool; private ObjectPool explosionCubePool; public GameObject levelEndPrefab; [HideInInspector] public GameObject levelEndGO; [HideInInspector] public int currentLevel; [HideInInspector] public int target; [HideInInspector] public int movingGlass; [HideInInspector] public float glassMovementSpeed; [HideInInspector] public int staticGlass; [HideInInspector] public int pole; [HideInInspector] public float distanceBetweenObstacles; private Player player; public static LevelManager Instance { get; private set; } void Awake() { Instance = this; foreach (ObjectPool objectPool in FindObjectsOfType<ObjectPool>()) { if (objectPool.poolType == PoolType.Glass) glassPool = objectPool; if (objectPool.poolType == PoolType.Pole) polePool = objectPool; if (objectPool.poolType == PoolType.ExplosionCube) explosionCubePool = objectPool; } StartGameplay(); } public void StartGameplay() { if (!player) player = FindObjectOfType<Player>(); setLevel(InGameData.Instance.playerData.levelsUnlocked); generateLevel(); ColorPalateManager.Instance.StartGameplay(); player.StartGameplay(); UIManager.Instance.StartGameplay(InGameData.Instance.playerData.levelsUnlocked); } public void setLevel(int level) { currentLevel = level; target = levels[currentLevel - 1].target; movingGlass = levels[currentLevel - 1].movingGlass; glassMovementSpeed = levels[currentLevel - 1].glassMovementSpeed; staticGlass = levels[currentLevel - 1].staticGlass; pole = levels[currentLevel - 1].pole; distanceBetweenObstacles = levels[currentLevel - 1].distanceBetweenObstacles; } void generateLevel() { if (glassPool) glassPool.disableAll(); if (polePool) polePool.disableAll(); if (explosionCubePool) explosionCubePool.disableAll(); float lastSpawnedZ = player.startingPosition.z + distanceBetweenObstacles * 4; Vector3 positionToSpawnAt; do { int spawnDecision = Random.Range(0,3); switch (spawnDecision) { case 0: if (movingGlass > 0) { lastSpawnedZ += distanceBetweenObstacles; positionToSpawnAt = new Vector3(lanes[Random.Range(0, lanes.Length/2 + 1) *2].position.x ,1, lastSpawnedZ); glassPool.spawnObject(positionToSpawnAt, glassMovementSpeed); movingGlass -= 1; } break; case 1: if (staticGlass > 0) { lastSpawnedZ += distanceBetweenObstacles; positionToSpawnAt = new Vector3(lanes[Random.Range(0, lanes.Length/2 + 1) * 2].position.x, 1, lastSpawnedZ); glassPool.spawnObject(positionToSpawnAt, 0); staticGlass -= 1; } break; case 2: if (pole > 0) { lastSpawnedZ += distanceBetweenObstacles; positionToSpawnAt = new Vector3(lanes[Random.Range(0, lanes.Length)].position.x, 1, lastSpawnedZ); polePool.spawnObject(positionToSpawnAt, 0); pole -= 1; } break; default: break; } } while (movingGlass > 0 || staticGlass > 0 || pole > 0); //Spawn Level exit if (!levelEndGO) levelEndGO = Instantiate(levelEndPrefab, Vector3.zero, Quaternion.identity) as GameObject; levelEndGO.transform.position = new Vector3(0, 1, lastSpawnedZ + distanceBetweenObstacles * 4); foreach (Transform child in levelEndGO.transform) if (!child.gameObject.activeSelf) child.gameObject.SetActive(true); } public void LevelCleared() { Debug.Log("currentLevel " + currentLevel); Debug.Log("levels.Length " + levels.Length); if (levels.Length > currentLevel) { InGameData.Instance.playerData.levelsUnlocked = currentLevel + 1; LocalSave.Instance.SaveData(); } } }
35.066667
132
0.576046
[ "MIT" ]
waqaas993/mindstorm-task
Assets/Scripts/LevelManager.cs
4,736
C#
using Righthand.Immutable; namespace KzsRest.Models { public class Player { public int Id { get; } public int? Number { get; } public string FullName { get; } public string NationalityCode { get; } public string Nationality { get; } public int? BirthYear { get; } public string Position { get; } public int? Height { get; } public Player(int id, int? number, string fullName, string nationalityCode, string nationality, int? birthYear, string position, int? height) { Id = id; Number = number; FullName = fullName; NationalityCode = nationalityCode; Nationality = nationality; BirthYear = birthYear; Position = position; Height = height; } public Player Clone(Param<int>? id = null, Param<int?>? number = null, Param<string>? fullName = null, Param<string>? nationalityCode = null, Param<string>? nationality = null, Param<int?>? birthYear = null, Param<string>? position = null, Param<int?>? height = null) { return new Player(id.HasValue ? id.Value.Value : Id, number.HasValue ? number.Value.Value : Number, fullName.HasValue ? fullName.Value.Value : FullName, nationalityCode.HasValue ? nationalityCode.Value.Value : NationalityCode, nationality.HasValue ? nationality.Value.Value : Nationality, birthYear.HasValue ? birthYear.Value.Value : BirthYear, position.HasValue ? position.Value.Value : Position, height.HasValue ? height.Value.Value : Height); } public override bool Equals(object obj) { if (obj == null || GetType() != obj.GetType()) return false; var o = (Player)obj; return Equals(Id, o.Id) && Equals(Number, o.Number) && Equals(FullName, o.FullName) && Equals(NationalityCode, o.NationalityCode) && Equals(Nationality, o.Nationality) && Equals(BirthYear, o.BirthYear) && Equals(Position, o.Position) && Equals(Height, o.Height);} public override int GetHashCode() { unchecked { int hash = 23; hash = hash * 37 + Id.GetHashCode(); hash = hash * 37 + (Number != null ? Number.GetHashCode() : 0); hash = hash * 37 + (FullName != null ? FullName.GetHashCode() : 0); hash = hash * 37 + (NationalityCode != null ? NationalityCode.GetHashCode() : 0); hash = hash * 37 + (Nationality != null ? Nationality.GetHashCode() : 0); hash = hash * 37 + (BirthYear != null ? BirthYear.GetHashCode() : 0); hash = hash * 37 + (Position != null ? Position.GetHashCode() : 0); hash = hash * 37 + (Height != null ? Height.GetHashCode() : 0); return hash; } } } }
43.078125
275
0.610809
[ "MIT" ]
MihaMarkic/KzsRestService
source/KzsRest/KzsRest.Models/Player.cs
2,759
C#
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.Video; using UnityEngine.UI; using DG.Tweening; public class RoadDisplay : MonoBehaviour { public string content; public string header; public void StartThing(System.Action _d, string _h, string _c) { done = _d; content = _c; header = _h; GetComponentInChildren<TMPro.TMP_Text>().text = header; GetComponentInChildren<DG.Tweening.DOTweenAnimation>().DOPlayById("firstTween"); } public void FeedText() { GetComponentInChildren<TMPro.TMP_Text>().fontSize = 42; GetComponentInChildren<TMPro.TMP_Text>().text = content; } System.Action done; public void Terminate() { done(); Destroy(gameObject); } }
24.454545
88
0.674102
[ "Unlicense" ]
SandGardeners/Exhaustlands
Assets/Scripts/UIDisplay/RoadDisplay.cs
807
C#
// <auto-generated> // Code generated by Microsoft (R) AutoRest Code Generator. // Changes may cause incorrect behavior and will be lost if the code is // regenerated. // </auto-generated> namespace Gov.Lclb.Cllb.Interfaces { using Models; using System.Collections; using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; /// <summary> /// Extension methods for Invoices. /// </summary> public static partial class InvoicesExtensions { /// <summary> /// Get entities from invoices /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='top'> /// Show only the first n items /// </param> /// <param name='skip'> /// Skip only the first n items /// </param> /// <param name='search'> /// Search items by search phrases /// </param> /// <param name='filter'> /// Filter items by property values /// </param> /// <param name='count'> /// Include count of items /// </param> /// <param name='orderby'> /// Order items by property values /// </param> /// <param name='select'> /// Select properties to be returned /// </param> /// <param name='expand'> /// Expand related entities /// </param> public static GetOKResponseModelModelModelModelModelModelModelModelModelModelModelModelModelModelModelModelModelModel Get(this IInvoices operations, int? top = default(int?), int? skip = default(int?), string search = default(string), string filter = default(string), bool? count = default(bool?), IList<string> orderby = default(IList<string>), IList<string> select = default(IList<string>), IList<string> expand = default(IList<string>)) { return operations.GetAsync(top, skip, search, filter, count, orderby, select, expand).GetAwaiter().GetResult(); } /// <summary> /// Get entities from invoices /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='top'> /// Show only the first n items /// </param> /// <param name='skip'> /// Skip only the first n items /// </param> /// <param name='search'> /// Search items by search phrases /// </param> /// <param name='filter'> /// Filter items by property values /// </param> /// <param name='count'> /// Include count of items /// </param> /// <param name='orderby'> /// Order items by property values /// </param> /// <param name='select'> /// Select properties to be returned /// </param> /// <param name='expand'> /// Expand related entities /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<GetOKResponseModelModelModelModelModelModelModelModelModelModelModelModelModelModelModelModelModelModel> GetAsync(this IInvoices operations, int? top = default(int?), int? skip = default(int?), string search = default(string), string filter = default(string), bool? count = default(bool?), IList<string> orderby = default(IList<string>), IList<string> select = default(IList<string>), IList<string> expand = default(IList<string>), CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.GetWithHttpMessagesAsync(top, skip, search, filter, count, orderby, select, expand, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Add new entity to invoices /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='body'> /// New entity /// </param> /// <param name='prefer'> /// Required in order for the service to return a JSON representation of the /// object. /// </param> public static MicrosoftDynamicsCRMinvoice Create(this IInvoices operations, MicrosoftDynamicsCRMinvoice body, string prefer = "return=representation") { return operations.CreateAsync(body, prefer).GetAwaiter().GetResult(); } /// <summary> /// Add new entity to invoices /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='body'> /// New entity /// </param> /// <param name='prefer'> /// Required in order for the service to return a JSON representation of the /// object. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<MicrosoftDynamicsCRMinvoice> CreateAsync(this IInvoices operations, MicrosoftDynamicsCRMinvoice body, string prefer = "return=representation", CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.CreateWithHttpMessagesAsync(body, prefer, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Delete entity from invoices /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='invoiceid'> /// key: invoiceid /// </param> /// <param name='ifMatch'> /// ETag /// </param> public static void Delete(this IInvoices operations, string invoiceid, string ifMatch = default(string)) { operations.DeleteAsync(invoiceid, ifMatch).GetAwaiter().GetResult(); } /// <summary> /// Delete entity from invoices /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='invoiceid'> /// key: invoiceid /// </param> /// <param name='ifMatch'> /// ETag /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task DeleteAsync(this IInvoices operations, string invoiceid, string ifMatch = default(string), CancellationToken cancellationToken = default(CancellationToken)) { (await operations.DeleteWithHttpMessagesAsync(invoiceid, ifMatch, null, cancellationToken).ConfigureAwait(false)).Dispose(); } /// <summary> /// Get entity from invoices by key /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='invoiceid'> /// key: invoiceid /// </param> /// <param name='select'> /// Select properties to be returned /// </param> /// <param name='expand'> /// Expand related entities /// </param> public static MicrosoftDynamicsCRMinvoice GetByKey(this IInvoices operations, string invoiceid, IList<string> select = default(IList<string>), IList<string> expand = default(IList<string>)) { return operations.GetByKeyAsync(invoiceid, select, expand).GetAwaiter().GetResult(); } /// <summary> /// Get entity from invoices by key /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='invoiceid'> /// key: invoiceid /// </param> /// <param name='select'> /// Select properties to be returned /// </param> /// <param name='expand'> /// Expand related entities /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<MicrosoftDynamicsCRMinvoice> GetByKeyAsync(this IInvoices operations, string invoiceid, IList<string> select = default(IList<string>), IList<string> expand = default(IList<string>), CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.GetByKeyWithHttpMessagesAsync(invoiceid, select, expand, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Update entity in invoices /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='invoiceid'> /// key: invoiceid /// </param> /// <param name='body'> /// New property values /// </param> public static void Update(this IInvoices operations, string invoiceid, MicrosoftDynamicsCRMinvoice body) { operations.UpdateAsync(invoiceid, body).GetAwaiter().GetResult(); } /// <summary> /// Update entity in invoices /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='invoiceid'> /// key: invoiceid /// </param> /// <param name='body'> /// New property values /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task UpdateAsync(this IInvoices operations, string invoiceid, MicrosoftDynamicsCRMinvoice body, CancellationToken cancellationToken = default(CancellationToken)) { (await operations.UpdateWithHttpMessagesAsync(invoiceid, body, null, cancellationToken).ConfigureAwait(false)).Dispose(); } /// <summary> /// Invoke function GetQuantityDecimal /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='entity'> /// </param> /// <param name='product'> /// </param> /// <param name='uoM'> /// </param> public static MicrosoftDynamicsCRMGetQuantityDecimalResponse GetQuantityDecimal(this IInvoices operations, string entity, string product, string uoM) { return operations.GetQuantityDecimalAsync(entity, product, uoM).GetAwaiter().GetResult(); } /// <summary> /// Invoke function GetQuantityDecimal /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='entity'> /// </param> /// <param name='product'> /// </param> /// <param name='uoM'> /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<MicrosoftDynamicsCRMGetQuantityDecimalResponse> GetQuantityDecimalAsync(this IInvoices operations, string entity, string product, string uoM, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.GetQuantityDecimalWithHttpMessagesAsync(entity, product, uoM, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Invoke action LockInvoicePricing /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='invoiceid'> /// </param> public static void LockInvoicePricing(this IInvoices operations, string invoiceid) { operations.LockInvoicePricingAsync(invoiceid).GetAwaiter().GetResult(); } /// <summary> /// Invoke action LockInvoicePricing /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='invoiceid'> /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task LockInvoicePricingAsync(this IInvoices operations, string invoiceid, CancellationToken cancellationToken = default(CancellationToken)) { (await operations.LockInvoicePricingWithHttpMessagesAsync(invoiceid, null, cancellationToken).ConfigureAwait(false)).Dispose(); } } }
43.468085
534
0.532201
[ "Apache-2.0" ]
rafaelponcedeleon/ag-lclb-cllc-public
cllc-interfaces/Dynamics-Autorest/InvoicesExtensions.cs
14,301
C#
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.SceneManagement; public class MainMenu : MonoBehaviour { public void PlayGame() { LevelManager levelManager = GameObject.FindObjectOfType<LevelManager>(); levelManager.loadGameRoom(); } public void QuitGame() { Debug.Log("QUIT!"); Application.Quit(); } }
20.75
80
0.672289
[ "MIT" ]
GambuzX/MyMicroAddiction
project/Assets/Scripts/MainMenu/MainMenu.cs
417
C#
// Copyright (c) MOSA Project. Licensed under the New BSD License. using Mosa.Compiler.Framework.Analysis; namespace Mosa.Compiler.Framework.Stages { /// <summary> /// The Block Ordering Stage reorders blocks to optimize loops and reduce the distance of jumps and branches. /// </summary> public class BlockOrderingStage : BaseMethodCompilerStage { protected override void Run() { var blockOrderAnalysis = new LoopAwareBlockOrder(); blockOrderAnalysis.Analyze(BasicBlocks); var newBlockOrder = blockOrderAnalysis.NewBlockOrder; if (HasProtectedRegions) { newBlockOrder = AddMissingBlocksIfRequired(newBlockOrder); } BasicBlocks.ReorderBlocks(newBlockOrder); DumpTrace(blockOrderAnalysis); } private void DumpTrace(LoopAwareBlockOrder blockOrderAnalysis) { var trace = CreateTraceLog(); if (trace == null) return; int index = 0; foreach (var block in blockOrderAnalysis.NewBlockOrder) { if (block != null) trace.Log($"# {index.ToString()} Block {block} #{block.Sequence.ToString()}"); else trace.Log($"# {index.ToString()} NONE"); index++; } trace.Log(); foreach (var block in BasicBlocks) { int depth = blockOrderAnalysis.GetLoopDepth(block); int depthindex = blockOrderAnalysis.GetLoopIndex(block); trace.Log($"Block {block} #{block.Sequence.ToString()} -> Depth: {depth.ToString()} Index: {depthindex.ToString()}"); } } } }
23.852459
121
0.699656
[ "BSD-3-Clause" ]
Arakis/MOSA-Project
Source/Mosa.Compiler.Framework/Stages/BlockOrderingStage.cs
1,455
C#
namespace p04._01.MatrixShuffling { using System; using System.Linq; class MatrixShuffling { static int rows; static string[][] matrix; static void Main(string[] args) { int[] size = Console.ReadLine() .Split(" ", StringSplitOptions .RemoveEmptyEntries) .Select(int.Parse) .ToArray(); rows = size[0]; matrix = new string[rows][]; FillInTheMatrix(); string input = Console.ReadLine(); while (input.Equals("END") == false) { string[] tokens = input .Split(" ", StringSplitOptions .RemoveEmptyEntries); string command = tokens[0]; if (tokens.Length == 5 && command == "swap") { int firstRow = int.Parse(tokens[1]); int firstCol = int.Parse(tokens[2]); int secondRow = int.Parse(tokens[3]); int secondCol = int.Parse(tokens[4]); bool isValidFirstElement = IsOutOfTheRange(firstRow, firstCol); bool isValidSecondElement = IsOutOfTheRange(secondRow, secondCol); if (isValidFirstElement && isValidSecondElement) { ResultInvalidInput(); input = Console.ReadLine(); continue; } string temp = matrix[firstRow][firstCol]; matrix[firstRow][firstCol] = matrix[secondRow][secondCol]; matrix[secondRow][secondCol] = temp; PrintResult(); } else { ResultInvalidInput(); } input = Console.ReadLine(); } } private static void PrintResult() { foreach (string[] row in matrix) { Console.WriteLine(string.Join(" ", row)); } } private static void ResultInvalidInput() { Console.WriteLine("Invalid input!"); } private static bool IsOutOfTheRange(int row, int col) { bool isInvalidInput = row < 0 || row >= matrix.Length || col < 0 || col >= matrix[row].Length; if (!isInvalidInput) { return false; } return true; } private static void FillInTheMatrix() { for (int row = 0; row < matrix.Length; row++) { string[] input = Console.ReadLine() .Split(" ", StringSplitOptions .RemoveEmptyEntries); matrix[row] = input; } } } }
27.596491
86
0.413223
[ "MIT" ]
vesy53/SoftUni
C# Advanced/C#Adanced/LabEndExercises/04.MultidimensionalArraysExercise/p04.01.Matrixshuffling/Matrixshuffling.cs
3,148
C#
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Diagnostics; using System.Windows.Forms; using System.IO; using System.Net; using Codeplex.Data; namespace VisualFormTest { public partial class KancolleInfoFleet_ConvertDeckBuilder : Form { CheckBox[] cbs; public KancolleInfoFleet_ConvertDeckBuilder(int deckMax, int selectedDeck) { InitializeComponent(); cbs = new CheckBox[] { checkBox1, checkBox2, checkBox3, checkBox4 }; for(int i=0; i<Math.Min(deckMax, cbs.Length); i++) { cbs[i].Enabled = true; } if(selectedDeck >= 0 && selectedDeck < cbs.Length) { cbs[selectedDeck].Checked = true; } } private void linkLabel1_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e) { Process.Start(linkLabel1.Text); } private void button_selectall_Click(object sender, EventArgs e) { bool isAllSelected = checkBox1.Checked && checkBox2.Checked && checkBox3.Checked && checkBox4.Checked; foreach (var x in cbs) x.Checked = !isAllSelected; } private async void button_convert_Click(object sender, EventArgs e) { if (checkBox1.Checked || checkBox2.Checked || checkBox3.Checked || checkBox4.Checked) { } else return; //ボタンを無効にする button_convert.Enabled = false; //どれか選択されている場合 int end = cbs.Length; for(int i=cbs.Length-1; i>=0; i--) { if(cbs[i].Checked) { end = i; break; } } List<bool> checks = new List<bool>(); for(int i=0; i<=end; i++) { checks.Add(cbs[i].Checked); } //変換後の文字の取得 string convert = KancolleInfoFleet.context_ConvertDeckBuilderLogic(checks); if (convert != null) { textBox1.Text = convert; //リンクラベルに変換 string encode = Uri.EscapeUriString(convert); string url = @"http://www.kancolle-calc.net/deckbuilder.html?predeck=" + encode; //2艦隊以上出力する場合は短縮URLに変換 if(checks.Where(x => x).Count() >= 2) { await Task.Factory.StartNew(() => { try { //is.gdを使用 var httpWebRequest = (HttpWebRequest)WebRequest.Create("https://is.gd/create.php?format=simple&url="+url); httpWebRequest.Method = "POST"; //レスポンスを読む var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse(); string responseText = null; using (var streamReader = new StreamReader(httpResponse.GetResponseStream())) { responseText = streamReader.ReadToEnd(); } //is.gdのレスポンス if(responseText != null) { if(responseText.Contains("error")) { MessageBox.Show(responseText); } else { url = responseText; } } } catch(Exception ex) { MessageBox.Show(ex.ToString()); } }); } linkLabel2.Text = url; } //ボタンを有効に戻す button_convert.Enabled = true; } private void linkLabel2_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e) { if (linkLabel2.Text != "Link") { Process.Start(linkLabel2.Text); } } } }
34.470149
138
0.441438
[ "MIT" ]
yamadansan/HoppoAlpha
VisualFormTest/KancolleInfoFleet_ConvertDeckBuilder.cs
4,783
C#
using Microsoft.Xna.Framework; namespace SixteenBox.Graphics { interface IDrawable { void Draw(GameTime gameTime); } }
14.1
37
0.673759
[ "MIT" ]
RafaelMFonseca/SixteenBox
SixteenBox/Graphics/IDrawable.cs
143
C#
/* * Copyright 2010-2014 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ /* * Do not modify this file. This file is generated from the waf-2015-08-24.normal.json service model. */ using System; using System.Collections.Generic; using System.Globalization; using System.IO; using System.Text; using System.Xml.Serialization; using Amazon.WAF.Model; using Amazon.Runtime; using Amazon.Runtime.Internal; using Amazon.Runtime.Internal.Transform; using Amazon.Runtime.Internal.Util; using ThirdParty.Json.LitJson; namespace Amazon.WAF.Model.Internal.MarshallTransformations { /// <summary> /// UpdateRateBasedRule Request Marshaller /// </summary> public class UpdateRateBasedRuleRequestMarshaller : IMarshaller<IRequest, UpdateRateBasedRuleRequest> , IMarshaller<IRequest,AmazonWebServiceRequest> { /// <summary> /// Marshaller the request object to the HTTP request. /// </summary> /// <param name="input"></param> /// <returns></returns> public IRequest Marshall(AmazonWebServiceRequest input) { return this.Marshall((UpdateRateBasedRuleRequest)input); } /// <summary> /// Marshaller the request object to the HTTP request. /// </summary> /// <param name="publicRequest"></param> /// <returns></returns> public IRequest Marshall(UpdateRateBasedRuleRequest publicRequest) { IRequest request = new DefaultRequest(publicRequest, "Amazon.WAF"); string target = "AWSWAF_20150824.UpdateRateBasedRule"; request.Headers["X-Amz-Target"] = target; request.Headers["Content-Type"] = "application/x-amz-json-1.1"; request.HttpMethod = "POST"; string uriResourcePath = "/"; request.ResourcePath = uriResourcePath; using (StringWriter stringWriter = new StringWriter(CultureInfo.InvariantCulture)) { JsonWriter writer = new JsonWriter(stringWriter); writer.WriteObjectStart(); var context = new JsonMarshallerContext(request, writer); if(publicRequest.IsSetChangeToken()) { context.Writer.WritePropertyName("ChangeToken"); context.Writer.Write(publicRequest.ChangeToken); } if(publicRequest.IsSetRateLimit()) { context.Writer.WritePropertyName("RateLimit"); context.Writer.Write(publicRequest.RateLimit); } if(publicRequest.IsSetRuleId()) { context.Writer.WritePropertyName("RuleId"); context.Writer.Write(publicRequest.RuleId); } if(publicRequest.IsSetUpdates()) { context.Writer.WritePropertyName("Updates"); context.Writer.WriteArrayStart(); foreach(var publicRequestUpdatesListValue in publicRequest.Updates) { context.Writer.WriteObjectStart(); var marshaller = RuleUpdateMarshaller.Instance; marshaller.Marshall(publicRequestUpdatesListValue, context); context.Writer.WriteObjectEnd(); } context.Writer.WriteArrayEnd(); } writer.WriteObjectEnd(); string snippet = stringWriter.ToString(); request.Content = System.Text.Encoding.UTF8.GetBytes(snippet); } return request; } } }
36.525862
153
0.605381
[ "Apache-2.0" ]
Murcho/aws-sdk-net
sdk/src/Services/WAF/Generated/Model/Internal/MarshallTransformations/UpdateRateBasedRuleRequestMarshaller.cs
4,237
C#
//------------------------------------------------------------------------------ // <auto-generated> // This code was generated by a tool. // Runtime Version:4.0.30319.42000 // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ [assembly: System.Windows.Resources.AssemblyAssociatedContentFileAttribute("modeldb.context.tt")] [assembly: System.Windows.Resources.AssemblyAssociatedContentFileAttribute("modeldb.tt")]
39.2
97
0.539116
[ "Unlicense" ]
UagNanit/-Team-Project
Interpol/obj/Debug/Interpol_Content.g.cs
590
C#
using System.Linq; using Microsoft.Extensions.DependencyInjection; namespace Abp.MsDependencyInjection.Extensions { public static class ServiceCollectionExtensions { internal static T GetSingletonServiceOrNull<T>(this IServiceCollection services) { return (T)services .FirstOrDefault(d => d.ServiceType == typeof(T)) ?.ImplementationInstance; } } }
26.9375
88
0.665893
[ "MIT" ]
jefftindall/aspnetboilerplate
src/Abp.AspNetCore/MsDependencyInjection/Extensions/ServiceCollectionExtensions.cs
433
C#
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Runtime.CompilerServices; using System.Text; using System.Text.RegularExpressions; using JetBrains.Annotations; using OpenMLTD.MillionDance.Entities.Pmx; using OpenMLTD.MillionDance.Entities.Pmx.Extensions; using OpenMLTD.MillionDance.Extensions; using OpenTK; namespace OpenMLTD.MillionDance.Core { internal sealed class PmxWriter : DisposableBase { public PmxWriter([NotNull] Stream stream) { _writer = new BinaryWriter(stream); } public void Write([NotNull] PmxModel model) { EnsureNotDisposed(); WriteHeader(); WriteElementFormats(); WritePmxModel(model); } protected override void Dispose(bool disposing) { _writer?.Dispose(); _writer = null; base.Dispose(disposing); } private PmxFormatVersion MajorVersion { get; } = PmxFormatVersion.Version2; private float DetailedVersion { get; } = 2.0f; private PmxStringEncoding StringEncoding { get; } = PmxStringEncoding.Utf16; private int UvaCount { get; } = 0; private int VertexElementSize { get; } = 4; private int BoneElementSize { get; } = 4; private int MorphElementSize { get; } = 4; private int MaterialElementSize { get; } = 4; private int RigidBodyElementSize { get; } = 4; private int TexElementSize { get; } = 4; private void WritePmxModel([NotNull] PmxModel model) { BuildTextureNameMap(model); WriteString(model.Name); WriteString(model.NameEnglish); WriteString(model.Comment); WriteString(model.CommentEnglish); WriteVertexInfo(); WriteFaceInfo(); WriteTextureInfo(); WriteMaterialInfo(); WriteBoneInfo(); WriteMorphInfo(); WriteNodeInfo(); WriteRigidBodyInfo(); WriteJointInfo(); WriteSoftBodyInfo(); void WriteVertexInfo() { if (model.Vertices != null) { _writer.Write(model.Vertices.Count); foreach (var vertex in model.Vertices) { WritePmxVertex(vertex); } } else { _writer.Write(0); } } void WriteFaceInfo() { if (model.FaceTriangles != null) { _writer.Write(model.FaceTriangles.Count); foreach (var v in model.FaceTriangles) { _writer.WriteInt32AsVarLenInt(v, VertexElementSize, true); } } else { _writer.Write(0); } } void WriteTextureInfo() { var textureCount = _textureNameList.Count; _writer.Write(textureCount); foreach (var textureName in _textureNameList) { WriteString(textureName); } } void WriteMaterialInfo() { if (model.Materials != null) { _writer.Write(model.Materials.Count); foreach (var material in model.Materials) { WritePmxMaterial(material); } } else { _writer.Write(0); } } void WriteBoneInfo() { if (model.Bones != null) { _writer.Write(model.Bones.Count); foreach (var bone in model.Bones) { WritePmxBone(bone); } } else { _writer.Write(0); } } void WriteMorphInfo() { if (model.Morphs != null) { _writer.Write(model.Morphs.Count); foreach (var morph in model.Morphs) { WritePmxMorph(morph); } } else { _writer.Write(0); } } void WriteNodeInfo() { if (model.Nodes != null) { _writer.Write(model.Nodes.Count); foreach (var node in model.Nodes) { WritePmxNode(node); } } else { _writer.Write(0); } } void WriteRigidBodyInfo() { if (model.RigidBodies != null) { _writer.Write(model.RigidBodies.Count); foreach (var body in model.RigidBodies) { WritePmxRigidBody(body); } } else { _writer.Write(0); } } void WriteJointInfo() { if (model.Joints != null) { _writer.Write(model.Joints.Count); foreach (var joint in model.Joints) { WritePmxJoint(joint); } } else { _writer.Write(0); } } void WriteSoftBodyInfo() { if (DetailedVersion < 2.1f) { return; } if (model.SoftBodies != null) { _writer.Write(model.SoftBodies.Count); foreach (var body in model.SoftBodies) { WritePmxSoftBody(body); } } else { _writer.Write(0); } } } private void WritePmxVertex([NotNull] PmxVertex vertex) { _writer.Write(vertex.Position); _writer.Write(vertex.Normal); _writer.Write(vertex.UV); for (var i = 0; i < UvaCount && i < PmxVertex.MaxUvaCount; ++i) { _writer.Write(vertex.Uva[i]); } _writer.Write((byte)vertex.Deformation); switch (vertex.Deformation) { case Deformation.Bdef1: _writer.WriteInt32AsVarLenInt(vertex.BoneWeights[0].BoneIndex, BoneElementSize); break; case Deformation.Bdef2: _writer.WriteInt32AsVarLenInt(vertex.BoneWeights[0].BoneIndex, BoneElementSize); _writer.WriteInt32AsVarLenInt(vertex.BoneWeights[1].BoneIndex, BoneElementSize); _writer.Write(vertex.BoneWeights[0].Weight); break; case Deformation.Bdef4: case Deformation.Qdef: _writer.WriteInt32AsVarLenInt(vertex.BoneWeights[0].BoneIndex, BoneElementSize); _writer.WriteInt32AsVarLenInt(vertex.BoneWeights[1].BoneIndex, BoneElementSize); _writer.WriteInt32AsVarLenInt(vertex.BoneWeights[2].BoneIndex, BoneElementSize); _writer.WriteInt32AsVarLenInt(vertex.BoneWeights[3].BoneIndex, BoneElementSize); _writer.Write(vertex.BoneWeights[0].Weight); _writer.Write(vertex.BoneWeights[1].Weight); _writer.Write(vertex.BoneWeights[2].Weight); _writer.Write(vertex.BoneWeights[3].Weight); break; case Deformation.Sdef: { _writer.WriteInt32AsVarLenInt(vertex.BoneWeights[0].BoneIndex, BoneElementSize); _writer.WriteInt32AsVarLenInt(vertex.BoneWeights[1].BoneIndex, BoneElementSize); _writer.Write(vertex.BoneWeights[0].Weight); _writer.Write(vertex.C0); _writer.Write(vertex.R0); _writer.Write(vertex.R1); break; } default: throw new ArgumentOutOfRangeException(); } _writer.Write(vertex.EdgeScale); } private void WritePmxMaterial([NotNull] PmxMaterial material) { WriteString(material.Name); WriteString(material.NameEnglish); _writer.Write(material.Diffuse); _writer.Write(material.Specular); _writer.Write(material.SpecularPower); _writer.Write(material.Ambient); _writer.Write((byte)material.Flags); _writer.Write(material.EdgeColor); _writer.Write(material.EdgeSize); var texNameIndex = GetTextureIndex(material.TextureFileName); _writer.WriteInt32AsVarLenInt(texNameIndex, TexElementSize); var sphereTexNameIndex = GetTextureIndex(material.SphereTextureFileName); _writer.WriteInt32AsVarLenInt(sphereTexNameIndex, TexElementSize); _writer.Write((byte)material.SphereMode); var mappedToonTexture = !IsNormalToonTexture(material.ToonTextureFileName, out var toon); _writer.Write(!mappedToonTexture); if (mappedToonTexture) { var toonTexNameIndex = GetTextureIndex(material.ToonTextureFileName); _writer.WriteInt32AsVarLenInt(toonTexNameIndex, TexElementSize); } else { _writer.Write((byte)toon); } WriteString(material.MemoTextureFileName); _writer.Write(material.AppliedFaceVertexCount); bool IsNormalToonTexture(string name, out int toonIndex) { if (string.IsNullOrEmpty(name)) { toonIndex = 0; return true; } var match = ToonNameRegex.Match(name); if (!match.Success) { toonIndex = -1; return false; } toonIndex = Convert.ToInt32(match.Groups["toonIndex"].Value); return toonIndex >= 0; } } private void WritePmxBone([NotNull] PmxBone bone) { WriteString(bone.Name); WriteString(bone.NameEnglish); _writer.Write(bone.InitialPosition); _writer.WriteInt32AsVarLenInt(bone.ParentIndex, BoneElementSize); _writer.Write(bone.Level); _writer.Write((ushort)bone.Flags); if (bone.HasFlag(BoneFlags.ToBone)) { _writer.WriteInt32AsVarLenInt(bone.To_Bone, BoneElementSize); } else { _writer.Write(bone.To_Offset); } if (bone.HasFlag(BoneFlags.AppendRotation) || bone.HasFlag(BoneFlags.AppendTranslation)) { _writer.WriteInt32AsVarLenInt(bone.AppendParentIndex, BoneElementSize); _writer.Write(bone.AppendRatio); } if (bone.HasFlag(BoneFlags.FixedAxis)) { _writer.Write(bone.Axis); } if (bone.HasFlag(BoneFlags.LocalFrame)) { var rotation = bone.InitialRotation; var mat = Matrix4.CreateFromQuaternion(rotation); var localX = mat.Row0.Xyz; var localZ = mat.Row2.Xyz; localX.Normalize(); localZ.Normalize(); _writer.Write(localX); _writer.Write(localZ); } if (bone.HasFlag(BoneFlags.ExternalParent)) { _writer.Write(bone.ExternalParentIndex); } if (bone.HasFlag(BoneFlags.IK) && bone.IK != null) { WritePmxIK(bone.IK); } } private void WritePmxIK([NotNull] PmxIK ik) { _writer.WriteInt32AsVarLenInt(ik.TargetBoneIndex, BoneElementSize); _writer.Write(ik.LoopCount); _writer.Write(ik.AngleLimit); if (ik.Links != null) { _writer.Write(ik.Links.Count); foreach (var link in ik.Links) { WriteIKLink(link); } } else { _writer.Write(0); } } private void WriteIKLink([NotNull] IKLink link) { _writer.WriteInt32AsVarLenInt(link.BoneIndex, BoneElementSize); _writer.Write(link.IsLimited); if (link.IsLimited) { _writer.Write(link.LowerBound); _writer.Write(link.UpperBound); } } private void WritePmxMorph([NotNull] PmxMorph morph) { WriteString(morph.Name); WriteString(morph.NameEnglish); _writer.Write((sbyte)morph.Panel); _writer.Write((byte)morph.OffsetKind); if (morph.Offsets != null) { _writer.Write(morph.Offsets.Count); foreach (var subm in morph.Offsets) { switch (subm) { case PmxGroupMorph m0: WritePmxGroupMorph(m0); break; case PmxVertexMorph m1: WritePmxVertexMorph(m1); break; case PmxBoneMorph m2: WritePmxBoneMorph(m2); break; case PmxUVMorph m3: WritePmxUVMorph(m3); break; case PmxMaterialMorph m4: WritePmxMaterialMorph(m4); break; case PmxImpulseMorph m5: WritePmxImpulseMorph(m5); break; default: throw new ArgumentOutOfRangeException(); } } } else { _writer.Write(0); } } private void WritePmxGroupMorph([NotNull] PmxGroupMorph morph) { _writer.WriteInt32AsVarLenInt(morph.Index, MorphElementSize); _writer.Write(morph.Ratio); } private void WritePmxVertexMorph([NotNull] PmxVertexMorph morph) { _writer.WriteInt32AsVarLenInt(morph.Index, MorphElementSize); _writer.Write(morph.Offset); } private void WritePmxBoneMorph([NotNull] PmxBoneMorph morph) { _writer.WriteInt32AsVarLenInt(morph.Index, MorphElementSize); _writer.Write(morph.Translation); _writer.Write(morph.Rotation); } private void WritePmxUVMorph([NotNull] PmxUVMorph morph) { _writer.WriteInt32AsVarLenInt(morph.Index, MorphElementSize); _writer.Write(morph.Offset); } private void WritePmxMaterialMorph([NotNull] PmxMaterialMorph morph) { _writer.WriteInt32AsVarLenInt(morph.Index, MorphElementSize); _writer.Write((byte)morph.Op); _writer.Write(morph.Diffuse); _writer.Write(morph.Specular); _writer.Write(morph.SpecularPower); _writer.Write(morph.Ambient); _writer.Write(morph.EdgeColor); _writer.Write(morph.EdgeSize); _writer.Write(morph.Texture); _writer.Write(morph.Sphere); _writer.Write(morph.Toon); } private void WritePmxImpulseMorph([NotNull] PmxImpulseMorph morph) { _writer.WriteInt32AsVarLenInt(morph.Index, MorphElementSize); _writer.Write(morph.IsLocal); _writer.Write(morph.Velocity); _writer.Write(morph.Torque); } private void WritePmxNode([NotNull] PmxNode node) { WriteString(node.Name); WriteString(node.NameEnglish); _writer.Write(node.IsSystemNode); if (node.Elements != null) { _writer.Write(node.Elements.Count); foreach (var element in node.Elements) { WriteNodeElement(element); } } else { _writer.Write(0); } } private void WriteNodeElement([NotNull] NodeElement element) { _writer.Write((byte)element.ElementType); switch (element.ElementType) { case ElementType.Bone: _writer.WriteInt32AsVarLenInt(element.Index, BoneElementSize); break; case ElementType.Morph: _writer.WriteInt32AsVarLenInt(element.Index, MorphElementSize); break; default: throw new ArgumentOutOfRangeException(); } } private void WritePmxRigidBody([NotNull] PmxRigidBody body) { WriteString(body.Name); WriteString(body.NameEnglish); _writer.WriteInt32AsVarLenInt(body.BoneIndex, BoneElementSize); _writer.Write((byte)body.GroupIndex); _writer.Write(body.PassGroup.ToFlagBits()); _writer.Write((byte)body.BoundingBoxKind); _writer.Write(body.BoundingBoxSize); _writer.Write(body.Position); _writer.Write(body.RotationAngles); _writer.Write(body.Mass); _writer.Write(body.PositionDamping); _writer.Write(body.RotationDamping); _writer.Write(body.Restitution); _writer.Write(body.Friction); _writer.Write((byte)body.KineticMode); } private void WritePmxJoint([NotNull] PmxJoint joint) { WriteString(joint.Name); WriteString(joint.NameEnglish); _writer.Write((byte)joint.Kind); _writer.WriteInt32AsVarLenInt(joint.BodyIndex1, RigidBodyElementSize); _writer.WriteInt32AsVarLenInt(joint.BodyIndex2, RigidBodyElementSize); _writer.Write(joint.Position); _writer.Write(joint.Rotation); _writer.Write(joint.LowerTranslationLimit); _writer.Write(joint.UpperTranslationLimit); _writer.Write(joint.LowerRotationLimit); _writer.Write(joint.UpperRotationLimit); _writer.Write(joint.TranslationSpringConstants); _writer.Write(joint.RotationSpringConstants); } private void WritePmxSoftBody([NotNull] PmxSoftBody body) { WriteString(body.Name); WriteString(body.NameEnglish); _writer.Write((byte)body.Shape); _writer.WriteInt32AsVarLenInt(body.MaterialIndex, MaterialElementSize); _writer.Write((byte)body.GroupIndex); _writer.Write(body.PassGroup.ToFlagBits()); _writer.Write((byte)body.Flags); _writer.Write(body.BendingLinkDistance); _writer.Write(body.ClusterCount); _writer.Write(body.TotalMass); _writer.Write(body.Margin); var config = body.Config; _writer.Write(config.AeroModel); _writer.Write(config.VCF); _writer.Write(config.DP); _writer.Write(config.DG); _writer.Write(config.LF); _writer.Write(config.PR); _writer.Write(config.VC); _writer.Write(config.DF); _writer.Write(config.MT); _writer.Write(config.CHR); _writer.Write(config.KHR); _writer.Write(config.SHR); _writer.Write(config.AHR); _writer.Write(config.SRHR_CL); _writer.Write(config.SKHR_CL); _writer.Write(config.SSHR_CL); _writer.Write(config.SR_SPLT_CL); _writer.Write(config.SK_SPLT_CL); _writer.Write(config.SS_SPLT_CL); _writer.Write(config.V_IT); _writer.Write(config.P_IT); _writer.Write(config.D_IT); _writer.Write(config.C_IT); var matCfg = body.MaterialConfig; _writer.Write(matCfg.LST); _writer.Write(matCfg.AST); _writer.Write(matCfg.VST); if (body.BodyAnchors != null) { _writer.Write(body.BodyAnchors.Count); foreach (var anchor in body.BodyAnchors) { WriteBodyAnchor(anchor); } } else { _writer.Write(0); } if (body.VertexPins != null) { _writer.Write(body.VertexPins.Count); foreach (var pin in body.VertexPins) { WriteVertexPin(pin); } } else { _writer.Write(0); } } private void WriteBodyAnchor([NotNull] BodyAnchor anchor) { _writer.WriteInt32AsVarLenInt(anchor.BodyIndex, RigidBodyElementSize); _writer.WriteInt32AsVarLenInt(anchor.VertexIndex, VertexElementSize, true); _writer.Write(anchor.IsNear); } private void WriteVertexPin([NotNull] VertexPin pin) { _writer.WriteInt32AsVarLenInt(pin.VertexIndex, VertexElementSize, true); } private void WriteHeader() { byte[] magicBytes; switch (MajorVersion) { case PmxFormatVersion.Version1: magicBytes = PmxSignatureV1; break; case PmxFormatVersion.Version2: magicBytes = PmxSignatureV2; break; default: throw new ArgumentOutOfRangeException(); } _writer.Write(magicBytes); _writer.Write(DetailedVersion); } private void WriteElementFormats() { byte[] elementSizes; byte elementSizeEntryCount; switch (MajorVersion) { case PmxFormatVersion.Version1: elementSizeEntryCount = 5; elementSizes = new byte[elementSizeEntryCount]; elementSizes[0] = (byte)VertexElementSize; elementSizes[1] = (byte)BoneElementSize; elementSizes[2] = (byte)MorphElementSize; elementSizes[3] = (byte)MaterialElementSize; elementSizes[4] = (byte)RigidBodyElementSize; break; case PmxFormatVersion.Version2: elementSizeEntryCount = 8; elementSizes = new byte[elementSizeEntryCount]; elementSizes[0] = (byte)StringEncoding; elementSizes[1] = (byte)UvaCount; elementSizes[2] = (byte)VertexElementSize; elementSizes[3] = (byte)TexElementSize; elementSizes[4] = (byte)MaterialElementSize; elementSizes[5] = (byte)BoneElementSize; elementSizes[6] = (byte)MorphElementSize; elementSizes[7] = (byte)RigidBodyElementSize; break; default: throw new ArgumentOutOfRangeException(); } _writer.Write(elementSizeEntryCount); _writer.Write(elementSizes); } private void WriteString([CanBeNull] string str) { if (string.IsNullOrEmpty(str)) { _writer.Write(0); return; } Encoding enc; switch (MajorVersion) { case PmxFormatVersion.Version1: enc = Utf8NoBom; break; case PmxFormatVersion.Version2: switch (StringEncoding) { case PmxStringEncoding.Utf16: enc = Utf16NoBom; break; case PmxStringEncoding.Utf8: enc = Utf8NoBom; break; default: throw new ArgumentOutOfRangeException(); } break; default: throw new ArgumentOutOfRangeException(); } var bytes = enc.GetBytes(str); _writer.Write(bytes.Length); _writer.Write(bytes); } private void BuildTextureNameMap([NotNull] PmxModel model) { var materials = model.Materials; if (materials == null) { return; } var nameList = new List<string>(); foreach (var material in materials) { if (!string.IsNullOrEmpty(material.TextureFileName)) { nameList.Add(material.TextureFileName); } if (!string.IsNullOrEmpty(material.SphereTextureFileName)) { nameList.Add(material.SphereTextureFileName); } if (!string.IsNullOrEmpty(material.ToonTextureFileName) && !ToonNameRegex.IsMatch(material.ToonTextureFileName)) { nameList.Add(material.ToonTextureFileName); } } _textureNameList.AddRange(nameList.Distinct()); } [MethodImpl(MethodImplOptions.AggressiveInlining)] private int GetTextureIndex([NotNull] string s) { return _textureNameList.IndexOf(s); } private enum PmxFormatVersion { Unknown = 0, Version1 = 1, Version2 = 2 } private enum PmxStringEncoding { Utf16 = 0, Utf8 = 1 } private static readonly byte[] PmxSignatureV1 = { 0x50, 0x6d, 0x78, 0x20 }; // "Pmx " private static readonly byte[] PmxSignatureV2 = { 0x50, 0x4d, 0x58, 0x20 }; // "PMX " private static readonly Encoding Utf16NoBom = new UnicodeEncoding(false, false); private static readonly Encoding Utf8NoBom = new UTF8Encoding(false); private static readonly Regex ToonNameRegex = new Regex(@"^toon(?<toonIndex>\d+)\.bmp$"); private BinaryWriter _writer; private readonly List<string> _textureNameList = new List<string>(); } }
34.767196
130
0.526784
[ "BSD-3-Clause-Clear" ]
CptCipher/MLTDTools
src/MillionDance/Core/PmxWriter.cs
26,286
C#
using System; using Legacy.Core.Api; using Legacy.Core.EventManagement; using Legacy.Views; using UnityEngine; using Object = System.Object; namespace Legacy { [AddComponentMenu("MM Legacy/Views/Scene/SceneEventView_TwoObjects")] public class SceneEventView_TwoObjects : BaseView { [SerializeField] private String m_viewListenCommandName; [SerializeField] private GameObject m_passiveObject; [SerializeField] private GameObject m_activeObject; protected override void Awake() { } private void Start() { LegacyLogic.Instance.EventManager.RegisterEvent(EEventType.PREFAB_CONTAINER_TRIGGER_ANIM, new EventHandler(OnAnimTriggered)); SetActiveRecursively(m_passiveObject, true); SetActiveRecursively(m_activeObject, false); } private void OnAnimTriggered(Object p_sender, EventArgs p_args) { StringEventArgs stringEventArgs = p_args as StringEventArgs; if (stringEventArgs != null && p_sender == null) { String[] array = stringEventArgs.text.Split(new Char[] { '_' }); if (array.Length > 1 && array[0] == m_viewListenCommandName && array[1] == "Activate") { SetActiveRecursively(m_passiveObject, false); SetActiveRecursively(m_activeObject, true); } else if (array.Length > 1 && array[0] == m_viewListenCommandName && array[1] == "Deactivate") { SetActiveRecursively(m_passiveObject, true); SetActiveRecursively(m_activeObject, false); } } } private void SetActiveRecursively(GameObject obj, Boolean state) { if (obj != null) { obj.SetActive(state); } } protected override void OnDestroy() { base.OnDestroy(); LegacyLogic.Instance.EventManager.UnregisterEvent(EEventType.PREFAB_CONTAINER_TRIGGER_ANIM, new EventHandler(OnAnimTriggered)); } } }
25.642857
130
0.727577
[ "MIT" ]
Albeoris/MMXLegacy
Legacy.Framework/Legacy/SceneEventView_TwoObjects.cs
1,797
C#
using System.Collections; using System.Diagnostics.CodeAnalysis; using System.Text; using System.Text.RegularExpressions; namespace Dgt.Nonograms.Engine; public sealed class Line : IEnumerable<CellState>, IEquatable<Line> { private static readonly Regex ParseRegex = new(BuildParsePattern()); private static string BuildParsePattern() { var characters = string.Create(CellState.All.Count, CellState.All, (span, state) => { for (var i = 0; i < span.Length; i++) { span[i] = state[i]; } }); return $@"^[{characters}]+$"; } private readonly CellState[] _cellStates; public static readonly Line Empty = new(Array.Empty<CellState>()); public Line(IEnumerable<CellState> cellStates) { if(cellStates is null) throw new ArgumentNullException(nameof(cellStates)); _cellStates = cellStates.ToArray(); } public static bool TryParse(string s, [NotNullWhen(true)] out Line? result) { var canParse = s is not null && IsValidLineString(s); result = canParse ? DoParse(s!) : null; return result is not null; } public static Line Parse(string s) { if (s is null) throw new ArgumentNullException(nameof(s)); if (!IsValidLineString(s)) throw CreateInvalidLineStringException(s); return DoParse(s); } private static bool IsValidLineString(string s) => ParseRegex.IsMatch(s); private static Exception CreateInvalidLineStringException(string s) { var messageBuilder = new StringBuilder("The input string was not in a correct format."); messageBuilder.Append(" Lines can only consist of"); for(var i = 0; i < CellState.All.Count; i++) { var isLastItem = i == CellState.All.Count - 1; var cellState = CellState.All[i]; if (isLastItem) { messageBuilder.Append(" or"); } messageBuilder.Append($" '{cellState.Character}' ({cellState.Description})"); messageBuilder.Append(isLastItem ? '.' : ','); } messageBuilder.Append($" Actual value was '{s}'."); throw new FormatException(messageBuilder.ToString()) { Data = { { "s", s } } }; } private static Line DoParse(string s) => new(s.Select(c => (CellState)c)); public static implicit operator string(Line l) { if (l is null) { return string.Empty; } return string.Create(l.Length, l, (span, state) => { for (var i = 0; i < state.Length; i++) { span[i] = state[i]; } }); } public static implicit operator bool?[](Line l) { if(l is null) { return Array.Empty<bool?>(); } var values = new bool?[l.Length]; for (var i = 0; i < values.Length; i++) { values[i] = l[i]; } return values; } public static implicit operator Line(bool?[] b) { if(b is null) { return Empty; } var cellStates = b.Select(x => (CellState)x); return new(cellStates); } public int Length => _cellStates.Length; public CellState this[int index] { get { if(index < 0 || index >= Length) { throw new ArgumentOutOfRangeException(nameof(index), index, $"Index was out of range. Must be non-negative and less than the length of the line ({Length})."); } return _cellStates[index]; } } public bool Equals(Line? other) { if(other is null) { return false; } else if(ReferenceEquals(this, other)) { return true; } else if(other.Length != Length) { return false; } // We could cast both to string and compare those, but this avoids the allocations that would occur with that implementation for(var i = 0; i < Length; i++) { if(this[i] != other[i]) { return false; } } return true; } public override bool Equals(object? obj) { if(obj is null) { return false; } else if(obj is Line l) { return Equals(l); } else { return false; } } public override int GetHashCode() => ((string)this).GetHashCode(); IEnumerator<CellState> IEnumerable<CellState>.GetEnumerator() { return _cellStates.AsEnumerable().GetEnumerator(); } IEnumerator IEnumerable.GetEnumerator() { return _cellStates.GetEnumerator(); } }
24.465
174
0.540773
[ "MIT" ]
mmmcaffeine/nonograms
src/Engine/Line.cs
4,895
C#
using System; using System.Collections; using Harmony; using MelonLoader; using UnityEngine; namespace AudicaModding { public class AudicaMod : MelonMod { public static class BuildInfo { public const string Name = "ScorePercentage"; // Name of the Mod. (MUST BE SET) public const string Author = "Alternity"; // Author of the Mod. (Set as null if none) public const string Company = null; // Company that made the Mod. (Set as null if none) public const string Version = "1.1.1"; // Version of the Mod. (MUST BE SET) public const string DownloadLink = null; // Download Link for the Mod. (Set as null if none) } public static MenuState.State menuState; public static MenuState.State oldMenuState; public static StarThresholds starThresholds; public static string selectedSong; public static int ostMaxTotalScore = 0; public static int extrasMaxTotalScore = 0; public static string leaderboardUserColor = "yellow"; public static string leaderboardHighScoreSize = "225"; public static string leaderboardPercentSize = "150"; public static string leaderboardUsernameSize = "225"; public static string songListHighScoreSize = "26"; public static string songListPercentSize = "17"; public static string inGameCurrentScoreSize = "120"; public static string inGameCurrentPercentSize = "75"; public static string inGameHighScoreLabelText = "HIGH SCORE: "; public static string inGameHighScoreLabelSize = "55"; public static string inGameHighScoreSize = "55"; public static string inGamePercentSize = "40"; public static string historyTopScoreSize = "20"; public static string historyTopPercentSize = "14"; public override void OnApplicationStart() { HarmonyInstance instance = HarmonyInstance.Create("AudicaMod"); } private void SaveConfig() { MelonPrefs.SetString("ScorePercentage", "leaderboardUserColor", leaderboardUserColor); MelonPrefs.SetString("ScorePercentage", "leaderboardHighScoreSize", leaderboardHighScoreSize); MelonPrefs.SetString("ScorePercentage", "leaderboardPercentSize", leaderboardPercentSize); MelonPrefs.SetString("ScorePercentage", "leaderboardUsernameSize", leaderboardUsernameSize); MelonPrefs.SetString("ScorePercentage", "songListHighScoreSize", songListHighScoreSize); MelonPrefs.SetString("ScorePercentage", "songListPercentSize", songListPercentSize); MelonPrefs.SetString("ScorePercentage", "inGameCurrentScoreSize", inGameCurrentScoreSize); MelonPrefs.SetString("ScorePercentage", "inGameCurrentPercentSize", inGameCurrentPercentSize); MelonPrefs.SetString("ScorePercentage", "inGameHighScoreLabelText", inGameHighScoreLabelText); MelonPrefs.SetString("ScorePercentage", "inGameHighScoreLabelSize", inGameHighScoreLabelSize); MelonPrefs.SetString("ScorePercentage", "inGameHighScoreSize", inGameHighScoreSize); MelonPrefs.SetString("ScorePercentage", "inGamePercentSize", inGamePercentSize); MelonPrefs.SetString("ScorePercentage", "historyTopScoreSize", historyTopScoreSize); MelonPrefs.SetString("ScorePercentage", "historyTopPercentSize", historyTopPercentSize); } private void LoadConfig() { leaderboardUserColor = MelonPrefs.GetString("ScorePercentage", "leaderboardUserColor"); leaderboardHighScoreSize = MelonPrefs.GetString("ScorePercentage", "leaderboardHighScoreSize"); leaderboardPercentSize = MelonPrefs.GetString("ScorePercentage", "leaderboardPercentSize"); leaderboardUsernameSize = MelonPrefs.GetString("ScorePercentage", "leaderboardUsernameSize"); songListHighScoreSize = MelonPrefs.GetString("ScorePercentage", "songListHighScoreSize"); songListPercentSize = MelonPrefs.GetString("ScorePercentage", "songListPercentSize"); inGameCurrentScoreSize = MelonPrefs.GetString("ScorePercentage", "inGameCurrentScoreSize"); inGameCurrentPercentSize = MelonPrefs.GetString("ScorePercentage", "inGameCurrentPercentSize"); inGameHighScoreLabelText = MelonPrefs.GetString("ScorePercentage", "inGameHighScoreLabelText"); inGameHighScoreLabelSize = MelonPrefs.GetString("ScorePercentage", "inGameHighScoreLabelSize"); inGameHighScoreSize = MelonPrefs.GetString("ScorePercentage", "inGameHighScoreSize"); inGamePercentSize = MelonPrefs.GetString("ScorePercentage", "inGamePercentSize"); historyTopScoreSize = MelonPrefs.GetString("ScorePercentage", "historyTopScoreSize"); historyTopPercentSize = MelonPrefs.GetString("ScorePercentage", "historyTopPercentSize"); } private void CreateConfig() { MelonPrefs.RegisterString("ScorePercentage", "leaderboardUserColor", "yellow"); MelonPrefs.RegisterString("ScorePercentage", "leaderboardHighScoreSize", "225"); MelonPrefs.RegisterString("ScorePercentage", "leaderboardPercentSize", "150"); MelonPrefs.RegisterString("ScorePercentage", "leaderboardUsernameSize", "225"); MelonPrefs.RegisterString("ScorePercentage", "songListHighScoreSize", "26"); MelonPrefs.RegisterString("ScorePercentage", "songListPercentSize", "17"); MelonPrefs.RegisterString("ScorePercentage", "inGameCurrentScoreSize", "120"); MelonPrefs.RegisterString("ScorePercentage", "inGameCurrentPercentSize", "75"); MelonPrefs.RegisterString("ScorePercentage", "inGameHighScoreLabelText", "HIGH SCORE: "); MelonPrefs.RegisterString("ScorePercentage", "inGameHighScoreLabelSize", "55"); MelonPrefs.RegisterString("ScorePercentage", "inGameHighScoreSize", "55"); MelonPrefs.RegisterString("ScorePercentage", "inGamePercentSize", "40"); MelonPrefs.RegisterString("ScorePercentage", "historyTopScoreSize", "20"); MelonPrefs.RegisterString("ScorePercentage", "historyTopPercentSize", "14"); } public override void OnLevelWasLoaded(int level) { if (!MelonPrefs.HasKey("ScorePercentage", "leaderboardUserColor")) { CreateConfig(); } else { LoadConfig(); } } public static float GetHighScorePercentage(string songID) { //Get the needed data HighScoreRecords.HighScoreInfo highScoreInfo = HighScoreRecords.GetHighScore(songID); float highScore = Convert.ToSingle(highScoreInfo.score); float maxPossibleScore = Convert.ToSingle(starThresholds.GetMaxRawScore(songID, highScoreInfo.difficulty)); //Calculate score percentage float percentage = (highScore / maxPossibleScore) * 100; return percentage; } //This returns the percentage of the specified score for the specified song and difficulty compared to the max possible score public static float GetScorePercentage(string songID, float score, KataConfig.Difficulty difficulty) { //Get data float maxPossibleScore = Convert.ToSingle(starThresholds.GetMaxRawScore(songID, difficulty)); //Calculate score percentage float percentage = (score / maxPossibleScore) * 100; return percentage; } //This is a function for the coroutine public static IEnumerator UpdateLeaderboardRowCoroutine(LeaderboardRow leaderboardRow) { UpdateLeaderboardRow(leaderboardRow); return null; } //The process to update a LeaderboardRow public static void UpdateLeaderboardRow(LeaderboardRow leaderboardRow) { //DoWork function is really intensive so it's called only when absolutely required //This function will calculate the total max possible score for either OST or with extras void DoWork(bool e) { Il2CppSystem.Collections.Generic.List<SongList.SongData> songs = SongList.I.songs; int totalMaxScore = 0; for (int i = 0; i < songs.Count; i++) { SongList.SongData song = songs[i]; if (e) { if (song.dlc | song.unlockable) { totalMaxScore += starThresholds.GetMaxRawScore(song.songID, KataConfig.Difficulty.Expert); } } if (song.dlc == false && song.unlockable == false && song.extrasSong == false) { totalMaxScore += starThresholds.GetMaxRawScore(song.songID, KataConfig.Difficulty.Expert); } } if (e) { extrasMaxTotalScore = totalMaxScore; } else { ostMaxTotalScore = totalMaxScore; } } float score = Convert.ToSingle(leaderboardRow.mData.score.Split('.')[0]); float percentage; if (menuState != MenuState.State.MainPage) { percentage = GetScorePercentage(selectedSong, score, KataConfig.Difficulty.Expert); } else { LeaderboardDisplay leaderboardDisplay = UnityEngine.Object.FindObjectOfType<LeaderboardDisplay>(); bool extras = leaderboardDisplay.extrasButton.IsChecked.Invoke(); DoWork(extras); if (extras) { if (extrasMaxTotalScore == 0) { DoWork(extras); } percentage = (score / extrasMaxTotalScore) * 100; } else { if (ostMaxTotalScore == 0) { DoWork(extras); } percentage = (score / ostMaxTotalScore) * 100; } } //Make pretty-ish strings leaderboardRow.username.text = "<size=" + leaderboardUsernameSize + ">" + leaderboardRow.username.text + "</size>"; string scoreString = "<size=" + leaderboardHighScoreSize + ">" + String.Format("{0:n0}", score).Replace(",", " ") + "</size>"; string percentageString = "<size=" + leaderboardPercentSize + "> (" + String.Format("{0:0.00}", percentage) + "%)</size>"; //Update label if (leaderboardRow.score.text.Contains("<color=yellow>")) { leaderboardRow.score.text = "<color=" + leaderboardUserColor + ">" + scoreString + percentageString + "</color>"; } else { leaderboardRow.score.text = scoreString + percentageString; } if (leaderboardRow.rank.text.Contains("<color=yellow>")) { leaderboardRow.rank.text = leaderboardRow.rank.text.Replace("<color=yellow>", "<color=" + leaderboardUserColor + ">"); } if (leaderboardRow.username.text.Contains("<color=yellow>")) { leaderboardRow.username.text = leaderboardRow.username.text.Replace("<color=yellow>", "<color=" + leaderboardUserColor + ">"); } } public static void ScoreKeeperDisplayUpdate(ScoreKeeperDisplay scoreKeeperDisplay) { if (!KataConfig.I.practiceMode) { int score = ScoreKeeper.I.mScore; float percentage = GetScorePercentage(selectedSong, score, KataConfig.I.GetDifficulty()); //Make pretty-ish strings string scoreString = "<size=" + inGameCurrentScoreSize + ">" + String.Format("{0:n0}", score).Replace(",", " ") + "</size>"; string percentageString = "<size=" + inGameCurrentPercentSize + "> (" + String.Format("{0:0.00}", percentage) + "%)</size>"; scoreKeeperDisplay.scoreDisplay.text = scoreString + percentageString; HighScoreRecords.HighScoreInfo highScoreInfo = HighScoreRecords.GetHighScore(selectedSong); float highScore = Convert.ToSingle(highScoreInfo.score); float highScorePercentage = GetHighScorePercentage(selectedSong); string highScoreString = "<size=" + inGameHighScoreSize + ">" + String.Format("{0:n0}", highScore).Replace(",", " ") + "</size>"; string highScorePercentageString = "<size=" + inGamePercentSize + "> (" + String.Format("{0:0.00}", highScorePercentage) + "%)</size>"; scoreKeeperDisplay.highScoreDisplay.text = "<size=" + inGameHighScoreLabelSize + ">" + inGameHighScoreLabelText + "</size>" + highScoreString + highScorePercentageString; } } public static void SetData(LeaderboardRow leaderboardRow) { UpdateLeaderboardRow(leaderboardRow); //MelonCoroutines.Start(UpdateLeaderboardRowCoroutine(leaderboardRow)); } //Tracking the play history SetTopScore function public static void SetTopScore(SongInfoTopScoreItem item) { SongInfoTopScoreItem topScoreItem = item; //Get percentage float percentage = GetHighScorePercentage(selectedSong); //Make pretty-ish strings string scoreString = "<size=" + historyTopScoreSize + ">" + String.Format("{0:n0}", HighScoreRecords.GetHighScore(selectedSong).score).Replace(",", " ") + "</size>"; string percentageString = "<size=" + historyTopPercentSize + "> (" + String.Format("{0:0.00}", percentage) + "%)</size>"; //Update label topScoreItem.score.text = scoreString + percentageString; } //Tracking the song's buttons score display update function public static void UpdateScoreDisplays(SongSelectItem item, int score) { //If the score is zero we don't do anything if (score != 0) { SongSelectItem button = item; //Get percentage float percentage = GetHighScorePercentage(button.GetSongData().songID); //Make pretty-ish strings string scoreString = "<size=" + songListHighScoreSize + ">" + String.Format("{0:n0}", score).Replace(",", " ") + "</size>"; string percentageString = "<size=" + songListPercentSize + "> (" + String.Format("{0:0.00}", percentage) + "%)</size>"; //Update button button.highScoreLabel.text = scoreString + percentageString; } } //Tracking selected song public static void OnSelect(SongSelectItem ssi) { SongSelectItem button = ssi; string songID = button.mSongData.songID; selectedSong = songID; MelonLogger.Log(songID); } public override void OnUpdate() { //Tracking menu state menuState = MenuState.GetState(); //If menu changes if (menuState != oldMenuState) { //Updating state oldMenuState = menuState; //Put stuff to do when a menu change triggers here //Doing this in an effort to call this the less often possible. //It doesn't work at boot so going it at a menu change is reasonable I guess starThresholds = UnityEngine.Object.FindObjectOfType<StarThresholds>(); } } } }
49.646302
193
0.63737
[ "MIT" ]
Alternity156/AudicaScorePercentage
src/Main.cs
15,440
C#
using System; using System.Collections.Generic; using System.Linq; using Microsoft.Extensions.Logging; using NBitcoin; using Blockcore.Interfaces; using Blockcore.Networks; using Blockcore.Consensus.Chain; using Blockcore.Consensus.BlockInfo; using Blockcore.Consensus.TransactionInfo; namespace Blockcore.Features.BlockStore { public interface IUtxoIndexer { ReconstructedCoinviewContext GetCoinviewAtHeight(int blockHeight); } /// <summary> /// This is a separate use case from the address indexer, as we need full details about the current items in the UTXO set in order to /// be able to potentially build transactions from them. The address indexer is also intended for long-running use cases, and does /// incur overhead in processing each block. This indexer, conversely, is designed for occasional usage without the requirement /// of persisting its output for rapid lookup. /// The actual coindb is not well suited to this kind of query either, as it is being accessed frequently and lacks a 'snapshot' /// facility. This indexer therefore trades query speed for implementation simplicity, as we only have to enumerate the entire chain /// without regard for significantly impacting other components. /// Allowing the height to be specified is an additional convenience that the coindb on its own would not give us without additional /// consistency safeguards, which may be invasive. For example, halting consensus at a specific height to build a snapshot. /// </summary> /// <remarks>This borrows heavily from the <see cref="Stratis.Bitcoin.Features.SmartContracts.ReflectionExecutor.Controllers.BalancesController"/>, but is less specialised.</remarks> public class UtxoIndexer : IUtxoIndexer { private readonly Network network; private readonly ChainIndexer chainIndexer; private readonly IBlockStore blockStore; private readonly ILogger logger; public UtxoIndexer(Network network, ChainIndexer chainIndexer, IBlockStore blockStore, ILoggerFactory loggerFactory) { this.network = network; this.chainIndexer = chainIndexer; this.blockStore = blockStore; this.logger = loggerFactory.CreateLogger(this.GetType().FullName); } public ReconstructedCoinviewContext GetCoinviewAtHeight(int blockHeight) { var coinView = new ReconstructedCoinviewContext(); // TODO: Make this a command line option const int batchSize = 1000; IEnumerable<ChainedHeader> allBlockHeaders = this.chainIndexer.EnumerateToTip(this.chainIndexer.Genesis); int totalBlocksCounted = 0; int i = 0; while (true) { List<ChainedHeader> headers = allBlockHeaders.Skip(i * batchSize).Take(batchSize).ToList(); List<Block> blocks = this.blockStore.GetBlocks(headers.Select(x => x.HashBlock).ToList()); foreach (Block block in blocks) { this.AdjustCoinviewForBlock(block, coinView); totalBlocksCounted += 1; // We have reached the block height asked for. if (totalBlocksCounted >= blockHeight) break; } // We have seen every block up to the tip or the chosen block height. if (headers.Count < batchSize || totalBlocksCounted >= blockHeight) break; // Give the user some feedback every 10k blocks if (i % 10 == 9) this.logger.LogInformation($"Processed {totalBlocksCounted} blocks for UTXO indexing."); i++; } return coinView; } private void AdjustCoinviewForBlock(Block block, ReconstructedCoinviewContext coinView) { foreach (Transaction tx in block.Transactions) { // Add outputs for (int i = 0; i < tx.Outputs.Count; i++) { TxOut output = tx.Outputs[i]; if (output.Value <= 0 || output.ScriptPubKey.IsUnspendable) continue; coinView.UnspentOutputs.Add(new OutPoint(tx, i)); coinView.Transactions[tx.GetHash()] = tx; } // Spend inputs. Coinbases are special in that they don't reference previous transactions for their inputs, so ignore them. if (tx.IsCoinBase) continue; foreach (TxIn txIn in tx.Inputs) { // TODO: This is inefficient because the Transactions dictionary entry does not get deleted, so extra memory gets used if (!coinView.UnspentOutputs.Remove(txIn.PrevOut)) { throw new Exception("Attempted to spend a prevOut that isn't in the coinview at this time."); } } } } } }
43.210084
186
0.623493
[ "MIT" ]
Botcoin-Abacus/blockcore
src/Features/Blockcore.Features.BlockStore/UtxoIndexing/UtxoIndexer.cs
5,144
C#
using System.Text.Json; namespace DotNetRuntime; public class RuntimeResponse { public string Data { get; set; } public int StatusCode { get; set; } public RuntimeResponse( string data = "", int statusCode = 200) { Data = data; StatusCode = statusCode; } public RuntimeResponse Send( string data, int statusCode = 200) { Data = data; StatusCode = statusCode; return this; } public RuntimeResponse Json( Dictionary<string, object?> data, int statusCode = 200) { Data = JsonSerializer.Serialize(data); StatusCode = statusCode; return this; } }
18.552632
46
0.575887
[ "MIT" ]
open-runtimes/runtimes
runtimes/dotnet-6.0/src/RuntimeResponse.cs
705
C#
#if THUNDERKIT_CONFIGURED using global::RoR2; namespace PassivePicasso.ThunderKit.Proxy.RoR2 { public partial class TeleportOutController : global::RoR2.TeleportOutController {} } #endif
27.142857
86
0.815789
[ "MIT" ]
Jarlyk/Rain-of-Stages
Assets/RainOfStages/RoR2/GeneratedProxies/RoR2/TeleportOutController.cs
190
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Hout.Models.ParamValidation { public class InvalidParameterException : Exception { public InvalidParameterException(string message) : base(message) { } } }
21.714286
76
0.753289
[ "MIT" ]
Inrego/Hout
Hout.Models/ParamValidation/InvalidParameterException.cs
306
C#
using System; using System.Data; using System.Net; using System.Text; using System.Web.UI.WebControls; using CMS.Base; using CMS.Base.Web.UI; using CMS.EventLog; using CMS.Helpers; using CMS.PortalEngine.Web.UI; public partial class CMSWebParts_WebServices_GridForRESTService : CMSAbstractWebPart { #region "Properties" /// <summary> /// Gets or sets the URL for querying REST Service. /// </summary> public string RESTServiceQueryURL { get { return UrlResolver.ResolveUrl(ValidationHelper.GetString(GetValue("RESTServiceQueryURL"), "")); } set { SetValue("RESTServiceQueryURL", value); } } /// <summary> /// Gets or sets the user name. /// </summary> public string UserName { get { return ValidationHelper.GetString(GetValue("UserName"), ""); } set { SetValue("UserName", value); } } /// <summary> /// Gets or sets the user password. /// </summary> public string Password { get { return ValidationHelper.GetString(GetValue("Password"), ""); } set { SetValue("Password", value); } } #endregion /// <summary> /// Content loaded event handler. /// </summary> public override void OnContentLoaded() { base.OnContentLoaded(); SetupControl(); } /// <summary> /// Initializes the control properties. /// </summary> protected void SetupControl() { if (StopProcessing) { basicDataGrid.Visible = false; } else { ReloadData(); } } /// <summary> /// Reload control's data. /// </summary> public override void ReloadData() { base.ReloadData(); if (!string.IsNullOrEmpty(RESTServiceQueryURL)) { try { HttpWebRequest request = CreateWebRequest(); HttpWebResponse response = (HttpWebResponse)request.GetResponse(); // If everything went ok, parse the xml recieved to dataset and bind it to the grid if (response.StatusCode == HttpStatusCode.OK) { DataSet ds = new DataSet(); ds.ReadXml(response.GetResponseStream()); basicDataGrid.DataSource = ds; basicDataGrid.DataBind(); basicDataGrid.ItemDataBound += new DataGridItemEventHandler(basicDataGrid_ItemDataBound); } } catch (Exception ex) { // Handle the error EventLogProvider.LogException("GridForRESTService", "GETDATA", ex); lblError.Text = ResHelper.GetStringFormat("RESTService.RequestFailed", ex.Message); lblError.Visible = true; } } } protected void basicDataGrid_ItemDataBound(object sender, DataGridItemEventArgs e) { // Encode content of the cells foreach (TableCell item in e.Item.Cells) { item.Text = HTMLHelper.HTMLEncode(item.Text); } } /// <summary> /// Creates the WebRequest for querying the REST service. /// </summary> private HttpWebRequest CreateWebRequest() { string url = RESTServiceQueryURL; if (url.StartsWithCSafe("/")) { url = URLHelper.GetAbsoluteUrl(url); } HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url); request.Method = "GET"; request.ContentLength = 0; request.ContentType = "text/xml"; // Set credentials for basic authentication if (!string.IsNullOrEmpty(UserName)) { // Set the authorization header for basic authentication request.Headers["Authorization"] = "Basic " + Convert.ToBase64String(ASCIIEncoding.ASCII.GetBytes(UserName + ":" + Password)); } return request; } }
26.182927
139
0.5347
[ "MIT" ]
CMeeg/kentico-contrib
src/CMS/CMSWebParts/WebServices/GridForRESTService.ascx.cs
4,296
C#
/* * Copyright 2010-2014 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ /* * Do not modify this file. This file is generated from the robomaker-2018-06-29.normal.json service model. */ using System; using System.Collections.Generic; using System.Xml.Serialization; using System.Text; using System.IO; using Amazon.Runtime; using Amazon.Runtime.Internal; namespace Amazon.RoboMaker.Model { /// <summary> /// Container for the parameters to the CreateRobot operation. /// Creates a robot. /// </summary> public partial class CreateRobotRequest : AmazonRoboMakerRequest { private Architecture _architecture; private string _greengrassGroupId; private string _name; private Dictionary<string, string> _tags = new Dictionary<string, string>(); /// <summary> /// Gets and sets the property Architecture. /// <para> /// The target architecture of the robot. /// </para> /// </summary> [AWSProperty(Required=true)] public Architecture Architecture { get { return this._architecture; } set { this._architecture = value; } } // Check to see if Architecture property is set internal bool IsSetArchitecture() { return this._architecture != null; } /// <summary> /// Gets and sets the property GreengrassGroupId. /// <para> /// The Greengrass group id. /// </para> /// </summary> [AWSProperty(Required=true, Min=1, Max=1224)] public string GreengrassGroupId { get { return this._greengrassGroupId; } set { this._greengrassGroupId = value; } } // Check to see if GreengrassGroupId property is set internal bool IsSetGreengrassGroupId() { return this._greengrassGroupId != null; } /// <summary> /// Gets and sets the property Name. /// <para> /// The name for the robot. /// </para> /// </summary> [AWSProperty(Required=true, Min=1, Max=255)] public string Name { get { return this._name; } set { this._name = value; } } // Check to see if Name property is set internal bool IsSetName() { return this._name != null; } /// <summary> /// Gets and sets the property Tags. /// <para> /// A map that contains tag keys and tag values that are attached to the robot. /// </para> /// </summary> [AWSProperty(Min=0, Max=50)] public Dictionary<string, string> Tags { get { return this._tags; } set { this._tags = value; } } // Check to see if Tags property is set internal bool IsSetTags() { return this._tags != null && this._tags.Count > 0; } } }
29.745763
107
0.58433
[ "Apache-2.0" ]
FoxBearBear/aws-sdk-net
sdk/src/Services/RoboMaker/Generated/Model/CreateRobotRequest.cs
3,510
C#
namespace Contoso.Domain.Tokens { using More.Domain.Commands; using System; public class ReserveToken : Command { public ReserveToken( Guid aggregateId, string billingAccountId, string catalogId ) { AggregateId = aggregateId; BillingAccountId = billingAccountId; CatalogId = catalogId; } public string BillingAccountId { get; } public string CatalogId { get; } } }
24.421053
90
0.622845
[ "MIT" ]
commonsensesoftware/More.Cqrs
samples/tokens/src/Contoso.Tokens.Domain/Tokens/ReserveToken.cs
466
C#
// <auto-generated /> using System; using InstaAutoBot.EntityFrameworkCore; using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Infrastructure; using Microsoft.EntityFrameworkCore.Metadata; using Microsoft.EntityFrameworkCore.Migrations; using Microsoft.EntityFrameworkCore.Storage.ValueConversion; namespace InstaAutoBot.Migrations { [DbContext(typeof(InstaAutoBotDbContext))] [Migration("20190208051931_Upgrade_ABP_4_2_0")] partial class Upgrade_ABP_4_2_0 { protected override void BuildTargetModel(ModelBuilder modelBuilder) { #pragma warning disable 612, 618 modelBuilder .HasAnnotation("ProductVersion", "2.2.1-servicing-10028") .HasAnnotation("Relational:MaxIdentifierLength", 128) .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); modelBuilder.Entity("Abp.Application.Editions.Edition", b => { b.Property<int>("Id") .ValueGeneratedOnAdd() .HasColumnType("int") .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); b.Property<DateTime>("CreationTime") .HasColumnType("datetime2"); b.Property<long?>("CreatorUserId") .HasColumnType("bigint"); b.Property<long?>("DeleterUserId") .HasColumnType("bigint"); b.Property<DateTime?>("DeletionTime") .HasColumnType("datetime2"); b.Property<string>("DisplayName") .IsRequired() .HasColumnType("nvarchar(64)") .HasMaxLength(64); b.Property<bool>("IsDeleted") .HasColumnType("bit"); b.Property<DateTime?>("LastModificationTime") .HasColumnType("datetime2"); b.Property<long?>("LastModifierUserId") .HasColumnType("bigint"); b.Property<string>("Name") .IsRequired() .HasColumnType("nvarchar(32)") .HasMaxLength(32); b.HasKey("Id"); b.ToTable("AbpEditions"); }); modelBuilder.Entity("Abp.Application.Features.FeatureSetting", b => { b.Property<long>("Id") .ValueGeneratedOnAdd() .HasColumnType("bigint") .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); b.Property<DateTime>("CreationTime") .HasColumnType("datetime2"); b.Property<long?>("CreatorUserId") .HasColumnType("bigint"); b.Property<string>("Discriminator") .IsRequired() .HasColumnType("nvarchar(max)"); b.Property<string>("Name") .IsRequired() .HasColumnType("nvarchar(128)") .HasMaxLength(128); b.Property<int?>("TenantId") .HasColumnType("int"); b.Property<string>("Value") .IsRequired() .HasColumnType("nvarchar(2000)") .HasMaxLength(2000); b.HasKey("Id"); b.ToTable("AbpFeatures"); b.HasDiscriminator<string>("Discriminator").HasValue("FeatureSetting"); }); modelBuilder.Entity("Abp.Auditing.AuditLog", b => { b.Property<long>("Id") .ValueGeneratedOnAdd() .HasColumnType("bigint") .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); b.Property<string>("BrowserInfo") .HasColumnType("nvarchar(512)") .HasMaxLength(512); b.Property<string>("ClientIpAddress") .HasColumnType("nvarchar(64)") .HasMaxLength(64); b.Property<string>("ClientName") .HasColumnType("nvarchar(128)") .HasMaxLength(128); b.Property<string>("CustomData") .HasColumnType("nvarchar(2000)") .HasMaxLength(2000); b.Property<string>("Exception") .HasColumnType("nvarchar(2000)") .HasMaxLength(2000); b.Property<int>("ExecutionDuration") .HasColumnType("int"); b.Property<DateTime>("ExecutionTime") .HasColumnType("datetime2"); b.Property<int?>("ImpersonatorTenantId") .HasColumnType("int"); b.Property<long?>("ImpersonatorUserId") .HasColumnType("bigint"); b.Property<string>("MethodName") .HasColumnType("nvarchar(256)") .HasMaxLength(256); b.Property<string>("Parameters") .HasColumnType("nvarchar(1024)") .HasMaxLength(1024); b.Property<string>("ReturnValue") .HasColumnType("nvarchar(max)"); b.Property<string>("ServiceName") .HasColumnType("nvarchar(256)") .HasMaxLength(256); b.Property<int?>("TenantId") .HasColumnType("int"); b.Property<long?>("UserId") .HasColumnType("bigint"); b.HasKey("Id"); b.HasIndex("TenantId", "ExecutionDuration"); b.HasIndex("TenantId", "ExecutionTime"); b.HasIndex("TenantId", "UserId"); b.ToTable("AbpAuditLogs"); }); modelBuilder.Entity("Abp.Authorization.PermissionSetting", b => { b.Property<long>("Id") .ValueGeneratedOnAdd() .HasColumnType("bigint") .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); b.Property<DateTime>("CreationTime") .HasColumnType("datetime2"); b.Property<long?>("CreatorUserId") .HasColumnType("bigint"); b.Property<string>("Discriminator") .IsRequired() .HasColumnType("nvarchar(max)"); b.Property<bool>("IsGranted") .HasColumnType("bit"); b.Property<string>("Name") .IsRequired() .HasColumnType("nvarchar(128)") .HasMaxLength(128); b.Property<int?>("TenantId") .HasColumnType("int"); b.HasKey("Id"); b.HasIndex("TenantId", "Name"); b.ToTable("AbpPermissions"); b.HasDiscriminator<string>("Discriminator").HasValue("PermissionSetting"); }); modelBuilder.Entity("Abp.Authorization.Roles.RoleClaim", b => { b.Property<long>("Id") .ValueGeneratedOnAdd() .HasColumnType("bigint") .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); b.Property<string>("ClaimType") .HasColumnType("nvarchar(256)") .HasMaxLength(256); b.Property<string>("ClaimValue") .HasColumnType("nvarchar(max)"); b.Property<DateTime>("CreationTime") .HasColumnType("datetime2"); b.Property<long?>("CreatorUserId") .HasColumnType("bigint"); b.Property<int>("RoleId") .HasColumnType("int"); b.Property<int?>("TenantId") .HasColumnType("int"); b.HasKey("Id"); b.HasIndex("RoleId"); b.HasIndex("TenantId", "ClaimType"); b.ToTable("AbpRoleClaims"); }); modelBuilder.Entity("Abp.Authorization.Users.UserAccount", b => { b.Property<long>("Id") .ValueGeneratedOnAdd() .HasColumnType("bigint") .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); b.Property<DateTime>("CreationTime") .HasColumnType("datetime2"); b.Property<long?>("CreatorUserId") .HasColumnType("bigint"); b.Property<long?>("DeleterUserId") .HasColumnType("bigint"); b.Property<DateTime?>("DeletionTime") .HasColumnType("datetime2"); b.Property<string>("EmailAddress") .HasColumnType("nvarchar(256)") .HasMaxLength(256); b.Property<bool>("IsDeleted") .HasColumnType("bit"); b.Property<DateTime?>("LastModificationTime") .HasColumnType("datetime2"); b.Property<long?>("LastModifierUserId") .HasColumnType("bigint"); b.Property<int?>("TenantId") .HasColumnType("int"); b.Property<long>("UserId") .HasColumnType("bigint"); b.Property<long?>("UserLinkId") .HasColumnType("bigint"); b.Property<string>("UserName") .HasColumnType("nvarchar(256)") .HasMaxLength(256); b.HasKey("Id"); b.HasIndex("EmailAddress"); b.HasIndex("UserName"); b.HasIndex("TenantId", "EmailAddress"); b.HasIndex("TenantId", "UserId"); b.HasIndex("TenantId", "UserName"); b.ToTable("AbpUserAccounts"); }); modelBuilder.Entity("Abp.Authorization.Users.UserClaim", b => { b.Property<long>("Id") .ValueGeneratedOnAdd() .HasColumnType("bigint") .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); b.Property<string>("ClaimType") .HasColumnType("nvarchar(256)") .HasMaxLength(256); b.Property<string>("ClaimValue") .HasColumnType("nvarchar(max)"); b.Property<DateTime>("CreationTime") .HasColumnType("datetime2"); b.Property<long?>("CreatorUserId") .HasColumnType("bigint"); b.Property<int?>("TenantId") .HasColumnType("int"); b.Property<long>("UserId") .HasColumnType("bigint"); b.HasKey("Id"); b.HasIndex("UserId"); b.HasIndex("TenantId", "ClaimType"); b.ToTable("AbpUserClaims"); }); modelBuilder.Entity("Abp.Authorization.Users.UserLogin", b => { b.Property<long>("Id") .ValueGeneratedOnAdd() .HasColumnType("bigint") .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); b.Property<string>("LoginProvider") .IsRequired() .HasColumnType("nvarchar(128)") .HasMaxLength(128); b.Property<string>("ProviderKey") .IsRequired() .HasColumnType("nvarchar(256)") .HasMaxLength(256); b.Property<int?>("TenantId") .HasColumnType("int"); b.Property<long>("UserId") .HasColumnType("bigint"); b.HasKey("Id"); b.HasIndex("UserId"); b.HasIndex("TenantId", "UserId"); b.HasIndex("TenantId", "LoginProvider", "ProviderKey"); b.ToTable("AbpUserLogins"); }); modelBuilder.Entity("Abp.Authorization.Users.UserLoginAttempt", b => { b.Property<long>("Id") .ValueGeneratedOnAdd() .HasColumnType("bigint") .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); b.Property<string>("BrowserInfo") .HasColumnType("nvarchar(512)") .HasMaxLength(512); b.Property<string>("ClientIpAddress") .HasColumnType("nvarchar(64)") .HasMaxLength(64); b.Property<string>("ClientName") .HasColumnType("nvarchar(128)") .HasMaxLength(128); b.Property<DateTime>("CreationTime") .HasColumnType("datetime2"); b.Property<byte>("Result") .HasColumnType("tinyint"); b.Property<string>("TenancyName") .HasColumnType("nvarchar(64)") .HasMaxLength(64); b.Property<int?>("TenantId") .HasColumnType("int"); b.Property<long?>("UserId") .HasColumnType("bigint"); b.Property<string>("UserNameOrEmailAddress") .HasColumnType("nvarchar(255)") .HasMaxLength(255); b.HasKey("Id"); b.HasIndex("UserId", "TenantId"); b.HasIndex("TenancyName", "UserNameOrEmailAddress", "Result"); b.ToTable("AbpUserLoginAttempts"); }); modelBuilder.Entity("Abp.Authorization.Users.UserOrganizationUnit", b => { b.Property<long>("Id") .ValueGeneratedOnAdd() .HasColumnType("bigint") .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); b.Property<DateTime>("CreationTime") .HasColumnType("datetime2"); b.Property<long?>("CreatorUserId") .HasColumnType("bigint"); b.Property<bool>("IsDeleted") .HasColumnType("bit"); b.Property<long>("OrganizationUnitId") .HasColumnType("bigint"); b.Property<int?>("TenantId") .HasColumnType("int"); b.Property<long>("UserId") .HasColumnType("bigint"); b.HasKey("Id"); b.HasIndex("TenantId", "OrganizationUnitId"); b.HasIndex("TenantId", "UserId"); b.ToTable("AbpUserOrganizationUnits"); }); modelBuilder.Entity("Abp.Authorization.Users.UserRole", b => { b.Property<long>("Id") .ValueGeneratedOnAdd() .HasColumnType("bigint") .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); b.Property<DateTime>("CreationTime") .HasColumnType("datetime2"); b.Property<long?>("CreatorUserId") .HasColumnType("bigint"); b.Property<int>("RoleId") .HasColumnType("int"); b.Property<int?>("TenantId") .HasColumnType("int"); b.Property<long>("UserId") .HasColumnType("bigint"); b.HasKey("Id"); b.HasIndex("UserId"); b.HasIndex("TenantId", "RoleId"); b.HasIndex("TenantId", "UserId"); b.ToTable("AbpUserRoles"); }); modelBuilder.Entity("Abp.Authorization.Users.UserToken", b => { b.Property<long>("Id") .ValueGeneratedOnAdd() .HasColumnType("bigint") .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); b.Property<DateTime?>("ExpireDate") .HasColumnType("datetime2"); b.Property<string>("LoginProvider") .HasColumnType("nvarchar(128)") .HasMaxLength(128); b.Property<string>("Name") .HasColumnType("nvarchar(128)") .HasMaxLength(128); b.Property<int?>("TenantId") .HasColumnType("int"); b.Property<long>("UserId") .HasColumnType("bigint"); b.Property<string>("Value") .HasColumnType("nvarchar(512)") .HasMaxLength(512); b.HasKey("Id"); b.HasIndex("UserId"); b.HasIndex("TenantId", "UserId"); b.ToTable("AbpUserTokens"); }); modelBuilder.Entity("Abp.BackgroundJobs.BackgroundJobInfo", b => { b.Property<long>("Id") .ValueGeneratedOnAdd() .HasColumnType("bigint") .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); b.Property<DateTime>("CreationTime") .HasColumnType("datetime2"); b.Property<long?>("CreatorUserId") .HasColumnType("bigint"); b.Property<bool>("IsAbandoned") .HasColumnType("bit"); b.Property<string>("JobArgs") .IsRequired() .HasColumnType("nvarchar(max)") .HasMaxLength(1048576); b.Property<string>("JobType") .IsRequired() .HasColumnType("nvarchar(512)") .HasMaxLength(512); b.Property<DateTime?>("LastTryTime") .HasColumnType("datetime2"); b.Property<DateTime>("NextTryTime") .HasColumnType("datetime2"); b.Property<byte>("Priority") .HasColumnType("tinyint"); b.Property<short>("TryCount") .HasColumnType("smallint"); b.HasKey("Id"); b.HasIndex("IsAbandoned", "NextTryTime"); b.ToTable("AbpBackgroundJobs"); }); modelBuilder.Entity("Abp.Configuration.Setting", b => { b.Property<long>("Id") .ValueGeneratedOnAdd() .HasColumnType("bigint") .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); b.Property<DateTime>("CreationTime") .HasColumnType("datetime2"); b.Property<long?>("CreatorUserId") .HasColumnType("bigint"); b.Property<DateTime?>("LastModificationTime") .HasColumnType("datetime2"); b.Property<long?>("LastModifierUserId") .HasColumnType("bigint"); b.Property<string>("Name") .IsRequired() .HasColumnType("nvarchar(256)") .HasMaxLength(256); b.Property<int?>("TenantId") .HasColumnType("int"); b.Property<long?>("UserId") .HasColumnType("bigint"); b.Property<string>("Value") .HasColumnType("nvarchar(2000)") .HasMaxLength(2000); b.HasKey("Id"); b.HasIndex("UserId"); b.HasIndex("TenantId", "Name"); b.ToTable("AbpSettings"); }); modelBuilder.Entity("Abp.EntityHistory.EntityChange", b => { b.Property<long>("Id") .ValueGeneratedOnAdd() .HasColumnType("bigint") .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); b.Property<DateTime>("ChangeTime") .HasColumnType("datetime2"); b.Property<byte>("ChangeType") .HasColumnType("tinyint"); b.Property<long>("EntityChangeSetId") .HasColumnType("bigint"); b.Property<string>("EntityId") .HasColumnType("nvarchar(48)") .HasMaxLength(48); b.Property<string>("EntityTypeFullName") .HasColumnType("nvarchar(192)") .HasMaxLength(192); b.Property<int?>("TenantId") .HasColumnType("int"); b.HasKey("Id"); b.HasIndex("EntityChangeSetId"); b.HasIndex("EntityTypeFullName", "EntityId"); b.ToTable("AbpEntityChanges"); }); modelBuilder.Entity("Abp.EntityHistory.EntityChangeSet", b => { b.Property<long>("Id") .ValueGeneratedOnAdd() .HasColumnType("bigint") .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); b.Property<string>("BrowserInfo") .HasColumnType("nvarchar(512)") .HasMaxLength(512); b.Property<string>("ClientIpAddress") .HasColumnType("nvarchar(64)") .HasMaxLength(64); b.Property<string>("ClientName") .HasColumnType("nvarchar(128)") .HasMaxLength(128); b.Property<DateTime>("CreationTime") .HasColumnType("datetime2"); b.Property<string>("ExtensionData") .HasColumnType("nvarchar(max)"); b.Property<int?>("ImpersonatorTenantId") .HasColumnType("int"); b.Property<long?>("ImpersonatorUserId") .HasColumnType("bigint"); b.Property<string>("Reason") .HasColumnType("nvarchar(256)") .HasMaxLength(256); b.Property<int?>("TenantId") .HasColumnType("int"); b.Property<long?>("UserId") .HasColumnType("bigint"); b.HasKey("Id"); b.HasIndex("TenantId", "CreationTime"); b.HasIndex("TenantId", "Reason"); b.HasIndex("TenantId", "UserId"); b.ToTable("AbpEntityChangeSets"); }); modelBuilder.Entity("Abp.EntityHistory.EntityPropertyChange", b => { b.Property<long>("Id") .ValueGeneratedOnAdd() .HasColumnType("bigint") .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); b.Property<long>("EntityChangeId") .HasColumnType("bigint"); b.Property<string>("NewValue") .HasColumnType("nvarchar(512)") .HasMaxLength(512); b.Property<string>("OriginalValue") .HasColumnType("nvarchar(512)") .HasMaxLength(512); b.Property<string>("PropertyName") .HasColumnType("nvarchar(96)") .HasMaxLength(96); b.Property<string>("PropertyTypeFullName") .HasColumnType("nvarchar(192)") .HasMaxLength(192); b.Property<int?>("TenantId") .HasColumnType("int"); b.HasKey("Id"); b.HasIndex("EntityChangeId"); b.ToTable("AbpEntityPropertyChanges"); }); modelBuilder.Entity("Abp.Localization.ApplicationLanguage", b => { b.Property<int>("Id") .ValueGeneratedOnAdd() .HasColumnType("int") .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); b.Property<DateTime>("CreationTime") .HasColumnType("datetime2"); b.Property<long?>("CreatorUserId") .HasColumnType("bigint"); b.Property<long?>("DeleterUserId") .HasColumnType("bigint"); b.Property<DateTime?>("DeletionTime") .HasColumnType("datetime2"); b.Property<string>("DisplayName") .IsRequired() .HasColumnType("nvarchar(64)") .HasMaxLength(64); b.Property<string>("Icon") .HasColumnType("nvarchar(128)") .HasMaxLength(128); b.Property<bool>("IsDeleted") .HasColumnType("bit"); b.Property<bool>("IsDisabled") .HasColumnType("bit"); b.Property<DateTime?>("LastModificationTime") .HasColumnType("datetime2"); b.Property<long?>("LastModifierUserId") .HasColumnType("bigint"); b.Property<string>("Name") .IsRequired() .HasColumnType("nvarchar(10)") .HasMaxLength(10); b.Property<int?>("TenantId") .HasColumnType("int"); b.HasKey("Id"); b.HasIndex("TenantId", "Name"); b.ToTable("AbpLanguages"); }); modelBuilder.Entity("Abp.Localization.ApplicationLanguageText", b => { b.Property<long>("Id") .ValueGeneratedOnAdd() .HasColumnType("bigint") .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); b.Property<DateTime>("CreationTime") .HasColumnType("datetime2"); b.Property<long?>("CreatorUserId") .HasColumnType("bigint"); b.Property<string>("Key") .IsRequired() .HasColumnType("nvarchar(256)") .HasMaxLength(256); b.Property<string>("LanguageName") .IsRequired() .HasColumnType("nvarchar(10)") .HasMaxLength(10); b.Property<DateTime?>("LastModificationTime") .HasColumnType("datetime2"); b.Property<long?>("LastModifierUserId") .HasColumnType("bigint"); b.Property<string>("Source") .IsRequired() .HasColumnType("nvarchar(128)") .HasMaxLength(128); b.Property<int?>("TenantId") .HasColumnType("int"); b.Property<string>("Value") .IsRequired() .HasColumnType("nvarchar(max)") .HasMaxLength(67108864); b.HasKey("Id"); b.HasIndex("TenantId", "Source", "LanguageName", "Key"); b.ToTable("AbpLanguageTexts"); }); modelBuilder.Entity("Abp.Notifications.NotificationInfo", b => { b.Property<Guid>("Id") .ValueGeneratedOnAdd() .HasColumnType("uniqueidentifier"); b.Property<DateTime>("CreationTime") .HasColumnType("datetime2"); b.Property<long?>("CreatorUserId") .HasColumnType("bigint"); b.Property<string>("Data") .HasColumnType("nvarchar(max)") .HasMaxLength(1048576); b.Property<string>("DataTypeName") .HasColumnType("nvarchar(512)") .HasMaxLength(512); b.Property<string>("EntityId") .HasColumnType("nvarchar(96)") .HasMaxLength(96); b.Property<string>("EntityTypeAssemblyQualifiedName") .HasColumnType("nvarchar(512)") .HasMaxLength(512); b.Property<string>("EntityTypeName") .HasColumnType("nvarchar(250)") .HasMaxLength(250); b.Property<string>("ExcludedUserIds") .HasColumnType("nvarchar(max)") .HasMaxLength(131072); b.Property<string>("NotificationName") .IsRequired() .HasColumnType("nvarchar(96)") .HasMaxLength(96); b.Property<byte>("Severity") .HasColumnType("tinyint"); b.Property<string>("TenantIds") .HasColumnType("nvarchar(max)") .HasMaxLength(131072); b.Property<string>("UserIds") .HasColumnType("nvarchar(max)") .HasMaxLength(131072); b.HasKey("Id"); b.ToTable("AbpNotifications"); }); modelBuilder.Entity("Abp.Notifications.NotificationSubscriptionInfo", b => { b.Property<Guid>("Id") .ValueGeneratedOnAdd() .HasColumnType("uniqueidentifier"); b.Property<DateTime>("CreationTime") .HasColumnType("datetime2"); b.Property<long?>("CreatorUserId") .HasColumnType("bigint"); b.Property<string>("EntityId") .HasColumnType("nvarchar(96)") .HasMaxLength(96); b.Property<string>("EntityTypeAssemblyQualifiedName") .HasColumnType("nvarchar(512)") .HasMaxLength(512); b.Property<string>("EntityTypeName") .HasColumnType("nvarchar(250)") .HasMaxLength(250); b.Property<string>("NotificationName") .HasColumnType("nvarchar(96)") .HasMaxLength(96); b.Property<int?>("TenantId") .HasColumnType("int"); b.Property<long>("UserId") .HasColumnType("bigint"); b.HasKey("Id"); b.HasIndex("NotificationName", "EntityTypeName", "EntityId", "UserId"); b.HasIndex("TenantId", "NotificationName", "EntityTypeName", "EntityId", "UserId"); b.ToTable("AbpNotificationSubscriptions"); }); modelBuilder.Entity("Abp.Notifications.TenantNotificationInfo", b => { b.Property<Guid>("Id") .ValueGeneratedOnAdd() .HasColumnType("uniqueidentifier"); b.Property<DateTime>("CreationTime") .HasColumnType("datetime2"); b.Property<long?>("CreatorUserId") .HasColumnType("bigint"); b.Property<string>("Data") .HasColumnType("nvarchar(max)") .HasMaxLength(1048576); b.Property<string>("DataTypeName") .HasColumnType("nvarchar(512)") .HasMaxLength(512); b.Property<string>("EntityId") .HasColumnType("nvarchar(96)") .HasMaxLength(96); b.Property<string>("EntityTypeAssemblyQualifiedName") .HasColumnType("nvarchar(512)") .HasMaxLength(512); b.Property<string>("EntityTypeName") .HasColumnType("nvarchar(250)") .HasMaxLength(250); b.Property<string>("NotificationName") .IsRequired() .HasColumnType("nvarchar(96)") .HasMaxLength(96); b.Property<byte>("Severity") .HasColumnType("tinyint"); b.Property<int?>("TenantId") .HasColumnType("int"); b.HasKey("Id"); b.HasIndex("TenantId"); b.ToTable("AbpTenantNotifications"); }); modelBuilder.Entity("Abp.Notifications.UserNotificationInfo", b => { b.Property<Guid>("Id") .ValueGeneratedOnAdd() .HasColumnType("uniqueidentifier"); b.Property<DateTime>("CreationTime") .HasColumnType("datetime2"); b.Property<int>("State") .HasColumnType("int"); b.Property<int?>("TenantId") .HasColumnType("int"); b.Property<Guid>("TenantNotificationId") .HasColumnType("uniqueidentifier"); b.Property<long>("UserId") .HasColumnType("bigint"); b.HasKey("Id"); b.HasIndex("UserId", "State", "CreationTime"); b.ToTable("AbpUserNotifications"); }); modelBuilder.Entity("Abp.Organizations.OrganizationUnit", b => { b.Property<long>("Id") .ValueGeneratedOnAdd() .HasColumnType("bigint") .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); b.Property<string>("Code") .IsRequired() .HasColumnType("nvarchar(95)") .HasMaxLength(95); b.Property<DateTime>("CreationTime") .HasColumnType("datetime2"); b.Property<long?>("CreatorUserId") .HasColumnType("bigint"); b.Property<long?>("DeleterUserId") .HasColumnType("bigint"); b.Property<DateTime?>("DeletionTime") .HasColumnType("datetime2"); b.Property<string>("DisplayName") .IsRequired() .HasColumnType("nvarchar(128)") .HasMaxLength(128); b.Property<bool>("IsDeleted") .HasColumnType("bit"); b.Property<DateTime?>("LastModificationTime") .HasColumnType("datetime2"); b.Property<long?>("LastModifierUserId") .HasColumnType("bigint"); b.Property<long?>("ParentId") .HasColumnType("bigint"); b.Property<int?>("TenantId") .HasColumnType("int"); b.HasKey("Id"); b.HasIndex("ParentId"); b.HasIndex("TenantId", "Code"); b.ToTable("AbpOrganizationUnits"); }); modelBuilder.Entity("Abp.Organizations.OrganizationUnitRole", b => { b.Property<long>("Id") .ValueGeneratedOnAdd() .HasColumnType("bigint") .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); b.Property<DateTime>("CreationTime") .HasColumnType("datetime2"); b.Property<long?>("CreatorUserId") .HasColumnType("bigint"); b.Property<bool>("IsDeleted") .HasColumnType("bit"); b.Property<long>("OrganizationUnitId") .HasColumnType("bigint"); b.Property<int>("RoleId") .HasColumnType("int"); b.Property<int?>("TenantId") .HasColumnType("int"); b.HasKey("Id"); b.HasIndex("TenantId", "OrganizationUnitId"); b.HasIndex("TenantId", "RoleId"); b.ToTable("AbpOrganizationUnitRoles"); }); modelBuilder.Entity("InstaAutoBot.Authorization.Roles.Role", b => { b.Property<int>("Id") .ValueGeneratedOnAdd() .HasColumnType("int") .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); b.Property<string>("ConcurrencyStamp") .IsConcurrencyToken() .HasColumnType("nvarchar(128)") .HasMaxLength(128); b.Property<DateTime>("CreationTime") .HasColumnType("datetime2"); b.Property<long?>("CreatorUserId") .HasColumnType("bigint"); b.Property<long?>("DeleterUserId") .HasColumnType("bigint"); b.Property<DateTime?>("DeletionTime") .HasColumnType("datetime2"); b.Property<string>("Description") .HasColumnType("nvarchar(max)") .HasMaxLength(5000); b.Property<string>("DisplayName") .IsRequired() .HasColumnType("nvarchar(64)") .HasMaxLength(64); b.Property<bool>("IsDefault") .HasColumnType("bit"); b.Property<bool>("IsDeleted") .HasColumnType("bit"); b.Property<bool>("IsStatic") .HasColumnType("bit"); b.Property<DateTime?>("LastModificationTime") .HasColumnType("datetime2"); b.Property<long?>("LastModifierUserId") .HasColumnType("bigint"); b.Property<string>("Name") .IsRequired() .HasColumnType("nvarchar(32)") .HasMaxLength(32); b.Property<string>("NormalizedName") .IsRequired() .HasColumnType("nvarchar(32)") .HasMaxLength(32); b.Property<int?>("TenantId") .HasColumnType("int"); b.HasKey("Id"); b.HasIndex("CreatorUserId"); b.HasIndex("DeleterUserId"); b.HasIndex("LastModifierUserId"); b.HasIndex("TenantId", "NormalizedName"); b.ToTable("AbpRoles"); }); modelBuilder.Entity("InstaAutoBot.Authorization.Users.User", b => { b.Property<long>("Id") .ValueGeneratedOnAdd() .HasColumnType("bigint") .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); b.Property<int>("AccessFailedCount") .HasColumnType("int"); b.Property<string>("AuthenticationSource") .HasColumnType("nvarchar(64)") .HasMaxLength(64); b.Property<string>("ConcurrencyStamp") .IsConcurrencyToken() .HasColumnType("nvarchar(128)") .HasMaxLength(128); b.Property<DateTime>("CreationTime") .HasColumnType("datetime2"); b.Property<long?>("CreatorUserId") .HasColumnType("bigint"); b.Property<long?>("DeleterUserId") .HasColumnType("bigint"); b.Property<DateTime?>("DeletionTime") .HasColumnType("datetime2"); b.Property<string>("EmailAddress") .IsRequired() .HasColumnType("nvarchar(256)") .HasMaxLength(256); b.Property<string>("EmailConfirmationCode") .HasColumnType("nvarchar(328)") .HasMaxLength(328); b.Property<bool>("IsActive") .HasColumnType("bit"); b.Property<bool>("IsDeleted") .HasColumnType("bit"); b.Property<bool>("IsEmailConfirmed") .HasColumnType("bit"); b.Property<bool>("IsLockoutEnabled") .HasColumnType("bit"); b.Property<bool>("IsPhoneNumberConfirmed") .HasColumnType("bit"); b.Property<bool>("IsTwoFactorEnabled") .HasColumnType("bit"); b.Property<DateTime?>("LastModificationTime") .HasColumnType("datetime2"); b.Property<long?>("LastModifierUserId") .HasColumnType("bigint"); b.Property<DateTime?>("LockoutEndDateUtc") .HasColumnType("datetime2"); b.Property<string>("Name") .IsRequired() .HasColumnType("nvarchar(64)") .HasMaxLength(64); b.Property<string>("NormalizedEmailAddress") .IsRequired() .HasColumnType("nvarchar(256)") .HasMaxLength(256); b.Property<string>("NormalizedUserName") .IsRequired() .HasColumnType("nvarchar(256)") .HasMaxLength(256); b.Property<string>("Password") .IsRequired() .HasColumnType("nvarchar(128)") .HasMaxLength(128); b.Property<string>("PasswordResetCode") .HasColumnType("nvarchar(328)") .HasMaxLength(328); b.Property<string>("PhoneNumber") .HasColumnType("nvarchar(32)") .HasMaxLength(32); b.Property<string>("SecurityStamp") .HasColumnType("nvarchar(128)") .HasMaxLength(128); b.Property<string>("Surname") .IsRequired() .HasColumnType("nvarchar(64)") .HasMaxLength(64); b.Property<int?>("TenantId") .HasColumnType("int"); b.Property<string>("UserName") .IsRequired() .HasColumnType("nvarchar(256)") .HasMaxLength(256); b.HasKey("Id"); b.HasIndex("CreatorUserId"); b.HasIndex("DeleterUserId"); b.HasIndex("LastModifierUserId"); b.HasIndex("TenantId", "NormalizedEmailAddress"); b.HasIndex("TenantId", "NormalizedUserName"); b.ToTable("AbpUsers"); }); modelBuilder.Entity("InstaAutoBot.MultiTenancy.Tenant", b => { b.Property<int>("Id") .ValueGeneratedOnAdd() .HasColumnType("int") .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); b.Property<string>("ConnectionString") .HasColumnType("nvarchar(1024)") .HasMaxLength(1024); b.Property<DateTime>("CreationTime") .HasColumnType("datetime2"); b.Property<long?>("CreatorUserId") .HasColumnType("bigint"); b.Property<long?>("DeleterUserId") .HasColumnType("bigint"); b.Property<DateTime?>("DeletionTime") .HasColumnType("datetime2"); b.Property<int?>("EditionId") .HasColumnType("int"); b.Property<bool>("IsActive") .HasColumnType("bit"); b.Property<bool>("IsDeleted") .HasColumnType("bit"); b.Property<DateTime?>("LastModificationTime") .HasColumnType("datetime2"); b.Property<long?>("LastModifierUserId") .HasColumnType("bigint"); b.Property<string>("Name") .IsRequired() .HasColumnType("nvarchar(128)") .HasMaxLength(128); b.Property<string>("TenancyName") .IsRequired() .HasColumnType("nvarchar(64)") .HasMaxLength(64); b.HasKey("Id"); b.HasIndex("CreatorUserId"); b.HasIndex("DeleterUserId"); b.HasIndex("EditionId"); b.HasIndex("LastModifierUserId"); b.HasIndex("TenancyName"); b.ToTable("AbpTenants"); }); modelBuilder.Entity("Abp.Application.Features.EditionFeatureSetting", b => { b.HasBaseType("Abp.Application.Features.FeatureSetting"); b.Property<int>("EditionId") .HasColumnType("int"); b.HasIndex("EditionId", "Name"); b.ToTable("AbpFeatures"); b.HasDiscriminator().HasValue("EditionFeatureSetting"); }); modelBuilder.Entity("Abp.MultiTenancy.TenantFeatureSetting", b => { b.HasBaseType("Abp.Application.Features.FeatureSetting"); b.HasIndex("TenantId", "Name"); b.ToTable("AbpFeatures"); b.HasDiscriminator().HasValue("TenantFeatureSetting"); }); modelBuilder.Entity("Abp.Authorization.Roles.RolePermissionSetting", b => { b.HasBaseType("Abp.Authorization.PermissionSetting"); b.Property<int>("RoleId") .HasColumnType("int"); b.HasIndex("RoleId"); b.ToTable("AbpPermissions"); b.HasDiscriminator().HasValue("RolePermissionSetting"); }); modelBuilder.Entity("Abp.Authorization.Users.UserPermissionSetting", b => { b.HasBaseType("Abp.Authorization.PermissionSetting"); b.Property<long>("UserId") .HasColumnType("bigint"); b.HasIndex("UserId"); b.ToTable("AbpPermissions"); b.HasDiscriminator().HasValue("UserPermissionSetting"); }); modelBuilder.Entity("Abp.Authorization.Roles.RoleClaim", b => { b.HasOne("InstaAutoBot.Authorization.Roles.Role") .WithMany("Claims") .HasForeignKey("RoleId") .OnDelete(DeleteBehavior.Cascade); }); modelBuilder.Entity("Abp.Authorization.Users.UserClaim", b => { b.HasOne("InstaAutoBot.Authorization.Users.User") .WithMany("Claims") .HasForeignKey("UserId") .OnDelete(DeleteBehavior.Cascade); }); modelBuilder.Entity("Abp.Authorization.Users.UserLogin", b => { b.HasOne("InstaAutoBot.Authorization.Users.User") .WithMany("Logins") .HasForeignKey("UserId") .OnDelete(DeleteBehavior.Cascade); }); modelBuilder.Entity("Abp.Authorization.Users.UserRole", b => { b.HasOne("InstaAutoBot.Authorization.Users.User") .WithMany("Roles") .HasForeignKey("UserId") .OnDelete(DeleteBehavior.Cascade); }); modelBuilder.Entity("Abp.Authorization.Users.UserToken", b => { b.HasOne("InstaAutoBot.Authorization.Users.User") .WithMany("Tokens") .HasForeignKey("UserId") .OnDelete(DeleteBehavior.Cascade); }); modelBuilder.Entity("Abp.Configuration.Setting", b => { b.HasOne("InstaAutoBot.Authorization.Users.User") .WithMany("Settings") .HasForeignKey("UserId"); }); modelBuilder.Entity("Abp.EntityHistory.EntityChange", b => { b.HasOne("Abp.EntityHistory.EntityChangeSet") .WithMany("EntityChanges") .HasForeignKey("EntityChangeSetId") .OnDelete(DeleteBehavior.Cascade); }); modelBuilder.Entity("Abp.EntityHistory.EntityPropertyChange", b => { b.HasOne("Abp.EntityHistory.EntityChange") .WithMany("PropertyChanges") .HasForeignKey("EntityChangeId") .OnDelete(DeleteBehavior.Cascade); }); modelBuilder.Entity("Abp.Organizations.OrganizationUnit", b => { b.HasOne("Abp.Organizations.OrganizationUnit", "Parent") .WithMany("Children") .HasForeignKey("ParentId"); }); modelBuilder.Entity("InstaAutoBot.Authorization.Roles.Role", b => { b.HasOne("InstaAutoBot.Authorization.Users.User", "CreatorUser") .WithMany() .HasForeignKey("CreatorUserId"); b.HasOne("InstaAutoBot.Authorization.Users.User", "DeleterUser") .WithMany() .HasForeignKey("DeleterUserId"); b.HasOne("InstaAutoBot.Authorization.Users.User", "LastModifierUser") .WithMany() .HasForeignKey("LastModifierUserId"); }); modelBuilder.Entity("InstaAutoBot.Authorization.Users.User", b => { b.HasOne("InstaAutoBot.Authorization.Users.User", "CreatorUser") .WithMany() .HasForeignKey("CreatorUserId"); b.HasOne("InstaAutoBot.Authorization.Users.User", "DeleterUser") .WithMany() .HasForeignKey("DeleterUserId"); b.HasOne("InstaAutoBot.Authorization.Users.User", "LastModifierUser") .WithMany() .HasForeignKey("LastModifierUserId"); }); modelBuilder.Entity("InstaAutoBot.MultiTenancy.Tenant", b => { b.HasOne("InstaAutoBot.Authorization.Users.User", "CreatorUser") .WithMany() .HasForeignKey("CreatorUserId"); b.HasOne("InstaAutoBot.Authorization.Users.User", "DeleterUser") .WithMany() .HasForeignKey("DeleterUserId"); b.HasOne("Abp.Application.Editions.Edition", "Edition") .WithMany() .HasForeignKey("EditionId"); b.HasOne("InstaAutoBot.Authorization.Users.User", "LastModifierUser") .WithMany() .HasForeignKey("LastModifierUserId"); }); modelBuilder.Entity("Abp.Application.Features.EditionFeatureSetting", b => { b.HasOne("Abp.Application.Editions.Edition", "Edition") .WithMany() .HasForeignKey("EditionId") .OnDelete(DeleteBehavior.Cascade); }); modelBuilder.Entity("Abp.Authorization.Roles.RolePermissionSetting", b => { b.HasOne("InstaAutoBot.Authorization.Roles.Role") .WithMany("Permissions") .HasForeignKey("RoleId") .OnDelete(DeleteBehavior.Cascade); }); modelBuilder.Entity("Abp.Authorization.Users.UserPermissionSetting", b => { b.HasOne("InstaAutoBot.Authorization.Users.User") .WithMany("Permissions") .HasForeignKey("UserId") .OnDelete(DeleteBehavior.Cascade); }); #pragma warning restore 612, 618 } } }
36.883588
125
0.446405
[ "MIT" ]
priteshzhao/insta-auto-bot-
aspnet-core/src/InstaAutoBot.EntityFrameworkCore/Migrations/20190208051931_Upgrade_ABP_4_2_0.Designer.cs
57,981
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 codecommit-2015-04-13.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.CodeCommit.Model; using Amazon.Runtime; using Amazon.Runtime.Internal; using Amazon.Runtime.Internal.Transform; using Amazon.Runtime.Internal.Util; using ThirdParty.Json.LitJson; namespace Amazon.CodeCommit.Model.Internal.MarshallTransformations { /// <summary> /// Response Unmarshaller for FileEntryRequiredException Object /// </summary> public class FileEntryRequiredExceptionUnmarshaller : IErrorResponseUnmarshaller<FileEntryRequiredException, JsonUnmarshallerContext> { /// <summary> /// Unmarshaller the response from the service to the response class. /// </summary> /// <param name="context"></param> /// <returns></returns> public FileEntryRequiredException Unmarshall(JsonUnmarshallerContext context) { return this.Unmarshall(context, new ErrorResponse()); } /// <summary> /// Unmarshaller the response from the service to the response class. /// </summary> /// <param name="context"></param> /// <param name="errorResponse"></param> /// <returns></returns> public FileEntryRequiredException Unmarshall(JsonUnmarshallerContext context, ErrorResponse errorResponse) { context.Read(); FileEntryRequiredException unmarshalledObject = new FileEntryRequiredException(errorResponse.Message, errorResponse.InnerException, errorResponse.Type, errorResponse.Code, errorResponse.RequestId, errorResponse.StatusCode); int targetDepth = context.CurrentDepth; while (context.ReadAtDepth(targetDepth)) { } return unmarshalledObject; } private static FileEntryRequiredExceptionUnmarshaller _instance = new FileEntryRequiredExceptionUnmarshaller(); /// <summary> /// Gets the singleton. /// </summary> public static FileEntryRequiredExceptionUnmarshaller Instance { get { return _instance; } } } }
35.117647
143
0.673367
[ "Apache-2.0" ]
ChristopherButtars/aws-sdk-net
sdk/src/Services/CodeCommit/Generated/Model/Internal/MarshallTransformations/FileEntryRequiredExceptionUnmarshaller.cs
2,985
C#
// Copyright (c) Nate McMaster. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. // This file has been modified from the original form. See Notice.txt in the project root for more information. using System; using System.IO; namespace McMaster.Extensions.CommandLineUtils { /// <summary> /// An implementation of <see cref="IConsole"/> that wraps <see cref="System.Console"/>. /// </summary> public class PhysicalConsole : IConsole { /// <summary> /// A shared instance of <see cref="PhysicalConsole"/>. /// </summary> public static IConsole Singleton { get; } = new PhysicalConsole(); // TODO: in 3.0 make this type truly a singleton by adding a private ctor // this is techinally a breaking change, so wait till 3.0 // private PhysicalConsole() // { // } /// <summary> /// <see cref="Console.CancelKeyPress"/>. /// </summary> public event ConsoleCancelEventHandler? CancelKeyPress { add => Console.CancelKeyPress += value; remove => Console.CancelKeyPress -= value; } /// <summary> /// <see cref="Console.Error"/>. /// </summary> public TextWriter Error => Console.Error; /// <summary> /// <see cref="Console.In"/>. /// </summary> public TextReader In => Console.In; /// <summary> /// <see cref="Console.Out"/>. /// </summary> public TextWriter Out => Console.Out; /// <summary> /// <see cref="Console.IsInputRedirected"/>. /// </summary> public bool IsInputRedirected => Console.IsInputRedirected; /// <summary> /// <see cref="Console.IsOutputRedirected"/>. /// </summary> public bool IsOutputRedirected => Console.IsOutputRedirected; /// <summary> /// <see cref="Console.IsErrorRedirected"/>. /// </summary> public bool IsErrorRedirected => Console.IsErrorRedirected; /// <summary> /// <see cref="Console.ForegroundColor"/>. /// </summary> public ConsoleColor ForegroundColor { get => Console.ForegroundColor; set => Console.ForegroundColor = value; } /// <summary> /// <see cref="Console.BackgroundColor"/>. /// </summary> public ConsoleColor BackgroundColor { get => Console.BackgroundColor; set => Console.BackgroundColor = value; } /// <summary> /// <see cref="Console.ResetColor"/>. /// </summary> public void ResetColor() => Console.ResetColor(); } }
31.157303
111
0.563289
[ "Apache-2.0" ]
Alxandr/CommandLineUtils
src/CommandLineUtils/IO/PhysicalConsole.cs
2,775
C#
namespace EArchive.EArsivVeri { [System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "4.8.3928.0")] [System.SerializableAttribute()] [System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true, Namespace = "http://earsiv.efatura.gov.tr")] public enum vergiBilgiTypeVergiVergiKodu { /// <remarks/> [System.Xml.Serialization.XmlEnumAttribute("0003")] Item0003, /// <remarks/> [System.Xml.Serialization.XmlEnumAttribute("0011")] Item0011, /// <remarks/> [System.Xml.Serialization.XmlEnumAttribute("0015")] Item0015, /// <remarks/> [System.Xml.Serialization.XmlEnumAttribute("0021")] Item0021, /// <remarks/> [System.Xml.Serialization.XmlEnumAttribute("0061")] Item0061, /// <remarks/> [System.Xml.Serialization.XmlEnumAttribute("0071")] Item0071, /// <remarks/> [System.Xml.Serialization.XmlEnumAttribute("0073")] Item0073, /// <remarks/> [System.Xml.Serialization.XmlEnumAttribute("0074")] Item0074, /// <remarks/> [System.Xml.Serialization.XmlEnumAttribute("0075")] Item0075, /// <remarks/> [System.Xml.Serialization.XmlEnumAttribute("0076")] Item0076, /// <remarks/> [System.Xml.Serialization.XmlEnumAttribute("0077")] Item0077, /// <remarks/> [System.Xml.Serialization.XmlEnumAttribute("1047")] Item1047, /// <remarks/> [System.Xml.Serialization.XmlEnumAttribute("1048")] Item1048, /// <remarks/> [System.Xml.Serialization.XmlEnumAttribute("4080")] Item4080, /// <remarks/> [System.Xml.Serialization.XmlEnumAttribute("4081")] Item4081, /// <remarks/> [System.Xml.Serialization.XmlEnumAttribute("4171")] Item4171, /// <remarks/> [System.Xml.Serialization.XmlEnumAttribute("9015")] Item9015, /// <remarks/> [System.Xml.Serialization.XmlEnumAttribute("9021")] Item9021, /// <remarks/> [System.Xml.Serialization.XmlEnumAttribute("9077")] Item9077, /// <remarks/> [System.Xml.Serialization.XmlEnumAttribute("8001")] Item8001, /// <remarks/> [System.Xml.Serialization.XmlEnumAttribute("8002")] Item8002, /// <remarks/> [System.Xml.Serialization.XmlEnumAttribute("4071")] Item4071, /// <remarks/> [System.Xml.Serialization.XmlEnumAttribute("8004")] Item8004, /// <remarks/> [System.Xml.Serialization.XmlEnumAttribute("8005")] Item8005, /// <remarks/> [System.Xml.Serialization.XmlEnumAttribute("8006")] Item8006, /// <remarks/> [System.Xml.Serialization.XmlEnumAttribute("8007")] Item8007, /// <remarks/> [System.Xml.Serialization.XmlEnumAttribute("8008")] Item8008, /// <remarks/> [System.Xml.Serialization.XmlEnumAttribute("9040")] Item9040, } }
26
113
0.575977
[ "MIT" ]
hkutluay/EArchive
EArchive/EArsivVeri/vergiBilgiTypeVergiVergiKodu.cs
3,172
C#
// Copyright (C) 2009-2018 Luca Piccioni // // 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. // Macro utility for logging platform-relared function calls #undef PLATFORM_LOG_ENABLED using System; using System.Collections.Generic; using System.ComponentModel; using System.Diagnostics.CodeAnalysis; using System.Runtime.InteropServices; namespace Khronos { /// <summary> /// Interface implemented by those classes which are able to get function pointers from dynamically loaded libraries. /// </summary> interface IGetProcAddressOS { /// <summary> /// Add a path of a directory as additional path for searching libraries. /// </summary> /// <param name="libraryDirPath"> /// A <see cref="String"/> that specify the absolute path of the directory where the libraries are loaded using /// <see cref="GetProcAddress(string, string)"/> method. /// </param> void AddLibraryDirectory(string libraryDirPath); /// <summary> /// Get a function pointer from a library, specified by path. /// </summary> /// <param name="library"> /// A <see cref="String"/> that specifies the path of the library defining the function. /// </param> /// <param name="function"> /// A <see cref="String"/> that specifies the function name. /// </param> /// <returns> /// It returns an <see cref="IntPtr"/> that specifies the address of the function <paramref name="function"/>. /// </returns> IntPtr GetProcAddress(string library, string function); } /// <summary> /// Abtract an interface for loading procedures from dynamically loaded libraries. /// </summary> internal static class GetProcAddressOS { #region Constructors /// <summary> /// Static constructor. /// </summary> static GetProcAddressOS() { #if !NETSTANDARD1_1 string envOsLoader = Environment.GetEnvironmentVariable("OPENGL_NET_OSLOADER"); #else string envOsLoader = null; #endif switch (envOsLoader) { case "EGL": // Force using eglGetProcAddress _GetProcAddressOS = GetProcAddressEGL.Instance; // Use EGL backend as default // Egl.IsRequired = true; -.- break; default: _GetProcAddressOS = CreateOS(); break; } } /// <summary> /// Most appropriate <see cref="IGetProcAddressOS"/> for the current platform. /// </summary> private static readonly IGetProcAddressOS _GetProcAddressOS; /// <summary> /// Create an <see cref="IGetProcAddressOS"/> for the hosting platform. /// </summary> /// <returns> /// It returns the most appropriate <see cref="IGetProcAddressOS"/> for the current platform. /// </returns> private static IGetProcAddressOS CreateOS() { switch (Platform.CurrentPlatformId) { case Platform.Id.WindowsNT: return new GetProcAddressWindows(); case Platform.Id.Linux: return new GetProcAddressLinux(); case Platform.Id.MacOS: return new GetProcAddressOSX(); case Platform.Id.Android: return new GetProcAddressEGL(); default: throw new NotSupportedException($"platform {Platform.CurrentPlatformId} not supported"); } } #endregion #region Abstract Interface /// <summary> /// Add a path of a directory as additional path for searching libraries. /// </summary> /// <param name="libraryDirPath"> /// A <see cref="String"/> that specify the absolute path of the directory where the libraries are loaded using /// <see cref="GetProcAddress(string, string)"/> method. /// </param> public static void AddLibraryDirectory(string libraryDirPath) { _GetProcAddressOS.AddLibraryDirectory(libraryDirPath); } /// <summary> /// Get a function pointer from a library, specified by path. /// </summary> /// <param name="library"> /// A <see cref="String"/> that specifies the path of the library defining the function. /// </param> /// <param name="function"> /// A <see cref="String"/> that specifies the function name. /// </param> /// <returns> /// It returns an <see cref="IntPtr"/> that specifies the address of the function <paramref name="function"/>. /// </returns> public static IntPtr GetProcAddress(string library, string function) { return _GetProcAddressOS.GetProcAddress(library, function); } #endregion } /// <summary> /// Class able to get function pointers on Windows platform. /// </summary> internal class GetProcAddressWindows : IGetProcAddressOS { #region Singleton /// <summary> /// The <see cref="GetGLProcAddressEGL"/> singleton instance. /// </summary> public static readonly GetProcAddressWindows Instance = new GetProcAddressWindows(); #endregion #region Windows Platform Imports static class UnsafeNativeMethods { [DllImport("Kernel32.dll", SetLastError = true)] public static extern IntPtr LoadLibrary(string lpFileName); [DllImport("Kernel32.dll", EntryPoint = "GetProcAddress", CharSet = CharSet.Ansi, ExactSpelling = true, SetLastError = true)] public static extern IntPtr Win32GetProcAddress(IntPtr hModule, string lpProcName); } #endregion #region IGetProcAddress Implementation /// <summary> /// Add a path of a directory as additional path for searching libraries. /// </summary> /// <param name="libraryDirPath"> /// A <see cref="String"/> that specify the absolute path of the directory where the libraries are loaded using /// <see cref="GetProcAddress(string, string)"/> method. /// </param> public void AddLibraryDirectory(string libraryDirPath) { #if NETSTANDARD1_1 || NETSTANDARD1_4 || NETCOREAPP1_1 // Note: no support for library directories for the following targets: // - .NET Standard 1.4 and below // - .NET Core App 1.1 #else string path = Environment.GetEnvironmentVariable("PATH"); Environment.SetEnvironmentVariable("PATH", $"{path};{libraryDirPath}", EnvironmentVariableTarget.Process); #endif } /// <summary> /// Get a function pointer from a library, specified by path. /// </summary> /// <param name="library"> /// A <see cref="String"/> that specifies the path of the library defining the function. /// </param> /// <param name="function"> /// A <see cref="String"/> that specifies the function name. /// </param> /// <returns> /// It returns an <see cref="IntPtr"/> that specifies the address of the function <paramref name="function"/>. /// </returns> public IntPtr GetProcAddress(string library, string function) { IntPtr handle = GetLibraryHandle(library); return GetProcAddress(handle, function); } /// <summary> /// Get a function pointer from a library, specified by handle. /// </summary> /// <param name="library"> /// A <see cref="IntPtr"/> which represents an opaque handle to the library containing the function. /// </param> /// <param name="function"> /// A <see cref="String"/> that specifies the function name. /// </param> /// <returns> /// It returns an <see cref="IntPtr"/> that specifies the address of the function <paramref name="function"/>. /// </returns> private IntPtr GetProcAddress(IntPtr library, string function) { if (library == IntPtr.Zero) throw new ArgumentNullException(nameof(library)); if (function == null) throw new ArgumentNullException(nameof(function)); IntPtr procAddress = UnsafeNativeMethods.Win32GetProcAddress(library, function); #if PLATFORM_LOG_ENABLED KhronosApi.LogFunction("GetProcAddress(0x{0}, {1}) = 0x{2}", library.ToString("X8"), function, procAddress.ToString("X8")); #endif return procAddress; } /// <summary> /// Get the handle relative to the specified library. /// </summary> /// <param name="libraryPath"> /// A <see cref="String"/> that specify the path of the library to load. /// </param> /// <returns> /// It returns a <see cref="IntPtr"/> that represents the handle of the library loaded from <paramref name="libraryPath"/>. /// </returns> public IntPtr GetLibraryHandle(string libraryPath) { IntPtr libraryHandle; if (_LibraryHandles.TryGetValue(libraryPath, out libraryHandle) == false) { // Load library libraryHandle = UnsafeNativeMethods.LoadLibrary(libraryPath); #if PLATFORM_LOG_ENABLED KhronosApi.LogFunction("LoadLibrary({0}) = 0x{1}", libraryPath, libraryHandle.ToString("X8")); #endif _LibraryHandles.Add(libraryPath, libraryHandle); } if (libraryHandle == IntPtr.Zero) throw new InvalidOperationException($"unable to load library at {libraryPath}", new Win32Exception(Marshal.GetLastWin32Error())); return libraryHandle; } /// <summary> /// Currently loaded libraries. /// </summary> private static readonly Dictionary<string, IntPtr> _LibraryHandles = new Dictionary<string,IntPtr>(); #endregion } /// <summary> /// Class able to get function pointers on X11 platform. /// </summary> internal class GetProcAddressLinux : IGetProcAddressOS { #region Singleton /// <summary> /// The <see cref="GetGLProcAddressEGL"/> singleton instance. /// </summary> internal static readonly GetProcAddressLinux Instance = new GetProcAddressLinux(); #endregion #region Linux Platform Imports [SuppressMessage("ReSharper", "InconsistentNaming")] static class UnsafeNativeMethods { public const int RTLD_LAZY = 1; public const int RTLD_NOW = 2; [DllImport("dl")] public static extern IntPtr dlopen([MarshalAs(UnmanagedType.LPTStr)] string filename, int flags); [DllImport("dl")] public static extern IntPtr dlsym(IntPtr handle, [MarshalAs(UnmanagedType.LPTStr)] string symbol); [DllImport("dl")] public static extern string dlerror(); } #endregion #region IGetProcAdress Implementation /// <summary> /// Add a path of a directory as additional path for searching libraries. /// </summary> /// <param name="libraryDirPath"> /// A <see cref="String"/> that specify the absolute path of the directory where the libraries are loaded using /// <see cref="GetProcAddress(string, string)"/> method. /// </param> public void AddLibraryDirectory(string libraryDirPath) { } /// <summary> /// Get a function pointer from a library, specified by path. /// </summary> /// <param name="library"> /// A <see cref="String"/> that specifies the path of the library defining the function. /// </param> /// <param name="function"> /// A <see cref="String"/> that specifies the function name. /// </param> /// <returns> /// It returns an <see cref="IntPtr"/> that specifies the address of the function <paramref name="function"/>. /// </returns> public IntPtr GetProcAddress(string library, string function) { IntPtr handle = GetLibraryHandle(library); return GetProcAddress(handle, function); } /// <summary> /// Get a function pointer from a library, specified by handle. /// </summary> /// <param name="library"> /// A <see cref="IntPtr"/> which represents an opaque handle to the library containing the function. /// </param> /// <param name="function"> /// A <see cref="String"/> that specifies the function name. /// </param> /// <returns> /// It returns an <see cref="IntPtr"/> that specifies the address of the function <paramref name="function"/>. /// </returns> private IntPtr GetProcAddress(IntPtr library, string function) { if (library == IntPtr.Zero) throw new ArgumentNullException(nameof(library)); if (function == null) throw new ArgumentNullException(nameof(function)); return UnsafeNativeMethods.dlsym(library, function); } internal static IntPtr GetLibraryHandle(string libraryPath) { return GetLibraryHandle(libraryPath, true); } internal static IntPtr GetLibraryHandle(string libraryPath, bool throws) { IntPtr libraryHandle; if (_LibraryHandles.TryGetValue(libraryPath, out libraryHandle) == false) { if ((libraryHandle = UnsafeNativeMethods.dlopen(libraryPath, UnsafeNativeMethods.RTLD_LAZY)) == IntPtr.Zero) { if (throws) throw new InvalidOperationException($"unable to load library at {libraryPath}", new InvalidOperationException(UnsafeNativeMethods.dlerror())); } _LibraryHandles.Add(libraryPath, libraryHandle); } return libraryHandle; } /// <summary> /// Currently loaded libraries. /// </summary> private static readonly Dictionary<string, IntPtr> _LibraryHandles = new Dictionary<string,IntPtr>(); #endregion } /// <summary> /// Class able to get function pointers on OSX platform. /// </summary> internal class GetProcAddressOSX : IGetProcAddressOS { #region Singleton /// <summary> /// The <see cref="GetProcAddressOSX"/> singleton instance. /// </summary> public static readonly GetProcAddressOSX Instance = new GetProcAddressOSX(); #endregion #region OSX Platform Imports static class UnsafeNativeMethods { [DllImport(Library, EntryPoint = "NSIsSymbolNameDefined")] public static extern bool NSIsSymbolNameDefined(string s); [DllImport(Library, EntryPoint = "NSLookupAndBindSymbol")] public static extern IntPtr NSLookupAndBindSymbol(string s); [DllImport(Library, EntryPoint = "NSAddressOfSymbol")] public static extern IntPtr NSAddressOfSymbol(IntPtr symbol); } #endregion #region IGetProcAddress Implementation /// <summary> /// Add a path of a directory as additional path for searching libraries. /// </summary> /// <param name="libraryDirPath"> /// A <see cref="String"/> that specify the absolute path of the directory where the libraries are loaded using /// <see cref="GetProcAddress(string, string)"/> method. /// </param> public void AddLibraryDirectory(string libraryDirPath) { } /// <summary> /// Get a function pointer from a library, specified by path. /// </summary> /// <param name="library"> /// A <see cref="String"/> that specifies the path of the library defining the function. /// </param> /// <param name="function"> /// A <see cref="String"/> that specifies the function name. /// </param> /// <returns> /// It returns an <see cref="IntPtr"/> that specifies the address of the function <paramref name="function"/>. /// </returns> public IntPtr GetProcAddress(string library, string function) { return GetProcAddressCore(function); } /// <summary> /// Get a function pointer from the OpenGL driver. /// </summary> /// <param name="function"> /// A <see cref="String"/> that specifies the function name. /// </param> /// <returns> /// It returns an <see cref="IntPtr"/> that specifies the address of the function <paramref name="function"/>. /// </returns> public IntPtr GetProcAddressCore(string function) { string fname = "_" + function; if (!UnsafeNativeMethods.NSIsSymbolNameDefined(fname)) return IntPtr.Zero; IntPtr symbol = UnsafeNativeMethods.NSLookupAndBindSymbol(fname); if (symbol != IntPtr.Zero) symbol = UnsafeNativeMethods.NSAddressOfSymbol(symbol); return symbol; } /// <summary> /// The OpenGL library on OSX platform. /// </summary> private const string Library = "libdl.dylib"; #endregion #region IGetGLProcAddress Implementation /// <summary> /// Get a function pointer from the OpenGL driver. /// </summary> /// <param name="function"> /// A <see cref="String"/> that specifies the function name. /// </param> /// <returns> /// It returns an <see cref="IntPtr"/> that specifies the address of the function <paramref name="function"/>. If not /// defined, it returns <see cref="IntPtr.Zero"/>. /// </returns> public IntPtr GetProcAddress(string function) { return GetProcAddressCore(function); } #endregion } /// <summary> /// Class able to get function pointers on different platforms supporting EGL. /// </summary> internal class GetProcAddressEGL : IGetProcAddressOS { #region Singleton /// <summary> /// The <see cref="GetProcAddressEGL"/> singleton instance. /// </summary> public static readonly GetProcAddressEGL Instance = new GetProcAddressEGL(); #endregion #region IGetProcAddress Implementation /// <summary> /// Add a path of a directory as additional path for searching libraries. /// </summary> /// <param name="libraryDirPath"> /// A <see cref="String"/> that specify the absolute path of the directory where the libraries are loaded using /// <see cref="GetProcAddress(string, string)"/> method. /// </param> public void AddLibraryDirectory(string libraryDirPath) { } /// <summary> /// Get a function pointer from a library, specified by path. /// </summary> /// <param name="library"> /// A <see cref="String"/> that specifies the path of the library defining the function. /// </param> /// <param name="function"> /// A <see cref="String"/> that specifies the function name. /// </param> /// <returns> /// It returns an <see cref="IntPtr"/> that specifies the address of the function <paramref name="function"/>. /// </returns> public IntPtr GetProcAddress(string library, string function) { return GetProcAddressCore(function); } /// <summary> /// Static import for eglGetProcAddress. /// </summary> /// <param name="funcname"></param> /// <returns></returns> [DllImport("libEGL.dll", EntryPoint = "eglGetProcAddress")] public static extern IntPtr GetProcAddressCore(string funcname); #endregion } }
32.155867
148
0.696095
[ "MIT" ]
hasali19/OpenGL.Net
Khronos.Net/GetProcAddressOS.cs
18,361
C#
using Camunda.Api.Client.UserTask; using Refit; using System.Collections.Generic; using System.Net.Http; using System.Threading.Tasks; namespace Camunda.Api.Client.Filter { internal interface IFilterRestService { [Get("/filter")] Task<List<FilterInfo.Response>> GetList(QueryDictionary query, int? firstResult, int? maxResults); [Get("/filter/count")] Task<CountResult> GetListCount(QueryDictionary query); [Get("/filter/{id}")] Task<FilterInfo.Response> Get(string id); [Post("/filter/create")] Task<FilterInfo.Response> Create([Body] FilterInfo.Request filterInfo); [Delete("/filter/{id}")] Task Delete(string id); [Put("/filter/{id}")] Task Update(string id, [Body] FilterInfo.Request filterInfo); [Get("/filter/{id}/singleResult")] Task<UserTaskInfo> Execute(string id); [Post("/filter/{id}/list")] Task<List<UserTaskInfo>> ExecuteList(string id, int firstResult, int maxResults, [Body] TaskQuery query); [Post("/filter/{id}/count")] Task<CountResult> ExecuteCount(string id, [Body] TaskQuery query); } }
30.128205
113
0.648511
[ "MIT" ]
Maicelicious/Camunda.Api.Client
Camunda.Api.Client/Filter/IFilterRestService.cs
1,177
C#
// Copyright 2021 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // Generated code. DO NOT EDIT! using gaxgrpc = Google.Api.Gax.Grpc; using wkt = Google.Protobuf.WellKnownTypes; using grpccore = Grpc.Core; using moq = Moq; using st = System.Threading; using stt = System.Threading.Tasks; using xunit = Xunit; namespace Google.Cloud.Dialogflow.V2.Tests { /// <summary>Generated unit tests.</summary> public sealed class GeneratedParticipantsClientTest { [xunit::FactAttribute] public void CreateParticipantRequestObject() { moq::Mock<Participants.ParticipantsClient> mockGrpcClient = new moq::Mock<Participants.ParticipantsClient>(moq::MockBehavior.Strict); CreateParticipantRequest request = new CreateParticipantRequest { ParentAsConversationName = ConversationName.FromProjectConversation("[PROJECT]", "[CONVERSATION]"), Participant = new Participant(), }; Participant expectedResponse = new Participant { ParticipantName = ParticipantName.FromProjectConversationParticipant("[PROJECT]", "[CONVERSATION]", "[PARTICIPANT]"), Role = Participant.Types.Role.HumanAgent, SipRecordingMediaLabel = "sip_recording_media_labela9ddfd5d", DocumentsMetadataFilters = { { "key8a0b6e3c", "value60c16320" }, }, }; mockGrpcClient.Setup(x => x.CreateParticipant(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); ParticipantsClient client = new ParticipantsClientImpl(mockGrpcClient.Object, null); Participant response = client.CreateParticipant(request); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task CreateParticipantRequestObjectAsync() { moq::Mock<Participants.ParticipantsClient> mockGrpcClient = new moq::Mock<Participants.ParticipantsClient>(moq::MockBehavior.Strict); CreateParticipantRequest request = new CreateParticipantRequest { ParentAsConversationName = ConversationName.FromProjectConversation("[PROJECT]", "[CONVERSATION]"), Participant = new Participant(), }; Participant expectedResponse = new Participant { ParticipantName = ParticipantName.FromProjectConversationParticipant("[PROJECT]", "[CONVERSATION]", "[PARTICIPANT]"), Role = Participant.Types.Role.HumanAgent, SipRecordingMediaLabel = "sip_recording_media_labela9ddfd5d", DocumentsMetadataFilters = { { "key8a0b6e3c", "value60c16320" }, }, }; mockGrpcClient.Setup(x => x.CreateParticipantAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<Participant>(stt::Task.FromResult(expectedResponse), null, null, null, null)); ParticipantsClient client = new ParticipantsClientImpl(mockGrpcClient.Object, null); Participant responseCallSettings = await client.CreateParticipantAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); Participant responseCancellationToken = await client.CreateParticipantAsync(request, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void CreateParticipant() { moq::Mock<Participants.ParticipantsClient> mockGrpcClient = new moq::Mock<Participants.ParticipantsClient>(moq::MockBehavior.Strict); CreateParticipantRequest request = new CreateParticipantRequest { ParentAsConversationName = ConversationName.FromProjectConversation("[PROJECT]", "[CONVERSATION]"), Participant = new Participant(), }; Participant expectedResponse = new Participant { ParticipantName = ParticipantName.FromProjectConversationParticipant("[PROJECT]", "[CONVERSATION]", "[PARTICIPANT]"), Role = Participant.Types.Role.HumanAgent, SipRecordingMediaLabel = "sip_recording_media_labela9ddfd5d", DocumentsMetadataFilters = { { "key8a0b6e3c", "value60c16320" }, }, }; mockGrpcClient.Setup(x => x.CreateParticipant(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); ParticipantsClient client = new ParticipantsClientImpl(mockGrpcClient.Object, null); Participant response = client.CreateParticipant(request.Parent, request.Participant); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task CreateParticipantAsync() { moq::Mock<Participants.ParticipantsClient> mockGrpcClient = new moq::Mock<Participants.ParticipantsClient>(moq::MockBehavior.Strict); CreateParticipantRequest request = new CreateParticipantRequest { ParentAsConversationName = ConversationName.FromProjectConversation("[PROJECT]", "[CONVERSATION]"), Participant = new Participant(), }; Participant expectedResponse = new Participant { ParticipantName = ParticipantName.FromProjectConversationParticipant("[PROJECT]", "[CONVERSATION]", "[PARTICIPANT]"), Role = Participant.Types.Role.HumanAgent, SipRecordingMediaLabel = "sip_recording_media_labela9ddfd5d", DocumentsMetadataFilters = { { "key8a0b6e3c", "value60c16320" }, }, }; mockGrpcClient.Setup(x => x.CreateParticipantAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<Participant>(stt::Task.FromResult(expectedResponse), null, null, null, null)); ParticipantsClient client = new ParticipantsClientImpl(mockGrpcClient.Object, null); Participant responseCallSettings = await client.CreateParticipantAsync(request.Parent, request.Participant, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); Participant responseCancellationToken = await client.CreateParticipantAsync(request.Parent, request.Participant, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void CreateParticipantResourceNames() { moq::Mock<Participants.ParticipantsClient> mockGrpcClient = new moq::Mock<Participants.ParticipantsClient>(moq::MockBehavior.Strict); CreateParticipantRequest request = new CreateParticipantRequest { ParentAsConversationName = ConversationName.FromProjectConversation("[PROJECT]", "[CONVERSATION]"), Participant = new Participant(), }; Participant expectedResponse = new Participant { ParticipantName = ParticipantName.FromProjectConversationParticipant("[PROJECT]", "[CONVERSATION]", "[PARTICIPANT]"), Role = Participant.Types.Role.HumanAgent, SipRecordingMediaLabel = "sip_recording_media_labela9ddfd5d", DocumentsMetadataFilters = { { "key8a0b6e3c", "value60c16320" }, }, }; mockGrpcClient.Setup(x => x.CreateParticipant(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); ParticipantsClient client = new ParticipantsClientImpl(mockGrpcClient.Object, null); Participant response = client.CreateParticipant(request.ParentAsConversationName, request.Participant); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task CreateParticipantResourceNamesAsync() { moq::Mock<Participants.ParticipantsClient> mockGrpcClient = new moq::Mock<Participants.ParticipantsClient>(moq::MockBehavior.Strict); CreateParticipantRequest request = new CreateParticipantRequest { ParentAsConversationName = ConversationName.FromProjectConversation("[PROJECT]", "[CONVERSATION]"), Participant = new Participant(), }; Participant expectedResponse = new Participant { ParticipantName = ParticipantName.FromProjectConversationParticipant("[PROJECT]", "[CONVERSATION]", "[PARTICIPANT]"), Role = Participant.Types.Role.HumanAgent, SipRecordingMediaLabel = "sip_recording_media_labela9ddfd5d", DocumentsMetadataFilters = { { "key8a0b6e3c", "value60c16320" }, }, }; mockGrpcClient.Setup(x => x.CreateParticipantAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<Participant>(stt::Task.FromResult(expectedResponse), null, null, null, null)); ParticipantsClient client = new ParticipantsClientImpl(mockGrpcClient.Object, null); Participant responseCallSettings = await client.CreateParticipantAsync(request.ParentAsConversationName, request.Participant, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); Participant responseCancellationToken = await client.CreateParticipantAsync(request.ParentAsConversationName, request.Participant, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void GetParticipantRequestObject() { moq::Mock<Participants.ParticipantsClient> mockGrpcClient = new moq::Mock<Participants.ParticipantsClient>(moq::MockBehavior.Strict); GetParticipantRequest request = new GetParticipantRequest { ParticipantName = ParticipantName.FromProjectConversationParticipant("[PROJECT]", "[CONVERSATION]", "[PARTICIPANT]"), }; Participant expectedResponse = new Participant { ParticipantName = ParticipantName.FromProjectConversationParticipant("[PROJECT]", "[CONVERSATION]", "[PARTICIPANT]"), Role = Participant.Types.Role.HumanAgent, SipRecordingMediaLabel = "sip_recording_media_labela9ddfd5d", DocumentsMetadataFilters = { { "key8a0b6e3c", "value60c16320" }, }, }; mockGrpcClient.Setup(x => x.GetParticipant(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); ParticipantsClient client = new ParticipantsClientImpl(mockGrpcClient.Object, null); Participant response = client.GetParticipant(request); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task GetParticipantRequestObjectAsync() { moq::Mock<Participants.ParticipantsClient> mockGrpcClient = new moq::Mock<Participants.ParticipantsClient>(moq::MockBehavior.Strict); GetParticipantRequest request = new GetParticipantRequest { ParticipantName = ParticipantName.FromProjectConversationParticipant("[PROJECT]", "[CONVERSATION]", "[PARTICIPANT]"), }; Participant expectedResponse = new Participant { ParticipantName = ParticipantName.FromProjectConversationParticipant("[PROJECT]", "[CONVERSATION]", "[PARTICIPANT]"), Role = Participant.Types.Role.HumanAgent, SipRecordingMediaLabel = "sip_recording_media_labela9ddfd5d", DocumentsMetadataFilters = { { "key8a0b6e3c", "value60c16320" }, }, }; mockGrpcClient.Setup(x => x.GetParticipantAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<Participant>(stt::Task.FromResult(expectedResponse), null, null, null, null)); ParticipantsClient client = new ParticipantsClientImpl(mockGrpcClient.Object, null); Participant responseCallSettings = await client.GetParticipantAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); Participant responseCancellationToken = await client.GetParticipantAsync(request, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void GetParticipant() { moq::Mock<Participants.ParticipantsClient> mockGrpcClient = new moq::Mock<Participants.ParticipantsClient>(moq::MockBehavior.Strict); GetParticipantRequest request = new GetParticipantRequest { ParticipantName = ParticipantName.FromProjectConversationParticipant("[PROJECT]", "[CONVERSATION]", "[PARTICIPANT]"), }; Participant expectedResponse = new Participant { ParticipantName = ParticipantName.FromProjectConversationParticipant("[PROJECT]", "[CONVERSATION]", "[PARTICIPANT]"), Role = Participant.Types.Role.HumanAgent, SipRecordingMediaLabel = "sip_recording_media_labela9ddfd5d", DocumentsMetadataFilters = { { "key8a0b6e3c", "value60c16320" }, }, }; mockGrpcClient.Setup(x => x.GetParticipant(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); ParticipantsClient client = new ParticipantsClientImpl(mockGrpcClient.Object, null); Participant response = client.GetParticipant(request.Name); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task GetParticipantAsync() { moq::Mock<Participants.ParticipantsClient> mockGrpcClient = new moq::Mock<Participants.ParticipantsClient>(moq::MockBehavior.Strict); GetParticipantRequest request = new GetParticipantRequest { ParticipantName = ParticipantName.FromProjectConversationParticipant("[PROJECT]", "[CONVERSATION]", "[PARTICIPANT]"), }; Participant expectedResponse = new Participant { ParticipantName = ParticipantName.FromProjectConversationParticipant("[PROJECT]", "[CONVERSATION]", "[PARTICIPANT]"), Role = Participant.Types.Role.HumanAgent, SipRecordingMediaLabel = "sip_recording_media_labela9ddfd5d", DocumentsMetadataFilters = { { "key8a0b6e3c", "value60c16320" }, }, }; mockGrpcClient.Setup(x => x.GetParticipantAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<Participant>(stt::Task.FromResult(expectedResponse), null, null, null, null)); ParticipantsClient client = new ParticipantsClientImpl(mockGrpcClient.Object, null); Participant responseCallSettings = await client.GetParticipantAsync(request.Name, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); Participant responseCancellationToken = await client.GetParticipantAsync(request.Name, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void GetParticipantResourceNames() { moq::Mock<Participants.ParticipantsClient> mockGrpcClient = new moq::Mock<Participants.ParticipantsClient>(moq::MockBehavior.Strict); GetParticipantRequest request = new GetParticipantRequest { ParticipantName = ParticipantName.FromProjectConversationParticipant("[PROJECT]", "[CONVERSATION]", "[PARTICIPANT]"), }; Participant expectedResponse = new Participant { ParticipantName = ParticipantName.FromProjectConversationParticipant("[PROJECT]", "[CONVERSATION]", "[PARTICIPANT]"), Role = Participant.Types.Role.HumanAgent, SipRecordingMediaLabel = "sip_recording_media_labela9ddfd5d", DocumentsMetadataFilters = { { "key8a0b6e3c", "value60c16320" }, }, }; mockGrpcClient.Setup(x => x.GetParticipant(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); ParticipantsClient client = new ParticipantsClientImpl(mockGrpcClient.Object, null); Participant response = client.GetParticipant(request.ParticipantName); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task GetParticipantResourceNamesAsync() { moq::Mock<Participants.ParticipantsClient> mockGrpcClient = new moq::Mock<Participants.ParticipantsClient>(moq::MockBehavior.Strict); GetParticipantRequest request = new GetParticipantRequest { ParticipantName = ParticipantName.FromProjectConversationParticipant("[PROJECT]", "[CONVERSATION]", "[PARTICIPANT]"), }; Participant expectedResponse = new Participant { ParticipantName = ParticipantName.FromProjectConversationParticipant("[PROJECT]", "[CONVERSATION]", "[PARTICIPANT]"), Role = Participant.Types.Role.HumanAgent, SipRecordingMediaLabel = "sip_recording_media_labela9ddfd5d", DocumentsMetadataFilters = { { "key8a0b6e3c", "value60c16320" }, }, }; mockGrpcClient.Setup(x => x.GetParticipantAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<Participant>(stt::Task.FromResult(expectedResponse), null, null, null, null)); ParticipantsClient client = new ParticipantsClientImpl(mockGrpcClient.Object, null); Participant responseCallSettings = await client.GetParticipantAsync(request.ParticipantName, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); Participant responseCancellationToken = await client.GetParticipantAsync(request.ParticipantName, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void UpdateParticipantRequestObject() { moq::Mock<Participants.ParticipantsClient> mockGrpcClient = new moq::Mock<Participants.ParticipantsClient>(moq::MockBehavior.Strict); UpdateParticipantRequest request = new UpdateParticipantRequest { Participant = new Participant(), UpdateMask = new wkt::FieldMask(), }; Participant expectedResponse = new Participant { ParticipantName = ParticipantName.FromProjectConversationParticipant("[PROJECT]", "[CONVERSATION]", "[PARTICIPANT]"), Role = Participant.Types.Role.HumanAgent, SipRecordingMediaLabel = "sip_recording_media_labela9ddfd5d", DocumentsMetadataFilters = { { "key8a0b6e3c", "value60c16320" }, }, }; mockGrpcClient.Setup(x => x.UpdateParticipant(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); ParticipantsClient client = new ParticipantsClientImpl(mockGrpcClient.Object, null); Participant response = client.UpdateParticipant(request); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task UpdateParticipantRequestObjectAsync() { moq::Mock<Participants.ParticipantsClient> mockGrpcClient = new moq::Mock<Participants.ParticipantsClient>(moq::MockBehavior.Strict); UpdateParticipantRequest request = new UpdateParticipantRequest { Participant = new Participant(), UpdateMask = new wkt::FieldMask(), }; Participant expectedResponse = new Participant { ParticipantName = ParticipantName.FromProjectConversationParticipant("[PROJECT]", "[CONVERSATION]", "[PARTICIPANT]"), Role = Participant.Types.Role.HumanAgent, SipRecordingMediaLabel = "sip_recording_media_labela9ddfd5d", DocumentsMetadataFilters = { { "key8a0b6e3c", "value60c16320" }, }, }; mockGrpcClient.Setup(x => x.UpdateParticipantAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<Participant>(stt::Task.FromResult(expectedResponse), null, null, null, null)); ParticipantsClient client = new ParticipantsClientImpl(mockGrpcClient.Object, null); Participant responseCallSettings = await client.UpdateParticipantAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); Participant responseCancellationToken = await client.UpdateParticipantAsync(request, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void UpdateParticipant() { moq::Mock<Participants.ParticipantsClient> mockGrpcClient = new moq::Mock<Participants.ParticipantsClient>(moq::MockBehavior.Strict); UpdateParticipantRequest request = new UpdateParticipantRequest { Participant = new Participant(), UpdateMask = new wkt::FieldMask(), }; Participant expectedResponse = new Participant { ParticipantName = ParticipantName.FromProjectConversationParticipant("[PROJECT]", "[CONVERSATION]", "[PARTICIPANT]"), Role = Participant.Types.Role.HumanAgent, SipRecordingMediaLabel = "sip_recording_media_labela9ddfd5d", DocumentsMetadataFilters = { { "key8a0b6e3c", "value60c16320" }, }, }; mockGrpcClient.Setup(x => x.UpdateParticipant(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); ParticipantsClient client = new ParticipantsClientImpl(mockGrpcClient.Object, null); Participant response = client.UpdateParticipant(request.Participant, request.UpdateMask); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task UpdateParticipantAsync() { moq::Mock<Participants.ParticipantsClient> mockGrpcClient = new moq::Mock<Participants.ParticipantsClient>(moq::MockBehavior.Strict); UpdateParticipantRequest request = new UpdateParticipantRequest { Participant = new Participant(), UpdateMask = new wkt::FieldMask(), }; Participant expectedResponse = new Participant { ParticipantName = ParticipantName.FromProjectConversationParticipant("[PROJECT]", "[CONVERSATION]", "[PARTICIPANT]"), Role = Participant.Types.Role.HumanAgent, SipRecordingMediaLabel = "sip_recording_media_labela9ddfd5d", DocumentsMetadataFilters = { { "key8a0b6e3c", "value60c16320" }, }, }; mockGrpcClient.Setup(x => x.UpdateParticipantAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<Participant>(stt::Task.FromResult(expectedResponse), null, null, null, null)); ParticipantsClient client = new ParticipantsClientImpl(mockGrpcClient.Object, null); Participant responseCallSettings = await client.UpdateParticipantAsync(request.Participant, request.UpdateMask, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); Participant responseCancellationToken = await client.UpdateParticipantAsync(request.Participant, request.UpdateMask, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void AnalyzeContentRequestObject() { moq::Mock<Participants.ParticipantsClient> mockGrpcClient = new moq::Mock<Participants.ParticipantsClient>(moq::MockBehavior.Strict); AnalyzeContentRequest request = new AnalyzeContentRequest { ParticipantAsParticipantName = ParticipantName.FromProjectConversationParticipant("[PROJECT]", "[CONVERSATION]", "[PARTICIPANT]"), ReplyAudioConfig = new OutputAudioConfig(), TextInput = new TextInput(), EventInput = new EventInput(), QueryParams = new QueryParameters(), RequestId = "request_id362c8df6", AssistQueryParams = new AssistQueryParameters(), }; AnalyzeContentResponse expectedResponse = new AnalyzeContentResponse { ReplyText = "reply_text33e99f0a", ReplyAudio = new OutputAudio(), AutomatedAgentReply = new AutomatedAgentReply(), Message = new Message(), HumanAgentSuggestionResults = { new SuggestionResult(), }, EndUserSuggestionResults = { new SuggestionResult(), }, DtmfParameters = new DtmfParameters(), }; mockGrpcClient.Setup(x => x.AnalyzeContent(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); ParticipantsClient client = new ParticipantsClientImpl(mockGrpcClient.Object, null); AnalyzeContentResponse response = client.AnalyzeContent(request); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task AnalyzeContentRequestObjectAsync() { moq::Mock<Participants.ParticipantsClient> mockGrpcClient = new moq::Mock<Participants.ParticipantsClient>(moq::MockBehavior.Strict); AnalyzeContentRequest request = new AnalyzeContentRequest { ParticipantAsParticipantName = ParticipantName.FromProjectConversationParticipant("[PROJECT]", "[CONVERSATION]", "[PARTICIPANT]"), ReplyAudioConfig = new OutputAudioConfig(), TextInput = new TextInput(), EventInput = new EventInput(), QueryParams = new QueryParameters(), RequestId = "request_id362c8df6", AssistQueryParams = new AssistQueryParameters(), }; AnalyzeContentResponse expectedResponse = new AnalyzeContentResponse { ReplyText = "reply_text33e99f0a", ReplyAudio = new OutputAudio(), AutomatedAgentReply = new AutomatedAgentReply(), Message = new Message(), HumanAgentSuggestionResults = { new SuggestionResult(), }, EndUserSuggestionResults = { new SuggestionResult(), }, DtmfParameters = new DtmfParameters(), }; mockGrpcClient.Setup(x => x.AnalyzeContentAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<AnalyzeContentResponse>(stt::Task.FromResult(expectedResponse), null, null, null, null)); ParticipantsClient client = new ParticipantsClientImpl(mockGrpcClient.Object, null); AnalyzeContentResponse responseCallSettings = await client.AnalyzeContentAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); AnalyzeContentResponse responseCancellationToken = await client.AnalyzeContentAsync(request, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void AnalyzeContent1() { moq::Mock<Participants.ParticipantsClient> mockGrpcClient = new moq::Mock<Participants.ParticipantsClient>(moq::MockBehavior.Strict); AnalyzeContentRequest request = new AnalyzeContentRequest { ParticipantAsParticipantName = ParticipantName.FromProjectConversationParticipant("[PROJECT]", "[CONVERSATION]", "[PARTICIPANT]"), TextInput = new TextInput(), }; AnalyzeContentResponse expectedResponse = new AnalyzeContentResponse { ReplyText = "reply_text33e99f0a", ReplyAudio = new OutputAudio(), AutomatedAgentReply = new AutomatedAgentReply(), Message = new Message(), HumanAgentSuggestionResults = { new SuggestionResult(), }, EndUserSuggestionResults = { new SuggestionResult(), }, DtmfParameters = new DtmfParameters(), }; mockGrpcClient.Setup(x => x.AnalyzeContent(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); ParticipantsClient client = new ParticipantsClientImpl(mockGrpcClient.Object, null); AnalyzeContentResponse response = client.AnalyzeContent(request.Participant, request.TextInput); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task AnalyzeContent1Async() { moq::Mock<Participants.ParticipantsClient> mockGrpcClient = new moq::Mock<Participants.ParticipantsClient>(moq::MockBehavior.Strict); AnalyzeContentRequest request = new AnalyzeContentRequest { ParticipantAsParticipantName = ParticipantName.FromProjectConversationParticipant("[PROJECT]", "[CONVERSATION]", "[PARTICIPANT]"), TextInput = new TextInput(), }; AnalyzeContentResponse expectedResponse = new AnalyzeContentResponse { ReplyText = "reply_text33e99f0a", ReplyAudio = new OutputAudio(), AutomatedAgentReply = new AutomatedAgentReply(), Message = new Message(), HumanAgentSuggestionResults = { new SuggestionResult(), }, EndUserSuggestionResults = { new SuggestionResult(), }, DtmfParameters = new DtmfParameters(), }; mockGrpcClient.Setup(x => x.AnalyzeContentAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<AnalyzeContentResponse>(stt::Task.FromResult(expectedResponse), null, null, null, null)); ParticipantsClient client = new ParticipantsClientImpl(mockGrpcClient.Object, null); AnalyzeContentResponse responseCallSettings = await client.AnalyzeContentAsync(request.Participant, request.TextInput, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); AnalyzeContentResponse responseCancellationToken = await client.AnalyzeContentAsync(request.Participant, request.TextInput, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void AnalyzeContent1ResourceNames() { moq::Mock<Participants.ParticipantsClient> mockGrpcClient = new moq::Mock<Participants.ParticipantsClient>(moq::MockBehavior.Strict); AnalyzeContentRequest request = new AnalyzeContentRequest { ParticipantAsParticipantName = ParticipantName.FromProjectConversationParticipant("[PROJECT]", "[CONVERSATION]", "[PARTICIPANT]"), TextInput = new TextInput(), }; AnalyzeContentResponse expectedResponse = new AnalyzeContentResponse { ReplyText = "reply_text33e99f0a", ReplyAudio = new OutputAudio(), AutomatedAgentReply = new AutomatedAgentReply(), Message = new Message(), HumanAgentSuggestionResults = { new SuggestionResult(), }, EndUserSuggestionResults = { new SuggestionResult(), }, DtmfParameters = new DtmfParameters(), }; mockGrpcClient.Setup(x => x.AnalyzeContent(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); ParticipantsClient client = new ParticipantsClientImpl(mockGrpcClient.Object, null); AnalyzeContentResponse response = client.AnalyzeContent(request.ParticipantAsParticipantName, request.TextInput); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task AnalyzeContent1ResourceNamesAsync() { moq::Mock<Participants.ParticipantsClient> mockGrpcClient = new moq::Mock<Participants.ParticipantsClient>(moq::MockBehavior.Strict); AnalyzeContentRequest request = new AnalyzeContentRequest { ParticipantAsParticipantName = ParticipantName.FromProjectConversationParticipant("[PROJECT]", "[CONVERSATION]", "[PARTICIPANT]"), TextInput = new TextInput(), }; AnalyzeContentResponse expectedResponse = new AnalyzeContentResponse { ReplyText = "reply_text33e99f0a", ReplyAudio = new OutputAudio(), AutomatedAgentReply = new AutomatedAgentReply(), Message = new Message(), HumanAgentSuggestionResults = { new SuggestionResult(), }, EndUserSuggestionResults = { new SuggestionResult(), }, DtmfParameters = new DtmfParameters(), }; mockGrpcClient.Setup(x => x.AnalyzeContentAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<AnalyzeContentResponse>(stt::Task.FromResult(expectedResponse), null, null, null, null)); ParticipantsClient client = new ParticipantsClientImpl(mockGrpcClient.Object, null); AnalyzeContentResponse responseCallSettings = await client.AnalyzeContentAsync(request.ParticipantAsParticipantName, request.TextInput, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); AnalyzeContentResponse responseCancellationToken = await client.AnalyzeContentAsync(request.ParticipantAsParticipantName, request.TextInput, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void AnalyzeContent2() { moq::Mock<Participants.ParticipantsClient> mockGrpcClient = new moq::Mock<Participants.ParticipantsClient>(moq::MockBehavior.Strict); AnalyzeContentRequest request = new AnalyzeContentRequest { ParticipantAsParticipantName = ParticipantName.FromProjectConversationParticipant("[PROJECT]", "[CONVERSATION]", "[PARTICIPANT]"), EventInput = new EventInput(), }; AnalyzeContentResponse expectedResponse = new AnalyzeContentResponse { ReplyText = "reply_text33e99f0a", ReplyAudio = new OutputAudio(), AutomatedAgentReply = new AutomatedAgentReply(), Message = new Message(), HumanAgentSuggestionResults = { new SuggestionResult(), }, EndUserSuggestionResults = { new SuggestionResult(), }, DtmfParameters = new DtmfParameters(), }; mockGrpcClient.Setup(x => x.AnalyzeContent(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); ParticipantsClient client = new ParticipantsClientImpl(mockGrpcClient.Object, null); AnalyzeContentResponse response = client.AnalyzeContent(request.Participant, request.EventInput); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task AnalyzeContent2Async() { moq::Mock<Participants.ParticipantsClient> mockGrpcClient = new moq::Mock<Participants.ParticipantsClient>(moq::MockBehavior.Strict); AnalyzeContentRequest request = new AnalyzeContentRequest { ParticipantAsParticipantName = ParticipantName.FromProjectConversationParticipant("[PROJECT]", "[CONVERSATION]", "[PARTICIPANT]"), EventInput = new EventInput(), }; AnalyzeContentResponse expectedResponse = new AnalyzeContentResponse { ReplyText = "reply_text33e99f0a", ReplyAudio = new OutputAudio(), AutomatedAgentReply = new AutomatedAgentReply(), Message = new Message(), HumanAgentSuggestionResults = { new SuggestionResult(), }, EndUserSuggestionResults = { new SuggestionResult(), }, DtmfParameters = new DtmfParameters(), }; mockGrpcClient.Setup(x => x.AnalyzeContentAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<AnalyzeContentResponse>(stt::Task.FromResult(expectedResponse), null, null, null, null)); ParticipantsClient client = new ParticipantsClientImpl(mockGrpcClient.Object, null); AnalyzeContentResponse responseCallSettings = await client.AnalyzeContentAsync(request.Participant, request.EventInput, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); AnalyzeContentResponse responseCancellationToken = await client.AnalyzeContentAsync(request.Participant, request.EventInput, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void AnalyzeContent2ResourceNames() { moq::Mock<Participants.ParticipantsClient> mockGrpcClient = new moq::Mock<Participants.ParticipantsClient>(moq::MockBehavior.Strict); AnalyzeContentRequest request = new AnalyzeContentRequest { ParticipantAsParticipantName = ParticipantName.FromProjectConversationParticipant("[PROJECT]", "[CONVERSATION]", "[PARTICIPANT]"), EventInput = new EventInput(), }; AnalyzeContentResponse expectedResponse = new AnalyzeContentResponse { ReplyText = "reply_text33e99f0a", ReplyAudio = new OutputAudio(), AutomatedAgentReply = new AutomatedAgentReply(), Message = new Message(), HumanAgentSuggestionResults = { new SuggestionResult(), }, EndUserSuggestionResults = { new SuggestionResult(), }, DtmfParameters = new DtmfParameters(), }; mockGrpcClient.Setup(x => x.AnalyzeContent(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); ParticipantsClient client = new ParticipantsClientImpl(mockGrpcClient.Object, null); AnalyzeContentResponse response = client.AnalyzeContent(request.ParticipantAsParticipantName, request.EventInput); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task AnalyzeContent2ResourceNamesAsync() { moq::Mock<Participants.ParticipantsClient> mockGrpcClient = new moq::Mock<Participants.ParticipantsClient>(moq::MockBehavior.Strict); AnalyzeContentRequest request = new AnalyzeContentRequest { ParticipantAsParticipantName = ParticipantName.FromProjectConversationParticipant("[PROJECT]", "[CONVERSATION]", "[PARTICIPANT]"), EventInput = new EventInput(), }; AnalyzeContentResponse expectedResponse = new AnalyzeContentResponse { ReplyText = "reply_text33e99f0a", ReplyAudio = new OutputAudio(), AutomatedAgentReply = new AutomatedAgentReply(), Message = new Message(), HumanAgentSuggestionResults = { new SuggestionResult(), }, EndUserSuggestionResults = { new SuggestionResult(), }, DtmfParameters = new DtmfParameters(), }; mockGrpcClient.Setup(x => x.AnalyzeContentAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<AnalyzeContentResponse>(stt::Task.FromResult(expectedResponse), null, null, null, null)); ParticipantsClient client = new ParticipantsClientImpl(mockGrpcClient.Object, null); AnalyzeContentResponse responseCallSettings = await client.AnalyzeContentAsync(request.ParticipantAsParticipantName, request.EventInput, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); AnalyzeContentResponse responseCancellationToken = await client.AnalyzeContentAsync(request.ParticipantAsParticipantName, request.EventInput, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void SuggestArticlesRequestObject() { moq::Mock<Participants.ParticipantsClient> mockGrpcClient = new moq::Mock<Participants.ParticipantsClient>(moq::MockBehavior.Strict); SuggestArticlesRequest request = new SuggestArticlesRequest { ParentAsParticipantName = ParticipantName.FromProjectConversationParticipant("[PROJECT]", "[CONVERSATION]", "[PARTICIPANT]"), LatestMessageAsMessageName = MessageName.FromProjectConversationMessage("[PROJECT]", "[CONVERSATION]", "[MESSAGE]"), ContextSize = 1799545581, AssistQueryParams = new AssistQueryParameters(), }; SuggestArticlesResponse expectedResponse = new SuggestArticlesResponse { ArticleAnswers = { new ArticleAnswer(), }, LatestMessage = "latest_message4af0b23b", ContextSize = 1799545581, }; mockGrpcClient.Setup(x => x.SuggestArticles(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); ParticipantsClient client = new ParticipantsClientImpl(mockGrpcClient.Object, null); SuggestArticlesResponse response = client.SuggestArticles(request); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task SuggestArticlesRequestObjectAsync() { moq::Mock<Participants.ParticipantsClient> mockGrpcClient = new moq::Mock<Participants.ParticipantsClient>(moq::MockBehavior.Strict); SuggestArticlesRequest request = new SuggestArticlesRequest { ParentAsParticipantName = ParticipantName.FromProjectConversationParticipant("[PROJECT]", "[CONVERSATION]", "[PARTICIPANT]"), LatestMessageAsMessageName = MessageName.FromProjectConversationMessage("[PROJECT]", "[CONVERSATION]", "[MESSAGE]"), ContextSize = 1799545581, AssistQueryParams = new AssistQueryParameters(), }; SuggestArticlesResponse expectedResponse = new SuggestArticlesResponse { ArticleAnswers = { new ArticleAnswer(), }, LatestMessage = "latest_message4af0b23b", ContextSize = 1799545581, }; mockGrpcClient.Setup(x => x.SuggestArticlesAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<SuggestArticlesResponse>(stt::Task.FromResult(expectedResponse), null, null, null, null)); ParticipantsClient client = new ParticipantsClientImpl(mockGrpcClient.Object, null); SuggestArticlesResponse responseCallSettings = await client.SuggestArticlesAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); SuggestArticlesResponse responseCancellationToken = await client.SuggestArticlesAsync(request, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void SuggestArticles() { moq::Mock<Participants.ParticipantsClient> mockGrpcClient = new moq::Mock<Participants.ParticipantsClient>(moq::MockBehavior.Strict); SuggestArticlesRequest request = new SuggestArticlesRequest { ParentAsParticipantName = ParticipantName.FromProjectConversationParticipant("[PROJECT]", "[CONVERSATION]", "[PARTICIPANT]"), }; SuggestArticlesResponse expectedResponse = new SuggestArticlesResponse { ArticleAnswers = { new ArticleAnswer(), }, LatestMessage = "latest_message4af0b23b", ContextSize = 1799545581, }; mockGrpcClient.Setup(x => x.SuggestArticles(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); ParticipantsClient client = new ParticipantsClientImpl(mockGrpcClient.Object, null); SuggestArticlesResponse response = client.SuggestArticles(request.Parent); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task SuggestArticlesAsync() { moq::Mock<Participants.ParticipantsClient> mockGrpcClient = new moq::Mock<Participants.ParticipantsClient>(moq::MockBehavior.Strict); SuggestArticlesRequest request = new SuggestArticlesRequest { ParentAsParticipantName = ParticipantName.FromProjectConversationParticipant("[PROJECT]", "[CONVERSATION]", "[PARTICIPANT]"), }; SuggestArticlesResponse expectedResponse = new SuggestArticlesResponse { ArticleAnswers = { new ArticleAnswer(), }, LatestMessage = "latest_message4af0b23b", ContextSize = 1799545581, }; mockGrpcClient.Setup(x => x.SuggestArticlesAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<SuggestArticlesResponse>(stt::Task.FromResult(expectedResponse), null, null, null, null)); ParticipantsClient client = new ParticipantsClientImpl(mockGrpcClient.Object, null); SuggestArticlesResponse responseCallSettings = await client.SuggestArticlesAsync(request.Parent, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); SuggestArticlesResponse responseCancellationToken = await client.SuggestArticlesAsync(request.Parent, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void SuggestArticlesResourceNames() { moq::Mock<Participants.ParticipantsClient> mockGrpcClient = new moq::Mock<Participants.ParticipantsClient>(moq::MockBehavior.Strict); SuggestArticlesRequest request = new SuggestArticlesRequest { ParentAsParticipantName = ParticipantName.FromProjectConversationParticipant("[PROJECT]", "[CONVERSATION]", "[PARTICIPANT]"), }; SuggestArticlesResponse expectedResponse = new SuggestArticlesResponse { ArticleAnswers = { new ArticleAnswer(), }, LatestMessage = "latest_message4af0b23b", ContextSize = 1799545581, }; mockGrpcClient.Setup(x => x.SuggestArticles(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); ParticipantsClient client = new ParticipantsClientImpl(mockGrpcClient.Object, null); SuggestArticlesResponse response = client.SuggestArticles(request.ParentAsParticipantName); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task SuggestArticlesResourceNamesAsync() { moq::Mock<Participants.ParticipantsClient> mockGrpcClient = new moq::Mock<Participants.ParticipantsClient>(moq::MockBehavior.Strict); SuggestArticlesRequest request = new SuggestArticlesRequest { ParentAsParticipantName = ParticipantName.FromProjectConversationParticipant("[PROJECT]", "[CONVERSATION]", "[PARTICIPANT]"), }; SuggestArticlesResponse expectedResponse = new SuggestArticlesResponse { ArticleAnswers = { new ArticleAnswer(), }, LatestMessage = "latest_message4af0b23b", ContextSize = 1799545581, }; mockGrpcClient.Setup(x => x.SuggestArticlesAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<SuggestArticlesResponse>(stt::Task.FromResult(expectedResponse), null, null, null, null)); ParticipantsClient client = new ParticipantsClientImpl(mockGrpcClient.Object, null); SuggestArticlesResponse responseCallSettings = await client.SuggestArticlesAsync(request.ParentAsParticipantName, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); SuggestArticlesResponse responseCancellationToken = await client.SuggestArticlesAsync(request.ParentAsParticipantName, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void SuggestFaqAnswersRequestObject() { moq::Mock<Participants.ParticipantsClient> mockGrpcClient = new moq::Mock<Participants.ParticipantsClient>(moq::MockBehavior.Strict); SuggestFaqAnswersRequest request = new SuggestFaqAnswersRequest { ParentAsParticipantName = ParticipantName.FromProjectConversationParticipant("[PROJECT]", "[CONVERSATION]", "[PARTICIPANT]"), LatestMessageAsMessageName = MessageName.FromProjectConversationMessage("[PROJECT]", "[CONVERSATION]", "[MESSAGE]"), ContextSize = 1799545581, AssistQueryParams = new AssistQueryParameters(), }; SuggestFaqAnswersResponse expectedResponse = new SuggestFaqAnswersResponse { FaqAnswers = { new FaqAnswer(), }, LatestMessage = "latest_message4af0b23b", ContextSize = 1799545581, }; mockGrpcClient.Setup(x => x.SuggestFaqAnswers(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); ParticipantsClient client = new ParticipantsClientImpl(mockGrpcClient.Object, null); SuggestFaqAnswersResponse response = client.SuggestFaqAnswers(request); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task SuggestFaqAnswersRequestObjectAsync() { moq::Mock<Participants.ParticipantsClient> mockGrpcClient = new moq::Mock<Participants.ParticipantsClient>(moq::MockBehavior.Strict); SuggestFaqAnswersRequest request = new SuggestFaqAnswersRequest { ParentAsParticipantName = ParticipantName.FromProjectConversationParticipant("[PROJECT]", "[CONVERSATION]", "[PARTICIPANT]"), LatestMessageAsMessageName = MessageName.FromProjectConversationMessage("[PROJECT]", "[CONVERSATION]", "[MESSAGE]"), ContextSize = 1799545581, AssistQueryParams = new AssistQueryParameters(), }; SuggestFaqAnswersResponse expectedResponse = new SuggestFaqAnswersResponse { FaqAnswers = { new FaqAnswer(), }, LatestMessage = "latest_message4af0b23b", ContextSize = 1799545581, }; mockGrpcClient.Setup(x => x.SuggestFaqAnswersAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<SuggestFaqAnswersResponse>(stt::Task.FromResult(expectedResponse), null, null, null, null)); ParticipantsClient client = new ParticipantsClientImpl(mockGrpcClient.Object, null); SuggestFaqAnswersResponse responseCallSettings = await client.SuggestFaqAnswersAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); SuggestFaqAnswersResponse responseCancellationToken = await client.SuggestFaqAnswersAsync(request, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void SuggestFaqAnswers() { moq::Mock<Participants.ParticipantsClient> mockGrpcClient = new moq::Mock<Participants.ParticipantsClient>(moq::MockBehavior.Strict); SuggestFaqAnswersRequest request = new SuggestFaqAnswersRequest { ParentAsParticipantName = ParticipantName.FromProjectConversationParticipant("[PROJECT]", "[CONVERSATION]", "[PARTICIPANT]"), }; SuggestFaqAnswersResponse expectedResponse = new SuggestFaqAnswersResponse { FaqAnswers = { new FaqAnswer(), }, LatestMessage = "latest_message4af0b23b", ContextSize = 1799545581, }; mockGrpcClient.Setup(x => x.SuggestFaqAnswers(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); ParticipantsClient client = new ParticipantsClientImpl(mockGrpcClient.Object, null); SuggestFaqAnswersResponse response = client.SuggestFaqAnswers(request.Parent); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task SuggestFaqAnswersAsync() { moq::Mock<Participants.ParticipantsClient> mockGrpcClient = new moq::Mock<Participants.ParticipantsClient>(moq::MockBehavior.Strict); SuggestFaqAnswersRequest request = new SuggestFaqAnswersRequest { ParentAsParticipantName = ParticipantName.FromProjectConversationParticipant("[PROJECT]", "[CONVERSATION]", "[PARTICIPANT]"), }; SuggestFaqAnswersResponse expectedResponse = new SuggestFaqAnswersResponse { FaqAnswers = { new FaqAnswer(), }, LatestMessage = "latest_message4af0b23b", ContextSize = 1799545581, }; mockGrpcClient.Setup(x => x.SuggestFaqAnswersAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<SuggestFaqAnswersResponse>(stt::Task.FromResult(expectedResponse), null, null, null, null)); ParticipantsClient client = new ParticipantsClientImpl(mockGrpcClient.Object, null); SuggestFaqAnswersResponse responseCallSettings = await client.SuggestFaqAnswersAsync(request.Parent, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); SuggestFaqAnswersResponse responseCancellationToken = await client.SuggestFaqAnswersAsync(request.Parent, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void SuggestFaqAnswersResourceNames() { moq::Mock<Participants.ParticipantsClient> mockGrpcClient = new moq::Mock<Participants.ParticipantsClient>(moq::MockBehavior.Strict); SuggestFaqAnswersRequest request = new SuggestFaqAnswersRequest { ParentAsParticipantName = ParticipantName.FromProjectConversationParticipant("[PROJECT]", "[CONVERSATION]", "[PARTICIPANT]"), }; SuggestFaqAnswersResponse expectedResponse = new SuggestFaqAnswersResponse { FaqAnswers = { new FaqAnswer(), }, LatestMessage = "latest_message4af0b23b", ContextSize = 1799545581, }; mockGrpcClient.Setup(x => x.SuggestFaqAnswers(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); ParticipantsClient client = new ParticipantsClientImpl(mockGrpcClient.Object, null); SuggestFaqAnswersResponse response = client.SuggestFaqAnswers(request.ParentAsParticipantName); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task SuggestFaqAnswersResourceNamesAsync() { moq::Mock<Participants.ParticipantsClient> mockGrpcClient = new moq::Mock<Participants.ParticipantsClient>(moq::MockBehavior.Strict); SuggestFaqAnswersRequest request = new SuggestFaqAnswersRequest { ParentAsParticipantName = ParticipantName.FromProjectConversationParticipant("[PROJECT]", "[CONVERSATION]", "[PARTICIPANT]"), }; SuggestFaqAnswersResponse expectedResponse = new SuggestFaqAnswersResponse { FaqAnswers = { new FaqAnswer(), }, LatestMessage = "latest_message4af0b23b", ContextSize = 1799545581, }; mockGrpcClient.Setup(x => x.SuggestFaqAnswersAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<SuggestFaqAnswersResponse>(stt::Task.FromResult(expectedResponse), null, null, null, null)); ParticipantsClient client = new ParticipantsClientImpl(mockGrpcClient.Object, null); SuggestFaqAnswersResponse responseCallSettings = await client.SuggestFaqAnswersAsync(request.ParentAsParticipantName, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); SuggestFaqAnswersResponse responseCancellationToken = await client.SuggestFaqAnswersAsync(request.ParentAsParticipantName, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } } }
57.018437
242
0.637549
[ "Apache-2.0" ]
amanda-tarafa/google-cloud-dotnet
apis/Google.Cloud.Dialogflow.V2/Google.Cloud.Dialogflow.V2.Tests/ParticipantsClientTest.g.cs
64,944
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace IndicesNome { class Program { static void Main(string[] args) { /*Leia uma matriz de tamanho 3 x ? contendo as letras do Alfabeto Maiúsculas na linha 0 seguida das letras minúsculas na linha 1 e os números de 0 a 9. * Faça um programa que mostre os índices da Matriz que formam seu nome e o seu RG. char[][] matriz = { {'A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T', 'U','V','W','X','Y','Z'}, {'a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w', 'x','y','z'}, {'0','1','2','3','4','5','6','7','8','9','-','.',' '} }; // Inicializar o array com os caracteres que formam seus nomes e números // Por exemplo, Cris seria formado pelos seguintes caracteres: char[][] dados = new char[2][]; char[] nome = "Cristiane Tuji".toCharArray(); char[] RG = "12.345.678-9".toCharArray(); dados[0] = nome; dados[1] = RG; String[] indices = {"Índices do nome: ","Índices do RG: "}; // Criar o código que percorra o array contendo seus dados e busque os índices de cada item na matriz. Para percorrer uma matriz são necessários dois for. Para percorrer duas matrizes são necessários 4 for.*/ char[][] matriz = { new char[] {'A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T', 'U','V','W','X','Y','Z'}, new char[] {'a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w', 'x','y','z'}, new char[] {'0','1','2','3','4','5','6','7','8','9','-','.',' ','x'} }; char[][] dados = new char[2][]; char[] nome = "Daniel Spósito".ToCharArray(); char[] RG = "34.347.251-x".ToCharArray(); dados[0] = nome; dados[1] = RG; for (int i=0; i<dados.Length;i++) { for (int y = 0; y< dados[i].Length; y++) { for (int z = 0; z < matriz.Length; z++) { for (int w = 0; w < matriz[z].Length; w++) { if (dados[i][y]==matriz[z][w]) { Console.WriteLine(dados[i][y]+" está na coordenada " + z +" "+ w +" da array "); } } } } } Console.ReadKey(); } } }
42.52381
164
0.433371
[ "MIT" ]
danielspositocoelho/DS-EtecAlbertEinstein-Programacao_e_Algoritmos
Matrizes/IndicesNome/Program.cs
2,697
C#
namespace Microsoft.Azure.PowerShell.Cmdlets.DataProtection.Models.Api202101 { using Microsoft.Azure.PowerShell.Cmdlets.DataProtection.Runtime.PowerShell; /// <summary>CheckNameAvailability Request</summary> [System.ComponentModel.TypeConverter(typeof(CheckNameAvailabilityRequestTypeConverter))] public partial class CheckNameAvailabilityRequest { /// <summary> /// <c>AfterDeserializeDictionary</c> will be called after the deserialization has finished, allowing customization of the /// object before it is returned. Implement this method in a partial class to enable this behavior /// </summary> /// <param name="content">The global::System.Collections.IDictionary content that should be used.</param> partial void AfterDeserializeDictionary(global::System.Collections.IDictionary content); /// <summary> /// <c>AfterDeserializePSObject</c> will be called after the deserialization has finished, allowing customization of the object /// before it is returned. Implement this method in a partial class to enable this behavior /// </summary> /// <param name="content">The global::System.Management.Automation.PSObject content that should be used.</param> partial void AfterDeserializePSObject(global::System.Management.Automation.PSObject content); /// <summary> /// <c>BeforeDeserializeDictionary</c> will be called before the deserialization has commenced, allowing complete customization /// of the object before it is deserialized. /// If you wish to disable the default deserialization entirely, return <c>true</c> in the <see "returnNow" /> output parameter. /// Implement this method in a partial class to enable this behavior. /// </summary> /// <param name="content">The global::System.Collections.IDictionary content that should be used.</param> /// <param name="returnNow">Determines if the rest of the serialization should be processed, or if the method should return /// instantly.</param> partial void BeforeDeserializeDictionary(global::System.Collections.IDictionary content, ref bool returnNow); /// <summary> /// <c>BeforeDeserializePSObject</c> will be called before the deserialization has commenced, allowing complete customization /// of the object before it is deserialized. /// If you wish to disable the default deserialization entirely, return <c>true</c> in the <see "returnNow" /> output parameter. /// Implement this method in a partial class to enable this behavior. /// </summary> /// <param name="content">The global::System.Management.Automation.PSObject content that should be used.</param> /// <param name="returnNow">Determines if the rest of the serialization should be processed, or if the method should return /// instantly.</param> partial void BeforeDeserializePSObject(global::System.Management.Automation.PSObject content, ref bool returnNow); /// <summary> /// Deserializes a <see cref="global::System.Collections.IDictionary" /> into a new instance of <see cref="Microsoft.Azure.PowerShell.Cmdlets.DataProtection.Models.Api202101.CheckNameAvailabilityRequest" /// />. /// </summary> /// <param name="content">The global::System.Collections.IDictionary content that should be used.</param> internal CheckNameAvailabilityRequest(global::System.Collections.IDictionary content) { bool returnNow = false; BeforeDeserializeDictionary(content, ref returnNow); if (returnNow) { return; } // actually deserialize ((Microsoft.Azure.PowerShell.Cmdlets.DataProtection.Models.Api202101.ICheckNameAvailabilityRequestInternal)this).Name = (string) content.GetValueForProperty("Name",((Microsoft.Azure.PowerShell.Cmdlets.DataProtection.Models.Api202101.ICheckNameAvailabilityRequestInternal)this).Name, global::System.Convert.ToString); ((Microsoft.Azure.PowerShell.Cmdlets.DataProtection.Models.Api202101.ICheckNameAvailabilityRequestInternal)this).Type = (string) content.GetValueForProperty("Type",((Microsoft.Azure.PowerShell.Cmdlets.DataProtection.Models.Api202101.ICheckNameAvailabilityRequestInternal)this).Type, global::System.Convert.ToString); AfterDeserializeDictionary(content); } /// <summary> /// Deserializes a <see cref="global::System.Management.Automation.PSObject" /> into a new instance of <see cref="Microsoft.Azure.PowerShell.Cmdlets.DataProtection.Models.Api202101.CheckNameAvailabilityRequest" /// />. /// </summary> /// <param name="content">The global::System.Management.Automation.PSObject content that should be used.</param> internal CheckNameAvailabilityRequest(global::System.Management.Automation.PSObject content) { bool returnNow = false; BeforeDeserializePSObject(content, ref returnNow); if (returnNow) { return; } // actually deserialize ((Microsoft.Azure.PowerShell.Cmdlets.DataProtection.Models.Api202101.ICheckNameAvailabilityRequestInternal)this).Name = (string) content.GetValueForProperty("Name",((Microsoft.Azure.PowerShell.Cmdlets.DataProtection.Models.Api202101.ICheckNameAvailabilityRequestInternal)this).Name, global::System.Convert.ToString); ((Microsoft.Azure.PowerShell.Cmdlets.DataProtection.Models.Api202101.ICheckNameAvailabilityRequestInternal)this).Type = (string) content.GetValueForProperty("Type",((Microsoft.Azure.PowerShell.Cmdlets.DataProtection.Models.Api202101.ICheckNameAvailabilityRequestInternal)this).Type, global::System.Convert.ToString); AfterDeserializePSObject(content); } /// <summary> /// Deserializes a <see cref="global::System.Collections.IDictionary" /> into an instance of <see cref="Microsoft.Azure.PowerShell.Cmdlets.DataProtection.Models.Api202101.CheckNameAvailabilityRequest" /// />. /// </summary> /// <param name="content">The global::System.Collections.IDictionary content that should be used.</param> /// <returns> /// an instance of <see cref="Microsoft.Azure.PowerShell.Cmdlets.DataProtection.Models.Api202101.ICheckNameAvailabilityRequest" /// />. /// </returns> public static Microsoft.Azure.PowerShell.Cmdlets.DataProtection.Models.Api202101.ICheckNameAvailabilityRequest DeserializeFromDictionary(global::System.Collections.IDictionary content) { return new CheckNameAvailabilityRequest(content); } /// <summary> /// Deserializes a <see cref="global::System.Management.Automation.PSObject" /> into an instance of <see cref="Microsoft.Azure.PowerShell.Cmdlets.DataProtection.Models.Api202101.CheckNameAvailabilityRequest" /// />. /// </summary> /// <param name="content">The global::System.Management.Automation.PSObject content that should be used.</param> /// <returns> /// an instance of <see cref="Microsoft.Azure.PowerShell.Cmdlets.DataProtection.Models.Api202101.ICheckNameAvailabilityRequest" /// />. /// </returns> public static Microsoft.Azure.PowerShell.Cmdlets.DataProtection.Models.Api202101.ICheckNameAvailabilityRequest DeserializeFromPSObject(global::System.Management.Automation.PSObject content) { return new CheckNameAvailabilityRequest(content); } /// <summary> /// Creates a new instance of <see cref="CheckNameAvailabilityRequest" />, deserializing the content from a json string. /// </summary> /// <param name="jsonText">a string containing a JSON serialized instance of this model.</param> /// <returns>an instance of the <see cref="className" /> model class.</returns> public static Microsoft.Azure.PowerShell.Cmdlets.DataProtection.Models.Api202101.ICheckNameAvailabilityRequest FromJsonString(string jsonText) => FromJson(Microsoft.Azure.PowerShell.Cmdlets.DataProtection.Runtime.Json.JsonNode.Parse(jsonText)); /// <summary>Serializes this instance to a json string.</summary> /// <returns>a <see cref="System.String" /> containing this model serialized to JSON text.</returns> public string ToJsonString() => ToJson(null, Microsoft.Azure.PowerShell.Cmdlets.DataProtection.Runtime.SerializationMode.IncludeAll)?.ToString(); } /// CheckNameAvailability Request [System.ComponentModel.TypeConverter(typeof(CheckNameAvailabilityRequestTypeConverter))] public partial interface ICheckNameAvailabilityRequest { } }
66.511111
329
0.702083
[ "MIT" ]
AverageDesigner/azure-powershell
src/DataProtection/generated/api/Models/Api202101/CheckNameAvailabilityRequest.PowerShell.cs
8,845
C#
using System; using System.Collections.Generic; using System.Linq; namespace Caomei.Core.Extensions { public static class DistinctExtensions { public static IEnumerable<T> Distinct<T, V>(this IEnumerable<T> source, Func<T, V> keySelector) { return source.Distinct(new CommonEqualityComparer<T, V>(keySelector)); } } }
26.142857
103
0.68306
[ "MIT" ]
suncaomei/CaomeiTemplate_WTM_Blazor
Caomie.Core/Extensions/DistinctExtension.cs
366
C#
using System.Collections.Generic; using System.Net; using System.Net.Http; using System.Threading.Tasks; using Microsoft.Extensions.Configuration; using NUnit.Framework; using Shouldly; namespace Stackage.Core.Tests.DefaultMiddleware.Readiness { public class alternate_endpoint : middleware_scenario { private HttpResponseMessage _response; private string _content; [OneTimeSetUp] public async Task setup_scenario() { _response = await TestService.GetAsync("/is-ready"); _content = await _response.Content.ReadAsStringAsync(); } protected override void ConfigureConfiguration(IConfigurationBuilder configurationBuilder) { base.ConfigureConfiguration(configurationBuilder); configurationBuilder .AddInMemoryCollection(new Dictionary<string, string> { {"STACKAGE:HEALTH:READINESSENDPOINT", "/is-ready"} }); } [Test] public void should_return_status_code_200() { _response.StatusCode.ShouldBe(HttpStatusCode.OK); } [Test] public void should_return_content_healthy() { _content.ShouldBe("Healthy"); } [Test] public void should_return_content_type_text_plain() { _response.Content.Headers.ContentType.MediaType.ShouldBe("text/plain"); } } }
26.245283
96
0.672178
[ "MIT" ]
concilify/stackage-core-nuget
package/Stackage.Core.Tests/DefaultMiddleware/Readiness/alternate_endpoint.cs
1,391
C#
// *** WARNING: this file was generated by the Pulumi SDK Generator. *** // *** Do not edit by hand unless you're certain you know what you are doing! *** using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Threading.Tasks; using Pulumi.Serialization; namespace Pulumi.AzureNative.DataCatalog.Latest.Inputs { /// <summary> /// User principals. /// </summary> public sealed class PrincipalsArgs : Pulumi.ResourceArgs { /// <summary> /// Object Id for the user /// </summary> [Input("objectId")] public Input<string>? ObjectId { get; set; } /// <summary> /// UPN of the user. /// </summary> [Input("upn")] public Input<string>? Upn { get; set; } public PrincipalsArgs() { } } }
24.4
81
0.593677
[ "Apache-2.0" ]
pulumi-bot/pulumi-azure-native
sdk/dotnet/DataCatalog/Latest/Inputs/PrincipalsArgs.cs
854
C#
using System.Collections.Generic; using FluentAssertions; using Xunit; namespace Atc.Tests.Extensions { public class ReadOnlyListExtensionsTests { [Theory] [InlineData(15, new[] { "a", "b", "c", "d" })] public void GetUniqueCombinations(int expected, string[] input) { // Act var actual = input.GetUniqueCombinations(); // Assert actual.Should().NotBeNull().And.HaveCount(expected); } [Theory] [InlineData(15, new[] { "a", "b", "c", "d" })] public void GetUniqueCombinationsAsCommaSeparated(int expected, string[] input) { // Act var actual = input.GetUniqueCombinationsAsCommaSeparated(); // Assert actual.Should().NotBeNull().And.HaveCount(expected); } [Theory] [InlineData(16, new[] { "a", "b", "c", "d" })] public void GetPowerSet(int expected, string[] input) { // Act var actual = input.GetPowerSet(); // Assert actual.Should().NotBeNull().And.HaveCount(expected); } } }
27.595238
87
0.540121
[ "MIT" ]
TomMalow/atc
test/Atc.Tests/Extensions/ReadOnlyListExtensionsTests.cs
1,161
C#
using System; using System.Reflection; using System.Runtime.InteropServices; using System.Runtime.CompilerServices; // 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("AWSSDK.CodeArtifact")] #if BCL35 [assembly: AssemblyDescription("The Amazon Web Services SDK for .NET (3.5) - CodeArtifact. Added support for AWS CodeArtifact.")] #elif BCL45 [assembly: AssemblyDescription("The Amazon Web Services SDK for .NET (4.5) - CodeArtifact. Added support for AWS CodeArtifact.")] #elif NETSTANDARD20 [assembly: AssemblyDescription("The Amazon Web Services SDK for .NET (NetStandard 2.0) - CodeArtifact. Added support for AWS CodeArtifact.")] #elif NETCOREAPP3_1 [assembly: AssemblyDescription("The Amazon Web Services SDK for .NET (.NET Core 3.1) - CodeArtifact. Added support for AWS CodeArtifact.")] #else #error Unknown platform constant - unable to set correct AssemblyDescription #endif [assembly: AssemblyConfiguration("")] [assembly: AssemblyProduct("Amazon Web Services SDK for .NET")] [assembly: AssemblyCompany("Amazon.com, Inc")] [assembly: AssemblyCopyright("Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.")] [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)] // 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("3.3")] [assembly: AssemblyFileVersion("3.7.0.114")] [assembly: System.CLSCompliant(true)] #if BCL [assembly: System.Security.AllowPartiallyTrustedCallers] #endif
41.686275
141
0.761994
[ "Apache-2.0" ]
pcameron-/aws-sdk-net
sdk/src/Services/CodeArtifact/Properties/AssemblyInfo.cs
2,126
C#
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.RazorPages; using Microsoft.Extensions.Logging; using presentation.Model; using presentation.Services; namespace presentation.Pages.Submissions { public class IndexModel : PageModel { public IndexModel(ILogger<IndexModel> logger, SubmissionService submissionService) { _logger = logger; _submissionService = submissionService; } public async Task OnGetAsync() { try { Submissions = await _submissionService.GetUserSubmissionsAsync(User.GetEmail()); } catch(OperationFailedException e) { ModelState.AddModelError(string.Empty, e.Message); } } [BindProperty] public Submission MySubmission { get; set; } public IList<string> Errors = new List<string>(); public IEnumerable<Submission> Submissions = Enumerable.Empty<Submission>(); private ILogger<IndexModel> _logger = null; private SubmissionService _submissionService = null; } }
28.272727
96
0.647106
[ "MIT" ]
cppseminar/APC
cppseminar/presentation/Pages/Submissions/Index.cshtml.cs
1,244
C#
using System.Collections.Generic; using UnicornHack.Generation; using UnicornHack.Generation.Effects; using UnicornHack.Primitives; namespace UnicornHack.Data.Abilities { public static partial class AbilityData { public static readonly LeveledAbility ShortRangeWeapons = new LeveledAbility { Name = "short range weapons", Type = AbilityType.Skill, Cost = 4, Activation = ActivationType.Always, Cumulative = true, LeveledEffects = new Dictionary<int, IReadOnlyList<Effect>> {{1, new List<Effect>()}} }; } }
29.285714
97
0.655285
[ "Apache-2.0" ]
AndriySvyryd/UnicornHack
src/UnicornHack.Core/Data/Abilities/ShortRangeWeapons.cs
615
C#
// Lucene version compatibility level 4.8.1 using YAF.Lucene.Net.Analysis.Util; using System; using System.Collections.Generic; namespace YAF.Lucene.Net.Analysis.Shingle { /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /// <summary> /// Factory for <see cref="ShingleFilter"/>. /// <code> /// &lt;fieldType name="text_shingle" class="solr.TextField" positionIncrementGap="100"&gt; /// &lt;analyzer&gt; /// &lt;tokenizer class="solr.WhitespaceTokenizerFactory"/&gt; /// &lt;filter class="solr.ShingleFilterFactory" minShingleSize="2" maxShingleSize="2" /// outputUnigrams="true" outputUnigramsIfNoShingles="false" tokenSeparator=" " fillerToken="_"/&gt; /// &lt;/analyzer&gt; /// &lt;/fieldType&gt;</code> /// </summary> public class ShingleFilterFactory : TokenFilterFactory { private readonly int minShingleSize; private readonly int maxShingleSize; private readonly bool outputUnigrams; private readonly bool outputUnigramsIfNoShingles; private readonly string tokenSeparator; private readonly string fillerToken; /// <summary> /// Creates a new <see cref="ShingleFilterFactory"/> </summary> public ShingleFilterFactory(IDictionary<string, string> args) : base(args) { maxShingleSize = GetInt32(args, "maxShingleSize", ShingleFilter.DEFAULT_MAX_SHINGLE_SIZE); if (maxShingleSize < 2) { throw new ArgumentOutOfRangeException(nameof(maxShingleSize), "Invalid maxShingleSize (" + maxShingleSize + ") - must be at least 2"); // LUCENENET specific - changed from IllegalArgumentException to ArgumentOutOfRangeException (.NET convention) } minShingleSize = GetInt32(args, "minShingleSize", ShingleFilter.DEFAULT_MIN_SHINGLE_SIZE); if (minShingleSize < 2) { throw new ArgumentOutOfRangeException(nameof(minShingleSize), "Invalid minShingleSize (" + minShingleSize + ") - must be at least 2"); // LUCENENET specific - changed from IllegalArgumentException to ArgumentOutOfRangeException (.NET convention) } if (minShingleSize > maxShingleSize) { throw new ArgumentException("Invalid minShingleSize (" + minShingleSize + ") - must be no greater than maxShingleSize (" + maxShingleSize + ")"); } outputUnigrams = GetBoolean(args, "outputUnigrams", true); outputUnigramsIfNoShingles = GetBoolean(args, "outputUnigramsIfNoShingles", false); tokenSeparator = Get(args, "tokenSeparator", ShingleFilter.DEFAULT_TOKEN_SEPARATOR); fillerToken = Get(args, "fillerToken", ShingleFilter.DEFAULT_FILLER_TOKEN); if (args.Count > 0) { throw new ArgumentException(string.Format(J2N.Text.StringFormatter.CurrentCulture, "Unknown parameters: {0}", args)); } } public override TokenStream Create(TokenStream input) { ShingleFilter r = new ShingleFilter(input, minShingleSize, maxShingleSize); r.SetOutputUnigrams(outputUnigrams); r.SetOutputUnigramsIfNoShingles(outputUnigramsIfNoShingles); r.SetTokenSeparator(tokenSeparator); r.SetFillerToken(fillerToken); return r; } } }
51.345238
262
0.651287
[ "Apache-2.0" ]
10by10pixel/YAFNET
yafsrc/Lucene.Net/Lucene.Net.Analysis.Common/Analysis/Shingle/ShingleFilterFactory.cs
4,232
C#
using OTAPI.Patcher.Engine.Extensions; using OTAPI.Patcher.Engine.Modification; namespace OTAPI.Patcher.Engine.Modifications.Hooks.Net { public class SendData : ModificationBase { public override System.Collections.Generic.IEnumerable<string> AssemblyTargets => new[] { "Terraria, Version=1.3.0.7, Culture=neutral, PublicKeyToken=null", "TerrariaServer, Version=1.3.0.7, Culture=neutral, PublicKeyToken=null" }; public override string Description => "Hooking NetMessage.SendData..."; public override void Run() { int tmpI = 0; float tmpF = 0; string tmpS = null; var vanilla = this.Method(() => Terraria.NetMessage.SendData(0, -1, -1, "", 0, 0, 0, 0, 0, 0, 0)); var callback = this.Method(() => OTAPI.Callbacks.Terraria.NetMessage.SendData( ref tmpI, ref tmpI, ref tmpI, ref tmpS, ref tmpI, ref tmpF, ref tmpF, ref tmpF, ref tmpI, ref tmpI, ref tmpI )); //Few stack issues arose trying to inject a callback before for lock, so i'll resort to //wrapping the method; vanilla.Wrap ( beginCallback: callback, endCallback: null, beginIsCancellable: true, noEndHandling: false, allowCallbackInstance: false ); } } //public static class NetManager_Debug //{ // public static void SendData(global::Terraria.Net.Sockets.ISocket socket, global::Terraria.Net.NetPacket packet) // { // try // { // socket.AsyncSend(packet.Buffer.Data, 0, packet.Length, new global::Terraria.Net.Sockets.SocketSendCallback((object state) => // { // ((global::Terraria.Net.NetPacket)state).Recycle(); // }), packet); // } // catch (System.Exception ex) // { // System.Console.WriteLine(" Exception normal: Tried to send data to a client after losing connection" + ex); // } // } //} }
35.254237
133
0.582692
[ "MIT" ]
chi-rei-den/Open-Terraria-API
OTAPI.Modifications/OTAPI.Modifications.Net.SendData/Modifications/SendData.cs
2,082
C#
/** * Copyright 2021 d-fens GmbH * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ namespace biz.dfch.CS.Playground.Fynn._20210319 { public class Entry<TKey, TValue> { public Entry<TKey, TValue> Next { get; set; } public TKey Key { get; set; } public TValue Value { get; set; } public Entry(TKey key, TValue value) { Key = key; Value = value; Next = null; } } }
29.393939
75
0.650515
[ "Apache-2.0" ]
dfensgmbh/biz.dfch.CS.Examples.DataTypes
src/biz.dfch.CS.Playground.Fynn/20210319/Entry.cs
972
C#
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using System.Windows.Forms; namespace pharmacy_management_system { internal static class Program { /// <summary> /// The main entry point for the application. /// </summary> [STAThread] static void Main() { Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); Application.Run(new Form1()); } } }
23.217391
65
0.627341
[ "MIT" ]
Dihan141/SWE-4202-Lab
Lab 5/pharmacy management system/Program.cs
536
C#
using CSharpier.DocTypes; using CSharpier.SyntaxPrinter; using Microsoft.CodeAnalysis.CSharp.Syntax; namespace CSharpier.SyntaxPrinter.SyntaxNodePrinters { public static class LiteralExpression { public static Doc Print(LiteralExpressionSyntax node) { return Token.Print(node.Token); } } }
22.6
61
0.713864
[ "MIT" ]
belav/csharpier
Src/CSharpier/SyntaxPrinter/SyntaxNodePrinters/LiteralExpression.cs
339
C#
using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using ContentAggregator.Common; using ContentAggregator.Context.Entities.Likes; namespace ContentAggregator.Context.Entities { public class Comment : PostBaseEntity { [Required] [MaxLength(Consts.CommentContentLength)] public string Content { get; set; } [Required] public string PostId { get; set; } public virtual Post Post { get; set; } public virtual ICollection<Response> Responses { get; set; } public virtual ICollection<BaseLikeEntity<Comment>> CommentLikes { get; set; } } }
30.571429
86
0.699377
[ "MIT" ]
kotwica407/ContentAggregator
ContentAggregator.Context/Entities/Comment.cs
644
C#
using System; using System.Collections.Generic; using System.Text; namespace OpenShadows.FileFormats { public static class FormatHelper { public static string GetFileType(string extension) { return extension.ToUpper() switch { "ALF" => "Game archive files", "3DM" => "3d map", "DSC" => "3d map animation data", "NEI" => "3d map portal data (???)", "PAL" => "3d map texture palette", "PPD" => "3d map sky definition (???)", "TAB" => "3d map shading information (???)", "PIX" => "3d map texture", "AIF" => "image", "NVF" => "image set", "ACE" => "animated sprites", "BOB" => "animated screens", "PCX" => "image (ZSoft PC Paintbrush)", "AAF" => "cutscene definition", "SMK" => "video (Smacker)", "ASF" => "audio (raw PCM unsigned 8-bit, mono 22050 Hz) with ASF header", "RAW" => "audio (raw PCM unsigned 8-bit, mono 22050 Hz)", "HMI" => "audio (Human Machine Interfaces format)", "LXT" => "text definition", "XDF" => "dialogue definition", "DAT" => "different types of gamedata", "NPC" => "joinable npc data", "HTT" => "some form of hyper text", "ANN" => "map annotations for minimaps", "APA" => "(???)", "MSK" => "(???)", "MST" => "(???)", "LST" => "(???)", "MOF" => "(???)", "MOV" => "(???)", "OFF" => "(???)", _ => "<!!!NEVER SEEN BEFORE!!!>" }; } } }
28.653061
77
0.531339
[ "MIT" ]
shihan42/OpenShadows
Src/OpenShadows.FileFormats/FormatHelper.cs
1,406
C#
using System; using System.Collections; using System.Collections.Generic; using UnityEngine; //using UnityEngine.Purchasing; public class TWShop : TWBoard//, IStoreListener { // public void OnInitialized(IStoreController controller, IExtensionProvider extensions) // { // Debug.Log("OnInitialized: PASS"); // // Overall Purchasing system, configured with products for this application. // m_StoreController = controller; // // Store specific subsystem, for accessing device-specific store features. // m_StoreExtensionProvider = extensions; // } // public void OnInitializeFailed(InitializationFailureReason error) // { // Debug.Log("OnInitializeFailed InitializationFailureReason:" + error); // TW.I.AddWarning("", "Shop Init Error!"); // } // public void OnPurchaseFailed(Product i, PurchaseFailureReason p) // { // Debug.Log(string.Format("OnPurchaseFailed: FAIL. Product: '{0}', PurchaseFailureReason: {1}", i.definition.storeSpecificId, p)); // TW.I.AddWarning("", "Purchase Failed!"); // } // public PurchaseProcessingResult ProcessPurchase(PurchaseEventArgs args) // { // foreach (KeyValuePair<int, st_shop> ITEM in st_shopTable.I.VALUE) // { // if (String.Equals(args.purchasedProduct.definition.id, ITEM.Value.stringid, StringComparison.Ordinal)) // { // if( ITEM.Value.is_ads==true) // { // PlayerInfo.IS_REMOVED_ADS.SetAndSave(1); // } // else // { // if(ITEM.Value.coin>0) // { // PlayerInfo.COIN.PlusAndSave(ITEM.Value.coin); // } // else // { // PlayerInfo.GEM.PlusAndSave(ITEM.Value.gem); // } // if (MainMenu.I != null) MainMenu.I.UpdateGemCoinInfo(); // } // TW.I.AddWarning("", "Purchase successful!"); // break; // } // } // return PurchaseProcessingResult.Complete; // } // private static IStoreController m_StoreController; // The Unity Purchasing system. // private static IExtensionProvider m_StoreExtensionProvider; // The store-specific Purchasing subsystems // public static TWShop I; // private void Awake() // { // I = this; // } // void Start () // { // base.InitTWBoard(); // if (m_StoreController == null) // { // InitializePurchasing(); // } // } // public void InitializePurchasing() // { // if (IsInitialized()) // { // return; // } // //var builder = ConfigurationBuilder.Instance(StandardPurchasingModule.Instance()); // foreach( KeyValuePair<int,st_shop> ITEM in st_shopTable.I.VALUE) // { // //builder.AddProduct(ITEM.Value.stringid, ProductType.Consumable); // } // //UnityPurchasing.Initialize(this, builder); // } // private bool IsInitialized() // { // return m_StoreController != null && m_StoreExtensionProvider != null; // } // void Update () // { //} // public void UserClick(st_shop ST_SHOP) // { // BuyProductID(ST_SHOP.stringid); // } // void BuyProductID(string productId) // { // if (IsInitialized()) // { // Product product = m_StoreController.products.WithID(productId); // if (product != null && product.availableToPurchase) // { // Debug.Log(string.Format("Purchasing product asychronously: '{0}'", product.definition.id)); // m_StoreController.InitiatePurchase(product); // } // else // { // Debug.Log("BuyProductID: FAIL. Not purchasing product, either is not found or is not available for purchase"); // } // } // else // { // Debug.Log("BuyProductID FAIL. Not initialized."); // } // } // public void RestorePurchases() // { // if (!IsInitialized()) // { // Debug.Log("RestorePurchases FAIL. Not initialized."); // return; // } // if (Application.platform == RuntimePlatform.IPhonePlayer || // Application.platform == RuntimePlatform.OSXPlayer) // { // Debug.Log("RestorePurchases started ..."); // //var apple = m_StoreExtensionProvider.GetExtension<IAppleExtensions>(); // // apple.RestoreTransactions((result) => { // //Debug.Log("RestorePurchases continuing: " + result + ". If no further messages, no purchases available to restore."); // // }); // } // else // { // Debug.Log("RestorePurchases FAIL. Not supported on this platform. Current = " + Application.platform); // } // } }
34.778523
139
0.533385
[ "Apache-2.0" ]
Cupham/BLEPersonalHealthGateway
Assets/TLib/TW/TWShop/TWShop.cs
5,184
C#
using System; using System.Collections.Generic; using System.Text; using System.IO; namespace CCMEngine { public interface ICCMNotify { void OnMetric(ccMetric metric, object context); } public class FileAnalyzer { ICCMNotify callback = null; LookAheadLangParser parser = null; object context = null; bool suppressMethodSignatures = false; string filename; char[] buffer = null; ParserSwitchBehavior switchBehavior; public FileAnalyzer(StreamReader filestream, ICCMNotify callback, object context, bool suppressMethodSignatures, string filename, ParserSwitchBehavior switchBehavior = ParserSwitchBehavior.TraditionalInclude) { this.buffer = new char[filestream.BaseStream.Length]; filestream.Read(this.buffer, 0, this.buffer.Length); var processStream = new StreamReader(new MemoryStream(Encoding.Default.GetBytes(this.buffer))); // run through preprocessor before setting up parser... Preprocessor preprocessor = new Preprocessor(processStream); StreamReader stream = preprocessor.Process(); // this construct should be fixed and support OCP if (filename.ToLower().EndsWith(".js") || filename.ToLower().EndsWith(".ts")) this.parser = LookAheadLangParser.CreateJavascriptParser(stream); else this.parser = LookAheadLangParser.CreateCppParser(stream); this.callback = callback; this.context = context; this.suppressMethodSignatures = suppressMethodSignatures; this.filename = filename; this.switchBehavior = switchBehavior; } private int GetLineNumber(int offset) { int lineNumber = 1; for (int i = 0; i < offset && i < this.buffer.Length ; ++i) { if (this.buffer[i].Equals('\n')) ++lineNumber; } return lineNumber; } private void OnLocalFunction(IFunctionStream functionStream) { try { functionStream.AdvanceToNextFunction(); } catch (CCCParserSuccessException info) { OnFunction(info.Function, info.StreamOffset, functionStream); } } private void OnFunction(string unit, int streamOffset, IFunctionStream funcStream) { BlockAnalyzer analyzer = new BlockAnalyzer(this.parser, funcStream, this.OnLocalFunction, this.switchBehavior); int ccm = 1 + analyzer.ConsumeBlockCalculateAdditionalComplexity(); var metric = new ccMetric(this.filename, unit, ccm); metric.StartLineNumber = GetLineNumber(streamOffset); metric.EndLineNumber = GetLineNumber(this.parser.StreamOffset); this.callback.OnMetric(metric, this.context); } public static IFunctionStream CreateFunctionStream(LookAheadLangParser parser, string filename, bool suppressMethodSignatures) { if (filename.ToLower().EndsWith(".js") || filename.ToLower().EndsWith(".ts")) return new JSParser(parser); return new CCCParser(parser, suppressMethodSignatures); } public void Analyze() { try { IFunctionStream functionFinder = CreateFunctionStream(this.parser, this.filename, this.suppressMethodSignatures); while(true) { try { functionFinder.AdvanceToNextFunction(); // will throw CCCParserSuccessException when it finds a function } catch(CCCParserSuccessException info) { OnFunction(info.Function, info.StreamOffset, functionFinder); } } } catch (EndOfStreamException) { // we are done! } } } }
30.834711
134
0.653444
[ "MIT" ]
ardalis/ccm
source/CCMEngine/FileAnalyzer.cs
3,731
C#
namespace _04.EmployeesWithSalaryOver50000 { using System; using System.IO; using System.Linq; using P02_DatabaseFirst.Data; public class StartUp { public static void Main() { using (SoftUniContext context = new SoftUniContext()) { var employees = context .Employees.Where(e => e.Salary > 50000) .OrderBy(e => e.FirstName) .Select(e => new { e.FirstName }).ToArray(); File.Delete("Output.txt"); foreach (var e in employees) { File.AppendAllText("Output.txt", $"{e.FirstName}{Environment.NewLine}"); } } } } }
25.875
92
0.449275
[ "MIT" ]
ShadyObeyd/DatabaseAdvanced-EntityFramework-June2018
03.IntroductionToEntityFramework-Exercise/04.EmployeesWithSalaryOver50000/StartUp.cs
830
C#
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; namespace WebApplication9 { public partial class Site_Mobile : System.Web.UI.MasterPage { protected void Page_Load(object sender, EventArgs e) { } } }
20.176471
64
0.670554
[ "MIT" ]
mcadidvijay/PCHeart
Site.Mobile.Master.cs
343
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using MongoDB.Bson; using MongoDB.Bson.Serialization.Attributes; namespace Kangaroo.Models { public class TimeEntry { [BsonId] public ObjectId Id { get; set; } public decimal? Quantity { get; set; } private DateTime date; public string UserName { get ; set; } public DateTime Date { get { return date.ToLocalTime(); } set { date = value.ToUniversalTime(); } } public string Project { get; set; } public TimeEntry() { //Id = Guid.NewGuid(); } } }
19.771429
51
0.563584
[ "MIT" ]
SamLeach/KangarooTimeTracker
Kangaroo/Models/TimeEntry.cs
694
C#
using Spfx.Serialization; using System.Runtime.Serialization; namespace Spfx.Runtime.Messages { [DataContract] public sealed class RemoteCallFailureResponse : RemoteInvocationResponse { [DataMember] public IRemoteExceptionInfo Error { get; set; } internal override void ForwardResult(IInvocationResponseHandler completion) { completion?.TrySetException(Error.RecreateException()); } public RemoteCallFailureResponse(long callId, IRemoteExceptionInfo ex) : base(callId) { Error = ex; } } }
26.333333
84
0.636076
[ "MIT" ]
fbrosseau/SimpleProcessFramework
SimpleProcessFramework/Runtime/Messages/RemoteCallFailureResponse.cs
634
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Philadelphia.Common { /// <summary>value that is not a class field</summary> public class RemoteValue<LocalT,RemOperResT> : IReadWriteValue<LocalT> { public LocalT Value { get; private set; } private readonly LocalT _invalidValue; private readonly Func<RemOperResT,LocalT> _remToLocal; private readonly Func<LocalT,Task<RemOperResT>> _saveOperation; private readonly HashSet<string> _errors = new HashSet<string>(); private int _pendingRemoteCalls = 0; private bool _remoteCallingEnabled = true; public IEnumerable<string> Errors => _errors; /// <summary>(oldValue, newValue) => shouldReplicate? </summary> public Func<LocalT,LocalT,bool> RemoteCallFilter { get; set; } = (_, __) => true; public event Validate<LocalT> Validate; public event ValueChangedRich<LocalT> Changed; public RemoteValue( LocalT initialValue, Func<LocalT, Task<RemOperResT>> saveOperation, Func<RemOperResT,LocalT> remToLocal, LocalT invalidValue = default(LocalT), Action<RemoteValue<LocalT,RemOperResT>> initialization = null) { Value = initialValue; _saveOperation = saveOperation; _invalidValue = invalidValue; _remToLocal = remToLocal; if (initialization != null) { _remoteCallingEnabled = false; try { Logger.Debug(GetType(), "WithinConstructor initialization starting"); initialization(this); } finally { _remoteCallingEnabled = true; Logger.Debug(GetType(), "WithinConstructor initialization ended"); } } } private void RecalculateErrors(LocalT input) { _errors.Clear(); Validate?.Invoke(input, _errors); } public void Reset(bool isUserChange= false, object sender = null) { Initialize(_invalidValue, isUserChange, sender); } public void Initialize(LocalT newValue, bool isUserChange, object sender) { sender = sender ?? this; Logger.Debug(GetType(), "Initializing starting toValue={0} remoteCallingEnabled={1}", newValue, _remoteCallingEnabled); var oldRemoteCallingEnabled = _remoteCallingEnabled; _remoteCallingEnabled = false; var oldValue = Value; var factSaved = newValue; RecalculateErrors(newValue); //may be rejected by validation BUT yet still errors should be calculated Value = newValue; Logger.Debug(GetType(), "DoChange OldValue={0} NewValue={1} FactSaved={2} Errors={3} Sender={4}", oldValue, newValue, factSaved, Errors.PrettyToString(), sender); Changed?.Invoke(sender, oldValue, newValue, Errors, isUserChange); _remoteCallingEnabled = oldRemoteCallingEnabled; } public async Task<Unit> DoChange( LocalT newValue, bool isUserChange, object sender = null, bool mayBeRejectedByValidation = true) { return await DoChangeWithCallingSave(newValue, isUserChange, sender, mayBeRejectedByValidation); } private async Task<Unit> DoChangeWithCallingSave( LocalT newValue, bool isUserChange, object sender = null, bool mayBeRejectedByValidation = true) { var oldValue = Value; var isSaveCalled = false; var factSaved = newValue; Logger.Debug(GetType(), "DoChange entering OldValue={0} NewValue={1} isUserChange={2} _pendingRemoteCalls={3}", oldValue, newValue, isUserChange, _pendingRemoteCalls, _remoteCallingEnabled); _pendingRemoteCalls++; RecalculateErrors(newValue); //may be rejected by validation BUT yet still errors should be calculated var shouldReplicateFilterAnswer = RemoteCallFilter(Value, newValue); Logger.Debug(GetType(), "DoChange errorsCount={0} RemoteCallingEnabled={1} mayBeRejectedByValidation={2} shouldReplicateFilterAnswer={3}", _errors.Count, _remoteCallingEnabled, mayBeRejectedByValidation, shouldReplicateFilterAnswer); if (!mayBeRejectedByValidation || _errors.Count <= 0) { try { if (_remoteCallingEnabled && shouldReplicateFilterAnswer) { isSaveCalled = true; var raw = await _saveOperation(newValue); factSaved = _remToLocal(raw); } Value = newValue; } catch (Exception ex) { Logger.Error(GetType(), "Remote save failed due to {0}", ex); _errors.Add(ex.Message); } } if (sender == null) { sender = this; } /* Propagate change (to UI) if: -offline / without remote save because change is likely to be synchronous OR -online and current UI value is the same as before request Why? Because in UI user when he is in the middle of typing long value (that potentially is saved on-each-key-pressed) program should not overwrite UI value with domain value that is likely to be out of date (due to server saving network related delay). Thus don't change value in the field in the middle of typing if it is not neccessary */ var shouldPropagate = true; //if operation failed then there's no value to be converted if (isSaveCalled && !_errors.Any()) { var factNewValue = factSaved; shouldPropagate = object.Equals(factNewValue, newValue); } Logger.Debug(GetType(), "DoChange OldValue={0} NewValue={1} FactSaved={2} Errors={3} Sender={4} shouldPropagate?={5} isSaveCalled={6} _pendingRemoteCalls={7}", oldValue, newValue, factSaved, Errors.PrettyToString(), sender, shouldPropagate, isSaveCalled, _pendingRemoteCalls); _pendingRemoteCalls--; if (shouldPropagate && _pendingRemoteCalls <= 0) { Changed?.Invoke(sender, oldValue, newValue, Errors, isUserChange); } return Unit.Instance; } public override string ToString() { return string.Format("[RemoteValue: Value={0}, Errors={1}, Validators?={2} Changed?={3}]", Value, Errors.PrettyToString(), Validate!=null, Changed != null); } } }
42.846626
172
0.596363
[ "Apache-2.0" ]
todo-it/philadelphia
Philadelphia.Common/Mvp/PlatformAgnostic/RemoteValue.cs
6,986
C#
//----------------------------------------------------------------------------- // Copyright : (c) Chris Moore, 2020 // License : MIT //----------------------------------------------------------------------------- namespace Z0 { using System; using System.Runtime.CompilerServices; using System.Xml; using static Root; partial struct XmlParts { public readonly struct ElementEnd : IXmlPart<Name> { public Name Value {get;} public XmlNodeType Kind => XmlNodeType.EndElement; [MethodImpl(Inline)] public ElementEnd(string value) { Value = value; } public string Format() => string.Format("</{0}>", Value); } } }
25.483871
79
0.418987
[ "BSD-3-Clause" ]
0xCM/z0
src/xml/src/models/ElementEnd.cs
790
C#
using System; using System.Collections.Generic; using System.Text; using System.Text.Json.Serialization; namespace Desafio.Tech.Dog.ApplicationService.Contracts.Responses.Turma { public abstract class TurmaBaseResponse { [JsonIgnore] public bool Success { get; protected set; } public IList<string> Errors { get; protected set; } public string Message { get; protected set; } public void SetError(string error) { Success = false; if (Errors == null) Errors = new List<string>(); Errors.Add(error); } } }
26.125
71
0.617225
[ "MIT" ]
diegopsalles/desafio-tech-dog
Desafio.Tech.Dog/Desafio.Tech.Dog.ApplicationService/Contracts/Responses/Turma/TurmaBaseResponse.cs
629
C#
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; using TeleSharp.TL; namespace TeleSharp.TL { [TLObject(-317144808)] public class TLEncryptedMessage : TLAbsEncryptedMessage { public override int Constructor { get { return -317144808; } } public long RandomId { get; set; } public int ChatId { get; set; } public int Date { get; set; } public byte[] Bytes { get; set; } public TLAbsEncryptedFile File { get; set; } public void ComputeFlags() { } public override void DeserializeBody(BinaryReader br) { RandomId = br.ReadInt64(); ChatId = br.ReadInt32(); Date = br.ReadInt32(); Bytes = BytesUtil.Deserialize(br); File = (TLAbsEncryptedFile)ObjectUtils.DeserializeObject(br); } public override void SerializeBody(BinaryWriter bw) { bw.Write(Constructor); bw.Write(RandomId); bw.Write(ChatId); bw.Write(Date); BytesUtil.Serialize(Bytes, bw); ObjectUtils.SerializeObject(File, bw); } } }
23.836364
73
0.559878
[ "MIT" ]
Vladimir-Novick/TLSharp.NetCore2
TeleSharp.NetCore2.TL/TL/TLEncryptedMessage.cs
1,311
C#
// Copyright (c) .NET Foundation and Contributors (https://dotnetfoundation.org) // Copyright (c) 2018-2021 Stride and its contributors (https://stride3d.net) // Copyright (c) 2011-2018 Silicon Studio Corp. (https://www.siliconstudio.co.jp) // See the LICENSE.md file in the project root for full license information. using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Stride.Particles.Sorters { public class ArrayPool<T> where T : struct { private readonly Dictionary<int, Stack<T[]>> _pool = new Dictionary<int, Stack<T[]>>(); public readonly T[] Empty = new T[0]; public virtual void Clear() { _pool.Clear(); } public virtual T[] Allocate(int size) { if (size < 0) throw new ArgumentOutOfRangeException(nameof(size), "Must be positive."); if (size == 0) return Empty; Stack<T[]> candidates; return _pool.TryGetValue(size, out candidates) && candidates.Count > 0 ? candidates.Pop() : new T[size]; } public virtual void Free(T[] array) { if (array == null) throw new ArgumentNullException(nameof(array)); if (array.Length == 0) return; Stack<T[]> candidates; if (!_pool.TryGetValue(array.Length, out candidates)) _pool.Add(array.Length, candidates = new Stack<T[]>()); candidates.Push(array); } } public class ConcurrentArrayPool<T> : ArrayPool<T> where T : struct { public override T[] Allocate(int size) { lock (this) { return base.Allocate(size); } } public override void Free(T[] array) { lock (this) { base.Free(array); } } public override void Clear() { lock (this) { base.Clear(); } } } }
27.48
116
0.551674
[ "MIT" ]
Ethereal77/stride
sources/engine/Stride.Particles/Sorters/ArrayPool.cs
2,061
C#
// Copyright (c) .NET Foundation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for license information. using System; using Microsoft.ApplicationInsights.SnapshotCollector; using Microsoft.ApplicationInsights.WindowsServer.Channel.Implementation; using Microsoft.Azure.WebJobs.Hosting; using Newtonsoft.Json; using Newtonsoft.Json.Linq; namespace Microsoft.Azure.WebJobs.Logging.ApplicationInsights { public class ApplicationInsightsLoggerOptions : IOptionsFormatter { /// <summary> /// Gets or sets Application Insights instrumentation key. /// </summary> public string InstrumentationKey { get; set; } /// <summary> /// Gets or sets Application Insights connection string. If set, this will /// take precedence over the InstrumentationKey and overwrite it. /// </summary> public string ConnectionString { get; set; } /// <summary> /// Gets or sets sampling settings. /// </summary> public SamplingPercentageEstimatorSettings SamplingSettings { get; set; } /// <summary> /// Gets or sets excluded types for sampling. /// </summary> public string SamplingExcludedTypes { get; set; } /// <summary> /// Gets or sets included types for sampling. /// </summary> public string SamplingIncludedTypes { get; set; } /// <summary> /// Gets or sets snapshot collection options. /// </summary> public SnapshotCollectorConfiguration SnapshotConfiguration { get; set; } /// <summary> /// Gets or sets authentication key for Quick Pulse (Live Metrics). /// </summary> [Obsolete("Use LiveMetricsAuthenticationApiKey instead.")] public string QuickPulseAuthenticationApiKey { get { return LiveMetricsAuthenticationApiKey; } set { LiveMetricsAuthenticationApiKey = value; } } /// <summary> /// Gets or sets authentication key for Live Metrics. /// </summary> public string LiveMetricsAuthenticationApiKey { get; set; } /// <summary> /// Gets or sets the time to delay Quick Pulse (Live Metrics) initialization. Delaying this initialization /// can result in decreased application startup time. Default value is 15 seconds. /// </summary> [Obsolete("Use LiveMetricsInitializationDelay instead.")] public TimeSpan QuickPulseInitializationDelay { get { return LiveMetricsInitializationDelay; } set { LiveMetricsInitializationDelay = value; } } /// <summary> /// Gets or sets the time to delay Live Metrics initialization. Delaying this initialization /// can result in decreased application startup time. Default value is 15 seconds. /// </summary> public TimeSpan LiveMetricsInitializationDelay { get; set; } = TimeSpan.FromSeconds(15); /// <summary> /// Gets or sets flag that enables Kudu performance counters collection. /// https://github.com/projectkudu/kudu/wiki/Perf-Counters-exposed-as-environment-variables. /// Enabled by default. /// </summary> public bool EnablePerformanceCountersCollection { get; set; } = true; /// <summary> /// Gets or sets the flag that enables live metrics collection. /// Enabled by default. /// </summary> public bool EnableLiveMetrics { get; set; } = true; /// <summary> /// Gets or sets the flag that enables dependency tracking. /// Enabled by default. /// </summary> public bool EnableDependencyTracking { get; set; } = true; /// <summary> /// Gets or sets HTTP request collection options. /// </summary> public HttpAutoCollectionOptions HttpAutoCollectionOptions { get; set; } = new HttpAutoCollectionOptions(); public string Format() { JObject sampling = null; if (SamplingSettings != null) { sampling = new JObject { { nameof(SamplingPercentageEstimatorSettings.EvaluationInterval), SamplingSettings.EvaluationInterval }, { nameof(SamplingPercentageEstimatorSettings.InitialSamplingPercentage), SamplingSettings.InitialSamplingPercentage }, { nameof(SamplingPercentageEstimatorSettings.MaxSamplingPercentage), SamplingSettings.MaxSamplingPercentage }, { nameof(SamplingPercentageEstimatorSettings.MaxTelemetryItemsPerSecond), SamplingSettings.MaxTelemetryItemsPerSecond }, { nameof(SamplingPercentageEstimatorSettings.MinSamplingPercentage), SamplingSettings.MinSamplingPercentage }, { nameof(SamplingPercentageEstimatorSettings.MovingAverageRatio), SamplingSettings.MovingAverageRatio }, { nameof(SamplingPercentageEstimatorSettings.SamplingPercentageDecreaseTimeout), SamplingSettings.SamplingPercentageDecreaseTimeout }, { nameof(SamplingPercentageEstimatorSettings.SamplingPercentageIncreaseTimeout), SamplingSettings.SamplingPercentageIncreaseTimeout }, }; } JObject snapshot = null; if (SnapshotConfiguration != null) { snapshot = new JObject { { nameof(SnapshotCollectorConfiguration.FailedRequestLimit), SnapshotConfiguration.FailedRequestLimit }, { nameof(SnapshotCollectorConfiguration.IsEnabled), SnapshotConfiguration.IsEnabled }, { nameof(SnapshotCollectorConfiguration.IsEnabledInDeveloperMode), SnapshotConfiguration.IsEnabledInDeveloperMode }, { nameof(SnapshotCollectorConfiguration.IsEnabledWhenProfiling), SnapshotConfiguration.IsEnabledWhenProfiling }, { nameof(SnapshotCollectorConfiguration.IsLowPrioritySnapshotUploader), SnapshotConfiguration.IsLowPrioritySnapshotUploader }, { nameof(SnapshotCollectorConfiguration.MaximumCollectionPlanSize), SnapshotConfiguration.MaximumCollectionPlanSize }, { nameof(SnapshotCollectorConfiguration.MaximumSnapshotsRequired), SnapshotConfiguration.MaximumSnapshotsRequired }, { nameof(SnapshotCollectorConfiguration.ProblemCounterResetInterval), SnapshotConfiguration.ProblemCounterResetInterval }, { nameof(SnapshotCollectorConfiguration.ProvideAnonymousTelemetry), SnapshotConfiguration.ProvideAnonymousTelemetry }, { nameof(SnapshotCollectorConfiguration.ReconnectInterval), SnapshotConfiguration.ReconnectInterval }, { nameof(SnapshotCollectorConfiguration.ShadowCopyFolder), SnapshotConfiguration.ShadowCopyFolder }, { nameof(SnapshotCollectorConfiguration.SnapshotInLowPriorityThread), SnapshotConfiguration.SnapshotInLowPriorityThread }, { nameof(SnapshotCollectorConfiguration.SnapshotsPerDayLimit), SnapshotConfiguration.SnapshotsPerDayLimit }, { nameof(SnapshotCollectorConfiguration.SnapshotsPerTenMinutesLimit), SnapshotConfiguration.SnapshotsPerTenMinutesLimit }, { nameof(SnapshotCollectorConfiguration.TempFolder), SnapshotConfiguration.TempFolder }, { nameof(SnapshotCollectorConfiguration.ThresholdForSnapshotting), SnapshotConfiguration.ThresholdForSnapshotting } }; } JObject httpOptions = new JObject { { nameof(HttpAutoCollectionOptions.EnableHttpTriggerExtendedInfoCollection), HttpAutoCollectionOptions.EnableHttpTriggerExtendedInfoCollection }, { nameof(HttpAutoCollectionOptions.EnableW3CDistributedTracing), HttpAutoCollectionOptions.EnableW3CDistributedTracing }, { nameof(HttpAutoCollectionOptions.EnableResponseHeaderInjection), HttpAutoCollectionOptions.EnableResponseHeaderInjection } }; JObject options = new JObject { { nameof(SamplingSettings), sampling }, { nameof(SamplingExcludedTypes), SamplingExcludedTypes }, { nameof(SamplingIncludedTypes), SamplingIncludedTypes }, { nameof(SnapshotConfiguration), snapshot }, { nameof(EnablePerformanceCountersCollection), EnablePerformanceCountersCollection }, { nameof(HttpAutoCollectionOptions), httpOptions }, { nameof(LiveMetricsInitializationDelay), LiveMetricsInitializationDelay }, { nameof(EnableLiveMetrics), EnableLiveMetrics }, { nameof(EnableDependencyTracking), EnableDependencyTracking } }; return options.ToString(Formatting.Indented); } } }
50.972067
161
0.662648
[ "MIT" ]
Chris-Johnston/azure-webjobs-sdk
src/Microsoft.Azure.WebJobs.Logging.ApplicationInsights/ApplicationInsightsLoggerOptions.cs
9,126
C#
// ------------------------------------------------------------------------------ // Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License in the project root for license information. // ------------------------------------------------------------------------------ // **NOTE** This file was generated by a tool and any changes will be overwritten. // <auto-generated/> // Template Source: Templates\CSharp\Requests\EntityRequest.cs.tt namespace Microsoft.Graph { using System; using System.Collections.Generic; using System.IO; using System.Net.Http; using System.Threading; using System.Linq.Expressions; /// <summary> /// The type GroupLifecyclePolicyRequest. /// </summary> public partial class GroupLifecyclePolicyRequest : BaseRequest, IGroupLifecyclePolicyRequest { /// <summary> /// Constructs a new GroupLifecyclePolicyRequest. /// </summary> /// <param name="requestUrl">The URL for the built request.</param> /// <param name="client">The <see cref="IBaseClient"/> for handling requests.</param> /// <param name="options">Query and header option name value pairs for the request.</param> public GroupLifecyclePolicyRequest( string requestUrl, IBaseClient client, IEnumerable<Option> options) : base(requestUrl, client, options) { } /// <summary> /// Creates the specified GroupLifecyclePolicy using POST. /// </summary> /// <param name="groupLifecyclePolicyToCreate">The GroupLifecyclePolicy to create.</param> /// <returns>The created GroupLifecyclePolicy.</returns> public System.Threading.Tasks.Task<GroupLifecyclePolicy> CreateAsync(GroupLifecyclePolicy groupLifecyclePolicyToCreate) { return this.CreateAsync(groupLifecyclePolicyToCreate, CancellationToken.None); } /// <summary> /// Creates the specified GroupLifecyclePolicy using POST. /// </summary> /// <param name="groupLifecyclePolicyToCreate">The GroupLifecyclePolicy to create.</param> /// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param> /// <returns>The created GroupLifecyclePolicy.</returns> public async System.Threading.Tasks.Task<GroupLifecyclePolicy> CreateAsync(GroupLifecyclePolicy groupLifecyclePolicyToCreate, CancellationToken cancellationToken) { this.ContentType = "application/json"; this.Method = "POST"; var newEntity = await this.SendAsync<GroupLifecyclePolicy>(groupLifecyclePolicyToCreate, cancellationToken).ConfigureAwait(false); this.InitializeCollectionProperties(newEntity); return newEntity; } /// <summary> /// Deletes the specified GroupLifecyclePolicy. /// </summary> /// <returns>The task to await.</returns> public System.Threading.Tasks.Task DeleteAsync() { return this.DeleteAsync(CancellationToken.None); } /// <summary> /// Deletes the specified GroupLifecyclePolicy. /// </summary> /// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param> /// <returns>The task to await.</returns> public async System.Threading.Tasks.Task DeleteAsync(CancellationToken cancellationToken) { this.Method = "DELETE"; await this.SendAsync<GroupLifecyclePolicy>(null, cancellationToken).ConfigureAwait(false); } /// <summary> /// Gets the specified GroupLifecyclePolicy. /// </summary> /// <returns>The GroupLifecyclePolicy.</returns> public System.Threading.Tasks.Task<GroupLifecyclePolicy> GetAsync() { return this.GetAsync(CancellationToken.None); } /// <summary> /// Gets the specified GroupLifecyclePolicy. /// </summary> /// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param> /// <returns>The GroupLifecyclePolicy.</returns> public async System.Threading.Tasks.Task<GroupLifecyclePolicy> GetAsync(CancellationToken cancellationToken) { this.Method = "GET"; var retrievedEntity = await this.SendAsync<GroupLifecyclePolicy>(null, cancellationToken).ConfigureAwait(false); this.InitializeCollectionProperties(retrievedEntity); return retrievedEntity; } /// <summary> /// Updates the specified GroupLifecyclePolicy using PATCH. /// </summary> /// <param name="groupLifecyclePolicyToUpdate">The GroupLifecyclePolicy to update.</param> /// <returns>The updated GroupLifecyclePolicy.</returns> public System.Threading.Tasks.Task<GroupLifecyclePolicy> UpdateAsync(GroupLifecyclePolicy groupLifecyclePolicyToUpdate) { return this.UpdateAsync(groupLifecyclePolicyToUpdate, CancellationToken.None); } /// <summary> /// Updates the specified GroupLifecyclePolicy using PATCH. /// </summary> /// <param name="groupLifecyclePolicyToUpdate">The GroupLifecyclePolicy to update.</param> /// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param> /// <exception cref="ClientException">Thrown when an object returned in a response is used for updating an object in Microsoft Graph.</exception> /// <returns>The updated GroupLifecyclePolicy.</returns> public async System.Threading.Tasks.Task<GroupLifecyclePolicy> UpdateAsync(GroupLifecyclePolicy groupLifecyclePolicyToUpdate, CancellationToken cancellationToken) { if (groupLifecyclePolicyToUpdate.AdditionalData != null) { if (groupLifecyclePolicyToUpdate.AdditionalData.ContainsKey(Constants.HttpPropertyNames.ResponseHeaders) || groupLifecyclePolicyToUpdate.AdditionalData.ContainsKey(Constants.HttpPropertyNames.StatusCode)) { throw new ClientException( new Error { Code = GeneratedErrorConstants.Codes.NotAllowed, Message = String.Format(GeneratedErrorConstants.Messages.ResponseObjectUsedForUpdate, groupLifecyclePolicyToUpdate.GetType().Name) }); } } if (groupLifecyclePolicyToUpdate.AdditionalData != null) { if (groupLifecyclePolicyToUpdate.AdditionalData.ContainsKey(Constants.HttpPropertyNames.ResponseHeaders) || groupLifecyclePolicyToUpdate.AdditionalData.ContainsKey(Constants.HttpPropertyNames.StatusCode)) { throw new ClientException( new Error { Code = GeneratedErrorConstants.Codes.NotAllowed, Message = String.Format(GeneratedErrorConstants.Messages.ResponseObjectUsedForUpdate, groupLifecyclePolicyToUpdate.GetType().Name) }); } } this.ContentType = "application/json"; this.Method = "PATCH"; var updatedEntity = await this.SendAsync<GroupLifecyclePolicy>(groupLifecyclePolicyToUpdate, cancellationToken).ConfigureAwait(false); this.InitializeCollectionProperties(updatedEntity); return updatedEntity; } /// <summary> /// Adds the specified expand value to the request. /// </summary> /// <param name="value">The expand value.</param> /// <returns>The request object to send.</returns> public IGroupLifecyclePolicyRequest Expand(string value) { this.QueryOptions.Add(new QueryOption("$expand", value)); return this; } /// <summary> /// Adds the specified expand value to the request. /// </summary> /// <param name="expandExpression">The expression from which to calculate the expand value.</param> /// <returns>The request object to send.</returns> public IGroupLifecyclePolicyRequest Expand(Expression<Func<GroupLifecyclePolicy, object>> expandExpression) { if (expandExpression == null) { throw new ArgumentNullException(nameof(expandExpression)); } string error; string value = ExpressionExtractHelper.ExtractMembers(expandExpression, out error); if (value == null) { throw new ArgumentException(error, nameof(expandExpression)); } else { this.QueryOptions.Add(new QueryOption("$expand", value)); } return this; } /// <summary> /// Adds the specified select value to the request. /// </summary> /// <param name="value">The select value.</param> /// <returns>The request object to send.</returns> public IGroupLifecyclePolicyRequest Select(string value) { this.QueryOptions.Add(new QueryOption("$select", value)); return this; } /// <summary> /// Adds the specified select value to the request. /// </summary> /// <param name="selectExpression">The expression from which to calculate the select value.</param> /// <returns>The request object to send.</returns> public IGroupLifecyclePolicyRequest Select(Expression<Func<GroupLifecyclePolicy, object>> selectExpression) { if (selectExpression == null) { throw new ArgumentNullException(nameof(selectExpression)); } string error; string value = ExpressionExtractHelper.ExtractMembers(selectExpression, out error); if (value == null) { throw new ArgumentException(error, nameof(selectExpression)); } else { this.QueryOptions.Add(new QueryOption("$select", value)); } return this; } /// <summary> /// Initializes any collection properties after deserialization, like next requests for paging. /// </summary> /// <param name="groupLifecyclePolicyToInitialize">The <see cref="GroupLifecyclePolicy"/> with the collection properties to initialize.</param> private void InitializeCollectionProperties(GroupLifecyclePolicy groupLifecyclePolicyToInitialize) { } } }
45.021097
170
0.630459
[ "MIT" ]
OfficeGlobal/msgraph-beta-sdk-dotnet
src/Microsoft.Graph/Requests/Generated/GroupLifecyclePolicyRequest.cs
10,670
C#
 using System; namespace AltoMultiThreadDownloadManager.EventArguments { /// <summary> /// Event arguments for file merging event /// </summary> public class MergingProgressChangedEventArgs: EventArgs { /// <summary> /// Constructor for progress changed arguments /// </summary> /// <param name="progress">Progress for file merging process; max = 100</param> public MergingProgressChangedEventArgs(double progress) { Progress = progress; } /// <summary> /// Gets or sets the progress value /// </summary> public double Progress { get; set; } } }
25.083333
87
0.671096
[ "MIT" ]
aalitor/AltoMultiThreadDownloadManager-master
AltoMultiThreadDownloadManager/EventArguments/MergingProgressChangedEventArgs.cs
604
C#
using Microsoft.AspNetCore.Mvc; using Microsoft.Extensions.Logging; using MvcBlazorDemo.Models; using System.Diagnostics; namespace MvcBlazorDemo.Controllers { public class HomeController : Controller { private readonly ILogger<HomeController> _logger; public HomeController(ILogger<HomeController> logger) { _logger = logger; } public IActionResult Index() { return View(); } public IActionResult Blazor() { return View("_Host"); } public IActionResult Privacy() { return View(); } [ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)] public IActionResult Error() { return View(new ErrorViewModel { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier }); } } }
23.615385
112
0.60152
[ "MIT" ]
araujofrancisco/MvcBlazorDemo
MvcBlazorDemo/Controllers/HomeController.cs
923
C#
using System; using System.Windows; using GongSolutions.Wpf.DragDrop; using GongSolutions.Wpf.DragDrop.Utilities; namespace Showcase.WPF.DragDrop.Models { using System.Collections; using System.Collections.Generic; using System.Linq; public class SerializableDropHandler : IDropTarget { #if !NETCOREAPP3_1_OR_GREATER /// <inheritdoc /> public void DragEnter(IDropInfo dropInfo) { // nothing here } #endif /// <inheritdoc /> public void DragOver(IDropInfo dropInfo) { var wrapper = GetSerializableWrapper(dropInfo); if (wrapper != null && dropInfo.TargetCollection != null) { dropInfo.Effects = ShouldCopyData(dropInfo, wrapper.DragDropCopyKeyState) ? DragDropEffects.Copy : DragDropEffects.Move; dropInfo.DropTargetAdorner = DropTargetAdorners.Insert; } } #if !NETCOREAPP3_1_OR_GREATER /// <inheritdoc /> public void DragLeave(IDropInfo dropInfo) { // nothing here } #endif /// <inheritdoc /> public void Drop(IDropInfo dropInfo) { var wrapper = GetSerializableWrapper(dropInfo); if (wrapper == null || dropInfo.TargetCollection == null) { return; } // at this point the drag info can be null, cause the other app doesn't know it var insertIndex = dropInfo.UnfilteredInsertIndex; var destinationList = dropInfo.TargetCollection.TryGetList(); var data = wrapper.Items.ToList(); bool isSameCollection = false; var copyData = ShouldCopyData(dropInfo, wrapper.DragDropCopyKeyState); if (!copyData) { var sourceList = dropInfo.DragInfo?.SourceCollection?.TryGetList(); if (sourceList != null) { isSameCollection = sourceList.IsSameObservableCollection(destinationList); if (!isSameCollection) { foreach (var o in data) { var index = sourceList.IndexOf(o); if (index != -1) { sourceList.RemoveAt(index); // so, is the source list the destination list too ? if (destinationList != null && Equals(sourceList, destinationList) && index < insertIndex) { --insertIndex; } } } } } } if (destinationList != null) { var objects2Insert = new List<object>(); // check for cloning var cloneData = dropInfo.Effects.HasFlag(DragDropEffects.Copy) || dropInfo.Effects.HasFlag(DragDropEffects.Link); foreach (var o in data) { var obj2Insert = o; if (cloneData) { if (o is ICloneable cloneable) { obj2Insert = cloneable.Clone(); } } objects2Insert.Add(obj2Insert); if (!cloneData && isSameCollection) { var index = destinationList.IndexOf(o); if (index != -1) { if (insertIndex > index) { insertIndex--; } Move(destinationList, index, insertIndex++); } } else { destinationList.Insert(insertIndex++, obj2Insert); } } DefaultDropHandler.SelectDroppedItems(dropInfo, objects2Insert); } } private static void Move(IList list, int sourceIndex, int destinationIndex) { if (!list.IsObservableCollection()) { throw new ArgumentException("ObservableCollection<T> was expected", nameof(list)); } if (sourceIndex != destinationIndex) { var method = list.GetType().GetMethod("Move", System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.Public); _ = method?.Invoke(list, new object[] { sourceIndex, destinationIndex }); } } private static SerializableWrapper GetSerializableWrapper(IDropInfo dropInfo) { var data = dropInfo.Data; if (data is DataObject dataObject) { var dataFormat = DataFormats.GetDataFormat(DataFormats.Serializable); data = dataObject.GetDataPresent(dataFormat.Name) ? dataObject.GetData(dataFormat.Name) : data; } var wrapper = data as SerializableWrapper; return wrapper; } private static bool ShouldCopyData(IDropInfo dropInfo, DragDropKeyStates dragDropCopyKeyState) { // default should always the move action/effect if (dropInfo == null) { return false; } var copyData = ((dragDropCopyKeyState != default) && dropInfo.KeyStates.HasFlag(dragDropCopyKeyState)) || dragDropCopyKeyState.HasFlag(DragDropKeyStates.LeftMouseButton); return copyData; } } }
34.988095
143
0.493875
[ "BSD-3-Clause" ]
FroggieFrog/gong-wpf-dragdrop
src/Showcase/Models/SerializableDropHandler.cs
5,880
C#
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace LuceneServerNET.Services { public class LuceneServiceOptions { public string RootPath { get; set; } public string ArchivePath { get; set; } } }
20.071429
47
0.704626
[ "Apache-2.0" ]
jugstalt/LuceneServerNET
src/LuceneServerNET/Services/LuceneServiceOptions.cs
283
C#
using System; using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Infrastructure; using Microsoft.EntityFrameworkCore.Metadata; using Microsoft.EntityFrameworkCore.Migrations; using MyCompany.EntityFrameworkCore; namespace MyCompany.Migrations { [DbContext(typeof(MyCompanyDbContext))] [Migration("20170621153937_Added_Description_And_IsActive_To_Role")] partial class Added_Description_And_IsActive_To_Role { protected override void BuildTargetModel(ModelBuilder modelBuilder) { modelBuilder .HasAnnotation("ProductVersion", "1.1.2") .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); modelBuilder.Entity("Abp.Application.Editions.Edition", b => { b.Property<int>("Id") .ValueGeneratedOnAdd() .HasColumnType("int"); b.Property<DateTime>("CreationTime") .HasColumnType("datetime2"); b.Property<long?>("CreatorUserId") .HasColumnType("bigint"); b.Property<long?>("DeleterUserId") .HasColumnType("bigint"); b.Property<DateTime?>("DeletionTime") .HasColumnType("datetime2"); b.Property<string>("DisplayName") .IsRequired() .HasColumnType("nvarchar(64)") .HasMaxLength(64); b.Property<bool>("IsDeleted") .HasColumnType("bit"); b.Property<DateTime?>("LastModificationTime") .HasColumnType("datetime2"); b.Property<long?>("LastModifierUserId") .HasColumnType("bigint"); b.Property<string>("Name") .IsRequired() .HasColumnType("nvarchar(32)") .HasMaxLength(32); b.HasKey("Id"); b.ToTable("AbpEditions"); }); modelBuilder.Entity("Abp.Application.Features.FeatureSetting", b => { b.Property<long>("Id") .ValueGeneratedOnAdd() .HasColumnType("bigint"); b.Property<DateTime>("CreationTime") .HasColumnType("datetime2"); b.Property<long?>("CreatorUserId") .HasColumnType("bigint"); b.Property<string>("Discriminator") .IsRequired() .HasColumnType("nvarchar(max)"); b.Property<string>("Name") .IsRequired() .HasColumnType("nvarchar(128)") .HasMaxLength(128); b.Property<string>("Value") .IsRequired() .HasColumnType("nvarchar(2000)") .HasMaxLength(2000); b.HasKey("Id"); b.ToTable("AbpFeatures"); b.HasDiscriminator<string>("Discriminator").HasValue("FeatureSetting"); }); modelBuilder.Entity("Abp.Auditing.AuditLog", b => { b.Property<long>("Id") .ValueGeneratedOnAdd() .HasColumnType("bigint"); b.Property<string>("BrowserInfo") .HasColumnType("nvarchar(256)") .HasMaxLength(256); b.Property<string>("ClientIpAddress") .HasColumnType("nvarchar(64)") .HasMaxLength(64); b.Property<string>("ClientName") .HasColumnType("nvarchar(128)") .HasMaxLength(128); b.Property<string>("CustomData") .HasColumnType("nvarchar(2000)") .HasMaxLength(2000); b.Property<string>("Exception") .HasColumnType("nvarchar(2000)") .HasMaxLength(2000); b.Property<int>("ExecutionDuration") .HasColumnType("int"); b.Property<DateTime>("ExecutionTime") .HasColumnType("datetime2"); b.Property<int?>("ImpersonatorTenantId") .HasColumnType("int"); b.Property<long?>("ImpersonatorUserId") .HasColumnType("bigint"); b.Property<string>("MethodName") .HasColumnType("nvarchar(256)") .HasMaxLength(256); b.Property<string>("Parameters") .HasColumnType("nvarchar(1024)") .HasMaxLength(1024); b.Property<string>("ServiceName") .HasColumnType("nvarchar(256)") .HasMaxLength(256); b.Property<int?>("TenantId") .HasColumnType("int"); b.Property<long?>("UserId") .HasColumnType("bigint"); b.HasKey("Id"); b.HasIndex("TenantId", "ExecutionDuration"); b.HasIndex("TenantId", "ExecutionTime"); b.HasIndex("TenantId", "UserId"); b.ToTable("AbpAuditLogs"); }); modelBuilder.Entity("Abp.Authorization.PermissionSetting", b => { b.Property<long>("Id") .ValueGeneratedOnAdd() .HasColumnType("bigint"); b.Property<DateTime>("CreationTime") .HasColumnType("datetime2"); b.Property<long?>("CreatorUserId") .HasColumnType("bigint"); b.Property<string>("Discriminator") .IsRequired() .HasColumnType("nvarchar(max)"); b.Property<bool>("IsGranted") .HasColumnType("bit"); b.Property<string>("Name") .IsRequired() .HasColumnType("nvarchar(128)") .HasMaxLength(128); b.Property<int?>("TenantId") .HasColumnType("int"); b.HasKey("Id"); b.HasIndex("TenantId", "Name"); b.ToTable("AbpPermissions"); b.HasDiscriminator<string>("Discriminator").HasValue("PermissionSetting"); }); modelBuilder.Entity("Abp.Authorization.Roles.RoleClaim", b => { b.Property<long>("Id") .ValueGeneratedOnAdd() .HasColumnType("bigint"); b.Property<string>("ClaimType") .HasColumnType("nvarchar(450)"); b.Property<string>("ClaimValue") .HasColumnType("nvarchar(max)"); b.Property<DateTime>("CreationTime") .HasColumnType("datetime2"); b.Property<long?>("CreatorUserId") .HasColumnType("bigint"); b.Property<int>("RoleId") .HasColumnType("int"); b.Property<int?>("TenantId") .HasColumnType("int"); b.HasKey("Id"); b.HasIndex("RoleId"); b.HasIndex("TenantId", "ClaimType"); b.ToTable("AbpRoleClaims"); }); modelBuilder.Entity("Abp.Authorization.Users.UserAccount", b => { b.Property<long>("Id") .ValueGeneratedOnAdd() .HasColumnType("bigint"); b.Property<DateTime>("CreationTime") .HasColumnType("datetime2"); b.Property<long?>("CreatorUserId") .HasColumnType("bigint"); b.Property<long?>("DeleterUserId") .HasColumnType("bigint"); b.Property<DateTime?>("DeletionTime") .HasColumnType("datetime2"); b.Property<string>("EmailAddress") .HasColumnType("nvarchar(450)"); b.Property<bool>("IsDeleted") .HasColumnType("bit"); b.Property<DateTime?>("LastLoginTime") .HasColumnType("datetime2"); b.Property<DateTime?>("LastModificationTime") .HasColumnType("datetime2"); b.Property<long?>("LastModifierUserId") .HasColumnType("bigint"); b.Property<int?>("TenantId") .HasColumnType("int"); b.Property<long>("UserId") .HasColumnType("bigint"); b.Property<long?>("UserLinkId") .HasColumnType("bigint"); b.Property<string>("UserName") .HasColumnType("nvarchar(450)"); b.HasKey("Id"); b.HasIndex("EmailAddress"); b.HasIndex("UserName"); b.HasIndex("TenantId", "EmailAddress"); b.HasIndex("TenantId", "UserId"); b.HasIndex("TenantId", "UserName"); b.ToTable("AbpUserAccounts"); }); modelBuilder.Entity("Abp.Authorization.Users.UserClaim", b => { b.Property<long>("Id") .ValueGeneratedOnAdd() .HasColumnType("bigint"); b.Property<string>("ClaimType") .HasColumnType("nvarchar(450)"); b.Property<string>("ClaimValue") .HasColumnType("nvarchar(max)"); b.Property<DateTime>("CreationTime") .HasColumnType("datetime2"); b.Property<long?>("CreatorUserId") .HasColumnType("bigint"); b.Property<int?>("TenantId") .HasColumnType("int"); b.Property<long>("UserId") .HasColumnType("bigint"); b.HasKey("Id"); b.HasIndex("UserId"); b.HasIndex("TenantId", "ClaimType"); b.ToTable("AbpUserClaims"); }); modelBuilder.Entity("Abp.Authorization.Users.UserLogin", b => { b.Property<long>("Id") .ValueGeneratedOnAdd() .HasColumnType("bigint"); b.Property<string>("LoginProvider") .IsRequired() .HasColumnType("nvarchar(128)") .HasMaxLength(128); b.Property<string>("ProviderKey") .IsRequired() .HasColumnType("nvarchar(256)") .HasMaxLength(256); b.Property<int?>("TenantId") .HasColumnType("int"); b.Property<long>("UserId") .HasColumnType("bigint"); b.HasKey("Id"); b.HasIndex("UserId"); b.HasIndex("TenantId", "UserId"); b.HasIndex("TenantId", "LoginProvider", "ProviderKey"); b.ToTable("AbpUserLogins"); }); modelBuilder.Entity("Abp.Authorization.Users.UserLoginAttempt", b => { b.Property<long>("Id") .ValueGeneratedOnAdd() .HasColumnType("bigint"); b.Property<string>("BrowserInfo") .HasColumnType("nvarchar(256)") .HasMaxLength(256); b.Property<string>("ClientIpAddress") .HasColumnType("nvarchar(64)") .HasMaxLength(64); b.Property<string>("ClientName") .HasColumnType("nvarchar(128)") .HasMaxLength(128); b.Property<DateTime>("CreationTime") .HasColumnType("datetime2"); b.Property<byte>("Result") .HasColumnType("tinyint"); b.Property<string>("TenancyName") .HasColumnType("nvarchar(64)") .HasMaxLength(64); b.Property<int?>("TenantId") .HasColumnType("int"); b.Property<long?>("UserId") .HasColumnType("bigint"); b.Property<string>("UserNameOrEmailAddress") .HasColumnType("nvarchar(255)") .HasMaxLength(255); b.HasKey("Id"); b.HasIndex("UserId", "TenantId"); b.HasIndex("TenancyName", "UserNameOrEmailAddress", "Result"); b.ToTable("AbpUserLoginAttempts"); }); modelBuilder.Entity("Abp.Authorization.Users.UserOrganizationUnit", b => { b.Property<long>("Id") .ValueGeneratedOnAdd() .HasColumnType("bigint"); b.Property<DateTime>("CreationTime") .HasColumnType("datetime2"); b.Property<long?>("CreatorUserId") .HasColumnType("bigint"); b.Property<long>("OrganizationUnitId") .HasColumnType("bigint"); b.Property<int?>("TenantId") .HasColumnType("int"); b.Property<long>("UserId") .HasColumnType("bigint"); b.HasKey("Id"); b.HasIndex("TenantId", "OrganizationUnitId"); b.HasIndex("TenantId", "UserId"); b.ToTable("AbpUserOrganizationUnits"); }); modelBuilder.Entity("Abp.Authorization.Users.UserRole", b => { b.Property<long>("Id") .ValueGeneratedOnAdd() .HasColumnType("bigint"); b.Property<DateTime>("CreationTime") .HasColumnType("datetime2"); b.Property<long?>("CreatorUserId") .HasColumnType("bigint"); b.Property<int>("RoleId") .HasColumnType("int"); b.Property<int?>("TenantId") .HasColumnType("int"); b.Property<long>("UserId") .HasColumnType("bigint"); b.HasKey("Id"); b.HasIndex("UserId"); b.HasIndex("TenantId", "RoleId"); b.HasIndex("TenantId", "UserId"); b.ToTable("AbpUserRoles"); }); modelBuilder.Entity("Abp.Authorization.Users.UserToken", b => { b.Property<long>("Id") .ValueGeneratedOnAdd() .HasColumnType("bigint"); b.Property<string>("LoginProvider") .HasColumnType("nvarchar(max)"); b.Property<string>("Name") .HasColumnType("nvarchar(max)"); b.Property<int?>("TenantId") .HasColumnType("int"); b.Property<long>("UserId") .HasColumnType("bigint"); b.Property<string>("Value") .HasColumnType("nvarchar(max)"); b.HasKey("Id"); b.HasIndex("UserId"); b.HasIndex("TenantId", "UserId"); b.ToTable("AbpUserTokens"); }); modelBuilder.Entity("Abp.BackgroundJobs.BackgroundJobInfo", b => { b.Property<long>("Id") .ValueGeneratedOnAdd() .HasColumnType("bigint"); b.Property<DateTime>("CreationTime") .HasColumnType("datetime2"); b.Property<long?>("CreatorUserId") .HasColumnType("bigint"); b.Property<bool>("IsAbandoned") .HasColumnType("bit"); b.Property<string>("JobArgs") .IsRequired() .HasColumnType("nvarchar(max)") .HasMaxLength(1048576); b.Property<string>("JobType") .IsRequired() .HasColumnType("nvarchar(512)") .HasMaxLength(512); b.Property<DateTime?>("LastTryTime") .HasColumnType("datetime2"); b.Property<DateTime>("NextTryTime") .HasColumnType("datetime2"); b.Property<byte>("Priority") .HasColumnType("tinyint"); b.Property<short>("TryCount") .HasColumnType("smallint"); b.HasKey("Id"); b.HasIndex("IsAbandoned", "NextTryTime"); b.ToTable("AbpBackgroundJobs"); }); modelBuilder.Entity("Abp.Configuration.Setting", b => { b.Property<long>("Id") .ValueGeneratedOnAdd() .HasColumnType("bigint"); b.Property<DateTime>("CreationTime") .HasColumnType("datetime2"); b.Property<long?>("CreatorUserId") .HasColumnType("bigint"); b.Property<DateTime?>("LastModificationTime") .HasColumnType("datetime2"); b.Property<long?>("LastModifierUserId") .HasColumnType("bigint"); b.Property<string>("Name") .IsRequired() .HasColumnType("nvarchar(256)") .HasMaxLength(256); b.Property<int?>("TenantId") .HasColumnType("int"); b.Property<long?>("UserId") .HasColumnType("bigint"); b.Property<string>("Value") .HasColumnType("nvarchar(2000)") .HasMaxLength(2000); b.HasKey("Id"); b.HasIndex("UserId"); b.HasIndex("TenantId", "Name"); b.ToTable("AbpSettings"); }); modelBuilder.Entity("Abp.Localization.ApplicationLanguage", b => { b.Property<int>("Id") .ValueGeneratedOnAdd() .HasColumnType("int"); b.Property<DateTime>("CreationTime") .HasColumnType("datetime2"); b.Property<long?>("CreatorUserId") .HasColumnType("bigint"); b.Property<long?>("DeleterUserId") .HasColumnType("bigint"); b.Property<DateTime?>("DeletionTime") .HasColumnType("datetime2"); b.Property<string>("DisplayName") .IsRequired() .HasColumnType("nvarchar(64)") .HasMaxLength(64); b.Property<string>("Icon") .HasColumnType("nvarchar(128)") .HasMaxLength(128); b.Property<bool>("IsDeleted") .HasColumnType("bit"); b.Property<bool>("IsDisabled") .HasColumnType("bit"); b.Property<DateTime?>("LastModificationTime") .HasColumnType("datetime2"); b.Property<long?>("LastModifierUserId") .HasColumnType("bigint"); b.Property<string>("Name") .IsRequired() .HasColumnType("nvarchar(10)") .HasMaxLength(10); b.Property<int?>("TenantId") .HasColumnType("int"); b.HasKey("Id"); b.HasIndex("TenantId", "Name"); b.ToTable("AbpLanguages"); }); modelBuilder.Entity("Abp.Localization.ApplicationLanguageText", b => { b.Property<long>("Id") .ValueGeneratedOnAdd() .HasColumnType("bigint"); b.Property<DateTime>("CreationTime") .HasColumnType("datetime2"); b.Property<long?>("CreatorUserId") .HasColumnType("bigint"); b.Property<string>("Key") .IsRequired() .HasColumnType("nvarchar(256)") .HasMaxLength(256); b.Property<string>("LanguageName") .IsRequired() .HasColumnType("nvarchar(10)") .HasMaxLength(10); b.Property<DateTime?>("LastModificationTime") .HasColumnType("datetime2"); b.Property<long?>("LastModifierUserId") .HasColumnType("bigint"); b.Property<string>("Source") .IsRequired() .HasColumnType("nvarchar(128)") .HasMaxLength(128); b.Property<int?>("TenantId") .HasColumnType("int"); b.Property<string>("Value") .IsRequired() .HasColumnType("nvarchar(max)") .HasMaxLength(67108864); b.HasKey("Id"); b.HasIndex("TenantId", "Source", "LanguageName", "Key"); b.ToTable("AbpLanguageTexts"); }); modelBuilder.Entity("Abp.Notifications.NotificationInfo", b => { b.Property<Guid>("Id") .ValueGeneratedOnAdd() .HasColumnType("uniqueidentifier"); b.Property<DateTime>("CreationTime") .HasColumnType("datetime2"); b.Property<long?>("CreatorUserId") .HasColumnType("bigint"); b.Property<string>("Data") .HasColumnType("nvarchar(max)") .HasMaxLength(1048576); b.Property<string>("DataTypeName") .HasColumnType("nvarchar(512)") .HasMaxLength(512); b.Property<string>("EntityId") .HasColumnType("nvarchar(96)") .HasMaxLength(96); b.Property<string>("EntityTypeAssemblyQualifiedName") .HasColumnType("nvarchar(512)") .HasMaxLength(512); b.Property<string>("EntityTypeName") .HasColumnType("nvarchar(250)") .HasMaxLength(250); b.Property<string>("ExcludedUserIds") .HasColumnType("nvarchar(max)") .HasMaxLength(131072); b.Property<string>("NotificationName") .IsRequired() .HasColumnType("nvarchar(96)") .HasMaxLength(96); b.Property<byte>("Severity") .HasColumnType("tinyint"); b.Property<string>("TenantIds") .HasColumnType("nvarchar(max)") .HasMaxLength(131072); b.Property<string>("UserIds") .HasColumnType("nvarchar(max)") .HasMaxLength(131072); b.HasKey("Id"); b.ToTable("AbpNotifications"); }); modelBuilder.Entity("Abp.Notifications.NotificationSubscriptionInfo", b => { b.Property<Guid>("Id") .ValueGeneratedOnAdd() .HasColumnType("uniqueidentifier"); b.Property<DateTime>("CreationTime") .HasColumnType("datetime2"); b.Property<long?>("CreatorUserId") .HasColumnType("bigint"); b.Property<string>("EntityId") .HasColumnType("nvarchar(96)") .HasMaxLength(96); b.Property<string>("EntityTypeAssemblyQualifiedName") .HasColumnType("nvarchar(512)") .HasMaxLength(512); b.Property<string>("EntityTypeName") .HasColumnType("nvarchar(250)") .HasMaxLength(250); b.Property<string>("NotificationName") .HasColumnType("nvarchar(96)") .HasMaxLength(96); b.Property<int?>("TenantId") .HasColumnType("int"); b.Property<long>("UserId") .HasColumnType("bigint"); b.HasKey("Id"); b.HasIndex("NotificationName", "EntityTypeName", "EntityId", "UserId"); b.HasIndex("TenantId", "NotificationName", "EntityTypeName", "EntityId", "UserId"); b.ToTable("AbpNotificationSubscriptions"); }); modelBuilder.Entity("Abp.Notifications.TenantNotificationInfo", b => { b.Property<Guid>("Id") .ValueGeneratedOnAdd() .HasColumnType("uniqueidentifier"); b.Property<DateTime>("CreationTime") .HasColumnType("datetime2"); b.Property<long?>("CreatorUserId") .HasColumnType("bigint"); b.Property<string>("Data") .HasColumnType("nvarchar(max)") .HasMaxLength(1048576); b.Property<string>("DataTypeName") .HasColumnType("nvarchar(512)") .HasMaxLength(512); b.Property<string>("EntityId") .HasColumnType("nvarchar(96)") .HasMaxLength(96); b.Property<string>("EntityTypeAssemblyQualifiedName") .HasColumnType("nvarchar(512)") .HasMaxLength(512); b.Property<string>("EntityTypeName") .HasColumnType("nvarchar(250)") .HasMaxLength(250); b.Property<string>("NotificationName") .IsRequired() .HasColumnType("nvarchar(96)") .HasMaxLength(96); b.Property<byte>("Severity") .HasColumnType("tinyint"); b.Property<int?>("TenantId") .HasColumnType("int"); b.HasKey("Id"); b.HasIndex("TenantId"); b.ToTable("AbpTenantNotifications"); }); modelBuilder.Entity("Abp.Notifications.UserNotificationInfo", b => { b.Property<Guid>("Id") .ValueGeneratedOnAdd() .HasColumnType("uniqueidentifier"); b.Property<DateTime>("CreationTime") .HasColumnType("datetime2"); b.Property<int>("State") .HasColumnType("int"); b.Property<int?>("TenantId") .HasColumnType("int"); b.Property<Guid>("TenantNotificationId") .HasColumnType("uniqueidentifier"); b.Property<long>("UserId") .HasColumnType("bigint"); b.HasKey("Id"); b.HasIndex("UserId", "State", "CreationTime"); b.ToTable("AbpUserNotifications"); }); modelBuilder.Entity("Abp.Organizations.OrganizationUnit", b => { b.Property<long>("Id") .ValueGeneratedOnAdd() .HasColumnType("bigint"); b.Property<string>("Code") .IsRequired() .HasColumnType("nvarchar(95)") .HasMaxLength(95); b.Property<DateTime>("CreationTime") .HasColumnType("datetime2"); b.Property<long?>("CreatorUserId") .HasColumnType("bigint"); b.Property<long?>("DeleterUserId") .HasColumnType("bigint"); b.Property<DateTime?>("DeletionTime") .HasColumnType("datetime2"); b.Property<string>("DisplayName") .IsRequired() .HasColumnType("nvarchar(128)") .HasMaxLength(128); b.Property<bool>("IsDeleted") .HasColumnType("bit"); b.Property<DateTime?>("LastModificationTime") .HasColumnType("datetime2"); b.Property<long?>("LastModifierUserId") .HasColumnType("bigint"); b.Property<long?>("ParentId") .HasColumnType("bigint"); b.Property<int?>("TenantId") .HasColumnType("int"); b.HasKey("Id"); b.HasIndex("ParentId"); b.HasIndex("TenantId", "Code"); b.ToTable("AbpOrganizationUnits"); }); modelBuilder.Entity("MyCompany.Authorization.Roles.Role", b => { b.Property<int>("Id") .ValueGeneratedOnAdd() .HasColumnType("int"); b.Property<string>("ConcurrencyStamp") .IsConcurrencyToken() .HasColumnType("nvarchar(max)"); b.Property<DateTime>("CreationTime") .HasColumnType("datetime2"); b.Property<long?>("CreatorUserId") .HasColumnType("bigint"); b.Property<long?>("DeleterUserId") .HasColumnType("bigint"); b.Property<DateTime?>("DeletionTime") .HasColumnType("datetime2"); b.Property<string>("Description") .HasColumnType("nvarchar(max)") .HasMaxLength(5000); b.Property<string>("DisplayName") .IsRequired() .HasColumnType("nvarchar(64)") .HasMaxLength(64); b.Property<bool>("IsActive") .HasColumnType("bit"); b.Property<bool>("IsDefault") .HasColumnType("bit"); b.Property<bool>("IsDeleted") .HasColumnType("bit"); b.Property<bool>("IsStatic") .HasColumnType("bit"); b.Property<DateTime?>("LastModificationTime") .HasColumnType("datetime2"); b.Property<long?>("LastModifierUserId") .HasColumnType("bigint"); b.Property<string>("Name") .IsRequired() .HasColumnType("nvarchar(32)") .HasMaxLength(32); b.Property<string>("NormalizedName") .IsRequired() .HasColumnType("nvarchar(32)") .HasMaxLength(32); b.Property<int?>("TenantId") .HasColumnType("int"); b.HasKey("Id"); b.HasIndex("CreatorUserId"); b.HasIndex("DeleterUserId"); b.HasIndex("LastModifierUserId"); b.HasIndex("TenantId", "NormalizedName"); b.ToTable("AbpRoles"); }); modelBuilder.Entity("MyCompany.Authorization.Users.User", b => { b.Property<long>("Id") .ValueGeneratedOnAdd() .HasColumnType("bigint"); b.Property<int>("AccessFailedCount") .HasColumnType("int"); b.Property<string>("AuthenticationSource") .HasColumnType("nvarchar(64)") .HasMaxLength(64); b.Property<string>("ConcurrencyStamp") .IsConcurrencyToken() .HasColumnType("nvarchar(max)"); b.Property<DateTime>("CreationTime") .HasColumnType("datetime2"); b.Property<long?>("CreatorUserId") .HasColumnType("bigint"); b.Property<long?>("DeleterUserId") .HasColumnType("bigint"); b.Property<DateTime?>("DeletionTime") .HasColumnType("datetime2"); b.Property<string>("EmailAddress") .IsRequired() .HasColumnType("nvarchar(256)") .HasMaxLength(256); b.Property<string>("EmailConfirmationCode") .HasColumnType("nvarchar(328)") .HasMaxLength(328); b.Property<bool>("IsActive") .HasColumnType("bit"); b.Property<bool>("IsDeleted") .HasColumnType("bit"); b.Property<bool>("IsEmailConfirmed") .HasColumnType("bit"); b.Property<bool>("IsLockoutEnabled") .HasColumnType("bit"); b.Property<bool>("IsPhoneNumberConfirmed") .HasColumnType("bit"); b.Property<bool>("IsTwoFactorEnabled") .HasColumnType("bit"); b.Property<DateTime?>("LastLoginTime") .HasColumnType("datetime2"); b.Property<DateTime?>("LastModificationTime") .HasColumnType("datetime2"); b.Property<long?>("LastModifierUserId") .HasColumnType("bigint"); b.Property<DateTime?>("LockoutEndDateUtc") .HasColumnType("datetime2"); b.Property<string>("Name") .IsRequired() .HasColumnType("nvarchar(32)") .HasMaxLength(32); b.Property<string>("NormalizedEmailAddress") .IsRequired() .HasColumnType("nvarchar(256)") .HasMaxLength(256); b.Property<string>("NormalizedUserName") .IsRequired() .HasColumnType("nvarchar(32)") .HasMaxLength(32); b.Property<string>("Password") .IsRequired() .HasColumnType("nvarchar(128)") .HasMaxLength(128); b.Property<string>("PasswordResetCode") .HasColumnType("nvarchar(328)") .HasMaxLength(328); b.Property<string>("PhoneNumber") .HasColumnType("nvarchar(max)"); b.Property<string>("SecurityStamp") .HasColumnType("nvarchar(max)"); b.Property<string>("Surname") .IsRequired() .HasColumnType("nvarchar(32)") .HasMaxLength(32); b.Property<int?>("TenantId") .HasColumnType("int"); b.Property<string>("UserName") .IsRequired() .HasColumnType("nvarchar(32)") .HasMaxLength(32); b.HasKey("Id"); b.HasIndex("CreatorUserId"); b.HasIndex("DeleterUserId"); b.HasIndex("LastModifierUserId"); b.HasIndex("TenantId", "NormalizedEmailAddress"); b.HasIndex("TenantId", "NormalizedUserName"); b.ToTable("AbpUsers"); }); modelBuilder.Entity("MyCompany.MultiTenancy.Tenant", b => { b.Property<int>("Id") .ValueGeneratedOnAdd() .HasColumnType("int"); b.Property<string>("ConnectionString") .HasColumnType("nvarchar(1024)") .HasMaxLength(1024); b.Property<DateTime>("CreationTime") .HasColumnType("datetime2"); b.Property<long?>("CreatorUserId") .HasColumnType("bigint"); b.Property<long?>("DeleterUserId") .HasColumnType("bigint"); b.Property<DateTime?>("DeletionTime") .HasColumnType("datetime2"); b.Property<int?>("EditionId") .HasColumnType("int"); b.Property<bool>("IsActive") .HasColumnType("bit"); b.Property<bool>("IsDeleted") .HasColumnType("bit"); b.Property<DateTime?>("LastModificationTime") .HasColumnType("datetime2"); b.Property<long?>("LastModifierUserId") .HasColumnType("bigint"); b.Property<string>("Name") .IsRequired() .HasColumnType("nvarchar(128)") .HasMaxLength(128); b.Property<string>("TenancyName") .IsRequired() .HasColumnType("nvarchar(64)") .HasMaxLength(64); b.HasKey("Id"); b.HasIndex("CreatorUserId"); b.HasIndex("DeleterUserId"); b.HasIndex("EditionId"); b.HasIndex("LastModifierUserId"); b.HasIndex("TenancyName"); b.ToTable("AbpTenants"); }); modelBuilder.Entity("Abp.Application.Features.EditionFeatureSetting", b => { b.HasBaseType("Abp.Application.Features.FeatureSetting"); b.Property<int>("EditionId") .HasColumnType("int"); b.HasIndex("EditionId", "Name"); b.ToTable("AbpFeatures"); b.HasDiscriminator().HasValue("EditionFeatureSetting"); }); modelBuilder.Entity("Abp.MultiTenancy.TenantFeatureSetting", b => { b.HasBaseType("Abp.Application.Features.FeatureSetting"); b.Property<int>("TenantId") .HasColumnType("int"); b.HasIndex("TenantId", "Name"); b.ToTable("AbpFeatures"); b.HasDiscriminator().HasValue("TenantFeatureSetting"); }); modelBuilder.Entity("Abp.Authorization.Roles.RolePermissionSetting", b => { b.HasBaseType("Abp.Authorization.PermissionSetting"); b.Property<int>("RoleId") .HasColumnType("int"); b.HasIndex("RoleId"); b.ToTable("AbpPermissions"); b.HasDiscriminator().HasValue("RolePermissionSetting"); }); modelBuilder.Entity("Abp.Authorization.Users.UserPermissionSetting", b => { b.HasBaseType("Abp.Authorization.PermissionSetting"); b.Property<long>("UserId") .HasColumnType("bigint"); b.HasIndex("UserId"); b.ToTable("AbpPermissions"); b.HasDiscriminator().HasValue("UserPermissionSetting"); }); modelBuilder.Entity("Abp.Authorization.Roles.RoleClaim", b => { b.HasOne("MyCompany.Authorization.Roles.Role") .WithMany("Claims") .HasForeignKey("RoleId") .OnDelete(DeleteBehavior.Cascade); }); modelBuilder.Entity("Abp.Authorization.Users.UserClaim", b => { b.HasOne("MyCompany.Authorization.Users.User") .WithMany("Claims") .HasForeignKey("UserId") .OnDelete(DeleteBehavior.Cascade); }); modelBuilder.Entity("Abp.Authorization.Users.UserLogin", b => { b.HasOne("MyCompany.Authorization.Users.User") .WithMany("Logins") .HasForeignKey("UserId") .OnDelete(DeleteBehavior.Cascade); }); modelBuilder.Entity("Abp.Authorization.Users.UserRole", b => { b.HasOne("MyCompany.Authorization.Users.User") .WithMany("Roles") .HasForeignKey("UserId") .OnDelete(DeleteBehavior.Cascade); }); modelBuilder.Entity("Abp.Authorization.Users.UserToken", b => { b.HasOne("MyCompany.Authorization.Users.User") .WithMany("Tokens") .HasForeignKey("UserId") .OnDelete(DeleteBehavior.Cascade); }); modelBuilder.Entity("Abp.Configuration.Setting", b => { b.HasOne("MyCompany.Authorization.Users.User") .WithMany("Settings") .HasForeignKey("UserId"); }); modelBuilder.Entity("Abp.Organizations.OrganizationUnit", b => { b.HasOne("Abp.Organizations.OrganizationUnit", "Parent") .WithMany("Children") .HasForeignKey("ParentId"); }); modelBuilder.Entity("MyCompany.Authorization.Roles.Role", b => { b.HasOne("MyCompany.Authorization.Users.User", "CreatorUser") .WithMany() .HasForeignKey("CreatorUserId"); b.HasOne("MyCompany.Authorization.Users.User", "DeleterUser") .WithMany() .HasForeignKey("DeleterUserId"); b.HasOne("MyCompany.Authorization.Users.User", "LastModifierUser") .WithMany() .HasForeignKey("LastModifierUserId"); }); modelBuilder.Entity("MyCompany.Authorization.Users.User", b => { b.HasOne("MyCompany.Authorization.Users.User", "CreatorUser") .WithMany() .HasForeignKey("CreatorUserId"); b.HasOne("MyCompany.Authorization.Users.User", "DeleterUser") .WithMany() .HasForeignKey("DeleterUserId"); b.HasOne("MyCompany.Authorization.Users.User", "LastModifierUser") .WithMany() .HasForeignKey("LastModifierUserId"); }); modelBuilder.Entity("MyCompany.MultiTenancy.Tenant", b => { b.HasOne("MyCompany.Authorization.Users.User", "CreatorUser") .WithMany() .HasForeignKey("CreatorUserId"); b.HasOne("MyCompany.Authorization.Users.User", "DeleterUser") .WithMany() .HasForeignKey("DeleterUserId"); b.HasOne("Abp.Application.Editions.Edition", "Edition") .WithMany() .HasForeignKey("EditionId"); b.HasOne("MyCompany.Authorization.Users.User", "LastModifierUser") .WithMany() .HasForeignKey("LastModifierUserId"); }); modelBuilder.Entity("Abp.Application.Features.EditionFeatureSetting", b => { b.HasOne("Abp.Application.Editions.Edition", "Edition") .WithMany() .HasForeignKey("EditionId") .OnDelete(DeleteBehavior.Cascade); }); modelBuilder.Entity("Abp.Authorization.Roles.RolePermissionSetting", b => { b.HasOne("MyCompany.Authorization.Roles.Role") .WithMany("Permissions") .HasForeignKey("RoleId") .OnDelete(DeleteBehavior.Cascade); }); modelBuilder.Entity("Abp.Authorization.Users.UserPermissionSetting", b => { b.HasOne("MyCompany.Authorization.Users.User") .WithMany("Permissions") .HasForeignKey("UserId") .OnDelete(DeleteBehavior.Cascade); }); } } }
35.42511
117
0.430206
[ "MIT" ]
StefanKoenen/aspnetboilerplate-5844
aspnet-core/src/MyCompany.EntityFrameworkCore/Migrations/20170621153937_Added_Description_And_IsActive_To_Role.Designer.cs
48,249
C#
#pragma checksum "..\..\..\..\pages\report\ReportPage.xaml" "{ff1816ec-aa5e-4d10-87f7-6f4963833460}" "5D84D8A3900FA93149CB19FBBCFAFE2E128DAEF0" //------------------------------------------------------------------------------ // <auto-generated> // 此代码由工具生成。 // 运行时版本:4.0.30319.42000 // // 对此文件的更改可能会导致不正确的行为,并且如果 // 重新生成代码,这些更改将会丢失。 // </auto-generated> //------------------------------------------------------------------------------ using System; using System.Diagnostics; using System.Windows; using System.Windows.Automation; using System.Windows.Controls; using System.Windows.Controls.Primitives; using System.Windows.Data; using System.Windows.Documents; using System.Windows.Ink; using System.Windows.Input; using System.Windows.Markup; using System.Windows.Media; using System.Windows.Media.Animation; using System.Windows.Media.Effects; using System.Windows.Media.Imaging; using System.Windows.Media.Media3D; using System.Windows.Media.TextFormatting; using System.Windows.Navigation; using System.Windows.Shapes; using System.Windows.Shell; namespace EPSM_System.pages.report { /// <summary> /// ReportPage /// </summary> public partial class ReportPage : System.Windows.Controls.Page, System.Windows.Markup.IComponentConnector { #line 12 "..\..\..\..\pages\report\ReportPage.xaml" [System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1823:AvoidUnusedPrivateFields")] internal System.Windows.Controls.Button btnAdd; #line default #line hidden #line 15 "..\..\..\..\pages\report\ReportPage.xaml" [System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1823:AvoidUnusedPrivateFields")] internal System.Windows.Controls.Button btnEdit; #line default #line hidden #line 18 "..\..\..\..\pages\report\ReportPage.xaml" [System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1823:AvoidUnusedPrivateFields")] internal System.Windows.Controls.Button btnDelete; #line default #line hidden #line 22 "..\..\..\..\pages\report\ReportPage.xaml" [System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1823:AvoidUnusedPrivateFields")] internal System.Windows.Controls.DatePicker dpStartDate; #line default #line hidden #line 24 "..\..\..\..\pages\report\ReportPage.xaml" [System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1823:AvoidUnusedPrivateFields")] internal System.Windows.Controls.DatePicker dpEndDate; #line default #line hidden #line 25 "..\..\..\..\pages\report\ReportPage.xaml" [System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1823:AvoidUnusedPrivateFields")] internal System.Windows.Controls.Button btnSearch; #line default #line hidden #line 29 "..\..\..\..\pages\report\ReportPage.xaml" [System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1823:AvoidUnusedPrivateFields")] internal System.Windows.Controls.DataGrid dgUsers; #line default #line hidden private bool _contentLoaded; /// <summary> /// InitializeComponent /// </summary> [System.Diagnostics.DebuggerNonUserCodeAttribute()] [System.CodeDom.Compiler.GeneratedCodeAttribute("PresentationBuildTasks", "4.0.0.0")] public void InitializeComponent() { if (_contentLoaded) { return; } _contentLoaded = true; System.Uri resourceLocater = new System.Uri("/EPSM_System;component/pages/report/reportpage.xaml", System.UriKind.Relative); #line 1 "..\..\..\..\pages\report\ReportPage.xaml" System.Windows.Application.LoadComponent(this, resourceLocater); #line default #line hidden } [System.Diagnostics.DebuggerNonUserCodeAttribute()] [System.CodeDom.Compiler.GeneratedCodeAttribute("PresentationBuildTasks", "4.0.0.0")] [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] [System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Design", "CA1033:InterfaceMethodsShouldBeCallableByChildTypes")] [System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity")] [System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1800:DoNotCastUnnecessarily")] void System.Windows.Markup.IComponentConnector.Connect(int connectionId, object target) { switch (connectionId) { case 1: this.btnAdd = ((System.Windows.Controls.Button)(target)); #line 12 "..\..\..\..\pages\report\ReportPage.xaml" this.btnAdd.Click += new System.Windows.RoutedEventHandler(this.BtnAdd_Click); #line default #line hidden return; case 2: this.btnEdit = ((System.Windows.Controls.Button)(target)); #line 15 "..\..\..\..\pages\report\ReportPage.xaml" this.btnEdit.Click += new System.Windows.RoutedEventHandler(this.BtnEdit_Click); #line default #line hidden return; case 3: this.btnDelete = ((System.Windows.Controls.Button)(target)); #line 18 "..\..\..\..\pages\report\ReportPage.xaml" this.btnDelete.Click += new System.Windows.RoutedEventHandler(this.BtnDelete_Click); #line default #line hidden return; case 4: this.dpStartDate = ((System.Windows.Controls.DatePicker)(target)); return; case 5: this.dpEndDate = ((System.Windows.Controls.DatePicker)(target)); return; case 6: this.btnSearch = ((System.Windows.Controls.Button)(target)); #line 25 "..\..\..\..\pages\report\ReportPage.xaml" this.btnSearch.Click += new System.Windows.RoutedEventHandler(this.BtnSearch_Click); #line default #line hidden return; case 7: this.dgUsers = ((System.Windows.Controls.DataGrid)(target)); return; } this._contentLoaded = true; } } }
38.715084
144
0.611544
[ "Apache-2.0" ]
yuanhang110/EPSM_System
EPSM_System/obj/Debug/pages/report/ReportPage.g.cs
7,038
C#
using Ship; using System.Collections; using System.Collections.Generic; using System.Linq; using Tokens; namespace Ship { namespace SecondEdition.VCX100LightFreighter { public class Chopper : VCX100LightFreighter { public Chopper() : base() { PilotInfo = new PilotCardInfo( "\"Chopper\"", 2, 72, isLimited: true, abilityType: typeof(Abilities.SecondEdition.ChopperPilotAbility), seImageNumber: 75 ); } } } } namespace Abilities.SecondEdition { public class ChopperPilotAbility : Abilities.FirstEdition.ChopperPilotAbility { protected override void AssignStressTokenRecursive() { if (shipsToAssignStress.Count > 0) { GenericShip shipToAssignStress = shipsToAssignStress[0]; shipsToAssignStress.Remove(shipToAssignStress); Messages.ShowErrorToHuman(shipToAssignStress.PilotInfo.PilotName + " is bumped into \"Chopper\" and gets a jam token."); shipToAssignStress.Tokens.AssignTokens(() => new JamToken(shipToAssignStress), 2, AssignStressTokenRecursive); } else { Triggers.FinishTrigger(); } } } }
29.395833
136
0.564139
[ "MIT" ]
GeneralVryth/FlyCasual
Assets/Scripts/Model/Content/SecondEdition/Pilots/VCX100LightFreighter/Chopper.cs
1,413
C#
using UnityEngine; namespace Kakomi.Utility { public static class ColorExtension { public static Color SetAlpha(this Color color, float alpha) { return new Color(color.r, color.g, color.b, alpha); } } }
20.916667
67
0.61753
[ "MIT" ]
kitatas/Kakomi
Assets/Kakomi/Scripts/Utility/ColorExtension.cs
251
C#
using System.Collections; using System.Collections.Generic; using UnityEngine; using Valve.VR; public class TrackPadMovement : MonoBehaviour { public float m_Sensitivity = 0.1f; public float m_MaxSpeed = 1.0f; public SteamVR_Action_Boolean m_MovePress = null; public SteamVR_Action_Vector2 m_MoveValue = null; public SteamVR_Input_Sources handType; public SteamVR_Action_Boolean grabGripAction = SteamVR_Input.GetAction<SteamVR_Action_Boolean>("GrabGrip"); private float m_Speed; private CharacterController m_CharacterController = null; private Transform m_CameraRig = null; private Transform m_Head = null; private void Awake() { m_CharacterController = GetComponent<CharacterController>(); } private void Start() { m_CameraRig = SteamVR_Render.Top().origin; m_Head = SteamVR_Render.Top().head; } public void TestingGrab() { if(grabGripAction.GetStateDown(handType)) { Debug.Log("They have Pressed me!"); } } private void Update() { // HandleHead(); // HandleHeight(); CalculateMovement(); } private void HandleHead() { //Store Current Values Vector3 oldPosition = m_CameraRig.position; Quaternion oldRotation = m_CameraRig.rotation; //Rotation transform.eulerAngles = new Vector3(0.0f, m_Head.rotation.eulerAngles.y, 0.0f); //Restore the Values m_CameraRig.position = oldPosition; m_CameraRig.rotation = oldRotation; } private void CalculateMovement() { //Figure Out Movement Orientation Vector3 orientationEuler = new Vector3(0, transform.eulerAngles.y, 0); Quaternion orientation = Quaternion.Euler(orientationEuler); Vector3 movement = Vector3.zero; //If not Moving if(m_MovePress.GetStateUp(SteamVR_Input_Sources.Any)) m_Speed = 0; //If button Pressed if(m_MovePress.state) { // Add then Clamp m_Speed += m_MoveValue.axis.y * m_Sensitivity; m_Speed = Mathf.Clamp(m_Speed, -m_MaxSpeed, m_MaxSpeed); //Orientation movement += orientation * (m_Speed * Vector3.forward) * Time.deltaTime; } // Apply m_CharacterController.Move(movement); } private void HandleHeight() { //Get the Head in local Space float headHeight = Mathf.Clamp(m_Head.localPosition.y, 1, 2); m_CharacterController.height = headHeight; //Cut in Half Vector3 newCenter = Vector3.zero; newCenter.y = m_CharacterController.height / 2; newCenter.y += m_CharacterController.skinWidth; //Move Capsule in LocalSpace newCenter.x = m_Head.localPosition.x; newCenter.z = m_Head.localPosition.z; //Rotate newCenter = Quaternion.Euler(0, -transform.eulerAngles.y, 0) * newCenter; //Apply m_CharacterController.center = newCenter; } }
26.410256
111
0.637217
[ "MIT" ]
TusiimeAllan/VR_Vaccination_Sensitization
Assets/Scripts/TrackPadMovement.cs
3,092
C#