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 |
|---|---|---|---|---|---|---|---|---|
namespace Sekiro_Save_Manager.Forms
{
partial class MainForm
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.components = new System.ComponentModel.Container();
this.btnBackup = new System.Windows.Forms.Button();
this.lvBackups = new System.Windows.Forms.ListView();
this.colComment = ((System.Windows.Forms.ColumnHeader)(new System.Windows.Forms.ColumnHeader()));
this.colDate = ((System.Windows.Forms.ColumnHeader)(new System.Windows.Forms.ColumnHeader()));
this.colLocation = ((System.Windows.Forms.ColumnHeader)(new System.Windows.Forms.ColumnHeader()));
this.colSource = ((System.Windows.Forms.ColumnHeader)(new System.Windows.Forms.ColumnHeader()));
this.btnProfileLocation = new System.Windows.Forms.Button();
this.label2 = new System.Windows.Forms.Label();
this.txtSaveLocation = new System.Windows.Forms.TextBox();
this.tabControl1 = new System.Windows.Forms.TabControl();
this.tabPage1 = new System.Windows.Forms.TabPage();
this.tabPage2 = new System.Windows.Forms.TabPage();
this.txtLog = new System.Windows.Forms.TextBox();
this.tabPage3 = new System.Windows.Forms.TabPage();
this.groupBox1 = new System.Windows.Forms.GroupBox();
this.label1 = new System.Windows.Forms.Label();
this.btnAutoBackupLocation = new System.Windows.Forms.Button();
this.numBackupInterval = new System.Windows.Forms.NumericUpDown();
this.txtAutoBackupLocation = new System.Windows.Forms.TextBox();
this.label3 = new System.Windows.Forms.Label();
this.chkAutoBackup = new System.Windows.Forms.CheckBox();
this.menuStrip1 = new System.Windows.Forms.MenuStrip();
this.fileToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.exitToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.helpToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.aboutToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.BackupTimer = new System.Windows.Forms.Timer(this.components);
this.btnRestore = new System.Windows.Forms.Button();
this.chkHideRestoreWarning = new System.Windows.Forms.CheckBox();
this.chkTrayMinimize = new System.Windows.Forms.CheckBox();
this.TrayIcon = new System.Windows.Forms.NotifyIcon(this.components);
this.btnEdit = new System.Windows.Forms.Button();
this.tabControl1.SuspendLayout();
this.tabPage1.SuspendLayout();
this.tabPage2.SuspendLayout();
this.tabPage3.SuspendLayout();
this.groupBox1.SuspendLayout();
((System.ComponentModel.ISupportInitialize)(this.numBackupInterval)).BeginInit();
this.menuStrip1.SuspendLayout();
this.SuspendLayout();
//
// btnBackup
//
this.btnBackup.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left)));
this.btnBackup.Enabled = false;
this.btnBackup.Location = new System.Drawing.Point(6, 284);
this.btnBackup.Name = "btnBackup";
this.btnBackup.Size = new System.Drawing.Size(75, 23);
this.btnBackup.TabIndex = 0;
this.btnBackup.Text = "Backup...";
this.btnBackup.UseVisualStyleBackColor = true;
this.btnBackup.Click += new System.EventHandler(this.btnBackup_Click);
//
// lvBackups
//
this.lvBackups.Columns.AddRange(new System.Windows.Forms.ColumnHeader[] {
this.colComment,
this.colDate,
this.colLocation,
this.colSource});
this.lvBackups.FullRowSelect = true;
this.lvBackups.Location = new System.Drawing.Point(3, 3);
this.lvBackups.Name = "lvBackups";
this.lvBackups.Size = new System.Drawing.Size(676, 239);
this.lvBackups.TabIndex = 1;
this.lvBackups.UseCompatibleStateImageBehavior = false;
this.lvBackups.View = System.Windows.Forms.View.Details;
this.lvBackups.SelectedIndexChanged += new System.EventHandler(this.lvBackups_SelectedIndexChanged);
//
// colComment
//
this.colComment.Text = "Comment";
this.colComment.Width = 153;
//
// colDate
//
this.colDate.Text = "Backup Date";
this.colDate.Width = 120;
//
// colLocation
//
this.colLocation.Text = "Location";
this.colLocation.Width = 180;
//
// colSource
//
this.colSource.Text = "Source Location";
this.colSource.Width = 212;
//
// btnProfileLocation
//
this.btnProfileLocation.Location = new System.Drawing.Point(498, 34);
this.btnProfileLocation.Name = "btnProfileLocation";
this.btnProfileLocation.Size = new System.Drawing.Size(75, 23);
this.btnProfileLocation.TabIndex = 3;
this.btnProfileLocation.Text = "Browse...";
this.btnProfileLocation.UseVisualStyleBackColor = true;
this.btnProfileLocation.Click += new System.EventHandler(this.btnProfileLocation_Click);
//
// label2
//
this.label2.AutoSize = true;
this.label2.Location = new System.Drawing.Point(6, 13);
this.label2.Name = "label2";
this.label2.Size = new System.Drawing.Size(115, 13);
this.label2.TabIndex = 4;
this.label2.Text = "Game Profile Directory:";
//
// txtSaveLocation
//
this.txtSaveLocation.Location = new System.Drawing.Point(9, 37);
this.txtSaveLocation.Name = "txtSaveLocation";
this.txtSaveLocation.ReadOnly = true;
this.txtSaveLocation.Size = new System.Drawing.Size(483, 20);
this.txtSaveLocation.TabIndex = 5;
//
// tabControl1
//
this.tabControl1.Controls.Add(this.tabPage1);
this.tabControl1.Controls.Add(this.tabPage2);
this.tabControl1.Controls.Add(this.tabPage3);
this.tabControl1.Location = new System.Drawing.Point(12, 27);
this.tabControl1.Name = "tabControl1";
this.tabControl1.SelectedIndex = 0;
this.tabControl1.Size = new System.Drawing.Size(690, 339);
this.tabControl1.TabIndex = 6;
//
// tabPage1
//
this.tabPage1.Controls.Add(this.btnEdit);
this.tabPage1.Controls.Add(this.lvBackups);
this.tabPage1.Controls.Add(this.btnRestore);
this.tabPage1.Controls.Add(this.btnBackup);
this.tabPage1.Location = new System.Drawing.Point(4, 22);
this.tabPage1.Name = "tabPage1";
this.tabPage1.Padding = new System.Windows.Forms.Padding(3);
this.tabPage1.Size = new System.Drawing.Size(682, 313);
this.tabPage1.TabIndex = 0;
this.tabPage1.Text = "Backups";
this.tabPage1.UseVisualStyleBackColor = true;
//
// tabPage2
//
this.tabPage2.Controls.Add(this.txtLog);
this.tabPage2.Location = new System.Drawing.Point(4, 22);
this.tabPage2.Name = "tabPage2";
this.tabPage2.Padding = new System.Windows.Forms.Padding(3);
this.tabPage2.Size = new System.Drawing.Size(682, 284);
this.tabPage2.TabIndex = 1;
this.tabPage2.Text = "Logs";
this.tabPage2.UseVisualStyleBackColor = true;
//
// txtLog
//
this.txtLog.Dock = System.Windows.Forms.DockStyle.Fill;
this.txtLog.Location = new System.Drawing.Point(3, 3);
this.txtLog.Multiline = true;
this.txtLog.Name = "txtLog";
this.txtLog.ReadOnly = true;
this.txtLog.Size = new System.Drawing.Size(676, 278);
this.txtLog.TabIndex = 6;
//
// tabPage3
//
this.tabPage3.Controls.Add(this.chkTrayMinimize);
this.tabPage3.Controls.Add(this.chkHideRestoreWarning);
this.tabPage3.Controls.Add(this.groupBox1);
this.tabPage3.Controls.Add(this.label2);
this.tabPage3.Controls.Add(this.btnProfileLocation);
this.tabPage3.Controls.Add(this.txtSaveLocation);
this.tabPage3.Location = new System.Drawing.Point(4, 22);
this.tabPage3.Name = "tabPage3";
this.tabPage3.Padding = new System.Windows.Forms.Padding(3);
this.tabPage3.Size = new System.Drawing.Size(682, 284);
this.tabPage3.TabIndex = 2;
this.tabPage3.Text = "Options";
this.tabPage3.UseVisualStyleBackColor = true;
//
// groupBox1
//
this.groupBox1.Controls.Add(this.label1);
this.groupBox1.Controls.Add(this.btnAutoBackupLocation);
this.groupBox1.Controls.Add(this.numBackupInterval);
this.groupBox1.Controls.Add(this.txtAutoBackupLocation);
this.groupBox1.Controls.Add(this.label3);
this.groupBox1.Controls.Add(this.chkAutoBackup);
this.groupBox1.Location = new System.Drawing.Point(9, 122);
this.groupBox1.Name = "groupBox1";
this.groupBox1.Size = new System.Drawing.Size(647, 156);
this.groupBox1.TabIndex = 6;
this.groupBox1.TabStop = false;
this.groupBox1.Text = "Incremental Backup";
//
// label1
//
this.label1.AutoSize = true;
this.label1.Location = new System.Drawing.Point(4, 77);
this.label1.Name = "label1";
this.label1.Size = new System.Drawing.Size(139, 13);
this.label1.TabIndex = 7;
this.label1.Text = "Automatic Backup Directory";
//
// btnAutoBackupLocation
//
this.btnAutoBackupLocation.Location = new System.Drawing.Point(495, 99);
this.btnAutoBackupLocation.Name = "btnAutoBackupLocation";
this.btnAutoBackupLocation.Size = new System.Drawing.Size(75, 23);
this.btnAutoBackupLocation.TabIndex = 7;
this.btnAutoBackupLocation.Text = "Browse...";
this.btnAutoBackupLocation.UseVisualStyleBackColor = true;
this.btnAutoBackupLocation.Click += new System.EventHandler(this.btnAutoBackupLocation_Click);
//
// numBackupInterval
//
this.numBackupInterval.Location = new System.Drawing.Point(142, 51);
this.numBackupInterval.Maximum = new decimal(new int[] {
1440,
0,
0,
0});
this.numBackupInterval.Minimum = new decimal(new int[] {
1,
0,
0,
0});
this.numBackupInterval.Name = "numBackupInterval";
this.numBackupInterval.Size = new System.Drawing.Size(88, 20);
this.numBackupInterval.TabIndex = 6;
this.numBackupInterval.Value = new decimal(new int[] {
1,
0,
0,
0});
this.numBackupInterval.ValueChanged += new System.EventHandler(this.numBackupInterval_ValueChanged);
//
// txtAutoBackupLocation
//
this.txtAutoBackupLocation.Location = new System.Drawing.Point(6, 102);
this.txtAutoBackupLocation.Name = "txtAutoBackupLocation";
this.txtAutoBackupLocation.ReadOnly = true;
this.txtAutoBackupLocation.Size = new System.Drawing.Size(483, 20);
this.txtAutoBackupLocation.TabIndex = 8;
//
// label3
//
this.label3.AutoSize = true;
this.label3.Location = new System.Drawing.Point(4, 53);
this.label3.Name = "label3";
this.label3.Size = new System.Drawing.Size(132, 13);
this.label3.TabIndex = 5;
this.label3.Text = "Backup interval (minutes): ";
//
// chkAutoBackup
//
this.chkAutoBackup.AutoSize = true;
this.chkAutoBackup.Location = new System.Drawing.Point(7, 20);
this.chkAutoBackup.Name = "chkAutoBackup";
this.chkAutoBackup.Size = new System.Drawing.Size(160, 17);
this.chkAutoBackup.TabIndex = 0;
this.chkAutoBackup.Text = "Enable incremental backups";
this.chkAutoBackup.UseVisualStyleBackColor = true;
this.chkAutoBackup.CheckedChanged += new System.EventHandler(this.chkAutoBackup_CheckedChanged);
//
// menuStrip1
//
this.menuStrip1.Items.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.fileToolStripMenuItem,
this.helpToolStripMenuItem});
this.menuStrip1.Location = new System.Drawing.Point(0, 0);
this.menuStrip1.Name = "menuStrip1";
this.menuStrip1.Size = new System.Drawing.Size(714, 24);
this.menuStrip1.TabIndex = 7;
this.menuStrip1.Text = "menuStrip1";
//
// fileToolStripMenuItem
//
this.fileToolStripMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.exitToolStripMenuItem});
this.fileToolStripMenuItem.Name = "fileToolStripMenuItem";
this.fileToolStripMenuItem.Size = new System.Drawing.Size(37, 20);
this.fileToolStripMenuItem.Text = "&File";
//
// exitToolStripMenuItem
//
this.exitToolStripMenuItem.Name = "exitToolStripMenuItem";
this.exitToolStripMenuItem.Size = new System.Drawing.Size(92, 22);
this.exitToolStripMenuItem.Text = "&Exit";
this.exitToolStripMenuItem.Click += new System.EventHandler(this.exitToolStripMenuItem_Click);
//
// helpToolStripMenuItem
//
this.helpToolStripMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.aboutToolStripMenuItem});
this.helpToolStripMenuItem.Name = "helpToolStripMenuItem";
this.helpToolStripMenuItem.Size = new System.Drawing.Size(44, 20);
this.helpToolStripMenuItem.Text = "&Help";
//
// aboutToolStripMenuItem
//
this.aboutToolStripMenuItem.Name = "aboutToolStripMenuItem";
this.aboutToolStripMenuItem.Size = new System.Drawing.Size(116, 22);
this.aboutToolStripMenuItem.Text = "About...";
this.aboutToolStripMenuItem.Click += new System.EventHandler(this.aboutToolStripMenuItem_Click);
//
// BackupTimer
//
this.BackupTimer.Interval = 600000;
this.BackupTimer.Tick += new System.EventHandler(this.BackupTimer_Tick);
//
// btnRestore
//
this.btnRestore.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left)));
this.btnRestore.Enabled = false;
this.btnRestore.Location = new System.Drawing.Point(87, 284);
this.btnRestore.Name = "btnRestore";
this.btnRestore.Size = new System.Drawing.Size(75, 23);
this.btnRestore.TabIndex = 8;
this.btnRestore.Text = "Restore...";
this.btnRestore.UseVisualStyleBackColor = true;
this.btnRestore.Click += new System.EventHandler(this.btnRestore_Click);
//
// chkHideRestoreWarning
//
this.chkHideRestoreWarning.AutoSize = true;
this.chkHideRestoreWarning.Location = new System.Drawing.Point(9, 66);
this.chkHideRestoreWarning.Name = "chkHideRestoreWarning";
this.chkHideRestoreWarning.Size = new System.Drawing.Size(204, 17);
this.chkHideRestoreWarning.TabIndex = 9;
this.chkHideRestoreWarning.Text = "Hide warning when restoring backups";
this.chkHideRestoreWarning.UseVisualStyleBackColor = true;
this.chkHideRestoreWarning.CheckedChanged += new System.EventHandler(this.chkHideRestoreWarning_CheckedChanged);
//
// chkTrayMinimize
//
this.chkTrayMinimize.AutoSize = true;
this.chkTrayMinimize.Location = new System.Drawing.Point(9, 89);
this.chkTrayMinimize.Name = "chkTrayMinimize";
this.chkTrayMinimize.Size = new System.Drawing.Size(133, 17);
this.chkTrayMinimize.TabIndex = 10;
this.chkTrayMinimize.Text = "Minimize to system tray";
this.chkTrayMinimize.UseVisualStyleBackColor = true;
//
// TrayIcon
//
this.TrayIcon.Text = "Sekiro Save Manager";
this.TrayIcon.MouseDoubleClick += new System.Windows.Forms.MouseEventHandler(this.TrayIcon_MouseDoubleClick);
//
// btnEdit
//
this.btnEdit.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left)));
this.btnEdit.Enabled = false;
this.btnEdit.Location = new System.Drawing.Point(601, 284);
this.btnEdit.Name = "btnEdit";
this.btnEdit.Size = new System.Drawing.Size(75, 23);
this.btnEdit.TabIndex = 9;
this.btnEdit.Text = "Edit";
this.btnEdit.UseVisualStyleBackColor = true;
this.btnEdit.Click += new System.EventHandler(this.btnEdit_Click);
//
// MainForm
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(714, 378);
this.Controls.Add(this.tabControl1);
this.Controls.Add(this.menuStrip1);
this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedSingle;
this.MainMenuStrip = this.menuStrip1;
this.MaximizeBox = false;
this.Name = "MainForm";
this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen;
this.Text = "Sekiro Save Manager";
this.Resize += new System.EventHandler(this.MainForm_Resize);
this.tabControl1.ResumeLayout(false);
this.tabPage1.ResumeLayout(false);
this.tabPage2.ResumeLayout(false);
this.tabPage2.PerformLayout();
this.tabPage3.ResumeLayout(false);
this.tabPage3.PerformLayout();
this.groupBox1.ResumeLayout(false);
this.groupBox1.PerformLayout();
((System.ComponentModel.ISupportInitialize)(this.numBackupInterval)).EndInit();
this.menuStrip1.ResumeLayout(false);
this.menuStrip1.PerformLayout();
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
private System.Windows.Forms.Button btnBackup;
private System.Windows.Forms.ListView lvBackups;
private System.Windows.Forms.ColumnHeader colComment;
private System.Windows.Forms.ColumnHeader colLocation;
private System.Windows.Forms.ColumnHeader colDate;
private System.Windows.Forms.Button btnProfileLocation;
private System.Windows.Forms.Label label2;
private System.Windows.Forms.TextBox txtSaveLocation;
private System.Windows.Forms.TabControl tabControl1;
private System.Windows.Forms.TabPage tabPage1;
private System.Windows.Forms.TabPage tabPage2;
private System.Windows.Forms.TabPage tabPage3;
private System.Windows.Forms.MenuStrip menuStrip1;
private System.Windows.Forms.ToolStripMenuItem fileToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem exitToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem helpToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem aboutToolStripMenuItem;
private System.Windows.Forms.TextBox txtLog;
private System.Windows.Forms.Timer BackupTimer;
private System.Windows.Forms.GroupBox groupBox1;
private System.Windows.Forms.CheckBox chkAutoBackup;
private System.Windows.Forms.Label label3;
private System.Windows.Forms.NumericUpDown numBackupInterval;
private System.Windows.Forms.ColumnHeader colSource;
private System.Windows.Forms.Button btnRestore;
private System.Windows.Forms.Label label1;
private System.Windows.Forms.Button btnAutoBackupLocation;
private System.Windows.Forms.TextBox txtAutoBackupLocation;
private System.Windows.Forms.CheckBox chkHideRestoreWarning;
private System.Windows.Forms.CheckBox chkTrayMinimize;
private System.Windows.Forms.NotifyIcon TrayIcon;
private System.Windows.Forms.Button btnEdit;
}
}
| 49.248908 | 160 | 0.60822 | [
"Apache-2.0"
] | NateShoffner/Sekiro-Save-Manager | Sekiro Save Manager/Forms/MainForm.Designer.cs | 22,558 | C# |
namespace Paseto.Cryptography.Internal.Ed25519Ref10
{
internal static partial class GroupOperations
{
internal static void ge_tobytes(byte[] s, int offset, ref GroupElementP2 h)
{
FieldOperations.fe_invert(out FieldElement recip, ref h.Z);
FieldOperations.fe_mul(out FieldElement x, ref h.X, ref recip);
FieldOperations.fe_mul(out FieldElement y, ref h.Y, ref recip);
FieldOperations.fe_tobytes(s, offset, ref y);
s[offset + 31] ^= (byte)(FieldOperations.fe_isnegative(ref x) << 7);
}
}
} | 38.428571 | 84 | 0.704461 | [
"MIT"
] | daviddesmet/paseto-dotnet | src/Paseto.Cryptography/Internal/Ed25519Ref10/ge_tobytes.cs | 540 | 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 _5ifdoblementeenlazado_multas_de_transito
{
public partial class frmMultas : Form
{
//@mau: Instancia para list item (Ver linea 57)
ListViewItem item;
public frmMultas()
{
InitializeComponent();
}
private void frmMultas_Load(object sender, EventArgs e)
{
// Fecha actual formato corto
lblFecha.Text = DateTime.Today.Date.ToShortDateString();
// Hora actual formato corto
lblHora.Text = DateTime.Now.ToShortTimeString();
}
private void btnRegistrar_Click(object sender, EventArgs e)
{
//Capurando datos
string placa = txtPlaca.Text;
double velocidad = double.Parse(txtVelocidad.Text);
DateTime fecha = DateTime.Parse(lblFecha.Text);
DateTime hora = DateTime.Parse(lblHora.Text);
//Procesando
double multa = 0;
if (velocidad <= 70) multa = 0;
else if (velocidad > 70 && velocidad <= 90) multa = 120;
else if (velocidad > 90 && velocidad <= 100) multa = 240;
else if (velocidad > 100) multa = 350;
//Imprimiendo los resultados
//@mau: crea un objeto fila y lo anade a la vista
ListViewItem fila = new ListViewItem(placa);
fila.SubItems.Add(lblFecha.Text);
fila.SubItems.Add(lblHora.Text);
fila.SubItems.Add(velocidad.ToString("0.00"));
fila.SubItems.Add(multa.ToString("C"));
lvMultas.Items.Add(fila);
}
private void btnEliminar_Click(object sender, EventArgs e)
{
//@mau: Ver en la linea 15
if (item != null)
{
lvMultas.Items.Remove(item);
MessageBox.Show("Multa eliminada correctamente...");
} else
{
MessageBox.Show("Debe selecionar un multa de la lista");
}
}
private void btnSalir_Click(object sender, EventArgs e)
{
this.Close();
}
private void lvMultas_MouseClick(object sender, MouseEventArgs e)
{
item = lvMultas.GetItemAt(e.X, e.Y);
}
}
}
| 31.3 | 73 | 0.567492 | [
"MIT"
] | mauriciogpro/e-dot-net | 4_Cap/5ifdoblementeenlazado_multas de transito/5ifdoblementeenlazado_multas_de_transito/Form1.cs | 2,506 | C# |
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Text;
using Amp.Tokenizer;
namespace Amp.Parser
{
public abstract class AmpElement : IFormattable
{
public sealed override string ToString()
{
return ToString("", CultureInfo.InvariantCulture, false, false);
}
public string ToFullString()
{
return ToString("", CultureInfo.InvariantCulture, true, true);
}
string IFormattable.ToString(string format, IFormatProvider formatProvider)
{
return ToString(format, formatProvider, false, false);
}
protected virtual string ToString(string format, IFormatProvider formatProvider, bool leading, bool following)
{
StringBuilder sb = new StringBuilder();
using (StringWriter sw = new StringWriter(sb))
{
WriteTo(sw, formatProvider, format, leading, following);
}
return sb.ToString();
}
public abstract void WriteTo(TextWriter tw, IFormatProvider formatProvider, string format, bool leading, bool following);
public abstract AmpRange GetRange();
/// <summary>
///
/// </summary>
public virtual bool IsError { get; set; }
}
}
| 27.530612 | 129 | 0.619718 | [
"Apache-2.0"
] | AmpScm/AmpParser | src/AmpParser/Parser/AmpElement.cs | 1,351 | C# |
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Reflection;
namespace CoreFX.Notification.Smtp.Utils
{
public static class EmailUtil
{
public static string ToHtmlTable<T>(this List<T> records)
{
var ret = string.Empty;
return records == null || !records.Any()
? ret
: "<table cellspacing='0' cellpadding='1' border='1'>" +
records.First().GetType().GetProperties()
.Where(o => !IsJsonIgnored(o))
.Select(p => (string.IsNullOrEmpty(GetPropertyValue(typeof(DisplayAttribute), "Description", p))) ? p.Name : GetPropertyValue(typeof(DisplayAttribute), "Description", p)).ToList().ToColumnHeaders() +
records.Aggregate(ret, (current, t) => current + t.ToHtmlTableRow()) +
"</table>";
}
public static bool IsJsonIgnored(PropertyInfo prop)
{
return prop.GetCustomAttributes(true)
.Where(o =>
o.GetType() == typeof(Newtonsoft.Json.JsonIgnoreAttribute) ||
o.GetType() == typeof(System.Text.Json.Serialization.JsonIgnoreAttribute)
).Any();
}
private static string GetPropertyValue(Type type, string propName, PropertyInfo prop)
{
string value = null;
var d = (from q in prop.GetCustomAttributesData()
where q.ToString().Contains(type.FullName)
select q).FirstOrDefault();
if (null != d)
{
var d2 = (from q in d.NamedArguments
where q.MemberInfo.Name == propName
select q.TypedValue.Value).FirstOrDefault();
if (null != d2)
{
value = d2.ToString();
}
}
return value;
}
public static string ToColumnHeaders<T>(this List<T> props)
{
var ret = string.Empty;
return props == null || !props.Any()
? ret
: "<tr>" +
props
.Aggregate(ret,
(current, propValue) =>
current +
("<th style='font-size: 11pt; font-weight: bold; background-color:blue; color:white'>" +
(Convert.ToString(propValue).Length <= 100
? Convert.ToString(propValue)
: Convert.ToString(propValue).Substring(0, 100)) + "</th>")) +
"</tr>";
}
private static string ToHtmlTableRow<T>(this T model)
{
var ret = string.Empty;
return model == null
? ret
: "<tr style='text-align:left'>" +
model.GetType()
.GetProperties()
.Where(o => !IsJsonIgnored(o))
.Aggregate(ret,
(current, prop) =>
current + ("<td style='font-size: 11pt; font-weight: normal;'>" +
((Convert.ToString(prop.GetValue(model, null)).Length <= 100
? Convert.ToString(prop.GetValue(model, null))
: Convert.ToString(prop.GetValue(model, null)).Substring(0, 100))) +
"</td>")) + "</tr>";
}
}
}
| 40.043956 | 219 | 0.468716 | [
"BSD-3-Clause"
] | BlackIkeEagle0/osisdie4 | src/Library/CoreFX/Notification/Smtp/Utils/EmailUtil.cs | 3,646 | C# |
using System;
using System.Reactive.Linq;
namespace Proxoft.Maps.Core.Api
{
public sealed class NoMap : IMap
{
public static readonly NoMap Instance = new();
private NoMap()
{
}
public IObservable<Event> OnEvent => Observable.Never<Event>();
public ApiStatus Status => ApiStatus.NotAvailable;
public IMarker AddMarker(MarkerOptions options)
=> NoMarker.Instance;
public void Dispose()
{
}
public void FitBounds(LatLngBounds bounds)
{
}
public void FitBounds(LatLngBounds bounds, Padding padding, ZoomLevel zoom)
{
}
public void PanTo(LatLng center)
{
}
public void SetCenter(LatLng position)
{
}
public void ZoomTo(ZoomLevel zoom)
{
}
}
}
| 19.021739 | 83 | 0.561143 | [
"MIT"
] | proxoft/Maps | Source/Maps.Core/Api/Maps/NoMap.cs | 877 | C# |
using System.Reflection;
namespace Dserv.Server
{
public static class EmbeddedResourceHandlerExtension
{
public static DservBuilder UseEmbeddedResources(this DservBuilder builder, params Assembly[] assemblies)
{
builder.AddHandler(new EmbeddedResourceHandler(assemblies));
return builder;
}
}
} | 27.923077 | 113 | 0.680441 | [
"MIT"
] | tomgilder/dserv | src/Server/Dserv.Server.Shared/EmbeddedResourceHandlerExtension.cs | 365 | 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 clouddirectory-2017-01-11.normal.json service model.
*/
using System;
using Amazon.Runtime;
using Amazon.Util.Internal;
namespace Amazon.CloudDirectory
{
/// <summary>
/// Configuration for accessing Amazon CloudDirectory service
/// </summary>
public partial class AmazonCloudDirectoryConfig : ClientConfig
{
private static readonly string UserAgentString =
InternalSDKUtils.BuildUserAgentString("3.7.0.61");
private string _userAgent = UserAgentString;
/// <summary>
/// Default constructor
/// </summary>
public AmazonCloudDirectoryConfig()
{
this.AuthenticationServiceName = "clouddirectory";
}
/// <summary>
/// The constant used to lookup in the region hash the endpoint.
/// </summary>
public override string RegionEndpointServiceName
{
get
{
return "clouddirectory";
}
}
/// <summary>
/// Gets the ServiceVersion property.
/// </summary>
public override string ServiceVersion
{
get
{
return "2017-01-11";
}
}
/// <summary>
/// Gets the value of UserAgent property.
/// </summary>
public override string UserAgent
{
get
{
return _userAgent;
}
}
}
} | 26.5 | 112 | 0.593868 | [
"Apache-2.0"
] | ebattalio/aws-sdk-net | sdk/src/Services/CloudDirectory/Generated/AmazonCloudDirectoryConfig.cs | 2,120 | C# |
using System;
using System.Collections.Generic;
using System.IO;
using NUnit.Framework;
using UniGLTF;
using UnityEngine;
namespace VRM
{
public class VRMLoadTest
{
static IEnumerable<FileInfo> EnumerateGltfFiles(DirectoryInfo dir)
{
if (dir.Name == ".git")
{
yield break;
}
foreach (var child in dir.EnumerateDirectories())
{
foreach (var x in EnumerateGltfFiles(child))
{
yield return x;
}
}
foreach (var child in dir.EnumerateFiles())
{
switch (child.Extension.ToLower())
{
case ".vrm":
yield return child;
break;
}
}
}
static void Message(string path, Exception exception)
{
while (exception.InnerException != null)
{
exception = exception.InnerException;
}
{
Debug.LogError($"LoadError: {path}");
Debug.LogException(exception);
}
}
static GameObject Load(FileInfo gltf, DirectoryInfo root, byte[] bytes = null)
{
var parser = new GltfParser();
try
{
if (bytes != null)
{
parser.Parse(gltf.FullName, bytes);
}
else
{
parser.ParsePath(gltf.FullName);
}
}
catch (Exception ex)
{
Debug.LogError($"ParseError: {gltf}");
Debug.LogException(ex);
return null;
}
try
{
using (var importer = new VRMImporterContext(parser))
{
importer.Load();
return importer.DisposeOnGameObjectDestroyed().gameObject;
}
}
catch (Exception ex)
{
Message(gltf.FullName.Substring(root.FullName.Length), ex);
return null;
}
}
[Test]
public void VrmTestModelsTests()
{
var env = System.Environment.GetEnvironmentVariable("VRM_TEST_MODELS");
if (string.IsNullOrEmpty(env))
{
return;
}
var root = new DirectoryInfo(env);
if (!root.Exists)
{
return;
}
foreach (var gltf in EnumerateGltfFiles(root))
{
// import
var go = Load(gltf, root);
try
{
// export
var vrm = VRMExporter.Export(UniGLTF.MeshExportSettings.Default, go);
// re import
if (vrm != null)
{
Load(gltf, root, vrm.ToGlbBytes());
}
}
finally
{
GameObject.DestroyImmediate(go);
}
}
}
}
}
| 26.443548 | 89 | 0.407441 | [
"MIT"
] | mi-tesseract/UniVRM | Assets/VRM/Tests/VRMLoadTests.cs | 3,281 | C# |
using Autofac;
using Surging.Core.CPlatform.Support;
using System.Linq;
using Surging.Core.CPlatform.Routing;
using Surging.Core.CPlatform.Address;
using System.Threading.Tasks;
using Surging.Core.ServiceHosting.Internal;
using Surging.Core.CPlatform.Runtime.Server;
using System.Net;
using System.Net.NetworkInformation;
using Microsoft.Extensions.Logging;
using Surging.Core.CPlatform.Runtime.Client;
using System;
using Surging.Core.CPlatform.Configurations;
using Surging.Core.CPlatform.Module;
using System.Diagnostics;
using Surging.Core.CPlatform.Engines;
using Surging.Core.CPlatform.Utilities;
using System.Collections.Generic;
using Microsoft.Extensions.Configuration;
using System.IO;
using Surging.Core.CPlatform.Transport.Implementation;
namespace Surging.Core.CPlatform
{
public static class ServiceHostBuilderExtensions
{
public static IServiceHostBuilder UseServer(this IServiceHostBuilder hostBuilder, string ip, int port, string token = "True")
{
return hostBuilder.MapServices(async mapper =>
{
BuildServiceEngine(mapper);
mapper.Resolve<IServiceTokenGenerator>().GeneratorToken(token);
int _port = AppConfig.ServerOptions.Port = AppConfig.ServerOptions.Port == 0 ? port : AppConfig.ServerOptions.Port;
string _ip = AppConfig.ServerOptions.Ip = AppConfig.ServerOptions.Ip ?? ip;
_port = AppConfig.ServerOptions.Port = AppConfig.ServerOptions.IpEndpoint?.Port ?? _port;
_ip = AppConfig.ServerOptions.Ip = AppConfig.ServerOptions.IpEndpoint?.Address.ToString() ?? _ip;
_ip = NetUtils.GetHostAddress(_ip);
mapper.Resolve<IModuleProvider>().Initialize();
if (!AppConfig.ServerOptions.DisableServiceRegistration)
{
await mapper.Resolve<IServiceCommandManager>().SetServiceCommandsAsync();
await ConfigureRoute(mapper);
}
var serviceHosts = mapper.Resolve<IList<Runtime.Server.IServiceHost>>();
Task.Factory.StartNew(async () =>
{
foreach (var serviceHost in serviceHosts)
await serviceHost.StartAsync(_ip, _port);
mapper.Resolve<IServiceEngineLifetime>().NotifyStarted();
}).Wait();
});
}
public static IServiceHostBuilder UseServer(this IServiceHostBuilder hostBuilder, Action<SurgingServerOptions> options)
{
var serverOptions = new SurgingServerOptions();
options.Invoke(serverOptions);
AppConfig.ServerOptions = serverOptions;
return hostBuilder.UseServer(serverOptions.Ip, serverOptions.Port, serverOptions.Token);
}
public static IServiceHostBuilder UseClient(this IServiceHostBuilder hostBuilder)
{
return hostBuilder.MapServices(mapper =>
{
var serviceEntryManager = mapper.Resolve<IServiceEntryManager>();
var addressDescriptors = serviceEntryManager.GetEntries().Select(i =>
{
i.Descriptor.Metadatas = null;
return new ServiceSubscriber
{
Address = new[] { new IpAddressModel {
Ip = Dns.GetHostEntry(Dns.GetHostName())
.AddressList.FirstOrDefault<IPAddress>
(a => a.AddressFamily.ToString().Equals("InterNetwork")).ToString() } },
ServiceDescriptor = i.Descriptor
};
}).ToList();
mapper.Resolve<IServiceSubscribeManager>().SetSubscribersAsync(addressDescriptors);
mapper.Resolve<IModuleProvider>().Initialize();
});
}
public static void BuildServiceEngine(IContainer container)
{
if (container.IsRegistered<IServiceEngine>())
{
var builder = new ContainerBuilder();
container.Resolve<IServiceEngineBuilder>().Build(builder);
var configBuilder = container.Resolve<IConfigurationBuilder>();
var appSettingPath = Path.Combine(AppConfig.ServerOptions.RootPath, "appsettings.json");
configBuilder.AddCPlatformFile("${appsettingspath}|" + appSettingPath, optional: false, reloadOnChange: true);
builder.Update(container);
}
}
public static async Task ConfigureRoute(IContainer mapper)
{
if (AppConfig.ServerOptions.Protocol == CommunicationProtocol.Tcp ||
AppConfig.ServerOptions.Protocol == CommunicationProtocol.None)
{
var routeProvider = mapper.Resolve<IServiceRouteProvider>();
if (AppConfig.ServerOptions.EnableRouteWatch)
new ServiceRouteWatch(mapper.Resolve<CPlatformContainer>(),
async () => await routeProvider.RegisterRoutes(
Math.Round(Convert.ToDecimal(Process.GetCurrentProcess().TotalProcessorTime.TotalSeconds), 2, MidpointRounding.AwayFromZero)));
else
await routeProvider.RegisterRoutes(0);
}
}
}
}
| 45.880342 | 151 | 0.627049 | [
"MIT"
] | 914132883/surging | src/Surging.Core/Surging.Core.CPlatform/ServiceHostBuilderExtensions.cs | 5,370 | C# |
using System;
using System.Collections.Generic;
using System.Threading;
using Xunit;
namespace Compilify.LanguageServices
{
public class CSharpCompilerTests
{
[Fact] // NOTE: This test will fail when executed by NCrunch.
public void CodeCanBeCompiledAndExecuted()
{
var classes = new Document("Classes", "public static void SayHello() { Console.WriteLine(\"Hello, world!\"); }");
var content = new Document("Content", "SayHello(); return \"Done!\";");
var command = new EvaluateCodeCommand
{
ClientId = Guid.NewGuid().ToString("N"),
Documents = new List<Document> { content, classes },
Name = "Untitled",
Submitted = DateTime.UtcNow,
TimeoutPeriod = TimeSpan.FromSeconds(30)
};
var sandbox = new Sandbox();
var compiler = new CSharpCompiler();
var actual = compiler.Compile(command);
Assert.NotNull(actual);
var result = sandbox.Execute(actual, Timeout.InfiniteTimeSpan);
Assert.NotNull(result);
Assert.Equal("Hello, world!\r\n", result.ConsoleOutput);
Assert.Equal("\"Done!\"", result.Result);
}
}
}
| 34.675 | 125 | 0.537851 | [
"MIT"
] | jrusbatch/compilify | Tests/LanguageServices.Tests/LanguageServices/CSharpCompilerTests.cs | 1,389 | C# |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.Reflection;
using Microsoft.DotNet.RemoteExecutor;
using Xunit;
namespace System.Text.RegularExpressions.Tests
{
public class RegexCacheTests
{
[Theory]
[InlineData(0)]
[InlineData(12)]
public void CacheSize_Set(int newCacheSize)
{
int originalCacheSize = Regex.CacheSize;
try
{
Regex.CacheSize = newCacheSize;
Assert.Equal(newCacheSize, Regex.CacheSize);
}
finally
{
Regex.CacheSize = originalCacheSize;
}
}
[Fact]
public void CacheSize_Set_NegativeValue_ThrowsArgumentOutOfRangeException()
{
AssertExtensions.Throws<ArgumentOutOfRangeException>("value", () => Regex.CacheSize = -1);
}
[Fact]
public void Ctor_Cache_Second_drops_first()
{
RemoteExecutor.Invoke(() =>
{
Regex.CacheSize = 1;
Assert.True(Regex.IsMatch("1", "1"));
Assert.True(Regex.IsMatch("2", "2")); // previous removed from cache
Assert.True(GetCachedItemsNum() == 1);
return RemoteExecutor.SuccessExitCode;
}).Dispose();
}
[Fact]
public void Ctor_Cache_Shrink_cache()
{
RemoteExecutor.Invoke(() =>
{
Regex.CacheSize = 2;
Assert.True(Regex.IsMatch("1", "1"));
Assert.True(Regex.IsMatch("2", "2"));
Assert.True(GetCachedItemsNum() == 2);
Regex.CacheSize = 1;
Assert.True(GetCachedItemsNum() == 1);
Regex.CacheSize = 0; // clear
Assert.True(GetCachedItemsNum() == 0);
return RemoteExecutor.SuccessExitCode;
}).Dispose();
}
[Fact]
public void Ctor_Cache_Promote_entries()
{
RemoteExecutor.Invoke(() =>
{
Regex.CacheSize = 3;
Assert.True(Regex.IsMatch("1", "1"));
Assert.True(Regex.IsMatch("2", "2"));
Assert.True(Regex.IsMatch("3", "3"));
Assert.True(GetCachedItemsNum() == 3);
Assert.True(Regex.IsMatch("1", "1")); // should be put first
Assert.True(GetCachedItemsNum() == 3);
Regex.CacheSize = 1; // only 1 stays
Assert.True(GetCachedItemsNum() == 1);
return RemoteExecutor.SuccessExitCode;
}).Dispose();
}
[Fact]
public void Ctor_Cache_Uses_culture_and_options()
{
RemoteExecutor.Invoke(() =>
{
Regex.CacheSize = 0;
Regex.CacheSize = 3;
Assert.True(Regex.IsMatch("1", "1", RegexOptions.IgnoreCase));
Assert.True(Regex.IsMatch("1", "1", RegexOptions.Multiline));
Assert.True(GetCachedItemsNum() == 2);
// Force to set a different culture than the current culture!
CultureInfo.CurrentCulture = CultureInfo.CurrentCulture.Equals(CultureInfo.GetCultureInfo("de-DE")) ? CultureInfo.InvariantCulture : CultureInfo.GetCultureInfo("de-DE");
Assert.True(Regex.IsMatch("1", "1", RegexOptions.Multiline));
Assert.True(GetCachedItemsNum() == 3);
return RemoteExecutor.SuccessExitCode;
}).Dispose();
}
[Fact]
public void Ctor_Cache_Uses_dictionary_linked_list_switch_does_not_throw()
{
// assume the limit is less than the cache size so we cross it two times:
RemoteExecutor.Invoke(() =>
{
int original = Regex.CacheSize;
Regex.CacheSize = 0;
Fill(original);
const int limit = 10;
Regex.CacheSize = limit - 1;
Regex.CacheSize = 0;
Fill(original);
Remove(original);
void Fill(int n)
{
for (int i = 0; i < n; i++)
{
Regex.CacheSize++;
Assert.True(Regex.IsMatch(i.ToString(), i.ToString()));
Assert.True(GetCachedItemsNum() == i + 1);
}
}
void Remove(int n)
{
for (int i = 0; i < original; i++)
{
Regex.CacheSize--;
Assert.True(GetCachedItemsNum() == Regex.CacheSize);
}
}
return RemoteExecutor.SuccessExitCode;
}).Dispose();
}
private int GetCachedItemsNum()
{
return (int)typeof(Regex)
.GetField("s_cacheCount", BindingFlags.NonPublic | BindingFlags.Static)
.GetValue(null);
}
}
}
| 35.54 | 185 | 0.507222 | [
"MIT"
] | AntonLandor/corefx | src/System.Text.RegularExpressions/tests/Regex.Cache.Tests.cs | 5,331 | C# |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#if WINDOWS_BASE
using MS.Internal.WindowsBase;
#elif PRESENTATION_CORE
using MS.Internal.PresentationCore;
#elif PRESENTATIONFRAMEWORK
using MS.Internal.PresentationFramework;
#elif REACHFRAMEWORK
using MS.Internal.ReachFramework;
#elif UIAUTOMATIONTYPES
using MS.Internal.UIAutomationTypes;
#else
using MS.Internal;
#endif
using System;
using System.Runtime.InteropServices;
using System.Security;
#if WINDOWS_BASE
namespace MS.Internal.WindowsBase.Interop
#elif PRESENTATION_CORE
namespace System.Windows.Interop
#elif PRESENTATIONFRAMEWORK
namespace MS.Internal.PresentationFramework.Interop
#elif REACHFRAMEWORK
namespace MS.Internal.ReachFramework.Interop
#elif UIAUTOMATIONTYPES
namespace MS.Internal.UIAutomationTypes.Interop
#else
namespace Microsoft.Internal.Interop
#endif
{
/// <summary>
/// DevDiv:1158540
/// Adding wrapper around OSVersionHelper native code. This is linked into PresentationNative so we just PInvoke it from there.
///
/// To add a new OS:
/// Make sure you have followed the instructions in OperatingSystemVersion.cs to get here
/// Add appropriate PInvoke to your new Is{OSName}OrGreater function
/// Add case to switch statement in IsOsVersionOrGreater
/// Add new if statement to the TOP of GetOsVersion
/// </summary>
internal static class OSVersionHelper
{
#region Static OS Members
internal static bool IsOsWindows10RS5OrGreater { get; set; }
internal static bool IsOsWindows10RS3OrGreater { get; set; }
internal static bool IsOsWindows10RS2OrGreater { get; set; }
internal static bool IsOsWindows10RS1OrGreater { get; set; }
internal static bool IsOsWindows10TH2OrGreater { get; set; }
internal static bool IsOsWindows10TH1OrGreater { get; set; }
internal static bool IsOsWindows10OrGreater { get; set; }
internal static bool IsOsWindows8Point1OrGreater { get; set; }
internal static bool IsOsWindows8OrGreater { get; set; }
internal static bool IsOsWindows7SP1OrGreater { get; set; }
internal static bool IsOsWindows7OrGreater { get; set; }
internal static bool IsOsWindowsVistaSP2OrGreater { get; set; }
internal static bool IsOsWindowsVistaSP1OrGreater { get; set; }
internal static bool IsOsWindowsVistaOrGreater { get; set; }
internal static bool IsOsWindowsXPSP3OrGreater { get; set; }
internal static bool IsOsWindowsXPSP2OrGreater { get; set; }
internal static bool IsOsWindowsXPSP1OrGreater { get; set; }
internal static bool IsOsWindowsXPOrGreater { get; set; }
internal static bool IsOsWindowsServer { get; set; }
#endregion
#region Constructor
static OSVersionHelper()
{
IsOsWindows10RS5OrGreater = IsWindows10RS5OrGreater();
IsOsWindows10RS3OrGreater = IsWindows10RS3OrGreater();
IsOsWindows10RS2OrGreater = IsWindows10RS2OrGreater();
IsOsWindows10RS1OrGreater = IsWindows10RS1OrGreater();
IsOsWindows10TH2OrGreater = IsWindows10TH2OrGreater();
IsOsWindows10TH1OrGreater = IsWindows10TH1OrGreater();
IsOsWindows10OrGreater = IsWindows10OrGreater();
IsOsWindows8Point1OrGreater = IsWindows8Point1OrGreater();
IsOsWindows8OrGreater = IsWindows8OrGreater();
IsOsWindows7SP1OrGreater = IsWindows7SP1OrGreater();
IsOsWindows7OrGreater = IsWindows7OrGreater();
IsOsWindowsVistaSP2OrGreater = IsWindowsVistaSP2OrGreater();
IsOsWindowsVistaSP1OrGreater = IsWindowsVistaSP1OrGreater();
IsOsWindowsVistaOrGreater = IsWindowsVistaOrGreater();
IsOsWindowsXPSP3OrGreater = IsWindowsXPSP3OrGreater();
IsOsWindowsXPSP2OrGreater = IsWindowsXPSP2OrGreater();
IsOsWindowsXPSP1OrGreater = IsWindowsXPSP1OrGreater();
IsOsWindowsXPOrGreater = IsWindowsXPOrGreater();
IsOsWindowsServer = IsWindowsServer();
}
#endregion
#region DLL Imports
[DllImport(DllImport.PresentationNative, CallingConvention = CallingConvention.Cdecl)]
[return: MarshalAs(UnmanagedType.I1)]
static extern bool IsWindows10RS5OrGreater();
[DllImport(DllImport.PresentationNative, CallingConvention = CallingConvention.Cdecl)]
[return: MarshalAs(UnmanagedType.I1)]
static extern bool IsWindows10RS3OrGreater();
[DllImport(DllImport.PresentationNative, CallingConvention = CallingConvention.Cdecl)]
[return: MarshalAs(UnmanagedType.I1)]
static extern bool IsWindows10RS2OrGreater();
[DllImport(DllImport.PresentationNative, CallingConvention = CallingConvention.Cdecl)]
[return: MarshalAs(UnmanagedType.I1)]
static extern bool IsWindows10RS1OrGreater();
[DllImport(DllImport.PresentationNative, CallingConvention = CallingConvention.Cdecl)]
[return: MarshalAs(UnmanagedType.I1)]
static extern bool IsWindows10TH2OrGreater();
[DllImport(DllImport.PresentationNative, CallingConvention = CallingConvention.Cdecl)]
[return: MarshalAs(UnmanagedType.I1)]
static extern bool IsWindows10TH1OrGreater();
[DllImport(DllImport.PresentationNative, CallingConvention = CallingConvention.Cdecl)]
[return: MarshalAs(UnmanagedType.I1)]
static extern bool IsWindows10OrGreater();
[DllImport(DllImport.PresentationNative, CallingConvention = CallingConvention.Cdecl)]
[return: MarshalAs(UnmanagedType.I1)]
static extern bool IsWindows8Point1OrGreater();
[DllImport(DllImport.PresentationNative, CallingConvention = CallingConvention.Cdecl)]
[return: MarshalAs(UnmanagedType.I1)]
static extern bool IsWindows8OrGreater();
[DllImport(DllImport.PresentationNative, CallingConvention = CallingConvention.Cdecl)]
[return: MarshalAs(UnmanagedType.I1)]
static extern bool IsWindows7SP1OrGreater();
[DllImport(DllImport.PresentationNative, CallingConvention = CallingConvention.Cdecl)]
[return: MarshalAs(UnmanagedType.I1)]
static extern bool IsWindows7OrGreater();
[DllImport(DllImport.PresentationNative, CallingConvention = CallingConvention.Cdecl)]
[return: MarshalAs(UnmanagedType.I1)]
static extern bool IsWindowsVistaSP2OrGreater();
[DllImport(DllImport.PresentationNative, CallingConvention = CallingConvention.Cdecl)]
[return: MarshalAs(UnmanagedType.I1)]
static extern bool IsWindowsVistaSP1OrGreater();
[DllImport(DllImport.PresentationNative, CallingConvention = CallingConvention.Cdecl)]
[return: MarshalAs(UnmanagedType.I1)]
static extern bool IsWindowsVistaOrGreater();
[DllImport(DllImport.PresentationNative, CallingConvention = CallingConvention.Cdecl)]
[return: MarshalAs(UnmanagedType.I1)]
static extern bool IsWindowsXPSP3OrGreater();
[DllImport(DllImport.PresentationNative, CallingConvention = CallingConvention.Cdecl)]
[return: MarshalAs(UnmanagedType.I1)]
static extern bool IsWindowsXPSP2OrGreater();
[DllImport(DllImport.PresentationNative, CallingConvention = CallingConvention.Cdecl)]
[return: MarshalAs(UnmanagedType.I1)]
static extern bool IsWindowsXPSP1OrGreater();
[DllImport(DllImport.PresentationNative, CallingConvention = CallingConvention.Cdecl)]
[return: MarshalAs(UnmanagedType.I1)]
static extern bool IsWindowsXPOrGreater();
[DllImport(DllImport.PresentationNative, CallingConvention = CallingConvention.Cdecl)]
[return: MarshalAs(UnmanagedType.I1)]
static extern bool IsWindowsServer();
#endregion
#region Managed API
internal static bool IsOsVersionOrGreater(OperatingSystemVersion osVer)
{
switch (osVer)
{
case OperatingSystemVersion.Windows10RS5:
return IsOsWindows10RS5OrGreater;
case OperatingSystemVersion.Windows10RS3:
return IsOsWindows10RS3OrGreater;
case OperatingSystemVersion.Windows10RS2:
return IsOsWindows10RS2OrGreater;
case OperatingSystemVersion.Windows10RS1:
return IsOsWindows10RS1OrGreater;
case OperatingSystemVersion.Windows10TH2:
return IsOsWindows10TH2OrGreater;
case OperatingSystemVersion.Windows10:
return IsOsWindows10OrGreater;
case OperatingSystemVersion.Windows8Point1:
return IsOsWindows8Point1OrGreater;
case OperatingSystemVersion.Windows8:
return IsOsWindows8OrGreater;
case OperatingSystemVersion.Windows7SP1:
return IsOsWindows7SP1OrGreater;
case OperatingSystemVersion.Windows7:
return IsOsWindows7OrGreater;
case OperatingSystemVersion.WindowsVistaSP2:
return IsOsWindowsVistaSP2OrGreater;
case OperatingSystemVersion.WindowsVistaSP1:
return IsOsWindowsVistaSP1OrGreater;
case OperatingSystemVersion.WindowsVista:
return IsOsWindowsVistaOrGreater;
case OperatingSystemVersion.WindowsXPSP3:
return IsOsWindowsXPSP3OrGreater;
case OperatingSystemVersion.WindowsXPSP2:
return IsOsWindowsXPSP2OrGreater;
}
throw new ArgumentException(string.Format("{0} is not a valid OS!", osVer.ToString()), "osVer");
}
internal static OperatingSystemVersion GetOsVersion()
{
if (IsOsWindows10RS5OrGreater)
{
return OperatingSystemVersion.Windows10RS5;
}
else if (IsOsWindows10RS3OrGreater)
{
return OperatingSystemVersion.Windows10RS3;
}
else if (IsOsWindows10RS2OrGreater)
{
return OperatingSystemVersion.Windows10RS2;
}
else if (IsOsWindows10RS1OrGreater)
{
return OperatingSystemVersion.Windows10RS1;
}
else if (IsOsWindows10TH2OrGreater)
{
return OperatingSystemVersion.Windows10TH2;
}
else if (IsOsWindows10OrGreater)
{
return OperatingSystemVersion.Windows10;
}
else if (IsOsWindows8Point1OrGreater)
{
return OperatingSystemVersion.Windows8Point1;
}
else if (IsOsWindows8OrGreater)
{
return OperatingSystemVersion.Windows8;
}
else if (IsOsWindows7SP1OrGreater)
{
return OperatingSystemVersion.Windows7SP1;
}
else if (IsOsWindows7OrGreater)
{
return OperatingSystemVersion.Windows7;
}
else if (IsOsWindowsVistaSP2OrGreater)
{
return OperatingSystemVersion.WindowsVistaSP2;
}
else if (IsOsWindowsVistaSP1OrGreater)
{
return OperatingSystemVersion.WindowsVistaSP1;
}
else if (IsOsWindowsVistaOrGreater)
{
return OperatingSystemVersion.WindowsVista;
}
else if (IsOsWindowsXPSP3OrGreater)
{
return OperatingSystemVersion.WindowsXPSP3;
}
else if (IsOsWindowsXPSP2OrGreater)
{
return OperatingSystemVersion.WindowsXPSP2;
}
throw new Exception("OSVersionHelper.GetOsVersion Could not detect OS!");
}
#endregion
}
}
| 37.576687 | 132 | 0.669469 | [
"MIT"
] | 56hide/wpf | src/Microsoft.DotNet.Wpf/src/Shared/System/Windows/InterOp/OSVersionHelper.cs | 12,250 | C# |
using System.Data.Entity.Infrastructure.Interception;
using Sentry.Extensibility;
namespace Sentry.EntityFramework;
/// <summary>
/// Sentry Database Logger
/// </summary>
public static class SentryDatabaseLogging
{
private static int Init = 0;
/// <summary>
/// Adds an instance of <see cref="SentryCommandInterceptor"/> to <see cref="DbInterception"/>
/// This is a static setup call, so make sure you only call it once for each <see cref="IQueryLogger"/> instance you want to register globally
/// </summary>
/// <param name="logger">Query Logger.</param>
[Obsolete("This method is called automatically by options.AddEntityFramework. This method will be removed in future versions.")]
public static SentryCommandInterceptor? UseBreadcrumbs(IQueryLogger? logger = null) => UseBreadcrumbs(logger);
internal static SentryCommandInterceptor? UseBreadcrumbs(
IQueryLogger? queryLogger = null,
bool initOnce = true,
IDiagnosticLogger? diagnosticLogger = null)
{
if (initOnce && Interlocked.Exchange(ref Init, 1) != 0)
{
diagnosticLogger?.LogWarning("{0}.{1} was already executed.",
nameof(SentryDatabaseLogging), nameof(UseBreadcrumbs));
return null;
}
diagnosticLogger?.LogInfo("{0}.{1} adding interceptor.",
nameof(SentryDatabaseLogging), nameof(UseBreadcrumbs));
queryLogger ??= new SentryQueryLogger();
var interceptor = new SentryCommandInterceptor(queryLogger);
DbInterception.Add(interceptor);
return interceptor;
}
}
| 38.380952 | 146 | 0.684864 | [
"MIT"
] | TawasalMessenger/sentry-dotnet | src/Sentry.EntityFramework/SentryDatabaseLogging.cs | 1,612 | C# |
namespace ResTB.DB.Migrations
{
using System;
using System.Data.Entity.Migrations;
public partial class HazardMap : DbMigration
{
public override void Up()
{
CreateTable(
"public.HazardMap",
c => new
{
ID = c.Int(nullable: false, identity: true),
Index = c.Int(nullable: false),
BeforeAction = c.Boolean(nullable: false),
NatHazard_ID = c.Int(),
Project_Id = c.Int(),
})
.PrimaryKey(t => t.ID)
.ForeignKey("public.NatHazard", t => t.NatHazard_ID)
.ForeignKey("public.Project", t => t.Project_Id)
.Index(t => t.NatHazard_ID)
.Index(t => t.Project_Id);
AddColumn("public.DamageExtent", "HazardMap_ID", c => c.Int());
CreateIndex("public.DamageExtent", "HazardMap_ID");
AddForeignKey("public.DamageExtent", "HazardMap_ID", "public.HazardMap", "ID");
}
public override void Down()
{
DropForeignKey("public.HazardMap", "Project_Id", "public.Project");
DropForeignKey("public.HazardMap", "NatHazard_ID", "public.NatHazard");
DropForeignKey("public.DamageExtent", "HazardMap_ID", "public.HazardMap");
DropIndex("public.HazardMap", new[] { "Project_Id" });
DropIndex("public.HazardMap", new[] { "NatHazard_ID" });
DropIndex("public.DamageExtent", new[] { "HazardMap_ID" });
DropColumn("public.DamageExtent", "HazardMap_ID");
DropTable("public.HazardMap");
}
}
}
| 40.136364 | 91 | 0.516421 | [
"Apache-2.0"
] | GEOTEST-AG/MiResiliencia | DB/Migrations/202008101844431_HazardMap.cs | 1,768 | C# |
/**
* Copyright 2013 Canada Health Infoway, Inc.
*
* 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.
*
* Author: $LastChangedBy: gng $
* Last modified: $LastChangedDate: 2015-11-19 18:20:12 -0500 (Fri, 30 Jan 2015) $
* Revision: $LastChangedRevision: 9755 $
*/
/* This class was auto-generated by the message builder generator tools. */
namespace Ca.Infoway.Messagebuilder.Model.Ccda_r1_1.Merged {
using Ca.Infoway.Messagebuilder.Annotation;
using Ca.Infoway.Messagebuilder.Datatype;
using Ca.Infoway.Messagebuilder.Datatype.Impl;
using Ca.Infoway.Messagebuilder.Datatype.Lang;
using Ca.Infoway.Messagebuilder.Model;
using System.Collections.Generic;
[Hl7PartTypeMappingAttribute(new string[] {"ConsultationNote.Authenticator","ContinuityOfCareDocumentCCD.Authenticator","DiagnosticImagingReport.Authenticator","DischargeSummary.Authenticator","HistoryAndPhysical.Authenticator","OperativeNote.Authenticator","ProcedureNote.Authenticator","ProgressNote.Authenticator","USRealmHeader.Authenticator","UnstructuredDocument.Authenticator"})]
public class Authenticator : MessagePartBean {
private II typeId;
private LIST<II, Identifier> templateId;
private TS_R2 time;
private Ca.Infoway.Messagebuilder.Model.Ccda_r1_1.Merged.AuthenticatorAssignedEntity assignedEntity;
public Authenticator() {
this.typeId = new IIImpl();
this.templateId = new LISTImpl<II, Identifier>(typeof(IIImpl));
this.time = new TS_R2Impl();
}
/**
* <summary>Un-merged Business Name: (no business name
* specified)</summary>
*
* <remarks>Relationship:
* DiagnosticImagingReport.Authenticator.typeId
* Conformance/Cardinality: OPTIONAL (0-1) Un-merged Business
* Name: (no business name specified) Relationship:
* ProgressNote.Authenticator.typeId Conformance/Cardinality:
* OPTIONAL (0-1) Un-merged Business Name: (no business name
* specified) Relationship:
* ConsultationNote.Authenticator.typeId
* Conformance/Cardinality: OPTIONAL (0-1) Un-merged Business
* Name: (no business name specified) Relationship:
* UnstructuredDocument.Authenticator.typeId
* Conformance/Cardinality: OPTIONAL (0-1) Un-merged Business
* Name: (no business name specified) Relationship:
* OperativeNote.Authenticator.typeId Conformance/Cardinality:
* OPTIONAL (0-1) Un-merged Business Name: (no business name
* specified) Relationship: ProcedureNote.Authenticator.typeId
* Conformance/Cardinality: OPTIONAL (0-1) Un-merged Business
* Name: (no business name specified) Relationship:
* HistoryAndPhysical.Authenticator.typeId
* Conformance/Cardinality: OPTIONAL (0-1) Un-merged Business
* Name: (no business name specified) Relationship:
* ContinuityOfCareDocumentCCD.Authenticator.typeId
* Conformance/Cardinality: OPTIONAL (0-1) Un-merged Business
* Name: (no business name specified) Relationship:
* DischargeSummary.Authenticator.typeId
* Conformance/Cardinality: OPTIONAL (0-1) Un-merged Business
* Name: (no business name specified) Relationship:
* USRealmHeader.Authenticator.typeId Conformance/Cardinality:
* OPTIONAL (0-1)</remarks>
*/
[Hl7XmlMappingAttribute(new string[] {"typeId"})]
public Identifier TypeId {
get { return this.typeId.Value; }
set { this.typeId.Value = value; }
}
/**
* <summary>Un-merged Business Name: (no business name
* specified)</summary>
*
* <remarks>Relationship:
* DiagnosticImagingReport.Authenticator.templateId
* Conformance/Cardinality: OPTIONAL (0-*) Un-merged Business
* Name: (no business name specified) Relationship:
* ProgressNote.Authenticator.templateId
* Conformance/Cardinality: OPTIONAL (0-*) Un-merged Business
* Name: (no business name specified) Relationship:
* ConsultationNote.Authenticator.templateId
* Conformance/Cardinality: OPTIONAL (0-*) Un-merged Business
* Name: (no business name specified) Relationship:
* UnstructuredDocument.Authenticator.templateId
* Conformance/Cardinality: OPTIONAL (0-*) Un-merged Business
* Name: (no business name specified) Relationship:
* OperativeNote.Authenticator.templateId
* Conformance/Cardinality: OPTIONAL (0-*) Un-merged Business
* Name: (no business name specified) Relationship:
* ProcedureNote.Authenticator.templateId
* Conformance/Cardinality: OPTIONAL (0-*) Un-merged Business
* Name: (no business name specified) Relationship:
* HistoryAndPhysical.Authenticator.templateId
* Conformance/Cardinality: OPTIONAL (0-*) Un-merged Business
* Name: (no business name specified) Relationship:
* ContinuityOfCareDocumentCCD.Authenticator.templateId
* Conformance/Cardinality: OPTIONAL (0-*) Un-merged Business
* Name: (no business name specified) Relationship:
* DischargeSummary.Authenticator.templateId
* Conformance/Cardinality: OPTIONAL (0-*) Un-merged Business
* Name: (no business name specified) Relationship:
* USRealmHeader.Authenticator.templateId
* Conformance/Cardinality: OPTIONAL (0-*)</remarks>
*/
[Hl7XmlMappingAttribute(new string[] {"templateId"})]
public IList<Identifier> TemplateId {
get { return this.templateId.RawList(); }
}
/**
* <summary>Un-merged Business Name: (no business name
* specified)</summary>
*
* <remarks>Relationship:
* DiagnosticImagingReport.Authenticator.time
* Conformance/Cardinality: POPULATED (1) Un-merged Business
* Name: (no business name specified) Relationship:
* ProgressNote.Authenticator.time Conformance/Cardinality:
* POPULATED (1) Un-merged Business Name: (no business name
* specified) Relationship: ConsultationNote.Authenticator.time
* Conformance/Cardinality: POPULATED (1) Un-merged Business
* Name: (no business name specified) Relationship:
* UnstructuredDocument.Authenticator.time
* Conformance/Cardinality: POPULATED (1) Un-merged Business
* Name: (no business name specified) Relationship:
* OperativeNote.Authenticator.time Conformance/Cardinality:
* POPULATED (1) Un-merged Business Name: (no business name
* specified) Relationship: ProcedureNote.Authenticator.time
* Conformance/Cardinality: POPULATED (1) Un-merged Business
* Name: (no business name specified) Relationship:
* HistoryAndPhysical.Authenticator.time
* Conformance/Cardinality: POPULATED (1) Un-merged Business
* Name: (no business name specified) Relationship:
* ContinuityOfCareDocumentCCD.Authenticator.time
* Conformance/Cardinality: POPULATED (1) Un-merged Business
* Name: (no business name specified) Relationship:
* DischargeSummary.Authenticator.time Conformance/Cardinality:
* POPULATED (1) Un-merged Business Name: (no business name
* specified) Relationship: USRealmHeader.Authenticator.time
* Conformance/Cardinality: POPULATED (1)</remarks>
*/
[Hl7XmlMappingAttribute(new string[] {"time"})]
public MbDate Time {
get { return this.time.Value; }
set { this.time.Value = value; }
}
/**
* <summary>Un-merged Business Name: (no business name
* specified)</summary>
*
* <remarks>Relationship:
* DiagnosticImagingReport.Authenticator.assignedEntity
* Conformance/Cardinality: POPULATED (1) Un-merged Business
* Name: (no business name specified) Relationship:
* ProgressNote.Authenticator.assignedEntity
* Conformance/Cardinality: POPULATED (1) Un-merged Business
* Name: (no business name specified) Relationship:
* ConsultationNote.Authenticator.assignedEntity
* Conformance/Cardinality: POPULATED (1) Un-merged Business
* Name: (no business name specified) Relationship:
* UnstructuredDocument.Authenticator.assignedEntity
* Conformance/Cardinality: POPULATED (1) Un-merged Business
* Name: (no business name specified) Relationship:
* OperativeNote.Authenticator.assignedEntity
* Conformance/Cardinality: POPULATED (1) Un-merged Business
* Name: (no business name specified) Relationship:
* ProcedureNote.Authenticator.assignedEntity
* Conformance/Cardinality: POPULATED (1) Un-merged Business
* Name: (no business name specified) Relationship:
* HistoryAndPhysical.Authenticator.assignedEntity
* Conformance/Cardinality: POPULATED (1) Un-merged Business
* Name: (no business name specified) Relationship:
* ContinuityOfCareDocumentCCD.Authenticator.assignedEntity
* Conformance/Cardinality: POPULATED (1) Un-merged Business
* Name: (no business name specified) Relationship:
* DischargeSummary.Authenticator.assignedEntity
* Conformance/Cardinality: POPULATED (1) Un-merged Business
* Name: (no business name specified) Relationship:
* USRealmHeader.Authenticator.assignedEntity
* Conformance/Cardinality: POPULATED (1)</remarks>
*/
[Hl7XmlMappingAttribute(new string[] {"assignedEntity"})]
public Ca.Infoway.Messagebuilder.Model.Ccda_r1_1.Merged.AuthenticatorAssignedEntity AssignedEntity {
get { return this.assignedEntity; }
set { this.assignedEntity = value; }
}
}
} | 52.68932 | 391 | 0.657914 | [
"ECL-2.0",
"Apache-2.0"
] | CanadaHealthInfoway/message-builder-dotnet | message-builder-ccda-r1_1/Main/Ca/Infoway/Messagebuilder/Model/Ccda_r1_1/Merged/Authenticator.cs | 10,854 | 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("BankKata.UnitTests")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("BankKata.UnitTests")]
[assembly: AssemblyCopyright("Copyright © 2018")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("275c52b4-5adf-49e4-8c88-cf5204118135")]
// 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.945946 | 84 | 0.748575 | [
"MIT"
] | ijrussell/LeedsSharp-OutsideIn-TDD | BankKataOutsideInTDD/BankKata.UnitTests/Properties/AssemblyInfo.cs | 1,407 | C# |
//
// Klak - Utilities for creative coding with Unity
//
// Copyright (C) 2016 Keijiro Takahashi
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
using UnityEngine;
using UnityEditor;
namespace Klak.Wiring.Patcher
{
// Inspector GUI for the specialized node
[CustomEditor(typeof(Node))]
class NodeEditor : Editor
{
// Node component editor
Editor _editor;
void OnEnable()
{
if (_editor == null)
_editor = CreateEditor(((Node)target).runtimeInstance);
}
void OnDestroy()
{
DestroyImmediate(_editor);
}
public override bool RequiresConstantRepaint()
{
return _editor.RequiresConstantRepaint();
}
protected override void OnHeaderGUI()
{
var node = (Node)target;
if (_editor == null || !node.isValid) return;
EditorGUILayout.Space();
// Retrieve the header title (type name).
var instance = node.runtimeInstance;
var title = ObjectNames.NicifyVariableName(instance.GetType().Name);
// Show the header title.
GUILayout.BeginHorizontal();
GUILayout.Space(14);
EditorGUILayout.LabelField(title, EditorStyles.boldLabel);
GUILayout.EndHorizontal();
EditorGUILayout.Space();
}
public override void OnInspectorGUI()
{
var node = (Node)target;
if (_editor == null || !node.isValid) return;
// Show the node name field.
var instance = node.runtimeInstance;
instance.name = EditorGUILayout.TextField("Name", instance.name);
EditorGUILayout.Space();
// Node properties
_editor.OnInspectorGUI();
}
}
}
| 31.977778 | 80 | 0.64107 | [
"MIT"
] | MichaelProkofyev/Tower_Of_Nam | Assets/External/Klak/Klak/Wiring/Editor/Patcher/NodeEditor.cs | 2,878 | C# |
using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Linq;
using System.Threading.Tasks;
using System.Web;
using Microsoft.AspNetCore.Mvc;
using YahooFantasyWrapper.Client;
using YahooFantasyWrapper.Models;
using YahooFantasyWrapper.Web.Models;
namespace YahooFantasyWrapper.Web.Controllers
{
[Route("api/[controller]")]
public class AccountController : Controller
{
private readonly IYahooAuthClient _authClient;
private readonly IYahooFantasyClient _fantasyClient;
public AccountController(IYahooAuthClient authClient, IYahooFantasyClient fantasyClient)
{
this._authClient = authClient;
this._fantasyClient = fantasyClient;
}
private NameValueCollection Parameters
{
get { return HttpUtility.ParseQueryString(Request.QueryString.Value); }
}
[HttpGet("[action]")]
public string Login()
{
return this._authClient.GetLoginLinkUri();
}
[HttpGet("[action]")]
public async Task<UserModel> GetAuth(string code)
{
var authModel = new UserModel();
if (
(this.Parameters != null & this.Parameters.Count > 0)
|| this._authClient.UserInfo != null
) {
if (this._authClient.UserInfo == null)
{
this._authClient.UserInfo = await this._authClient.GetUserInfo(this.Parameters);
authModel.AccessToken = _authClient.Auth.AccessToken;
authModel.UserInfo = _authClient.UserInfo;
}
else
{
authModel.AccessToken = _authClient.Auth.AccessToken;
authModel.UserInfo = _authClient.UserInfo;
}
}
return authModel;
}
}
}
| 31.064516 | 100 | 0.601246 | [
"Apache-2.0"
] | GravlLift/YahooFantasyWrapper | src/YahooFantasyWrapper.Web/Controllers/AccountController.cs | 1,926 | C# |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Herocontroller : MonoBehaviour
{
[SerializeField] private LayerMask groundLayers;
[SerializeField] private float runSpeed = 8f;
[SerializeField] private float jumpHeight = 2f;
private float gravity = -50f;
private CharacterController characterController;
private Vector3 velocity;
private bool isGrounded;
private float horizontalInput;
// Start is called before the first frame update
void Start()
{
characterController = GetComponent<CharacterController>();
}
// Update is called once per frame
void Update()
{
horizontalInput = 1;
//faceforward
transform.forward = new Vector3(horizontalInput, 0, Mathf.Abs(horizontalInput) - 1);
//is grounded
isGrounded = Physics.CheckSphere(transform.position, 0.1f, groundLayers, QueryTriggerInteraction.Ignore);
if (isGrounded && velocity.y < 0)
{
velocity.y = 0;
}
else
{
velocity.y += gravity * Time.deltaTime;
}
characterController.Move(new Vector3(horizontalInput * runSpeed, 0, 0) * Time.deltaTime);
if (isGrounded && Input.GetButtonDown("Jump"))
{
velocity.y += Mathf.Sqrt(jumpHeight * -2 * gravity);
}
characterController.Move(velocity * Time.deltaTime);
}
}
| 28.307692 | 113 | 0.633832 | [
"MIT"
] | DmalleWors/NRunner | Assets/Hero/Herocontroller.cs | 1,472 | C# |
namespace Xunit.Sdk
{
/// <summary>
/// Exception thrown when Option is unexpectedly None.
/// </summary>
#if XUNIT_VISIBILITY_INTERNAL
internal
#else
public
#endif
class SomeException : XunitException
{
/// <summary>
/// Creates a new instance of the <see cref="SomeException"/> class.
/// </summary>
public SomeException()
: base("Assert.Some() Failure")
{ }
}
} | 22.45 | 76 | 0.576837 | [
"MIT"
] | colethecoder/ExtUnit | ExtUnit/ExtendedSdk/Exceptions/SomeException.cs | 451 | C# |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class MaintainNodeScale : MonoBehaviour {
GameObject treeContainer;
public float targetScale = 1f;
private void Awake()
{
treeContainer = GameObject.Find("TreeContainer");
}
// Use this for initialization
void Start()
{
}
// Update is called once per frame
void Update()
{
if (transform.hasChanged)
{
transform.localScale = new Vector3(
targetScale / treeContainer.transform.localScale.x,
targetScale / treeContainer.transform.localScale.y,
targetScale / treeContainer.transform.localScale.z
);
transform.hasChanged = false;
}
}
}
| 22.25 | 67 | 0.606742 | [
"Apache-2.0"
] | TomHemery/Third-Year-Project-VR-Phylogenetic-Tree-Viewer | Assets/Scripts/BasicTreeViewer/Tree/MaintainNodeScale.cs | 803 | C# |
/**
* Module: MoralisSessionTokenResponse.cs
* Descriptiontion: Sample game controller that demonstrates how to use the Moralis
* Web3Api to retieve and display a list of ERC20 Tokens..
* Author: Moralis Web3 Technology AB, 559307-5988 - David B. Goodrich
*
* MIT License
*
* Copyright (c) 2021 Moralis Web3 Technology AB, 559307-5988
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using Assets.Scripts;
using UnityEngine.Networking;
using System.Text;
using System.IO;
using System;
using System.Runtime.Serialization.Formatters.Binary;
using System.Net;
#if UNITY_WEBGL
using Moralis.WebGL.Platform.Objects;
using Moralis.WebGL.Web3Api.Models;
using Cysharp.Threading.Tasks;
using Newtonsoft.Json;
using Assets.MoralisWeb3ApiSdk.Example.Scripts;
#else
using Moralis.Platform.Objects;
using Moralis.Web3Api.Models;
#endif
/// <summary>
/// Sample game controller that demonstrates how to use the Moralis Web3Api to retieve
/// and display a list of ERC20 Tokens..
/// </summary>
public class TokenListController : MonoBehaviour
{
/// <summary>
/// Prefab of the item to draw the token to and show in the list.
/// </summary>
public GameObject ListItemPrefab;
/// <summary>
/// Vertical layout to hold the Token item list.
/// </summary>
public Transform TokenListTransform;
/// <summary>
/// Chain ID to fetch tokens from. Might be better to make this
/// a drop down that is selectable at run time.
/// </summary>
public int ChainId;
private bool tokensLoaded;
public async void PopulateWallet()
{
if (!tokensLoaded)
{
// Make sure that duplicate tokens are not loaded.
tokensLoaded = true;
// Get user object and display user name
MoralisUser user = await MoralisInterface.GetUserAsync();
#if UNITY_WEBGL
List<Erc20TokenBalance> balances = await RetreiveBalances(user);
await BuildTokenList(balances);
#else
StartCoroutine(BuildTokenList(user));
#endif
}
}
#if UNITY_WEBGL
private async UniTask<List<Erc20TokenBalance>> RetreiveBalances(MoralisUser user)
{
List<Erc20TokenBalance> tokens = new List<Erc20TokenBalance>();
if (user != null)
{
string addr = user.authData["moralisEth"]["id"].ToString();
tokens = await MoralisInterface.GetClient().Web3Api.Account.GetTokenBalances(addr.ToLower(),
(ChainList)ChainId);
}
return tokens;
}
async UniTask BuildTokenList(List<Erc20TokenBalance> tokens)
{
foreach (Erc20TokenBalance token in tokens)
{
// Ignor entry without symbol or without thumbnail image
if (string.IsNullOrWhiteSpace(token.Symbol))
{
continue;
}
// Create and add an Token button to the display list.
var tokenObj = Instantiate(ListItemPrefab, TokenListTransform);
var tokenSymbol = tokenObj.GetFirstChildComponentByName<Text>("TokenSymbolText", false);
var tokenBalanace = tokenObj.GetFirstChildComponentByName<Text>("TokenCountText", false);
var tokenImage = tokenObj.GetFirstChildComponentByName<Image>("TokenThumbNail", false);
var tokenButton = tokenObj.GetComponent<Button>();
var parentTransform = TokenListTransform.GetComponent<RectTransform>();
double balance = 0.0;
float tokenDecimals = 18.0f;
// Make sure a response to the balanace request weas received. The
// IsNullOrWhitespace check may not be necessary ...
if (token != null && !string.IsNullOrWhiteSpace(token.Balance))
{
double.TryParse(token.Balance, out balance);
float.TryParse(token.Decimals, out tokenDecimals);
}
tokenSymbol.text = token.Symbol;
tokenBalanace.text = string.Format("{0:0.##} ", balance / (double)Mathf.Pow(10.0f, tokenDecimals));
// When button clicked display theCoingecko page for that token.
tokenButton.onClick.AddListener(delegate
{
// Display token CoinGecko page on click.
Application.OpenURL($"https://coinmarketcap.com/currencies/{token.Name}");
});
// If token has a thumbnail image try to retrieve the image
if (!string.IsNullOrWhiteSpace(token.Thumbnail))
{
// Field(s) for the cloud function.
IDictionary<string, object> pars = new Dictionary<string, object>();
pars.Add("url", token.Thumbnail);
string bodyData = JsonConvert.SerializeObject(pars);
ResourceResponse resourceResponse = await MoralisInterface.GetClient().Cloud.RunAsync<ResourceResponse>("loadResource", pars);
Texture2D tokenTexture = new Texture2D(64, 64);
ResourceData rData = resourceResponse.resourceData;
tokenTexture.LoadImage(rData.data);
var sprite = Sprite.Create(tokenTexture,
new Rect(0.0f, 0.0f, tokenTexture.width, tokenTexture.height),
new Vector2(0.75f, 0.75f), 100.0f);
tokenImage.sprite = sprite;
}
}
}
#else
IEnumerator BuildTokenList(MoralisUser user)
{
if (user != null)
{
string addr = user.authData["moralisEth"]["id"].ToString();
List<Erc20TokenBalance> tokens =
MoralisInterface.GetClient().Web3Api.Account.GetTokenBalances(addr.ToLower(),
(ChainList)ChainId);
foreach (Erc20TokenBalance token in tokens)
{
// Ignor entry without symbol
if (string.IsNullOrWhiteSpace(token.Symbol))
{
continue;
}
// Create and add an Token button to the display list.
var tokenObj = Instantiate(ListItemPrefab, TokenListTransform);
var tokenSymbol = tokenObj.GetFirstChildComponentByName<Text>("TokenSymbolText", false);
var tokenBalanace = tokenObj.GetFirstChildComponentByName<Text>("TokenCountText", false);
var tokenImage = tokenObj.GetFirstChildComponentByName<Image>("TokenThumbNail", false);
var tokenButton = tokenObj.GetComponent<Button>();
var rectTransform = tokenObj.GetComponent<RectTransform>();
var parentTransform = TokenListTransform.GetComponent<RectTransform>();
double balance = 0.0;
float tokenDecimals = 18.0f;
// Make sure a response to the balanace request weas received. The
// IsNullOrWhitespace check may not be necessary ...
if (token != null && !string.IsNullOrWhiteSpace(token.Balance))
{
double.TryParse(token.Balance, out balance);
float.TryParse(token.Decimals, out tokenDecimals);
}
tokenSymbol.text = token.Symbol;
tokenBalanace.text = string.Format("{0:0.##} ", balance / (double)Mathf.Pow(10.0f, tokenDecimals));
// When button clicked display theCoingecko page for that token.
tokenButton.onClick.AddListener(delegate
{
// Display token CoinGecko page on click.
Application.OpenURL($"https://coinmarketcap.com/currencies/{token.Name}");
});
using (UnityWebRequest imageRequest = UnityWebRequestTexture.GetTexture(token.Thumbnail))
{
yield return imageRequest.SendWebRequest();
if (imageRequest.isNetworkError)
{
Debug.Log("Error Getting Nft Image: " + imageRequest.error);
}
else
{
Texture2D tokenTexture = ((DownloadHandlerTexture)imageRequest.downloadHandler).texture;
var sprite = Sprite.Create(tokenTexture,
new Rect(0.0f, 0.0f, tokenTexture.width, tokenTexture.height),
new Vector2(0.75f, 0.75f), 100.0f);
tokenImage.sprite = sprite;
}
}
}
}
}
#endif
}
| 39.542169 | 142 | 0.610502 | [
"MIT"
] | AllTrueVision/ethereum-unity-boilerplate | Assets/MoralisWeb3ApiSdk/Example/Scripts/TokenListController.cs | 9,846 | 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("AlbumTracker.WebApi")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("AlbumTracker.WebApi")]
[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("76bbe71f-6f02-47af-9cd4-6aef1cf6a81c")]
// 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 Revision and Build Numbers
// by using the '*' as shown below:
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| 38.083333 | 84 | 0.749818 | [
"MIT"
] | webley/album-tracker | AlbumTracker.WebApi/Properties/AssemblyInfo.cs | 1,374 | C# |
// Copyright (c) junjie sun. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System;
using System.Collections.Generic;
using System.Text;
using XNode.Security;
using XNode.Serializer;
using XNode.Server.Configuration;
using XNode.ProtocolStack;
using XNode.Server.Route;
using XNode.Communication;
namespace XNode.Server
{
/// <summary>
/// XNode服务端配置类
/// </summary>
public class NodeServerConfig
{
/// <summary>
/// 服务地址
/// </summary>
public string Host { get; set; }
/// <summary>
/// 服务端口
/// </summary>
public int Port { get; set; }
/// <summary>
/// 服务配置
/// </summary>
public IList<ServiceInfo> ServiceConfigs { get; set; }
/// <summary>
/// 服务提供器实例
/// </summary>
public IServiceProvider ServiceProvider { get; set; }
/// <summary>
/// 协议栈工厂实例
/// </summary>
public IProtocolStackFactory ProtocolStackFactory { get; set; }
/// <summary>
/// 路由工厂实例
/// </summary>
public IRouteFactory RouteFactory { get; set; }
/// <summary>
/// 序列化器实例
/// </summary>
public ISerializer Serializer { get; set; }
/// <summary>
/// 服务处理器实例
/// </summary>
public IServiceProcessor ServiceProcessor { get; set; }
/// <summary>
/// 服务调用器实例
/// </summary>
public IServiceInvoker ServiceInvoker { get; set; }
/// <summary>
/// 登录验证器实例
/// </summary>
public ILoginValidator LoginValidator { get; set; }
/// <summary>
/// 服务端底层通信实现
/// </summary>
public IServer Communication { get; set; }
}
}
| 23.987013 | 101 | 0.54575 | [
"MIT"
] | junjie-sun/XNode | src/XNode/XNode/Server/NodeServerConfig.cs | 1,997 | C# |
using DesignPatternsAdapter.TwoProviders;
using System.Threading.Tasks;
using Xunit;
using Xunit.Abstractions;
namespace DesignPatternsAdapterTest
{
public class TwoProvidersTest
{
private readonly ITestOutputHelper _output;
public TwoProvidersTest(ITestOutputHelper output)
{
_output = output;
}
[Fact]
public async Task DisplayCharactersFromFile()
{
var service = new StarWarsCharacterDisplayService();
var result = await service.ListCharacters(StarWarsCharacterDisplayService.CharacterSource.File);
_output.WriteLine(result);
}
[Fact]
public async Task DisplayCharactersFromApi()
{
var service = new StarWarsCharacterDisplayService();
var result = await service.ListCharacters(StarWarsCharacterDisplayService.CharacterSource.Api);
_output.WriteLine(result);
}
}
}
| 25.447368 | 108 | 0.662875 | [
"MIT"
] | jasarsoft/design-patterns-adapter | DesignPatternsAdapterTest/TwoProvidersTest.cs | 967 | C# |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Xml;
using System.Data.SqlTypes;
using System.Diagnostics;
using System.IO;
using System.Xml.Serialization;
using System.Collections;
namespace System.Data.Common
{
internal sealed class SqlDoubleStorage : DataStorage
{
private SqlDouble[] _values;
public SqlDoubleStorage(DataColumn column)
: base(column, typeof(SqlDouble), SqlDouble.Null, SqlDouble.Null, StorageType.SqlDouble)
{
}
public override object Aggregate(int[] records, AggregateType kind)
{
bool hasData = false;
try
{
switch (kind)
{
case AggregateType.Sum:
SqlDouble sum = 0.0d;
foreach (int record in records)
{
if (IsNull(record))
continue;
checked { sum += _values[record]; }
hasData = true;
}
if (hasData)
{
return sum;
}
return _nullValue;
case AggregateType.Mean:
SqlDouble meanSum = 0.0d;
int meanCount = 0;
foreach (int record in records)
{
if (IsNull(record))
continue;
checked { meanSum += _values[record]; }
meanCount++;
hasData = true;
}
if (hasData)
{
SqlDouble mean = 0.0d;
checked { mean = (meanSum / meanCount); }
return mean;
}
return _nullValue;
case AggregateType.Var:
case AggregateType.StDev:
int count = 0;
SqlDouble var = 0.0d;
SqlDouble prec = 0.0d;
SqlDouble dsum = 0.0d;
SqlDouble sqrsum = 0.0d;
foreach (int record in records)
{
if (IsNull(record))
continue;
dsum += _values[record];
sqrsum += _values[record] * _values[record];
count++;
}
if (count > 1)
{
var = count * sqrsum - (dsum * dsum);
prec = var / (dsum * dsum);
// we are dealing with the risk of a cancellation error
// double is guaranteed only for 15 digits so a difference
// with a result less than 1e-15 should be considered as zero
if ((prec < 1e-15) || (var < 0))
var = 0;
else
var = var / (count * (count - 1));
if (kind == AggregateType.StDev)
{
return Math.Sqrt(var.Value);
}
return var;
}
return _nullValue;
case AggregateType.Min:
SqlDouble min = SqlDouble.MaxValue;
for (int i = 0; i < records.Length; i++)
{
int record = records[i];
if (IsNull(record))
continue;
if ((SqlDouble.LessThan(_values[record], min)).IsTrue)
min = _values[record];
hasData = true;
}
if (hasData)
{
return min;
}
return _nullValue;
case AggregateType.Max:
SqlDouble max = SqlDouble.MinValue;
for (int i = 0; i < records.Length; i++)
{
int record = records[i];
if (IsNull(record))
continue;
if ((SqlDouble.GreaterThan(_values[record], max)).IsTrue)
max = _values[record];
hasData = true;
}
if (hasData)
{
return max;
}
return _nullValue;
case AggregateType.First:
if (records.Length > 0)
{
return _values[records[0]];
}
return null;// no data => null
case AggregateType.Count:
count = 0;
for (int i = 0; i < records.Length; i++)
{
if (!IsNull(records[i]))
count++;
}
return count;
}
}
catch (OverflowException)
{
throw ExprException.Overflow(typeof(SqlDouble));
}
throw ExceptionBuilder.AggregateException(kind, _dataType);
}
public override int Compare(int recordNo1, int recordNo2)
{
return _values[recordNo1].CompareTo(_values[recordNo2]);
}
public override int CompareValueTo(int recordNo, object value)
{
return _values[recordNo].CompareTo((SqlDouble)value);
}
public override object ConvertValue(object value)
{
if (null != value)
{
return SqlConvert.ConvertToSqlDouble(value);
}
return _nullValue;
}
public override void Copy(int recordNo1, int recordNo2)
{
_values[recordNo2] = _values[recordNo1];
}
public override object Get(int record)
{
return _values[record];
}
public override bool IsNull(int record)
{
return (_values[record].IsNull);
}
public override void Set(int record, object value)
{
_values[record] = SqlConvert.ConvertToSqlDouble(value);
}
public override void SetCapacity(int capacity)
{
SqlDouble[] newValues = new SqlDouble[capacity];
if (null != _values)
{
Array.Copy(_values, 0, newValues, 0, Math.Min(capacity, _values.Length));
}
_values = newValues;
}
public override object ConvertXmlToObject(string s)
{
SqlDouble newValue = new SqlDouble();
string tempStr = string.Concat("<col>", s, "</col>"); // this is done since you can give fragmet to reader
StringReader strReader = new StringReader(tempStr);
IXmlSerializable tmp = newValue;
using (XmlTextReader xmlTextReader = new XmlTextReader(strReader))
{
tmp.ReadXml(xmlTextReader);
}
return ((SqlDouble)tmp);
}
public override string ConvertObjectToXml(object value)
{
Debug.Assert(!DataStorage.IsObjectNull(value), "we shouldn't have null here");
Debug.Assert((value.GetType() == typeof(SqlDouble)), "wrong input type");
StringWriter strwriter = new StringWriter(FormatProvider);
using (XmlTextWriter xmlTextWriter = new XmlTextWriter(strwriter))
{
((IXmlSerializable)value).WriteXml(xmlTextWriter);
}
return (strwriter.ToString());
}
protected override object GetEmptyStorage(int recordCount)
{
return new SqlDouble[recordCount];
}
protected override void CopyValue(int record, object store, BitArray nullbits, int storeIndex)
{
SqlDouble[] typedStore = (SqlDouble[])store;
typedStore[storeIndex] = _values[record];
nullbits.Set(storeIndex, IsNull(record));
}
protected override void SetStorage(object store, BitArray nullbits)
{
_values = (SqlDouble[])store;
//SetNullStorage(nullbits);
}
}
}
| 35.600775 | 118 | 0.424279 | [
"MIT"
] | Geotab/corefx | src/System.Data.Common/src/System/Data/Common/SQLTypes/SQLDoubleStorage.cs | 9,185 | C# |
//-----------------------------------------------------------------------
// <copyright company="Sherlock">
// Copyright 2013 Sherlock. Licensed under the Apache License, Version 2.0.
// </copyright>
//-----------------------------------------------------------------------
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated from a template.
//
// Manual changes to this file may cause unexpected behavior in your application.
// Manual changes to this file will be overwritten if the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
namespace Sherlock.Shared.DataAccess
{
using System;
using System.Collections.Generic;
/// <summary>
/// Defines a test that should be executed.
/// </summary>
public partial class Test
{
/// <summary>
/// Initializes a new instance of the <see cref="Test" /> class.
/// </summary>
public Test()
{
this.TestEnvironments = new HashSet<TestEnvironment>();
}
/// <summary>
/// Gets or sets the ID of the test.
/// </summary>
internal int pk_TestId { get; set; }
/// <summary>
/// Gets or sets the name of the product that is being tested.
/// </summary>
public string ProductName { get; set; }
/// <summary>
/// Gets or sets the version of the product that is being tested.
/// </summary>
public string ProductVersion { get; set; }
/// <summary>
/// Gets or sets the name of the user that requested the test.
/// </summary>
public string Owner { get; set; }
/// <summary>
/// Gets or sets the description for the current test.
/// </summary>
public string TestDescription { get; set; }
/// <summary>
/// Gets or sets the date and time on which the test was requested.
/// </summary>
public System.DateTimeOffset RequestTime { get; internal set; }
/// <summary>
/// Gets or sets the date and time on which the test was started.
/// </summary>
public Nullable<System.DateTimeOffset> StartTime { get; internal set; }
/// <summary>
/// Gets or sets the date and time on which the test was completed.
/// </summary>
public Nullable<System.DateTimeOffset> EndTime { get; internal set; }
/// <summary>
/// Gets or sets the full path to the directory in which the test report should be placed.
/// </summary>
public string ReportPath { get; set; }
/// <summary>
/// Gets or sets a value indicating whether the test setup is completed and the test is ready for execution.
/// </summary>
internal bool IsReadyForExecution { get; set; }
/// <summary>
/// Gets or sets the collection containing all the environments required for the test.
/// </summary>
internal ICollection<TestEnvironment> TestEnvironments { get; set; }
}
}
| 36.384615 | 117 | 0.510722 | [
"Apache-2.0"
] | pvandervelde/Sherlock | src/shared.dataaccess/Test.cs | 3,311 | C# |
using System;
namespace Sirh3e.Rust.Result
{
public readonly partial struct Result<TOk, TErr>
{
/// <summary>
///
/// </summary>
/// <param name="onOk"></param>
/// <param name="onErr"></param>
/// <exception cref="ArgumentNullException"></exception>
public void Match(Action<TOk> onOk, Action<TErr> onErr)
{
if ( IsOk )
{
if ( onOk is null )
{
throw new ArgumentNullException(nameof(onOk));
}
onOk(_ok);
}
else
{
if ( onErr is null )
{
throw new ArgumentNullException(nameof(onErr));
}
onErr(_err);
}
}
/// <summary>
///
/// </summary>
/// <param name="onOk"></param>
/// <param name="onErr"></param>
/// <typeparam name="T"></typeparam>
/// <returns></returns>
/// <exception cref="ArgumentNullException"></exception>
public T Match<T>(Func<TOk, T> onOk, Func<TErr, T> onErr)
{
if ( IsOk )
{
if ( onOk is null )
{
throw new ArgumentNullException(nameof(onOk));
}
return onOk(_ok);
}
if ( onErr is null )
{
throw new ArgumentNullException(nameof(onErr));
}
return onErr(_err);
}
}
} | 26.206349 | 68 | 0.394306 | [
"BSD-3-Clause"
] | sirh3e/Rust | src/Sirh3e.Rust/Result/Result.Match.cs | 1,653 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace DTAConfig.CustomSettings
{
sealed class FileSourceDestinationInfo
{
public FileSourceDestinationInfo(string source, string destination)
{
SourcePath = source;
DestinationPath = destination;
}
public string SourcePath { get; private set; }
public string DestinationPath { get; private set; }
}
}
| 24.761905 | 76 | 0.653846 | [
"MIT"
] | Metadorius/xna-cncnet-client | DTAConfig/CustomSettings/FileSourceDestinationInfo.cs | 502 | C# |
using DotNETDevOps.JsonFunctions;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Text.Json;
using System.Threading.Tasks;
namespace EAVFW.Extensions.Manifest.ManifestEnricherTool
{
public partial class ManifestCommand
{
public string Path { get; set; } = Directory.GetCurrentDirectory();
private static string? ToSchemaName(string? displayName)
{
return displayName?.Replace(" ", "").Replace(":", "_").Replace("/", "or").Replace("-", "").Replace("(", "").Replace(")", ""); ;
}
private JObject Merge(JObject jToken, object obj)
{
jToken = (JObject)jToken.DeepClone();
var jobj = JToken.FromObject(obj) as JObject;
foreach (var p in jobj.Properties())
{
if (!(p.Value.Type == JTokenType.Null || p.Value.Type == JTokenType.Undefined))
jToken[p.Name] = p.Value;
}
if (!jToken.ContainsKey("schemaName"))
jToken["schemaName"] = ToSchemaName(jToken.SelectToken("$.displayName")?.ToString());
if (!jToken.ContainsKey("logicalName"))
jToken["logicalName"] = jToken.SelectToken("$.schemaName")?.ToString().ToLower();
return jToken as JObject;
}
private JObject CreateAttribute(JObject attr, string displayName, object type, string? schemaName = null, object? additionalProps = null)
{
if (additionalProps != null)
return Merge(Merge(attr, new { displayName, type, schemaName }), additionalProps);
return Merge(attr, new { displayName, type, schemaName });
}
private object[] CreateOptions(params string[] args)
{
return args.Select((o, i) => new { label = o, value = i + 1 }).ToArray();
}
public async Task<JsonDocument> LoadJsonDocumentAsync(FileStream fs, string customizationprefix, ILogger logger)
{
var jsonraw = Newtonsoft.Json.Linq.JToken.ReadFrom(new Newtonsoft.Json.JsonTextReader(new StreamReader(fs)));
var insertMerges = jsonraw.SelectToken("$.variables.options.insertMergeLayoutVariable")?.ToObject<string>();
foreach (var entitieP in (jsonraw.SelectToken("$.entities") as JObject)?.Properties() ?? Enumerable.Empty<JProperty>())
{
var entity = (JObject)entitieP.Value;
if (!entity.ContainsKey("displayName"))
entity["displayName"] = entitieP.Name;
if (!entity.ContainsKey("schemaName"))
entity["schemaName"] = entity.SelectToken("$.displayName")?.ToString().Replace(" ", "");
if (!entity.ContainsKey("logicalName"))
entity["logicalName"] = entity.SelectToken("$.schemaName")?.ToString().ToLower();
if (!entity.ContainsKey("collectionSchemaName"))
entity["collectionSchemaName"] = ToSchemaName(entity["pluralName"]?.ToString());
JObject SetDefault(JToken obj, JObject localeEnglish)
{
var value = new JObject(new JProperty("1033", localeEnglish));
obj["locale"] = value;
return value;
}
var entityLocaleEnglish = new JObject(new JProperty("displayName", entity["displayName"]), new JProperty("pluralName", entity["pluralName"]));
var entityLocale = entity.SelectToken("$.locale") as JObject ?? SetDefault(entity, entityLocaleEnglish);
if (!entityLocale.ContainsKey("1033"))
entityLocale["1033"] = entityLocaleEnglish;
var attributes = entitieP.Value.SelectToken("$.attributes") as JObject;
if (attributes == null)
{
entitieP.Value["attributes"] = attributes = new JObject();
}
if (attributes != null)
{
if (!attributes.Properties().Any(p => p.Value.SelectToken("$.isPrimaryKey")?.ToObject<bool>() ?? false))
{
attributes["Id"] = JToken.FromObject(new { isPrimaryKey = true, type = "guid" });
}
//Replace string attributes
foreach (var attr in attributes.Properties().ToArray())
{
if (attr.Name == "[merge()]")
{
await RunReplacements(jsonraw, customizationprefix,logger, attr);
}
else if (attr.Value.Type == JTokenType.String)
{
await RunReplacements(jsonraw, customizationprefix,logger, attr.Value);
}
}
var queue = new Queue<JObject?>(attributes.Properties().Select(c => c.Value as JObject));
foreach (var attribute in attributes.Properties())
{
if (!string.IsNullOrEmpty(insertMerges))
{
var value = attribute.Value as JObject;
if (!value?.ContainsKey("[merge()]")??false)
value.Add(new JProperty("[merge()]", $"[variables('{insertMerges}')]"));
queue.Enqueue(value);
}
}
while (queue.Count > 0)
{
var attr = queue.Dequeue();
if (!attr.ContainsKey("displayName"))
attr["displayName"] = (attr.Parent as JProperty)?.Name;
if (attr["type"]?.ToString() == "address")
{
var displayName = attr.SelectToken("$.displayName")?.ToString();
attr["__unroll__path"] = attr.Path;
var unrolls = new[] {
Merge(attr,new { displayName=$"{displayName}: Address Type", type=new { type ="picklist",
isGlobal=false,
name=$"{displayName}: Address Type",
options=CreateOptions("Bill To","Ship To","Primary","Other")
} }),
Merge(attr,new { displayName=$"{displayName}: City", type="string"}),
Merge(attr,new { displayName=$"{displayName}: Country", type="string", schemaName=ToSchemaName( $"{displayName}: Country")}),
Merge(attr,new { displayName=$"{displayName}: County", type="string"}),
Merge(attr,new { displayName=$"{displayName}: Fax", type="string"}),
Merge(attr,new { displayName=$"{displayName}: Freight Terms", schemaName=ToSchemaName( $"{displayName}: Freight Terms Code"), type=new { type="picklist",
isGlobal=false,
name=$"{displayName}: Freight Terms",
options=CreateOptions("FOB","No Charge")
} }),
// Merge(attr,new { displayName=$"{displayName}: Id",schemaName=ToSchemaName( $"{displayName}: AddressId"),type ="guid"}),
CreateAttribute(attr,$"{displayName}: Latitude","float"),
CreateAttribute(attr,$"{displayName}: Longitude","float"),
CreateAttribute(attr,$"{displayName}: Name","string",null, new { isPrimaryField = !attributes.Properties().Any(p=>p.Value.SelectToken("$.isPrimaryField") != null) }),
CreateAttribute(attr,$"{displayName}: Phone","phone", ToSchemaName( $"{displayName}: Telephone 1")),
CreateAttribute(attr,$"{displayName}: Telephone 2","phone", ToSchemaName( $"{displayName}: Telephone 2")),
CreateAttribute(attr,$"{displayName}: Telephone 3","phone", ToSchemaName( $"{displayName}: Telephone 3")),
CreateAttribute(attr,$"{displayName}: Post Office Box","string"),
CreateAttribute(attr,$"{displayName}: Primary Contact Name","string"),
CreateAttribute(attr,$"{displayName}: Shipping Method",new { type="picklist",
isGlobal=false,
name=$"{displayName}: Shipping Method",
options=CreateOptions("Airborne","DHL","FedEx","UPS","Postal Mail","Full Load","Will Call"),
}, ToSchemaName( $"{displayName}: Shipping Method Code")),
CreateAttribute(attr,$"{displayName}: State/Province","string"),
CreateAttribute(attr,$"{displayName}: Street 1","string",ToSchemaName( $"{displayName}: line1")),
CreateAttribute(attr,$"{displayName}: Street 2","string",ToSchemaName( $"{displayName}: line2")),
CreateAttribute(attr,$"{displayName}: Street 3","string",ToSchemaName( $"{displayName}: line3")),
CreateAttribute(attr,$"{displayName}: UPS Zone","string"),
CreateAttribute(attr,$"{displayName}: UTC Offset","timezone"),
CreateAttribute(attr,$"{displayName}: ZIP/Postal Code","string",ToSchemaName( $"{displayName}: Postal Code")),
CreateAttribute(attr,$"{displayName}: State/Province","string"),
};
attr["schemaName"] = displayName.Replace(" ", "").Replace(":", "_") + "_Composite";
attr["type"] = "MultilineText";
foreach (var unroll in unrolls)
{
queue.Enqueue(unroll);
}
//if(!attributes.Properties().Any(p=>p.Value.SelectToken("$.isPrimaryField") != null))
//{
// attr["type"] = JObject.FromObject(new { type = "string", maxLength = 1024 });
// attr["isPrimaryField"] = true;
//}
}
if (!attr.ContainsKey("schemaName"))
{
attr["schemaName"] = ToSchemaName(attr.SelectToken("$.displayName").ToString());
await RunReplacements(jsonraw, customizationprefix, logger,attr);
switch (attr.SelectToken("$.type.type")?.ToString()?.ToLower())
{
case "lookup":
case "customer":
if (!attr["schemaName"].ToString().EndsWith("Id"))
attr["schemaName"] = $"{ToSchemaName(attr.SelectToken("$.displayName").ToString())}Id";
break;
}
}
if (!attr.ContainsKey("logicalName"))
attr["logicalName"] = attr.SelectToken("$.schemaName").ToString().ToLower();
if (!attr.ContainsKey("type"))
attr["type"] = "string";
if (attr.Parent == null && !(attributes.ContainsKey(attr["logicalName"].ToString()) || attributes.ContainsKey(attr["schemaName"].ToString()) || attributes.ContainsKey(attr["displayName"].ToString())))
attributes[attr["logicalName"].ToString()] = attr;
if (attr.SelectToken("$.type").Type == JTokenType.String)
{
attr["type"] = JToken.FromObject(new { type = attr.SelectToken("$.type") });
}
}
foreach (var attr in attributes.Properties())
{
var attributeLocaleEnglish = new JObject(new JProperty("displayName", attr.Value["displayName"]));
var attributeLocale = attr.Value.SelectToken("$.locale") as JObject ?? SetDefault(attr.Value, attributeLocaleEnglish);
if (!attributeLocale.ContainsKey("1033"))
attributeLocale["1033"] = attributeLocaleEnglish;
}
}
}
await RunReplacements(jsonraw, customizationprefix,logger);
foreach (var entitieP in (jsonraw.SelectToken("$.entities") as JObject)?.Properties() ?? Enumerable.Empty<JProperty>())
{
var attributes = entitieP.Value.SelectToken("$.attributes") as JObject;
foreach (var attributeDefinition in attributes.Properties())
{
var attr = attributeDefinition.Value;
switch (attr.SelectToken("$.type.type")?.ToString()?.ToLower())
{
case "lookup":
attr["type"]["foreignKey"] = JToken.FromObject(new
{
principalTable = jsonraw.SelectToken($"$.entities['{ attr["type"]["referenceType"] }'].logicalName").ToString(),
principalColumn = jsonraw.SelectToken($"$.entities['{ attr["type"]["referenceType"] }'].attributes").OfType<JProperty>()
.Concat(jsonraw.SelectToken($"$.entities['{ attr["type"]["referenceType"] }'].TPT") == null ? Enumerable.Empty<JProperty>() : jsonraw.SelectToken($"$.entities['{jsonraw.SelectToken($"$.entities['{ attr["type"]["referenceType"] }'].TPT") }'].attributes").OfType<JProperty>())
.GroupBy(k => k.Name).Select(g => g.First())
.Single(a => a.Value.SelectToken("$.isPrimaryKey")?.ToObject<bool>() ?? false).Value.SelectToken("$.logicalName").ToString(),
principalNameColumn = jsonraw.SelectToken($"$.entities['{ attr["type"]["referenceType"] }'].attributes").OfType<JProperty>()
.Concat(jsonraw.SelectToken($"$.entities['{ attr["type"]["referenceType"] }'].TPT") == null ? Enumerable.Empty<JProperty>() : jsonraw.SelectToken($"$.entities['{jsonraw.SelectToken($"$.entities['{ attr["type"]["referenceType"] }'].TPT") }'].attributes").OfType<JProperty>())
.GroupBy(k => k.Name).Select(g => g.First())
.Single(a => a.Value.SelectToken("$.isPrimaryField")?.ToObject<bool>() ?? false).Value.SelectToken("$.logicalName").ToString(),
name = TrimId(attr.SelectToken("$.logicalName")?.ToString()) // jsonraw.SelectToken($"$.entities['{ attr["type"]["referenceType"] }'].logicalName").ToString().Replace(" ", ""),
});
break;
case "float":
case "decimal":
if (attr.SelectToken("$.type.sql") == null)
{
attr["type"]["sql"] = JToken.FromObject(new { precision = 18, scale = 4 });
}
if (attr.SelectToken("$.type.sql.precision") == null)
{
attr["type"]["sql"]["precision"] = 18;
}
if (attr.SelectToken("$.type.sql.scale") == null)
{
attr["type"]["sql"]["scale"] = 4;
}
break;
}
}
}
var defaultControls = jsonraw.SelectToken("$.controls");
if (defaultControls != null)
{
logger.LogInformation("Replacing default Controls");
foreach (var defaultControl in defaultControls.OfType<JProperty>())
{
logger.LogInformation("Replacing default Controls : {Type}", defaultControl.Name);
foreach (var entity in jsonraw.SelectToken("$.entities")?.OfType<JProperty>() ?? Enumerable.Empty<JProperty>())
{
foreach (var attribute in entity.Value.SelectToken("$.attributes")?.OfType<JProperty>() ?? Enumerable.Empty<JProperty>())
{
var attributeType = (attribute.Value.SelectToken("$.type.type") ?? attribute.Value.SelectToken("$.type")).ToString();
if (string.Equals(attributeType, defaultControl.Name, StringComparison.OrdinalIgnoreCase))
{
logger.LogInformation("Replacing default Controls for {entity} {attribute} : {type}", entity.Name, attribute.Name, defaultControl.Name);
var formFields = (entity.Value.SelectToken($"$.forms")?.OfType<JProperty>() ?? Enumerable.Empty<JProperty>())
.Select(c => c.Value.SelectToken($"$.columns['{attribute.Name}']")).Where(c => c != null).ToArray();
{
foreach (var formField in formFields)
{
var control = formField.SelectToken("$.control");
if (control == null)
{
var replacement = defaultControl.Value.DeepClone(); ;
formField["control"] = replacement;
var q = new Queue<JToken>(new[] { replacement });
while (q.Any())
{
var e = q.Dequeue();
if (e is JObject obj)
{
foreach (var prop in e.OfType<JProperty>())
{
q.Enqueue(prop);
}
}
else if (e is JProperty prop)
{
q.Enqueue(prop.Value);
}
else if (e is JArray array)
{
foreach (var ee in array)
{
q.Enqueue(ee);
}
}
else if (e.Type == JTokenType.String)
{
var str = e.ToString();
if (str.StartsWith("[[") && str.EndsWith("]]"))
{
e.Replace(str.Substring(1, str.Length - 2));
}
}
}
logger.LogInformation("Replacing default Controls for {entity} {attribute} {formname}: {type}", entity.Name, attribute.Name, (formField.Parent.Parent.Parent as JProperty)?.Name, defaultControl.Name);
}
}
}
}
}
}
}
}
await RunReplacements(jsonraw, customizationprefix,logger);
foreach (var (entityDefinition, attributeDefinition2) in jsonraw.SelectToken("$.entities").OfType<JProperty>()
.SelectMany(e => e.Value.SelectToken("$.attributes").OfType<JProperty>().Select(p => (e, p)))
.Where(a => a.p.Value.SelectToken("$.type.type")?.ToString().ToLower() == "choices")
.ToArray())
{
var nentity = $"{attributeDefinition2.Value.SelectToken("$.type.name")}";
jsonraw["entities"][nentity] = JToken.FromObject(
new
{
pluralName = $"{attributeDefinition2.Value.SelectToken("$.type.pluralName")}",
displayName = nentity,
logicalName = $"{attributeDefinition2.Value.SelectToken("$.type.name")}".Replace(" ", "").ToLower(),
schemaName = $"{attributeDefinition2.Value.SelectToken("$.type.name")}".Replace(" ", ""),
collectionSchemaName = $"{attributeDefinition2.Value.SelectToken("$.type.pluralName")}".Replace(" ", ""),
keys = new Dictionary<string, object>
{
[$"IX_{entityDefinition.Name}Value"] = new[] { entityDefinition.Name, nentity + " Value" }
},
attributes = new Dictionary<string, object>
{
["Id"] = new
{
displayName = "Id",
logicalName = "id",
schemaName = "Id",
type = "guid",
isPrimaryKey = true,
},
[entityDefinition.Name] = new
{
displayName = entityDefinition.Value.SelectToken("$.displayName"),
logicalName = entityDefinition.Value.SelectToken("$.logicalName")+"id",
schemaName = entityDefinition.Value.SelectToken("$.schemaName") + "Id",
type = new
{
type = "lookup",
referenceType = entityDefinition.Name,
},
},
[nentity+" Value"] = new
{
displayName = nentity+" Value",
logicalName = $"{attributeDefinition2.Value.SelectToken("$.type.name")}".Replace(" ", "").ToLower(),
schemaName = $"{attributeDefinition2.Value.SelectToken("$.type.name")}".Replace(" ", "") +"Value",
// isPrimaryKey = true,
type = new
{
type = "choice",
name = $"{attributeDefinition2.Value.SelectToken("$.type.name")}".Replace(" ", "") + "Value",
options = attributeDefinition2.Value.SelectToken("$.type.options")
}
}
}
});
//attributeDefinition2.Value.SelectToken("$.type").Replace(JToken.FromObject(
// new
// {
// type = "lookup",
// referenceType = $"{attributeDefinition2.Value.SelectToken("$.type.name")}"
// }
// ));
attributeDefinition2.Value["type"]["logicalName"] = $"{attributeDefinition2.Value.SelectToken("$.type.name")}".Replace(" ", "").ToLower();
attributeDefinition2.Value["type"]["schemaName"] = $"{attributeDefinition2.Value.SelectToken("$.type.name")}".Replace(" ", "");
attributeDefinition2.Value["type"]["collectionSchemaName"] = $"{attributeDefinition2.Value.SelectToken("$.type.pluralName")}".Replace(" ", "");
attributeDefinition2.Value["type"]["principalColumn"] = entityDefinition.Value.SelectToken("$.logicalName") + "id";
// attributeDefinition2.Remove();
}
var json = JsonDocument.Parse(jsonraw.ToString(), new JsonDocumentOptions
{
CommentHandling = JsonCommentHandling.Skip
});
Directory.CreateDirectory("obj");
File.WriteAllText("obj/manifest.g.json", jsonraw.ToString(Newtonsoft.Json.Formatting.Indented));
///For loop over jsonraw.selectToken("$.entities")
///write a file to obj/specs/<entity.logicalName>.spec.g.json
///containing a json schema file for the entity attributes. Sadly there is no strict type map of possible types.
///Types can be anything random that i later maps to something in dynamics. (use tolower)
/// Currently from AttributeTypeCodeConverter - currency,customer,datetime,multilinetext,memo,int,integer,timezone,phone,float,guid,string,text,boolean,bool,
/// and type.type can be autonumber,choice,picklist,choices,state,status,lookup,string,text
bool ConvertToSchemaType(JToken attrType, out JToken type)
{
type = null;
var inp = attrType?.ToString();
if (!(attrType.Type == JTokenType.String))
{
inp = attrType.SelectToken("$.type")?.ToString();
}
switch (inp.ToLower())
{
case "binary":
type = JToken.FromObject(new
{
type = "string",
contentEncoding = "base64"
});
return true;
case "datetime":
type = "datetime";
return true;
case "customer":
return false;
case "string":
case "text":
case "multilinetext":
type = "string";
return true;
case "integer":
type = "integer";
return true;
case "decimal":
type = "number";
return true;
case "boolean":
type = "boolean";
return true;
case "lookup":
var foreignTable = jsonraw.SelectToken($"$.entities['{attrType.SelectToken("$.referenceType")}']");
var fatAttributes = foreignTable.SelectToken("$.attributes");
var fat = fatAttributes.OfType<JProperty>().Where(c => c.Value.SelectToken("$.isPrimaryKey")?.ToObject<bool>() ?? false)
.Select(a => a.Value.SelectToken("$.type")).Single();
if (fat.Type == JTokenType.Object)
fat = fat.SelectToken("$.type");
ConvertToSchemaType(fat?.ToString(), out type);
type["x-foreign-key"] = JToken.FromObject(new
{
table = new
{
logicalName = foreignTable.SelectToken("$.logicalName"),
schemaName = foreignTable.SelectToken("$.schemaName"),
pluralName = foreignTable.SelectToken("$.pluralName"),
},
columns = fatAttributes.OfType<JProperty>().Where(c => c.Value.SelectToken("$.isPrimaryKey")?.ToObject<bool>() ?? false)
.Select(a => new
{
logicalName = a.SelectToken("$.logicalName"),
schemaName = a.SelectToken("$.schemaName"),
})
});
return true;
case "guid":
type = JToken.FromObject(new
{
type = "string",
format = "uuid"
});
return true;
case "choices":
type = JToken.FromObject(new
{
type = "array",
items = new
{
type = "integer",
@enum = attrType.SelectToken("$.options").OfType<JProperty>().Select(c => c.Value.ToObject<int>())
}
});
return true;
case "choice":
type = JToken.FromObject(new
{
type = "integer",
@enum = attrType.SelectToken("$.options").OfType<JProperty>().Select(c => c.Value.Type== JTokenType.Object ? c.Value.SelectToken("$.value") : c.Value).Select(v => v.ToObject<int>())
});
return true;
default:
throw new NotImplementedException(inp);
}
}
Directory.CreateDirectory("obj/models");
foreach (var entity in (jsonraw.SelectToken("$.entities") as JObject)?.Properties() ?? Enumerable.Empty<JProperty>())
{
try
{
var entityValue = entity.Value as JObject;
var schema = new JObject
{
["title"] = entity.Name,
["$schema"] = "http://json-schema.org/draft-07/schema#",
["type"] = "object",
};
var properties = new JObject();
foreach (var attr in (entityValue.SelectToken("$.attributes") as JObject)?.Properties() ?? Enumerable.Empty<JProperty>())
{
var attrValue = attr.Value as JObject;
var attrType = attrValue.SelectToken("$.type");
var logicalName = attrValue.SelectToken("$.logicalName").ToString();
var displayName = attrValue.SelectToken("$.displayName").ToString();
var propValues = new JObject();
propValues["title"] = displayName;
if (!ConvertToSchemaType(attrType, out var type)) continue;
propValues["type"] = type;
properties[logicalName] = propValues;
}
schema["properties"] = properties;
var filePath = $"obj/models/{entityValue["logicalName"]}.spec.g.json";
File.WriteAllText(filePath, schema.ToString(Newtonsoft.Json.Formatting.Indented));
}
catch (Exception ex)
{
Console.WriteLine($"Warning: Failed to generate jsonschema for {entity.Name}");
Console.Write(ex);
}
}
return json;
}
private string TrimId(string v)
{
if (string.IsNullOrEmpty(v))
return v;
if (v.EndsWith("id", StringComparison.OrdinalIgnoreCase))
return v.Substring(0, v.Length - 2);
return v;
}
private async Task RunReplacements(JToken jsonraw, string customizationprefix, ILogger logger, JToken elementToRunReplacementFor = null)
{
var entityPath = string.Empty;
var attributePath = string.Empty;
JToken currentElement = null;
JToken localelement = null;
JToken[] localarguments = null;
var q = new Queue<JToken>(new[] { elementToRunReplacementFor ?? jsonraw });
var expressionParser = new ExpressionParser<Newtonsoft.Json.Linq.JToken>(
Options.Create(new ExpressionParserOptions<Newtonsoft.Json.Linq.JToken>() { Document = jsonraw, ThrowOnError = true }), logger,
new DefaultExpressionFunctionFactory<Newtonsoft.Json.Linq.JToken>()
{
Functions =
{
["data"] = (parser,Document,arguments) => {Console.WriteLine(arguments[0]); var child=JToken.Parse(File.ReadAllText(System.IO.Path.Combine(System.IO.Path.GetDirectoryName(Path) ,arguments[0]?.ToString())));// q.Enqueue(child);
return Task.FromResult<JToken>(child); },
["customizationprefix"] =(parser,Document,arguments) => Task.FromResult<JToken>(customizationprefix),
["propertyNames"] = (parser,document,arguments) => Task.FromResult<JToken>((arguments[0] is JObject obj ? JToken.FromObject( obj.Properties().Select(k=>k.Name)):new JArray())),
["indexOf"] =(parser,document,arguments) => Task.FromResult<JToken>(Array.IndexOf( arguments[0].ToArray(),arguments[1])),
["default"] = (parser,document,arguments) => Task.FromResult(arguments[0] == null || arguments[0].Type == JTokenType.Null ? arguments[1]:arguments[0]),
["unfoldsource"] = (parser,document,arguments)=> Task.FromResult(document.SelectToken(arguments[0]["__unroll__path"].ToString())),
["if"] = (parser,document,arguments) => Task.FromResult(arguments[0].ToObject<bool>() ? arguments[1]:arguments[2]),
["condition"] = (parser,document,arguments) => Task.FromResult(arguments[0].ToObject<bool>() ? arguments[1]:arguments[2]),
["in"] =(parser,document,arguments) => Task.FromResult(JToken.FromObject( arguments[1] != null && ( arguments[1] is JObject obj ? obj.ContainsKey(arguments[0].ToString()) : arguments[1].Any(a=>arguments[0].Equals(a))) )),
["variables"] = (parser,document,arguments)=> { localarguments= arguments; return Task.FromResult(jsonraw.SelectToken($"$.variables.{arguments.First()}")?.DeepClone()); },
["concat"] = (parser,document,arguments)=>Task.FromResult<JToken>(string.Join("",arguments.Select(k=>k.ToString())) ),
["entity"] = (parser, document, arguments) =>
{
var entity = document.SelectToken(entityPath);
return Task.FromResult<JToken>(entity);
},
["toLogicalName"] = (parser,document,arguments) => Task.FromResult<JToken>(ToSchemaName(arguments[0].ToString()).ToLower()),
["attribute"] = (parser, document, arguments) => Task.FromResult(document.SelectToken(attributePath)),
["attributes"] = (parser, document, arguments) => Task.FromResult(document.SelectToken(entityPath+".attributes")),
["select"] = (parser, document, arguments) => Task.FromResult(arguments.FirstOrDefault(a=>!(a== null || a.Type == JTokenType.Null))),
["propertyName"] = (parser, document, arguments) => Task.FromResult<JToken>( arguments[0].Parent is JProperty prop ? prop.Name : null),
["parent"] =(parser, document, arguments) => Task.FromResult<JToken>( arguments.Any() ? (arguments[0].Parent is JProperty prop ? prop.Parent:arguments[0].Parent) : (currentElement.Parent is JProperty prop1 ? prop1.Parent:currentElement.Parent)),
["element"]=(parser,document,arguments)=>Task.FromResult(localelement ?? currentElement),
["map"] =async (parser, document, arguments) =>{
return JToken.FromObject( await Task.WhenAll( arguments[0].Select(a=>{
localelement = a;
return parser.EvaluateAsync(arguments[1].ToString());
})));
}
}
});
while (q.Count > 0)
{
var a = q.Dequeue();
if (a == null)
continue;
entityPath = ExtractPath(a, "entities");
attributePath = ExtractPath(a, "attributes") ?? ExtractPath(a, "columns");
try
{
if (a is JProperty prop)
{
var value = prop.Value;
var str = prop.Name;
if (ShouldEvaluate(str))
{
if (str == "[merge()]")
{
var parentObj = prop.Parent as JObject;
var obj = prop.Value;
if (obj.Type == JTokenType.String && ShouldEvaluate(obj.ToString()))
{
currentElement = obj;
obj = await EvaluateAsync(expressionParser, obj.ToString());
}
foreach (var childProp in (obj as JObject).Properties().ToArray())
{
childProp.Remove();
parentObj.Add(childProp);
// parentObj.Add(childProp.Name, childProp.Value);
q.Enqueue(childProp);
}
prop.Remove();
continue;
}
currentElement = prop.Value;
var nToken = await EvaluateAsync(expressionParser, str);
if (nToken.Type == JTokenType.Null || nToken.Type == JTokenType.Undefined)
{
prop.Remove();
continue;
}
var nProp = new JProperty(nToken.ToString(), value);
prop.Replace(nProp);
q.Enqueue(nProp);
}
else
{
q.Enqueue(value);
}
}
else if (a is JObject obj)
{
foreach (var p in obj.Properties())
{
q.Enqueue(p);
}
}
else if (a is JArray array)
{
foreach (var element in array)
q.Enqueue(element);
}
else if (a.Type == JTokenType.String)
{
var str = a.ToString();
if (ShouldEvaluate(str))
{
currentElement = a;
var t = await EvaluateAsync(expressionParser, str);
a.Replace(t);
q.Enqueue(t);
}
}
}
catch (Exception ex)
{
Console.WriteLine($"{entityPath}| {attributePath}");
throw;
}
}
}
private static async Task<JToken> EvaluateAsync(ExpressionParser<JToken> expressionParser, string str)
{
try
{
var nToken = await expressionParser.EvaluateAsync(str);
if (nToken == null)
{
return nToken;
}
if (nToken.Type == JTokenType.Object)
{
var q = new Queue<JToken>();
q.Enqueue(nToken);
while (q.Count > 0)
{
var c = q.Dequeue();
if (c is JObject o)
{
foreach (var p in o.Properties())
q.Enqueue(p);
}
else if (c is JProperty p)
{
if (p.Name.StartsWith("[["))
{
var nprop = new JProperty(p.Name.Substring(1, p.Name.Length - 2), p.Value);
p.Replace(nprop);
q.Enqueue(nprop);
}
else
{
q.Enqueue(p.Value);
}
}
else if (c is JArray a)
{
foreach (var e in a)
q.Enqueue(e);
}
else if (c.Type == JTokenType.String && c.ToString().StartsWith("[["))
{
// var ch = await expressionParser.EvaluateAsync(c.ToString().Substring(1, c.ToString().Length - 2));
// c.Replace(ch);
// q.Enqueue(ch);
var child = c.ToString().Substring(1, c.ToString().Length - 2);
// var childToken = await EvaluateAsync(expressionParser, child);
c.Replace(child);
}
}
}
while (nToken.Type == JTokenType.String && ShouldEvaluate(nToken.ToString().Substring(1, nToken.ToString().Length - 2)))
{
nToken = await expressionParser.EvaluateAsync(nToken.ToString().Substring(1, nToken.ToString().Length - 2));
}
return nToken;
}
catch (Exception ex)
{
Console.WriteLine("EvaluateAsync");
throw;
}
}
private static bool ShouldEvaluate(string str)
{
return str.StartsWith("[") && str.EndsWith("]") && !str.StartsWith("[[");
}
private static string ExtractPath(JToken token, string part)
{
string partPath;
if (token.Path.Contains(part) && !token.Path.EndsWith(part))
{
var idx = token.Path.IndexOf(part) + part.Length + 1;
partPath = new string(token.Path.TakeWhile((c, i) => i < idx || !(c == '.' || c == ']')).ToArray());
if (partPath.EndsWith('\''))
partPath += ']';
}
else
{
partPath = string.Empty;
}
if (partPath.EndsWith("[merge()]"))
{
partPath = partPath.Replace("[merge()]", "");
}
return string.IsNullOrEmpty(partPath) ? null : partPath;
}
}
}
| 48.52546 | 310 | 0.439862 | [
"MIT"
] | EAVFW/EAVFW.Extensions.Manifest.ManifestEnricherTool | src/EAVFW.Extensions.Manifest.ManifestEnricherTool/manifest.cs | 44,791 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Secao9.Entities
{
class HourContract
{
public DateTime Date { get; set; }
public double ValuePerHour { get; set; }
public int Hours { get; set; }
public HourContract(DateTime date, double valuePerHour, int hours)
{
Date = date;
ValuePerHour = valuePerHour;
Hours = hours;
}
public double TotalValue()
{
return Hours * ValuePerHour;
}
}
}
| 21.428571 | 74 | 0.586667 | [
"MIT"
] | zJhol/worker | Secao9/Entities/HourContract.cs | 602 | C# |
/****************************************************************************
Copyright (c) 2013-2015 scutgame.com
http://www.scutgame.com
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
****************************************************************************/
using System;
using System.Collections.Generic;
using System.Configuration;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using ZyGames.Framework.Common;
using ZyGames.Framework.Common.Configuration;
using ZyGames.Framework.Data;
namespace ZyGames.Framework.Game.Runtime
{
/// <summary>
///
/// </summary>
public class DefaultAppConfigger : DefaultDataConfigger
{
/// <summary>
/// init
/// </summary>
public DefaultAppConfigger()
{
ConfigFile = Path.Combine(MathUtils.RuntimePath, "GameServer.exe.config");
}
/// <summary>
///
/// </summary>
protected override void LoadConfigData()
{
ConfigurationManager.RefreshSection("appSettings");
ConfigurationManager.RefreshSection("connectionStrings");
var er = ConfigurationManager.ConnectionStrings.GetEnumerator();
while (er.MoveNext())
{
var connSetting = er.Current as ConnectionStringSettings;
if (connSetting == null) continue;
AddNodeData(new ConnectionSection(connSetting.Name, connSetting.ProviderName, connSetting.ConnectionString));
}
base.LoadConfigData();
}
}
/// <summary>
///
/// </summary>
public class AppServerConfigger : DataConfigger
{
/// <summary>
/// init
/// </summary>
public AppServerConfigger()
{
ConfigFile = Path.Combine(MathUtils.RuntimePath, "AppServer.config");
}
/// <summary>
///
/// </summary>
protected override void LoadConfigData()
{
}
}
}
| 35.54023 | 126 | 0.616429 | [
"Unlicense"
] | HongXiao/Scut | Source/Middleware/ZyGames.Framework.Game/Runtime/AppServerConfigger.cs | 3,094 | C# |
using System.Linq;
using System.Runtime.Serialization;
using StandardDot.Caching.Redis.Enums;
using StandardDot.CoreExtensions;
using StandardDot.CoreExtensions.Object;
namespace StandardDot.Caching.Redis.Dto
{
[DataContract]
public class RedisId
{
// new []
// {
// "hashSetIdentifier",
// "objectIdentifier",
// "serviceType"
// };
private static string[] _dataMemberNames =
typeof(RedisId).GetProperties()
.Select(x => x.GetCustomAttributes(typeof(DataMemberAttribute), true).Cast<DataMemberAttribute>())
.SelectMany(x => x).Select(x => x.Name)
.ToArray();
public static string[] DataMemberNames => _dataMemberNames;
[DataMember(Name = "hashSetIdentifier")]
public string HashSetIdentifier { get; set; }
[DataMember(Name = "objectIdentifier")]
public string ObjectIdentifier { get; set; }
[DataMember(Name = "serviceType")]
public RedisServiceType ServiceType { get; set; }
[IgnoreDataMember]
public string FullKey
{
get
{
switch (ServiceType)
{
case RedisServiceType.HashSet:
return (HashSetIdentifier ?? "") + ":" + (ObjectIdentifier ?? "");
case RedisServiceType.KeyValue:
default:
return (string.IsNullOrWhiteSpace(HashSetIdentifier) ? "" : HashSetIdentifier + ":")
+ (ObjectIdentifier ?? "");
}
}
}
[IgnoreDataMember]
public bool HasFullKey
{
get
{
switch (ServiceType)
{
case RedisServiceType.HashSet:
return !(string.IsNullOrWhiteSpace(HashSetIdentifier) || string.IsNullOrWhiteSpace(ObjectIdentifier));
case RedisServiceType.KeyValue:
default:
return !(string.IsNullOrWhiteSpace(ObjectIdentifier));
}
}
}
public static implicit operator string(RedisId id)
{
return id?.SerializeJson();
}
public static implicit operator RedisId(string id)
{
return id?.DeserializeJson<RedisId>();
}
}
} | 24.25641 | 108 | 0.684461 | [
"MIT"
] | mrlunchbox777/StandardDot | src/CachingRedis/Dto/RedisId.cs | 1,892 | C# |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using NUnit.Framework;
namespace NUnitTestProject;
[TestFixture]
public class NUnitTest1
{
[Test]
public void PassTestMethod1()
{
Assert.AreEqual(5, 5);
}
[Test]
public void FailTestMethod1()
{
Assert.AreEqual(5, 6);
}
}
| 19 | 101 | 0.672769 | [
"MIT"
] | Evangelink/vstest | test/TestAssets/NUTestProject/Class1.cs | 439 | C# |
using UnityEngine;
public class ConeCast2DExample : MonoBehaviour {
public float radius;
public float depth;
public float angle;
private Physics physics;
void FixedUpdate ()
{
RaycastHit2D[] coneHits = Physics2DCones.ConeCastAll(transform.position, transform.forward, angle, depth);
for (int i = 0; i < coneHits.Length; i++)
{
//do something with collider information
coneHits[i].collider.gameObject.GetComponent<Renderer>().material.color = new Color(0, 0, 1f);
}
}
}
public class ConeCast2DExample2 : MonoBehaviour
{
public float radius;
public float depth;
public float angle;
private RayCastHit2D[] hits = new RayCastHit2D[100];
void FixedUpdate()
{
int numResults = Physics2DCones.ConeCastNonAlloc(transform.position, radius, transform.forward, hits, depth);
for (int i = 0; i < numResults; i++)
{
//do something with collider information
hits[i].collider.gameObject.GetComponent<Renderer>().material.color = new Color(0, 0, 1f);
}
}
}
| 25.340909 | 117 | 0.64574 | [
"MIT"
] | AshbyGeek/ConeCast | Physics2DConesExample.cs | 1,117 | C# |
// *** WARNING: this file was generated by the Pulumi SDK Generator. ***
// *** Do not edit by hand unless you're certain you know what you are doing! ***
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Threading.Tasks;
using Pulumi.Serialization;
namespace Pulumi.AzureNextGen.Storage.V20210101.Inputs
{
/// <summary>
/// Settings for Azure Files identity based authentication.
/// </summary>
public sealed class AzureFilesIdentityBasedAuthenticationArgs : Pulumi.ResourceArgs
{
/// <summary>
/// Required if choose AD.
/// </summary>
[Input("activeDirectoryProperties")]
public Input<Inputs.ActiveDirectoryPropertiesArgs>? ActiveDirectoryProperties { get; set; }
/// <summary>
/// Indicates the directory service used.
/// </summary>
[Input("directoryServiceOptions", required: true)]
public InputUnion<string, Pulumi.AzureNextGen.Storage.V20210101.DirectoryServiceOptions> DirectoryServiceOptions { get; set; } = null!;
public AzureFilesIdentityBasedAuthenticationArgs()
{
}
}
}
| 33.257143 | 143 | 0.683849 | [
"Apache-2.0"
] | pulumi/pulumi-azure-nextgen | sdk/dotnet/Storage/V20210101/Inputs/AzureFilesIdentityBasedAuthenticationArgs.cs | 1,164 | C# |
/*
* Copyright (c) 2018 THL A29 Limited, a Tencent company. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
namespace TencentCloud.Ms.V20180408.Models
{
using Newtonsoft.Json;
using System.Collections.Generic;
using TencentCloud.Common;
public class CreateScanInstancesResponse : AbstractModel
{
/// <summary>
/// 任务唯一标识
/// </summary>
[JsonProperty("ItemId")]
public string ItemId{ get; set; }
/// <summary>
/// 任务状态: 1-已完成,2-处理中,3-处理出错,4-处理超时
/// </summary>
[JsonProperty("Progress")]
public ulong? Progress{ get; set; }
/// <summary>
/// 提交成功的app的md5集合
/// </summary>
[JsonProperty("AppMd5s")]
public string[] AppMd5s{ get; set; }
/// <summary>
/// 剩余可用次数
/// </summary>
[JsonProperty("LimitCount")]
public ulong? LimitCount{ get; set; }
/// <summary>
/// 到期时间
/// </summary>
[JsonProperty("LimitTime")]
public ulong? LimitTime{ get; set; }
/// <summary>
/// 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
/// </summary>
[JsonProperty("RequestId")]
public string RequestId{ get; set; }
/// <summary>
/// For internal usage only. DO NOT USE IT.
/// </summary>
public override void ToMap(Dictionary<string, string> map, string prefix)
{
this.SetParamSimple(map, prefix + "ItemId", this.ItemId);
this.SetParamSimple(map, prefix + "Progress", this.Progress);
this.SetParamArraySimple(map, prefix + "AppMd5s.", this.AppMd5s);
this.SetParamSimple(map, prefix + "LimitCount", this.LimitCount);
this.SetParamSimple(map, prefix + "LimitTime", this.LimitTime);
this.SetParamSimple(map, prefix + "RequestId", this.RequestId);
}
}
}
| 31.177215 | 81 | 0.599269 | [
"Apache-2.0"
] | TencentCloud/tencentcloud-sdk-dotnet | TencentCloud/Ms/V20180408/Models/CreateScanInstancesResponse.cs | 2,605 | C# |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.Extensions.DependencyInjection;
namespace Microsoft.AspNetCore.Hosting.Tests.Internal
{
public class MyContainer : IServiceProvider
{
private IServiceProvider _inner;
private IServiceCollection _services;
public bool FancyMethodCalled { get; private set; }
public IServiceCollection Services => _services;
public string Environment { get; set; }
public object GetService(Type serviceType)
{
return _inner.GetService(serviceType);
}
public void Populate(IServiceCollection services)
{
_services = services;
}
public void Build()
{
_inner = _services.BuildServiceProvider();
}
public void MyFancyContainerMethod()
{
FancyMethodCalled = true;
}
}
}
| 25.045455 | 71 | 0.654265 | [
"MIT"
] | 48355746/AspNetCore | src/Hosting/Hosting/test/Internal/MyContainer.cs | 1,104 | C# |
using Harmony;
using Multiplayer.Common;
using RimWorld;
using RimWorld.Planet;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using Verse;
namespace Multiplayer.Client
{
public class MultiplayerMapComp : IExposable
{
public static bool tickingFactions;
public Map map;
//public IdBlock mapIdBlock;
public Dictionary<int, FactionMapData> factionMapData = new Dictionary<int, FactionMapData>();
public CaravanFormingSession caravanForming;
public TransporterLoading transporterLoading;
public List<PersistentDialog> mapDialogs = new List<PersistentDialog>();
// for SaveCompression
public List<Thing> tempLoadedThings;
public MultiplayerMapComp(Map map)
{
this.map = map;
}
public void CreateCaravanFormingSession(bool reform, Action onClosed, bool mapAboutToBeRemoved)
{
if (caravanForming != null) return;
caravanForming = new CaravanFormingSession(map, reform, onClosed, mapAboutToBeRemoved);
}
public void CreateTransporterLoadingSession(List<CompTransporter> transporters)
{
if (transporterLoading != null) return;
transporterLoading = new TransporterLoading(map, transporters);
}
public void DoTick()
{
if (Multiplayer.Client == null) return;
tickingFactions = true;
foreach (var data in factionMapData)
{
map.PushFaction(data.Key);
data.Value.listerHaulables.ListerHaulablesTick();
data.Value.resourceCounter.ResourceCounterTick();
map.PopFaction();
}
tickingFactions = false;
}
public void SetFaction(Faction faction)
{
if (!factionMapData.TryGetValue(faction.loadID, out FactionMapData data))
return;
map.designationManager = data.designationManager;
map.areaManager = data.areaManager;
map.zoneManager = data.zoneManager;
map.haulDestinationManager = data.haulDestinationManager;
map.listerHaulables = data.listerHaulables;
map.resourceCounter = data.resourceCounter;
map.listerFilthInHomeArea = data.listerFilthInHomeArea;
}
public void ExposeData()
{
// Data marker
if (Scribe.mode == LoadSaveMode.Saving)
{
bool isPlayerHome = map.IsPlayerHome;
Scribe_Values.Look(ref isPlayerHome, "isPlayerHome", false, true);
}
Scribe_Deep.Look(ref caravanForming, "caravanFormingSession", map);
Scribe_Deep.Look(ref transporterLoading, "transporterLoading", map);
Scribe_Collections.Look(ref mapDialogs, "mapDialogs", LookMode.Deep, map);
if (Scribe.mode == LoadSaveMode.LoadingVars && mapDialogs == null)
mapDialogs = new List<PersistentDialog>();
//Multiplayer.ExposeIdBlock(ref mapIdBlock, "mapIdBlock");
ExposeFactionData();
}
private int currentFactionId;
private void ExposeFactionData()
{
if (Scribe.mode == LoadSaveMode.Saving)
{
int currentFactionId = Faction.OfPlayer.loadID;
ScribeUtil.LookValue(currentFactionId, "currentFactionId");
var data = new Dictionary<int, FactionMapData>(factionMapData);
data.Remove(currentFactionId);
ScribeUtil.LookWithValueKey(ref data, "factionMapData", LookMode.Deep, map);
}
else
{
// The faction whose data is currently set
Scribe_Values.Look(ref currentFactionId, "currentFactionId");
ScribeUtil.LookWithValueKey(ref factionMapData, "factionMapData", LookMode.Deep, map);
if (factionMapData == null)
factionMapData = new Dictionary<int, FactionMapData>();
}
if (Scribe.mode == LoadSaveMode.PostLoadInit)
{
factionMapData[currentFactionId] = FactionMapData.FromMap(map, currentFactionId);
}
}
}
public class FactionMapData : IExposable
{
public Map map;
public int factionId;
// Saved
public DesignationManager designationManager;
public AreaManager areaManager;
public ZoneManager zoneManager;
public HashSet<Thing> claimed = new HashSet<Thing>();
public HashSet<Thing> forbidden = new HashSet<Thing>();
// Not saved
public HaulDestinationManager haulDestinationManager;
public ListerHaulables listerHaulables;
public ResourceCounter resourceCounter;
public ListerFilthInHomeArea listerFilthInHomeArea;
// Loading ctor
public FactionMapData(Map map)
{
this.map = map;
haulDestinationManager = new HaulDestinationManager(map);
listerHaulables = new ListerHaulables(map);
resourceCounter = new ResourceCounter(map);
listerFilthInHomeArea = new ListerFilthInHomeArea(map);
}
private FactionMapData(int factionId, Map map) : this(map)
{
this.factionId = factionId;
designationManager = new DesignationManager(map);
areaManager = new AreaManager(map);
zoneManager = new ZoneManager(map);
}
public void ExposeData()
{
Scribe_Values.Look(ref factionId, "factionId");
Scribe_Deep.Look(ref designationManager, "designationManager", map);
Scribe_Deep.Look(ref areaManager, "areaManager", map);
Scribe_Deep.Look(ref zoneManager, "zoneManager", map);
}
public static FactionMapData New(int factionId, Map map)
{
return new FactionMapData(factionId, map);
}
public static FactionMapData FromMap(Map map, int factionId)
{
return new FactionMapData(map)
{
factionId = factionId,
designationManager = map.designationManager,
areaManager = map.areaManager,
zoneManager = map.zoneManager,
haulDestinationManager = map.haulDestinationManager,
listerHaulables = map.listerHaulables,
resourceCounter = map.resourceCounter,
listerFilthInHomeArea = map.listerFilthInHomeArea,
};
}
}
[HarmonyPatch(typeof(MapDrawer), nameof(MapDrawer.DrawMapMesh))]
static class ForceShowDialogs
{
static void Prefix(MapDrawer __instance)
{
if (Multiplayer.Client == null) return;
var comp = __instance.map.MpComp();
if (comp.mapDialogs.Any())
{
// This makes it so only one of the same type should open
// They're blocking windows
foreach(var a in comp.mapDialogs) {
if (Find.WindowStack.IsOpen(a.GetType())) {
return;
}
}
Find.WindowStack.Add(comp.mapDialogs.First().Dialog);
}
else if (comp.caravanForming != null)
{
if (!Find.WindowStack.IsOpen(typeof(MpFormingCaravanWindow)))
comp.caravanForming.OpenWindow(false);
}
else if (comp.transporterLoading != null)
{
if (!Find.WindowStack.IsOpen(typeof(MpLoadTransportersWindow)))
comp.transporterLoading.OpenWindow(false);
}
else if (Multiplayer.WorldComp.trading.FirstOrDefault(t => t.playerNegotiator.Map == comp.map) is MpTradeSession trading)
{
if (!Find.WindowStack.IsOpen(typeof(TradingWindow)))
Find.WindowStack.Add(new TradingWindow() { selectedTab = Multiplayer.WorldComp.trading.IndexOf(trading) });
}
}
}
}
| 34.621849 | 133 | 0.597087 | [
"MIT"
] | JortonMV/Multiplayer | Source/Client/Comp/MultiplayerMapComp.cs | 8,242 | C# |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.IO;
using JetBrains.Annotations;
using Tauron.Application.Files.Ini.Parser;
namespace Tauron.Application.Files.Ini;
[PublicAPI]
[Serializable]
public record IniFile(ImmutableDictionary<string, IniSection> Sections) : IEnumerable<IniSection>
{
public IniFile()
: this(ImmutableDictionary<string, IniSection>.Empty) { }
public IniSection? this[string name] => Sections.TryGetValue(name, out var section) ? section : null;
public IEnumerator<IniSection> GetEnumerator() => Sections.Values.GetEnumerator();
IEnumerator IEnumerable.GetEnumerator() => GetEnumerator();
public IniFile AddSection(string name)
{
var section = new IniSection(name);
return this with { Sections = Sections.Add(name, section) };
}
public void Save(string path) => new IniWriter(this, new StreamWriter(path)).Write();
public string GetData(string name, string sectionName, string defaultValue)
{
var keyData = this[sectionName]?.GetSingleEntry(name);
if (keyData == null) return string.Empty;
return string.IsNullOrWhiteSpace(keyData.Value) ? defaultValue : keyData.Value;
}
public IniFile SetData(string sectionName, string name, string value)
{
var section = this[sectionName];
if (section != null)
return this with { Sections = Sections.SetItem(sectionName, section with { Entries = section.Entries.SetItem(name, new SingleIniEntry(name, value)) }) };
return this with { Sections = Sections.Add(sectionName, new IniSection(sectionName, ImmutableDictionary<string, IniEntry>.Empty.Add(name, new SingleIniEntry(name, value)))) };
}
public IniFile SetData(string sectionName, string name, IEnumerable<string> value)
{
var section = this[sectionName];
if (section != null)
return this with { Sections = Sections.SetItem(sectionName, section with { Entries = section.Entries.SetItem(name, new ListIniEntry(name, value)) }) };
return this with { Sections = Sections.Add(sectionName, new IniSection(sectionName, ImmutableDictionary<string, IniEntry>.Empty.Add(name, new ListIniEntry(name, value)))) };
}
#region Content Load
public static IniFile Parse(TextReader reader)
{
using (reader)
{
return new IniParser(reader).Parse();
}
}
public static IniFile ParseContent(string content) => Parse(new StringReader(content));
public static IniFile ParseFile(string path) => Parse(new StreamReader(path));
public static IniFile ParseStream(Stream stream) => Parse(new StreamReader(stream));
#endregion
} | 34.6 | 183 | 0.701951 | [
"MIT"
] | Tauron1990/Project-Manager-Akka | Src/Shared/Tauron.Application.Files/Ini/IniFile.cs | 2,770 | C# |
//******************************************************************************************************
// Program.cs - Gbtc
//
// Copyright © 2015, Grid Protection Alliance. All Rights Reserved.
//
// Licensed to the Grid Protection Alliance (GPA) under one or more contributor license agreements. See
// the NOTICE file distributed with this work for additional information regarding copyright ownership.
// The GPA licenses this file to you under the Eclipse Public License -v 1.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.opensource.org/licenses/eclipse-1.0.php
//
// Unless agreed to in writing, the subject software distributed under the License is distributed on an
// "AS-IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. Refer to the
// License for the specific language governing permissions and limitations.
//
// Code Modification History:
// ----------------------------------------------------------------------------------------------------
// 09/02/2010 - J. Ritchie Carroll
// Generated original version of source code.
//
//******************************************************************************************************
using System;
using System.ServiceProcess;
using System.Windows.Forms;
using GSF.Console;
using GSF.TimeSeries;
namespace PTPSync
{
static class Program
{
/// <summary>
/// The main entry point for the application.
/// </summary>
static void Main()
{
ServiceHost host = new ServiceHost();
bool runAsService;
bool runAsApplication;
Arguments args = new Arguments(Environment.CommandLine, true);
if (args.Count > 1)
{
MessageBox.Show("Too many arguments. If specified, argument must be one of: -RunAsService, -RunAsApplication or -RunAsConsole.");
Environment.Exit(1);
}
if (args.Count == 0)
{
#if DEBUG
runAsService = false;
runAsApplication = true;
#else
runAsService = true;
runAsApplication = false;
#endif
}
else
{
runAsService = args.Exists("RunAsService");
runAsApplication = args.Exists("RunAsApplication");
if (!runAsService && !runAsApplication && !args.Exists("RunAsConsole"))
{
MessageBox.Show("Invalid argument. If specified, argument must be one of: -RunAsService, -RunAsApplication or -RunAsConsole.");
Environment.Exit(1);
}
}
if (runAsService)
{
// Run as Windows Service.
ServiceBase.Run(new ServiceBase[] { host });
}
else if (runAsApplication)
{
// Run as Windows Application.
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new DebugHost(host));
}
else
{
ConsoleHost consoleHost = new ConsoleHost(host);
consoleHost.Run();
Environment.Exit(0);
}
}
}
} | 36.425532 | 147 | 0.528914 | [
"MIT"
] | GridProtectionAlliance/PTPSync | Source/Applications/PTPSync/PTPSync/Program.cs | 3,427 | 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: global::Xamarin.Forms.Xaml.XamlResourceIdAttribute("HyperLove.ViewModel.Preferences.Premium.Exercise.xaml", "ViewModel/Preferences/Premium/Exercise.xaml", typeof(global::HyperLove.ViewModel.Preferences.Premium.Exercise))]
namespace HyperLove.ViewModel.Preferences.Premium {
[global::Xamarin.Forms.Xaml.XamlFilePathAttribute("ViewModel\\Preferences\\Premium\\Exercise.xaml")]
public partial class Exercise : global::HyperLove.ViewModel.ModalPage {
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("Xamarin.Forms.Build.Tasks.XamlG", "2.0.0.0")]
private global::Xamarin.Forms.StackLayout ui_pop_modal;
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("Xamarin.Forms.Build.Tasks.XamlG", "2.0.0.0")]
private global::Xamarin.Forms.Label ui_pop_title;
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("Xamarin.Forms.Build.Tasks.XamlG", "2.0.0.0")]
private void InitializeComponent() {
global::Xamarin.Forms.Xaml.Extensions.LoadFromXaml(this, typeof(Exercise));
ui_pop_modal = global::Xamarin.Forms.NameScopeExtensions.FindByName<global::Xamarin.Forms.StackLayout>(this, "ui_pop_modal");
ui_pop_title = global::Xamarin.Forms.NameScopeExtensions.FindByName<global::Xamarin.Forms.Label>(this, "ui_pop_title");
}
}
}
| 53.848485 | 232 | 0.653911 | [
"MIT"
] | Boowman/HyperLove | HyperLove/obj/Debug/netstandard2.0/ViewModel/Preferences/Premium/Exercise.xaml.g.cs | 1,777 | C# |
using System.Windows.Controls;
namespace GClient.Module.Connection.Views
{
public partial class ArchiveView : UserControl
{
public ArchiveView()
{
InitializeComponent();
}
}
} | 18.666667 | 50 | 0.620536 | [
"MIT"
] | tnunnink/GMerge | src/GClient.Module.Connection/Views/ArchiveView.xaml.cs | 224 | C# |
// Licensed to Elasticsearch B.V under one or more agreements.
// Elasticsearch B.V licenses this file to you under the Apache 2.0 License.
// See the LICENSE file in the project root for more information
using System;
using System.Linq;
using FluentAssertions;
using Nest;
using Tests.Core.Extensions;
using Tests.Core.ManagedElasticsearch.Clusters;
using Tests.Domain;
using Tests.Framework.EndpointTests.TestState;
using static Nest.Infer;
namespace Tests.Aggregations.Bucket.GeoTileGrid
{
public class GeoTileGridAggregationUsageTests : AggregationUsageTestBase<ReadOnlyCluster>
{
public GeoTileGridAggregationUsageTests(ReadOnlyCluster i, EndpointUsage usage) : base(i, usage) { }
protected override object AggregationJson => new
{
my_geotile = new
{
geotile_grid = new
{
field = "locationPoint",
precision = 3,
size = 1000,
shard_size = 100
}
}
};
protected override Func<AggregationContainerDescriptor<Project>, IAggregationContainer> FluentAggs => a => a
.GeoTile("my_geotile", g => g
.Field(p => p.LocationPoint)
.Precision(GeoTilePrecision.Precision3)
.Size(1000)
.ShardSize(100)
);
protected override AggregationDictionary InitializerAggs =>
new GeoTileGridAggregation("my_geotile")
{
Field = Field<Project>(p => p.LocationPoint),
Precision = GeoTilePrecision.Precision3,
Size = 1000,
ShardSize = 100
};
protected override void ExpectResponse(ISearchResponse<Project> response)
{
response.ShouldBeValid();
var myGeoTileGrid = response.Aggregations.GeoTile("my_geotile");
myGeoTileGrid.Should().NotBeNull();
var firstBucket = myGeoTileGrid.Buckets.First();
firstBucket.Key.Should().NotBeNullOrWhiteSpace();
firstBucket.DocCount.Should().BeGreaterThan(0);
}
}
}
| 28.634921 | 110 | 0.736696 | [
"Apache-2.0"
] | Jiasyuan/elasticsearch-net | tests/Tests/Aggregations/Bucket/GeoTileGrid/GeoTileGridAggregationUsageTests.cs | 1,804 | C# |
using System.Collections.Generic;
using AutoMapper;
using FluentAssertions;
using Microsoft.Extensions.Logging;
using NSubstitute;
using Sfa.Tl.Matching.Application.Interfaces;
using Sfa.Tl.Matching.Application.Mappers;
using Sfa.Tl.Matching.Application.Services;
using Sfa.Tl.Matching.Application.UnitTests.Services.RoutePath.Builders;
using Sfa.Tl.Matching.Data.Interfaces;
using Sfa.Tl.Matching.Data.Repositories;
using Sfa.Tl.Matching.Domain.Models;
using Sfa.Tl.Matching.Tests.Common;
using Xunit;
namespace Sfa.Tl.Matching.Application.UnitTests.Services.RoutePath
{
public class When_RoutePathService_Is_Called_To_Get_Route_Ids
{
private readonly IList<int> _result;
public When_RoutePathService_Is_Called_To_Get_Route_Ids()
{
var logger = Substitute.For<ILogger<GenericRepository<Route>>>();
var config = new MapperConfiguration(c =>
{
c.AddMaps(typeof(RouteMapper).Assembly);
});
var mapper = new Mapper(config);
using var dbContext = InMemoryDbContext.Create();
dbContext.AddRange(new ValidRouteListBuilder().Build());
dbContext.SaveChanges();
IRepository<Route> routeRepository = new GenericRepository<Route>(logger, dbContext);
IRoutePathService service = new RoutePathService(mapper, routeRepository);
_result = service.GetRouteIdsAsync().GetAwaiter().GetResult();
}
[Fact]
public void Then_The_Expected_Number_Of_Items_Is_Returned()
{
Assert.Equal(2, _result.Count);
}
[Fact]
public void Then_The_Expected_Ids_Are_Returned()
{
_result[0].Should().Be(1);
_result[1].Should().Be(2);
}
}
}
| 31.614035 | 97 | 0.676471 | [
"MIT"
] | SkillsFundingAgency/tl-matching | src/Sfa.Tl.Matching.Application.UnitTests/Services/RoutePath/When_RoutePathService_Is_Called_To_Get_Route_Ids.cs | 1,804 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Atc.Rest.ApiGenerator.Models;
using Atc.Rest.ApiGenerator.SyntaxGenerators.Api;
using Atc.Rest.ApiGenerator.SyntaxGenerators.Api.Interfaces;
using Atc.Rest.ApiGenerator.Tests.XUnitTestTypes.CodeGenerator;
using Microsoft.OpenApi.Models;
using VerifyXunit;
using Xunit;
namespace Atc.Rest.ApiGenerator.Tests.SyntaxGenerators.Api
{
[UsesVerify]
public class SyntaxGeneratorContractModelsTests : SyntaxGeneratorContractModelsTestBase
{
public static IEnumerable<object[]> TestInput { get; } = AllTestInput
.Where(x => x.TestDirectory.Contains("ContractMultiModels", StringComparison.Ordinal))
.Select(x => new object[] { x });
protected override ISyntaxGeneratorContractModels CreateGenerator(ApiProjectOptions apiProject)
{
// Verify spec file supported for unit test
Assert.True(apiProject.Document.Components.Schemas.Count > 0);
// Construct SUT
var apiOperationSchemaMaps = apiProject.Document.Components.Schemas
.Select(schema => new ApiOperationSchemaMap(schema.Key, SchemaMapLocatedAreaType.Response, FocusOnSegment, OperationType.Get, parentSchemaKey: null))
.ToList();
return new SyntaxGeneratorContractModels(apiProject, apiOperationSchemaMaps, FocusOnSegment);
}
[Theory(DisplayName = "Api Contract Model")]
[MemberData(nameof(TestInput))]
public Task ExecuteGeneratorTest(GeneratorTestInput input)
{
return VerifyGeneratedOutput(input);
}
}
} | 39.880952 | 165 | 0.718806 | [
"MIT"
] | atc-net/atc-rest-api-generator | test/Atc.Rest.ApiGenerator.Tests/SyntaxGenerators/Api/SyntaxGeneratorContractModelsTests.cs | 1,675 | C# |
using Microsoft.Bot.Builder.Adapters.Twilio;
using Microsoft.Bot.Builder.TraceExtensions;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Logging;
namespace AppointmentBot
{
public class TwilioAdapterWithErrorHandler : TwilioAdapter
{
public TwilioAdapterWithErrorHandler(IConfiguration configuration, ILogger<TwilioAdapter> logger)
: base(configuration, null, logger)
{
OnTurnError = async (turnContext, exception) =>
{
// Log any leaked exception from the application.
logger.LogError(exception, $"[OnTurnError] unhandled error : {exception.Message}");
// Send a message to the user
await turnContext.SendActivityAsync("The bot encountered an error or bug.");
await turnContext.SendActivityAsync("To continue to run this bot, please fix the bot source code.");
// Send a trace activity, which will be displayed in the Bot Framework Emulator
await turnContext.TraceActivityAsync("OnTurnError Trace", exception.Message, "https://www.botframework.com/schemas/error", "TurnError");
};
}
}
} | 45.185185 | 152 | 0.664754 | [
"MIT"
] | aurlaw/AzureBotDemo | AppointmentBot/TwilioAdapterWithErrorHandler.cs | 1,220 | C# |
namespace Factorio.ServerManager.Manager
{
using System.Diagnostics;
using System.Threading.Tasks;
using Microsoft.AspNetCore.SignalR;
public class ServerManager
{
private readonly IHubContext<ServerManagerHub> hubContext;
private Process p;
public ServerManager(IHubContext<ServerManagerHub> hubContext)
{
this.hubContext = hubContext;
}
public ServerStatus Status { get; private set; }
public string RecentOutput { get; private set; }
private Task ChangeStatus(ServerStatus newStatus)
{
var oldStatus = this.Status;
this.Status = newStatus;
return this.hubContext.Clients.All.SendAsync("server", new ServerNotification<StatusPayload>
{
NotificationType = NotificationType.StatusChange,
Payload = new StatusPayload
{
OldStatus = oldStatus,
NewStatus = newStatus
}
});
}
public async Task Start()
{
//var p = new Process
//{
// StartInfo = new ProcessStartInfo()
//};
await this.ChangeStatus(ServerStatus.Started);
}
public async Task Stop()
{
await this.ChangeStatus(ServerStatus.Stopped);
}
}
} | 27.588235 | 104 | 0.560057 | [
"MIT"
] | BWalti/dotnet-factorio-server-manager | Factorio.ServerManager/Factorio.ServerManager/Manager/ServerManager.cs | 1,407 | C# |
/*
* QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals.
* Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect Corporation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
using System;
using System.Collections.Generic;
using NodaTime;
using QuantConnect.Data;
using QuantConnect.Data.Market;
using QuantConnect.Data.UniverseSelection;
using QuantConnect.Interfaces;
using QuantConnect.Lean.Engine.DataFeeds;
using QuantConnect.Lean.Engine.DataFeeds.Enumerators;
using QuantConnect.Lean.Engine.DataFeeds.Enumerators.Factories;
using QuantConnect.Securities;
using QuantConnect.Util;
using HistoryRequest = QuantConnect.Data.HistoryRequest;
namespace QuantConnect.Lean.Engine.HistoricalData
{
/// <summary>
/// Provides an implementation of <see cref="IHistoryProvider"/> that uses <see cref="BaseData"/>
/// instances to retrieve historical data
/// </summary>
public class SubscriptionDataReaderHistoryProvider : SynchronizingHistoryProvider
{
private IDataProvider _dataProvider;
private IMapFileProvider _mapFileProvider;
private IFactorFileProvider _factorFileProvider;
private IDataCacheProvider _dataCacheProvider;
private bool _parallelHistoryRequestsEnabled;
private bool _initialized;
/// <summary>
/// Manager used to allow or deny access to a requested datasource for specific users
/// </summary>
protected IDataPermissionManager DataPermissionManager;
/// <summary>
/// Initializes this history provider to work for the specified job
/// </summary>
/// <param name="parameters">The initialization parameters</param>
public override void Initialize(HistoryProviderInitializeParameters parameters)
{
if (_initialized)
{
// let's make sure no one tries to change our parameters values
throw new InvalidOperationException("SubscriptionDataReaderHistoryProvider can only be initialized once");
}
_initialized = true;
_dataProvider = parameters.DataProvider;
_mapFileProvider = parameters.MapFileProvider;
_dataCacheProvider = parameters.DataCacheProvider;
_factorFileProvider = parameters.FactorFileProvider;
DataPermissionManager = parameters.DataPermissionManager;
_parallelHistoryRequestsEnabled = parameters.ParallelHistoryRequestsEnabled;
}
/// <summary>
/// Gets the history for the requested securities
/// </summary>
/// <param name="requests">The historical data requests</param>
/// <param name="sliceTimeZone">The time zone used when time stamping the slice instances</param>
/// <returns>An enumerable of the slices of data covering the span specified in each request</returns>
public override IEnumerable<Slice> GetHistory(IEnumerable<HistoryRequest> requests, DateTimeZone sliceTimeZone)
{
// create subscription objects from the configs
var subscriptions = new List<Subscription>();
foreach (var request in requests)
{
var subscription = CreateSubscription(request, request.StartTimeUtc, request.EndTimeUtc);
subscriptions.Add(subscription);
}
return CreateSliceEnumerableFromSubscriptions(subscriptions, sliceTimeZone);
}
/// <summary>
/// Creates a subscription to process the request
/// </summary>
private Subscription CreateSubscription(HistoryRequest request, DateTime startUtc, DateTime endUtc)
{
// data reader expects these values in local times
var startTimeLocal = startUtc.ConvertFromUtc(request.ExchangeHours.TimeZone);
var endTimeLocal = endUtc.ConvertFromUtc(request.ExchangeHours.TimeZone);
var config = request.ToSubscriptionDataConfig();
DataPermissionManager.AssertConfiguration(config, startTimeLocal, endTimeLocal);
var security = new Security(
request.ExchangeHours,
config,
new Cash(Currencies.NullCurrency, 0, 1m),
SymbolProperties.GetDefault(Currencies.NullCurrency),
ErrorCurrencyConverter.Instance,
RegisteredSecurityDataTypesProvider.Null,
new SecurityCache()
);
// Tradable dates are defined with the data time zone to access the right source
var tradableDates = Time.EachTradeableDayInTimeZone(request.ExchangeHours, startTimeLocal, endTimeLocal, request.DataTimeZone, request.IncludeExtendedMarketHours);
var dataReader = new SubscriptionDataReader(config,
startTimeLocal,
endTimeLocal,
_mapFileProvider,
_factorFileProvider,
tradableDates,
false,
_dataCacheProvider,
_dataProvider
);
dataReader.InvalidConfigurationDetected += (sender, args) => { OnInvalidConfigurationDetected(args); };
dataReader.NumericalPrecisionLimited += (sender, args) => { OnNumericalPrecisionLimited(args); };
dataReader.StartDateLimited += (sender, args) => { OnStartDateLimited(args); };
dataReader.DownloadFailed += (sender, args) => { OnDownloadFailed(args); };
dataReader.ReaderErrorDetected += (sender, args) => { OnReaderErrorDetected(args); };
IEnumerator<BaseData> reader = dataReader;
var intraday = GetIntradayDataEnumerator(dataReader, request);
if (intraday != null)
{
// we optionally concatenate the intraday data enumerator
reader = new ConcatEnumerator(true, reader, intraday);
}
reader = CorporateEventEnumeratorFactory.CreateEnumerators(
reader,
config,
_factorFileProvider,
dataReader,
_mapFileProvider,
startTimeLocal);
// optionally apply fill forward behavior
if (request.FillForwardResolution.HasValue)
{
// copy forward Bid/Ask bars for QuoteBars
if (request.DataType == typeof(QuoteBar))
{
reader = new QuoteBarFillForwardEnumerator(reader);
}
var readOnlyRef = Ref.CreateReadOnly(() => request.FillForwardResolution.Value.ToTimeSpan());
reader = new FillForwardEnumerator(reader, security.Exchange, readOnlyRef, request.IncludeExtendedMarketHours, endTimeLocal, config.Increment, config.DataTimeZone);
}
// since the SubscriptionDataReader performs an any overlap condition on the trade bar's entire
// range (time->end time) we can end up passing the incorrect data (too far past, possibly future),
// so to combat this we deliberately filter the results from the data reader to fix these cases
// which only apply to non-tick data
reader = new SubscriptionFilterEnumerator(reader, security, endTimeLocal, config.ExtendedMarketHours, false, request.ExchangeHours);
reader = new FilterEnumerator<BaseData>(reader, data =>
{
// allow all ticks
if (config.Resolution == Resolution.Tick) return true;
// filter out all aux data
if (data.DataType == MarketDataType.Auxiliary) return false;
// filter out future data
if (data.EndTime > endTimeLocal) return false;
// filter out data before the start
return data.EndTime > startTimeLocal;
});
var subscriptionRequest = new SubscriptionRequest(false, null, security, config, request.StartTimeUtc, request.EndTimeUtc);
if (_parallelHistoryRequestsEnabled)
{
return SubscriptionUtils.CreateAndScheduleWorker(subscriptionRequest, reader, _factorFileProvider, false);
}
return SubscriptionUtils.Create(subscriptionRequest, reader);
}
/// <summary>
/// Gets the intraday data enumerator if any
/// </summary>
protected virtual IEnumerator<BaseData> GetIntradayDataEnumerator(IEnumerator<BaseData> rawData, HistoryRequest request)
{
return null;
}
}
}
| 46.676923 | 180 | 0.65535 | [
"Apache-2.0"
] | BlackBoxAM/Lean | Engine/HistoricalData/SubscriptionDataReaderHistoryProvider.cs | 9,102 | C# |
namespace Atlas.Roleplay.Client.Interface
{
public enum MenuOperationType
{
Select,
Update,
SliderUpdate,
Close,
PostClose
}
} | 16.181818 | 41 | 0.573034 | [
"MIT"
] | Local9/Atlas | Atlas.Roleplay.Client/Interface/MenuOperationType.cs | 178 | C# |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Windows;
using System.Windows.Controls;
namespace System.Windows.Automation.Peers
{
///
public class Viewport3DAutomationPeer : FrameworkElementAutomationPeer
{
///
public Viewport3DAutomationPeer(Viewport3D owner)
: base(owner)
{ }
///
override protected string GetClassNameCore()
{
return "Viewport3D";
}
///
override protected AutomationControlType GetAutomationControlTypeCore()
{
return AutomationControlType.Custom;
}
}
}
| 25.09375 | 79 | 0.648817 | [
"MIT"
] | 00mjk/wpf | src/Microsoft.DotNet.Wpf/src/PresentationFramework/System/Windows/Automation/Peers/Viewport3DAutomationPeer.cs | 803 | C# |
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using ArchaicQuestII.GameLogic.Character;
using ArchaicQuestII.GameLogic.Character.Class;
using ArchaicQuestII.GameLogic.Character.Emote;
using ArchaicQuestII.GameLogic.Character.Help;
using ArchaicQuestII.GameLogic.Character.Model;
using ArchaicQuestII.GameLogic.Crafting;
using ArchaicQuestII.GameLogic.World.Room;
namespace ArchaicQuestII.GameLogic.Core
{
public interface ICache
{
/// <summary>
/// Add player to cache
/// </summary>
/// <returns>returns player Cache</returns>
bool AddPlayer(string id, Player player);
Player GetPlayer(string id);
Player RemovePlayer(string id);
ConcurrentDictionary<string, Player> GetPlayerCache();
Player PlayerAlreadyExists(Guid id);
bool AddRoom(string id, Room room);
bool AddOriginalRoom(string id, Room room);
List<Room> GetAllRoomsToRepop();
List<Room> GetOriginalRooms();
List<Room> GetAllRoomsInArea(int id);
List<Room> GetAllRooms();
Room GetRoom(string id);
Room GetOriginalRoom(string id);
bool UpdateRoom(string id, Room room, Player player);
bool AddSkill(int id, Skill.Model.Skill skill);
Skill.Model.Skill GetSkill(int id);
void ClearRoomCache();
void SetConfig(Config config);
Config GetConfig();
/// <summary>
/// areaId + Zindex
/// </summary>
/// <param name="areaId"></param>
/// <param name="room"></param>
void AddMap(string areaId, string room);
/// <summary>
/// Area Id + Z coord
/// </summary>
/// <param name="areaId"></param>
/// <returns></returns>
string GetMap(string areaId);
bool IsCharInCombat(string id);
bool AddCharToCombat(string id, Player character);
Player GetCharFromCombat(string id);
Player RemoveCharFromCombat(string id);
List<Player> GetCombatList();
/// <summary>
/// Experiment, Need to generate the commands list on start up
/// So things like socials & skills can work dynamically without
/// needing to change the backend code
/// </summary>
/// <returns></returns>
Dictionary<string, Action> GetCommands();
void AddCommand(string key, Action action);
public void AddSocial(string key, Emote emote);
public Dictionary<string, Emote> GetSocials();
bool AddQuest(int id, Quest quest);
Quest GetQuest(int id);
ConcurrentDictionary<int, Quest> GetQuestCache();
public bool AddHelp(int id, Help help);
public Help GetHelp(int id);
public List<Help> FindHelp(string id);
public bool AddCraftingRecipes(int id, CraftingRecipes CraftingRecipes);
public CraftingRecipes GetCraftingRecipes(int id, CraftingRecipes recipe);
public List<CraftingRecipes> GetCraftingRecipes();
public bool AddClass(string id, Class pcClass);
public Class GetClass(string id);
}
} | 33.817204 | 82 | 0.647695 | [
"MIT"
] | ArchaicQuest/ArchaicQuest-II | ArchaicQuestII.GameLogic/Core/ICache.cs | 3,147 | C# |
// GZipStream.cs
// ------------------------------------------------------------------
//
// Copyright (c) 2009 Dino Chiesa and Microsoft Corporation.
// All rights reserved.
//
// This code module is part of DotNetZip, a zipfile class library.
//
// ------------------------------------------------------------------
//
// This code is licensed under the Microsoft Public License.
// See the file License.txt for the license details.
// More info on: http://dotnetzip.codeplex.com
//
// ------------------------------------------------------------------
//
// last saved (in emacs):
// Time-stamp: <2009-August-12 15:35:30>
//
// ------------------------------------------------------------------
//
// This module defines the GZipStream class, which can be used as a replacement for
// the System.IO.Compression.GZipStream class in the .NET BCL. NB: The design is not
// completely OO clean: there is some intelligence in the ZlibBaseStream that reads the
// GZip header.
//
// ------------------------------------------------------------------
#if WINDOWS_PHONE
using System;
using System.IO;
namespace RestSharp.Compression.ZLib
{
/// <summary>
/// A class for compressing and decompressing GZIP streams.
/// </summary>
/// <remarks>
///
/// <para>
/// The GZipStream is a <see
/// href="http://en.wikipedia.org/wiki/Decorator_pattern">Decorator</see> on a <see
/// cref="Stream"/>. It adds GZIP compression or decompression to any stream.
/// </para>
///
/// <para> Like the <c>Compression.GZipStream</c> in the .NET Base
/// Class Library, the Ionic.Zlib.GZipStream can compress while writing, or decompress
/// while reading, but not vice versa. The compression method used is GZIP, which is
/// documented in <see href="http://www.ietf.org/rfc/rfc1952.txt">IETF RFC 1952</see>,
/// "GZIP file format specification version 4.3".</para>
///
/// <para> A GZipStream can be used to decompress data (through Read()) or to compress
/// data (through Write()), but not both. </para>
///
/// <para> If you wish to use the GZipStream to compress data, you must wrap it around a
/// write-able stream. As you call Write() on the GZipStream, the data will be
/// compressed into the GZIP format. If you want to decompress data, you must wrap the
/// GZipStream around a readable stream that contains an IETF RFC 1952-compliant stream.
/// The data will be decompressed as you call Read() on the GZipStream. </para>
///
/// <para> Though the GZIP format allows data from multiple files to be concatenated
/// together, this stream handles only a single segment of GZIP format, typically
/// representing a single file. </para>
///
/// <para>
/// This class is similar to <see cref="ZlibStream"/> and <see cref="DeflateStream"/>.
/// <c>ZlibStream</c> handles RFC1950-compliant streams. <see cref="DeflateStream"/>
/// handles RFC1951-compliant streams. This class handles RFC1952-compliant streams.
/// </para>
///
/// </remarks>
///
/// <seealso cref="DeflateStream" />
/// <seealso cref="ZlibStream" />
internal class GZipStream : System.IO.Stream
{
// GZip format
// source: http://tools.ietf.org/html/rfc1952
//
// header id: 2 bytes 1F 8B
// compress method 1 byte 8= DEFLATE (none other supported)
// flag 1 byte bitfield (See below)
// mtime 4 bytes time_t (seconds since jan 1, 1970 UTC of the file.
// xflg 1 byte 2 = max compress used , 4 = max speed (can be ignored)
// OS 1 byte OS for originating archive. set to 0xFF in compression.
// extra field length 2 bytes optional - only if FEXTRA is set.
// extra field varies
// filename varies optional - if FNAME is set. zero terminated. ISO-8859-1.
// file comment varies optional - if FCOMMENT is set. zero terminated. ISO-8859-1.
// crc16 1 byte optional - present only if FHCRC bit is set
// compressed data varies
// CRC32 4 bytes
// isize 4 bytes data size modulo 2^32
//
// FLG (FLaGs)
// bit 0 FTEXT - indicates file is ASCII text (can be safely ignored)
// bit 1 FHCRC - there is a CRC16 for the header immediately following the header
// bit 2 FEXTRA - extra fields are present
// bit 3 FNAME - the zero-terminated filename is present. encoding; ISO-8859-1.
// bit 4 FCOMMENT - a zero-terminated file comment is present. encoding: ISO-8859-1
// bit 5 reserved
// bit 6 reserved
// bit 7 reserved
//
// On consumption:
// Extra field is a bunch of nonsense and can be safely ignored.
// Header CRC and OS, likewise.
//
// on generation:
// all optional fields get 0, except for the OS, which gets 255.
//
/// <summary>
/// The Comment on the GZIP stream.
/// </summary>
/// <remarks>
/// <para>
/// The GZIP format allows for each file to optionally have an associated comment stored with the
/// file. The comment is encoded with the ISO-8859-1 code page. To include a comment in
/// a GZIP stream you create, set this property before calling Write() for the first time
/// on the GZipStream.
/// </para>
///
/// <para>
/// When using GZipStream to decompress, you can retrieve this property after the first
/// call to Read(). If no comment has been set in the GZIP bytestream, the Comment
/// property will return null (Nothing in VB).
/// </para>
/// </remarks>
public String Comment
{
get { return _Comment; }
set
{
if (_disposed)
throw new ObjectDisposedException("GZipStream");
_Comment = value;
}
}
/// <summary>
/// The FileName for the GZIP stream.
/// </summary>
/// <remarks>
/// <para>
/// The GZIP format optionally allows each file to have an associated filename. When
/// compressing data (through Write()), set this FileName before calling Write() the first
/// time on the GZipStream. The actual filename is encoded into the GZIP bytestream with
/// the ISO-8859-1 code page, according to RFC 1952. It is the application's responsibility to
/// insure that the FileName can be encoded and decoded correctly with this code page.
/// </para>
/// <para>
/// When decompressing (through Read()), you can retrieve this value any time after the
/// first Read(). In the case where there was no filename encoded into the GZIP
/// bytestream, the property will return null (Nothing in VB).
/// </para>
/// </remarks>
public String FileName
{
get { return _FileName; }
set
{
if (_disposed)
throw new ObjectDisposedException("GZipStream");
_FileName = value;
if (_FileName == null)
return;
if (_FileName.IndexOf("/") != -1)
{
_FileName = _FileName.Replace("/", "\\");
}
if (_FileName.EndsWith("\\"))
throw new Exception("Illegal filename");
if (_FileName.IndexOf("\\") != -1)
{
// trim any leading path
_FileName = Path.GetFileName(_FileName);
}
}
}
/// <summary>
/// The last modified time for the GZIP stream.
/// </summary>
///
/// <remarks> GZIP allows the storage of a last modified time with each GZIP entry.
/// When compressing data, you can set this before the first call to Write(). When
/// decompressing, you can retrieve this value any time after the first call to
/// Read(). </remarks>
public DateTime? LastModified;
/// <summary>
/// The CRC on the GZIP stream.
/// </summary>
/// <remarks>
/// This is used for internal error checking. You probably don't need to look at this property.
/// </remarks>
public int Crc32 { get { return _Crc32; } }
internal ZlibBaseStream _baseStream;
bool _disposed;
bool _firstReadDone;
string _FileName;
string _Comment;
int _Crc32;
/// <summary>
/// Create a GZipStream using the specified CompressionMode and the specified CompressionLevel,
/// and explicitly specify whether the stream should be left open after Deflation or Inflation.
/// </summary>
/// <remarks>
/// <para>
/// This constructor allows the application to request that the captive stream remain open after
/// the deflation or inflation occurs. By default, after Close() is called on the stream, the
/// captive stream is also closed. In some cases this is not desired, for example if the stream
/// is a memory stream that will be re-read after compressed data has been written to it. Specify true for the
/// leaveOpen parameter to leave the stream open.
/// </para>
/// <para>
/// As noted in the class documentation,
/// the CompressionMode (Compress or Decompress) also establishes the "direction" of the stream.
/// A GZipStream with CompressionMode.Compress works only through Write(). A GZipStream with
/// CompressionMode.Decompress works only through Read().
/// </para>
/// </remarks>
/// <example>
/// This example shows how to use a DeflateStream to compress data.
/// <code>
/// using (System.IO.Stream input = System.IO.File.OpenRead(fileToCompress))
/// {
/// using (var raw = System.IO.File.Create(outputFile))
/// {
/// using (Stream compressor = new GZipStream(raw, CompressionMode.Compress, CompressionLevel.BestCompression, true))
/// {
/// byte[] buffer = new byte[WORKING_BUFFER_SIZE];
/// int n;
/// while ((n= input.Read(buffer, 0, buffer.Length)) != 0)
/// {
/// compressor.Write(buffer, 0, n);
/// }
/// }
/// }
/// }
/// </code>
/// <code lang="VB">
/// Dim outputFile As String = (fileToCompress & ".compressed")
/// Using input As Stream = File.OpenRead(fileToCompress)
/// Using raw As FileStream = File.Create(outputFile)
/// Using compressor As Stream = New GZipStream(raw, CompressionMode.Compress, CompressionLevel.BestCompression, True)
/// Dim buffer As Byte() = New Byte(4096) {}
/// Dim n As Integer = -1
/// Do While (n <> 0)
/// If (n > 0) Then
/// compressor.Write(buffer, 0, n)
/// End If
/// n = input.Read(buffer, 0, buffer.Length)
/// Loop
/// End Using
/// End Using
/// End Using
/// </code>
/// </example>
/// <param name="stream">The stream which will be read or written.</param>
/// <param name="mode">Indicates whether the GZipStream will compress or decompress.</param>
/// <param name="leaveOpen">true if the application would like the stream to remain open after inflation/deflation.</param>
/// <param name="level">A tuning knob to trade speed for effectiveness.</param>
public GZipStream(Stream stream)
{
_baseStream = new ZlibBaseStream(stream, ZlibStreamFlavor.GZIP, false);
}
#region Zlib properties
/// <summary>
/// This property sets the flush behavior on the stream.
/// </summary>
virtual public FlushType FlushMode
{
get { return (this._baseStream._flushMode); }
set
{
if (_disposed) throw new ObjectDisposedException("GZipStream");
this._baseStream._flushMode = value;
}
}
/// <summary>
/// The size of the working buffer for the compression codec.
/// </summary>
///
/// <remarks>
/// <para>
/// The working buffer is used for all stream operations. The default size is 1024 bytes.
/// The minimum size is 128 bytes. You may get better performance with a larger buffer.
/// Then again, you might not. You would have to test it.
/// </para>
///
/// <para>
/// Set this before the first call to Read() or Write() on the stream. If you try to set it
/// afterwards, it will throw.
/// </para>
/// </remarks>
public int BufferSize
{
get { return this._baseStream._bufferSize; }
set
{
if (_disposed)
throw new ObjectDisposedException("GZipStream");
if (this._baseStream._workingBuffer != null)
throw new ZlibException("The working buffer is already set.");
if (value < ZlibConstants.WorkingBufferSizeMin)
throw new ZlibException(String.Format("Don't be silly. {0} bytes?? Use a bigger buffer.", value));
this._baseStream._bufferSize = value;
}
}
/// <summary> Returns the total number of bytes input so far.</summary>
virtual public long TotalIn
{
get { return this._baseStream._z.TotalBytesIn; }
}
/// <summary> Returns the total number of bytes output so far.</summary>
virtual public long TotalOut
{
get { return this._baseStream._z.TotalBytesOut; }
}
#endregion
#region Stream methods
/// <summary>
/// Dispose the stream.
/// </summary>
/// <remarks>
/// This may or may not result in a Close() call on the captive stream.
/// See the ctor's with leaveOpen parameters for more information.
/// </remarks>
protected override void Dispose(bool disposing)
{
try
{
if (!_disposed)
{
if (disposing && (this._baseStream != null))
{
this._baseStream.Close();
this._Crc32 = _baseStream.Crc32;
}
_disposed = true;
}
}
finally
{
base.Dispose(disposing);
}
}
/// <summary>
/// Indicates whether the stream can be read.
/// </summary>
/// <remarks>
/// The return value depends on whether the captive stream supports reading.
/// </remarks>
public override bool CanRead
{
get
{
if (_disposed)
throw new ObjectDisposedException("GZipStream");
return _baseStream._stream.CanRead;
}
}
/// <summary>
/// Indicates whether the stream supports Seek operations.
/// </summary>
/// <remarks>
/// Always returns false.
/// </remarks>
public override bool CanSeek
{
get { return false; }
}
/// <summary>
/// Indicates whether the stream can be written.
/// </summary>
/// <remarks>
/// The return value depends on whether the captive stream supports writing.
/// </remarks>
public override bool CanWrite
{
get
{
if (_disposed)
throw new ObjectDisposedException("GZipStream");
return _baseStream._stream.CanWrite;
}
}
/// <summary>
/// Flush the stream.
/// </summary>
public override void Flush()
{
if (_disposed)
throw new ObjectDisposedException("GZipStream");
_baseStream.Flush();
}
/// <summary>
/// Reading this property always throws a NotImplementedException.
/// </summary>
public override long Length
{
get { throw new NotImplementedException(); }
}
/// <summary>
/// The position of the stream pointer.
/// </summary>
/// <remarks>
/// Writing this property always throws a NotImplementedException. Reading will
/// return the total bytes written out, if used in writing, or the total bytes
/// read in, if used in reading. The count may refer to compressed bytes or
/// uncompressed bytes, depending on how you've used the stream.
/// </remarks>
public override long Position
{
get
{
if (this._baseStream._streamMode == ZlibBaseStream.StreamMode.Reader)
return this._baseStream._z.TotalBytesIn + this._baseStream._gzipHeaderByteCount;
return 0;
}
set { throw new NotImplementedException(); }
}
/// <summary>
/// Read and decompress data from the source stream.
/// </summary>
/// <remarks>
/// With a GZipStream, decompression is done through reading.
/// </remarks>
/// <example>
/// <code>
/// byte[] working = new byte[WORKING_BUFFER_SIZE];
/// using (System.IO.Stream input = System.IO.File.OpenRead(_CompressedFile))
/// {
/// using (Stream decompressor= new Ionic.Zlib.GZipStream(input, CompressionMode.Decompress, true))
/// {
/// using (var output = System.IO.File.Create(_DecompressedFile))
/// {
/// int n;
/// while ((n= decompressor.Read(working, 0, working.Length)) !=0)
/// {
/// output.Write(working, 0, n);
/// }
/// }
/// }
/// }
/// </code>
/// </example>
/// <param name="buffer">The buffer into which the decompressed data should be placed.</param>
/// <param name="offset">the offset within that data array to put the first byte read.</param>
/// <param name="count">the number of bytes to read.</param>
/// <returns>the number of bytes actually read</returns>
public override int Read(byte[] buffer, int offset, int count)
{
if (_disposed)
throw new ObjectDisposedException("GZipStream");
int n = _baseStream.Read(buffer, offset, count);
// Console.WriteLine("GZipStream::Read(buffer, off({0}), c({1}) = {2}", offset, count, n);
// Console.WriteLine( Util.FormatByteArray(buffer, offset, n) );
if (!_firstReadDone)
{
_firstReadDone = true;
FileName = _baseStream._GzipFileName;
Comment = _baseStream._GzipComment;
}
return n;
}
/// <summary>
/// Calling this method always throws a <see cref="NotImplementedException"/>.
/// </summary>
/// <param name="offset">irrelevant; it will always throw!</param>
/// <param name="origin">irrelevant; it will always throw!</param>
/// <returns>irrelevant!</returns>
public override long Seek(long offset, SeekOrigin origin)
{
throw new NotImplementedException();
}
/// <summary>
/// Calling this method always throws a NotImplementedException.
/// </summary>
/// <param name="value">irrelevant; this method will always throw!</param>
public override void SetLength(long value)
{
throw new NotImplementedException();
}
#endregion
internal static System.DateTime _unixEpoch = new System.DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);
internal static System.Text.Encoding iso8859dash1 = System.Text.Encoding.GetEncoding("iso-8859-1");
private int EmitHeader()
{
byte[] commentBytes = (Comment == null) ? null : iso8859dash1.GetBytes(Comment);
byte[] filenameBytes = (FileName == null) ? null : iso8859dash1.GetBytes(FileName);
int cbLength = (Comment == null) ? 0 : commentBytes.Length + 1;
int fnLength = (FileName == null) ? 0 : filenameBytes.Length + 1;
int bufferLength = 10 + cbLength + fnLength;
byte[] header = new byte[bufferLength];
int i = 0;
// ID
header[i++] = 0x1F;
header[i++] = 0x8B;
// compression method
header[i++] = 8;
byte flag = 0;
if (Comment != null)
flag ^= 0x10;
if (FileName != null)
flag ^= 0x8;
// flag
header[i++] = flag;
// mtime
if (!LastModified.HasValue)
LastModified = DateTime.Now;
System.TimeSpan delta = LastModified.Value - _unixEpoch;
Int32 timet = (Int32)delta.TotalSeconds;
Array.Copy(BitConverter.GetBytes(timet), 0, header, i, 4);
i += 4;
// xflg
header[i++] = 0; // this field is totally useless
// OS
header[i++] = 0xFF; // 0xFF == unspecified
// extra field length - only if FEXTRA is set, which it is not.
//header[i++]= 0;
//header[i++]= 0;
// filename
if (fnLength != 0)
{
Array.Copy(filenameBytes, 0, header, i, fnLength - 1);
i += fnLength - 1;
header[i++] = 0; // terminate
}
// comment
if (cbLength != 0)
{
Array.Copy(commentBytes, 0, header, i, cbLength - 1);
i += cbLength - 1;
header[i++] = 0; // terminate
}
_baseStream._stream.Write(header, 0, header.Length);
return header.Length; // bytes written
}
public override void Write(byte[] buffer, int offset, int count)
{
throw new NotImplementedException();
}
}
}
#endif
| 38.4967 | 133 | 0.526255 | [
"Apache-2.0"
] | BradBarnich/RestSharp | RestSharp/Compression/ZLib/GZipStream.cs | 23,331 | C# |
using Microsoft.AspNetCore.Mvc;
using Optivem.Northwind.Core.Application.Dto;
using Optivem.Northwind.Core.Application.Service;
using Optivem.Northwind.Core.Domain.Repository;
using Optivem.Platform.Web.AspNetCore.Rest;
namespace Optivem.Northwind.Web.Rest.Controllers
{
[Route("api/order-details")]
[ApiController]
public class OrderDetailsController : AspNetCoreCrudController<INorthwindUnitOfWork, IOrderDetailService, OrderDetailRequest, OrderDetailResponse, int>
{
public OrderDetailsController(INorthwindUnitOfWork unitOfWork, IOrderDetailService service)
: base(unitOfWork, service, e => e.Id, e => e.Id)
{
}
}
} | 37.611111 | 155 | 0.756278 | [
"MIT"
] | atomiv/erimont-cs | src/Web/AspNetCore/Rest/Controllers/OrderDetailsController.cs | 679 | 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 entitlement.marketplace-2017-01-11.normal.json service model.
*/
using System;
using System.Runtime.ExceptionServices;
using System.Threading;
using System.Threading.Tasks;
using System.Collections.Generic;
using Amazon.MarketplaceEntitlementService.Model;
using Amazon.MarketplaceEntitlementService.Model.Internal.MarshallTransformations;
using Amazon.Runtime;
using Amazon.Runtime.Internal;
using Amazon.Runtime.Internal.Auth;
using Amazon.Runtime.Internal.Transform;
namespace Amazon.MarketplaceEntitlementService
{
/// <summary>
/// Implementation for accessing MarketplaceEntitlementService
///
/// AWS Marketplace Entitlement Service
/// <para>
/// This reference provides descriptions of the AWS Marketplace Entitlement Service API.
/// </para>
///
/// <para>
/// AWS Marketplace Entitlement Service is used to determine the entitlement of a customer
/// to a given product. An entitlement represents capacity in a product owned by the customer.
/// For example, a customer might own some number of users or seats in an SaaS application
/// or some amount of data capacity in a multi-tenant database.
/// </para>
///
/// <para>
/// <b>Getting Entitlement Records</b>
/// </para>
/// <ul> <li>
/// <para>
/// <i>GetEntitlements</i>- Gets the entitlements for a Marketplace product.
/// </para>
/// </li> </ul>
/// </summary>
public partial class AmazonMarketplaceEntitlementServiceClient : AmazonServiceClient, IAmazonMarketplaceEntitlementService
{
#region Constructors
/// <summary>
/// Constructs AmazonMarketplaceEntitlementServiceClient with the credentials loaded from the application's
/// default configuration, and if unsuccessful from the Instance Profile service on an EC2 instance.
///
/// Example App.config with credentials set.
/// <code>
/// <?xml version="1.0" encoding="utf-8" ?>
/// <configuration>
/// <appSettings>
/// <add key="AWSProfileName" value="AWS Default"/>
/// </appSettings>
/// </configuration>
/// </code>
///
/// </summary>
public AmazonMarketplaceEntitlementServiceClient()
: base(FallbackCredentialsFactory.GetCredentials(), new AmazonMarketplaceEntitlementServiceConfig()) { }
/// <summary>
/// Constructs AmazonMarketplaceEntitlementServiceClient with the credentials loaded from the application's
/// default configuration, and if unsuccessful from the Instance Profile service on an EC2 instance.
///
/// Example App.config with credentials set.
/// <code>
/// <?xml version="1.0" encoding="utf-8" ?>
/// <configuration>
/// <appSettings>
/// <add key="AWSProfileName" value="AWS Default"/>
/// </appSettings>
/// </configuration>
/// </code>
///
/// </summary>
/// <param name="region">The region to connect.</param>
public AmazonMarketplaceEntitlementServiceClient(RegionEndpoint region)
: base(FallbackCredentialsFactory.GetCredentials(), new AmazonMarketplaceEntitlementServiceConfig{RegionEndpoint = region}) { }
/// <summary>
/// Constructs AmazonMarketplaceEntitlementServiceClient with the credentials loaded from the application's
/// default configuration, and if unsuccessful from the Instance Profile service on an EC2 instance.
///
/// Example App.config with credentials set.
/// <code>
/// <?xml version="1.0" encoding="utf-8" ?>
/// <configuration>
/// <appSettings>
/// <add key="AWSProfileName" value="AWS Default"/>
/// </appSettings>
/// </configuration>
/// </code>
///
/// </summary>
/// <param name="config">The AmazonMarketplaceEntitlementServiceClient Configuration Object</param>
public AmazonMarketplaceEntitlementServiceClient(AmazonMarketplaceEntitlementServiceConfig config)
: base(FallbackCredentialsFactory.GetCredentials(), config) { }
/// <summary>
/// Constructs AmazonMarketplaceEntitlementServiceClient with AWS Credentials
/// </summary>
/// <param name="credentials">AWS Credentials</param>
public AmazonMarketplaceEntitlementServiceClient(AWSCredentials credentials)
: this(credentials, new AmazonMarketplaceEntitlementServiceConfig())
{
}
/// <summary>
/// Constructs AmazonMarketplaceEntitlementServiceClient with AWS Credentials
/// </summary>
/// <param name="credentials">AWS Credentials</param>
/// <param name="region">The region to connect.</param>
public AmazonMarketplaceEntitlementServiceClient(AWSCredentials credentials, RegionEndpoint region)
: this(credentials, new AmazonMarketplaceEntitlementServiceConfig{RegionEndpoint = region})
{
}
/// <summary>
/// Constructs AmazonMarketplaceEntitlementServiceClient with AWS Credentials and an
/// AmazonMarketplaceEntitlementServiceClient Configuration object.
/// </summary>
/// <param name="credentials">AWS Credentials</param>
/// <param name="clientConfig">The AmazonMarketplaceEntitlementServiceClient Configuration Object</param>
public AmazonMarketplaceEntitlementServiceClient(AWSCredentials credentials, AmazonMarketplaceEntitlementServiceConfig clientConfig)
: base(credentials, clientConfig)
{
}
/// <summary>
/// Constructs AmazonMarketplaceEntitlementServiceClient with AWS Access Key ID and AWS Secret Key
/// </summary>
/// <param name="awsAccessKeyId">AWS Access Key ID</param>
/// <param name="awsSecretAccessKey">AWS Secret Access Key</param>
public AmazonMarketplaceEntitlementServiceClient(string awsAccessKeyId, string awsSecretAccessKey)
: this(awsAccessKeyId, awsSecretAccessKey, new AmazonMarketplaceEntitlementServiceConfig())
{
}
/// <summary>
/// Constructs AmazonMarketplaceEntitlementServiceClient with AWS Access Key ID and AWS Secret Key
/// </summary>
/// <param name="awsAccessKeyId">AWS Access Key ID</param>
/// <param name="awsSecretAccessKey">AWS Secret Access Key</param>
/// <param name="region">The region to connect.</param>
public AmazonMarketplaceEntitlementServiceClient(string awsAccessKeyId, string awsSecretAccessKey, RegionEndpoint region)
: this(awsAccessKeyId, awsSecretAccessKey, new AmazonMarketplaceEntitlementServiceConfig() {RegionEndpoint=region})
{
}
/// <summary>
/// Constructs AmazonMarketplaceEntitlementServiceClient with AWS Access Key ID, AWS Secret Key and an
/// AmazonMarketplaceEntitlementServiceClient Configuration object.
/// </summary>
/// <param name="awsAccessKeyId">AWS Access Key ID</param>
/// <param name="awsSecretAccessKey">AWS Secret Access Key</param>
/// <param name="clientConfig">The AmazonMarketplaceEntitlementServiceClient Configuration Object</param>
public AmazonMarketplaceEntitlementServiceClient(string awsAccessKeyId, string awsSecretAccessKey, AmazonMarketplaceEntitlementServiceConfig clientConfig)
: base(awsAccessKeyId, awsSecretAccessKey, clientConfig)
{
}
/// <summary>
/// Constructs AmazonMarketplaceEntitlementServiceClient with AWS Access Key ID and AWS Secret Key
/// </summary>
/// <param name="awsAccessKeyId">AWS Access Key ID</param>
/// <param name="awsSecretAccessKey">AWS Secret Access Key</param>
/// <param name="awsSessionToken">AWS Session Token</param>
public AmazonMarketplaceEntitlementServiceClient(string awsAccessKeyId, string awsSecretAccessKey, string awsSessionToken)
: this(awsAccessKeyId, awsSecretAccessKey, awsSessionToken, new AmazonMarketplaceEntitlementServiceConfig())
{
}
/// <summary>
/// Constructs AmazonMarketplaceEntitlementServiceClient with AWS Access Key ID and AWS Secret Key
/// </summary>
/// <param name="awsAccessKeyId">AWS Access Key ID</param>
/// <param name="awsSecretAccessKey">AWS Secret Access Key</param>
/// <param name="awsSessionToken">AWS Session Token</param>
/// <param name="region">The region to connect.</param>
public AmazonMarketplaceEntitlementServiceClient(string awsAccessKeyId, string awsSecretAccessKey, string awsSessionToken, RegionEndpoint region)
: this(awsAccessKeyId, awsSecretAccessKey, awsSessionToken, new AmazonMarketplaceEntitlementServiceConfig{RegionEndpoint = region})
{
}
/// <summary>
/// Constructs AmazonMarketplaceEntitlementServiceClient with AWS Access Key ID, AWS Secret Key and an
/// AmazonMarketplaceEntitlementServiceClient Configuration object.
/// </summary>
/// <param name="awsAccessKeyId">AWS Access Key ID</param>
/// <param name="awsSecretAccessKey">AWS Secret Access Key</param>
/// <param name="awsSessionToken">AWS Session Token</param>
/// <param name="clientConfig">The AmazonMarketplaceEntitlementServiceClient Configuration Object</param>
public AmazonMarketplaceEntitlementServiceClient(string awsAccessKeyId, string awsSecretAccessKey, string awsSessionToken, AmazonMarketplaceEntitlementServiceConfig clientConfig)
: base(awsAccessKeyId, awsSecretAccessKey, awsSessionToken, clientConfig)
{
}
#endregion
#region Overrides
/// <summary>
/// Creates the signer for the service.
/// </summary>
protected override AbstractAWSSigner CreateSigner()
{
return new AWS4Signer();
}
#endregion
#region Dispose
/// <summary>
/// Disposes the service client.
/// </summary>
protected override void Dispose(bool disposing)
{
base.Dispose(disposing);
}
#endregion
#region GetEntitlements
/// <summary>
/// GetEntitlements retrieves entitlement values for a given product. The results can
/// be filtered based on customer identifier or product dimensions.
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the GetEntitlements service method.</param>
///
/// <returns>The response from the GetEntitlements service method, as returned by MarketplaceEntitlementService.</returns>
/// <exception cref="Amazon.MarketplaceEntitlementService.Model.InternalServiceErrorException">
/// An internal error has occurred. Retry your request. If the problem persists, post
/// a message with details on the AWS forums.
/// </exception>
/// <exception cref="Amazon.MarketplaceEntitlementService.Model.InvalidParameterException">
/// One or more parameters in your request was invalid.
/// </exception>
/// <exception cref="Amazon.MarketplaceEntitlementService.Model.ThrottlingException">
/// The calls to the GetEntitlements API are throttled.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/entitlement.marketplace-2017-01-11/GetEntitlements">REST API Reference for GetEntitlements Operation</seealso>
public virtual GetEntitlementsResponse GetEntitlements(GetEntitlementsRequest request)
{
var marshaller = new GetEntitlementsRequestMarshaller();
var unmarshaller = GetEntitlementsResponseUnmarshaller.Instance;
return Invoke<GetEntitlementsRequest,GetEntitlementsResponse>(request, marshaller, unmarshaller);
}
/// <summary>
/// Initiates the asynchronous execution of the GetEntitlements operation.
/// </summary>
///
/// <param name="request">Container for the necessary parameters to execute the GetEntitlements operation.</param>
/// <param name="cancellationToken">
/// A cancellation token that can be used by other objects or threads to receive notice of cancellation.
/// </param>
/// <returns>The task object representing the asynchronous operation.</returns>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/entitlement.marketplace-2017-01-11/GetEntitlements">REST API Reference for GetEntitlements Operation</seealso>
public virtual Task<GetEntitlementsResponse> GetEntitlementsAsync(GetEntitlementsRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken))
{
var marshaller = new GetEntitlementsRequestMarshaller();
var unmarshaller = GetEntitlementsResponseUnmarshaller.Instance;
return InvokeAsync<GetEntitlementsRequest,GetEntitlementsResponse>(request, marshaller,
unmarshaller, cancellationToken);
}
#endregion
}
} | 47.365772 | 188 | 0.675097 | [
"Apache-2.0"
] | Murcho/aws-sdk-net | sdk/src/Services/MarketplaceEntitlementService/Generated/_bcl45/AmazonMarketplaceEntitlementServiceClient.cs | 14,115 | C# |
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using UnityEngine;
public class NearbyPositionSelector : MonoBehaviour, IPositionSeletor
{
public float PlacementSize;
public float SearchStepSize;
public float SearchStepSizeVariance;
public int MaxIters;
private const string StructTag = "StructureUnit";
private const int TerrainLayer = 1 << 8;
public Vector3 SelectPosition(IEnumerable<Vector3> centers, Vector3 checkSize)
{
Vector3 position = Vector3.zero;
Vector3 baseDirection = Random.onUnitSphere * SearchStepSize;
baseDirection = new Vector3(baseDirection.x, 0f, baseDirection.y);
foreach (Vector3 center in centers)
{
int iters = 0;
position = center;
while (!CanPlace(position, checkSize) && iters < MaxIters)
{
Vector2 randBase = Random.insideUnitCircle;
Vector3 rand = new Vector3(randBase.x, 0f, randBase.y);
position += rand * (SearchStepSize + GetVariance()) + (baseDirection * GetVariance());
iters++;
}
}
return position;
}
private float GetVariance() => Random.Range(-SearchStepSizeVariance, SearchStepSizeVariance);
private bool CanPlace (Vector3 position, Vector3 checkSize)
{
Collider[] colliders = Physics.OverlapBox(position, checkSize / 2f, Quaternion.identity, ~TerrainLayer);
return !colliders.Any(x => x.CompareTag(StructTag));
}
}
| 33.87234 | 113 | 0.636935 | [
"MIT"
] | Lomztein/Project-Frontline | Assets/Source/NearbyPositionSelector.cs | 1,594 | C# |
using System;
using System.Collections.ObjectModel;
using System.Reactive;
using System.Reactive.Disposables;
using System.Reactive.Linq;
using System.Reactive.Subjects;
using DynamicData;
using DynamicData.Binding;
using ReactiveUI;
using Rocket.Surgery.Airframe.ViewModels;
using Showroom.Scroll;
namespace Showroom.CollectionView.Scroll
{
public class InfiniteCollectionViewModel : NavigableViewModelBase
{
private readonly IInventoryDataService _inventoryDataService;
private ReadOnlyObservableCollection<InfiniteItemViewModel> _inventory;
private BehaviorSubject<IPageRequest> _pagingSubject;
private int _pageSize = 20;
public InfiniteCollectionViewModel(IInventoryDataService inventoryDataService)
{
_inventoryDataService = inventoryDataService;
_pagingSubject = new BehaviorSubject<IPageRequest>(new PageRequest(0, _pageSize));
_inventoryDataService
.ChangeSet
.Transform(x => new InfiniteItemViewModel(x))
.Sort(SortExpressionComparer<InfiniteItemViewModel>.Ascending(x => x.Id))
.Page(_pagingSubject.AsObservable())
.Bind(out _inventory)
.DisposeMany()
.Subscribe()
.DisposeWith(Garbage);
Load = ReactiveCommand.CreateFromObservable(ExecuteLoad);
}
/// <summary>
/// This was hard.
/// </summary>
public ReactiveCommand<Unit, Unit> Load { get; set; }
public ReadOnlyObservableCollection<InfiniteItemViewModel> Items => _inventory;
protected override IObservable<Unit> ExecuteInitialize() =>
_inventoryDataService.Read().Select(x => Unit.Default);
private IObservable<Unit> ExecuteLoad() =>
Observable
.Create<Unit>(observer =>
{
_pagingSubject.OnNext(new PageRequest(1, _pageSize + _pageSize));
return _inventoryDataService
.Read()
.Select(x => Unit.Default)
.Subscribe(observer);
});
}
} | 35 | 94 | 0.630385 | [
"MIT"
] | RLittlesII/ReactiveUI.Showroom | src/Forms/CollectionView/Scroll/InfiniteCollectionViewModel.cs | 2,205 | C# |
// Copyright 2017 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
using Google.Cloud.Spanner.V1;
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using Xunit;
namespace Google.Cloud.Spanner.Data.IntegrationTests
{
[Collection(nameof(SpannerDatabaseFixture))]
[CommonTestDiagnostics]
public class BindingTests
{
private readonly SpannerDatabaseFixture _fixture;
public BindingTests(SpannerDatabaseFixture fixture) =>
_fixture = fixture;
public static TheoryData<SpannerDbType> BindNullData { get; } = new TheoryData<SpannerDbType>
{
SpannerDbType.Bool,
SpannerDbType.String,
SpannerDbType.Int64,
SpannerDbType.Timestamp,
SpannerDbType.Float64,
SpannerDbType.Date,
SpannerDbType.Bytes,
SpannerDbType.ArrayOf(SpannerDbType.Bool),
SpannerDbType.ArrayOf(SpannerDbType.String),
SpannerDbType.ArrayOf(SpannerDbType.Int64),
SpannerDbType.ArrayOf(SpannerDbType.Timestamp),
SpannerDbType.ArrayOf(SpannerDbType.Float64),
SpannerDbType.ArrayOf(SpannerDbType.Date),
SpannerDbType.ArrayOf(SpannerDbType.Bytes),
};
public static TheoryData<SpannerDbType> BindNullNumericData { get; } = new TheoryData<SpannerDbType>
{
SpannerDbType.Numeric,
SpannerDbType.ArrayOf(SpannerDbType.Numeric),
};
// [START spanner_test_query_bind_bool_null]
// [END spanner_test_query_bind_bool_null]
// [START spanner_test_query_bind_int64_null]
// [END spanner_test_query_bind_int64_null]
// [START spanner_test_query_bind_float64_null]
// [END spanner_test_query_bind_float64_null]
// [START spanner_test_query_bind_string_null]
// [END spanner_test_query_bind_string_null]
// [START spanner_test_query_bind_bytes_null]
// [END spanner_test_query_bind_bytes_null]
// [START spanner_test_query_bind_timestamp_null]
// [END spanner_test_query_bind_timestamp_null]
// [START spanner_test_query_bind_date_null]
// [END spanner_test_query_bind_date_null]
// [START spanner_test_query_bind_bool_array_null]
// [END spanner_test_query_bind_bool_array_null]
// [START spanner_test_query_bind_int64_array_null]
// [END spanner_test_query_bind_int64_array_null]
// [START spanner_test_query_bind_float64_array_null]
// [END spanner_test_query_bind_float64_array_null]
// [START spanner_test_query_bind_string_array_null]
// [END spanner_test_query_bind_string_array_null]
// [START spanner_test_query_bind_bytes_array_null]
// [END spanner_test_query_bind_bytes_array_null]
// [START spanner_test_query_bind_timestamp_array_null]
// [END spanner_test_query_bind_timestamp_array_null]
// [START spanner_test_query_bind_date_array_null]
// [END spanner_test_query_bind_date_array_null]
[Theory]
[MemberData(nameof(BindNullData))]
public async Task BindNull(SpannerDbType parameterType)
{
using (var connection = _fixture.GetConnection())
{
var cmd = connection.CreateSelectCommand("SELECT @v");
cmd.Parameters.Add("v", parameterType, null);
using (var reader = await cmd.ExecuteReaderAsync())
{
Assert.True(await reader.ReadAsync());
Assert.True(reader.IsDBNull(0));
Assert.Equal(DBNull.Value, reader.GetValue(0));
Assert.False(await reader.ReadAsync());
}
}
}
// [START spanner_test_query_bind_numeric_null]
// [END spanner_test_query_bind_numeric_null]
// [START spanner_test_query_bind_numeric_array_null]
// [END spanner_test_query_bind_numeric_array_null]
[Theory]
[MemberData(nameof(BindNullNumericData))]
public async Task BindNullNumeric(SpannerDbType parameterType)
{
using (var connection = _fixture.GetConnection())
{
var cmd = connection.CreateSelectCommand("SELECT @v");
cmd.Parameters.Add("v", parameterType, null);
using (var reader = await cmd.ExecuteReaderAsync())
{
Assert.True(await reader.ReadAsync());
Assert.True(reader.IsDBNull(0));
Assert.Equal(DBNull.Value, reader.GetValue(0));
Assert.False(await reader.ReadAsync());
}
}
}
private async Task TestBindNonNull<T>(SpannerDbType parameterType, T value, Func<SpannerDataReader, T> typeSpecificReader = null)
{
int rowsRead;
var valueRead = default(T);
using (var connection = _fixture.GetConnection())
{
var cmd = connection.CreateSelectCommand("SELECT @v");
cmd.Parameters.Add("v", parameterType, value);
using (var reader = await cmd.ExecuteReaderAsync())
{
rowsRead = 0;
while (await reader.ReadAsync())
{
valueRead = reader.GetFieldValue<T>(0);
// Optional extra test for certain built in types
if (typeSpecificReader != null)
{
Assert.Equal(typeSpecificReader(reader), valueRead);
Assert.False(reader.IsDBNull(0));
}
rowsRead++;
}
}
}
Assert.Equal(1, rowsRead);
var valueAsArray = value as Array;
if (valueAsArray != null)
{
var valueReadAsArray = valueRead as Array;
Assert.NotNull(valueReadAsArray);
Assert.Equal(valueAsArray.Length, valueReadAsArray.Length);
for (int i = 0; i < valueAsArray.Length; i++)
{
Assert.Equal(valueAsArray.GetValue(i), valueReadAsArray.GetValue(i));
}
}
else
{
Assert.Equal(value, valueRead);
}
}
// [START spanner_test_query_bind_bool]
[Fact]
public Task BindBoolean() => TestBindNonNull(SpannerDbType.Bool, true, r => r.GetBoolean(0));
// [END spanner_test_query_bind_bool]
// [START spanner_test_query_bind_bool_array]
[Fact]
public Task BindBooleanArray() => TestBindNonNull(
SpannerDbType.ArrayOf(SpannerDbType.Bool),
new bool?[] {true, null, false});
// [END spanner_test_query_bind_bool_array]
// [START spanner_test_query_bind_bool_array_empty]
[Fact]
public Task BindBooleanEmptyArray() => TestBindNonNull(
SpannerDbType.ArrayOf(SpannerDbType.Bool),
new bool[] { });
// [END spanner_test_query_bind_bool_array_empty]
// [START spanner_test_query_bind_bytes]
[Fact]
public Task BindByteArray() => TestBindNonNull(
SpannerDbType.Bytes,
new byte[] {1, 2, 3});
// [END spanner_test_query_bind_bytes]
// [START spanner_test_query_bind_bytes_array]
[Fact]
public Task BindByteArrayList() => TestBindNonNull(
SpannerDbType.ArrayOf(SpannerDbType.Bytes),
new List<byte[]> {
new byte[] { 1, 2, 3 },
new byte[] { 4, 5, 6 },
null
});
// [END spanner_test_query_bind_bytes_array]
// [START spanner_test_query_bind_bytes_array_empty]
[Fact]
public Task BindEmptyByteArrayList() => TestBindNonNull(
SpannerDbType.ArrayOf(SpannerDbType.Bytes),
new List<byte[]>());
// [END spanner_test_query_bind_bytes_array_empty]
// [START spanner_test_query_bind_date]
[Fact]
public Task BindDate() => TestBindNonNull(
SpannerDbType.Date,
new DateTime(2017, 5, 26));
// [END spanner_test_query_bind_date]
// [START spanner_test_query_bind_date_array]
[Fact]
public Task BindDateArray() => TestBindNonNull(
SpannerDbType.ArrayOf(SpannerDbType.Date),
new DateTime?[] {new DateTime(2017, 5, 26), null, new DateTime(2017, 5, 9)});
// [END spanner_test_query_bind_date_array]
// [START spanner_test_query_bind_date_array_empty]
[Fact]
public Task BindDateEmptyArray() => TestBindNonNull(
SpannerDbType.ArrayOf(SpannerDbType.Date),
new DateTime?[] { });
// [END spanner_test_query_bind_date_array_empty]
// [START spanner_test_query_bind_float64]
[Fact]
public Task BindFloat64() => TestBindNonNull(SpannerDbType.Float64, 1.0, r => r.GetDouble(0));
// [END spanner_test_query_bind_float64]
// [START spanner_test_query_bind_float64_array]
[Fact]
public Task BindFloat64Array() => TestBindNonNull(
SpannerDbType.ArrayOf(SpannerDbType.Float64),
new double?[] {0.0, null, 1.0});
// [END spanner_test_query_bind_float64_array]
// [START spanner_test_query_bind_float64_array_empty]
[Fact]
public Task BindFloat64EmptyArray() => TestBindNonNull(
SpannerDbType.ArrayOf(SpannerDbType.Float64),
new double[] { });
// [END spanner_test_query_bind_float64_array_empty]
// [START spanner_test_query_bind_int64]
[Fact]
public Task BindInt64() => TestBindNonNull(SpannerDbType.Int64, 1, r => r.GetInt64(0));
// [END spanner_test_query_bind_int64]
// [START spanner_test_query_bind_int64_array]
[Fact]
public Task BindInt64Array() => TestBindNonNull(
SpannerDbType.ArrayOf(SpannerDbType.Int64),
new long?[] {1, null, 0});
// [END spanner_test_query_bind_int64_array]
// [START spanner_test_query_bind_int64_array_empty]
[Fact]
public Task BindInt64EmptyArray() => TestBindNonNull(
SpannerDbType.ArrayOf(SpannerDbType.Int64),
new long[] { });
// [END spanner_test_query_bind_int64_array_empty]
// [START spanner_test_query_bind_numeric]
[Fact]
public async Task BindNumeric()
{
await TestBindNonNull(SpannerDbType.Numeric, SpannerNumeric.Parse("1.0"), r => r.GetNumeric(0));
}
// [END spanner_test_query_bind_numeric]
// [START spanner_test_query_bind_numeric_array]
[Fact]
public async Task BindNumericArray()
{
await TestBindNonNull(
SpannerDbType.ArrayOf(SpannerDbType.Numeric),
new SpannerNumeric?[] {SpannerNumeric.Parse("0.0"), null, SpannerNumeric.Parse("1.0")});
}
// [END spanner_test_query_bind_numeric_array]
// [START spanner_test_query_bind_numeric_array_empty]
[Fact]
public async Task BindNumericEmptyArray()
{
await TestBindNonNull(SpannerDbType.ArrayOf(SpannerDbType.Numeric), new SpannerNumeric[] { });
}
// [END spanner_test_query_bind_numeric_array_empty]
// [START spanner_test_query_bind_string]
[Fact]
public Task BindString() => TestBindNonNull(SpannerDbType.String, "abc", r => r.GetString(0));
// [END spanner_test_query_bind_string]
// [START spanner_test_query_bind_string_array]
[Fact]
public Task BindStringArray() => TestBindNonNull(
SpannerDbType.ArrayOf(SpannerDbType.String),
new[] {"abc", null, "123"});
// [END spanner_test_query_bind_string_array]
// [START spanner_test_query_bind_string_array_empty]
[Fact]
public Task BindStringEmptyArray() => TestBindNonNull(
SpannerDbType.ArrayOf(SpannerDbType.String),
new string[] { });
// [END spanner_test_query_bind_string_array_empty]
// [START spanner_test_query_bind_timestamp]
[Fact]
public Task BindTimestamp() => TestBindNonNull(
SpannerDbType.Timestamp,
new DateTime(2017, 5, 26, 15, 0, 0));
// [END spanner_test_query_bind_timestamp]
// [START spanner_test_query_bind_timestamp_array]
[Fact]
public Task BindTimestampArray() => TestBindNonNull(
SpannerDbType.ArrayOf(SpannerDbType.Timestamp),
new DateTime?[]
{new DateTime(2017, 5, 26, 3, 15, 0), null, new DateTime(2017, 5, 9, 12, 30, 0)});
// [END spanner_test_query_bind_timestamp_array]
// [START spanner_test_query_bind_timestamp_array_empty]
[Fact]
public Task BindTimestampEmptyArray() => TestBindNonNull(
SpannerDbType.ArrayOf(SpannerDbType.Timestamp),
new DateTime?[] { });
// [END spanner_test_query_bind_timestamp_array_empty]
}
}
| 40.322674 | 137 | 0.617475 | [
"Apache-2.0"
] | snakefoot/google-cloud-dotnet | apis/Google.Cloud.Spanner.Data/Google.Cloud.Spanner.Data.IntegrationTests/BindingTests.cs | 13,873 | C# |
// ----------------------------------------------------------------------------------
//
// Copyright Microsoft Corporation
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// ----------------------------------------------------------------------------------
using System;
namespace Microsoft.Azure.Commands.DataLakeStore.Test.ScenarioTests
{
using Microsoft.WindowsAzure.Commands.ScenarioTest;
using ServiceManagemenet.Common.Models;
using Xunit;
public class AdlsAliasTests : AdlsTestsBase
{
public XunitTracingInterceptor _logger;
public AdlsAliasTests(Xunit.Abstractions.ITestOutputHelper output)
{
_logger = new XunitTracingInterceptor(output);
XunitTracingInterceptor.AddToContext(_logger);
}
[Fact]
[Trait(Category.AcceptanceType, Category.CheckIn)]
public void TestAdlsAccount()
{
NewInstance.RunPsTest(_logger, string.Format("Test-DataLakeStoreAccount -location '{0}'", AdlsTestsBase.resourceGroupLocation));
}
[Fact]
[Trait(Category.AcceptanceType, Category.CheckIn)]
public void TestAdlsAccountTiers()
{
NewInstance.RunPsTest(_logger, string.Format("Test-DataLakeStoreAccountTiers -location '{0}'", AdlsTestsBase.resourceGroupLocation));
}
[Fact]
[Trait(Category.AcceptanceType, Category.CheckIn)]
public void TestAdlsFirewallRules()
{
NewInstance.RunPsTest(_logger, string.Format("Test-DataLakeStoreFirewall -location '{0}'", AdlsTestsBase.resourceGroupLocation));
}
[Fact]
[Trait(Category.AcceptanceType, Category.CheckIn)]
public void TestAdlsTrustedIdProvider()
{
NewInstance.RunPsTest(_logger, string.Format("Test-DataLakeStoreTrustedIdProvider -location '{0}'", AdlsTestsBase.resourceGroupLocation));
}
[Fact]
[Trait(Category.AcceptanceType, Category.CheckIn)]
public void TestAdlsFileSystem()
{
NewInstance.RunPsTest(_logger, string.Format("Test-DataLakeStoreFileSystem -fileToCopy '{0}' -location '{1}'", ".\\ScenarioTests\\" + this.GetType().Name + ".ps1", AdlsTestsBase.resourceGroupLocation));
}
[Fact]
[Trait(Category.AcceptanceType, Category.CheckIn)]
public void TestAdlsFileSystemPermissions()
{
NewInstance.RunPsTest(_logger, string.Format("Test-DataLakeStoreFileSystemPermissions -location '{0}'", AdlsTestsBase.resourceGroupLocation));
}
[Fact]
[Trait(Category.AcceptanceType, Category.CheckIn)]
public void TestNegativeAdlsAccount()
{
NewInstance.RunPsTest(_logger, string.Format("Test-NegativeDataLakeStoreAccount -location '{0}'", AdlsTestsBase.resourceGroupLocation));
}
}
}
| 41.46988 | 215 | 0.636549 | [
"MIT"
] | FonsecaSergio/azure-powershell | src/ResourceManager/DataLakeStore/Commands.DataLakeStore.Test/ScenarioTests/AdlsAliasTests.cs | 3,362 | C# |
using NHapi.Base.Parser;
using NHapi.Base;
using NHapi.Base.Log;
using System;
using System.Collections.Generic;
using NHapi.Model.V23.Segment;
using NHapi.Model.V23.Datatype;
using NHapi.Base.Model;
namespace NHapi.Model.V23.Group
{
///<summary>
///Represents the ADT_A01_PROCEDURE Group. A Group is an ordered collection of message
/// segments that can repeat together or be optionally in/excluded together.
/// This Group contains the following elements:
///<ol>
///<li>0: PR1 (Procedures) </li>
///<li>1: ROL (Role) optional repeating</li>
///</ol>
///</summary>
[Serializable]
public class ADT_A01_PROCEDURE : AbstractGroup {
///<summary>
/// Creates a new ADT_A01_PROCEDURE Group.
///</summary>
public ADT_A01_PROCEDURE(IGroup parent, IModelClassFactory factory) : base(parent, factory){
try {
this.add(typeof(PR1), true, false);
this.add(typeof(ROL), false, true);
} catch(HL7Exception e) {
HapiLogFactory.GetHapiLog(GetType()).Error("Unexpected error creating ADT_A01_PROCEDURE - this is probably a bug in the source code generator.", e);
}
}
///<summary>
/// Returns PR1 (Procedures) - creates it if necessary
///</summary>
public PR1 PR1 {
get{
PR1 ret = null;
try {
ret = (PR1)this.GetStructure("PR1");
} catch(HL7Exception e) {
HapiLogFactory.GetHapiLog(GetType()).Error("Unexpected error accessing data - this is probably a bug in the source code generator.", e);
throw new System.Exception("An unexpected error ocurred",e);
}
return ret;
}
}
///<summary>
/// Returns first repetition of ROL (Role) - creates it if necessary
///</summary>
public ROL GetROL() {
ROL ret = null;
try {
ret = (ROL)this.GetStructure("ROL");
} catch(HL7Exception e) {
HapiLogFactory.GetHapiLog(GetType()).Error("Unexpected error accessing data - this is probably a bug in the source code generator.", e);
throw new System.Exception("An unexpected error ocurred",e);
}
return ret;
}
///<summary>
///Returns a specific repetition of ROL
/// * (Role) - creates it if necessary
/// throws HL7Exception if the repetition requested is more than one
/// greater than the number of existing repetitions.
///</summary>
public ROL GetROL(int rep) {
return (ROL)this.GetStructure("ROL", rep);
}
/**
* Returns the number of existing repetitions of ROL
*/
public int ROLRepetitionsUsed {
get{
int reps = -1;
try {
reps = this.GetAll("ROL").Length;
} catch (HL7Exception e) {
string message = "Unexpected error accessing data - this is probably a bug in the source code generator.";
HapiLogFactory.GetHapiLog(GetType()).Error(message, e);
throw new System.Exception(message);
}
return reps;
}
}
/**
* Enumerate over the ROL results
*/
public IEnumerable<ROL> ROLs
{
get
{
for (int rep = 0; rep < ROLRepetitionsUsed; rep++)
{
yield return (ROL)this.GetStructure("ROL", rep);
}
}
}
///<summary>
///Adds a new ROL
///</summary>
public ROL AddROL()
{
return this.AddStructure("ROL") as ROL;
}
///<summary>
///Removes the given ROL
///</summary>
public void RemoveROL(ROL toRemove)
{
this.RemoveStructure("ROL", toRemove);
}
///<summary>
///Removes the ROL at the given index
///</summary>
public void RemoveROLAt(int index)
{
this.RemoveRepetition("ROL", index);
}
}
}
| 26.902256 | 156 | 0.634433 | [
"MPL-2.0",
"MPL-2.0-no-copyleft-exception"
] | afaonline/nHapi | src/NHapi.Model.V23/Group/ADT_A01_PROCEDURE.cs | 3,578 | C# |
// This file is part of the DSharpPlus project.
//
// Copyright (c) 2015 Mike Santiago
// Copyright (c) 2016-2021 DSharpPlus Contributors
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Runtime.CompilerServices;
namespace DSharpPlus.VoiceNext
{
/// <summary>
/// Defines the format of PCM data consumed or produced by Opus.
/// </summary>
public struct AudioFormat
{
/// <summary>
/// Gets the collection of sampling rates (in Hz) the Opus encoder can use.
/// </summary>
public static IReadOnlyCollection<int> AllowedSampleRates { get; } = new ReadOnlyCollection<int>(new[] { 8000, 12000, 16000, 24000, 48000 });
/// <summary>
/// Gets the collection of channel counts the Opus encoder can use.
/// </summary>
public static IReadOnlyCollection<int> AllowedChannelCounts { get; } = new ReadOnlyCollection<int>(new[] { 1, 2 });
/// <summary>
/// Gets the collection of sample durations (in ms) the Opus encoder can use.
/// </summary>
public static IReadOnlyCollection<int> AllowedSampleDurations { get; } = new ReadOnlyCollection<int>(new[] { 5, 10, 20, 40, 60 });
/// <summary>
/// Gets the default audio format. This is a formt configured for 48kHz sampling rate, 2 channels, with music quality preset.
/// </summary>
public static AudioFormat Default { get; } = new AudioFormat(48000, 2, VoiceApplication.Music);
/// <summary>
/// Gets the audio sampling rate in Hz.
/// </summary>
public int SampleRate { get; }
/// <summary>
/// Gets the audio channel count.
/// </summary>
public int ChannelCount { get; }
/// <summary>
/// Gets the voice application, which dictates the quality preset.
/// </summary>
public VoiceApplication VoiceApplication { get; }
/// <summary>
/// Creates a new audio format for use with Opus encoder.
/// </summary>
/// <param name="sampleRate">Audio sampling rate in Hz.</param>
/// <param name="channelCount">Number of audio channels in the data.</param>
/// <param name="voiceApplication">Encoder preset to use.</param>
public AudioFormat(int sampleRate = 48000, int channelCount = 2, VoiceApplication voiceApplication = VoiceApplication.Music)
{
if (!AllowedSampleRates.Contains(sampleRate))
throw new ArgumentOutOfRangeException(nameof(sampleRate), "Invalid sample rate specified.");
if (!AllowedChannelCounts.Contains(channelCount))
throw new ArgumentOutOfRangeException(nameof(channelCount), "Invalid channel count specified.");
if (voiceApplication != VoiceApplication.Music && voiceApplication != VoiceApplication.Voice && voiceApplication != VoiceApplication.LowLatency)
throw new ArgumentOutOfRangeException(nameof(voiceApplication), "Invalid voice application specified.");
this.SampleRate = sampleRate;
this.ChannelCount = channelCount;
this.VoiceApplication = voiceApplication;
}
/// <summary>
/// Calculates a sample size in bytes.
/// </summary>
/// <param name="sampleDuration">Millsecond duration of a sample.</param>
/// <returns>Calculated sample size in bytes.</returns>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public int CalculateSampleSize(int sampleDuration)
{
if (!AllowedSampleDurations.Contains(sampleDuration))
throw new ArgumentOutOfRangeException(nameof(sampleDuration), "Invalid sample duration specified.");
// Sample size in bytes is a product of the following:
// - duration in milliseconds
// - number of channels
// - sample rate in kHz
// - size of data (in this case, sizeof(int16_t))
// which comes down to below:
return sampleDuration * this.ChannelCount * (this.SampleRate / 1000) * 2;
}
/// <summary>
/// Gets the maximum buffer size for decoding. This method should be called when decoding Opus data to PCM, to ensure sufficient buffer size.
/// </summary>
/// <returns>Buffer size required to decode data.</returns>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public int GetMaximumBufferSize()
=> this.CalculateMaximumFrameSize();
[MethodImpl(MethodImplOptions.AggressiveInlining)]
internal int CalculateSampleDuration(int sampleSize)
=> sampleSize / (this.SampleRate / 1000) / this.ChannelCount / 2 /* sizeof(int16_t) */;
[MethodImpl(MethodImplOptions.AggressiveInlining)]
internal int CalculateFrameSize(int sampleDuration)
=> sampleDuration * (this.SampleRate / 1000);
[MethodImpl(MethodImplOptions.AggressiveInlining)]
internal int CalculateMaximumFrameSize()
=> 120 * (this.SampleRate / 1000);
[MethodImpl(MethodImplOptions.AggressiveInlining)]
internal int SampleCountToSampleSize(int sampleCount)
=> sampleCount * this.ChannelCount * 2 /* sizeof(int16_t) */;
internal bool IsValid()
=> AllowedSampleRates.Contains(this.SampleRate) && AllowedChannelCounts.Contains(this.ChannelCount) &&
(this.VoiceApplication == VoiceApplication.Music || this.VoiceApplication == VoiceApplication.Voice || this.VoiceApplication == VoiceApplication.LowLatency);
}
}
| 47.153846 | 173 | 0.666766 | [
"MIT"
] | CatThingy/DSharpPlus | DSharpPlus.VoiceNext/AudioFormat.cs | 6,743 | C# |
using NetIRC.Messages;
using System.Linq;
using Xunit;
using System;
using System.Collections.Generic;
namespace NetIRC.Tests
{
public class IRCMessageTests
{
[Fact]
public void TestPingMessage()
{
var command = "PING";
var parameter = "tolsun.oulu.fi";
var parsedIRCMessage = new ParsedIRCMessage($"{command} {parameter}");
var pingMessage = new PingMessage(parsedIRCMessage);
Assert.Equal(parameter, pingMessage.Target);
}
[Fact]
public void TestMessageCreatedDate()
{
var parsedIRCMessage = new ParsedIRCMessage("PING 123");
var pingMessage = new PingMessage(parsedIRCMessage);
Assert.Equal(DateTime.Now, pingMessage.CreatedDate, TimeSpan.FromSeconds(1));
}
[Fact]
public void TestPongMessageTokens()
{
var pongMsg = new PongMessage("tolsun.oulu.fi");
Assert.Equal("PONG tolsun.oulu.fi", pongMsg.ToString());
}
[Theory]
[InlineData("WiZ", "Hello", false)]
[InlineData("WiZ", "Are you receiving this message ?", false)]
[InlineData("#NetIRC", "Hello", true)]
[InlineData("#NetIRC", "Are you receiving this message ?", true)]
public void TestPrivMsgMessage(string target, string text, bool isChannelMessage)
{
var prefix = "Angel!wings@irc.org";
var raw = $":{prefix} PRIVMSG {target} {(text.Contains(' ') ? $":{text}" : text)}";
var parsedIRCMessage = new ParsedIRCMessage(raw);
var privMsgMessage = new PrivMsgMessage(parsedIRCMessage);
Assert.Equal(prefix, privMsgMessage.Prefix.Raw);
Assert.Equal(target, privMsgMessage.To);
Assert.Equal(text, privMsgMessage.Message);
Assert.Equal(isChannelMessage, privMsgMessage.IsChannelMessage);
}
[Theory]
[InlineData("WiZ", "Hello", false)]
[InlineData("WiZ", ":Are you receiving this message ?", false)]
[InlineData("#NetIRC", "Hello", true)]
[InlineData("#NetIRC", ":Are you receiving this message ?", true)]
public void TestNoticeMessage(string target, string text, bool isChannelMessage)
{
var from = "irc.server.net";
var raw = $":{from} NOTICE {target} :{text}";
var parsedIRCMessage = new ParsedIRCMessage(raw);
var noticeMessage = new NoticeMessage(parsedIRCMessage);
Assert.Equal(from, noticeMessage.From);
Assert.Equal(target, noticeMessage.Target);
Assert.Equal(text, noticeMessage.Message);
Assert.Equal(isChannelMessage, noticeMessage.IsChannelMessage);
}
[Fact]
public void TestPrivMsgMessageWithNoSpacesAndStartingWithColon()
{
var target = "WiZ";
var message = ":)";
var privMsgMessage = new PrivMsgMessage(target, message);
Assert.Equal($"PRIVMSG {target} :{message}", privMsgMessage.ToString());
}
[Fact]
public void TestPrivMsgMessageTokens()
{
var target = "WiZ";
var message = "Are you receiving this message ?";
var privMsgMessage = new PrivMsgMessage(target, message);
Assert.Equal($"PRIVMSG {target} :{message}", privMsgMessage.ToString());
}
[Fact]
public void TestNoticeMessageTokens()
{
var target = "WiZ";
var message = "Are you receiving this message ?";
var privMsgMessage = new NoticeMessage(target, message);
Assert.Equal($"NOTICE {target} :{message}", privMsgMessage.ToString());
}
[Fact]
public void TestNickMessageTokens()
{
var newNick = "Kilroy";
var nickMessage = new NickMessage(newNick);
Assert.Equal($"NICK {newNick}", nickMessage.ToString());
}
[Fact]
public void TestUserMessageTokens()
{
var user = "guest";
var realName = "Ronnie Reagan";
var userMessage = new UserMessage(user, realName);
Assert.Equal($"USER {user} 0 - :{realName}", userMessage.ToString());
}
[Fact]
public void TestJoinMessageTokens()
{
var channel = "#chan";
var joinMessage = new JoinMessage(channel);
Assert.Equal($"JOIN {channel}", joinMessage.ToString());
}
[Fact]
public void TestJoinMessageWithKeyTokens()
{
var channel = "#chan";
var key = "12345";
var joinMessage = new JoinMessage(channel, key);
Assert.Equal($"JOIN {channel} {key}", joinMessage.ToString());
}
[Fact]
public void TestJoinMessageWithMultipleChannelsTokens()
{
var channels = new[] { "#chan1", "#chan2", "#chan3" };
var joinMessage = new JoinMessage(channels);
Assert.Equal($"JOIN {string.Join(",", channels)}", joinMessage.ToString());
}
[Fact]
public void TestJoinMessageWithMultipleChannelsAndKeysTokens()
{
var channelsWithKeys = new Dictionary<string, string>
{
{ "#chan1", "pass123" },
{ "#chan2", "anotherpass" }
};
var joinMessage = new JoinMessage(channelsWithKeys);
Assert.Equal(
$"JOIN {string.Join(",", channelsWithKeys.Keys)} {string.Join(",", channelsWithKeys.Values)}",
joinMessage.ToString());
}
[Fact]
public void TestPartMessageTokens()
{
var channel = "#chan";
var joinMessage = new PartMessage(channel);
Assert.Equal($"PART {channel}", joinMessage.ToString());
}
[Fact]
public void TestPartMessageWithMultipleChannelsTokens()
{
var channels = new[] { "#chan1", "#chan2" };
var joinMessage = new PartMessage(channels);
Assert.Equal($"PART {string.Join(",", channels)}", joinMessage.ToString());
}
[Fact]
public void TestQuitMessageTokens()
{
var message = "Out for lunch";
var joinMessage = new QuitMessage(message);
Assert.Equal($"QUIT :{message}", joinMessage.ToString());
}
[Fact]
public void TestTopicMessageTokens()
{
var channel = "#NetIRC";
var topic = "NetIRC is nice!";
var topicMessage = new TopicMessage(channel, topic);
Assert.Equal($"TOPIC {channel} :{topic}", topicMessage.ToString());
}
[Fact]
public void TestClientMessageWithoutTokens_ShouldReturnEmptyToString()
{
var testMessage = new TestClientMessage();
Assert.Equal(string.Empty, testMessage.ToString());
}
[Fact]
public void TestIRCMessageWithoutImplementingIClientMessage_ShouldReturnBaseToString()
{
var testMessage = new TestIRCMessage();
Assert.Equal(typeof(TestIRCMessage).FullName, testMessage.ToString());
}
[Fact]
public void TestModeMessage()
{
var prefix = "netIRC!~netIRC@XYZ.IP";
var target = "netIRC";
var modes = "+ix";
var raw = $":{prefix} MODE {target} :{modes}";
var parsedIRCMessage = new ParsedIRCMessage(raw);
var modeMessage = new ModeMessage(parsedIRCMessage);
Assert.Equal(prefix, modeMessage.Prefix.Raw);
Assert.Equal(target, modeMessage.Target);
Assert.Equal(modes, modeMessage.Modes);
}
[Fact]
public void TestModeMessageForChannel()
{
var prefix = "Fredi!~netIRC@XYZ.IP";
var target = "#NetIRC";
var modes = "+o";
var nick = "NetIRCClient";
var raw = $":{prefix} MODE {target} {modes} {nick}";
var parsedIRCMessage = new ParsedIRCMessage(raw);
var modeMessage = new ModeMessage(parsedIRCMessage);
Assert.Equal(prefix, modeMessage.Prefix.Raw);
Assert.Equal(target, modeMessage.Target);
Assert.Equal(modes, modeMessage.Modes);
Assert.Equal(nick, modeMessage.Parameters[0]);
}
[Fact]
public void TestModeMessageTokens()
{
var target = "WiZ";
var modes = "+i";
var modeMessage = new ModeMessage(target, modes);
Assert.Equal($"MODE {target} {modes}", modeMessage.ToString());
}
[Fact]
public void TestKickMessage()
{
var kickedBy = "Fredi";
var channel = "#netirctest";
var nick = "NetIRCConsoleClient";
var raw = $":{kickedBy}!~Fredi@XYZ.IP KICK {channel} {nick}";
var parsedIRCMessage = new ParsedIRCMessage(raw);
var kickMessage = new KickMessage(parsedIRCMessage);
Assert.Equal(kickedBy, kickMessage.KickedBy);
Assert.Equal(channel, kickMessage.Channel);
Assert.Equal(nick, kickMessage.Nick);
}
[Fact]
public void TestKickMessageWithComment()
{
var kickedBy = "Fredi";
var channel = "#netirctest";
var nick = "NetIRCConsoleClient";
var comment = "I love you!";
var raw = $":{kickedBy}!~Fredi@XYZ.IP KICK {channel} {nick} :{comment}";
var parsedIRCMessage = new ParsedIRCMessage(raw);
var kickMessage = new KickMessage(parsedIRCMessage);
Assert.Equal(kickedBy, kickMessage.KickedBy);
Assert.Equal(channel, kickMessage.Channel);
Assert.Equal(nick, kickMessage.Nick);
Assert.Equal(comment, kickMessage.Comment);
}
[Fact]
public void TestRplWelcomeMessage()
{
var message = "Welcome!";
var raw = $":irc.netirc.net 001 netIRCTest :{message}";
var parsedIRCMessage = new ParsedIRCMessage(raw);
var rplWelcomeMessage = new RplWelcomeMessage(parsedIRCMessage);
Assert.Equal(message, rplWelcomeMessage.Text);
}
[Fact]
public void TestPassMessageTokens()
{
var password = "pass123";
var passMessage = new PassMessage(password);
Assert.Equal($"PASS {password}", passMessage.ToString());
}
[Fact]
public void ParserShouldTrimTrailing()
{
var raw = ":irc.netirc.net 353 netIRCTest = #NetIRC :netIRCTest @Fredi ";
var parsedIRCMessage = new ParsedIRCMessage(raw);
var rplNamReplyMessage = new RplNamReplyMessage(parsedIRCMessage);
Assert.Equal(2, rplNamReplyMessage.Nicks.Count);
}
}
public class TestClientMessage : IRCMessage, IClientMessage
{
IEnumerable<string> IClientMessage.Tokens => Enumerable.Empty<string>();
}
public class TestIRCMessage : IRCMessage
{
}
}
| 32.49422 | 110 | 0.567909 | [
"MIT"
] | fredimachado/NetIRC | tests/NetIRC.Tests/IRCMessageTests.cs | 11,245 | C# |
using SEDC.CSharpAdv.VideoRental.Data.Models;
using SEDC.CSharpAdv.VideoRental.Services.Helpers;
using SEDC.CSharpAdv.VideoRental.Services.Interfaces;
using SEDC.CSharpAdv.VideoRental.Services.Menus;
using SEDC.CSharpAdv.VideoRental.Services.Services;
using System;
namespace SEDC.CSharpAdv.VideoRental.App
{
class Program
{
static void Main(string[] args)
{
User user = null;
IUserService userService = new UserService();
IMovieService movieService = new MovieService();
#region Login/SignUp
Screen.HomeScreen();
bool isLoggedIn = false;
while (!isLoggedIn)
{
Screen.StartMenu();
int startMenuInput = InputParser.ToInteger(1, 3);
switch(startMenuInput)
{
case 1:
user = userService.Login();
if(user != null)
{
isLoggedIn = true;
}
break;
case 2:
user = userService.SignUp();
if (user != null)
{
isLoggedIn = true;
}
break;
case 3:
Environment.Exit(0);
break;
}
}
#endregion
while (true)
{
Screen.ClearScreen();
Screen.MainMenu(user.FullName);
var selection = InputParser.ToInteger(1, 4);
switch (selection)
{
case 1:
movieService.ViewMovieList(user);
break;
case 2:
userService.ViewRentedMovies(user);
break;
case 3:
//TODO:
break;
case 4:
default:
Environment.Exit(0);
break;
}
}
}
}
}
| 30.106667 | 65 | 0.399469 | [
"MIT"
] | sedc-codecademy/skwd9-net-06-csharpadv | G3/Class05/SEDC.CSharpAdv.VideoRental/SEDC.CSharpAdv.VideoRental.App/Program.cs | 2,260 | C# |
// <auto-generated> - Template:WebApiController, Version:1.1, Id:4b60314b-c212-46e3-8945-3d5daecee905
using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Net;
using System.Threading.Tasks;
using System.Web;
using System.Web.Http;
using System.Web.Http.Routing;
using Marvin.JsonPatch;
using cghEnums = CodeGenHero.Repository.Enums;
using CodeGenHero.DataService;
using CodeGenHero.Logging;
using CodeGenHero.Repository;
using CodeGenHero.Repository.AutoMapper;
using CodeGenHero.WebApi;
using CGH.QuikRide.Repository.Interface;
using dtoQR = CGH.QuikRide.DTO.QR;
using entQR = CGH.QuikRide.Repository.Entities.QR;
namespace CGH.QuikRide.API.Controllers.QR
{
public partial class LocationTypesQRController : QRBaseApiController
{
private const string GET_LIST_ROUTE_NAME = "LocationTypesQRList";
private const int maxPageSize = 100;
private GenericFactory<entQR.LocationType, dtoQR.LocationType> _factory
= new GenericFactory<entQR.LocationType, dtoQR.LocationType>();
public LocationTypesQRController() : base()
{
}
public LocationTypesQRController(ILoggingService log, IQRRepository repository)
: base(log, repository)
{
}
[HttpDelete]
[VersionedRoute(template: "LocationTypes/{locationTypeId}", allowedVersion: 1)]
public async Task<IHttpActionResult> Delete(int locationTypeId)
{
try
{
if (!base.OnActionExecuting(out HttpStatusCode httpStatusCode, out string message)) { return Content(httpStatusCode, message); }
var result = await Repo.Delete_LocationTypeAsync(locationTypeId);
if (result.Status == cghEnums.RepositoryActionStatus.Deleted)
{
return StatusCode(HttpStatusCode.NoContent);
}
else if (result.Status == cghEnums.RepositoryActionStatus.NotFound)
{
return NotFound();
}
Warn("Unable to delete object via Web API", LogMessageType.Instance.Warn_WebApi, result.Exception, httpResponseStatusCode: 400, url: Request.RequestUri.ToString());
return BadRequest();
}
catch (Exception ex)
{
Error(message: ex.Message, logMessageType: LogMessageType.Instance.Exception_WebApi, ex: ex);
if (System.Diagnostics.Debugger.IsAttached)
System.Diagnostics.Debugger.Break();
return InternalServerError();
}
}
[HttpGet]
[VersionedRoute(template: "LocationTypes", allowedVersion: 1, Name = GET_LIST_ROUTE_NAME)]
public async Task<IHttpActionResult> Get(string sort = null,
string fields = null, string filter = null, int page = 1, int pageSize = maxPageSize)
{
try
{
if (!base.OnActionExecuting(out HttpStatusCode httpStatusCode, out string message)) { return Content(httpStatusCode, message); }
var fieldList = GetListByDelimiter(fields);
bool childrenRequested = false; // TODO: set this based upon actual fields requested.
var filterList = GetListByDelimiter(filter);
var dbItems = Repo.GetQueryable_LocationType().AsNoTracking();
RunCustomLogicAfterGetQueryableList(ref dbItems, ref filterList);
dbItems = dbItems.ApplyFilter(filterList);
dbItems = dbItems.ApplySort(sort ?? (typeof(entQR.LocationType).GetProperties(System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Instance)).First().Name);
if (pageSize > maxPageSize)
{ // ensure the page size isn't larger than the maximum.
pageSize = maxPageSize;
}
var urlHelper = new UrlHelper(Request);
PageData paginationHeader = BuildPaginationHeader(urlHelper, GET_LIST_ROUTE_NAME, page: page, totalCount: dbItems.Count(), pageSize: pageSize, sort: sort);
HttpContext.Current.Response.Headers.Add("X-Pagination", Newtonsoft.Json.JsonConvert.SerializeObject(paginationHeader));
// return result
return Ok(dbItems
.Skip(pageSize * (page - 1))
.Take(pageSize)
.ToList()
.Select(x => _factory.CreateDataShapedObject(x, fieldList, childrenRequested)));
}
catch (Exception ex)
{
Error(message: ex.Message, logMessageType: LogMessageType.Instance.Exception_WebApi, ex: ex);
if (System.Diagnostics.Debugger.IsAttached)
System.Diagnostics.Debugger.Break();
return InternalServerError();
}
}
[HttpGet]
[VersionedRoute(template: "LocationTypes/{locationTypeId}/{numChildLevels:int=0}", allowedVersion: 1)]
public async Task<IHttpActionResult> Get(int locationTypeId, int numChildLevels)
{
try
{
if (!base.OnActionExecuting(out HttpStatusCode httpStatusCode, out string message)) { return Content(httpStatusCode, message); }
var dbItem = await Repo.Get_LocationTypeAsync(locationTypeId, numChildLevels);
if (dbItem == null)
{
Warn("Unable to get object via Web API", LogMessageType.Instance.Warn_WebApi, httpResponseStatusCode: 404, url: Request.RequestUri.ToString());
return NotFound();
}
RunCustomLogicOnGetEntityByPK(ref dbItem, locationTypeId, numChildLevels);
return Ok(_factory.Create(dbItem));
}
catch (Exception ex)
{
Error(message: ex.Message, logMessageType: LogMessageType.Instance.Exception_WebApi, ex: ex);
if (System.Diagnostics.Debugger.IsAttached)
System.Diagnostics.Debugger.Break();
return InternalServerError();
}
}
[HttpPatch]
[VersionedRoute(template: "LocationTypes/{locationTypeId}", allowedVersion: 1)]
public async Task<IHttpActionResult> Patch(int locationTypeId, [FromBody] JsonPatchDocument<dtoQR.LocationType> patchDocument)
{
try
{
if (!base.OnActionExecuting(out HttpStatusCode httpStatusCode, out string message)) { return Content(httpStatusCode, message); }
if (patchDocument == null)
{
return BadRequest();
}
var dbItem = await Repo.Get_LocationTypeAsync(locationTypeId, numChildLevels: 0);
if (dbItem == null)
{
return NotFound();
}
var dtoItem = _factory.Create(dbItem); // map
// apply changes to the DTO
patchDocument.ApplyTo(dtoItem);
dtoItem.LocationTypeId = locationTypeId;
// map the DTO with applied changes to the entity, & update
var updatedDBItem = _factory.Create(dtoItem); // map
var result = await Repo.UpdateAsync(updatedDBItem);
RunCustomLogicAfterUpdatePatch(ref updatedDBItem, ref result);
if (result.Status == cghEnums.RepositoryActionStatus.Updated)
{
// map to dto
var patchedDTOItem = _factory.Create(result.Entity);
return Ok(patchedDTOItem);
}
Warn("Unable to patch object via Web API", LogMessageType.Instance.Warn_WebApi, result.Exception, httpResponseStatusCode: 400, url: Request.RequestUri.ToString());
return BadRequest();
}
catch (Exception ex)
{
Error(message: ex.Message, logMessageType: LogMessageType.Instance.Exception_WebApi, ex: ex);
if (System.Diagnostics.Debugger.IsAttached)
System.Diagnostics.Debugger.Break();
return InternalServerError();
}
}
[HttpPost]
[VersionedRoute(template: "LocationTypes", allowedVersion: 1)]
public async Task<IHttpActionResult> Post([FromBody] dtoQR.LocationType dtoItem)
{
try
{
if (!base.OnActionExecuting(out HttpStatusCode httpStatusCode, out string message)) { return Content(httpStatusCode, message); }
if (dtoItem == null)
{
return BadRequest();
}
// try mapping & saving
var newDBItem = _factory.Create(dtoItem);
var result = await Repo.InsertAsync(newDBItem);
RunCustomLogicAfterInsert(ref newDBItem, ref result);
if (result.Status == cghEnums.RepositoryActionStatus.Created)
{ // map to dto
var newDTOItem = _factory.Create(result.Entity);
var uriFormatted = Request.RequestUri.ToString().EndsWith("/") == true ? Request.RequestUri.ToString().Substring(0, Request.RequestUri.ToString().Length - 1) : Request.RequestUri.ToString();
return Created($"{uriFormatted}/{newDTOItem.LocationTypeId}", newDTOItem);
}
Warn("Unable to create object via Web API", LogMessageType.Instance.Warn_WebApi, result.Exception, httpResponseStatusCode: 400, url: Request.RequestUri.ToString());
return BadRequest();
}
catch (Exception ex)
{
Error(message: ex.Message, logMessageType: LogMessageType.Instance.Exception_WebApi, ex: ex);
if (System.Diagnostics.Debugger.IsAttached)
System.Diagnostics.Debugger.Break();
return InternalServerError();
}
}
[HttpPut]
[VersionedRoute(template: "LocationTypes/{locationTypeId}", allowedVersion: 1)]
public async Task<IHttpActionResult> Put(int locationTypeId, [FromBody] dtoQR.LocationType dtoItem)
{
try
{
if (!base.OnActionExecuting(out HttpStatusCode httpStatusCode, out string message)) { return Content(httpStatusCode, message); }
if (dtoItem == null)
{
return BadRequest();
}
dtoItem.LocationTypeId = locationTypeId;
var updatedDBItem = _factory.Create(dtoItem); // map
var result = await Repo.UpdateAsync(updatedDBItem);
RunCustomLogicAfterUpdatePut(ref updatedDBItem, ref result);
if (result.Status == cghEnums.RepositoryActionStatus.Updated)
{
// map to dto
var updatedDTOItem = _factory.Create(result.Entity);
return Ok(updatedDTOItem);
}
else if (result.Status == cghEnums.RepositoryActionStatus.NotFound)
{
return NotFound();
}
Warn("Unable to update object via Web API", LogMessageType.Instance.Warn_WebApi, result.Exception, httpResponseStatusCode: 400, url: Request.RequestUri.ToString());
return BadRequest();
}
catch (Exception ex)
{
Error(message: ex.Message, logMessageType: LogMessageType.Instance.Exception_WebApi, ex: ex);
if (System.Diagnostics.Debugger.IsAttached)
System.Diagnostics.Debugger.Break();
return InternalServerError();
}
}
partial void RunCustomLogicAfterInsert(ref CGH.QuikRide.Repository.Entities.QR.LocationType newDBItem, ref IRepositoryActionResult<entQR.LocationType> result);
partial void RunCustomLogicAfterUpdatePatch(ref CGH.QuikRide.Repository.Entities.QR.LocationType updatedDBItem, ref IRepositoryActionResult<entQR.LocationType> result);
partial void RunCustomLogicAfterUpdatePut(ref CGH.QuikRide.Repository.Entities.QR.LocationType updatedDBItem, ref IRepositoryActionResult<entQR.LocationType> result);
partial void RunCustomLogicOnGetEntityByPK(ref entQR.LocationType dbItem, int locationTypeId, int numChildLevels);
partial void RunCustomLogicAfterGetQueryableList(ref IQueryable<entQR.LocationType> dbItems, ref List<string> filterList);
}
} | 35.665529 | 195 | 0.738756 | [
"MIT"
] | MSCTek/QuikRide | src/CGH.QuikRide.API/Controllers/QR/LocationTypesController.cs | 10,450 | C# |
using System;
using System.Collections.Generic;
using System.Configuration;
using System.IO;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;
using Grammophone.DataAccess;
using Grammophone.Domos.Accounting.Models;
using Grammophone.Domos.Domain.Accounting;
namespace Grammophone.Domos.Accounting
{
/// <summary>
/// Static class offering extension methods for
/// conversion between <see cref="BankAccountInfo"/>
/// and <see cref="EncryptedBankAccountInfo"/>.
/// </summary>
/// <remarks>
/// The encryption key is specified in the 'accountingEncryptionKey' and the
/// initialization vector in 'accountingEncryptionIV' entries
/// of section 'appSettings' in the application's configuration file,
/// written in base64 format.
/// </remarks>
public static class AccountingEncryption
{
#region Private fields
private static readonly Lazy<SymmetricAlgorithm> lazyEncryptionAlgorithm;
#endregion
#region Construction
/// <summary>
/// Static initialization.
/// </summary>
static AccountingEncryption()
{
lazyEncryptionAlgorithm = new Lazy<SymmetricAlgorithm>(
CreateEncryptionAlgorithm,
System.Threading.LazyThreadSafetyMode.PublicationOnly);
}
#endregion
#region Public methods
#region BankAccountInfo
/// <summary>
/// Decrypt a <see cref="EncryptedBankAccountInfo"/> into
/// a <see cref="BankAccountInfo"/>.
/// </summary>
/// <param name="encryptedBankAccountInfo">The bank account info to decrypt.</param>
public static BankAccountInfo Decrypt(
this EncryptedBankAccountInfo encryptedBankAccountInfo)
{
if (encryptedBankAccountInfo == null) throw new ArgumentNullException(nameof(encryptedBankAccountInfo));
return new BankAccountInfo
{
AccountCode = encryptedBankAccountInfo.AccountCode,
BankNumber = encryptedBankAccountInfo.BankNumber,
AccountNumber = DecryptString(encryptedBankAccountInfo.EncryptedAccountNumber),
TransitNumber = DecryptString(encryptedBankAccountInfo.EncryptedTransitNumber)
};
}
/// <summary>
/// Encrypt a <see cref="BankAccountInfo"/> into
/// an <see cref="EncryptedBankAccountInfo"/>.
/// </summary>
/// <param name="bankAccountInfo">The bank account info to encrypt.</param>
/// <param name="domainContainer">The domain container to create a proxy if necessary.</param>
/// <returns>
/// Returns an instance of a proxy to <see cref="EncryptedBankAccountInfo"/>
/// if <paramref name="domainContainer"/> has <see cref="IDomainContainer.IsProxyCreationEnabled"/>
/// set to true.
/// </returns>
public static EncryptedBankAccountInfo Encrypt(
this BankAccountInfo bankAccountInfo, IDomainContainer domainContainer)
{
if (bankAccountInfo == null) throw new ArgumentNullException(nameof(bankAccountInfo));
if (domainContainer == null) throw new ArgumentNullException(nameof(domainContainer));
var encryptedInfo = new EncryptedBankAccountInfo
{
BankNumber = bankAccountInfo.BankNumber,
AccountCode = bankAccountInfo.AccountCode,
EncryptedAccountNumber = EncryptString(bankAccountInfo.AccountNumber),
EncryptedTransitNumber = EncryptString(bankAccountInfo.TransitNumber)
};
return encryptedInfo;
}
/// <summary>
/// Clone an <see cref="EncryptedBankAccountInfo"/>.
/// </summary>
/// <param name="info">The bank account info to clone.</param>
/// <param name="domainContainer">The domain container to create a proxy if necessary.</param>
/// <returns>
/// Returns an instance of a proxy to <see cref="EncryptedBankAccountInfo"/>
/// if <paramref name="domainContainer"/> has <see cref="IDomainContainer.IsProxyCreationEnabled"/>
/// set to true.
/// </returns>
public static EncryptedBankAccountInfo Clone(
this EncryptedBankAccountInfo info, IDomainContainer domainContainer)
{
if (info == null) throw new ArgumentNullException(nameof(info));
if (domainContainer == null) throw new ArgumentNullException(nameof(domainContainer));
var clonedInfo = new EncryptedBankAccountInfo
{
AccountCode = info.AccountCode,
BankNumber = info.BankNumber,
EncryptedAccountNumber = info.EncryptedAccountNumber,
EncryptedTransitNumber = info.EncryptedTransitNumber
};
return clonedInfo;
}
#endregion
#region string
/// <summary>
/// Encrypt a string.
/// </summary>
/// <param name="value">The string to be encrypted.</param>
/// <returns>Returns the byte array of the encrypted string.</returns>
public static byte[] EncryptString(string value)
{
if (value == null) throw new ArgumentNullException(nameof(value));
var encryptor = lazyEncryptionAlgorithm.Value.CreateEncryptor();
using (var memoryStream = new MemoryStream())
{
using (var cryptoStream = new CryptoStream(memoryStream, encryptor, CryptoStreamMode.Write))
{
using (var writer = new StreamWriter(cryptoStream))
{
writer.Write(value);
}
return memoryStream.ToArray();
}
}
}
/// <summary>
/// Decrypt an encrypted string.
/// </summary>
/// <param name="encryptedText">The byte array holding the encrypted string.</param>
/// <returns>Returns the decrypted string.</returns>
public static string DecryptString(byte[] encryptedText)
{
if (encryptedText == null) return null;
var decryptor = lazyEncryptionAlgorithm.Value.CreateDecryptor();
using (var memoryStream = new MemoryStream(encryptedText))
{
using (var cryptoStream = new CryptoStream(memoryStream, decryptor, CryptoStreamMode.Read))
{
using (var reader = new StreamReader(cryptoStream))
{
return reader.ReadToEnd();
}
}
}
}
#endregion
#region decimal
/// <summary>
/// Encrypt a decimal value.
/// </summary>
/// <param name="value">The value to encrypt.</param>
/// <returns>Returns byte array of for the encrypted value.</returns>
public static byte[] EncryptDecimal(decimal value)
{
var encryptor = lazyEncryptionAlgorithm.Value.CreateEncryptor();
using (var memoryStream = new MemoryStream())
{
using (var cryptoStream = new CryptoStream(memoryStream, encryptor, CryptoStreamMode.Write))
{
using (var writer = new BinaryWriter(cryptoStream))
{
writer.Write(value);
}
return memoryStream.ToArray();
}
}
}
/// <summary>
/// Decrypt a decimal value.
/// </summary>
/// <param name="encryptedDecimal">The array of bytes holding the encrypted value.</param>
/// <returns>Returns the decrypted decimal.</returns>
public static decimal DecryptDecimal(byte[] encryptedDecimal)
{
var decryptor = lazyEncryptionAlgorithm.Value.CreateDecryptor();
using (var memoryStream = new MemoryStream(encryptedDecimal))
{
using (var cryptoStream = new CryptoStream(memoryStream, decryptor, CryptoStreamMode.Read))
{
using (var reader = new BinaryReader(cryptoStream))
{
return reader.ReadDecimal();
}
}
}
}
#endregion
#endregion
#region Private methods
/// <summary>
/// Create the encryption algorithm using the key and initializatio vector
/// specified in the application's configuration.
/// </summary>
/// <returns>Returns a symmetric encryption algorithm</returns>
/// <remarks>
/// See the remarks of <see cref="AccountingEncryption"/> for details about
/// configuration.
/// </remarks>
private static SymmetricAlgorithm CreateEncryptionAlgorithm()
{
string base64EncryptionKey = ConfigurationManager.AppSettings["accountingEncryptionKey"];
if (base64EncryptionKey == null)
throw new AccountingException(
"The 'accountingEncryptionKey' entry is missing from appSettings configuration section.");
string base64EncryptionIV = ConfigurationManager.AppSettings["accountingEncryptionIV"];
if (base64EncryptionIV == null)
throw new AccountingException(
"The 'accountingEncryptionIV' entry is missing from appSettings configuration section.");
byte[] key;
try
{
key = Convert.FromBase64String(base64EncryptionKey);
}
catch (FormatException ex)
{
throw new AccountingException(
"The 'accountingEncryptionKey' value in appSettings is not a valid base64 form.", ex);
}
byte[] iv;
try
{
iv = Convert.FromBase64String(base64EncryptionIV);
}
catch (FormatException ex)
{
throw new AccountingException(
"The 'accountingEncryptionIV' value in appSettings is not a valid base64 form.", ex);
}
var algorithm = new AesManaged();
algorithm.Key = key;
algorithm.IV = iv;
return algorithm;
}
#endregion
}
}
| 29.841379 | 107 | 0.715854 | [
"MIT"
] | grammophone/Grammophone.Domos.Accounting | AccountingEncryption.cs | 8,656 | C# |
using Rami.Wechat.Core.Comm;
using System;
using System.Collections.Generic;
using System.Security.Cryptography;
using System.Text;
using System.Xml;
namespace Rami.Wechat.Core.Merchant.Enterprise
{
/// <summary>
/// 企业支付数据(签名)
/// </summary>
public class EntPayData
{
/// <summary>
/// 支付配置
/// </summary>
private MerchantConf EntPayConf { get; set; }
/// <summary>
/// 构造方法
/// </summary>
public EntPayData()
{
this.EntPayConf = McPayConf.EntPayConf;
}
/// <summary>
/// 采用排序的Dictionary的好处是方便对数据包进行签名,不用再签名之前再做一次排序
/// </summary>
private SortedDictionary<string, object> m_values = new SortedDictionary<string, object>();
/// <summary>
/// 获取Dictionary
/// </summary>
/// <returns></returns>
public SortedDictionary<string, object> GetValues()
{
return m_values;
}
/// <summary>
/// 设置某个字段的值
/// </summary>
public void SetValue(string key, object value)
{
m_values[key] = value;
}
/// <summary>
/// 根据字段名获取某个字段的值
/// </summary>
public object GetValue(string key)
{
object o = null;
m_values.TryGetValue(key, out o);
return o;
}
/// <summary>
/// 获取字符串值
/// </summary>
/// <param name="key"></param>
/// <returns></returns>
public string GetAsStringValue(string key)
{
object o = null;
return m_values.TryGetValue(key, out o) ? o.ToString() : string.Empty;
}
/// <summary>
/// 判断某个字段是否已设置
/// </summary>
public bool IsSet(string key)
{
object o = null;
m_values.TryGetValue(key, out o);
if (null != o)
return true;
else
return false;
}
/// <summary>
/// 将Dictionary转成xml
/// </summary>
/// <returns></returns>
public string ToXml()
{
//数据为空时不能转化为xml格式
if (0 == m_values.Count)
{
WechatHelper.Log.Error("WxPayData数据为空!");
throw new Exception("WxPayData数据为空!");
}
string xml = "<xml>";
foreach (KeyValuePair<string, object> pair in m_values)
{
//字段值不能为null,会影响后续流程
if (pair.Value == null)
{
WechatHelper.Log.Error("WxPayData内部含有值为null的字段!");
throw new Exception(pair.Key + "为null的字段!");
}
if (pair.Value.GetType() == typeof(int))
{
xml += "<" + pair.Key + ">" + pair.Value + "</" + pair.Key + ">";
}
else if (pair.Value.GetType() == typeof(string))
{
//xml += "<" + pair.Key + ">" + "<![CDATA[" + pair.Value + "]]></" + pair.Key + ">";
xml += "<" + pair.Key + ">" + "" + pair.Value + "</" + pair.Key + ">";
}
else
{
//除了string和int类型不能含有其他数据类型
WechatHelper.Log.Error("WxPayData字段数据类型错误!");
throw new Exception("WxPayData字段数据类型错误!");
}
}
xml += "</xml>";
return xml;
}
/// <summary>
/// 将xml转为WxPayData对象并返回对象内部的数据
/// </summary>
/// <param name="xml"></param>
/// <returns></returns>
public SortedDictionary<string, object> FromXml(string xml)
{
if (string.IsNullOrEmpty(xml))
{
//WechatHelper.Log.Error("将空的xml串转换为WxPayData不合法!");
throw new Exception("将空的xml串转换为WxPayData不合法!");
}
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.LoadXml(xml);
XmlNode xmlNode = xmlDoc.FirstChild;//获取到根节点<xml>
XmlNodeList nodes = xmlNode.ChildNodes;
foreach (XmlNode xn in nodes)
{
XmlElement xe = (XmlElement)xn;
m_values[xe.Name] = xe.InnerText;//获取xml的键值对到WxPayData内部的数据中
}
try
{
//2015-06-29 错误是没有签名
if (m_values["return_code"].ToString() != "SUCCESS")
{
return m_values;
}
//CheckSign();//验证签名,不通过会抛异常 sign不会返回
}
catch (Exception ex)
{
throw new Exception(ex.Message);
}
return m_values;
}
/// <summary>
/// Dictionary格式转化成url参数格式
/// </summary>
public string ToUrl()
{
string buff = "";
foreach (KeyValuePair<string, object> pair in m_values)
{
if (pair.Value == null)
{
WechatHelper.Log.Error("WxPayData内部含有值为null的字段!");
throw new Exception("WxPayData内部含有值为null的字段!");
}
if (pair.Key != "sign" && pair.Value.ToString() != "")
{
buff += pair.Key + "=" + pair.Value + "&";
}
}
buff = buff.Trim('&');
return buff;
}
/// <summary>
/// Dictionary格式化成Json
/// </summary>
public string ToJson()
{
return SerializeHelper.JsonSerialize(m_values);
}
/// <summary>
/// 微信支付签名
/// </summary>
public string MakeSignWx()
{
//转url格式
string str = ToUrl();
//在string后加入API KEY
str += "&key=" + EntPayConf.PayKey;
//MD5加密
var md5 = MD5.Create();
var bs = md5.ComputeHash(Encoding.UTF8.GetBytes(str));
var sb = new StringBuilder();
foreach (byte b in bs)
{
sb.Append(b.ToString("x2"));
}
//所有字符转为大写
return sb.ToString().ToUpper();
}
/// <summary>
/// 企业支付签名
/// </summary>
/// <param name="type">1:红包;2:收/收款</param>
/// <returns></returns>
public string MakeSignQy(int type = 1)
{
// 红包签名
var lstNeeds = new List<string>();
if (type == 1)
{
lstNeeds = new List<string> { "act_name", "mch_billno", "mch_id", "nonce_str", "re_openid", "total_amount", "wxappid" };
}
else if (type == 2)
{
lstNeeds = new List<string> { "amount", "appid", "desc", "mch_id", "nonce_str", "openid", "partner_trade_no", "ww_msg_type" };
}
string str = string.Empty;
foreach (var key in lstNeeds)
{
if (m_values.ContainsKey(key))
{
str += key + "=" + m_values[key].ToString() + "&";
}
}
str = str.TrimEnd('&');
//在string后加入API KEY
str += "&secret=" + EntPayConf.PaySecret;
//MD5加密
var md5 = MD5.Create();
var bs = md5.ComputeHash(Encoding.UTF8.GetBytes(str));
var sb = new StringBuilder();
foreach (byte b in bs)
{
sb.Append(b.ToString("x2"));
}
//所有字符转为大写
return sb.ToString().ToUpper();
}
///// <summary>
///// 检测签名是否正确
///// </summary>
//public bool CheckSign()
//{
// //如果没有设置签名,则跳过检测
// if (!IsSet("sign"))
// {
// //WechatHelper.Log.Error("WxPayData签名存在但不合法!");
// throw new Exception("WxPayData签名存在但不合法!");
// }
// //如果设置了签名但是签名为空,则抛异常
// else if (GetValue("sign") == null || GetValue("sign").ToString() == "")
// {
// //WechatHelper.Log.Error("WxPayData签名存在但不合法!");
// throw new Exception("WxPayData签名存在但不合法!");
// }
// //获取接收到的签名
// string return_sign = GetValue("sign").ToString();
// //在本地计算新的签名
// string cal_sign = MakeSign();
// if (cal_sign == return_sign)
// {
// return true;
// }
// //WechatHelper.Log.Error("WxPayData签名验证错误!");
// throw new Exception("WxPayData签名验证错误!");
//}
}
}
| 29.12709 | 142 | 0.439316 | [
"MIT"
] | tamakiramimy/Rami.Wechat.Core | Rami.Wechat.Core/Merchant/Enterprise/EntPayData.cs | 9,579 | C# |
using System;
using System.Globalization;
using System.Text;
namespace MCCompilerConsole.Converter
{
/// <summary>
/// トークンベース
/// </summary>
public class TokenBase
{
public enum ValueKind
{
INT,
FLOAT,
INVALID,
}
public TokenBase(int kind, ValueKind valueType = ValueKind.INVALID, int valueI = 0, float valueF = 0.0f, int strIdx = 0, int strLen = 0, TokenBase nextToke = null)
{
this._kind = kind;
this.ValueType = valueType;
this.ValueI = valueI;
this.ValueF = valueF;
this.StrIdx = strIdx;
this.StrLen = strLen;
this.Next = nextToke;
}
public int _kind { get; set; } // 種類
public ValueKind ValueType { get; set; }//
public int ValueI { get; set; } // kindが整数の場合は値
public float ValueF { get; set; } // kindが不動小数点数の場合は値
public int StrIdx { get; set; } // トークンの文字位置のインデックス
public int StrLen { get; set; } // トークンの文字の長さ
public TokenBase Next { get; set; } // 次のトークン
}
/// <summary>
/// トークナイズ結果
/// </summary>
public class TokenizeResult : ResultBase
{
public override void Initialize()
{
base.Initialize();
HeadToken = null;
}
public void Set(bool success, TokenBase headToken)
{
this.Success = success;
this.HeadToken = headToken;
}
public TokenBase HeadToken { get; set; }
}
public class TokenizerBase
{
protected enum BaseNumber
{
Binary = 2,
Decimal = 10,
Hexadecimal = 16,
}
protected enum GetNumericError
{
None,
Success,
FormatDifferent,
MinOrMax,
}
protected TokenBase headToke; // トークンリストの先頭
protected TokenBase currentToken; // 現在のトークン
protected TokenizeResult result; // トークナイズ結果
protected StringInfo strInfo;
protected int strInfoIdx;
protected int sourceIdx;
protected bool isError;
static private readonly string[] Numerices =
{
"0", "1", "2", "3", "4", "5", "6", "7", "8", "9",
};
static private readonly string[] AvailableNumricesCharacter =
{
"0", "1", "2", "3", "4", "5", "6", "7", "8", "9",
"a", "A", "b" , "B", "c", "C", "d", "D", "e", "E", "f", "F",
".", "_"
};
static private readonly string[] BinaryNumbers =
{
"0", "1", "_"
};
static private readonly string[] DecimalNumbers =
{
"0", "1", "2", "3", "4", "5", "6", "7", "8", "9",
};
static private readonly string[] HexadecimalNumbers =
{
"0", "1", "2", "3", "4", "5", "6", "7", "8", "9",
"a", "A", "b" , "B", "c", "C", "d", "D", "e", "E", "f", "F",
};
static private readonly string[] FloatNumbers =
{
"0", "1", "2", "3", "4", "5", "6", "7", "8", "9", ".", "f", "F"
};
static private readonly string[] NewLine =
{
"\n", "\r", "\r\n"
};
protected bool isExisArray(string[] array, string str)
{
foreach (var s in array)
{
if (s == str)
{
return true;
}
}
return false;
}
private bool isUnicodeCategory(UnicodeCategory uc, string str)
{
UnicodeCategory _uc = CharUnicodeInfo.GetUnicodeCategory(str, 0);
return _uc == uc;
}
protected bool IsNumerices(string str) { return isExisArray(Numerices, str); }
protected bool IsAvailableNumricesCharacter(string str) { return isExisArray(AvailableNumricesCharacter, str); }
protected bool IsBinaryNumber(string str) { return isExisArray(BinaryNumbers, str); }
protected bool IsDecimalNumber(string str) { return isExisArray(DecimalNumbers, str); }
protected bool IsHexadecimalNumber(string str) { return isExisArray(HexadecimalNumbers, str); }
protected bool IsFloatNumbers(string str) { return isExisArray(FloatNumbers, str); }
protected bool IsNewLine(string str) { return isExisArray(NewLine, str); }
protected bool IsControlOrSpace(string str) { return IsControl(str) || IsUnicodeSpace(str); }
protected bool IsControl(string str) { return isUnicodeCategory(UnicodeCategory.Control, str); }
protected bool IsUnicodeSpace(string str)
{
return isUnicodeCategory(UnicodeCategory.SpaceSeparator, str)
|| isUnicodeCategory(UnicodeCategory.LineSeparator, str)
|| isUnicodeCategory(UnicodeCategory.ParagraphSeparator, str);
}
protected delegate bool Delimiter(string str);
/// <summary>
/// コンストラクタ
/// </summary>
public TokenizerBase()
{
headToke = null;
currentToken = null;
result = new TokenizeResult();
strInfo = null;
strInfoIdx = 0;
sourceIdx = 0;
isError = false;
}
/// <summary>
/// StringInfoの設定
/// </summary>
/// <param name="bytes">設定Bytes</param>
protected void SetStrInfo(byte[] bytes)
{
string utf8Source = Encoding.UTF8.GetString(bytes);
strInfo = new StringInfo(utf8Source);
}
/// <summary>
/// トークンの作成
/// </summary>
/// <param name="kind">トークンの種類</param>
/// <param name="strIdx">ソース内のインデックス</param>
/// <param name="strLen">トークンの文字数</param>
/// <returns></returns>
virtual protected TokenBase NewToken(int kind, int strIdx, int strLen)
{
return null;
}
/// <summary>
/// 数の取得
/// </summary>
/// <param name="str">チェック開始文字</param>
/// <returns>エラー状態、トークン</returns>
protected (GetNumericError error, TokenBase token) GetNumeric(string str)
{
if (IsNumerices(str))
{
TokenBase token = NewToken(0, sourceIdx, 0);
// 接頭辞
// 2進数 0b
// 16進数 0x
TokenBase.ValueKind valueKind = TokenBase.ValueKind.INT;
int valueI = 0;
float valueF = 0.0f;
string number = "";
bool isFloat = false;
BaseNumber fromBase = BaseNumber.Decimal;
string str2 = GetStrInfoStringTwo();
if (str2 != "")
{
// 先頭の文字で 2進数か10進数か16進数かわかる
if (str2 == "0b" || str2 == "0B")
{
// 2進数
fromBase = BaseNumber.Binary;
NextStrInfo(2); // 二文字文進める
}
else if (str2 == "0x" || str2 == "0X")
{
// 16進数
fromBase = BaseNumber.Hexadecimal;
NextStrInfo(2); // 二文字文進める
}
}
// 2進数は 0 & 1 & _
// 10進数は 0 ~ 9
// 16進数は 0 ~ 9 & a ~ F
// floatは 0 ~ 0 & .
bool isError = false;
string lastStr = "";
for (str = lastStr = GetStrInfoStringOne(); IsAvailableNumricesCharacter(str); NextStrInfo(1), str = lastStr = GetStrInfoStringOne())
{
number += str;
if (isFloat)
{
isError = !IsFloatNumbers(str);
}
else
{
if (str == ".")
{
if (fromBase == BaseNumber.Decimal)
{
isFloat = true;
continue;
}
isError = true;
}
if (str == "f" || str == "F")
{
if (fromBase == BaseNumber.Decimal)
{
isFloat = true;
continue;
}
else if (fromBase == BaseNumber.Hexadecimal)
{
continue;
}
isError = true;
}
switch (fromBase)
{
case BaseNumber.Binary: isError = !IsBinaryNumber(str); break;
case BaseNumber.Decimal: isError = !IsDecimalNumber(str); break;
case BaseNumber.Hexadecimal: isError = !IsHexadecimalNumber(str); break;
}
}
if (isError)
{
token.StrLen = sourceIdx - token.StrIdx;
return (GetNumericError.FormatDifferent, token);
}
}
// 16進数ではなく最後の文字が「f」or「F」ならば不動小数点数
// 2進数指定だった場合はエラー
if (lastStr == "f" || lastStr == "F")
{
if (fromBase == BaseNumber.Decimal)
{
isFloat = true;
}
if (fromBase == BaseNumber.Binary)
{
return (GetNumericError.FormatDifferent, null);
}
}
try
{
if (isFloat)
{
number = number.Replace('f', '\0');
number = number.Replace('F', '\0');
valueF = Convert.ToSingle(number);
valueKind = TokenBase.ValueKind.FLOAT;
}
else
{
valueI = Convert.ToInt32(number, (int)fromBase);
}
}
catch (FormatException)
{
// フォーマットが違う
token.StrLen = sourceIdx - token.StrIdx;
return (GetNumericError.FormatDifferent, token);
}
catch (OverflowException)
{
// MinValue 未満の数値か、MaxValue より大きい数値を表します。
token.StrLen = sourceIdx - token.StrIdx;
return (GetNumericError.MinOrMax, token);
}
token.ValueType = valueKind;
token.ValueI = valueI;
token.ValueF = valueF;
token.StrLen = sourceIdx - token.StrIdx; // sourceIdxとtoken.StrIdxの差異から文字の長さ求める
return (GetNumericError.Success, token);
}
return (GetNumericError.None, null);
}
/// <summary>
/// Asciiの制御文字とスペースの読み飛ばし
/// </summary>
/// <param name="str">開始文字</param>
/// <returns>true:読み飛ばした</returns>
protected bool SkipSpaceControlChar(string str)
{
// 空白・制御・改行文字はスキップする
if (IsControlOrSpace(str) || IsNewLine(str))
{
NextStrInfo(1);
return true;
}
return false;
}
/// <summary>
/// 1行コメントの読み飛ばし
/// </summary>
/// <param name="str">開始文字</param>
/// <returns>true:1行コメントを読み飛ばした</returns>
protected bool SkipLineComment(string str)
{
// 1行コメントの読み飛ばし
if (str == "//")
{
NextStrInfo(2); // 二文字文進む
str = GetStrInfoStringOne();
while (!IsNewLine(str) && str != "")
{
NextStrInfo(1); // 一文字文進む
str = GetStrInfoStringOne();
}
return true;
}
return false;
}
/// <summary>
/// ブロックコメントの読み飛ばし
/// </summary>
/// <param name="str">開始文字</param>
/// <returns>true:ブロックコメントを読み飛ばした</returns>
protected bool SkipBlockComment(string str)
{
// 複数行コメントの読み飛ばし
if (str == "/*")
{
NextStrInfo(2); // /*の二文字文進む
str = GetStrInfoStringTwo();
while (str != "*/" && str != "")
{
NextStrInfo(1); // 一文字文進む
str = GetStrInfoStringTwo();
}
NextStrInfo(2); // */の二文字文進む
return true;
}
return false;
}
/// <summary>
/// 指定予約語なのかチェック
/// </summary>
/// <param name="array">指定予約語達</param>
/// <param name="delimiter">区切り文字判定関数</param>
/// <returns>arrayの番号、-1:見つからなかった</returns>
protected int GetReserveWords((string word, int kind)[] array, Delimiter delimiter)
{
for(int i = 0; i < array.Length; i++)
{
// 予約語と完全一致
// -> return (予約語) と returnx (ユーザー定義の識別子)とを分けるため
// -> 予約語の後の文字が識別子を構成する文字ではないことを確認する
string word = GetStrInfoString(array[i].word.Length);
string nextchar = GetStrInfoString(strInfoIdx + array[i].word.Length, 1);
if (word == array[i].word && delimiter(nextchar))
{
return i;
}
}
return -1;
}
/// <summary>
/// 識別子の取得
/// </summary>
/// <param name="delimiter">区切り文字判定関数</param>
/// <param name="str">開始文字</param>
/// <returns>識別子の文字数</returns>
protected TokenBase GetIdentifier(Delimiter delimiter, string str)
{
if (!delimiter(str))
{
currentToken = NewToken(0, sourceIdx, 0);
int strLen = 0;
{
str = GetStrInfoStringOne();
while (!IsControlOrSpace(str) && !delimiter(str) && str != "")
{
strLen += GetStrByteLength(str);
NextStrInfo(1);
str = GetStrInfoStringOne();
}
}
currentToken.StrLen = strLen;
return currentToken;
}
return null;
}
/// <summary>
/// 文字列の取得
/// </summary>
/// <returns>文字列の文字数(バイト)</returns>
protected TokenBase GetString(string str)
{
// 文字列
if (str == "\"")
{
NextStrInfo(1);
int startIdx = sourceIdx;
int strLen = 0;
{
str = GetStrInfoStringOne();
while (str != "\"" && str != "")
{
strLen += GetStrByteLength(str);
NextStrInfo(1);
str = GetStrInfoStringOne();
}
if (str == "")
{
strLen = 0;
}
NextStrInfo(1); // "文字文進める(文字列の終わり"まで読み進める)
}
return NewToken(0, startIdx, strLen);
}
return null;
}
/// <summary>
/// strinfoから1文字取得
/// </summary>
/// <returns>文字</returns>
protected string GetStrInfoStringOne()
{
return GetStrInfoString(1);
}
/// <summary>
/// strinfoから2文字取得
/// </summary>
/// <returns>文字</returns>
protected string GetStrInfoStringTwo()
{
return GetStrInfoString(2);
}
/// <summary>
/// stringoから文字取得
/// </summary>
/// <param name="length">取得文字数</param>
/// <returns>文字</returns>
protected string GetStrInfoString(int length)
{
return GetStrInfoString(strInfoIdx, length);
}
/// <summary>
/// stringoから文字取得
/// </summary>
/// <param name="idx">取得開始文字</param>
/// <param name="length">取得文字数</param>
/// <returns>文字</returns>
protected string GetStrInfoString(int idx, int length)
{
int Max = Math.Min(idx + length, strInfo.LengthInTextElements);
int len = Max - idx;
if (idx < 0 || idx >= strInfo.LengthInTextElements)
{
return "";
}
if (idx + len > strInfo.LengthInTextElements)
{
return "";
}
return strInfo.SubstringByTextElements(idx, len);
}
/// <summary>
/// 次の文字に進む
/// </summary>
/// <param name="next">進む文字数</param>
protected void NextStrInfo(int next)
{
string str = GetStrInfoString(next);
int byteLength = GetStrByteLength(str);
strInfoIdx += next;
sourceIdx += byteLength;
}
/// <summary>
/// UTF8文字のバイトサイズを取得
/// </summary>
/// <param name="str">UTF8文字</param>
/// <returns>バイトサイズ</returns>
protected int GetStrByteLength(string str)
{
return Encoding.UTF8.GetBytes(str).Length;
}
/// <summary>
/// エラートークンの取得
/// </summary>
/// <returns>エラートークン</returns>
protected string GetErrorToken()
{
string str = GetStrInfoStringOne();
while (str != "")
{
// 空白文字はスキップする
if (IsControlOrSpace(str))
{
NextStrInfo(1);
str = GetStrInfoStringOne();
continue;
}
break;
}
return str;
}
/// <summary>
/// 初期化処理
/// </summary>
protected void Initialize(TokenBase token)
{
headToke = token;
currentToken = null;
result.Initialize();
isError = false;
strInfo = null;
strInfoIdx = 0;
sourceIdx = 0;
}
}
} | 32.365352 | 171 | 0.432243 | [
"MIT"
] | dennissato/MCCompilerConsole | Converter/TokenizerBase.cs | 20,347 | C# |
// *** WARNING: this file was generated by the Pulumi SDK Generator. ***
// *** Do not edit by hand unless you're certain you know what you are doing! ***
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Threading.Tasks;
using Pulumi.Serialization;
namespace Pulumi.AzureNextGen.Network.V20190601
{
public static class GetSecurityRule
{
public static Task<GetSecurityRuleResult> InvokeAsync(GetSecurityRuleArgs args, InvokeOptions? options = null)
=> Pulumi.Deployment.Instance.InvokeAsync<GetSecurityRuleResult>("azure-nextgen:network/v20190601:getSecurityRule", args ?? new GetSecurityRuleArgs(), options.WithVersion());
}
public sealed class GetSecurityRuleArgs : Pulumi.InvokeArgs
{
/// <summary>
/// The name of the network security group.
/// </summary>
[Input("networkSecurityGroupName", required: true)]
public string NetworkSecurityGroupName { get; set; } = null!;
/// <summary>
/// The name of the resource group.
/// </summary>
[Input("resourceGroupName", required: true)]
public string ResourceGroupName { get; set; } = null!;
/// <summary>
/// The name of the security rule.
/// </summary>
[Input("securityRuleName", required: true)]
public string SecurityRuleName { get; set; } = null!;
public GetSecurityRuleArgs()
{
}
}
[OutputType]
public sealed class GetSecurityRuleResult
{
/// <summary>
/// The network traffic is allowed or denied.
/// </summary>
public readonly string Access;
/// <summary>
/// A description for this rule. Restricted to 140 chars.
/// </summary>
public readonly string? Description;
/// <summary>
/// The destination address prefix. CIDR or destination IP range. Asterisk '*' can also be used to match all source IPs. Default tags such as 'VirtualNetwork', 'AzureLoadBalancer' and 'Internet' can also be used.
/// </summary>
public readonly string? DestinationAddressPrefix;
/// <summary>
/// The destination address prefixes. CIDR or destination IP ranges.
/// </summary>
public readonly ImmutableArray<string> DestinationAddressPrefixes;
/// <summary>
/// The application security group specified as destination.
/// </summary>
public readonly ImmutableArray<Outputs.ApplicationSecurityGroupResponse> DestinationApplicationSecurityGroups;
/// <summary>
/// The destination port or range. Integer or range between 0 and 65535. Asterisk '*' can also be used to match all ports.
/// </summary>
public readonly string? DestinationPortRange;
/// <summary>
/// The destination port ranges.
/// </summary>
public readonly ImmutableArray<string> DestinationPortRanges;
/// <summary>
/// The direction of the rule. The direction specifies if rule will be evaluated on incoming or outgoing traffic.
/// </summary>
public readonly string Direction;
/// <summary>
/// A unique read-only string that changes whenever the resource is updated.
/// </summary>
public readonly string? Etag;
/// <summary>
/// The name of the resource that is unique within a resource group. This name can be used to access the resource.
/// </summary>
public readonly string? Name;
/// <summary>
/// The priority of the rule. The value can be between 100 and 4096. The priority number must be unique for each rule in the collection. The lower the priority number, the higher the priority of the rule.
/// </summary>
public readonly int? Priority;
/// <summary>
/// Network protocol this rule applies to.
/// </summary>
public readonly string Protocol;
/// <summary>
/// The provisioning state of the public IP resource. Possible values are: 'Updating', 'Deleting', and 'Failed'.
/// </summary>
public readonly string? ProvisioningState;
/// <summary>
/// The CIDR or source IP range. Asterisk '*' can also be used to match all source IPs. Default tags such as 'VirtualNetwork', 'AzureLoadBalancer' and 'Internet' can also be used. If this is an ingress rule, specifies where network traffic originates from.
/// </summary>
public readonly string? SourceAddressPrefix;
/// <summary>
/// The CIDR or source IP ranges.
/// </summary>
public readonly ImmutableArray<string> SourceAddressPrefixes;
/// <summary>
/// The application security group specified as source.
/// </summary>
public readonly ImmutableArray<Outputs.ApplicationSecurityGroupResponse> SourceApplicationSecurityGroups;
/// <summary>
/// The source port or range. Integer or range between 0 and 65535. Asterisk '*' can also be used to match all ports.
/// </summary>
public readonly string? SourcePortRange;
/// <summary>
/// The source port ranges.
/// </summary>
public readonly ImmutableArray<string> SourcePortRanges;
[OutputConstructor]
private GetSecurityRuleResult(
string access,
string? description,
string? destinationAddressPrefix,
ImmutableArray<string> destinationAddressPrefixes,
ImmutableArray<Outputs.ApplicationSecurityGroupResponse> destinationApplicationSecurityGroups,
string? destinationPortRange,
ImmutableArray<string> destinationPortRanges,
string direction,
string? etag,
string? name,
int? priority,
string protocol,
string? provisioningState,
string? sourceAddressPrefix,
ImmutableArray<string> sourceAddressPrefixes,
ImmutableArray<Outputs.ApplicationSecurityGroupResponse> sourceApplicationSecurityGroups,
string? sourcePortRange,
ImmutableArray<string> sourcePortRanges)
{
Access = access;
Description = description;
DestinationAddressPrefix = destinationAddressPrefix;
DestinationAddressPrefixes = destinationAddressPrefixes;
DestinationApplicationSecurityGroups = destinationApplicationSecurityGroups;
DestinationPortRange = destinationPortRange;
DestinationPortRanges = destinationPortRanges;
Direction = direction;
Etag = etag;
Name = name;
Priority = priority;
Protocol = protocol;
ProvisioningState = provisioningState;
SourceAddressPrefix = sourceAddressPrefix;
SourceAddressPrefixes = sourceAddressPrefixes;
SourceApplicationSecurityGroups = sourceApplicationSecurityGroups;
SourcePortRange = sourcePortRange;
SourcePortRanges = sourcePortRanges;
}
}
}
| 39.9 | 264 | 0.640351 | [
"Apache-2.0"
] | test-wiz-sec/pulumi-azure-nextgen | sdk/dotnet/Network/V20190601/GetSecurityRule.cs | 7,182 | C# |
using InputSubsystem;
namespace ParserSubsystem
{
public interface IParser<in TS, out TE> where TS: ISymbol where TE: IExpression
{
public TE Parse(IInput<TS> input);
}
} | 21.222222 | 83 | 0.691099 | [
"Apache-2.0"
] | romarioGI/diploma | source/ParserSubsystem/IParser.cs | 191 | C# |
// <auto-generated>
// Generated by the protocol buffer compiler. DO NOT EDIT!
// source: google/cloud/speech/v1/resource.proto
// </auto-generated>
#pragma warning disable 1591, 0612, 3021
#region Designer generated code
using pb = global::Google.Protobuf;
using pbc = global::Google.Protobuf.Collections;
using pbr = global::Google.Protobuf.Reflection;
using scg = global::System.Collections.Generic;
namespace Google.Cloud.Speech.V1 {
/// <summary>Holder for reflection information generated from google/cloud/speech/v1/resource.proto</summary>
public static partial class ResourceReflection {
#region Descriptor
/// <summary>File descriptor for google/cloud/speech/v1/resource.proto</summary>
public static pbr::FileDescriptor Descriptor {
get { return descriptor; }
}
private static pbr::FileDescriptor descriptor;
static ResourceReflection() {
byte[] descriptorData = global::System.Convert.FromBase64String(
string.Concat(
"CiVnb29nbGUvY2xvdWQvc3BlZWNoL3YxL3Jlc291cmNlLnByb3RvEhZnb29n",
"bGUuY2xvdWQuc3BlZWNoLnYxGhlnb29nbGUvYXBpL3Jlc291cmNlLnByb3Rv",
"IvwBCgtDdXN0b21DbGFzcxIMCgRuYW1lGAEgASgJEhcKD2N1c3RvbV9jbGFz",
"c19pZBgCIAEoCRI8CgVpdGVtcxgDIAMoCzItLmdvb2dsZS5jbG91ZC5zcGVl",
"Y2gudjEuQ3VzdG9tQ2xhc3MuQ2xhc3NJdGVtGhoKCUNsYXNzSXRlbRINCgV2",
"YWx1ZRgBIAEoCTps6kFpCiFzcGVlY2guZ29vZ2xlYXBpcy5jb20vQ3VzdG9t",
"Q2xhc3MSRHByb2plY3RzL3twcm9qZWN0fS9sb2NhdGlvbnMve2xvY2F0aW9u",
"fS9jdXN0b21DbGFzc2VzL3tjdXN0b21fY2xhc3N9IvIBCglQaHJhc2VTZXQS",
"DAoEbmFtZRgBIAEoCRI5CgdwaHJhc2VzGAIgAygLMiguZ29vZ2xlLmNsb3Vk",
"LnNwZWVjaC52MS5QaHJhc2VTZXQuUGhyYXNlEg0KBWJvb3N0GAQgASgCGiYK",
"BlBocmFzZRINCgV2YWx1ZRgBIAEoCRINCgVib29zdBgCIAEoAjpl6kFiCh9z",
"cGVlY2guZ29vZ2xlYXBpcy5jb20vUGhyYXNlU2V0Ej9wcm9qZWN0cy97cHJv",
"amVjdH0vbG9jYXRpb25zL3tsb2NhdGlvbn0vcGhyYXNlU2V0cy97cGhyYXNl",
"X3NldH0izAEKEFNwZWVjaEFkYXB0YXRpb24SNgoLcGhyYXNlX3NldHMYASAD",
"KAsyIS5nb29nbGUuY2xvdWQuc3BlZWNoLnYxLlBocmFzZVNldBJDChVwaHJh",
"c2Vfc2V0X3JlZmVyZW5jZXMYAiADKAlCJPpBIQofc3BlZWNoLmdvb2dsZWFw",
"aXMuY29tL1BocmFzZVNldBI7Cg5jdXN0b21fY2xhc3NlcxgDIAMoCzIjLmdv",
"b2dsZS5jbG91ZC5zcGVlY2gudjEuQ3VzdG9tQ2xhc3NCegoaY29tLmdvb2ds",
"ZS5jbG91ZC5zcGVlY2gudjFCE1NwZWVjaFJlc291cmNlUHJvdG9QAVo8Z29v",
"Z2xlLmdvbGFuZy5vcmcvZ2VucHJvdG8vZ29vZ2xlYXBpcy9jbG91ZC9zcGVl",
"Y2gvdjE7c3BlZWNo+AEBogIDR0NTYgZwcm90bzM="));
descriptor = pbr::FileDescriptor.FromGeneratedCode(descriptorData,
new pbr::FileDescriptor[] { global::Google.Api.ResourceReflection.Descriptor, },
new pbr::GeneratedClrTypeInfo(null, null, new pbr::GeneratedClrTypeInfo[] {
new pbr::GeneratedClrTypeInfo(typeof(global::Google.Cloud.Speech.V1.CustomClass), global::Google.Cloud.Speech.V1.CustomClass.Parser, new[]{ "Name", "CustomClassId", "Items" }, null, null, null, new pbr::GeneratedClrTypeInfo[] { new pbr::GeneratedClrTypeInfo(typeof(global::Google.Cloud.Speech.V1.CustomClass.Types.ClassItem), global::Google.Cloud.Speech.V1.CustomClass.Types.ClassItem.Parser, new[]{ "Value" }, null, null, null, null)}),
new pbr::GeneratedClrTypeInfo(typeof(global::Google.Cloud.Speech.V1.PhraseSet), global::Google.Cloud.Speech.V1.PhraseSet.Parser, new[]{ "Name", "Phrases", "Boost" }, null, null, null, new pbr::GeneratedClrTypeInfo[] { new pbr::GeneratedClrTypeInfo(typeof(global::Google.Cloud.Speech.V1.PhraseSet.Types.Phrase), global::Google.Cloud.Speech.V1.PhraseSet.Types.Phrase.Parser, new[]{ "Value", "Boost" }, null, null, null, null)}),
new pbr::GeneratedClrTypeInfo(typeof(global::Google.Cloud.Speech.V1.SpeechAdaptation), global::Google.Cloud.Speech.V1.SpeechAdaptation.Parser, new[]{ "PhraseSets", "PhraseSetReferences", "CustomClasses" }, null, null, null, null)
}));
}
#endregion
}
#region Messages
/// <summary>
/// A set of words or phrases that represents a common concept likely to appear
/// in your audio, for example a list of passenger ship names. CustomClass items
/// can be substituted into placeholders that you set in PhraseSet phrases.
/// </summary>
public sealed partial class CustomClass : pb::IMessage<CustomClass>
#if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE
, pb::IBufferMessage
#endif
{
private static readonly pb::MessageParser<CustomClass> _parser = new pb::MessageParser<CustomClass>(() => new CustomClass());
private pb::UnknownFieldSet _unknownFields;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public static pb::MessageParser<CustomClass> Parser { get { return _parser; } }
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public static pbr::MessageDescriptor Descriptor {
get { return global::Google.Cloud.Speech.V1.ResourceReflection.Descriptor.MessageTypes[0]; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
pbr::MessageDescriptor pb::IMessage.Descriptor {
get { return Descriptor; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public CustomClass() {
OnConstruction();
}
partial void OnConstruction();
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public CustomClass(CustomClass other) : this() {
name_ = other.name_;
customClassId_ = other.customClassId_;
items_ = other.items_.Clone();
_unknownFields = pb::UnknownFieldSet.Clone(other._unknownFields);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public CustomClass Clone() {
return new CustomClass(this);
}
/// <summary>Field number for the "name" field.</summary>
public const int NameFieldNumber = 1;
private string name_ = "";
/// <summary>
/// The resource name of the custom class.
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public string Name {
get { return name_; }
set {
name_ = pb::ProtoPreconditions.CheckNotNull(value, "value");
}
}
/// <summary>Field number for the "custom_class_id" field.</summary>
public const int CustomClassIdFieldNumber = 2;
private string customClassId_ = "";
/// <summary>
/// If this custom class is a resource, the custom_class_id is the resource id
/// of the CustomClass. Case sensitive.
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public string CustomClassId {
get { return customClassId_; }
set {
customClassId_ = pb::ProtoPreconditions.CheckNotNull(value, "value");
}
}
/// <summary>Field number for the "items" field.</summary>
public const int ItemsFieldNumber = 3;
private static readonly pb::FieldCodec<global::Google.Cloud.Speech.V1.CustomClass.Types.ClassItem> _repeated_items_codec
= pb::FieldCodec.ForMessage(26, global::Google.Cloud.Speech.V1.CustomClass.Types.ClassItem.Parser);
private readonly pbc::RepeatedField<global::Google.Cloud.Speech.V1.CustomClass.Types.ClassItem> items_ = new pbc::RepeatedField<global::Google.Cloud.Speech.V1.CustomClass.Types.ClassItem>();
/// <summary>
/// A collection of class items.
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public pbc::RepeatedField<global::Google.Cloud.Speech.V1.CustomClass.Types.ClassItem> Items {
get { return items_; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public override bool Equals(object other) {
return Equals(other as CustomClass);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public bool Equals(CustomClass other) {
if (ReferenceEquals(other, null)) {
return false;
}
if (ReferenceEquals(other, this)) {
return true;
}
if (Name != other.Name) return false;
if (CustomClassId != other.CustomClassId) return false;
if(!items_.Equals(other.items_)) return false;
return Equals(_unknownFields, other._unknownFields);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public override int GetHashCode() {
int hash = 1;
if (Name.Length != 0) hash ^= Name.GetHashCode();
if (CustomClassId.Length != 0) hash ^= CustomClassId.GetHashCode();
hash ^= items_.GetHashCode();
if (_unknownFields != null) {
hash ^= _unknownFields.GetHashCode();
}
return hash;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public override string ToString() {
return pb::JsonFormatter.ToDiagnosticString(this);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public void WriteTo(pb::CodedOutputStream output) {
#if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE
output.WriteRawMessage(this);
#else
if (Name.Length != 0) {
output.WriteRawTag(10);
output.WriteString(Name);
}
if (CustomClassId.Length != 0) {
output.WriteRawTag(18);
output.WriteString(CustomClassId);
}
items_.WriteTo(output, _repeated_items_codec);
if (_unknownFields != null) {
_unknownFields.WriteTo(output);
}
#endif
}
#if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
void pb::IBufferMessage.InternalWriteTo(ref pb::WriteContext output) {
if (Name.Length != 0) {
output.WriteRawTag(10);
output.WriteString(Name);
}
if (CustomClassId.Length != 0) {
output.WriteRawTag(18);
output.WriteString(CustomClassId);
}
items_.WriteTo(ref output, _repeated_items_codec);
if (_unknownFields != null) {
_unknownFields.WriteTo(ref output);
}
}
#endif
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public int CalculateSize() {
int size = 0;
if (Name.Length != 0) {
size += 1 + pb::CodedOutputStream.ComputeStringSize(Name);
}
if (CustomClassId.Length != 0) {
size += 1 + pb::CodedOutputStream.ComputeStringSize(CustomClassId);
}
size += items_.CalculateSize(_repeated_items_codec);
if (_unknownFields != null) {
size += _unknownFields.CalculateSize();
}
return size;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public void MergeFrom(CustomClass other) {
if (other == null) {
return;
}
if (other.Name.Length != 0) {
Name = other.Name;
}
if (other.CustomClassId.Length != 0) {
CustomClassId = other.CustomClassId;
}
items_.Add(other.items_);
_unknownFields = pb::UnknownFieldSet.MergeFrom(_unknownFields, other._unknownFields);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public void MergeFrom(pb::CodedInputStream input) {
#if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE
input.ReadRawMessage(this);
#else
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
_unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input);
break;
case 10: {
Name = input.ReadString();
break;
}
case 18: {
CustomClassId = input.ReadString();
break;
}
case 26: {
items_.AddEntriesFrom(input, _repeated_items_codec);
break;
}
}
}
#endif
}
#if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
void pb::IBufferMessage.InternalMergeFrom(ref pb::ParseContext input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
_unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, ref input);
break;
case 10: {
Name = input.ReadString();
break;
}
case 18: {
CustomClassId = input.ReadString();
break;
}
case 26: {
items_.AddEntriesFrom(ref input, _repeated_items_codec);
break;
}
}
}
}
#endif
#region Nested types
/// <summary>Container for nested types declared in the CustomClass message type.</summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public static partial class Types {
/// <summary>
/// An item of the class.
/// </summary>
public sealed partial class ClassItem : pb::IMessage<ClassItem>
#if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE
, pb::IBufferMessage
#endif
{
private static readonly pb::MessageParser<ClassItem> _parser = new pb::MessageParser<ClassItem>(() => new ClassItem());
private pb::UnknownFieldSet _unknownFields;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public static pb::MessageParser<ClassItem> Parser { get { return _parser; } }
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public static pbr::MessageDescriptor Descriptor {
get { return global::Google.Cloud.Speech.V1.CustomClass.Descriptor.NestedTypes[0]; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
pbr::MessageDescriptor pb::IMessage.Descriptor {
get { return Descriptor; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public ClassItem() {
OnConstruction();
}
partial void OnConstruction();
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public ClassItem(ClassItem other) : this() {
value_ = other.value_;
_unknownFields = pb::UnknownFieldSet.Clone(other._unknownFields);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public ClassItem Clone() {
return new ClassItem(this);
}
/// <summary>Field number for the "value" field.</summary>
public const int ValueFieldNumber = 1;
private string value_ = "";
/// <summary>
/// The class item's value.
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public string Value {
get { return value_; }
set {
value_ = pb::ProtoPreconditions.CheckNotNull(value, "value");
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public override bool Equals(object other) {
return Equals(other as ClassItem);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public bool Equals(ClassItem other) {
if (ReferenceEquals(other, null)) {
return false;
}
if (ReferenceEquals(other, this)) {
return true;
}
if (Value != other.Value) return false;
return Equals(_unknownFields, other._unknownFields);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public override int GetHashCode() {
int hash = 1;
if (Value.Length != 0) hash ^= Value.GetHashCode();
if (_unknownFields != null) {
hash ^= _unknownFields.GetHashCode();
}
return hash;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public override string ToString() {
return pb::JsonFormatter.ToDiagnosticString(this);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public void WriteTo(pb::CodedOutputStream output) {
#if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE
output.WriteRawMessage(this);
#else
if (Value.Length != 0) {
output.WriteRawTag(10);
output.WriteString(Value);
}
if (_unknownFields != null) {
_unknownFields.WriteTo(output);
}
#endif
}
#if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
void pb::IBufferMessage.InternalWriteTo(ref pb::WriteContext output) {
if (Value.Length != 0) {
output.WriteRawTag(10);
output.WriteString(Value);
}
if (_unknownFields != null) {
_unknownFields.WriteTo(ref output);
}
}
#endif
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public int CalculateSize() {
int size = 0;
if (Value.Length != 0) {
size += 1 + pb::CodedOutputStream.ComputeStringSize(Value);
}
if (_unknownFields != null) {
size += _unknownFields.CalculateSize();
}
return size;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public void MergeFrom(ClassItem other) {
if (other == null) {
return;
}
if (other.Value.Length != 0) {
Value = other.Value;
}
_unknownFields = pb::UnknownFieldSet.MergeFrom(_unknownFields, other._unknownFields);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public void MergeFrom(pb::CodedInputStream input) {
#if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE
input.ReadRawMessage(this);
#else
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
_unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input);
break;
case 10: {
Value = input.ReadString();
break;
}
}
}
#endif
}
#if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
void pb::IBufferMessage.InternalMergeFrom(ref pb::ParseContext input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
_unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, ref input);
break;
case 10: {
Value = input.ReadString();
break;
}
}
}
}
#endif
}
}
#endregion
}
/// <summary>
/// Provides "hints" to the speech recognizer to favor specific words and phrases
/// in the results.
/// </summary>
public sealed partial class PhraseSet : pb::IMessage<PhraseSet>
#if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE
, pb::IBufferMessage
#endif
{
private static readonly pb::MessageParser<PhraseSet> _parser = new pb::MessageParser<PhraseSet>(() => new PhraseSet());
private pb::UnknownFieldSet _unknownFields;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public static pb::MessageParser<PhraseSet> Parser { get { return _parser; } }
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public static pbr::MessageDescriptor Descriptor {
get { return global::Google.Cloud.Speech.V1.ResourceReflection.Descriptor.MessageTypes[1]; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
pbr::MessageDescriptor pb::IMessage.Descriptor {
get { return Descriptor; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public PhraseSet() {
OnConstruction();
}
partial void OnConstruction();
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public PhraseSet(PhraseSet other) : this() {
name_ = other.name_;
phrases_ = other.phrases_.Clone();
boost_ = other.boost_;
_unknownFields = pb::UnknownFieldSet.Clone(other._unknownFields);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public PhraseSet Clone() {
return new PhraseSet(this);
}
/// <summary>Field number for the "name" field.</summary>
public const int NameFieldNumber = 1;
private string name_ = "";
/// <summary>
/// The resource name of the phrase set.
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public string Name {
get { return name_; }
set {
name_ = pb::ProtoPreconditions.CheckNotNull(value, "value");
}
}
/// <summary>Field number for the "phrases" field.</summary>
public const int PhrasesFieldNumber = 2;
private static readonly pb::FieldCodec<global::Google.Cloud.Speech.V1.PhraseSet.Types.Phrase> _repeated_phrases_codec
= pb::FieldCodec.ForMessage(18, global::Google.Cloud.Speech.V1.PhraseSet.Types.Phrase.Parser);
private readonly pbc::RepeatedField<global::Google.Cloud.Speech.V1.PhraseSet.Types.Phrase> phrases_ = new pbc::RepeatedField<global::Google.Cloud.Speech.V1.PhraseSet.Types.Phrase>();
/// <summary>
/// A list of word and phrases.
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public pbc::RepeatedField<global::Google.Cloud.Speech.V1.PhraseSet.Types.Phrase> Phrases {
get { return phrases_; }
}
/// <summary>Field number for the "boost" field.</summary>
public const int BoostFieldNumber = 4;
private float boost_;
/// <summary>
/// Hint Boost. Positive value will increase the probability that a specific
/// phrase will be recognized over other similar sounding phrases. The higher
/// the boost, the higher the chance of false positive recognition as well.
/// Negative boost values would correspond to anti-biasing. Anti-biasing is not
/// enabled, so negative boost will simply be ignored. Though `boost` can
/// accept a wide range of positive values, most use cases are best served with
/// values between 0 (exclusive) and 20. We recommend using a binary search
/// approach to finding the optimal value for your use case. Speech recognition
/// will skip PhraseSets with a boost value of 0.
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public float Boost {
get { return boost_; }
set {
boost_ = value;
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public override bool Equals(object other) {
return Equals(other as PhraseSet);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public bool Equals(PhraseSet other) {
if (ReferenceEquals(other, null)) {
return false;
}
if (ReferenceEquals(other, this)) {
return true;
}
if (Name != other.Name) return false;
if(!phrases_.Equals(other.phrases_)) return false;
if (!pbc::ProtobufEqualityComparers.BitwiseSingleEqualityComparer.Equals(Boost, other.Boost)) return false;
return Equals(_unknownFields, other._unknownFields);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public override int GetHashCode() {
int hash = 1;
if (Name.Length != 0) hash ^= Name.GetHashCode();
hash ^= phrases_.GetHashCode();
if (Boost != 0F) hash ^= pbc::ProtobufEqualityComparers.BitwiseSingleEqualityComparer.GetHashCode(Boost);
if (_unknownFields != null) {
hash ^= _unknownFields.GetHashCode();
}
return hash;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public override string ToString() {
return pb::JsonFormatter.ToDiagnosticString(this);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public void WriteTo(pb::CodedOutputStream output) {
#if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE
output.WriteRawMessage(this);
#else
if (Name.Length != 0) {
output.WriteRawTag(10);
output.WriteString(Name);
}
phrases_.WriteTo(output, _repeated_phrases_codec);
if (Boost != 0F) {
output.WriteRawTag(37);
output.WriteFloat(Boost);
}
if (_unknownFields != null) {
_unknownFields.WriteTo(output);
}
#endif
}
#if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
void pb::IBufferMessage.InternalWriteTo(ref pb::WriteContext output) {
if (Name.Length != 0) {
output.WriteRawTag(10);
output.WriteString(Name);
}
phrases_.WriteTo(ref output, _repeated_phrases_codec);
if (Boost != 0F) {
output.WriteRawTag(37);
output.WriteFloat(Boost);
}
if (_unknownFields != null) {
_unknownFields.WriteTo(ref output);
}
}
#endif
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public int CalculateSize() {
int size = 0;
if (Name.Length != 0) {
size += 1 + pb::CodedOutputStream.ComputeStringSize(Name);
}
size += phrases_.CalculateSize(_repeated_phrases_codec);
if (Boost != 0F) {
size += 1 + 4;
}
if (_unknownFields != null) {
size += _unknownFields.CalculateSize();
}
return size;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public void MergeFrom(PhraseSet other) {
if (other == null) {
return;
}
if (other.Name.Length != 0) {
Name = other.Name;
}
phrases_.Add(other.phrases_);
if (other.Boost != 0F) {
Boost = other.Boost;
}
_unknownFields = pb::UnknownFieldSet.MergeFrom(_unknownFields, other._unknownFields);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public void MergeFrom(pb::CodedInputStream input) {
#if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE
input.ReadRawMessage(this);
#else
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
_unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input);
break;
case 10: {
Name = input.ReadString();
break;
}
case 18: {
phrases_.AddEntriesFrom(input, _repeated_phrases_codec);
break;
}
case 37: {
Boost = input.ReadFloat();
break;
}
}
}
#endif
}
#if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
void pb::IBufferMessage.InternalMergeFrom(ref pb::ParseContext input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
_unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, ref input);
break;
case 10: {
Name = input.ReadString();
break;
}
case 18: {
phrases_.AddEntriesFrom(ref input, _repeated_phrases_codec);
break;
}
case 37: {
Boost = input.ReadFloat();
break;
}
}
}
}
#endif
#region Nested types
/// <summary>Container for nested types declared in the PhraseSet message type.</summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public static partial class Types {
/// <summary>
/// A phrases containing words and phrase "hints" so that
/// the speech recognition is more likely to recognize them. This can be used
/// to improve the accuracy for specific words and phrases, for example, if
/// specific commands are typically spoken by the user. This can also be used
/// to add additional words to the vocabulary of the recognizer. See
/// [usage limits](https://cloud.google.com/speech-to-text/quotas#content).
///
/// List items can also include pre-built or custom classes containing groups
/// of words that represent common concepts that occur in natural language. For
/// example, rather than providing a phrase hint for every month of the
/// year (e.g. "i was born in january", "i was born in febuary", ...), use the
/// pre-built `$MONTH` class improves the likelihood of correctly transcribing
/// audio that includes months (e.g. "i was born in $month").
/// To refer to pre-built classes, use the class' symbol prepended with `$`
/// e.g. `$MONTH`. To refer to custom classes that were defined inline in the
/// request, set the class's `custom_class_id` to a string unique to all class
/// resources and inline classes. Then use the class' id wrapped in $`{...}`
/// e.g. "${my-months}". To refer to custom classes resources, use the class'
/// id wrapped in `${}` (e.g. `${my-months}`).
///
/// Speech-to-Text supports three locations: `global`, `us` (US North America),
/// and `eu` (Europe). If you are calling the `speech.googleapis.com`
/// endpoint, use the `global` location. To specify a region, use a
/// [regional endpoint](/speech-to-text/docs/endpoints) with matching `us` or
/// `eu` location value.
/// </summary>
public sealed partial class Phrase : pb::IMessage<Phrase>
#if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE
, pb::IBufferMessage
#endif
{
private static readonly pb::MessageParser<Phrase> _parser = new pb::MessageParser<Phrase>(() => new Phrase());
private pb::UnknownFieldSet _unknownFields;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public static pb::MessageParser<Phrase> Parser { get { return _parser; } }
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public static pbr::MessageDescriptor Descriptor {
get { return global::Google.Cloud.Speech.V1.PhraseSet.Descriptor.NestedTypes[0]; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
pbr::MessageDescriptor pb::IMessage.Descriptor {
get { return Descriptor; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public Phrase() {
OnConstruction();
}
partial void OnConstruction();
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public Phrase(Phrase other) : this() {
value_ = other.value_;
boost_ = other.boost_;
_unknownFields = pb::UnknownFieldSet.Clone(other._unknownFields);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public Phrase Clone() {
return new Phrase(this);
}
/// <summary>Field number for the "value" field.</summary>
public const int ValueFieldNumber = 1;
private string value_ = "";
/// <summary>
/// The phrase itself.
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public string Value {
get { return value_; }
set {
value_ = pb::ProtoPreconditions.CheckNotNull(value, "value");
}
}
/// <summary>Field number for the "boost" field.</summary>
public const int BoostFieldNumber = 2;
private float boost_;
/// <summary>
/// Hint Boost. Overrides the boost set at the phrase set level.
/// Positive value will increase the probability that a specific phrase will
/// be recognized over other similar sounding phrases. The higher the boost,
/// the higher the chance of false positive recognition as well. Negative
/// boost will simply be ignored. Though `boost` can accept a wide range of
/// positive values, most use cases are best served
/// with values between 0 and 20. We recommend using a binary search approach
/// to finding the optimal value for your use case. Speech recognition
/// will skip PhraseSets with a boost value of 0.
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public float Boost {
get { return boost_; }
set {
boost_ = value;
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public override bool Equals(object other) {
return Equals(other as Phrase);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public bool Equals(Phrase other) {
if (ReferenceEquals(other, null)) {
return false;
}
if (ReferenceEquals(other, this)) {
return true;
}
if (Value != other.Value) return false;
if (!pbc::ProtobufEqualityComparers.BitwiseSingleEqualityComparer.Equals(Boost, other.Boost)) return false;
return Equals(_unknownFields, other._unknownFields);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public override int GetHashCode() {
int hash = 1;
if (Value.Length != 0) hash ^= Value.GetHashCode();
if (Boost != 0F) hash ^= pbc::ProtobufEqualityComparers.BitwiseSingleEqualityComparer.GetHashCode(Boost);
if (_unknownFields != null) {
hash ^= _unknownFields.GetHashCode();
}
return hash;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public override string ToString() {
return pb::JsonFormatter.ToDiagnosticString(this);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public void WriteTo(pb::CodedOutputStream output) {
#if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE
output.WriteRawMessage(this);
#else
if (Value.Length != 0) {
output.WriteRawTag(10);
output.WriteString(Value);
}
if (Boost != 0F) {
output.WriteRawTag(21);
output.WriteFloat(Boost);
}
if (_unknownFields != null) {
_unknownFields.WriteTo(output);
}
#endif
}
#if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
void pb::IBufferMessage.InternalWriteTo(ref pb::WriteContext output) {
if (Value.Length != 0) {
output.WriteRawTag(10);
output.WriteString(Value);
}
if (Boost != 0F) {
output.WriteRawTag(21);
output.WriteFloat(Boost);
}
if (_unknownFields != null) {
_unknownFields.WriteTo(ref output);
}
}
#endif
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public int CalculateSize() {
int size = 0;
if (Value.Length != 0) {
size += 1 + pb::CodedOutputStream.ComputeStringSize(Value);
}
if (Boost != 0F) {
size += 1 + 4;
}
if (_unknownFields != null) {
size += _unknownFields.CalculateSize();
}
return size;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public void MergeFrom(Phrase other) {
if (other == null) {
return;
}
if (other.Value.Length != 0) {
Value = other.Value;
}
if (other.Boost != 0F) {
Boost = other.Boost;
}
_unknownFields = pb::UnknownFieldSet.MergeFrom(_unknownFields, other._unknownFields);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public void MergeFrom(pb::CodedInputStream input) {
#if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE
input.ReadRawMessage(this);
#else
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
_unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input);
break;
case 10: {
Value = input.ReadString();
break;
}
case 21: {
Boost = input.ReadFloat();
break;
}
}
}
#endif
}
#if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
void pb::IBufferMessage.InternalMergeFrom(ref pb::ParseContext input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
_unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, ref input);
break;
case 10: {
Value = input.ReadString();
break;
}
case 21: {
Boost = input.ReadFloat();
break;
}
}
}
}
#endif
}
}
#endregion
}
/// <summary>
/// Speech adaptation configuration.
/// </summary>
public sealed partial class SpeechAdaptation : pb::IMessage<SpeechAdaptation>
#if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE
, pb::IBufferMessage
#endif
{
private static readonly pb::MessageParser<SpeechAdaptation> _parser = new pb::MessageParser<SpeechAdaptation>(() => new SpeechAdaptation());
private pb::UnknownFieldSet _unknownFields;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public static pb::MessageParser<SpeechAdaptation> Parser { get { return _parser; } }
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public static pbr::MessageDescriptor Descriptor {
get { return global::Google.Cloud.Speech.V1.ResourceReflection.Descriptor.MessageTypes[2]; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
pbr::MessageDescriptor pb::IMessage.Descriptor {
get { return Descriptor; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public SpeechAdaptation() {
OnConstruction();
}
partial void OnConstruction();
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public SpeechAdaptation(SpeechAdaptation other) : this() {
phraseSets_ = other.phraseSets_.Clone();
phraseSetReferences_ = other.phraseSetReferences_.Clone();
customClasses_ = other.customClasses_.Clone();
_unknownFields = pb::UnknownFieldSet.Clone(other._unknownFields);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public SpeechAdaptation Clone() {
return new SpeechAdaptation(this);
}
/// <summary>Field number for the "phrase_sets" field.</summary>
public const int PhraseSetsFieldNumber = 1;
private static readonly pb::FieldCodec<global::Google.Cloud.Speech.V1.PhraseSet> _repeated_phraseSets_codec
= pb::FieldCodec.ForMessage(10, global::Google.Cloud.Speech.V1.PhraseSet.Parser);
private readonly pbc::RepeatedField<global::Google.Cloud.Speech.V1.PhraseSet> phraseSets_ = new pbc::RepeatedField<global::Google.Cloud.Speech.V1.PhraseSet>();
/// <summary>
/// A collection of phrase sets. To specify the hints inline, leave the
/// phrase set's `name` blank and fill in the rest of its fields. Any
/// phrase set can use any custom class.
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public pbc::RepeatedField<global::Google.Cloud.Speech.V1.PhraseSet> PhraseSets {
get { return phraseSets_; }
}
/// <summary>Field number for the "phrase_set_references" field.</summary>
public const int PhraseSetReferencesFieldNumber = 2;
private static readonly pb::FieldCodec<string> _repeated_phraseSetReferences_codec
= pb::FieldCodec.ForString(18);
private readonly pbc::RepeatedField<string> phraseSetReferences_ = new pbc::RepeatedField<string>();
/// <summary>
/// A collection of phrase set resource names to use.
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public pbc::RepeatedField<string> PhraseSetReferences {
get { return phraseSetReferences_; }
}
/// <summary>Field number for the "custom_classes" field.</summary>
public const int CustomClassesFieldNumber = 3;
private static readonly pb::FieldCodec<global::Google.Cloud.Speech.V1.CustomClass> _repeated_customClasses_codec
= pb::FieldCodec.ForMessage(26, global::Google.Cloud.Speech.V1.CustomClass.Parser);
private readonly pbc::RepeatedField<global::Google.Cloud.Speech.V1.CustomClass> customClasses_ = new pbc::RepeatedField<global::Google.Cloud.Speech.V1.CustomClass>();
/// <summary>
/// A collection of custom classes. To specify the classes inline, leave the
/// class' `name` blank and fill in the rest of its fields, giving it a unique
/// `custom_class_id`. Refer to the inline defined class in phrase hints by its
/// `custom_class_id`.
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public pbc::RepeatedField<global::Google.Cloud.Speech.V1.CustomClass> CustomClasses {
get { return customClasses_; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public override bool Equals(object other) {
return Equals(other as SpeechAdaptation);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public bool Equals(SpeechAdaptation other) {
if (ReferenceEquals(other, null)) {
return false;
}
if (ReferenceEquals(other, this)) {
return true;
}
if(!phraseSets_.Equals(other.phraseSets_)) return false;
if(!phraseSetReferences_.Equals(other.phraseSetReferences_)) return false;
if(!customClasses_.Equals(other.customClasses_)) return false;
return Equals(_unknownFields, other._unknownFields);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public override int GetHashCode() {
int hash = 1;
hash ^= phraseSets_.GetHashCode();
hash ^= phraseSetReferences_.GetHashCode();
hash ^= customClasses_.GetHashCode();
if (_unknownFields != null) {
hash ^= _unknownFields.GetHashCode();
}
return hash;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public override string ToString() {
return pb::JsonFormatter.ToDiagnosticString(this);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public void WriteTo(pb::CodedOutputStream output) {
#if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE
output.WriteRawMessage(this);
#else
phraseSets_.WriteTo(output, _repeated_phraseSets_codec);
phraseSetReferences_.WriteTo(output, _repeated_phraseSetReferences_codec);
customClasses_.WriteTo(output, _repeated_customClasses_codec);
if (_unknownFields != null) {
_unknownFields.WriteTo(output);
}
#endif
}
#if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
void pb::IBufferMessage.InternalWriteTo(ref pb::WriteContext output) {
phraseSets_.WriteTo(ref output, _repeated_phraseSets_codec);
phraseSetReferences_.WriteTo(ref output, _repeated_phraseSetReferences_codec);
customClasses_.WriteTo(ref output, _repeated_customClasses_codec);
if (_unknownFields != null) {
_unknownFields.WriteTo(ref output);
}
}
#endif
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public int CalculateSize() {
int size = 0;
size += phraseSets_.CalculateSize(_repeated_phraseSets_codec);
size += phraseSetReferences_.CalculateSize(_repeated_phraseSetReferences_codec);
size += customClasses_.CalculateSize(_repeated_customClasses_codec);
if (_unknownFields != null) {
size += _unknownFields.CalculateSize();
}
return size;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public void MergeFrom(SpeechAdaptation other) {
if (other == null) {
return;
}
phraseSets_.Add(other.phraseSets_);
phraseSetReferences_.Add(other.phraseSetReferences_);
customClasses_.Add(other.customClasses_);
_unknownFields = pb::UnknownFieldSet.MergeFrom(_unknownFields, other._unknownFields);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public void MergeFrom(pb::CodedInputStream input) {
#if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE
input.ReadRawMessage(this);
#else
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
_unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input);
break;
case 10: {
phraseSets_.AddEntriesFrom(input, _repeated_phraseSets_codec);
break;
}
case 18: {
phraseSetReferences_.AddEntriesFrom(input, _repeated_phraseSetReferences_codec);
break;
}
case 26: {
customClasses_.AddEntriesFrom(input, _repeated_customClasses_codec);
break;
}
}
}
#endif
}
#if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
void pb::IBufferMessage.InternalMergeFrom(ref pb::ParseContext input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
_unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, ref input);
break;
case 10: {
phraseSets_.AddEntriesFrom(ref input, _repeated_phraseSets_codec);
break;
}
case 18: {
phraseSetReferences_.AddEntriesFrom(ref input, _repeated_phraseSetReferences_codec);
break;
}
case 26: {
customClasses_.AddEntriesFrom(ref input, _repeated_customClasses_codec);
break;
}
}
}
}
#endif
}
#endregion
}
#endregion Designer generated code
| 39.852632 | 449 | 0.654196 | [
"Apache-2.0"
] | GoogleCloudPlatform/google-cloud-dotnet | apis/Google.Cloud.Speech.V1/Google.Cloud.Speech.V1/Resource.g.cs | 53,004 | C# |
using FluentAssertions;
using System;
using System.Linq.Expressions;
using System.Reflection;
namespace ESFA.DC.ILR.Model.Tests.Abstract
{
public class AbstractModelTests<T> where T : new()
{
protected DateTime DateTime()
{
return new DateTime(2018, 1, 1);
}
protected long Long()
{
return 12345678910;
}
protected decimal Decimal()
{
return 1.234M;
}
protected T TestNullableSpecifiedTrue<TValue, TNullable>(Expression<Func<T, TValue>> propertyExpression, TValue value, Expression<Func<T, bool>> specifiedPropertyExpression, Expression<Func<T, TNullable>> nullablePropertyExpression)
{
var modelObject = new T();
Set(modelObject, propertyExpression, value);
Set(modelObject, specifiedPropertyExpression, true);
var nullable = Get(modelObject, nullablePropertyExpression);
nullable.Should().Be(value);
nullable.Should().NotBeNull();
return modelObject;
}
protected T TestNullableSpecifiedFalse<TValue, TNullable>(Expression<Func<T, TValue>> propertyExpression, TValue value, Expression<Func<T, bool>> specifiedPropertyExpression, Expression<Func<T, TNullable>> nullablePropertyExpression)
{
var modelObject = new T();
Set(modelObject, propertyExpression, value);
Set(modelObject, specifiedPropertyExpression, false);
var nullable = Get(modelObject, nullablePropertyExpression);
nullable.Should().BeNull();
return modelObject;
}
private T Set<TValue>(T input, Expression<Func<T, TValue>> expression, TValue value)
{
MemberExpression body = expression.Body as MemberExpression;
if (body == null)
{
throw new ArgumentException("The provided lambda expression '" + expression.Body + "' must refer to a property of : " + typeof(T).Name);
}
PropertyInfo member = body.Member as PropertyInfo;
if (member == null)
{
throw new ArgumentException("The provided lambda expression '" + body.Member + "' must refer to a property of : " + typeof(T).Name);
}
member.SetValue(input, value, null);
return input;
}
private TValue Get<TValue>(T input, Expression<Func<T, TValue>> expression)
{
MemberExpression body = expression.Body as MemberExpression;
if (body == null)
{
throw new ArgumentException("The provided lambda expression '" + expression.Body + "' must refer to a property of : " + typeof(T).Name);
}
PropertyInfo member = body.Member as PropertyInfo;
if (member == null)
{
throw new ArgumentException("The provided lambda expression '" + body.Member + "' must refer to a property of : " + typeof(T).Name);
}
return (TValue)member.GetValue(input);
}
}
}
| 33.221053 | 241 | 0.595057 | [
"MIT"
] | SkillsFundingAgency/DC-ILR-1718-Model | src/ESFA.DC.ILR.Model.Tests/Abstract/AbstractModelTests.cs | 3,158 | C# |
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System.Linq;
using System.Net.Http;
using System.Web.Http.Controllers;
using System.Web.Http.OData.Routing;
using System.Web.Http.OData.Routing.Conventions;
namespace NuGet.Server.V2.OData.Conventions
{
/// <summary>
/// Maps /$count on an Action to an action method called ActionCount().
/// </summary>
public class ActionCountRoutingConvention
: IODataRoutingConvention
{
private readonly string _controllerName;
public ActionCountRoutingConvention(string controllerName)
{
_controllerName = controllerName;
}
public string SelectController(ODataPath odataPath, HttpRequestMessage request)
{
if (odataPath.PathTemplate == "~/action/$count")
{
return _controllerName;
}
return null;
}
public string SelectAction(ODataPath odataPath, HttpControllerContext controllerContext, ILookup<string, HttpActionDescriptor> actionMap)
{
if (odataPath.PathTemplate != "~/action/$count")
{
return null;
}
var actionSegment = odataPath.Segments.OfType<ActionPathSegment>().Single();
var action = actionSegment.Action;
if (action.IsBindable)
{
return null;
}
var actionName = action.Name + "Count";
if (actionMap.Contains(actionName) && actionMap[actionName].Any(desc => MatchHttpMethod(desc, controllerContext.Request.Method)))
{
return actionName;
}
return null;
}
private static bool MatchHttpMethod(HttpActionDescriptor desc, HttpMethod method)
{
var supportedMethods = desc.ActionBinding.ActionDescriptor.SupportedHttpMethods;
return supportedMethods.Contains(method);
}
}
} | 33.142857 | 145 | 0.624521 | [
"ECL-2.0",
"Apache-2.0"
] | 563256676/test2 | src/NuGet.Server.V2/OData/Conventions/ActionCountRoutingConvention.cs | 2,088 | C# |
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Collections.Generic;
using System.Globalization;
using Microsoft.Extensions.Logging.Internal;
namespace Microsoft.Extensions.Logging
{
/// <summary>
/// ILogger extension methods for common scenarios.
/// </summary>
public static class LoggerExtensions
{
private static readonly Func<FormattedLogValues, Exception, string> _messageFormatter = MessageFormatter;
//------------------------------------------DEBUG------------------------------------------//
/// <summary>
/// Formats and writes a debug log message.
/// </summary>
/// <param name="logger">The <see cref="ILogger"/> to write to.</param>
/// <param name="eventId">The event id associated with the log.</param>
/// <param name="exception">The exception to log.</param>
/// <param name="message">Format string of the log message in message template format. Example: <code>"User {User} logged in from {Address}"</code></param>
/// <param name="args">An object array that contains zero or more objects to format.</param>
/// <example>logger.LogDebug(0, exception, "Error while processing request from {Address}", address)</example>
public static void LogDebug(this ILogger logger, EventId eventId, Exception exception, string message, params object[] args)
{
logger.Log(LogLevel.Debug, eventId, exception, message, args);
}
/// <summary>
/// Formats and writes a debug log message.
/// </summary>
/// <param name="logger">The <see cref="ILogger"/> to write to.</param>
/// <param name="eventId">The event id associated with the log.</param>
/// <param name="message">Format string of the log message in message template format. Example: <code>"User {User} logged in from {Address}"</code></param>
/// <param name="args">An object array that contains zero or more objects to format.</param>
/// <example>logger.LogDebug(0, "Processing request from {Address}", address)</example>
public static void LogDebug(this ILogger logger, EventId eventId, string message, params object[] args)
{
logger.Log(LogLevel.Debug, eventId, message, args);
}
/// <summary>
/// Formats and writes a debug log message.
/// </summary>
/// <param name="logger">The <see cref="ILogger"/> to write to.</param>
/// <param name="exception">The exception to log.</param>
/// <param name="message">Format string of the log message in message template format. Example: <code>"User {User} logged in from {Address}"</code></param>
/// <param name="args">An object array that contains zero or more objects to format.</param>
/// <example>logger.LogDebug(exception, "Error while processing request from {Address}", address)</example>
public static void LogDebug(this ILogger logger, Exception exception, string message, params object[] args)
{
logger.Log(LogLevel.Debug, exception, message, args);
}
/// <summary>
/// Formats and writes a debug log message.
/// </summary>
/// <param name="logger">The <see cref="ILogger"/> to write to.</param>
/// <param name="message">Format string of the log message in message template format. Example: <code>"User {User} logged in from {Address}"</code></param>
/// <param name="args">An object array that contains zero or more objects to format.</param>
/// <example>logger.LogDebug("Processing request from {Address}", address)</example>
public static void LogDebug(this ILogger logger, string message, params object[] args)
{
logger.Log(LogLevel.Debug, message, args);
}
//------------------------------------------TRACE------------------------------------------//
/// <summary>
/// Formats and writes a trace log message.
/// </summary>
/// <param name="logger">The <see cref="ILogger"/> to write to.</param>
/// <param name="eventId">The event id associated with the log.</param>
/// <param name="exception">The exception to log.</param>
/// <param name="message">Format string of the log message in message template format. Example: <code>"User {User} logged in from {Address}"</code></param>
/// <param name="args">An object array that contains zero or more objects to format.</param>
/// <example>logger.LogTrace(0, exception, "Error while processing request from {Address}", address)</example>
public static void LogTrace(this ILogger logger, EventId eventId, Exception exception, string message, params object[] args)
{
logger.Log(LogLevel.Trace, eventId, exception, message, args);
}
/// <summary>
/// Formats and writes a trace log message.
/// </summary>
/// <param name="logger">The <see cref="ILogger"/> to write to.</param>
/// <param name="eventId">The event id associated with the log.</param>
/// <param name="message">Format string of the log message in message template format. Example: <code>"User {User} logged in from {Address}"</code></param>
/// <param name="args">An object array that contains zero or more objects to format.</param>
/// <example>logger.LogTrace(0, "Processing request from {Address}", address)</example>
public static void LogTrace(this ILogger logger, EventId eventId, string message, params object[] args)
{
logger.Log(LogLevel.Trace, eventId, message, args);
}
/// <summary>
/// Formats and writes a trace log message.
/// </summary>
/// <param name="logger">The <see cref="ILogger"/> to write to.</param>
/// <param name="exception">The exception to log.</param>
/// <param name="message">Format string of the log message in message template format. Example: <code>"User {User} logged in from {Address}"</code></param>
/// <param name="args">An object array that contains zero or more objects to format.</param>
/// <example>logger.LogTrace(exception, "Error while processing request from {Address}", address)</example>
public static void LogTrace(this ILogger logger, Exception exception, string message, params object[] args)
{
logger.Log(LogLevel.Trace, exception, message, args);
}
/// <summary>
/// Formats and writes a trace log message.
/// </summary>
/// <param name="logger">The <see cref="ILogger"/> to write to.</param>
/// <param name="message">Format string of the log message in message template format. Example: <code>"User {User} logged in from {Address}"</code></param>
/// <param name="args">An object array that contains zero or more objects to format.</param>
/// <example>logger.LogTrace("Processing request from {Address}", address)</example>
public static void LogTrace(this ILogger logger, string message, params object[] args)
{
logger.Log(LogLevel.Trace, message, args);
}
//------------------------------------------INFORMATION------------------------------------------//
/// <summary>
/// Formats and writes an informational log message.
/// </summary>
/// <param name="logger">The <see cref="ILogger"/> to write to.</param>
/// <param name="eventId">The event id associated with the log.</param>
/// <param name="exception">The exception to log.</param>
/// <param name="message">Format string of the log message in message template format. Example: <code>"User {User} logged in from {Address}"</code></param>
/// <param name="args">An object array that contains zero or more objects to format.</param>
/// <example>logger.LogInformation(0, exception, "Error while processing request from {Address}", address)</example>
public static void LogInformation(this ILogger logger, EventId eventId, Exception exception, string message, params object[] args)
{
logger.Log(LogLevel.Information, eventId, exception, message, args);
}
/// <summary>
/// Formats and writes an informational log message.
/// </summary>
/// <param name="logger">The <see cref="ILogger"/> to write to.</param>
/// <param name="eventId">The event id associated with the log.</param>
/// <param name="message">Format string of the log message in message template format. Example: <code>"User {User} logged in from {Address}"</code></param>
/// <param name="args">An object array that contains zero or more objects to format.</param>
/// <example>logger.LogInformation(0, "Processing request from {Address}", address)</example>
public static void LogInformation(this ILogger logger, EventId eventId, string message, params object[] args)
{
logger.Log(LogLevel.Information, eventId, message, args);
}
/// <summary>
/// Formats and writes an informational log message.
/// </summary>
/// <param name="logger">The <see cref="ILogger"/> to write to.</param>
/// <param name="exception">The exception to log.</param>
/// <param name="message">Format string of the log message in message template format. Example: <code>"User {User} logged in from {Address}"</code></param>
/// <param name="args">An object array that contains zero or more objects to format.</param>
/// <example>logger.LogInformation(exception, "Error while processing request from {Address}", address)</example>
public static void LogInformation(this ILogger logger, Exception exception, string message, params object[] args)
{
logger.Log(LogLevel.Information, exception, message, args);
}
/// <summary>
/// Formats and writes an informational log message.
/// </summary>
/// <param name="logger">The <see cref="ILogger"/> to write to.</param>
/// <param name="message">Format string of the log message in message template format. Example: <code>"User {User} logged in from {Address}"</code></param>
/// <param name="args">An object array that contains zero or more objects to format.</param>
/// <example>logger.LogInformation("Processing request from {Address}", address)</example>
public static void LogInformation(this ILogger logger, string message, params object[] args)
{
logger.Log(LogLevel.Information, message, args);
}
//------------------------------------------WARNING------------------------------------------//
/// <summary>
/// Formats and writes a warning log message.
/// </summary>
/// <param name="logger">The <see cref="ILogger"/> to write to.</param>
/// <param name="eventId">The event id associated with the log.</param>
/// <param name="exception">The exception to log.</param>
/// <param name="message">Format string of the log message in message template format. Example: <code>"User {User} logged in from {Address}"</code></param>
/// <param name="args">An object array that contains zero or more objects to format.</param>
/// <example>logger.LogWarning(0, exception, "Error while processing request from {Address}", address)</example>
public static void LogWarning(this ILogger logger, EventId eventId, Exception exception, string message, params object[] args)
{
logger.Log(LogLevel.Warning, eventId, exception, message, args);
}
/// <summary>
/// Formats and writes a warning log message.
/// </summary>
/// <param name="logger">The <see cref="ILogger"/> to write to.</param>
/// <param name="eventId">The event id associated with the log.</param>
/// <param name="message">Format string of the log message in message template format. Example: <code>"User {User} logged in from {Address}"</code></param>
/// <param name="args">An object array that contains zero or more objects to format.</param>
/// <example>logger.LogWarning(0, "Processing request from {Address}", address)</example>
public static void LogWarning(this ILogger logger, EventId eventId, string message, params object[] args)
{
logger.Log(LogLevel.Warning, eventId, message, args);
}
/// <summary>
/// Formats and writes a warning log message.
/// </summary>
/// <param name="logger">The <see cref="ILogger"/> to write to.</param>
/// <param name="exception">The exception to log.</param>
/// <param name="message">Format string of the log message in message template format. Example: <code>"User {User} logged in from {Address}"</code></param>
/// <param name="args">An object array that contains zero or more objects to format.</param>
/// <example>logger.LogWarning(exception, "Error while processing request from {Address}", address)</example>
public static void LogWarning(this ILogger logger, Exception exception, string message, params object[] args)
{
logger.Log(LogLevel.Warning, exception, message, args);
}
/// <summary>
/// Formats and writes a warning log message.
/// </summary>
/// <param name="logger">The <see cref="ILogger"/> to write to.</param>
/// <param name="message">Format string of the log message in message template format. Example: <code>"User {User} logged in from {Address}"</code></param>
/// <param name="args">An object array that contains zero or more objects to format.</param>
/// <example>logger.LogWarning("Processing request from {Address}", address)</example>
public static void LogWarning(this ILogger logger, string message, params object[] args)
{
logger.Log(LogLevel.Warning, message, args);
}
//------------------------------------------ERROR------------------------------------------//
/// <summary>
/// Formats and writes an error log message.
/// </summary>
/// <param name="logger">The <see cref="ILogger"/> to write to.</param>
/// <param name="eventId">The event id associated with the log.</param>
/// <param name="exception">The exception to log.</param>
/// <param name="message">Format string of the log message in message template format. Example: <code>"User {User} logged in from {Address}"</code></param>
/// <param name="args">An object array that contains zero or more objects to format.</param>
/// <example>logger.LogError(0, exception, "Error while processing request from {Address}", address)</example>
public static void LogError(this ILogger logger, EventId eventId, Exception exception, string message, params object[] args)
{
logger.Log(LogLevel.Error, eventId, exception, message, args);
}
/// <summary>
/// Formats and writes an error log message.
/// </summary>
/// <param name="logger">The <see cref="ILogger"/> to write to.</param>
/// <param name="eventId">The event id associated with the log.</param>
/// <param name="message">Format string of the log message in message template format. Example: <code>"User {User} logged in from {Address}"</code></param>
/// <param name="args">An object array that contains zero or more objects to format.</param>
/// <example>logger.LogError(0, "Processing request from {Address}", address)</example>
public static void LogError(this ILogger logger, EventId eventId, string message, params object[] args)
{
logger.Log(LogLevel.Error, eventId, message, args);
}
/// <summary>
/// Formats and writes an error log message.
/// </summary>
/// <param name="logger">The <see cref="ILogger"/> to write to.</param>
/// <param name="exception">The exception to log.</param>
/// <param name="message">Format string of the log message in message template format. Example: <code>"User {User} logged in from {Address}"</code></param>
/// <param name="args">An object array that contains zero or more objects to format.</param>
/// <example>logger.LogError(exception, "Error while processing request from {Address}", address)</example>
public static void LogError(this ILogger logger, Exception exception, string message, params object[] args)
{
logger.Log(LogLevel.Error, exception, message, args);
}
/// <summary>
/// Formats and writes an error log message.
/// </summary>
/// <param name="logger">The <see cref="ILogger"/> to write to.</param>
/// <param name="message">Format string of the log message in message template format. Example: <code>"User {User} logged in from {Address}"</code></param>
/// <param name="args">An object array that contains zero or more objects to format.</param>
/// <example>logger.LogError("Processing request from {Address}", address)</example>
public static void LogError(this ILogger logger, string message, params object[] args)
{
logger.Log(LogLevel.Error, message, args);
}
//------------------------------------------CRITICAL------------------------------------------//
/// <summary>
/// Formats and writes a critical log message.
/// </summary>
/// <param name="logger">The <see cref="ILogger"/> to write to.</param>
/// <param name="eventId">The event id associated with the log.</param>
/// <param name="exception">The exception to log.</param>
/// <param name="message">Format string of the log message in message template format. Example: <code>"User {User} logged in from {Address}"</code></param>
/// <param name="args">An object array that contains zero or more objects to format.</param>
/// <example>logger.LogCritical(0, exception, "Error while processing request from {Address}", address)</example>
public static void LogCritical(this ILogger logger, EventId eventId, Exception exception, string message, params object[] args)
{
logger.Log(LogLevel.Critical, eventId, exception, message, args);
}
/// <summary>
/// Formats and writes a critical log message.
/// </summary>
/// <param name="logger">The <see cref="ILogger"/> to write to.</param>
/// <param name="eventId">The event id associated with the log.</param>
/// <param name="message">Format string of the log message in message template format. Example: <code>"User {User} logged in from {Address}"</code></param>
/// <param name="args">An object array that contains zero or more objects to format.</param>
/// <example>logger.LogCritical(0, "Processing request from {Address}", address)</example>
public static void LogCritical(this ILogger logger, EventId eventId, string message, params object[] args)
{
logger.Log(LogLevel.Critical, eventId, message, args);
}
/// <summary>
/// Formats and writes a critical log message.
/// </summary>
/// <param name="logger">The <see cref="ILogger"/> to write to.</param>
/// <param name="exception">The exception to log.</param>
/// <param name="message">Format string of the log message in message template format. Example: <code>"User {User} logged in from {Address}"</code></param>
/// <param name="args">An object array that contains zero or more objects to format.</param>
/// <example>logger.LogCritical(exception, "Error while processing request from {Address}", address)</example>
public static void LogCritical(this ILogger logger, Exception exception, string message, params object[] args)
{
logger.Log(LogLevel.Critical, exception, message, args);
}
/// <summary>
/// Formats and writes a critical log message.
/// </summary>
/// <param name="logger">The <see cref="ILogger"/> to write to.</param>
/// <param name="message">Format string of the log message in message template format. Example: <code>"User {User} logged in from {Address}"</code></param>
/// <param name="args">An object array that contains zero or more objects to format.</param>
/// <example>logger.LogCritical("Processing request from {Address}", address)</example>
public static void LogCritical(this ILogger logger, string message, params object[] args)
{
logger.Log(LogLevel.Critical, message, args);
}
/// <summary>
/// Formats and writes a log message at the specified log level.
/// </summary>
/// <param name="logger">The <see cref="ILogger"/> to write to.</param>
/// <param name="logLevel">Entry will be written on this level.</param>
/// <param name="message">Format string of the log message.</param>
/// <param name="args">An object array that contains zero or more objects to format.</param>
public static void Log(this ILogger logger, LogLevel logLevel, string message, params object[] args)
{
logger.Log(logLevel, 0, null, message, args);
}
/// <summary>
/// Formats and writes a log message at the specified log level.
/// </summary>
/// <param name="logger">The <see cref="ILogger"/> to write to.</param>
/// <param name="logLevel">Entry will be written on this level.</param>
/// <param name="eventId">The event id associated with the log.</param>
/// <param name="message">Format string of the log message.</param>
/// <param name="args">An object array that contains zero or more objects to format.</param>
public static void Log(this ILogger logger, LogLevel logLevel, EventId eventId, string message, params object[] args)
{
logger.Log(logLevel, eventId, null, message, args);
}
/// <summary>
/// Formats and writes a log message at the specified log level.
/// </summary>
/// <param name="logger">The <see cref="ILogger"/> to write to.</param>
/// <param name="logLevel">Entry will be written on this level.</param>
/// <param name="exception">The exception to log.</param>
/// <param name="message">Format string of the log message.</param>
/// <param name="args">An object array that contains zero or more objects to format.</param>
public static void Log(this ILogger logger, LogLevel logLevel, Exception exception, string message, params object[] args)
{
logger.Log(logLevel, 0, exception, message, args);
}
/// <summary>
/// Formats and writes a log message at the specified log level.
/// </summary>
/// <param name="logger">The <see cref="ILogger"/> to write to.</param>
/// <param name="logLevel">Entry will be written on this level.</param>
/// <param name="eventId">The event id associated with the log.</param>
/// <param name="exception">The exception to log.</param>
/// <param name="message">Format string of the log message.</param>
/// <param name="args">An object array that contains zero or more objects to format.</param>
public static void Log(this ILogger logger, LogLevel logLevel, EventId eventId, Exception exception, string message, params object[] args)
{
if (logger == null)
{
throw new ArgumentNullException(nameof(logger));
}
logger.Log(logLevel, eventId, new FormattedLogValues(message, args), exception, _messageFormatter);
}
//------------------------------------------Scope------------------------------------------//
/// <summary>
/// Formats the message and creates a scope.
/// </summary>
/// <param name="logger">The <see cref="ILogger"/> to create the scope in.</param>
/// <param name="messageFormat">Format string of the log message in message template format. Example: <code>"User {User} logged in from {Address}"</code></param>
/// <param name="args">An object array that contains zero or more objects to format.</param>
/// <returns>A disposable scope object. Can be null.</returns>
/// <example>
/// using(logger.BeginScope("Processing request from {Address}", address))
/// {
/// }
/// </example>
public static IDisposable BeginScope(
this ILogger logger,
string messageFormat,
params object[] args)
{
if (logger == null)
{
throw new ArgumentNullException(nameof(logger));
}
return logger.BeginScope(new FormattedLogValues(messageFormat, args));
}
//------------------------------------------HELPERS------------------------------------------//
private static string MessageFormatter(FormattedLogValues state, Exception error)
{
return state.ToString();
}
}
}
| 59.145161 | 169 | 0.613425 | [
"Apache-2.0"
] | andrijacacanoviclogeecom/Logging | src/Microsoft.Extensions.Logging.Abstractions/LoggerExtensions.cs | 25,669 | C# |
using Microsoft.Practices.Prism.StoreApps;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Windows.UI.Xaml;
namespace Pithline.FMS.VehicleInspection.UILogic
{
public class AppSettings : BindableBase
{
private static readonly AppSettings _instance = new AppSettings();
public AppSettings()
{
}
public static AppSettings Instance { get { return _instance; } }
private int isSyncingCustDetails;
public int IsSyncingCustDetails
{
get { return isSyncingCustDetails; }
set { SetProperty(ref isSyncingCustDetails, value); }
}
private int isSyncingVehDetails;
public int IsSyncingVehDetails
{
get { return isSyncingVehDetails; }
set { SetProperty(ref isSyncingVehDetails, value); }
}
private int isSynchronizing;
public int IsSynchronizing
{
get { return isSynchronizing; }
set { SetProperty(ref isSynchronizing, value); }
}
private bool synced;
public bool Synced
{
get { return synced; }
set { SetProperty(ref synced, value); }
}
private string errorMessage;
public string ErrorMessage
{
get { return errorMessage; }
set { SetProperty(ref errorMessage, value); }
}
}
}
| 24.683333 | 74 | 0.604321 | [
"MIT"
] | noorsyyad/FleetManagementSystem | Pithline.FMS.VehicleInspection.UILogic/AppSettings.cs | 1,483 | C# |
using System;
namespace NetTopologySuite.Algorithm
{
/// <summary>
///
/// </summary>
public class NotRepresentableException : ApplicationException
{
/// <summary>
///
/// </summary>
public NotRepresentableException() : base("Projective point not representable on the Cartesian plane.") { }
}
}
| 22 | 115 | 0.607955 | [
"EPL-1.0"
] | Amit909Singh/NetTopologySuite | src/NetTopologySuite/Algorithm/NotRepresentableException.cs | 352 | C# |
using System;
using System.Collections.Generic;
using System.Threading;
using ServiceStack.Commands;
using ServiceStack.Support;
#if NETFX_CORE
using Windows.System.Threading;
#endif
namespace ServiceStack
{
public class CommandsUtils
{
public static List<T> ExecuteAsyncCommandList<T>(TimeSpan timeout, params ICommandList<T>[] commands)
{
return ExecuteAsyncCommandList(timeout, commands);
}
public static List<T> ExecuteAsyncCommandList<T>(TimeSpan timeout, IEnumerable<ICommandList<T>> commands)
{
var results = new List<T>();
var waitHandles = new List<WaitHandle>();
foreach (ICommandList<T> command in commands)
{
var waitHandle = new AutoResetEvent(false);
waitHandles.Add(waitHandle);
var commandResultsHandler = new CommandResultsHandler<T>(results, command, waitHandle);
#if NETFX_CORE
ThreadPool.RunAsync(new WorkItemHandler((IAsyncAction) => ExecuteCommandList(commandResultsHandler)));
#else
ThreadPool.QueueUserWorkItem(ExecuteCommandList, commandResultsHandler);
#endif
}
WaitAll(waitHandles.ToArray(), timeout);
return results;
}
public static void WaitAll(WaitHandle[] waitHandles, TimeSpan timeout)
{
// throws an exception if there are no wait handles
if (waitHandles != null && waitHandles.Length > 0)
{
#if !SILVERLIGHT && !MONOTOUCH && !XBOX
if (Thread.CurrentThread.GetApartmentState() == ApartmentState.STA)
{
// WaitAll for multiple handles on an STA thread is not supported.
// CurrentThread is ApartmentState.STA when run under unit tests
foreach (WaitHandle waitHandle in waitHandles)
{
waitHandle.WaitOne(timeout, false);
}
}
else
{
if (!WaitHandle.WaitAll(waitHandles, timeout, false))
{
throw new TimeoutException();
}
}
#else
if (!WaitHandle.WaitAll(waitHandles, timeout))
{
throw new TimeoutException();
}
#endif
}
}
private static void ExecuteCommandList(object state)
{
var handler = (ICommandExec)state;
handler.Execute();
}
private static void ExecuteCommandExec(object state)
{
var command = (ICommandExec)state;
command.Execute();
}
public static void ExecuteAsyncCommandExec(TimeSpan timeout, IEnumerable<ICommandExec> commands)
{
foreach (ICommandExec command in commands)
{
#if NETFX_CORE
ThreadPool.RunAsync(new WorkItemHandler((IAsyncAction) => ExecuteCommandExec(command)));
#else
ThreadPool.QueueUserWorkItem(ExecuteCommandExec, command);
#endif
}
}
/// <summary>
/// Provide the an option for the callee to block until all commands are executed
/// </summary>
/// <param name="commands"></param>
/// <returns></returns>
public static List<WaitHandle> ExecuteAsyncCommandExec(IEnumerable<ICommandExec> commands)
{
var waitHandles = new List<WaitHandle>();
foreach (var command in commands)
{
var waitHandle = new AutoResetEvent(false);
waitHandles.Add(waitHandle);
var commandExecsHandler = new CommandExecsHandler(command, waitHandle);
#if NETFX_CORE
ThreadPool.RunAsync(new WorkItemHandler((IAsyncAction) => ExecuteCommandList(commandExecsHandler)));
#else
ThreadPool.QueueUserWorkItem(ExecuteCommandList, commandExecsHandler);
#endif
}
return waitHandles;
}
}
} | 34.403361 | 118 | 0.581094 | [
"Apache-2.0"
] | PPPInc/ServiceStack | src/ServiceStack.Common/CommandsUtils.cs | 4,094 | 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 redshift-2012-12-01.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.Redshift.Model;
using Amazon.Runtime;
using Amazon.Runtime.Internal;
using Amazon.Runtime.Internal.Transform;
using Amazon.Runtime.Internal.Util;
namespace Amazon.Redshift.Model.Internal.MarshallTransformations
{
/// <summary>
/// Response Unmarshaller for CreateCluster operation
/// </summary>
public class CreateClusterResponseUnmarshaller : XmlResponseUnmarshaller
{
public override AmazonWebServiceResponse Unmarshall(XmlUnmarshallerContext context)
{
CreateClusterResponse response = new CreateClusterResponse();
context.Read();
int targetDepth = context.CurrentDepth;
while (context.ReadAtDepth(targetDepth))
{
if (context.IsStartElement)
{
if(context.TestExpression("CreateClusterResult", 2))
{
UnmarshallResult(context, response);
continue;
}
if (context.TestExpression("ResponseMetadata", 2))
{
response.ResponseMetadata = ResponseMetadataUnmarshaller.Instance.Unmarshall(context);
}
}
}
return response;
}
private static void UnmarshallResult(XmlUnmarshallerContext context, CreateClusterResponse response)
{
int originalDepth = context.CurrentDepth;
int targetDepth = originalDepth + 1;
if (context.IsStartOfDocument)
targetDepth += 2;
while (context.ReadAtDepth(originalDepth))
{
if (context.IsStartElement || context.IsAttribute)
{
if ( context.TestExpression("Cluster", targetDepth))
{
response.Cluster = ClusterUnmarshaller.Instance.Unmarshall(context);
continue;
}
}
}
return;
}
public override AmazonServiceException UnmarshallException(XmlUnmarshallerContext context, Exception innerException, HttpStatusCode statusCode)
{
ErrorResponse errorResponse = ErrorResponseUnmarshaller.GetInstance().Unmarshall(context);
if (errorResponse.Code != null && errorResponse.Code.Equals("ClusterAlreadyExists"))
{
return new ClusterAlreadyExistsException(errorResponse.Message, innerException, errorResponse.Type, errorResponse.Code, errorResponse.RequestId, statusCode);
}
if (errorResponse.Code != null && errorResponse.Code.Equals("ClusterParameterGroupNotFound"))
{
return new ClusterParameterGroupNotFoundException(errorResponse.Message, innerException, errorResponse.Type, errorResponse.Code, errorResponse.RequestId, statusCode);
}
if (errorResponse.Code != null && errorResponse.Code.Equals("ClusterQuotaExceeded"))
{
return new ClusterQuotaExceededException(errorResponse.Message, innerException, errorResponse.Type, errorResponse.Code, errorResponse.RequestId, statusCode);
}
if (errorResponse.Code != null && errorResponse.Code.Equals("ClusterSecurityGroupNotFound"))
{
return new ClusterSecurityGroupNotFoundException(errorResponse.Message, innerException, errorResponse.Type, errorResponse.Code, errorResponse.RequestId, statusCode);
}
if (errorResponse.Code != null && errorResponse.Code.Equals("ClusterSubnetGroupNotFoundFault"))
{
return new ClusterSubnetGroupNotFoundException(errorResponse.Message, innerException, errorResponse.Type, errorResponse.Code, errorResponse.RequestId, statusCode);
}
if (errorResponse.Code != null && errorResponse.Code.Equals("HsmClientCertificateNotFoundFault"))
{
return new HsmClientCertificateNotFoundException(errorResponse.Message, innerException, errorResponse.Type, errorResponse.Code, errorResponse.RequestId, statusCode);
}
if (errorResponse.Code != null && errorResponse.Code.Equals("HsmConfigurationNotFoundFault"))
{
return new HsmConfigurationNotFoundException(errorResponse.Message, innerException, errorResponse.Type, errorResponse.Code, errorResponse.RequestId, statusCode);
}
if (errorResponse.Code != null && errorResponse.Code.Equals("InsufficientClusterCapacity"))
{
return new InsufficientClusterCapacityException(errorResponse.Message, innerException, errorResponse.Type, errorResponse.Code, errorResponse.RequestId, statusCode);
}
if (errorResponse.Code != null && errorResponse.Code.Equals("InvalidClusterSubnetGroupStateFault"))
{
return new InvalidClusterSubnetGroupStateException(errorResponse.Message, innerException, errorResponse.Type, errorResponse.Code, errorResponse.RequestId, statusCode);
}
if (errorResponse.Code != null && errorResponse.Code.Equals("InvalidElasticIpFault"))
{
return new InvalidElasticIpException(errorResponse.Message, innerException, errorResponse.Type, errorResponse.Code, errorResponse.RequestId, statusCode);
}
if (errorResponse.Code != null && errorResponse.Code.Equals("InvalidSubnet"))
{
return new InvalidSubnetException(errorResponse.Message, innerException, errorResponse.Type, errorResponse.Code, errorResponse.RequestId, statusCode);
}
if (errorResponse.Code != null && errorResponse.Code.Equals("InvalidTagFault"))
{
return new InvalidTagException(errorResponse.Message, innerException, errorResponse.Type, errorResponse.Code, errorResponse.RequestId, statusCode);
}
if (errorResponse.Code != null && errorResponse.Code.Equals("InvalidVPCNetworkStateFault"))
{
return new InvalidVPCNetworkStateException(errorResponse.Message, innerException, errorResponse.Type, errorResponse.Code, errorResponse.RequestId, statusCode);
}
if (errorResponse.Code != null && errorResponse.Code.Equals("NumberOfNodesPerClusterLimitExceeded"))
{
return new NumberOfNodesPerClusterLimitExceededException(errorResponse.Message, innerException, errorResponse.Type, errorResponse.Code, errorResponse.RequestId, statusCode);
}
if (errorResponse.Code != null && errorResponse.Code.Equals("NumberOfNodesQuotaExceeded"))
{
return new NumberOfNodesQuotaExceededException(errorResponse.Message, innerException, errorResponse.Type, errorResponse.Code, errorResponse.RequestId, statusCode);
}
if (errorResponse.Code != null && errorResponse.Code.Equals("TagLimitExceededFault"))
{
return new TagLimitExceededException(errorResponse.Message, innerException, errorResponse.Type, errorResponse.Code, errorResponse.RequestId, statusCode);
}
if (errorResponse.Code != null && errorResponse.Code.Equals("UnauthorizedOperation"))
{
return new UnauthorizedOperationException(errorResponse.Message, innerException, errorResponse.Type, errorResponse.Code, errorResponse.RequestId, statusCode);
}
return new AmazonRedshiftException(errorResponse.Message, innerException, errorResponse.Type, errorResponse.Code, errorResponse.RequestId, statusCode);
}
private static CreateClusterResponseUnmarshaller _instance = new CreateClusterResponseUnmarshaller();
internal static CreateClusterResponseUnmarshaller GetInstance()
{
return _instance;
}
public static CreateClusterResponseUnmarshaller Instance
{
get
{
return _instance;
}
}
}
} | 50.916201 | 189 | 0.656024 | [
"Apache-2.0"
] | samritchie/aws-sdk-net | AWSSDK_DotNet35/Amazon.Redshift/Model/Internal/MarshallTransformations/CreateClusterResponseUnmarshaller.cs | 9,114 | C# |
// *********************************************************************
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License
// *********************************************************************
using Microsoft.StreamProcessing;
using Microsoft.StreamProcessing.Internal;
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace ComponentTesting.Aggregates
{
[TestClass]
public class AggregateByKey : TestWithConfigSettingsAndMemoryLeakDetection
{
public AggregateByKey()
: base(new ConfigModifier()
.ForceRowBasedExecution(false)
.DontFallBackToRowBasedExecution(true)
.UseMultiString(false)
.MultiStringTransforms(Config.CodegenOptions.MultiStringFlags.None))
{ }
[TestMethod, TestCategory("Gated")]
public void TestAggregateByKey()
{
var input = new[]
{
StreamEvent.CreateStart(0, 100),
StreamEvent.CreateStart(0, 105),
StreamEvent.CreateStart(0, 104),
StreamEvent.CreateStart(0, 200),
StreamEvent.CreateStart(0, 201),
StreamEvent.CreateStart(0, 300),
StreamEvent.CreateStart(0, 302),
StreamEvent.CreateStart(0, 303),
StreamEvent.CreatePunctuation<int>(StreamEvent.InfinitySyncTime)
}.ToStreamable().SetProperty().IsConstantDuration(true, StreamEvent.InfinitySyncTime);
var output = input
.AggregateByKey(
a => a / 100,
b => b.Count(),
(key, count) => key * 100 + (int)count * 10);
var correct = new[]
{
StreamEvent.CreateStart(0, 130),
StreamEvent.CreateStart(0, 220),
StreamEvent.CreateStart(0, 330),
StreamEvent.CreatePunctuation<int>(StreamEvent.InfinitySyncTime)
};
Assert.IsTrue(output.IsEquivalentTo(correct));
}
[TestMethod, TestCategory("Gated")]
public void TestAggregateByKey2()
{
var input = new[]
{
StreamEvent.CreateStart(0, 100),
StreamEvent.CreateStart(0, 105),
StreamEvent.CreateStart(0, 104),
StreamEvent.CreateStart(0, 200),
StreamEvent.CreateStart(0, 201),
StreamEvent.CreateStart(0, 300),
StreamEvent.CreateStart(0, 302),
StreamEvent.CreateStart(0, 303),
StreamEvent.CreatePunctuation<int>(StreamEvent.InfinitySyncTime)
}.ToStreamable().SetProperty().IsConstantDuration(true, StreamEvent.InfinitySyncTime);
var output = input
.Select(e => new StructTuple<long, long> { Item1 = 0, Item2 = e })
.AggregateByKey(
a => (int)a.Item2 / 100,
b => b.Sum(s => (int)(s.Item2 & 0xffff)),
(key, sum) => new StructTuple<int, ulong> { Item1 = key, Item2 = (ulong)key * 100 + (ulong)sum * 10 })
.Select(e => (int)e.Item2);
var correct = new[]
{
StreamEvent.CreateStart(0, 3190),
StreamEvent.CreateStart(0, 4210),
StreamEvent.CreateStart(0, 9350),
StreamEvent.CreatePunctuation<int>(StreamEvent.InfinitySyncTime)
};
Assert.IsTrue(output.IsEquivalentTo(correct));
}
[TestMethod, TestCategory("Gated")]
public void TestAggregateByKey3()
{
var input = new[]
{
StreamEvent.CreateStart(0, 100),
StreamEvent.CreateStart(0, 105),
StreamEvent.CreateStart(0, 104),
StreamEvent.CreateStart(0, 200),
StreamEvent.CreateStart(0, 201),
StreamEvent.CreateStart(0, 300),
StreamEvent.CreateStart(0, 302),
StreamEvent.CreateStart(0, 303),
StreamEvent.CreatePunctuation<int>(StreamEvent.InfinitySyncTime)
}.ToStreamable().SetProperty().IsConstantDuration(true, StreamEvent.InfinitySyncTime);
var output = input
.Select(e => new StructTuple<long, long> { Item1 = 0, Item2 = e })
.AggregateByKey(
a => (int)a.Item2 / 100,
b => b.Sum(s => (int)(s.Item2 & 0xffff)),
c => c.Count(),
(sum, count) => new StructTuple<int, ulong> { Item1 = sum, Item2 = count * 34 },
(key, agg) => new StructTuple<int, ulong, ulong> { Item1 = key, Item2 = (ulong)key * 100 + (ulong)agg.Item1 * 10, Item3 = (ulong)key * 100 + (ulong)agg.Item2 * 0 })
.Select(e => (int)e.Item2);
var correct = new[]
{
StreamEvent.CreateStart(0, 3190),
StreamEvent.CreateStart(0, 4210),
StreamEvent.CreateStart(0, 9350),
StreamEvent.CreatePunctuation<int>(StreamEvent.InfinitySyncTime)
};
Assert.IsTrue(output.IsEquivalentTo(correct));
}
}
}
| 40.083333 | 180 | 0.527311 | [
"MIT"
] | domoritz/Trill | Sources/Test/TrillTest/Aggregates/PerKeyAggregate.cs | 5,293 | C# |
// ----------------------------------------------------------------------
// @Namespace : VgoGltf
// @Struct : Vector4Byte
// ----------------------------------------------------------------------
namespace VgoGltf
{
using System;
using System.Runtime.InteropServices;
/// <summary>
/// Vector4 (byte)
/// </summary>
[Serializable]
[StructLayout(LayoutKind.Sequential, Pack = 1)]
public struct Vector4Ubyte
{
/// <summary></summary>
public byte X;
/// <summary></summary>
public byte Y;
/// <summary></summary>
public byte Z;
/// <summary></summary>
public byte W;
/// <summary>
/// Create a new instance of Vector4Ubyte with x and y and z and w.
/// </summary>
/// <param name="x"></param>
/// <param name="y"></param>
/// <param name="z"></param>
/// <param name="w"></param>
public Vector4Ubyte(byte x, byte y, byte z, byte w)
{
X = x;
Y = y;
Z = z;
W = w;
}
}
}
| 24.6 | 75 | 0.415537 | [
"MIT"
] | izayoijiichan/vgo.gltf | Runtime/Structs/Vector4Ubyte.cs | 1,109 | C# |
namespace ExcelReadWrite.Domain
{
public class HyperaPharmaNota : BaseDomain
{
}
public class HyperaPharmaRetorno : BaseDomain
{
}
} | 15.8 | 49 | 0.670886 | [
"MIT"
] | wmalves/ExcelReadWrite | Domain/HyperaPharma.cs | 160 | C# |
using System;
using System.Linq;
using MediaBrowser.Model.Plugins;
using Trakt.Model;
namespace Trakt.Configuration
{
public class PluginConfiguration : BasePluginConfiguration
{
public PluginConfiguration()
{
TraktUsers = Array.Empty<TraktUser>();
}
public TraktUser[] TraktUsers { get; set; }
public void AddUser(string userId)
{
var traktUsers = TraktUsers.ToList();
var traktUser = new TraktUser
{
LinkedMbUserId = userId
};
traktUsers.Add(traktUser);
TraktUsers = traktUsers.ToArray();
}
}
}
| 23.068966 | 62 | 0.576981 | [
"MIT"
] | Vagab0nd/jellyfin-plugin-trakt | Trakt/Configuration/PluginConfiguration.cs | 671 | C# |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the Apache 2.0 License.
// See the LICENSE file in the project root for more information.
using System.Collections.Generic;
namespace Steeltoe.Management
{
public interface IEndpointOptions
{
bool? Enabled { get; }
string Id { get; }
string Path { get; }
Permissions RequiredPermissions { get; }
bool IsAccessAllowed(Permissions permissions);
IEnumerable<string> AllowedVerbs { get; }
bool ExactMatch { get; }
}
}
| 23.538462 | 78 | 0.668301 | [
"Apache-2.0"
] | Chatina73/steeltoe | src/Management/src/Abstractions/IEndpointOptions.cs | 614 | C# |
using OWML.ModHelper.Events;
using UnityEngine;
using UnityEngine.UI;
namespace NomaiVR
{
internal class Dialogue : NomaiVRModule<Dialogue.Behaviour, Dialogue.Behaviour.Patch>
{
protected override bool IsPersistent => false;
protected override OWScene[] Scenes => PlayableScenes;
public class Behaviour : MonoBehaviour
{
private static Transform _canvasTransform;
private static Transform _attentionPoint = null;
private const float _dialogeRenderSize = 0.0015f;
internal void Start()
{
_canvasTransform = GameObject.Find("DialogueCanvas").transform;
_canvasTransform.localScale *= _dialogeRenderSize;
// Prevent dialogue box from flying off after a while.
_canvasTransform.parent = new GameObject().transform;
_canvasTransform.parent.gameObject.AddComponent<FollowTarget>().target = Locator.GetPlayerTransform();
var canvas = _canvasTransform.gameObject.GetComponent<Canvas>();
canvas.renderMode = RenderMode.WorldSpace;
}
internal void Update()
{
if (_attentionPoint != null && _canvasTransform != null)
{
var headPosition = PlayerHelper.PlayerHead.position;
_canvasTransform.LookAt(2 * _attentionPoint.position - headPosition, PlayerHelper.PlayerHead.up);
// Move so it is 1 unit away from the player
var offset = (_attentionPoint.position - headPosition).normalized;
_canvasTransform.position = headPosition + offset;
}
}
public class Patch : NomaiVRPatch
{
public override void ApplyPatches()
{
NomaiVR.Pre<CharacterDialogueTree>("StartConversation", typeof(Patch), nameof(PreStartConversation));
NomaiVR.Post<CharacterDialogueTree>("StartConversation", typeof(Patch), nameof(PostStartConversation));
NomaiVR.Pre<CharacterDialogueTree>("EndConversation", typeof(Patch), nameof(PreEndConversation));
NomaiVR.Post<DialogueOptionUI>("Awake", typeof(Patch), nameof(PostDialogueOptionAwake));
NomaiVR.Post<DialogueOptionUI>("SetSelected", typeof(Patch), nameof(PreSetButtonPromptImage));
}
private static void PreSetButtonPromptImage(Image ____buttonPromptImage)
{
var texture = AssetLoader.EmptyTexture;
____buttonPromptImage.sprite = Sprite.Create(texture, new Rect(0f, 0f, texture.width, texture.height), new Vector2(0.5f, 0.5f), texture.width);
}
private static void PostDialogueOptionAwake(DialogueOptionUI __instance)
{
var text = __instance.GetComponentInChildren<Text>();
var collider = __instance.gameObject.AddComponent<BoxCollider>();
var rectTransform = text.GetComponent<RectTransform>();
var thickness = 10f;
var height = 40;
var width = rectTransform.rect.width;
collider.size = new Vector3(width, height, thickness);
collider.center = new Vector3(0, -height * 0.5f, thickness * 0.5f);
MaterialHelper.MakeGraphicChildrenDrawOnTop(__instance.gameObject);
}
private static void PreStartConversation(CharacterDialogueTree __instance)
{
_attentionPoint = __instance.GetValue<Transform>("_attentionPoint");
}
private static void PostStartConversation()
{
MaterialHelper.MakeGraphicChildrenDrawOnTop(_canvasTransform.gameObject);
}
private static void PreEndConversation()
{
_attentionPoint = null;
}
}
}
}
}
| 43.333333 | 163 | 0.586779 | [
"MIT"
] | senritsu/nomai-vr | NomaiVR/UI/Dialogue.cs | 4,162 | C# |
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using Threax.ProcessHelper;
namespace Threax.Provision.AzPowershell
{
public class ArmTemplateManager : IArmTemplateManager
{
private readonly IShellRunner shellRunner;
public ArmTemplateManager(IShellRunner shellRunner)
{
this.shellRunner = shellRunner;
}
public Task ResourceGroupDeployment(String resourceGroupName, String templateFile, String? templateParameterFile, Object args)
{
var pwsh = shellRunner.CreateCommandBuilder();
pwsh.SetUnrestrictedExecution();
pwsh.AddCommand($"Import-Module Az.Resources");
var commands = new FormattableString[] { $"New-AzResourceGroupDeployment -Name {Guid.NewGuid()} -ResourceGroupName {resourceGroupName}" }.Concat(SetupArgs(ref templateFile, ref templateParameterFile, args));
pwsh.AddResultCommand(commands);
return shellRunner.RunProcessVoidAsync(pwsh,
invalidExitCodeMessage: $"Error creating Arm Template '{templateFile}' in Resource Group '{resourceGroupName}'.");
}
public Task ResourceGroupDeployment(String resourceGroupName, String templateFile, Object args)
{
return ResourceGroupDeployment(resourceGroupName, templateFile, null, args);
}
public Task ResourceGroupDeployment(String resourceGroupName, String templateFile, String? templateParametersFile)
{
return ResourceGroupDeployment(resourceGroupName, templateFile, templateParametersFile, new Object());
}
public Task ResourceGroupDeployment(String resourceGroupName, String templateFile)
{
return ResourceGroupDeployment(resourceGroupName, templateFile, null);
}
public Task ResourceGroupDeployment(String resourceGroupName, ArmTemplate armTemplate)
{
return ResourceGroupDeployment(resourceGroupName, armTemplate.GetTemplatePath(), armTemplate.GetParametersPath(), armTemplate);
}
public Task SubscriptionDeployment(String location, String templateFile, String? templateParameterFile, Object args)
{
var pwsh = shellRunner.CreateCommandBuilder();
pwsh.SetUnrestrictedExecution();
pwsh.AddCommand($"Import-Module Az.Resources");
var commands = new FormattableString[] { $"New-AzDeployment -Name {Guid.NewGuid()} -Location {location}" }.Concat(SetupArgs(ref templateFile, ref templateParameterFile, args));
pwsh.AddResultCommand(commands);
return shellRunner.RunProcessVoidAsync(pwsh,
invalidExitCodeMessage: $"Error creating Arm Template Deployment '{templateFile}' in Location '{location}'.");
}
public Task SubscriptionDeployment(String location, String templateFile, Object args)
{
return SubscriptionDeployment(location, templateFile, null, args);
}
public Task SubscriptionDeployment(String location, String templateFile, String? templateParametersFile)
{
return SubscriptionDeployment(location, templateFile, templateParametersFile, new Object());
}
public Task SubscriptionDeployment(String location, String templateFile)
{
return SubscriptionDeployment(location, templateFile, null);
}
public Task SubscriptionDeployment(String resourceGroupName, ArmTemplate armTemplate)
{
return SubscriptionDeployment(resourceGroupName, armTemplate.GetTemplatePath(), armTemplate.GetParametersPath(), armTemplate);
}
private static IEnumerable<FormattableString> SetupArgs(ref string templateFile, ref string? templateParameterFile, Object args)
{
templateFile = Path.GetFullPath(templateFile);
var mainArgs = new List<FormattableString>()
{
$" -TemplateFile {templateFile}"
};
if (templateParameterFile != null)
{
templateParameterFile = Path.GetFullPath(templateParameterFile);
mainArgs.Add($" -TemplateParameterFile {templateParameterFile}");
}
foreach (var prop in TypeHelper.GetPropertiesAndValues(args).Where(i => i.Value != null))
{
mainArgs.Add($" -{new RawProcessString(prop.Key)} {prop.Value}");
}
return mainArgs;
}
}
}
| 41.834862 | 219 | 0.676974 | [
"MIT"
] | threax/Threax.Pipelines | Threax.Provision.AzPowershell/ArmTemplateManager.cs | 4,562 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace SerrisCodeEditor.Functions.Settings
{
public static class DefaultSettings
{
public static SettingsMenu[] DefaultSettingsMenuList =
{
//EDITOR
new SettingsMenu
{
Name = GlobalVariables.GlobalizationRessources.GetString("settings-editor"),
Icon = "",
Settings = new List<Setting>
{
new Setting
{
Description = GlobalVariables.GlobalizationRessources.GetString("settings-editor_showline"),
Type = SettingType.Checkbox,
VarSaveName = "editor_linenumbers",
VarSaveDefaultContent = true
},
new Setting
{
Description = GlobalVariables.GlobalizationRessources.GetString("settings-editor_showminimap"),
Type = SettingType.Checkbox,
VarSaveName = "editor_minimap",
VarSaveDefaultContent = true
},
new Setting
{
Description = GlobalVariables.GlobalizationRessources.GetString("settings-editor_quicksuggests"),
Type = SettingType.Checkbox,
VarSaveName = "editor_quicksuggestions",
VarSaveDefaultContent = true
},
new Setting
{
Description = GlobalVariables.GlobalizationRessources.GetString("settings-editor_wrappingcode"),
Type = SettingType.Checkbox,
VarSaveName = "editor_wordwrap",
VarSaveDefaultContent = false
},
new Setting
{
Description = GlobalVariables.GlobalizationRessources.GetString("settings-editor_fontsize"),
Type = SettingType.TextboxNumber,
VarSaveName = "editor_fontsize",
VarSaveDefaultContent = 14
},
new Setting
{
Description = GlobalVariables.GlobalizationRessources.GetString("settings-editor_fontfamily"),
Type = SettingType.ComboBox,
VarSaveName = "editor_fontfamily",
VarSaveDefaultContent = "Consolas",
Parameter = Microsoft.Graphics.Canvas.Text.CanvasTextFormat.GetSystemFontFamilies().ToList()
}
}
},
//UI
new SettingsMenu
{
Name = GlobalVariables.GlobalizationRessources.GetString("settings-ui"),
Icon = "",
Settings = new List<Setting>
{
new Setting
{
Description = GlobalVariables.GlobalizationRessources.GetString("settings-ui_extendedview"),
Type = SettingType.Checkbox,
VarSaveName = "ui_extendedview",
VarSaveDefaultContent = false
},
new Setting
{
Description = GlobalVariables.GlobalizationRessources.GetString("settings-ui_closepanelauto"),
Type = SettingType.Checkbox,
VarSaveName = "ui_closepanelauto",
VarSaveDefaultContent = true
},
new Setting
{
Description = GlobalVariables.GlobalizationRessources.GetString("settings-ui_leftpanelength"),
Type = SettingType.TextboxNumber,
VarSaveName = "ui_leftpanelength",
VarSaveDefaultContent = 60
},
new Setting
{
Description = GlobalVariables.GlobalizationRessources.GetString("settings-ui_leftpaneopenlength"),
Type = SettingType.TextboxNumber,
VarSaveName = "ui_leftpaneopenlength",
VarSaveDefaultContent = 320
}
}
},
//CREDITS
new SettingsMenu
{
Name = GlobalVariables.GlobalizationRessources.GetString("settings-credits"),
Icon = "",
Settings = new List<Setting>
{
new Setting
{
Description = GlobalVariables.GlobalizationRessources.GetString("settings-credits_aboutapp"),
Type = SettingType.Separator
},
new Setting
{
Description = "Serris Code Editor",
Type = SettingType.SecondDescription,
Parameter = GlobalVariables.GlobalizationRessources.GetString("settings-credits_byseeriis")
},
new Setting
{
Description = GlobalVariables.GlobalizationRessources.GetString("settings-credits_maindev"),
Type = SettingType.SecondDescription,
Parameter = "DeerisLeGris (France)"
},
new Setting
{
Description = GlobalVariables.GlobalizationRessources.GetString("settings-credits_version"),
Type = SettingType.SecondDescription,
Parameter = SCEELibs.SCEInfos.versionName + " - BUILD: " + SCEELibs.SCEInfos.getBuildVersion()
},
new Setting
{
Description = GlobalVariables.GlobalizationRessources.GetString("settings-credits_scegithub"),
Type = SettingType.Link,
Parameter = "https://github.com/Seeriis/SerrisCodeEditor"
},
new Setting
{
Description = GlobalVariables.GlobalizationRessources.GetString("settings-credits_licenses"),
Type = SettingType.Separator
},
new Setting
{
Description = "JsBridge",
Type = SettingType.License,
Parameter = new Tuple<string, string>("by deltakosh (with Apache License 2.0)", "apache.txt")
},
new Setting
{
Description = "MVVMLight",
Type = SettingType.License,
Parameter = new Tuple<string, string>("by Laurent Bugnion (GalaSoft) (with MIT license)", "mit_mvvm.txt")
},
new Setting
{
Description = "Newtonsoft.Json",
Type = SettingType.License,
Parameter = new Tuple<string, string>("by James Newton-King (with MIT license)", "mit_json.txt")
},
new Setting
{
Description = "UWP Community Toolkit",
Type = SettingType.License,
Parameter = new Tuple<string, string>("by Microsoft (with MIT license)", "mit_toolkit.txt")
},
new Setting
{
Description = "Monaco Editor",
Type = SettingType.License,
Parameter = new Tuple<string, string>("by Microsoft (with MIT license)", "mit_monaco.txt")
},
new Setting
{
Description = "SerialQueue",
Type = SettingType.License,
Parameter = new Tuple<string, string>("by Orion Edwards (with MIT license)", "mit_serialqueue.txt")
},
new Setting
{
Description = "Devicon",
Type = SettingType.License,
Parameter = new Tuple<string, string>("by Konpa (with MIT license)", "mit_devicon.txt")
},
new Setting
{
Description = "Win2D",
Type = SettingType.License,
Parameter = new Tuple<string, string>("by Microsoft", "win2d.htm")
},
new Setting
{
Description = "UDE",
Type = SettingType.License,
Parameter = new Tuple<string, string>("by Rudi Pettazzi (with MPL 1.1 license)", "MPL.txt")
},
}
}
};
}
}
| 36.486486 | 129 | 0.455132 | [
"MIT"
] | AdminVIKO/SerrisCodeEditor | SerrisCodeEditor/SerrisCodeEditor/Functions/Settings/DefaultSettings.cs | 9,458 | C# |
using System;
namespace HttpClientFactorySample
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Hello World!");
}
}
}
| 14.692308 | 46 | 0.549738 | [
"Apache-2.0"
] | xyfy/dotnet-core-Example | HttpClientFactorySample/Program.cs | 193 | C# |
using System;
using UnityEngine;
[Serializable]
public class SpawnPoolEntry
{
[SerializeField]
private ObjectPool _pool;
[SerializeField]
private ushort _priority;
public ObjectPool Pool
{
get { return _pool; }
}
public ushort Priority
{
get { return _priority; }
}
}
| 12.478261 | 27 | 0.724739 | [
"MIT"
] | willem88836/GGJ2021 | Assets/Scripts/Object_Spawning/SpawnPoolEntry.cs | 289 | C# |
namespace Essensoft.Paylink.Alipay.Response
{
/// <summary>
/// AlipayOpenServicemarketCommodityShopOfflineResponse.
/// </summary>
public class AlipayOpenServicemarketCommodityShopOfflineResponse : AlipayResponse
{
}
}
| 24.5 | 85 | 0.734694 | [
"MIT"
] | Frunck8206/payment | src/Essensoft.Paylink.Alipay/Response/AlipayOpenServicemarketCommodityShopOfflineResponse.cs | 247 | C# |
using ff14bot.Managers;
using Newtonsoft.Json;
namespace LlamaLibrary.Retainers
{
//TODO This needs to be somewhere else, Maybe a DataClass folder/namespace
public class RetainerTaskData
{
public int Id { get; set; }
public byte ClassJobCategory { get; set; }
public bool IsRandom { get; set; }
public int RetainerLevel { get; set; }
public int VentureCost { get; set; }
public int MaxTime { get; set; }
public int Experience { get; set; }
public int RequiredItemLevel { get; set; }
public int RequiredGathering { get; set; }
public string NameRaw { get; set; }
public int ItemId { get; set; }
[JsonIgnore]
public string Name
{
get
{
if (IsRandom)
{
return NameRaw;
}
else
{
return DataManager.GetItem((uint)ItemId).CurrentLocaleName;
}
}
}
[JsonConstructor]
public RetainerTaskData(int id, byte classJobCategory, bool isRandom, int retainerLevel, int ventureCost, int maxTime, int experience, int requiredItemLevel, int requiredGathering, string nameRaw, int itemId)
{
Id = id;
ClassJobCategory = classJobCategory;
IsRandom = isRandom;
RetainerLevel = retainerLevel;
VentureCost = ventureCost;
MaxTime = maxTime;
Experience = experience;
RequiredItemLevel = requiredItemLevel;
RequiredGathering = requiredGathering;
NameRaw = nameRaw;
ItemId = itemId;
}
public override string ToString()
{
return $"{Id} - {IsRandom} {NameRaw}";
}
}
} | 31.862069 | 216 | 0.549242 | [
"MIT"
] | nt153133/__LlamaLibrary | Retainers/RetainerTaskData.cs | 1,850 | 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("AlexaSkill")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("AlexaSkill")]
[assembly: AssemblyCopyright("Copyright © 2020")]
[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("c6a817c2-7f62-41c3-bfde-43abf6ead46d")]
// 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 Revision and Build Numbers
// by using the '*' as shown below:
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| 37.444444 | 84 | 0.750742 | [
"MIT"
] | ManishMehmood/TDS-Hackathon-2020 | AlexaSkill/Properties/AssemblyInfo.cs | 1,351 | C# |
using UdonSharp;
using UnityEngine;
using VRC.SDKBase;
using VRC.Udon;
public class pickup_setvelocity : UdonSharpBehaviour
{
public VRCPlayerApi PlayerApiref;
private Transform transform;
public Vector3 direction;
public float speed = 1;
private bool state = false;
void Start()
{
transform = GetComponent<Transform>();
PlayerApiref = Networking.LocalPlayer;
}
private void Update()
{
if (state)
{
PlayerApiref.SetVelocity(transform.rotation * direction.normalized * speed);
}
}
public void OnPickupUseDown()
{
state = true;
}
public void OnPickupUseUp()
{
state = false;
}
public void OnDrop()
{
state = false;
}
}
| 17.727273 | 88 | 0.605128 | [
"MIT"
] | jetdog8808/Udon-playground | Assets/jetdogs-prefabs-udon/U# scripts/pickup_setvelocity.cs | 780 | C# |
/*using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using UnityEditor;
using UnityEngine;
public class VisibleIfDrawer : PropertyDrawer
{
bool init = false;
VisibleIfAttribute data;
FieldInfo firstField;
FieldInfo secondField;
Type sourceType;
object secondValue;
void Init()
{
data = (VisibleIfAttribute)attribute;
sourceType = fieldInfo.DeclaringType;
var firstField = sourceType.GetField(data.FieldName, BindingFlags.Public | BindingFlags.Instance);
if (firstField == null)
{
firstField = sourceType.GetField(data.FieldName, BindingFlags.NonPublic | BindingFlags.Instance);
}
if (firstField == null)
{
throw new Exception($"Could not find the field {data.FieldName} on type {sourceType}");
}
if (data.FieldToCompareTo != null)
{
secondField = sourceType.GetField(data.FieldToCompareTo, BindingFlags.Public | BindingFlags.Instance);
if (secondField == null)
{
secondField = sourceType.GetField(data.FieldToCompareTo, BindingFlags.NonPublic | BindingFlags.Instance);
}
if (secondField == null)
{
throw new Exception($"Could not find the field {data.FieldToCompareTo} on type {sourceType}");
}
}
else
{
secondValue = data.ValueToCompareTo;
}
}
bool ShouldBeVisible
{
get
{
if (secondField != null)
{
}
else
{
var firstValue =
switch (data.Operation)
{
case VisibilityOperation.EqualTo:
return secondValue.Equals();
break;
case VisibilityOperation.NotEqualTo:
break;
case VisibilityOperation.GreaterThan:
break;
case VisibilityOperation.LessThan:
break;
case VisibilityOperation.GreaterThanOrEqual:
break;
case VisibilityOperation.LessThanOrEqual:
break;
default:
break;
}
}
}
}
public override void OnGUI(Rect position, SerializedProperty property, GUIContent label)
{
if (!init)
{
init = true;
Init();
}
base.OnGUI(position, property, label);
}
}
*/ | 20.362745 | 109 | 0.694271 | [
"MIT"
] | nickc01/Nitro | Assets/Editor/VisibleIfDrawer.cs | 2,079 | C# |
using Newtonsoft.Json;
namespace Thenewboston.Validator.Models
{
public class ValidatorBank
{
[JsonProperty(PropertyName = "account_number")]
public string AccountNumber { get; set; }
[JsonProperty(PropertyName = "ip_address")]
public string IpAddress { get; set; }
[JsonProperty(PropertyName = "node_identifier")]
public string NodeIdentifier { get; set; }
[JsonProperty(PropertyName = "port")]
public int? Port { get; set; }
[JsonProperty(PropertyName = "protocol")]
public string Protocol { get; set; }
[JsonProperty(PropertyName = "version")]
public string Version { get; set; }
[JsonProperty(PropertyName = "default_transaction_fee")]
public int DefaultTransactionFee { get; set; }
[JsonProperty(PropertyName = "confirmation_expiration")]
public string ConfirmationExpiration { get; set; }
[JsonProperty(PropertyName = "trust")]
public string Trust { get; set; }
}
}
| 29.885714 | 64 | 0.633843 | [
"MIT"
] | Mirch/dotnetcore-sdk | src/Thenewboston/Validator/Models/ValidatorBank.cs | 1,048 | C# |
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
public class Anchor : MonoBehaviour {
private AnchorCollider maleAnchor;
private AnchorCollider femaleAnchor;
void Awake () {
foreach (AnchorCollider anchorCollider in GetComponentsInChildren<AnchorCollider>()) {
if (anchorCollider.gender == "male")
maleAnchor = anchorCollider;
else if (anchorCollider.gender == "female")
femaleAnchor = anchorCollider;
}
}
public AnchorCollider GetMaleAnchor () {
return maleAnchor;
}
public AnchorCollider GetFemaleAnchor () {
return femaleAnchor;
}
// Return a list of all game objects that are correctly locked with this anchor.
public List<GameObject> GetLockedList () {
List<GameObject> lockedList = new List<GameObject> ();
// Find an anchor that this male is connected to
foreach (AnchorCollider otherFemaleAnchor in maleAnchor.GetAttachedFemales()) {
Anchor otherAnchor = otherFemaleAnchor.GetComponentInParent<Anchor>();
// Check if this female is also connected to the other anchor's male point
if (femaleAnchor.GetAttachedMales().Contains(otherAnchor.GetMaleAnchor())) {
if (!lockedList.Contains(otherAnchor.gameObject))
lockedList.Add(otherAnchor.gameObject);
}
}
return lockedList;
}
}
/*
private MaleAnchor maleAnchor;
private FemaleAnchor femaleAnchor;
void Start () {
foreach (MaleAnchor anchor in GetComponentsInChildren<MaleAnchor>()) {
maleAnchor = anchor;
}
foreach (FemaleAnchor anchor in GetComponentsInChildren<FemaleAnchor>()) {
femaleAnchor = anchor;
}
}
public MaleAnchor GetMaleAnchor () {
return maleAnchor;
}
public FemaleAnchor GetFemaleAnchor () {
return femaleAnchor;
}
// Return a list of all game objects that are correctly locked with this anchor.
public List<GameObject> GetLockedList () {
List<GameObject> lockedList = new List<GameObject> ();
// Find an anchor that this male is connected to
foreach (FemaleAnchor otherFemaleAnchor in maleAnchor.GetAttachedFemales()) {
Anchor otherAnchor = otherFemaleAnchor.GetComponentInParent<Anchor>();
// Check if this female is also connected to the other anchor's male point
if (femaleAnchor.GetAttachedMales().Contains(otherAnchor.GetMaleAnchor())) {
if (!lockedList.Contains(otherAnchor.gameObject))
lockedList.Add(otherAnchor.gameObject);
}
}
return lockedList;
}
*/
| 24.816327 | 88 | 0.738076 | [
"MIT"
] | tomhettinger/PirateStorm | Assets/Scripts/Anchor.cs | 2,434 | C# |
using System;
using FluentAssertions;
using Xunit;
namespace RestSharp.Serializers.Newtonsoft.Json.Tests
{
public class NewtonsoftJsonSerializerTests
{
#region Fields & Properties
private Person PersonObject => new Person()
{
Name = "John Smith",
FavoriteNumber = 34,
FavoriteColor = ConsoleColor.Red,
HasChildren = true,
NetWorth = 231453.56,
DateOfBirth = new DateTime(1956, 8, 12)
};
private string PersonString =>
"{\"Name\":\"John Smith\",\"FavoriteNumber\":34,\"FavoriteColor\":12,\"HasChildren\":true,\"NetWorth\":231453.56,\"DateOfBirth\":\"1956-08-12T00:00:00\"}";
#endregion
[Fact]
public void Serialize()
{
var serializer = NewtonsoftJsonSerializer.Default;
var result = serializer.Serialize(PersonObject);
result.Should().BeEquivalentTo(PersonString);
}
[Fact]
public void Deserialize()
{
var serializer = NewtonsoftJsonSerializer.Default;
var restResponse = new RestResponse() {Content = PersonString};
var result = serializer.Deserialize<Person>(restResponse);
result.Should().BeEquivalentTo(PersonObject);
}
public class Person
{
public string Name { get; set; }
public int FavoriteNumber { get; set; }
public ConsoleColor FavoriteColor { get; set; }
public bool HasChildren { get; set; }
public double NetWorth { get; set; }
public DateTime DateOfBirth { get; set; }
}
}
}
| 30.125 | 167 | 0.578542 | [
"Apache-2.0"
] | adamfisher/RestSharp.Newtonsoft.Json | RestSharp.Serializers.Newtonsoft.Json.Tests/NewtonsoftJsonSerializerTests.cs | 1,687 | C# |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for license information.
namespace Microsoft.Azure.Management.ServiceBus.Fluent
{
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Azure.Management.ResourceManager.Fluent.Core;
using Microsoft.Azure.Management.ResourceManager.Fluent.Core.ResourceActions;
using Microsoft.Azure.Management.ServiceBus.Fluent.Models;
using Microsoft.Azure.Management.ServiceBus.Fluent.Topic.Definition;
using Microsoft.Azure.Management.ServiceBus.Fluent.Topic.Update;
using System.Collections.Generic;
using System;
internal partial class TopicImpl
{
/// <summary>
/// Gets the manager client of this resource type.
/// </summary>
Microsoft.Azure.Management.ServiceBus.Fluent.IServiceBusManager Microsoft.Azure.Management.ResourceManager.Fluent.Core.IHasManager<Microsoft.Azure.Management.ServiceBus.Fluent.IServiceBusManager>.Manager
{
get
{
return this.Manager as Microsoft.Azure.Management.ServiceBus.Fluent.IServiceBusManager;
}
}
/// <summary>
/// Gets the resource ID string.
/// </summary>
string Microsoft.Azure.Management.ResourceManager.Fluent.Core.IHasId.Id
{
get
{
return this.Id;
}
}
/// <summary>
/// Gets the name of the resource.
/// </summary>
string Microsoft.Azure.Management.ResourceManager.Fluent.Core.IHasName.Name
{
get
{
return this.Name;
}
}
/// <summary>
/// The idle interval after which the topic is automatically deleted.
/// Note: unless it is explicitly overridden the default delete on idle duration
/// is infinite (TimeSpan.Max).
/// </summary>
/// <param name="durationInMinutes">Idle duration in minutes.</param>
/// <return>The next stage of topic definition.</return>
Microsoft.Azure.Management.ServiceBus.Fluent.Topic.Definition.IWithCreate Microsoft.Azure.Management.ServiceBus.Fluent.Topic.Definition.IWithDeleteOnIdle.WithDeleteOnIdleDurationInMinutes(int durationInMinutes)
{
return this.WithDeleteOnIdleDurationInMinutes(durationInMinutes) as Microsoft.Azure.Management.ServiceBus.Fluent.Topic.Definition.IWithCreate;
}
/// <summary>
/// The idle interval after which the topic is automatically deleted.
/// </summary>
/// <param name="durationInMinutes">Idle duration in minutes.</param>
/// <return>The next stage of topic update.</return>
Microsoft.Azure.Management.ServiceBus.Fluent.Topic.Update.IUpdate Microsoft.Azure.Management.ServiceBus.Fluent.Topic.Update.IWithDeleteOnIdle.WithDeleteOnIdleDurationInMinutes(int durationInMinutes)
{
return this.WithDeleteOnIdleDurationInMinutes(durationInMinutes) as Microsoft.Azure.Management.ServiceBus.Fluent.Topic.Update.IUpdate;
}
/// <summary>
/// Specifies that the default batching should be disabled on this topic.
/// With batching Service Bus can batch multiple message when it write or delete messages
/// from it's internal store.
/// </summary>
/// <return>The next stage of topic definition.</return>
Microsoft.Azure.Management.ServiceBus.Fluent.Topic.Definition.IWithCreate Microsoft.Azure.Management.ServiceBus.Fluent.Topic.Definition.IWithMessageBatching.WithoutMessageBatching()
{
return this.WithoutMessageBatching() as Microsoft.Azure.Management.ServiceBus.Fluent.Topic.Definition.IWithCreate;
}
/// <summary>
/// Specifies that batching of messages should be disabled when Service Bus write messages to
/// or delete messages from it's internal store.
/// </summary>
/// <return>The next stage of topic update.</return>
Microsoft.Azure.Management.ServiceBus.Fluent.Topic.Update.IUpdate Microsoft.Azure.Management.ServiceBus.Fluent.Topic.Update.IWithMessageBatching.WithoutMessageBatching()
{
return this.WithoutMessageBatching() as Microsoft.Azure.Management.ServiceBus.Fluent.Topic.Update.IUpdate;
}
/// <summary>
/// Specifies that service bus can batch multiple message when it write messages to or delete
/// messages from it's internal store. This increases the throughput.
/// </summary>
/// <return>The next stage of topic update.</return>
Microsoft.Azure.Management.ServiceBus.Fluent.Topic.Update.IUpdate Microsoft.Azure.Management.ServiceBus.Fluent.Topic.Update.IWithMessageBatching.WithMessageBatching()
{
return this.WithMessageBatching() as Microsoft.Azure.Management.ServiceBus.Fluent.Topic.Update.IUpdate;
}
/// <summary>
/// Specifies the duration of the duplicate message detection history.
/// </summary>
/// <param name="duplicateDetectionHistoryDuration">Duration of the history.</param>
/// <return>The next stage of topic definition.</return>
Microsoft.Azure.Management.ServiceBus.Fluent.Topic.Definition.IWithCreate Microsoft.Azure.Management.ServiceBus.Fluent.Topic.Definition.IWithDuplicateMessageDetection.WithDuplicateMessageDetection(TimeSpan duplicateDetectionHistoryDuration)
{
return this.WithDuplicateMessageDetection(duplicateDetectionHistoryDuration) as Microsoft.Azure.Management.ServiceBus.Fluent.Topic.Definition.IWithCreate;
}
/// <summary>
/// Specifies that duplicate message detection needs to be disabled.
/// </summary>
/// <return>The next stage of topic update.</return>
Microsoft.Azure.Management.ServiceBus.Fluent.Topic.Update.IUpdate Microsoft.Azure.Management.ServiceBus.Fluent.Topic.Update.IWithDuplicateMessageDetection.WithoutDuplicateMessageDetection()
{
return this.WithoutDuplicateMessageDetection() as Microsoft.Azure.Management.ServiceBus.Fluent.Topic.Update.IUpdate;
}
/// <summary>
/// Specifies the duration of the duplicate message detection history.
/// </summary>
/// <param name="duration">Duration of the history.</param>
/// <return>The next stage of topic update.</return>
Microsoft.Azure.Management.ServiceBus.Fluent.Topic.Update.IUpdate Microsoft.Azure.Management.ServiceBus.Fluent.Topic.Update.IWithDuplicateMessageDetection.WithDuplicateMessageDetectionHistoryDuration(TimeSpan duration)
{
return this.WithDuplicateMessageDetectionHistoryDuration(duration) as Microsoft.Azure.Management.ServiceBus.Fluent.Topic.Update.IUpdate;
}
/// <summary>
/// Specifies that partitioning should be enabled on this topic.
/// </summary>
/// <return>The next stage of topic definition.</return>
Microsoft.Azure.Management.ServiceBus.Fluent.Topic.Definition.IWithCreate Microsoft.Azure.Management.ServiceBus.Fluent.Topic.Definition.IWithPartitioning.WithPartitioning()
{
return this.WithPartitioning() as Microsoft.Azure.Management.ServiceBus.Fluent.Topic.Definition.IWithCreate;
}
/// <summary>
/// Specifies that the default partitioning should be disabled on this topic.
/// Note: if the parent Service Bus is Premium SKU then partition cannot be
/// disabled.
/// </summary>
/// <return>The next stage of topic definition.</return>
Microsoft.Azure.Management.ServiceBus.Fluent.Topic.Definition.IWithCreate Microsoft.Azure.Management.ServiceBus.Fluent.Topic.Definition.IWithPartitioning.WithoutPartitioning()
{
return this.WithoutPartitioning() as Microsoft.Azure.Management.ServiceBus.Fluent.Topic.Definition.IWithCreate;
}
/// <summary>
/// Creates a send authorization rule for the topic.
/// </summary>
/// <param name="name">Rule name.</param>
/// <return>Next stage of the topic definition.</return>
Microsoft.Azure.Management.ServiceBus.Fluent.Topic.Definition.IWithCreate Microsoft.Azure.Management.ServiceBus.Fluent.Topic.Definition.IWithAuthorizationRule.WithNewSendRule(string name)
{
return this.WithNewSendRule(name) as Microsoft.Azure.Management.ServiceBus.Fluent.Topic.Definition.IWithCreate;
}
/// <summary>
/// Creates a manage authorization rule for the topic.
/// </summary>
/// <param name="name">Rule name.</param>
/// <return>Next stage of the topic definition.</return>
Microsoft.Azure.Management.ServiceBus.Fluent.Topic.Definition.IWithCreate Microsoft.Azure.Management.ServiceBus.Fluent.Topic.Definition.IWithAuthorizationRule.WithNewManageRule(string name)
{
return this.WithNewManageRule(name) as Microsoft.Azure.Management.ServiceBus.Fluent.Topic.Definition.IWithCreate;
}
/// <summary>
/// Creates a listen authorization rule for the topic.
/// </summary>
/// <param name="name">Rule name.</param>
/// <return>Next stage of the topic definition.</return>
Microsoft.Azure.Management.ServiceBus.Fluent.Topic.Definition.IWithCreate Microsoft.Azure.Management.ServiceBus.Fluent.Topic.Definition.IWithAuthorizationRule.WithNewListenRule(string name)
{
return this.WithNewListenRule(name) as Microsoft.Azure.Management.ServiceBus.Fluent.Topic.Definition.IWithCreate;
}
/// <summary>
/// Creates a send authorization rule for the topic.
/// </summary>
/// <param name="name">Rule name.</param>
/// <return>Next stage of the topic update.</return>
Microsoft.Azure.Management.ServiceBus.Fluent.Topic.Update.IUpdate Microsoft.Azure.Management.ServiceBus.Fluent.Topic.Update.IWithAuthorizationRule.WithNewSendRule(string name)
{
return this.WithNewSendRule(name) as Microsoft.Azure.Management.ServiceBus.Fluent.Topic.Update.IUpdate;
}
/// <summary>
/// Creates a manage authorization rule for the topic.
/// </summary>
/// <param name="name">Rule name.</param>
/// <return>Next stage of the topic update.</return>
Microsoft.Azure.Management.ServiceBus.Fluent.Topic.Update.IUpdate Microsoft.Azure.Management.ServiceBus.Fluent.Topic.Update.IWithAuthorizationRule.WithNewManageRule(string name)
{
return this.WithNewManageRule(name) as Microsoft.Azure.Management.ServiceBus.Fluent.Topic.Update.IUpdate;
}
/// <summary>
/// Creates a listen authorization rule for the topic.
/// </summary>
/// <param name="name">Rule name.</param>
/// <return>Next stage of the topic update.</return>
Microsoft.Azure.Management.ServiceBus.Fluent.Topic.Update.IUpdate Microsoft.Azure.Management.ServiceBus.Fluent.Topic.Update.IWithAuthorizationRule.WithNewListenRule(string name)
{
return this.WithNewListenRule(name) as Microsoft.Azure.Management.ServiceBus.Fluent.Topic.Update.IUpdate;
}
/// <summary>
/// Removes an authorization rule for the topic.
/// </summary>
/// <param name="name">Rule name.</param>
/// <return>Next stage of the topic update.</return>
Microsoft.Azure.Management.ServiceBus.Fluent.Topic.Update.IUpdate Microsoft.Azure.Management.ServiceBus.Fluent.Topic.Update.IWithAuthorizationRule.WithoutAuthorizationRule(string name)
{
return this.WithoutAuthorizationRule(name) as Microsoft.Azure.Management.ServiceBus.Fluent.Topic.Update.IUpdate;
}
/// <summary>
/// Creates a subscription entity for the Service Bus topic.
/// </summary>
/// <param name="name">Queue name.</param>
/// <return>The next stage of topic definition.</return>
Microsoft.Azure.Management.ServiceBus.Fluent.Topic.Definition.IWithCreate Microsoft.Azure.Management.ServiceBus.Fluent.Topic.Definition.IWithSubscription.WithNewSubscription(string name)
{
return this.WithNewSubscription(name) as Microsoft.Azure.Management.ServiceBus.Fluent.Topic.Definition.IWithCreate;
}
/// <summary>
/// Creates a subscription entity for the Service Bus topic.
/// </summary>
/// <param name="name">Queue name.</param>
/// <return>Next stage of the Service Bus topic update.</return>
Microsoft.Azure.Management.ServiceBus.Fluent.Topic.Update.IUpdate Microsoft.Azure.Management.ServiceBus.Fluent.Topic.Update.IWithSubscription.WithNewSubscription(string name)
{
return this.WithNewSubscription(name) as Microsoft.Azure.Management.ServiceBus.Fluent.Topic.Update.IUpdate;
}
/// <summary>
/// Removes a subscription entity associated with the Service Bus topic.
/// </summary>
/// <param name="name">Subscription name.</param>
/// <return>Next stage of the Service Bus topic update.</return>
Microsoft.Azure.Management.ServiceBus.Fluent.Topic.Update.IUpdate Microsoft.Azure.Management.ServiceBus.Fluent.Topic.Update.IWithSubscription.WithoutSubscription(string name)
{
return this.WithoutSubscription(name) as Microsoft.Azure.Management.ServiceBus.Fluent.Topic.Update.IUpdate;
}
/// <summary>
/// Specifies the duration after which the message expires.
/// Note: unless it is explicitly overridden the default ttl is infinite (TimeSpan.Max).
/// </summary>
/// <param name="ttl">Time to live duration.</param>
/// <return>The next stage of topic definition.</return>
Microsoft.Azure.Management.ServiceBus.Fluent.Topic.Definition.IWithCreate Microsoft.Azure.Management.ServiceBus.Fluent.Topic.Definition.IWithDefaultMessageTTL.WithDefaultMessageTTL(TimeSpan ttl)
{
return this.WithDefaultMessageTTL(ttl) as Microsoft.Azure.Management.ServiceBus.Fluent.Topic.Definition.IWithCreate;
}
/// <summary>
/// Specifies the duration after which the message expires.
/// </summary>
/// <param name="ttl">Time to live duration.</param>
/// <return>The next stage of topic update.</return>
Microsoft.Azure.Management.ServiceBus.Fluent.Topic.Update.IUpdate Microsoft.Azure.Management.ServiceBus.Fluent.Topic.Update.IWithDefaultMessageTTL.WithDefaultMessageTTL(TimeSpan ttl)
{
return this.WithDefaultMessageTTL(ttl) as Microsoft.Azure.Management.ServiceBus.Fluent.Topic.Update.IUpdate;
}
/// <summary>
/// Gets number of subscriptions for the topic.
/// </summary>
int Microsoft.Azure.Management.ServiceBus.Fluent.ITopic.SubscriptionCount
{
get
{
return this.SubscriptionCount();
}
}
/// <summary>
/// Gets number of messages transferred to another topic, topic, or subscription.
/// </summary>
long Microsoft.Azure.Management.ServiceBus.Fluent.ITopic.TransferMessageCount
{
get
{
return this.TransferMessageCount();
}
}
/// <summary>
/// Gets the maximum size of memory allocated for the topic in megabytes.
/// </summary>
long Microsoft.Azure.Management.ServiceBus.Fluent.ITopic.MaxSizeInMB
{
get
{
return this.MaxSizeInMB();
}
}
/// <summary>
/// Gets the exact time the topic was created.
/// </summary>
System.DateTime Microsoft.Azure.Management.ServiceBus.Fluent.ITopic.CreatedAt
{
get
{
return this.CreatedAt();
}
}
/// <summary>
/// Gets number of messages sent to the topic that are yet to be released
/// for consumption.
/// </summary>
long Microsoft.Azure.Management.ServiceBus.Fluent.ITopic.ScheduledMessageCount
{
get
{
return this.ScheduledMessageCount();
}
}
/// <summary>
/// Gets indicates whether express entities are enabled.
/// </summary>
bool Microsoft.Azure.Management.ServiceBus.Fluent.ITopic.IsExpressEnabled
{
get
{
return this.IsExpressEnabled();
}
}
/// <summary>
/// Gets current size of the topic, in bytes.
/// </summary>
long Microsoft.Azure.Management.ServiceBus.Fluent.ITopic.CurrentSizeInBytes
{
get
{
return this.CurrentSizeInBytes();
}
}
/// <summary>
/// Gets number of active messages in the topic.
/// </summary>
long Microsoft.Azure.Management.ServiceBus.Fluent.ITopic.ActiveMessageCount
{
get
{
return this.ActiveMessageCount();
}
}
/// <summary>
/// Gets entry point to manage subscriptions associated with the topic.
/// </summary>
Microsoft.Azure.Management.ServiceBus.Fluent.ISubscriptions Microsoft.Azure.Management.ServiceBus.Fluent.ITopic.Subscriptions
{
get
{
return this.Subscriptions() as Microsoft.Azure.Management.ServiceBus.Fluent.ISubscriptions;
}
}
/// <summary>
/// Gets the current status of the topic.
/// </summary>
Microsoft.Azure.Management.ServiceBus.Fluent.Models.EntityStatus Microsoft.Azure.Management.ServiceBus.Fluent.ITopic.Status
{
get
{
return this.Status();
}
}
/// <summary>
/// Gets the duration after which the message expires, starting from when the message is sent to topic.
/// </summary>
System.TimeSpan Microsoft.Azure.Management.ServiceBus.Fluent.ITopic.DefaultMessageTtlDuration
{
get
{
return this.DefaultMessageTtlDuration();
}
}
/// <summary>
/// Gets entry point to manage authorization rules for the Service Bus topic.
/// </summary>
Microsoft.Azure.Management.ServiceBus.Fluent.ITopicAuthorizationRules Microsoft.Azure.Management.ServiceBus.Fluent.ITopic.AuthorizationRules
{
get
{
return this.AuthorizationRules() as Microsoft.Azure.Management.ServiceBus.Fluent.ITopicAuthorizationRules;
}
}
/// <summary>
/// Gets last time a message was sent, or the last time there was a receive request to this topic.
/// </summary>
System.DateTime Microsoft.Azure.Management.ServiceBus.Fluent.ITopic.AccessedAt
{
get
{
return this.AccessedAt();
}
}
/// <summary>
/// Gets indicates whether the topic is to be partitioned across multiple message brokers.
/// </summary>
bool Microsoft.Azure.Management.ServiceBus.Fluent.ITopic.IsPartitioningEnabled
{
get
{
return this.IsPartitioningEnabled();
}
}
/// <summary>
/// Gets number of messages transferred into dead letters.
/// </summary>
long Microsoft.Azure.Management.ServiceBus.Fluent.ITopic.TransferDeadLetterMessageCount
{
get
{
return this.TransferDeadLetterMessageCount();
}
}
/// <summary>
/// Gets the idle duration after which the topic is automatically deleted.
/// </summary>
long Microsoft.Azure.Management.ServiceBus.Fluent.ITopic.DeleteOnIdleDurationInMinutes
{
get
{
return this.DeleteOnIdleDurationInMinutes();
}
}
/// <summary>
/// Gets indicates whether server-side batched operations are enabled.
/// </summary>
bool Microsoft.Azure.Management.ServiceBus.Fluent.ITopic.IsBatchedOperationsEnabled
{
get
{
return this.IsBatchedOperationsEnabled();
}
}
/// <summary>
/// Gets indicates if this topic requires duplicate detection.
/// </summary>
bool Microsoft.Azure.Management.ServiceBus.Fluent.ITopic.IsDuplicateDetectionEnabled
{
get
{
return this.IsDuplicateDetectionEnabled();
}
}
/// <summary>
/// Gets number of messages in the dead-letter topic.
/// </summary>
long Microsoft.Azure.Management.ServiceBus.Fluent.ITopic.DeadLetterMessageCount
{
get
{
return this.DeadLetterMessageCount();
}
}
/// <summary>
/// Gets the exact time the topic was updated.
/// </summary>
System.DateTime Microsoft.Azure.Management.ServiceBus.Fluent.ITopic.UpdatedAt
{
get
{
return this.UpdatedAt();
}
}
/// <summary>
/// Gets the duration of the duplicate detection history.
/// </summary>
System.TimeSpan Microsoft.Azure.Management.ServiceBus.Fluent.ITopic.DuplicateMessageDetectionHistoryDuration
{
get
{
return this.DuplicateMessageDetectionHistoryDuration();
}
}
/// <summary>
/// Gets the name of the region the resource is in.
/// </summary>
string Microsoft.Azure.Management.ResourceManager.Fluent.Core.IResource.RegionName
{
get
{
return this.RegionName;
}
}
/// <summary>
/// Gets the type of the resource.
/// </summary>
string Microsoft.Azure.Management.ResourceManager.Fluent.Core.IResource.Type
{
get
{
return this.Type;
}
}
/// <summary>
/// Gets the region the resource is in.
/// </summary>
Microsoft.Azure.Management.ResourceManager.Fluent.Core.Region Microsoft.Azure.Management.ResourceManager.Fluent.Core.IResource.Region
{
get
{
return this.Region as Microsoft.Azure.Management.ResourceManager.Fluent.Core.Region;
}
}
/// <summary>
/// Gets the tags for the resource.
/// </summary>
System.Collections.Generic.IReadOnlyDictionary<string, string> Microsoft.Azure.Management.ResourceManager.Fluent.Core.IResource.Tags
{
get
{
return this.Tags as System.Collections.Generic.IReadOnlyDictionary<string, string>;
}
}
/// <summary>
/// Specifies the maximum size of memory allocated for the topic.
/// </summary>
/// <param name="sizeInMB">Size in MB.</param>
/// <return>The next stage of topic definition.</return>
Microsoft.Azure.Management.ServiceBus.Fluent.Topic.Definition.IWithCreate Microsoft.Azure.Management.ServiceBus.Fluent.Topic.Definition.IWithSize.WithSizeInMB(long sizeInMB)
{
return this.WithSizeInMB(sizeInMB) as Microsoft.Azure.Management.ServiceBus.Fluent.Topic.Definition.IWithCreate;
}
/// <summary>
/// Specifies the maximum size of memory allocated for the topic.
/// </summary>
/// <param name="sizeInMB">Size in MB.</param>
/// <return>The next stage of topic update.</return>
Microsoft.Azure.Management.ServiceBus.Fluent.Topic.Update.IUpdate Microsoft.Azure.Management.ServiceBus.Fluent.Topic.Update.IWithSize.WithSizeInMB(long sizeInMB)
{
return this.WithSizeInMB(sizeInMB) as Microsoft.Azure.Management.ServiceBus.Fluent.Topic.Update.IUpdate;
}
/// <summary>
/// Specifies that messages in this topic are express hence they can be cached in memory
/// for some time before storing it in messaging store.
/// Note: By default topic is not express.
/// </summary>
/// <return>The next stage of topic definition.</return>
Microsoft.Azure.Management.ServiceBus.Fluent.Topic.Definition.IWithCreate Microsoft.Azure.Management.ServiceBus.Fluent.Topic.Definition.IWithExpressMessage.WithExpressMessage()
{
return this.WithExpressMessage() as Microsoft.Azure.Management.ServiceBus.Fluent.Topic.Definition.IWithCreate;
}
/// <summary>
/// Specifies that messages in this topic are not express hence they should be cached in memory.
/// </summary>
/// <return>The next stage of topic update.</return>
Microsoft.Azure.Management.ServiceBus.Fluent.Topic.Update.IUpdate Microsoft.Azure.Management.ServiceBus.Fluent.Topic.Update.IWithExpressMessage.WithoutExpressMessage()
{
return this.WithoutExpressMessage() as Microsoft.Azure.Management.ServiceBus.Fluent.Topic.Update.IUpdate;
}
/// <summary>
/// Specifies that messages in this topic are express hence they can be cached in memory
/// for some time before storing it in messaging store.
/// </summary>
/// <return>The next stage of topic update.</return>
Microsoft.Azure.Management.ServiceBus.Fluent.Topic.Update.IUpdate Microsoft.Azure.Management.ServiceBus.Fluent.Topic.Update.IWithExpressMessage.WithExpressMessage()
{
return this.WithExpressMessage() as Microsoft.Azure.Management.ServiceBus.Fluent.Topic.Update.IUpdate;
}
/// <summary>
/// Gets the name of the resource group.
/// </summary>
string Microsoft.Azure.Management.ResourceManager.Fluent.Core.IHasResourceGroup.ResourceGroupName
{
get
{
return this.ResourceGroupName;
}
}
}
} | 43.6 | 248 | 0.640435 | [
"MIT"
] | abharath27/azure-libraries-for-net | src/ResourceManagement/ServiceBus/Domain/InterfaceImpl/TopicImpl.cs | 26,596 | C# |
using System;
using System.Linq;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
/*
1.02 - RemoveChild method
*/
namespace Battlehub.UIControls
{
/// <summary>
/// Data Item Expanding event arguments
/// </summary>
public class ItemExpandingArgs : EventArgs
{
/// <summary>
/// Data Item
/// </summary>
public object Item
{
get;
private set;
}
/// <summary>
/// Specify item's children using this property
/// </summary>
public IEnumerable Children
{
get;
set;
}
public ItemExpandingArgs(object item)
{
Item = item;
}
}
/// <summary>
/// TreeView data binding event arguments
/// </summary>
public class TreeViewItemDataBindingArgs : ItemDataBindingArgs
{
/// <summary>
/// Set to true if data bound item has children
/// </summary>
public bool HasChildren
{
get;
set;
}
}
public class TreeView : ItemsControl<TreeViewItemDataBindingArgs>
{
/// <summary>
/// Raised on item expanding
/// </summary>
public event EventHandler<ItemExpandingArgs> ItemExpanding;
/// <summary>
/// Indent between parent and children
/// </summary>
public int Indent = 20;
public bool CanReparent = true;
protected override bool CanScroll
{
get { return base.CanScroll || CanReparent; }
}
/// <summary>
/// Auto Expand items
/// </summary>
public bool AutoExpand = false;
protected override void OnEnableOverride()
{
base.OnEnableOverride();
TreeViewItem.ParentChanged += OnTreeViewItemParentChanged;
}
protected override void OnDisableOverride()
{
base.OnDisableOverride();
TreeViewItem.ParentChanged -= OnTreeViewItemParentChanged;
}
public TreeViewItem GetTreeViewItem(int siblingIndex)
{
return (TreeViewItem)GetItemContainer(siblingIndex);
}
public TreeViewItem GetTreeViewItem(object obj)
{
return (TreeViewItem)GetItemContainer(obj);
}
/// <summary>
/// Add data item as last child of parent
/// </summary>
/// <param name="parent">parent data item</param>
/// <param name="item">data item to add</param>
public void AddChild(object parent, object item)
{
if (parent == null)
{
Add(item);
}
else
{
TreeViewItem parentContainer = (TreeViewItem)GetItemContainer(parent);
if(parentContainer == null)
{
return;
}
int index = -1;
if (parentContainer.IsExpanded)
{
if (parentContainer.HasChildren)
{
TreeViewItem lastDescendant = parentContainer.LastDescendant();
index = IndexOf(lastDescendant.Item) + 1;
}
else
{
index = IndexOf(parentContainer.Item) + 1;
}
}
else
{
parentContainer.CanExpand = true;
}
if(index > -1)
{
TreeViewItem addedItem = (TreeViewItem)Insert(index, item);
addedItem.Parent = parentContainer;
}
}
}
public override void Remove(object item)
{
throw new NotSupportedException("This method is not supported for TreeView use RemoveChild instead");
}
public void RemoveChild(object parent, object item, bool isLastChild)
{
if(parent == null)
{
base.Remove(item);
}
else
{
if(GetItemContainer(item) != null)
{
base.Remove(item);
}
else
{
//Parent item is not expanded (if isLastChild just remove parent expander
if (isLastChild)
{
TreeViewItem parentContainer = (TreeViewItem)GetItemContainer(parent);
if (parentContainer)
{
parentContainer.CanExpand = false;
}
}
}
}
}
/// <summary>
/// Change data item parent
/// </summary>
/// <param name="parent">new parent</param>
/// <param name="item">data item</param>
public void ChangeParent(object parent, object item)
{
if(IsDropInProgress)
{
return;
}
ItemContainer dragItem = GetItemContainer(item);
if (dragItem == null)
{
return;
}
ItemContainer dropTarget = GetItemContainer(parent);
ItemContainer[] dragItems = new[] { dragItem };
if (CanDrop(dragItems, dropTarget))
{
Drop(dragItems, dropTarget, ItemDropAction.SetLastChild);
}
}
/// <summary>
/// Check wheter item is expanded
/// </summary>
/// <param name="item"></param>
/// <returns></returns>
public bool IsExpanded(object item)
{
TreeViewItem itemContainer = (TreeViewItem)GetItemContainer(item);
if(itemContainer == null)
{
return false;
}
return itemContainer.IsExpanded;
}
/// <summary>
/// To prevent Expand method call during drag drop operation
/// </summary>
private bool m_expandSilently;
/// <summary>
/// Expand Tree View Item
/// </summary>
/// <param name="item">tree view item to expand</param>
public void Expand(TreeViewItem item)
{
if(m_expandSilently)
{
return;
}
if(ItemExpanding != null)
{
ItemExpandingArgs args = new ItemExpandingArgs(item.Item);
ItemExpanding(this, args);
IEnumerable children = args.Children;
int containerIndex = item.transform.GetSiblingIndex();
int itemIndex = IndexOf(item.Item);
item.CanExpand = children != null;
if (item.CanExpand)
{
foreach(object childItem in children)
{
containerIndex++;
itemIndex++;
InsertItem(itemIndex, childItem);
TreeViewItem childContainer = (TreeViewItem)InstantiateItemContainer(containerIndex);
childContainer.Item = childItem;
childContainer.Parent = item;
DataBindItem(childItem, childContainer);
}
UpdateSelectedItemIndex();
}
}
}
/// <summary>
/// Collapse tree view item
/// </summary>
/// <param name="item">tree view item to collapse</param>
public void Collapse(TreeViewItem item)
{
int containerIndex = item.transform.GetSiblingIndex();
int itemIndex = IndexOf(item.Item);
Collapse(item, containerIndex + 1, itemIndex + 1);
}
private void Unselect(List<object> selectedItems, TreeViewItem item, ref int containerIndex, ref int itemIndex )
{
while (true)
{
TreeViewItem child = (TreeViewItem)GetItemContainer(containerIndex);
if (child == null || child.Parent != item)
{
break;
}
containerIndex++;
itemIndex++;
selectedItems.Remove(child.Item);
Unselect(selectedItems, child, ref containerIndex, ref itemIndex);
}
}
private void Collapse(TreeViewItem item, int containerIndex, int itemIndex)
{
while (true)
{
TreeViewItem child = (TreeViewItem)GetItemContainer(containerIndex);
if (child == null || child.Parent != item)
{
break;
}
Collapse(child, containerIndex + 1, itemIndex + 1);
RemoveItemAt(itemIndex);
DestroyItemContainer(containerIndex);
}
}
protected override ItemContainer InstantiateItemContainerOverride(GameObject container)
{
TreeViewItem itemContainer = container.GetComponent<TreeViewItem>();
if (itemContainer == null)
{
itemContainer = container.AddComponent<TreeViewItem>();
itemContainer.gameObject.name = "TreeViewItem";
}
return itemContainer;
}
protected override void DestroyItem(object item)
{
TreeViewItem itemContainer = (TreeViewItem)GetItemContainer(item);
if(itemContainer != null)
{
Collapse(itemContainer);
base.DestroyItem(item);
if(itemContainer.Parent != null && !itemContainer.Parent.HasChildren)
{
itemContainer.Parent.CanExpand = false;
}
}
}
public override void DataBindItem(object item, ItemContainer itemContainer)
{
TreeViewItemDataBindingArgs args = new TreeViewItemDataBindingArgs();
args.Item = item;
args.ItemPresenter = itemContainer.ItemPresenter == null ? gameObject : itemContainer.ItemPresenter;
args.EditorPresenter = itemContainer.EditorPresenter == null ? gameObject : itemContainer.EditorPresenter;
RaiseItemDataBinding(args);
TreeViewItem treeViewItem = (TreeViewItem)itemContainer;
treeViewItem.CanExpand = args.HasChildren;
treeViewItem.CanEdit = args.CanEdit;
treeViewItem.CanDrag = args.CanDrag;
treeViewItem.CanDrop = args.CanBeParent;
}
protected override bool CanDrop(ItemContainer[] dragItems, ItemContainer dropTarget)
{
if(!base.CanDrop(dragItems, dropTarget))
{
return false;
}
TreeViewItem tvDropTarget = (TreeViewItem)dropTarget;
if (tvDropTarget == null)
{
return true;
}
foreach(ItemContainer dragItem in dragItems)
{
TreeViewItem tvDragItem = (TreeViewItem)dragItem;
if (tvDropTarget.IsDescendantOf(tvDragItem))
{
return false;
}
}
return true;
}
private void OnTreeViewItemParentChanged(object sender, ParentChangedEventArgs e)
{
TreeViewItem tvItem = (TreeViewItem)sender;
if (!CanHandleEvent(tvItem))
{
return;
}
TreeViewItem oldParent = e.OldParent;
if (DropMarker.Action != ItemDropAction.SetLastChild && DropMarker.Action != ItemDropAction.None)
{
if (oldParent != null && !oldParent.HasChildren)
{
oldParent.CanExpand = false;
}
return;
}
TreeViewItem tvDropTarget = e.NewParent;
if(tvDropTarget != null)
{
if (tvDropTarget.CanExpand)
{
tvDropTarget.IsExpanded = true;
}
else
{
tvDropTarget.CanExpand = true;
try
{
m_expandSilently = true;
tvDropTarget.IsExpanded = true;
}
finally
{
m_expandSilently = false;
}
}
}
TreeViewItem dragItemChild = tvItem.FirstChild();
TreeViewItem lastChild = null;
if(tvDropTarget != null)
{
lastChild = tvDropTarget.LastChild();
if (lastChild == null)
{
lastChild = tvDropTarget;
}
}
else
{
lastChild = (TreeViewItem)LastItemContainer();
}
if(lastChild != tvItem)
{
TreeViewItem lastDescendant = lastChild.LastDescendant();
if(lastDescendant != null)
{
lastChild = lastDescendant;
}
if(!lastChild.IsDescendantOf(tvItem))
{
base.SetNextSibling(lastChild, tvItem);
}
}
if (dragItemChild != null)
{
MoveSubtree(tvItem, dragItemChild);
}
if (oldParent != null && !oldParent.HasChildren)
{
oldParent.CanExpand = false;
}
}
private void MoveSubtree(TreeViewItem parent, TreeViewItem child)
{
int parentSiblingIndex = parent.transform.GetSiblingIndex();
int siblingIndex = child.transform.GetSiblingIndex();
bool incrementSiblingIndex = false;
if(parentSiblingIndex < siblingIndex)
{
incrementSiblingIndex = true;
}
TreeViewItem prev = parent;
while (child != null && child.IsDescendantOf(parent))
{
if(prev == child)
{
break;
}
base.SetNextSibling(prev, child);
prev = child;
if(incrementSiblingIndex)
{
siblingIndex++;
}
child = (TreeViewItem)GetItemContainer(siblingIndex);
}
}
protected override void Drop(ItemContainer[] dragItems, ItemContainer dropTarget, ItemDropAction action)
{
TreeViewItem tvDropTarget = (TreeViewItem)dropTarget;
if (action == ItemDropAction.SetLastChild)
{
for (int i = 0; i < dragItems.Length; ++i)
{
TreeViewItem tvDragItem = (TreeViewItem)dragItems[i];
if(tvDropTarget != tvDragItem) //disallow self parenting
{
tvDragItem.Parent = tvDropTarget;
}
}
}
else if (action == ItemDropAction.SetPrevSibling)
{
for (int i = 0; i < dragItems.Length; ++i)
{
SetPrevSibling(tvDropTarget, dragItems[i]);
}
}
else if (action == ItemDropAction.SetNextSibling)
{
for (int i = dragItems.Length - 1; i >= 0; --i)
{
SetNextSibling(tvDropTarget, dragItems[i]);
}
}
UpdateSelectedItemIndex();
}
protected override void SetNextSibling(ItemContainer sibling, ItemContainer nextSibling)
{
TreeViewItem tvSibling = (TreeViewItem)sibling;
TreeViewItem lastDescendant = tvSibling.LastDescendant();
if(lastDescendant == null)
{
lastDescendant = tvSibling;
}
TreeViewItem tvItem = (TreeViewItem)nextSibling;
TreeViewItem dragItemChild = tvItem.FirstChild();
base.SetNextSibling(lastDescendant, nextSibling);
if (dragItemChild != null)
{
MoveSubtree(tvItem, dragItemChild);
}
tvItem.Parent = tvSibling.Parent;
}
protected override void SetPrevSibling(ItemContainer sibling, ItemContainer prevSibling)
{
TreeViewItem tvSibling = (TreeViewItem)sibling;
TreeViewItem tvItem = (TreeViewItem)prevSibling;
TreeViewItem dragItemChild = tvItem.FirstChild();
base.SetPrevSibling(sibling, prevSibling);
if (dragItemChild != null)
{
MoveSubtree(tvItem, dragItemChild);
}
tvItem.Parent = tvSibling.Parent;
}
public void UpdateIndent(object obj)
{
TreeViewItem item = GetTreeViewItem(obj);
if (item == null)
{
return;
}
item.UpdateIndent();
}
public void FixScrollRect()
{
Canvas.ForceUpdateCanvases();
RectTransform rt = Panel.GetComponent<RectTransform>();
rt.SetSizeWithCurrentAnchors(RectTransform.Axis.Vertical, rt.rect.height - 0.01f);
}
}
}
| 30.765921 | 120 | 0.485818 | [
"MIT"
] | dayfox5317/ET_Lua | Unity/Assets/Cold/UIControls/TreeView/TreeView.cs | 17,877 | C# |
// <copyright>
// Copyright 2013 by the Spark Development Network
//
// 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.
// </copyright>
//
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.IO;
using System.Linq;
using System.Web.UI;
using System.Web.UI.WebControls;
using Rock;
using Rock.Data;
using Rock.Model;
using Rock.Web.Cache;
using Rock.Web.UI.Controls;
using Rock.Attribute;
using Rock.Security;
namespace RockWeb.Blocks.Groups
{
/// <summary>
/// Template block for developers to use to start a new block.
/// </summary>
[DisplayName( "Group Member Add From URL" )]
[Category( "Groups" )]
[Description( "Adds a person to a group based on inputs from the URL query string." )]
[GroupField("Default Group", "The default group to use if one is not passed through the query string (optional).", false)]
[GroupRoleField("", "Default Group Member Role", "The default role to use if one is not passed through the quert string (optional).", false)]
[CodeEditorField("Success Message", "Lava template to display when person has been added to the group.", CodeEditorMode.Lava, CodeEditorTheme.Rock, 300, true, @"<div class='alert alert-success'>
{{ Person.NickName }} has been added to the group '{{ Group.Name }}' with the role of {{ Role.Name }}.
</div>")]
[CodeEditorField( "Already In Group Message", "Lava template to display when person is already in the group with that role.", CodeEditorMode.Lava, CodeEditorTheme.Rock, 300, true, @"<div class='alert alert-warning'>
{{ Person.NickName }} is already in the group '{{ Group.Name }}' with the role of {{ Role.Name }}.
</div>" )]
[BooleanField("Enable Debug", "Shows the Lava variables availabled for this block")]
[EnumField("Group Member Status", "The status to use when adding a person to the group.", typeof(GroupMemberStatus), true, "Active")]
public partial class GroupMemberAddFromUrl : Rock.Web.UI.RockBlock
{
#region Fields
// used for private variables
#endregion
#region Properties
// used for public / protected properties
#endregion
#region Base Control Methods
// overrides of the base RockBlock methods (i.e. OnInit, OnLoad)
/// <summary>
/// Raises the <see cref="E:System.Web.UI.Control.Init" /> event.
/// </summary>
/// <param name="e">An <see cref="T:System.EventArgs" /> object that contains the event data.</param>
protected override void OnInit( EventArgs e )
{
base.OnInit( e );
// this event gets fired after block settings are updated. it's nice to repaint the screen if these settings would alter it
this.BlockUpdated += Block_BlockUpdated;
this.AddConfigurationUpdateTrigger( upnlContent );
}
/// <summary>
/// Raises the <see cref="E:System.Web.UI.Control.Load" /> event.
/// </summary>
/// <param name="e">The <see cref="T:System.EventArgs" /> object that contains the event data.</param>
protected override void OnLoad( EventArgs e )
{
base.OnLoad( e );
if ( !Page.IsPostBack )
{
RockContext rockContext = new RockContext();
Group group = null;
Guid personGuid = Guid.Empty;
GroupTypeRole groupMemberRole = null;
// get group id from url
if ( Request["GroupId"] != null )
{
int groupId = 0;
if ( Int32.TryParse( Request["GroupId"], out groupId ) )
{
group = new GroupService( rockContext ).Queryable("GroupType,GroupType.Roles").Where(g => g.Id == groupId ).FirstOrDefault();
}
}
else
{
Guid groupGuid = Guid.Empty;
if ( Guid.TryParse( GetAttributeValue( "DefaultGroup" ), out groupGuid ) ) {
group = new GroupService( rockContext ).Queryable( "GroupType,GroupType.Roles" ).Where( g => g.Guid == groupGuid ).FirstOrDefault(); ;
}
}
if ( group == null )
{
lAlerts.Text = "Could not determine the group to add to.";
return;
}
// get group role id from url
if ( Request["GroupMemberRoleId"] != null )
{
int groupMemberRoleId = 0;
if ( Int32.TryParse( Request["GroupMemberRoleId"], out groupMemberRoleId ) )
{
groupMemberRole = new GroupTypeRoleService( rockContext ).Get( groupMemberRoleId );
}
}
else
{
Guid groupMemberRoleGuid = Guid.Empty;
if ( Guid.TryParse( GetAttributeValue( "DefaultGroupMemberRole" ), out groupMemberRoleGuid ) )
{
groupMemberRole = new GroupTypeRoleService( rockContext ).Get( groupMemberRoleGuid );
}
}
if ( groupMemberRole == null )
{
lAlerts.Text += "Could not determine the group role to use for the add.";
return;
}
// get person
if ( Request["PersonGuid"] != null )
{
Guid.TryParse( Request["PersonGuid"], out personGuid );
}
if ( personGuid == Guid.Empty )
{
lAlerts.Text += "A valid person identifier was not found in the page address.";
return;
}
// ensure that the group type has this role
if ( ! group.GroupType.Roles.Contains( groupMemberRole ) )
{
lAlerts.Text += "The group you have provided does not have the group member role configured.";
return;
}
// get person
Person person = new PersonService( rockContext ).Get( personGuid );
if ( person == null )
{
lAlerts.Text += "A person could not be found for the identifier provided.";
return;
}
// hide alert
divAlert.Visible = false;
// get status
var groupMemberStatus = this.GetAttributeValue( "GroupMemberStatus" ).ConvertToEnum<GroupMemberStatus>( GroupMemberStatus.Active );
// load merge fields
var mergeFields = new Dictionary<string, object>();
mergeFields.Add( "GroupMemberStatus", groupMemberStatus.ToString() );
mergeFields.Add( "Group", group );
mergeFields.Add( "Person", person );
mergeFields.Add( "Role", groupMemberRole );
mergeFields.Add( "CurrentPerson", CurrentPerson );
// show debug info?
bool enableDebug = GetAttributeValue( "EnableDebug" ).AsBoolean();
if ( enableDebug && IsUserAuthorized( Authorization.EDIT ) )
{
lDebug.Visible = true;
lDebug.Text = mergeFields.lavaDebugInfo();
}
// ensure that the person is not already in the group
if ( group.Members.Where( m => m.PersonId == person.Id && m.GroupRoleId == groupMemberRole.Id ).Count() != 0 )
{
string templateInGroup = GetAttributeValue( "AlreadyInGroupMessage" );
lContent.Text = templateInGroup.ResolveMergeFields( mergeFields );
return;
}
// add person to group
GroupMember groupMember = new GroupMember();
groupMember.GroupId = group.Id;
groupMember.PersonId = person.Id;
groupMember.GroupRoleId = groupMemberRole.Id;
groupMember.GroupMemberStatus = groupMemberStatus;
group.Members.Add( groupMember );
try
{
rockContext.SaveChanges();
}
catch ( Exception ex )
{
divAlert.Visible = true;
lAlerts.Text = String.Format( "An error occurred adding {0} to the group {1}. Message: {2}.", person.FullName, group.Name, ex.Message );
}
string templateSuccess = GetAttributeValue( "SuccessMessage" );
lContent.Text = templateSuccess.ResolveMergeFields( mergeFields );
}
}
#endregion
#region Events
// handlers called by the controls on your block
/// <summary>
/// Handles the BlockUpdated event of the control.
/// </summary>
/// <param name="sender">The source of the event.</param>
/// <param name="e">The <see cref="EventArgs"/> instance containing the event data.</param>
protected void Block_BlockUpdated( object sender, EventArgs e )
{
}
#endregion
#region Methods
// helper functional methods (like BindGrid(), etc.)
#endregion
}
} | 39.968254 | 219 | 0.550338 | [
"Apache-2.0",
"Unlicense"
] | ThursdayChurch/rockweb.thursdaychurch.org | Blocks/Groups/GroupMemberAddFromUrl.ascx.cs | 10,074 | C# |
using System;
using System.Collections.Generic;
using UnityEngine;
// Token: 0x020001F5 RID: 501
[Serializable]
public class BMFont
{
// Token: 0x170001A7 RID: 423
// (get) Token: 0x06000EB4 RID: 3764 RVA: 0x00076F52 File Offset: 0x00075352
public bool isValid
{
get
{
return this.mSaved.Count > 0;
}
}
// Token: 0x170001A8 RID: 424
// (get) Token: 0x06000EB5 RID: 3765 RVA: 0x00076F62 File Offset: 0x00075362
// (set) Token: 0x06000EB6 RID: 3766 RVA: 0x00076F6A File Offset: 0x0007536A
public int charSize
{
get
{
return this.mSize;
}
set
{
this.mSize = value;
}
}
// Token: 0x170001A9 RID: 425
// (get) Token: 0x06000EB7 RID: 3767 RVA: 0x00076F73 File Offset: 0x00075373
// (set) Token: 0x06000EB8 RID: 3768 RVA: 0x00076F7B File Offset: 0x0007537B
public int baseOffset
{
get
{
return this.mBase;
}
set
{
this.mBase = value;
}
}
// Token: 0x170001AA RID: 426
// (get) Token: 0x06000EB9 RID: 3769 RVA: 0x00076F84 File Offset: 0x00075384
// (set) Token: 0x06000EBA RID: 3770 RVA: 0x00076F8C File Offset: 0x0007538C
public int texWidth
{
get
{
return this.mWidth;
}
set
{
this.mWidth = value;
}
}
// Token: 0x170001AB RID: 427
// (get) Token: 0x06000EBB RID: 3771 RVA: 0x00076F95 File Offset: 0x00075395
// (set) Token: 0x06000EBC RID: 3772 RVA: 0x00076F9D File Offset: 0x0007539D
public int texHeight
{
get
{
return this.mHeight;
}
set
{
this.mHeight = value;
}
}
// Token: 0x170001AC RID: 428
// (get) Token: 0x06000EBD RID: 3773 RVA: 0x00076FA6 File Offset: 0x000753A6
public int glyphCount
{
get
{
return (!this.isValid) ? 0 : this.mSaved.Count;
}
}
// Token: 0x170001AD RID: 429
// (get) Token: 0x06000EBE RID: 3774 RVA: 0x00076FC4 File Offset: 0x000753C4
// (set) Token: 0x06000EBF RID: 3775 RVA: 0x00076FCC File Offset: 0x000753CC
public string spriteName
{
get
{
return this.mSpriteName;
}
set
{
this.mSpriteName = value;
}
}
// Token: 0x170001AE RID: 430
// (get) Token: 0x06000EC0 RID: 3776 RVA: 0x00076FD5 File Offset: 0x000753D5
public List<BMGlyph> glyphs
{
get
{
return this.mSaved;
}
}
// Token: 0x06000EC1 RID: 3777 RVA: 0x00076FE0 File Offset: 0x000753E0
public BMGlyph GetGlyph(int index, bool createIfMissing)
{
BMGlyph bmglyph = null;
if (this.mDict.Count == 0)
{
int i = 0;
int count = this.mSaved.Count;
while (i < count)
{
BMGlyph bmglyph2 = this.mSaved[i];
this.mDict.Add(bmglyph2.index, bmglyph2);
i++;
}
}
if (!this.mDict.TryGetValue(index, out bmglyph) && createIfMissing)
{
bmglyph = new BMGlyph();
bmglyph.index = index;
this.mSaved.Add(bmglyph);
this.mDict.Add(index, bmglyph);
}
return bmglyph;
}
// Token: 0x06000EC2 RID: 3778 RVA: 0x0007707C File Offset: 0x0007547C
public BMGlyph GetGlyph(int index)
{
return this.GetGlyph(index, false);
}
// Token: 0x06000EC3 RID: 3779 RVA: 0x00077086 File Offset: 0x00075486
public void Clear()
{
this.mDict.Clear();
this.mSaved.Clear();
}
// Token: 0x06000EC4 RID: 3780 RVA: 0x000770A0 File Offset: 0x000754A0
public void Trim(int xMin, int yMin, int xMax, int yMax)
{
if (this.isValid)
{
int i = 0;
int count = this.mSaved.Count;
while (i < count)
{
BMGlyph bmglyph = this.mSaved[i];
if (bmglyph != null)
{
bmglyph.Trim(xMin, yMin, xMax, yMax);
}
i++;
}
}
}
// Token: 0x04000D7A RID: 3450
[HideInInspector]
[SerializeField]
private int mSize = 16;
// Token: 0x04000D7B RID: 3451
[HideInInspector]
[SerializeField]
private int mBase;
// Token: 0x04000D7C RID: 3452
[HideInInspector]
[SerializeField]
private int mWidth;
// Token: 0x04000D7D RID: 3453
[HideInInspector]
[SerializeField]
private int mHeight;
// Token: 0x04000D7E RID: 3454
[HideInInspector]
[SerializeField]
private string mSpriteName;
// Token: 0x04000D7F RID: 3455
[HideInInspector]
[SerializeField]
private List<BMGlyph> mSaved = new List<BMGlyph>();
// Token: 0x04000D80 RID: 3456
private Dictionary<int, BMGlyph> mDict = new Dictionary<int, BMGlyph>();
}
| 20.22549 | 77 | 0.67111 | [
"Unlicense"
] | larryeedwards/openyan | Assembly-CSharp/BMFont.cs | 4,128 | C# |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.