content stringlengths 5 1.04M | avg_line_length float64 1.75 12.9k | max_line_length int64 2 244k | alphanum_fraction float64 0 0.98 | licenses list | repository_name stringlengths 7 92 | path stringlengths 3 249 | size int64 5 1.04M | lang stringclasses 2 values |
|---|---|---|---|---|---|---|---|---|
using System;
using System.Net.Http;
using System.Threading.Tasks;
using Grpc.Net.Client;
using Grpc.Net.Client.Web;
using Microsoft.AspNetCore.Components;
using Microsoft.AspNetCore.Components.WebAssembly.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using MudBlazor.Services;
using Plk.Blazor.DragDrop;
namespace JBlazorWasm {
public class Program {
public static async Task Main(string[] args) {
var builder = WebAssemblyHostBuilder.CreateDefault(args);
builder.RootComponents.Add<App>("#app");
builder.Services.AddScoped(
sp => new HttpClient {BaseAddress = new Uri(builder.HostEnvironment.BaseAddress)});
builder.Services.AddMudServices();
builder.Services.AddBlazorDragDrop();
builder.Services.AddSingleton(services => {
// Get the service address from appsettings.json
var config = services.GetRequiredService<IConfiguration>();
var backendUrl = config["BackendUrl"];
// If no address is set then fallback to the current webpage URL
if (string.IsNullOrEmpty(backendUrl)) {
var navigationManager = services.GetRequiredService<NavigationManager>();
backendUrl = navigationManager.BaseUri;
}
// Create a channel with a GrpcWebHandler that is addressed to the backend server.
//
// GrpcWebText is used because server streaming requires it. If server streaming is not used in your app
// then GrpcWeb is recommended because it produces smaller messages.
var httpHandler = new GrpcWebHandler(GrpcWebMode.GrpcWebText, new HttpClientHandler());
return GrpcChannel.ForAddress(backendUrl, new GrpcChannelOptions {HttpHandler = httpHandler});
});
await builder.Build().RunAsync();
}
}
} | 42.765957 | 120 | 0.656219 | [
"MIT"
] | nameofSEOKWONHONG/JW2Library | JW2Library.Implement/JBlazorWasm/Program.cs | 2,010 | C# |
using System;
using System.IO;
using YamlDotNet.Serialization;
public class Configuration
{
public string GameServerIp { get; set; }
public int GameServerApiPort { get; set; }
public Configuration()
{
GameServerIp = "127.0.0.1";
GameServerApiPort = 13345;
}
public static Configuration GetConfiguration(String filePath)
{
using (var input = File.OpenText(filePath))
{
return (new Deserializer()).Deserialize<Configuration>(input);
}
}
}
| 21.875 | 74 | 0.638095 | [
"Apache-2.0"
] | lostinplace/sample-empyrion-mod | Empyrion Mod/Configuration.cs | 527 | C# |
using System.Collections.Generic;
using System.IO;
namespace AzureDevOpsWikiToPdf
{
public interface IWikiEntry
{
string FullName { get; }
string MarkdownName { get; }
string ReViewName { get; }
IReadOnlyList<IWikiEntry> WikiEntries { get; }
void Write(TextWriter textWriter);
}
} | 18.777778 | 54 | 0.647929 | [
"MIT"
] | nuitsjp/Azure-DevOps-Wiki-to-PDF | Source/AzureDevOpsWikiToPdf/IWikiEntry.cs | 340 | C# |
using System;
namespace Faster.Ioc.Zero.Benchmark.Complex
{
public interface ISubObjectThree
{
}
public class SubObjectThree : ISubObjectThree
{
public SubObjectThree(IThirdService thirdService)
{
if (thirdService == null)
{
throw new ArgumentNullException(nameof(thirdService));
}
}
protected SubObjectThree()
{
}
}
}
| 17.5 | 70 | 0.553846 | [
"MIT"
] | Wsm2110/Faster.Ioc.Zero | src/Faster.Ioc.Zero.Benchmark/Complex/SubObjectThree.cs | 457 | C# |
#if !NETCOREAPP
using System;
using System.Data.OleDb;
using FileHelpers.DataLink;
using NUnit.Framework;
namespace FileHelpers.Tests.DataLink
{
[TestFixture]
[Explicit]
[Category("Advanced")]
public class DataLinks
{
private FileDataLink mLink;
#region " FillRecordOrders "
protected void FillRecordOrders(object rec, object[] fields)
{
var record = (OrdersFixed) rec;
record.OrderID = (int) fields[0];
record.CustomerID = (string) fields[1];
record.EmployeeID = (int) fields[2];
record.OrderDate = (DateTime) fields[3];
record.RequiredDate = (DateTime) fields[4];
if (fields[5] != DBNull.Value)
record.ShippedDate = (DateTime) fields[5];
else
record.ShippedDate = DateTime.MinValue;
record.ShipVia = (int) fields[6];
record.Freight = (decimal) fields[7];
}
#endregion
[Test]
public void OrdersDbToFile()
{
var storage = new AccessStorage(typeof (OrdersFixed), @"..\data\TestData.mdb");
storage.SelectSql = "SELECT * FROM Orders";
storage.FillRecordCallback = new FillRecordHandler(FillRecordOrders);
mLink = new FileDataLink(storage);
mLink.ExtractToFile(@"..\data\temp.txt");
int extractNum = mLink.LastExtractedRecords.Length;
var records = (OrdersFixed[]) mLink.FileHelperEngine.ReadFile(@"..\data\temp.txt");
Assert.AreEqual(extractNum, records.Length);
}
[Test]
public void OrdersDbToFileEasy()
{
var storage = new AccessStorage(typeof (OrdersFixed), @"..\data\TestData.mdb");
storage.SelectSql = "SELECT * FROM Orders";
storage.FillRecordCallback = new FillRecordHandler(FillRecordOrders);
var records = (OrdersFixed[]) FileDataLink.EasyExtractToFile(storage, @"..\data\temp.txt");
int extractNum = records.Length;
records = (OrdersFixed[]) CommonEngine.ReadFile(typeof (OrdersFixed), @"..\data\temp.txt");
Assert.AreEqual(extractNum, records.Length);
}
private void FillRecordCustomers(object rec, object[] fields)
{
var record = (CustomersVerticalBar) rec;
record.CustomerID = (string) fields[0];
record.CompanyName = (string) fields[1];
record.ContactName = (string) fields[2];
record.ContactTitle = (string) fields[3];
record.Address = (string) fields[4];
record.City = (string) fields[5];
record.Country = (string) fields[6];
}
[Test]
public void CustomersDbToFile()
{
var storage = new AccessStorage(typeof (CustomersVerticalBar), @"..\data\TestData.mdb");
storage.SelectSql = "SELECT * FROM Customers";
storage.FillRecordCallback = new FillRecordHandler(FillRecordCustomers);
mLink = new FileDataLink(storage);
mLink.ExtractToFile(@"..\data\temp.txt");
int extractNum = mLink.LastExtractedRecords.Length;
var records = (CustomersVerticalBar[]) mLink.FileHelperEngine.ReadFile(@"..\data\temp.txt");
Assert.AreEqual(extractNum, records.Length);
}
private object FillRecord(object[] fields)
{
var record = new CustomersVerticalBar();
record.CustomerID = (string) fields[0];
record.CompanyName = (string) fields[1];
record.ContactName = (string) fields[2];
record.ContactTitle = (string) fields[3];
record.Address = (string) fields[4];
record.City = (string) fields[5];
record.Country = (string) fields[6];
return record;
}
#region " GetInsertSql "
protected string GetInsertSqlCust(object record)
{
var obj = (CustomersVerticalBar) record;
return
string.Format(
"INSERT INTO CustomersTemp (Address, City, CompanyName, ContactName, ContactTitle, Country, CustomerID) " +
" VALUES ( \"{0}\" , \"{1}\" , \"{2}\" , \"{3}\" , \"{4}\" , \"{5}\" , \"{6}\" ); ",
obj.Address,
obj.City,
obj.CompanyName,
obj.ContactName,
obj.ContactTitle,
obj.Country,
obj.CustomerID
);
}
#endregion
[Test]
public void CustomersFileToDb()
{
var storage = new AccessStorage(typeof (CustomersVerticalBar), @"..\data\TestData.mdb");
storage.InsertSqlCallback = new InsertSqlHandler(GetInsertSqlCust);
mLink = new FileDataLink(storage);
ClearData(((AccessStorage) mLink.DataStorage).AccessFileName, "CustomersTemp");
int count = Count(((AccessStorage) mLink.DataStorage).AccessFileName, "CustomersTemp");
Assert.AreEqual(0, count);
mLink.InsertFromFile(@"..\data\UpLoadCustomers.txt");
count = Count(((AccessStorage) mLink.DataStorage).AccessFileName, "CustomersTemp");
Assert.AreEqual(91, count);
ClearData(((AccessStorage) mLink.DataStorage).AccessFileName, "CustomersTemp");
}
protected object FillRecordOrder(object[] fields)
{
var record = new OrdersFixed();
record.OrderID = (int) fields[0];
record.CustomerID = (string) fields[1];
record.EmployeeID = (int) fields[2];
record.OrderDate = (DateTime) fields[3];
record.RequiredDate = (DateTime) fields[4];
if (fields[5] != DBNull.Value)
record.ShippedDate = (DateTime) fields[5];
else
record.ShippedDate = DateTime.MinValue;
record.ShipVia = (int) fields[6];
record.Freight = (decimal) fields[7];
return record;
}
#region " GetInsertSql "
protected string GetInsertSqlOrder(object record)
{
var obj = (OrdersFixed) record;
return
string.Format(
"INSERT INTO OrdersTemp (CustomerID, EmployeeID, Freight, OrderDate, OrderID, RequiredDate, ShippedDate, ShipVia) " +
" VALUES ( \"{0}\" , \"{1}\" , \"{2}\" , \"{3}\" , \"{4}\" , \"{5}\" , \"{6}\" , \"{7}\" ) ",
obj.CustomerID,
obj.EmployeeID,
obj.Freight,
obj.OrderDate,
obj.OrderID,
obj.RequiredDate,
obj.ShippedDate,
obj.ShipVia
);
}
#endregion
[Test]
[Ignore("Needs Access Installed")]
public void OrdersFileToDb()
{
var storage = new AccessStorage(typeof (OrdersFixed), @"..\data\TestData.mdb");
storage.InsertSqlCallback = new InsertSqlHandler(GetInsertSqlOrder);
mLink = new FileDataLink(storage);
ClearData(((AccessStorage) mLink.DataStorage).AccessFileName, "OrdersTemp");
int count = Count(((AccessStorage) mLink.DataStorage).AccessFileName, "OrdersTemp");
Assert.AreEqual(0, count);
mLink.InsertFromFile(@"..\data\UpLoadOrders.txt");
count = Count(((AccessStorage) mLink.DataStorage).AccessFileName, "OrdersTemp");
Assert.AreEqual(830, count);
ClearData(((AccessStorage) mLink.DataStorage).AccessFileName, "OrdersTemp");
}
private const string AccessConnStr =
@"Jet OLEDB:Global Partial Bulk Ops=2;Jet OLEDB:Registry Path=;Jet OLEDB:Database Locking Mode=1;Jet OLEDB:Database Password=;Data Source=""<BASE>"";Password=;Jet OLEDB:Engine Type=5;Jet OLEDB:Global Bulk Transactions=1;Provider=""Microsoft.Jet.OLEDB.4.0"";Jet OLEDB:System database=;Jet OLEDB:SFP=False;Extended Properties=;Mode=Share Deny None;Jet OLEDB:New Database Password=;Jet OLEDB:Create System Database=False;Jet OLEDB:Don't Copy Locale on Compact=False;Jet OLEDB:Compact Without Replica Repair=False;User ID=Admin;Jet OLEDB:Encrypt Database=False";
public void ClearData(string fileName, string table)
{
string conString = AccessConnStr.Replace("<BASE>", fileName);
var conn = new OleDbConnection(conString);
var cmd = new OleDbCommand("DELETE FROM " + table, conn);
conn.Open();
cmd.ExecuteNonQuery();
conn.Close();
int count = Count(((AccessStorage) mLink.DataStorage).AccessFileName, "OrdersTemp");
}
public int Count(string fileName, string table)
{
string conString = AccessConnStr.Replace("<BASE>", fileName);
var conn = new OleDbConnection(conString);
var cmd = new OleDbCommand("SELECT COUNT (*) FROM " + table, conn);
conn.Open();
var res = (int) cmd.ExecuteScalar();
conn.Close();
return res;
}
}
}
#endif
| 38.35743 | 571 | 0.554706 | [
"MIT"
] | DillonBroadus/FileHelpers | FileHelpers.Tests/Tests/DataLink/DataLinkTests.cs | 9,551 | C# |
using System;
using System.IO;
using Microsoft.AspNetCore.Http;
using Sikiro.Tookits.Base;
using Sikiro.Tookits.Extension;
namespace Sikiro.Common.Utils
{
public static class UploadHelper
{
/// <summary>
/// 存放路径
/// </summary>
/// <param name="path"></param>
/// <param name="imgFile"></param>
/// <returns></returns>
public static ServiceResult Img(string path, IFormFile imgFile)
{
path.ThrowIfNull();
imgFile.ThrowIfNull();
try
{
if (imgFile != null && !string.IsNullOrEmpty(imgFile.FileName))
{
var extensionName = Path.GetExtension(imgFile.FileName);
var filename = Guid.NewGuid().ToString("N") + extensionName;
if (!Directory.Exists(path))
Directory.CreateDirectory(path);
filename = Path.Combine(path, filename);
using (var fs = File.Create(filename))
{
imgFile.CopyTo(fs);
fs.Flush();
}
return ServiceResult.IsSuccess("上传成功", filename);
}
}
catch (Exception e)
{
e.WriteToFile("上传异常");
}
return ServiceResult.IsFailed("上传失败");
}
}
}
| 27.653846 | 80 | 0.477747 | [
"MIT"
] | 364988343/Sikiro.RBAC | src/GS.Common.Utils/UploadHelper.cs | 1,472 | C# |
using System;
using System.Collections.Generic;
using System.Text;
using Microsoft.AspNetCore.Identity.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore;
using LiftoffRMAV.Models;
namespace LiftoffRMAV.Data
{
public class ApplicationDbContext : IdentityDbContext<RmavUser,RmavRole,int>
{
public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options)
: base(options)
{}
public DbSet<Games> Games { get; set; }
public DbSet<Items> Items { get; set; }
protected override void OnModelCreating(ModelBuilder builder)
{
base.OnModelCreating(builder);
builder.Entity<RmavUser>().Ignore(e => e.FullName);
}
}
}
| 27.37037 | 83 | 0.682003 | [
"MIT"
] | AJacobs94/LiftoffRMAV | Data/ApplicationDbContext.cs | 741 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace CollectionStudy
{
public class Class1
{
static void Main() {
var a = new List<int>();
a.TrimExcess();
var stringList = new List<string>() { "asd", "sdsd" };
var ataa = new datetimeindex();
Random dd = new Random();
//dd.Next(2, 7);
int aa = 0;
while (aa!=2)
{
aa= dd.Next(2, 7);
Console.WriteLine(aa);
}
Console.ReadKey();
}
}
}
| 22.827586 | 66 | 0.471299 | [
"Apache-2.0"
] | flxwhy/.NetStudy | repos/CollectionStudy/CollectionStudy/Class1.cs | 664 | C# |
using Il2CppSystem.Collections.Generic;
using UnityEngine;
namespace AudicaModding
{
internal static class RandomSong
{
private static int historySize = 10;
private static List<string> currentSongs = new List<string>();
private static List<string> currentSongsFull = new List<string>();
private static List<string> recentlySelected = new List<string>();
public static void UpdateAvailableSongs(List<string> songs)
{
currentSongsFull = songs;
FillSongList();
if (currentSongsFull.Count == 0)
RandomSongButton.Disable();
else
RandomSongButton.Enable();
}
public static void SelectRandomSong()
{
if (currentSongsFull.Count == 0)
return;
if (currentSongs.Count == 0)
{
recentlySelected.Clear();
FillSongList();
}
int songCount = currentSongs.Count;
System.Random rand = new System.Random();
int idx = rand.Next(0, songCount);
string songID = currentSongs[idx];
SongList.SongData data = SongList.I.GetSong(songID);
if (data != null)
{
// remove from the random songs list
currentSongs.RemoveAt(idx);
if (recentlySelected.Count > historySize)
{
recentlySelected.RemoveAt(0);
}
recentlySelected.Add(songID);
SongDataHolder.I.songData = data;
MenuState.I.GoToLaunchPage();
}
}
private static void FillSongList()
{
currentSongs = new List<string>();
// remove recently selected songs from the list
for (int i = 0; i < currentSongsFull.Count; i++)
{
string songID = currentSongsFull[i];
if (!recentlySelected.Contains(songID))
{
currentSongs.Add(songID);
}
}
}
}
}
| 30.905405 | 75 | 0.484915 | [
"MIT"
] | MeepsKitten/SongBrowser | AudicaMod/src/RandomSong/RandomSong.cs | 2,289 | C# |
using System;
using System.Drawing;
namespace ChromaWrapper.Sdk
{
/// <summary>
/// Represents a special case of <see cref="ChromaColor"/> used in custom keyboard effects that implement the <see cref="IKeyGridEffect"/> interface.
/// </summary>
/// <remarks>
/// The Razer Chroma SDK's keyboard effects that have a <c>Key</c> grid require that a <c>0x01000000</c> mask
/// be applied to the corresponding color in order to be actually rendered; otherwise, the color is treated
/// as transparent and therefore is not rendered.
/// </remarks>
/// <seealso cref="ChromaColor"/>
public readonly struct ChromaKeyColor : IEquatable<ChromaKeyColor>
{
internal const int KeySetFlag = 0x1000000;
internal static readonly ChromaKeyColor Transparent;
private readonly int _value;
private ChromaKeyColor(int fbgr)
{
_value = (fbgr & KeySetFlag) != 0
? (fbgr & (KeySetFlag | ChromaColor.ColorMask))
: 0;
}
/// <summary>
/// Gets the red component value of this <see cref="ChromaKeyColor"/> structure.
/// </summary>
/// <remarks>
/// If <see cref="IsTransparent"/> is <c>true</c>, this property always returns 0.
/// </remarks>
public byte R => (byte)(_value & 0xFF);
/// <summary>
/// Gets the green component value of this <see cref="ChromaKeyColor"/> structure.
/// </summary>
/// <remarks>
/// If <see cref="IsTransparent"/> is <c>true</c>, this property always returns 0.
/// </remarks>
public byte G => (byte)((_value >> 8) & 0xFF);
/// <summary>
/// Gets the blue component value of this <see cref="ChromaKeyColor"/> structure.
/// </summary>
/// <remarks>
/// If <see cref="IsTransparent"/> is <c>true</c>, this property always returns 0.
/// </remarks>
public byte B => (byte)((_value >> 16) & 0xFF);
/// <summary>
/// Gets a value indicating whether this <see cref="ChromaKeyColor"/> structure is the <see cref="Transparent"/> key color.
/// </summary>
public bool IsTransparent => (_value & KeySetFlag) == 0;
/// <summary>
/// Converts a <see cref="Color"/> structure to a <see cref="ChromaKeyColor"/> structure.
/// </summary>
/// <param name="color">The color to convert.</param>
public static explicit operator ChromaKeyColor(Color color)
{
return FromColor(color);
}
/// <summary>
/// Converts a <see cref="ChromaKeyColor"/> structure to a <see cref="Color"/> structure.
/// </summary>
/// <param name="color">The color to convert.</param>
public static implicit operator Color(ChromaKeyColor color)
{
return color.ToColor();
}
/// <summary>
/// Convert a <see cref="ChromaColor"/> structure to a <see cref="ChromaKeyColor"/> structure.
/// </summary>
/// <param name="color">The color to convert.</param>
public static implicit operator ChromaKeyColor(ChromaColor color)
{
return FromChromaColor(color);
}
/// <summary>
/// Convert a <see cref="ChromaKeyColor"/> structure to a <see cref="ChromaColor"/> structure.
/// </summary>
/// <param name="color">The color to convert.</param>
public static explicit operator ChromaColor(ChromaKeyColor color)
{
return color.ToChromaColor();
}
/// <summary>
/// Returns a value indicating whether two <see cref="ChromaKeyColor"/> values are equal.
/// </summary>
/// <param name="left">The first value to compare.</param>
/// <param name="right">The second value to compare.</param>
/// <returns><c>true</c> if <paramref name="left"/> and <paramref name="right"/> represent the same color; otherwise, <c>false</c>.</returns>
public static bool operator ==(ChromaKeyColor left, ChromaKeyColor right)
{
return left.Equals(right);
}
/// <summary>
/// Returns a value indicating whether two <see cref="ChromaKeyColor"/> values are different.
/// </summary>
/// <param name="left">The first value to compare.</param>
/// <param name="right">The second value to compare.</param>
/// <returns><c>true</c> if <paramref name="left"/> and <paramref name="right"/> represent different colors; otherwise, <c>false</c>.</returns>
public static bool operator !=(ChromaKeyColor left, ChromaKeyColor right)
{
return !(left == right);
}
/// <summary>
/// Creates a <see cref="ChromaKeyColor"/> structure from a <see cref="Color"/> structure.
/// </summary>
/// <param name="color">The <see cref="Color"/> structure to copy the RGB components from.</param>
/// <returns>The new <see cref="ChromaKeyColor"/> structure.</returns>
/// <remarks>If <paramref name="color"/> is the transparent color, <see cref="Transparent"/> will be produced; otherwise, only RGB components are copied.</remarks>
public static ChromaKeyColor FromColor(Color color)
{
return color == Color.Transparent
? Transparent
: ChromaColor.FromColor(color);
}
/// <summary>
/// Creates a <see cref="ChromaKeyColor"/> structure from a <see cref="ChromaColor"/> structure.
/// </summary>
/// <param name="color">The <see cref="ChromaColor"/> structure to copy the RGB components from.</param>
/// <returns>The new <see cref="ChromaKeyColor"/> structure.</returns>
public static ChromaKeyColor FromChromaColor(ChromaColor color)
{
return new ChromaKeyColor(color.ToInt32() | KeySetFlag);
}
/// <summary>
/// Gets the <see cref="Color"/> representation of this <see cref="ChromaKeyColor"/> structure.
/// </summary>
/// <returns>The new <see cref="Color"/> structure.</returns>
public Color ToColor()
{
return IsTransparent
? Color.Transparent
: Color.FromArgb(R, G, B);
}
/// <summary>
/// Gets the <see cref="ChromaColor"/> representation of this <see cref="ChromaKeyColor"/> structure.
/// </summary>
/// <returns>The new <see cref="ChromaColor"/> structure.</returns>
public ChromaColor ToChromaColor()
{
return ChromaColor.FromInt32(_value & ChromaColor.ColorMask);
}
/// <summary>
/// Indicates whether the current color object is equal to another color object.
/// </summary>
/// <param name="other">A color to compare with this color.</param>
/// <returns><c>true</c> if the current color is equal to the color in <paramref name="other"/>; otherwise, false.</returns>
public bool Equals(ChromaKeyColor other)
{
return _value.Equals(other._value);
}
/// <summary>
/// Indicates whether this instance and a specified object are equal.
/// </summary>
/// <param name="obj">An object to compare with this object.</param>
/// <returns><c>true</c> if <paramref name="obj"/> and this instance are the same type and represents the same value; otherwise, <c>false</c>.</returns>
public override bool Equals(object? obj)
{
return obj is ChromaKeyColor color && Equals(color);
}
/// <summary>
/// Returns the hash code for this instance.
/// </summary>
/// <returns>A 32-bit signed integer hash code.</returns>
public override int GetHashCode()
{
return _value;
}
/// <summary>
/// Converts this <see cref="ChromaKeyColor"/> structure to a human-readable string.
/// </summary>
/// <returns>An HTML hex triplet string representation of this structure's color, or '(Transparent)' if there's no color set.</returns>
public override string ToString()
{
return _value == 0
? "(Transparent)"
: ((ChromaColor)this).ToString();
}
internal static ChromaKeyColor FromInt32(int value)
{
return new ChromaKeyColor(value);
}
internal int ToInt32()
{
return _value;
}
}
}
| 40.777251 | 171 | 0.579847 | [
"MIT"
] | poveden/ChromaWrapper | src/Sdk/ChromaKeyColor.cs | 8,606 | C# |
/*
* Created by Alexandre Rocha Lima e Marcondes
* User: Administrator
* Date: 28/09/2005
* Time: 16:13
*
* Description: An SQL Builder, Object Interface to Database Tables
* Its based on DataObjects from php PEAR
* 1. Builds SQL statements based on the objects vars and the builder methods.
* 2. acts as a datastore for a table row.
* The core class is designed to be extended for each of your tables so that you put the
* data logic inside the data classes.
* included is a Generator to make your configuration files and your base classes.
*
* CSharp DataObject
* Copyright (c) 2005, Alessandro de Oliveira Binhara
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification, are
* permitted provided that the following conditions are met:
*
* - Redistributions of source code must retain the above copyright notice, this list
* of conditions and the following disclaimer.
*
* - Redistributions in binary form must reproduce the above copyright notice, this list
* of conditions and the following disclaimer in the documentation and/or other materials
* provided with the distribution.
*
* - Neither the name of the <ORGANIZATION> nor the names of its contributors may be used to
* endorse or promote products derived from this software without specific prior written
* permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS &AS IS& AND ANY EXPRESS
* OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
* AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER
* IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
* OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.Data;
using System.Data.SqlClient;
using CsDO.Lib;
using System.Data.Common;
namespace CsDO.Drivers.SqlServer
{
[Obsolete("Use CsDO configuration files instead")]
public class SqlServerDriver : IDataBase
{
private SqlConnection conn = null;
private string connectionString = null;
public DbConnection Connection { get { return conn; } }
public SqlServerDriver() {
connectionString = Config.GetDbConectionString(Config.DBMS.MSSQLServer);
}
public SqlServerDriver(string server, string user, string database, string password)
{
connectionString = "Server="+server+";User Id="+user+";Password="+password+";Database="+database+";";
}
protected string getUrl()
{
return connectionString;
}
protected string getUrlSys()
{
return getUrl();
}
public DataTable getSchema()
{
return conn.GetSchema();
}
public DataTable getSchema(string collectionName)
{
return conn.GetSchema(collectionName);
}
public DataTable getSchema(string collectionName, string[] restrictions)
{
return conn.GetSchema(collectionName, restrictions);
}
public DbCommand getCommand(String sql)
{
return new SqlCommand(sql, (SqlConnection) getConnection());
}
public DbCommand getSystemCommand(String sql)
{
return new SqlCommand(sql, (SqlConnection) getSystemConnection());
}
public DbDataAdapter getDataAdapter(DbCommand command)
{
return new SqlDataAdapter((SqlCommand) command);
}
public DbConnection getConnection()
{
open(getUrl());
return conn;
}
public DbConnection getSystemConnection()
{
open(getUrlSys());
return conn;
}
public DbParameter getParameter ()
{
throw new System.NotImplementedException ();
}
public DbParameter getParameter (string name, DbType type, int size)
{
throw new System.NotImplementedException ();
}
public void open(string URL)
{
try
{
if (conn == null)
{
conn = new SqlConnection(URL);
conn.Open();
}
else
{
if (conn.State == ConnectionState.Broken
|| conn.State == ConnectionState.Closed)
{
conn.Open();
}
}
}
catch (DataException)
{
conn.Dispose();
}
}
public void close()
{
if (conn != null)
conn.Close();
}
}
}
| 29.017964 | 105 | 0.662196 | [
"MIT",
"BSD-3-Clause"
] | MonoBrasil/CsDO | CsDO.Drivers/SqlServerDriver.cs | 4,846 | C# |
using CertificateManager.Entities;
using CertificateManager.Logic;
using CertificateManager.Logic.ActiveDirectory;
using CertificateManager.Logic.ActiveDirectory.Interfaces;
using CertificateManager.Logic.Interfaces;
using CertificateManager.Repository;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
namespace CertificateManager.Controllers
{
public class ScriptController : Controller
{
IScriptManagementLogic scriptLogic;
IConfigurationRepository configurationRepository;
HttpResponseHandler http;
IPowershellEngine powershell;
public ScriptController(IConfigurationRepository configurationRepository, IScriptManagementLogic scriptLogic, IPowershellEngine powershell)
{
this.powershell = powershell;
this.scriptLogic = scriptLogic;
this.configurationRepository = configurationRepository;
this.http = new HttpResponseHandler(this);
}
[HttpGet]
[Route("view/script/{id:guid}")]
public ActionResult ViewScript(Guid id)
{
ViewBag.NodeId = id;
return View();
}
[HttpGet]
[Route("view/scripts")]
public ActionResult ViewScripts()
{
return View();
}
[HttpGet]
[Route("scripts")]
public JsonResult GetScripts()
{
var nodes = scriptLogic.All(User);
return http.RespondSuccess(nodes);
}
[HttpGet]
[Route("script/{id:guid}")]
public JsonResult GetScript(Guid id)
{
Script node = scriptLogic.Get(id.ToString(), User);
return http.RespondSuccess(node);
}
[HttpDelete]
[Route("script")]
public JsonResult Delete(Script script)
{
scriptLogic.Delete(script.Id.ToString(), User);
return http.RespondSuccess();
}
[HttpPost]
[Route("script")]
public JsonResult Add(Script script)
{
scriptLogic.Add(script, User);
return http.RespondSuccess();
}
[HttpPut]
[Route("script")]
public JsonResult Update(Script script)
{
powershell.ValidateSyntax(script, User);
scriptLogic.Update(script, User);
return http.RespondSuccess();
}
}
} | 28.255814 | 147 | 0.609877 | [
"MIT"
] | corymurphy/CertificateManager | CertificateManager/Controllers/ScriptController.cs | 2,432 | C# |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using Microsoft.Protocols.TestTools.StackSdk.Asn1;
namespace Microsoft.Protocols.TestTools.StackSdk.Security.KerberosLib
{
/*
KERB-AD-RESTRICTION-ENTRY ::= SEQUENCE {
restriction-type [0] Int32,
restriction [1] OCTET STRING
}
*/
public class KERB_AD_RESTRICTION_ENTRY : Asn1Sequence
{
[Asn1Field(0), Asn1Tag(Asn1TagType.Context, 0)]
public KerbInt32 restriction_type { get; set; }
/// <summary>
/// If the LSAP_TOKEN_INFO_INTEGRITY is needed, use following code to get the object.
/// LSAP_TOKEN_INFO_INTEGRITY ltii = new LSAP_TOKEN_INFO_INTEGRITY();
/// ltii.GetElements(SomeObj.restriction);
/// </summary>
[Asn1Field(1), Asn1Tag(Asn1TagType.Context, 1)]
public Asn1OctetString restriction { get; set; }
public KERB_AD_RESTRICTION_ENTRY()
{
this.restriction_type = null;
this.restriction = null;
}
public KERB_AD_RESTRICTION_ENTRY(
KerbInt32 param0,
Asn1OctetString param1)
{
this.restriction_type = param0;
this.restriction = param1;
}
//Added manually
public KERB_AD_RESTRICTION_ENTRY(
KerbInt32 param0,
LSAP_TOKEN_INFO_INTEGRITY param1)
{
this.restriction_type = param0;
this.restriction = param1.SetElements();
}
public override int BerEncode(IAsn1BerEncodingBuffer buffer, bool explicitTag)
{
int len = base.BerEncode(buffer);
len += LengthBerEncode(buffer, len);
len += TagBerEncode(buffer, new Asn1Tag(Asn1TagType.Universal,
Asn1TagValue.Sequence) { EncodingWay = EncodingWay.Constructed });
return len;
}
public override int BerDecode(IAsn1DecodingBuffer buffer, bool explicitTag = true)
{
int consumed = 0;
int length;
Asn1Tag tag;
consumed += TagBerDecode(buffer, out tag);
consumed += LengthBerDecode(buffer, out length);
consumed += base.BerDecode(buffer);
return consumed;
}
}
}
| 31.72973 | 101 | 0.616269 | [
"MIT"
] | 0neb1n/WindowsProtocolTestSuites | ProtoSDK/KerberosLib/Asn1Code/Kile/KERB_AD_RESTRICTION_ENTRY.cs | 2,348 | C# |
#if !NETSTANDARD13
/*
* Copyright 2010-2014 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
/*
* Do not modify this file. This file is generated from the ssm-2014-11-06.normal.json service model.
*/
using Amazon.Runtime;
namespace Amazon.SimpleSystemsManagement.Model
{
/// <summary>
/// Paginator for the DescribeAutomationExecutions operation
///</summary>
public interface IDescribeAutomationExecutionsPaginator
{
/// <summary>
/// Enumerable containing all full responses for the operation
/// </summary>
IPaginatedEnumerable<DescribeAutomationExecutionsResponse> Responses { get; }
/// <summary>
/// Enumerable containing all of the AutomationExecutionMetadataList
/// </summary>
IPaginatedEnumerable<AutomationExecutionMetadata> AutomationExecutionMetadataList { get; }
}
}
#endif | 34.85 | 101 | 0.713056 | [
"Apache-2.0"
] | DetlefGolze/aws-sdk-net | sdk/src/Services/SimpleSystemsManagement/Generated/Model/_bcl45+netstandard/IDescribeAutomationExecutionsPaginator.cs | 1,394 | C# |
// --------------------------------------------------------------------------------------------------------------------
// <copyright file="WhenParsingFeatureFiles.cs" company="PicklesDoc">
// Copyright 2011 Jeffrey Cameron
// Copyright 2012-present PicklesDoc team and community contributors
//
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// </copyright>
// --------------------------------------------------------------------------------------------------------------------
using System.Linq;
using Autofac;
using DocumentFormat.OpenXml.Bibliography;
using NFluent;
using NUnit.Framework;
using PicklesDoc.Pickles.Extensions;
using PicklesDoc.Pickles.ObjectModel;
using StringReader = System.IO.StringReader;
namespace PicklesDoc.Pickles.Test
{
[TestFixture]
public class WhenParsingFeatureFiles : BaseFixture
{
private const string DocStringDelimiter = "\"\"\"";
[Test]
public void ThenCanParseFeatureWithMultipleScenariosSuccessfully()
{
string featureText =
@"# ignore this comment
Feature: Test
In order to do something
As a user
I want to run this scenario
Scenario: A scenario
Given some feature
When it runs
Then I should see that this thing happens
Scenario: Another scenario
Given some other feature
When it runs
Then I should see that this other thing happens
And something else";
var parser = Container.Resolve<FeatureParser>();
Feature feature = parser.Parse(new StringReader(featureText));
Check.That(feature).IsNotNull();
Check.That(feature.Name).IsEqualTo("Test");
Check.That(feature.Description.ComparisonNormalize()).IsEqualTo(@"In order to do something
As a user
I want to run this scenario".ComparisonNormalize());
Check.That(feature.FeatureElements.Count).IsEqualTo(2);
Check.That(feature.Tags).IsEmpty();
IFeatureElement scenario = feature.FeatureElements[0];
Check.That(scenario.Name).IsEqualTo("A scenario");
Check.That(scenario.Description).IsEqualTo("");
Check.That(scenario.Steps.Count).IsEqualTo(3);
Check.That(scenario.Tags).IsEmpty();
Step givenStep = scenario.Steps[0];
Check.That(givenStep.Keyword).IsEqualTo(Keyword.Given);
Check.That(givenStep.Name).IsEqualTo("some feature");
Check.That(givenStep.DocStringArgument).IsNull();
Check.That(givenStep.TableArgument).IsNull();
Step whenStep = scenario.Steps[1];
Check.That(whenStep.Keyword).IsEqualTo(Keyword.When);
Check.That(whenStep.Name).IsEqualTo("it runs");
Check.That(whenStep.DocStringArgument).IsNull();
Check.That(whenStep.TableArgument).IsNull();
Step thenStep = scenario.Steps[2];
Check.That(thenStep.Keyword).IsEqualTo(Keyword.Then);
Check.That(thenStep.Name).IsEqualTo("I should see that this thing happens");
Check.That(thenStep.DocStringArgument).IsNull();
Check.That(thenStep.TableArgument).IsNull();
IFeatureElement scenario2 = feature.FeatureElements[1];
Check.That(scenario2.Name).IsEqualTo("Another scenario");
Check.That(scenario2.Description).IsEqualTo(string.Empty);
Check.That(scenario2.Steps.Count).IsEqualTo(4);
Check.That(scenario2.Tags).IsEmpty();
Step givenStep2 = scenario2.Steps[0];
Check.That(givenStep2.Keyword).IsEqualTo(Keyword.Given);
Check.That(givenStep2.Name).IsEqualTo("some other feature");
Check.That(givenStep2.DocStringArgument).IsNull();
Check.That(givenStep2.TableArgument).IsNull();
Step whenStep2 = scenario2.Steps[1];
Check.That(whenStep2.Keyword).IsEqualTo(Keyword.When);
Check.That(whenStep2.Name).IsEqualTo("it runs");
Check.That(whenStep2.DocStringArgument).IsNull();
Check.That(whenStep2.TableArgument).IsNull();
Step thenStep2 = scenario2.Steps[2];
Check.That(thenStep2.Keyword).IsEqualTo(Keyword.Then);
Check.That(thenStep2.Name).IsEqualTo("I should see that this other thing happens");
Check.That(thenStep2.DocStringArgument).IsNull();
Check.That(thenStep2.TableArgument).IsNull();
Step thenStep3 = scenario2.Steps[3];
Check.That(thenStep3.Keyword).IsEqualTo(Keyword.And);
Check.That(thenStep3.Name).IsEqualTo("something else");
Check.That(thenStep3.DocStringArgument).IsNull();
Check.That(thenStep3.TableArgument).IsNull();
}
[Test]
public void ThenCanParseMostBasicFeatureSuccessfully()
{
string featureText =
@"# ignore this comment
Feature: Test
In order to do something
As a user
I want to run this scenario
Scenario: A scenario
Given some feature
When it runs
Then I should see that this thing happens";
var parser = Container.Resolve<FeatureParser>();
Feature feature = parser.Parse(new StringReader(featureText));
Check.That(feature).IsNotNull();
Check.That(feature.Name).IsEqualTo("Test");
Check.That(feature.Description.ComparisonNormalize()).IsEqualTo(@"In order to do something
As a user
I want to run this scenario".ComparisonNormalize());
Check.That(feature.FeatureElements.Count).IsEqualTo(1);
Check.That(feature.Tags).IsEmpty();
IFeatureElement scenario = feature.FeatureElements.First();
Check.That(scenario.Name).IsEqualTo("A scenario");
Check.That(scenario.Description).IsEqualTo(string.Empty);
Check.That(scenario.Steps.Count).IsEqualTo(3);
Check.That(scenario.Tags).IsEmpty();
Step givenStep = scenario.Steps[0];
Check.That(givenStep.Keyword).IsEqualTo(Keyword.Given);
Check.That(givenStep.Name).IsEqualTo("some feature");
Check.That(givenStep.DocStringArgument).IsNull();
Check.That(givenStep.TableArgument).IsNull();
Step whenStep = scenario.Steps[1];
Check.That(whenStep.Keyword).IsEqualTo(Keyword.When);
Check.That(whenStep.Name).IsEqualTo("it runs");
Check.That(whenStep.DocStringArgument).IsNull();
Check.That(whenStep.TableArgument).IsNull();
Step thenStep = scenario.Steps[2];
Check.That(thenStep.Keyword).IsEqualTo(Keyword.Then);
Check.That(thenStep.Name).IsEqualTo("I should see that this thing happens");
Check.That(thenStep.DocStringArgument).IsNull();
Check.That(thenStep.TableArgument).IsNull();
}
[Test]
public void ThenCanParseScenarioOutlinesSuccessfully()
{
string featureText =
@"# ignore this comment
Feature: Test
In order to do something
As a user
I want to run this scenario
Scenario Outline: A scenario outline
Given some feature with <keyword1>
When it runs
Then I should see <keyword2>
Examples:
| keyword1 | keyword2 |
| this | that |";
var parser = Container.Resolve<FeatureParser>();
Feature feature = parser.Parse(new StringReader(featureText));
var scenarioOutline = feature.FeatureElements[0] as ScenarioOutline;
Check.That(scenarioOutline).IsNotNull();
Check.That(scenarioOutline.Name).IsEqualTo("A scenario outline");
Check.That(scenarioOutline.Description).IsEqualTo(string.Empty);
Check.That(scenarioOutline.Steps.Count).IsEqualTo(3);
Step givenStep = scenarioOutline.Steps[0];
Check.That(givenStep.Keyword).IsEqualTo(Keyword.Given);
Check.That(givenStep.Name).IsEqualTo("some feature with <keyword1>");
Check.That(givenStep.DocStringArgument).IsNull();
Check.That(givenStep.TableArgument).IsNull();
Step whenStep = scenarioOutline.Steps[1];
Check.That(whenStep.Keyword).IsEqualTo(Keyword.When);
Check.That(whenStep.Name).IsEqualTo("it runs");
Check.That(whenStep.DocStringArgument).IsNull();
Check.That(whenStep.TableArgument).IsNull();
Step thenStep = scenarioOutline.Steps[2];
Check.That(thenStep.Keyword).IsEqualTo(Keyword.Then);
Check.That(thenStep.Name).IsEqualTo("I should see <keyword2>");
Check.That(thenStep.DocStringArgument).IsNull();
Check.That(thenStep.TableArgument).IsNull();
var examples = scenarioOutline.Examples;
Check.That(examples.First().Name).IsNullOrEmpty();
Check.That(examples.First().Description).IsNullOrEmpty();
Table table = examples.First().TableArgument;
Check.That(table.HeaderRow.Cells[0]).IsEqualTo("keyword1");
Check.That(table.HeaderRow.Cells[1]).IsEqualTo("keyword2");
Check.That(table.DataRows[0].Cells[0]).IsEqualTo("this");
Check.That(table.DataRows[0].Cells[1]).IsEqualTo("that");
}
[Test]
public void ThenCanParseScenarioWithBackgroundSuccessfully()
{
string featureText =
@"# ignore this comment
Feature: Test
In order to do something
As a user
I want to run this scenario
Background: Some background for the scenarios
Given some prior context
And yet more prior context
Scenario: A scenario
Given some feature
When it runs
Then I should see that this thing happens";
var parser = Container.Resolve<FeatureParser>();
Feature feature = parser.Parse(new StringReader(featureText));
Check.That(feature.Background).IsNotNull();
Check.That(feature.Background.Name).IsEqualTo("Some background for the scenarios");
Check.That(feature.Background.Description).IsEqualTo(string.Empty);
Check.That(feature.Background.Steps.Count).IsEqualTo(2);
Check.That(feature.Background.Tags).IsEmpty();
Step givenStep1 = feature.Background.Steps[0];
Check.That(givenStep1.Keyword).IsEqualTo(Keyword.Given);
Check.That(givenStep1.Name).IsEqualTo("some prior context");
Check.That(givenStep1.DocStringArgument).IsNull();
Check.That(givenStep1.TableArgument).IsNull();
Step givenStep2 = feature.Background.Steps[1];
Check.That(givenStep2.Keyword).IsEqualTo(Keyword.And);
Check.That(givenStep2.Name).IsEqualTo("yet more prior context");
Check.That(givenStep2.DocStringArgument).IsNull();
Check.That(givenStep2.TableArgument).IsNull();
}
[Test]
public void ThenCanParseScenarioWithDocstringSuccessfully()
{
string docstring = string.Format(
@"{0}
This is a document string
it can be many lines long
{0}",
DocStringDelimiter);
string featureText =
string.Format(
@"Feature: Test
In order to do something
As a user
I want to run this scenario
Scenario: A scenario
Given some feature
{0}
When it runs
Then I should see that this thing happens",
docstring);
var parser = Container.Resolve<FeatureParser>();
Feature feature = parser.Parse(new StringReader(featureText));
Check.That(feature.FeatureElements[0].Steps[0].DocStringArgument.ComparisonNormalize()).IsEqualTo(@"This is a document string
it can be many lines long".ComparisonNormalize());
}
[Test]
public void ThenCanParseScenarioWithTableSuccessfully()
{
string featureText =
@"# ignore this comment
Feature: Test
In order to do something
As a user
I want to run this scenario
Scenario: A scenario
Given some feature with a table
| Column1 | Column2 |
| Value 1 | Value 2 |
When it runs
Then I should see that this thing happens";
var parser = Container.Resolve<FeatureParser>();
Feature feature = parser.Parse(new StringReader(featureText));
Table table = feature.FeatureElements[0].Steps[0].TableArgument;
Check.That(table.HeaderRow.Cells[0]).IsEqualTo("Column1");
Check.That(table.HeaderRow.Cells[1]).IsEqualTo("Column2");
Check.That(table.DataRows[0].Cells[0]).IsEqualTo("Value 1");
Check.That(table.DataRows[0].Cells[1]).IsEqualTo("Value 2");
}
[Test]
public void Then_can_parse_scenario_with_tags_successfully()
{
string featureText =
@"# ignore this comment
@feature-tag
Feature: Test
In order to do something
As a user
I want to run this scenario
@scenario-tag-1 @scenario-tag-2
Scenario: A scenario
Given some feature
When it runs
Then I should see that this thing happens";
var parser = Container.Resolve<FeatureParser>();
Feature feature = parser.Parse(new StringReader(featureText));
Check.That(feature.Tags[0]).IsEqualTo("@feature-tag");
Check.That(feature.FeatureElements[0].Tags[0]).IsEqualTo("@scenario-tag-1");
Check.That(feature.FeatureElements[0].Tags[1]).IsEqualTo("@scenario-tag-2");
}
[Test]
public void Then_can_parse_scenario_with_comments_successfully()
{
string featureText =
@"# ignore this comment
Feature: Test
In order to do something
As a user
I want to run this scenario
Scenario: A scenario
# A single line comment
Given some feature
# A multiline comment - first line
# Second line
When it runs
Then I should see that this thing happens
# A last comment after the scenario";
var parser = Container.Resolve<FeatureParser>();
Feature feature = parser.Parse(new StringReader(featureText));
IFeatureElement scenario = feature.FeatureElements.First();
Step stepGiven = scenario.Steps[0];
Check.That(stepGiven.Comments.Count).IsEqualTo(1);
Check.That(stepGiven.Comments[0].Text).IsEqualTo("# A single line comment");
Step stepWhen = scenario.Steps[1];
Check.That(stepWhen.Comments.Count).IsEqualTo(2);
Check.That(stepWhen.Comments[0].Text).IsEqualTo("# A multiline comment - first line");
Check.That(stepWhen.Comments[1].Text).IsEqualTo("# Second line");
Step stepThen = scenario.Steps[2];
Check.That(stepThen.Comments.Count).IsEqualTo(1);
Check.That(stepThen.Comments.Count(o => o.Type == CommentType.StepComment)).IsEqualTo(0);
Check.That(stepThen.Comments.Count(o => o.Type == CommentType.AfterLastStepComment)).IsEqualTo(1);
Check.That(stepThen.Comments[0].Text = "# A last comment after the scenario");
}
[Test]
public void Then_can_parse_and_ignore_feature_with_tag_in_configuration_ignore_tag()
{
var featureText =
@"# ignore this comment
@feature-tag @exclude-tag
Feature: Test
In order to do something
As a user
I want to run this scenario
@scenario-tag-1 @scenario-tag-2
Scenario: A scenario
Given some feature
When it runs
Then I should see that this thing happens";
var parser = Container.Resolve<FeatureParser>();
var feature = parser.Parse(new StringReader(featureText));
Check.That(feature).IsNull();
}
[Test]
public void Then_can_parse_and_ignore_scenario_with_tag_in_configuration_ignore_tag()
{
var featureText =
@"# ignore this comment
@feature-tag
Feature: Test
In order to do something
As a user
I want to run this scenario
@scenario-tag-1 @scenario-tag-2
Scenario: A scenario
Given some feature
When it runs
Then I should see that this thing happens
@scenario-tag-1 @scenario-tag-2 @exclude-tag
Scenario: B scenario
Given some feature
When it runs
Then I should see that this thing happens
@scenario-tag-1 @scenario-tag-2
Scenario: C scenario
Given some feature
When it runs
Then I should see that this thing happens";
var parser = Container.Resolve<FeatureParser>();
var feature = parser.Parse(new StringReader(featureText));
Check.That(feature.FeatureElements.Count).IsEqualTo(2);
Check.That(feature.FeatureElements.FirstOrDefault(fe => fe.Name == "A scenario")).IsNotNull();
Check.That(feature.FeatureElements.FirstOrDefault(fe => fe.Name == "B scenario")).IsNull();
Check.That(feature.FeatureElements.FirstOrDefault(fe => fe.Name == "C scenario")).IsNotNull();
}
[Test]
public void Then_can_parse_and_ignore_scenario_with_tag_in_configuration_ignore_tag_and_keep_feature()
{
var featureText =
@"# ignore this comment
@feature-tag
Feature: Test
In order to do something
As a user
I want to run this scenario
@scenario-tag-1 @scenario-tag-2 @Exclude-Tag
Scenario: A scenario
Given some feature
When it runs
Then I should see that this thing happens
@scenario-tag-1 @scenario-tag-2 @exclude-tag
Scenario: B scenario
Given some feature
When it runs
Then I should see that this thing happens";
var parser = Container.Resolve<FeatureParser>();
var feature = parser.Parse(new StringReader(featureText));
Check.That(feature).IsNotNull();
Check.That(feature.FeatureElements).IsEmpty();
}
[Test]
public void Then_can_parse_and_ignore_with_with_tag_without_sensitivity()
{
var featureText =
@"# ignore this comment
@feature-tag
Feature: Test
In order to do something
As a user
I want to run this scenario
@scenario-tag-1 @scenario-tag-2 @Exclude-Tag
Scenario: A scenario
Given some feature
When it runs
Then I should see that this thing happens
@scenario-tag-1 @scenario-tag-2 @exclude-tag
Scenario: B scenario
Given some feature
When it runs
Then I should see that this thing happens
@scenario-tag-1 @scenario-tag-2 @ExClUdE-tAg
Scenario: C scenario
Given some feature
When it runs
Then I should see that this thing happens";
var parser = Container.Resolve<FeatureParser>();
var feature = parser.Parse(new StringReader(featureText));
Check.That(feature).IsNotNull();
Check.That(feature.FeatureElements).IsEmpty();
}
}
}
| 37.172676 | 137 | 0.635988 | [
"Apache-2.0"
] | Lordsauron/pickles | src/Pickles/Pickles.Test/WhenParsingFeatureFiles.cs | 19,592 | C# |
// <auto-generated>
// Generated by the protocol buffer compiler. DO NOT EDIT!
// source: google/ads/googleads/v9/resources/feed_item_target.proto
// </auto-generated>
#pragma warning disable 1591, 0612, 3021
#region Designer generated code
using pb = global::Google.Protobuf;
using pbc = global::Google.Protobuf.Collections;
using pbr = global::Google.Protobuf.Reflection;
using scg = global::System.Collections.Generic;
namespace Google.Ads.GoogleAds.V9.Resources {
/// <summary>Holder for reflection information generated from google/ads/googleads/v9/resources/feed_item_target.proto</summary>
public static partial class FeedItemTargetReflection {
#region Descriptor
/// <summary>File descriptor for google/ads/googleads/v9/resources/feed_item_target.proto</summary>
public static pbr::FileDescriptor Descriptor {
get { return descriptor; }
}
private static pbr::FileDescriptor descriptor;
static FeedItemTargetReflection() {
byte[] descriptorData = global::System.Convert.FromBase64String(
string.Concat(
"Cjhnb29nbGUvYWRzL2dvb2dsZWFkcy92OS9yZXNvdXJjZXMvZmVlZF9pdGVt",
"X3RhcmdldC5wcm90bxIhZ29vZ2xlLmFkcy5nb29nbGVhZHMudjkucmVzb3Vy",
"Y2VzGi1nb29nbGUvYWRzL2dvb2dsZWFkcy92OS9jb21tb24vY3JpdGVyaWEu",
"cHJvdG8aO2dvb2dsZS9hZHMvZ29vZ2xlYWRzL3Y5L2VudW1zL2ZlZWRfaXRl",
"bV90YXJnZXRfZGV2aWNlLnByb3RvGjtnb29nbGUvYWRzL2dvb2dsZWFkcy92",
"OS9lbnVtcy9mZWVkX2l0ZW1fdGFyZ2V0X3N0YXR1cy5wcm90bxo5Z29vZ2xl",
"L2Fkcy9nb29nbGVhZHMvdjkvZW51bXMvZmVlZF9pdGVtX3RhcmdldF90eXBl",
"LnByb3RvGh9nb29nbGUvYXBpL2ZpZWxkX2JlaGF2aW9yLnByb3RvGhlnb29n",
"bGUvYXBpL3Jlc291cmNlLnByb3RvGhxnb29nbGUvYXBpL2Fubm90YXRpb25z",
"LnByb3RvIqkICg5GZWVkSXRlbVRhcmdldBJGCg1yZXNvdXJjZV9uYW1lGAEg",
"ASgJQi/gQQX6QSkKJ2dvb2dsZWFkcy5nb29nbGVhcGlzLmNvbS9GZWVkSXRl",
"bVRhcmdldBJBCglmZWVkX2l0ZW0YDCABKAlCKeBBBfpBIwohZ29vZ2xlYWRz",
"Lmdvb2dsZWFwaXMuY29tL0ZlZWRJdGVtSAGIAQESbAoVZmVlZF9pdGVtX3Rh",
"cmdldF90eXBlGAMgASgOMkguZ29vZ2xlLmFkcy5nb29nbGVhZHMudjkuZW51",
"bXMuRmVlZEl0ZW1UYXJnZXRUeXBlRW51bS5GZWVkSXRlbVRhcmdldFR5cGVC",
"A+BBAxIlChNmZWVkX2l0ZW1fdGFyZ2V0X2lkGA0gASgDQgPgQQNIAogBARJh",
"CgZzdGF0dXMYCyABKA4yTC5nb29nbGUuYWRzLmdvb2dsZWFkcy52OS5lbnVt",
"cy5GZWVkSXRlbVRhcmdldFN0YXR1c0VudW0uRmVlZEl0ZW1UYXJnZXRTdGF0",
"dXNCA+BBAxI9CghjYW1wYWlnbhgOIAEoCUIp4EEF+kEjCiFnb29nbGVhZHMu",
"Z29vZ2xlYXBpcy5jb20vQ2FtcGFpZ25IABI8CghhZF9ncm91cBgPIAEoCUIo",
"4EEF+kEiCiBnb29nbGVhZHMuZ29vZ2xlYXBpcy5jb20vQWRHcm91cEgAEkMK",
"B2tleXdvcmQYByABKAsyKy5nb29nbGUuYWRzLmdvb2dsZWFkcy52OS5jb21t",
"b24uS2V5d29yZEluZm9CA+BBBUgAElEKE2dlb190YXJnZXRfY29uc3RhbnQY",
"ECABKAlCMuBBBfpBLAoqZ29vZ2xlYWRzLmdvb2dsZWFwaXMuY29tL0dlb1Rh",
"cmdldENvbnN0YW50SAASYwoGZGV2aWNlGAkgASgOMkwuZ29vZ2xlLmFkcy5n",
"b29nbGVhZHMudjkuZW51bXMuRmVlZEl0ZW1UYXJnZXREZXZpY2VFbnVtLkZl",
"ZWRJdGVtVGFyZ2V0RGV2aWNlQgPgQQVIABJKCgthZF9zY2hlZHVsZRgKIAEo",
"CzIuLmdvb2dsZS5hZHMuZ29vZ2xlYWRzLnY5LmNvbW1vbi5BZFNjaGVkdWxl",
"SW5mb0ID4EEFSAA6nQHqQZkBCidnb29nbGVhZHMuZ29vZ2xlYXBpcy5jb20v",
"RmVlZEl0ZW1UYXJnZXQSbmN1c3RvbWVycy97Y3VzdG9tZXJfaWR9L2ZlZWRJ",
"dGVtVGFyZ2V0cy97ZmVlZF9pZH1+e2ZlZWRfaXRlbV9pZH1+e2ZlZWRfaXRl",
"bV90YXJnZXRfdHlwZX1+e2ZlZWRfaXRlbV90YXJnZXRfaWR9QggKBnRhcmdl",
"dEIMCgpfZmVlZF9pdGVtQhYKFF9mZWVkX2l0ZW1fdGFyZ2V0X2lkQoACCiVj",
"b20uZ29vZ2xlLmFkcy5nb29nbGVhZHMudjkucmVzb3VyY2VzQhNGZWVkSXRl",
"bVRhcmdldFByb3RvUAFaSmdvb2dsZS5nb2xhbmcub3JnL2dlbnByb3RvL2dv",
"b2dsZWFwaXMvYWRzL2dvb2dsZWFkcy92OS9yZXNvdXJjZXM7cmVzb3VyY2Vz",
"ogIDR0FBqgIhR29vZ2xlLkFkcy5Hb29nbGVBZHMuVjkuUmVzb3VyY2VzygIh",
"R29vZ2xlXEFkc1xHb29nbGVBZHNcVjlcUmVzb3VyY2Vz6gIlR29vZ2xlOjpB",
"ZHM6Okdvb2dsZUFkczo6Vjk6OlJlc291cmNlc2IGcHJvdG8z"));
descriptor = pbr::FileDescriptor.FromGeneratedCode(descriptorData,
new pbr::FileDescriptor[] { global::Google.Ads.GoogleAds.V9.Common.CriteriaReflection.Descriptor, global::Google.Ads.GoogleAds.V9.Enums.FeedItemTargetDeviceReflection.Descriptor, global::Google.Ads.GoogleAds.V9.Enums.FeedItemTargetStatusReflection.Descriptor, global::Google.Ads.GoogleAds.V9.Enums.FeedItemTargetTypeReflection.Descriptor, global::Google.Api.FieldBehaviorReflection.Descriptor, global::Google.Api.ResourceReflection.Descriptor, global::Google.Api.AnnotationsReflection.Descriptor, },
new pbr::GeneratedClrTypeInfo(null, null, new pbr::GeneratedClrTypeInfo[] {
new pbr::GeneratedClrTypeInfo(typeof(global::Google.Ads.GoogleAds.V9.Resources.FeedItemTarget), global::Google.Ads.GoogleAds.V9.Resources.FeedItemTarget.Parser, new[]{ "ResourceName", "FeedItem", "FeedItemTargetType", "FeedItemTargetId", "Status", "Campaign", "AdGroup", "Keyword", "GeoTargetConstant", "Device", "AdSchedule" }, new[]{ "Target", "FeedItem", "FeedItemTargetId" }, null, null, null)
}));
}
#endregion
}
#region Messages
/// <summary>
/// A feed item target.
/// </summary>
public sealed partial class FeedItemTarget : pb::IMessage<FeedItemTarget>
#if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE
, pb::IBufferMessage
#endif
{
private static readonly pb::MessageParser<FeedItemTarget> _parser = new pb::MessageParser<FeedItemTarget>(() => new FeedItemTarget());
private pb::UnknownFieldSet _unknownFields;
private int _hasBits0;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public static pb::MessageParser<FeedItemTarget> Parser { get { return _parser; } }
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public static pbr::MessageDescriptor Descriptor {
get { return global::Google.Ads.GoogleAds.V9.Resources.FeedItemTargetReflection.Descriptor.MessageTypes[0]; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
pbr::MessageDescriptor pb::IMessage.Descriptor {
get { return Descriptor; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public FeedItemTarget() {
OnConstruction();
}
partial void OnConstruction();
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public FeedItemTarget(FeedItemTarget other) : this() {
_hasBits0 = other._hasBits0;
resourceName_ = other.resourceName_;
feedItem_ = other.feedItem_;
feedItemTargetType_ = other.feedItemTargetType_;
feedItemTargetId_ = other.feedItemTargetId_;
status_ = other.status_;
switch (other.TargetCase) {
case TargetOneofCase.Campaign:
Campaign = other.Campaign;
break;
case TargetOneofCase.AdGroup:
AdGroup = other.AdGroup;
break;
case TargetOneofCase.Keyword:
Keyword = other.Keyword.Clone();
break;
case TargetOneofCase.GeoTargetConstant:
GeoTargetConstant = other.GeoTargetConstant;
break;
case TargetOneofCase.Device:
Device = other.Device;
break;
case TargetOneofCase.AdSchedule:
AdSchedule = other.AdSchedule.Clone();
break;
}
_unknownFields = pb::UnknownFieldSet.Clone(other._unknownFields);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public FeedItemTarget Clone() {
return new FeedItemTarget(this);
}
/// <summary>Field number for the "resource_name" field.</summary>
public const int ResourceNameFieldNumber = 1;
private string resourceName_ = "";
/// <summary>
/// Immutable. The resource name of the feed item target.
/// Feed item target resource names have the form:
/// `customers/{customer_id}/feedItemTargets/{feed_id}~{feed_item_id}~{feed_item_target_type}~{feed_item_target_id}`
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public string ResourceName {
get { return resourceName_; }
set {
resourceName_ = pb::ProtoPreconditions.CheckNotNull(value, "value");
}
}
/// <summary>Field number for the "feed_item" field.</summary>
public const int FeedItemFieldNumber = 12;
private string feedItem_;
/// <summary>
/// Immutable. The feed item to which this feed item target belongs.
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public string FeedItem {
get { return feedItem_ ?? ""; }
set {
feedItem_ = pb::ProtoPreconditions.CheckNotNull(value, "value");
}
}
/// <summary>Gets whether the "feed_item" field is set</summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public bool HasFeedItem {
get { return feedItem_ != null; }
}
/// <summary>Clears the value of the "feed_item" field</summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public void ClearFeedItem() {
feedItem_ = null;
}
/// <summary>Field number for the "feed_item_target_type" field.</summary>
public const int FeedItemTargetTypeFieldNumber = 3;
private global::Google.Ads.GoogleAds.V9.Enums.FeedItemTargetTypeEnum.Types.FeedItemTargetType feedItemTargetType_ = global::Google.Ads.GoogleAds.V9.Enums.FeedItemTargetTypeEnum.Types.FeedItemTargetType.Unspecified;
/// <summary>
/// Output only. The target type of this feed item target. This field is read-only.
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public global::Google.Ads.GoogleAds.V9.Enums.FeedItemTargetTypeEnum.Types.FeedItemTargetType FeedItemTargetType {
get { return feedItemTargetType_; }
set {
feedItemTargetType_ = value;
}
}
/// <summary>Field number for the "feed_item_target_id" field.</summary>
public const int FeedItemTargetIdFieldNumber = 13;
private long feedItemTargetId_;
/// <summary>
/// Output only. The ID of the targeted resource. This field is read-only.
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public long FeedItemTargetId {
get { if ((_hasBits0 & 1) != 0) { return feedItemTargetId_; } else { return 0L; } }
set {
_hasBits0 |= 1;
feedItemTargetId_ = value;
}
}
/// <summary>Gets whether the "feed_item_target_id" field is set</summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public bool HasFeedItemTargetId {
get { return (_hasBits0 & 1) != 0; }
}
/// <summary>Clears the value of the "feed_item_target_id" field</summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public void ClearFeedItemTargetId() {
_hasBits0 &= ~1;
}
/// <summary>Field number for the "status" field.</summary>
public const int StatusFieldNumber = 11;
private global::Google.Ads.GoogleAds.V9.Enums.FeedItemTargetStatusEnum.Types.FeedItemTargetStatus status_ = global::Google.Ads.GoogleAds.V9.Enums.FeedItemTargetStatusEnum.Types.FeedItemTargetStatus.Unspecified;
/// <summary>
/// Output only. Status of the feed item target.
/// This field is read-only.
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public global::Google.Ads.GoogleAds.V9.Enums.FeedItemTargetStatusEnum.Types.FeedItemTargetStatus Status {
get { return status_; }
set {
status_ = value;
}
}
/// <summary>Field number for the "campaign" field.</summary>
public const int CampaignFieldNumber = 14;
/// <summary>
/// Immutable. The targeted campaign.
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public string Campaign {
get { return targetCase_ == TargetOneofCase.Campaign ? (string) target_ : ""; }
set {
target_ = pb::ProtoPreconditions.CheckNotNull(value, "value");
targetCase_ = TargetOneofCase.Campaign;
}
}
/// <summary>Field number for the "ad_group" field.</summary>
public const int AdGroupFieldNumber = 15;
/// <summary>
/// Immutable. The targeted ad group.
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public string AdGroup {
get { return targetCase_ == TargetOneofCase.AdGroup ? (string) target_ : ""; }
set {
target_ = pb::ProtoPreconditions.CheckNotNull(value, "value");
targetCase_ = TargetOneofCase.AdGroup;
}
}
/// <summary>Field number for the "keyword" field.</summary>
public const int KeywordFieldNumber = 7;
/// <summary>
/// Immutable. The targeted keyword.
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public global::Google.Ads.GoogleAds.V9.Common.KeywordInfo Keyword {
get { return targetCase_ == TargetOneofCase.Keyword ? (global::Google.Ads.GoogleAds.V9.Common.KeywordInfo) target_ : null; }
set {
target_ = value;
targetCase_ = value == null ? TargetOneofCase.None : TargetOneofCase.Keyword;
}
}
/// <summary>Field number for the "geo_target_constant" field.</summary>
public const int GeoTargetConstantFieldNumber = 16;
/// <summary>
/// Immutable. The targeted geo target constant resource name.
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public string GeoTargetConstant {
get { return targetCase_ == TargetOneofCase.GeoTargetConstant ? (string) target_ : ""; }
set {
target_ = pb::ProtoPreconditions.CheckNotNull(value, "value");
targetCase_ = TargetOneofCase.GeoTargetConstant;
}
}
/// <summary>Field number for the "device" field.</summary>
public const int DeviceFieldNumber = 9;
/// <summary>
/// Immutable. The targeted device.
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public global::Google.Ads.GoogleAds.V9.Enums.FeedItemTargetDeviceEnum.Types.FeedItemTargetDevice Device {
get { return targetCase_ == TargetOneofCase.Device ? (global::Google.Ads.GoogleAds.V9.Enums.FeedItemTargetDeviceEnum.Types.FeedItemTargetDevice) target_ : global::Google.Ads.GoogleAds.V9.Enums.FeedItemTargetDeviceEnum.Types.FeedItemTargetDevice.Unspecified; }
set {
target_ = value;
targetCase_ = TargetOneofCase.Device;
}
}
/// <summary>Field number for the "ad_schedule" field.</summary>
public const int AdScheduleFieldNumber = 10;
/// <summary>
/// Immutable. The targeted schedule.
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public global::Google.Ads.GoogleAds.V9.Common.AdScheduleInfo AdSchedule {
get { return targetCase_ == TargetOneofCase.AdSchedule ? (global::Google.Ads.GoogleAds.V9.Common.AdScheduleInfo) target_ : null; }
set {
target_ = value;
targetCase_ = value == null ? TargetOneofCase.None : TargetOneofCase.AdSchedule;
}
}
private object target_;
/// <summary>Enum of possible cases for the "target" oneof.</summary>
public enum TargetOneofCase {
None = 0,
Campaign = 14,
AdGroup = 15,
Keyword = 7,
GeoTargetConstant = 16,
Device = 9,
AdSchedule = 10,
}
private TargetOneofCase targetCase_ = TargetOneofCase.None;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public TargetOneofCase TargetCase {
get { return targetCase_; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public void ClearTarget() {
targetCase_ = TargetOneofCase.None;
target_ = null;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public override bool Equals(object other) {
return Equals(other as FeedItemTarget);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public bool Equals(FeedItemTarget other) {
if (ReferenceEquals(other, null)) {
return false;
}
if (ReferenceEquals(other, this)) {
return true;
}
if (ResourceName != other.ResourceName) return false;
if (FeedItem != other.FeedItem) return false;
if (FeedItemTargetType != other.FeedItemTargetType) return false;
if (FeedItemTargetId != other.FeedItemTargetId) return false;
if (Status != other.Status) return false;
if (Campaign != other.Campaign) return false;
if (AdGroup != other.AdGroup) return false;
if (!object.Equals(Keyword, other.Keyword)) return false;
if (GeoTargetConstant != other.GeoTargetConstant) return false;
if (Device != other.Device) return false;
if (!object.Equals(AdSchedule, other.AdSchedule)) return false;
if (TargetCase != other.TargetCase) return false;
return Equals(_unknownFields, other._unknownFields);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public override int GetHashCode() {
int hash = 1;
if (ResourceName.Length != 0) hash ^= ResourceName.GetHashCode();
if (HasFeedItem) hash ^= FeedItem.GetHashCode();
if (FeedItemTargetType != global::Google.Ads.GoogleAds.V9.Enums.FeedItemTargetTypeEnum.Types.FeedItemTargetType.Unspecified) hash ^= FeedItemTargetType.GetHashCode();
if (HasFeedItemTargetId) hash ^= FeedItemTargetId.GetHashCode();
if (Status != global::Google.Ads.GoogleAds.V9.Enums.FeedItemTargetStatusEnum.Types.FeedItemTargetStatus.Unspecified) hash ^= Status.GetHashCode();
if (targetCase_ == TargetOneofCase.Campaign) hash ^= Campaign.GetHashCode();
if (targetCase_ == TargetOneofCase.AdGroup) hash ^= AdGroup.GetHashCode();
if (targetCase_ == TargetOneofCase.Keyword) hash ^= Keyword.GetHashCode();
if (targetCase_ == TargetOneofCase.GeoTargetConstant) hash ^= GeoTargetConstant.GetHashCode();
if (targetCase_ == TargetOneofCase.Device) hash ^= Device.GetHashCode();
if (targetCase_ == TargetOneofCase.AdSchedule) hash ^= AdSchedule.GetHashCode();
hash ^= (int) targetCase_;
if (_unknownFields != null) {
hash ^= _unknownFields.GetHashCode();
}
return hash;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public override string ToString() {
return pb::JsonFormatter.ToDiagnosticString(this);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public void WriteTo(pb::CodedOutputStream output) {
#if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE
output.WriteRawMessage(this);
#else
if (ResourceName.Length != 0) {
output.WriteRawTag(10);
output.WriteString(ResourceName);
}
if (FeedItemTargetType != global::Google.Ads.GoogleAds.V9.Enums.FeedItemTargetTypeEnum.Types.FeedItemTargetType.Unspecified) {
output.WriteRawTag(24);
output.WriteEnum((int) FeedItemTargetType);
}
if (targetCase_ == TargetOneofCase.Keyword) {
output.WriteRawTag(58);
output.WriteMessage(Keyword);
}
if (targetCase_ == TargetOneofCase.Device) {
output.WriteRawTag(72);
output.WriteEnum((int) Device);
}
if (targetCase_ == TargetOneofCase.AdSchedule) {
output.WriteRawTag(82);
output.WriteMessage(AdSchedule);
}
if (Status != global::Google.Ads.GoogleAds.V9.Enums.FeedItemTargetStatusEnum.Types.FeedItemTargetStatus.Unspecified) {
output.WriteRawTag(88);
output.WriteEnum((int) Status);
}
if (HasFeedItem) {
output.WriteRawTag(98);
output.WriteString(FeedItem);
}
if (HasFeedItemTargetId) {
output.WriteRawTag(104);
output.WriteInt64(FeedItemTargetId);
}
if (targetCase_ == TargetOneofCase.Campaign) {
output.WriteRawTag(114);
output.WriteString(Campaign);
}
if (targetCase_ == TargetOneofCase.AdGroup) {
output.WriteRawTag(122);
output.WriteString(AdGroup);
}
if (targetCase_ == TargetOneofCase.GeoTargetConstant) {
output.WriteRawTag(130, 1);
output.WriteString(GeoTargetConstant);
}
if (_unknownFields != null) {
_unknownFields.WriteTo(output);
}
#endif
}
#if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
void pb::IBufferMessage.InternalWriteTo(ref pb::WriteContext output) {
if (ResourceName.Length != 0) {
output.WriteRawTag(10);
output.WriteString(ResourceName);
}
if (FeedItemTargetType != global::Google.Ads.GoogleAds.V9.Enums.FeedItemTargetTypeEnum.Types.FeedItemTargetType.Unspecified) {
output.WriteRawTag(24);
output.WriteEnum((int) FeedItemTargetType);
}
if (targetCase_ == TargetOneofCase.Keyword) {
output.WriteRawTag(58);
output.WriteMessage(Keyword);
}
if (targetCase_ == TargetOneofCase.Device) {
output.WriteRawTag(72);
output.WriteEnum((int) Device);
}
if (targetCase_ == TargetOneofCase.AdSchedule) {
output.WriteRawTag(82);
output.WriteMessage(AdSchedule);
}
if (Status != global::Google.Ads.GoogleAds.V9.Enums.FeedItemTargetStatusEnum.Types.FeedItemTargetStatus.Unspecified) {
output.WriteRawTag(88);
output.WriteEnum((int) Status);
}
if (HasFeedItem) {
output.WriteRawTag(98);
output.WriteString(FeedItem);
}
if (HasFeedItemTargetId) {
output.WriteRawTag(104);
output.WriteInt64(FeedItemTargetId);
}
if (targetCase_ == TargetOneofCase.Campaign) {
output.WriteRawTag(114);
output.WriteString(Campaign);
}
if (targetCase_ == TargetOneofCase.AdGroup) {
output.WriteRawTag(122);
output.WriteString(AdGroup);
}
if (targetCase_ == TargetOneofCase.GeoTargetConstant) {
output.WriteRawTag(130, 1);
output.WriteString(GeoTargetConstant);
}
if (_unknownFields != null) {
_unknownFields.WriteTo(ref output);
}
}
#endif
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public int CalculateSize() {
int size = 0;
if (ResourceName.Length != 0) {
size += 1 + pb::CodedOutputStream.ComputeStringSize(ResourceName);
}
if (HasFeedItem) {
size += 1 + pb::CodedOutputStream.ComputeStringSize(FeedItem);
}
if (FeedItemTargetType != global::Google.Ads.GoogleAds.V9.Enums.FeedItemTargetTypeEnum.Types.FeedItemTargetType.Unspecified) {
size += 1 + pb::CodedOutputStream.ComputeEnumSize((int) FeedItemTargetType);
}
if (HasFeedItemTargetId) {
size += 1 + pb::CodedOutputStream.ComputeInt64Size(FeedItemTargetId);
}
if (Status != global::Google.Ads.GoogleAds.V9.Enums.FeedItemTargetStatusEnum.Types.FeedItemTargetStatus.Unspecified) {
size += 1 + pb::CodedOutputStream.ComputeEnumSize((int) Status);
}
if (targetCase_ == TargetOneofCase.Campaign) {
size += 1 + pb::CodedOutputStream.ComputeStringSize(Campaign);
}
if (targetCase_ == TargetOneofCase.AdGroup) {
size += 1 + pb::CodedOutputStream.ComputeStringSize(AdGroup);
}
if (targetCase_ == TargetOneofCase.Keyword) {
size += 1 + pb::CodedOutputStream.ComputeMessageSize(Keyword);
}
if (targetCase_ == TargetOneofCase.GeoTargetConstant) {
size += 2 + pb::CodedOutputStream.ComputeStringSize(GeoTargetConstant);
}
if (targetCase_ == TargetOneofCase.Device) {
size += 1 + pb::CodedOutputStream.ComputeEnumSize((int) Device);
}
if (targetCase_ == TargetOneofCase.AdSchedule) {
size += 1 + pb::CodedOutputStream.ComputeMessageSize(AdSchedule);
}
if (_unknownFields != null) {
size += _unknownFields.CalculateSize();
}
return size;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public void MergeFrom(FeedItemTarget other) {
if (other == null) {
return;
}
if (other.ResourceName.Length != 0) {
ResourceName = other.ResourceName;
}
if (other.HasFeedItem) {
FeedItem = other.FeedItem;
}
if (other.FeedItemTargetType != global::Google.Ads.GoogleAds.V9.Enums.FeedItemTargetTypeEnum.Types.FeedItemTargetType.Unspecified) {
FeedItemTargetType = other.FeedItemTargetType;
}
if (other.HasFeedItemTargetId) {
FeedItemTargetId = other.FeedItemTargetId;
}
if (other.Status != global::Google.Ads.GoogleAds.V9.Enums.FeedItemTargetStatusEnum.Types.FeedItemTargetStatus.Unspecified) {
Status = other.Status;
}
switch (other.TargetCase) {
case TargetOneofCase.Campaign:
Campaign = other.Campaign;
break;
case TargetOneofCase.AdGroup:
AdGroup = other.AdGroup;
break;
case TargetOneofCase.Keyword:
if (Keyword == null) {
Keyword = new global::Google.Ads.GoogleAds.V9.Common.KeywordInfo();
}
Keyword.MergeFrom(other.Keyword);
break;
case TargetOneofCase.GeoTargetConstant:
GeoTargetConstant = other.GeoTargetConstant;
break;
case TargetOneofCase.Device:
Device = other.Device;
break;
case TargetOneofCase.AdSchedule:
if (AdSchedule == null) {
AdSchedule = new global::Google.Ads.GoogleAds.V9.Common.AdScheduleInfo();
}
AdSchedule.MergeFrom(other.AdSchedule);
break;
}
_unknownFields = pb::UnknownFieldSet.MergeFrom(_unknownFields, other._unknownFields);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public void MergeFrom(pb::CodedInputStream input) {
#if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE
input.ReadRawMessage(this);
#else
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
_unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input);
break;
case 10: {
ResourceName = input.ReadString();
break;
}
case 24: {
FeedItemTargetType = (global::Google.Ads.GoogleAds.V9.Enums.FeedItemTargetTypeEnum.Types.FeedItemTargetType) input.ReadEnum();
break;
}
case 58: {
global::Google.Ads.GoogleAds.V9.Common.KeywordInfo subBuilder = new global::Google.Ads.GoogleAds.V9.Common.KeywordInfo();
if (targetCase_ == TargetOneofCase.Keyword) {
subBuilder.MergeFrom(Keyword);
}
input.ReadMessage(subBuilder);
Keyword = subBuilder;
break;
}
case 72: {
target_ = input.ReadEnum();
targetCase_ = TargetOneofCase.Device;
break;
}
case 82: {
global::Google.Ads.GoogleAds.V9.Common.AdScheduleInfo subBuilder = new global::Google.Ads.GoogleAds.V9.Common.AdScheduleInfo();
if (targetCase_ == TargetOneofCase.AdSchedule) {
subBuilder.MergeFrom(AdSchedule);
}
input.ReadMessage(subBuilder);
AdSchedule = subBuilder;
break;
}
case 88: {
Status = (global::Google.Ads.GoogleAds.V9.Enums.FeedItemTargetStatusEnum.Types.FeedItemTargetStatus) input.ReadEnum();
break;
}
case 98: {
FeedItem = input.ReadString();
break;
}
case 104: {
FeedItemTargetId = input.ReadInt64();
break;
}
case 114: {
Campaign = input.ReadString();
break;
}
case 122: {
AdGroup = input.ReadString();
break;
}
case 130: {
GeoTargetConstant = input.ReadString();
break;
}
}
}
#endif
}
#if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
void pb::IBufferMessage.InternalMergeFrom(ref pb::ParseContext input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
_unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, ref input);
break;
case 10: {
ResourceName = input.ReadString();
break;
}
case 24: {
FeedItemTargetType = (global::Google.Ads.GoogleAds.V9.Enums.FeedItemTargetTypeEnum.Types.FeedItemTargetType) input.ReadEnum();
break;
}
case 58: {
global::Google.Ads.GoogleAds.V9.Common.KeywordInfo subBuilder = new global::Google.Ads.GoogleAds.V9.Common.KeywordInfo();
if (targetCase_ == TargetOneofCase.Keyword) {
subBuilder.MergeFrom(Keyword);
}
input.ReadMessage(subBuilder);
Keyword = subBuilder;
break;
}
case 72: {
target_ = input.ReadEnum();
targetCase_ = TargetOneofCase.Device;
break;
}
case 82: {
global::Google.Ads.GoogleAds.V9.Common.AdScheduleInfo subBuilder = new global::Google.Ads.GoogleAds.V9.Common.AdScheduleInfo();
if (targetCase_ == TargetOneofCase.AdSchedule) {
subBuilder.MergeFrom(AdSchedule);
}
input.ReadMessage(subBuilder);
AdSchedule = subBuilder;
break;
}
case 88: {
Status = (global::Google.Ads.GoogleAds.V9.Enums.FeedItemTargetStatusEnum.Types.FeedItemTargetStatus) input.ReadEnum();
break;
}
case 98: {
FeedItem = input.ReadString();
break;
}
case 104: {
FeedItemTargetId = input.ReadInt64();
break;
}
case 114: {
Campaign = input.ReadString();
break;
}
case 122: {
AdGroup = input.ReadString();
break;
}
case 130: {
GeoTargetConstant = input.ReadString();
break;
}
}
}
}
#endif
}
#endregion
}
#endregion Designer generated code
| 42.107831 | 509 | 0.672276 | [
"Apache-2.0"
] | friedenberg/google-ads-dotnet | src/V9/Types/FeedItemTarget.g.cs | 32,802 | 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 Amica.Models.Resources {
using System;
using System.Reflection;
/// <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", "15.0.0.0")]
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
public class TransportModeResources {
private static global::System.Resources.ResourceManager resourceMan;
private static global::System.Globalization.CultureInfo resourceCulture;
[global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
internal TransportModeResources() {
}
/// <summary>
/// Returns the cached ResourceManager instance used by this class.
/// </summary>
[global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
public static global::System.Resources.ResourceManager ResourceManager {
get {
if (object.ReferenceEquals(resourceMan, null)) {
global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("Amica.Models.Resources.TransportModeResources", typeof(TransportModeResources).GetTypeInfo().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)]
public static global::System.Globalization.CultureInfo Culture {
get {
return resourceCulture;
}
set {
resourceCulture = value;
}
}
/// <summary>
/// Looks up a localized string similar to Corriere.
/// </summary>
public static string Courier {
get {
return ResourceManager.GetString("Courier", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Destinatario.
/// </summary>
public static string Recipient {
get {
return ResourceManager.GetString("Recipient", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Mittente.
/// </summary>
public static string Sender {
get {
return ResourceManager.GetString("Sender", resourceCulture);
}
}
}
}
| 40.315217 | 217 | 0.591264 | [
"BSD-3-Clause"
] | CIR2000/Amica.Models | Models/Resources/TransportModeResources.Designer.cs | 3,711 | C# |
//
// relationType.cs.cs
//
// This file was generated by XMLSPY 2004 Enterprise Edition.
//
// YOU SHOULD NOT MODIFY THIS FILE, BECAUSE IT WILL BE
// OVERWRITTEN WHEN YOU RE-RUN CODE GENERATION.
//
// Refer to the XMLSPY Documentation for further details.
// http://www.altova.com/xmlspy
//
using System;
using System.Collections;
using System.Xml;
using Altova.Types;
namespace imsmd_rootv1p2p1
{
public class relationType : Altova.Node
{
#region Forward constructors
public relationType() : base() { SetCollectionParents(); }
public relationType(XmlDocument doc) : base(doc) { SetCollectionParents(); }
public relationType(XmlNode node) : base(node) { SetCollectionParents(); }
public relationType(Altova.Node node) : base(node) { SetCollectionParents(); }
#endregion // Forward constructors
public override void AdjustPrefix()
{
int nCount;
nCount = DomChildCount(NodeType.Element, "http://www.imsglobal.org/xsd/imsmd_rootv1p2p1", "kind");
for (int i = 0; i < nCount; i++)
{
XmlNode DOMNode = GetDomChildAt(NodeType.Element, "http://www.imsglobal.org/xsd/imsmd_rootv1p2p1", "kind", i);
InternalAdjustPrefix(DOMNode, true);
new kindType(DOMNode).AdjustPrefix();
}
nCount = DomChildCount(NodeType.Element, "http://www.imsglobal.org/xsd/imsmd_rootv1p2p1", "resource");
for (int i = 0; i < nCount; i++)
{
XmlNode DOMNode = GetDomChildAt(NodeType.Element, "http://www.imsglobal.org/xsd/imsmd_rootv1p2p1", "resource", i);
InternalAdjustPrefix(DOMNode, true);
new resourceType(DOMNode).AdjustPrefix();
}
}
#region kind accessor methods
public int GetkindMinCount()
{
return 0;
}
public int kindMinCount
{
get
{
return 0;
}
}
public int GetkindMaxCount()
{
return 1;
}
public int kindMaxCount
{
get
{
return 1;
}
}
public int GetkindCount()
{
return DomChildCount(NodeType.Element, "http://www.imsglobal.org/xsd/imsmd_rootv1p2p1", "kind");
}
public int kindCount
{
get
{
return DomChildCount(NodeType.Element, "http://www.imsglobal.org/xsd/imsmd_rootv1p2p1", "kind");
}
}
public bool Haskind()
{
return HasDomChild(NodeType.Element, "http://www.imsglobal.org/xsd/imsmd_rootv1p2p1", "kind");
}
public kindType GetkindAt(int index)
{
return new kindType(GetDomChildAt(NodeType.Element, "http://www.imsglobal.org/xsd/imsmd_rootv1p2p1", "kind", index));
}
public kindType Getkind()
{
return GetkindAt(0);
}
public kindType kind
{
get
{
return GetkindAt(0);
}
}
public void RemovekindAt(int index)
{
RemoveDomChildAt(NodeType.Element, "http://www.imsglobal.org/xsd/imsmd_rootv1p2p1", "kind", index);
}
public void Removekind()
{
while (Haskind())
RemovekindAt(0);
}
public void Addkind(kindType newValue)
{
AppendDomElement("http://www.imsglobal.org/xsd/imsmd_rootv1p2p1", "kind", newValue);
}
public void InsertkindAt(kindType newValue, int index)
{
InsertDomElementAt("http://www.imsglobal.org/xsd/imsmd_rootv1p2p1", "kind", index, newValue);
}
public void ReplacekindAt(kindType newValue, int index)
{
ReplaceDomElementAt("http://www.imsglobal.org/xsd/imsmd_rootv1p2p1", "kind", index, newValue);
}
#endregion // kind accessor methods
#region kind collection
public kindCollection Mykinds = new kindCollection( );
public class kindCollection: IEnumerable
{
relationType parent;
public relationType Parent
{
set
{
parent = value;
}
}
public kindEnumerator GetEnumerator()
{
return new kindEnumerator(parent);
}
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
}
public class kindEnumerator: IEnumerator
{
int nIndex;
relationType parent;
public kindEnumerator(relationType par)
{
parent = par;
nIndex = -1;
}
public void Reset()
{
nIndex = -1;
}
public bool MoveNext()
{
nIndex++;
return(nIndex < parent.kindCount );
}
public kindType Current
{
get
{
return(parent.GetkindAt(nIndex));
}
}
object IEnumerator.Current
{
get
{
return(Current);
}
}
}
#endregion // kind collection
#region resource accessor methods
public int GetresourceMinCount()
{
return 0;
}
public int resourceMinCount
{
get
{
return 0;
}
}
public int GetresourceMaxCount()
{
return 1;
}
public int resourceMaxCount
{
get
{
return 1;
}
}
public int GetresourceCount()
{
return DomChildCount(NodeType.Element, "http://www.imsglobal.org/xsd/imsmd_rootv1p2p1", "resource");
}
public int resourceCount
{
get
{
return DomChildCount(NodeType.Element, "http://www.imsglobal.org/xsd/imsmd_rootv1p2p1", "resource");
}
}
public bool Hasresource()
{
return HasDomChild(NodeType.Element, "http://www.imsglobal.org/xsd/imsmd_rootv1p2p1", "resource");
}
public resourceType GetresourceAt(int index)
{
return new resourceType(GetDomChildAt(NodeType.Element, "http://www.imsglobal.org/xsd/imsmd_rootv1p2p1", "resource", index));
}
public resourceType Getresource()
{
return GetresourceAt(0);
}
public resourceType resource
{
get
{
return GetresourceAt(0);
}
}
public void RemoveresourceAt(int index)
{
RemoveDomChildAt(NodeType.Element, "http://www.imsglobal.org/xsd/imsmd_rootv1p2p1", "resource", index);
}
public void Removeresource()
{
while (Hasresource())
RemoveresourceAt(0);
}
public void Addresource(resourceType newValue)
{
AppendDomElement("http://www.imsglobal.org/xsd/imsmd_rootv1p2p1", "resource", newValue);
}
public void InsertresourceAt(resourceType newValue, int index)
{
InsertDomElementAt("http://www.imsglobal.org/xsd/imsmd_rootv1p2p1", "resource", index, newValue);
}
public void ReplaceresourceAt(resourceType newValue, int index)
{
ReplaceDomElementAt("http://www.imsglobal.org/xsd/imsmd_rootv1p2p1", "resource", index, newValue);
}
#endregion // resource accessor methods
#region resource collection
public resourceCollection Myresources = new resourceCollection( );
public class resourceCollection: IEnumerable
{
relationType parent;
public relationType Parent
{
set
{
parent = value;
}
}
public resourceEnumerator GetEnumerator()
{
return new resourceEnumerator(parent);
}
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
}
public class resourceEnumerator: IEnumerator
{
int nIndex;
relationType parent;
public resourceEnumerator(relationType par)
{
parent = par;
nIndex = -1;
}
public void Reset()
{
nIndex = -1;
}
public bool MoveNext()
{
nIndex++;
return(nIndex < parent.resourceCount );
}
public resourceType Current
{
get
{
return(parent.GetresourceAt(nIndex));
}
}
object IEnumerator.Current
{
get
{
return(Current);
}
}
}
#endregion // resource collection
private void SetCollectionParents()
{
Mykinds.Parent = this;
Myresources.Parent = this;
}
}
}
| 20.62117 | 128 | 0.654194 | [
"MIT"
] | Zenithcoder/SCORM-LearningManagementSystem | SCORM_XMLObjects/V1_2/imsmd_rootv1p2p1/relationType.cs | 7,403 | C# |
namespace WildFarm.Models.Animals.Mammals.Felines
{
using System;
using System.Collections.Generic;
public class Cat : Feline
{
private const double IncreaseWeight = 0.30;
private List<string> eatableFood = new List<string> { "Vegetable", "Meat", };
public Cat(string name, double weight, string livingRegion, string breed)
: base(name, weight, livingRegion, breed)
{
}
protected override List<string> EatableFood => this.eatableFood;
protected override double WeightGainPerPieceOfFood => IncreaseWeight;
public override string ProduceSound() => "Meow";
}
}
| 30 | 85 | 0.657576 | [
"MIT"
] | ivanov-mi/SoftUni-Training | 03CSharpOOP/05Polymorphism/03WildFarm/Models/Animals/Mammals/Felines/Cat.cs | 662 | C# |
using System;
using System.Collections.Generic;
using System.Text;
namespace EFFC.Frame.Net.Module.Extend.WebGo.Logic
{
public abstract partial class GoLogic
{
Extentions _ext = null;
public Extentions ExtFunc
{
get
{
if (_ext == null) _ext = new Extentions(this);
return _ext;
}
}
public class Extentions
{
GoLogic _logic;
public Extentions(GoLogic logic)
{
_logic = logic;
}
}
}
}
| 18.40625 | 62 | 0.490662 | [
"BSD-2-Clause"
] | redwolf0817/EFFC.Frame.Net.Core | EFFC.Frame.Net.Module.Go/Logic/GoLogic.Extention.cs | 591 | C# |
using MathNet.Numerics;
using MathNet.Numerics.LinearAlgebra;
using RecSys.Numerical;
using System;
using System.Collections.Generic;
using System.Linq;
namespace RecSys.Core
{
/// <summary>
/// This class implements core functions for item recommendations.
/// </summary>
public class ItemRecommendationCore
{
#region GetTopNItemsByUser
/// <summary>
/// Get the top N items of each user.
/// The selection is based on the values stored in the matrix,
/// where an item with higher value is considered as better.
/// </summary>
/// <param name="R">The user-by-item matrix,
/// each value indicates the quality of the item to a user.</param>
/// <param name="topN">The number of items to be recommended for each user.</param>
/// <returns>Each Key is a user and Value is the top N recommended items for that user.</returns>
public static Dictionary<int, List<int>> GetTopNItemsByUser(DataMatrix R, int topN)
{
int userCount = R.UserCount;
int itemCount = R.ItemCount;
Dictionary<int, List<int>> topNItemsByUser = new Dictionary<int, List<int>>(userCount);
// Select top N items for each user
foreach (Tuple<int, Vector<double>> user in R.Users)
{
int indexOfUser = user.Item1;
// To be sorted soon
List<double> ratingsOfItemsSortedByRating = user.Item2.ToList();
// TODO: this is important, because some models like PrefNMF may produce
// negative scores, without setting the 0 to negative infinity these
// items will be ranked before the test items and they are always not relevant items!
ratingsOfItemsSortedByRating.ForEach(x => x = x == 0 ? double.NegativeInfinity : x);
List<int> indexesOfItemsSortedByRating = Enumerable.Range(0, ratingsOfItemsSortedByRating.Count).ToList();
// Sort by rating
Sorting.Sort<double, int>(ratingsOfItemsSortedByRating, indexesOfItemsSortedByRating);
// Make it descending order by rating
ratingsOfItemsSortedByRating.Reverse();
indexesOfItemsSortedByRating.Reverse();
topNItemsByUser[indexOfUser] = indexesOfItemsSortedByRating.GetRange(0, topN);
// In case the ratings of the top N items need to be stored
// in the future, implement the following:
//for (int i = 0; i < topN; ++i)
//{
// ratingsOfItemsSortedByRating[i] is the rating of the ith item in topN list
// indexesOfItemsSortedByRating[i] is the index (in the R) of the ith item in topN list
//}
}
return topNItemsByUser;
}
#endregion
#region GetRelevantItemsByUser
// Get the relevant items of each user, i.e. rated no lower than the criteria
public static Dictionary<int, List<int>> GetRelevantItemsByUser(DataMatrix R, double criteria)
{
int userCount = R.UserCount;
int itemCount = R.ItemCount;
Dictionary<int, List<int>> relevantItemsByUser = new Dictionary<int, List<int>>(userCount);
// Select relevant items for each user
foreach (Tuple<int, Vector<double>> user in R.Users)
{
int userIndex = user.Item1;
RatingVector userRatings = new RatingVector(user.Item2);
List<int> relevantItems = new List<int>();
foreach (Tuple<int, double> element in userRatings.Ratings)
{
int itemIndex = element.Item1;
double rating = element.Item2;
if (rating >= criteria)
{
// This is a relevant item
relevantItems.Add(itemIndex);
}
}
relevantItemsByUser[userIndex] = relevantItems;
}
return relevantItemsByUser;
}
#endregion
}
}
| 41.643564 | 122 | 0.584879 | [
"MIT"
] | wubin7019088/RecSys | src/RecSys/Core/ItemRecommendationCore.cs | 4,208 | C# |
using System.Web.Mvc;
using Microsoft.Practices.Unity;
using Unity.Mvc5;
using Services;
namespace InsurerWebApplication
{
public static class UnityConfig
{
public static void RegisterComponents()
{
var container = new UnityContainer();
// register all your components with the container here
// it is NOT necessary to register your controllers
container.RegisterType<ICustomer, svcCustomer>();
container.RegisterType<IQuote, svcQuote>();
DependencyResolver.SetResolver(new UnityDependencyResolver(container));
}
}
} | 30.136364 | 84 | 0.631976 | [
"MIT"
] | petronerd/purus | InsurerWebApplication/App_Start/UnityConfig.cs | 663 | C# |
using Newtonsoft.Json;
namespace Ptv.Timetable
{
[JsonObject()]
public class Gps : Item
{
[JsonProperty(PropertyName = "longitude", NullValueHandling = NullValueHandling.Include)]
public double Longitude { get; set; }
[JsonProperty(PropertyName = "latitude", NullValueHandling = NullValueHandling.Include)]
public double Latitude { get; set; }
}
}
| 26.6 | 97 | 0.671679 | [
"Apache-2.0"
] | huming2207/Ptv.Net | Ptv/Timetable/gps.cs | 401 | C# |
using System.Collections.Generic;
using System.Linq;
namespace UniDi
{
[NoReflectionBaking]
public class FactoryArgumentsToChoiceBinder<TParam1, TParam2, TParam3, TParam4, TParam5, TContract> : FactoryToChoiceBinder<TParam1, TParam2, TParam3, TParam4, TParam5, TContract>
{
public FactoryArgumentsToChoiceBinder(
DiContainer bindContainer, BindInfo bindInfo, FactoryBindInfo factoryBindInfo)
: base(bindContainer, bindInfo, factoryBindInfo)
{
}
// We use generics instead of params object[] so that we preserve type info
// So that you can for example pass in a variable that is null and the type info will
// still be used to map null on to the correct field
public FactoryToChoiceBinder<TParam1, TParam2, TParam3, TParam4, TParam5, TContract> WithFactoryArguments<T>(T param)
{
FactoryBindInfo.Arguments = InjectUtil.CreateArgListExplicit(param);
return this;
}
public FactoryToChoiceBinder<TParam1, TParam2, TParam3, TParam4, TParam5, TContract> WithFactoryArguments<TFactoryParam1, TFactoryParam2>(TFactoryParam1 param1, TFactoryParam2 param2)
{
FactoryBindInfo.Arguments = InjectUtil.CreateArgListExplicit(param1, param2);
return this;
}
public FactoryToChoiceBinder<TParam1, TParam2, TParam3, TParam4, TParam5, TContract> WithFactoryArguments<TFactoryParam1, TFactoryParam2, TFactoryParam3>(
TFactoryParam1 param1, TFactoryParam2 param2, TFactoryParam3 param3)
{
FactoryBindInfo.Arguments = InjectUtil.CreateArgListExplicit(param1, param2, param3);
return this;
}
public FactoryToChoiceBinder<TParam1, TParam2, TParam3, TParam4, TParam5, TContract> WithFactoryArguments<TFactoryParam1, TFactoryParam2, TFactoryParam3, TFactoryParam4>(
TFactoryParam1 param1, TFactoryParam2 param2, TFactoryParam3 param3, TFactoryParam4 param4)
{
FactoryBindInfo.Arguments = InjectUtil.CreateArgListExplicit(param1, param2, param3, param4);
return this;
}
public FactoryToChoiceBinder<TParam1, TParam2, TParam3, TParam4, TParam5, TContract> WithFactoryArguments<TFactoryParam1, TFactoryParam2, TFactoryParam3, TFactoryParam4, TFactoryParam5>(
TFactoryParam1 param1, TFactoryParam2 param2, TFactoryParam3 param3, TFactoryParam4 param4, TFactoryParam5 param5)
{
FactoryBindInfo.Arguments = InjectUtil.CreateArgListExplicit(param1, param2, param3, param4, param5);
return this;
}
public FactoryToChoiceBinder<TParam1, TParam2, TParam3, TParam4, TParam5, TContract> WithFactoryArguments<TFactoryParam1, TFactoryParam2, TFactoryParam3, TFactoryParam4, TFactoryParam5, TFactoryParam6>(
TFactoryParam1 param1, TFactoryParam2 param2, TFactoryParam3 param3, TFactoryParam4 param4, TFactoryParam5 param5, TFactoryParam6 param6)
{
FactoryBindInfo.Arguments = InjectUtil.CreateArgListExplicit(param1, param2, param3, param4, param5, param6);
return this;
}
public FactoryToChoiceBinder<TParam1, TParam2, TParam3, TParam4, TParam5, TContract> WithFactoryArguments(object[] args)
{
FactoryBindInfo.Arguments = InjectUtil.CreateArgList(args);
return this;
}
public FactoryToChoiceBinder<TParam1, TParam2, TParam3, TParam4, TParam5, TContract> WithFactoryArgumentsExplicit(IEnumerable<TypeValuePair> extraArgs)
{
FactoryBindInfo.Arguments = extraArgs.ToList();
return this;
}
}
}
| 51.138889 | 210 | 0.712928 | [
"Apache-2.0"
] | UniDi/UniDi | Source/Binding/Binders/Factory/FactoryArgumentsToChoiceBinder/FactoryArgumentsToChoiceBinder5.cs | 3,682 | C# |
namespace ProductShop.App.Models
{
using System.Collections.Generic;
public class ShortUserProductsModel
{
public string FirstName { get; set; }
public string LastName { get; set; }
public List<ShortProductModel> Products { get; set; }
}
} | 21.769231 | 61 | 0.65371 | [
"MIT"
] | thelad43/Databases-Advanced-Entity-Framework-SoftUni | 10. Exercise JSON Processing/Product Shop/ProductShop/ProductShop.App/Models/ShortUserProductsModel.cs | 285 | C# |
//===================================================================================
// Microsoft patterns & practices
// Composite Application Guidance for Windows Presentation Foundation and Silverlight
//===================================================================================
// Copyright (c) Microsoft Corporation. All rights reserved.
// THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY
// OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT
// LIMITED TO THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
// FITNESS FOR A PARTICULAR PURPOSE.
//===================================================================================
// The example companies, organizations, products, domain names,
// e-mail addresses, logos, people, places, and events depicted
// herein are fictitious. No association with any real company,
// organization, product, domain name, email address, logo, person,
// places, or events is intended or should be inferred.
//===================================================================================
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Automation;
using Modularity.Tests.AcceptanceTest.TestEntities.Page;
using AcceptanceTestLibrary.Common;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using AcceptanceTestLibrary.ApplicationHelper;
namespace Modularity.Tests.AcceptanceTest.TestEntities.Assertion
{
public static class ShellAssertion<TApp>
where TApp : AppLauncherBase, new()
{
#region Defining modules in code
//check if Modules A, B and D have been loaded as expected
public static void AssertDefiningModulesInCode()
{
InternalAssertControls();
}
public static void AssertOnDemandDefineModulesInCodeCLoading()
{
InternalAssertControl(Shell<TApp>.ModuleC, "Loading of Module C failed");
}
#endregion
#region Remote Module Loading
//check if Modules Y and Z have been loaded as expected
public static void AssertRemoteModuleLoading()
{
InternalAssertControl(Shell<TApp>.ModuleY, "Loading of Module Y failed");
InternalAssertControl(Shell<TApp>.ModuleZ, "Loading of Module Z failed");
InternalAssertControl(Shell<TApp>.ModuleW, "Loading of Module W failed");
}
public static void AssertOnDemandRemoteModuleXLoading()
{
InternalAssertControl(Shell<TApp>.ModuleX, "Loading of Module X failed");
}
#endregion
#region Directory Lookup Module Loading
//check if Modules A, B and D have been loaded as expected
public static void AssertDirectoryLookupModuleLoading()
{
InternalAssertControls();
}
public static void AssertOnDemandDirectoryLookupModuleCLoading()
{
InternalAssertControl(Shell<TApp>.ModuleC, "Loading of Module C failed");
}
#endregion
#region Configuration Module Loading
//check if Modules A, B and D have been loaded as expected
public static void AssertConfigurationModuleLoading()
{
InternalAssertControls();
}
public static void AssertOnDemandConfigurationModuleCLoading()
{
InternalAssertControl(Shell<TApp>.ModuleC, "Loading of Module C failed");
}
#endregion
private static void InternalAssertControls()
{
InternalAssertControl(Shell<TApp>.ModuleA, "Loading of Module A failed");
InternalAssertControl(Shell<TApp>.ModuleB, "Loading of Module B failed");
InternalAssertControl(Shell<TApp>.ModuleD, "Loading of Module D failed");
}
private static void InternalAssertControl(AutomationElement control, string message)
{
Assert.IsNotNull(control, message);
}
}
}
| 37.87619 | 92 | 0.625597 | [
"Apache-2.0"
] | andrewdbond/CompositeWPF | sourceCode/compositewpf/V2.2/trunk/Quickstarts/Modularity/Modularity.Tests.AcceptanceTest/Modularity.Tests.AcceptanceTest/TestEntities/Assertion/ShellAssertion.cs | 3,977 | C# |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class AdditionalInfo : MonoBehaviour {
[SerializeField]
string header;
//[SerializeField]
//string line1;
//[SerializeField]
//string line2;
//[SerializeField]
//string line3;
//[SerializeField]
//string line4;
//[SerializeField]
//string line5;
//[SerializeField]
//string line6;
//[SerializeField]
//string line7;
//[SerializeField]
//string line8;
[SerializeField]
string[] lines = new string[8];
public string GetHeader()
{
return header;
}
public string[] GetLines()
{
return lines;
}
//// Use this for initialization
//void Start () {
//}
//// Update is called once per frame
//void Update () {
//}
}
| 17.625 | 45 | 0.589835 | [
"Apache-2.0"
] | InconstantUA/CastleBite | Castle Bite/Assets/Script/Generic/AdditionalInfo.cs | 848 | C# |
using Mono.Addins;
using System.Reflection;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("Addin.XSLT")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("SIL")]
[assembly: AssemblyProduct("Addin.XSLT")]
[assembly: AssemblyCopyright("Copyright © SIL 2007")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("a8757a37-99f8-4d54-a662-e7e6fdf666e0")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Revision and Build Numbers
// by using the '*' as shown below:
[assembly: AssemblyVersion("1.9.0.10")]
[assembly: AssemblyFileVersion("1.9.0.10")]
[assembly: Addin]
[assembly: AddinDependency("WeSay.AddinLib", "1.0")] | 34.365854 | 84 | 0.745209 | [
"MIT-0",
"MIT"
] | MaxMood96/wesay | src/Addin.Transform/Properties/AssemblyInfo.cs | 1,410 | 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>
//------------------------------------------------------------------------------
namespace ASC.Web.CRM.Controls.Settings {
public partial class VoipCalls {
/// <summary>
/// controlsHolder control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.PlaceHolder controlsHolder;
}
}
| 31.6 | 84 | 0.481013 | [
"Apache-2.0"
] | Ektai-Solution-Pty-Ltd/CommunityServer | web/studio/ASC.Web.Studio/Products/CRM/Controls/Settings/VoipSettings/VoipCalls.ascx.designer.cs | 790 | C# |
using Amazon.JSII.Runtime.Deputy;
#pragma warning disable CS0672,CS0809,CS1591
namespace aws
{
[JsiiInterface(nativeType: typeof(IWafv2WebAclRuleStatementOrStatementStatementOrStatementStatementXssMatchStatementFieldToMatchMethod), fullyQualifiedName: "aws.Wafv2WebAclRuleStatementOrStatementStatementOrStatementStatementXssMatchStatementFieldToMatchMethod")]
public interface IWafv2WebAclRuleStatementOrStatementStatementOrStatementStatementXssMatchStatementFieldToMatchMethod
{
[JsiiTypeProxy(nativeType: typeof(IWafv2WebAclRuleStatementOrStatementStatementOrStatementStatementXssMatchStatementFieldToMatchMethod), fullyQualifiedName: "aws.Wafv2WebAclRuleStatementOrStatementStatementOrStatementStatementXssMatchStatementFieldToMatchMethod")]
internal sealed class _Proxy : DeputyBase, aws.IWafv2WebAclRuleStatementOrStatementStatementOrStatementStatementXssMatchStatementFieldToMatchMethod
{
private _Proxy(ByRefValue reference): base(reference)
{
}
}
}
}
| 52.3 | 272 | 0.835564 | [
"MIT"
] | scottenriquez/cdktf-alpha-csharp-testing | resources/.gen/aws/aws/IWafv2WebAclRuleStatementOrStatementStatementOrStatementStatementXssMatchStatementFieldToMatchMethod.cs | 1,046 | C# |
using DbStatute.Fundamentals.Multiples;
using DbStatute.Interfaces;
using DbStatute.Interfaces.Multiples;
using RepoDb;
using RepoDb.Enumerations;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Threading.Tasks;
namespace DbStatute.Multiples
{
public class MultipleSelectByIds<TModel> : MultipleSelectBase<TModel>, IMultipleSelectByIds<TModel>
where TModel : class, IModel, new()
{
public MultipleSelectByIds(IEnumerable<object> ids)
{
Ids = ids ?? throw new ArgumentNullException(nameof(ids));
}
public IEnumerable<object> Ids { get; }
protected override async IAsyncEnumerable<TModel> SelectAsSignlyOperationAsync(IDbConnection dbConnection)
{
foreach (object id in Ids)
{
TModel selectedModel = await dbConnection.QueryAsync<TModel>(id, null, null, 1, Hints, Cacheable?.Key, Cacheable?.ItemExpiration, CommandTimeout, Transaction, Cacheable?.Cache, Trace, StatementBuilder)
.ContinueWith(x => x.Result.FirstOrDefault());
if (selectedModel is null)
{
continue;
}
yield return selectedModel;
}
}
protected override async Task<IEnumerable<TModel>> SelectOperationAsync(IDbConnection dbConnection)
{
QueryField queryField = new QueryField("Id", Operation.In, Ids);
return await dbConnection.QueryAsync<TModel>(queryField, null, null, 1, Hints, Cacheable?.Key, Cacheable?.ItemExpiration, CommandTimeout, Transaction, Cacheable?.Cache, Trace, StatementBuilder);
}
}
} | 36.489362 | 217 | 0.66414 | [
"MIT"
] | alper-atay/DbStatute | DbStatute/DbStatute/Multiples/MultipleSelectByIds.cs | 1,717 | C# |
using System;
using Sitecore.Data;
using Sitecore.Data.Fields;
using Sitecore.Data.Items;
using Sitecore.Layouts;
using Sitecore.SecurityModel;
namespace Sitecore.Demo.Edge.Foundation.BranchPresets
{
public static class LayoutHelper
{
/// <summary>
/// Helper method that loops over all Shared and Final renderings in all devices attached to an item and invokes a function on each of them. The function may request the deletion of the item
/// by returning a specific enum value.
/// </summary>
public static void ApplyActionToAllRenderings(Item item, Func<RenderingDefinition, RenderingActionResult> action)
{
ApplyActionToAllSharedRenderings(item, action);
ApplyActionToAllFinalRenderings(item, action);
}
/// <summary>
/// Helper method that loops over all Shared renderings in all devices attached to an item and invokes a function on each of them. The function may request the deletion of the item
/// by returning a specific enum value.
/// </summary>
public static void ApplyActionToAllSharedRenderings(Item item, Func<RenderingDefinition, RenderingActionResult> action)
{
// NOTE: when dealing with layouts its important to get and set the field value with LayoutField.Get/SetFieldValue()
// if you fail to do this you will not process layout deltas correctly and may instead override all fields (breaking full inheritance),
// or attempt to get the layout definition for a delta value, which will result in your wiping the layout details when they get saved.
ApplyActionToAllRenderings(item, FieldIDs.LayoutField, action);
}
/// <summary>
/// Helper method that loops over all Final renderings in all devices attached to an item and invokes a function on each of them. The function may request the deletion of the item
/// by returning a specific enum value.
/// </summary>
public static void ApplyActionToAllFinalRenderings(Item item, Func<RenderingDefinition, RenderingActionResult> action)
{
// NOTE: when dealing with layouts its important to get and set the field value with LayoutField.Get/SetFieldValue()
// if you fail to do this you will not process layout deltas correctly and may instead override all fields (breaking full inheritance),
// or attempt to get the layout definition for a delta value, which will result in your wiping the layout details when they get saved.
ApplyActionToAllRenderings(item, FieldIDs.FinalLayoutField, action);
}
private static void ApplyActionToAllRenderings(Item item, ID fieldId, Func<RenderingDefinition, RenderingActionResult> action)
{
string currentLayoutXml = LayoutField.GetFieldValue(item.Fields[fieldId]);
if (string.IsNullOrEmpty(currentLayoutXml)) return;
var newXml = ApplyActionToLayoutXml(currentLayoutXml, action);
// save a modified layout value if necessary
if (newXml != null)
{
using (new SecurityDisabler())
using (new EditContext(item))
LayoutField.SetFieldValue(item.Fields[fieldId], newXml);
}
}
private static string ApplyActionToLayoutXml(string xml, Func<RenderingDefinition, RenderingActionResult> action)
{
LayoutDefinition layout = LayoutDefinition.Parse(xml);
xml = layout.ToXml(); // normalize the output in case of any minor XML differences (spaces, etc)
// loop over devices in the rendering
for (int deviceIndex = layout.Devices.Count - 1; deviceIndex >= 0; deviceIndex--)
{
var device = layout.Devices[deviceIndex] as DeviceDefinition;
if (device == null) continue;
// loop over renderings within the device
for (int renderingIndex = device.Renderings.Count - 1; renderingIndex >= 0; renderingIndex--)
{
var rendering = device.Renderings[renderingIndex] as RenderingDefinition;
if (rendering == null) continue;
// run the action on the rendering
RenderingActionResult result = action(rendering);
// remove the rendering if the action method requested it
if (result == RenderingActionResult.Delete)
device.Renderings.RemoveAt(renderingIndex);
}
}
string layoutXml = layout.ToXml();
// save a modified layout value if necessary
if (layoutXml != xml)
{
return layoutXml;
}
return null;
}
}
}
| 47.714286 | 203 | 0.628743 | [
"MIT"
] | MadhavJ/Sitecore.Demo.Edge | Website/src/Foundation/BranchPresets/LayoutHelper.cs | 4,908 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace TRFDControl.FDEntryTypes
{
public class TR3MinecartRotateRightEntry : FDEntry
{
}
}
| 17.230769 | 54 | 0.767857 | [
"MIT"
] | chreden/TR2-Rando | TRFDControl/FDEntryTypes/TR3MinecartRotateRightEntry.cs | 226 | C# |
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("GildedRose.DL")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("GildedRose.DL")]
[assembly: AssemblyCopyright("Copyright © 2019")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("85399f6e-8d3c-4195-963e-dc55a6a8a01c")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| 37.675676 | 84 | 0.746772 | [
"MIT"
] | mosarsh/Gilded-Rose-API | GildedRose.DL/Properties/AssemblyInfo.cs | 1,397 | C# |
/*
* Copyright 2016-2017 Mohawk College of Applied Arts and Technology
*
* 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.
*
* User: Nityan
* Date: 2017-4-9
*/
using System;
namespace PatientGenerator.Core.Model.Common
{
/// <summary>
/// Represents a patient.
/// </summary>
public class Patient
{
/// <summary>
/// Initializes a new instance of the <see cref="Patient"/> class.
/// </summary>
public Patient()
{
}
/// <summary>
/// Gets or sets the address line.
/// </summary>
/// <value>The address line.</value>
public string AddressLine { get; set; }
/// <summary>
/// Gets or sets the city.
/// </summary>
/// <value>The city.</value>
public string City { get; set; }
/// <summary>
/// Gets or sets the country.
/// </summary>
/// <value>The country.</value>
public string Country { get; set; }
/// <summary>
/// Gets or sets the date of birth.
/// </summary>
/// <value>The date of birth.</value>
public DateTime DateOfBirth { get; set; }
/// <summary>
/// Gets or sets the email.
/// </summary>
/// <value>The email.</value>
public string Email { get; set; }
/// <summary>
/// Gets or sets the first name.
/// </summary>
/// <value>The first name.</value>
public string FirstName { get; set; }
/// <summary>
/// Gets or sets the gender.
/// </summary>
/// <value>The gender.</value>
public string Gender { get; set; }
/// <summary>
/// Gets or sets the health card no.
/// </summary>
/// <value>The health card no.</value>
public string HealthCardNo { get; set; }
/// <summary>
/// Gets or sets the language.
/// </summary>
/// <value>The language.</value>
public string Language { get; set; }
/// <summary>
/// Gets or sets the last name.
/// </summary>
/// <value>The last name.</value>
public string LastName { get; set; }
/// <summary>
/// Gets or sets the name of the middle.
/// </summary>
/// <value>The name of the middle.</value>
public string MiddleName { get; set; }
/// <summary>
/// Gets or sets the phone no.
/// </summary>
/// <value>The phone no.</value>
public string PhoneNo { get; set; }
/// <summary>
/// Gets or sets the postal code.
/// </summary>
/// <value>The postal code.</value>
public string PostalCode { get; set; }
/// <summary>
/// Gets or sets the province.
/// </summary>
/// <value>The province.</value>
public string Province { get; set; }
}
} | 24.741667 | 80 | 0.6194 | [
"Apache-2.0"
] | MohawkMEDIC/patient-generator | PatientGenerator.Core.Model/Common/Patient.cs | 2,971 | 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>
//------------------------------------------------------------------------------
#region Usings Setup
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Net;
using Mozu.Api;
using Mozu.Api.Security;
using Mozu.Api.Test.Helpers;
using System.Diagnostics;
using Newtonsoft.Json.Linq;
using System.Threading;
#endregion
namespace Mozu.Api.Test.Factories.Commerce.Catalog.Admin
{
/// <summary>
/// Use the Product Publishing resource to publish or discard pending changes to products in a master catalog, or to add or remove pending changes to and from product publish sets.You can use product publish sets to group pending product changes together and publish them all at the same time.
/// </summary>
public partial class PublishingScopeFactory : BaseDataFactory
{
/// <summary>
///
/// <example>
/// <code>
/// var result = PublishingScopeFactory.GetPublishSet(handler : handler, publishSetCode : publishSetCode, responseFields : responseFields, expectedCode: expectedCode, successCode: successCode);
/// var optionalCasting = ConvertClass<PublishSet/>(result);
/// return optionalCasting;
/// </code>
/// </example>
/// </summary>
public static Mozu.Api.Contracts.ProductAdmin.PublishSet GetPublishSet(ServiceClientMessageHandler handler,
string publishSetCode, string responseFields = null,
HttpStatusCode expectedCode = HttpStatusCode.OK, HttpStatusCode successCode = HttpStatusCode.OK)
{
SetSdKparameters();
var currentClassName = System.Reflection.MethodInfo.GetCurrentMethod().DeclaringType.Name;
var currentMethodName = System.Reflection.MethodBase.GetCurrentMethod().Name;
Debug.WriteLine(currentMethodName + '.' + currentMethodName );
var apiClient = Mozu.Api.Clients.Commerce.Catalog.Admin.PublishingScopeClient.GetPublishSetClient(
publishSetCode : publishSetCode, responseFields : responseFields );
try
{
apiClient.WithContext(handler.ApiContext).ExecuteAsync(default(CancellationToken)).Wait();
}
catch (ApiException ex)
{
// Custom error handling for test cases can be placed here
Exception customException = TestFailException.GetCustomTestException(ex, currentClassName, currentMethodName, expectedCode);
if (customException != null)
throw customException;
return null;
}
return ResponseMessageFactory.CheckResponseCodes(apiClient.HttpResponse.StatusCode, expectedCode, successCode)
? (apiClient.Result())
: null;
}
/// <summary>
///
/// <example>
/// <code>
/// var result = PublishingScopeFactory.GetPublishSets(handler : handler, responseFields : responseFields, expectedCode: expectedCode, successCode: successCode);
/// var optionalCasting = ConvertClass<PublishSetCollection/>(result);
/// return optionalCasting;
/// </code>
/// </example>
/// </summary>
public static Mozu.Api.Contracts.ProductAdmin.PublishSetCollection GetPublishSets(ServiceClientMessageHandler handler,
string responseFields = null,
HttpStatusCode expectedCode = HttpStatusCode.OK, HttpStatusCode successCode = HttpStatusCode.OK)
{
SetSdKparameters();
var currentClassName = System.Reflection.MethodInfo.GetCurrentMethod().DeclaringType.Name;
var currentMethodName = System.Reflection.MethodBase.GetCurrentMethod().Name;
Debug.WriteLine(currentMethodName + '.' + currentMethodName );
var apiClient = Mozu.Api.Clients.Commerce.Catalog.Admin.PublishingScopeClient.GetPublishSetsClient(
responseFields : responseFields );
try
{
apiClient.WithContext(handler.ApiContext).ExecuteAsync(default(CancellationToken)).Wait();
}
catch (ApiException ex)
{
// Custom error handling for test cases can be placed here
Exception customException = TestFailException.GetCustomTestException(ex, currentClassName, currentMethodName, expectedCode);
if (customException != null)
throw customException;
return null;
}
return ResponseMessageFactory.CheckResponseCodes(apiClient.HttpResponse.StatusCode, expectedCode, successCode)
? (apiClient.Result())
: null;
}
/// <summary>
///
/// <example>
/// <code>
/// var result = PublishingScopeFactory.DiscardDrafts(handler : handler, publishScope : publishScope, dataViewMode: dataViewMode, expectedCode: expectedCode, successCode: successCode);
/// var optionalCasting = ConvertClass<void/>(result);
/// return optionalCasting;
/// </code>
/// </example>
/// </summary>
public static void DiscardDrafts(ServiceClientMessageHandler handler,
Mozu.Api.Contracts.ProductAdmin.PublishingScope publishScope, DataViewMode dataViewMode= DataViewMode.Live,
HttpStatusCode expectedCode = HttpStatusCode.NoContent, HttpStatusCode successCode = HttpStatusCode.NoContent)
{
SetSdKparameters();
var currentClassName = System.Reflection.MethodInfo.GetCurrentMethod().DeclaringType.Name;
var currentMethodName = System.Reflection.MethodBase.GetCurrentMethod().Name;
Debug.WriteLine(currentMethodName + '.' + currentMethodName );
var apiClient = Mozu.Api.Clients.Commerce.Catalog.Admin.PublishingScopeClient.DiscardDraftsClient(
publishScope : publishScope, dataViewMode: dataViewMode );
try
{
apiClient.WithContext(handler.ApiContext).ExecuteAsync(default(CancellationToken)).Wait();
}
catch (ApiException ex)
{
// Custom error handling for test cases can be placed here
Exception customException = TestFailException.GetCustomTestException(ex, currentClassName, currentMethodName, expectedCode);
if (customException != null)
throw customException;
}
var noResponse = ResponseMessageFactory.CheckResponseCodes(apiClient.HttpResponse.StatusCode, expectedCode, successCode)
? (apiClient.Result())
: null;
}
/// <summary>
///
/// <example>
/// <code>
/// var result = PublishingScopeFactory.PublishDrafts(handler : handler, publishScope : publishScope, dataViewMode: dataViewMode, expectedCode: expectedCode, successCode: successCode);
/// var optionalCasting = ConvertClass<void/>(result);
/// return optionalCasting;
/// </code>
/// </example>
/// </summary>
public static void PublishDrafts(ServiceClientMessageHandler handler,
Mozu.Api.Contracts.ProductAdmin.PublishingScope publishScope, DataViewMode dataViewMode= DataViewMode.Live,
HttpStatusCode expectedCode = HttpStatusCode.NoContent, HttpStatusCode successCode = HttpStatusCode.NoContent)
{
SetSdKparameters();
var currentClassName = System.Reflection.MethodInfo.GetCurrentMethod().DeclaringType.Name;
var currentMethodName = System.Reflection.MethodBase.GetCurrentMethod().Name;
Debug.WriteLine(currentMethodName + '.' + currentMethodName );
var apiClient = Mozu.Api.Clients.Commerce.Catalog.Admin.PublishingScopeClient.PublishDraftsClient(
publishScope : publishScope, dataViewMode: dataViewMode );
try
{
apiClient.WithContext(handler.ApiContext).ExecuteAsync(default(CancellationToken)).Wait();
}
catch (ApiException ex)
{
// Custom error handling for test cases can be placed here
Exception customException = TestFailException.GetCustomTestException(ex, currentClassName, currentMethodName, expectedCode);
if (customException != null)
throw customException;
}
var noResponse = ResponseMessageFactory.CheckResponseCodes(apiClient.HttpResponse.StatusCode, expectedCode, successCode)
? (apiClient.Result())
: null;
}
/// <summary>
///
/// <example>
/// <code>
/// var result = PublishingScopeFactory.AssignProductsToPublishSet(handler : handler, publishSet : publishSet, responseFields : responseFields, expectedCode: expectedCode, successCode: successCode);
/// var optionalCasting = ConvertClass<PublishSet/>(result);
/// return optionalCasting;
/// </code>
/// </example>
/// </summary>
public static Mozu.Api.Contracts.ProductAdmin.PublishSet AssignProductsToPublishSet(ServiceClientMessageHandler handler,
Mozu.Api.Contracts.ProductAdmin.PublishSet publishSet, string responseFields = null,
HttpStatusCode expectedCode = HttpStatusCode.OK, HttpStatusCode successCode = HttpStatusCode.OK)
{
SetSdKparameters();
var currentClassName = System.Reflection.MethodInfo.GetCurrentMethod().DeclaringType.Name;
var currentMethodName = System.Reflection.MethodBase.GetCurrentMethod().Name;
Debug.WriteLine(currentMethodName + '.' + currentMethodName );
var apiClient = Mozu.Api.Clients.Commerce.Catalog.Admin.PublishingScopeClient.AssignProductsToPublishSetClient(
publishSet : publishSet, responseFields : responseFields );
try
{
apiClient.WithContext(handler.ApiContext).ExecuteAsync(default(CancellationToken)).Wait();
}
catch (ApiException ex)
{
// Custom error handling for test cases can be placed here
Exception customException = TestFailException.GetCustomTestException(ex, currentClassName, currentMethodName, expectedCode);
if (customException != null)
throw customException;
return null;
}
return ResponseMessageFactory.CheckResponseCodes(apiClient.HttpResponse.StatusCode, expectedCode, successCode)
? (apiClient.Result())
: null;
}
/// <summary>
///
/// <example>
/// <code>
/// var result = PublishingScopeFactory.DeletePublishSet(handler : handler, publishSetCode : publishSetCode, discardDrafts : discardDrafts, expectedCode: expectedCode, successCode: successCode);
/// var optionalCasting = ConvertClass<void/>(result);
/// return optionalCasting;
/// </code>
/// </example>
/// </summary>
public static void DeletePublishSet(ServiceClientMessageHandler handler,
string publishSetCode, bool? discardDrafts = null,
HttpStatusCode expectedCode = HttpStatusCode.NoContent, HttpStatusCode successCode = HttpStatusCode.NoContent)
{
SetSdKparameters();
var currentClassName = System.Reflection.MethodInfo.GetCurrentMethod().DeclaringType.Name;
var currentMethodName = System.Reflection.MethodBase.GetCurrentMethod().Name;
Debug.WriteLine(currentMethodName + '.' + currentMethodName );
var apiClient = Mozu.Api.Clients.Commerce.Catalog.Admin.PublishingScopeClient.DeletePublishSetClient(
publishSetCode : publishSetCode, discardDrafts : discardDrafts );
try
{
apiClient.WithContext(handler.ApiContext).ExecuteAsync(default(CancellationToken)).Wait();
}
catch (ApiException ex)
{
// Custom error handling for test cases can be placed here
Exception customException = TestFailException.GetCustomTestException(ex, currentClassName, currentMethodName, expectedCode);
if (customException != null)
throw customException;
}
var noResponse = ResponseMessageFactory.CheckResponseCodes(apiClient.HttpResponse.StatusCode, expectedCode, successCode)
? (apiClient.Result())
: null;
}
}
}
| 42.715909 | 294 | 0.732908 | [
"MIT"
] | GaryWayneSmith/mozu-dotnet | Mozu.Api.Test/Factories/Commerce/Catalog/Admin/PublishingScopeFactory.cs | 11,277 | C# |
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;
using Xunit;
namespace Avatars.AcceptanceTests
{
partial class AvatarGeneration
{
static (ImmutableArray<Diagnostic>, Compilation) GetGeneratedOutput(string source, [CallerMemberName] string? test = null)
{
var syntaxTree = CSharpSyntaxTree.ParseText(source, path: test + ".cs");
var references = new List<MetadataReference>();
var assemblies = AppDomain.CurrentDomain.GetAssemblies();
foreach (var assembly in assemblies)
{
if (!assembly.IsDynamic && !string.IsNullOrEmpty(assembly.Location))
references.Add(MetadataReference.CreateFromFile(assembly.Location));
}
var compilation = CSharpCompilation.Create(test,
new SyntaxTree[]
{
syntaxTree,
CSharpSyntaxTree.ParseText(File.ReadAllText("Avatar/Avatar.cs"), path: "Avatar.cs"),
}, references, new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary));
var diagnostics = compilation.GetDiagnostics();
if (diagnostics.Any())
return (diagnostics, compilation);
ISourceGenerator generator = new AvatarGenerator();
var driver = CSharpGeneratorDriver.Create(generator);
driver.RunGeneratorsAndUpdateCompilation(compilation, out var output, out diagnostics);
return (diagnostics, output);
}
static Assembly Emit(Compilation compilation)
{
using var stream = new MemoryStream();
var result = compilation.Emit(stream);
if (!result.Success)
{
Assert.False(true,
"Emit failed:\r\n" +
Environment.NewLine +
string.Join(Environment.NewLine, result.Diagnostics.Select(d => d.ToString())));
}
stream.Seek(0, SeekOrigin.Begin);
return Assembly.Load(stream.ToArray());
}
}
}
| 35.338462 | 130 | 0.61515 | [
"MIT"
] | atifaziz/avatar | src/Avatar.IntegrationTests/AvatarGeneration.Helpers.cs | 2,299 | C# |
// Copyright (c) 2021 Ezequias Silva.
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at https://mozilla.org/MPL/2.0/.
using SunEngine.GL;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Text;
namespace SunEngine.Graphics
{
public class Shader : GraphicObject
{
private int bindingPointCount;
public Shader(IGL gl, params ShaderProgram[] shaders) : this(gl, (IEnumerable<ShaderProgram>)shaders)
{
}
internal Shader(IGL gl, IEnumerable<ShaderProgram> shaders) : base(gl, gl.CreateProgram())
{
bindingPointCount = 0;
List<int> shaderHandles = new List<int>();
foreach (ShaderProgram program in shaders)
{
int shaderHandle = CompileShaderProgram(program);
GL.AttachShader(Handle, shaderHandle);
GL.CheckErros();
shaderHandles.Add(shaderHandle);
}
GL.LinkProgram(Handle);
GL.CheckErros();
GL.ValidateProgram(Handle);
GL.CheckErros();
WriteProgramInfoLog();
foreach (int shaderHandle in shaderHandles)
{
GL.DetachShader(Handle, shaderHandle);
GL.CheckErros();
GL.DeleteShader(shaderHandle);
GL.CheckErros();
}
}
[Conditional("DEBUG")]
private void WriteProgramInfoLog()
{
Console.WriteLine(GL.GetProgramInfoLog(Handle));
}
private int CompileShaderProgram(ShaderProgram program)
{
int shaderObject = GL.CreateShader(program.ShaderType);
GL.CheckErros();
if (program.IsASCII)
{
string text = Encoding.ASCII.GetString(program.Data);
GL.ShaderSource(shaderObject, text);
GL.CheckErros();
GL.CompileShader(shaderObject);
GL.CheckErros();
return shaderObject;
}
else
{
GL.DeleteShader(shaderObject);
GL.CheckErros();
throw new NotImplementedException("Non-UTF8 shaders have not been implemented.");
}
}
public void Use()
{
GL.UseProgram(Handle);
GL.CheckErros();
}
protected override void Dispose(bool disposing)
{
if (disposing)
{
GL.DeleteProgram(Handle);
GL.CheckErros();
}
}
public void ResetBindingPointCount()
{
bindingPointCount = 0;
}
public void SetUniformBuffer<T>(Buffer<T> buffer, int index) where T : unmanaged
{
GL.UniformBlockBinding(Handle, index, bindingPointCount);
GL.CheckErros();
GL.BindBufferBase(BufferTarget.UniformBuffer, bindingPointCount, buffer.Handle);
GL.CheckErros();
bindingPointCount++;
}
public void SetUniformBuffer<T>(Buffer<T> buffer, string uniformBlockName) where T : unmanaged
{
int index = GetUniformBufferIndex(uniformBlockName);
SetUniformBuffer(buffer, index);
}
public int GetUniformBufferIndex(string uniformBlockName)
{
return GL.GetUniformBlockIndex(Handle, uniformBlockName); ;
}
}
} | 29.809917 | 109 | 0.558913 | [
"MPL-2.0",
"MPL-2.0-no-copyleft-exception"
] | ezequias2d/SunEngine | SunEngine/Graphics/Shader.cs | 3,609 | C# |
using System.Threading.Tasks;
using BookLovers.Base.Domain.Services;
using BookLovers.Base.Infrastructure;
using BookLovers.Base.Infrastructure.Commands;
using BookLovers.Base.Infrastructure.ModuleCommunication;
using BookLovers.Publication.Application.Commands.Publishers;
using BookLovers.Publication.Domain.Publishers;
using BookLovers.Publication.Integration.ApplicationEvents.Publishers;
namespace BookLovers.Publication.Application.CommandHandlers.Publishers
{
internal class ArchivePublisherHandler : ICommandHandler<ArchivePublisherCommand>
{
private readonly IUnitOfWork _unitOfWork;
private readonly IAggregateManager<Publisher> _aggregateManager;
private readonly IInMemoryEventBus _eventBus;
public ArchivePublisherHandler(
IUnitOfWork unitOfWork,
IAggregateManager<Publisher> aggregateManager,
IInMemoryEventBus eventBus)
{
this._unitOfWork = unitOfWork;
this._aggregateManager = aggregateManager;
this._eventBus = eventBus;
}
public async Task HandleAsync(ArchivePublisherCommand command)
{
var publisher = await this._unitOfWork.GetAsync<Publisher>(command.PublisherGuid);
this._aggregateManager.Archive(publisher);
await this._unitOfWork.CommitAsync(publisher);
await this._eventBus.Publish(new PublisherArchivedIntegrationEvent(command.PublisherGuid));
}
}
} | 38.102564 | 103 | 0.742934 | [
"MIT"
] | kamilk08/BookLoversApi | BookLovers.Publication.Application/CommandHandlers/Publishers/ArchivePublisherHandler.cs | 1,488 | C# |
namespace IntruderLib.Models.Rooms
{
using Newtonsoft.Json;
/// <summary>
/// Match set score.
/// </summary>
public class SetScore
{
/// <summary>
/// Gets or sets the score for the Guards.
/// </summary>
[JsonProperty("guards")]
public int Guards { get; set; }
/// <summary>
/// Gets or sets the score for the Intruders.
/// </summary>
[JsonProperty("intruders")]
public int Intruders { get; set; }
}
}
| 22.391304 | 53 | 0.526214 | [
"MIT"
] | BloonBot/IntruderLib | IntruderLib/Models/Rooms/SetScore.cs | 515 | C# |
/*
* Copyright 2010-2014 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
/*
* Do not modify this file. This file is generated from the elasticloadbalancingv2-2015-12-01.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.ElasticLoadBalancingV2.Model
{
/// <summary>
/// Information about a forward action.
/// </summary>
public partial class ForwardActionConfig
{
private List<TargetGroupTuple> _targetGroups = new List<TargetGroupTuple>();
private TargetGroupStickinessConfig _targetGroupStickinessConfig;
/// <summary>
/// Gets and sets the property TargetGroups.
/// <para>
/// One or more target groups. For Network Load Balancers, you can specify a single target
/// group.
/// </para>
/// </summary>
public List<TargetGroupTuple> TargetGroups
{
get { return this._targetGroups; }
set { this._targetGroups = value; }
}
// Check to see if TargetGroups property is set
internal bool IsSetTargetGroups()
{
return this._targetGroups != null && this._targetGroups.Count > 0;
}
/// <summary>
/// Gets and sets the property TargetGroupStickinessConfig.
/// <para>
/// The target group stickiness for the rule.
/// </para>
/// </summary>
public TargetGroupStickinessConfig TargetGroupStickinessConfig
{
get { return this._targetGroupStickinessConfig; }
set { this._targetGroupStickinessConfig = value; }
}
// Check to see if TargetGroupStickinessConfig property is set
internal bool IsSetTargetGroupStickinessConfig()
{
return this._targetGroupStickinessConfig != null;
}
}
} | 32.597403 | 120 | 0.656175 | [
"Apache-2.0"
] | DetlefGolze/aws-sdk-net | sdk/src/Services/ElasticLoadBalancingV2/Generated/Model/ForwardActionConfig.cs | 2,510 | C# |
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.Threading.Tasks;
using System.Windows.Forms;
using CollectionManager.DataTypes;
using OsuMemoryDataProvider;
using StreamCompanionTypes;
using StreamCompanionTypes.DataTypes;
using StreamCompanionTypes.Enums;
using StreamCompanionTypes.Interfaces;
using StreamCompanionTypes.Interfaces.Services;
namespace OsuMemoryEventSource
{
public partial class FirstRunMemoryCalibration : UserControl, IFirstRunControl
{
private readonly object _lockingObject = new object();
private readonly List<Map> _maps = new List<Map>
{
new Map("Thunderclowns - Find The Memes In You", 314211,
new List<int> {712858, 712859, 712847, 712945, 701254}),
new Map("Bachelor Party - Kappa Kappa (Forsen Edition)", 312113, new List<int> {958367, 696895}),
new Map("NOMA - Brain Power Long Version", 432822, new List<int> {933228}),
new Map("Memme - Chinese Restaurant", 399404, new List<int> {869286, 875324}),
new Map("Yuyoyuppe - Bad Apple!!", 299000, new List<int> {670892, 670894, 670893}),
new Map("Kommisar - Bad Apple!! (Chiptune ver.)", 28222, new List<int> {94187, 94186, 94188, 94189}),
new Map("Freezer feat. Kiichigo - Berry Go!!", 1034502,
new List<int> {2162847, 2162848, 2164477, 2170342, 2170756, 2171102})
};
private readonly SettingNames _names = SettingNames.Instance;
private readonly ISettings _settings;
private readonly int ExpectedMods = 89; //HRNFDTHD
private readonly IOsuMemoryReader memoryReader;
private readonly Random rnd = new Random();
private Map _currentMap;
private volatile bool Passed;
private ILogger _logger;
public event EventHandler<FirstRunCompletedEventArgs> Completed;
private Map CurrentMap
{
get => _currentMap;
set
{
_currentMap = value;
linkLabel_mapDL.Text = $"Click here for map download ({value.DownloadLink})";
label_beatmapDL.Text =
"Enable following mods: HR,NF,DT,HD" + Environment.NewLine +
" and play this map:" + Environment.NewLine +
" \"" + value.MapName + "\" with any difficulty in osu! mode";
}
}
public FirstRunMemoryCalibration(IOsuMemoryReader reader, ISettings settings, ILogger logger)
{
memoryReader = reader;
_settings = settings;
_logger = logger;
InitializeComponent();
pictureBox1.Image = StreamCompanionHelper.StreamCompanionLogo();
CurrentMap = _maps[rnd.Next(0, _maps.Count)];
_settings.Add(_names.EnableMemoryScanner.Name, true);
_settings.Add(_names.EnableMemoryPooling.Name, true);
}
private void SetCalibrationText(string text)
{
if (label_CalibrationResult.InvokeRequired)
{
Invoke((MethodInvoker)delegate { SetCalibrationText(text); });
return;
}
label_CalibrationResult.Text = text;
}
public void GotMemory(int mapId, OsuStatus status, string mapString)
{
if (!IsHandleCreated)
return;
_logger.Log($"FirstRun: mapId: {mapId}, status: {status}, mapString: {mapString}", LogLevel.Debug);
_logger.Log($"FirstRun: looking for: {CurrentMap}", LogLevel.Debug);
lock (_lockingObject)
{
Invoke((MethodInvoker)delegate
{
label_memoryStatus.Text =
$"{status}, id:{mapId}, is valid mapset:{CurrentMap.BelongsToSet(mapId)}";
});
if (CurrentMap.BelongsToSet(mapId) && status == OsuStatus.Playing)
{
Invoke((MethodInvoker)delegate
{
SetCalibrationText("Searching. It can take up to 20 seconds.");
});
var mods = Helpers.ExecWithTimeout(async token =>
{
if (token.IsCancellationRequested)
return -1;
//ugly workaround
SetCalibrationText("Initial search delay... waiting 3 seconds");
await Task.Delay(3000);
return memoryReader.GetPlayingMods();
}, 20000).Result;
Passed = mods == ExpectedMods;
Invoke((MethodInvoker)delegate
{
if (Passed)
{
Completed?.Invoke(this, new FirstRunCompletedEventArgs { ControlCompletionStatus = FirstRunStatus.Ok });
}
else
{
var resultText =
$"Something went wrong(mods: {(Mods)mods}). Maybe try again with another map?";
SetCalibrationText(resultText);
}
});
}
}
}
public void SetNextMap()
{
CurrentMap = _maps[(_maps.IndexOf(CurrentMap) + 1) % _maps.Count];
SetCalibrationText("Waiting...");
}
private void linkLabel_mapDL_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
{
try
{
Process.Start(CurrentMap.DownloadLink);
}
catch (Win32Exception)
{
MessageBox.Show("Your system doesn't have a default browser set" + Environment.NewLine +
"Sadly there is nothing I can do to fix this" + Environment.NewLine +
"Either fix that(google can help), or write shown url in your browser window manually",
"Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void button_anotherMap_Click(object sender, EventArgs e)
{
SetNextMap();
}
private class Map
{
public string MapName { get; }
public int MapSetId { get; }
public List<int> Diffs { get; }
public string DownloadLink => $"https://osu.ppy.sh/beatmapsets/{MapSetId}/download";
public Map(string mapName, int mapSetId, List<int> diffs)
{
MapName = mapName;
MapSetId = mapSetId;
Diffs = diffs;
}
public bool BelongsToSet(int mapId)
{
return Diffs.Contains(mapId);
}
public override string ToString()
=> $"{MapName}; setId: {MapSetId}; diffIds:[{string.Join(",", Diffs)}]";
}
}
} | 37.534392 | 131 | 0.54384 | [
"MIT"
] | cadon0/StreamCompanion | plugins/OsuMemoryEventSource/FirstRunMemoryCalibration.cs | 7,094 | C# |
using System.Data.Entity.ModelConfiguration;
using Core.DomainModel.Organization;
namespace Infrastructure.DataAccess.Mapping
{
public class OrganizationTypeMap : EntityTypeConfiguration<OrganizationType>
{
public OrganizationTypeMap()
{
// Properties
Property(x => x.Name).IsRequired();
Property(t => t.Category).IsRequired();
// Table & Column Mappings
ToTable("OrganizationTypes");
}
}
} | 27.111111 | 80 | 0.635246 | [
"MPL-2.0",
"MPL-2.0-no-copyleft-exception"
] | Strongminds/kitos | Infrastructure.DataAccess/Mapping/OrganizationTypeMap.cs | 488 | C# |
using System;
using Harmony;
using Overload;
using UnityEngine;
namespace GameMod
{
class MPPickupCheck
{
public static bool PickupCheck = true;
}
// Allow picking up items in MP when item is adjacent to an inverted segment. Items also no longer get stuck inside grates. by Terminal
[HarmonyPatch(typeof(Item), "ItemIsReachable")]
internal class MPItemInvertedSegment
{
private static bool Prefix(ref bool __result)
{
//Debug.Log("ItemIsReachable " + (Overload.NetworkManager.IsServer() ? "server" : "conn " + NetworkMatch.m_my_lobby_id) + " PickupCheck=" + MPPickupCheck.PickupCheck);
if (GameplayManager.IsMultiplayerActive && !MPPickupCheck.PickupCheck)
{
__result = true;
return false;
}
return true;
}
}
}
| 30 | 179 | 0.631034 | [
"MIT"
] | DissCent/olmod | GameMod/MPPickupCheck.cs | 872 | C# |
using Foundation;
using UIKit;
using Avalonia;
using Avalonia.Controls;
using Avalonia.iOS;
using Avalonia.Media;
namespace DirectPackageInstaller.iOS
{
// The UIApplicationDelegate for the application. This class is responsible for launching the
// User Interface of the application, as well as listening (and optionally responding) to
// application events from iOS.
[Register("AppDelegate")]
public partial class AppDelegate : AvaloniaAppDelegate<App>
{
}
} | 28.882353 | 98 | 0.753564 | [
"Unlicense"
] | marcussacana/DirectPackageInstaller | DirectPackageInstaller/DirectPackageInstaller.iOS/AppDelegate.cs | 491 | C# |
using System;
namespace EPPlusEnumerable
{
/// <summary>
/// Use this attribute to denote that the property is to be excluded and not outputted in the Excel worksheet.
/// </summary>
[AttributeUsage(AttributeTargets.Property, AllowMultiple = false, Inherited = true)]
public class SpreadsheetExcludeAttribute : Attribute
{
#region Constructors
public SpreadsheetExcludeAttribute()
{
}
#endregion
}
}
| 22.52381 | 114 | 0.661734 | [
"MIT"
] | aricept/EPPlusEnumerable | EPPlusEnumerable/SpreadsheetExcludeAttribute.cs | 475 | C# |
/*
* Copyright 2018 JDCLOUD.COM
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http:#www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* history replicator task
* 同步历史数据API
*
* OpenAPI spec version: v1
* Contact:
*
* NOTE: This class is auto generated by the jdcloud code generator program.
*/
using System;
using System.Collections.Generic;
using System.Text;
using JDCloudSDK.Core.Service;
namespace JDCloudSDK.Ossopenapi.Apis
{
/// <summary>
/// 停止bucket名称获取该bucket下的同步任务
/// </summary>
public class AbortHistoricalReplicatTaskResult : JdcloudResult
{
}
} | 25.731707 | 76 | 0.726066 | [
"Apache-2.0"
] | jdcloud-api/jdcloud-sdk-net | sdk/src/Service/Ossopenapi/Apis/AbortHistoricalReplicatTaskResult.cs | 1,093 | C# |
namespace SharedTrip.ViewModel
{
public class UserLoginForm
{
public string UserName { get; set; }
public string Password { get; set; }
}
}
| 17 | 44 | 0.611765 | [
"MIT"
] | Anzzhhela98/C-Web | C# Web Basics/Exam Preparation/SharedTrip/ViewModel/UserLoginForm.cs | 172 | C# |
using UnityEngine;
using System.Collections; using FastCollections;
using System;
using System.Text;
namespace RTSLockstep
{
public class DefaultData : ICommandData
{
public DefaultData()
{
}
public DefaultData(DataType dataType, object value)
{
Value = value;
this.DataType = dataType;
}
public DefaultData(object value)
{
Value = value;
this.DataType = GetDataType(value.GetType());
}
public object Value { get; protected set; }
public DataType DataType { get; protected set; }
public bool Is(DataType dataType)
{
return this.DataType == dataType;
}
public DataType GetDataType(Type type)
{
if (type == typeof(int))
return DataType.Int;
if (type == typeof(uint))
return DataType.UInt;
if (type == typeof(ushort))
return DataType.UShort;
if (type == typeof(long))
return DataType.Long;
if (type == typeof(byte))
return DataType.Byte;
if (type == typeof(bool))
return DataType.Bool;
if (type == typeof(string))
return DataType.String;
if (type == typeof(byte[]))
return DataType.ByteArray;
throw new System.Exception(string.Format("Type '{0}' is not a valid DefaultData Type.", type));
}
public void Write(Writer writer)
{
writer.Write((byte)this.DataType);
switch (this.DataType)
{
case DataType.Int:
writer.Write((int)Value);
break;
case DataType.UInt:
writer.Write((uint)Value);
break;
case DataType.UShort:
writer.Write((ushort)Value);
break;
case DataType.Long:
writer.Write((long)Value);
break;
case DataType.Byte:
writer.Write((byte)Value);
break;
case DataType.Bool:
writer.Write((bool)Value);
break;
case DataType.String:
writer.Write((string)Value);
break;
case DataType.ByteArray:
writer.WriteByteArray((byte[])Value);
break;
}
}
public void Read(Reader reader)
{
this.DataType = (DataType)reader.ReadByte();
switch (this.DataType)
{
case DataType.Int:
Value = reader.ReadInt();
break;
case DataType.UInt:
Value = reader.ReadUInt();
break;
case DataType.UShort:
Value = reader.ReadUShort();
break;
case DataType.Long:
Value = reader.ReadLong();
break;
case DataType.Byte:
Value = reader.ReadByte();
break;
case DataType.Bool:
Value = reader.ReadBool();
break;
case DataType.String:
Value = reader.ReadString();
break;
case DataType.ByteArray:
Value = reader.ReadByteArray();
break;
}
}
}
public enum DataType : byte
{
Int,
UInt,
UShort,
Long,
Byte,
Bool,
String,
ByteArray
}
} | 28.80597 | 107 | 0.442228 | [
"MIT"
] | mrdav30/LockstepRTSEngine | Assets/Core/Game/Player/Commands/Default/DefaultData.cs | 3,862 | C# |
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.DependencyInjection;
using OmniPay.Core.Utils;
using OmniPay.Wechatpay.Middleware;
namespace OmniPay.Wechatpay.Extensions
{
public static class WeChatPayApplicationBuilderExtensions
{
//public static IEndpointConventionBuilder UseWeChatPayEndpoints(this IEndpointRouteBuilder endpoints,string pattern) {
// var pipeline = endpoints.CreateApplicationBuilder()
// .UseMiddleware<WechatPayMiddleware>().Build();
// return endpoints.Map(pattern, pipeline).WithDisplayName("wechatpay") ;
//}
/// <summary>
/// 使用OmniPay
/// </summary>
/// <param name="app"></param>
/// <returns></returns>
public static IApplicationBuilder UseOmniPay(this IApplicationBuilder app)
{
app.UseMiddleware<WechatPayMiddleware>();
//var httpContextAccessor = app.ApplicationServices.GetRequiredService<IHttpContextAccessor>();
//HttpUtil.Configure(httpContextAccessor);
return app;
}
}
}
| 36.709677 | 127 | 0.676626 | [
"MIT"
] | hueifeng/AspNetCore.Free.Pay | src/OmniPay.Wechatpay/Extensions/WeChatPayApplicationBuilderExtensions.cs | 1,144 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
namespace Logs_Aggregator
{
public class LogsAggregator
{
public static void Main()
{
int n = int.Parse(Console.ReadLine());
var users = new SortedDictionary<string, Logs>();
for (int i = 0; i < n; i++)
{
var input = Console.ReadLine()
.Split(' ');
string ip = input[0];
string userName = input[1];
int duration = int.Parse(input[2]);
if (!users.ContainsKey(userName))
{
users[userName] = new Logs
{
IpAndDuration = new SortedDictionary<string, int>()
};
}
if (!users[userName].IpAndDuration.ContainsKey(ip))
{
users[userName].IpAndDuration[ip] = 0;
}
users[userName].IpAndDuration[ip] += duration;
}
foreach (var user in users)
{
Console.WriteLine($"{user.Key}: {user.Value.TotalTime()} [{PrintKeys(user)}]");
}
}
public static object PrintKeys(KeyValuePair<string, Logs> user)
{
string temp = user.Value.IpAndDuration.Keys.ToArray()[0];
foreach (var ip in user.Value.IpAndDuration.Keys.ToArray().Skip(1))
{
temp = temp + ", " + ip;
}
return temp;
}
}
}
| 28.690909 | 95 | 0.458175 | [
"MIT"
] | Koceto/SoftUni | Old Code/Programming Fundamentals/Dictionaries, Lambda and LINQ - Exercises/Logs Aggregator/Logs Aggregator/Program.cs | 1,580 | C# |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class TargetRadar : MonoBehaviour
{
void Start ()
{
}
private bool enemyInRange = false;
/// <summary>
/// Checks if enemy is in range.
/// </summary>
/// <param name="other">Other.</param>
void OnTriggerEnter2D (Collider2D other)
{
if (!other.tag.Contains ("Enemy") && !other.tag.Contains ("Shot") && !other.tag.Contains ("Radar")) {
this.enemyInRange = true;
}
}
/// <summary>
/// Checks if enemy is not in range.
/// </summary>
/// <param name="other">Other.</param>
void OnTriggerExit2D (Collider2D other)
{
if (!other.tag.Contains ("Enemy") && !other.tag.Contains ("Shot") && !other.tag.Contains ("Radar")) {
this.enemyInRange = false;
}
}
//void OnTriggerStay2D(Collider2D other)
//{
// if (!other.name.Equals (enemyShip)) {
// this.enemyInRange = true;
// }
//}
/// <summary>
/// Pings the radar.
/// </summary>
/// <returns><c>true</c>, if ping was radared, <c>false</c> otherwise.</returns>
public bool RadarPing ()
{
return this.enemyInRange;
}
}
| 21.735849 | 104 | 0.607639 | [
"MIT"
] | OskariV/DeepSpaceGame | TargetRadar.cs | 1,154 | C# |
/* ====================================================================
Licensed to the Apache Software Foundation (ASF) under one or more
contributor license agreements. See the NOTICE file distributed with
this work for Additional information regarding copyright ownership.
The ASF licenses this file to You under the Apache License, Version 2.0
(the "License"); you may not use this file except in compliance with
the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==================================================================== */
using Npoi.Core.OpenXml4Net.OPC;
using Npoi.Core.Util;
using Npoi.Core.XWPF.UserModel;
using NUnit.Framework;
using System;
using System.IO;
using System.Net;
using System.Text.RegularExpressions;
namespace Npoi.Core.OpenXml4Net.Tests.OPC
{
[TestFixture]
public class TestRelationships
{
private static string HYPERLINK_REL_TYPE =
"http://schemas.openxmlformats.org/officeDocument/2006/relationships/hyperlink";
private static string COMMENTS_REL_TYPE =
"http://schemas.openxmlformats.org/officeDocument/2006/relationships/comments";
private static string SHEET_WITH_COMMENTS =
"/xl/worksheets/sheet1.xml";
private static POILogger logger = POILogFactory.GetLogger(typeof(TestPackageCoreProperties));
/**
* Test relationships are correctly loaded. This at the moment fails (as of r499)
* whenever a document is loaded before its correspondig .rels file has been found.
* The code in this case assumes there are no relationships defined, but it should
* really look also for not yet loaded parts.
*/
[Test]
public void TestLoadRelationships() {
Stream is1 = OpenXml4NetTestDataSamples.OpenSampleStream("sample.xlsx");
OPCPackage pkg = OPCPackage.Open(is1);
logger.Log(POILogger.DEBUG, "1: " + pkg);
PackageRelationshipCollection rels = pkg.GetRelationshipsByType(PackageRelationshipTypes.CORE_DOCUMENT);
PackageRelationship coreDocRelationship = rels.GetRelationship(0);
PackagePart corePart = pkg.GetPart(coreDocRelationship);
string[] relIds = { "rId1", "rId2", "rId3" };
foreach (string relId in relIds) {
PackageRelationship rel = corePart.GetRelationship(relId);
Assert.IsNotNull(rel);
PackagePartName relName = PackagingUriHelper.CreatePartName(rel.TargetUri);
PackagePart sheetPart = pkg.GetPart(relName);
Assert.AreEqual(1, sheetPart.Relationships.Size, "Number of relationships1 for " + sheetPart.PartName);
}
}
/**
* Checks that we can fetch a collection of relations by
* type, then grab from within there by id
*/
[Test]
public void TestFetchFromCollection() {
Stream is1 = OpenXml4NetTestDataSamples.OpenSampleStream("ExcelWithHyperlinks.xlsx");
OPCPackage pkg = OPCPackage.Open(is1);
PackagePart sheet = pkg.GetPart(
PackagingUriHelper.CreatePartName(SHEET_WITH_COMMENTS));
Assert.IsNotNull(sheet);
Assert.IsTrue(sheet.HasRelationships);
Assert.AreEqual(6, sheet.Relationships.Size);
// Should have three hyperlinks, and one comment
PackageRelationshipCollection hyperlinks =
sheet.GetRelationshipsByType(HYPERLINK_REL_TYPE);
PackageRelationshipCollection comments =
sheet.GetRelationshipsByType(COMMENTS_REL_TYPE);
Assert.AreEqual(3, hyperlinks.Size);
Assert.AreEqual(1, comments.Size);
// Check we can Get bits out by id
// Hyperlinks are rId1, rId2 and rId3
// Comment is rId6
Assert.IsNotNull(hyperlinks.GetRelationshipByID("rId1"));
Assert.IsNotNull(hyperlinks.GetRelationshipByID("rId2"));
Assert.IsNotNull(hyperlinks.GetRelationshipByID("rId3"));
Assert.IsNull(hyperlinks.GetRelationshipByID("rId6"));
Assert.IsNull(comments.GetRelationshipByID("rId1"));
Assert.IsNull(comments.GetRelationshipByID("rId2"));
Assert.IsNull(comments.GetRelationshipByID("rId3"));
Assert.IsNotNull(comments.GetRelationshipByID("rId6"));
Assert.IsNotNull(sheet.GetRelationship("rId1"));
Assert.IsNotNull(sheet.GetRelationship("rId2"));
Assert.IsNotNull(sheet.GetRelationship("rId3"));
Assert.IsNotNull(sheet.GetRelationship("rId6"));
}
/**
* Excel uses relations on sheets to store the details of
* external hyperlinks. Check we can load these ok.
*/
[Test]
public void TestLoadExcelHyperlinkRelations() {
Stream is1 = OpenXml4NetTestDataSamples.OpenSampleStream("ExcelWithHyperlinks.xlsx");
OPCPackage pkg = OPCPackage.Open(is1);
PackagePart sheet = pkg.GetPart(
PackagingUriHelper.CreatePartName(SHEET_WITH_COMMENTS));
Assert.IsNotNull(sheet);
// rId1 is url
PackageRelationship url = sheet.GetRelationship("rId1");
Assert.IsNotNull(url);
Assert.AreEqual("rId1", url.Id);
Assert.AreEqual("/xl/worksheets/sheet1.xml", url.SourceUri.ToString());
Assert.AreEqual("http://poi.apache.org/", url.TargetUri.ToString());
// rId2 is file
PackageRelationship file = sheet.GetRelationship("rId2");
Assert.IsNotNull(file);
Assert.AreEqual("rId2", file.Id);
Assert.AreEqual("/xl/worksheets/sheet1.xml", file.SourceUri.ToString());
Assert.AreEqual("WithVariousData.xlsx", file.TargetUri.ToString());
// rId3 is mailto
PackageRelationship mailto = sheet.GetRelationship("rId3");
Assert.IsNotNull(mailto);
Assert.AreEqual("rId3", mailto.Id);
Assert.AreEqual("/xl/worksheets/sheet1.xml", mailto.SourceUri.ToString());
Assert.AreEqual("mailto:dev@poi.apache.org?subject=XSSF%20Hyperlinks", mailto.TargetUri.AbsoluteUri);
}
/*
* Excel uses relations on sheets to store the details of
* external hyperlinks. Check we can create these OK,
* then still read them later
*/
[Test]
public void TestCreateExcelHyperlinkRelations() {
string filepath = OpenXml4NetTestDataSamples.GetSampleFileName("ExcelWithHyperlinks.xlsx");
OPCPackage pkg = OPCPackage.Open(filepath, PackageAccess.READ_WRITE);
PackagePart sheet = pkg.GetPart(
PackagingUriHelper.CreatePartName(SHEET_WITH_COMMENTS));
Assert.IsNotNull(sheet);
Assert.AreEqual(3, sheet.GetRelationshipsByType(HYPERLINK_REL_TYPE).Size);
// Add three new ones
PackageRelationship openxml4j =
sheet.AddExternalRelationship("http://www.Openxml4j.org/", HYPERLINK_REL_TYPE);
PackageRelationship sf =
sheet.AddExternalRelationship("http://openxml4j.sf.net/", HYPERLINK_REL_TYPE);
PackageRelationship file =
sheet.AddExternalRelationship("MyDocument.docx", HYPERLINK_REL_TYPE);
// Check they were Added properly
Assert.IsNotNull(openxml4j);
Assert.IsNotNull(sf);
Assert.IsNotNull(file);
Assert.AreEqual(6, sheet.GetRelationshipsByType(HYPERLINK_REL_TYPE).Size);
Assert.AreEqual("http://www.openxml4j.org/", openxml4j.TargetUri.ToString());
Assert.AreEqual("/xl/worksheets/sheet1.xml", openxml4j.SourceUri.ToString());
Assert.AreEqual(HYPERLINK_REL_TYPE, openxml4j.RelationshipType);
Assert.AreEqual("http://openxml4j.sf.net/", sf.TargetUri.ToString());
Assert.AreEqual("/xl/worksheets/sheet1.xml", sf.SourceUri.ToString());
Assert.AreEqual(HYPERLINK_REL_TYPE, sf.RelationshipType);
Assert.AreEqual("MyDocument.docx", file.TargetUri.ToString());
Assert.AreEqual("/xl/worksheets/sheet1.xml", file.SourceUri.ToString());
Assert.AreEqual(HYPERLINK_REL_TYPE, file.RelationshipType);
// Will Get ids 7, 8 and 9, as we already have 1-6
Assert.AreEqual("rId7", openxml4j.Id);
Assert.AreEqual("rId8", sf.Id);
Assert.AreEqual("rId9", file.Id);
// Write out and re-load
MemoryStream baos = new MemoryStream();
pkg.Save(baos);
MemoryStream bais = new MemoryStream(baos.ToArray());
pkg = OPCPackage.Open(bais);
// use revert to not re-write the input file
pkg.Revert();
// Check again
sheet = pkg.GetPart(
PackagingUriHelper.CreatePartName(SHEET_WITH_COMMENTS));
Assert.AreEqual(6, sheet.GetRelationshipsByType(HYPERLINK_REL_TYPE).Size);
Assert.AreEqual("http://poi.apache.org/",
sheet.GetRelationship("rId1").TargetUri.ToString());
Assert.AreEqual("mailto:dev@poi.apache.org?subject=XSSF Hyperlinks",
sheet.GetRelationship("rId3").TargetUri.ToString());
Assert.AreEqual("http://www.openxml4j.org/",
sheet.GetRelationship("rId7").TargetUri.ToString());
Assert.AreEqual("http://openxml4j.sf.net/",
sheet.GetRelationship("rId8").TargetUri.ToString());
Assert.AreEqual("MyDocument.docx",
sheet.GetRelationship("rId9").TargetUri.ToString());
}
[Test]
public void TestCreateRelationsFromScratch() {
MemoryStream baos = new MemoryStream();
OPCPackage pkg = OPCPackage.Create(baos);
PackagePart partA =
pkg.CreatePart(PackagingUriHelper.CreatePartName("/partA"), "text/plain");
PackagePart partB =
pkg.CreatePart(PackagingUriHelper.CreatePartName("/partB"), "image/png");
Assert.IsNotNull(partA);
Assert.IsNotNull(partB);
// Internal
partA.AddRelationship(partB.PartName, TargetMode.Internal, "http://example/Rel");
// External
partA.AddExternalRelationship("http://poi.apache.org/", "http://example/poi");
partB.AddExternalRelationship("http://poi.apache.org/ss/", "http://example/poi/ss");
// Check as expected currently
Assert.AreEqual("/partB", partA.GetRelationship("rId1").TargetUri.ToString());
Assert.AreEqual("http://poi.apache.org/",
partA.GetRelationship("rId2").TargetUri.ToString());
Assert.AreEqual("http://poi.apache.org/ss/",
partB.GetRelationship("rId1").TargetUri.ToString());
// Save, and re-load
pkg.Close();
MemoryStream bais = new MemoryStream(baos.ToArray());
pkg = OPCPackage.Open(bais);
partA = pkg.GetPart(PackagingUriHelper.CreatePartName("/partA"));
partB = pkg.GetPart(PackagingUriHelper.CreatePartName("/partB"));
// Check the relations
Assert.AreEqual(2, partA.Relationships.Size);
Assert.AreEqual(1, partB.Relationships.Size);
Assert.AreEqual("/partB", partA.GetRelationship("rId1").TargetUri.OriginalString);
Assert.AreEqual("http://poi.apache.org/",
partA.GetRelationship("rId2").TargetUri.ToString());
Assert.AreEqual("http://poi.apache.org/ss/",
partB.GetRelationship("rId1").TargetUri.ToString());
// Check core too
Assert.AreEqual("/docProps/core.xml",
pkg.GetRelationshipsByType(
"http://schemas.openxmlformats.org/package/2006/relationships/metadata/core-properties").GetRelationship(0).TargetUri.ToString());
// Add some more
partB.AddExternalRelationship("http://poi.apache.org/new", "http://example/poi/new");
partB.AddExternalRelationship("http://poi.apache.org/alt", "http://example/poi/alt");
// Check the relations
Assert.AreEqual(2, partA.Relationships.Size);
Assert.AreEqual(3, partB.Relationships.Size);
Assert.AreEqual("/partB", partA.GetRelationship("rId1").TargetUri.OriginalString);
Assert.AreEqual("http://poi.apache.org/",
partA.GetRelationship("rId2").TargetUri.OriginalString);
Assert.AreEqual("http://poi.apache.org/ss/",
partB.GetRelationship("rId1").TargetUri.OriginalString);
Assert.AreEqual("http://poi.apache.org/new",
partB.GetRelationship("rId2").TargetUri.OriginalString);
Assert.AreEqual("http://poi.apache.org/alt",
partB.GetRelationship("rId3").TargetUri.OriginalString);
}
[Test]
public void TestTargetWithSpecialChars() {
OPCPackage pkg;
string filepath = OpenXml4NetTestDataSamples.GetSampleFileName("50154.xlsx");
pkg = OPCPackage.Open(filepath);
Assert_50154(pkg);
MemoryStream baos = new MemoryStream();
pkg.Save(baos);
// use revert to not re-write the input file
pkg.Revert();
MemoryStream bais = new MemoryStream(baos.ToArray());
pkg = OPCPackage.Open(bais);
Assert_50154(pkg);
}
public void Assert_50154(OPCPackage pkg) {
Uri drawingUri = new Uri("/xl/drawings/drawing1.xml", UriKind.Relative);
PackagePart drawingPart = pkg.GetPart(PackagingUriHelper.CreatePartName(drawingUri));
PackageRelationshipCollection drawingRels = drawingPart.Relationships;
Assert.AreEqual(6, drawingRels.Size);
// expected one image
Assert.AreEqual(1, drawingPart.GetRelationshipsByType("http://schemas.openxmlformats.org/officeDocument/2006/relationships/image").Size);
// and three hyperlinks
Assert.AreEqual(5, drawingPart.GetRelationshipsByType("http://schemas.openxmlformats.org/officeDocument/2006/relationships/hyperlink").Size);
PackageRelationship rId1 = drawingPart.GetRelationship("rId1");
Uri parent = drawingPart.PartName.URI;
Uri rel1 = new Uri(Path.Combine(parent.ToString(), rId1.TargetUri.ToString()), UriKind.Relative);
Uri rel11 = PackagingUriHelper.RelativizeUri(drawingPart.PartName.URI, rId1.TargetUri);
Assert.AreEqual("'Another Sheet'!A1", WebUtility.UrlDecode(rel1.ToString().Split(new char[] { '#' })[1]));
Assert.AreEqual("'Another Sheet'!A1", WebUtility.UrlDecode(rel11.ToString().Split(new char[] { '#' })[1]));
PackageRelationship rId2 = drawingPart.GetRelationship("rId2");
Uri rel2 = PackagingUriHelper.RelativizeUri(drawingPart.PartName.URI, rId2.TargetUri);
Assert.AreEqual("../media/image1.png", rel2.OriginalString);
PackageRelationship rId3 = drawingPart.GetRelationship("rId3");
Uri rel3 = new Uri(Path.Combine(parent.ToString(), rId3.TargetUri.ToString()), UriKind.Relative);
Assert.AreEqual("#ThirdSheet!A1", rel3.OriginalString.Split(new char[] { '/' })[3]);
PackageRelationship rId4 = drawingPart.GetRelationship("rId4");
Uri rel4 = new Uri(Path.Combine(parent.ToString(), rId4.TargetUri.ToString()), UriKind.Relative);
Assert.AreEqual("#'\u0410\u043F\u0430\u0447\u0435 \u041F\u041E\u0418'!A1", WebUtility.UrlDecode(rel4.OriginalString.Split(new char[] { '/' })[3]));
PackageRelationship rId5 = drawingPart.GetRelationship("rId5");
Uri rel5 = new Uri(Path.Combine(parent.ToString(), rId5.TargetUri.ToString()), UriKind.Relative);
// back slashed have been Replaced with forward
//Assert.AreEqual("file:///D:/chan-chan.mp3", rel5.ToString());
PackageRelationship rId6 = drawingPart.GetRelationship("rId6");
Uri rel6 = new Uri(ResolveRelativePath(parent.ToString(), WebUtility.UrlDecode(rId6.TargetUri.ToString())), UriKind.Relative);
//Assert.AreEqual("../../../../../../../cygwin/home/yegor/dinom/&&&[access].2010-10-26.log", rel6.OriginalString);
//Assert.AreEqual("#'\u0410\u043F\u0430\u0447\u0435 \u041F\u041E\u0418'!A5", HttpUtility.UrlDecode(rel6.OriginalString.Split(new char[] { '/' })[3]));
}
public static string ResolveRelativePath(string referencePath, string relativePath) {
return Path.GetFullPath(Path.Combine(referencePath, relativePath));
}
[Test]
public void TestSelfRelations_bug51187() {
MemoryStream baos = new MemoryStream();
OPCPackage pkg = OPCPackage.Create(baos);
PackagePart partA =
pkg.CreatePart(PackagingUriHelper.CreatePartName("/partA"), "text/plain");
Assert.IsNotNull(partA);
// reference itself
PackageRelationship rel1 = partA.AddRelationship(partA.PartName, TargetMode.Internal, "partA");
// Save, and re-load
pkg.Close();
MemoryStream bais = new MemoryStream(baos.ToArray());
pkg = OPCPackage.Open(bais);
partA = pkg.GetPart(PackagingUriHelper.CreatePartName("/partA"));
// Check the relations
Assert.AreEqual(1, partA.Relationships.Size);
PackageRelationship rel2 = partA.Relationships.GetRelationship(0);
Assert.AreEqual(rel1.RelationshipType, rel2.RelationshipType);
Assert.AreEqual(rel1.Id, rel2.Id);
Assert.AreEqual(rel1.SourceUri, rel2.SourceUri);
Assert.AreEqual(rel1.TargetUri, rel2.TargetUri);
Assert.AreEqual(rel1.TargetMode, rel2.TargetMode);
}
[Test]
public void TestTrailingSpacesInURI_53282() {
OPCPackage pkg = null;
using (Stream stream = OpenXml4NetTestDataSamples.OpenSampleStream("53282.xlsx")) {
pkg = OPCPackage.Open(stream);
}
PackageRelationshipCollection sheetRels = pkg.GetPartsByName(new Regex("/xl/worksheets/sheet1.xml"))[0].Relationships;
Assert.AreEqual(3, sheetRels.Size);
PackageRelationship rId1 = sheetRels.GetRelationshipByID("rId1");
Assert.AreEqual(TargetMode.External, rId1.TargetMode);
Uri targetUri = rId1.TargetUri;
Assert.AreEqual("mailto:nobody@nowhere.uk%C2%A0", targetUri.OriginalString);
//Assert.AreEqual("nobody@nowhere.uk\u00A0", targetUri.OriginalString);
Console.WriteLine("how to get string \"nobody@nowhere.uk\\u00A0\"");
MemoryStream out1 = new MemoryStream();
pkg.Save(out1);
pkg = OPCPackage.Open(new ByteArrayInputStream(out1.ToArray()));
out1.Dispose();
sheetRels = pkg.GetPartsByName(new Regex("/xl/worksheets/sheet1.xml"))[(0)].Relationships;
Assert.AreEqual(3, sheetRels.Size);
rId1 = sheetRels.GetRelationshipByID("rId1");
Assert.AreEqual(TargetMode.External, rId1.TargetMode);
targetUri = rId1.TargetUri;
Assert.AreEqual("mailto:nobody@nowhere.uk%C2%A0", targetUri.OriginalString);
//Assert.AreEqual("nobody@nowhere.uk\u00A0", targetUri.Scheme);
}
[Test]
public void TestEntitiesInRels_56164() {
Stream is1 = OpenXml4NetTestDataSamples.OpenSampleStream("PackageRelsHasEntities.ooxml");
OPCPackage p = OPCPackage.Open(is1);
is1.Dispose();
// Should have 3 root relationships
bool foundDocRel = false, foundCorePropRel = false, foundExtPropRel = false;
foreach (PackageRelationship pr in p.Relationships) {
if (pr.RelationshipType.Equals(PackageRelationshipTypes.CORE_DOCUMENT))
foundDocRel = true;
if (pr.RelationshipType.Equals(PackageRelationshipTypes.CORE_PROPERTIES))
foundCorePropRel = true;
if (pr.RelationshipType.Equals(PackageRelationshipTypes.EXTENDED_PROPERTIES))
foundExtPropRel = true;
}
Assert.IsTrue(foundDocRel, "Core/Doc Relationship not found in " + p.Relationships);
Assert.IsTrue(foundCorePropRel, "Core Props Relationship not found in " + p.Relationships);
Assert.IsTrue(foundExtPropRel, "Ext Props Relationship not found in " + p.Relationships);
// Should have normal work parts
bool foundCoreProps = false, foundDocument = false, foundTheme1 = false;
foreach (PackagePart part in p.GetParts()) {
if (part.PartName.ToString().Equals("/docProps/core.xml")) {
Assert.AreEqual(ContentTypes.CORE_PROPERTIES_PART, part.ContentType);
foundCoreProps = true;
}
if (part.PartName.ToString().Equals("/word/document.xml")) {
Assert.AreEqual(XWPFRelation.DOCUMENT.ContentType, part.ContentType);
foundDocument = true;
}
if (part.PartName.ToString().Equals("/word/theme/theme1.xml")) {
Assert.AreEqual(XWPFRelation.THEME.ContentType, part.ContentType);
foundTheme1 = true;
}
}
Assert.IsTrue(foundCoreProps, "Core not found in " + Arrays.ToString(p.GetParts().ToArray()));
Assert.IsTrue(foundDocument, "Document not found in " + Arrays.ToString(p.GetParts().ToArray()));
Assert.IsTrue(foundTheme1, "Theme1 not found in " + Arrays.ToString(p.GetParts().ToArray()));
}
}
} | 49.408791 | 162 | 0.627508 | [
"Apache-2.0"
] | Arch/Npoi.Core | test/Npoi.Core.OpenXml4Net.Tests/TestRelationships.cs | 22,481 | C# |
// ------------------------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License in the project root for license information.
// ------------------------------------------------------------------------------
// **NOTE** This file was generated by a tool and any changes will be overwritten.
// <auto-generated/>
// Template Source: EntityCollectionRequest.cs.tt
namespace Microsoft.Graph
{
using System;
using System.Collections.Generic;
using System.Net.Http;
using System.Threading;
using System.Linq.Expressions;
/// <summary>
/// The type VirtualEndpointCloudPCsCollectionRequest.
/// </summary>
public partial class VirtualEndpointCloudPCsCollectionRequest : BaseRequest, IVirtualEndpointCloudPCsCollectionRequest
{
/// <summary>
/// Constructs a new VirtualEndpointCloudPCsCollectionRequest.
/// </summary>
/// <param name="requestUrl">The URL for the built request.</param>
/// <param name="client">The <see cref="IBaseClient"/> for handling requests.</param>
/// <param name="options">Query and header option name value pairs for the request.</param>
public VirtualEndpointCloudPCsCollectionRequest(
string requestUrl,
IBaseClient client,
IEnumerable<Option> options)
: base(requestUrl, client, options)
{
}
/// <summary>
/// Adds the specified CloudPC to the collection via POST.
/// </summary>
/// <param name="cloudPC">The CloudPC to add.</param>
/// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param>
/// <returns>The created CloudPC.</returns>
public System.Threading.Tasks.Task<CloudPC> AddAsync(CloudPC cloudPC, CancellationToken cancellationToken = default)
{
this.ContentType = CoreConstants.MimeTypeNames.Application.Json;
this.Method = HttpMethods.POST;
return this.SendAsync<CloudPC>(cloudPC, cancellationToken);
}
/// <summary>
/// Adds the specified CloudPC to the collection via POST and returns a <see cref="GraphResponse{CloudPC}"/> object of the request.
/// </summary>
/// <param name="cloudPC">The CloudPC to add.</param>
/// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param>
/// <returns>The <see cref="GraphResponse{CloudPC}"/> object of the request.</returns>
public System.Threading.Tasks.Task<GraphResponse<CloudPC>> AddResponseAsync(CloudPC cloudPC, CancellationToken cancellationToken = default)
{
this.ContentType = CoreConstants.MimeTypeNames.Application.Json;
this.Method = HttpMethods.POST;
return this.SendAsyncWithGraphResponse<CloudPC>(cloudPC, cancellationToken);
}
/// <summary>
/// Gets the collection page.
/// </summary>
/// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param>
/// <returns>The collection page.</returns>
public async System.Threading.Tasks.Task<IVirtualEndpointCloudPCsCollectionPage> GetAsync(CancellationToken cancellationToken = default)
{
this.Method = HttpMethods.GET;
var response = await this.SendAsync<VirtualEndpointCloudPCsCollectionResponse>(null, cancellationToken).ConfigureAwait(false);
if (response?.Value?.CurrentPage != null)
{
response.Value.InitializeNextPageRequest(this.Client, response.NextLink);
// Copy the additional data collection to the page itself so that information is not lost
response.Value.AdditionalData = response.AdditionalData;
return response.Value;
}
return null;
}
/// <summary>
/// Gets the collection page and returns a <see cref="GraphResponse{VirtualEndpointCloudPCsCollectionResponse}"/> object.
/// </summary>
/// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param>
/// <returns>The <see cref="GraphResponse{VirtualEndpointCloudPCsCollectionResponse}"/> object.</returns>
public System.Threading.Tasks.Task<GraphResponse<VirtualEndpointCloudPCsCollectionResponse>> GetResponseAsync(CancellationToken cancellationToken = default)
{
this.Method = HttpMethods.GET;
return this.SendAsyncWithGraphResponse<VirtualEndpointCloudPCsCollectionResponse>(null, cancellationToken);
}
/// <summary>
/// Adds the specified expand value to the request.
/// </summary>
/// <param name="value">The expand value.</param>
/// <returns>The request object to send.</returns>
public IVirtualEndpointCloudPCsCollectionRequest Expand(string value)
{
this.QueryOptions.Add(new QueryOption("$expand", value));
return this;
}
/// <summary>
/// Adds the specified expand value to the request.
/// </summary>
/// <param name="expandExpression">The expression from which to calculate the expand value.</param>
/// <returns>The request object to send.</returns>
public IVirtualEndpointCloudPCsCollectionRequest Expand(Expression<Func<CloudPC, object>> expandExpression)
{
if (expandExpression == null)
{
throw new ArgumentNullException(nameof(expandExpression));
}
string error;
string value = ExpressionExtractHelper.ExtractMembers(expandExpression, out error);
if (value == null)
{
throw new ArgumentException(error, nameof(expandExpression));
}
else
{
this.QueryOptions.Add(new QueryOption("$expand", value));
}
return this;
}
/// <summary>
/// Adds the specified select value to the request.
/// </summary>
/// <param name="value">The select value.</param>
/// <returns>The request object to send.</returns>
public IVirtualEndpointCloudPCsCollectionRequest Select(string value)
{
this.QueryOptions.Add(new QueryOption("$select", value));
return this;
}
/// <summary>
/// Adds the specified select value to the request.
/// </summary>
/// <param name="selectExpression">The expression from which to calculate the select value.</param>
/// <returns>The request object to send.</returns>
public IVirtualEndpointCloudPCsCollectionRequest Select(Expression<Func<CloudPC, object>> selectExpression)
{
if (selectExpression == null)
{
throw new ArgumentNullException(nameof(selectExpression));
}
string error;
string value = ExpressionExtractHelper.ExtractMembers(selectExpression, out error);
if (value == null)
{
throw new ArgumentException(error, nameof(selectExpression));
}
else
{
this.QueryOptions.Add(new QueryOption("$select", value));
}
return this;
}
/// <summary>
/// Adds the specified top value to the request.
/// </summary>
/// <param name="value">The top value.</param>
/// <returns>The request object to send.</returns>
public IVirtualEndpointCloudPCsCollectionRequest Top(int value)
{
this.QueryOptions.Add(new QueryOption("$top", value.ToString()));
return this;
}
/// <summary>
/// Adds the specified filter value to the request.
/// </summary>
/// <param name="value">The filter value.</param>
/// <returns>The request object to send.</returns>
public IVirtualEndpointCloudPCsCollectionRequest Filter(string value)
{
this.QueryOptions.Add(new QueryOption("$filter", value));
return this;
}
/// <summary>
/// Adds the specified skip value to the request.
/// </summary>
/// <param name="value">The skip value.</param>
/// <returns>The request object to send.</returns>
public IVirtualEndpointCloudPCsCollectionRequest Skip(int value)
{
this.QueryOptions.Add(new QueryOption("$skip", value.ToString()));
return this;
}
/// <summary>
/// Adds the specified orderby value to the request.
/// </summary>
/// <param name="value">The orderby value.</param>
/// <returns>The request object to send.</returns>
public IVirtualEndpointCloudPCsCollectionRequest OrderBy(string value)
{
this.QueryOptions.Add(new QueryOption("$orderby", value));
return this;
}
}
}
| 43.784689 | 164 | 0.608458 | [
"MIT"
] | ScriptBox99/msgraph-beta-sdk-dotnet | src/Microsoft.Graph/Generated/requests/VirtualEndpointCloudPCsCollectionRequest.cs | 9,151 | C# |
using System;
using System.Collections.Generic;
using Shouldly.Tests.TestHelpers;
namespace Shouldly.Tests.Dictionaries.ShouldContainKeyAndValue
{
public class GuidScenario : ShouldlyShouldTestScenario
{
private readonly Dictionary<Guid, Guid> _dictionary = new Dictionary<Guid, Guid>
{
{ GuidKey, GuidValue}
};
private static readonly Guid GuidKey = Guid.NewGuid();
private static readonly Guid GuidValue = Guid.NewGuid();
private readonly Guid _missingGuidKey = new Guid("1924e617-2fc2-47ae-ad38-b6f30ec2226b");
private readonly Guid _missingGuidValue = new Guid("F08A0B08-C9F4-49BB-A4D4-BE06E88B69C8");
protected override void ShouldThrowAWobbly()
{
_dictionary.ShouldContainKeyAndValue(_missingGuidKey, _missingGuidValue);
}
protected override string ChuckedAWobblyErrorMessage
{
get { return "Dictionary \"_dictionary\" should contain key \"1924e617-2fc2-47ae-ad38-b6f30ec2226b\" with value \"f08a0b08-c9f4-49bb-a4d4-be06e88b69c8\" but the key does not exist"; }
}
protected override void ShouldPass()
{
_dictionary.ShouldContainKeyAndValue(GuidKey, GuidValue);
}
}
} | 37.235294 | 195 | 0.687204 | [
"BSD-3-Clause"
] | asgerhallas/shouldly | src/Shouldly.Tests/Dictionaries/ShouldContainKeyAndValue/GuidScenario.cs | 1,268 | C# |
using System;
using System.Collections.Generic;
using System.Text;
public class EnduranceDriver : Driver
{
public EnduranceDriver(string name, Car car)
: base(name, car, 1.5)
{
}
}
| 15.769231 | 49 | 0.668293 | [
"MIT"
] | mmihaylov82/CSharp-OOP-Basics | 09. Exam Retake - Grand Prix - 5 September 2017/GrandPrix/Models/EnduranceDriver.cs | 207 | C# |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using UnityEngine;
namespace UnityEditor.VFX.Block
{
enum AttributeCompositionMode
{
Overwrite,
Add,
Multiply,
Blend
}
enum TextureDataEncoding
{
UnsignedNormalized,
Signed
}
enum RandomMode
{
Off,
PerComponent,
Uniform,
}
class VFXBlockUtility
{
public static string GetNameString(AttributeCompositionMode mode)
{
switch (mode)
{
case AttributeCompositionMode.Overwrite: return "Set";
case AttributeCompositionMode.Add: return "Add";
case AttributeCompositionMode.Multiply: return "Multiply";
case AttributeCompositionMode.Blend: return "Blend";
default: throw new ArgumentException();
}
}
public static string GetNameString(RandomMode mode)
{
switch (mode)
{
case RandomMode.Off: return "";
case RandomMode.PerComponent: return "Random (Per-component)";
case RandomMode.Uniform: return "Random (Uniform)";
default: throw new ArgumentException();
}
}
public static string GetComposeString(AttributeCompositionMode mode, params string[] parameters)
{
switch (mode)
{
case AttributeCompositionMode.Overwrite: return string.Format("{0} = {1};", parameters);
case AttributeCompositionMode.Add: return string.Format("{0} += {1};", parameters);
case AttributeCompositionMode.Multiply: return string.Format("{0} *= {1};", parameters);
case AttributeCompositionMode.Blend: return string.Format("{0} = lerp({0},{1},{2});", parameters);
default: throw new System.NotImplementedException("VFXBlockUtility.GetComposeFormatString() does not implement return string for : " + mode.ToString());
}
}
public static string GetRandomMacroString(RandomMode mode, int attributeSize, string postfix, params string[] parameters)
{
switch (mode)
{
case RandomMode.Off:
return parameters[0] + postfix;
case RandomMode.Uniform:
return string.Format("lerp({0},{1},RAND)", parameters.Select(s => s + postfix).ToArray());
case RandomMode.PerComponent:
string rand = GetRandStringFromSize(attributeSize);
return string.Format("lerp({0},{1}," + rand + ")", parameters.Select(s => s + postfix).ToArray());
default: throw new System.NotImplementedException("VFXBlockUtility.GetRandomMacroString() does not implement return string for RandomMode : " + mode.ToString());
}
}
public static string GetRandStringFromSize(int size)
{
if (size < 0 || size > 4)
throw new ArgumentOutOfRangeException("Size can be only of 1, 2, 3 or 4");
return "RAND" + ((size != 1) ? size.ToString() : "");
}
// TODO Remove that
public static string GetSizeVector(VFXContext context, int nbComponents = 3)
{
var data = context.GetData();
string size = data.IsCurrentAttributeRead(VFXAttribute.Size, context) ? "size" : VFXAttribute.kDefaultSize.ToString();
string scaleX = data.IsCurrentAttributeRead(VFXAttribute.ScaleX, context) ? "scaleX" : "1.0f";
string scaleY = nbComponents >= 2 && data.IsCurrentAttributeRead(VFXAttribute.ScaleY, context) ? "scaleY" : "1.0f";
string scaleZ = nbComponents >= 3 && data.IsCurrentAttributeRead(VFXAttribute.ScaleZ, context) ? "scaleZ" : "1.0f";
switch (nbComponents)
{
case 1: return string.Format("(size * {0})", scaleX);
case 2: return string.Format("(size * float2({0},{1}))", scaleX, scaleY);
case 3: return string.Format("(size * float3({0},{1},{2}))", scaleX, scaleY, scaleZ);
default:
throw new ArgumentException("NbComponents must be between 1 and 3");
}
}
// TODO Remove that
public static string SetSizesFromVector(VFXContext context, string vector, int nbComponents = 3)
{
if (nbComponents < 1 || nbComponents > 3)
throw new ArgumentException("NbComponents must be between 1 and 3");
var data = context.GetData();
string res = string.Empty;
if (data.IsCurrentAttributeWritten(VFXAttribute.ScaleX, context))
res += string.Format("scaleX = {0}.x / size;\n", vector);
if (nbComponents >= 2 && data.IsCurrentAttributeWritten(VFXAttribute.ScaleY, context))
res += string.Format("scaleY = {0}.y / size;\n", vector);
if (nbComponents >= 3 && data.IsCurrentAttributeWritten(VFXAttribute.ScaleZ, context))
res += string.Format("scaleZ = {0}.z / size;\n", vector);
return res.TrimEnd(new[] { '\n' });
}
public static bool ConvertToVariadicAttributeIfNeeded(ref string attribName, out VariadicChannelOptions outChannel)
{
var attrib = VFXAttribute.Find(attribName);
if (attrib.variadic == VFXVariadic.BelongsToVariadic)
{
char component = attrib.name.ToLower().Last();
VariadicChannelOptions channel;
switch (component)
{
case 'x':
channel = VariadicChannelOptions.X;
break;
case 'y':
channel = VariadicChannelOptions.Y;
break;
case 'z':
channel = VariadicChannelOptions.Z;
break;
default:
throw new InvalidOperationException(string.Format("Cannot convert {0} to variadic version", attrib.name));
}
attribName = VFXAttribute.Find(attrib.name.Substring(0, attrib.name.Length - 1)).name; // Just to ensure the attribute can be found
outChannel = channel;
return true;
}
outChannel = VariadicChannelOptions.X;
return false;
}
static VariadicChannelOptions ChannelFromMask(string mask)
{
mask = mask.ToLower();
if (mask == "x")
return VariadicChannelOptions.X;
else if (mask == "y")
return VariadicChannelOptions.Y;
else if (mask == "z")
return VariadicChannelOptions.Z;
else if (mask == "xy")
return VariadicChannelOptions.XY;
else if (mask == "xz")
return VariadicChannelOptions.XZ;
else if (mask == "yz")
return VariadicChannelOptions.YZ;
else if (mask == "xyz")
return VariadicChannelOptions.XYZ;
return VariadicChannelOptions.X;
}
static string MaskFromChannel(VariadicChannelOptions channel)
{
switch (channel)
{
case VariadicChannelOptions.X: return "x";
case VariadicChannelOptions.Y: return "y";
case VariadicChannelOptions.Z: return "z";
case VariadicChannelOptions.XY: return "xy";
case VariadicChannelOptions.XZ: return "xz";
case VariadicChannelOptions.YZ: return "yz";
case VariadicChannelOptions.XYZ: return "xyz";
}
throw new InvalidOperationException("MaskFromChannel missing for " + channel);
}
public static bool ConvertSizeAttributeIfNeeded(ref string attribName, ref VariadicChannelOptions channels)
{
if (attribName == "size")
{
if (channels == VariadicChannelOptions.X) // Consider sizeX as uniform
{
return true;
}
else
{
attribName = "scale";
return true;
}
}
if (attribName == "sizeX")
{
attribName = "size";
channels = VariadicChannelOptions.X;
return true;
}
if (attribName == "sizeY")
{
attribName = "scale";
channels = VariadicChannelOptions.Y;
return true;
}
if (attribName == "sizeZ")
{
attribName = "scale";
channels = VariadicChannelOptions.Z;
return true;
}
return false;
}
public static bool SanitizeAttribute(ref string attribName, ref VariadicChannelOptions channels, int version)
{
bool settingsChanged = false;
string oldName = attribName;
VariadicChannelOptions oldChannels = channels;
if (version < 1 && channels == VariadicChannelOptions.XZ) // Enumerators have changed
{
channels = VariadicChannelOptions.XYZ;
settingsChanged = true;
}
if (version < 1 && VFXBlockUtility.ConvertSizeAttributeIfNeeded(ref attribName, ref channels))
{
Debug.Log(string.Format("Sanitizing attribute: Convert {0} with channel {2} to {1}", oldName, attribName, oldChannels));
settingsChanged = true;
}
// Changes attribute to variadic version
VariadicChannelOptions newChannels;
if (VFXBlockUtility.ConvertToVariadicAttributeIfNeeded(ref attribName, out newChannels))
{
Debug.Log(string.Format("Sanitizing attribute: Convert {0} to variadic attribute {1} with channel {2}", oldName, attribName, newChannels));
channels = newChannels;
settingsChanged = true;
}
return settingsChanged;
}
static public bool SanitizeAttribute(ref string attribName, ref string channelsMask, int version)
{
var channels = ChannelFromMask(channelsMask);
var settingsChanged = SanitizeAttribute(ref attribName, ref channels, version);
channelsMask = MaskFromChannel(channels);
return settingsChanged;
}
}
}
| 39.028986 | 177 | 0.552079 | [
"Apache-2.0"
] | CrazyJohn16/JoaoArena | Library/PackageCache/com.unity.visualeffectgraph@7.3.1/Editor/Models/Blocks/Implementations/VFXBlockUtility.cs | 10,772 | C# |
namespace Coevent.Entities;
using System;
public class Account : AuditColumns
{
#region Properties
public long Id { get; set; }
public string Name { get; set; }
public string Description { get; set; }
public AccountType AccountType { get; set; }
public bool IsDisabled { get; set; }
public long OwnerId { get; set; }
public User? Owner { get; set; }
public ICollection<Calendar> Calendars { get; } = new List<Calendar>();
public ICollection<Event> Events { get; } = new List<Event>();
public ICollection<Schedule> Schedules { get; } = new List<Schedule>();
public ICollection<Trait> Traits { get; } = new List<Trait>();
public ICollection<Criteria> Criterias { get; } = new List<Criteria>();
public ICollection<Survey> Surveys { get; } = new List<Survey>();
public ICollection<UserAccount> UsersManyToMany { get; } = new List<UserAccount>();
public ICollection<User> Users { get; } = new List<User>();
public ICollection<Role> Roles { get; } = new List<Role>();
public ICollection<Claim> Claims { get; } = new List<Claim>();
public ICollection<UserClaim> UserClaims { get; } = new List<UserClaim>();
#endregion
#region Constructors
protected Account()
{
this.Name = String.Empty;
this.Description = string.Empty;
this.Owner = null!;
}
public Account(string name, User owner)
{
this.Name = name;
this.Description = String.Empty;
this.Owner = owner ?? throw new ArgumentNullException(nameof(owner));
this.OwnerId = owner.Id;
}
public Account(string name, long ownerId)
{
this.Name = name;
this.Description = String.Empty;
this.OwnerId = ownerId;
}
#endregion
#region Methods
#endregion
}
| 25.305556 | 87 | 0.630077 | [
"Apache-2.0"
] | FosolSolutions/coevent | api/libs/entities/Account.cs | 1,824 | C# |
using Andtech.Common;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
namespace Andtech.Gooball
{
internal class UnityProcess
{
public int ExitCode { get; set; }
private readonly UnityStartInfo startInfo;
public UnityProcess(UnityStartInfo startInfo)
{
this.startInfo = startInfo;
}
public async Task RunAsync()
{
var arguments = new List<string>(startInfo.Args);
var isUsingExplicitLogFile = ArgumentUtility.TryGetOption(arguments, "logFile", out var logFilePath);
var isUsingTempLogFile = startInfo.Follow && !isUsingExplicitLogFile;
var isLogging = isUsingExplicitLogFile || isUsingTempLogFile;
if (isUsingTempLogFile)
{
var fileName = $"LogFile-{DateTime.UtcNow.ToBinary()}.txt";
logFilePath = Path.Combine(startInfo.Project.Path, fileName);
arguments.Add("-logFile");
arguments.Add(logFilePath);
}
var argsString = string.Join(" ", arguments.Select(x => $"\"{x}\""));
if (startInfo.DryRun)
{
Console.WriteLine($"[DRY RUN] {startInfo.Editor.ExecutablePath} {argsString}");
}
else
{
var cts = new CancellationTokenSource();
if (startInfo.Follow)
{
try
{
File.WriteAllText(logFilePath, string.Empty);
}
catch { }
var tail = new Tail(logFilePath);
tail.Listen(cancellationToken: cts.Token);
}
Log.WriteLine($"{startInfo.Editor.ExecutablePath} {argsString}", Verbosity.verbose);
using (var process = new Process())
{
process.StartInfo.FileName = startInfo.Editor.ExecutablePath;
process.StartInfo.UseShellExecute = false;
process.StartInfo.RedirectStandardOutput = true;
process.StartInfo.Arguments = argsString;
process.Start();
process.WaitForExit();
ExitCode = process.ExitCode;
}
cts.Cancel();
}
if (isUsingTempLogFile)
{
File.Delete(logFilePath);
}
}
}
}
| 24.209302 | 105 | 0.659942 | [
"BSD-3-Clause"
] | andtechstudios/gooball | src/Gooball/Core/Unity/UnityProcess.cs | 2,084 | C# |
/*===============================================================================
EntitySpaces Studio by EntitySpaces, LLC
Persistence Layer and Business Objects for Microsoft .NET
EntitySpaces(TM) is a legal trademark of EntitySpaces, LLC
http://www.entityspaces.net
===============================================================================
EntitySpaces Version : 2012.1.0930.0
EntitySpaces Driver : SQL
Date Generated : 9/23/2012 6:16:17 PM
===============================================================================
*/
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Runtime.Serialization;
using EntitySpaces.DynamicQuery;
#if(!SILVERLIGHT)
using System.ServiceModel.DomainServices.Server;
#endif
namespace BusinessObjects
{
public partial class Employees
{
#if(SILVERLIGHT)
[Display(AutoGenerateField=false)]
public Dictionary<string, object> esExtraColumns
{
get
{
if (_esExtraColumns == null)
{
if (this.esExtendedData != null)
{
_esExtraColumns = esDataContractSerializer.FromXml(this.esExtendedData,
typeof(Dictionary<string, object>))
as Dictionary<string, object>;
}
else
{
_esExtraColumns = new Dictionary<string, object>();
}
}
return _esExtraColumns;
}
set { }
}
private Dictionary<string, object> _esExtraColumns;
#endif
}
} | 24.47619 | 81 | 0.575875 | [
"Unlicense"
] | EntitySpaces/EntitySpaces-CompleteSource | Samples/Silverlight_RiaServices_Hierarchical_CS/Silverlight_RiaServices.Web/Generated/Employees.Shared.cs | 1,542 | C# |
using QSP.Utilities.Units;
namespace QSP.UI.UserControls.TakeoffLanding.Common
{
public class AircraftRequest
{
public string Aircraft { get; private set; }
public string Registration { get; private set; }
public double TakeOffWeightKg { get; private set; }
public double LandingWeightKg { get; private set; }
public double ZfwKg { get; private set; }
public WeightUnit WtUnit { get; private set; }
public AircraftRequest(
string Aircraft,
string Registration,
double TakeOffWeightKg,
double LandingWeightKg,
double ZfwKg,
WeightUnit WtUnit)
{
this.Aircraft = Aircraft;
this.Registration = Registration;
this.TakeOffWeightKg = TakeOffWeightKg;
this.LandingWeightKg = LandingWeightKg;
this.ZfwKg = ZfwKg;
this.WtUnit = WtUnit;
}
}
}
| 31.258065 | 59 | 0.595459 | [
"MIT"
] | JetStream96/QSimPlanner | src/QSP/UI/UserControls/TakeoffLanding/Common/AircraftRequest.cs | 971 | C# |
/* TODO: Is this class actually used???? */
using System;
namespace Core.Networking {
class PacketStack {
private byte[] buffer;
public PacketStack() {
buffer = new byte[0];
}
public void Append(OutPacket p) {
byte[] packetBuffer = p.BuildEncrypted();
if (buffer.Length == 0) {
buffer = packetBuffer;
} else {
Array.Resize(ref buffer, buffer.Length + packetBuffer.Length);
Array.Copy(packetBuffer, 0, buffer, buffer.Length - packetBuffer.Length, packetBuffer.Length);
}
}
public byte[] Buffer { get { return this.buffer; } }
}
} | 27.88 | 110 | 0.545194 | [
"MIT"
] | Darkr4ptor/WCPStandard | Core/Networking/PacketStack.cs | 697 | C# |
using System.Threading;
using Assets.Scripts.InMaze.Networking.Jsonify;
using Assets.Scripts.InMaze.Networking.UDP;
using UnityEngine;
namespace Assets.Scripts.InMaze.Multiplayer
{
public abstract class AbsServerController : MonoBehaviour
{
// Should be instantiated for this class
public static bool IsPresent;
protected UDP Server, Spec;
// Use this for initialization
protected virtual void Start()
{
Server = new UServer()
.SetOnPlayerUpdatedEventHandler(PlayerUpdate);
Spec = new USpectator(USpectator.DEFAULT_URL);
new Thread(() => { Server.start(); }).Start();
new Thread(() => { Spec.start(); }).Start();
}
// Leave scene
protected virtual void OnDestroy()
{
if (Server != null) Server.stop();
if (Spec != null) Spec.stop();
IsPresent = false;
StopAllCoroutines();
}
// When player finished updating in UServer
protected abstract void PlayerUpdate(PlayerNode player);
}
}
| 29.315789 | 64 | 0.601436 | [
"Apache-2.0"
] | myze/Unity-App | Assets/Scripts/InMaze/Multiplayer/AbsServerController.cs | 1,116 | 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>
//------------------------------------------------------------------------------
using System;
using System.Reflection;
[assembly: System.Reflection.AssemblyCompanyAttribute("SoftplanAPI1")]
[assembly: System.Reflection.AssemblyConfigurationAttribute("Debug")]
[assembly: System.Reflection.AssemblyFileVersionAttribute("1.0.0.0")]
[assembly: System.Reflection.AssemblyInformationalVersionAttribute("1.0.0")]
[assembly: System.Reflection.AssemblyProductAttribute("SoftplanAPI1")]
[assembly: System.Reflection.AssemblyTitleAttribute("SoftplanAPI1")]
[assembly: System.Reflection.AssemblyVersionAttribute("1.0.0.0")]
// Gerado pela classe WriteCodeFragment do MSBuild.
| 41.041667 | 80 | 0.648731 | [
"MIT"
] | almirtavares/softplanapi | SoftplanAPI1/obj/Debug/netcoreapp3.1/SoftplanAPI1.AssemblyInfo.cs | 985 | C# |
namespace SistemaControleEstoque.Migrations
{
using System;
using System.Data.Entity.Migrations;
public partial class Estoque : DbMigration
{
public override void Up()
{
CreateTable(
"dbo.Estoques",
c => new
{
Id = c.Int(nullable: false, identity: true),
Produto = c.String(),
Quantidade = c.Int(nullable: false),
Valor = c.Decimal(nullable: false, precision: 18, scale: 2),
Ativo = c.Boolean(nullable: false),
UsuarioCriacao = c.Int(nullable: false),
UsuarioAlteracao = c.Int(nullable: false),
DataCriaca = c.DateTime(nullable: false),
DataAlteracao = c.DateTime(nullable: false),
})
.PrimaryKey(t => t.Id);
}
public override void Down()
{
DropTable("dbo.Estoques");
}
}
}
| 32.264706 | 84 | 0.449407 | [
"MIT"
] | Brunobagesteiro/Aula70483 | SistemaControleEstoque/SistemaControleEstoque/Migrations/201912170035055_Estoque.cs | 1,097 | C# |
// Copyright (C) Microsoft. All rights reserved.
// Licensed under the MIT License. See LICENSE.txt in the project root for license information.
using System;
using System.IO;
using System.Linq;
using RulesEngine;
using Newtonsoft.Json;
using System.Collections.Generic;
namespace Microsoft.AppInspector
{
/// <summary>
/// Used to test a specific set of rules were all found in target source; Pass/Fail as well as inverse option to test if a set of rules is not
/// found in source code
/// </summary>
public class TagTestCommand : ICommand
{
enum TagTestType { RulesPresent, RulesNotPresent}
private string _arg_srcPath;
private string _arg_customRulesPath;
private string _arg_outputFile;
private bool _arg_ignoreDefaultRules;
private TagTestType _arg_tagTestType;
private RuleSet _rulesSet;
private WriteOnce.ConsoleVerbosity _arg_consoleVerbosityLevel;
public enum ExitCode
{
NoDiff = 0,
DiffFound = 1,
CriticalError = 2
}
/// Compares a set of rules against a source path...
/// Used for both RulesPresent and RulesNotePresent options
/// Focus is pass/fail not detailed comparison output -see Tagdiff for more
public TagTestCommand(TagTestCommandOptions opt)
{
_arg_srcPath = opt.SourcePath;
_arg_customRulesPath = opt.CustomRulesPath;
_arg_outputFile = opt.OutputFilePath;
if (!Enum.TryParse(opt.ConsoleVerbosityLevel, true, out _arg_consoleVerbosityLevel))
throw new OpException(String.Format(ErrMsg.FormatString(ErrMsg.ID.CMD_INVALID_ARG_VALUE, "-x")));
WriteOnce.Verbosity = _arg_consoleVerbosityLevel;
if (string.IsNullOrEmpty(opt.TestType))
_arg_tagTestType = TagTestType.RulesPresent;
else if (!Enum.TryParse(opt.TestType, true, out _arg_tagTestType))
throw new OpException(ErrMsg.FormatString(ErrMsg.ID.CMD_INVALID_ARG_VALUE, opt.TestType));
_arg_ignoreDefaultRules = opt.IgnoreDefaultRules;
_rulesSet = new RuleSet(Program.Logger);
if (string.IsNullOrEmpty(opt.CustomRulesPath) && _arg_ignoreDefaultRules)
throw new OpException(ErrMsg.GetString(ErrMsg.ID.CMD_NORULES_SPECIFIED));
ConfigureRules();
ConfigureOutput();
}
public void ConfigureRules()
{
List<string> rulePaths = new List<string>();
if (!_arg_ignoreDefaultRules)
rulePaths.Add(Utils.GetPath(Utils.AppPath.defaultRules));
if (!string.IsNullOrEmpty(_arg_customRulesPath))
rulePaths.Add(_arg_customRulesPath);
foreach (string rulePath in rulePaths)
{
if (Directory.Exists(rulePath))
_rulesSet.AddDirectory(rulePath);
else if (File.Exists(rulePath))
_rulesSet.AddFile(rulePath);
else
{
throw new OpException(ErrMsg.FormatString(ErrMsg.ID.CMD_INVALID_RULE_PATH, rulePath));
}
}
//error check based on ruleset not path enumeration
if (_rulesSet.Count() == 0)
{
throw new OpException(ErrMsg.GetString(ErrMsg.ID.CMD_NORULES_SPECIFIED));
}
}
void ConfigureOutput()
{
//setup output
TextWriter outputWriter;
if (!string.IsNullOrEmpty(_arg_outputFile))
{
outputWriter = File.CreateText(_arg_outputFile);
outputWriter.WriteLine(Program.GetVersionString());
WriteOnce.Writer = outputWriter;
}
}
public int Run()
{
WriteOnce.Operation(ErrMsg.FormatString(ErrMsg.ID.CMD_RUNNING, "tagtest"));
//init based on true or false present argument value
bool testSuccess = true;
//one file vs ruleset
string tmp1 = Path.GetTempFileName();
WriteOnce.ConsoleVerbosity saveVerbosity = WriteOnce.Verbosity;
AnalyzeCommand.ExitCode result = AnalyzeCommand.ExitCode.CriticalError;
//setup analyze call with silent option
#region analyzesetup
try
{
AnalyzeCommand cmd1 = new AnalyzeCommand(new AnalyzeCommandOptions
{
SourcePath = _arg_srcPath,
OutputFilePath = tmp1,
OutputFileFormat = "json",
CustomRulesPath = _arg_customRulesPath,
IgnoreDefaultRules = _arg_ignoreDefaultRules,
SimpleTagsOnly = true,
AllowDupTags = false,
ConsoleVerbosityLevel = "None"
});
//quiet analysis commands
result = (AnalyzeCommand.ExitCode)cmd1.Run();
}
catch (Exception e)
{
WriteOnce.Verbosity = saveVerbosity;
throw e;
}
//restore
WriteOnce.Verbosity = saveVerbosity;
if (result == AnalyzeCommand.ExitCode.CriticalError)
{
throw new OpException(ErrMsg.GetString(ErrMsg.ID.CMD_CRITICAL_FILE_ERR));
}
else if (result == AnalyzeCommand.ExitCode.NoMatches)
{
//results
WriteOnce.General(ErrMsg.FormatString(ErrMsg.ID.TAGTEST_RESULTS_TEST_TYPE, _arg_tagTestType.ToString()), false, WriteOnce.ConsoleVerbosity.Low);
if (_arg_tagTestType == TagTestType.RulesPresent)
WriteOnce.Any(ErrMsg.GetString(ErrMsg.ID.TAGTEST_RESULTS_FAIL), true, ConsoleColor.Red, WriteOnce.ConsoleVerbosity.Low);
else
WriteOnce.Any(ErrMsg.GetString(ErrMsg.ID.TAGTEST_RESULTS_SUCCESS), true, ConsoleColor.Green, WriteOnce.ConsoleVerbosity.Low);
WriteOnce.FlushAll();
WriteOnce.Operation(ErrMsg.FormatString(ErrMsg.ID.CMD_COMPLETED, "Tagtest"));
return (int)ExitCode.CriticalError;
}
#endregion
//assumed (result == AnalyzeCommand.ExitCode.MatchesFound)
string file1TagsJson = File.ReadAllText(tmp1);
file1TagsJson = file1TagsJson.Substring(file1TagsJson.IndexOf("["));
var file1TagsObj = JsonConvert.DeserializeObject<TagsFile[]>(file1TagsJson);
var file1Tags = file1TagsObj.First(); // here we have a single FileList object
File.Delete(tmp1);
foreach (Rule r in _rulesSet)
{
//supports both directions by generalizing
string[] testList1 = _arg_tagTestType == TagTestType.RulesNotPresent ?
r.Tags : file1Tags.Tags;
string[] testList2 = _arg_tagTestType == TagTestType.RulesNotPresent ?
file1Tags.Tags : r.Tags;
foreach (string t in testList2)
{
if (TagTest(testList1, t))
WriteOnce.Result(ErrMsg.FormatString(ErrMsg.ID.TAGTEST_RESULTS_TAGS_FOUND, t), true, WriteOnce.ConsoleVerbosity.High);
else
{
testSuccess = false;
WriteOnce.Result(ErrMsg.FormatString(ErrMsg.ID.TAGTEST_RESULTS_TAGS_MISSING, t), true, WriteOnce.ConsoleVerbosity.High);
}
}
}
//results
WriteOnce.General(ErrMsg.FormatString(ErrMsg.ID.TAGTEST_RESULTS_TEST_TYPE, _arg_tagTestType.ToString()), false, WriteOnce.ConsoleVerbosity.Low);
if (testSuccess)
WriteOnce.Any(ErrMsg.GetString(ErrMsg.ID.TAGTEST_RESULTS_SUCCESS), true, ConsoleColor.Green, WriteOnce.ConsoleVerbosity.Low);
else
WriteOnce.Any(ErrMsg.GetString(ErrMsg.ID.TAGTEST_RESULTS_FAIL), true, ConsoleColor.Red, WriteOnce.ConsoleVerbosity.Low);
WriteOnce.FlushAll();
WriteOnce.Operation(ErrMsg.FormatString(ErrMsg.ID.CMD_COMPLETED, "Tagtest"));
return testSuccess ? (int)ExitCode.NoDiff : (int)ExitCode.DiffFound;
}
bool TagTest(string[] list, string test)
{
if (_arg_tagTestType == TagTestType.RulesNotPresent)
return (!list.Any(v => v.Equals(test)));
else
return (list.Any(v => v.Equals(test)));
}
}
}
| 39.29148 | 160 | 0.590048 | [
"MIT"
] | dezsiszabi/ApplicationInspector | AppInspector/Commands/TagTestCommand.cs | 8,764 | C# |
using RogueSharp.Random;
namespace RogueSharp.DiceNotation
{
/// <summary>
/// The Dice class is a static class that has convenience methods for parsing and rolling dice
/// </summary>
public static class Dice
{
private static readonly IDiceParser _diceParser = new DiceParser();
/// <summary>
/// Parse the specified string into a DiceExpression
/// </summary>
/// <param name="expression">The string dice expression to parse. Ex. 3d6+4</param>
/// <returns>A DiceExpression representing the parsed string</returns>
public static DiceExpression Parse( string expression )
{
return _diceParser.Parse( expression );
}
/// <summary>
/// A convenience method for parsing a dice expression from a string, rolling the dice, and returning the total.
/// </summary>
/// <param name="expression">The string dice expression to parse. Ex. 3d6+4</param>
/// <param name="random">IRandom RNG used to perform the Roll.</param>
/// <returns>An integer result of the sum of the dice rolled including constants and scalars in the expression</returns>
public static int Roll( string expression, IRandom random )
{
return Parse( expression ).Roll( random ).Value;
}
/// <summary>
/// A convenience method for parsing a dice expression from a string, rolling the dice, and returning the total.
/// </summary>
/// <param name="expression">The string dice expression to parse. Ex. 3d6+4</param>
/// <returns>An integer result of the sum of the dice rolled including constants and scalars in the expression</returns>
/// <remarks>Uses DotNetRandom as its RNG</remarks>
public static int Roll( string expression )
{
return Roll( expression, Singleton.DefaultRandom );
}
}
} | 43.255814 | 126 | 0.662366 | [
"MIT"
] | FaronBracy/RogueSharp | RogueSharp/DiceNotation/Dice.cs | 1,860 | 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 Bright.Serialization;
using System.Collections.Generic;
using SimpleJSON;
namespace editor.cfg.limit
{
public sealed partial class MonthlyLimit : limit.LimitBase
{
public MonthlyLimit()
{
}
public override void LoadJson(SimpleJSON.JSONObject _json)
{
{
var _fieldJson = _json["num"];
if (_fieldJson != null)
{
if(!_fieldJson.IsNumber) { throw new SerializationException(); } Num = _fieldJson;
}
}
}
public override void SaveJson(SimpleJSON.JSONObject _json)
{
_json["$type"] = "limit.MonthlyLimit";
{
_json["num"] = new JSONNumber(Num);
}
}
public static MonthlyLimit LoadJsonMonthlyLimit(SimpleJSON.JSONNode _json)
{
MonthlyLimit obj = new limit.MonthlyLimit();
obj.LoadJson((SimpleJSON.JSONObject)_json);
return obj;
}
public static void SaveJsonMonthlyLimit(MonthlyLimit _obj, SimpleJSON.JSONNode _json)
{
_obj.SaveJson((SimpleJSON.JSONObject)_json);
}
public int Num { get; set; }
}
}
| 25.288136 | 99 | 0.548257 | [
"MIT"
] | HFX-93/luban_examples | Projects/Csharp_Unity_Editor_json/Assets/Gen/limit/MonthlyLimit.cs | 1,492 | C# |
using CapFrameX.Data.Session.Classes;
using CapFrameX.Data.Session.Contracts;
using CapFrameX.Statistics.NetStandard.Contracts;
using System;
using System.Collections.Generic;
using System.Linq;
namespace CapFrameX.Statistics.NetStandard
{
public static class SessionExtensions
{
public static IList<double> GetFrametimeTimeWindow(this ISession session, double startTime, double endTime, IFrametimeStatisticProviderOptions options, ERemoveOutlierMethod eRemoveOutlierMethod = ERemoveOutlierMethod.None)
{
IList<double> frametimesTimeWindow = new List<double>();
var frametimeStatisticProvider = new FrametimeStatisticProvider(options);
var frameStarts = session.Runs.SelectMany(r => r.CaptureData.TimeInSeconds).ToArray();
var frametimes = frametimeStatisticProvider?.GetOutlierAdjustedSequence(session.Runs.SelectMany(r => r.CaptureData.MsBetweenPresents).ToArray(), eRemoveOutlierMethod);
if (frametimes.Any() && frameStarts.Any())
{
for (int i = 0; i < frametimes.Count(); i++)
{
if (frameStarts[i] >= startTime && frameStarts[i] <= endTime)
{
frametimesTimeWindow.Add(frametimes[i]);
}
}
}
return frametimesTimeWindow;
}
public static IList<Point> GetFrametimePointsTimeWindow(this ISession session, double startTime, double endTime, IFrametimeStatisticProviderOptions options, ERemoveOutlierMethod eRemoveOutlierMethod = ERemoveOutlierMethod.None)
{
IList<Point> frametimesPointsWindow = new List<Point>();
var frametimeStatisticProvider = new FrametimeStatisticProvider(options);
var frametimes = frametimeStatisticProvider?.GetOutlierAdjustedSequence(session.Runs.SelectMany(r => r.CaptureData.MsBetweenPresents).ToArray(), eRemoveOutlierMethod);
var frameStarts = session.Runs.SelectMany(r => r.CaptureData.TimeInSeconds).ToArray();
if (frametimes.Any() && frameStarts.Any())
{
for (int i = 0; i < frametimes.Count(); i++)
{
if (frameStarts[i] >= startTime && frameStarts[i] <= endTime)
{
frametimesPointsWindow.Add(new Point(frameStarts[i], frametimes[i]));
}
}
}
return frametimesPointsWindow;
}
/// <summary>
/// Source: https://github.com/GameTechDev/PresentMon
/// Formular: LatencyMs =~ MsBetweenPresents + MsUntilDisplayed - previous(MsInPresentAPI)
/// </summary>
/// <returns></returns>
public static IList<double> GetApproxInputLagTimes(this ISession session)
{
var frameTimes = session.Runs.SelectMany(r => r.CaptureData.MsBetweenPresents).ToArray();
var appMissed = session.Runs.SelectMany(r => r.CaptureData.Dropped).ToArray();
var untilDisplayedTimes = session.Runs.SelectMany(r => r.CaptureData.MsUntilDisplayed).ToArray();
var inPresentAPITimes = session.Runs.SelectMany(r => r.CaptureData.MsInPresentAPI).ToArray();
var inputLagTimes = new List<double>(frameTimes.Count() - 1);
for (int i = 2; i < frameTimes.Count(); i++)
{
if (!appMissed[i])
inputLagTimes.Add(frameTimes[i] + untilDisplayedTimes[i] + (0.5 * frameTimes[i - 1]) - (0.5 * inPresentAPITimes[i - 1]) - (0.5 * inPresentAPITimes[i - 2]));
}
return inputLagTimes;
}
public static IList<double> GetUpperBoundInputLagTimes(this ISession session)
{
var frameTimes = session.Runs.SelectMany(r => r.CaptureData.MsBetweenPresents).ToArray();
var appMissed = session.Runs.SelectMany(r => r.CaptureData.Dropped).ToArray();
var untilDisplayedTimes = session.Runs.SelectMany(r => r.CaptureData.MsUntilDisplayed).ToArray();
var inPresentAPITimes = session.Runs.SelectMany(r => r.CaptureData.MsInPresentAPI).ToArray();
var upperBoundInputLagTimes = new List<double>(frameTimes.Count() - 1);
for (int i = 2; i < frameTimes.Count(); i++)
{
if (!appMissed[i])
upperBoundInputLagTimes.Add(frameTimes[i] + untilDisplayedTimes[i] + frameTimes[i - 1] - inPresentAPITimes[i - 2]);
}
return upperBoundInputLagTimes;
}
public static IList<double> GetLowerBoundInputLagTimes(this ISession session)
{
var frameTimes = session.Runs.SelectMany(r => r.CaptureData.MsBetweenPresents).ToArray();
var appMissed = session.Runs.SelectMany(r => r.CaptureData.Dropped).ToArray();
var untilDisplayedTimes = session.Runs.SelectMany(r => r.CaptureData.MsUntilDisplayed).ToArray();
var inPresentAPITimes = session.Runs.SelectMany(r => r.CaptureData.MsInPresentAPI).ToArray();
var lowerBoundInputLagTimes = new List<double>(frameTimes.Count() - 1);
for (int i = 2; i < frameTimes.Count(); i++)
{
if (!appMissed[i])
lowerBoundInputLagTimes.Add(frameTimes[i] + untilDisplayedTimes[i] - inPresentAPITimes[i - 1]);
}
return lowerBoundInputLagTimes;
}
public static double GetSyncRangePercentage(this ISession session, int syncRangeLower, int syncRangeUpper)
{
var displayTimes = session.Runs.SelectMany(r => r.CaptureData.MsBetweenDisplayChange);
if (!displayTimes.Any())
{
return 0d;
}
bool IsInRange(double value)
{
int hz = (int)Math.Round(value, 0);
if (hz >= syncRangeLower && hz <= syncRangeUpper)
return true;
else
return false;
};
return displayTimes.Select(time => 1000d / time)
.Count(hz => IsInRange(hz)) / (double)displayTimes.Count();
}
public static IList<Point> GetGPULoadPointTimeWindow(this ISession session)
{
var list = new List<Point>();
var times = session.Runs.SelectMany(r => r.SensorData2.MeasureTime.Values).ToArray();
var loads = session.Runs.SelectMany(r => r.SensorData2.GpuUsage).ToArray();
if (loads.Any())
{
for (int i = 0; i < times.Count(); i++)
{
list.Add(new Point(times[i], loads[i]));
}
}
return list;
}
public static IList<Point> GetCPULoadPointTimeWindow(this ISession session)
{
var list = new List<Point>();
var times = session.Runs.SelectMany(r => r.SensorData2.MeasureTime.Values).ToArray();
var loads = session.Runs.SelectMany(r => r.SensorData2.CpuUsage).ToArray();
if (loads.Any())
{
for (int i = 0; i < times.Count(); i++)
{
list.Add(new Point(times[i], loads[i]));
}
}
return list;
}
public static IList<Point> GetCPUMaxThreadLoadPointTimeWindow(this ISession session)
{
var list = new List<Point>();
var times = session.Runs.SelectMany(r => r.SensorData2.MeasureTime.Values).ToArray();
var loads = session.Runs.SelectMany(r => r.SensorData2.CpuMaxThreadUsage).ToArray();
if (loads.Any())
{
for (int i = 0; i < times.Count(); i++)
{
list.Add(new Point(times[i], loads[i]));
}
}
return list;
}
public static IList<Point> GetGpuPowerLimitPointTimeWindow(this ISession session)
{
var list = new List<Point>();
var times = session.Runs.SelectMany(r => r.SensorData2.MeasureTime.Values).ToArray();
var limits = session.Runs.SelectMany(r => r.SensorData2.GPUPowerLimit).Select(limit => limit * 100).ToArray();
if (limits.Any())
{
for (int i = 0; i < times.Count(); i++)
{
list.Add(new Point(times[i], limits[i]));
}
}
return list;
}
public static IList<Point> GetFpsPointsTimeWindow(this ISession session, double startTime, double endTime,
IFrametimeStatisticProviderOptions options, ERemoveOutlierMethod eRemoveOutlierMethod = ERemoveOutlierMethod.None,
EFilterMode filterMode = EFilterMode.None)
{
IList<Point> fpsPoints = null;
var frametimePoints = session.GetFrametimePointsTimeWindow(startTime, endTime, options, eRemoveOutlierMethod);
var intervalFrametimePoints = session.GetFrametimePointsTimeWindow(0, endTime, options, eRemoveOutlierMethod);
switch (filterMode)
{
case EFilterMode.TimeIntervalAverage:
var timeIntervalAverageFilter = new IntervalTimeAverageFilter(options.IntervalAverageWindowTime);
var timeIntervalAveragePoints = timeIntervalAverageFilter
.ProcessSamples(intervalFrametimePoints.Select(pnt => pnt.Y).ToList(), startTime * 1000, endTime * 1000, session.Runs.SelectMany(r => r.CaptureData.TimeInSeconds).Last() * 1000);
fpsPoints = timeIntervalAveragePoints.Select(pnt => new Point(pnt.X / 1000, 1000 / pnt.Y)).ToList();
break;
default:
fpsPoints = frametimePoints.Select(pnt => new Point(pnt.X, 1000 / pnt.Y)).ToList();
break;
}
return fpsPoints;
}
public static bool HasValidSensorData(this ISession session)
{
return session.Runs.All(run => run.SensorData2 != null && run.SensorData2.MeasureTime.Values.Any());
}
public static string GetPresentationMode(this IEnumerable<ISessionRun> runs)
{
var presentModes = runs.SelectMany(r => r.CaptureData.PresentMode);
var orderedByFrequency = presentModes.GroupBy(x => x).OrderByDescending(x => x.Count()).Select(x => x.Key);
var presentMode = (EPresentMode)orderedByFrequency.First();
switch (presentMode)
{
case EPresentMode.HardwareLegacyFlip:
case EPresentMode.HardwareLegacyCopyToFrontBuffer:
return "Fullscreen Exclusive";
case EPresentMode.HardwareComposedIndependentFlip:
case EPresentMode.HardwareIndependentFlip:
return "Fullscreen Optimized or Borderless";
case EPresentMode.ComposedFlip:
case EPresentMode.ComposedCopyWithGPUGDI:
return "Windowed or Borderless";
default:
return "Unknown";
}
}
}
}
| 45.691057 | 235 | 0.588256 | [
"MIT"
] | CXWorld/CapFrameX | source/CapFrameX.Statistics.NetStandard/SessionExtensions.cs | 11,242 | C# |
using System;
using System.Security.Cryptography.X509Certificates;
using System.Threading.Tasks;
using Microsoft.Azure.KeyVault;
using Microsoft.IdentityModel.Clients.ActiveDirectory;
namespace AspNetCoreSpa.STS.Services.Certificate
{
public class KeyVaultCertificateService : ICertificateService
{
private readonly string _vaultAddress;
private readonly string _vaultClientId;
private readonly string _vaultClientSecret;
public KeyVaultCertificateService(string vaultAddress, string vaultClientId, string vaultClientSecret)
{
_vaultAddress = vaultAddress;
_vaultClientId = vaultClientId;
_vaultClientSecret = vaultClientSecret;
}
public X509Certificate2 GetCertificateFromKeyVault(string vaultCertificateName)
{
var keyVaultClient = new KeyVaultClient(AuthenticationCallback);
var certBundle = keyVaultClient.GetCertificateAsync(_vaultAddress, vaultCertificateName).Result;
var certContent = keyVaultClient.GetSecretAsync(certBundle.SecretIdentifier.Identifier).Result;
var certBytes = Convert.FromBase64String(certContent.Value);
var cert = new X509Certificate2(certBytes);
return cert;
}
private async Task<string> AuthenticationCallback(string authority, string resource, string scope)
{
var clientCredential = new ClientCredential(_vaultClientId, _vaultClientSecret);
var context = new AuthenticationContext(authority, TokenCache.DefaultShared);
var result = await context.AcquireTokenAsync(resource, clientCredential);
return result.AccessToken;
}
}
} | 40.209302 | 110 | 0.720648 | [
"MIT"
] | Anberm/AspNetCoreSpa | src/AspNetCoreSpa.STS/Services/Certificate/KeyVaultCertificateService.cs | 1,731 | C# |
namespace Unamit.Models
{
public class User
{
public string Id;
public string Password;
public string Partner;
}
} | 14.777778 | 27 | 0.669173 | [
"MIT"
] | coenvdwel/unamit | Unamit/Models/User.cs | 135 | C# |
// ------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by SpecFlow (http://www.specflow.org/).
// SpecFlow Version:1.5.0.0
// Runtime Version:4.0.30319.1
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
// ------------------------------------------------------------------------------
#region Designer generated code
namespace SimpleCqrs.EventStore.SqlServer.Tests.Features
{
using TechTalk.SpecFlow;
[System.CodeDom.Compiler.GeneratedCodeAttribute("TechTalk.SpecFlow", "1.5.0.0")]
[System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
[NUnit.Framework.TestFixtureAttribute()]
[NUnit.Framework.DescriptionAttribute("Get Events")]
public partial class GetEventsFeature
{
private static TechTalk.SpecFlow.ITestRunner testRunner;
#line 1 "GetEvents.feature"
#line hidden
[NUnit.Framework.TestFixtureSetUpAttribute()]
public virtual void FeatureSetup()
{
testRunner = TechTalk.SpecFlow.TestRunnerManager.GetTestRunner();
TechTalk.SpecFlow.FeatureInfo featureInfo = new TechTalk.SpecFlow.FeatureInfo(new System.Globalization.CultureInfo("en-US"), "Get Events", "In order to retrieve events from my SQL Server event store\nAs a Simple CQRS devel" +
"oper\nI want to pass a request to retrieve events and get the appropriate events " +
"back", GenerationTargetLanguage.CSharp, ((string[])(null)));
testRunner.OnFeatureStart(featureInfo);
}
[NUnit.Framework.TestFixtureTearDownAttribute()]
public virtual void FeatureTearDown()
{
testRunner.OnFeatureEnd();
testRunner = null;
}
public virtual void ScenarioSetup(TechTalk.SpecFlow.ScenarioInfo scenarioInfo)
{
testRunner.OnScenarioStart(scenarioInfo);
this.FeatureBackground();
}
[NUnit.Framework.TearDownAttribute()]
public virtual void ScenarioTearDown()
{
testRunner.OnScenarioEnd();
}
public virtual void FeatureBackground()
{
#line 6
#line hidden
#line 7
testRunner.Given("the connection string to my database is", "Data Source=.\\SQLEXPRESS;Initial Catalog=test;Integrated Security=True;MultipleAc" +
"tiveResultSets=True;", ((TechTalk.SpecFlow.Table)(null)));
#line hidden
}
[NUnit.Framework.TestAttribute()]
[NUnit.Framework.DescriptionAttribute("Get Events by aggregate root id")]
public virtual void GetEventsByAggregateRootId()
{
TechTalk.SpecFlow.ScenarioInfo scenarioInfo = new TechTalk.SpecFlow.ScenarioInfo("Get Events by aggregate root id", ((string[])(null)));
#line 12
this.ScenarioSetup(scenarioInfo);
#line hidden
TechTalk.SpecFlow.Table table1 = new TechTalk.SpecFlow.Table(new string[] {
"EventDate",
"Data",
"Sequence",
"AggregateRootId",
"EventType"});
table1.AddRow(new string[] {
"3/20/2010 3:01:04 AM",
"Serialized Object",
"1",
"8312E92C-DF1C-4970-A9D5-6414120C3CF7",
"SimpleCqrs.EventStore.SqlServer.Tests.SomethingHappenedEvent, SimpleCqrs.EventSto" +
"re.SqlServer.Tests"});
table1.AddRow(new string[] {
"3/20/2010 4:01:04 AM",
"Serialized Objecta",
"2",
"D50E4D4F-0893-45B2-92F8-897514812A91",
"SimpleCqrs.EventStore.SqlServer.Tests.SomethingHappenedEvent, SimpleCqrs.EventSto" +
"re.SqlServer.Tests"});
table1.AddRow(new string[] {
"3/20/2010 5:01:04 AM",
"Serialized Object2",
"3",
"8312E92C-DF1C-4970-A9D5-6414120C3CF7",
"SimpleCqrs.EventStore.SqlServer.Tests.SomethingElseHappenedEvent, SimpleCqrs.Even" +
"tStore.SqlServer.Tests"});
#line 13
testRunner.Given("I have the following events in the database", ((string)(null)), table1);
#line hidden
TechTalk.SpecFlow.Table table2 = new TechTalk.SpecFlow.Table(new string[] {
"Field",
"Value"});
table2.AddRow(new string[] {
"Sequence",
"97"});
#line 18
testRunner.And("deserializing \'Serialized Object\' will return a SomethingHappenedEvent with the f" +
"ollowing data", ((string)(null)), table2);
#line hidden
TechTalk.SpecFlow.Table table3 = new TechTalk.SpecFlow.Table(new string[] {
"Field",
"Value"});
table3.AddRow(new string[] {
"Sequence",
"98"});
#line 21
testRunner.And("deserializing \'Serialized Object2\' will return a SomethingElseHappenedEvent with " +
"the following data", ((string)(null)), table3);
#line 24
testRunner.When("I retrieve the domain events for \'8312E92C-DF1C-4970-A9D5-6414120C3CF7\'");
#line hidden
TechTalk.SpecFlow.Table table4 = new TechTalk.SpecFlow.Table(new string[] {
"Sequence"});
table4.AddRow(new string[] {
"97"});
table4.AddRow(new string[] {
"98"});
#line 25
testRunner.Then("I should get back the following DomainEvents", ((string)(null)), table4);
#line hidden
testRunner.CollectScenarioErrors();
}
[NUnit.Framework.TestAttribute()]
[NUnit.Framework.DescriptionAttribute("Get Events by sequence")]
public virtual void GetEventsBySequence()
{
TechTalk.SpecFlow.ScenarioInfo scenarioInfo = new TechTalk.SpecFlow.ScenarioInfo("Get Events by sequence", ((string[])(null)));
#line 30
this.ScenarioSetup(scenarioInfo);
#line hidden
TechTalk.SpecFlow.Table table5 = new TechTalk.SpecFlow.Table(new string[] {
"EventDate",
"Data",
"Sequence",
"AggregateRootId",
"EventType"});
table5.AddRow(new string[] {
"3/20/2010 3:01:04 AM",
"Serialized Object",
"1",
"8312E92C-DF1C-4970-A9D5-6414120C3CF7",
"SimpleCqrs.EventStore.SqlServer.Tests.SomethingHappenedEvent, SimpleCqrs.EventSto" +
"re.SqlServer.Tests"});
table5.AddRow(new string[] {
"3/20/2010 4:01:04 AM",
"Serialized Objecta",
"2",
"D50E4D4F-0893-45B2-92F8-897514812A91",
"SimpleCqrs.EventStore.SqlServer.Tests.SomethingHappenedEvent, SimpleCqrs.EventSto" +
"re.SqlServer.Tests"});
table5.AddRow(new string[] {
"3/20/2010 5:01:04 AM",
"Serialized Object2",
"3",
"8312E92C-DF1C-4970-A9D5-6414120C3CF7",
"SimpleCqrs.EventStore.SqlServer.Tests.SomethingElseHappenedEvent, SimpleCqrs.Even" +
"tStore.SqlServer.Tests"});
#line 31
testRunner.Given("I have the following events in the database", ((string)(null)), table5);
#line hidden
TechTalk.SpecFlow.Table table6 = new TechTalk.SpecFlow.Table(new string[] {
"Field",
"Value"});
table6.AddRow(new string[] {
"Sequence",
"97"});
#line 36
testRunner.And("deserializing \'Serialized Object\' will return a SomethingHappenedEvent with the f" +
"ollowing data", ((string)(null)), table6);
#line hidden
TechTalk.SpecFlow.Table table7 = new TechTalk.SpecFlow.Table(new string[] {
"Field",
"Value"});
table7.AddRow(new string[] {
"Sequence",
"98"});
#line 39
testRunner.And("deserializing \'Serialized Object2\' will return a SomethingElseHappenedEvent with " +
"the following data", ((string)(null)), table7);
#line 42
testRunner.When("I retrieve the domain events for \'8312E92C-DF1C-4970-A9D5-6414120C3CF7\' and seque" +
"nce 2");
#line hidden
TechTalk.SpecFlow.Table table8 = new TechTalk.SpecFlow.Table(new string[] {
"Sequence"});
table8.AddRow(new string[] {
"98"});
#line 43
testRunner.Then("I should get back the following DomainEvents", ((string)(null)), table8);
#line hidden
testRunner.CollectScenarioErrors();
}
[NUnit.Framework.TestAttribute()]
[NUnit.Framework.DescriptionAttribute("Get events with one event type")]
public virtual void GetEventsWithOneEventType()
{
TechTalk.SpecFlow.ScenarioInfo scenarioInfo = new TechTalk.SpecFlow.ScenarioInfo("Get events with one event type", ((string[])(null)));
#line 47
this.ScenarioSetup(scenarioInfo);
#line hidden
TechTalk.SpecFlow.Table table9 = new TechTalk.SpecFlow.Table(new string[] {
"EventDate",
"Data",
"Sequence",
"AggregateRootId",
"EventType"});
table9.AddRow(new string[] {
"3/20/2010 3:01:04 AM",
"Serialized Object",
"1",
"8312E92C-DF1C-4970-A9D5-6414120C3CF7",
"SimpleCqrs.EventStore.SqlServer.Tests.SomethingHappenedEvent, SimpleCqrs.EventSto" +
"re.SqlServer.Tests"});
table9.AddRow(new string[] {
"3/20/2010 4:01:04 AM",
"Serialized Object2",
"2",
"D50E4D4F-0893-45B2-92F8-897514812A91",
"SimpleCqrs.EventStore.SqlServer.Tests.SomethingHappenedEvent, SimpleCqrs.EventSto" +
"re.SqlServer.Tests"});
table9.AddRow(new string[] {
"3/20/2010 5:01:04 AM",
"Serialized Object3",
"3",
"8312E92C-DF1C-4970-A9D5-6414120C3CF7",
"SimpleCqrs.EventStore.SqlServer.Tests.SomethingElseHappenedEvent, SimpleCqrs.Even" +
"tStore.SqlServer.Tests"});
#line 48
testRunner.Given("I have the following events in the database", ((string)(null)), table9);
#line hidden
TechTalk.SpecFlow.Table table10 = new TechTalk.SpecFlow.Table(new string[] {
"Field",
"Value"});
table10.AddRow(new string[] {
"Sequence",
"97"});
#line 53
testRunner.And("deserializing \'Serialized Object\' will return a SomethingHappenedEvent with the f" +
"ollowing data", ((string)(null)), table10);
#line hidden
TechTalk.SpecFlow.Table table11 = new TechTalk.SpecFlow.Table(new string[] {
"Field",
"Value"});
table11.AddRow(new string[] {
"Sequence",
"98"});
#line 56
testRunner.And("deserializing \'Serialized Object2\' will return a SomethingHappenedEvent with the " +
"following data", ((string)(null)), table11);
#line hidden
TechTalk.SpecFlow.Table table12 = new TechTalk.SpecFlow.Table(new string[] {
"Field",
"Value"});
table12.AddRow(new string[] {
"Sequence",
"99"});
#line 59
testRunner.And("deserializing \'Serialized Object3\' will return a SomethingElseHappenedEvent with " +
"the following data", ((string)(null)), table12);
#line hidden
TechTalk.SpecFlow.Table table13 = new TechTalk.SpecFlow.Table(new string[] {
"Type"});
table13.AddRow(new string[] {
"SimpleCqrs.EventStore.SqlServer.Tests.SomethingHappenedEvent, SimpleCqrs.EventSto" +
"re.SqlServer.Tests"});
#line 62
testRunner.When("I retrieve the domain events for the following types", ((string)(null)), table13);
#line hidden
TechTalk.SpecFlow.Table table14 = new TechTalk.SpecFlow.Table(new string[] {
"Sequence"});
table14.AddRow(new string[] {
"97"});
table14.AddRow(new string[] {
"98"});
#line 65
testRunner.Then("I should get back the following DomainEvents", ((string)(null)), table14);
#line hidden
testRunner.CollectScenarioErrors();
}
[NUnit.Framework.TestAttribute()]
[NUnit.Framework.DescriptionAttribute("Get events with two event types")]
public virtual void GetEventsWithTwoEventTypes()
{
TechTalk.SpecFlow.ScenarioInfo scenarioInfo = new TechTalk.SpecFlow.ScenarioInfo("Get events with two event types", ((string[])(null)));
#line 70
this.ScenarioSetup(scenarioInfo);
#line hidden
TechTalk.SpecFlow.Table table15 = new TechTalk.SpecFlow.Table(new string[] {
"EventDate",
"Data",
"Sequence",
"AggregateRootId",
"EventType"});
table15.AddRow(new string[] {
"3/20/2010 3:01:04 AM",
"Serialized Object",
"1",
"8312E92C-DF1C-4970-A9D5-6414120C3CF7",
"SimpleCqrs.EventStore.SqlServer.Tests.SomethingHappenedEvent, SimpleCqrs.EventSto" +
"re.SqlServer.Tests"});
table15.AddRow(new string[] {
"3/20/2010 4:01:04 AM",
"Serialized Object2",
"2",
"D50E4D4F-0893-45B2-92F8-897514812A91",
"SimpleCqrs.EventStore.SqlServer.Tests.SomethingHappenedEvent, SimpleCqrs.EventSto" +
"re.SqlServer.Tests"});
table15.AddRow(new string[] {
"3/20/2010 5:01:04 AM",
"Serialized Object3",
"3",
"8312E92C-DF1C-4970-A9D5-6414120C3CF7",
"SimpleCqrs.EventStore.SqlServer.Tests.SomethingElseHappenedEvent, SimpleCqrs.Even" +
"tStore.SqlServer.Tests"});
#line 71
testRunner.Given("I have the following events in the database", ((string)(null)), table15);
#line hidden
TechTalk.SpecFlow.Table table16 = new TechTalk.SpecFlow.Table(new string[] {
"Field",
"Value"});
table16.AddRow(new string[] {
"Sequence",
"97"});
#line 76
testRunner.And("deserializing \'Serialized Object\' will return a SomethingHappenedEvent with the f" +
"ollowing data", ((string)(null)), table16);
#line hidden
TechTalk.SpecFlow.Table table17 = new TechTalk.SpecFlow.Table(new string[] {
"Field",
"Value"});
table17.AddRow(new string[] {
"Sequence",
"98"});
#line 79
testRunner.And("deserializing \'Serialized Object2\' will return a SomethingHappenedEvent with the " +
"following data", ((string)(null)), table17);
#line hidden
TechTalk.SpecFlow.Table table18 = new TechTalk.SpecFlow.Table(new string[] {
"Field",
"Value"});
table18.AddRow(new string[] {
"Sequence",
"99"});
#line 82
testRunner.And("deserializing \'Serialized Object3\' will return a SomethingElseHappenedEvent with " +
"the following data", ((string)(null)), table18);
#line hidden
TechTalk.SpecFlow.Table table19 = new TechTalk.SpecFlow.Table(new string[] {
"Type"});
table19.AddRow(new string[] {
"SimpleCqrs.EventStore.SqlServer.Tests.SomethingHappenedEvent, SimpleCqrs.EventSto" +
"re.SqlServer.Tests"});
table19.AddRow(new string[] {
"SimpleCqrs.EventStore.SqlServer.Tests.SomethingElseHappenedEvent, SimpleCqrs.Even" +
"tStore.SqlServer.Tests"});
#line 85
testRunner.When("I retrieve the domain events for the following types", ((string)(null)), table19);
#line hidden
TechTalk.SpecFlow.Table table20 = new TechTalk.SpecFlow.Table(new string[] {
"Sequence"});
table20.AddRow(new string[] {
"97"});
table20.AddRow(new string[] {
"98"});
table20.AddRow(new string[] {
"99"});
#line 89
testRunner.Then("I should get back the following DomainEvents", ((string)(null)), table20);
#line hidden
testRunner.CollectScenarioErrors();
}
}
}
#endregion
| 47.228426 | 238 | 0.518594 | [
"Unlicense",
"MIT"
] | AdnanAsotic/SimpleCQRS | src/Tests/EventStores/SimpleCqrs.EventStore.SqlServer.Tests/Features/GetEvents.feature.cs | 18,608 | C# |
using System;
using System.Linq;
// using System.Collections.Generic;
// using System.IO;
//
// using CPU = Cosmos.Assembler.x86;
// using System.Reflection;
using Cosmos.Assembler;
using Cosmos.IL2CPU.ILOpCodes;
using XSharp.Compiler;
using static XSharp.Compiler.XSRegisters;
using CPUx86 = Cosmos.Assembler.x86;
namespace Cosmos.IL2CPU.X86.IL
{
/// <summary>
/// Finds the value of a field in the object whose reference is currently on the evaluation stack.
/// </summary>
/// <remarks>
/// MSDN:
/// The stack transitional behavior, in sequential order, is:
/// 1. An object reference (or pointer) is pushed onto the stack.
/// 2. The object reference (or pointer) is popped from the stack; the value of the specified field in the object is found.
/// 3. The value stored in the field is pushed onto the stack.
/// The ldfld instruction pushes the value of a field located in an object onto the stack.
/// The object must be on the stack as an object reference (type O), a managed pointer (type &),
/// an unmanaged pointer (type native int), a transient pointer (type *), or an instance of a value type.
/// The use of an unmanaged pointer is not permitted in verifiable code.
/// The object's field is specified by a metadata token that must refer to a field member.
/// The return type is the same as the one associated with the field. The field may be either an instance field
/// (in which case the object must not be a null reference) or a static field.
///
/// The ldfld instruction can be preceded by either or both of the Unaligned and Volatile prefixes.
///
/// NullReferenceException is thrown if the object is null and the field is not static.
///
/// MissingFieldException is thrown if the specified field is not found in the metadata.
///
/// This is typically checked when Microsoft Intermediate Language (MSIL) instructions are converted to native code, not at run time.
/// </remarks>
[Cosmos.IL2CPU.OpCode(ILOpCode.Code.Ldfld)]
public class Ldfld : ILOp
{
public Ldfld(Cosmos.Assembler.Assembler aAsmblr)
: base(aAsmblr)
{
}
public override void Execute(MethodInfo aMethod, ILOpCode aOpCode)
{
var xOpCode = (ILOpCodes.OpField)aOpCode;
DoExecute(Assembler, xOpCode.Value.DeclaringType, xOpCode.Value.GetFullName(), true, DebugEnabled, aOpCode.StackPopTypes[0]);
}
public static int GetFieldOffset(Type aDeclaringType, string aFieldId)
{
int xExtraOffset = 0;
var xFieldInfo = ResolveField(aDeclaringType, aFieldId, true);
bool xNeedsGC = TypeIsReferenceType(aDeclaringType);
if (xNeedsGC)
{
xExtraOffset = 12;
}
return (int)(xExtraOffset + xFieldInfo.Offset);
}
public static void DoExecute(Cosmos.Assembler.Assembler Assembler, Type aDeclaringType, string xFieldId, bool aDerefExternalField, bool debugEnabled, Type aTypeOnStack)
{
var xOffset = GetFieldOffset(aDeclaringType, xFieldId);
var xFields = GetFieldsInfo(aDeclaringType, false);
var xFieldInfo = (from item in xFields
where item.Id == xFieldId
select item).Single();
XS.Comment("Field: " + xFieldInfo.Id);
XS.Comment("Type: " + xFieldInfo.FieldType.ToString());
XS.Comment("Size: " + xFieldInfo.Size);
XS.Comment("DeclaringType: " + aDeclaringType.FullName);
XS.Comment("TypeOnStack: " + aTypeOnStack.FullName);
XS.Comment("Offset: " + xOffset + " (includes object header)");
if (aDeclaringType.IsValueType && aTypeOnStack == aDeclaringType)
{
#region Read struct value from stack
// This is a 3-step process
// 1. Move the actual value below the stack (negative to ESP)
// 2. Move the value at the right spot of the stack (positive to stack)
// 3. Adjust stack to remove the struct
//
// This is necessary, as the value could otherwise overwrite the struct too soon.
var xTypeStorageSize = GetStorageSize(aDeclaringType);
var xFieldStorageSize = xFieldInfo.Size;
// Step 1, Move the actual value below the stack (negative to ESP)
CopyValue(ESP, -(int)xFieldStorageSize, ESP, xOffset, xFieldStorageSize);
// Step 2 Move the value at the right spot of the stack (positive to stack)
var xStackOffset = (int)(Align(xTypeStorageSize, 4) - xFieldStorageSize);
CopyValue(ESP, xStackOffset, ESP, -(int)xFieldStorageSize, xFieldStorageSize);
// Step 3 Adjust stack to remove the struct
XS.Add(ESP, Align((uint)(xStackOffset), 4));
#endregion Read struct value from stack
return;
}
// pushed size is always 4 or 8
var xSize = xFieldInfo.Size;
if (TypeIsReferenceType(aTypeOnStack))
{
DoNullReferenceCheck(Assembler, debugEnabled, 4);
XS.Add(ESP, 4);
}
else
{
DoNullReferenceCheck(Assembler, debugEnabled, 0);
}
XS.Pop(ECX);
XS.Add(ECX, (uint)(xOffset));
if (xFieldInfo.IsExternalValue && aDerefExternalField)
{
XS.Set(ECX, ECX, sourceIsIndirect: true);
}
for (int i = 1; i <= (xSize / 4); i++)
{
XS.Set(EAX, ECX, sourceDisplacement: (int)(xSize - (i * 4)));
XS.Push(EAX);
}
XS.Set(EAX, 0);
switch (xSize % 4)
{
case 1:
XS.Set(AL, ECX, sourceIsIndirect: true);
XS.Push(EAX);
break;
case 2:
XS.Set(AX, ECX, sourceIsIndirect: true);
XS.Push(EAX);
break;
case 3: //For Release
XS.Set(EAX, ECX, sourceIsIndirect: true);
XS.ShiftRight(EAX, 8);
XS.Push(EAX);
break;
case 0:
{
break;
}
default:
throw new Exception(string.Format("Remainder size {0} {1:D} not supported!", xFieldInfo.FieldType.ToString(), xSize));
}
}
}
}
| 41.89697 | 177 | 0.560538 | [
"BSD-3-Clause"
] | ERamaM/Cosmos | source/Cosmos.IL2CPU/IL/Ldfld.cs | 6,913 | C# |
using System.IO;
using Super.Model.Selection.Stores;
namespace Super.Runtime
{
sealed class BytesToStreamSelector : ActivatedStore<byte[], MemoryStream>
{
public static BytesToStreamSelector Default { get; } = new BytesToStreamSelector();
BytesToStreamSelector() {}
}
} | 23.25 | 85 | 0.767025 | [
"MIT"
] | SuperDotNet/Super.NET | Super/Runtime/BytesToStreamSelector.cs | 281 | C# |
namespace _2.单行重复渲染示例
{
public class StudentInfo
{
public string Name { get; set; }
public bool Gender { get; set; }
public string Class { get; set; }
public string RecordNo { get; set; }
public string Phone { get; set; }
public string Email { get; set; }
}
} | 26.666667 | 44 | 0.5625 | [
"MIT"
] | Nokecy/ExcelReport | examples/2.单行重复渲染示例/StudentInfo.cs | 338 | C# |
#region
using System;
using System.IO;
using System.Linq;
using System.Net;
using ComponentAce.Compression.Libs.zlib;
#endregion
namespace LegendaryClient.Patcher.Logic
{
internal class LeagueDownloadLogic
{
public static string ReleaseListing = "";
public static string SolutionManifest = "";
/// <summary>
/// Gets the Latest LeagueOfLegends lol_game_client_sln version
/// </summary>
public string[] GetLolClientSlnVersion()
{
//Get the GameClientSln version
using (new WebClient())
{
ReleaseListing =
new WebClient().DownloadString(
"http://l3cdn.riotgames.com/releases/live/solutions/lol_game_client_sln/releases/releaselisting_NA");
}
return ReleaseListing.Split(new[] {Environment.NewLine}, StringSplitOptions.None).Skip(1).ToArray();
}
/// <summary>
/// Gets the SolutionManifest
/// </summary>
/// <returns>
/// The SolutionManifest file from riot
/// </returns>
public string CreateConfigurationManifest()
{
string latestSlnVersion = Convert.ToString(GetLolClientSlnVersion());
//Get GameClient Language files
using (new WebClient())
{
SolutionManifest =
new WebClient().DownloadString(
"http://l3cdn.riotgames.com/releases/live/solutions/lol_game_client_sln/releases/" +
latestSlnVersion + "/solutionmanifest");
}
return SolutionManifest;
}
public static void DecompressFile(string inFile, string outFile)
{
int data;
const int stopByte = -1;
var outFileStream = new FileStream(outFile, FileMode.Create);
var inZStream = new ZInputStream(File.Open(inFile, FileMode.Open, FileAccess.Read));
while (stopByte != (data = inZStream.Read()))
{
var dataByte = (byte) data;
outFileStream.WriteByte(dataByte);
}
inZStream.Close();
outFileStream.Close();
}
}
} | 31.985915 | 125 | 0.56539 | [
"BSD-2-Clause"
] | nongnoobjung/Legendary-Garena | LegendaryClient.Patcher/Logic/LeagueDownloadLogic.cs | 2,273 | C# |
using NUnit.Framework;
using System;
using System.Collections.Generic;
using System.Text;
using Virgil.SDK.Web.Authorization;
namespace Virgil.SDK.Tests.Shared
{
[TestFixture]
public class CachingJwtProviderTests
{
[Test]
public async System.Threading.Tasks.Task CachingJwtProvider_Should_ReturnTheSameTokenIfValidAsync()
{
var provider = new CachingJwtProvider(IntegrationHelper.GetObtainToken(10));
var jwt = await provider.GetTokenAsync(new TokenContext("some_identity", "sme_operation"));
var jwt2 = await provider.GetTokenAsync(new TokenContext("some_identity", "sme_operation"));
Assert.AreSame(jwt, jwt2);
}
[Test]
public async System.Threading.Tasks.Task CachingJwtProvider_Should_ReturnNewTokenIfExpired()
{
var provider = new CachingJwtProvider(IntegrationHelper.GetObtainToken(0.001));
var jwt = await provider.GetTokenAsync(new TokenContext("some_identity", "sme_operation"));
var jwt2 = await provider.GetTokenAsync(new TokenContext("some_identity", "sme_operation"));
Assert.AreNotEqual(jwt, jwt2);
}
}
}
| 36.363636 | 107 | 0.6925 | [
"BSD-3-Clause"
] | VirgilSecurity/virgil-net | SDK/Source/Tests/Virgil.SDK.Tests.Shared/CachingJwtProviderTests.cs | 1,202 | C# |
namespace EWSEditor.ExchangeReports
{
partial class TotalEmailsSentAndReceivedPerDayAndSize
{
/// <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.SuspendLayout();
//
// TotalEmailsSentAndReceivedPerDayAndSize
//
this.AutoScaleDimensions = new System.Drawing.SizeF(8F, 16F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(1005, 480);
this.Name = "TotalEmailsSentAndReceivedPerDayAndSize";
this.Text = "TotalEmailsSentAndReceivedPerDayAndSize";
this.Load += new System.EventHandler(this.TotalEmailsSentAndReceivedPerDayAndSize_Load);
this.ResumeLayout(false);
}
#endregion
}
} | 34.319149 | 107 | 0.593304 | [
"MIT"
] | manoj75/o365-EWS-Editor | EWSEditor/ExchangeReports/TotalEmailsSentAndReceivedPerDayAndSize.Designer.cs | 1,615 | C# |
using System;
using System.Collections.Generic;
namespace _08._Balanced_Parentheses
{
class Program
{
static void Main(string[] args)
{
var charParenthesis = new char[]
{
'[',
'(',
'{',
']',
')',
'}'
};
var input = Console.ReadLine().ToCharArray();
Stack<char> stack = new Stack<char>();
bool isBalanced = true;
for (int i = 0; i < input.Length; i++)
{
char current = input[i];
switch (current)
{
case '(':
stack.Push(')');
break;
case '[':
stack.Push(']');
break;
case '{':
stack.Push('}');
break;
case ')':
case ']':
case '}':
if (stack.Count == 0 || stack.Pop() != current)
{
isBalanced = false;
}
break;
default:
break;
}
if (!isBalanced)
{
break;
}
}
Console.WriteLine(isBalanced ? "YES" : "NO");
}
}
}
| 24.333333 | 71 | 0.285062 | [
"Apache-2.0"
] | Vladimir-Dodnikov/CSharp---Advanced | 01. StacksAndQueues - Exercises/08. Balanced Parentheses/Program.cs | 1,535 | C# |
using Microsoft.Extensions.DependencyInjection;
using TypedRest.Endpoints;
namespace TypedRest;
public class DependencyInjectionTest
{
[Fact]
public void TestGetRequiredService()
{
var services = new ServiceCollection();
services.AddTypedRest(new Uri("http://example.com/"));
var provider = services.BuildServiceProvider();
provider.GetRequiredService<EntryEndpoint>()
.Uri.Should().Be(new Uri("http://example.com/"));
}
} | 27.166667 | 65 | 0.683027 | [
"MIT"
] | 1and1-webhosting-infrastructure/TypedRest | src/UnitTests/DependencyInjectionTest.cs | 489 | 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.
namespace System.Windows.Forms {
using System.Diagnostics;
using System;
/// <include file='doc\IWin32window.uex' path='docs/doc[@for="IWin32Window"]/*' />
/// <devdoc>
/// <para>Provides an interface to expose Win32 HWND handles.</para>
/// </devdoc>
[System.Runtime.InteropServices.Guid("458AB8A2-A1EA-4d7b-8EBE-DEE5D3D9442C"), System.Runtime.InteropServices.InterfaceTypeAttribute(System.Runtime.InteropServices.ComInterfaceType.InterfaceIsIUnknown)]
[System.Runtime.InteropServices.ComVisible(true)]
public interface IWin32Window {
/// <include file='doc\IWin32window.uex' path='docs/doc[@for="IWin32Window.Handle"]/*' />
/// <devdoc>
/// <para>Gets the handle to the window represented by the implementor.</para>
/// </devdoc>
IntPtr Handle { get; }
}
}
| 40.653846 | 205 | 0.687796 | [
"MIT"
] | OliaG/winforms | src/System.Windows.Forms/src/System/Windows/Forms/IWin32window.cs | 1,057 | 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 waf-regional-2016-11-28.normal.json service model.
*/
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Net;
using System.Text;
using System.Xml.Serialization;
using Amazon.WAFRegional.Model;
using Amazon.Runtime;
using Amazon.Runtime.Internal;
using Amazon.Runtime.Internal.Transform;
using Amazon.Runtime.Internal.Util;
using ThirdParty.Json.LitJson;
namespace Amazon.WAFRegional.Model.Internal.MarshallTransformations
{
/// <summary>
/// Response Unmarshaller for ListSqlInjectionMatchSets operation
/// </summary>
public class ListSqlInjectionMatchSetsResponseUnmarshaller : JsonResponseUnmarshaller
{
/// <summary>
/// Unmarshaller the response from the service to the response class.
/// </summary>
/// <param name="context"></param>
/// <returns></returns>
public override AmazonWebServiceResponse Unmarshall(JsonUnmarshallerContext context)
{
ListSqlInjectionMatchSetsResponse response = new ListSqlInjectionMatchSetsResponse();
context.Read();
int targetDepth = context.CurrentDepth;
while (context.ReadAtDepth(targetDepth))
{
if (context.TestExpression("NextMarker", targetDepth))
{
var unmarshaller = StringUnmarshaller.Instance;
response.NextMarker = unmarshaller.Unmarshall(context);
continue;
}
if (context.TestExpression("SqlInjectionMatchSets", targetDepth))
{
var unmarshaller = new ListUnmarshaller<SqlInjectionMatchSetSummary, SqlInjectionMatchSetSummaryUnmarshaller>(SqlInjectionMatchSetSummaryUnmarshaller.Instance);
response.SqlInjectionMatchSets = unmarshaller.Unmarshall(context);
continue;
}
}
return response;
}
/// <summary>
/// Unmarshaller error response to exception.
/// </summary>
/// <param name="context"></param>
/// <param name="innerException"></param>
/// <param name="statusCode"></param>
/// <returns></returns>
public override AmazonServiceException UnmarshallException(JsonUnmarshallerContext context, Exception innerException, HttpStatusCode statusCode)
{
var errorResponse = JsonErrorResponseUnmarshaller.GetInstance().Unmarshall(context);
errorResponse.InnerException = innerException;
errorResponse.StatusCode = statusCode;
var responseBodyBytes = context.GetResponseBodyBytes();
using (var streamCopy = new MemoryStream(responseBodyBytes))
using (var contextCopy = new JsonUnmarshallerContext(streamCopy, false, null))
{
if (errorResponse.Code != null && errorResponse.Code.Equals("WAFInternalErrorException"))
{
return WAFInternalErrorExceptionUnmarshaller.Instance.Unmarshall(contextCopy, errorResponse);
}
if (errorResponse.Code != null && errorResponse.Code.Equals("WAFInvalidAccountException"))
{
return WAFInvalidAccountExceptionUnmarshaller.Instance.Unmarshall(contextCopy, errorResponse);
}
}
return new AmazonWAFRegionalException(errorResponse.Message, errorResponse.InnerException, errorResponse.Type, errorResponse.Code, errorResponse.RequestId, errorResponse.StatusCode);
}
private static ListSqlInjectionMatchSetsResponseUnmarshaller _instance = new ListSqlInjectionMatchSetsResponseUnmarshaller();
internal static ListSqlInjectionMatchSetsResponseUnmarshaller GetInstance()
{
return _instance;
}
/// <summary>
/// Gets the singleton.
/// </summary>
public static ListSqlInjectionMatchSetsResponseUnmarshaller Instance
{
get
{
return _instance;
}
}
}
} | 40.941667 | 195 | 0.638917 | [
"Apache-2.0"
] | philasmar/aws-sdk-net | sdk/src/Services/WAFRegional/Generated/Model/Internal/MarshallTransformations/ListSqlInjectionMatchSetsResponseUnmarshaller.cs | 4,913 | C# |
namespace Microsoft.VisualStudio.Shell.Interop
{
public interface SVsRegisterNewDialogFilters
{
}
}
| 15.25 | 48 | 0.688525 | [
"Apache-2.0"
] | JetBrains/JetBrains.EnvDTE | Shell.Interop/Shell/Interop/SVsRegisterNewDialogFilters.cs | 124 | C# |
using System.Collections.Generic;
using System.Security.AccessControl;
using System.Text;
#if NETCOREAPP2_0
using System.Threading.Tasks;
using System.Threading;
#endif
namespace System.IO.Abstractions
{
/// <inheritdoc cref="File"/>
[Serializable]
public abstract class FileBase : IFile
{
protected FileBase(IFileSystem fileSystem)
{
FileSystem = fileSystem;
}
[Obsolete("This constructor only exists to support mocking libraries.", error: true)]
internal FileBase() { }
/// <summary>
/// Exposes the underlying filesystem implementation. This is useful for implementing extension methods.
/// </summary>
public IFileSystem FileSystem { get; }
/// <inheritdoc cref="File.AppendAllLines(string,IEnumerable{string})"/>
public abstract void AppendAllLines(string path, IEnumerable<string> contents);
/// <inheritdoc cref="File.AppendAllLines(string,IEnumerable{string},Encoding)"/>
public abstract void AppendAllLines(string path, IEnumerable<string> contents, Encoding encoding);
#if NETCOREAPP2_0
/// <inheritdoc cref="File.AppendAllLinesAsync(string,IEnumerable{string},CancellationToken)"/>
public abstract Task AppendAllLinesAsync(string path, IEnumerable<string> contents, CancellationToken cancellationToken);
/// <inheritdoc cref="File.AppendAllLinesAsync(string,IEnumerable{string},Encoding,CancellationToken)"/>
public abstract Task AppendAllLinesAsync(string path, IEnumerable<string> contents, Encoding encoding, CancellationToken cancellationToken);
#endif
/// <inheritdoc cref="File.AppendAllText(string,string)"/>
public abstract void AppendAllText(string path, string contents);
/// <inheritdoc cref="File.AppendAllText(string,string,Encoding)"/>
public abstract void AppendAllText(string path, string contents, Encoding encoding);
#if NETCOREAPP2_0
/// <inheritdoc cref="File.AppendAllTextAsync(string,string,CancellationToken)"/>
public abstract Task AppendAllTextAsync(String path, String contents, CancellationToken cancellationToken);
/// <inheritdoc cref="File.AppendAllTextAsync(string,string,Encoding,CancellationToken)"/>
public abstract Task AppendAllTextAsync(String path, String contents, Encoding encoding, CancellationToken cancellationToken);
#endif
/// <inheritdoc cref="File.AppendText"/>
public abstract StreamWriter AppendText(string path);
/// <inheritdoc cref="File.Copy(string,string)"/>
public abstract void Copy(string sourceFileName, string destFileName);
/// <inheritdoc cref="File.Copy(string,string,bool)"/>
public abstract void Copy(string sourceFileName, string destFileName, bool overwrite);
/// <inheritdoc cref="File.Create(string)"/>
public abstract Stream Create(string path);
/// <inheritdoc cref="File.Create(string,int)"/>
public abstract Stream Create(string path, int bufferSize);
/// <inheritdoc cref="File.Create(string,int,FileOptions)"/>
public abstract Stream Create(string path, int bufferSize, FileOptions options);
#if NET40
/// <inheritdoc cref="File.Create(string,int,FileOptions,FileSecurity)"/>
public abstract Stream Create(string path, int bufferSize, FileOptions options, FileSecurity fileSecurity);
#endif
/// <inheritdoc cref="File.CreateText"/>
public abstract StreamWriter CreateText(string path);
#if NET40
/// <inheritdoc cref="File.Decrypt"/>
public abstract void Decrypt(string path);
#endif
/// <inheritdoc cref="File.Delete"/>
public abstract void Delete(string path);
#if NET40
/// <inheritdoc cref="File.Encrypt"/>
public abstract void Encrypt(string path);
#endif
/// <inheritdoc cref="File.Exists"/>
/// <summary>
/// Determines whether the specified file exists.
/// </summary>
/// <param name="path">The file to check.</param>
/// <returns><see langword="true"/> if the caller has the required permissions and path contains the name of an existing file; otherwise, <see langword="false"/>. This method also returns <see langword="false"/> if <paramref name="path"/> is <see langword="null"/>, an invalid path, or a zero-length string. If the caller does not have sufficient permissions to read the specified file, no exception is thrown and the method returns <see langword="false"/> regardless of the existence of <paramref name="path"/>.</returns>
/// <remarks>
/// <para>
/// The Exists method should not be used for path validation, this method merely checks if the file specified in <paramref name="path"/> exists.
/// Passing an invalid path to Exists returns <see langword="false"/>.
/// </para>
/// <para>
/// Be aware that another process can potentially do something with the file in between the time you call the Exists method and perform another operation on the file, such as <see cref="Delete"/>.
/// </para>
/// <para>
/// The <paramref name="path"/> parameter is permitted to specify relative or absolute path information.
/// Relative path information is interpreted as relative to the current working directory.
/// To obtain the current working directory, see <see cref="DirectoryBase.GetCurrentDirectory"/>.
/// </para>
/// <para>
/// If <paramref name="path"/> describes a directory, this method returns <see langword="false"/>. Trailing spaces are removed from the <paramref name="path"/> parameter before determining if the file exists.
/// </para>
/// <para>
/// The Exists method returns <see langword="false"/> if any error occurs while trying to determine if the specified file exists.
/// This can occur in situations that raise exceptions such as passing a file name with invalid characters or too many characters
/// a failing or missing disk, or if the caller does not have permission to read the file.
/// </para>
/// </remarks>
public abstract bool Exists(string path);
/// <inheritdoc cref="File.GetAccessControl(string)"/>
public abstract FileSecurity GetAccessControl(string path);
/// <inheritdoc cref="File.GetAccessControl(string,AccessControlSections)"/>
public abstract FileSecurity GetAccessControl(string path, AccessControlSections includeSections);
/// <inheritdoc cref="File.GetAttributes"/>
/// <summary>
/// Gets the <see cref="FileAttributes"/> of the file on the path.
/// </summary>
/// <param name="path">The path to the file.</param>
/// <returns>The <see cref="FileAttributes"/> of the file on the path.</returns>
/// <exception cref="ArgumentException"><paramref name="path"/> is empty, contains only white spaces, or contains invalid characters.</exception>
/// <exception cref="PathTooLongException">The specified path, file name, or both exceed the system-defined maximum length. For example, on Windows-based platforms, paths must be less than 248 characters, and file names must be less than 260 characters.</exception>
/// <exception cref="NotSupportedException"><paramref name="path"/> is in an invalid format.</exception>
/// <exception cref="FileNotFoundException"><paramref name="path"/> represents a file and is invalid, such as being on an unmapped drive, or the file cannot be found.</exception>
/// <exception cref="DirectoryNotFoundException"><paramref name="path"/> represents a directory and is invalid, such as being on an unmapped drive, or the directory cannot be found.</exception>
/// <exception cref="IOException">This file is being used by another process.</exception>
/// <exception cref="UnauthorizedAccessException">The caller does not have the required permission.</exception>
public abstract FileAttributes GetAttributes(string path);
/// <inheritdoc cref="File.GetCreationTime"/>
/// <summary>
/// Returns the creation date and time of the specified file or directory.
/// </summary>
/// <param name="path">The file or directory for which to obtain creation date and time information. </param>
/// <returns>A <see cref="DateTime"/> structure set to the creation date and time for the specified file or directory. This value is expressed in local time.</returns>
/// <exception cref="UnauthorizedAccessException">The caller does not have the required permission.</exception>
/// <exception cref="ArgumentException"><paramref name="path"/> is empty, contains only white spaces, or contains invalid characters.</exception>
/// <exception cref="ArgumentNullException"><paramref name="path"/> is <see langword="null"/>.</exception>
/// <exception cref="PathTooLongException">The specified path, file name, or both exceed the system-defined maximum length. For example, on Windows-based platforms, paths must be less than 248 characters, and file names must be less than 260 characters.</exception>
/// <exception cref="NotSupportedException"><paramref name="path"/> is in an invalid format.</exception>
/// <remarks>
/// <para>
/// The <paramref name="path"/> parameter is permitted to specify relative or absolute path information. Relative path information is interpreted as relative to the current working directory. To obtain the current working directory, see <see cref="DirectoryBase.GetCurrentDirectory"/>.
/// </para>
/// <para>
/// If the file described in the <paramref name="path"/> parameter does not exist, this method returns 12:00 midnight, January 1, 1601 A.D. (C.E.) Coordinated Universal Time (UTC), adjusted to local time.
/// </para>
/// <para>
/// NTFS-formatted drives may cache file meta-info, such as file creation time, for a short period of time, which is known as "file tunneling." As a result, it may be necessary to explicitly set the creation time of a file if you are overwriting or replacing an existing file.
/// </para>
/// </remarks>
public abstract DateTime GetCreationTime(string path);
/// <inheritdoc cref="File.GetCreationTimeUtc"/>
/// <summary>
/// Returns the creation date and time, in coordinated universal time (UTC), of the specified file or directory.
/// </summary>
/// <param name="path">The file or directory for which to obtain creation date and time information. </param>
/// <returns>A <see cref="DateTime"/> structure set to the creation date and time for the specified file or directory. This value is expressed in UTC time.</returns>
/// <exception cref="UnauthorizedAccessException">The caller does not have the required permission.</exception>
/// <exception cref="ArgumentException"><paramref name="path"/> is empty, contains only white spaces, or contains invalid characters.</exception>
/// <exception cref="ArgumentNullException"><paramref name="path"/> is <see langword="null"/>.</exception>
/// <exception cref="PathTooLongException">The specified path, file name, or both exceed the system-defined maximum length. For example, on Windows-based platforms, paths must be less than 248 characters, and file names must be less than 260 characters.</exception>
/// <exception cref="NotSupportedException"><paramref name="path"/> is in an invalid format.</exception>
/// <remarks>
/// <para>
/// The <paramref name="path"/> parameter is permitted to specify relative or absolute path information. Relative path information is interpreted as relative to the current working directory. To obtain the current working directory, see <see cref="DirectoryBase.GetCurrentDirectory"/>.
/// </para>
/// <para>
/// If the file described in the <paramref name="path"/> parameter does not exist, this method returns 12:00 midnight, January 1, 1601 A.D. (C.E.) Coordinated Universal Time (UTC).
/// </para>
/// <para>
/// NTFS-formatted drives may cache file meta-info, such as file creation time, for a short period of time, which is known as "file tunneling." As a result, it may be necessary to explicitly set the creation time of a file if you are overwriting or replacing an existing file.
/// </para>
/// </remarks>
public abstract DateTime GetCreationTimeUtc(string path);
/// <inheritdoc cref="File.GetLastAccessTime"/>
/// <summary>
/// Returns the date and time the specified file or directory was last accessed.
/// </summary>
/// <param name="path">The file or directory for which to obtain access date and time information. </param>
/// <returns>A <see cref="DateTime"/> structure set to the date and time that the specified file or directory was last accessed. This value is expressed in local time.</returns>
/// <exception cref="UnauthorizedAccessException">The caller does not have the required permission.</exception>
/// <exception cref="ArgumentException"><paramref name="path"/> is empty, contains only white spaces, or contains invalid characters.</exception>
/// <exception cref="ArgumentNullException"><paramref name="path"/> is <see langword="null"/>.</exception>
/// <exception cref="PathTooLongException">The specified path, file name, or both exceed the system-defined maximum length. For example, on Windows-based platforms, paths must be less than 248 characters, and file names must be less than 260 characters.</exception>
/// <exception cref="NotSupportedException"><paramref name="path"/> is in an invalid format.</exception>
/// <remarks>
/// <para>
/// The <paramref name="path"/> parameter is permitted to specify relative or absolute path information. Relative path information is interpreted as relative to the current working directory. To obtain the current working directory, see <see cref="DirectoryBase.GetCurrentDirectory"/>.
/// </para>
/// <para>
/// If the file described in the <paramref name="path"/> parameter does not exist, this method returns 12:00 midnight, January 1, 1601 A.D. (C.E.) Coordinated Universal Time (UTC), adjusted to local time.
/// </para>
/// <para>
/// NTFS-formatted drives may cache file meta-info, such as file creation time, for a short period of time, which is known as "file tunneling." As a result, it may be necessary to explicitly set the creation time of a file if you are overwriting or replacing an existing file.
/// </para>
/// </remarks>
public abstract DateTime GetLastAccessTime(string path);
/// <inheritdoc cref="File.GetLastAccessTimeUtc"/>
/// <summary>
/// Returns the date and time, in coordinated universal time (UTC), that the specified file or directory was last accessed.
/// </summary>
/// <param name="path">The file or directory for which to obtain creation date and time information. </param>
/// <returns>A <see cref="DateTime"/> structure set to the date and time that the specified file or directory was last accessed. This value is expressed in UTC time.</returns>
/// <exception cref="UnauthorizedAccessException">The caller does not have the required permission.</exception>
/// <exception cref="ArgumentException"><paramref name="path"/> is empty, contains only white spaces, or contains invalid characters.</exception>
/// <exception cref="ArgumentNullException"><paramref name="path"/> is <see langword="null"/>.</exception>
/// <exception cref="PathTooLongException">The specified path, file name, or both exceed the system-defined maximum length. For example, on Windows-based platforms, paths must be less than 248 characters, and file names must be less than 260 characters.</exception>
/// <exception cref="NotSupportedException"><paramref name="path"/> is in an invalid format.</exception>
/// <remarks>
/// <para>
/// The <paramref name="path"/> parameter is permitted to specify relative or absolute path information. Relative path information is interpreted as relative to the current working directory. To obtain the current working directory, see <see cref="DirectoryBase.GetCurrentDirectory"/>.
/// </para>
/// <para>
/// If the file described in the <paramref name="path"/> parameter does not exist, this method returns 12:00 midnight, January 1, 1601 A.D. (C.E.) Coordinated Universal Time (UTC).
/// </para>
/// <para>
/// NTFS-formatted drives may cache file meta-info, such as file creation time, for a short period of time, which is known as "file tunneling." As a result, it may be necessary to explicitly set the creation time of a file if you are overwriting or replacing an existing file.
/// </para>
/// </remarks>
public abstract DateTime GetLastAccessTimeUtc(string path);
/// <inheritdoc cref="File.GetLastWriteTime"/>
/// <summary>
/// Returns the date and time the specified file or directory was last written to.
/// </summary>
/// <param name="path">The file or directory for which to obtain creation date and time information. </param>
/// <returns>A <see cref="DateTime"/> structure set to the date and time that the specified file or directory was last written to. This value is expressed in local time.</returns>
/// <exception cref="UnauthorizedAccessException">The caller does not have the required permission.</exception>
/// <exception cref="ArgumentException"><paramref name="path"/> is empty, contains only white spaces, or contains invalid characters.</exception>
/// <exception cref="ArgumentNullException"><paramref name="path"/> is <see langword="null"/>.</exception>
/// <exception cref="PathTooLongException">The specified path, file name, or both exceed the system-defined maximum length. For example, on Windows-based platforms, paths must be less than 248 characters, and file names must be less than 260 characters.</exception>
/// <exception cref="NotSupportedException"><paramref name="path"/> is in an invalid format.</exception>
/// <remarks>
/// <para>
/// If the file described in the path parameter does not exist, this method returns 12:00 midnight, January 1, 1601 A.D. (C.E.) Coordinated Universal Time (UTC), adjusted to local time.
/// </para>
/// <para>
/// The <paramref name="path"/> parameter is permitted to specify relative or absolute path information. Relative path information is interpreted as relative to the current working directory. To obtain the current working directory, see <see cref="DirectoryBase.GetCurrentDirectory"/>.
/// </para>
/// <para>
/// NTFS-formatted drives may cache file meta-info, such as file creation time, for a short period of time, which is known as "file tunneling." As a result, it may be necessary to explicitly set the creation time of a file if you are overwriting or replacing an existing file.
/// </para>
/// </remarks>
public abstract DateTime GetLastWriteTime(string path);
/// <inheritdoc cref="File.GetLastWriteTimeUtc"/>
/// <summary>
/// Returns the date and time, in coordinated universal time (UTC), that the specified file or directory was last written to.
/// </summary>
/// <param name="path">The file or directory for which to obtain creation date and time information. </param>
/// <returns>A <see cref="DateTime"/> structure set to the date and time that the specified file or directory was last written to. This value is expressed in local time.</returns>
/// <exception cref="UnauthorizedAccessException">The caller does not have the required permission.</exception>
/// <exception cref="ArgumentException"><paramref name="path"/> is empty, contains only white spaces, or contains invalid characters.</exception>
/// <exception cref="ArgumentNullException"><paramref name="path"/> is <see langword="null"/>.</exception>
/// <exception cref="PathTooLongException">The specified path, file name, or both exceed the system-defined maximum length. For example, on Windows-based platforms, paths must be less than 248 characters, and file names must be less than 260 characters.</exception>
/// <exception cref="NotSupportedException"><paramref name="path"/> is in an invalid format.</exception>
/// <remarks>
/// <para>
/// If the file described in the path parameter does not exist, this method returns 12:00 midnight, January 1, 1601 A.D. (C.E.) Coordinated Universal Time (UTC).
/// </para>
/// <para>
/// The <paramref name="path"/> parameter is permitted to specify relative or absolute path information. Relative path information is interpreted as relative to the current working directory. To obtain the current working directory, see <see cref="DirectoryBase.GetCurrentDirectory"/>.
/// </para>
/// <para>
/// NTFS-formatted drives may cache file meta-info, such as file creation time, for a short period of time, which is known as "file tunneling." As a result, it may be necessary to explicitly set the creation time of a file if you are overwriting or replacing an existing file.
/// </para>
/// </remarks>
public abstract DateTime GetLastWriteTimeUtc(string path);
/// <inheritdoc cref="File.Move"/>
public abstract void Move(string sourceFileName, string destFileName);
/// <inheritdoc cref="File.Open(string,FileMode)"/>
public abstract Stream Open(string path, FileMode mode);
/// <inheritdoc cref="File.Open(string,FileMode,FileAccess)"/>
public abstract Stream Open(string path, FileMode mode, FileAccess access);
/// <inheritdoc cref="File.Open(string,FileMode,FileAccess,FileShare)"/>
public abstract Stream Open(string path, FileMode mode, FileAccess access, FileShare share);
/// <inheritdoc cref="File.OpenRead"/>
public abstract Stream OpenRead(string path);
/// <inheritdoc cref="File.OpenText"/>
public abstract StreamReader OpenText(string path);
/// <inheritdoc cref="File.OpenWrite"/>
public abstract Stream OpenWrite(string path);
/// <inheritdoc cref="File.ReadAllBytes"/>
public abstract byte[] ReadAllBytes(string path);
#if NETCOREAPP2_0
/// <inheritdoc cref="File.ReadAllBytesAsync"/>
public abstract Task<byte[]> ReadAllBytesAsync(string path, CancellationToken cancellationToken);
#endif
/// <inheritdoc cref="File.ReadAllLines(string)"/>
public abstract string[] ReadAllLines(string path);
/// <inheritdoc cref="File.ReadAllLines(string,Encoding)"/>
public abstract string[] ReadAllLines(string path, Encoding encoding);
#if NETCOREAPP2_0
/// <inheritdoc cref="File.ReadAllLinesAsync(string,CancellationToken)"/>
public abstract Task<string[]> ReadAllLinesAsync(string path, CancellationToken cancellationToken);
/// <inheritdoc cref="File.ReadAllLinesAsync(string,Encoding,CancellationToken)"/>
public abstract Task<string[]> ReadAllLinesAsync(string path, Encoding encoding, CancellationToken cancellationToken);
#endif
/// <inheritdoc cref="File.ReadAllText(string)"/>
public abstract string ReadAllText(string path);
/// <inheritdoc cref="File.ReadAllText(string,Encoding)"/>
public abstract string ReadAllText(string path, Encoding encoding);
#if NETCOREAPP2_0
///<inheritdoc cref="File.ReadAllTextAsync(string,CancellationToken)"/>
public abstract Task<string> ReadAllTextAsync(string path, CancellationToken cancellationToken);
///<inheritdoc cref="File.ReadAllTextAsync(string,Encoding,CancellationToken)"/>
public abstract Task<string> ReadAllTextAsync(string path, Encoding encoding, CancellationToken cancellationToken);
#endif
/// <inheritdoc cref="File.ReadLines(string)"/>
public abstract IEnumerable<string> ReadLines(string path);
/// <inheritdoc cref="File.ReadLines(string,Encoding)"/>
public abstract IEnumerable<string> ReadLines(string path, Encoding encoding);
#if NET40
/// <inheritdoc cref="File.Replace(string,string,string)"/>
public abstract void Replace(string sourceFileName, string destinationFileName, string destinationBackupFileName);
/// <inheritdoc cref="File.Replace(string,string,string,bool)"/>
public abstract void Replace(string sourceFileName, string destinationFileName, string destinationBackupFileName, bool ignoreMetadataErrors);
#endif
/// <inheritdoc cref="File.SetAccessControl(string,FileSecurity)"/>
public abstract void SetAccessControl(string path, FileSecurity fileSecurity);
/// <inheritdoc cref="File.SetAttributes"/>
public abstract void SetAttributes(string path, FileAttributes fileAttributes);
/// <inheritdoc cref="File.SetCreationTime"/>
public abstract void SetCreationTime(string path, DateTime creationTime);
/// <inheritdoc cref="File.SetCreationTimeUtc"/>
public abstract void SetCreationTimeUtc(string path, DateTime creationTimeUtc);
/// <inheritdoc cref="File.SetLastAccessTime"/>
public abstract void SetLastAccessTime(string path, DateTime lastAccessTime);
/// <inheritdoc cref="File.SetLastAccessTimeUtc"/>
public abstract void SetLastAccessTimeUtc(string path, DateTime lastAccessTimeUtc);
/// <inheritdoc cref="File.SetLastWriteTime"/>
public abstract void SetLastWriteTime(string path, DateTime lastWriteTime);
/// <inheritdoc cref="File.SetLastWriteTimeUtc"/>
public abstract void SetLastWriteTimeUtc(string path, DateTime lastWriteTimeUtc);
/// <inheritdoc cref="File.WriteAllBytes"/>
/// <summary>
/// Creates a new file, writes the specified byte array to the file, and then closes the file.
/// If the target file already exists, it is overwritten.
/// </summary>
/// <param name="path">The file to write to.</param>
/// <param name="bytes">The bytes to write to the file. </param>
/// <exception cref="ArgumentException"><paramref name="path"/> is a zero-length string, contains only white space, or contains one or more invalid characters as defined by <see cref="Path.GetInvalidPathChars"/>.</exception>
/// <exception cref="ArgumentNullException"><paramref name="path"/> is <see langword="null"/> or contents is empty.</exception>
/// <exception cref="PathTooLongException">
/// The specified path, file name, or both exceed the system-defined maximum length.
/// For example, on Windows-based platforms, paths must be less than 248 characters, and file names must be less than 260 characters.
/// </exception>
/// <exception cref="DirectoryNotFoundException">The specified path is invalid (for example, it is on an unmapped drive).</exception>
/// <exception cref="IOException">An I/O error occurred while opening the file.</exception>
/// <exception cref="UnauthorizedAccessException">
/// path specified a file that is read-only.
/// -or-
/// This operation is not supported on the current platform.
/// -or-
/// path specified a directory.
/// -or-
/// The caller does not have the required permission.
/// </exception>
/// <exception cref="FileNotFoundException">The file specified in <paramref name="path"/> was not found.</exception>
/// <exception cref="NotSupportedException"><paramref name="path"/> is in an invalid format.</exception>
/// <exception cref="System.Security.SecurityException">The caller does not have the required permission.</exception>
/// <remarks>
/// Given a byte array and a file path, this method opens the specified file, writes the contents of the byte array to the file, and then closes the file.
/// </remarks>
public abstract void WriteAllBytes(string path, byte[] bytes);
/// <inheritdoc cref="File.WriteAllLines(string,IEnumerable{string})"/>
/// <summary>
/// Creates a new file, writes a collection of strings to the file, and then closes the file.
/// </summary>
/// <param name="path">The file to write to.</param>
/// <param name="contents">The lines to write to the file.</param>
/// <exception cref="ArgumentException"><paramref name="path"/> is a zero-length string, contains only white space, or contains one or more invalid characters as defined by <see cref="Path.GetInvalidPathChars"/>.</exception>
/// <exception cref="ArgumentNullException">Either <paramref name="path"/> or <paramref name="contents"/> is <see langword="null"/>.</exception>
/// <exception cref="DirectoryNotFoundException">The specified path is invalid (for example, it is on an unmapped drive).</exception>
/// <exception cref="FileNotFoundException">The file specified in <paramref name="path"/> was not found.</exception>
/// <exception cref="IOException">An I/O error occurred while opening the file.</exception>
/// <exception cref="PathTooLongException">
/// The specified path, file name, or both exceed the system-defined maximum length.
/// For example, on Windows-based platforms, paths must be less than 248 characters, and file names must be less than 260 characters.
/// </exception>
/// <exception cref="NotSupportedException"><paramref name="path"/> is in an invalid format.</exception>
/// <exception cref="System.Security.SecurityException">The caller does not have the required permission.</exception>
/// <exception cref="UnauthorizedAccessException">
/// <paramref name="path"/> specified a file that is read-only.
/// -or-
/// This operation is not supported on the current platform.
/// -or-
/// <paramref name="path"/> specified a directory.
/// -or-
/// The caller does not have the required permission.
/// </exception>
/// <remarks>
/// <para>
/// If the target file already exists, it is overwritten.
/// </para>
/// <para>
/// You can use this method to create the contents for a collection class that takes an <see cref="IEnumerable{T}"/> in its constructor, such as a <see cref="List{T}"/>, <see cref="HashSet{T}"/>, or a <see cref="SortedSet{T}"/> class.
/// </para>
/// </remarks>
#if NETCOREAPP2_0
/// <inheritdoc cref="File.WriteAllBytesAsync"/>
public abstract Task WriteAllBytesAsync(string path, byte[] bytes, CancellationToken cancellationToken);
#endif
public abstract void WriteAllLines(string path, IEnumerable<string> contents);
/// <inheritdoc cref="File.WriteAllLines(string,IEnumerable{string},Encoding)"/>
/// <summary>
/// Creates a new file by using the specified encoding, writes a collection of strings to the file, and then closes the file.
/// </summary>
/// <param name="path">The file to write to.</param>
/// <param name="contents">The lines to write to the file.</param>
/// <param name="encoding">The character encoding to use.</param>
/// <exception cref="ArgumentException"><paramref name="path"/> is a zero-length string, contains only white space, or contains one or more invalid characters as defined by <see cref="Path.GetInvalidPathChars"/>.</exception>
/// <exception cref="ArgumentNullException">Either <paramref name="path"/>, <paramref name="contents"/>, or <paramref name="encoding"/> is <see langword="null"/>.</exception>
/// <exception cref="DirectoryNotFoundException">The specified path is invalid (for example, it is on an unmapped drive).</exception>
/// <exception cref="FileNotFoundException">The file specified in <paramref name="path"/> was not found.</exception>
/// <exception cref="IOException">An I/O error occurred while opening the file.</exception>
/// <exception cref="PathTooLongException">
/// The specified path, file name, or both exceed the system-defined maximum length.
/// For example, on Windows-based platforms, paths must be less than 248 characters, and file names must be less than 260 characters.
/// </exception>
/// <exception cref="NotSupportedException"><paramref name="path"/> is in an invalid format.</exception>
/// <exception cref="System.Security.SecurityException">The caller does not have the required permission.</exception>
/// <exception cref="UnauthorizedAccessException">
/// <paramref name="path"/> specified a file that is read-only.
/// -or-
/// This operation is not supported on the current platform.
/// -or-
/// <paramref name="path"/> specified a directory.
/// -or-
/// The caller does not have the required permission.
/// </exception>
/// <remarks>
/// <para>
/// If the target file already exists, it is overwritten.
/// </para>
/// <para>
/// You can use this method to create a file that contains the following:
/// <list type="bullet">
/// <item>
/// <description>The results of a LINQ to Objects query on the lines of a file, as obtained by using the ReadLines method.</description>
/// </item>
/// <item>
/// <description>The contents of a collection that implements an <see cref="IEnumerable{T}"/> of strings.</description>
/// </item>
/// </list>
/// </para>
/// </remarks>
public abstract void WriteAllLines(string path, IEnumerable<string> contents, Encoding encoding);
/// <inheritdoc cref="File.WriteAllLines(string,string[])"/>
/// <summary>
/// Creates a new file, writes the specified string array to the file by using the specified encoding, and then closes the file.
/// </summary>
/// <param name="path">The file to write to.</param>
/// <param name="contents">The string array to write to the file.</param>
/// <exception cref="ArgumentException"><paramref name="path"/> is a zero-length string, contains only white space, or contains one or more invalid characters as defined by <see cref="Path.GetInvalidPathChars"/>.</exception>
/// <exception cref="ArgumentNullException">Either <paramref name="path"/> or <paramref name="contents"/> is <see langword="null"/>.</exception>
/// <exception cref="PathTooLongException">
/// The specified path, file name, or both exceed the system-defined maximum length.
/// For example, on Windows-based platforms, paths must be less than 248 characters, and file names must be less than 260 characters.
/// </exception>
/// <exception cref="DirectoryNotFoundException">The specified path is invalid (for example, it is on an unmapped drive).</exception>
/// <exception cref="IOException">An I/O error occurred while opening the file.</exception>
/// <exception cref="UnauthorizedAccessException">
/// <paramref name="path"/> specified a file that is read-only.
/// -or-
/// This operation is not supported on the current platform.
/// -or-
/// <paramref name="path"/> specified a directory.
/// -or-
/// The caller does not have the required permission.
/// </exception>
/// <exception cref="FileNotFoundException">The file specified in <paramref name="path"/> was not found.</exception>
/// <exception cref="NotSupportedException"><paramref name="path"/> is in an invalid format.</exception>
/// <exception cref="System.Security.SecurityException">The caller does not have the required permission.</exception>
/// <remarks>
/// <para>
/// If the target file already exists, it is overwritten.
/// </para>
/// <para>
/// The default behavior of the WriteAllLines method is to write out data using UTF-8 encoding without a byte order mark (BOM). If it is necessary to include a UTF-8 identifier, such as a byte order mark, at the beginning of a file, use the <see cref="WriteAllLines(string, string[], Encoding)"/> method overload with <see cref="UTF8Encoding"/> encoding.
/// </para>
/// <para>
/// Given a string array and a file path, this method opens the specified file, writes the string array to the file using the specified encoding,
/// and then closes the file.
/// </para>
/// </remarks>
public abstract void WriteAllLines(string path, string[] contents);
/// <inheritdoc cref="File.WriteAllLines(string,string[],Encoding)"/>
/// <summary>
/// Creates a new file, writes the specified string array to the file by using the specified encoding, and then closes the file.
/// </summary>
/// <param name="path">The file to write to.</param>
/// <param name="contents">The string array to write to the file.</param>
/// <param name="encoding">An <see cref="Encoding"/> object that represents the character encoding applied to the string array.</param>
/// <exception cref="ArgumentException"><paramref name="path"/> is a zero-length string, contains only white space, or contains one or more invalid characters as defined by <see cref="Path.GetInvalidPathChars"/>.</exception>
/// <exception cref="ArgumentNullException">Either <paramref name="path"/> or <paramref name="contents"/> is <see langword="null"/>.</exception>
/// <exception cref="PathTooLongException">
/// The specified path, file name, or both exceed the system-defined maximum length.
/// For example, on Windows-based platforms, paths must be less than 248 characters, and file names must be less than 260 characters.
/// </exception>
/// <exception cref="DirectoryNotFoundException">The specified path is invalid (for example, it is on an unmapped drive).</exception>
/// <exception cref="IOException">An I/O error occurred while opening the file.</exception>
/// <exception cref="UnauthorizedAccessException">
/// <paramref name="path"/> specified a file that is read-only.
/// -or-
/// This operation is not supported on the current platform.
/// -or-
/// <paramref name="path"/> specified a directory.
/// -or-
/// The caller does not have the required permission.
/// </exception>
/// <exception cref="FileNotFoundException">The file specified in <paramref name="path"/> was not found.</exception>
/// <exception cref="NotSupportedException"><paramref name="path"/> is in an invalid format.</exception>
/// <exception cref="System.Security.SecurityException">The caller does not have the required permission.</exception>
/// <remarks>
/// <para>
/// If the target file already exists, it is overwritten.
/// </para>
/// <para>
/// Given a string array and a file path, this method opens the specified file, writes the string array to the file using the specified encoding,
/// and then closes the file.
/// </para>
/// </remarks>
public abstract void WriteAllLines(string path, string[] contents, Encoding encoding);
/// <inheritdoc cref="File.WriteAllText(string,string)"/>
/// <summary>
/// Creates a new file, writes the specified string to the file using the specified encoding, and then closes the file. If the target file already exists, it is overwritten.
/// </summary>
/// <param name="path">The file to write to. </param>
/// <param name="contents">The string to write to the file. </param>
/// <exception cref="ArgumentException"><paramref name="path"/> is a zero-length string, contains only white space, or contains one or more invalid characters as defined by <see cref="Path.GetInvalidPathChars"/>.</exception>
/// <exception cref="ArgumentNullException"><paramref name="path"/> is <see langword="null"/> or contents is empty.</exception>
/// <exception cref="PathTooLongException">
/// The specified path, file name, or both exceed the system-defined maximum length.
/// For example, on Windows-based platforms, paths must be less than 248 characters, and file names must be less than 260 characters.
/// </exception>
/// <exception cref="DirectoryNotFoundException">The specified path is invalid (for example, it is on an unmapped drive).</exception>
/// <exception cref="IOException">An I/O error occurred while opening the file.</exception>
/// <exception cref="UnauthorizedAccessException">
/// path specified a file that is read-only.
/// -or-
/// This operation is not supported on the current platform.
/// -or-
/// path specified a directory.
/// -or-
/// The caller does not have the required permission.
/// </exception>
/// <exception cref="FileNotFoundException">The file specified in <paramref name="path"/> was not found.</exception>
/// <exception cref="NotSupportedException"><paramref name="path"/> is in an invalid format.</exception>
/// <exception cref="System.Security.SecurityException">The caller does not have the required permission.</exception>
/// <remarks>
/// This method uses UTF-8 encoding without a Byte-Order Mark (BOM), so using the <see cref="M:Encoding.GetPreamble"/> method will return an empty byte array.
/// If it is necessary to include a UTF-8 identifier, such as a byte order mark, at the beginning of a file, use the <see cref="WriteAllText(string,string, Encoding)"/> method overload with <see cref="UTF8Encoding"/> encoding.
/// <para>
/// Given a string and a file path, this method opens the specified file, writes the string to the file, and then closes the file.
/// </para>
/// </remarks>
#if NETCOREAPP2_0
/// <inheritdoc cref="File.WriteAllLinesAsync(string,IEnumerable{string},CancellationToken)"/>
public abstract Task WriteAllLinesAsync(string path, IEnumerable<string> contents, CancellationToken cancellationToken);
/// <inheritdoc cref="File.WriteAllLinesAsync(string,IEnumerable{string},Encoding,CancellationToken)"/>
public abstract Task WriteAllLinesAsync(string path, IEnumerable<string> contents, Encoding encoding, CancellationToken cancellationToken);
/// <inheritdoc cref="File.WriteAllLinesAsync(string,string[],CancellationToken)"/>
public abstract Task WriteAllLinesAsync(string path, string[] contents, CancellationToken cancellationToken);
/// <inheritdoc cref="File.WriteAllLinesAsync(string,string[],Encoding,CancellationToken)"/>
public abstract Task WriteAllLinesAsync(string path, string[] contents, Encoding encoding, CancellationToken cancellationToken);
#endif
public abstract void WriteAllText(string path, string contents);
/// <inheritdoc cref="File.WriteAllText(string,string,Encoding)"/>
/// <summary>
/// Creates a new file, writes the specified string to the file using the specified encoding, and then closes the file. If the target file already exists, it is overwritten.
/// </summary>
/// <param name="path">The file to write to. </param>
/// <param name="contents">The string to write to the file. </param>
/// <param name="encoding">The encoding to apply to the string.</param>
/// <exception cref="ArgumentException"><paramref name="path"/> is a zero-length string, contains only white space, or contains one or more invalid characters as defined by <see cref="Path.GetInvalidPathChars"/>.</exception>
/// <exception cref="ArgumentNullException"><paramref name="path"/> is <see langword="null"/> or contents is empty.</exception>
/// <exception cref="PathTooLongException">
/// The specified path, file name, or both exceed the system-defined maximum length.
/// For example, on Windows-based platforms, paths must be less than 248 characters, and file names must be less than 260 characters.
/// </exception>
/// <exception cref="DirectoryNotFoundException">The specified path is invalid (for example, it is on an unmapped drive).</exception>
/// <exception cref="IOException">An I/O error occurred while opening the file.</exception>
/// <exception cref="UnauthorizedAccessException">
/// path specified a file that is read-only.
/// -or-
/// This operation is not supported on the current platform.
/// -or-
/// path specified a directory.
/// -or-
/// The caller does not have the required permission.
/// </exception>
/// <exception cref="FileNotFoundException">The file specified in <paramref name="path"/> was not found.</exception>
/// <exception cref="NotSupportedException"><paramref name="path"/> is in an invalid format.</exception>
/// <exception cref="System.Security.SecurityException">The caller does not have the required permission.</exception>
/// <remarks>
/// Given a string and a file path, this method opens the specified file, writes the string to the file using the specified encoding, and then closes the file.
/// The file handle is guaranteed to be closed by this method, even if exceptions are raised.
/// </remarks>
public abstract void WriteAllText(string path, string contents, Encoding encoding);
#if NETCOREAPP2_0
/// <inheritdoc cref="File.WriteAllTextAsync(string,string,CancellationToken)"/>
public abstract Task WriteAllTextAsync(string path, string contents, CancellationToken cancellationToken);
/// <inheritdoc cref="File.WriteAllTextAsync(string,string,Encoding,CancellationToken)"/>
public abstract Task WriteAllTextAsync(string path, string contents, Encoding encoding, CancellationToken cancellationToken);
#endif
}
}
| 70.059701 | 530 | 0.67925 | [
"MIT"
] | fedoranimus/System.IO.Abstractions | System.IO.Abstractions/FileBase.cs | 46,942 | C# |
using UnityEngine;
namespace SoftBody.Collision
{
/// <summary>
/// Base interface for spheres that handle collision responses.
/// </summary>
public interface ISphereCollisionResponder : ICollisionResponder
{
Vector3 Position { get; }
float Radius { get; }
}
} | 23.230769 | 68 | 0.655629 | [
"MIT"
] | nielsdos/UnityClothSimulation | Assets/Scripts/SoftBody/Collision/ISphereCollisionResponder.cs | 302 | 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 PromosiMVC
{
using System;
using System.Collections.Generic;
public partial class City
{
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")]
public City()
{
this.Company = new HashSet<Company>();
}
public long Id { get; set; }
public string Name { get; set; }
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
public virtual ICollection<Company> Company { get; set; }
}
}
| 36.033333 | 129 | 0.550416 | [
"Apache-2.0"
] | RandomLyrics/aaabbbcdefgh | PromosiMVC/City.cs | 1,081 | C# |
using Jint.DebuggerExample.Commands;
using Jint.DebuggerExample.Debug;
using Jint.DebuggerExample.UI;
using Jint.DebuggerExample.Utilities;
using Jint.Native;
using Jint.Native.Array;
using Jint.Native.Object;
using Jint.Runtime.Debugger;
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading;
namespace Jint.DebuggerExample
{
class Program
{
private static CommandManager commandManager;
private static Debugger debugger;
private static ScriptLoader scriptLoader;
private static Display display;
private static ScriptDisplay scriptDisplay;
private static Prompt prompt;
private static ErrorDisplay errorDisplay;
private static InfoDisplay infoDisplay;
private static HelpDisplay helpDisplay;
private static AreaToggler mainDisplayToggler;
static void Main(string[] args)
{
commandManager = new CommandManager()
.Add(new Command("continue", "c", "Run without stepping", Run))
.Add(new Command("pause", "p", "Pause execution", Pause))
.Add(new Command("kill", "Cancel execution", Stop))
.Add(new Command("step", "s", "Step into", StepInto))
.Add(new Command("next", "n", "Step over", StepOver))
.Add(new Command("up", "Step out", StepOut))
.Add(new Command("break", "bp", "Toggle breakpoint", ToggleBreakPoint))
.Add(new Command("list", "l", "Display source view", ShowSource))
.Add(new Command("help", "h", "Display list of commands", ShowHelp))
.Add(new Command("exit", "x", "Exit the debuger", Exit));
SetupDebugger(args);
SetupUI();
prompt.Command += Prompt_Command;
prompt.Start();
display.Start();
}
private static void SetupUI()
{
display = new Display();
display.Ready += Display_Ready;
// Simple Dispatcher and SynchronizationContext do the same job as in a typical GUI:
// - SynchronizationContext Keeps async code continuations running on the main (UI) thread
// - Dispatcher allows other threads to invoke Actions on the main (UI) thread
SynchronizationContext.SetSynchronizationContext(new ConsoleSynchronizationContext(display));
Dispatcher.Init(display);
mainDisplayToggler = new AreaToggler();
scriptDisplay = new ScriptDisplay(display, debugger, new Bounds(0, 0, Length.Percent(60), -2));
infoDisplay = new InfoDisplay(display, new Bounds(Length.Percent(60), 0, Length.Percent(40), -2));
helpDisplay = new HelpDisplay(display, new Bounds(0, 0, Length.Percent(100), -2));
prompt = new Prompt(display, new Bounds(0, -2, Length.Percent(100), 1));
errorDisplay = new ErrorDisplay(display, new Bounds(0, -1, Length.Percent(100), 1));
mainDisplayToggler
.Add(scriptDisplay)
.Add(helpDisplay);
display.Add(scriptDisplay);
display.Add(helpDisplay);
display.Add(infoDisplay);
display.Add(prompt);
display.Add(errorDisplay);
}
private static void SetupDebugger(string[] paths)
{
debugger = new Debugger();
debugger.Pause += Debugger_Pause;
debugger.Continue += Debugger_Continue;
scriptLoader = new ScriptLoader(debugger);
foreach (var path in paths)
{
scriptLoader.Load(path);
}
}
private static void Display_Ready()
{
debugger.Execute();
}
private static void Debugger_Pause(DebugInformation info)
{
// We're being called from the Jint thread. Execute on UI thread:
Dispatcher.Invoke(() => UpdateDisplay(info));
}
private static void Debugger_Continue()
{
// We're being called from the Jint thread. Execute on UI thread:
Dispatcher.Invoke(() =>
{
scriptDisplay.ExecutingLocation = null;
});
}
private static void UpdateDisplay(DebugInformation info)
{
string source = info.CurrentStatement.Location.Source;
int startLine = info.CurrentStatement.Location.Start.Line;
int endLine = info.CurrentStatement.Location.End.Line;
scriptDisplay.Script = scriptLoader.GetScript(source);
scriptDisplay.ExecutingLocation = info.CurrentStatement.Location;
StringBuilder infoBuilder = new StringBuilder();
infoBuilder.AppendLine(Colorizer.Foreground("Scopes", Colors.Header));
infoBuilder.AppendLine(Colorizer.Foreground("Local", Colors.Header2));
BuildScope(infoBuilder, info.Locals);
infoBuilder.AppendLine(Colorizer.Foreground("Global", Colors.Header2));
BuildScope(infoBuilder, info.Globals);
infoBuilder.AppendLine();
infoBuilder.AppendLine(Colorizer.Foreground("Call stack", Colors.Header));
foreach (var item in info.CallStack)
{
infoBuilder.AppendLine($" {item}");
}
infoDisplay.Content = infoBuilder.ToString();
mainDisplayToggler.Show(scriptDisplay);
}
private static void BuildScope(StringBuilder builder, Dictionary<string, JsValue> scope)
{
foreach (var item in scope)
{
string value = item.Value switch
{
ArrayInstance _ => "[...]",
ObjectInstance _ => "{...}",
_ => item.Value.ToString()
};
builder.AppendLine($" {item.Key} : {value}");
}
}
private static void Prompt_Command(string commandLine)
{
try
{
bool handled = commandManager.Parse(commandLine);
if (!handled)
{
throw new CommandException($"Unknown command '{commandLine}'. Type 'help' for a list of commands.");
}
else
{
errorDisplay.Error = null;
}
}
catch (CommandException ex)
{
errorDisplay.Error = ex.Message;
}
}
private static void Run(string[] arguments)
{
debugger.Run();
}
private static void Pause(string[] arguments)
{
debugger.Stop();
}
private static void Stop(string[] arguments)
{
debugger.Cancel();
}
private static void StepOver(string[] arguments)
{
debugger.StepOver();
}
private static void StepOut(string[] arguments)
{
debugger.StepOut();
}
private static void StepInto(string[] arguments)
{
debugger.StepInto();
}
private static void ToggleBreakPoint(string[] arguments)
{
string scriptId = scriptDisplay.Script.Id;
int line;
switch (arguments.Length)
{
case 1:
line = Int32.Parse(arguments[0]);
break;
case 2:
scriptId = arguments[0];
line = Int32.Parse(arguments[1]);
break;
default:
throw new CommandException("Usage: bp <script id> [line number]");
}
if (debugger.HasBreakPoint(scriptId, line))
{
debugger.RemoveBreakPoint(scriptId, line);
}
else
{
if (!debugger.TryAddBreakPoint(scriptId, line))
{
throw new CommandException($"Failed adding breakpoint at {scriptId} line {line}");
}
}
if (scriptDisplay.Script.Id == scriptId)
{
scriptDisplay.Invalidate();
}
}
private static void ShowSource(string[] arguments)
{
mainDisplayToggler.Show(scriptDisplay);
}
private static void ShowHelp(string[] arguments)
{
var help = Colorizer.Foreground("Debugger commands", Colors.Header) +
Environment.NewLine +
commandManager.BuildHelp();
helpDisplay.Content = help;
mainDisplayToggler.Show(helpDisplay);
}
private static void Exit(string[] arguments)
{
debugger.Cancel();
prompt.Stop();
display.Stop();
}
}
}
| 33.349442 | 120 | 0.549103 | [
"MIT"
] | Jither/Jint.AbandonedDebuggerExample | Jint.DebuggerExample/Program.cs | 8,973 | 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>
//------------------------------------------------------------------------------
using System;
using System.Reflection;
[assembly: System.Reflection.AssemblyCompanyAttribute("dotnetcore")]
[assembly: System.Reflection.AssemblyConfigurationAttribute("Debug")]
[assembly: System.Reflection.AssemblyFileVersionAttribute("1.0.0.0")]
[assembly: System.Reflection.AssemblyInformationalVersionAttribute("1.0.0")]
[assembly: System.Reflection.AssemblyProductAttribute("dotnetcore")]
[assembly: System.Reflection.AssemblyTitleAttribute("dotnetcore")]
[assembly: System.Reflection.AssemblyVersionAttribute("1.0.0.0")]
// Generated by the MSBuild WriteCodeFragment class.
| 40.833333 | 80 | 0.646939 | [
"MIT"
] | harith-a/dotnetcore-vue-starter | dotnetcore/obj/Debug/netcoreapp2.1/dotnetcore.AssemblyInfo.cs | 980 | C# |
// ------------------------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License in the project root for license information.
// ------------------------------------------------------------------------------
// **NOTE** This file was generated by a tool and any changes will be overwritten.
namespace Microsoft.Graph
{
using System;
using System.Collections.Generic;
/// <summary>
/// The interface IGroupMembersCollectionWithReferencesRequestBuilder.
/// </summary>
public partial interface IGroupMembersCollectionWithReferencesRequestBuilder
{
/// <summary>
/// Builds the request.
/// </summary>
/// <returns>The built request.</returns>
IGroupMembersCollectionWithReferencesRequest Request();
/// <summary>
/// Builds the request.
/// </summary>
/// <param name="options">The query and header options for the request.</param>
/// <returns>The built request.</returns>
IGroupMembersCollectionWithReferencesRequest Request(IEnumerable<Option> options);
/// <summary>
/// Gets an <see cref="IDirectoryObjectWithReferenceRequestBuilder"/> for the specified DirectoryObject.
/// </summary>
/// <param name="id">The ID for the DirectoryObject.</param>
/// <returns>The <see cref="IDirectoryObjectWithReferenceRequestBuilder"/>.</returns>
IDirectoryObjectWithReferenceRequestBuilder this[string id] { get; }
/// <summary>
/// Gets an <see cref="IGroupMembersCollectionReferencesRequestBuilder"/> for the references in the collection.
/// </summary>
/// <returns>The <see cref="IGroupMembersCollectionReferencesRequestBuilder"/>.</returns>
IGroupMembersCollectionReferencesRequestBuilder References { get; }
}
}
| 43.311111 | 153 | 0.615187 | [
"MIT"
] | MIchaelMainer/msgraph-sdk-dotnet | src/Microsoft.Graph/Requests/Generated/IGroupMembersCollectionWithReferencesRequestBuilder.cs | 1,949 | C# |
// *** WARNING: this file was generated by the Pulumi Kubernetes codegen tool. ***
// *** Do not edit by hand unless you're certain you know what you are doing! ***
using System.Collections.Immutable;
using System.Threading.Tasks;
using Pulumi.Serialization;
namespace Pulumi.Kubernetes.ApiExtensions.V1
{
/// <summary>
/// CustomResourceDefinitionList is a list of CustomResourceDefinition objects.
/// </summary>
public partial class CustomResourceDefinitionList : Pulumi.CustomResource
{
/// <summary>
/// APIVersion defines the versioned schema of this representation of an object. Servers
/// should convert recognized schemas to the latest internal value, and may reject
/// unrecognized values. More info:
/// https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources
/// </summary>
[Output("apiVersion")]
public Output<string> ApiVersion { get; private set; } = null!;
/// <summary>
/// items list individual CustomResourceDefinition objects
/// </summary>
[Output("items")]
public Output<ImmutableArray<Types.Outputs.ApiExtensions.V1.CustomResourceDefinition>> Items { get; private set; } = null!;
/// <summary>
/// Kind is a string value representing the REST resource this object represents. Servers
/// may infer this from the endpoint the client submits requests to. Cannot be updated. In
/// CamelCase. More info:
/// https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds
/// </summary>
[Output("kind")]
public Output<string> Kind { get; private set; } = null!;
[Output("metadata")]
public Output<Types.Outputs.Meta.V1.ListMeta> Metadata { get; private set; } = null!;
/// <summary>
/// Create a CustomResourceDefinitionList resource with the given unique name, arguments, and options.
/// </summary>
/// <param name="name">The unique name of the resource</param>
/// <param name="args">The arguments used to populate this resource's properties</param>
/// <param name="options">A bag of options that control this resource's behavior</param>
public CustomResourceDefinitionList(string name, Types.Inputs.ApiExtensions.V1.CustomResourceDefinitionListArgs? args = null, CustomResourceOptions? options = null)
: base("kubernetes:apiextensions.k8s.io/v1:CustomResourceDefinitionList", name, SetAPIKindAndVersion(args), MakeResourceOptions(options))
{
}
private static ResourceArgs SetAPIKindAndVersion(Types.Inputs.ApiExtensions.V1.CustomResourceDefinitionListArgs? args)
{
if (args != null) {
args.ApiVersion = "apiextensions.k8s.io/v1";
args.Kind = "CustomResourceDefinitionList";
}
return args ?? ResourceArgs.Empty;
}
private static CustomResourceOptions MakeResourceOptions(CustomResourceOptions? options)
{
var defaultOptions = new CustomResourceOptions
{
Version = Utilities.Version,
};
return CustomResourceOptions.Merge(defaultOptions, options);
}
/// <summary>
/// Get an existing CustomResourceDefinitionList resource's state with the given name and ID.
/// </summary>
/// <param name="name">The unique name of the resulting resource.</param>
/// <param name="id">The unique provider ID of the resource to lookup.</param>
/// <param name="options">A bag of options that control this resource's behavior</param>
public static CustomResourceDefinitionList Get(string name, Input<string> id, CustomResourceOptions? options = null)
{
return new CustomResourceDefinitionList(name, null, CustomResourceOptions.Merge(options, new CustomResourceOptions
{
Id = id,
}));
}
}
}
| 45.865169 | 172 | 0.653356 | [
"Apache-2.0"
] | RichardWLaub/pulumi-kubernetes | sdk/dotnet/ApiExtensions/V1/CustomResourceDefinitionList.cs | 4,082 | C# |
using MediatR;
using Net6WebApiTemplate.Application.Categories.Dto;
using Net6WebApiTemplate.Application.Common.Interfaces;
using Net6WebApiTemplate.Domain.Entities;
namespace Net6WebApiTemplate.Application.Categories.Commands.CreateCategory;
public class CreateCategoryCommandHandler : IRequestHandler<CreateCategoryCommand, CategoryDto>
{
private readonly IMediator _mediator;
private readonly INet6WebApiTemplateDbContext _dbContext;
public CreateCategoryCommandHandler(IMediator mediator, INet6WebApiTemplateDbContext dbContext)
{
_mediator = mediator;
_dbContext = dbContext;
}
public async Task<CategoryDto> Handle(CreateCategoryCommand request, CancellationToken cancellationToken)
{
Category category = new()
{
Description = request.Description,
CategoryName = request.CategoryName
};
_dbContext.Categories.Add(category);
await _dbContext.SaveChangesAsync(cancellationToken);
CategoryDto categoryDto = new()
{
Description = request.Description,
CategoryName = request.CategoryName
};
return categoryDto;
}
}
| 31.342105 | 109 | 0.72712 | [
"MIT"
] | marlonajgayle/Net6WebApiTemplate | src/Content/src/Net6WebApiTemplate.Application/Categories/Commands/CreateCategory/CreateCategoryCommandHandler.cs | 1,193 | C# |
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using osu.Framework.Configuration;
using osu.Game.Rulesets.Objects;
using osu.Game.Rulesets.UI.Scrolling.Algorithms;
namespace osu.Game.Rulesets.UI.Scrolling
{
public interface IScrollingInfo
{
/// <summary>
/// The direction <see cref="HitObject"/>s should scroll in.
/// </summary>
IBindable<ScrollingDirection> Direction { get; }
/// <summary>
///
/// </summary>
IBindable<double> TimeRange { get; }
/// <summary>
/// The algorithm which controls <see cref="HitObject"/> positions and sizes.
/// </summary>
IScrollAlgorithm Algorithm { get; }
}
}
| 29.964286 | 86 | 0.607867 | [
"MIT"
] | Shawdooow/osu-sym | osu.Game/Rulesets/UI/Scrolling/IScrollingInfo.cs | 814 | C# |
using Microsoft.Practices.Unity.Configuration;
using System;
using System.Collections.Generic;
using Unity;
using Unity.Injection;
using Unity.Interception.PolicyInjection;
namespace Microsoft.Practices.Unity.InterceptionExtension.Configuration
{
/// <summary>
/// A shortcut element to enable the policy injection behavior.
/// </summary>
public class PolicyInjectionElement : InjectionMemberElement
{
/// <summary>
/// Each element must have a unique key, which is generated by the subclasses.
/// </summary>
public override string Key
{
get { return "policyInjection"; }
}
/// <summary>
/// Return the set of <see cref="InjectionMember"/>s that are needed
/// to configure the container according to this configuration element.
/// </summary>
/// <param name="container">Container that is being configured.</param>
/// <param name="fromType">Type that is being registered.</param>
/// <param name="toType">Type that <paramref name="fromType"/> is being mapped to.</param>
/// <param name="name">Name this registration is under.</param>
/// <returns>One or more <see cref="InjectionMember"/> objects that should be
/// applied to the container registration.</returns>
public override IEnumerable<InjectionMember> GetInjectionMembers(IUnityContainer container, Type fromType,
Type toType, string name)
{
var behaviorElement = new InterceptionBehaviorElement
{
TypeName = typeof(PolicyInjectionBehavior).AssemblyQualifiedName
};
return behaviorElement.GetInjectionMembers(container, fromType, toType, name);
}
}
}
| 39.866667 | 114 | 0.651059 | [
"Apache-2.0"
] | unitycontainer/interception-configuration | src/PolicyInjectionElement.cs | 1,796 | C# |
using System.IO;
using System.Runtime.Serialization;
using GameEstate.Formats.Red.CR2W.Reflection;
using FastMember;
using static GameEstate.Formats.Red.Records.Enums;
namespace GameEstate.Formats.Red.Types
{
[DataContract(Namespace = "")]
[REDMeta]
public class CMoveSTFaceTargetFacing : IMoveTargetSteeringTask
{
public CMoveSTFaceTargetFacing(CR2WFile cr2w, CVariable parent, string name) : base(cr2w, parent, name){ }
public static new CVariable Create(CR2WFile cr2w, CVariable parent, string name) => new CMoveSTFaceTargetFacing(cr2w, parent, name);
public override void Read(BinaryReader file, uint size) => base.Read(file, size);
public override void Write(BinaryWriter file) => base.Write(file);
}
} | 32.521739 | 135 | 0.755348 | [
"MIT"
] | smorey2/GameEstate | src/GameEstate.Formats.Red/Formats/Red/W3/RTTIConvert/CMoveSTFaceTargetFacing.cs | 748 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Collections;
using System.Reflection;
namespace XUCore.Script
{
/// <summary>
/// Member access expressions for "." property or "." method.
/// </summary>
public class MemberAccessExpression : Expression
{
/// <summary>
/// Initialize
/// </summary>
/// <param name="variableExp">The variable expression to use instead of passing in name of variable.</param>
/// <param name="memberName">Name of member, this could be a property or a method name.</param>
/// <param name="isAssignment">Whether or not this is part of an assigment</param>
public MemberAccessExpression(Expression variableExp, string memberName, bool isAssignment)
{
this.VariableExp = variableExp;
this.MemberName = memberName;
this.IsAssignment = isAssignment;
}
/// <summary>
/// The variable expression representing the list.
/// </summary>
public Expression VariableExp;
/// <summary>
/// The name of the member.
/// </summary>
public string MemberName;
/// <summary>
/// Whether or not this member access is part of an assignment.
/// </summary>
public bool IsAssignment;
/// <summary>
/// Either external function or member name.
/// </summary>
/// <returns></returns>
public override object Evaluate()
{
Type type = null;
string variableName = string.Empty;
// Case 1: "user.create" -> external or internal script.
if (VariableExp is VariableExpression )
{
var exp = VariableExp as VariableExpression;
variableName = exp.Name;
string funcname = variableName + "." + MemberName;
// External function
if(Ctx.ExternalFunctions.Contains(funcname))
return funcname;
// Case "Person.Create" -> static method call on custom object?
if (Ctx.Types.Contains(variableName))
{
type = Ctx.Types.Get(variableName);
return new Tuple<string, string, MethodInfo>(type.Name, MemberName, type.GetMethod(MemberName));
}
}
object obj = VariableExp.Evaluate();
type = obj.GetType();
// Case 2: "user.name" -> property of map/object.
if (obj is LMap)
{
if (IsAssignment)
return new Tuple<LMap, string>((LMap)obj, MemberName);
else
return ((LMap)obj).ExecuteMethod(MemberName, null);
}
// Case 2a: string.Method
if (obj is string)
{
return new Tuple<LString, string, string>(null, obj.ToString(), MemberName);
}
// Case 2b: date.Method
if (obj is DateTime)
{
return new Tuple<LDate, string, object, string>(null, variableName, obj, MemberName);
}
// Case 3: "user.name" -> property on object user.
MemberInfo[] members = type.GetMember(MemberName);
MemberInfo result = null;
if (obj is LArray && (members == null || members.Length == 0))
{
MemberName = LArray.MapMethod(MemberName);
members = type.GetMember(MemberName);
}
result = members[0];
if (result.MemberType == MemberTypes.Property)
{
if (IsAssignment)
return new Tuple<object, string, string, PropertyInfo>(obj, null, MemberName, type.GetProperty(MemberName));
else
return type.GetProperty(MemberName).GetValue(obj, null);
}
// Case 4: "user.create" -> method on object user.
if (result.MemberType == MemberTypes.Method)
{
string name = (VariableExp is VariableExpression)
? ((VariableExpression)VariableExp).Name
: null;
return new Tuple<object, string, string, MethodInfo>(obj, name, MemberName, type.GetMethod(MemberName));
}
return result;
}
}
}
| 35.4375 | 128 | 0.535935 | [
"MIT"
] | xuyiazl/XUCore.NetCore | src/XUCore.Script/Expressions/MemberAccessExpression.cs | 4,538 | C# |
using MediatR;
using R.Systems.Lexica.Core.Common.Models;
namespace R.Systems.Lexica.Core.Sets.Queries.GetSet;
public class GetSetQuery : IRequest<Set>
{
public string SetName { get; set; } = "";
}
public class GetSetQueryHandler : IRequestHandler<GetSetQuery, Set>
{
public GetSetQueryHandler(IGetSetRepository repository)
{
Repository = repository;
}
public IGetSetRepository Repository { get; }
public async Task<Set> Handle(GetSetQuery request, CancellationToken cancellationToken)
{
return await Repository.GetSetAsync(request.SetName);
}
}
| 24.96 | 92 | 0.698718 | [
"MIT"
] | lrydzkowski/R.Systems.Lexica | R.Systems.Lexica.Core/Sets/Queries/GetSet/GetSetQuery.cs | 626 | C# |
using System;
using AoLibs.Navigation.iOS.Navigation.Attributes;
using AoLibs.Navigation.iOS.Navigation.Controllers;
using AoLibs.Sample.Shared;
using AoLibs.Sample.Shared.Models;
using AoLibs.Sample.Shared.NavArgs;
using AoLibs.Sample.Shared.ViewModels;
using AoLibs.Utilities.iOS;
using AoLibs.Utilities.iOS.Extensions;
using GalaSoft.MvvmLight.Helpers;
namespace AoLibs.Sample.iOS.ViewControllers
{
[NavigationPage((int)PageIndex.PageB, NavigationPageAttribute.PageProvider.Cached, StoryboardName = "Main",
ViewControllerIdentifier = "TestPageBViewController")]
public partial class TestPageBViewController : ViewControllerBase<TestViewModelB>
{
public TestPageBViewController (IntPtr handle) : base (handle)
{
}
public override void NavigatedBack()
{
base.NavigatedBack();
}
public override void NavigatedFrom()
{
base.NavigatedFrom();
}
public override void NavigatedTo()
{
ViewModel.NavigatedTo(NavigationArguments as PageBNavArgs);
base.NavigatedTo();
}
public override void InitBindings()
{
Bindings.Add(this.SetBinding(() => ViewModel.Message, () => Label.Text));
GoBackButton.SetOnClickCommand(ViewModel.GoBackCommand);
NavigateMore.SetOnClickCommand(ViewModel.NavigateCCommand);
NavigateCNoBackstack.SetOnClickCommand(ViewModel.NavigateCNoBackCommand);
}
}
} | 32.934783 | 111 | 0.690429 | [
"MIT"
] | Drutol/AoLibs | AoLibs.Sample.iOS/ViewControllers/TestPageBViewController.cs | 1,517 | C# |
using UnityEngine;
using System.Threading;
using System.Collections.Generic;
public class LoadChunks : MonoBehaviour
{
World world;
int deleteTimer = 0;
int chunkGenTimer = 0;
void Start()
{
world = World.instance;
}
// Update is called once per frame
void Update()
{
if (deleteTimer == Config.Env.WaitBetweenDeletes)
{
DeleteChunks();
deleteTimer = 0;
return;
}
else
{
deleteTimer++;
}
if (chunkGenTimer == Config.Env.WaitBetweenChunkGen)
{
FindChunksAndLoad();
chunkGenTimer = 0;
return;
}
else
{
chunkGenTimer++;
}
}
void DeleteChunks()
{
var chunksToDelete = new List<BlockPos>();
foreach (var chunk in world.chunks)
{
Vector3 chunkPos = chunk.Key;
float distance = Vector3.Distance(
new Vector3(chunkPos.x, 0, chunkPos.z),
new Vector3(transform.position.x, 0, transform.position.z));
if (distance > Config.Env.DistanceToDeleteChunks * Config.Env.BlockSize)
chunksToDelete.Add(chunk.Key);
}
foreach (var chunk in chunksToDelete)
world.DestroyChunk(chunk);
}
bool FindChunksAndLoad()
{
//Cycle through the array of positions
for (int i = 0; i < Data.chunkLoadOrder.Length; i++)
{
//Get the position of this gameobject to generate around
BlockPos playerPos = ((BlockPos)transform.position).ContainingChunkCoordinates();
//translate the player position and array position into chunk position
BlockPos newChunkPos = new BlockPos(
Data.chunkLoadOrder[i].x * Config.Env.ChunkSize + playerPos.x,
0,
Data.chunkLoadOrder[i].z * Config.Env.ChunkSize + playerPos.z
);
//Get the chunk in the defined position
Chunk newChunk = world.GetChunk(newChunkPos);
//If the chunk already exists and it's already
//rendered or in queue to be rendered continue
if (newChunk != null && newChunk.GetFlag(Chunk.Flag.loaded))
continue;
LoadChunkColumn(newChunkPos);
return true;
}
return false;
}
public void LoadChunkColumn(BlockPos columnPosition)
{
//First create the chunk game objects in the world class
//The world class wont do any generation when threaded chunk creation is enabled
for (int y = Config.Env.WorldMinY; y <= Config.Env.WorldMaxY; y += Config.Env.ChunkSize)
{
for (int x = columnPosition.x - Config.Env.ChunkSize; x <= columnPosition.x + Config.Env.ChunkSize; x += Config.Env.ChunkSize)
{
for (int z = columnPosition.z - Config.Env.ChunkSize; z <= columnPosition.z + Config.Env.ChunkSize; z += Config.Env.ChunkSize)
{
BlockPos pos = new BlockPos(x, y, z);
Chunk chunk = world.GetChunk(pos);
if (chunk == null)
{
world.CreateChunk(pos);
}
}
}
}
for (int y = Config.Env.WorldMaxY; y >= Config.Env.WorldMinY; y -= Config.Env.ChunkSize)
{
BlockPos pos = new BlockPos(columnPosition.x, y, columnPosition.z);
Chunk chunk = world.GetChunk(pos);
if (chunk != null)
{
chunk.SetFlag(Chunk.Flag.loaded, true);
}
}
//Start the threaded chunk generation
if (Config.Toggle.UseMultiThreading) {
Thread thread = new Thread(() => { LoadChunkColumnInner(columnPosition); } );
thread.Start();
}
else
{
LoadChunkColumnInner(columnPosition);
}
}
void LoadChunkColumnInner(BlockPos columnPosition)
{
Chunk chunk;
// Terrain generation can happen in another thread meaning that we will reach this point before the
//thread completes, we need to wait for all the chunks we depend on to finish generating before we
//can calculate any light spread or render the chunk
if (Config.Toggle.UseMultiThreading)
{
for (int y = Config.Env.WorldMaxY; y >= Config.Env.WorldMinY; y -= Config.Env.ChunkSize)
{
for (int x = -Config.Env.ChunkSize; x <= Config.Env.ChunkSize; x += Config.Env.ChunkSize)
{
for (int z = -Config.Env.ChunkSize; z <= Config.Env.ChunkSize; z += Config.Env.ChunkSize)
{
chunk = world.GetChunk(columnPosition.Add(x, y, z));
while (!chunk.GetFlag(Chunk.Flag.terrainGenerated))
{
Thread.Sleep(0);
}
}
}
}
}
//Render chunk
for (int y = Config.Env.WorldMaxY; y >= Config.Env.WorldMinY; y -= Config.Env.ChunkSize)
{
chunk = world.GetChunk(columnPosition.Add(0, y, 0));
if(Config.Toggle.LightSceneOnStart){
BlockLight.FloodLightChunkColumn(world, chunk);
}
chunk.UpdateChunk();
}
}
}
| 31.577143 | 142 | 0.535469 | [
"Apache-2.0"
] | Hengle/Voxelmetric1 | Assets/Voxelmetric/Code/World/LoadChunks.cs | 5,528 | C# |
using System;
using System.Net.Sockets;
using System.Net.Security;
using System.Security.Authentication;
using System.Security.Cryptography.X509Certificates;
namespace Bytewizer.TinyCLR.Sockets.Channel
{
/// <summary>
/// Represents an authenticated ssl stream builder for server side applications.
/// </summary>
public class SslStreamBuilder
{
private TimeSpan _handshakeTimeout = TimeSpan.FromMilliseconds(10000);
/// <summary>
/// Initializes a new instance of the <see cref="SslStreamBuilder"/> class.
/// </summary>
public SslStreamBuilder(X509Certificate certificate, SslProtocols allowedProtocols)
{
Certificate = certificate ?? throw new ArgumentNullException(nameof(certificate));
Protocols = allowedProtocols;
}
/// <summary>
/// Builds a new <see cref="SslStream"/> from a connected socket.
/// </summary>
/// <param name="socket">The connected socket to create a stream with.</param>
public SslStream Build(Socket socket)
{
SslStream stream;
try
{
stream = new SslStream(socket);
stream.AuthenticateAsServer(Certificate, Protocols);
stream.ReadTimeout = (int)HandshakeTimeout.TotalMilliseconds;
}
catch (InvalidOperationException)
{
throw new InvalidOperationException($"Handshake was not completed within the given interval.");
}
catch (Exception ex)
{
throw new InvalidOperationException($"Failed to authenticate {socket.RemoteEndPoint}.", ex);
}
return stream;
}
/// <summary>
/// Amount of time to wait for the TLS handshake to complete.
/// </summary>
public TimeSpan HandshakeTimeout
{
get => _handshakeTimeout;
set
{
if (value <= TimeSpan.Zero && value <= TimeSpan.FromMilliseconds(int.MaxValue))
{
throw new ArgumentOutOfRangeException(nameof(value));
}
_handshakeTimeout = value;
}
}
/// <summary>
/// The X.509 certificate.
/// </summary>
public X509Certificate Certificate { get; private set; }
/// <summary>
/// Allowed versions of ssl protocols.
/// </summary>
public SslProtocols Protocols { get; private set; }
}
}
| 32.910256 | 110 | 0.577328 | [
"MIT"
] | PervasiveDigital/microserver | src/Bytewizer.TinyCLR.Sockets/Channel/SslStreamBuilder.cs | 2,569 | C# |
/* ------------------------------------------------------------------------- */
//
// Copyright (c) 2010 CubeSoft, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
/* ------------------------------------------------------------------------- */
using NUnit.Framework;
namespace Cube.Pdf.Tests
{
/* --------------------------------------------------------------------- */
///
/// MetadataTest
///
/// <summary>
/// Tests for the Metadata class through various IDocumentReader
/// implementations.
/// </summary>
///
/* --------------------------------------------------------------------- */
[TestFixture]
class PdfVersionTest
{
#region Tests
/* ----------------------------------------------------------------- */
///
/// GetString
///
/// <summary>
/// Executes the test to get string that represents PDF version.
/// </summary>
///
/// <remarks>
/// 既知の PDF バージョンおよびサブセットを列挙します。
/// </remarks>
///
/* ----------------------------------------------------------------- */
[TestCase("", 1, 2, 0, ExpectedResult = "PDF 1.2")]
[TestCase("", 1, 3, 0, ExpectedResult = "PDF 1.3")]
[TestCase("", 1, 4, 0, ExpectedResult = "PDF 1.4")]
[TestCase("", 1, 5, 0, ExpectedResult = "PDF 1.5")]
[TestCase("", 1, 6, 0, ExpectedResult = "PDF 1.6")]
[TestCase("", 1, 7, 0, ExpectedResult = "PDF 1.7")]
[TestCase("", 1, 7, 1, ExpectedResult = "PDF 1.7 ExtensionLevel 1")]
[TestCase("", 1, 7, 3, ExpectedResult = "PDF 1.7 ExtensionLevel 3")]
[TestCase("", 1, 7, 5, ExpectedResult = "PDF 1.7 ExtensionLevel 5")]
[TestCase("", 1, 7, 6, ExpectedResult = "PDF 1.7 ExtensionLevel 6")]
[TestCase("", 1, 7, 8, ExpectedResult = "PDF 1.7 ExtensionLevel 8")]
[TestCase("", 2, 0, 0, ExpectedResult = "PDF 2.0")]
[TestCase("A-1a", 1, 4, 0, ExpectedResult = "PDF/A-1a 1.4")]
[TestCase("A-1b", 1, 4, 0, ExpectedResult = "PDF/A-1b 1.4")]
[TestCase("A-2", 1, 7, 0, ExpectedResult = "PDF/A-2 1.7")]
[TestCase("A-3", 1, 7, 0, ExpectedResult = "PDF/A-3 1.7")]
[TestCase("E-1", 1, 6, 0, ExpectedResult = "PDF/E-1 1.6")]
[TestCase("UA-1", 1, 7, 0, ExpectedResult = "PDF/UA-1 1.7")]
[TestCase("VT-1", 1, 6, 0, ExpectedResult = "PDF/VT-1 1.6")]
[TestCase("VT-2", 1, 6, 0, ExpectedResult = "PDF/VT-2 1.6")]
[TestCase("VT-2s", 1, 6, 0, ExpectedResult = "PDF/VT-2s 1.6")]
[TestCase("X-1a", 1, 3, 0, ExpectedResult = "PDF/X-1a 1.3")]
[TestCase("X-1a", 1, 4, 0, ExpectedResult = "PDF/X-1a 1.4")]
[TestCase("X-3", 1, 3, 0, ExpectedResult = "PDF/X-3 1.3")]
[TestCase("X-3", 1, 4, 0, ExpectedResult = "PDF/X-3 1.4")]
[TestCase("X-4", 1, 6, 0, ExpectedResult = "PDF/X-4 1.6")]
[TestCase("X-4p", 1, 6, 0, ExpectedResult = "PDF/X-4p 1.6")]
[TestCase("X-5", 1, 6, 0, ExpectedResult = "PDF/X-5 1.6")]
public string GetString(string subset, int major, int minor, int extension) =>
new PdfVersion(subset, major, minor, extension).ToString();
/* ----------------------------------------------------------------- */
///
/// GetString_Default
///
/// <summary>
/// Executes the test to get string that represents PDF version.
/// </summary>
///
/* ----------------------------------------------------------------- */
[Test]
public void GetString_Default() =>
Assert.That(new PdfVersion().ToString(), Is.EqualTo("PDF 1.0"));
#endregion
}
}
| 44.309278 | 86 | 0.465333 | [
"Apache-2.0"
] | WPG/Cube.Pdf | Libraries/Tests/Sources/PdfVersionTest.cs | 4,346 | C# |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.