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 |
|---|---|---|---|---|---|---|---|---|
// Default URL for triggering event grid function in the local environment.
// http://localhost:7071/runtime/webhooks/EventGrid?functionName={functionname}
// Learn how to locally debug an Event Grid-triggered function:
// https://aka.ms/AA30pjh
// Use for local testing:
// https://{ID}.ngrok.io/runtime/webhooks/EventGrid?functionName=Thumbnail
using Azure.Storage.Blobs;
using Microsoft.Azure.EventGrid.Models;
using Microsoft.Azure.WebJobs;
using Microsoft.Azure.WebJobs.Extensions.EventGrid;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json.Linq;
using SixLabors.ImageSharp;
using SixLabors.ImageSharp.Formats;
using SixLabors.ImageSharp.Formats.Gif;
using SixLabors.ImageSharp.Formats.Jpeg;
using SixLabors.ImageSharp.Formats.Png;
using SixLabors.ImageSharp.PixelFormats;
using SixLabors.ImageSharp.Processing;
using System;
using System.IO;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
namespace ImageFunctions
{
public static class Thumbnail
{
private static readonly string BLOB_STORAGE_CONNECTION_STRING = Environment.GetEnvironmentVariable("AzureWebJobsStorage");
private static string GetBlobNameFromUrl(string bloblUrl)
{
var uri = new Uri(bloblUrl);
var blobClient = new BlobClient(uri);
return blobClient.Name;
}
private static IImageEncoder GetEncoder(string extension)
{
IImageEncoder encoder = null;
extension = extension.Replace(".", "");
var isSupported = Regex.IsMatch(extension, "gif|png|jpe?g", RegexOptions.IgnoreCase);
if (isSupported)
{
switch (extension.ToLower())
{
case "png":
encoder = new PngEncoder();
break;
case "jpg":
encoder = new JpegEncoder();
break;
case "jpeg":
encoder = new JpegEncoder();
break;
case "gif":
encoder = new GifEncoder();
break;
default:
break;
}
}
return encoder;
}
[FunctionName("Thumbnail")]
public static async Task Run(
[EventGridTrigger]EventGridEvent eventGridEvent,
[Blob("{data.url}", FileAccess.Read)] Stream input,
ILogger log)
{
try
{
if (input != null)
{
var createdEvent = ((JObject)eventGridEvent.Data).ToObject<StorageBlobCreatedEventData>();
var extension = Path.GetExtension(createdEvent.Url);
var encoder = GetEncoder(extension);
if (encoder != null)
{
var thumbnailWidth = Convert.ToInt32(Environment.GetEnvironmentVariable("THUMBNAIL_WIDTH"));
var thumbContainerName = Environment.GetEnvironmentVariable("THUMBNAIL_CONTAINER_NAME");
var blobServiceClient = new BlobServiceClient(BLOB_STORAGE_CONNECTION_STRING);
var blobContainerClient = blobServiceClient.GetBlobContainerClient(thumbContainerName);
var blobName = GetBlobNameFromUrl(createdEvent.Url);
using (var output = new MemoryStream())
using (Image image = Image.Load(input))
{
var divisor = (double)image.Width / (double)thumbnailWidth;
var height = Convert.ToInt32(Math.Round((image.Height / divisor)));
image.Mutate(x => x.Resize(thumbnailWidth, height));
image.Save(output, encoder);
output.Position = 0;
await blobContainerClient.UploadBlobAsync(blobName, output);
}
}
else
{
log.LogInformation($"No encoder support for: {createdEvent.Url}");
}
}
}
catch (Exception ex)
{
log.LogInformation(ex.Message);
throw;
}
}
}
}
| 36.933884 | 130 | 0.546207 | [
"MIT"
] | fredtvet/function-image-upload-resize-clone | ImageFunctions/Thumbnail.cs | 4,469 | C# |
namespace E2ETests
{
public class RemoteDeploymentConfig
{
/// <summary>
/// Name or IP address of the server to deploy to
/// </summary>
public string ServerName { get; set; }
/// <summary>
/// Account name for the credentials required to setup a powershell session to the target server
/// </summary>
public string AccountName { get; set; }
/// <summary>
/// Account password for the credentials required to setup a powershell session to the target server
/// </summary>
public string AccountPassword { get; set; }
/// <summary>
/// The file share on the target server to copy the files to
/// </summary>
public string FileSharePath { get; set; }
/// <summary>
/// Location of the dotnet runtime zip file which is required for testing portable apps.
/// When both <see cref="DotnetRuntimeZipFilePath"/> and <see cref="DotnetRuntimeFolderPath"/> properties
/// are provided, the <see cref="DotnetRuntimeZipFilePath"/> property is preferred.
/// </summary>
public string DotnetRuntimeZipFilePath { get; set; }
/// <summary>
/// Location of the dotnet runtime folder which is required for testing portable apps.
/// This property is probably more useful for users as they can point their local 'dotnet' runtime folder.
/// </summary>
public string DotnetRuntimeFolderPath { get; set; }
/// <summary>
/// Path to the parent folder containing 'dotnet.exe' on remote server's file share
/// </summary>
public string DotnetRuntimePathOnShare { get; set; }
}
}
| 39.136364 | 114 | 0.619628 | [
"Apache-2.0"
] | 06b/AspNetCore | src/MusicStore/test/MusicStore.E2ETests/RemoteDeploymentConfig.cs | 1,724 | C# |
using System.Collections.Generic;
using System.IO;
using CsvHelper;
namespace IatConsole.Assembly.Components.PickPlaceBom
{
public static class CsvBomImporter
{
public static List<CsvBomComponent> ReadBomComponents(IatRunConfiguration config)
{
string filename = config.AssemblyDataSettings.PickPlaceBomImportSettings.BomFile;
var rd = new CsvReader(new StreamReader(filename));
List<CsvBomComponent> bomComponents = new List<CsvBomComponent>();
while (rd.Read())
{
if (rd.IsRecordEmpty()) continue;
CsvBomComponent cbc = new CsvBomComponent
{
LibRef = rd[config.AssemblyDataSettings.PickPlaceBomImportSettings.BomPartReferenceColumnName],
Description = rd[config.AssemblyDataSettings.PickPlaceBomImportSettings.BomDescriptionColumnName],
Designator = rd[config.AssemblyDataSettings.PickPlaceBomImportSettings.BomDesignatorColumnName]
};
bomComponents.Add(cbc);
}
return bomComponents;
}
}
}
| 35.090909 | 118 | 0.645941 | [
"MIT"
] | somnatic/iat | IatConsole/Assembly/Components/PickPlaceBom/CsvBomImporter.cs | 1,160 | C# |
namespace Introduction
{
partial class PAGE_7_GUESS_THE_WORD_GAME
{
/// <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()
{
System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(PAGE_7_GUESS_THE_WORD_GAME));
this.panel1 = new System.Windows.Forms.Panel();
this.label_Word = new System.Windows.Forms.Label();
this.label1 = new System.Windows.Forms.Label();
this.groupBox1 = new System.Windows.Forms.GroupBox();
this.button_Z = new System.Windows.Forms.Button();
this.button_Y = new System.Windows.Forms.Button();
this.button_X = new System.Windows.Forms.Button();
this.button_W = new System.Windows.Forms.Button();
this.button_V = new System.Windows.Forms.Button();
this.button_U = new System.Windows.Forms.Button();
this.button_T = new System.Windows.Forms.Button();
this.button_S = new System.Windows.Forms.Button();
this.button_R = new System.Windows.Forms.Button();
this.button_Q = new System.Windows.Forms.Button();
this.button_P = new System.Windows.Forms.Button();
this.button_O = new System.Windows.Forms.Button();
this.button_N = new System.Windows.Forms.Button();
this.button_M = new System.Windows.Forms.Button();
this.button_L = new System.Windows.Forms.Button();
this.button_K = new System.Windows.Forms.Button();
this.button_J = new System.Windows.Forms.Button();
this.button_I = new System.Windows.Forms.Button();
this.button_H = new System.Windows.Forms.Button();
this.button_G = new System.Windows.Forms.Button();
this.button_F = new System.Windows.Forms.Button();
this.button_E = new System.Windows.Forms.Button();
this.button_D = new System.Windows.Forms.Button();
this.button_B = new System.Windows.Forms.Button();
this.button_C = new System.Windows.Forms.Button();
this.button_A = new System.Windows.Forms.Button();
this.groupBox2 = new System.Windows.Forms.GroupBox();
this.label_MissedLtrCnt = new System.Windows.Forms.Label();
this.label2 = new System.Windows.Forms.Label();
this.label_MissedLetters = new System.Windows.Forms.Label();
this.pictureBox1 = new System.Windows.Forms.PictureBox();
this.pictureBox2 = new System.Windows.Forms.PictureBox();
this.label5 = new System.Windows.Forms.Label();
this.label4 = new System.Windows.Forms.Label();
this.button3 = new System.Windows.Forms.Button();
this.label3 = new System.Windows.Forms.Label();
this.label6 = new System.Windows.Forms.Label();
this.panel1.SuspendLayout();
this.groupBox1.SuspendLayout();
this.groupBox2.SuspendLayout();
((System.ComponentModel.ISupportInitialize)(this.pictureBox1)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.pictureBox2)).BeginInit();
this.SuspendLayout();
//
// panel1
//
this.panel1.BackColor = System.Drawing.SystemColors.MenuHighlight;
this.panel1.Controls.Add(this.label_Word);
this.panel1.Controls.Add(this.label1);
this.panel1.Location = new System.Drawing.Point(25, 297);
this.panel1.Name = "panel1";
this.panel1.Size = new System.Drawing.Size(507, 136);
this.panel1.TabIndex = 0;
//
// label_Word
//
this.label_Word.AutoSize = true;
this.label_Word.Font = new System.Drawing.Font("Segoe UI", 24F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.label_Word.ForeColor = System.Drawing.SystemColors.Menu;
this.label_Word.Location = new System.Drawing.Point(118, 65);
this.label_Word.Name = "label_Word";
this.label_Word.Size = new System.Drawing.Size(137, 54);
this.label_Word.TabIndex = 1;
this.label_Word.Text = "label3";
//
// label1
//
this.label1.AutoSize = true;
this.label1.Font = new System.Drawing.Font("Segoe UI", 13.8F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.label1.ForeColor = System.Drawing.SystemColors.Menu;
this.label1.Location = new System.Drawing.Point(15, 12);
this.label1.Name = "label1";
this.label1.Size = new System.Drawing.Size(335, 32);
this.label1.TabIndex = 0;
this.label1.Text = "Guess the Following Word : ";
//
// groupBox1
//
this.groupBox1.BackColor = System.Drawing.SystemColors.ControlDark;
this.groupBox1.Controls.Add(this.button_Z);
this.groupBox1.Controls.Add(this.button_Y);
this.groupBox1.Controls.Add(this.button_X);
this.groupBox1.Controls.Add(this.button_W);
this.groupBox1.Controls.Add(this.button_V);
this.groupBox1.Controls.Add(this.button_U);
this.groupBox1.Controls.Add(this.button_T);
this.groupBox1.Controls.Add(this.button_S);
this.groupBox1.Controls.Add(this.button_R);
this.groupBox1.Controls.Add(this.button_Q);
this.groupBox1.Controls.Add(this.button_P);
this.groupBox1.Controls.Add(this.button_O);
this.groupBox1.Controls.Add(this.button_N);
this.groupBox1.Controls.Add(this.button_M);
this.groupBox1.Controls.Add(this.button_L);
this.groupBox1.Controls.Add(this.button_K);
this.groupBox1.Controls.Add(this.button_J);
this.groupBox1.Controls.Add(this.button_I);
this.groupBox1.Controls.Add(this.button_H);
this.groupBox1.Controls.Add(this.button_G);
this.groupBox1.Controls.Add(this.button_F);
this.groupBox1.Controls.Add(this.button_E);
this.groupBox1.Controls.Add(this.button_D);
this.groupBox1.Controls.Add(this.button_B);
this.groupBox1.Controls.Add(this.button_C);
this.groupBox1.Controls.Add(this.button_A);
this.groupBox1.Font = new System.Drawing.Font("Segoe UI", 13.8F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.groupBox1.ForeColor = System.Drawing.Color.Indigo;
this.groupBox1.Location = new System.Drawing.Point(25, 439);
this.groupBox1.Name = "groupBox1";
this.groupBox1.Size = new System.Drawing.Size(507, 228);
this.groupBox1.TabIndex = 1;
this.groupBox1.TabStop = false;
this.groupBox1.Text = "KEY PAD";
//
// button_Z
//
this.button_Z.BackColor = System.Drawing.Color.Black;
this.button_Z.Font = new System.Drawing.Font("Segoe UI", 12F, System.Drawing.FontStyle.Bold);
this.button_Z.ForeColor = System.Drawing.SystemColors.Menu;
this.button_Z.Location = new System.Drawing.Point(247, 169);
this.button_Z.Name = "button_Z";
this.button_Z.Size = new System.Drawing.Size(34, 38);
this.button_Z.TabIndex = 25;
this.button_Z.Text = "Z";
this.button_Z.UseVisualStyleBackColor = false;
this.button_Z.Click += new System.EventHandler(this.button_Z_Click);
//
// button_Y
//
this.button_Y.BackColor = System.Drawing.Color.Black;
this.button_Y.Font = new System.Drawing.Font("Segoe UI", 12F, System.Drawing.FontStyle.Bold);
this.button_Y.ForeColor = System.Drawing.SystemColors.Menu;
this.button_Y.Location = new System.Drawing.Point(207, 169);
this.button_Y.Name = "button_Y";
this.button_Y.Size = new System.Drawing.Size(34, 38);
this.button_Y.TabIndex = 24;
this.button_Y.Text = "Y";
this.button_Y.UseVisualStyleBackColor = false;
this.button_Y.Click += new System.EventHandler(this.button_Y_Click);
//
// button_X
//
this.button_X.BackColor = System.Drawing.Color.Black;
this.button_X.Font = new System.Drawing.Font("Segoe UI", 12F, System.Drawing.FontStyle.Bold);
this.button_X.ForeColor = System.Drawing.SystemColors.Menu;
this.button_X.Location = new System.Drawing.Point(367, 125);
this.button_X.Name = "button_X";
this.button_X.Size = new System.Drawing.Size(34, 38);
this.button_X.TabIndex = 23;
this.button_X.Text = "X";
this.button_X.UseVisualStyleBackColor = false;
this.button_X.Click += new System.EventHandler(this.button_X_Click);
//
// button_W
//
this.button_W.BackColor = System.Drawing.Color.Black;
this.button_W.Font = new System.Drawing.Font("Segoe UI", 12F, System.Drawing.FontStyle.Bold);
this.button_W.ForeColor = System.Drawing.SystemColors.Menu;
this.button_W.Location = new System.Drawing.Point(327, 125);
this.button_W.Name = "button_W";
this.button_W.Size = new System.Drawing.Size(34, 38);
this.button_W.TabIndex = 22;
this.button_W.Text = "W";
this.button_W.UseVisualStyleBackColor = false;
this.button_W.Click += new System.EventHandler(this.button_W_Click);
//
// button_V
//
this.button_V.BackColor = System.Drawing.Color.Black;
this.button_V.Font = new System.Drawing.Font("Segoe UI", 12F, System.Drawing.FontStyle.Bold);
this.button_V.ForeColor = System.Drawing.SystemColors.Menu;
this.button_V.Location = new System.Drawing.Point(287, 125);
this.button_V.Name = "button_V";
this.button_V.Size = new System.Drawing.Size(34, 38);
this.button_V.TabIndex = 21;
this.button_V.Text = "V";
this.button_V.UseVisualStyleBackColor = false;
this.button_V.Click += new System.EventHandler(this.button_V_Click);
//
// button_U
//
this.button_U.BackColor = System.Drawing.Color.Black;
this.button_U.Font = new System.Drawing.Font("Segoe UI", 12F, System.Drawing.FontStyle.Bold);
this.button_U.ForeColor = System.Drawing.SystemColors.Menu;
this.button_U.Location = new System.Drawing.Point(247, 125);
this.button_U.Name = "button_U";
this.button_U.Size = new System.Drawing.Size(34, 38);
this.button_U.TabIndex = 20;
this.button_U.Text = "U";
this.button_U.UseVisualStyleBackColor = false;
this.button_U.Click += new System.EventHandler(this.button_U_Click);
//
// button_T
//
this.button_T.BackColor = System.Drawing.Color.Black;
this.button_T.Font = new System.Drawing.Font("Segoe UI", 12F, System.Drawing.FontStyle.Bold);
this.button_T.ForeColor = System.Drawing.SystemColors.Menu;
this.button_T.Location = new System.Drawing.Point(207, 125);
this.button_T.Name = "button_T";
this.button_T.Size = new System.Drawing.Size(34, 38);
this.button_T.TabIndex = 19;
this.button_T.Text = "T";
this.button_T.UseVisualStyleBackColor = false;
this.button_T.Click += new System.EventHandler(this.button_T_Click);
//
// button_S
//
this.button_S.BackColor = System.Drawing.Color.Black;
this.button_S.Font = new System.Drawing.Font("Segoe UI", 12F, System.Drawing.FontStyle.Bold);
this.button_S.ForeColor = System.Drawing.SystemColors.Menu;
this.button_S.Location = new System.Drawing.Point(166, 125);
this.button_S.Name = "button_S";
this.button_S.Size = new System.Drawing.Size(34, 38);
this.button_S.TabIndex = 18;
this.button_S.Text = "S";
this.button_S.UseVisualStyleBackColor = false;
this.button_S.Click += new System.EventHandler(this.button_S_Click);
//
// button_R
//
this.button_R.BackColor = System.Drawing.Color.Black;
this.button_R.Font = new System.Drawing.Font("Segoe UI", 12F, System.Drawing.FontStyle.Bold);
this.button_R.ForeColor = System.Drawing.SystemColors.Menu;
this.button_R.Location = new System.Drawing.Point(126, 125);
this.button_R.Name = "button_R";
this.button_R.Size = new System.Drawing.Size(34, 38);
this.button_R.TabIndex = 17;
this.button_R.Text = "R";
this.button_R.UseVisualStyleBackColor = false;
this.button_R.Click += new System.EventHandler(this.button_R_Click);
//
// button_Q
//
this.button_Q.BackColor = System.Drawing.Color.Black;
this.button_Q.Font = new System.Drawing.Font("Segoe UI", 12F, System.Drawing.FontStyle.Bold);
this.button_Q.ForeColor = System.Drawing.SystemColors.Menu;
this.button_Q.Location = new System.Drawing.Point(86, 125);
this.button_Q.Name = "button_Q";
this.button_Q.Size = new System.Drawing.Size(34, 38);
this.button_Q.TabIndex = 16;
this.button_Q.Text = "Q";
this.button_Q.UseVisualStyleBackColor = false;
this.button_Q.Click += new System.EventHandler(this.button_Q_Click);
//
// button_P
//
this.button_P.BackColor = System.Drawing.Color.Black;
this.button_P.Font = new System.Drawing.Font("Segoe UI", 12F, System.Drawing.FontStyle.Bold);
this.button_P.ForeColor = System.Drawing.SystemColors.Menu;
this.button_P.Location = new System.Drawing.Point(367, 81);
this.button_P.Name = "button_P";
this.button_P.Size = new System.Drawing.Size(34, 38);
this.button_P.TabIndex = 15;
this.button_P.Text = "P";
this.button_P.UseVisualStyleBackColor = false;
this.button_P.Click += new System.EventHandler(this.button_P_Click);
//
// button_O
//
this.button_O.BackColor = System.Drawing.Color.Black;
this.button_O.Font = new System.Drawing.Font("Segoe UI", 12F, System.Drawing.FontStyle.Bold);
this.button_O.ForeColor = System.Drawing.SystemColors.Menu;
this.button_O.Location = new System.Drawing.Point(327, 81);
this.button_O.Name = "button_O";
this.button_O.Size = new System.Drawing.Size(34, 38);
this.button_O.TabIndex = 14;
this.button_O.Text = "O";
this.button_O.UseVisualStyleBackColor = false;
this.button_O.Click += new System.EventHandler(this.button_O_Click);
//
// button_N
//
this.button_N.BackColor = System.Drawing.Color.Black;
this.button_N.Font = new System.Drawing.Font("Segoe UI", 12F, System.Drawing.FontStyle.Bold);
this.button_N.ForeColor = System.Drawing.SystemColors.Menu;
this.button_N.Location = new System.Drawing.Point(287, 81);
this.button_N.Name = "button_N";
this.button_N.Size = new System.Drawing.Size(34, 38);
this.button_N.TabIndex = 13;
this.button_N.Text = "N";
this.button_N.UseVisualStyleBackColor = false;
this.button_N.Click += new System.EventHandler(this.button_N_Click);
//
// button_M
//
this.button_M.BackColor = System.Drawing.Color.Black;
this.button_M.Font = new System.Drawing.Font("Segoe UI", 12F, System.Drawing.FontStyle.Bold);
this.button_M.ForeColor = System.Drawing.SystemColors.Menu;
this.button_M.Location = new System.Drawing.Point(247, 81);
this.button_M.Name = "button_M";
this.button_M.Size = new System.Drawing.Size(34, 38);
this.button_M.TabIndex = 12;
this.button_M.Text = "M";
this.button_M.UseVisualStyleBackColor = false;
this.button_M.Click += new System.EventHandler(this.button_M_Click);
//
// button_L
//
this.button_L.BackColor = System.Drawing.Color.Black;
this.button_L.Font = new System.Drawing.Font("Segoe UI", 12F, System.Drawing.FontStyle.Bold);
this.button_L.ForeColor = System.Drawing.SystemColors.Menu;
this.button_L.Location = new System.Drawing.Point(207, 81);
this.button_L.Name = "button_L";
this.button_L.Size = new System.Drawing.Size(34, 38);
this.button_L.TabIndex = 11;
this.button_L.Text = "L";
this.button_L.UseVisualStyleBackColor = false;
this.button_L.Click += new System.EventHandler(this.button_L_Click);
//
// button_K
//
this.button_K.BackColor = System.Drawing.Color.Black;
this.button_K.Font = new System.Drawing.Font("Segoe UI", 12F, System.Drawing.FontStyle.Bold);
this.button_K.ForeColor = System.Drawing.SystemColors.Menu;
this.button_K.Location = new System.Drawing.Point(166, 81);
this.button_K.Name = "button_K";
this.button_K.Size = new System.Drawing.Size(34, 38);
this.button_K.TabIndex = 10;
this.button_K.Text = "K";
this.button_K.UseVisualStyleBackColor = false;
this.button_K.Click += new System.EventHandler(this.button_K_Click);
//
// button_J
//
this.button_J.BackColor = System.Drawing.Color.Black;
this.button_J.Font = new System.Drawing.Font("Segoe UI", 12F, System.Drawing.FontStyle.Bold);
this.button_J.ForeColor = System.Drawing.SystemColors.Menu;
this.button_J.Location = new System.Drawing.Point(126, 81);
this.button_J.Name = "button_J";
this.button_J.Size = new System.Drawing.Size(34, 38);
this.button_J.TabIndex = 9;
this.button_J.Text = "J";
this.button_J.UseVisualStyleBackColor = false;
this.button_J.Click += new System.EventHandler(this.button_J_Click);
//
// button_I
//
this.button_I.BackColor = System.Drawing.Color.Black;
this.button_I.Font = new System.Drawing.Font("Segoe UI", 12F, System.Drawing.FontStyle.Bold);
this.button_I.ForeColor = System.Drawing.SystemColors.Menu;
this.button_I.Location = new System.Drawing.Point(86, 81);
this.button_I.Name = "button_I";
this.button_I.Size = new System.Drawing.Size(34, 38);
this.button_I.TabIndex = 8;
this.button_I.Text = "I";
this.button_I.UseVisualStyleBackColor = false;
this.button_I.Click += new System.EventHandler(this.button_I_Click);
//
// button_H
//
this.button_H.BackColor = System.Drawing.Color.Black;
this.button_H.Font = new System.Drawing.Font("Segoe UI", 12F, System.Drawing.FontStyle.Bold);
this.button_H.ForeColor = System.Drawing.SystemColors.Menu;
this.button_H.Location = new System.Drawing.Point(367, 37);
this.button_H.Name = "button_H";
this.button_H.Size = new System.Drawing.Size(34, 38);
this.button_H.TabIndex = 7;
this.button_H.Text = "H";
this.button_H.UseVisualStyleBackColor = false;
this.button_H.Click += new System.EventHandler(this.button_H_Click);
//
// button_G
//
this.button_G.BackColor = System.Drawing.Color.Black;
this.button_G.Font = new System.Drawing.Font("Segoe UI", 12F, System.Drawing.FontStyle.Bold);
this.button_G.ForeColor = System.Drawing.SystemColors.Menu;
this.button_G.Location = new System.Drawing.Point(327, 37);
this.button_G.Name = "button_G";
this.button_G.Size = new System.Drawing.Size(34, 38);
this.button_G.TabIndex = 6;
this.button_G.Text = "G";
this.button_G.UseVisualStyleBackColor = false;
this.button_G.Click += new System.EventHandler(this.button_G_Click);
//
// button_F
//
this.button_F.BackColor = System.Drawing.Color.Black;
this.button_F.Font = new System.Drawing.Font("Segoe UI", 12F, System.Drawing.FontStyle.Bold);
this.button_F.ForeColor = System.Drawing.SystemColors.Menu;
this.button_F.Location = new System.Drawing.Point(287, 37);
this.button_F.Name = "button_F";
this.button_F.Size = new System.Drawing.Size(34, 38);
this.button_F.TabIndex = 5;
this.button_F.Text = "F";
this.button_F.UseVisualStyleBackColor = false;
this.button_F.Click += new System.EventHandler(this.button_F_Click);
//
// button_E
//
this.button_E.BackColor = System.Drawing.Color.Black;
this.button_E.Font = new System.Drawing.Font("Segoe UI", 12F, System.Drawing.FontStyle.Bold);
this.button_E.ForeColor = System.Drawing.SystemColors.Menu;
this.button_E.Location = new System.Drawing.Point(247, 37);
this.button_E.Name = "button_E";
this.button_E.Size = new System.Drawing.Size(34, 38);
this.button_E.TabIndex = 4;
this.button_E.Text = "E";
this.button_E.UseVisualStyleBackColor = false;
this.button_E.Click += new System.EventHandler(this.button_E_Click);
//
// button_D
//
this.button_D.BackColor = System.Drawing.Color.Black;
this.button_D.Font = new System.Drawing.Font("Segoe UI", 12F, System.Drawing.FontStyle.Bold);
this.button_D.ForeColor = System.Drawing.SystemColors.Menu;
this.button_D.Location = new System.Drawing.Point(207, 37);
this.button_D.Name = "button_D";
this.button_D.Size = new System.Drawing.Size(34, 38);
this.button_D.TabIndex = 3;
this.button_D.Text = "D";
this.button_D.UseVisualStyleBackColor = false;
this.button_D.Click += new System.EventHandler(this.button_D_Click);
//
// button_B
//
this.button_B.BackColor = System.Drawing.Color.Black;
this.button_B.Font = new System.Drawing.Font("Segoe UI", 12F, System.Drawing.FontStyle.Bold);
this.button_B.ForeColor = System.Drawing.SystemColors.Menu;
this.button_B.Location = new System.Drawing.Point(126, 37);
this.button_B.Name = "button_B";
this.button_B.Size = new System.Drawing.Size(34, 38);
this.button_B.TabIndex = 2;
this.button_B.Text = "B";
this.button_B.UseVisualStyleBackColor = false;
this.button_B.Click += new System.EventHandler(this.button_B_Click);
//
// button_C
//
this.button_C.BackColor = System.Drawing.Color.Black;
this.button_C.Font = new System.Drawing.Font("Segoe UI", 12F, System.Drawing.FontStyle.Bold);
this.button_C.ForeColor = System.Drawing.SystemColors.Menu;
this.button_C.Location = new System.Drawing.Point(166, 37);
this.button_C.Name = "button_C";
this.button_C.Size = new System.Drawing.Size(34, 38);
this.button_C.TabIndex = 1;
this.button_C.Text = "C";
this.button_C.UseVisualStyleBackColor = false;
this.button_C.Click += new System.EventHandler(this.button_C_Click);
//
// button_A
//
this.button_A.BackColor = System.Drawing.Color.Black;
this.button_A.Font = new System.Drawing.Font("Segoe UI", 12F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.button_A.ForeColor = System.Drawing.SystemColors.Menu;
this.button_A.Location = new System.Drawing.Point(86, 37);
this.button_A.Name = "button_A";
this.button_A.Size = new System.Drawing.Size(34, 38);
this.button_A.TabIndex = 0;
this.button_A.Text = "A";
this.button_A.UseVisualStyleBackColor = false;
this.button_A.Click += new System.EventHandler(this.button_A_Click);
//
// groupBox2
//
this.groupBox2.BackColor = System.Drawing.Color.Yellow;
this.groupBox2.Controls.Add(this.label_MissedLtrCnt);
this.groupBox2.Font = new System.Drawing.Font("Cooper Black", 12F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.groupBox2.Location = new System.Drawing.Point(564, 439);
this.groupBox2.Name = "groupBox2";
this.groupBox2.Size = new System.Drawing.Size(262, 228);
this.groupBox2.TabIndex = 2;
this.groupBox2.TabStop = false;
this.groupBox2.Text = "REMAINING TURNS";
//
// label_MissedLtrCnt
//
this.label_MissedLtrCnt.AutoSize = true;
this.label_MissedLtrCnt.BackColor = System.Drawing.Color.Chartreuse;
this.label_MissedLtrCnt.Font = new System.Drawing.Font("Segoe UI", 48F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.label_MissedLtrCnt.Location = new System.Drawing.Point(94, 72);
this.label_MissedLtrCnt.Name = "label_MissedLtrCnt";
this.label_MissedLtrCnt.Size = new System.Drawing.Size(91, 106);
this.label_MissedLtrCnt.TabIndex = 0;
this.label_MissedLtrCnt.Text = "0";
//
// label2
//
this.label2.AutoSize = true;
this.label2.Font = new System.Drawing.Font("Segoe UI", 13.8F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.label2.ForeColor = System.Drawing.Color.Red;
this.label2.Location = new System.Drawing.Point(572, 297);
this.label2.Name = "label2";
this.label2.Size = new System.Drawing.Size(200, 32);
this.label2.TabIndex = 3;
this.label2.Text = "Missed Letters : ";
//
// label_MissedLetters
//
this.label_MissedLetters.AutoSize = true;
this.label_MissedLetters.Font = new System.Drawing.Font("Segoe UI", 16.2F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.label_MissedLetters.ForeColor = System.Drawing.Color.Red;
this.label_MissedLetters.Location = new System.Drawing.Point(571, 340);
this.label_MissedLetters.Name = "label_MissedLetters";
this.label_MissedLetters.Size = new System.Drawing.Size(96, 38);
this.label_MissedLetters.TabIndex = 4;
this.label_MissedLetters.Text = "label3";
//
// pictureBox1
//
this.pictureBox1.Image = ((System.Drawing.Image)(resources.GetObject("pictureBox1.Image")));
this.pictureBox1.Location = new System.Drawing.Point(-1, -1);
this.pictureBox1.Name = "pictureBox1";
this.pictureBox1.Size = new System.Drawing.Size(1044, 712);
this.pictureBox1.SizeMode = System.Windows.Forms.PictureBoxSizeMode.StretchImage;
this.pictureBox1.TabIndex = 8;
this.pictureBox1.TabStop = false;
//
// pictureBox2
//
this.pictureBox2.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
this.pictureBox2.Image = ((System.Drawing.Image)(resources.GetObject("pictureBox2.Image")));
this.pictureBox2.Location = new System.Drawing.Point(417, -1);
this.pictureBox2.Name = "pictureBox2";
this.pictureBox2.Size = new System.Drawing.Size(212, 173);
this.pictureBox2.SizeMode = System.Windows.Forms.PictureBoxSizeMode.StretchImage;
this.pictureBox2.TabIndex = 10;
this.pictureBox2.TabStop = false;
//
// label5
//
this.label5.AutoSize = true;
this.label5.BackColor = System.Drawing.Color.Black;
this.label5.Font = new System.Drawing.Font("Cooper Black", 16.2F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.label5.ForeColor = System.Drawing.Color.White;
this.label5.Location = new System.Drawing.Point(635, 80);
this.label5.Name = "label5";
this.label5.Size = new System.Drawing.Size(23, 32);
this.label5.TabIndex = 14;
this.label5.Text = ".";
//
// label4
//
this.label4.AutoSize = true;
this.label4.BackColor = System.Drawing.Color.Black;
this.label4.Font = new System.Drawing.Font("Cooper Black", 16.2F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.label4.ForeColor = System.Drawing.Color.White;
this.label4.Location = new System.Drawing.Point(635, 128);
this.label4.Name = "label4";
this.label4.Size = new System.Drawing.Size(198, 32);
this.label4.TabIndex = 15;
this.label4.Text = "Final Score : ";
//
// button3
//
this.button3.BackgroundImage = ((System.Drawing.Image)(resources.GetObject("button3.BackgroundImage")));
this.button3.BackgroundImageLayout = System.Windows.Forms.ImageLayout.Stretch;
this.button3.FlatAppearance.BorderColor = System.Drawing.Color.Turquoise;
this.button3.FlatAppearance.BorderSize = 5;
this.button3.Font = new System.Drawing.Font("Cooper Black", 13.8F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.button3.ForeColor = System.Drawing.SystemColors.Menu;
this.button3.Location = new System.Drawing.Point(871, 563);
this.button3.Name = "button3";
this.button3.Size = new System.Drawing.Size(158, 104);
this.button3.TabIndex = 20;
this.button3.Text = "NEXT";
this.button3.UseVisualStyleBackColor = true;
this.button3.Click += new System.EventHandler(this.button3_Click);
//
// label3
//
this.label3.AutoSize = true;
this.label3.BackColor = System.Drawing.Color.WhiteSmoke;
this.label3.Font = new System.Drawing.Font("Cooper Black", 16.2F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.label3.Location = new System.Drawing.Point(254, 175);
this.label3.Name = "label3";
this.label3.Size = new System.Drawing.Size(536, 32);
this.label3.TabIndex = 21;
this.label3.Text = "GAME_1_GUESS_THE_WORD_GAME";
//
// label6
//
this.label6.AutoSize = true;
this.label6.Font = new System.Drawing.Font("Segoe UI", 13.8F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.label6.ForeColor = System.Drawing.Color.Green;
this.label6.Location = new System.Drawing.Point(30, 230);
this.label6.Name = "label6";
this.label6.Size = new System.Drawing.Size(95, 32);
this.label6.TabIndex = 22;
this.label6.Text = "HINT : ";
//
// PAGE_7_GUESS_THE_WORD_GAME
//
this.AutoScaleDimensions = new System.Drawing.SizeF(8F, 16F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(1026, 665);
this.Controls.Add(this.label6);
this.Controls.Add(this.label3);
this.Controls.Add(this.button3);
this.Controls.Add(this.label4);
this.Controls.Add(this.label5);
this.Controls.Add(this.pictureBox2);
this.Controls.Add(this.label_MissedLetters);
this.Controls.Add(this.label2);
this.Controls.Add(this.groupBox2);
this.Controls.Add(this.groupBox1);
this.Controls.Add(this.panel1);
this.Controls.Add(this.pictureBox1);
this.MaximizeBox = false;
this.Name = "PAGE_7_GUESS_THE_WORD_GAME";
this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen;
this.Text = "PAGE_7_GUESS_THE_WORD_GAME";
this.panel1.ResumeLayout(false);
this.panel1.PerformLayout();
this.groupBox1.ResumeLayout(false);
this.groupBox2.ResumeLayout(false);
this.groupBox2.PerformLayout();
((System.ComponentModel.ISupportInitialize)(this.pictureBox1)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.pictureBox2)).EndInit();
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
private System.Windows.Forms.Panel panel1;
private System.Windows.Forms.Label label1;
private System.Windows.Forms.GroupBox groupBox1;
private System.Windows.Forms.GroupBox groupBox2;
private System.Windows.Forms.Label label2;
private System.Windows.Forms.Label label_MissedLtrCnt;
private System.Windows.Forms.Label label_MissedLetters;
private System.Windows.Forms.Button button_A;
private System.Windows.Forms.Button button_Z;
private System.Windows.Forms.Button button_Y;
private System.Windows.Forms.Button button_X;
private System.Windows.Forms.Button button_W;
private System.Windows.Forms.Button button_V;
private System.Windows.Forms.Button button_U;
private System.Windows.Forms.Button button_T;
private System.Windows.Forms.Button button_S;
private System.Windows.Forms.Button button_R;
private System.Windows.Forms.Button button_Q;
private System.Windows.Forms.Button button_P;
private System.Windows.Forms.Button button_O;
private System.Windows.Forms.Button button_N;
private System.Windows.Forms.Button button_M;
private System.Windows.Forms.Button button_L;
private System.Windows.Forms.Button button_K;
private System.Windows.Forms.Button button_J;
private System.Windows.Forms.Button button_I;
private System.Windows.Forms.Button button_H;
private System.Windows.Forms.Button button_G;
private System.Windows.Forms.Button button_F;
private System.Windows.Forms.Button button_E;
private System.Windows.Forms.Button button_D;
private System.Windows.Forms.Button button_B;
private System.Windows.Forms.Button button_C;
private System.Windows.Forms.Label label_Word;
private System.Windows.Forms.PictureBox pictureBox1;
private System.Windows.Forms.PictureBox pictureBox2;
private System.Windows.Forms.Label label5;
private System.Windows.Forms.Label label4;
private System.Windows.Forms.Button button3;
private System.Windows.Forms.Label label3;
private System.Windows.Forms.Label label6;
}
} | 54.690202 | 167 | 0.597919 | [
"MIT"
] | JOYSTON-LEWIS/DASHGLAM | PAGE_7_GUESS_THE_WORD_GAME.Designer.cs | 37,957 | C# |
using System;
using System.Buffers;
using System.Diagnostics.CodeAnalysis;
using Xunit;
namespace DotNext.Buffers
{
using static IO.StreamSource;
[ExcludeFromCodeCoverage]
public sealed class SparseBufferWriterTests : Test
{
[Theory]
[InlineData(false, SparseBufferGrowth.None)]
[InlineData(true, SparseBufferGrowth.None)]
[InlineData(false, SparseBufferGrowth.Linear)]
[InlineData(true, SparseBufferGrowth.Linear)]
[InlineData(false, SparseBufferGrowth.Exponential)]
[InlineData(true, SparseBufferGrowth.Exponential)]
public static void WriteSequence(bool copyMemory, SparseBufferGrowth growth)
{
using var writer = new SparseBufferWriter<byte>(128, growth);
var sequence = ToReadOnlySequence(new ReadOnlyMemory<byte>(RandomBytes(5000)), 1000);
writer.Write(in sequence, copyMemory);
Equal(sequence.ToArray(), writer.ToReadOnlySequence().ToArray());
}
[Theory]
[InlineData(1000)]
[InlineData(10_000)]
[InlineData(100_000)]
public static void StressTest(int totalSize)
{
using var writer = new SparseBufferWriter<byte>();
using var output = writer.AsStream();
var data = RandomBytes(2048);
for (int remaining = totalSize, take; remaining > 0; remaining -= take)
{
take = Math.Min(remaining, data.Length);
output.Write(data, 0, take);
remaining -= take;
}
}
}
} | 36.244444 | 98 | 0.607603 | [
"MIT"
] | human33/dotNext | src/DotNext.Tests/Buffers/SparseBufferWriterTests.cs | 1,631 | C# |
Here we begin with a macro recursion.
<?cs def:map_val(val) ?>
<?cs var:val ?>
<?cs call:map_val(val + 1) ?>
<?cs /def ?>
<?cs call:map_val(#0) ?>
End of the macro recursion with problems. This line should not be displayed. | 32.428571 | 76 | 0.665198 | [
"BSD-2-Clause"
] | WillYee/clearsilver | cs/test_macro_recursion_failing.cs | 227 | C# |
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
using System;
using DevExpress.Xpo;
using DevExpress.Xpo.Metadata;
using DevExpress.Data.Filtering;
using System.Collections.Generic;
using System.ComponentModel;
using System.Reflection;
namespace CDS.Core.Client.DataAccessLayer.XDB
{
[Persistent(@"CDS_ORG.ORG_TRX_ShippingType")]
public partial class CDS_ORG_ORG_TRX_ShippingType : XPLiteObject
{
byte _Id;
[Key]
public byte Id
{
get { return _Id; }
set { SetPropertyValue<byte>("Id", ref _Id, value); }
}
string _Name;
[Size(20)]
public string Name
{
get { return _Name; }
set { SetPropertyValue<string>("Name", ref _Name, value); }
}
[Association(@"CDS_ORG_ORG_TRX_HeaderReferencesCDS_ORG_ORG_TRX_ShippingType")]
public XPCollection<CDS_ORG_ORG_TRX_Header> CDS_ORG_ORG_TRX_Headers { get { return GetCollection<CDS_ORG_ORG_TRX_Header>("CDS_ORG_ORG_TRX_Headers"); } }
}
}
| 32.756098 | 160 | 0.583023 | [
"Apache-2.0"
] | RetroRabbit/CDS-Core | CDS.Core.Client.DataAccessLayer/XDB/CDSXDBModelCode/CDS_ORG_ORG_TRX_ShippingType.Designer.cs | 1,343 | C# |
using Songhay.Extensions;
using Songhay.Feeds.Models;
using Songhay.Models;
using System.IO;
namespace Songhay.Feeds.Extensions
{
/// <summary>
/// Extension of <see cref="FeedsMetadata"/>
/// </summary>
public static class FeedsMetadataExtensions
{
/// <summary>
/// Converts <see cref="FeedsMetadata"/> to root directory.
/// </summary>
/// <param name="meta">The meta.</param>
/// <param name="args">The arguments.</param>
/// <returns></returns>
/// <exception cref="DirectoryNotFoundException">The expected root directory is not here.</exception>
public static string ToRootDirectory(this FeedsMetadata meta, ProgramArgs args)
{
var basePath = args.HasArg(ProgramArgs.BasePath, requiresValue: false) ? args.GetBasePathValue() : Directory.GetCurrentDirectory();
var rootDirectory = meta.FeedsDirectory.StartsWith("./") ?
ProgramFileUtility.GetCombinedPath(basePath, meta.FeedsDirectory)
:
meta.FeedsDirectory;
rootDirectory = Path.GetFullPath(rootDirectory);
if (!Directory.Exists(rootDirectory)) Directory.CreateDirectory(rootDirectory);
return rootDirectory;
}
}
}
| 34.837838 | 143 | 0.637704 | [
"MIT"
] | BryanWilhite/Songhay.Feeds | Songhay.Feeds/Extensions/FeedsMetadataExtensions.cs | 1,291 | C# |
#pragma checksum "..\..\CompareView.xaml" "{ff1816ec-aa5e-4d10-87f7-6f4963833460}" "5CC69A5EF4FFA14A4E9AA91F9E87375CC3C298CC"
//------------------------------------------------------------------------------
// <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>
//------------------------------------------------------------------------------
using System;
using System.Diagnostics;
using System.Windows;
using System.Windows.Automation;
using System.Windows.Controls;
using System.Windows.Controls.Primitives;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Markup;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Media.Effects;
using System.Windows.Media.Imaging;
using System.Windows.Media.Media3D;
using System.Windows.Media.TextFormatting;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Windows.Shell;
namespace ICSharpCode.Profiler.Controls {
/// <summary>
/// CompareView
/// </summary>
public partial class CompareView : System.Windows.Controls.UserControl, System.Windows.Markup.IComponentConnector {
#line 38 "..\..\CompareView.xaml"
[System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1823:AvoidUnusedPrivateFields")]
internal System.Windows.Controls.ComboBox baseFileName;
#line default
#line hidden
#line 41 "..\..\CompareView.xaml"
[System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1823:AvoidUnusedPrivateFields")]
internal System.Windows.Controls.ComboBox compareFileName;
#line default
#line hidden
private bool _contentLoaded;
/// <summary>
/// InitializeComponent
/// </summary>
[System.Diagnostics.DebuggerNonUserCodeAttribute()]
[System.CodeDom.Compiler.GeneratedCodeAttribute("PresentationBuildTasks", "4.0.0.0")]
public void InitializeComponent() {
if (_contentLoaded) {
return;
}
_contentLoaded = true;
System.Uri resourceLocater = new System.Uri("/ICSharpCode.Profiler.Controls;component/compareview.xaml", System.UriKind.Relative);
#line 1 "..\..\CompareView.xaml"
System.Windows.Application.LoadComponent(this, resourceLocater);
#line default
#line hidden
}
[System.Diagnostics.DebuggerNonUserCodeAttribute()]
[System.CodeDom.Compiler.GeneratedCodeAttribute("PresentationBuildTasks", "4.0.0.0")]
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)]
[System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Design", "CA1033:InterfaceMethodsShouldBeCallableByChildTypes")]
[System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity")]
[System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1800:DoNotCastUnnecessarily")]
void System.Windows.Markup.IComponentConnector.Connect(int connectionId, object target) {
switch (connectionId)
{
case 1:
this.baseFileName = ((System.Windows.Controls.ComboBox)(target));
return;
case 2:
this.compareFileName = ((System.Windows.Controls.ComboBox)(target));
return;
}
this._contentLoaded = true;
}
}
}
| 38.96 | 142 | 0.652207 | [
"MIT"
] | Plankankul/SharpDevelop-w-Framework | src/AddIns/Analysis/Profiler/Frontend/Controls/obj/Debug/CompareView.g.cs | 3,898 | C# |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See LICENSE in the project root for license information.
using UnityEngine;
using UnityEditor;
namespace Microsoft.MixedReality.Toolkit.Utilities.Editor
{
[CustomEditor( typeof(BaseObjectCollection), true )]
public class BaseCollectionInspector : UnityEditor.Editor
{
private SerializedProperty ignoreInactiveTransforms;
private SerializedProperty sortType;
protected virtual void OnEnable()
{
ignoreInactiveTransforms = serializedObject.FindProperty("ignoreInactiveTransforms");
sortType = serializedObject.FindProperty("sortType");
}
sealed public override void OnInspectorGUI()
{
serializedObject.Update();
EditorGUILayout.PropertyField(ignoreInactiveTransforms);
EditorGUILayout.PropertyField(sortType);
OnInspectorGUIInsertion();
serializedObject.ApplyModifiedProperties();
// Place the button at the bottom
BaseObjectCollection collection = (BaseObjectCollection)target;
if (GUILayout.Button("Update Collection"))
{
collection.UpdateCollection();
}
}
protected virtual void OnInspectorGUIInsertion() { }
}
} | 35.948718 | 98 | 0.656205 | [
"MIT"
] | LocalJoost/MRTK2GrabDemo | Assets/MixedRealityToolkit.SDK/Inspectors/UX/Collections/BaseCollectionInspector.cs | 1,404 | C# |
// ---------------------------------------------------------------------------
// <copyright file="TDSMessageType.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
// ---------------------------------------------------------------------------
namespace TDSClient.TDS.Header
{
/// <summary>
/// Enum describing TDS Message Type
/// </summary>
public enum TDSMessageType : byte
{
/// <summary>
/// SQL Batch Message
/// </summary>
SQLBatch = 1,
/// <summary>
/// TDS7 Pre Login Message
/// </summary>
PreTDS7Login,
/// <summary>
/// RPC Message
/// </summary>
RPC,
/// <summary>
/// Tabular Result Message
/// </summary>
TabularResult,
/// <summary>
/// Attention Signal Message
/// </summary>
AttentionSignal = 6,
/// <summary>
/// Bulk Load Data Message
/// </summary>
BulkLoadData,
/// <summary>
/// Federated Authentication Token Message
/// </summary>
FedAuthToken,
/// <summary>
/// Transaction Manager Request Message
/// </summary>
TransactionManagerRequest = 14,
/// <summary>
/// TDS7 Login Message
/// </summary>
TDS7Login = 16,
/// <summary>
/// SSPI Message
/// </summary>
SSPI,
/// <summary>
/// PreLogin Message
/// </summary>
PreLogin
}
} | 23.217391 | 80 | 0.432584 | [
"MIT"
] | Azure/SQL-Connectivity-Checker | TDSClient/TDSClient/TDS/Header/TDSMessageType.cs | 1,604 | C# |
/*
* Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH
* under one or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information regarding copyright
* ownership. Camunda licenses this file to you under the Apache License,
* Version 2.0; 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 org.camunda.bpm.engine.cdi.annotation.@event
{
public class BusinessProcessDefinitionLiteral : AnnotationLiteral<BusinessProcessDefinition>, BusinessProcessDefinition
{
protected internal readonly string key;
public BusinessProcessDefinitionLiteral(string key)
{
this.key = key;
}
public override string value()
{
return key;
}
}
} | 33.771429 | 120 | 0.762267 | [
"Apache-2.0"
] | luizfbicalho/Camunda.NET | camunda-bpm-platform-net/engine-cdi/src/main/java/org/camunda/bpm/engine/cdi/annotation/event/BusinessProcessDefinitionLiteral.cs | 1,184 | C# |
// IGameState.cs
// Copyright (c) 2014+ by Michael Penner. All rights reserved.
namespace TheBeginnersCave.Framework
{
/// <summary></summary>
public interface IGameState : Eamon.Framework.IGameState
{
#region Properties
/// <summary>
/// Gets or sets a value indicating the Trollsfire sword's activation state.
/// </summary>
long Trollsfire { get; set; }
/// <summary></summary>
long BookWarning { get; set; }
#endregion
}
}
| 19.916667 | 79 | 0.646444 | [
"MIT"
] | TheRealEamonCS/Eamon-CS | Adventures/TheBeginnersCave/Framework/IGameState.cs | 480 | C# |
#region License
// <copyright>
// iGeospatial Geometries Package
//
// This is part of the Open Geospatial Library for .NET.
//
// Package Description:
// This is a collection of C# classes that implement the fundamental
// operations required to validate a given geo-spatial data set to
// a known topological specification.
// It aims to provide a complete implementation of the Open Geospatial
// Consortium (www.opengeospatial.org) specifications for Simple
// Feature Geometry.
//
// Contact Information:
// Paul Selormey (paulselormey@gmail.com or paul@toolscenter.org)
//
// Credits:
// This library is based on the JTS Topology Suite, a Java library by
//
// Vivid Solutions Inc. (www.vividsolutions.com)
//
// License:
// See the license.txt file in the package directory.
// </copyright>
#endregion
using System;
using System.Collections;
using iGeospatial.Coordinates;
namespace iGeospatial.Geometries.Noding
{
/// <summary>
/// Computes all intersections between segments in a set of
/// <see cref="SegmentString"/>s.
/// </summary>
/// <remarks>
/// Intersections found are represented as <see cref="SegmentNode"/>s
/// and added to the <see cref="SegmentString"/>s in which they occur.
/// As a final step in the noding a new set of segment strings split
/// at the nodes may be returned.
/// </remarks>
internal interface INoder
{
/// <summary>
/// Gets a <see cref="IList"/> of fully noded
/// <see cref="SegmentStrings"/>.
/// </summary>
/// <value>
/// A <see cref="IList"/> of SegmentStrings
/// </value>
/// <remarks>
/// The SegmentStrings have the same context as their parent.
/// </remarks>
IList NodedSubstrings
{
get;
}
/// <summary>
/// Computes the noding for a collection of <see cref="SegmentString"/>s.
/// </summary>
/// <param name="segStrings">
/// A collection of <see cref="SegmentString"/>s to node.
/// </param>
/// <remarks>
/// Some Noders may add all these nodes to the input SegmentStrings;
/// others may only add some or none at all.
/// </remarks>
void ComputeNodes(IList segStrings);
}
} | 31.702703 | 81 | 0.616368 | [
"MIT"
] | IBAS0742/iGeospatial_change | Geometries/Noding/Noder.cs | 2,346 | C# |
using Microsoft.DotNet.Cli.Utils;
using Newtonsoft.Json.Linq;
namespace Microsoft.DotNet.Tools.Run.LaunchSettings
{
internal interface ILaunchSettingsProvider
{
string CommandName { get; }
LaunchSettingsApplyResult TryApplySettings(JObject document, JObject model, ref ICommand command);
}
}
| 23.142857 | 106 | 0.75 | [
"MIT"
] | LordMike/cli | src/dotnet/commands/dotnet-run/LaunchSettings/ILaunchSettingsProvider.cs | 326 | C# |
using NUnit.Framework;
using PlaneGeometry;
using System;
using System.Linq;
namespace Tests
{
/// <summary>
/// Tests of figures
/// </summary>
public class FigureTests
{
[Test]
public void TestCircle()
{
var instance = new Circle(0.51);
Assert.IsTrue(instance.FigureName == "circle");
Assert.LessOrEqual(Math.Abs(instance.Area - 0.817128249198705221324133543991), 0.00001);
ParallelEnumerable.Range(-1, 2).ForAll(x => Assert.Catch<ArgumentException>(() => new Circle(x)));
}
[Test]
public void TestTriangle()
{
var instance = new Triangle(0.51, 1.1, 0.9);
Assert.IsTrue(instance.FigureName == "triangle");
Assert.IsFalse(instance.IsRightTriangle);
Assert.LessOrEqual(Math.Abs(instance.Area - 0.22681930996941155494888055833816), 0.00001);
new[] { -1, 0, 3 }.AsParallel().ForAll(x =>
{
Assert.Catch<ArgumentException>(() => new Triangle(x, 1, 1));
Assert.Catch<ArgumentException>(() => new Triangle(1, x, 1));
Assert.Catch<ArgumentException>(() => new Triangle(1, 1, x));
if (x < 1)
{
Assert.Catch<ArgumentException>(() => new Triangle(x, x, 1));
Assert.Catch<ArgumentException>(() => new Triangle(x, 1, x));
Assert.Catch<ArgumentException>(() => new Triangle(1, x, x));
Assert.Catch<ArgumentException>(() => new Triangle(x, x, x));
}
});
}
[Test]
public void TestEllipse()
{
var instance = new Ellipse(0.51, 1.1);
Assert.IsTrue(instance.FigureName == "ellipse");
Assert.IsFalse(instance.IsCircle);
Assert.LessOrEqual(Math.Abs(instance.Area - 1.7624334786638740067775429380198), 0.00001);
ParallelEnumerable.Range(-1, 2).ForAll(x =>
{
Assert.Catch<ArgumentException>(() => new Ellipse(x, 1));
Assert.Catch<ArgumentException>(() => new Ellipse(1, x));
Assert.Catch<ArgumentException>(() => new Ellipse(x, x));
});
}
[Test]
public void TestRoundEllipse()
{
var instance = new Ellipse(1.1, 1.1);
Assert.IsTrue(instance.FigureName == "round ellipse");
Assert.IsTrue(instance.IsCircle);
Assert.LessOrEqual(Math.Abs(instance.Area - 3.8013271108436498185397984937682), 0.00001);
}
[Test]
public void TestRightTriangle()
{
var instance = new Triangle(3, 4, 5);
Assert.IsTrue(instance.FigureName == "right triangle");
Assert.IsTrue(instance.IsRightTriangle);
Assert.LessOrEqual(Math.Abs(instance.Area - 6), 0.00001);
}
}
} | 37.7625 | 111 | 0.528633 | [
"MIT"
] | z0262/Plane-Geometry-Example | PlaneGeometry.Tests/FiguresTests.cs | 3,021 | C# |
using System;
using System.Collections;
namespace GameServer.Model
{
public class UsersChecking
{
public static ArrayList users = new ArrayList();
public static bool isUserRegistered(string username)
{
Console.WriteLine("Username SIZE: " + users.ToArray().Length);
if (users.Contains(username))
{
return true;
}
else
{
users.Add(username);
return false;
}
}
}
}
| 20.884615 | 74 | 0.506446 | [
"MIT"
] | amado-developer/Networking-Project2_CardGame | GameServer/GameServer/Model/UsersChecking.cs | 545 | 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 ec2-2016-11-15.normal.json service model.
*/
using System;
using System.Collections.Generic;
using System.Xml.Serialization;
using System.Text;
using System.IO;
using System.Net;
using Amazon.Runtime;
using Amazon.Runtime.Internal;
namespace Amazon.EC2.Model
{
/// <summary>
/// This is the response object from the DisableFastSnapshotRestores operation.
/// </summary>
public partial class DisableFastSnapshotRestoresResponse : AmazonWebServiceResponse
{
private List<DisableFastSnapshotRestoreSuccessItem> _successful = new List<DisableFastSnapshotRestoreSuccessItem>();
private List<DisableFastSnapshotRestoreErrorItem> _unsuccessful = new List<DisableFastSnapshotRestoreErrorItem>();
/// <summary>
/// Gets and sets the property Successful.
/// <para>
/// Information about the snapshots for which fast snapshot restores were successfully
/// disabled.
/// </para>
/// </summary>
public List<DisableFastSnapshotRestoreSuccessItem> Successful
{
get { return this._successful; }
set { this._successful = value; }
}
// Check to see if Successful property is set
internal bool IsSetSuccessful()
{
return this._successful != null && this._successful.Count > 0;
}
/// <summary>
/// Gets and sets the property Unsuccessful.
/// <para>
/// Information about the snapshots for which fast snapshot restores could not be disabled.
/// </para>
/// </summary>
public List<DisableFastSnapshotRestoreErrorItem> Unsuccessful
{
get { return this._unsuccessful; }
set { this._unsuccessful = value; }
}
// Check to see if Unsuccessful property is set
internal bool IsSetUnsuccessful()
{
return this._unsuccessful != null && this._unsuccessful.Count > 0;
}
}
} | 34.103896 | 124 | 0.661081 | [
"Apache-2.0"
] | ChristopherButtars/aws-sdk-net | sdk/src/Services/EC2/Generated/Model/DisableFastSnapshotRestoresResponse.cs | 2,626 | C# |
namespace Rinjani
{
public interface IConfigValidator
{
void Validate(ConfigRoot config);
}
} | 16.285714 | 41 | 0.657895 | [
"MIT"
] | bitrinjani/rinjani | Rinjani/IConfigValidator.cs | 116 | C# |
namespace SampleApp.Tests
{
using System;
using System.IO;
using System.Reflection;
using NUnit.Framework;
using TestStack.ConventionTests;
using TestStack.ConventionTests.ConventionData;
using TestStack.ConventionTests.Conventions;
[TestFixture]
public class SqlScriptTests
{
readonly string projectLocation;
public SqlScriptTests()
{
projectLocation =
Path.GetFullPath(Path.Combine(Assembly.GetExecutingAssembly().Location,
@"..\..\..\..\SampleApp\SampleApp.csproj"));
}
[Test]
public void SqlScriptsShouldBeEmbeddedResources()
{
Convention.Is(new FilesAreEmbeddedResources(".sql"), new ProjectFileItems(projectLocation));
}
}
} | 28.62069 | 105 | 0.615663 | [
"MIT"
] | TestStack/ConventionTests | Samples/SampleApp.Tests/SqlScriptTests.cs | 804 | C# |
using MQTTnet.EventBus.Serializers;
namespace MQTTnet.EventBus.ConfigurationApp
{
public class ChangeNodeStateConverter : IEventConverter<ChangeNodeState>
{
public ChangeNodeState Deserialize(byte[] body)
{
var data = TextConvert.ToUTF8String(body);
var strNodeId = data.Substring(0, data.Length - 1);
if (!int.TryParse(strNodeId, out int nodeId))
return null;
var strActionType = data.Substring(data.Length - 1);
if (!int.TryParse(strActionType, out int actionType))
return null;
return new ChangeNodeState { NodeId = nodeId, ActionType = actionType };
}
public byte[] Serialize(ChangeNodeState @event)
=> TextConvert.ToUTF8ByteArray($"{@event.NodeId}{@event.ActionType}");
}
}
| 32.961538 | 84 | 0.618436 | [
"MIT"
] | Revalcon/MQTTnet.EventBus | samples/MQTTnet.EventBus.ConfigurationApp/NodeState/ChangeNodeStateConverter.cs | 859 | C# |
using Microsoft.AspNetCore.Mvc;
using Abp.AspNetCore.Mvc.Authorization;
using Volo.PostgreSqlDemo.Controllers;
namespace Volo.PostgreSqlDemo.Web.Controllers
{
[AbpMvcAuthorize]
public class AboutController : PostgreSqlDemoControllerBase
{
public ActionResult Index()
{
return View();
}
}
}
| 21.3125 | 63 | 0.697947 | [
"MIT"
] | OzBob/aspnetboilerplate-samples | PostgreSqlDemo/aspnet-core/src/Volo.PostgreSqlDemo.Web.Mvc/Controllers/AboutController.cs | 343 | C# |
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
// Runtime Version:4.0.30319.42000
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
namespace DawkinsWeasel.Properties {
using System;
/// <summary>
/// A strongly-typed resource class, for looking up localized strings, etc.
/// </summary>
// This class was auto-generated by the StronglyTypedResourceBuilder
// class via a tool like ResGen or Visual Studio.
// To add or remove a member, edit your .ResX file then rerun ResGen
// with the /str option, or rebuild your VS project.
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "4.0.0.0")]
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
internal class Resources {
private static global::System.Resources.ResourceManager resourceMan;
private static global::System.Globalization.CultureInfo resourceCulture;
[global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
internal Resources() {
}
/// <summary>
/// Returns the cached ResourceManager instance used by this class.
/// </summary>
[global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
internal static global::System.Resources.ResourceManager ResourceManager {
get {
if (object.ReferenceEquals(resourceMan, null)) {
global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("DawkinsWeasel.Properties.Resources", typeof(Resources).Assembly);
resourceMan = temp;
}
return resourceMan;
}
}
/// <summary>
/// Overrides the current thread's CurrentUICulture property for all
/// resource lookups using this strongly typed resource class.
/// </summary>
[global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
internal static global::System.Globalization.CultureInfo Culture {
get {
return resourceCulture;
}
set {
resourceCulture = value;
}
}
}
}
| 44.5625 | 180 | 0.600281 | [
"MIT"
] | PacktPublishing/The-Modern-CSharp-Challenge | Chapter08/DawkinsWeasel/Properties/Resources.Designer.cs | 2,854 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using BTCPayServer.BIP78.Sender;
using BTCPayServer.Client;
using BTCPayServer.Client.Models;
using BTCPayServer.Controllers;
using BTCPayServer.Data;
using BTCPayServer.Events;
using BTCPayServer.Lightning;
using BTCPayServer.Lightning.CLightning;
using BTCPayServer.Models.AccountViewModels;
using BTCPayServer.Models.StoreViewModels;
using BTCPayServer.Payments.Lightning;
using BTCPayServer.Payments.PayJoin.Sender;
using BTCPayServer.Services;
using BTCPayServer.Services.Stores;
using BTCPayServer.Services.Wallets;
using BTCPayServer.Tests.Logging;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Mvc;
using Microsoft.CodeAnalysis.Operations;
using NBitcoin;
using NBitcoin.Payment;
using NBitpayClient;
using NBXplorer.DerivationStrategy;
using NBXplorer.Models;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using Xunit;
using Xunit.Sdk;
namespace BTCPayServer.Tests
{
public class TestAccount
{
readonly ServerTester parent;
public TestAccount(ServerTester parent)
{
this.parent = parent;
BitPay = new Bitpay(new Key(), parent.PayTester.ServerUri);
}
public void GrantAccess(bool isAdmin = false)
{
GrantAccessAsync(isAdmin).GetAwaiter().GetResult();
}
public async Task MakeAdmin(bool isAdmin = true)
{
var userManager = parent.PayTester.GetService<UserManager<ApplicationUser>>();
var u = await userManager.FindByIdAsync(UserId);
if (isAdmin)
await userManager.AddToRoleAsync(u, Roles.ServerAdmin);
else
await userManager.RemoveFromRoleAsync(u, Roles.ServerAdmin);
IsAdmin = true;
}
public Task<BTCPayServerClient> CreateClient()
{
return Task.FromResult(new BTCPayServerClient(parent.PayTester.ServerUri, RegisterDetails.Email,
RegisterDetails.Password));
}
public async Task<BTCPayServerClient> CreateClient(params string[] permissions)
{
var manageController = parent.PayTester.GetController<UIManageController>(UserId, StoreId, IsAdmin);
var x = Assert.IsType<RedirectToActionResult>(await manageController.AddApiKey(
new UIManageController.AddApiKeyViewModel()
{
PermissionValues = permissions.Select(s =>
{
Permission.TryParse(s, out var p);
return p;
}).GroupBy(permission => permission.Policy).Select(p =>
{
var stores = p.Where(permission => !string.IsNullOrEmpty(permission.Scope))
.Select(permission => permission.Scope).ToList();
return new UIManageController.AddApiKeyViewModel.PermissionValueItem()
{
Permission = p.Key,
Forbidden = false,
StoreMode = stores.Any() ? UIManageController.AddApiKeyViewModel.ApiKeyStoreMode.Specific : UIManageController.AddApiKeyViewModel.ApiKeyStoreMode.AllStores,
SpecificStores = stores,
Value = true
};
}).ToList()
}));
var statusMessage = manageController.TempData.GetStatusMessageModel();
Assert.NotNull(statusMessage);
var str = "<code class='alert-link'>";
var apiKey = statusMessage.Html.Substring(statusMessage.Html.IndexOf(str) + str.Length);
apiKey = apiKey.Substring(0, apiKey.IndexOf("</code>"));
return new BTCPayServerClient(parent.PayTester.ServerUri, apiKey);
}
public void Register(bool isAdmin = false)
{
RegisterAsync(isAdmin).GetAwaiter().GetResult();
}
public async Task GrantAccessAsync(bool isAdmin = false)
{
await RegisterAsync(isAdmin);
await CreateStoreAsync();
var store = GetController<UIStoresController>();
var pairingCode = BitPay.RequestClientAuthorization("test", Facade.Merchant);
Assert.IsType<ViewResult>(await store.RequestPairing(pairingCode.ToString()));
await store.Pair(pairingCode.ToString(), StoreId);
}
public BTCPayServerClient CreateClientFromAPIKey(string apiKey)
{
return new BTCPayServerClient(parent.PayTester.ServerUri, apiKey);
}
public void CreateStore()
{
CreateStoreAsync().GetAwaiter().GetResult();
}
public async Task SetNetworkFeeMode(NetworkFeeMode mode)
{
await ModifyPayment(payment =>
{
payment.NetworkFeeMode = mode;
});
}
public async Task ModifyPayment(Action<PaymentViewModel> modify)
{
var storeController = GetController<UIStoresController>();
var response = storeController.Payment();
PaymentViewModel payment = (PaymentViewModel)((ViewResult)response).Model;
modify(payment);
await storeController.Payment(payment);
}
public async Task ModifyWalletSettings(Action<WalletSettingsViewModel> modify)
{
var storeController = GetController<UIStoresController>();
var response = await storeController.WalletSettings(StoreId, "BTC");
WalletSettingsViewModel walletSettings = (WalletSettingsViewModel)((ViewResult)response).Model;
modify(walletSettings);
storeController.UpdateWalletSettings(walletSettings).GetAwaiter().GetResult();
}
public async Task ModifyOnchainPaymentSettings(Action<WalletSettingsViewModel> modify)
{
var storeController = GetController<UIStoresController>();
var response = await storeController.WalletSettings(StoreId, "BTC");
WalletSettingsViewModel walletSettings = (WalletSettingsViewModel)((ViewResult)response).Model;
modify(walletSettings);
storeController.UpdatePaymentSettings(walletSettings).GetAwaiter().GetResult();
}
public T GetController<T>(bool setImplicitStore = true) where T : Controller
{
var controller = parent.PayTester.GetController<T>(UserId, setImplicitStore ? StoreId : null, IsAdmin);
return controller;
}
public async Task CreateStoreAsync()
{
if (UserId is null)
{
await RegisterAsync();
}
var store = GetController<UIUserStoresController>();
await store.CreateStore(new CreateStoreViewModel { Name = "Test Store" });
StoreId = store.CreatedStoreId;
parent.Stores.Add(StoreId);
}
public BTCPayNetwork SupportedNetwork { get; set; }
public WalletId RegisterDerivationScheme(string crytoCode, ScriptPubKeyType segwit = ScriptPubKeyType.Legacy, bool importKeysToNBX = false)
{
return RegisterDerivationSchemeAsync(crytoCode, segwit, importKeysToNBX).GetAwaiter().GetResult();
}
public async Task<WalletId> RegisterDerivationSchemeAsync(string cryptoCode, ScriptPubKeyType segwit = ScriptPubKeyType.Legacy,
bool importKeysToNBX = false, bool importsKeysToBitcoinCore = false)
{
if (StoreId is null)
await CreateStoreAsync();
SupportedNetwork = parent.NetworkProvider.GetNetwork<BTCPayNetwork>(cryptoCode);
var store = parent.PayTester.GetController<UIStoresController>(UserId, StoreId, true);
var generateRequest = new WalletSetupRequest
{
ScriptPubKeyType = segwit,
SavePrivateKeys = importKeysToNBX,
ImportKeysToRPC = importsKeysToBitcoinCore
};
await store.GenerateWallet(StoreId, cryptoCode, WalletSetupMethod.HotWallet, generateRequest);
Assert.NotNull(store.GenerateWalletResponse);
GenerateWalletResponseV = store.GenerateWalletResponse;
return new WalletId(StoreId, cryptoCode);
}
public GenerateWalletResponse GenerateWalletResponseV { get; set; }
public DerivationStrategyBase DerivationScheme
{
get => GenerateWalletResponseV.DerivationScheme;
}
private async Task RegisterAsync(bool isAdmin = false)
{
var account = parent.PayTester.GetController<UIAccountController>();
RegisterDetails = new RegisterViewModel()
{
Email = Guid.NewGuid() + "@toto.com",
ConfirmPassword = "Kitten0@",
Password = "Kitten0@",
IsAdmin = isAdmin
};
await account.Register(RegisterDetails);
//this addresses an obscure issue where LockSubscription is unintentionally set to "true",
//resulting in a large number of tests failing.
if (account.RegisteredUserId == null)
{
var settings = parent.PayTester.GetService<SettingsRepository>();
var policies = await settings.GetSettingAsync<PoliciesSettings>() ?? new PoliciesSettings();
policies.LockSubscription = false;
await account.Register(RegisterDetails);
}
UserId = account.RegisteredUserId;
IsAdmin = account.RegisteredAdmin;
}
public RegisterViewModel RegisterDetails { get; set; }
public Bitpay BitPay
{
get;
set;
}
public string UserId
{
get;
set;
}
public string StoreId
{
get;
set;
}
public bool IsAdmin { get; internal set; }
public void RegisterLightningNode(string cryptoCode, LightningConnectionType connectionType, bool isMerchant = true)
{
RegisterLightningNodeAsync(cryptoCode, connectionType, isMerchant).GetAwaiter().GetResult();
}
public Task RegisterLightningNodeAsync(string cryptoCode, bool isMerchant = true, string storeId = null)
{
return RegisterLightningNodeAsync(cryptoCode, null, isMerchant, storeId);
}
public async Task RegisterLightningNodeAsync(string cryptoCode, LightningConnectionType? connectionType, bool isMerchant = true, string storeId = null)
{
var storeController = GetController<UIStoresController>();
var connectionString = parent.GetLightningConnectionString(connectionType, isMerchant);
var nodeType = connectionString == LightningSupportedPaymentMethod.InternalNode ? LightningNodeType.Internal : LightningNodeType.Custom;
var vm = new LightningNodeViewModel { ConnectionString = connectionString, LightningNodeType = nodeType, SkipPortTest = true };
await storeController.SetupLightningNode(storeId ?? StoreId,
vm, "save", cryptoCode);
if (storeController.ModelState.ErrorCount != 0)
Assert.False(true, storeController.ModelState.FirstOrDefault().Value.Errors[0].ErrorMessage);
}
public async Task RegisterInternalLightningNodeAsync(string cryptoCode, string storeId = null)
{
var storeController = GetController<UIStoresController>();
var vm = new LightningNodeViewModel { ConnectionString = "", LightningNodeType = LightningNodeType.Internal, SkipPortTest = true };
await storeController.SetupLightningNode(storeId ?? StoreId,
vm, "save", cryptoCode);
if (storeController.ModelState.ErrorCount != 0)
Assert.False(true, storeController.ModelState.FirstOrDefault().Value.Errors[0].ErrorMessage);
}
public async Task<Coin> ReceiveUTXO(Money value, BTCPayNetwork network)
{
var cashCow = parent.ExplorerNode;
var btcPayWallet = parent.PayTester.GetService<BTCPayWalletProvider>().GetWallet(network);
var address = (await btcPayWallet.ReserveAddressAsync(this.DerivationScheme)).Address;
await parent.WaitForEvent<NewOnChainTransactionEvent>(async () =>
{
await cashCow.SendToAddressAsync(address, value);
});
int i = 0;
while (i < 30)
{
var result = (await btcPayWallet.GetUnspentCoins(DerivationScheme))
.FirstOrDefault(c => c.ScriptPubKey == address.ScriptPubKey)?.Coin;
if (result != null)
{
return result;
}
await Task.Delay(1000);
i++;
}
Assert.False(true);
return null;
}
public async Task<BitcoinAddress> GetNewAddress(BTCPayNetwork network)
{
var cashCow = parent.ExplorerNode;
var btcPayWallet = parent.PayTester.GetService<BTCPayWalletProvider>().GetWallet(network);
var address = (await btcPayWallet.ReserveAddressAsync(this.DerivationScheme)).Address;
return address;
}
public async Task<PSBT> Sign(PSBT psbt)
{
var btcPayWallet = parent.PayTester.GetService<BTCPayWalletProvider>()
.GetWallet(psbt.Network.NetworkSet.CryptoCode);
var explorerClient = parent.PayTester.GetService<ExplorerClientProvider>()
.GetExplorerClient(psbt.Network.NetworkSet.CryptoCode);
psbt = (await explorerClient.UpdatePSBTAsync(new UpdatePSBTRequest()
{
DerivationScheme = DerivationScheme,
PSBT = psbt
})).PSBT;
return psbt.SignAll(this.DerivationScheme, GenerateWalletResponseV.AccountHDKey,
GenerateWalletResponseV.AccountKeyPath);
}
Logging.ILog TestLogs => this.parent.TestLogs;
public async Task<PSBT> SubmitPayjoin(Invoice invoice, PSBT psbt, string expectedError = null, bool senderError = false)
{
var endpoint = GetPayjoinBitcoinUrl(invoice, psbt.Network);
if (endpoint == null)
{
throw new InvalidOperationException("No payjoin endpoint for the invoice");
}
var pjClient = parent.PayTester.GetService<PayjoinClient>();
var storeRepository = parent.PayTester.GetService<StoreRepository>();
var store = await storeRepository.FindStore(StoreId);
var settings = store.GetSupportedPaymentMethods(parent.NetworkProvider).OfType<DerivationSchemeSettings>()
.First();
TestLogs.LogInformation($"Proposing {psbt.GetGlobalTransaction().GetHash()}");
if (expectedError is null && !senderError)
{
var proposed = await pjClient.RequestPayjoin(endpoint, new PayjoinWallet(settings), psbt, default);
TestLogs.LogInformation($"Proposed payjoin is {proposed.GetGlobalTransaction().GetHash()}");
Assert.NotNull(proposed);
return proposed;
}
else
{
if (senderError)
{
await Assert.ThrowsAsync<PayjoinSenderException>(async () => await pjClient.RequestPayjoin(endpoint, new PayjoinWallet(settings), psbt, default));
}
else
{
var ex = await Assert.ThrowsAsync<PayjoinReceiverException>(async () => await pjClient.RequestPayjoin(endpoint, new PayjoinWallet(settings), psbt, default));
var split = expectedError.Split('|');
Assert.Equal(split[0], ex.ErrorCode);
if (split.Length > 1)
Assert.Contains(split[1], ex.ReceiverMessage);
}
return null;
}
}
public async Task<Transaction> SubmitPayjoin(Invoice invoice, Transaction transaction, BTCPayNetwork network,
string expectedError = null)
{
var response =
await SubmitPayjoinCore(transaction.ToHex(), invoice, network.NBitcoinNetwork, expectedError);
if (response == null)
return null;
var signed = Transaction.Parse(await response.Content.ReadAsStringAsync(), network.NBitcoinNetwork);
return signed;
}
async Task<HttpResponseMessage> SubmitPayjoinCore(string content, Invoice invoice, Network network,
string expectedError)
{
var bip21 = GetPayjoinBitcoinUrl(invoice, network);
bip21.TryGetPayjoinEndpoint(out var endpoint);
var response = await parent.PayTester.HttpClient.PostAsync(endpoint,
new StringContent(content, Encoding.UTF8, "text/plain"));
if (expectedError != null)
{
var split = expectedError.Split('|');
Assert.False(response.IsSuccessStatusCode);
var error = JObject.Parse(await response.Content.ReadAsStringAsync());
if (split.Length > 0)
Assert.Equal(split[0], error["errorCode"].Value<string>());
if (split.Length > 1)
Assert.Contains(split[1], error["message"].Value<string>());
return null;
}
else
{
if (!response.IsSuccessStatusCode)
{
var error = JObject.Parse(await response.Content.ReadAsStringAsync());
Assert.True(false,
$"Error: {error["errorCode"].Value<string>()}: {error["message"].Value<string>()}");
}
}
return response;
}
public static BitcoinUrlBuilder GetPayjoinBitcoinUrl(Invoice invoice, Network network)
{
var parsedBip21 = new BitcoinUrlBuilder(
invoice.CryptoInfo.First(c => c.CryptoCode == network.NetworkSet.CryptoCode).PaymentUrls.BIP21,
network);
if (!parsedBip21.TryGetPayjoinEndpoint(out var endpoint))
return null;
return parsedBip21;
}
class WebhookListener : IDisposable
{
private Client.Models.StoreWebhookData _wh;
private FakeServer _server;
private readonly List<WebhookInvoiceEvent> _webhookEvents;
private CancellationTokenSource _cts;
public WebhookListener(Client.Models.StoreWebhookData wh, FakeServer server, List<WebhookInvoiceEvent> webhookEvents)
{
_wh = wh;
_server = server;
_webhookEvents = webhookEvents;
_cts = new CancellationTokenSource();
_ = Listen(_cts.Token);
}
async Task Listen(CancellationToken cancellation)
{
while (!cancellation.IsCancellationRequested)
{
var req = await _server.GetNextRequest(cancellation);
var bytes = await req.Request.Body.ReadBytesAsync((int)req.Request.Headers.ContentLength);
var callback = Encoding.UTF8.GetString(bytes);
_webhookEvents.Add(JsonConvert.DeserializeObject<WebhookInvoiceEvent>(callback));
req.Response.StatusCode = 200;
_server.Done();
}
}
public void Dispose()
{
_cts.Cancel();
_server.Dispose();
}
}
public List<WebhookInvoiceEvent> WebhookEvents { get; set; } = new List<WebhookInvoiceEvent>();
public TEvent AssertHasWebhookEvent<TEvent>(WebhookEventType eventType, Action<TEvent> assert) where TEvent : class
{
int retry = 0;
retry:
foreach (var evt in WebhookEvents)
{
if (evt.Type == eventType)
{
var typedEvt = evt.ReadAs<TEvent>();
try
{
assert(typedEvt);
return typedEvt;
}
catch (XunitException)
{
}
}
}
if (retry < 3)
{
Thread.Sleep(1000);
retry++;
goto retry;
}
Assert.True(false, "No webhook event match the assertion");
return null;
}
public async Task SetupWebhook()
{
FakeServer server = new FakeServer();
await server.Start();
var client = await CreateClient(Policies.CanModifyStoreWebhooks);
var wh = await client.CreateWebhook(StoreId, new CreateStoreWebhookRequest()
{
AutomaticRedelivery = false,
Url = server.ServerUri.AbsoluteUri
});
parent.Resources.Add(new WebhookListener(wh, server, WebhookEvents));
}
public async Task PayInvoice(string invoiceId)
{
var inv = await BitPay.GetInvoiceAsync(invoiceId);
var net = parent.ExplorerNode.Network;
this.parent.ExplorerNode.SendToAddress(BitcoinAddress.Create(inv.BitcoinAddress, net), inv.BtcDue);
await TestUtils.EventuallyAsync(async () =>
{
var localInvoice = await BitPay.GetInvoiceAsync(invoiceId, Facade.Merchant);
Assert.Equal("paid", localInvoice.Status);
});
}
public async Task AddGuest(string userId)
{
var repo = this.parent.PayTester.GetService<StoreRepository>();
await repo.AddStoreUser(StoreId, userId, "Guest");
}
public async Task AddOwner(string userId)
{
var repo = this.parent.PayTester.GetService<StoreRepository>();
await repo.AddStoreUser(StoreId, userId, "Owner");
}
}
}
| 42.046642 | 184 | 0.600612 | [
"MIT"
] | ibtcpay/btcpayserver | BTCPayServer.Tests/TestAccount.cs | 22,537 | C# |
namespace AnyService.Models
{
public class AuditRecordModel
{
public string Id { get; set; }
public string AuditRecordType { get; set; }
public string EntityName { get; set; }
public string EntityId { get; set; }
public string OnUtc { get; set; }
public string UserId { get; set; }
public string ClientId { get; set; }
public string Data { get; set; }
}
}
| 28.866667 | 51 | 0.586605 | [
"MIT"
] | saturn72/AnyService | src/AnyService/Models/AuditRecordModel.cs | 435 | C# |
// This file is auto-generated, don't edit it. Thanks.
using System;
using System.Collections.Generic;
using System.IO;
using Tea;
namespace AntChain.SDK.TRADE.Models
{
public class QueryWareslifeInstanceRequest : TeaModel {
// OAuth模式下的授权token
[NameInMap("auth_token")]
[Validation(Required=false)]
public string AuthToken { get; set; }
// 租户id
[NameInMap("tenant_id")]
[Validation(Required=true)]
public string TenantId { get; set; }
// 商品code
[NameInMap("product_codes")]
[Validation(Required=true)]
public List<string> ProductCodes { get; set; }
}
}
| 22.166667 | 59 | 0.628571 | [
"MIT"
] | alipay/antchain-openapi-prod-sdk | trade/csharp/core/Models/QueryWareslifeInstanceRequest.cs | 685 | C# |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See LICENSE in the project root for license information.
using UnityEngine;
namespace HoloToolkit.Unity
{
// The easiest way to use this script is to drop in the HeadsUpDirectionIndicator prefab
// from the HoloToolKit. If you're having issues with the prefab or can't find it,
// you can simply create an empty GameObject and attach this script. You'll need to
// create your own pointer object which can by any 3D game object. You'll need to adjust
// the depth, margin and pivot variables to affect the right appearance. After that you
// simply need to specify the "targetObject" and then you should be set.
//
// This script assumes your point object "aims" along its local up axis and orients the
// object according to that assumption.
public class HeadsUpDirectionIndicator : MonoBehaviour
{
// Use as a named indexer for Unity's frustum planes. The order follows that laid
// out in the API documentation. DO NOT CHANGE ORDER unless a corresponding change
// has been made in the Unity API.
private enum FrustumPlanes
{
Left = 0,
Right,
Bottom,
Top,
Near,
Far
}
[Tooltip("The object the direction indicator will point to.")]
public GameObject TargetObject;
[Tooltip("The camera depth at which the indicator rests.")]
public float Depth;
[Tooltip("The point around which the indicator pivots. Should be placed at the model's 'tip'.")]
public Vector3 Pivot;
[Tooltip("The object used to 'point' at the target.")]
public GameObject PointerPrefab;
[Tooltip("Determines what percentage of the visible field should be margin.")]
[Range(0.0f, 1.0f)]
public float IndicatorMarginPercent;
[Tooltip("Debug draw the planes used to calculate the pointer lock location.")]
public bool DebugDrawPointerOrientationPlanes;
private GameObject pointer;
private static int frustumLastUpdated = -1;
private static Plane[] frustumPlanes;
private static Vector3 cameraForward;
private static Vector3 cameraPosition;
private static Vector3 cameraRight;
private static Vector3 cameraUp;
private Plane[] indicatorVolume;
private void Start()
{
Depth = Mathf.Clamp(Depth, CameraCache.Main.nearClipPlane, CameraCache.Main.farClipPlane);
if (PointerPrefab == null)
{
this.gameObject.SetActive(false);
return;
}
pointer = GameObject.Instantiate(PointerPrefab);
// We create the effect of pivoting rotations by parenting the pointer and
// offsetting its position.
pointer.transform.parent = transform;
pointer.transform.position = -Pivot;
// Allocate the space to hold the indicator volume planes. Later portions of the algorithm take for
// granted that these objects have been initialized.
indicatorVolume = new Plane[]
{
new Plane(),
new Plane(),
new Plane(),
new Plane(),
new Plane(),
new Plane()
};
}
// Update the direction indicator's position and orientation every frame.
private void Update()
{
if (!HasObjectsToTrack()) { return; }
int currentFrameCount = Time.frameCount;
if (currentFrameCount != frustumLastUpdated)
{
// Collect the updated camera information for the current frame
CacheCameraTransform(CameraCache.Main);
frustumLastUpdated = currentFrameCount;
}
UpdatePointerTransform(CameraCache.Main, indicatorVolume, TargetObject.transform.position);
}
private bool HasObjectsToTrack()
{
return TargetObject != null && pointer != null;
}
// Cache data from the camera state that are costly to retrieve.
private void CacheCameraTransform(Camera camera)
{
cameraForward = camera.transform.forward;
cameraPosition = camera.transform.position;
cameraRight = camera.transform.right;
cameraUp = camera.transform.up;
frustumPlanes = GeometryUtility.CalculateFrustumPlanes(camera);
}
// Assuming the target object is outside the view which of the four "wall" planes should
// the pointer snap to.
private FrustumPlanes GetExitPlane(Vector3 targetPosition, Camera camera)
{
// To do this we first create two planes that diagonally bisect the frustum
// These panes create four quadrants. We then infer the exit plane based on
// which quadrant the target position is in.
// Calculate a set of vectors that can be used to build the frustum corners in world
// space.
float aspect = camera.aspect;
float fovy = 0.5f * camera.fieldOfView;
float near = camera.nearClipPlane;
float far = camera.farClipPlane;
float tanFovy = Mathf.Tan(Mathf.Deg2Rad * fovy);
float tanFovx = aspect * tanFovy;
// Calculate the edges of the frustum as world space offsets from the middle of the
// frustum in world space.
Vector3 nearTop = near * tanFovy * cameraUp;
Vector3 nearRight = near * tanFovx * cameraRight;
Vector3 nearBottom = -nearTop;
Vector3 nearLeft = -nearRight;
Vector3 farTop = far * tanFovy * cameraUp;
Vector3 farRight = far * tanFovx * cameraRight;
Vector3 farLeft = -farRight;
// Calculate the center point of the near plane and the far plane as offsets from the
// camera in world space.
Vector3 nearBase = near * cameraForward;
Vector3 farBase = far * cameraForward;
// Calculate the frustum corners needed to create 'd'
Vector3 nearUpperLeft = nearBase + nearTop + nearLeft;
Vector3 nearLowerRight = nearBase + nearBottom + nearRight;
Vector3 farUpperLeft = farBase + farTop + farLeft;
Plane d = new Plane(nearUpperLeft, nearLowerRight, farUpperLeft);
// Calculate the frustum corners needed to create 'e'
Vector3 nearUpperRight = nearBase + nearTop + nearRight;
Vector3 nearLowerLeft = nearBase + nearBottom + nearLeft;
Vector3 farUpperRight = farBase + farTop + farRight;
Plane e = new Plane(nearUpperRight, nearLowerLeft, farUpperRight);
#if UNITY_EDITOR
if (DebugDrawPointerOrientationPlanes)
{
// Debug draw a triangle coplanar with 'd'
Debug.DrawLine(nearUpperLeft, nearLowerRight);
Debug.DrawLine(nearLowerRight, farUpperLeft);
Debug.DrawLine(farUpperLeft, nearUpperLeft);
// Debug draw a triangle coplanar with 'e'
Debug.DrawLine(nearUpperRight, nearLowerLeft);
Debug.DrawLine(nearLowerLeft, farUpperRight);
Debug.DrawLine(farUpperRight, nearUpperRight);
}
#endif
// We're not actually interested in the "distance" to the planes. But the sign
// of the distance tells us which quadrant the target position is in.
float dDistance = d.GetDistanceToPoint(targetPosition);
float eDistance = e.GetDistanceToPoint(targetPosition);
// d e
// +\- +/-
// \ -d +e /
// \ /
// \ /
// \ /
// \ /
// +d +e \/
// /\ -d -e
// / \
// / \
// / \
// / \
// / +d -e \
// +/- +\-
if (dDistance > 0.0f)
{
if (eDistance > 0.0f)
{
return FrustumPlanes.Left;
} else
{
return FrustumPlanes.Bottom;
}
} else
{
if (eDistance > 0.0f)
{
return FrustumPlanes.Top;
} else
{
return FrustumPlanes.Right;
}
}
}
// given a frustum wall we wish to snap the pointer to, this function returns a ray
// along which the pointer should be placed to appear at the appropriate point along
// the edge of the indicator field.
private bool TryGetIndicatorPosition(Vector3 targetPosition, Plane frustumWall, out Ray r)
{
// Think of the pointer as pointing the shortest rotation a user must make to see a
// target. The shortest rotation can be obtained by finding the great circle defined
// be the target, the camera position and the center position of the view. The tangent
// vector of the great circle points the direction of the shortest rotation. This
// great circle and thus any of it's tangent vectors are coplanar with the plane
// defined by these same three points.
Vector3 cameraToTarget = targetPosition - cameraPosition;
Vector3 normal = Vector3.Cross(cameraToTarget.normalized, cameraForward);
// In the case that the three points are colinear we cannot form a plane but we'll
// assume the target is directly behind us and we'll use a pre-chosen plane.
if (normal == Vector3.zero)
{
normal = -Vector3.right;
}
Plane q = new Plane(normal, targetPosition);
return TryIntersectPlanes(frustumWall, q, out r);
}
// Obtain the line of intersection of two planes. This is based on a method
// described in the GPU Gems series.
private bool TryIntersectPlanes(Plane p, Plane q, out Ray intersection)
{
Vector3 rNormal = Vector3.Cross(p.normal, q.normal);
float det = rNormal.sqrMagnitude;
if (det != 0.0f)
{
Vector3 rPoint = ((Vector3.Cross(rNormal, q.normal) * p.distance) +
(Vector3.Cross(p.normal, rNormal) * q.distance)) / det;
intersection = new Ray(rPoint, rNormal);
return true;
} else
{
intersection = new Ray();
return false;
}
}
// Modify the pointer location and orientation to point along the shortest rotation,
// toward tergetPosition, keeping the pointer confined inside the frustum defined by
// planes.
private void UpdatePointerTransform(Camera camera, Plane[] planes, Vector3 targetPosition)
{
// Use the camera information to create the new bounding volume
UpdateIndicatorVolume(camera);
// Start by assuming the pointer should be placed at the target position.
Vector3 indicatorPosition = cameraPosition + Depth * (targetPosition - cameraPosition).normalized;
// ArrayGenerator the target position with the frustum planes except the "far" plane since
// far away objects should be considered in view.
bool pointNotInsideIndicatorField = false;
for (int i = 0; i < 5; ++i)
{
float dot = Vector3.Dot(planes[i].normal, (targetPosition - cameraPosition).normalized);
if (dot <= 0.0f)
{
pointNotInsideIndicatorField = true;
break;
}
}
// if the target object appears outside the indicator area...
if (pointNotInsideIndicatorField)
{
// ...then we need to do some geometry calculations to lock it to the edge.
// used to determine which edge of the screen the indicator vector
// would exit through.
FrustumPlanes exitPlane = GetExitPlane(targetPosition, camera);
Ray r;
if (TryGetIndicatorPosition(targetPosition, planes[(int)exitPlane], out r))
{
indicatorPosition = cameraPosition + Depth * r.direction.normalized;
}
}
this.transform.position = indicatorPosition;
// The pointer's direction should always appear pointing away from the user's center
// of view. Thus we find the center point of the user's view in world space.
// But the pointer should also appear perpendicular to the viewer so we find the
// center position of the view that is on the same plane as the pointer position.
// We do this by projecting the vector from the pointer to the camera onto the
// the camera's forward vector.
Vector3 indicatorFieldOffset = indicatorPosition - cameraPosition;
indicatorFieldOffset = Vector3.Dot(indicatorFieldOffset, cameraForward) * cameraForward;
Vector3 indicatorFieldCenter = cameraPosition + indicatorFieldOffset;
Vector3 pointerDirection = (indicatorPosition - indicatorFieldCenter).normalized;
// Align this object's up vector with the pointerDirection
this.transform.rotation = Quaternion.LookRotation(cameraForward, pointerDirection);
}
// Here we adjust the Camera's frustum planes to place the cursor in a smaller
// volume, thus creating the effect of a "margin"
private void UpdateIndicatorVolume(Camera camera)
{
// The top, bottom and side frustum planes are used to restrict the movement
// of the pointer. These reside at indices 0-3;
for (int i = 0; i < 4; ++i)
{
// We can make the frustum smaller by rotating the walls "in" toward the
// camera's forward vector.
// First find the angle between the Camera's forward and the plane's normal
float angle = Mathf.Acos(Vector3.Dot(frustumPlanes[i].normal.normalized, cameraForward));
// Then we calculate how much we should rotate the plane in based on the
// user's setting. 90 degrees is our maximum as at that point we no longer
// have a valid frustum.
float angleStep = IndicatorMarginPercent * (0.5f * Mathf.PI - angle);
// Because the frustum plane normals face in we must actually rotate away from the forward vector
// to narrow the frustum.
Vector3 normal = Vector3.RotateTowards(frustumPlanes[i].normal, cameraForward, -angleStep, 0.0f);
indicatorVolume[i].normal = normal.normalized;
indicatorVolume[i].distance = frustumPlanes[i].distance;
}
indicatorVolume[4] = frustumPlanes[4];
indicatorVolume[5] = frustumPlanes[5];
}
}
}
| 42.936813 | 113 | 0.585066 | [
"MIT"
] | Upd4ting/HololensTemplate | Assets/MixedRealityToolkit-Unity/Assets/HoloToolkit/Utilities/Scripts/HeadsUpDirectionIndicator.cs | 15,629 | C# |
/*<FILE_LICENSE>
* NFX (.NET Framework Extension) Unistack Library
* Copyright 2003-2014 IT Adapter Inc / 2015 Aum Code LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* 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.
</FILE_LICENSE>*/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using NFX.DataAccess.Distributed;
namespace NFX
{
/// <summary>
/// Represents an Electronic Link which is an alpha-encoded identifier along with metadata information.
/// Warning! This class MAY generate fragments of profanity, however any ID can be regenerated using a different seed passed to Encode(seed)
/// </summary>
public sealed class ELink
{
#region CONSTS
private const string ALPHABET_SOURCE =
@"
AB, AC, AU, AK, AD, AS, AM, AL, AZ, AG, AN, AF, AP, AQ, AR, AX,
AI, AJ, AT, AW, BA, BE, BI, BO, BU, BR, CA, CB, CD, CE, CI, CH,
CO, CU, CR, CK, DA, DB, DE, DI, DO, DU, EB, ED, EF, EG, EJ, EK,
EL, EM, EN, EP, EQ, ER, ES, ET, EV, EW, EX, EZ, FA, FE, FI, FO,
FU, FT, FZ, FL, GA, GE, GI, GL, GM, GN, GO, GP, GR, GU, GV, GW,
GX, GZ, HA, HE, HI, HM, HN, HO, HP, HT, HU, IB, IC, ID, IF, IG,
IT, IK, IJ, IL, IM, IN, IP, IR, IS, IV, IW, IX, IZ, JA, JE, JI,
JO, JZ, JU, JK, JC, JN, KA, KE, KO, KU, KI, KR, KL, KN, KY, LA,
LE, LI, LM, LN, LO, LR, LS, LT, LU, LV, LY, LZ, MA, MB, MC, MD,
ME, MI, MO, MU, MR, MN, MY, MZ, NA, NE, NI, NM, NO, NU, NY, NX,
NZ, OB, OC, OD, OF, OA, OG, OH, OI, OJ, OK, OL, OM, OP, OR, OS,
OT, OV, OW, OX, OY, OZ, PA, PE, PI, PO, PS, PU, PY, PZ, QU, QA,
RA, RE, RI, RO, RU, RY, SA, SE, SI, SO, SU, SY, SH, SM, SN, SB,
SD, ST, SV, SQ, TA, TE, TI, TO, TM, TN, TR, TS, TU, TV, TY, TZ,
UB, UC, UD, UF, UG, UK, UL, UM, UN, UP, UR, UZ, VA, VE, VI, VO,
VU, ZA, ZE, ZI, ZO, ZU, WA, WE, WI, WO, WU, WR, YA, YE, YO, XA
";
public static readonly string[] ALPHABET;
public static readonly Dictionary<string, int> RALPHABET;
public const int MAX_LINK_CHAR_SIZE = 1024;
static ELink()
{
ALPHABET = new string[256];
RALPHABET = new Dictionary<string,int>(256);
var lst = ALPHABET_SOURCE.Split(',');
for(int i=0, j=0; j< ALPHABET.Length; i++)
{
var e = lst[i].Trim(' ', '\n', '\r').ToUpperInvariant();
if (e.IsNullOrWhiteSpace()) continue;
ALPHABET[j] = e;
RALPHABET[e] = j;
j++;
}
}
#endregion
#region .ctor
/// <summary>
/// Creates an Elink instance initialized with GDID of 0 Era having its ID set to ulong value
/// </summary>
public ELink(UInt64 id, byte[] metadata)
{
m_GDID = new GDID(0, id);
m_Metadata = metadata;
if (m_Metadata!=null && ((m_Metadata.Length*2) > MAX_LINK_CHAR_SIZE))
throw new NFXException(StringConsts.ELINK_CHAR_LENGTH_LIMIT_ERROR.Args("metadata[{0}]".Args(m_Metadata.Length)));
}
/// <summary>
/// Create ELink instance from GDID (with era).
/// </summary>
public ELink(GDID gdid, byte[] metadata)
{
m_GDID = gdid;
m_Metadata = metadata;
if (m_Metadata!=null && ((m_Metadata.Length*2) > MAX_LINK_CHAR_SIZE))
throw new NFXException(StringConsts.ELINK_CHAR_LENGTH_LIMIT_ERROR.Args("metadata[{0}]".Args(m_Metadata.Length)));
}
public ELink(string link)
{
if (link.IsNullOrWhiteSpace()) throw new NFXException(StringConsts.ARGUMENT_ERROR + "ELink.ctor(link=null|empty)");
if (link.Length > MAX_LINK_CHAR_SIZE)
throw new NFXException(StringConsts.ELINK_CHAR_LENGTH_LIMIT_ERROR.Args(link.Substring(0, 20)));
m_Link = link;
decode();
}
#endregion
#region Fields
private GDID m_GDID;
private byte[] m_Metadata;
private string m_Link;
#endregion
#region Properies
/// <summary>
/// Returns the ID portion of GDID represented by this instance
/// </summary>
public UInt64 ID { get{ return m_GDID.ID; }}
/// <summary>
/// Returns metadata attached to this instance, or null if there is no metadata specified
/// </summary>
public byte[] Metadata { get { return m_Metadata;}}
/// <summary>
/// Returns a link encoded as a string using whatever randomization seed was passed to the last Encode(seed) call.
/// If Encode() was not called, then the link will get encoded using system rnd for a seed value
/// </summary>
public string Link
{
get
{
if (m_Link==null) Encode();
return m_Link;
}
}
/// <summary>
/// Returns the GDID that this link represents
/// </summary>
public GDID GDID { get{ return m_GDID;}}
#endregion
#region Methods
/// <summary>
/// Encodes a link into a textual form, using the supplied randomization seed, otherwise the system rnd is used.
/// A seed has 4 effective bits, yielding 16 possible variations for every link
/// </summary>
public void Encode(byte? seed = null) //props -> link
{
/* Format
* [lead1][lead2][csum] - [... era ...] - [... id ...]{-[...metadata...]}
* 1bt 1bt 1bt 0..4bts 1..8bts md-len bts
*
* [lead1] = [rnd][authority] rnd 0..f
* 4bi 4bi
* [lead2] = [eraLen][idLen] idLen is w/o authority
* 4bi 4bi
* [csum] = CRC32(era, id, md_len, metadata_bytes) % 0xff
*
* [era] = LitEndian uint32 0..4 bytes
* [id] = LitEndian 1..8 bytes LitEndian uint64 w/o authority
*
*
* [metadata] = 0..limited by MAX_LINK_CHAR_SIZE/2
*
*/
int rnd = (!seed.HasValue ? (byte)(ExternalRandomGenerator.Instance.NextRandomInteger & 0xff) : seed.Value) & 0x0f;
var era = m_GDID.Era;
var id = m_GDID.ID;
var eraLength =
(era & 0xff000000) > 0 ? 4 :
(era & 0xff0000) > 0 ? 3 :
(era & 0xff00) > 0 ? 2 :
(era & 0xff) > 0 ? 1 : 0;
var idLength =
(id & 0x0f00000000000000) > 0 ? 8 : //notice Authority exclusion in mask
(id & 0xff000000000000) > 0 ? 7 :
(id & 0xff0000000000) > 0 ? 6 :
(id & 0xff00000000) > 0 ? 5 :
(id & 0xff000000) > 0 ? 4 :
(id & 0xff0000) > 0 ? 3 :
(id & 0xff00) > 0 ? 2 : 1;
var lead1 = (rnd << 4) | m_GDID.Authority;
var lead2 = (eraLength << 4) | idLength;
var crcValue = crc(era, id, m_Metadata);
rnd |= rnd << 4;
var result = new StringBuilder();
result.Append( ALPHABET[ lead1 ] );
result.Append( ALPHABET[ lead2 ^ rnd ]);
result.Append( ALPHABET[ crcValue ^ rnd ]);
result.Append( '-' );
ulong seg = era;
if (seg>0)
{
for(var i=0; i<eraLength; i++)
{
result.Append( ALPHABET[ (int)(seg & 0xff) ^ rnd ] );
seg >>= 8;
}
}
seg = id;
for(var i=0; i<idLength; i++)
{
if (i==4 && idLength>5)
result.Append( '-' );
result.Append( ALPHABET[ (int)(seg & 0xff) ^ rnd ] );
seg >>= 8;
}
if (m_Metadata!=null)
{
result.Append( '-' );
for(var i=0; i<m_Metadata.Length; i++)
result.Append( ALPHABET[ m_Metadata[i] ^ rnd ] );
}
var link = result.ToString();
if (link.Length > MAX_LINK_CHAR_SIZE)
throw new NFXException(StringConsts.ELINK_CHAR_LENGTH_LIMIT_ERROR.Args(link.Substring(0, 20)));
m_Link = link;
}
private byte crc(uint era, ulong id, byte[] md)
{
ulong sum = era * 0xaa55aa55;
sum ^= id;
if (md!=null)
sum ^= ((ulong)md.Length * 0xee77);
return (byte)(sum % 251);
}
private void decode() //link -> props
{
List<byte> data = new List<byte>(32);
char pc = (char)0;
for(var i=0; i<m_Link.Length; i++)
{
char c = m_Link[i];
if (c=='-' || c==' ') continue;
if (pc!=(char)0)
{
var seg = string.Concat(pc, c).ToUpperInvariant();
pc = (char)0;
var sid = 0;
if (!RALPHABET.TryGetValue(seg, out sid))
throw new NFXException(StringConsts.ELINK_CHAR_COMBINATION_ERROR.Args(m_Link, seg));
data.Add((byte)sid);
}
else
pc = c;
}
if (data.Count<4 || pc!=(char)0)
throw new NFXException(StringConsts.ELINK_CHAR_LENGTH_ERROR.Args(m_Link));
//2 control bytes
var lead1 = data[0];
var rnd = (lead1 & 0xf0) >> 4;
rnd |= rnd << 4;
var authority = lead1 & 0x0f;
var lead2 = data[1] ^ rnd;
var eraLength = (lead2 & 0xf0) >> 4;
var idLength = lead2 & 0x0f;
var csum = data[2] ^ rnd;
if (eraLength>4 || idLength<1 || idLength>8)
throw new NFXException(StringConsts.ELINK_SEGMENT_LENGTH_ERROR.Args(m_Link));
if (data.Count-3 < eraLength + idLength)
throw new NFXException(StringConsts.ELINK_CHAR_LENGTH_ERROR.Args(m_Link));
UInt32 era = 0;
var idx = 3;
if (eraLength>0)
{
for(var i=0; i<eraLength; i++,idx++)
era |= (UInt32)((byte)(data[idx] ^ rnd)) << (8 * i);
}
UInt64 id = 0;
if (idLength>0)
{
for(var i=0; i<idLength; i++,idx++)
id |= (UInt64)((byte)(data[idx] ^ rnd)) << (8 * i);
}
id |= ((ulong)authority << 60);
byte[] metadata = null;
if (idx<data.Count)
{
metadata = new byte[data.Count - idx];
for(var j=0; idx<data.Count; idx++, j++)
metadata[j] = (byte)(data[idx] ^ rnd);
}
var thiscsum = crc(era, id, metadata);
if (csum!=thiscsum)
throw new NFXException(StringConsts.ELINK_CSUM_MISMATCH_ERROR.Args(m_Link));
m_GDID = new GDID(era, id);
m_Metadata = metadata;
}
#endregion
}
} | 37.227273 | 145 | 0.444673 | [
"Apache-2.0"
] | PavelTorgashov/nfx | Source/NFX/ELink.cs | 13,104 | C# |
// Copyright (c) 2020 .NET Foundation and Contributors. All rights reserved.
// 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 full license information.
using System;
using System.Collections.Generic;
using System.Linq;
using Mono.Cecil;
using Mono.Cecil.Cil;
namespace ReactiveUI.Fody
{
/// <summary>
/// Mono.Cecil extension methods.
/// </summary>
public static class CecilExtensions
{
/// <summary>
/// Emits the specified il.
/// </summary>
/// <param name="body">The body.</param>
/// <param name="il">The il.</param>
public static void Emit(this MethodBody body, Action<ILProcessor> il)
{
if (body == null)
{
throw new ArgumentNullException(nameof(body));
}
if (il == null)
{
throw new ArgumentNullException(nameof(il));
}
il(body.GetILProcessor());
}
/// <summary>
/// Makes the method generic.
/// </summary>
/// <param name="method">The method.</param>
/// <param name="genericArguments">The generic arguments.</param>
/// <returns>A generic method with generic typed arguments.</returns>
public static GenericInstanceMethod MakeGenericMethod(this MethodReference method, params TypeReference[] genericArguments)
{
if (genericArguments == null)
{
throw new ArgumentNullException(nameof(genericArguments));
}
var result = new GenericInstanceMethod(method);
foreach (var argument in genericArguments)
{
result.GenericArguments.Add(argument);
}
return result;
}
/// <summary>
/// Determines whether [is assignable from] [the specified type].
/// </summary>
/// <param name="baseType">Type of the base.</param>
/// <param name="type">The type.</param>
/// <param name="logger">The logger.</param>
/// <returns>
/// <c>true</c> if [is assignable from] [the specified type]; otherwise, <c>false</c>.
/// </returns>
public static bool IsAssignableFrom(this TypeReference baseType, TypeReference type, Action<string>? logger = null)
{
if (baseType == null)
{
throw new ArgumentNullException(nameof(baseType));
}
if (type == null)
{
throw new ArgumentNullException(nameof(type));
}
return baseType.Resolve().IsAssignableFrom(type.Resolve(), logger);
}
/// <summary>
/// Determines whether [is assignable from] [the specified type].
/// </summary>
/// <param name="baseType">Type of the base.</param>
/// <param name="type">The type.</param>
/// <param name="logger">The logger.</param>
/// <returns>
/// <c>true</c> if [is assignable from] [the specified type]; otherwise, <c>false</c>.
/// </returns>
public static bool IsAssignableFrom(this TypeDefinition baseType, TypeDefinition type, Action<string>? logger = null)
{
logger ??= x => { };
Queue<TypeDefinition> queue = new Queue<TypeDefinition>();
queue.Enqueue(type);
while (queue.Any())
{
var current = queue.Dequeue();
logger(current.FullName);
if (baseType.FullName == current.FullName)
{
return true;
}
if (current.BaseType != null)
{
queue.Enqueue(current.BaseType.Resolve());
}
foreach (var @interface in current.Interfaces)
{
queue.Enqueue(@interface.InterfaceType.Resolve());
}
}
return false;
}
/// <summary>
/// Determines whether the specified attribute type is defined.
/// </summary>
/// <param name="member">The member.</param>
/// <param name="attributeType">Type of the attribute.</param>
/// <returns>
/// <c>true</c> if the specified attribute type is defined; otherwise, <c>false</c>.
/// </returns>
public static bool IsDefined(this IMemberDefinition member, TypeReference attributeType)
{
if (member == null)
{
throw new ArgumentNullException(nameof(member));
}
return member.HasCustomAttributes && member.CustomAttributes.Any(x => x.AttributeType.FullName == attributeType.FullName);
}
/// <summary>
/// Binds the method to the specified generic type.
/// </summary>
/// <param name="method">The method.</param>
/// <param name="genericType">Type of the generic.</param>
/// <returns>The method bound to the generic type.</returns>
public static MethodReference Bind(this MethodReference method, GenericInstanceType genericType)
{
if (method == null)
{
throw new ArgumentNullException(nameof(method));
}
var reference = new MethodReference(method.Name, method.ReturnType, genericType)
{
HasThis = method.HasThis,
ExplicitThis = method.ExplicitThis,
CallingConvention = method.CallingConvention
};
foreach (var parameter in method.Parameters)
{
reference.Parameters.Add(new ParameterDefinition(parameter.ParameterType));
}
return reference;
}
/// <summary>
/// Binds the generic type definition to a field.
/// </summary>
/// <param name="field">The field.</param>
/// <param name="genericTypeDefinition">The generic type definition.</param>
/// <returns>The field bound to the generic type.</returns>
public static FieldReference BindDefinition(this FieldReference field, TypeReference genericTypeDefinition)
{
if (field == null)
{
throw new ArgumentNullException(nameof(field));
}
if (genericTypeDefinition == null)
{
throw new ArgumentNullException(nameof(genericTypeDefinition));
}
if (!genericTypeDefinition.HasGenericParameters)
{
return field;
}
var genericDeclaration = new GenericInstanceType(genericTypeDefinition);
foreach (var parameter in genericTypeDefinition.GenericParameters)
{
genericDeclaration.GenericArguments.Add(parameter);
}
var reference = new FieldReference(field.Name, field.FieldType, genericDeclaration);
return reference;
}
/// <summary>
/// Finds an assembly in a module.
/// </summary>
/// <param name="currentModule">The current module.</param>
/// <param name="assemblyName">Name of the assembly.</param>
/// <returns>The assembly if found, null if not.</returns>
public static AssemblyNameReference FindAssembly(this ModuleDefinition currentModule, string assemblyName)
{
if (currentModule == null)
{
throw new ArgumentNullException(nameof(currentModule));
}
return currentModule.AssemblyReferences.SingleOrDefault(x => x.Name == assemblyName);
}
/// <summary>
/// Finds a type reference in the module.
/// </summary>
/// <param name="currentModule">The current module.</param>
/// <param name="namespace">The namespace.</param>
/// <param name="typeName">Name of the type.</param>
/// <param name="scope">The scope.</param>
/// <param name="typeParameters">The type parameters.</param>
/// <returns>The type reference.</returns>
public static TypeReference FindType(this ModuleDefinition currentModule, string @namespace, string typeName, IMetadataScope? scope = null, params string[] typeParameters)
{
if (typeParameters == null)
{
throw new ArgumentNullException(nameof(typeParameters));
}
var result = new TypeReference(@namespace, typeName, currentModule, scope);
foreach (var typeParameter in typeParameters)
{
result.GenericParameters.Add(new GenericParameter(typeParameter, result));
}
return result;
}
/// <summary>
/// Compares two type references for equality.
/// </summary>
/// <param name="type">The type.</param>
/// <param name="compareTo">The compare to.</param>
/// <returns>A value indicating the result of the comparison.</returns>
public static bool CompareTo(this TypeReference type, TypeReference compareTo)
{
if (type == null)
{
throw new ArgumentNullException(nameof(type));
}
if (compareTo == null)
{
throw new ArgumentNullException(nameof(compareTo));
}
return type.FullName == compareTo.FullName;
}
}
}
| 36.40824 | 179 | 0.554881 | [
"MIT"
] | mfmadsen/ReactiveUI | src/ReactiveUI.Fody/CecilExtensions.cs | 9,723 | C# |
using Creational.Prototype.Example1.Models.Prototypes;
using System.Collections.Generic;
namespace Creational.Prototype.Example1.Models.Entities
{
class ColorManager
{
private Dictionary<string, ColorPrototype> _colors =
new Dictionary<string, ColorPrototype>();
// Indexer
public ColorPrototype this[string key]
{
get { return _colors[key]; }
set { _colors.Add(key, value); }
}
}
}
| 22.666667 | 60 | 0.632353 | [
"Apache-2.0"
] | TheChanec/Design-Patterns | Creational.Prototype/Example1/Models/Entities/ColorManager.cs | 478 | C# |
using HADES.Models;
using HADES.Util;
using HADES.Util.Exceptions;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authentication.Cookies;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Localization;
using Serilog;
using System.Collections.Generic;
using System.Security.Claims;
using System.Threading.Tasks;
namespace HADES.Controllers
{
public class AccountController : LocalizedController<AccountController>
{
public AccountController(IStringLocalizer<AccountController> localizer) : base(localizer)
{
}
[HttpGet]
[AllowAnonymous]
public IActionResult LogIn()
{
if (User.Identity.IsAuthenticated)
{
return RedirectToAction("MainView", "Home");
}
var model = new LoginViewModel();
return View(model);
}
[HttpPost]
[AllowAnonymous]
public async Task<IActionResult> LogIn(LoginViewModel model)
{
if (User.Identity.IsAuthenticated)
{
return RedirectToAction("MainView", "Home");
}
if (ModelState.IsValid)
{
try
{
IUser User = ConnexionUtil.Login(model.Username, model.Password);
Log.Information("{User} logged on from login page", User.GetName());
var claims = new List<Claim>{
new Claim("id", User.GetId().ToString()),
new Claim("isDefault", User.IsDefaultUser().ToString()),
new Claim(ClaimTypes.Name, User.GetName(), ClaimValueTypes.String)
};
var claimsIdentity = new ClaimsIdentity(
claims, CookieAuthenticationDefaults.AuthenticationScheme);
var authProperties = new AuthenticationProperties();
await HttpContext.SignInAsync(
CookieAuthenticationDefaults.AuthenticationScheme,
new ClaimsPrincipal(claimsIdentity),
authProperties);
return RedirectToAction("MainView", "Home");
}
catch (ForbiddenException)
{
return RedirectToAction("AccessDenied", "Account");
}
catch (LoginException)
{
ModelState.AddModelError("", Localizer["MSG_Invalid"]);
return View(model);
}
catch (ADException)
{
ModelState.AddModelError("", Localizer["MSG_LDAP"]);
return View(model);
}
}
else
{
ModelState.AddModelError("", Localizer["MSG_Invalid"]);
return View(model);
}
}
[AllowAnonymous]
public ViewResult AccessDenied()
{
return View();
}
[AllowAnonymous]
public async Task<IActionResult> LogOut()
{
await HttpContext.SignOutAsync(CookieAuthenticationDefaults.AuthenticationScheme);
return RedirectToAction("LogIn", "Account");
}
}
}
| 32.238095 | 97 | 0.537666 | [
"MIT"
] | mikeyX101/HADES | HADES/Controllers/AccountController.cs | 3,387 | C# |
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using Orleans.CodeGeneration;
// 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("OrleansManager")]
[assembly: AssemblyDescription("Orleans - Management Tool")]
[assembly: AssemblyConfiguration("")]
// 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("3728e057-95c2-4301-97f0-039339860db4")]
[assembly: SkipCodeGeneration]
| 40.045455 | 84 | 0.788876 | [
"MIT"
] | ghuntley/orleans | src/OrleansManager/Properties/AssemblyInfo.cs | 881 | C# |
// 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 GoogleMobileAds.Api;
namespace GoogleMobileAds.Common
{
public interface IAdLoaderClient
{
event EventHandler<AdFailedToLoadEventArgs> OnAdFailedToLoad;
event EventHandler<CustomNativeEventArgs> OnCustomNativeTemplateAdLoaded;
void LoadAd(AdRequest request);
}
}
| 31.464286 | 81 | 0.749149 | [
"MIT"
] | AaqeelorShahid/Clone-of-AA-game---Unity | Assets/GoogleMobileAds/Common/IAdLoaderClient.cs | 883 | 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.Reflection;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Xunit;
// ReSharper disable UnusedMember.Local
// ReSharper disable UnassignedGetOnlyAutoProperty
// ReSharper disable InconsistentNaming
namespace Microsoft.EntityFrameworkCore.Metadata.Internal
{
public class ClrPropertySetterFactoryTest
{
[ConditionalFact]
public void Property_is_returned_if_it_implements_IClrPropertySetter()
{
var property = new FakeProperty();
Assert.Same(property, new ClrPropertySetterFactory().Create(property));
}
private class FakeProperty : IProperty, IClrPropertySetter
{
public void SetClrValue(object instance, object value)
=> throw new NotImplementedException();
public object this[string name]
=> throw new NotImplementedException();
public IAnnotation FindAnnotation(string name)
=> throw new NotImplementedException();
public IEnumerable<IAnnotation> GetAnnotations()
=> throw new NotImplementedException();
public string Name { get; }
public ITypeBase DeclaringType { get; }
public Type ClrType { get; }
public IEntityType DeclaringEntityType { get; }
public bool IsNullable { get; }
public bool IsReadOnlyBeforeSave { get; }
public bool IsReadOnlyAfterSave { get; }
public bool IsStoreGeneratedAlways { get; }
public ValueGenerated ValueGenerated { get; }
public bool IsConcurrencyToken { get; }
public PropertyInfo PropertyInfo { get; }
public FieldInfo FieldInfo { get; }
}
[ConditionalFact]
public void Delegate_setter_is_returned_for_IProperty_property()
{
var entityType = CreateModel().AddEntityType(typeof(Customer));
var idProperty = entityType.AddProperty(Customer.IdProperty);
var customer = new Customer { Id = 7 };
new ClrPropertySetterFactory().Create(idProperty).SetClrValue(customer, 77);
Assert.Equal(77, customer.Id);
}
[ConditionalFact]
public void Delegate_setter_is_returned_for_property_type_and_name()
{
var customer = new Customer { Id = 7 };
new ClrPropertySetterFactory().Create(typeof(Customer).GetAnyProperty("Id")).SetClrValue(customer, 77);
Assert.Equal(77, customer.Id);
}
[ConditionalFact]
public void Delegate_setter_can_set_value_type_property()
{
var entityType = CreateModel().AddEntityType(typeof(Customer));
var idProperty = entityType.AddProperty(Customer.IdProperty);
var customer = new Customer { Id = 7 };
new ClrPropertySetterFactory().Create(idProperty).SetClrValue(customer, 1);
Assert.Equal(1, customer.Id);
}
[ConditionalFact]
public void Delegate_setter_can_set_reference_type_property()
{
var entityType = CreateModel().AddEntityType(typeof(Customer));
var idProperty = entityType.AddProperty(Customer.ContentProperty);
var customer = new Customer { Id = 7 };
new ClrPropertySetterFactory().Create(idProperty).SetClrValue(customer, "MyString");
Assert.Equal("MyString", customer.Content);
}
[ConditionalFact]
public void Delegate_setter_can_set_nullable_property()
{
var entityType = CreateModel().AddEntityType(typeof(Customer));
var idProperty = entityType.AddProperty(Customer.OptionalIntProperty);
var customer = new Customer { Id = 7 };
new ClrPropertySetterFactory().Create(idProperty).SetClrValue(customer, 3);
Assert.Equal(3, customer.OptionalInt);
}
[ConditionalFact]
public void Delegate_setter_can_set_nullable_property_with_null_value()
{
var entityType = CreateModel().AddEntityType(typeof(Customer));
var idProperty = entityType.AddProperty(Customer.OptionalIntProperty);
var customer = new Customer { Id = 7 };
new ClrPropertySetterFactory().Create(idProperty).SetClrValue(customer, null);
Assert.Null(customer.OptionalInt);
}
[ConditionalFact]
public void Delegate_setter_can_set_enum_property()
{
var entityType = CreateModel().AddEntityType(typeof(Customer));
var idProperty = entityType.AddProperty(Customer.FlagProperty);
var customer = new Customer { Id = 7 };
new ClrPropertySetterFactory().Create(idProperty).SetClrValue(customer, Flag.One);
Assert.Equal(Flag.One, customer.Flag);
}
[ConditionalFact]
public void Delegate_setter_can_set_nullable_enum_property()
{
var entityType = CreateModel().AddEntityType(typeof(Customer));
var idProperty = entityType.AddProperty(Customer.OptionalFlagProperty);
var customer = new Customer { Id = 7 };
new ClrPropertySetterFactory().Create(idProperty).SetClrValue(customer, Flag.Two);
Assert.Equal(Flag.Two, customer.OptionalFlag);
}
[ConditionalFact]
public void Delegate_setter_can_set_on_virtual_privatesetter_property_override_singlebasetype()
{
var entityType = CreateModel().AddEntityType(typeof(ConcreteEntity1));
var property = entityType.AddProperty(
typeof(ConcreteEntity1).GetProperty(nameof(ConcreteEntity1.VirtualPrivateProperty_Override)));
var entity = new ConcreteEntity1();
new ClrPropertySetterFactory().Create(property).SetClrValue(entity, 100);
Assert.Equal(100, entity.VirtualPrivateProperty_Override);
}
[ConditionalFact]
public void Delegate_setter_can_set_on_virtual_privatesetter_property_override_multiplebasetypes()
{
var entityType = CreateModel().AddEntityType(typeof(ConcreteEntity2));
var property = entityType.AddProperty(
typeof(ConcreteEntity2).GetProperty(nameof(ConcreteEntity2.VirtualPrivateProperty_Override)));
var entity = new ConcreteEntity2();
new ClrPropertySetterFactory().Create(property).SetClrValue(entity, 100);
Assert.Equal(100, entity.VirtualPrivateProperty_Override);
}
[ConditionalFact]
public void Delegate_setter_can_set_on_virtual_privatesetter_property_no_override_singlebasetype()
{
var entityType = CreateModel().AddEntityType(typeof(ConcreteEntity1));
var property = entityType.AddProperty(
typeof(ConcreteEntity1).GetProperty(nameof(ConcreteEntity1.VirtualPrivateProperty_NoOverride)));
var entity = new ConcreteEntity1();
new ClrPropertySetterFactory().Create(property).SetClrValue(entity, 100);
Assert.Equal(100, entity.VirtualPrivateProperty_NoOverride);
}
[ConditionalFact]
public void Delegate_setter_can_set_on_virtual_privatesetter_property_no_override_multiplebasetypes()
{
var entityType = CreateModel().AddEntityType(typeof(ConcreteEntity2));
var property = entityType.AddProperty(
typeof(ConcreteEntity2).GetProperty(nameof(ConcreteEntity2.VirtualPrivateProperty_NoOverride)));
var entity = new ConcreteEntity2();
new ClrPropertySetterFactory().Create(property).SetClrValue(entity, 100);
Assert.Equal(100, entity.VirtualPrivateProperty_NoOverride);
}
[ConditionalFact]
public void Delegate_setter_can_set_on_privatesetter_property_singlebasetype()
{
var entityType = CreateModel().AddEntityType(typeof(ConcreteEntity1));
var property = entityType.AddProperty(typeof(ConcreteEntity1).GetProperty(nameof(ConcreteEntity1.PrivateProperty)));
var entity = new ConcreteEntity1();
new ClrPropertySetterFactory().Create(property).SetClrValue(entity, 100);
Assert.Equal(100, entity.PrivateProperty);
}
[ConditionalFact]
public void Delegate_setter_can_set_on_privatesetter_property_multiplebasetypes()
{
var entityType = CreateModel().AddEntityType(typeof(ConcreteEntity2));
var property = entityType.AddProperty(typeof(ConcreteEntity2).GetProperty(nameof(ConcreteEntity2.PrivateProperty)));
var entity = new ConcreteEntity2();
new ClrPropertySetterFactory().Create(property).SetClrValue(entity, 100);
Assert.Equal(100, entity.PrivateProperty);
}
[ConditionalFact]
public void Delegate_setter_throws_if_no_setter_found()
{
var entityType = CreateModel().AddEntityType(typeof(ConcreteEntity1));
var property = entityType.AddProperty(typeof(ConcreteEntity1).GetProperty(nameof(ConcreteEntity1.NoSetterProperty)));
Assert.Throws<InvalidOperationException>(
() => new ClrPropertySetterFactory().Create(property));
entityType = CreateModel().AddEntityType(typeof(ConcreteEntity2));
property = entityType.AddProperty(typeof(ConcreteEntity2).GetProperty(nameof(ConcreteEntity2.NoSetterProperty)));
Assert.Throws<InvalidOperationException>(
() => new ClrPropertySetterFactory().Create(property));
}
[ConditionalFact]
public void Delegate_setter_can_set_index_properties()
{
var entityType = CreateModel().AddEntityType(typeof(IndexedClass));
var propertyA = entityType.AddIndexerProperty("PropertyA", typeof(string));
var propertyB = entityType.AddIndexerProperty("PropertyB", typeof(int));
var indexedClass = new IndexedClass { Id = 7 };
Assert.Equal("ValueA", indexedClass["PropertyA"]);
Assert.Equal(123, indexedClass["PropertyB"]);
new ClrPropertySetterFactory().Create(propertyA).SetClrValue(indexedClass, "UpdatedValue");
new ClrPropertySetterFactory().Create(propertyB).SetClrValue(indexedClass, 42);
Assert.Equal("UpdatedValue", indexedClass["PropertyA"]);
Assert.Equal(42, indexedClass["PropertyB"]);
}
private IMutableModel CreateModel()
=> new Model();
#region Fixture
private enum Flag
{
One,
Two
}
private class Customer
{
public static readonly PropertyInfo IdProperty = typeof(Customer).GetProperty(nameof(Id));
public static readonly PropertyInfo OptionalIntProperty = typeof(Customer).GetProperty(nameof(OptionalInt));
public static readonly PropertyInfo ContentProperty = typeof(Customer).GetProperty(nameof(Content));
public static readonly PropertyInfo FlagProperty = typeof(Customer).GetProperty(nameof(Flag));
public static readonly PropertyInfo OptionalFlagProperty = typeof(Customer).GetProperty(nameof(OptionalFlag));
public int Id { get; set; }
public string Content { get; set; }
public int? OptionalInt { get; set; }
public Flag Flag { get; set; }
public Flag? OptionalFlag { get; set; }
}
private class ConcreteEntity2 : ConcreteEntity1
{
// ReSharper disable once RedundantOverriddenMember
public override int VirtualPrivateProperty_Override
=> base.VirtualPrivateProperty_Override;
}
private class ConcreteEntity1 : BaseEntity
{
// ReSharper disable once RedundantOverriddenMember
public override int VirtualPrivateProperty_Override
=> base.VirtualPrivateProperty_Override;
}
private class BaseEntity
{
public virtual int VirtualPrivateProperty_Override { get; private set; }
public virtual int VirtualPrivateProperty_NoOverride { get; private set; }
public int PrivateProperty { get; private set; }
public int NoSetterProperty { get; }
}
private class IndexedClass
{
private readonly Dictionary<string, object> _internalValues = new()
{
{ "PropertyA", "ValueA" }, { "PropertyB", 123 }
};
internal int Id { get; set; }
internal object this[string name] { get => _internalValues[name]; set => _internalValues[name] = value; }
}
#endregion
}
}
| 40.613707 | 129 | 0.655519 | [
"Apache-2.0"
] | benaadams/efcore | test/EFCore.Tests/Metadata/Internal/ClrPropertySetterFactoryTest.cs | 13,037 | C# |
using System.Collections.Generic;
using System.Xml.Serialization;
using Niue.Alipay.Domain;
namespace Niue.Alipay.Response
{
/// <summary>
/// KoubeiCraftsmanDataProviderBatchqueryResponse.
/// </summary>
public class KoubeiCraftsmanDataProviderBatchqueryResponse : AopResponse
{
/// <summary>
/// craftsmans:手艺人信息
/// </summary>
[XmlArray("craftsmans")]
[XmlArrayItem("craftsman_open_model")]
public List<CraftsmanOpenModel> Craftsmans { get; set; }
/// <summary>
/// 当前页码
/// </summary>
[XmlElement("current_page_no")]
public long CurrentPageNo { get; set; }
/// <summary>
/// 每页记录数
/// </summary>
[XmlElement("page_size")]
public long PageSize { get; set; }
/// <summary>
/// 门店下共手艺人数目
/// </summary>
[XmlElement("total_craftsmans")]
public long TotalCraftsmans { get; set; }
/// <summary>
/// 总页码数目
/// </summary>
[XmlElement("total_page_no")]
public long TotalPageNo { get; set; }
}
}
| 25.636364 | 76 | 0.56383 | [
"MIT"
] | P79N6A/abp-ant-design-pro-vue | Niue.Alipay/Response/KoubeiCraftsmanDataProviderBatchqueryResponse.cs | 1,186 | C# |
using System;
using Microsoft.AspNetCore.Mvc.Controllers;
using Microsoft.OData.Edm;
namespace Microsoft.AspNetCore.Mvc.ApiExplorer
{
/// <summary>
/// Provides extension methods for the <see cref="ApiDescription" /> class.
/// </summary>
public static class ApiDescriptionExtensions
{
/// <summary>
/// Gets the entity data model (EDM) associated with the API description.
/// </summary>
/// <param name="apiDescription">The <see cref="ApiDescription">API description</see> to get the model for.</param>
/// <returns>The associated <see cref="IEdmModel">EDM model</see> or <c>null</c> if there is no associated model.</returns>
public static IEdmModel? EdmModel(this ApiDescription apiDescription)
{
return apiDescription.GetProperty<IEdmModel>();
}
/// <summary>
/// Gets the entity set associated with the API description.
/// </summary>
/// <param name="apiDescription">The <see cref="ApiDescription">API description</see> to get the entity set for.</param>
/// <returns>The associated <see cref="IEdmEntitySet">entity set</see> or <c>null</c> if there is no associated entity set.</returns>
public static IEdmEntitySet? EntitySet(this ApiDescription apiDescription)
{
if (apiDescription == null)
{
throw new ArgumentNullException(nameof(apiDescription));
}
var key = typeof(IEdmEntitySet);
if (apiDescription.Properties.TryGetValue(key, out var value))
{
return (IEdmEntitySet)value;
}
var container = apiDescription.EdmModel()?.EntityContainer;
if (container == null || !(apiDescription.ActionDescriptor is ControllerActionDescriptor descriptor))
{
return default;
}
var entitySetName = descriptor.ControllerName;
var entitySet = container.FindEntitySet(entitySetName);
descriptor.Properties[key] = entitySet;
return entitySet;
}
/// <summary>
/// Gets the entity type associated with the API description.
/// </summary>
/// <param name="apiDescription">The <see cref="ApiDescription">API description</see> to get the entity type for.</param>
/// <returns>
/// The associated <see cref="IEdmEntityType">entity type</see> or <c>null</c> if there is no associated entity
/// type.
/// </returns>
public static IEdmEntityType? EntityType(this ApiDescription apiDescription)
{
return apiDescription.EntitySet()?.EntityType();
}
/// <summary>
/// Gets the operation associated with the API description.
/// </summary>
/// <param name="apiDescription">The <see cref="ApiDescription">API description</see> to get the operation for.</param>
/// <returns>
/// The associated <see cref="IEdmOperation">EDM operation</see> or <c>null</c> if there is no associated
/// operation.
/// </returns>
public static IEdmOperation? Operation(this ApiDescription apiDescription)
{
return apiDescription.GetProperty<IEdmOperation>();
}
}
} | 41.012195 | 141 | 0.60898 | [
"MIT"
] | StennGroup/stenn-aspnetcore-versioning | src/Stenn.AspNetCore.OData.Versioning.ApiExplorer/Mvc/ApiDescriptionExtensions.cs | 3,365 | C# |
using System.Collections.Generic;
using System.IO;
using System.Net.Http;
using System.Threading.Tasks;
using Selenoid.Client.Infrastructure.Common.List;
using Selenoid.Client.Infrastructure.Video.List;
using Selenoid.Client.Models;
namespace Selenoid.Client
{
public class SelenoidVideoClient : ISelenoidVideoClient
{
private readonly HttpClient httpClient;
private readonly ISelenoidClientSettings settings;
private readonly IListItemsConverter<VideoListItemConverter> listItemsConverter;
public SelenoidVideoClient(HttpClient httpClient,
ISelenoidClientSettings settings,
IListItemsConverter<VideoListItemConverter> listItemsConverter)
{
this.httpClient = httpClient;
this.settings = settings;
this.listItemsConverter = listItemsConverter;
}
public async Task<List<SelenoidListItem>> GetAsync()
{
var stringResponse = await httpClient.GetStringAsync($"{settings.SelenoidHostUrl}/video/").ConfigureAwait(false);
var items = listItemsConverter.Convert(stringResponse);
return items;
}
public Task<Stream> GetAsync(string videoName)
{
var fileUrl = $"{settings.SelenoidHostUrl}/video/{videoName}";
return httpClient.GetStreamAsync(fileUrl);
}
public Task DeleteAsync(string videoName)
{
return httpClient.DeleteAsync($"{settings.SelenoidHostUrl}/video/{videoName}.");
}
}
} | 35.090909 | 125 | 0.685881 | [
"MIT"
] | Greved/selenoid.client | Selenoid.Client/SelenoidVideoClient.cs | 1,546 | C# |
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
namespace Confifu
{
/// <summary>
/// Represents AppEnv logic
/// </summary>
public class AppEnv
{
class AppEnvExpression
{
AppEnv Left { get; }
AppEnv Right { get; }
AppEnvOperation Op { get; }
internal AppEnvExpression(AppEnvOperation op, AppEnv left, AppEnv right)
{
Op = op;
Left = left;
Right = right;
}
internal bool IsIn(string testEnv) => Op.Match(
union: () => Left.IsIn(testEnv) || Right.IsIn(testEnv),
intersect: () => Left.IsIn(testEnv) && Right.IsIn(testEnv),
negative: () => !Left.IsIn(testEnv)
);
public override string ToString()
{
return Op.Match(
union: () => $"{Left} + {Right}",
intersect: () => $"{Left.ToExpressionString()} * {Right.ToExpressionString()}",
negative: () => $"!{Left.ToExpressionString()}"
);
}
}
class AppEnvOperation
{
public static AppEnvOperation Union = new AppEnvOperation(1);
public static AppEnvOperation Intersect = new AppEnvOperation(2);
public static AppEnvOperation Negative = new AppEnvOperation(3);
int value;
private AppEnvOperation(int value)
{
this.value = value;
}
public T Match<T>(Func<T> union, Func<T> intersect, Func<T> negative)
{
if (this.Equals(Union))
return union();
if (this.Equals(Intersect))
return intersect();
if (this.Equals(Negative))
return negative();
Debug.Assert(false, "Unknown AppEnvOperation");
throw new Exception("wtf!!"); // support compiler, actually must not happen
}
public override bool Equals(object obj)
{
var op = obj as AppEnvOperation;
if (op == null) return false;
return op.value == this.value;
}
public override int GetHashCode() => value.GetHashCode();
}
private HashSet<string> include;
private AppEnvExpression expression;
private AppEnv(IEnumerable<string> include)
{
this.include = new HashSet<string>(include, StringComparer.CurrentCultureIgnoreCase);
}
private AppEnv(AppEnvExpression expression)
{
this.expression = expression;
}
internal string ToExpressionString() => IsExpression() ? $"({this})" : this.ToString();
internal bool IsExpression() => expression != null;
/// <summary>
/// AppEnv instance containing All environments
/// </summary>
/// <returns></returns>
public static AppEnv All = !new AppEnv(new string[0]);
/// <summary>
/// Creates AppEnv instance with single <paramref name="appEnvs"/> environment
/// </summary>
/// <param name="appEnvs"></param>
/// <returns></returns>
public static AppEnv In(params string[] appEnvs) => new AppEnv(appEnvs);
/// <summary>
/// Creates AppEnv instance contains all environments except <paramref name="appEnvs"/>
/// </summary>
/// <param name="appEnvs"></param>
/// <returns></returns>
public static AppEnv NotIn(params string[] appEnvs) => !In(appEnvs);
/// <summary>
/// Creates new AppEnv containing both environments
/// </summary>
/// <param name="another"></param>
/// <returns></returns>
public AppEnv Plus(AppEnv another)
=> new AppEnv(new AppEnvExpression(AppEnvOperation.Union, this, another));
/// <summary>
/// Creates new AppEnv containing intersection of both environments
/// </summary>
/// <param name="another"></param>
/// <returns></returns>
public AppEnv Intersects(AppEnv another)
=> new AppEnv(new AppEnvExpression(AppEnvOperation.Intersect, this, another));
/// <summary>
/// Creates new AppEnv containing instance environments except of environments from <paramref name="another"/>
/// </summary>
/// <param name="another"></param>
/// <returns></returns>
public AppEnv Minus(AppEnv another) => this.Intersects(another.Negative());
/// <summary>
/// Creates new AppEnv containing Reverse environments
/// </summary>
/// <returns></returns>
public AppEnv Negative() => new AppEnv(new AppEnvExpression(AppEnvOperation.Negative, this, null));
public static AppEnv operator +(AppEnv appEnv1, AppEnv appEnv2) => appEnv1.Plus(appEnv2);
public static AppEnv operator *(AppEnv appEnv1, AppEnv appEnv2) => appEnv1.Intersects(appEnv2);
public static AppEnv operator -(AppEnv appEnv1, AppEnv appEnv2) => appEnv1.Minus(appEnv2);
public static AppEnv operator !(AppEnv appEnv1) => appEnv1.Negative();
public static implicit operator AppEnv (string s)
{
return AppEnv.In(s);
}
/// <summary>
/// Check is <paramref name="environment"/> in
/// </summary>
/// <param name="environment"></param>
/// <returns></returns>
public bool IsIn(string environment)
{
if (expression != null)
return expression.IsIn(environment);
return include.Contains(environment);
}
public override string ToString()
{
if (expression != null)
return expression.ToString();
return "[" + string.Join(",", include)+ "]";
}
private static IEnumerable<string> MergeInclude(IEnumerable<string> first, IEnumerable<string> second,
Func<IEnumerable<string>, IEnumerable<string>, IEnumerable<string>> mergeFunc)
{
// null means all set
if (first == null || second == null)
return null;
return mergeFunc(first, second);
}
private static IEnumerable<string> MergeExclude(IEnumerable<string> first, IEnumerable<string> second,
Func<IEnumerable<string>, IEnumerable<string>, IEnumerable<string>> mergeFunc)
{
if (first == null && second == null)
return null;
if (first == null)
return second;
if (second == null)
return first;
return mergeFunc(first, second);
}
}
} | 34.91 | 118 | 0.541392 | [
"MIT"
] | Steinpilz/confifu | src/app/Confifu/AppEnv.cs | 6,984 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace HeartOfGold.Web.Models
{
public class Item
{
public int ID { get; set; }
public string Name { get; set; }
public string Description { get; set; }
public CategoryName Category { get; set; }
public int QuantityOnHand { get; set; }
public bool Active { get; set; }
}
} | 25.058824 | 50 | 0.619718 | [
"MIT"
] | deanwiseman/Heart-of-Gold | HeartOfGold/HeartOfGold.Web/Models/Item.cs | 428 | C# |
using System.Web.Mvc;
namespace JerryPlat.Web.Areas.Admin
{
public class AdminAreaRegistration : AreaRegistration
{
public override string AreaName
{
get
{
return "Admin";
}
}
public override void RegisterArea(AreaRegistrationContext context)
{
context.MapRoute(
"Admin_default",
"Admin/{controller}/{action}/{id}",
new { controller = "Home", action = "Index", id = UrlParameter.Optional },
new string[] { "JerryPlat.Web.Areas.Admin.Controllers" }
);
}
}
} | 26.36 | 90 | 0.517451 | [
"MIT"
] | JerryPCN/Jerry-Project-Template | SRC/JerryPlat.Web/Areas/Admin/AdminAreaRegistration.cs | 661 | C# |
namespace P01_StudentSystem.Data.Models
{
using System.ComponentModel.DataAnnotations;
public class Resource
{
public int ResourceId { get; set; }
[MaxLength(50)]
public string Name { get; set; }
public string Url { get; set; }
public ResourceType ResourceType { get; set; }
public int CourseId { get; set; }
public Course Course { get; set; }
}
public enum ResourceType
{
Video = 1,
Presentation = 2,
Document = 3,
Other = 4
}
}
| 20.678571 | 54 | 0.540587 | [
"MIT"
] | marinakolova/CSharp-Courses | Entity-Framework-Core-October-2019/05-EntityRelations/StudentSystem/P01_StudentSystem.Data.Models/Resource.cs | 581 | C# |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
using System.Collections.Generic;
using System.Linq;
using Windows.Data.Json;
using Windows.UI;
using Windows.UI.Xaml.Markup;
namespace VanArsdel.Devices
{
public interface IPropertyColorPalette : IProperty
{
Color SelectedColor { get; set; }
Color CustomColor { get; set; }
IReadOnlyList<Color> Colors { get; }
}
public class PropertyColorPalette : Property, IPropertyColorPalette
{
public static PropertyColorPalette ParsePropertyColorPalette(JsonObject data)
{
Color value = VanArsdel.Utils.ColorUtils.ParseColorString(data["Value"].GetString());
Color customColor = VanArsdel.Utils.ColorUtils.ParseColorString(data["CustomColor"].GetString());
JsonArray paletteData = data["Palette"].GetArray();
List<Color> palette = new List<Color>();
foreach (var node in paletteData)
{
palette.Add(VanArsdel.Utils.ColorUtils.ParseColorString(node.GetString()));
}
bool isVisibleInProductEditor = bool.Parse(data["IsVisibleInProductEditor"].GetString());
bool isVisibleInMyLights = bool.Parse(data["IsVisibleInMyLights"].GetString());
List<PropertyMetadataItem> metadata = null;
if (data.ContainsKey("Metadata"))
{
metadata = PropertyMetadataItem.ParsePropertyMetadataItemList(data["Metadata"].GetArray());
}
return new PropertyColorPalette(data["Id"].GetString(), data["Caption"].GetString(), value, palette, customColor, isVisibleInProductEditor, isVisibleInMyLights, metadata);
}
public PropertyColorPalette(string id, string header, Color selectedColor, IReadOnlyList<Color> colors, Color customColor, bool isVisibleInProductEditor, bool isVisibleInMyLights, List<PropertyMetadataItem> metadata)
: base(id, PropertyEditorType.ColorPalette, header, isVisibleInProductEditor, isVisibleInMyLights, metadata)
{
_colors = colors;
_selectedColor = selectedColor;
_customColor = customColor;
}
private Color _selectedColor;
public Color SelectedColor
{
get { return _selectedColor; }
set
{
if (_selectedColor != value)
{
_selectedColor = value;
RaiseValueChanged();
RaisePropertyChangedFromSource();
}
}
}
private Color _customColor;
public Color CustomColor
{
get { return _customColor; }
set
{
if (_customColor != value)
{
_customColor = value;
RaisePropertyChangedFromSource();
}
}
}
private readonly IReadOnlyList<Color> _colors;
public IReadOnlyList<Color> Colors
{
get { return _colors; }
}
public override bool ComparePresetValueString(string value)
{
object boxedColor = XamlBindingHelper.ConvertValue(typeof(Color), value);
if (boxedColor is Color c)
{
return c == _selectedColor;
}
return false;
}
public override void SetPresetValueString(string value)
{
object boxedColor = XamlBindingHelper.ConvertValue(typeof(Color), value);
if (boxedColor is Color c)
{
if (!_colors.Contains(c))
{
CustomColor = c;
}
SelectedColor = c;
}
}
public override IProperty Clone()
{
List<Color> _clonedColors = new List<Color>(_colors.Count);
for (int i = 0; i < _colors.Count; i++)
{
_clonedColors.Add(_colors[i]);
}
return new PropertyColorPalette(_id, _header, _selectedColor, _clonedColors, _customColor, _isVisibleInProductEditor, _isVisibleInMyLights, _metadata.Clone());
}
}
public class PropertyColorPaletteForwarder : PropertyForwarder<IPropertyColorPalette>, IPropertyColorPalette
{
public PropertyColorPaletteForwarder(string id, IEnumerable<IProperty> linkedProperties)
: base(id, PropertyEditorType.ColorPalette, linkedProperties)
{ }
public Color SelectedColor
{
get
{
if (_linkedProperties == null || _linkedProperties.Count == 0)
{
return Windows.UI.Colors.Black;
}
return _linkedProperties[0].SelectedColor;
}
set
{
foreach (var prop in _linkedProperties)
{
prop.SelectedColor = value;
}
}
}
public Color CustomColor
{
get
{
if (_linkedProperties == null || _linkedProperties.Count == 0)
{
return Windows.UI.Colors.White;
}
return _linkedProperties[0].CustomColor;
}
set
{
foreach (var prop in _linkedProperties)
{
prop.CustomColor = value;
}
}
}
public IReadOnlyList<Color> Colors
{
get
{
if (_linkedProperties == null || _linkedProperties.Count == 0)
{
return null;
}
return _linkedProperties[0].Colors;
}
}
}
}
| 33.344633 | 224 | 0.546256 | [
"MIT"
] | Bhaskers-Blu-Org2/VanArsdel | VanArsdel/Model/Devices/PropertyColorPalette.cs | 5,904 | C# |
namespace Signum.Test.LinqProvider;
public class TakeSkipTest
{
public TakeSkipTest()
{
MusicStarter.StartAndLoad();
Connector.CurrentLogger = new DebugTextWriter();
}
[Fact]
public void Take()
{
var takeArtist = Database.Query<ArtistEntity>().Take(2).ToList();
Assert.Equal(2, takeArtist.Count);
}
[Fact]
public void TakeOrder()
{
var takeArtist = Database.Query<ArtistEntity>().OrderBy(a => a.Name).Take(2).ToList();
Assert.Equal(2, takeArtist.Count);
}
[Fact]
public void TakeSql()
{
var takeAlbum = Database.Query<AlbumEntity>().Select(a => new { a.Name, TwoSongs = a.Songs.Take(2) }).ToList();
Assert.True(takeAlbum.All(a => a.TwoSongs.Count() <= 2));
}
[Fact]
public void Skip()
{
var skipArtist = Database.Query<ArtistEntity>().Skip(2).ToList();
}
[Fact]
public void SkipAllAggregates()
{
var allAggregates = Database.Query<ArtistEntity>().GroupBy(a => new { }).Select(gr => new { Count = gr.Count(), MaxId = gr.Max(a=>a.Id) }).Skip(2).ToList();
}
[Fact]
public void AllAggregatesOrderByAndByKeys()
{
var allAggregates = Database.Query<ArtistEntity>().GroupBy(a => new { }).Select(gr => new { Count = gr.Count(), MaxId = gr.Max(a => a.Id) }).OrderBy(a => a.Count).OrderAlsoByKeys().ToList();
}
[Fact]
public void SkipAllAggregatesOrderBy()
{
var allAggregates = Database.Query<ArtistEntity>().GroupBy(a => new { }).Select(gr => new { Count = gr.Count(), MaxId = gr.Max(a => a.Id) }).OrderBy(a=>a.Count).Skip(2).ToList();
}
[Fact]
public void AllAggregatesCount()
{
var count = Database.Query<ArtistEntity>().GroupBy(a => new { }).Select(gr => new { Count = gr.Count(), MaxId = gr.Max(a => a.Id) }).OrderBy(a => a.Count).Count();
Assert.Equal(1, count);
}
[Fact]
public void SkipOrder()
{
var skipArtist = Database.Query<ArtistEntity>().OrderBy(a => a.Name).Skip(2).ToList();
}
[Fact]
public void SkipSql()
{
var takeAlbum = Database.Query<AlbumEntity>().Select(a => new { a.Name, TwoSongs = a.Songs.Skip(2) }).ToList();
}
[Fact]
public void SkipTake()
{
var skipArtist = Database.Query<ArtistEntity>().Skip(2).Take(1).ToList();
}
[Fact]
public void SkipTakeOrder()
{
var skipArtist = Database.Query<ArtistEntity>().OrderBy(a => a.Name).Skip(2).Take(1).ToList();
}
[Fact]
public void InnerTake()
{
var result = Database.Query<AlbumEntity>()
.Where(dr => dr.Songs.OrderByDescending(a => a.Seconds).Take(1).Where(a => a.Name.Contains("Zero")).Any())
.Select(a => a.ToLite())
.ToList();
Assert.Empty(result);
}
[Fact]
public void OrderByCommonSelectPaginate()
{
TestPaginate(Database.Query<ArtistEntity>().OrderBy(a => a.Sex).Select(a => a.Name));
}
[Fact]
public void OrderBySelectPaginate()
{
TestPaginate(Database.Query<ArtistEntity>().OrderBy(a => a.Name).Select(a => a.Name));
}
[Fact]
public void OrderByDescendingSelectPaginate()
{
TestPaginate(Database.Query<ArtistEntity>().OrderByDescending(a => a.Name).Select(a => a.Name));
}
[Fact]
public void OrderByThenBySelectPaginate()
{
TestPaginate(Database.Query<ArtistEntity>().OrderBy(a => a.Name).ThenBy(a => a.Id).Select(a => a.Name));
}
[Fact]
public void SelectOrderByPaginate()
{
TestPaginate(Database.Query<ArtistEntity>().Select(a => a.Name).OrderBy(a => a));
}
[Fact]
public void SelectOrderByDescendingPaginate()
{
TestPaginate(Database.Query<ArtistEntity>().Select(a => a.Name).OrderByDescending(a => a));
}
private void TestPaginate<T>(IQueryable<T> query)
{
var list = query.OrderAlsoByKeys().ToList();
int pageSize = 2;
var list2 = 0.To(((list.Count / pageSize) + 1)).SelectMany(page =>
query.OrderAlsoByKeys().Skip(pageSize * page).Take(pageSize).ToList()).ToList();
Assert.Equal(list, list2);
}
}
| 29.308725 | 199 | 0.572933 | [
"MIT"
] | Faridmehr/framework | Signum.Test/LinqProvider/TakeSkipTest.cs | 4,367 | C# |
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using Microsoft.CodeAnalysis.Text;
using Microsoft.VisualStudio.Text;
namespace ShaderTools.CodeAnalysis.Editor.Shared.Extensions
{
/// <summary>
/// Extension methods for the editor Span struct
/// </summary>
internal static class SpanExtensions
{
/// <summary>
/// Convert the editor Span instance to the corresponding TextSpan instance
/// </summary>
/// <param name="span"></param>
/// <returns></returns>
public static TextSpan ToTextSpan(this Span span)
{
return new TextSpan(span.Start, span.Length);
}
}
}
| 33.375 | 162 | 0.635456 | [
"Apache-2.0"
] | BigHeadGift/HLSL | src/ShaderTools.CodeAnalysis.EditorFeatures/Shared/Extensions/SpanExtensions.cs | 780 | C# |
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by Codezu.
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
using System;
namespace Mozu.Api.Contracts.Location
{
///
/// Container for the label that describes the range of operating hours for a location.
///
public class Hours
{
///
///Descriptive text used as a label for objects, such as field names, facets, date ranges, contact information, and package information.
///
public string Label { get; set; }
}
} | 26.607143 | 139 | 0.524832 | [
"MIT"
] | thomsumit/mozu-dotnet | Mozu.Api/Contracts/Location/Hours.cs | 745 | C# |
// Copyright (c) Microsoft Open Technologies, Inc. All rights reserved. See License.txt in the project root for license information.
namespace System.Data.Entity.Infrastructure
{
using System.Collections;
using System.Collections.Generic;
using System.Data.Entity.Core.Objects.ELinq;
using System.Data.Entity.Internal;
using System.Data.Entity.Internal.Linq;
using System.Data.Entity.Resources;
using System.Linq;
using System.Linq.Expressions;
using Moq;
using Xunit;
using MockHelper = System.Data.Entity.Core.Objects.MockHelper;
public class DbQueryTests : TestBase
{
[Fact]
public void String_Include_with_null_string_called_on_actual_DbQuery_throws()
{
Assert.Equal(
Strings.ArgumentIsNullOrWhitespace("path"),
Assert.Throws<ArgumentException>(() =>
new DbQuery<object>(new Mock<IInternalQuery<object>>().Object).Include(null)).Message);
}
[Fact]
public void String_Include_with_empty_string_called_on_actual_DbQuery_throws()
{
Assert.Equal(
Strings.ArgumentIsNullOrWhitespace("path"),
Assert.Throws<ArgumentException>(() =>
new DbQuery<object>(new Mock<IInternalQuery<object>>().Object).Include("")).Message);
}
[Fact]
public void String_Include_with_whitespace_string_called_on_actual_DbQuery_throws()
{
Assert.Equal(
Strings.ArgumentIsNullOrWhitespace("path"),
Assert.Throws<ArgumentException>(() =>
new DbQuery<object>(new Mock<IInternalQuery<object>>().Object).Include(" ")).Message);
}
[Fact]
public void Non_generic_String_Include_with_null_string_called_on_actual_DbQuery_throws()
{
Assert.Equal(
Strings.ArgumentIsNullOrWhitespace("path"),
Assert.Throws<ArgumentException>(() =>
new InternalDbQuery<object>(new Mock<IInternalQuery<object>>().Object).Include(null)).Message);
}
[Fact]
public void Non_generic_String_Include_with_empty_string_called_on_actual_DbQuery_throws()
{
Assert.Equal(
Strings.ArgumentIsNullOrWhitespace("path"),
Assert.Throws<ArgumentException>(() =>
new InternalDbQuery<object>(new Mock<IInternalQuery<object>>().Object).Include("")).Message);
}
[Fact]
public void Non_generic_String_Include_with_whitespace_string_called_on_actual_DbQuery_throws()
{
Assert.Equal(
Strings.ArgumentIsNullOrWhitespace("path"),
Assert.Throws<ArgumentException>(() =>
new InternalDbQuery<object>(new Mock<IInternalQuery<object>>().Object).Include(" ")).Message);
}
[Fact]
public void Methods_delegate_to_underlying_InternalQuery_correctly()
{
#if !NET40
VerifyMethod(
q => ((IDbAsyncEnumerable)q).GetAsyncEnumerator(),
m => m.GetAsyncEnumerator());
VerifyMethod(
q => ((IDbAsyncEnumerable<string>)q).GetAsyncEnumerator(),
m => m.GetAsyncEnumerator());
#endif
VerifyMethod(
q => ((IEnumerable<string>)q).GetEnumerator(),
m => m.GetEnumerator());
VerifyMethod(
q => q.AsNoTracking(),
m => m.AsNoTracking());
VerifyMethod(
q => q.Include("a"),
m => m.Include("a"));
}
[Fact]
public void Properties_delegate_to_underlying_InternalQuery_correctly()
{
VerifyGetter(
q => ((IQueryable)q).ElementType,
m => m.ElementType);
VerifyGetter(
q => ((IQueryable)q).Expression,
m => m.Expression);
VerifyGetter(
q => ((IQueryable)q).Provider,
m => m.InternalContext);
}
[Fact]
public void NonGeneric_methods_delegate_to_underlying_InternalQuery_correctly()
{
var internalQueryMock = new Mock<IInternalQuery<string>>();
var nonGenericInternalQueryMock = internalQueryMock.As<IInternalQuery>();
nonGenericInternalQueryMock.Setup(m => m.GetEnumerator()).Returns(new Mock<IEnumerator>().Object);
var dbQuery = new InternalDbQuery<string>(internalQueryMock.Object);
#if !NET40
((IDbAsyncEnumerable)dbQuery).GetAsyncEnumerator();
nonGenericInternalQueryMock.Verify(m => m.GetAsyncEnumerator(), Times.Once());
#endif
((IEnumerable)dbQuery).GetEnumerator();
nonGenericInternalQueryMock.Verify(m => m.GetEnumerator(), Times.Once());
}
private void VerifyGetter<TProperty, TInternalProperty>(
Func<DbQuery<string>, TProperty> getterFunc,
Expression<Func<IInternalQuery<string>, TInternalProperty>> mockGetterFunc)
{
Assert.NotNull(getterFunc);
Assert.NotNull(mockGetterFunc);
var internalQueryMock = new Mock<IInternalQuery<string>>();
internalQueryMock.Setup(m => m.ElementType).Returns(typeof(string));
internalQueryMock.Setup(m => m.Expression).Returns(Expression.Constant(new object()));
internalQueryMock.Setup(m => m.InternalContext).Returns(new Mock<InternalContextForMock<DbContext>>().Object);
internalQueryMock.Setup(m => m.ObjectQueryProvider).Returns(
new ObjectQueryProvider(MockHelper.CreateMockObjectContext<string>()));
var dbQuery = new DbQuery<string>(internalQueryMock.Object);
getterFunc(dbQuery);
internalQueryMock.VerifyGet(mockGetterFunc, Times.Once());
}
private void VerifyMethod(Action<DbQuery<string>> methodInvoke, Expression<Action<IInternalQuery<string>>> mockMethodInvoke)
{
Assert.NotNull(methodInvoke);
Assert.NotNull(mockMethodInvoke);
var internalQueryMock = new Mock<IInternalQuery<string>>();
internalQueryMock.Setup(m => m.GetEnumerator()).Returns(new Mock<IEnumerator<string>>().Object);
internalQueryMock.Setup(m => m.AsNoTracking()).Returns(internalQueryMock.Object);
internalQueryMock.Setup(m => m.Include(It.IsAny<string>())).Returns(internalQueryMock.Object);
var dbQuery = new DbQuery<string>(internalQueryMock.Object);
methodInvoke(dbQuery);
internalQueryMock.Verify(mockMethodInvoke, Times.Once());
}
}
}
| 41.453988 | 133 | 0.617434 | [
"Apache-2.0"
] | CZEMacLeod/EntityFramework6 | test/EntityFramework/UnitTests/Infrastructure/DbQueryTests.cs | 6,759 | C# |
using Supido.Business.Attributes;
using Supido.Business.Meta;
using Supido.Core.Types;
using Supido.Core.Utils;
using System;
using System.Collections.Generic;
using System.Reflection;
using Telerik.OpenAccess.Metadata;
using Telerik.OpenAccess.Metadata.Relational;
namespace Supido.Business.Security
{
/// <summary>
/// Security scanner for assemblies
/// </summary>
public class SecurityScanner
{
#region - Fields -
/// <summary>
/// The metatables
/// </summary>
private Dictionary<string, MetaPersistentType> metatables;
/// <summary>
/// The metatables, but the string index is only class name without namespace.
/// </summary>
private Dictionary<string, MetaPersistentType> typeMetatables = new Dictionary<string, MetaPersistentType>();
#endregion
#region - Properties -
/// <summary>
/// Gets the parent security manager.
/// </summary>
/// <value>
/// The parent.
/// </value>
public ISecurityManager Parent { get; private set; }
/// <summary>
/// Gets or sets the entity preffix.
/// </summary>
/// <value>
/// The entity preffix.
/// </value>
public string EntityPreffix { get; set; }
/// <summary>
/// Gets or sets the entity suffix.
/// </summary>
/// <value>
/// The entity suffix.
/// </value>
public string EntitySuffix { get; set; }
/// <summary>
/// Gets or sets the dto preffix.
/// </summary>
/// <value>
/// The dto preffix.
/// </value>
public string DtoPreffix { get; set; }
/// <summary>
/// Gets or sets the dto suffix.
/// </summary>
/// <value>
/// The dto suffix.
/// </value>
public string DtoSuffix { get; set; }
/// <summary>
/// Gets or sets the filter preffix.
/// </summary>
/// <value>
/// The filter preffix.
/// </value>
public string FilterPreffix { get; set; }
/// <summary>
/// Gets or sets the filter suffix.
/// </summary>
/// <value>
/// The filter suffix.
/// </value>
public string FilterSuffix { get; set; }
/// <summary>
/// Gets or sets the bo preffix.
/// </summary>
/// <value>
/// The bo preffix.
/// </value>
public string BOPreffix { get; set; }
/// <summary>
/// Gets or sets the bo suffix.
/// </summary>
/// <value>
/// The bo suffix.
/// </value>
public string BOSuffix { get; set; }
/// <summary>
/// Gets or sets the metatables.
/// </summary>
/// <value>
/// The metatables.
/// </value>
public Dictionary<string, MetaPersistentType> Metatables
{
get
{
return this.metatables;
}
set
{
this.metatables = value;
this.typeMetatables.Clear();
foreach (KeyValuePair<string, MetaPersistentType> kvp in this.metatables)
{
this.typeMetatables.Add(this.GetClassName(kvp.Key).ToLower(), kvp.Value);
}
}
}
#endregion
#region - Constructors -
/// <summary>
/// Initializes a new instance of the <see cref="SecurityScanner"/> class.
/// </summary>
/// <param name="parent">The parent.</param>
public SecurityScanner(ISecurityManager parent)
{
this.Parent = parent;
this.EntityPreffix = string.Empty;
this.EntitySuffix = string.Empty;
this.DtoPreffix = string.Empty;
this.DtoSuffix = string.Empty;
}
#endregion
#region - Methods -
/// <summary>
/// Removes the preffix from a name.
/// </summary>
/// <param name="name">The name.</param>
/// <param name="preffix">The preffix.</param>
/// <returns></returns>
private string RemovePreffix(string name, string preffix)
{
if (!string.IsNullOrEmpty(preffix))
{
if (name.StartsWith(preffix))
{
name = name.Substring(preffix.Length);
}
}
return name;
}
/// <summary>
/// Removes the suffix from a name.
/// </summary>
/// <param name="name">The name.</param>
/// <param name="suffix">The suffix.</param>
/// <returns></returns>
private string RemoveSuffix(string name, string suffix)
{
if (!string.IsNullOrEmpty(suffix))
{
if (name.EndsWith(suffix))
{
name = name.Substring(0, name.Length - suffix.Length);
}
}
return name;
}
/// <summary>
/// Gets the name of the entity from a dto name.
/// </summary>
/// <param name="name">The name.</param>
/// <returns></returns>
private string GetEntityName(string name)
{
name = this.RemovePreffix(name, this.DtoPreffix);
name = this.RemoveSuffix(name, this.DtoSuffix);
return this.EntityPreffix + name + this.EntitySuffix;
}
/// <summary>
/// Gets the class name form a full name.
/// </summary>
/// <param name="name">The name.</param>
/// <returns></returns>
private string GetClassName(string name)
{
int i = name.LastIndexOf('.');
if (i > -1)
{
return name.Substring(i + 1, name.Length - i - 1);
}
else
{
return name;
}
}
/// <summary>
/// Determines whether the specified type is dto.
/// </summary>
/// <param name="type">The type.</param>
/// <returns></returns>
private bool IsDto(Type type)
{
return AttributeUtil.GetAttributeFrom<DtoAttribute>(type) != null;
}
/// <summary>
/// Determines whether the specified type is filter.
/// </summary>
/// <param name="type">The type.</param>
/// <returns></returns>
private bool IsFilter(Type type)
{
return AttributeUtil.GetAttributeFrom<FilterAttribute>(type) != null;
}
/// <summary>
/// Determines whether the specified type is bo.
/// </summary>
/// <param name="type">The type.</param>
/// <returns></returns>
private bool IsBO(Type type)
{
return AttributeUtil.GetAttributeFrom<BOAttribute>(type) != null;
}
public void ProcessDynamicDto(Type dtoType, Type entityType)
{
IMetamodelEntity metaEntity = this.Parent.MetamodelManager.RegisterEntity(entityType, dtoType);
if (this.Metatables.ContainsKey(entityType.FullName))
{
MetaPersistentType metaType = this.Metatables[entityType.FullName];
Dictionary<MetaColumn, MetaMember> mapColumns = new Dictionary<MetaColumn, MetaMember>();
foreach (MetaMember member in metaType.Members)
{
MetaPrimitiveMember primitiveMember = member as MetaPrimitiveMember;
if (primitiveMember != null)
{
mapColumns.Add(primitiveMember.Column, member);
}
}
MetaTable metaTable = metaType.Table;
foreach (MetaColumn metaColumn in metaTable.Columns)
{
MetaMember member = mapColumns[metaColumn];
metaEntity.AddField(member.Name, metaColumn.IsPrimaryKey, !metaColumn.IsPrimaryKey);
}
}
}
/// <summary>
/// Processes the type if it's a DTO
/// </summary>
/// <param name="type">The type.</param>
private void ProcessDto(Type type)
{
DtoAttribute dtoAttribute = AttributeUtil.GetAttributeFrom<DtoAttribute>(type);
if (dtoAttribute != null)
{
Type entityType = null;
if (dtoAttribute.EntityType != null)
{
entityType = dtoAttribute.EntityType;
}
else
{
string entityName = dtoAttribute.EntityName;
if (string.IsNullOrEmpty(entityName))
{
entityName = this.GetEntityName(type.Name);
}
entityType = TypesManager.ResolveType(entityName);
if (entityType == null)
{
if (this.typeMetatables.ContainsKey(entityName.ToLower()))
{
entityName = this.typeMetatables[entityName.ToLower()].FullName;
entityType = TypesManager.ResolveType(entityName);
}
}
}
if (entityType != null)
{
IMetamodelEntity metaEntity = this.Parent.MetamodelManager.RegisterEntity(entityType, type);
if (this.Metatables.ContainsKey(entityType.FullName))
{
MetaPersistentType metaType = this.Metatables[entityType.FullName];
Dictionary<MetaColumn, MetaMember> mapColumns = new Dictionary<MetaColumn, MetaMember>();
foreach (MetaMember member in metaType.Members)
{
MetaPrimitiveMember primitiveMember = member as MetaPrimitiveMember;
if (primitiveMember != null)
{
mapColumns.Add(primitiveMember.Column, member);
}
}
MetaTable metaTable = metaType.Table;
foreach (MetaColumn metaColumn in metaTable.Columns)
{
MetaMember member = mapColumns[metaColumn];
metaEntity.AddField(member.Name, metaColumn.IsPrimaryKey, !metaColumn.IsPrimaryKey);
}
}
}
}
}
/// <summary>
/// Processes a type if its a Filter
/// </summary>
/// <param name="type">The type.</param>
/// <returns></returns>
private void ProcessFilter(Type type, Dictionary<string, Type> dtoMap)
{
FilterAttribute filterAttribute = AttributeUtil.GetAttributeFrom<FilterAttribute>(type);
if (filterAttribute == null)
{
return;
}
if (filterAttribute.DtoType != null)
{
this.Parent.BOManager.AddFilterType(filterAttribute.DtoType, type);
return;
}
string name = string.IsNullOrEmpty(filterAttribute.Name) ? type.Name : filterAttribute.Name;
if (name.IndexOf('.') > -1)
{
Type dtoType = TypesManager.ResolveType(name);
if (dtoType != null)
{
this.Parent.BOManager.AddFilterType(dtoType, type);
}
return;
}
if (dtoMap.ContainsKey(name))
{
this.Parent.BOManager.AddFilterType(dtoMap[name], type);
return;
}
string testname = this.DtoPreffix + name + this.DtoSuffix;
if (dtoMap.ContainsKey(testname))
{
this.Parent.BOManager.AddFilterType(dtoMap[testname], type);
return;
}
testname = name;
testname = this.RemovePreffix(testname, this.FilterPreffix);
testname = this.RemoveSuffix(testname, this.FilterSuffix);
if (dtoMap.ContainsKey(testname))
{
this.Parent.BOManager.AddFilterType(dtoMap[testname], type);
return;
}
testname = this.DtoPreffix + testname + this.DtoSuffix;
if (dtoMap.ContainsKey(testname))
{
this.Parent.BOManager.AddFilterType(dtoMap[testname], type);
return;
}
}
/// <summary>
/// Processes a type if its a BO
/// </summary>
/// <param name="type">The type.</param>
/// <returns></returns>
private void ProcessBO(Type type, Dictionary<string, Type> dtoMap)
{
BOAttribute boAttribute = AttributeUtil.GetAttributeFrom<BOAttribute>(type);
if (boAttribute == null)
{
return;
}
if (boAttribute.DtoType != null)
{
this.Parent.BOManager.AddBOType(boAttribute.DtoType, type);
return;
}
string name = string.IsNullOrEmpty(boAttribute.Name) ? type.Name : boAttribute.Name;
if (name.IndexOf('.') > -1)
{
Type dtoType = TypesManager.ResolveType(name);
if (dtoType != null)
{
this.Parent.BOManager.AddBOType(dtoType, type);
}
return;
}
if (dtoMap.ContainsKey(name))
{
this.Parent.BOManager.AddBOType(dtoMap[name], type);
return;
}
string testname = this.DtoPreffix + name + this.DtoSuffix;
if (dtoMap.ContainsKey(testname))
{
this.Parent.BOManager.AddBOType(dtoMap[testname], type);
return;
}
testname = name;
testname = this.RemovePreffix(testname, this.BOPreffix);
testname = this.RemoveSuffix(testname, this.BOSuffix);
if (dtoMap.ContainsKey(testname))
{
this.Parent.BOManager.AddBOType(dtoMap[testname], type);
return;
}
testname = this.DtoPreffix + testname + this.DtoSuffix;
if (dtoMap.ContainsKey(testname))
{
this.Parent.BOManager.AddBOType(dtoMap[testname], type);
return;
}
}
/// <summary>
/// Scans the specified assembly.
/// </summary>
/// <param name="assembly">The assembly.</param>
protected void Scan(Assembly assembly)
{
IList<Type> dtoTypes = new List<Type>();
IList<Type> filterTypes = new List<Type>();
IList<Type> boTypes = new List<Type>();
IList<Type> serviceTypes = new List<Type>();
foreach (Type type in assembly.GetTypes())
{
if (this.IsDto(type))
{
dtoTypes.Add(type);
}
else if (this.IsFilter(type))
{
filterTypes.Add(type);
}
else if (this.IsBO(type))
{
boTypes.Add(type);
}
}
// Process Dtos
Dictionary<string, Type> dtoMap = new Dictionary<string, Type>();
foreach (Type type in dtoTypes)
{
dtoMap.Add(GetClassName(type.Name), type);
this.ProcessDto(type);
}
// Process filters
foreach (Type type in filterTypes)
{
this.ProcessFilter(type, dtoMap);
}
// Process filters
foreach (Type type in boTypes)
{
this.ProcessBO(type, dtoMap);
}
}
/// <summary>
/// Scans the specified assembly given its name.
/// </summary>
/// <param name="namespaceStr">The namespace string.</param>
protected void Scan(string namespaceStr)
{
Assembly assembly = Assembly.Load(namespaceStr);
if (assembly != null)
{
this.Scan(assembly);
}
}
/// <summary>
/// Scans several assemblies by the namespaces comma separated. If no assembly name its provided, then scan all the assemblies of the current domain.
/// </summary>
/// <param name="namespacesStr">The namespaces string.</param>
public void ScanNamespace(string namespacesStr)
{
if (string.IsNullOrEmpty(namespacesStr))
{
foreach (Assembly assembly in AppDomain.CurrentDomain.GetAssemblies())
{
this.Scan(assembly);
}
}
else
{
string[] namespaces = namespacesStr.Split(',');
foreach (string namespaceStr in namespaces)
{
this.Scan(namespacesStr.Trim());
}
}
}
/// <summary>
/// Finds the entity type given the entity name in the telerik metamodel.
/// </summary>
/// <param name="entityName">Name of the entity.</param>
/// <returns></returns>
public Type FindEntityTypeInMetamodel(string entityName)
{
if (this.typeMetatables.ContainsKey(entityName.ToLower()))
{
string fullName = this.typeMetatables[entityName.ToLower()].FullName;
return TypesManager.ResolveType(fullName);
}
return null;
}
#endregion
}
}
| 33.960748 | 157 | 0.491827 | [
"MIT"
] | jseijas/supido | Source/Supido.Business/Security/SecurityScanner.cs | 18,171 | C# |
// This file was automatically generated and may be regenerated at any
// time. To ensure any changes are retained, modify the tool with any segment/component/group/field name
// or type changes.
namespace Machete.HL7Schema.V26.Maps
{
using V26;
/// <summary>
/// PPR_PC1 (MessageMap) -
/// </summary>
public class PPR_PC1Map :
HL7V26LayoutMap<PPR_PC1>
{
public PPR_PC1Map()
{
Segment(x => x.MSH, 0, x => x.Required = true);
Segment(x => x.SFT, 1);
Segment(x => x.UAC, 2);
Segment(x => x.PID, 3, x => x.Required = true);
Layout(x => x.PatientVisit, 4);
Layout(x => x.Problem, 5, x => x.Required = true);
}
}
} | 30.958333 | 104 | 0.557201 | [
"Apache-2.0"
] | ahives/Machete | src/Machete.HL7Schema/V26/Messages/Maps/PPR_PC1Map.cs | 743 | C# |
// Copyright 2004-2009 Castle Project - http://www.castleproject.org/
//
// 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 Castle.Components.DictionaryAdapter
{
/// <summary>
/// Defines the contract for updating dictionary values.
/// </summary>
public interface IDictionaryPropertySetter : IDictionaryBehavior
{
/// <summary>
/// Sets the stored dictionary value.
/// </summary>
/// <param name="dictionaryAdapter">The dictionary adapter.</param>
/// <param name="key">The key.</param>
/// <param name="value">The stored value.</param>
/// <param name="property">The property.</param>
/// <returns>true if the property should be stored.</returns>
bool SetPropertyValue(IDictionaryAdapter dictionaryAdapter, string key, ref object value,
PropertyDescriptor property);
}
} | 39.970588 | 93 | 0.706402 | [
"Apache-2.0"
] | Convey-Compliance/Castle.Core-READONLY | src/Castle.Core/Components.DictionaryAdapter/IDictionaryPropertySetter.cs | 1,359 | C# |
/* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (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.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* The Original Code is Mozilla Universal charset detector code.
*
* The Initial Developer of the Original Code is
* Netscape Communications Corporation.
* Portions created by the Initial Developer are Copyright (C) 2001
* the Initial Developer. All Rights Reserved.
*
* Contributor(s):
* Shy Shalom <shooshX@gmail.com>
* Rudi Pettazzi <rudi.pettazzi@gmail.com> (C# port)
*
* Alternatively, the contents of this file may be used under the terms of
* either the GNU General Public License Version 2 or later (the "GPL"), or
* the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the MPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the MPL, the GPL or the LGPL.
*
* ***** END LICENSE BLOCK ***** */
using System;
namespace Ude.Core
{
public class Big5Prober : CharsetProber
{
//void GetDistribution(PRUint32 aCharLen, const char* aStr);
private CodingStateMachine codingSM;
private BIG5DistributionAnalyser distributionAnalyser;
private byte[] lastChar = new byte[2];
public Big5Prober()
{
this.codingSM = new CodingStateMachine(new BIG5SMModel());
this.distributionAnalyser = new BIG5DistributionAnalyser();
this.Reset();
}
public override ProbingState HandleData(byte[] buf, int offset, int len)
{
int codingState = 0;
int max = offset + len;
for (int i = offset; i < max; i++) {
codingState = codingSM.NextState(buf[i]);
if (codingState == SMModel.ERROR) {
state = ProbingState.NotMe;
break;
}
if (codingState == SMModel.ITSME) {
state = ProbingState.FoundIt;
break;
}
if (codingState == SMModel.START) {
int charLen = codingSM.CurrentCharLen;
if (i == offset) {
lastChar[1] = buf[offset];
distributionAnalyser.HandleOneChar(lastChar, 0, charLen);
} else {
distributionAnalyser.HandleOneChar(buf, i-1, charLen);
}
}
}
lastChar[0] = buf[max-1];
if (state == ProbingState.Detecting)
if (distributionAnalyser.GotEnoughData() && GetConfidence() > SHORTCUT_THRESHOLD)
state = ProbingState.FoundIt;
return state;
}
public override void Reset()
{
codingSM.Reset();
state = ProbingState.Detecting;
distributionAnalyser.Reset();
}
public override string GetCharsetName()
{
return "Big-5";
}
public override float GetConfidence()
{
return distributionAnalyser.GetConfidence();
}
}
}
| 37.678899 | 97 | 0.594351 | [
"MIT"
] | BUTTER-Tools/GetTextEncoding | ude-master/src/Library/Ude.Core/Big5Prober.cs | 4,107 | C# |
using System;
using System.Net.Mime;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using NHSD.BuyingCatalogue.Ordering.Api.Authorization;
using NHSD.BuyingCatalogue.Ordering.Api.Models;
using NHSD.BuyingCatalogue.Ordering.Api.Services;
using NHSD.BuyingCatalogue.Ordering.Common.Constants;
using NHSD.BuyingCatalogue.Ordering.Contracts;
using NHSD.BuyingCatalogue.Ordering.Domain;
namespace NHSD.BuyingCatalogue.Ordering.Api.Controllers
{
[Route("api/v1/orders/{callOffId}/sections/supplier")]
[ApiController]
[Produces(MediaTypeNames.Application.Json)]
[Authorize(Policy = PolicyName.CanAccessOrders)]
[AuthorizeOrganisation]
public sealed class SupplierSectionController : ControllerBase
{
private readonly ISupplierSectionService supplierSectionService;
private readonly IContactDetailsService contactDetailsService;
public SupplierSectionController(ISupplierSectionService supplierSectionService, IContactDetailsService contactDetailsService)
{
this.supplierSectionService = supplierSectionService ?? throw new ArgumentNullException(nameof(supplierSectionService));
this.contactDetailsService = contactDetailsService ?? throw new ArgumentNullException(nameof(contactDetailsService));
}
[HttpGet]
public async Task<ActionResult<SupplierModel>> GetAsync(CallOffId callOffId)
{
var order = await supplierSectionService.GetOrder(callOffId);
if (order is null)
return NotFound();
return new SupplierModel(order.Supplier, order.SupplierContact);
}
[HttpPut]
[Authorize(Policy = PolicyName.CanManageOrders)]
public async Task<IActionResult> UpdateAsync(CallOffId callOffId, SupplierModel model)
{
if (model is null)
throw new ArgumentNullException(nameof(model));
var order = await supplierSectionService.GetOrder(callOffId);
if (order is null)
return NotFound();
var supplierModel = new Supplier
{
Id = model.SupplierId,
Name = model.Name,
Address = contactDetailsService.AddOrUpdateAddress(order.Supplier?.Address, model.Address),
};
var contact = contactDetailsService.AddOrUpdatePrimaryContact(
order.SupplierContact,
model.PrimaryContact);
await supplierSectionService.SetSupplierSection(order, supplierModel, contact);
return NoContent();
}
}
}
| 37.450704 | 134 | 0.697255 | [
"MIT"
] | nhs-digital-gp-it-futures/BuyingCatalogueOrdering | src/NHSD.BuyingCatalogue.Ordering.Api/Controllers/SupplierSectionController.cs | 2,661 | C# |
namespace CVisualizer
{
public class VariableNode : Node
{
public VariableNode()
{
Label = "x";
}
public override double Calculate(double x)
{
return x;
}
public override string ToString()
{
return "x";
}
public override Node ReturnDerivative(double x)
{
return new NaturalNumberNode(1);
}
public override Node Simplify()
{
return this;
}
public override string ToPrefixString()
{
return ToString();
}
public override Node Copy()
{
return new VariableNode();
}
}
}
| 20.857143 | 55 | 0.471233 | [
"Apache-2.0"
] | nikolaynikolaevn/CVisualizer | CVisualizer/Nodes/VariableNode.cs | 732 | C# |
namespace Epic.OnlineServices.Lobby
{
public delegate void OnSendInviteCallback(SendInviteCallbackInfo data);
}
| 22.6 | 72 | 0.849558 | [
"MIT"
] | undancer/oni-data | Managed/firstpass/Epic/OnlineServices/Lobby/OnSendInviteCallback.cs | 113 | C# |
using Bogus;
namespace SkyCommerce.Models
{
public class Endereco
{
public string Nome { get; set; }
public string Sobrenome { get; set; }
public string Logradouro { get; set; }
public string Bairro { get; set; }
public string Cidade { get; set; }
public string Estado { get; set; }
public string Cep { get; set; }
public string Referencia { get; set; }
public string NomeEndereco { get; set; }
public TipoEndereco TipoEndereco { get; set; }
public Telefone Telefone { get; set; }
public static Faker<Endereco> Obter(string nome)
{
return new Faker<Endereco>("pt_BR")
.RuleFor(e => e.Logradouro, f => f.Address.StreetAddress())
.RuleFor(e => e.Bairro, f => f.Address.SecondaryAddress())
.RuleFor(e => e.Cidade, f => f.Address.City())
.RuleFor(e => e.Estado, f => f.Address.State())
.RuleFor(e => e.Cep, f => f.Address.ZipCode("?????-???"))
.RuleFor(e => e.Referencia, f => f.Lorem.Word())
.RuleFor(e => e.NomeEndereco, f => f.Lorem.Word())
.RuleFor(e => e.Telefone, f => f.Phone.PhoneNumber("(##) 9####-####"))
.RuleFor(e => e.Nome, nome)
.RuleFor(e => e.TipoEndereco, f => f.PickRandom<TipoEndereco>());
}
}
} | 41.441176 | 86 | 0.525195 | [
"MIT"
] | phillrog/curso-is4 | SkyCommerce.Loja/SkyCommerce.Domain/Models/Endereco.cs | 1,411 | C# |
public class Solution {
public int[] TwoSum (int[] nums, int target) {
for (int i = 0; i < nums.Length - 1; i++) {
for (int j = 1; j < nums.Length; j++) {
if (target == nums[i] + nums[j] && i != j)
return new int[] { i, j };
}
}
return null;
}
} | 30.636364 | 58 | 0.400593 | [
"MIT"
] | a26007565/myLeetCode | Easy/1.Two Sum.cs | 337 | C# |
namespace GGJ2021
{
public interface IGameOverController
{
void Show();
void Hide();
void SetWinner(string winner);
}
} | 14.333333 | 37 | 0.705426 | [
"MIT"
] | Snaki94/GGJ2021 | GGJ2021/Assets/Scripts/UI/GameOver/Interfaces/IGameOverController.cs | 131 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace BlueWind.Crawler.Manga
{
internal enum BuiltInSites
{
Manga24h,
BlogTruyen
}
}
| 14.642857 | 33 | 0.687805 | [
"Apache-2.0"
] | koneta/MangaPortal | trunk/src/BlueWind.Crawler.Manga/BuiltInSites.cs | 207 | C# |
using System.ComponentModel;
using System.Windows.Input;
using PS.Patterns.Aware;
namespace PS.WPF.Patterns.Command
{
public interface IUICommand : ICommand,
IDescriptionAware,
IGroupAware,
IOrderAware,
ITitleAware,
IIconAware,
IColorAware,
IVisibilityAware,
INotifyPropertyChanged
{
#region Members
void RaiseCanExecuteChanged();
#endregion
}
} | 28.565217 | 56 | 0.436834 | [
"MIT"
] | BlackGad/PS.Framework | PS.WPF/Patterns/Command/IUICommand.cs | 659 | C# |
using System;
using TB.AspNetCore.Domain.Enums;
namespace TB.AspNetCore.Domain.Models.Api
{
public class AdvertisingModel
{
/// <summary>
/// 唯一id
/// </summary>
public string Id { get; set; }
/// <summary>
/// 标题
/// </summary>
public string AdName { get; set; }
/// <summary>
/// 开始时间
/// </summary>
public DateTime? BeginTime { get; set; }
/// <summary>
/// 结束时间
/// </summary>
public DateTime? EndTime { get; set; }
/// <summary>
/// 图片s
/// </summary>
public string AdPic { get; set; }
/// <summary>
/// 描述
/// </summary>
public string AdDesc { get; set; }
/// <summary>
/// 类型
/// </summary>
public AdLocation AdLocation { get; set; }
}
}
| 22.666667 | 50 | 0.452489 | [
"MIT"
] | lap888/aspnetcore_baodian | TB.AspNetCore.Domain/Models/Api/AdvertisingModel.cs | 922 | C# |
using System;
using System.Drawing;
using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;
using System.Data;
using FractalControl;
namespace Fraktale
{
/// <summary>
/// Summary description for Form1.
/// </summary>
public class Form1 : System.Windows.Forms.Form
{
private System.Windows.Forms.TabControl tabControl1;
private System.Windows.Forms.TabPage tabPage1;
private System.Windows.Forms.TabPage tabPage2;
private FractalControl.FractalControl fractalControl1;
private FractalControlTwo.ArtControl artControl1;
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.Container components = null;
public Form1()
{
//
// Required for Windows Form Designer support
//
InitializeComponent();
//
// TODO: Add any constructor code after InitializeComponent call
//
}
/// <summary>
/// Clean up any resources being used.
/// </summary>
protected override void Dispose( bool disposing )
{
if( disposing )
{
if (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.tabControl1 = new System.Windows.Forms.TabControl();
this.tabPage1 = new System.Windows.Forms.TabPage();
this.fractalControl1 = new FractalControl.FractalControl();
this.tabPage2 = new System.Windows.Forms.TabPage();
this.artControl1 = new FractalControlTwo.ArtControl();
this.tabControl1.SuspendLayout();
this.tabPage1.SuspendLayout();
this.tabPage2.SuspendLayout();
this.SuspendLayout();
//
// tabControl1
//
this.tabControl1.Controls.Add(this.tabPage1);
this.tabControl1.Controls.Add(this.tabPage2);
this.tabControl1.Dock = System.Windows.Forms.DockStyle.Fill;
this.tabControl1.Location = new System.Drawing.Point(0, 0);
this.tabControl1.Name = "tabControl1";
this.tabControl1.SelectedIndex = 0;
this.tabControl1.Size = new System.Drawing.Size(656, 435);
this.tabControl1.TabIndex = 0;
//
// tabPage1
//
this.tabPage1.Controls.Add(this.fractalControl1);
this.tabPage1.Location = new System.Drawing.Point(4, 22);
this.tabPage1.Name = "tabPage1";
this.tabPage1.Size = new System.Drawing.Size(648, 409);
this.tabPage1.TabIndex = 0;
this.tabPage1.Text = "Mandelbrot & Julia";
//
// fractalControl1
//
this.fractalControl1.AutoScroll = true;
this.fractalControl1.AutoScrollMinSize = new System.Drawing.Size(400, 400);
this.fractalControl1.Dock = System.Windows.Forms.DockStyle.Fill;
this.fractalControl1.Location = new System.Drawing.Point(0, 0);
this.fractalControl1.Name = "fractalControl1";
this.fractalControl1.Size = new System.Drawing.Size(648, 409);
this.fractalControl1.TabIndex = 0;
this.fractalControl1.Load += new System.EventHandler(this.fractalControl1_Load);
//
// tabPage2
//
this.tabPage2.Controls.Add(this.artControl1);
this.tabPage2.Location = new System.Drawing.Point(4, 22);
this.tabPage2.Name = "tabPage2";
this.tabPage2.Size = new System.Drawing.Size(648, 409);
this.tabPage2.TabIndex = 1;
this.tabPage2.Text = "Artur";
//
// artControl1
//
this.artControl1.Dock = System.Windows.Forms.DockStyle.Fill;
this.artControl1.Location = new System.Drawing.Point(0, 0);
this.artControl1.Name = "artControl1";
this.artControl1.Size = new System.Drawing.Size(648, 409);
this.artControl1.TabIndex = 0;
//
// Form1
//
this.AutoScaleBaseSize = new System.Drawing.Size(5, 13);
this.ClientSize = new System.Drawing.Size(656, 435);
this.Controls.Add(this.tabControl1);
this.Name = "Form1";
this.Text = "Fraktale";
this.tabControl1.ResumeLayout(false);
this.tabPage1.ResumeLayout(false);
this.tabPage2.ResumeLayout(false);
this.ResumeLayout(false);
}
#endregion
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
{
Application.Run(new Form1());
}
private void fractalControl1_Load(object sender, System.EventArgs e)
{
}
}
}
| 30.401361 | 84 | 0.67778 | [
"MIT"
] | damiandragowski/fractals | Fraktale/MainForm.cs | 4,469 | C# |
using System.Collections.Generic;
using Essensoft.AspNetCore.Payment.Alipay.Response;
namespace Essensoft.AspNetCore.Payment.Alipay.Request
{
/// <summary>
/// zhima.credit.ep.scene.trade.consult
/// </summary>
public class ZhimaCreditEpSceneTradeConsultRequest : IAlipayRequest<ZhimaCreditEpSceneTradeConsultResponse>
{
/// <summary>
/// 交易评估咨询
/// </summary>
public string BizContent { get; set; }
#region IAlipayRequest Members
private bool needEncrypt = false;
private string apiVersion = "1.0";
private string terminalType;
private string terminalInfo;
private string prodCode;
private string notifyUrl;
private string returnUrl;
private AlipayObject bizModel;
public void SetNeedEncrypt(bool needEncrypt)
{
this.needEncrypt = needEncrypt;
}
public bool GetNeedEncrypt()
{
return needEncrypt;
}
public void SetNotifyUrl(string notifyUrl)
{
this.notifyUrl = notifyUrl;
}
public string GetNotifyUrl()
{
return notifyUrl;
}
public void SetReturnUrl(string returnUrl)
{
this.returnUrl = returnUrl;
}
public string GetReturnUrl()
{
return returnUrl;
}
public void SetTerminalType(string terminalType)
{
this.terminalType = terminalType;
}
public string GetTerminalType()
{
return terminalType;
}
public void SetTerminalInfo(string terminalInfo)
{
this.terminalInfo = terminalInfo;
}
public string GetTerminalInfo()
{
return terminalInfo;
}
public void SetProdCode(string prodCode)
{
this.prodCode = prodCode;
}
public string GetProdCode()
{
return prodCode;
}
public string GetApiName()
{
return "zhima.credit.ep.scene.trade.consult";
}
public void SetApiVersion(string apiVersion)
{
this.apiVersion = apiVersion;
}
public string GetApiVersion()
{
return apiVersion;
}
public IDictionary<string, string> GetParameters()
{
var parameters = new AlipayDictionary
{
{ "biz_content", BizContent }
};
return parameters;
}
public AlipayObject GetBizModel()
{
return bizModel;
}
public void SetBizModel(AlipayObject bizModel)
{
this.bizModel = bizModel;
}
#endregion
}
}
| 22.758065 | 111 | 0.548193 | [
"MIT"
] | lzw316/payment | src/Essensoft.AspNetCore.Payment.Alipay/Request/ZhimaCreditEpSceneTradeConsultRequest.cs | 2,836 | C# |
namespace P04.ArrayHistogram
{
using System;
using System.Collections.Generic;
public class ArrayHistogram
{
public static void Main()
{
var input = Console.ReadLine().Split();
var words = new List<string>();
var occurencesCnt = new List<int>();
foreach (var element in input)
{
if (!words.Contains(element))
{
words.Add(element);
occurencesCnt.Add(1);
}
else
{
var index = words.IndexOf(element);
occurencesCnt[index]++;
}
}
var isElementSwapped = false;
do
{
isElementSwapped = false;
for (var index = 0; index < occurencesCnt.Count - 1; index++)
{
if (occurencesCnt[index] < occurencesCnt[index + 1])
{
var temp = occurencesCnt[index];
occurencesCnt[index] = occurencesCnt[index + 1];
occurencesCnt[index + 1] = temp;
var tempWord = words[index];
words[index] = words[index + 1];
words[index + 1] = tempWord;
isElementSwapped = true;
}
}
}
while (isElementSwapped);
var percentage = 100.0 / input.Length;
for (var i = 0; i < words.Count; i++)
{
Console.WriteLine(
$"{words[i]} -> {occurencesCnt[i]} times ({occurencesCnt[i] * percentage:f2}%)");
}
}
}
} | 27.661538 | 101 | 0.412681 | [
"MIT"
] | ViktorAleksandrov/SoftUni--Technology-Fundamentals | Programming Fundamentals - Extended/L07.2. Array and List Algorithms - Exercises/P04.ArrayHistogram/ArrayHistogram.cs | 1,800 | C# |
namespace Biza.CodeAnalysis.Binding
{
public enum BoundNodeKind
{
LiteralExpression,
UnaryExpression,
BinaryExpression,
VariableExpression,
AssignmentExpression
}
}
| 18.166667 | 36 | 0.646789 | [
"MIT"
] | fabianobizarro/Biza | src/Biza/CodeAnalysis/Binding/BoundNodeKind.cs | 220 | C# |
using WitsmlExplorer.Api.Jobs.Common;
namespace WitsmlExplorer.Api.Jobs
{
public record CopyLogDataJob
{
public LogCurvesReference SourceLogCurvesReference { get; init; }
public LogReference TargetLogReference { get; init; }
}
}
| 23.454545 | 73 | 0.72093 | [
"Apache-2.0"
] | AtleH/witsml-explorer | Src/WitsmlExplorer.Api/Jobs/CopyLogDataJob.cs | 258 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace Example
{
static class Program
{
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new frmMain());
}
}
}
| 22.086957 | 65 | 0.610236 | [
"MIT"
] | orthoxerox/Neotoma | Example/Program.cs | 510 | C# |
// -----------------------------------------------------------------------
// <copyright file="Point.cs" company="">
// Triangle.NET code by Christian Woltering, http://triangle.codeplex.com/
// </copyright>
// -----------------------------------------------------------------------
using UnityEngine;
namespace TriangleNet.Geometry
{
using System;
using System.Diagnostics;
/// <summary>
/// Represents a 2D point.
/// </summary>
#if USE_Z
[DebuggerDisplay("ID {ID} [{X}, {Y}, {Z}]")]
#else
[DebuggerDisplay("ID {ID} [{X}, {Y}]")]
#endif
public class Point : IComparable<Point>, IEquatable<Point>
{
internal int id;
internal int label;
internal float x;
internal float y;
#if USE_Z
internal float z;
#endif
public Point()
: this(0.0f, 0.0f, 0)
{
}
public Point(float x, float y)
: this(x, y, 0)
{
}
public Point(float x, float y, int label)
{
this.x = x;
this.y = y;
this.label = label;
}
#region Public properties
/// <summary>
/// Gets or sets the vertex id.
/// </summary>
public int ID
{
get { return this.id; }
set { this.id = value; }
}
/// <summary>
/// Gets or sets the vertex x coordinate.
/// </summary>
public float X
{
get { return this.x; }
set { this.x = value; }
}
/// <summary>
/// Gets or sets the vertex y coordinate.
/// </summary>
public float Y
{
get { return this.y; }
set { this.y = value; }
}
#if USE_Z
/// <summary>
/// Gets or sets the vertex z coordinate.
/// </summary>
public float Z
{
get { return this.z; }
set { this.z = value; }
}
#endif
/// <summary>
/// Gets or sets a general-purpose label.
/// </summary>
/// <remarks>
/// This is used for the vertex boundary mark.
/// </remarks>
public int Label
{
get { return this.label; }
set { this.label = value; }
}
#endregion
#region Operator overloading / overriding Equals
// Compare "Guidelines for Overriding Equals() and Operator =="
// http://msdn.microsoft.com/en-us/library/ms173147.aspx
public static bool operator ==(Point a, Point b)
{
// If both are null, or both are same instance, return true.
if (Object.ReferenceEquals(a, b))
{
return true;
}
// If one is null, but not both, return false.
if (((object)a == null) || ((object)b == null))
{
return false;
}
return a.Equals(b);
}
public static bool operator !=(Point a, Point b)
{
return !(a == b);
}
public override bool Equals(object obj)
{
// If parameter is null return false.
if (obj == null)
{
return false;
}
Point p = obj as Point;
if ((object)p == null)
{
return false;
}
return (x == p.x) && (y == p.y);
}
public bool Equals(Point p)
{
// If vertex is null return false.
if ((object)p == null)
{
return false;
}
// Return true if the fields match:
return (x == p.x) && (y == p.y);
}
#endregion
public int CompareTo(Point other)
{
if (x == other.x && y == other.y)
{
return 0;
}
return (x < other.x || (x == other.x && y < other.y)) ? -1 : 1;
}
public override int GetHashCode()
{
int hash = 19;
hash = hash * 31 + x.GetHashCode();
hash = hash * 31 + y.GetHashCode();
return hash;
}
public static explicit operator Vector2(Point p)
{
return new Vector2(p.x, p.y);
}
public static explicit operator Vector3(Point p)
{
return new Vector3(p.x, p.y);
}
}
}
| 23.390625 | 75 | 0.428412 | [
"Unlicense"
] | bevanator/Triangle.Net-for-Unity | Assets/TriangleNet/Scripts/Source/Geometry/Point.cs | 4,493 | C# |
// Copyright © Tanner Gooding and Contributors. Licensed under the MIT License (MIT). See License.md in the repository root for more information.
// Ported from um/d3d12video.h in the Windows SDK for Windows 10.0.19041.0
// Original source is Copyright © Microsoft. All rights reserved.
using System;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
namespace TerraFX.Interop
{
[Guid("79A2E5FB-CCD2-469A-9FDE-195D10951F7E")]
[NativeTypeName("struct ID3D12VideoDecoder1 : ID3D12VideoDecoder")]
public unsafe partial struct ID3D12VideoDecoder1
{
public void** lpVtbl;
[MethodImpl(MethodImplOptions.AggressiveInlining)]
[return: NativeTypeName("HRESULT")]
public int QueryInterface([NativeTypeName("const IID &")] Guid* riid, [NativeTypeName("void **")] void** ppvObject)
{
return ((delegate* unmanaged<ID3D12VideoDecoder1*, Guid*, void**, int>)(lpVtbl[0]))((ID3D12VideoDecoder1*)Unsafe.AsPointer(ref this), riid, ppvObject);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
[return: NativeTypeName("ULONG")]
public uint AddRef()
{
return ((delegate* unmanaged<ID3D12VideoDecoder1*, uint>)(lpVtbl[1]))((ID3D12VideoDecoder1*)Unsafe.AsPointer(ref this));
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
[return: NativeTypeName("ULONG")]
public uint Release()
{
return ((delegate* unmanaged<ID3D12VideoDecoder1*, uint>)(lpVtbl[2]))((ID3D12VideoDecoder1*)Unsafe.AsPointer(ref this));
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
[return: NativeTypeName("HRESULT")]
public int GetPrivateData([NativeTypeName("const GUID &")] Guid* guid, [NativeTypeName("UINT *")] uint* pDataSize, [NativeTypeName("void *")] void* pData)
{
return ((delegate* unmanaged<ID3D12VideoDecoder1*, Guid*, uint*, void*, int>)(lpVtbl[3]))((ID3D12VideoDecoder1*)Unsafe.AsPointer(ref this), guid, pDataSize, pData);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
[return: NativeTypeName("HRESULT")]
public int SetPrivateData([NativeTypeName("const GUID &")] Guid* guid, [NativeTypeName("UINT")] uint DataSize, [NativeTypeName("const void *")] void* pData)
{
return ((delegate* unmanaged<ID3D12VideoDecoder1*, Guid*, uint, void*, int>)(lpVtbl[4]))((ID3D12VideoDecoder1*)Unsafe.AsPointer(ref this), guid, DataSize, pData);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
[return: NativeTypeName("HRESULT")]
public int SetPrivateDataInterface([NativeTypeName("const GUID &")] Guid* guid, [NativeTypeName("const IUnknown *")] IUnknown* pData)
{
return ((delegate* unmanaged<ID3D12VideoDecoder1*, Guid*, IUnknown*, int>)(lpVtbl[5]))((ID3D12VideoDecoder1*)Unsafe.AsPointer(ref this), guid, pData);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
[return: NativeTypeName("HRESULT")]
public int SetName([NativeTypeName("LPCWSTR")] ushort* Name)
{
return ((delegate* unmanaged<ID3D12VideoDecoder1*, ushort*, int>)(lpVtbl[6]))((ID3D12VideoDecoder1*)Unsafe.AsPointer(ref this), Name);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
[return: NativeTypeName("HRESULT")]
public int GetDevice([NativeTypeName("const IID &")] Guid* riid, [NativeTypeName("void **")] void** ppvDevice)
{
return ((delegate* unmanaged<ID3D12VideoDecoder1*, Guid*, void**, int>)(lpVtbl[7]))((ID3D12VideoDecoder1*)Unsafe.AsPointer(ref this), riid, ppvDevice);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public D3D12_VIDEO_DECODER_DESC GetDesc()
{
D3D12_VIDEO_DECODER_DESC result;
return *((delegate* unmanaged<ID3D12VideoDecoder1*, D3D12_VIDEO_DECODER_DESC*, D3D12_VIDEO_DECODER_DESC*>)(lpVtbl[8]))((ID3D12VideoDecoder1*)Unsafe.AsPointer(ref this), &result);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
[return: NativeTypeName("HRESULT")]
public int GetProtectedResourceSession([NativeTypeName("const IID &")] Guid* riid, [NativeTypeName("void **")] void** ppProtectedSession)
{
return ((delegate* unmanaged<ID3D12VideoDecoder1*, Guid*, void**, int>)(lpVtbl[9]))((ID3D12VideoDecoder1*)Unsafe.AsPointer(ref this), riid, ppProtectedSession);
}
}
}
| 50.820225 | 190 | 0.6761 | [
"MIT"
] | Perksey/terrafx.interop.windows | sources/Interop/Windows/um/d3d12video/ID3D12VideoDecoder1.cs | 4,525 | C# |
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Inventory : MonoBehaviour {
[SerializeField] private FoodType values = 0;
public bool this[FoodType food] {
get {
return (values & food) != 0;
}
private set {
if (value) {
values |= food;
} else {
values &= ~(food);
}
}
}
public void Recieve(FoodType food) {
this[food] = true;
}
}
| 16.384615 | 46 | 0.64554 | [
"MIT"
] | tjbearse/rgift | Assets/scripts/Inventory.cs | 426 | C# |
//------------------------------------------------------------------------------
// <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 SchoolSystem
{
using System;
using System.Collections.Generic;
public partial class FeeHead
{
public FeeHead()
{
this.ChallanToFeeHeads = new HashSet<ChallanToFeeHead>();
this.StudentToFeeHeads = new HashSet<StudentToFeeHead>();
}
public int Id { get; set; }
public Nullable<int> TypeId { get; set; }
public string Description { get; set; }
public Nullable<decimal> Amount { get; set; }
public Nullable<int> Type { get; set; }
public virtual ICollection<ChallanToFeeHead> ChallanToFeeHeads { get; set; }
public virtual ICollection<StudentToFeeHead> StudentToFeeHeads { get; set; }
}
}
| 35 | 84 | 0.554978 | [
"Apache-2.0"
] | JunaidSarfraz/SchoolSystem | SchoolSystem/FeeHead.cs | 1,155 | C# |
using Json.Schema;
using Json.Schema.Generation;
namespace ModDevToolsMod;
/// <summary>
/// Provides intent to create a `dynamicRef` keyword.
/// </summary>
public class DynamicRefIntent : ISchemaKeywordIntent {
public string Reference { get; }
/// <summary>
/// Creates a new instance of the <see cref="DynamicRefIntent"/> class.
/// </summary>
public DynamicRefIntent(string reference)
=> Reference = reference;
/// <summary>
/// Applies the keyword to the <see cref="JsonSchemaBuilder"/>.
/// </summary>
/// <param name="builder">The builder.</param>
public void Apply(JsonSchemaBuilder builder)
=> builder.DynamicRef(Reference);
/// <summary>Determines whether the specified object is equal to the current object.</summary>
/// <param name="obj">The object to compare with the current object.</param>
/// <returns>true if the specified object is equal to the current object; otherwise, false.</returns>
public override bool Equals(object? obj)
=> !ReferenceEquals(null, obj);
/// <summary>Serves as the default hash function.</summary>
/// <returns>A hash code for the current object.</returns>
public override int GetHashCode() {
unchecked {
return typeof(DynamicRefIntent).GetHashCode();
}
}
} | 31.775 | 104 | 0.698662 | [
"MIT"
] | DW2MC/DW2ModLoader | ModDevToolsMod/Json.Schema.Generation/DynamicRefIntent.cs | 1,271 | C# |
using System.Threading;
using Backend.Fx.Environment.Persistence;
using Backend.Fx.Logging;
using Backend.Fx.Patterns.DependencyInjection;
using Backend.Fx.Patterns.EventAggregation.Integration;
using FakeItEasy;
using Xunit;
namespace Backend.Fx.Tests.Patterns.DependencyInjection
{
public class TheBackendFxDbApplication
{
public TheBackendFxDbApplication()
{
IBackendFxApplication application = new BackendFxApplication(_fakes.CompositionRoot, _fakes.MessageBus, A.Fake<IExceptionLogger>());
_sut = new BackendFxDbApplication(_databaseBootstrapper, _databaseAvailabilityAwaiter, application);
}
private readonly DiTestFakes _fakes = new DiTestFakes();
private readonly IBackendFxApplication _sut;
private readonly IDatabaseBootstrapper _databaseBootstrapper = A.Fake<IDatabaseBootstrapper>();
private readonly IDatabaseAvailabilityAwaiter _databaseAvailabilityAwaiter = A.Fake<IDatabaseAvailabilityAwaiter>();
[Fact]
public void CallsDatabaseBootExtensionPointsOnBoot()
{
A.CallTo(() => _databaseAvailabilityAwaiter.WaitForDatabase(A<CancellationToken>._)).MustNotHaveHappened();
A.CallTo(() => _databaseBootstrapper.EnsureDatabaseExistence()).MustNotHaveHappened();
_sut.BootAsync();
A.CallTo(() => _databaseAvailabilityAwaiter.WaitForDatabase(A<CancellationToken>._)).MustHaveHappenedOnceExactly();
A.CallTo(() => _databaseBootstrapper.EnsureDatabaseExistence()).MustHaveHappenedOnceExactly();
}
[Fact]
public void CallsDatabaseBootstrapperDisposeOnDispose()
{
_sut.Dispose();
A.CallTo(() => _databaseBootstrapper.Dispose()).MustHaveHappenedOnceExactly();
}
[Fact]
public void DelegatesAllCalls()
{
var application =A.Fake<IBackendFxApplication>();
var sut = new BackendFxDbApplication(A.Fake<IDatabaseBootstrapper>(),
A.Fake<IDatabaseAvailabilityAwaiter>(),
application);
// ReSharper disable once UnusedVariable
IBackendFxApplicationAsyncInvoker ai = sut.AsyncInvoker;
A.CallTo(() => application.AsyncInvoker).MustHaveHappenedOnceExactly();
// ReSharper disable once UnusedVariable
ICompositionRoot cr = sut.CompositionRoot;
A.CallTo(() => application.CompositionRoot).MustHaveHappenedOnceExactly();
// ReSharper disable once UnusedVariable
IBackendFxApplicationInvoker i = sut.Invoker;
A.CallTo(() => application.Invoker).MustHaveHappenedOnceExactly();
// ReSharper disable once UnusedVariable
IMessageBus mb = sut.MessageBus;
A.CallTo(() => application.MessageBus).MustHaveHappenedOnceExactly();
sut.BootAsync();
A.CallTo(() => application.BootAsync(A<CancellationToken>._)).MustHaveHappenedOnceExactly();
sut.Dispose();
A.CallTo(() => application.Dispose()).MustHaveHappenedOnceExactly();
sut.WaitForBoot();
A.CallTo(() => application.WaitForBoot(A<int>._, A<CancellationToken>._)).MustHaveHappenedOnceExactly();
}
}
} | 43.896104 | 144 | 0.660651 | [
"MIT"
] | marcwittke/Backend.Fx | tests/Backend.Fx.Tests/Patterns/DependencyInjection/TheBackendFxDbApplication.cs | 3,380 | C# |
// <copyright file="Complex32Test.TextHandling.cs" company="Math.NET">
// Math.NET Numerics, part of the Math.NET Project
// http://numerics.mathdotnet.com
// http://github.com/mathnet/mathnet-numerics
//
// Copyright (c) 2009-2016 Math.NET
//
// 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.
// </copyright>
using System;
using System.Globalization;
using NUnit.Framework;
namespace MathNet.Numerics.UnitTests.ComplexTests
{
/// <summary>
/// Complex32 text handling tests.
/// </summary>
[TestFixture]
public class Complex32TextHandlingTest
{
/// <summary>
/// Can format complex to string.
/// </summary>
/// <param name="real">Real part.</param>
/// <param name="imag">Imaginary part.</param>
/// <param name="expected">Expected value.</param>
[TestCase(1, -2, "(1, -2)")]
[TestCase(1, 2, "(1, 2)")]
[TestCase(1, 0, "(1, 0)")]
[TestCase(0, -2, "(0, -2)")]
[TestCase(0, 2, "(0, 2)")]
[TestCase(0, 0, "(0, 0)")]
[TestCase(Single.NaN, Single.NaN, "({1}, {1})")]
[TestCase(Single.NaN, 0, "({1}, 0)")]
[TestCase(0, Single.NaN, "(0, {1})")]
[TestCase(Single.PositiveInfinity, Single.PositiveInfinity, "({2}, {2})")]
[TestCase(1.1f, 0, "(1{0}1, 0)")]
[TestCase(-1.1f, 0, "(-1{0}1, 0)")]
[TestCase(0, 1.1f, "(0, 1{0}1)")]
[TestCase(0, -1.1f, "(0, -1{0}1)")]
[TestCase(1.1f, 1.1f, "(1{0}1, 1{0}1)")]
public void CanFormatComplexToString(float real, float imag, string expected)
{
var numberFormat = NumberFormatInfo.CurrentInfo;
var a = new Complex32(real, imag);
Assert.AreEqual(
String.Format(
expected,
numberFormat.NumberDecimalSeparator,
numberFormat.NaNSymbol,
numberFormat.PositiveInfinitySymbol),
a.ToString());
}
#if !PORTABLE
/// <summary>
/// Can format complex to string with culture.
/// </summary>
/// <param name="cultureName">Culture ID.</param>
/// <param name="number">Complex Number.</param>
[TestCase("en-US", "1.1")]
[TestCase("tr-TR", "1,1")]
[TestCase("de-DE", "1,1")]
//[TestCase("de-CH", "1.1")] Windows 8.1 issue, see http://bit.ly/W81deCH
//[TestCase("he-IL", "1.1")] Mono 4 Issue
public void CanFormatComplexToStringWithCulture(string cultureName, string number)
{
var provider = new CultureInfo(cultureName);
var nan = double.NaN.ToString(provider);
var infinity = double.PositiveInfinity.ToString(provider);
Assert.AreEqual("(" + nan + ", " + nan + ")", Complex32.NaN.ToString(provider));
Assert.AreEqual("(" + infinity + ", " + infinity + ")", Complex32.PositiveInfinity.ToString(provider));
Assert.AreEqual("(0, 0)", Complex32.Zero.ToString(provider));
Assert.AreEqual("(" + String.Format("{0}", number) + ", 0)", new Complex32(1.1f, 0.0f).ToString(provider));
Assert.AreEqual("(" + String.Format("-{0}", number) + ", 0)", new Complex32(-1.1f, 0f).ToString(provider));
Assert.AreEqual("(0, " + String.Format("-{0}", number) + ")", new Complex32(0.0f, -1.1f).ToString(provider));
Assert.AreEqual("(0, " + String.Format("{0}", number) + ")", new Complex32(0.0f, 1.1f).ToString(provider));
Assert.AreEqual("(" + String.Format("{0}", number) + ", " + String.Format("{0}", number) + ")", new Complex32(1.1f, 1.1f).ToString(provider));
}
#endif
/// <summary>
/// Can format complex to string with format.
/// </summary>
[Test]
public void CanFormatComplexToStringWithFormat()
{
Assert.AreEqual("(0, 0)", String.Format("{0:G}", Complex32.Zero));
Assert.AreEqual("(1, 2)", String.Format("{0:G}", new Complex32(1, 2)));
Assert.AreEqual("(001, 002)", String.Format("{0:000;minus 000;zero}", new Complex32(1, 2)));
Assert.AreEqual("(zero, minus 002)", String.Format("{0:000;minus 000;zero}", new Complex32(0, -2)));
Assert.AreEqual("(zero, zero)", String.Format("{0:000;minus 000;zero}", Complex32.Zero));
Assert.AreEqual("(0, 0)", Complex32.Zero.ToString("G"));
Assert.AreEqual("(1, 2)", new Complex32(1, 2).ToString("G"));
Assert.AreEqual("(001, 002)", new Complex32(1, 2).ToString("#000;minus 000;zero"));
Assert.AreEqual("(zero, minus 002)", new Complex32(0, -2).ToString("#000;minus 000;zero"));
Assert.AreEqual("(zero, zero)", Complex32.Zero.ToString("#000;minus 000;zero"));
}
/// <summary>
/// Can format complex to string with format invariant.
/// </summary>
[Test]
public void CanFormatComplexToStringWithFormatInvariant()
{
var culture = CultureInfo.InvariantCulture;
Assert.AreEqual("(NaN, NaN)", String.Format(culture, "{0:.000}", Complex32.NaN));
Assert.AreEqual("(.000, .000)", String.Format(culture, "{0:.000}", Complex32.Zero));
Assert.AreEqual("(1.100, .000)", String.Format(culture, "{0:.000}", new Complex32(1.1f, 0.0f)));
Assert.AreEqual("(1.100, 1.100)", String.Format(culture, "{0:.000}", new Complex32(1.1f, 1.1f)));
Assert.AreEqual("(NaN, NaN)", Complex32.NaN.ToString("#.000", culture));
Assert.AreEqual("(Infinity, Infinity)", Complex32.PositiveInfinity.ToString("#.000", culture));
Assert.AreEqual("(.000, .000)", Complex32.Zero.ToString("#.000", culture));
Assert.AreEqual("(1.100, .000)", new Complex32(1.1f, 0.0f).ToString("#.000", culture));
Assert.AreEqual("(.000, -1.100)", new Complex32(0.0f, -1.1f).ToString("#.000", culture));
Assert.AreEqual("(.000, 1.100)", new Complex32(0.0f, 1.1f).ToString("#.000", culture));
Assert.AreEqual("(1.100, 1.100)", new Complex32(1.1f, 1.1f).ToString("#.000", culture));
}
/// <summary>
/// Can parse string to complex with a culture.
/// </summary>
/// <param name="text">Text to parse.</param>
/// <param name="expectedReal">Expected real part.</param>
/// <param name="expectedImaginary">Expected imaginary part.</param>
/// <param name="cultureName">Culture ID.</param>
[TestCase("-1 -2i", -1, -2, "en-US")]
[TestCase("-1 - 2i ", -1, -2, "de-CH")]
public void CanParseStringToComplexWithCulture(string text, float expectedReal, float expectedImaginary, string cultureName)
{
var parsed = Complex32.Parse(text, new CultureInfo(cultureName));
Assert.AreEqual(expectedReal, parsed.Real);
Assert.AreEqual(expectedImaginary, parsed.Imaginary);
}
/// <summary>
/// Can try parse string to complex with invariant.
/// </summary>
/// <param name="str">String to parse.</param>
/// <param name="expectedReal">Expected real part.</param>
/// <param name="expectedImaginary">Expected imaginary part.</param>
[TestCase("1", 1, 0)]
[TestCase("-1", -1, 0)]
[TestCase("-i", 0, -1)]
[TestCase("i", 0, 1)]
[TestCase("2i", 0, 2)]
[TestCase("1 + 2i", 1, 2)]
[TestCase("1+2i", 1, 2)]
[TestCase("1 - 2i", 1, -2)]
[TestCase("1-2i", 1, -2)]
[TestCase("1,2 ", 1, 2)]
[TestCase("1 , 2", 1, 2)]
[TestCase("1,2i", 1, 2)]
[TestCase("-1, -2i", -1, -2)]
[TestCase(" - 1 , - 2 i ", -1, -2)]
[TestCase("(+1,2i)", 1, 2)]
[TestCase("(-1 , -2)", -1, -2)]
[TestCase("(-1 , -2i)", -1, -2)]
[TestCase("(+1e1 , -2e-2i)", 10, -0.02f)]
[TestCase("(-1E1 -2e2i)", -10, -200)]
[TestCase("(-1e+1 -2e2i)", -10, -200)]
[TestCase("(-1e1 -2e+2i)", -10, -200)]
[TestCase("(-1e-1 -2E2i)", -0.1f, -200)]
[TestCase("(-1e1 -2e-2i)", -10, -0.02f)]
[TestCase("(-1E+1 -2e+2i)", -10, -200)]
[TestCase("(-1e-1,-2e-2i)", -0.1f, -0.02f)]
[TestCase("(+1 +2i)", 1, 2)]
[TestCase("(-1E+1 -2e+2i)", -10, -200)]
[TestCase("(-1e-1,-2e-2i)", -0.1f, -0.02f)]
public void CanTryParseStringToComplexWithInvariant(string str, float expectedReal, float expectedImaginary)
{
var invariantCulture = CultureInfo.InvariantCulture;
Complex32 z;
var ret = Complex32.TryParse(str, invariantCulture, out z);
Assert.IsTrue(ret);
Assert.AreEqual(expectedReal, z.Real);
Assert.AreEqual(expectedImaginary, z.Imaginary);
}
/// <summary>
/// If missing closing paren parse throws <c>FormatException</c>.
/// </summary>
[Test]
public void IfMissingClosingParenParseThrowsFormatException()
{
Assert.That(() => Complex32.Parse("(1,2"), Throws.TypeOf<FormatException>());
}
/// <summary>
/// Try parse can handle symbols.
/// </summary>
[Test]
public void TryParseCanHandleSymbols()
{
Complex32 z;
var ni = NumberFormatInfo.CurrentInfo;
var separator = CultureInfo.CurrentCulture.TextInfo.ListSeparator;
var ret = Complex32.TryParse(
ni.NegativeInfinitySymbol + separator + ni.PositiveInfinitySymbol, out z);
Assert.IsTrue(ret, "A1");
Assert.AreEqual(float.NegativeInfinity, z.Real, "A2");
Assert.AreEqual(float.PositiveInfinity, z.Imaginary, "A3");
ret = Complex32.TryParse(ni.NaNSymbol + separator + ni.NaNSymbol, out z);
Assert.IsTrue(ret, "B1");
Assert.AreEqual(float.NaN, z.Real, "B2");
Assert.AreEqual(float.NaN, z.Imaginary, "B3");
ret = Complex32.TryParse(ni.NegativeInfinitySymbol + "+" + ni.PositiveInfinitySymbol + "i", out z);
Assert.IsTrue(ret, "C1");
Assert.AreEqual(float.NegativeInfinity, z.Real, "C2");
Assert.AreEqual(float.PositiveInfinity, z.Imaginary, "C3");
ret = Complex32.TryParse(ni.NaNSymbol + "+" + ni.NaNSymbol + "i", out z);
Assert.IsTrue(ret, "D1");
Assert.AreEqual(float.NaN, z.Real, "D2");
Assert.AreEqual(float.NaN, z.Imaginary, "D3");
ret = Complex32.TryParse(
float.MaxValue.ToString("R") + " " + float.MinValue.ToString("R") + "i",
out z);
Assert.IsTrue(ret, "E1");
Assert.AreEqual(float.MaxValue, z.Real, "E2");
Assert.AreEqual(float.MinValue, z.Imaginary, "E3");
}
#if !PORTABLE
/// <summary>
/// Try parse can handle symbols with a culture.
/// </summary>
/// <param name="cultureName">Culture ID.</param>
[TestCase("en-US")]
[TestCase("tr-TR")]
[TestCase("de-DE")]
[TestCase("de-CH")]
//[TestCase("he-IL")] Mono 4 Issue
public void TryParseCanHandleSymbolsWithCulture(string cultureName)
{
Complex32 z;
var culture = new CultureInfo(cultureName);
var ni = culture.NumberFormat;
var separator = culture.TextInfo.ListSeparator;
var ret = Complex32.TryParse(
ni.NegativeInfinitySymbol + separator + ni.PositiveInfinitySymbol, culture, out z);
Assert.IsTrue(ret, "A1");
Assert.AreEqual(float.NegativeInfinity, z.Real, "A2");
Assert.AreEqual(float.PositiveInfinity, z.Imaginary, "A3");
ret = Complex32.TryParse(ni.NaNSymbol + separator + ni.NaNSymbol, culture, out z);
Assert.IsTrue(ret, "B1");
Assert.AreEqual(float.NaN, z.Real, "B2");
Assert.AreEqual(float.NaN, z.Imaginary, "B3");
ret = Complex32.TryParse(ni.NegativeInfinitySymbol + "+" + ni.PositiveInfinitySymbol + "i", culture, out z);
Assert.IsTrue(ret, "C1");
Assert.AreEqual(float.NegativeInfinity, z.Real, "C2");
Assert.AreEqual(float.PositiveInfinity, z.Imaginary, "C3");
ret = Complex32.TryParse(ni.NaNSymbol + "+" + ni.NaNSymbol + "i", culture, out z);
Assert.IsTrue(ret, "D1");
Assert.AreEqual(float.NaN, z.Real, "D2");
Assert.AreEqual(float.NaN, z.Imaginary, "D3");
ret = Complex32.TryParse(
float.MaxValue.ToString("R", culture) + " " + float.MinValue.ToString("R", culture) + "i",
culture,
out z);
Assert.IsTrue(ret, "E1");
Assert.AreEqual(float.MaxValue, z.Real, "E2");
Assert.AreEqual(float.MinValue, z.Imaginary, "E3");
}
#endif
/// <summary>
/// Try parse returns false when given bad value with invariant.
/// </summary>
/// <param name="str">String to parse.</param>
[TestCase("")]
[TestCase("+")]
[TestCase("1-")]
[TestCase("i+")]
[TestCase("1/2i")]
[TestCase("1i+2i")]
[TestCase("i1i")]
[TestCase("(1i,2)")]
[TestCase("1e+")]
[TestCase("1e")]
[TestCase("1,")]
[TestCase(",1")]
[TestCase(null)]
[TestCase("()")]
[TestCase("( )")]
public void TryParseReturnsFalseWhenGivenBadValueWithInvariant(string str)
{
Complex32 z;
var ret = Complex32.TryParse(str, CultureInfo.InvariantCulture, out z);
Assert.IsFalse(ret);
Assert.AreEqual(0, z.Real);
Assert.AreEqual(0, z.Imaginary);
}
}
}
| 45.304878 | 154 | 0.56393 | [
"MIT"
] | PGsHub/mathnet-numerics | src/UnitTests/ComplexTests/Complex32Test.TextHandling.cs | 14,860 | C# |
namespace MathLibrary
{
public class Calculator
{
public int Sum(int left, int right)
{
return left + right;
}
}
}
| 14.909091 | 43 | 0.506098 | [
"MIT"
] | JanneMattila/nuget-package-demo | src/MathLibrary/Calculator.cs | 166 | C# |
using System;
using System.Diagnostics.CodeAnalysis;
using System.Net.Http;
using LovePdf.Core;
using LovePdf.Model.Task;
using LovePdf.Model.TaskParams;
namespace Samples
{
[SuppressMessage("ReSharper", "UnusedVariable")]
public class TryCatchErrors
{
public void DoTask()
{
try
{
var api = new LovePdfApi("PUBLIC_KEY", "SECRET_KEY");
//create split task
var task = api.CreateTask<SplitTask>();
//file variable contains server file name
var file = task.AddFile("path/to/file/document.pdf");
//proces added files
//time var will contains information about time spent in process
var time = task.Process(new SplitParams(new SplitModeFixedRanges(3)));
task.DownloadFile("path");
}
catch (HttpRequestException ex)
{
var message = ex.Message;
if (ex.InnerException != null)
{
var innerException = ex.InnerException.Message;
}
}
catch (Exception ex)
{
var message = ex.Message;
if (ex.InnerException != null)
{
var innerException = ex.InnerException.Message;
}
}
}
}
} | 29.729167 | 86 | 0.512263 | [
"MIT"
] | ilovepdf/ilovepdf-net | ILovePDF/Samples/TryCatchErrors.cs | 1,429 | C# |
namespace Joke.Joke.Tree
{
public interface INamedType : INamedMember, IVisited
{
}
}
| 15 | 57 | 0.628571 | [
"MIT"
] | knutjelitto/Joke | Joke.Joke/Tree/INamedType.cs | 107 | 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 Mastersign.Bench.Dashboard
{
internal partial class AppInfoDialog : Form
{
private static readonly string[] KnownProperties = new[]
{
PropertyKeys.AppTyp,
PropertyKeys.AppWebsite,
PropertyKeys.AppVersion,
PropertyKeys.AppDependencies,
PropertyKeys.AppForce,
PropertyKeys.AppSetupTestFile,
PropertyKeys.AppPackageName,
PropertyKeys.AppUrl,
PropertyKeys.AppDownloadCookies,
PropertyKeys.AppDownloadHeaders,
PropertyKeys.AppResourceName,
PropertyKeys.AppArchiveName,
PropertyKeys.AppArchiveTyp,
PropertyKeys.AppArchivePath,
PropertyKeys.AppDir,
PropertyKeys.AppExe,
PropertyKeys.AppRegister,
PropertyKeys.AppPath,
PropertyKeys.AppEnvironment,
PropertyKeys.AppAdornedExecutables,
PropertyKeys.AppRegistryKeys,
PropertyKeys.AppLauncher,
PropertyKeys.AppLauncherExecutable,
PropertyKeys.AppLauncherArguments,
PropertyKeys.AppLauncherIcon,
};
public AppInfoDialog(BenchConfiguration config, AppFacade app)
{
InitializeComponent();
gridResolved.DoubleBuffered(true);
lblAppId.Text = app.ID;
LoadProperties(config, app);
}
private void LoadProperties(BenchConfiguration config, AppFacade app)
{
gridResolved.Rows.Clear();
AddRow(gridResolved, PropertyKeys.AppTyp, app.Typ);
AddRow(gridResolved, PropertyKeys.AppWebsite, app.Website);
AddRow(gridResolved, PropertyKeys.AppVersion, app.Version);
AddRow(gridResolved, PropertyKeys.AppDependencies, app.Dependencies);
AddRow(gridResolved, PropertyKeys.AppForce, app.Force);
AddRow(gridResolved, PropertyKeys.AppSetupTestFile, app.SetupTestFile);
AddRow(gridResolved, PropertyKeys.AppPackageName, app.PackageName);
AddRow(gridResolved, PropertyKeys.AppUrl, app.Url);
AddRow(gridResolved, PropertyKeys.AppDownloadCookies, app.DownloadCookies);
AddRow(gridResolved, PropertyKeys.AppDownloadHeaders, app.DownloadHeaders);
AddRow(gridResolved, PropertyKeys.AppResourceName, app.ResourceFileName);
AddRow(gridResolved, PropertyKeys.AppArchiveName, app.ResourceArchiveName);
AddRow(gridResolved, PropertyKeys.AppArchivePath, app.ResourceArchivePath);
AddRow(gridResolved, PropertyKeys.AppDir, app.Dir);
AddRow(gridResolved, PropertyKeys.AppExe, app.Exe);
AddRow(gridResolved, PropertyKeys.AppRegister, app.Register);
AddRow(gridResolved, PropertyKeys.AppPath, app.Path);
AddRow(gridResolved, PropertyKeys.AppEnvironment, app.Environment);
AddRow(gridResolved, PropertyKeys.AppAdornedExecutables, app.AdornedExecutables);
AddRow(gridResolved, PropertyKeys.AppRegistryKeys, app.RegistryKeys);
AddRow(gridResolved, PropertyKeys.AppLauncher, app.Launcher);
AddRow(gridResolved, PropertyKeys.AppLauncherExecutable, app.LauncherExecutable);
AddRow(gridResolved, PropertyKeys.AppLauncherArguments, app.LauncherArguments);
AddRow(gridResolved, PropertyKeys.AppLauncherIcon, app.LauncherIcon);
foreach(var key in config.PropertyNames(app.ID))
{
if (!KnownProperties.Contains(key))
{
AddRow(gridResolved, key, config.GetGroupValue(app.ID, key));
}
}
gridRaw.Rows.Clear();
foreach(var key in config.PropertyNames(app.ID))
{
AddRow(gridRaw, key, config.GetRawGroupValue(app.ID, key));
}
}
private void AddRow(DataGridView grid, string name, object value)
{
if (value is bool)
{
AddRow(grid, name, value.ToString());
}
else if (value is string)
{
AddRow(grid, name, (string)value);
}
else if (value is string[])
{
AddRow(grid, name, string.Join(", ",
((string[])value).Select(v => string.Format("`{0}`", v))));
}
else if (value is IDictionary<string, string>)
{
AddRow(grid, name, string.Join(", ",
((IDictionary<string, string>)value).Select(kvp => string.Format("`{0}`=`{1}`", kvp.Key, kvp.Value))));
}
else if (value == null)
{
AddRow(grid, name, null);
}
else
{
AddRow(grid, name, "UNKNOWN: " + value.ToString());
}
}
private void AddRow(DataGridView grid, string name, string value)
{
grid.Rows.Add(name, value);
}
}
}
| 41.476923 | 123 | 0.593843 | [
"MIT"
] | mastersign/bench-manager | BenchDashboard/AppInfoDialog.cs | 5,394 | C# |
// MIT License
//
// Copyright (c) 2017 Granikos GmbH & Co. KG (https://www.granikos.eu)
//
// 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.Web.Mvc;
namespace Granikos.SMTPSimulator.WebClient.Controllers
{
public class HomeController : Controller
{
public ActionResult Index()
{
return View();
}
}
} | 43.090909 | 82 | 0.716596 | [
"MIT"
] | Granikos/SMTPSimulator | Granikos.SMTPSimulator.WebClient/Controllers/HomeController.cs | 1,424 | C# |
using System.Reflection;
using System.Resources;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Windows;
// 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("Configuration Setup Utility")]
[assembly: AssemblyDescription("Setup and Configuration Utility for openPDC")]
[assembly: AssemblyCompany("Grid Protection Alliance")]
[assembly: AssemblyProduct("openPDC")]
[assembly: AssemblyCopyright("Copyright © 2020, Grid Protection Alliance. All Rights Reserved.")]
#if DEBUG
[assembly: AssemblyConfiguration("Debug Build")]
#else
[assembly: AssemblyConfiguration("Release Build")]
#endif
// 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)]
//In order to begin building localizable applications, set
//<UICulture>CultureYouAreCodingWith</UICulture> in your .csproj file
//inside a <PropertyGroup>. For example, if you are using US english
//in your source files, set the <UICulture> to en-US. Then uncomment
//the NeutralResourceLanguage attribute below. Update the "en-US" in
//the line below to match the UICulture setting in the project file.
//[assembly: NeutralResourcesLanguage("en-US", UltimateResourceFallbackLocation.Satellite)]
[assembly: ThemeInfo(
ResourceDictionaryLocation.None, //where theme specific resource dictionaries are located
//(used if a resource is not found in the page,
// or application resource dictionaries)
ResourceDictionaryLocation.SourceAssembly //where the generic resource dictionary is located
//(used if a resource is not found in the page,
// app, or any theme specific resource dictionaries)
)]
// 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("2.9.136.0")]
[assembly: AssemblyVersion("2.9.136.0")]
[assembly: AssemblyFileVersion("2.9.136.0")]
| 39.733333 | 98 | 0.762164 | [
"MIT"
] | joyshmitz/openPDC | Source/Tools/ConfigurationSetupUtility/Properties/AssemblyInfo.cs | 2,387 | 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.ComponentModel;
using System.ComponentModel.Design;
using System.Diagnostics;
namespace System.Windows.Forms.Design
{
internal class ContextMenuStripActionList : DesignerActionList
{
private readonly ToolStripDropDown _toolStripDropDown;
private bool _autoShow = false;
public ContextMenuStripActionList(ToolStripDropDownDesigner designer) : base(designer.Component)
{
_toolStripDropDown = (ToolStripDropDown)designer.Component;
}
//helper function to get the property on the actual Control
private object GetProperty(string propertyName)
{
PropertyDescriptor getProperty = TypeDescriptor.GetProperties(_toolStripDropDown)[propertyName];
Debug.Assert(getProperty != null, "Could not find given property in control.");
if (getProperty != null)
{
return getProperty.GetValue(_toolStripDropDown);
}
return null;
}
//helper function to change the property on the actual Control
private void ChangeProperty(string propertyName, object value)
{
PropertyDescriptor changingProperty = TypeDescriptor.GetProperties(_toolStripDropDown)[propertyName];
Debug.Assert(changingProperty != null, "Could not find given property in control.");
if (changingProperty != null)
{
changingProperty.SetValue(_toolStripDropDown, value);
}
}
/// <summary>
/// Controls whether the Chrome is Automatically shown on selection
/// </summary>
public override bool AutoShow
{
get => _autoShow;
set
{
if (_autoShow != value)
{
_autoShow = value;
}
}
}
public bool ShowImageMargin
{
get => (bool)GetProperty("ShowImageMargin");
set
{
if (value != ShowImageMargin)
{
ChangeProperty("ShowImageMargin", (object)value);
}
}
}
public bool ShowCheckMargin
{
get => (bool)GetProperty("ShowCheckMargin");
set
{
if (value != ShowCheckMargin)
{
ChangeProperty("ShowCheckMargin", (object)value);
}
}
}
public ToolStripRenderMode RenderMode
{
get => (ToolStripRenderMode)GetProperty("RenderMode");
set
{
if (value != RenderMode)
{
ChangeProperty("RenderMode", (object)value);
}
}
}
/// <summary>
/// The Main method to group the ActionItems and pass it to the Panel.
/// </summary>
public override DesignerActionItemCollection GetSortedActionItems()
{
DesignerActionItemCollection items = new DesignerActionItemCollection();
items.Add(new DesignerActionPropertyItem("RenderMode", SR.ToolStripActionList_RenderMode, SR.ToolStripActionList_Layout, SR.ToolStripActionList_RenderModeDesc));
if (_toolStripDropDown is ToolStripDropDownMenu)
{
items.Add(new DesignerActionPropertyItem("ShowImageMargin", SR.ContextMenuStripActionList_ShowImageMargin, SR.ToolStripActionList_Layout, SR.ContextMenuStripActionList_ShowImageMarginDesc));
items.Add(new DesignerActionPropertyItem("ShowCheckMargin", SR.ContextMenuStripActionList_ShowCheckMargin, SR.ToolStripActionList_Layout, SR.ContextMenuStripActionList_ShowCheckMarginDesc));
}
return items;
}
}
}
| 36.54955 | 206 | 0.597979 | [
"MIT"
] | ASHCO-2019/winforms | src/System.Windows.Forms.Design/src/System/Windows/Forms/Design/ContextMenuStripActionList.cs | 4,059 | C# |
using Microsoft.AspNetCore.Components;
namespace SmallsOnline.Blazor.Components.ListGroups
{
public partial class SimpleListGroupItem : BootstrapComponent
{
protected override void OnParametersSet()
{
AddClassNamesToClassList();
}
}
} | 23.666667 | 65 | 0.690141 | [
"MIT"
] | Smalls1652/SmallsOnline.Blazor.Components | src/SmallsOnline.Blazor.Components/components/list-groups/SimpleListGroupItem.razor.cs | 286 | C# |
using SQLite;
using System;
using System.Collections.Generic;
using System.Linq.Expressions;
using System.Threading.Tasks;
using ToDoListApp.Core.Repositories;
namespace ToDoListApp.Persistence.Repositories
{
public class DataBaseRepository<TEntity> : IDataBaseRepository<TEntity> where TEntity : class, new()
{
protected readonly TareasDatabase Context;
private readonly AsyncTableQuery<TEntity> _entities;
public DataBaseRepository(TareasDatabase context)
{
Context = context;
Context.CreateTableAsync<TEntity>().Wait();
_entities = Context.Table<TEntity>();
}
public async Task<TEntity> Get(int id) => await Context.FindAsync<TEntity>(id);
public async Task<List<TEntity>> GetAll() => await _entities.ToListAsync();
public async Task<List<TEntity>> Find(Expression<Func<TEntity, bool>> predicate) =>
await _entities.Where(predicate).ToListAsync();
public async Task<TEntity> SingleOrDefault(Expression<Func<TEntity, bool>> predicate) =>
await _entities.Where(predicate).FirstOrDefaultAsync();
public async Task<int> Add(TEntity entity) => await Context.InsertAsync(entity);
public async Task<int> AddRange(IEnumerable<TEntity> entities)
{
var count = 0;
await Context.RunInTransactionAsync(connection =>
{
count += connection.InsertAll(entities);
});
return count;
}
public async Task<int> Remove(TEntity entity) => await Context.DeleteAsync(entity);
public async Task<int> RemoveRange()
{
var count = 0;
await Context.RunInTransactionAsync(connection =>
{
count += connection.DeleteAll<TEntity>();
});
return count;
}
}
}
| 32.724138 | 104 | 0.632771 | [
"MIT"
] | zelote57/ToDoListXamarinForms | ListaPorHacer/ToDoListApp/ToDoListApp/Persistence/Repositories/DataBaseRepository.cs | 1,900 | 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.Blueprint
{
public static class GetBlueprint
{
/// <summary>
/// Represents a Blueprint definition.
/// API Version: 2018-11-01-preview.
/// </summary>
public static Task<GetBlueprintResult> InvokeAsync(GetBlueprintArgs args, InvokeOptions? options = null)
=> Pulumi.Deployment.Instance.InvokeAsync<GetBlueprintResult>("azure-nextgen:blueprint:getBlueprint", args ?? new GetBlueprintArgs(), options.WithVersion());
}
public sealed class GetBlueprintArgs : Pulumi.InvokeArgs
{
/// <summary>
/// Name of the blueprint definition.
/// </summary>
[Input("blueprintName", required: true)]
public string BlueprintName { get; set; } = null!;
/// <summary>
/// The scope of the resource. Valid scopes are: management group (format: '/providers/Microsoft.Management/managementGroups/{managementGroup}'), subscription (format: '/subscriptions/{subscriptionId}').
/// </summary>
[Input("resourceScope", required: true)]
public string ResourceScope { get; set; } = null!;
public GetBlueprintArgs()
{
}
}
[OutputType]
public sealed class GetBlueprintResult
{
/// <summary>
/// Multi-line explain this resource.
/// </summary>
public readonly string? Description;
/// <summary>
/// One-liner string explain this resource.
/// </summary>
public readonly string? DisplayName;
/// <summary>
/// String Id used to locate any resource on Azure.
/// </summary>
public readonly string Id;
/// <summary>
/// Layout view of the blueprint definition for UI reference.
/// </summary>
public readonly object? Layout;
/// <summary>
/// Name of this resource.
/// </summary>
public readonly string Name;
/// <summary>
/// Parameters required by this blueprint definition.
/// </summary>
public readonly ImmutableDictionary<string, Outputs.ParameterDefinitionResponse>? Parameters;
/// <summary>
/// Resource group placeholders defined by this blueprint definition.
/// </summary>
public readonly ImmutableDictionary<string, Outputs.ResourceGroupDefinitionResponse>? ResourceGroups;
/// <summary>
/// Status of the blueprint. This field is readonly.
/// </summary>
public readonly Outputs.BlueprintStatusResponse Status;
/// <summary>
/// The scope where this blueprint definition can be assigned.
/// </summary>
public readonly string TargetScope;
/// <summary>
/// Type of this resource.
/// </summary>
public readonly string Type;
/// <summary>
/// Published versions of this blueprint definition.
/// </summary>
public readonly object? Versions;
[OutputConstructor]
private GetBlueprintResult(
string? description,
string? displayName,
string id,
object? layout,
string name,
ImmutableDictionary<string, Outputs.ParameterDefinitionResponse>? parameters,
ImmutableDictionary<string, Outputs.ResourceGroupDefinitionResponse>? resourceGroups,
Outputs.BlueprintStatusResponse status,
string targetScope,
string type,
object? versions)
{
Description = description;
DisplayName = displayName;
Id = id;
Layout = layout;
Name = name;
Parameters = parameters;
ResourceGroups = resourceGroups;
Status = status;
TargetScope = targetScope;
Type = type;
Versions = versions;
}
}
}
| 32.813953 | 211 | 0.601937 | [
"Apache-2.0"
] | pulumi/pulumi-azure-nextgen | sdk/dotnet/Blueprint/GetBlueprint.cs | 4,233 | C# |
using FluentApiEFCoreExample.Entities;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Metadata.Builders;
namespace FluentApiEFCoreExample.EntityConfigurations
{
public class ArticleConfig : EntityConfiguration<Article>, IEntityTypeConfiguration<Article>, IEntityConfig
{
public void Configure(EntityTypeBuilder<Article> builder)
{
// Com este método, já configuramos as propriedades comuns,
// bem como nome da tabela e a chave primária
DefaultConfigs(builder, tableName: "ARTICLES");
// Crio um index na propriedade de título e marco como único,
// ou seja, eu garato que jamais havará 2 ou mais títulos iguais
// em nossa base
builder.HasIndex(x => x.Title).IsUnique();
builder.Property(x => x.Title) // Pego a propriedade de título
.HasMaxLength(120) // Informo que o título poderá ter no máximo 50 caracters
.IsRequired(); // Informo que o título é obrigatório em nossa base
builder.Property(x => x.Body) // Pego a propriedade de corpo do artigo
.IsRequired(); // Informo que o corpo do artigo é obrigatório
}
}
}
| 44.034483 | 111 | 0.643696 | [
"Apache-2.0"
] | manacespereira/FluentApiEFCoreExample | EntityConfigurations/ArticleConfig.cs | 1,295 | C# |
using Dapper;
using Inshapardaz.Domain.Adapters.Repositories.Library;
using Inshapardaz.Domain.Models;
using Inshapardaz.Domain.Models.Library;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
namespace Inshapardaz.Database.SqlServer.Repositories.Library
{
public class ArticleRepository : IArticleRepository
{
private readonly IProvideConnection _connectionProvider;
public ArticleRepository(IProvideConnection connectionProvider)
{
_connectionProvider = connectionProvider;
}
public async Task<ArticleModel> AddArticle(int libraryId, int peridicalId, int issueId, ArticleModel article, CancellationToken cancellationToken)
{
int id;
using (var connection = _connectionProvider.GetConnection())
{
var sql = @"INSERT INTO Article (Title, IssueId, AuthorId, SequenceNumber, SeriesName, SeriesIndex)
OUTPUT Inserted.Id VALUES (@Title, @IssueId, @AuthorId, @SequenceNumber, @SeriesName, @SeriesIndex)";
var command = new CommandDefinition(sql, new
{
Title = article.Title,
IssueId = issueId,
AuthorId = article.AuthorId,
SequenceNumber = article.SequenceNumber,
SeriesName = article.SeriesName,
SeriesIndex = article.SeriesIndex
}, cancellationToken: cancellationToken);
id = await connection.ExecuteScalarAsync<int>(command);
}
return await GetArticleById(libraryId, peridicalId, issueId, id, cancellationToken);
}
public async Task UpdateArticle(int libraryId, int periodicalId, int volumeNumber, int issueNumber, ArticleModel article, CancellationToken cancellationToken)
{
using (var connection = _connectionProvider.GetConnection())
{
var sql = @"UPDATE a SET a.Title = @Title, a.AuthorId = @AuthorId, a.SequenceNumber = @SequenceNumber
a.SeriesName = @SeriesName, a.SeriesIndex = @SeriesIndex
FROM Article a
INNER JOIN Issue i ON i.Id = a.IssueId
WHERE a.Id = @ArticleId
AND i.VolumeNumber = @VolumeNumber
AND i.IssueNumber = @IssueNumber
AND i.PeriodicalId = @PeriodicalId";
var args = new
{
LibraryId = libraryId,
PeriodicalId = periodicalId,
VolumeNumber = volumeNumber,
IssueNumber = issueNumber,
ArticleId = article.Id,
Title = article.Title,
AuthorId = article.AuthorId,
SequenceNumber = article.SequenceNumber,
SeriesName = article.SeriesName,
SeriesIndex = article.SeriesIndex
};
var command = new CommandDefinition(sql, args, cancellationToken: cancellationToken);
await connection.ExecuteAsync(command);
}
}
public async Task DeleteArticle(int libraryId, int periodicalId, int volumeNumber, int issueNumber, int articleId, CancellationToken cancellationToken)
{
using (var connection = _connectionProvider.GetConnection())
{
var sql = @"DELETE a
FROM Article a
INNER JOIN Issue i ON i.Id = a.IssueId
WHERE a.Id = @ArticleId
AND i.PeriodicalId = @PeriodicalId
AND i.VolumeNumber = @VolumeNumber
AND i.IssueNumber = @IssueNumber";
var command = new CommandDefinition(sql, new
{
PeriodicalId = periodicalId,
VolumeNumber = volumeNumber,
IssueNumber = issueNumber,
ArticleId = articleId
}, cancellationToken: cancellationToken);
await connection.ExecuteAsync(command);
}
}
public async Task<ArticleModel> GetArticleById(int libraryId, int periodicalId, int volumeNumber, int issueNumber, int articleId, CancellationToken cancellationToken)
{
using (var connection = _connectionProvider.GetConnection())
{
ArticleModel article = null;
var sql = @"SELECT a.*, ac.*, f.*
FROM Article a
INNER JOIN Issue i ON i.Id = a.IssueId
LEFT OUTER JOIN ArticleContent ac ON a.Id = ac.ArticleId
LEFT OUTER JOIN [File] f ON f.Id = cc.FileId
WHERE a.Id = @ArticleId
AND i.PeriodicalId = @PeriodicalId
AND i.VolumeNumber = @VolumeNumber
AND i.IssueNumber = @IssueNumber";
var command = new CommandDefinition(sql, new {
PeriodicalId = periodicalId,
VolumeNumber = volumeNumber,
IssueNumber = issueNumber,
ArticleId = articleId
}, cancellationToken: cancellationToken);
await connection.QueryAsync<ArticleModel, ArticleContentModel, FileModel, ArticleModel>(command, (a, ac, f) =>
{
if (article == null)
{
article = a;
}
if (ac != null)
{
var content = article.Contents.SingleOrDefault(x => x.Id == ac.Id);
if (content == null)
{
article.Contents.Add(ac);
}
}
if (f != null)
{
var content = article.Contents.SingleOrDefault(x => x.Id == ac.Id);
if (content != null)
{
content.MimeType = f.MimeType;
content.ContentUrl = f.FilePath;
}
}
return article;
});
return article;
}
}
public async Task<ArticleContentModel> GetArticleContentById(int libraryId, int periodicalId, int volumeNumber, int issueNumber, int articleId, string language, string mimeType, CancellationToken cancellationToken)
{
using (var connection = _connectionProvider.GetConnection())
{
ArticleModel article = null;
var sql = @"SELECT a.*, ac.*, f.*
FROM Article a
INNER JOIN Issue i ON i.Id = a.IssueId
LEFT OUTER JOIN ArticleContent ac ON a.Id = ac.ArticleId
LEFT OUTER JOIN [File] f ON f.Id = cc.FileId
WHERE a.Id = @ArticleId
AND i.PeriodicalId = @PeriodicalId
AND i.VolumeNumber = @VolumeNumber
AND i.IssueNumber = @IssueNumber
AND a.MimeType = @MimeType
AND a.Language = @Language";
var command = new CommandDefinition(sql, new {
PeriodicalId = periodicalId,
VolumeNumber = volumeNumber,
IssueNumber = issueNumber,
ArticleId = articleId,
MimeType = mimeType,
Language = language }, cancellationToken: cancellationToken);
await connection.QueryAsync<ArticleModel, ArticleContentModel, FileModel, ArticleModel>(command, (a, ac, f) =>
{
if (article == null)
{
article = a;
}
if (ac != null)
{
var content = article.Contents.SingleOrDefault(x => x.Id == ac.Id);
if (content == null)
{
article.Contents.Add(ac);
}
}
if (f != null)
{
var content = article.Contents.SingleOrDefault(x => x.Id == ac.Id);
if (content != null)
{
content.MimeType = f.MimeType;
content.ContentUrl = f.FilePath;
}
}
return article;
});
return null;
}
}
public async Task<IEnumerable<ArticleModel>> GetArticlesByIssue(int libraryId, int periodicalId, int volumeNumber, int issueNumber, CancellationToken cancellationToken)
{
using (var connection = _connectionProvider.GetConnection())
{
var articles = new Dictionary<int, ArticleModel>();
var sql = @"SELECT a.*, at.*
FROM Article a
INNER JOIN Issue i ON i.Id = a.IssueId
LEFT OUTER JOIN ArticleText at ON a.Id = at.ArticleId
WHERE i.PeriodicalId = @PeriodicalId
AND i.VolumeNumber = @VolumeNumber
AND i.IssueNumber = @IssueNumber";
var command = new CommandDefinition(sql, new {
PeriodicalId = periodicalId,
VolumeNumber = volumeNumber,
IssueNumber = issueNumber,
}, cancellationToken: cancellationToken);
await connection.QueryAsync<ArticleModel, ArticleContentModel, ArticleModel>(command, (a, at) =>
{
if (!articles.TryGetValue(a.Id, out ArticleModel article))
{
articles.Add(a.Id, article = a);
}
article = articles[a.Id];
if (at != null)
{
at.IssueId = a.Id;
var content = article.Contents.SingleOrDefault(x => x.Id == at.Id);
if (content == null)
{
article.Contents.Add(at);
}
}
return article;
});
return articles.Values;
}
}
public Task<ArticleContentModel> GetArticleContent(int libraryId, int periodicalId, int volumeNumber, int issueNumber, int articleId, string language, string mimeType, CancellationToken cancellationToken)
{
throw new NotImplementedException();
}
public Task<IEnumerable<ArticleContentModel>> GetArticleContents(int libraryId, int periodicalId, int volumeNumber, int issueNumber, int articleId, CancellationToken cancellationToken)
{
throw new NotImplementedException();
}
public Task<string> GetArticleContentUrl(int libraryId, int periodicalId, int volumeNumber, int issueNumber, int articleId, string language, string mimeType, CancellationToken cancellationToken)
{
throw new NotImplementedException();
}
public Task<ArticleContentModel> AddArticleContent(int libraryId, ArticleContentModel issueContent, CancellationToken cancellationToken)
{
throw new NotImplementedException();
}
public Task DeleteArticleContentById(int libraryId, int periodicalId, int volumeNumber, int issueNumber, int articleId, CancellationToken cancellationToken)
{
throw new NotImplementedException();
}
private async Task<ArticleModel> GetArticleById(int libraryId, int periodicalId, int issueId, int articleId, CancellationToken cancellationToken)
{
using (var connection = _connectionProvider.GetConnection())
{
ArticleModel article = null;
var sql = @"SELECT a.*, ac.*, f.*
FROM Article a
INNER JOIN Issue i ON i.Id = a.IssueId
LEFT OUTER JOIN ArticleContent ac ON a.Id = ac.ArticleId
LEFT OUTER JOIN [File] f ON f.Id = cc.FileId
WHERE a.Id = @ArticleId
AND i.PeriodicalId = @PeriodicalId
AND i.Id = @IssueId";
var command = new CommandDefinition(sql, new
{
PeriodicalId = periodicalId,
IssueId = issueId,
ArticleId = articleId
}, cancellationToken: cancellationToken);
await connection.QueryAsync<ArticleModel, ArticleContentModel, FileModel, ArticleModel>(command, (a, ac, f) =>
{
if (article == null)
{
article = a;
}
if (ac != null)
{
var content = article.Contents.SingleOrDefault(x => x.Id == ac.Id);
if (content == null)
{
article.Contents.Add(ac);
}
}
if (f != null)
{
var content = article.Contents.SingleOrDefault(x => x.Id == ac.Id);
if (content != null)
{
content.MimeType = f.MimeType;
content.ContentUrl = f.FilePath;
}
}
return article;
});
return article;
}
}
}
}
| 44.207951 | 222 | 0.490454 | [
"Apache-2.0"
] | inshapardaz/inshapardaz | src/Inshapardaz.Database.SqlServer/Repositories/Library/ArticleRepository.cs | 14,458 | C# |
using Microsoft.EntityFrameworkCore.Migrations;
namespace Silk.Core.Data.Migrations
{
public partial class NewGreetingOption : Migration
{
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.AddColumn<int>(
name: "GreetingOption",
table: "GuildConfigs",
type: "integer",
nullable: false,
defaultValue: 0);
}
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropColumn(
name: "GreetingOption",
table: "GuildConfigs");
}
}
}
| 27.4 | 71 | 0.570803 | [
"Apache-2.0"
] | Giggitybyte/Silk | src/Silk.Core.Data/Migrations/20210615011332_NewGreetingOption.cs | 687 | 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 Microsoft.Azure.Batch;
using Microsoft.Azure.Batch.Protocol;
using Microsoft.Azure.Batch.Protocol.Models;
using Microsoft.Rest.Azure;
using Microsoft.WindowsAzure.Commands.ScenarioTest;
using Moq;
using System;
using System.Collections.Generic;
using System.Management.Automation;
using Xunit;
using BatchClient = Microsoft.Azure.Commands.Batch.Models.BatchClient;
namespace Microsoft.Azure.Commands.Batch.Test.ComputeNodeUsers
{
public class RemoveBatchComputeNodeUserCommandTests : WindowsAzure.Commands.Test.Utilities.Common.RMTestBase
{
private RemoveBatchComputeNodeUserCommand cmdlet;
private Mock<BatchClient> batchClientMock;
private Mock<ICommandRuntime> commandRuntimeMock;
public RemoveBatchComputeNodeUserCommandTests(Xunit.Abstractions.ITestOutputHelper output)
{
ServiceManagemenet.Common.Models.XunitTracingInterceptor.AddToContext(new ServiceManagemenet.Common.Models.XunitTracingInterceptor(output));
batchClientMock = new Mock<BatchClient>();
commandRuntimeMock = new Mock<ICommandRuntime>();
cmdlet = new RemoveBatchComputeNodeUserCommand()
{
CommandRuntime = commandRuntimeMock.Object,
BatchClient = batchClientMock.Object,
};
}
[Fact]
[Trait(Category.AcceptanceType, Category.CheckIn)]
public void RemoveBatchComputeNodeUserParametersTest()
{
// Setup cmdlet without the required parameters
BatchAccountContext context = BatchTestHelpers.CreateBatchContextWithKeys();
cmdlet.BatchContext = context;
// Setup cmdlet to skip confirmation popup
cmdlet.Force = true;
commandRuntimeMock.Setup(f => f.ShouldProcess(It.IsAny<string>(), It.IsAny<string>())).Returns(true);
Assert.Throws<ArgumentNullException>(() => cmdlet.ExecuteCmdlet());
cmdlet.PoolId = "testPool";
cmdlet.ComputeNodeId = "computeNode1";
cmdlet.Name = "testUser";
// Don't go to the service on a Delete ComputeNodeUser call
RequestInterceptor interceptor = BatchTestHelpers.CreateFakeServiceResponseInterceptor<
ComputeNodeDeleteUserOptions,
AzureOperationHeaderResponse<ComputeNodeDeleteUserHeaders>>();
cmdlet.AdditionalBehaviors = new List<BatchClientBehavior>() { interceptor };
// Verify no exceptions when required parameters are set
cmdlet.ExecuteCmdlet();
}
}
}
| 44.376623 | 153 | 0.657009 | [
"MIT"
] | hchungmsft/azure-powershell | src/ResourceManager/AzureBatch/Commands.Batch.Test/ComputeNodeUsers/RemoveBatchComputeNodeUserCommandTests.cs | 3,343 | C# |
namespace Masa.Framework.Admin.Web.Shared
{
public partial class MainLayout
{
private HubConnection _hubConnection = default!;
private bool _show;
private string _msg = "";
[Inject]
public NavigationManager NavigationManager { get; set; } = default!;
[Inject]
public IHttpContextAccessor HttpContextAccessor { get; set; } = default!;
[Inject]
public ProtectedLocalStorage ProtectedLocalStorage { get; set; } = default!;
[Inject]
public IConfiguration Configuration { get; set; } = default!;
[Inject]
public PermissionHelper PermissionHelper { get; set; } = default!;
[Inject]
public NavHelper NavHelper { get; set; } = default!;
protected override async Task OnInitializedAsync()
{
await NavHelper.InitializationAsync();
}
protected override async Task OnAfterRenderAsync(bool firstRender)
{
if (firstRender)
{
var token = HttpContextAccessor.HttpContext?.User.Claims.FirstOrDefault(c => c.Type == "Token");
var isLogined = false;
try
{
isLogined = (await ProtectedLocalStorage.GetAsync<bool>("IsLogined")).Value;
}
catch (Exception ex)
{
}
if (token == null || isLogined != true)
{
NavigationManager.NavigateTo("/pages/authentication/Login-v2", true);
}
else
{
await StartSignalR(token.Value);
}
}
}
public async Task StartSignalR(string token)
{
_hubConnection = new HubConnectionBuilder()
.WithUrl($"{Configuration["ApiGateways:UserCaller"]}/hub/login", HttpTransportType.WebSockets | HttpTransportType.LongPolling
, options =>
{
options.AccessTokenProvider = () => Task.FromResult(token);
}
)
.ConfigureLogging(logging =>
{
logging.SetMinimumLevel(LogLevel.Information);
logging.AddConsole();
})
.WithAutomaticReconnect()
.Build();
_hubConnection.On<string>("Logout", Logout);
await _hubConnection.StartAsync();
}
public async Task Logout(string msg)
{
await ProtectedLocalStorage.SetAsync("IsLogined", false);
await _hubConnection.StopAsync();
await _hubConnection.DisposeAsync();
_show = true;
_msg = msg;
StateHasChanged();
await Task.Delay(5000);
GoToLogout();
}
public void GoToLogout()
{
NavigationManager.NavigateTo($"/Account/Logout", true);
}
}
}
| 31.010204 | 141 | 0.517604 | [
"Apache-2.0"
] | masalabs/MASA.Framework.Admin | src/Web/Masa.Framework.Admin.Web/Shared/MainLayout.razor.cs | 3,039 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace StringExtensions.Benchmark
{
public static class DataGenerator
{
public static List<Genre> Genres { get; }
public static List<Artist> Artists { get; }
public static List<Album> Albums { get; }
static DataGenerator()
{
Genres = new List<Genre>
{
new Genre { Name = "Rock" },
new Genre { Name = "Jazz" },
new Genre { Name = "Metal" },
new Genre { Name = "Alternative" },
new Genre { Name = "Disco" },
new Genre { Name = "Blues" },
new Genre { Name = "Latin" },
new Genre { Name = "Reggae" },
new Genre { Name = "Pop" },
new Genre { Name = "Classical" }
};
Artists = new List<Artist>
{
new Artist { Name = "Aaron Copland & London Symphony Orchestra" },
new Artist { Name = "Aaron Goldberg" },
new Artist { Name = "AC/DC" },
new Artist { Name = "Accept" },
new Artist { Name = "Adrian Leaper & Doreen de Feis" },
new Artist { Name = "Aerosmith" },
new Artist { Name = "Aisha Duo" },
new Artist { Name = "Alanis Morissette" },
new Artist { Name = "Alberto Turco & Nova Schola Gregoriana" },
new Artist { Name = "Alice In Chains" },
new Artist { Name = "Amy Winehouse" },
new Artist { Name = "Anita Ward" },
new Artist { Name = "Antônio Carlos Jobim" },
new Artist { Name = "Apocalyptica" },
new Artist { Name = "Audioslave" },
new Artist { Name = "Barry Wordsworth & BBC Concert Orchestra" },
new Artist { Name = "Berliner Philharmoniker & Hans Rosbaud" },
new Artist { Name = "Berliner Philharmoniker & Herbert Von Karajan" },
new Artist { Name = "Billy Cobham" },
new Artist { Name = "Black Label Society" },
new Artist { Name = "Black Sabbath" },
new Artist { Name = "Boston Symphony Orchestra & Seiji Ozawa" },
new Artist { Name = "Britten Sinfonia, Ivor Bolton & Lesley Garrett" },
new Artist { Name = "Bruce Dickinson" },
new Artist { Name = "Buddy Guy" },
new Artist { Name = "Caetano Veloso" },
new Artist { Name = "Cake" },
new Artist { Name = "Calexico" },
new Artist { Name = "Cássia Eller" },
new Artist { Name = "Chic" },
new Artist { Name = "Chicago Symphony Orchestra & Fritz Reiner" },
new Artist { Name = "Chico Buarque" },
new Artist { Name = "Chico Science & Nação Zumbi" },
new Artist { Name = "Choir Of Westminster Abbey & Simon Preston" },
new Artist { Name = "Chris Cornell" },
new Artist { Name = "Christopher O'Riley" },
new Artist { Name = "Cidade Negra" },
new Artist { Name = "Cláudio Zoli" },
new Artist { Name = "Creedence Clearwater Revival" },
new Artist { Name = "David Coverdale" },
new Artist { Name = "Deep Purple" },
new Artist { Name = "Dennis Chambers" },
new Artist { Name = "Djavan" },
new Artist { Name = "Donna Summer" },
new Artist { Name = "Dread Zeppelin" },
new Artist { Name = "Ed Motta" },
new Artist { Name = "Edo de Waart & San Francisco Symphony" },
new Artist { Name = "Elis Regina" },
new Artist { Name = "English Concert & Trevor Pinnock" },
new Artist { Name = "Eric Clapton" },
new Artist { Name = "Eugene Ormandy" },
new Artist { Name = "Faith No More" },
new Artist { Name = "Falamansa" },
new Artist { Name = "Foo Fighters" },
new Artist { Name = "Frank Zappa & Captain Beefheart" },
new Artist { Name = "Fretwork" },
new Artist { Name = "Funk Como Le Gusta" },
new Artist { Name = "Gerald Moore" },
new Artist { Name = "Gilberto Gil" },
new Artist { Name = "Godsmack" },
new Artist { Name = "Gonzaguinha" },
new Artist { Name = "Göteborgs Symfoniker & Neeme Järvi" },
new Artist { Name = "Guns N' Roses" },
new Artist { Name = "Gustav Mahler" },
new Artist { Name = "Incognito" },
new Artist { Name = "Iron Maiden" },
new Artist { Name = "James Levine" },
new Artist { Name = "Jamiroquai" },
new Artist { Name = "Jimi Hendrix" },
new Artist { Name = "Joe Satriani" },
new Artist { Name = "Jorge Ben" },
new Artist { Name = "Jota Quest" },
new Artist { Name = "Judas Priest" },
new Artist { Name = "Julian Bream" },
new Artist { Name = "Kent Nagano and Orchestre de l'Opéra de Lyon" },
new Artist { Name = "Kiss" },
new Artist { Name = "Led Zeppelin" },
new Artist { Name = "Legião Urbana" },
new Artist { Name = "Lenny Kravitz" },
new Artist { Name = "Les Arts Florissants & William Christie" },
new Artist { Name = "London Symphony Orchestra & Sir Charles Mackerras" },
new Artist { Name = "Luciana Souza/Romero Lubambo" },
new Artist { Name = "Lulu Santos" },
new Artist { Name = "Marcos Valle" },
new Artist { Name = "Marillion" },
new Artist { Name = "Marisa Monte" },
new Artist { Name = "Martin Roscoe" },
new Artist { Name = "Maurizio Pollini" },
new Artist { Name = "Mela Tenenbaum, Pro Musica Prague & Richard Kapp" },
new Artist { Name = "Men At Work" },
new Artist { Name = "Metallica" },
new Artist { Name = "Michael Tilson Thomas & San Francisco Symphony" },
new Artist { Name = "Miles Davis" },
new Artist { Name = "Milton Nascimento" },
new Artist { Name = "Mötley Crüe" },
new Artist { Name = "Motörhead" },
new Artist { Name = "Nash Ensemble" },
new Artist { Name = "Nicolaus Esterhazy Sinfonia" },
new Artist { Name = "Nirvana" },
new Artist { Name = "O Terço" },
new Artist { Name = "Olodum" },
new Artist { Name = "Orchestra of The Age of Enlightenment" },
new Artist { Name = "Os Paralamas Do Sucesso" },
new Artist { Name = "Ozzy Osbourne" },
new Artist { Name = "Page & Plant" },
new Artist { Name = "Paul D'Ianno" },
new Artist { Name = "Pearl Jam" },
new Artist { Name = "Pink Floyd" },
new Artist { Name = "Queen" },
new Artist { Name = "R.E.M." },
new Artist { Name = "Raul Seixas" },
new Artist { Name = "Red Hot Chili Peppers" },
new Artist { Name = "Roger Norrington, London Classical Players" },
new Artist { Name = "Royal Philharmonic Orchestra & Sir Thomas Beecham" },
new Artist { Name = "Rush" },
new Artist { Name = "Santana" },
new Artist { Name = "Scholars Baroque Ensemble" },
new Artist { Name = "Scorpions" },
new Artist { Name = "Sergei Prokofiev & Yuri Temirkanov" },
new Artist { Name = "Sir Georg Solti & Wiener Philharmoniker" },
new Artist { Name = "Skank" },
new Artist { Name = "Soundgarden" },
new Artist { Name = "Spyro Gyra" },
new Artist { Name = "Stevie Ray Vaughan & Double Trouble" },
new Artist { Name = "Stone Temple Pilots" },
new Artist { Name = "System Of A Down" },
new Artist { Name = "Temple of the Dog" },
new Artist { Name = "Terry Bozzio, Tony Levin & Steve Stevens" },
new Artist { Name = "The 12 Cellists of The Berlin Philharmonic" },
new Artist { Name = "The Black Crowes" },
new Artist { Name = "The Cult" },
new Artist { Name = "The Doors" },
new Artist { Name = "The King's Singers" },
new Artist { Name = "The Police" },
new Artist { Name = "The Posies" },
new Artist { Name = "The Rolling Stones" },
new Artist { Name = "The Who" },
new Artist { Name = "Tim Maia" },
new Artist { Name = "Ton Koopman" },
new Artist { Name = "U2" },
new Artist { Name = "UB40" },
new Artist { Name = "Van Halen" },
new Artist { Name = "Various Artists" },
new Artist { Name = "Velvet Revolver" },
new Artist { Name = "Vinícius De Moraes" },
new Artist { Name = "Wilhelm Kempff" },
new Artist { Name = "Yehudi Menuhin" },
new Artist { Name = "Yo-Yo Ma" },
new Artist { Name = "Zeca Pagodinho" }
};
Albums = new List<Album>
{
new Album { Title = "The Best Of Men At Work", Genre = Genres.Single(g => g.Name == "Rock"), Price = 8.99M, Artist = Artists.Single(a => a.Name == "Men At Work"), AlbumArtUrl = "/Content/Images/placeholder.gif" },
new Album { Title = "A Copland Celebration, Vol. I", Genre = Genres.Single(g => g.Name == "Classical"), Price = 8.99M, Artist = Artists.Single(a => a.Name == "Aaron Copland & London Symphony Orchestra"), AlbumArtUrl = "/Content/Images/placeholder.gif" },
new Album { Title = "Worlds", Genre = Genres.Single(g => g.Name == "Jazz"), Price = 8.99M, Artist = Artists.Single(a => a.Name == "Aaron Goldberg"), AlbumArtUrl = "/Content/Images/placeholder.gif" },
new Album { Title = "For Those About To Rock We Salute You", Genre = Genres.Single(g => g.Name == "Rock"), Price = 8.99M, Artist = Artists.Single(a => a.Name == "AC/DC"), AlbumArtUrl = "/Content/Images/placeholder.gif" },
new Album { Title = "Let There Be Rock", Genre = Genres.Single(g => g.Name == "Rock"), Price = 8.99M, Artist = Artists.Single(a => a.Name == "AC/DC"), AlbumArtUrl = "/Content/Images/placeholder.gif" },
new Album { Title = "Balls to the Wall", Genre = Genres.Single(g => g.Name == "Rock"), Price = 8.99M, Artist = Artists.Single(a => a.Name == "Accept"), AlbumArtUrl = "/Content/Images/placeholder.gif" },
new Album { Title = "Restless and Wild", Genre = Genres.Single(g => g.Name == "Rock"), Price = 8.99M, Artist = Artists.Single(a => a.Name == "Accept"), AlbumArtUrl = "/Content/Images/placeholder.gif" },
new Album { Title = "Górecki: Symphony No. 3", Genre = Genres.Single(g => g.Name == "Classical"), Price = 8.99M, Artist = Artists.Single(a => a.Name == "Adrian Leaper & Doreen de Feis"), AlbumArtUrl = "/Content/Images/placeholder.gif" },
new Album { Title = "Big Ones", Genre = Genres.Single(g => g.Name == "Rock"), Price = 8.99M, Artist = Artists.Single(a => a.Name == "Aerosmith"), AlbumArtUrl = "/Content/Images/placeholder.gif" },
new Album { Title = "Quiet Songs", Genre = Genres.Single(g => g.Name == "Jazz"), Price = 8.99M, Artist = Artists.Single(a => a.Name == "Aisha Duo"), AlbumArtUrl = "/Content/Images/placeholder.gif" },
new Album { Title = "Jagged Little Pill", Genre = Genres.Single(g => g.Name == "Rock"), Price = 8.99M, Artist = Artists.Single(a => a.Name == "Alanis Morissette"), AlbumArtUrl = "/Content/Images/placeholder.gif" },
new Album { Title = "Facelift", Genre = Genres.Single(g => g.Name == "Rock"), Price = 8.99M, Artist = Artists.Single(a => a.Name == "Alice In Chains"), AlbumArtUrl = "/Content/Images/placeholder.gif" },
new Album { Title = "Frank", Genre = Genres.Single(g => g.Name == "Pop"), Price = 8.99M, Artist = Artists.Single(a => a.Name == "Amy Winehouse"), AlbumArtUrl = "/Content/Images/placeholder.gif" },
new Album { Title = "Ring My Bell", Genre = Genres.Single(g => g.Name == "Disco"), Price = 8.99M, Artist = Artists.Single(a => a.Name == "Anita Ward"), AlbumArtUrl = "/Content/Images/placeholder.gif" },
new Album { Title = "Chill: Brazil (Disc 2)", Genre = Genres.Single(g => g.Name == "Latin"), Price = 8.99M, Artist = Artists.Single(a => a.Name == "Antônio Carlos Jobim"), AlbumArtUrl = "/Content/Images/placeholder.gif" },
new Album { Title = "Warner 25 Anos", Genre = Genres.Single(g => g.Name == "Jazz"), Price = 8.99M, Artist = Artists.Single(a => a.Name == "Antônio Carlos Jobim"), AlbumArtUrl = "/Content/Images/placeholder.gif" },
new Album { Title = "Plays Metallica By Four Cellos", Genre = Genres.Single(g => g.Name == "Metal"), Price = 8.99M, Artist = Artists.Single(a => a.Name == "Apocalyptica"), AlbumArtUrl = "/Content/Images/placeholder.gif" },
new Album { Title = "Revelations", Genre = Genres.Single(g => g.Name == "Alternative"), Price = 8.99M, Artist = Artists.Single(a => a.Name == "Audioslave"), AlbumArtUrl = "/Content/Images/placeholder.gif" },
new Album { Title = "Audioslave", Genre = Genres.Single(g => g.Name == "Rock"), Price = 8.99M, Artist = Artists.Single(a => a.Name == "Audioslave"), AlbumArtUrl = "/Content/Images/placeholder.gif" },
new Album { Title = "The Last Night of the Proms", Genre = Genres.Single(g => g.Name == "Classical"), Price = 8.99M, Artist = Artists.Single(a => a.Name == "Barry Wordsworth & BBC Concert Orchestra"), AlbumArtUrl = "/Content/Images/placeholder.gif" },
new Album { Title = "Sibelius: Finlandia", Genre = Genres.Single(g => g.Name == "Classical"), Price = 8.99M, Artist = Artists.Single(a => a.Name == "Berliner Philharmoniker & Hans Rosbaud"), AlbumArtUrl = "/Content/Images/placeholder.gif" },
new Album { Title = "Mozart: Symphonies Nos. 40 & 41", Genre = Genres.Single(g => g.Name == "Classical"), Price = 8.99M, Artist = Artists.Single(a => a.Name == "Berliner Philharmoniker & Herbert Von Karajan"), AlbumArtUrl = "/Content/Images/placeholder.gif" },
new Album { Title = "The Best Of Billy Cobham", Genre = Genres.Single(g => g.Name == "Jazz"), Price = 8.99M, Artist = Artists.Single(a => a.Name == "Billy Cobham"), AlbumArtUrl = "/Content/Images/placeholder.gif" },
new Album { Title = "Alcohol Fueled Brewtality Live! [Disc 1]", Genre = Genres.Single(g => g.Name == "Metal"), Price = 8.99M, Artist = Artists.Single(a => a.Name == "Black Label Society"), AlbumArtUrl = "/Content/Images/placeholder.gif" },
new Album { Title = "Alcohol Fueled Brewtality Live! [Disc 2]", Genre = Genres.Single(g => g.Name == "Metal"), Price = 8.99M, Artist = Artists.Single(a => a.Name == "Black Label Society"), AlbumArtUrl = "/Content/Images/placeholder.gif" },
new Album { Title = "Black Sabbath Vol. 4 (Remaster)", Genre = Genres.Single(g => g.Name == "Metal"), Price = 8.99M, Artist = Artists.Single(a => a.Name == "Black Sabbath"), AlbumArtUrl = "/Content/Images/placeholder.gif" },
new Album { Title = "Black Sabbath", Genre = Genres.Single(g => g.Name == "Metal"), Price = 8.99M, Artist = Artists.Single(a => a.Name == "Black Sabbath"), AlbumArtUrl = "/Content/Images/placeholder.gif" },
new Album { Title = "Carmina Burana", Genre = Genres.Single(g => g.Name == "Classical"), Price = 8.99M, Artist = Artists.Single(a => a.Name == "Boston Symphony Orchestra & Seiji Ozawa"), AlbumArtUrl = "/Content/Images/placeholder.gif" },
new Album { Title = "A Soprano Inspired", Genre = Genres.Single(g => g.Name == "Classical"), Price = 8.99M, Artist = Artists.Single(a => a.Name == "Britten Sinfonia, Ivor Bolton & Lesley Garrett"), AlbumArtUrl = "/Content/Images/placeholder.gif" },
new Album { Title = "Chemical Wedding", Genre = Genres.Single(g => g.Name == "Metal"), Price = 8.99M, Artist = Artists.Single(a => a.Name == "Bruce Dickinson"), AlbumArtUrl = "/Content/Images/placeholder.gif" },
new Album { Title = "Prenda Minha", Genre = Genres.Single(g => g.Name == "Latin"), Price = 8.99M, Artist = Artists.Single(a => a.Name == "Caetano Veloso"), AlbumArtUrl = "/Content/Images/placeholder.gif" },
new Album { Title = "Sozinho Remix Ao Vivo", Genre = Genres.Single(g => g.Name == "Latin"), Price = 8.99M, Artist = Artists.Single(a => a.Name == "Caetano Veloso"), AlbumArtUrl = "/Content/Images/placeholder.gif" },
new Album { Title = "Cake: B-Sides and Rarities", Genre = Genres.Single(g => g.Name == "Alternative"), Price = 8.99M, Artist = Artists.Single(a => a.Name == "Cake"), AlbumArtUrl = "/Content/Images/placeholder.gif" },
new Album { Title = "Carried to Dust (Bonus Track Version)", Genre = Genres.Single(g => g.Name == "Alternative"), Price = 8.99M, Artist = Artists.Single(a => a.Name == "Calexico"), AlbumArtUrl = "/Content/Images/placeholder.gif" },
new Album { Title = "Cássia Eller - Sem Limite [Disc 1]", Genre = Genres.Single(g => g.Name == "Latin"), Price = 8.99M, Artist = Artists.Single(a => a.Name == "Cássia Eller"), AlbumArtUrl = "/Content/Images/placeholder.gif" },
new Album { Title = "Le Freak", Genre = Genres.Single(g => g.Name == "Disco"), Price = 8.99M, Artist = Artists.Single(a => a.Name == "Chic"), AlbumArtUrl = "/Content/Images/placeholder.gif" },
new Album { Title = "Scheherazade", Genre = Genres.Single(g => g.Name == "Classical"), Price = 8.99M, Artist = Artists.Single(a => a.Name == "Chicago Symphony Orchestra & Fritz Reiner"), AlbumArtUrl = "/Content/Images/placeholder.gif" },
new Album { Title = "Minha Historia", Genre = Genres.Single(g => g.Name == "Latin"), Price = 8.99M, Artist = Artists.Single(a => a.Name == "Chico Buarque"), AlbumArtUrl = "/Content/Images/placeholder.gif" },
new Album { Title = "Afrociberdelia", Genre = Genres.Single(g => g.Name == "Latin"), Price = 8.99M, Artist = Artists.Single(a => a.Name == "Chico Science & Nação Zumbi"), AlbumArtUrl = "/Content/Images/placeholder.gif" },
new Album { Title = "Da Lama Ao Caos", Genre = Genres.Single(g => g.Name == "Latin"), Price = 8.99M, Artist = Artists.Single(a => a.Name == "Chico Science & Nação Zumbi"), AlbumArtUrl = "/Content/Images/placeholder.gif" },
new Album { Title = "Carry On", Genre = Genres.Single(g => g.Name == "Alternative"), Price = 8.99M, Artist = Artists.Single(a => a.Name == "Chris Cornell"), AlbumArtUrl = "/Content/Images/placeholder.gif" },
new Album { Title = "SCRIABIN: Vers la flamme", Genre = Genres.Single(g => g.Name == "Classical"), Price = 8.99M, Artist = Artists.Single(a => a.Name == "Christopher O'Riley"), AlbumArtUrl = "/Content/Images/placeholder.gif" },
new Album { Title = "Acústico MTV [Live]", Genre = Genres.Single(g => g.Name == "Reggae"), Price = 8.99M, Artist = Artists.Single(a => a.Name == "Cidade Negra"), AlbumArtUrl = "/Content/Images/placeholder.gif" },
new Album { Title = "Cidade Negra - Hits", Genre = Genres.Single(g => g.Name == "Reggae"), Price = 8.99M, Artist = Artists.Single(a => a.Name == "Cidade Negra"), AlbumArtUrl = "/Content/Images/placeholder.gif" },
new Album { Title = "Na Pista", Genre = Genres.Single(g => g.Name == "Latin"), Price = 8.99M, Artist = Artists.Single(a => a.Name == "Cláudio Zoli"), AlbumArtUrl = "/Content/Images/placeholder.gif" },
new Album { Title = "Chronicle, Vol. 1", Genre = Genres.Single(g => g.Name == "Rock"), Price = 8.99M, Artist = Artists.Single(a => a.Name == "Creedence Clearwater Revival"), AlbumArtUrl = "/Content/Images/placeholder.gif" },
new Album { Title = "Chronicle, Vol. 2", Genre = Genres.Single(g => g.Name == "Rock"), Price = 8.99M, Artist = Artists.Single(a => a.Name == "Creedence Clearwater Revival"), AlbumArtUrl = "/Content/Images/placeholder.gif" },
new Album { Title = "Into The Light", Genre = Genres.Single(g => g.Name == "Rock"), Price = 8.99M, Artist = Artists.Single(a => a.Name == "David Coverdale"), AlbumArtUrl = "/Content/Images/placeholder.gif" },
new Album { Title = "Come Taste The Band", Genre = Genres.Single(g => g.Name == "Rock"), Price = 8.99M, Artist = Artists.Single(a => a.Name == "Deep Purple"), AlbumArtUrl = "/Content/Images/placeholder.gif" },
new Album { Title = "Deep Purple In Rock", Genre = Genres.Single(g => g.Name == "Rock"), Price = 8.99M, Artist = Artists.Single(a => a.Name == "Deep Purple"), AlbumArtUrl = "/Content/Images/placeholder.gif" },
new Album { Title = "Fireball", Genre = Genres.Single(g => g.Name == "Rock"), Price = 8.99M, Artist = Artists.Single(a => a.Name == "Deep Purple"), AlbumArtUrl = "/Content/Images/placeholder.gif" },
new Album { Title = "Machine Head", Genre = Genres.Single(g => g.Name == "Rock"), Price = 8.99M, Artist = Artists.Single(a => a.Name == "Deep Purple"), AlbumArtUrl = "/Content/Images/placeholder.gif" },
new Album { Title = "MK III The Final Concerts [Disc 1]", Genre = Genres.Single(g => g.Name == "Rock"), Price = 8.99M, Artist = Artists.Single(a => a.Name == "Deep Purple"), AlbumArtUrl = "/Content/Images/placeholder.gif" },
new Album { Title = "Purpendicular", Genre = Genres.Single(g => g.Name == "Rock"), Price = 8.99M, Artist = Artists.Single(a => a.Name == "Deep Purple"), AlbumArtUrl = "/Content/Images/placeholder.gif" },
new Album { Title = "Slaves And Masters", Genre = Genres.Single(g => g.Name == "Rock"), Price = 8.99M, Artist = Artists.Single(a => a.Name == "Deep Purple"), AlbumArtUrl = "/Content/Images/placeholder.gif" },
new Album { Title = "Stormbringer", Genre = Genres.Single(g => g.Name == "Rock"), Price = 8.99M, Artist = Artists.Single(a => a.Name == "Deep Purple"), AlbumArtUrl = "/Content/Images/placeholder.gif" },
new Album { Title = "The Battle Rages On", Genre = Genres.Single(g => g.Name == "Rock"), Price = 8.99M, Artist = Artists.Single(a => a.Name == "Deep Purple"), AlbumArtUrl = "/Content/Images/placeholder.gif" },
new Album { Title = "The Final Concerts (Disc 2)", Genre = Genres.Single(g => g.Name == "Rock"), Price = 8.99M, Artist = Artists.Single(a => a.Name == "Deep Purple"), AlbumArtUrl = "/Content/Images/placeholder.gif" },
new Album { Title = "Outbreak", Genre = Genres.Single(g => g.Name == "Jazz"), Price = 8.99M, Artist = Artists.Single(a => a.Name == "Dennis Chambers"), AlbumArtUrl = "/Content/Images/placeholder.gif" },
new Album { Title = "Djavan Ao Vivo - Vol. 02", Genre = Genres.Single(g => g.Name == "Latin"), Price = 8.99M, Artist = Artists.Single(a => a.Name == "Djavan"), AlbumArtUrl = "/Content/Images/placeholder.gif" },
new Album { Title = "Djavan Ao Vivo - Vol. 1", Genre = Genres.Single(g => g.Name == "Latin"), Price = 8.99M, Artist = Artists.Single(a => a.Name == "Djavan"), AlbumArtUrl = "/Content/Images/placeholder.gif" },
new Album { Title = "MacArthur Park Suite", Genre = Genres.Single(g => g.Name == "Disco"), Price = 8.99M, Artist = Artists.Single(a => a.Name == "Donna Summer"), AlbumArtUrl = "/Content/Images/placeholder.gif" },
new Album { Title = "Un-Led-Ed", Genre = Genres.Single(g => g.Name == "Rock"), Price = 8.99M, Artist = Artists.Single(a => a.Name == "Dread Zeppelin"), AlbumArtUrl = "/Content/Images/placeholder.gif" },
new Album { Title = "The Best of Ed Motta", Genre = Genres.Single(g => g.Name == "Latin"), Price = 8.99M, Artist = Artists.Single(a => a.Name == "Ed Motta"), AlbumArtUrl = "/Content/Images/placeholder.gif" },
new Album { Title = "Adams, John: The Chairman Dances", Genre = Genres.Single(g => g.Name == "Classical"), Price = 8.99M, Artist = Artists.Single(a => a.Name == "Edo de Waart & San Francisco Symphony"), AlbumArtUrl = "/Content/Images/placeholder.gif" },
new Album { Title = "Elis Regina-Minha História", Genre = Genres.Single(g => g.Name == "Latin"), Price = 8.99M, Artist = Artists.Single(a => a.Name == "Elis Regina"), AlbumArtUrl = "/Content/Images/placeholder.gif" },
new Album { Title = "Pachelbel: Canon & Gigue", Genre = Genres.Single(g => g.Name == "Classical"), Price = 8.99M, Artist = Artists.Single(a => a.Name == "English Concert & Trevor Pinnock"), AlbumArtUrl = "/Content/Images/placeholder.gif" },
new Album { Title = "Unplugged", Genre = Genres.Single(g => g.Name == "Latin"), Price = 8.99M, Artist = Artists.Single(a => a.Name == "Eric Clapton"), AlbumArtUrl = "/Content/Images/placeholder.gif" },
new Album { Title = "The Cream Of Clapton", Genre = Genres.Single(g => g.Name == "Blues"), Price = 8.99M, Artist = Artists.Single(a => a.Name == "Eric Clapton"), AlbumArtUrl = "/Content/Images/placeholder.gif" },
new Album { Title = "Unplugged", Genre = Genres.Single(g => g.Name == "Blues"), Price = 8.99M, Artist = Artists.Single(a => a.Name == "Eric Clapton"), AlbumArtUrl = "/Content/Images/placeholder.gif" },
new Album { Title = "Respighi:Pines of Rome", Genre = Genres.Single(g => g.Name == "Classical"), Price = 8.99M, Artist = Artists.Single(a => a.Name == "Eugene Ormandy"), AlbumArtUrl = "/Content/Images/placeholder.gif" },
new Album { Title = "Strauss: Waltzes", Genre = Genres.Single(g => g.Name == "Classical"), Price = 8.99M, Artist = Artists.Single(a => a.Name == "Eugene Ormandy"), AlbumArtUrl = "/Content/Images/placeholder.gif" },
new Album { Title = "King For A Day Fool For A Lifetime", Genre = Genres.Single(g => g.Name == "Rock"), Price = 8.99M, Artist = Artists.Single(a => a.Name == "Faith No More"), AlbumArtUrl = "/Content/Images/placeholder.gif" },
new Album { Title = "Deixa Entrar", Genre = Genres.Single(g => g.Name == "Latin"), Price = 8.99M, Artist = Artists.Single(a => a.Name == "Falamansa"), AlbumArtUrl = "/Content/Images/placeholder.gif" },
new Album { Title = "In Your Honor [Disc 1]", Genre = Genres.Single(g => g.Name == "Rock"), Price = 8.99M, Artist = Artists.Single(a => a.Name == "Foo Fighters"), AlbumArtUrl = "/Content/Images/placeholder.gif" },
new Album { Title = "In Your Honor [Disc 2]", Genre = Genres.Single(g => g.Name == "Rock"), Price = 8.99M, Artist = Artists.Single(a => a.Name == "Foo Fighters"), AlbumArtUrl = "/Content/Images/placeholder.gif" },
new Album { Title = "The Colour And The Shape", Genre = Genres.Single(g => g.Name == "Rock"), Price = 8.99M, Artist = Artists.Single(a => a.Name == "Foo Fighters"), AlbumArtUrl = "/Content/Images/placeholder.gif" },
new Album { Title = "Bongo Fury", Genre = Genres.Single(g => g.Name == "Rock"), Price = 8.99M, Artist = Artists.Single(a => a.Name == "Frank Zappa & Captain Beefheart"), AlbumArtUrl = "/Content/Images/placeholder.gif" },
new Album { Title = "Roda De Funk", Genre = Genres.Single(g => g.Name == "Latin"), Price = 8.99M, Artist = Artists.Single(a => a.Name == "Funk Como Le Gusta"), AlbumArtUrl = "/Content/Images/placeholder.gif" },
new Album { Title = "Quanta Gente Veio Ver (Live)", Genre = Genres.Single(g => g.Name == "Latin"), Price = 8.99M, Artist = Artists.Single(a => a.Name == "Gilberto Gil"), AlbumArtUrl = "/Content/Images/placeholder.gif" },
new Album { Title = "Quanta Gente Veio ver--Bônus De Carnaval", Genre = Genres.Single(g => g.Name == "Jazz"), Price = 8.99M, Artist = Artists.Single(a => a.Name == "Gilberto Gil"), AlbumArtUrl = "/Content/Images/placeholder.gif" },
new Album { Title = "Faceless", Genre = Genres.Single(g => g.Name == "Metal"), Price = 8.99M, Artist = Artists.Single(a => a.Name == "Godsmack"), AlbumArtUrl = "/Content/Images/placeholder.gif" },
new Album { Title = "Meus Momentos", Genre = Genres.Single(g => g.Name == "Latin"), Price = 8.99M, Artist = Artists.Single(a => a.Name == "Gonzaguinha"), AlbumArtUrl = "/Content/Images/placeholder.gif" },
new Album { Title = "Nielsen: The Six Symphonies", Genre = Genres.Single(g => g.Name == "Classical"), Price = 8.99M, Artist = Artists.Single(a => a.Name == "Göteborgs Symfoniker & Neeme Järvi"), AlbumArtUrl = "/Content/Images/placeholder.gif" },
new Album { Title = "Appetite for Destruction", Genre = Genres.Single(g => g.Name == "Rock"), Price = 8.99M, Artist = Artists.Single(a => a.Name == "Guns N' Roses"), AlbumArtUrl = "/Content/Images/placeholder.gif" },
new Album { Title = "Use Your Illusion I", Genre = Genres.Single(g => g.Name == "Rock"), Price = 8.99M, Artist = Artists.Single(a => a.Name == "Guns N' Roses"), AlbumArtUrl = "/Content/Images/placeholder.gif" },
new Album { Title = "Use Your Illusion II", Genre = Genres.Single(g => g.Name == "Metal"), Price = 8.99M, Artist = Artists.Single(a => a.Name == "Guns N' Roses"), AlbumArtUrl = "/Content/Images/placeholder.gif" },
new Album { Title = "Blue Moods", Genre = Genres.Single(g => g.Name == "Jazz"), Price = 8.99M, Artist = Artists.Single(a => a.Name == "Incognito"), AlbumArtUrl = "/Content/Images/placeholder.gif" },
new Album { Title = "A Matter of Life and Death", Genre = Genres.Single(g => g.Name == "Rock"), Price = 8.99M, Artist = Artists.Single(a => a.Name == "Iron Maiden"), AlbumArtUrl = "/Content/Images/placeholder.gif" },
new Album { Title = "Brave New World", Genre = Genres.Single(g => g.Name == "Rock"), Price = 8.99M, Artist = Artists.Single(a => a.Name == "Iron Maiden"), AlbumArtUrl = "/Content/Images/placeholder.gif" },
new Album { Title = "Fear Of The Dark", Genre = Genres.Single(g => g.Name == "Rock"), Price = 8.99M, Artist = Artists.Single(a => a.Name == "Iron Maiden"), AlbumArtUrl = "/Content/Images/placeholder.gif" },
new Album { Title = "Live At Donington 1992 (Disc 1)", Genre = Genres.Single(g => g.Name == "Rock"), Price = 8.99M, Artist = Artists.Single(a => a.Name == "Iron Maiden"), AlbumArtUrl = "/Content/Images/placeholder.gif" },
new Album { Title = "Live At Donington 1992 (Disc 2)", Genre = Genres.Single(g => g.Name == "Rock"), Price = 8.99M, Artist = Artists.Single(a => a.Name == "Iron Maiden"), AlbumArtUrl = "/Content/Images/placeholder.gif" },
new Album { Title = "Rock In Rio [CD2]", Genre = Genres.Single(g => g.Name == "Rock"), Price = 8.99M, Artist = Artists.Single(a => a.Name == "Iron Maiden"), AlbumArtUrl = "/Content/Images/placeholder.gif" },
new Album { Title = "The Number of The Beast", Genre = Genres.Single(g => g.Name == "Rock"), Price = 8.99M, Artist = Artists.Single(a => a.Name == "Iron Maiden"), AlbumArtUrl = "/Content/Images/placeholder.gif" },
new Album { Title = "The X Factor", Genre = Genres.Single(g => g.Name == "Rock"), Price = 8.99M, Artist = Artists.Single(a => a.Name == "Iron Maiden"), AlbumArtUrl = "/Content/Images/placeholder.gif" },
new Album { Title = "Virtual XI", Genre = Genres.Single(g => g.Name == "Rock"), Price = 8.99M, Artist = Artists.Single(a => a.Name == "Iron Maiden"), AlbumArtUrl = "/Content/Images/placeholder.gif" },
new Album { Title = "A Real Dead One", Genre = Genres.Single(g => g.Name == "Metal"), Price = 8.99M, Artist = Artists.Single(a => a.Name == "Iron Maiden"), AlbumArtUrl = "/Content/Images/placeholder.gif" },
new Album { Title = "A Real Live One", Genre = Genres.Single(g => g.Name == "Metal"), Price = 8.99M, Artist = Artists.Single(a => a.Name == "Iron Maiden"), AlbumArtUrl = "/Content/Images/placeholder.gif" },
new Album { Title = "Live After Death", Genre = Genres.Single(g => g.Name == "Metal"), Price = 8.99M, Artist = Artists.Single(a => a.Name == "Iron Maiden"), AlbumArtUrl = "/Content/Images/placeholder.gif" },
new Album { Title = "No Prayer For The Dying", Genre = Genres.Single(g => g.Name == "Metal"), Price = 8.99M, Artist = Artists.Single(a => a.Name == "Iron Maiden"), AlbumArtUrl = "/Content/Images/placeholder.gif" },
new Album { Title = "Piece Of Mind", Genre = Genres.Single(g => g.Name == "Metal"), Price = 8.99M, Artist = Artists.Single(a => a.Name == "Iron Maiden"), AlbumArtUrl = "/Content/Images/placeholder.gif" },
new Album { Title = "Powerslave", Genre = Genres.Single(g => g.Name == "Metal"), Price = 8.99M, Artist = Artists.Single(a => a.Name == "Iron Maiden"), AlbumArtUrl = "/Content/Images/placeholder.gif" },
new Album { Title = "Rock In Rio [CD1]", Genre = Genres.Single(g => g.Name == "Metal"), Price = 8.99M, Artist = Artists.Single(a => a.Name == "Iron Maiden"), AlbumArtUrl = "/Content/Images/placeholder.gif" },
new Album { Title = "Rock In Rio [CD2]", Genre = Genres.Single(g => g.Name == "Metal"), Price = 8.99M, Artist = Artists.Single(a => a.Name == "Iron Maiden"), AlbumArtUrl = "/Content/Images/placeholder.gif" },
new Album { Title = "Seventh Son of a Seventh Son", Genre = Genres.Single(g => g.Name == "Metal"), Price = 8.99M, Artist = Artists.Single(a => a.Name == "Iron Maiden"), AlbumArtUrl = "/Content/Images/placeholder.gif" },
new Album { Title = "Somewhere in Time", Genre = Genres.Single(g => g.Name == "Metal"), Price = 8.99M, Artist = Artists.Single(a => a.Name == "Iron Maiden"), AlbumArtUrl = "/Content/Images/placeholder.gif" },
new Album { Title = "The Number of The Beast", Genre = Genres.Single(g => g.Name == "Metal"), Price = 8.99M, Artist = Artists.Single(a => a.Name == "Iron Maiden"), AlbumArtUrl = "/Content/Images/placeholder.gif" },
new Album { Title = "Iron Maiden", Genre = Genres.Single(g => g.Name == "Blues"), Price = 8.99M, Artist = Artists.Single(a => a.Name == "Iron Maiden"), AlbumArtUrl = "/Content/Images/placeholder.gif" },
new Album { Title = "Mascagni: Cavalleria Rusticana", Genre = Genres.Single(g => g.Name == "Classical"), Price = 8.99M, Artist = Artists.Single(a => a.Name == "James Levine"), AlbumArtUrl = "/Content/Images/placeholder.gif" },
new Album { Title = "Emergency On Planet Earth", Genre = Genres.Single(g => g.Name == "Rock"), Price = 8.99M, Artist = Artists.Single(a => a.Name == "Jamiroquai"), AlbumArtUrl = "/Content/Images/placeholder.gif" },
new Album { Title = "Are You Experienced?", Genre = Genres.Single(g => g.Name == "Rock"), Price = 8.99M, Artist = Artists.Single(a => a.Name == "Jimi Hendrix"), AlbumArtUrl = "/Content/Images/placeholder.gif" },
new Album { Title = "Surfing with the Alien (Remastered)", Genre = Genres.Single(g => g.Name == "Rock"), Price = 8.99M, Artist = Artists.Single(a => a.Name == "Joe Satriani"), AlbumArtUrl = "/Content/Images/placeholder.gif" },
new Album { Title = "Jorge Ben Jor 25 Anos", Genre = Genres.Single(g => g.Name == "Latin"), Price = 8.99M, Artist = Artists.Single(a => a.Name == "Jorge Ben"), AlbumArtUrl = "/Content/Images/placeholder.gif" },
new Album { Title = "Jota Quest-1995", Genre = Genres.Single(g => g.Name == "Latin"), Price = 8.99M, Artist = Artists.Single(a => a.Name == "Jota Quest"), AlbumArtUrl = "/Content/Images/placeholder.gif" },
new Album { Title = "Living After Midnight", Genre = Genres.Single(g => g.Name == "Metal"), Price = 8.99M, Artist = Artists.Single(a => a.Name == "Judas Priest"), AlbumArtUrl = "/Content/Images/placeholder.gif" },
new Album { Title = "Weill: The Seven Deadly Sins", Genre = Genres.Single(g => g.Name == "Classical"), Price = 8.99M, Artist = Artists.Single(a => a.Name == "Kent Nagano and Orchestre de l'Opéra de Lyon"), AlbumArtUrl = "/Content/Images/placeholder.gif" },
new Album { Title = "Greatest Kiss", Genre = Genres.Single(g => g.Name == "Rock"), Price = 8.99M, Artist = Artists.Single(a => a.Name == "Kiss"), AlbumArtUrl = "/Content/Images/placeholder.gif" },
new Album { Title = "Unplugged [Live]", Genre = Genres.Single(g => g.Name == "Rock"), Price = 8.99M, Artist = Artists.Single(a => a.Name == "Kiss"), AlbumArtUrl = "/Content/Images/placeholder.gif" },
new Album { Title = "BBC Sessions [Disc 1] [Live]", Genre = Genres.Single(g => g.Name == "Rock"), Price = 8.99M, Artist = Artists.Single(a => a.Name == "Led Zeppelin"), AlbumArtUrl = "/Content/Images/placeholder.gif" },
new Album { Title = "BBC Sessions [Disc 2] [Live]", Genre = Genres.Single(g => g.Name == "Rock"), Price = 8.99M, Artist = Artists.Single(a => a.Name == "Led Zeppelin"), AlbumArtUrl = "/Content/Images/placeholder.gif" },
new Album { Title = "Coda", Genre = Genres.Single(g => g.Name == "Rock"), Price = 8.99M, Artist = Artists.Single(a => a.Name == "Led Zeppelin"), AlbumArtUrl = "/Content/Images/placeholder.gif" },
new Album { Title = "Houses Of The Holy", Genre = Genres.Single(g => g.Name == "Rock"), Price = 8.99M, Artist = Artists.Single(a => a.Name == "Led Zeppelin"), AlbumArtUrl = "/Content/Images/placeholder.gif" },
new Album { Title = "In Through The Out Door", Genre = Genres.Single(g => g.Name == "Rock"), Price = 8.99M, Artist = Artists.Single(a => a.Name == "Led Zeppelin"), AlbumArtUrl = "/Content/Images/placeholder.gif" },
new Album { Title = "IV", Genre = Genres.Single(g => g.Name == "Rock"), Price = 8.99M, Artist = Artists.Single(a => a.Name == "Led Zeppelin"), AlbumArtUrl = "/Content/Images/placeholder.gif" },
new Album { Title = "Led Zeppelin I", Genre = Genres.Single(g => g.Name == "Rock"), Price = 8.99M, Artist = Artists.Single(a => a.Name == "Led Zeppelin"), AlbumArtUrl = "/Content/Images/placeholder.gif" },
new Album { Title = "Led Zeppelin II", Genre = Genres.Single(g => g.Name == "Rock"), Price = 8.99M, Artist = Artists.Single(a => a.Name == "Led Zeppelin"), AlbumArtUrl = "/Content/Images/placeholder.gif" },
new Album { Title = "Led Zeppelin III", Genre = Genres.Single(g => g.Name == "Rock"), Price = 8.99M, Artist = Artists.Single(a => a.Name == "Led Zeppelin"), AlbumArtUrl = "/Content/Images/placeholder.gif" },
new Album { Title = "Physical Graffiti [Disc 1]", Genre = Genres.Single(g => g.Name == "Rock"), Price = 8.99M, Artist = Artists.Single(a => a.Name == "Led Zeppelin"), AlbumArtUrl = "/Content/Images/placeholder.gif" },
new Album { Title = "Physical Graffiti [Disc 2]", Genre = Genres.Single(g => g.Name == "Rock"), Price = 8.99M, Artist = Artists.Single(a => a.Name == "Led Zeppelin"), AlbumArtUrl = "/Content/Images/placeholder.gif" },
new Album { Title = "Presence", Genre = Genres.Single(g => g.Name == "Rock"), Price = 8.99M, Artist = Artists.Single(a => a.Name == "Led Zeppelin"), AlbumArtUrl = "/Content/Images/placeholder.gif" },
new Album { Title = "The Song Remains The Same (Disc 1)", Genre = Genres.Single(g => g.Name == "Rock"), Price = 8.99M, Artist = Artists.Single(a => a.Name == "Led Zeppelin"), AlbumArtUrl = "/Content/Images/placeholder.gif" },
new Album { Title = "The Song Remains The Same (Disc 2)", Genre = Genres.Single(g => g.Name == "Rock"), Price = 8.99M, Artist = Artists.Single(a => a.Name == "Led Zeppelin"), AlbumArtUrl = "/Content/Images/placeholder.gif" },
new Album { Title = "Mais Do Mesmo", Genre = Genres.Single(g => g.Name == "Latin"), Price = 8.99M, Artist = Artists.Single(a => a.Name == "Legião Urbana"), AlbumArtUrl = "/Content/Images/placeholder.gif" },
new Album { Title = "Greatest Hits", Genre = Genres.Single(g => g.Name == "Reggae"), Price = 8.99M, Artist = Artists.Single(a => a.Name == "Lenny Kravitz"), AlbumArtUrl = "/Content/Images/placeholder.gif" },
new Album { Title = "Greatest Hits", Genre = Genres.Single(g => g.Name == "Rock"), Price = 8.99M, Artist = Artists.Single(a => a.Name == "Lenny Kravitz"), AlbumArtUrl = "/Content/Images/placeholder.gif" },
new Album { Title = "Greatest Hits", Genre = Genres.Single(g => g.Name == "Metal"), Price = 8.99M, Artist = Artists.Single(a => a.Name == "Lenny Kravitz"), AlbumArtUrl = "/Content/Images/placeholder.gif" },
new Album { Title = "Tchaikovsky: The Nutcracker", Genre = Genres.Single(g => g.Name == "Classical"), Price = 8.99M, Artist = Artists.Single(a => a.Name == "London Symphony Orchestra & Sir Charles Mackerras"), AlbumArtUrl = "/Content/Images/placeholder.gif" },
new Album { Title = "Duos II", Genre = Genres.Single(g => g.Name == "Latin"), Price = 8.99M, Artist = Artists.Single(a => a.Name == "Luciana Souza/Romero Lubambo"), AlbumArtUrl = "/Content/Images/placeholder.gif" },
new Album { Title = "Chill: Brazil (Disc 1)", Genre = Genres.Single(g => g.Name == "Latin"), Price = 8.99M, Artist = Artists.Single(a => a.Name == "Marcos Valle"), AlbumArtUrl = "/Content/Images/placeholder.gif" },
new Album { Title = "Misplaced Childhood", Genre = Genres.Single(g => g.Name == "Rock"), Price = 8.99M, Artist = Artists.Single(a => a.Name == "Marillion"), AlbumArtUrl = "/Content/Images/placeholder.gif" },
new Album { Title = "Barulhinho Bom", Genre = Genres.Single(g => g.Name == "Latin"), Price = 8.99M, Artist = Artists.Single(a => a.Name == "Marisa Monte"), AlbumArtUrl = "/Content/Images/placeholder.gif" },
new Album { Title = "Szymanowski: Piano Works, Vol. 1", Genre = Genres.Single(g => g.Name == "Classical"), Price = 8.99M, Artist = Artists.Single(a => a.Name == "Martin Roscoe"), AlbumArtUrl = "/Content/Images/placeholder.gif" },
new Album { Title = "...And Justice For All", Genre = Genres.Single(g => g.Name == "Metal"), Price = 8.99M, Artist = Artists.Single(a => a.Name == "Metallica"), AlbumArtUrl = "/Content/Images/placeholder.gif" },
new Album { Title = "Black Album", Genre = Genres.Single(g => g.Name == "Metal"), Price = 8.99M, Artist = Artists.Single(a => a.Name == "Metallica"), AlbumArtUrl = "/Content/Images/placeholder.gif" },
new Album { Title = "Garage Inc. (Disc 1)", Genre = Genres.Single(g => g.Name == "Metal"), Price = 8.99M, Artist = Artists.Single(a => a.Name == "Metallica"), AlbumArtUrl = "/Content/Images/placeholder.gif" },
new Album { Title = "Garage Inc. (Disc 2)", Genre = Genres.Single(g => g.Name == "Metal"), Price = 8.99M, Artist = Artists.Single(a => a.Name == "Metallica"), AlbumArtUrl = "/Content/Images/placeholder.gif" },
new Album { Title = "Load", Genre = Genres.Single(g => g.Name == "Metal"), Price = 8.99M, Artist = Artists.Single(a => a.Name == "Metallica"), AlbumArtUrl = "/Content/Images/placeholder.gif" },
new Album { Title = "Master Of Puppets", Genre = Genres.Single(g => g.Name == "Metal"), Price = 8.99M, Artist = Artists.Single(a => a.Name == "Metallica"), AlbumArtUrl = "/Content/Images/placeholder.gif" },
new Album { Title = "ReLoad", Genre = Genres.Single(g => g.Name == "Metal"), Price = 8.99M, Artist = Artists.Single(a => a.Name == "Metallica"), AlbumArtUrl = "/Content/Images/placeholder.gif" },
new Album { Title = "Ride The Lightning", Genre = Genres.Single(g => g.Name == "Metal"), Price = 8.99M, Artist = Artists.Single(a => a.Name == "Metallica"), AlbumArtUrl = "/Content/Images/placeholder.gif" },
new Album { Title = "St. Anger", Genre = Genres.Single(g => g.Name == "Metal"), Price = 8.99M, Artist = Artists.Single(a => a.Name == "Metallica"), AlbumArtUrl = "/Content/Images/placeholder.gif" },
new Album { Title = "Berlioz: Symphonie Fantastique", Genre = Genres.Single(g => g.Name == "Classical"), Price = 8.99M, Artist = Artists.Single(a => a.Name == "Michael Tilson Thomas & San Francisco Symphony"), AlbumArtUrl = "/Content/Images/placeholder.gif" },
new Album { Title = "Prokofiev: Romeo & Juliet", Genre = Genres.Single(g => g.Name == "Classical"), Price = 8.99M, Artist = Artists.Single(a => a.Name == "Michael Tilson Thomas & San Francisco Symphony"), AlbumArtUrl = "/Content/Images/placeholder.gif" },
new Album { Title = "Miles Ahead", Genre = Genres.Single(g => g.Name == "Jazz"), Price = 8.99M, Artist = Artists.Single(a => a.Name == "Miles Davis"), AlbumArtUrl = "/Content/Images/placeholder.gif" },
new Album { Title = "The Essential Miles Davis [Disc 1]", Genre = Genres.Single(g => g.Name == "Jazz"), Price = 8.99M, Artist = Artists.Single(a => a.Name == "Miles Davis"), AlbumArtUrl = "/Content/Images/placeholder.gif" },
new Album { Title = "The Essential Miles Davis [Disc 2]", Genre = Genres.Single(g => g.Name == "Jazz"), Price = 8.99M, Artist = Artists.Single(a => a.Name == "Miles Davis"), AlbumArtUrl = "/Content/Images/placeholder.gif" },
new Album { Title = "Milton Nascimento Ao Vivo", Genre = Genres.Single(g => g.Name == "Latin"), Price = 8.99M, Artist = Artists.Single(a => a.Name == "Milton Nascimento"), AlbumArtUrl = "/Content/Images/placeholder.gif" },
new Album { Title = "Minas", Genre = Genres.Single(g => g.Name == "Latin"), Price = 8.99M, Artist = Artists.Single(a => a.Name == "Milton Nascimento"), AlbumArtUrl = "/Content/Images/placeholder.gif" },
new Album { Title = "Motley Crue Greatest Hits", Genre = Genres.Single(g => g.Name == "Metal"), Price = 8.99M, Artist = Artists.Single(a => a.Name == "Mötley Crüe"), AlbumArtUrl = "/Content/Images/placeholder.gif" },
new Album { Title = "Ace Of Spades", Genre = Genres.Single(g => g.Name == "Metal"), Price = 8.99M, Artist = Artists.Single(a => a.Name == "Motörhead"), AlbumArtUrl = "/Content/Images/placeholder.gif" },
new Album { Title = "Mozart: Chamber Music", Genre = Genres.Single(g => g.Name == "Classical"), Price = 8.99M, Artist = Artists.Single(a => a.Name == "Nash Ensemble"), AlbumArtUrl = "/Content/Images/placeholder.gif" },
new Album { Title = "The Best of Beethoven", Genre = Genres.Single(g => g.Name == "Classical"), Price = 8.99M, Artist = Artists.Single(a => a.Name == "Nicolaus Esterhazy Sinfonia"), AlbumArtUrl = "/Content/Images/placeholder.gif" },
new Album { Title = "Nevermind", Genre = Genres.Single(g => g.Name == "Rock"), Price = 8.99M, Artist = Artists.Single(a => a.Name == "Nirvana"), AlbumArtUrl = "/Content/Images/placeholder.gif" },
new Album { Title = "Compositores", Genre = Genres.Single(g => g.Name == "Rock"), Price = 8.99M, Artist = Artists.Single(a => a.Name == "O Terço"), AlbumArtUrl = "/Content/Images/placeholder.gif" },
new Album { Title = "Olodum", Genre = Genres.Single(g => g.Name == "Latin"), Price = 8.99M, Artist = Artists.Single(a => a.Name == "Olodum"), AlbumArtUrl = "/Content/Images/placeholder.gif" },
new Album { Title = "Bach: The Brandenburg Concertos", Genre = Genres.Single(g => g.Name == "Classical"), Price = 8.99M, Artist = Artists.Single(a => a.Name == "Orchestra of The Age of Enlightenment"), AlbumArtUrl = "/Content/Images/placeholder.gif" },
new Album { Title = "Acústico MTV", Genre = Genres.Single(g => g.Name == "Latin"), Price = 8.99M, Artist = Artists.Single(a => a.Name == "Os Paralamas Do Sucesso"), AlbumArtUrl = "/Content/Images/placeholder.gif" },
new Album { Title = "Arquivo II", Genre = Genres.Single(g => g.Name == "Latin"), Price = 8.99M, Artist = Artists.Single(a => a.Name == "Os Paralamas Do Sucesso"), AlbumArtUrl = "/Content/Images/placeholder.gif" },
new Album { Title = "Arquivo Os Paralamas Do Sucesso", Genre = Genres.Single(g => g.Name == "Latin"), Price = 8.99M, Artist = Artists.Single(a => a.Name == "Os Paralamas Do Sucesso"), AlbumArtUrl = "/Content/Images/placeholder.gif" },
new Album { Title = "Tribute", Genre = Genres.Single(g => g.Name == "Metal"), Price = 8.99M, Artist = Artists.Single(a => a.Name == "Ozzy Osbourne"), AlbumArtUrl = "/Content/Images/placeholder.gif" },
new Album { Title = "Bark at the Moon (Remastered)", Genre = Genres.Single(g => g.Name == "Rock"), Price = 8.99M, Artist = Artists.Single(a => a.Name == "Ozzy Osbourne"), AlbumArtUrl = "/Content/Images/placeholder.gif" },
new Album { Title = "Blizzard of Ozz", Genre = Genres.Single(g => g.Name == "Rock"), Price = 8.99M, Artist = Artists.Single(a => a.Name == "Ozzy Osbourne"), AlbumArtUrl = "/Content/Images/placeholder.gif" },
new Album { Title = "Diary of a Madman (Remastered)", Genre = Genres.Single(g => g.Name == "Rock"), Price = 8.99M, Artist = Artists.Single(a => a.Name == "Ozzy Osbourne"), AlbumArtUrl = "/Content/Images/placeholder.gif" },
new Album { Title = "No More Tears (Remastered)", Genre = Genres.Single(g => g.Name == "Rock"), Price = 8.99M, Artist = Artists.Single(a => a.Name == "Ozzy Osbourne"), AlbumArtUrl = "/Content/Images/placeholder.gif" },
new Album { Title = "Speak of the Devil", Genre = Genres.Single(g => g.Name == "Rock"), Price = 8.99M, Artist = Artists.Single(a => a.Name == "Ozzy Osbourne"), AlbumArtUrl = "/Content/Images/placeholder.gif" },
new Album { Title = "Walking Into Clarksdale", Genre = Genres.Single(g => g.Name == "Rock"), Price = 8.99M, Artist = Artists.Single(a => a.Name == "Page & Plant"), AlbumArtUrl = "/Content/Images/placeholder.gif" },
new Album { Title = "The Beast Live", Genre = Genres.Single(g => g.Name == "Rock"), Price = 8.99M, Artist = Artists.Single(a => a.Name == "Paul D'Ianno"), AlbumArtUrl = "/Content/Images/placeholder.gif" },
new Album { Title = "Live On Two Legs [Live]", Genre = Genres.Single(g => g.Name == "Rock"), Price = 8.99M, Artist = Artists.Single(a => a.Name == "Pearl Jam"), AlbumArtUrl = "/Content/Images/placeholder.gif" },
new Album { Title = "Riot Act", Genre = Genres.Single(g => g.Name == "Rock"), Price = 8.99M, Artist = Artists.Single(a => a.Name == "Pearl Jam"), AlbumArtUrl = "/Content/Images/placeholder.gif" },
new Album { Title = "Ten", Genre = Genres.Single(g => g.Name == "Rock"), Price = 8.99M, Artist = Artists.Single(a => a.Name == "Pearl Jam"), AlbumArtUrl = "/Content/Images/placeholder.gif" },
new Album { Title = "Vs.", Genre = Genres.Single(g => g.Name == "Rock"), Price = 8.99M, Artist = Artists.Single(a => a.Name == "Pearl Jam"), AlbumArtUrl = "/Content/Images/placeholder.gif" },
new Album { Title = "Dark Side Of The Moon", Genre = Genres.Single(g => g.Name == "Rock"), Price = 8.99M, Artist = Artists.Single(a => a.Name == "Pink Floyd"), AlbumArtUrl = "/Content/Images/placeholder.gif" },
new Album { Title = "Greatest Hits I", Genre = Genres.Single(g => g.Name == "Rock"), Price = 8.99M, Artist = Artists.Single(a => a.Name == "Queen"), AlbumArtUrl = "/Content/Images/placeholder.gif" },
new Album { Title = "Greatest Hits II", Genre = Genres.Single(g => g.Name == "Rock"), Price = 8.99M, Artist = Artists.Single(a => a.Name == "Queen"), AlbumArtUrl = "/Content/Images/placeholder.gif" },
new Album { Title = "News Of The World", Genre = Genres.Single(g => g.Name == "Rock"), Price = 8.99M, Artist = Artists.Single(a => a.Name == "Queen"), AlbumArtUrl = "/Content/Images/placeholder.gif" },
new Album { Title = "New Adventures In Hi-Fi", Genre = Genres.Single(g => g.Name == "Rock"), Price = 8.99M, Artist = Artists.Single(a => a.Name == "R.E.M."), AlbumArtUrl = "/Content/Images/placeholder.gif" },
new Album { Title = "Raul Seixas", Genre = Genres.Single(g => g.Name == "Rock"), Price = 8.99M, Artist = Artists.Single(a => a.Name == "Raul Seixas"), AlbumArtUrl = "/Content/Images/placeholder.gif" },
new Album { Title = "By The Way", Genre = Genres.Single(g => g.Name == "Rock"), Price = 8.99M, Artist = Artists.Single(a => a.Name == "Red Hot Chili Peppers"), AlbumArtUrl = "/Content/Images/placeholder.gif" },
new Album { Title = "Californication", Genre = Genres.Single(g => g.Name == "Rock"), Price = 8.99M, Artist = Artists.Single(a => a.Name == "Red Hot Chili Peppers"), AlbumArtUrl = "/Content/Images/placeholder.gif" },
new Album { Title = "Purcell: The Fairy Queen", Genre = Genres.Single(g => g.Name == "Classical"), Price = 8.99M, Artist = Artists.Single(a => a.Name == "Roger Norrington, London Classical Players"), AlbumArtUrl = "/Content/Images/placeholder.gif" },
new Album { Title = "Haydn: Symphonies 99 - 104", Genre = Genres.Single(g => g.Name == "Classical"), Price = 8.99M, Artist = Artists.Single(a => a.Name == "Royal Philharmonic Orchestra & Sir Thomas Beecham"), AlbumArtUrl = "/Content/Images/placeholder.gif" },
new Album { Title = "Retrospective I (1974-1980)", Genre = Genres.Single(g => g.Name == "Rock"), Price = 8.99M, Artist = Artists.Single(a => a.Name == "Rush"), AlbumArtUrl = "/Content/Images/placeholder.gif" },
new Album { Title = "Santana - As Years Go By", Genre = Genres.Single(g => g.Name == "Rock"), Price = 8.99M, Artist = Artists.Single(a => a.Name == "Santana"), AlbumArtUrl = "/Content/Images/placeholder.gif" },
new Album { Title = "Santana Live", Genre = Genres.Single(g => g.Name == "Rock"), Price = 8.99M, Artist = Artists.Single(a => a.Name == "Santana"), AlbumArtUrl = "/Content/Images/placeholder.gif" },
new Album { Title = "Supernatural", Genre = Genres.Single(g => g.Name == "Rock"), Price = 8.99M, Artist = Artists.Single(a => a.Name == "Santana"), AlbumArtUrl = "/Content/Images/placeholder.gif" },
new Album { Title = "Handel: The Messiah (Highlights)", Genre = Genres.Single(g => g.Name == "Classical"), Price = 8.99M, Artist = Artists.Single(a => a.Name == "Scholars Baroque Ensemble"), AlbumArtUrl = "/Content/Images/placeholder.gif" },
new Album { Title = "Prokofiev: Symphony No.1", Genre = Genres.Single(g => g.Name == "Classical"), Price = 8.99M, Artist = Artists.Single(a => a.Name == "Sergei Prokofiev & Yuri Temirkanov"), AlbumArtUrl = "/Content/Images/placeholder.gif" },
new Album { Title = "Wagner: Favourite Overtures", Genre = Genres.Single(g => g.Name == "Classical"), Price = 8.99M, Artist = Artists.Single(a => a.Name == "Sir Georg Solti & Wiener Philharmoniker"), AlbumArtUrl = "/Content/Images/placeholder.gif" },
new Album { Title = "Maquinarama", Genre = Genres.Single(g => g.Name == "Rock"), Price = 8.99M, Artist = Artists.Single(a => a.Name == "Skank"), AlbumArtUrl = "/Content/Images/placeholder.gif" },
new Album { Title = "O Samba Poconé", Genre = Genres.Single(g => g.Name == "Rock"), Price = 8.99M, Artist = Artists.Single(a => a.Name == "Skank"), AlbumArtUrl = "/Content/Images/placeholder.gif" },
new Album { Title = "A-Sides", Genre = Genres.Single(g => g.Name == "Rock"), Price = 8.99M, Artist = Artists.Single(a => a.Name == "Soundgarden"), AlbumArtUrl = "/Content/Images/placeholder.gif" },
new Album { Title = "Heart of the Night", Genre = Genres.Single(g => g.Name == "Jazz"), Price = 8.99M, Artist = Artists.Single(a => a.Name == "Spyro Gyra"), AlbumArtUrl = "/Content/Images/placeholder.gif" },
new Album { Title = "Morning Dance", Genre = Genres.Single(g => g.Name == "Jazz"), Price = 8.99M, Artist = Artists.Single(a => a.Name == "Spyro Gyra"), AlbumArtUrl = "/Content/Images/placeholder.gif" },
new Album { Title = "In Step", Genre = Genres.Single(g => g.Name == "Blues"), Price = 8.99M, Artist = Artists.Single(a => a.Name == "Stevie Ray Vaughan & Double Trouble"), AlbumArtUrl = "/Content/Images/placeholder.gif" },
new Album { Title = "Core", Genre = Genres.Single(g => g.Name == "Rock"), Price = 8.99M, Artist = Artists.Single(a => a.Name == "Stone Temple Pilots"), AlbumArtUrl = "/Content/Images/placeholder.gif" },
new Album { Title = "Mezmerize", Genre = Genres.Single(g => g.Name == "Metal"), Price = 8.99M, Artist = Artists.Single(a => a.Name == "System Of A Down"), AlbumArtUrl = "/Content/Images/placeholder.gif" },
new Album { Title = "Temple of the Dog", Genre = Genres.Single(g => g.Name == "Alternative"), Price = 8.99M, Artist = Artists.Single(a => a.Name == "Temple of the Dog"), AlbumArtUrl = "/Content/Images/placeholder.gif" },
new Album { Title = "[1997] Black Light Syndrome", Genre = Genres.Single(g => g.Name == "Rock"), Price = 8.99M, Artist = Artists.Single(a => a.Name == "Terry Bozzio, Tony Levin & Steve Stevens"), AlbumArtUrl = "/Content/Images/placeholder.gif" },
new Album { Title = "South American Getaway", Genre = Genres.Single(g => g.Name == "Classical"), Price = 8.99M, Artist = Artists.Single(a => a.Name == "The 12 Cellists of The Berlin Philharmonic"), AlbumArtUrl = "/Content/Images/placeholder.gif" },
new Album { Title = "Live [Disc 1]", Genre = Genres.Single(g => g.Name == "Blues"), Price = 8.99M, Artist = Artists.Single(a => a.Name == "The Black Crowes"), AlbumArtUrl = "/Content/Images/placeholder.gif" },
new Album { Title = "Live [Disc 2]", Genre = Genres.Single(g => g.Name == "Blues"), Price = 8.99M, Artist = Artists.Single(a => a.Name == "The Black Crowes"), AlbumArtUrl = "/Content/Images/placeholder.gif" },
new Album { Title = "Beyond Good And Evil", Genre = Genres.Single(g => g.Name == "Rock"), Price = 8.99M, Artist = Artists.Single(a => a.Name == "The Cult"), AlbumArtUrl = "/Content/Images/placeholder.gif" },
new Album { Title = "The Doors", Genre = Genres.Single(g => g.Name == "Rock"), Price = 8.99M, Artist = Artists.Single(a => a.Name == "The Doors"), AlbumArtUrl = "/Content/Images/placeholder.gif" },
new Album { Title = "English Renaissance", Genre = Genres.Single(g => g.Name == "Classical"), Price = 8.99M, Artist = Artists.Single(a => a.Name == "The King's Singers"), AlbumArtUrl = "/Content/Images/placeholder.gif" },
new Album { Title = "The Police Greatest Hits", Genre = Genres.Single(g => g.Name == "Rock"), Price = 8.99M, Artist = Artists.Single(a => a.Name == "The Police"), AlbumArtUrl = "/Content/Images/placeholder.gif" },
new Album { Title = "Every Kind of Light", Genre = Genres.Single(g => g.Name == "Rock"), Price = 8.99M, Artist = Artists.Single(a => a.Name == "The Posies"), AlbumArtUrl = "/Content/Images/placeholder.gif" },
new Album { Title = "Hot Rocks, 1964-1971 (Disc 1)", Genre = Genres.Single(g => g.Name == "Rock"), Price = 8.99M, Artist = Artists.Single(a => a.Name == "The Rolling Stones"), AlbumArtUrl = "/Content/Images/placeholder.gif" },
new Album { Title = "No Security", Genre = Genres.Single(g => g.Name == "Rock"), Price = 8.99M, Artist = Artists.Single(a => a.Name == "The Rolling Stones"), AlbumArtUrl = "/Content/Images/placeholder.gif" },
new Album { Title = "Voodoo Lounge", Genre = Genres.Single(g => g.Name == "Rock"), Price = 8.99M, Artist = Artists.Single(a => a.Name == "The Rolling Stones"), AlbumArtUrl = "/Content/Images/placeholder.gif" },
new Album { Title = "My Generation - The Very Best Of The Who", Genre = Genres.Single(g => g.Name == "Rock"), Price = 8.99M, Artist = Artists.Single(a => a.Name == "The Who"), AlbumArtUrl = "/Content/Images/placeholder.gif" },
new Album { Title = "Serie Sem Limite (Disc 1)", Genre = Genres.Single(g => g.Name == "Latin"), Price = 8.99M, Artist = Artists.Single(a => a.Name == "Tim Maia"), AlbumArtUrl = "/Content/Images/placeholder.gif" },
new Album { Title = "Serie Sem Limite (Disc 2)", Genre = Genres.Single(g => g.Name == "Latin"), Price = 8.99M, Artist = Artists.Single(a => a.Name == "Tim Maia"), AlbumArtUrl = "/Content/Images/placeholder.gif" },
new Album { Title = "Bach: Toccata & Fugue in D Minor", Genre = Genres.Single(g => g.Name == "Classical"), Price = 8.99M, Artist = Artists.Single(a => a.Name == "Ton Koopman"), AlbumArtUrl = "/Content/Images/placeholder.gif" },
new Album { Title = "Achtung Baby", Genre = Genres.Single(g => g.Name == "Rock"), Price = 8.99M, Artist = Artists.Single(a => a.Name == "U2"), AlbumArtUrl = "/Content/Images/placeholder.gif" },
new Album { Title = "B-Sides 1980-1990", Genre = Genres.Single(g => g.Name == "Rock"), Price = 8.99M, Artist = Artists.Single(a => a.Name == "U2"), AlbumArtUrl = "/Content/Images/placeholder.gif" },
new Album { Title = "How To Dismantle An Atomic Bomb", Genre = Genres.Single(g => g.Name == "Rock"), Price = 8.99M, Artist = Artists.Single(a => a.Name == "U2"), AlbumArtUrl = "/Content/Images/placeholder.gif" },
new Album { Title = "Pop", Genre = Genres.Single(g => g.Name == "Rock"), Price = 8.99M, Artist = Artists.Single(a => a.Name == "U2"), AlbumArtUrl = "/Content/Images/placeholder.gif" },
new Album { Title = "Rattle And Hum", Genre = Genres.Single(g => g.Name == "Rock"), Price = 8.99M, Artist = Artists.Single(a => a.Name == "U2"), AlbumArtUrl = "/Content/Images/placeholder.gif" },
new Album { Title = "The Best Of 1980-1990", Genre = Genres.Single(g => g.Name == "Rock"), Price = 8.99M, Artist = Artists.Single(a => a.Name == "U2"), AlbumArtUrl = "/Content/Images/placeholder.gif" },
new Album { Title = "War", Genre = Genres.Single(g => g.Name == "Rock"), Price = 8.99M, Artist = Artists.Single(a => a.Name == "U2"), AlbumArtUrl = "/Content/Images/placeholder.gif" },
new Album { Title = "Zooropa", Genre = Genres.Single(g => g.Name == "Rock"), Price = 8.99M, Artist = Artists.Single(a => a.Name == "U2"), AlbumArtUrl = "/Content/Images/placeholder.gif" },
new Album { Title = "UB40 The Best Of - Volume Two [UK]", Genre = Genres.Single(g => g.Name == "Reggae"), Price = 8.99M, Artist = Artists.Single(a => a.Name == "UB40"), AlbumArtUrl = "/Content/Images/placeholder.gif" },
new Album { Title = "Diver Down", Genre = Genres.Single(g => g.Name == "Rock"), Price = 8.99M, Artist = Artists.Single(a => a.Name == "Van Halen"), AlbumArtUrl = "/Content/Images/placeholder.gif" },
new Album { Title = "The Best Of Van Halen, Vol. I", Genre = Genres.Single(g => g.Name == "Rock"), Price = 8.99M, Artist = Artists.Single(a => a.Name == "Van Halen"), AlbumArtUrl = "/Content/Images/placeholder.gif" },
new Album { Title = "Van Halen III", Genre = Genres.Single(g => g.Name == "Rock"), Price = 8.99M, Artist = Artists.Single(a => a.Name == "Van Halen"), AlbumArtUrl = "/Content/Images/placeholder.gif" },
new Album { Title = "Van Halen", Genre = Genres.Single(g => g.Name == "Rock"), Price = 8.99M, Artist = Artists.Single(a => a.Name == "Van Halen"), AlbumArtUrl = "/Content/Images/placeholder.gif" },
new Album { Title = "Axé Bahia 2001", Genre = Genres.Single(g => g.Name == "Pop"), Price = 8.99M, Artist = Artists.Single(a => a.Name == "Various Artists"), AlbumArtUrl = "/Content/Images/placeholder.gif" },
new Album { Title = "Sambas De Enredo 2001", Genre = Genres.Single(g => g.Name == "Latin"), Price = 8.99M, Artist = Artists.Single(a => a.Name == "Various Artists"), AlbumArtUrl = "/Content/Images/placeholder.gif" },
new Album { Title = "Vozes do MPB", Genre = Genres.Single(g => g.Name == "Latin"), Price = 8.99M, Artist = Artists.Single(a => a.Name == "Various Artists"), AlbumArtUrl = "/Content/Images/placeholder.gif" },
new Album { Title = "Contraband", Genre = Genres.Single(g => g.Name == "Rock"), Price = 8.99M, Artist = Artists.Single(a => a.Name == "Velvet Revolver"), AlbumArtUrl = "/Content/Images/placeholder.gif" },
new Album { Title = "Vinicius De Moraes", Genre = Genres.Single(g => g.Name == "Latin"), Price = 8.99M, Artist = Artists.Single(a => a.Name == "Vinícius De Moraes"), AlbumArtUrl = "/Content/Images/placeholder.gif" },
new Album { Title = "Bach: Goldberg Variations", Genre = Genres.Single(g => g.Name == "Classical"), Price = 8.99M, Artist = Artists.Single(a => a.Name == "Wilhelm Kempff"), AlbumArtUrl = "/Content/Images/placeholder.gif" },
new Album { Title = "Bartok: Violin & Viola Concertos", Genre = Genres.Single(g => g.Name == "Classical"), Price = 8.99M, Artist = Artists.Single(a => a.Name == "Yehudi Menuhin"), AlbumArtUrl = "/Content/Images/placeholder.gif" },
new Album { Title = "Bach: The Cello Suites", Genre = Genres.Single(g => g.Name == "Classical"), Price = 8.99M, Artist = Artists.Single(a => a.Name == "Yo-Yo Ma"), AlbumArtUrl = "/Content/Images/placeholder.gif" },
new Album { Title = "Ao Vivo [IMPORT]", Genre = Genres.Single(g => g.Name == "Latin"), Price = 8.99M, Artist = Artists.Single(a => a.Name == "Zeca Pagodinho"), AlbumArtUrl = "/Content/Images/placeholder.gif" },
};
}
public static List<Album> GetHeapAlbums()
{
var heapSalt = Guid.NewGuid().ToString();
var genresToRetrieve = new List<Genre>();
foreach(var genreToParse in Genres)
{
genresToRetrieve.Add(new Genre { Name = genreToParse.Name + heapSalt, Id = genreToParse.Id });
}
var artistsToRetrieve = new List<Artist>();
foreach (var artistToParse in Artists)
{
artistsToRetrieve.Add(new Artist { Name = artistToParse.Name + heapSalt, Id = artistToParse.Id });
}
var albumsToRetrieve = new List<Album>();
foreach (var albumToParse in Albums)
{
albumsToRetrieve.Add(new Album { AlbumArtUrl = albumToParse.AlbumArtUrl + heapSalt, Name = albumToParse.Name + heapSalt, Title = albumToParse + heapSalt, Price = albumToParse.Price, Id = albumToParse.Id, Artist = artistsToRetrieve.Single(q => q.Id == albumToParse.Artist.Id), Genre = genresToRetrieve.Single(q => q.Id == albumToParse.Genre.Id) });
}
return albumsToRetrieve;
}
public static List<StackAlbum> GetStackAlbums()
{
var sessionGuid = Guid.NewGuid().ToString();
var genresToRetrieve = new List<StackGenre>();
foreach (var genreToParse in Genres)
{
var genre = new StackGenre
{
Id = genreToParse.Id
};
genre.Name = new ValueStringReference(genreToParse.Name.AsSpan());
genresToRetrieve.Add(genre);
}
var artistsToRetrieve = new List<StackArtist>();
foreach (var artistToParse in Artists)
{
var artist = new StackArtist { Id = artistToParse.Id };
artist.Name = new ValueStringReference(artistToParse.Name.AsSpan());
artistsToRetrieve.Add(artist);
}
var albumsToRetrieve = new List<StackAlbum>();
foreach (var albumToParse in Albums)
{
var album = new StackAlbum { Price = albumToParse.Price, Id = albumToParse.Id, Artist = artistsToRetrieve.Single(q => q.Id == albumToParse.Artist.Id), Genre = genresToRetrieve.Single(q => q.Id == albumToParse.Genre.Id) };
album.Name = new ValueStringReference(albumToParse.Name.AsSpan());
album.Title = new ValueStringReference(albumToParse.Title.AsSpan());
album.AlbumArtUrl = new ValueStringReference(albumToParse.AlbumArtUrl.AsSpan());
albumsToRetrieve.Add(album);
}
return albumsToRetrieve;
}
}
}
| 142.40535 | 363 | 0.593362 | [
"MIT"
] | Lionhunter3k/ValueString | StringExtensions.Benchmark/DataGenerator.cs | 69,250 | C# |
using System;
namespace CuesheetSplitterEncoder.Core.Exceptions
{
public class CommandLineOperationException : Exception
{
readonly int _exitCode;
public CommandLineOperationException()
{
}
public CommandLineOperationException(string message)
: base(message)
{
}
public CommandLineOperationException(string message, Exception inner)
: base(message, inner)
{
}
public CommandLineOperationException(string message, int exitCode)
: base(message)
{
_exitCode = exitCode;
}
public int ExitCode
{
get { return _exitCode; }
}
public override string ToString()
{
return string.Format("Exit Code: {0}{1}{2}", _exitCode, Environment.NewLine, base.ToString());
}
}
} | 22.5 | 106 | 0.573333 | [
"MIT"
] | abelzile/cuesheet-splitter-encoder | src/CuesheetSplitterEncoder.Core/Exceptions/CommandLineOperationException.cs | 902 | C# |
using System;
using Unity.VisualScripting.FullSerializer.Internal;
namespace Unity.VisualScripting.FullSerializer
{
public class fsPrimitiveConverter : fsConverter
{
public override bool CanProcess(Type type)
{
return
type.Resolve().IsPrimitive ||
type == typeof(string) ||
type == typeof(decimal);
}
public override bool RequestCycleSupport(Type storageType)
{
return false;
}
public override bool RequestInheritanceSupport(Type storageType)
{
return false;
}
public override fsResult TrySerialize(object instance, out fsData serialized, Type storageType)
{
var instanceType = instance.GetType();
if (Serializer.Config.Serialize64BitIntegerAsString && (instanceType == typeof(Int64) || instanceType == typeof(UInt64)))
{
serialized = new fsData((string)Convert.ChangeType(instance, typeof(string)));
return fsResult.Success;
}
if (UseBool(instanceType))
{
serialized = new fsData((bool)instance);
return fsResult.Success;
}
if (UseInt64(instanceType))
{
serialized = new fsData((Int64)Convert.ChangeType(instance, typeof(Int64)));
return fsResult.Success;
}
if (UseDouble(instanceType))
{
// Casting from float to double introduces floating point jitter,
// ie, 0.1 becomes 0.100000001490116. Casting to decimal as an
// intermediate step removes the jitter. Not sure why.
if (instance.GetType() == typeof(float) &&
// Decimal can't store
// float.MinValue/float.MaxValue/float.PositiveInfinity/float.NegativeInfinity/float.NaN
// - an exception gets thrown in that scenario.
(float)instance != float.MinValue &&
(float)instance != float.MaxValue &&
!float.IsInfinity((float)instance) &&
!float.IsNaN((float)instance)
)
{
serialized = new fsData((double)(decimal)(float)instance);
return fsResult.Success;
}
serialized = new fsData((double)Convert.ChangeType(instance, typeof(double)));
return fsResult.Success;
}
if (UseString(instanceType))
{
serialized = new fsData((string)Convert.ChangeType(instance, typeof(string)));
return fsResult.Success;
}
serialized = null;
return fsResult.Fail("Unhandled primitive type " + instance.GetType());
}
public override fsResult TryDeserialize(fsData storage, ref object instance, Type storageType)
{
var result = fsResult.Success;
if (UseBool(storageType))
{
if ((result += CheckType(storage, fsDataType.Boolean)).Succeeded)
{
instance = storage.AsBool;
}
return result;
}
if (UseDouble(storageType) || UseInt64(storageType))
{
if (storage.IsDouble)
{
instance = Convert.ChangeType(storage.AsDouble, storageType);
}
else if (storage.IsInt64)
{
instance = Convert.ChangeType(storage.AsInt64, storageType);
}
else if (Serializer.Config.Serialize64BitIntegerAsString && storage.IsString &&
(storageType == typeof(Int64) || storageType == typeof(UInt64)))
{
instance = Convert.ChangeType(storage.AsString, storageType);
}
else
{
return fsResult.Fail(GetType().Name + " expected number but got " + storage.Type + " in " + storage);
}
return fsResult.Success;
}
if (UseString(storageType))
{
if ((result += CheckType(storage, fsDataType.String)).Succeeded)
{
var str = storage.AsString;
if (storageType == typeof(char))
{
if (storageType == typeof(char))
{
if (str.Length == 1)
{
instance = str[0];
}
else
{
instance = default(char);
}
}
}
else
{
instance = str;
}
}
return result;
}
return fsResult.Fail(GetType().Name + ": Bad data; expected bool, number, string, but got " + storage);
}
private static bool UseBool(Type type)
{
return type == typeof(bool);
}
private static bool UseInt64(Type type)
{
return type == typeof(sbyte) || type == typeof(byte) ||
type == typeof(Int16) || type == typeof(UInt16) ||
type == typeof(Int32) || type == typeof(UInt32) ||
type == typeof(Int64) || type == typeof(UInt64);
}
private static bool UseDouble(Type type)
{
return type == typeof(float) ||
type == typeof(double) ||
type == typeof(decimal);
}
private static bool UseString(Type type)
{
return type == typeof(string) ||
type == typeof(char);
}
}
}
| 34.982759 | 133 | 0.473632 | [
"MIT"
] | 2PUEG-VRIK/UnityEscapeGame | 2P-UnityEscapeGame/Library/PackageCache/com.unity.visualscripting@1.6.1/Runtime/VisualScripting.Core/Dependencies/FullSerializer/Converters/fsPrimitiveConverter.cs | 6,087 | C# |
namespace Dolgozat0303
{
partial class Form1
{
/// <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.tanuloneve = new System.Windows.Forms.Label();
this.igazolt = new System.Windows.Forms.Label();
this.igazolatlan = new System.Windows.Forms.Label();
this.FeltoltBtn = new System.Windows.Forms.Button();
this.tanulo2 = new System.Windows.Forms.Label();
this.igazolt2 = new System.Windows.Forms.Label();
this.igazolatlan2 = new System.Windows.Forms.Label();
this.label7 = new System.Windows.Forms.Label();
this.label8 = new System.Windows.Forms.Label();
this.LekerBtn = new System.Windows.Forms.Button();
this.textBox1 = new System.Windows.Forms.TextBox();
this.textBox2 = new System.Windows.Forms.TextBox();
this.textBox3 = new System.Windows.Forms.TextBox();
this.textBox4 = new System.Windows.Forms.TextBox();
this.SuspendLayout();
//
// tanuloneve
//
this.tanuloneve.AutoSize = true;
this.tanuloneve.Location = new System.Drawing.Point(12, 9);
this.tanuloneve.Name = "tanuloneve";
this.tanuloneve.Size = new System.Drawing.Size(70, 13);
this.tanuloneve.TabIndex = 0;
this.tanuloneve.Text = "Tanuló neve:";
//
// igazolt
//
this.igazolt.AutoSize = true;
this.igazolt.Location = new System.Drawing.Point(12, 72);
this.igazolt.Name = "igazolt";
this.igazolt.Size = new System.Drawing.Size(85, 13);
this.igazolt.TabIndex = 1;
this.igazolt.Text = "Igazolt hiányzás:";
//
// igazolatlan
//
this.igazolatlan.AutoSize = true;
this.igazolatlan.Location = new System.Drawing.Point(12, 114);
this.igazolatlan.Name = "igazolatlan";
this.igazolatlan.Size = new System.Drawing.Size(105, 13);
this.igazolatlan.TabIndex = 2;
this.igazolatlan.Text = "Igazolatlan hiányzás:";
//
// FeltoltBtn
//
this.FeltoltBtn.Location = new System.Drawing.Point(137, 155);
this.FeltoltBtn.Name = "FeltoltBtn";
this.FeltoltBtn.Size = new System.Drawing.Size(75, 23);
this.FeltoltBtn.TabIndex = 3;
this.FeltoltBtn.Text = "Feltöltés";
this.FeltoltBtn.UseVisualStyleBackColor = true;
this.FeltoltBtn.Click += new System.EventHandler(this.FeltoltBtn_Click);
//
// tanulo2
//
this.tanulo2.AutoSize = true;
this.tanulo2.Location = new System.Drawing.Point(12, 221);
this.tanulo2.Name = "tanulo2";
this.tanulo2.Size = new System.Drawing.Size(70, 13);
this.tanulo2.TabIndex = 4;
this.tanulo2.Text = "Tanuló neve:";
//
// igazolt2
//
this.igazolt2.AutoSize = true;
this.igazolt2.Location = new System.Drawing.Point(12, 245);
this.igazolt2.Name = "igazolt2";
this.igazolt2.Size = new System.Drawing.Size(85, 13);
this.igazolt2.TabIndex = 5;
this.igazolt2.Text = "Igazolt hiányzás:";
//
// igazolatlan2
//
this.igazolatlan2.AutoSize = true;
this.igazolatlan2.Location = new System.Drawing.Point(12, 274);
this.igazolatlan2.Name = "igazolatlan2";
this.igazolatlan2.Size = new System.Drawing.Size(105, 13);
this.igazolatlan2.TabIndex = 6;
this.igazolatlan2.Text = "Igazolatlan hiányzás:";
//
// label7
//
this.label7.AutoSize = true;
this.label7.Location = new System.Drawing.Point(123, 245);
this.label7.Name = "label7";
this.label7.Size = new System.Drawing.Size(35, 13);
this.label7.TabIndex = 7;
this.label7.Text = "label7";
this.label7.Visible = false;
//
// label8
//
this.label8.AutoSize = true;
this.label8.Location = new System.Drawing.Point(123, 274);
this.label8.Name = "label8";
this.label8.Size = new System.Drawing.Size(35, 13);
this.label8.TabIndex = 8;
this.label8.Text = "label8";
this.label8.Visible = false;
//
// LekerBtn
//
this.LekerBtn.Location = new System.Drawing.Point(30, 325);
this.LekerBtn.Name = "LekerBtn";
this.LekerBtn.Size = new System.Drawing.Size(75, 23);
this.LekerBtn.TabIndex = 9;
this.LekerBtn.Text = "Lekérés";
this.LekerBtn.UseVisualStyleBackColor = true;
this.LekerBtn.Click += new System.EventHandler(this.LekerBtn_Click);
//
// textBox1
//
this.textBox1.Location = new System.Drawing.Point(126, 12);
this.textBox1.Name = "textBox1";
this.textBox1.Size = new System.Drawing.Size(100, 20);
this.textBox1.TabIndex = 10;
//
// textBox2
//
this.textBox2.Location = new System.Drawing.Point(126, 65);
this.textBox2.Name = "textBox2";
this.textBox2.Size = new System.Drawing.Size(100, 20);
this.textBox2.TabIndex = 11;
//
// textBox3
//
this.textBox3.Location = new System.Drawing.Point(126, 107);
this.textBox3.Name = "textBox3";
this.textBox3.Size = new System.Drawing.Size(100, 20);
this.textBox3.TabIndex = 12;
//
// textBox4
//
this.textBox4.Location = new System.Drawing.Point(126, 218);
this.textBox4.Name = "textBox4";
this.textBox4.Size = new System.Drawing.Size(100, 20);
this.textBox4.TabIndex = 13;
//
// Form1
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(509, 445);
this.Controls.Add(this.textBox4);
this.Controls.Add(this.textBox3);
this.Controls.Add(this.textBox2);
this.Controls.Add(this.textBox1);
this.Controls.Add(this.LekerBtn);
this.Controls.Add(this.label8);
this.Controls.Add(this.label7);
this.Controls.Add(this.igazolatlan2);
this.Controls.Add(this.igazolt2);
this.Controls.Add(this.tanulo2);
this.Controls.Add(this.FeltoltBtn);
this.Controls.Add(this.igazolatlan);
this.Controls.Add(this.igazolt);
this.Controls.Add(this.tanuloneve);
this.Name = "Form1";
this.Text = "Form1";
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
private System.Windows.Forms.Label tanuloneve;
private System.Windows.Forms.Label igazolt;
private System.Windows.Forms.Label igazolatlan;
private System.Windows.Forms.Button FeltoltBtn;
private System.Windows.Forms.Label tanulo2;
private System.Windows.Forms.Label igazolt2;
private System.Windows.Forms.Label igazolatlan2;
private System.Windows.Forms.Label label7;
private System.Windows.Forms.Label label8;
private System.Windows.Forms.Button LekerBtn;
private System.Windows.Forms.TextBox textBox1;
private System.Windows.Forms.TextBox textBox2;
private System.Windows.Forms.TextBox textBox3;
private System.Windows.Forms.TextBox textBox4;
}
}
| 41.364486 | 107 | 0.556823 | [
"MIT"
] | kinga97/WinFormAlkalmazasok | Dolgozat0303/Dolgozat0303/Form1.Designer.cs | 8,868 | C# |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEditor;
using Utility.Noise;
[CustomEditor(typeof(FractalChain))]
public class FractalChainEditor : Editor {
Texture2D m_currentTex;
bool m_texUpdated;
public override void OnInspectorGUI()
{
base.OnInspectorGUI();
FractalChain t = (target as FractalChain);
if(GUILayout.Button("GENERATE"))
{
t.GenerateMap();
m_texUpdated = false;
}
if(t.CurrentTexture != null && !m_texUpdated)
{
m_currentTex = ResizeTexture(t.CurrentTexture, new Vector2Int(386,386));
m_texUpdated = true;
}
if(m_currentTex != null)
{
GUILayout.Label(m_currentTex);
}
}
public static Texture2D ResizeTexture(Texture2D src, Vector2Int newSize)
{
Texture2D newTex = new Texture2D(newSize.x,newSize.y);
try
{
newTex.GetPixels();
}
catch
{
return newTex;
}
if(src.height == 0 || src.width == 0)
{
return newTex;
}
for(int x = 0; x <= newSize.x; x++)
{
for(int y = 0; y <= newSize.y; y++)
{
int xPos = Mathf.RoundToInt(Mathf.Clamp01((float)(x+1)/newSize.x) * src.width);
int yPos = Mathf.RoundToInt(Mathf.Clamp01((float)(y+1)/newSize.y) * src.height);
newTex.SetPixel(x,y, src.GetPixel(xPos,yPos));
}
}
newTex.Apply();
return newTex;
}
} | 19.567164 | 84 | 0.666667 | [
"MIT"
] | iwoplaza/DreamHack-2018 | DreamHack 2018 - UnityProject/Assets/Scripts/Editor/FractalChainEditor.cs | 1,313 | C# |
using Microsoft.AspNetCore.Mvc;
using System.Collections.Generic;
using System.Linq;
namespace Yeast.WebApi
{
/// <summary>
/// Base class for API request parameters
/// </summary>
public class ApiRequestParams
{
/// <summary>
/// List of navigation properties to include
/// </summary>
[FromQuery(Name = "$include")]
public string[] Include { get; set; }
}
}
| 22.421053 | 52 | 0.605634 | [
"MIT"
] | YeastFx/Yeast | src/Yeast.WebApi/ApiRequestParams.cs | 428 | C# |
namespace SalaryForecaster.Core.Infrastructure
{
public interface ISettingsManager
{
string GetJsonPath();
string GetReleaseInfoPath();
}
} | 21 | 47 | 0.684524 | [
"MIT"
] | AlexanderYunker1983/SalaryForecaster | SalaryForecaster.Core/Infrastructure/ISettingsManager.cs | 170 | C# |
using AutoMapperConfiguration;
using Microsoft.EntityFrameworkCore;
using NicheMarket.Data;
using NicheMarket.Data.Models;
using NicheMarket.Services.Models;
using NicheMarket.Web.Models.BindingModels;
using NicheMarket.Web.Models.ViewModels;
using NUnit.Framework;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace NicheMarket.Services.Tests
{
[TestFixture]
class CategoryServiceTests
{
private NicheMarketDBContext dBContext;
private ICategoryService categoryService;
[SetUp]
public void SetUp()
{
AutoMapperConfig.RegisterMappings(
typeof(Category).Assembly.GetTypes(),
typeof(CreateCategoryModel).Assembly.GetTypes(),
typeof(CategoryViewModel).Assembly.GetTypes()
);
DbContextOptions<NicheMarketDBContext> options = new DbContextOptionsBuilder<NicheMarketDBContext>()
.UseInMemoryDatabase($"TESTS-DB-{Guid.NewGuid()}")
.Options;
this.dBContext = new NicheMarketDBContext(options);
this.categoryService = new CategoryService(dBContext);
}
[Test]
public async Task CreateCategory_ValidData_ShouldReturnTruthyValue()
{
CreateCategoryModel createCategoryModel = new CreateCategoryModel()
{
Name = "Test"
};
bool result = await categoryService.CreateCategory(createCategoryModel);
Assert.True(result, TestsMessages.ResultErrorMessage(nameof(categoryService.CreateCategory)));
}
[Test]
public async Task CreateCategory_ValidData_ShouldCorrectlyCreateEntity()
{
CreateCategoryModel createCategoryModel = new CreateCategoryModel()
{
Name = "Test"
};
await categoryService.CreateCategory(createCategoryModel);
Category actualEntity = await dBContext.Category.FirstOrDefaultAsync();
Assert.IsNotNull(actualEntity, TestsMessages.InvalidValueErrorMessage(nameof(categoryService.CreateCategory)));
}
[Test]
public async Task CreateCategoryWithName_ValidData_ShouldCorrectlyMapData()
{
CreateCategoryModel createCategoryModel = new CreateCategoryModel()
{
Name = "Test"
};
Category expectedEntity = new Category()
{
Name = "Test"
};
await categoryService.CreateCategory(createCategoryModel);
Category actualEntity = await dBContext.Category.FirstOrDefaultAsync();
Assert.AreEqual(expectedEntity.Name, actualEntity.Name, TestsMessages.MappingErrorMessage(nameof(categoryService.CreateCategory), nameof(actualEntity.Name)));
}
[Test]
public async Task EditCategory_ValidData_ShouldReturnTrue()
{
CreateCategoryModel createCategoryModel = new CreateCategoryModel()
{
Name = "Test"
};
await categoryService.CreateCategory(createCategoryModel);
Category expectedEntity = await dBContext.Category.FirstOrDefaultAsync();
CategoryViewModel categoryViewModel = new CategoryViewModel { Id = expectedEntity.Id, Name = "New name" };
bool result = await categoryService.EditCategory(categoryViewModel);
Assert.IsTrue(result, TestsMessages.ResultErrorMessage(nameof(categoryService.EditCategory)));
}
[Test]
public async Task EditCategory_ValidData_ShouldCorrectlyEditEntity()
{
CreateCategoryModel createCategoryModel = new CreateCategoryModel()
{
Name = "Test"
};
await categoryService.CreateCategory(createCategoryModel);
Category expectedEntity = await dBContext.Category.FirstOrDefaultAsync();
CategoryViewModel categoryViewModel = new CategoryViewModel { Id = expectedEntity.Id, Name = "New name" };
await categoryService.EditCategory(categoryViewModel);
Category actualEntity = await dBContext.Category.FirstOrDefaultAsync();
Assert.AreEqual(expectedEntity.Name, actualEntity.Name, TestsMessages.MappingErrorMessage(nameof(categoryService.EditCategory), nameof(actualEntity.Name)));
}
[Test]
public async Task EditCategory_ValidData_ShouldBeDifferentFromTheOldEntity()
{
CreateCategoryModel createCategoryModel = new CreateCategoryModel()
{
Name = "Test"
};
await categoryService.CreateCategory(createCategoryModel);
Category oldEntity = await dBContext.Category.FirstOrDefaultAsync();
CategoryViewModel categoryViewModel = new CategoryViewModel { Id = oldEntity.Id, Name = "New name" };
await categoryService.EditCategory(categoryViewModel);
Category actualEntity = await dBContext.Category.FirstOrDefaultAsync();
Assert.AreNotEqual(createCategoryModel.Name, actualEntity.Name, TestsMessages.MappingErrorMessage(nameof(categoryService.EditCategory), nameof(actualEntity.Name)));
}
[Test]
public async Task AllCategories_ValidData_ShouldReturnListOfProductViewModels()
{
CreateCategoryModel createCategoryModel = new CreateCategoryModel()
{
Name = "Test"
};
await categoryService.CreateCategory(createCategoryModel);
await categoryService.CreateCategory(createCategoryModel);
await categoryService.CreateCategory(createCategoryModel);
Assert.IsNotEmpty(await categoryService.AllCategories(), TestsMessages.ResultErrorMessage(nameof(categoryService.AllCategories)));
Assert.IsNotNull(await categoryService.AllCategories(), TestsMessages.ResultErrorMessage(nameof(categoryService.AllCategories)));
}
[Test]
public async Task AllCategories_ValidData_ShouldReturnTruthyValue()
{
CreateCategoryModel createCategoryModel = new CreateCategoryModel()
{
Name = "Test"
};
await categoryService.CreateCategory(createCategoryModel);
await categoryService.CreateCategory(createCategoryModel);
await categoryService.CreateCategory(createCategoryModel);
List<Category> expectedCategories = dBContext.Category.ToList();
List<CategoryViewModel> actualCategories = (await categoryService.AllCategories()).ToList();
Assert.AreEqual(expectedCategories.Count, actualCategories.Count, TestsMessages.ResultErrorMessage(nameof(categoryService.AllCategories)));
}
[Test]
public async Task AllCategories_ValidData_ShouldReturnEntitiesWithEqualIdValues()
{
CreateCategoryModel createCategoryModel = new CreateCategoryModel()
{
Name = "Test"
};
for (int i = 0; i < 3; i++)
{
createCategoryModel.Name += i.ToString();
await categoryService.CreateCategory(createCategoryModel);
}
List<Category> expectedCategories = dBContext.Category.ToList();
List<CategoryViewModel> actualCategories = (await categoryService.AllCategories()).ToList();
for (int i = 0; i < actualCategories.Count; i++)
{
Assert.AreEqual(actualCategories[i].Id, expectedCategories[i].Id, TestsMessages.MappingErrorMessage(nameof(categoryService.AllCategories), nameof(Category.Id)));
}
}
[Test]
public async Task AllCategories_ValidData_ShouldReturnEntitiesWithEqualNameValues()
{
CreateCategoryModel createCategoryModel = new CreateCategoryModel()
{
Name = "Test"
};
for (int i = 0; i < 3; i++)
{
createCategoryModel.Name += i.ToString();
await categoryService.CreateCategory(createCategoryModel);
}
List<Category> expectedCategories = dBContext.Category.ToList();
List<CategoryViewModel> actualCategories = (await categoryService.AllCategories()).ToList();
for (int i = 0; i < actualCategories.Count; i++)
{
Assert.AreEqual(actualCategories[i].Name, expectedCategories[i].Name, TestsMessages.MappingErrorMessage(nameof(categoryService.AllCategories), nameof(Category.Name)));
}
}
[TearDown]
public void Dispose()
{
this.dBContext.Dispose();
this.categoryService = null;
}
}
}
| 36.53719 | 183 | 0.652002 | [
"MIT"
] | Alexandra024905/Niche_Market | Tests/NicheMarket.Services.Tests/CategoryServiceTests.cs | 8,844 | 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.Data.Common;
using System.Diagnostics;
namespace Microsoft.EntityFrameworkCore.Diagnostics
{
/// <summary>
/// The <see cref="DiagnosticSource" /> event payload for
/// <see cref="RelationalEventId" /> command end events.
/// </summary>
public class CommandEndEventData : CommandEventData
{
/// <summary>
/// Constructs the event payload.
/// </summary>
/// <param name="eventDefinition"> The event definition. </param>
/// <param name="messageGenerator"> A delegate that generates a log message for this event. </param>
/// <param name="connection"> The <see cref="DbConnection" /> being used. </param>
/// <param name="command"> The <see cref="DbCommand" />. </param>
/// <param name="context"> The <see cref="DbContext" /> currently being used, to null if not known. </param>
/// <param name="executeMethod"> The <see cref="DbCommand" /> method. </param>
/// <param name="commandId"> A correlation ID that identifies the <see cref="DbCommand" /> instance being used. </param>
/// <param name="connectionId"> A correlation ID that identifies the <see cref="DbConnection" /> instance being used. </param>
/// <param name="async"> Indicates whether or not the command was executed asynchronously. </param>
/// <param name="logParameterValues"> Indicates whether or not the application allows logging of parameter values. </param>
/// <param name="startTime"> The start time of this event. </param>
/// <param name="duration"> The duration this event. </param>
public CommandEndEventData(
EventDefinitionBase eventDefinition,
Func<EventDefinitionBase, EventData, string> messageGenerator,
DbConnection connection,
DbCommand command,
DbContext? context,
DbCommandMethod executeMethod,
Guid commandId,
Guid connectionId,
bool async,
bool logParameterValues,
DateTimeOffset startTime,
TimeSpan duration)
: base(
eventDefinition,
messageGenerator,
connection,
command,
context,
executeMethod,
commandId,
connectionId,
async,
logParameterValues,
startTime)
=> Duration = duration;
/// <summary>
/// The duration this event.
/// </summary>
public virtual TimeSpan Duration { get; }
}
}
| 44.125 | 134 | 0.599858 | [
"Apache-2.0"
] | 0x0309/efcore | src/EFCore.Relational/Diagnostics/CommandEndEventData.cs | 2,824 | C# |
#pragma checksum "C:\Users\adamc\source\repos\Idea\Idea\MainPage.xaml" "{8829d00f-11b8-4213-878b-770e8597ac16}" "7B0AFB441FB132DA32D08DDBC07F62BA8751D90393CA72CBABC522BBD8AB33C1"
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
namespace Idea
{
partial class MainPage :
global::Windows.UI.Xaml.Controls.Page,
global::Windows.UI.Xaml.Markup.IComponentConnector,
global::Windows.UI.Xaml.Markup.IComponentConnector2
{
/// <summary>
/// Connect()
/// </summary>
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.Windows.UI.Xaml.Build.Tasks"," 10.0.19041.685")]
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
public void Connect(int connectionId, object target)
{
this._contentLoaded = true;
}
/// <summary>
/// GetBindingConnector(int connectionId, object target)
/// </summary>
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.Windows.UI.Xaml.Build.Tasks"," 10.0.19041.685")]
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
public global::Windows.UI.Xaml.Markup.IComponentConnector GetBindingConnector(int connectionId, object target)
{
global::Windows.UI.Xaml.Markup.IComponentConnector returnValue = null;
return returnValue;
}
}
}
| 41.585366 | 179 | 0.609971 | [
"MIT"
] | cybrneon/Idea | Idea/obj/x86/Debug/MainPage.g.cs | 1,707 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using FSO.Common.Serialization;
using Mina.Core.Buffer;
namespace FSO.Server.Protocol.Electron.Packets
{
public class PurchaseLotRequest : AbstractElectronPacket
{
public ushort LotLocation_X;
public ushort LotLocation_Y;
public string Name;
public bool StartFresh;
public bool MayorMode;
public override void Deserialize(IoBuffer input, ISerializationContext context)
{
LotLocation_X = input.GetUInt16();
LotLocation_Y = input.GetUInt16();
Name = input.GetPascalString();
StartFresh = input.GetBool();
MayorMode = input.GetBool();
}
public override ElectronPacketType GetPacketType()
{
return ElectronPacketType.PurchaseLotRequest;
}
public override void Serialize(IoBuffer output, ISerializationContext context)
{
output.PutUInt16(LotLocation_X);
output.PutUInt16(LotLocation_Y);
output.PutPascalString(Name);
output.PutBool(StartFresh);
output.PutBool(MayorMode);
}
}
}
| 29.069767 | 87 | 0.6488 | [
"MPL-2.0",
"MPL-2.0-no-copyleft-exception"
] | Blayer98/FreeSO | TSOClient/FSO.Server.Protocol/Electron/Packets/PurchaseLotRequest.cs | 1,252 | C# |
// Copyright (c) 2013-2019 Innoactive GmbH
// Licensed under the Apache License, Version 2.0
// Modifications copyright (c) 2021 MindPort GmbH
using System;
namespace VRBuilder.Core
{
[Obsolete("This event is not used anymore.")]
public class ChildDeactivatedEventArgs<TEntity> : EventArgs where TEntity : IEntity
{
public TEntity Child { get; private set; }
public ChildDeactivatedEventArgs(TEntity child)
{
Child = child;
}
}
}
| 24.65 | 87 | 0.669371 | [
"Apache-2.0"
] | MindPort-GmbH/VR-Builder-Core | Source/Core/Runtime/ChildDeactivatedEventArgs.cs | 493 | C# |
// This file is used by Code Analysis to maintain SuppressMessage
// attributes that are applied to this project.
// Project-level suppressions either have no target or are given
// a specific target and scoped to a namespace, type, member, etc.
using System.Diagnostics.CodeAnalysis;
[assembly: SuppressMessage("Style", "IDE0044:Add readonly modifier", Justification = "Broken Rule doesn't pick up on being set by razor page.", Scope = "namespaceanddescendants", Target = "Hashgraph.Portal.Pages")]
[assembly: SuppressMessage("Performance", "CA1805:Do not initialize unnecessarily", Justification = "Prefer this style", Scope = "namespaceanddescendants", Target = "Hashgraph.Portal.Pages")]
| 70.4 | 215 | 0.765625 | [
"Apache-2.0"
] | bugbytesinc/Hashgraph-Portal | Hashgraph.Portal/GlobalSuppressions.cs | 706 | C# |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.