content stringlengths 5 1.04M | avg_line_length float64 1.75 12.9k | max_line_length int64 2 244k | alphanum_fraction float64 0 0.98 | licenses list | repository_name stringlengths 7 92 | path stringlengths 3 249 | size int64 5 1.04M | lang stringclasses 2
values |
|---|---|---|---|---|---|---|---|---|
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace Poseidon.Archives.Utility
{
using Poseidon.Winform.Base;
/// <summary>
/// 多文件上传窗体
/// </summary>
public partial class FrmMultiUpload : BaseSingleForm
{
#region Field
/// <summary>
/// 模块名称
/// </summary>
private string module;
#endregion //Field
#region Constructor
public FrmMultiUpload(string module)
{
this.module = module;
InitializeComponent();
}
#endregion //Constructor
#region Function
protected override void InitForm()
{
this.uploadTool.Init(this.module);
base.InitForm();
}
#endregion //Function
}
}
| 20.586957 | 56 | 0.596621 | [
"MIT"
] | robertzml/Poseidon.Archives | Poseidon.Archives.Utility/Forms/FrmMultiUpload.cs | 971 | C# |
using System;
using Phantasma.RpcClient.DTOs;
using Phantasma.Cryptography;
namespace Phantom.Wallet.Models
{
public class MenuEntry
{
public string Id { get; set; }
public string Icon { get; set; }
public string Caption { get; set; }
public bool Enabled { get; set; }
public int Count { get; set; }
public bool IsSelected { get; set; }
}
public class AccountCache
{
public DateTime LastUpdated;
public Transaction[] Transactions;
public Holding[] Holdings;
public BalanceSheetDto[] Tokens;
}
public struct Holding
{
public string Name;
public string ChainName;
public string Symbol;
public string Chain;
public string Icon;
public decimal Amount;
public decimal Rate;
public decimal Price => (Amount * Rate);
public string AmountFormated => Amount.ToString("#,0.###########");
public string PriceFormated => Price.ToString("#,0");
public string CurrencySymbol;
public string Currency;
}
public struct Transaction
{
public string Type;
public DateTime Date;
public string Hash;
public string Amount;
public string Description;
}
public class Net
{
public string Name { get; set; }
public int Value { get; set; }
public bool IsEnabled { get; set; }
public string Url { get; set; }
}
public struct ErrorContext
{
public string ErrorDescription;
public string ErrorCode;
}
public struct MultisigSettings
{
public int addressCount;
public int signeeCount;
public Address[] addressArray;
}
public struct MultisigTx
{
public MultisigSettings Settings;
public string TxData;
}
public struct SettleTx
{
public string ChainName;
public string ChainAddress;
public string DestinationChainAddress;
}
public struct TransferTx
{
public bool IsFungible;
public string AddressTo;
public string FromChain;
public string ToChain;
public string FinalChain;
public string Symbol;
public string AmountOrId;
}
public struct ErrorRes
{
public string error;
}
}
| 23.524752 | 75 | 0.599747 | [
"MIT"
] | saleem9245/PhantomWallet | PhantomWallet/Models/Structs.cs | 2,378 | C# |
namespace Matrix.AppSample.SeedWork
{
public interface IDomainService<T> { }
}
| 16.8 | 42 | 0.738095 | [
"MIT"
] | eximiaco/app-sample | src/Matrix.AppSample/SeedWork/IDomainService.cs | 86 | C# |
using System;
using System.Linq;
using Demo.LearnByDoing.Core;
using Xunit;
using Xunit.Abstractions;
namespace Demo.LearnByDoing.Tests.CodeWars.Kyu7
{
public class SumOfAllTheMultiplesOf3Or5Test : BaseTest
{
public SumOfAllTheMultiplesOf3Or5Test(ITestOutputHelper output) : base(output)
{
}
[Fact]
public void MyTest()
{
Assert.Equal(8, Program.findSum(5));
Assert.Equal(33, Program.findSum(10));
}
}
public static class Program
{
public static int findSum(int n)
{
Func<int, int> isMultiplesOf3Or5 = x => (x % 3 == 0 || x % 5 == 0) ? x : 0;
return Enumerable.Range(1, n).Sum(isMultiplesOf3Or5);
}
}
}
| 20.15625 | 80 | 0.694574 | [
"MIT"
] | dance2die/Demo.LearnByDoing | Demo.LearnByDoing.Tests/CodeWars/Kyu7/SumOfAllTheMultiplesOf3Or5Test.cs | 647 | C# |
//
using System;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Identity;
using Microsoft.EntityFrameworkCore;
using NSG.NetIncident4.Core.Domain.Entities;
using NSG.NetIncident4.Core.Domain.Entities.Authentication;
using NSG.NetIncident4.Core.Migrations;
//
namespace NSG.Integration.Helpers
{
public class DatabaseSeeder
{
//
private readonly ApplicationDbContext _context;
private readonly UserManager<ApplicationUser> _userManager;
private readonly RoleManager<ApplicationRole> _roleManager;
//
public DatabaseSeeder(ApplicationDbContext context,
UserManager<ApplicationUser> userManager,
RoleManager<ApplicationRole> roleManager)
{
_context = context;
_userManager = userManager;
_roleManager = roleManager;
}
//
public async Task<bool> Seed()
{
//
Console.WriteLine("Entering Seed ...");
//
await SeedData.Initialize(_context, _roleManager, true);
await SeedData.SeedEmailTemplate(_context, true);
//
var users = await _context.Users.ToListAsync(); // needs Microsoft.EntityFrameworkCore;
Console.WriteLine("User count: " + users.Count.ToString());
Console.WriteLine("NoteType count: " + (await _context.NoteTypes.CountAsync()).ToString());
Console.WriteLine("Server count: " + (await _context.Servers.CountAsync()).ToString());
if (users.Count == 0)
{
await Seed_Users();
}
var _incidents = await _context.Incidents.ToListAsync();
Console.WriteLine("Incident count: " + _incidents.Count.ToString());
if (_incidents.Count == 0)
{
// serverId, incidentNoteId (for ping)
await Seed_Incidents(1, 1);
}
//
return true;
}
//
public async Task Seed_Users()
{
//
if (_userManager.Users.Count() == 0)
{
try
{
ApplicationUser _user1 =
new ApplicationUser { Email = NSG_Helpers.User_Email, UserName = NSG_Helpers.User_Name, PasswordHash = "AQAAAAEAACcQAAAAEB4oAR8WhJGi5QVXpuONJ4z69YqF/69GlCz4TtjbQVLA4ef69x0iDq5GLTzvqM2vwQ==", SecurityStamp = "VFV7PXFFMU4VZF57I3T7A6TXVF4VAY2M", ConcurrencyStamp = "24240e95-400c-434e-b498-16542c90de13", CompanyId = 1, FirstName = "Phillip", LastName = "Huhn", FullName = "Phillip Huhn", UserNicName = NSG_Helpers.User_Name, EmailConfirmed = true };
ApplicationUser _user2 =
new ApplicationUser { Email = NSG_Helpers.User_Email2, UserName = NSG_Helpers.User_Name2, PasswordHash = "AQAAAAEAACcQAAAAEGG4L+8q4FXRLAhrLWuALpnyStwzaYOaVA6LjBUrHHqs3AreDKMm9DnRa3B4PM1DYg==", SecurityStamp = "LTCQ4W2NCVQRESG6ZWMC7IBMWDZNICK7", ConcurrencyStamp = "2dab2144-81e5-4b76-a09c-c3b6c37f0f3b", CompanyId = 1, FirstName = "Author", LastName = "Huhn", FullName = "Author Huhn", UserNicName = "Art" };
// Add all the predefined profiles using the predefined password
Console.WriteLine($"User1: {NSG_Helpers.User_Name}, User2: {NSG_Helpers.User_Name2}");
IdentityResult _identityResults1 = await _userManager.CreateAsync(_user1, NSG_Helpers.Password);
if (_identityResults1.Succeeded)
{
await _userManager.AddToRolesAsync(_user1, new string[]{ "Admin" } );
_context.UserServers.Add(new ApplicationUserServer() { Id = _user1.Id, ServerId = 1 });
_context.SaveChanges();
}
IdentityResult _identityResults2 = await _userManager.CreateAsync(_user2, NSG_Helpers.Password2);
if (_identityResults2.Succeeded)
{
await _userManager.AddToRolesAsync(_user2, new string[] { "User" });
_context.UserServers.Add(new ApplicationUserServer() { Id = _user2.Id, ServerId = 1 });
_context.SaveChanges();
}
foreach( ApplicationUser _usr in _context.Users )
{
Console.WriteLine($"User: {_usr.UserName}, Email: {_usr.Email}, Name: {_usr.FullName}");
}
}
catch (Exception _ex)
{
foreach (ApplicationUser _u in _context.Users)
{
Console.WriteLine(_u.Id + " " + _u.UserName);
}
Console.WriteLine(_ex.Message);
Console.WriteLine(_ex.ToString());
throw new Exception($"Seed_Users: {_ex.Message}", _ex);
}
}
//
}
//
private async Task Seed_Incidents(int serverId, int pingNoteId)
{
//
try
{
/*
** Add incident, incident note and many-to-many linkage.
*/
Incident _inc = new Incident() { ServerId = serverId, IPAddress = "94.41.53.106", NIC_Id = "ripe.net",
NetworkName = "UBN Network", AbuseEmailAddress = "abuse@AbuseEmailAddress.com",
ISPTicketNumber = "", Mailed = false, Closed = false, Special = false, Notes = "", CreatedDate = DateTime.Now };
_context.Incidents.Add(_inc);
IncidentNote _incNote = new IncidentNote()
{
NoteTypeId = pingNoteId,
Note = "Pinging 94.41.53.106 with 32 bytes of data:",
CreatedDate = DateTime.Now
};
_context.IncidentNotes.Add(_incNote);
await _context.SaveChangesAsync(CancellationToken.None);
//
_context.IncidentIncidentNotes.Add(new IncidentIncidentNote() {
IncidentId = _inc.IncidentId, IncidentNoteId = _incNote.IncidentNoteId });
/*
** NetworkLog
*/
DateTime _dt = DateTime.Now.AddDays(-1);
int _incTypeSql = 3;
_context.NetworkLogs.AddRange(
new NetworkLog() { ServerId = serverId, IncidentId = _inc.IncidentId, IPAddress = "94.41.53.106", NetworkLogDate = _dt.AddMilliseconds(15), Log = "Fake log 1, Fake log 1, Fake log 1", IncidentTypeId = _incTypeSql },
new NetworkLog() { ServerId = serverId, IncidentId = _inc.IncidentId, IPAddress = "94.41.53.106", NetworkLogDate = _dt.AddMilliseconds(15), Log = "Fake log 1, Fake log 1, Fake log 1", IncidentTypeId = _incTypeSql },
new NetworkLog() { ServerId = serverId, IncidentId = null, IPAddress = "104.42.229.49", NetworkLogDate = _dt.AddMinutes(4), Log = "Fake log 2, Fake log 2, Fake log 2", IncidentTypeId = _incTypeSql },
new NetworkLog() { ServerId = serverId, IncidentId = null, IPAddress = "104.42.229.49", NetworkLogDate = _dt.AddMinutes(5), Log = "Fake log 3, Fake log 3, Fake log 3", IncidentTypeId = _incTypeSql },
new NetworkLog() { ServerId = serverId, IncidentId = null, IPAddress = "54.183.209.144", NetworkLogDate = _dt.AddMinutes(10), Log = "Fake log 4, Fake log 4, Fake log 4", IncidentTypeId = _incTypeSql }
);
//
await _context.SaveChangesAsync(CancellationToken.None);
//
}
catch (Exception _ex)
{
Console.WriteLine(_ex.Message);
Console.WriteLine(_ex.ToString());
throw new Exception( $"Seed_Incidents: {_ex.Message}", _ex );
}
//
}
}
}
| 52.986842 | 471 | 0.565557 | [
"Apache-2.0"
] | PHuhn/Net.Incident4 | NSG.NetIncident4.Core_Tests/Helpers/NSG.DatabaseSeeder.cs | 8,056 | C# |
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using ClearHl7.Extensions;
using ClearHl7.Helpers;
using ClearHl7.Serialization;
using ClearHl7.V231.Types;
namespace ClearHl7.V231.Segments
{
/// <summary>
/// HL7 Version 2 Segment PID - Patient Identification.
/// </summary>
public class PidSegment : ISegment
{
/// <inheritdoc/>
public string Id { get; } = "PID";
/// <inheritdoc/>
public int Ordinal { get; set; }
/// <summary>
/// PID.1 - Set ID - PID.
/// </summary>
public uint? SetIdPid { get; set; }
/// <summary>
/// PID.2 - Patient ID.
/// </summary>
public ExtendedCompositeIdWithCheckDigit PatientId { get; set; }
/// <summary>
/// PID.3 - Patient Identifier List.
/// </summary>
public IEnumerable<ExtendedCompositeIdWithCheckDigit> PatientIdentifierList { get; set; }
/// <summary>
/// PID.4 - Alternate Patient ID - PID.
/// </summary>
public IEnumerable<ExtendedCompositeIdWithCheckDigit> AlternatePatientIdPid { get; set; }
/// <summary>
/// PID.5 - Patient Name.
/// </summary>
public IEnumerable<ExtendedPersonName> PatientName { get; set; }
/// <summary>
/// PID.6 - Mother's Maiden Name.
/// </summary>
public IEnumerable<ExtendedPersonName> MothersMaidenName { get; set; }
/// <summary>
/// PID.7 - Date/Time of Birth.
/// </summary>
public DateTime? DateTimeOfBirth { get; set; }
/// <summary>
/// PID.8 - Administrative Sex.
/// <para>Suggested: 0001 Administrative Sex -> ClearHl7.Codes.V231.CodeAdministrativeSex</para>
/// </summary>
public string AdministrativeSex { get; set; }
/// <summary>
/// PID.9 - Patient Alias.
/// </summary>
public IEnumerable<ExtendedPersonName> PatientAlias { get; set; }
/// <summary>
/// PID.10 - Race.
/// <para>Suggested: 0005 Race -> ClearHl7.Codes.V231.CodeRace</para>
/// </summary>
public IEnumerable<CodedElement> Race { get; set; }
/// <summary>
/// PID.11 - Patient Address.
/// </summary>
public IEnumerable<ExtendedAddress> PatientAddress { get; set; }
/// <summary>
/// PID.12 - County Code.
/// <para>Suggested: 0289 County/Parish</para>
/// </summary>
public string CountyCode { get; set; }
/// <summary>
/// PID.13 - Phone Number - Home.
/// </summary>
public IEnumerable<ExtendedTelecommunicationNumber> PhoneNumberHome { get; set; }
/// <summary>
/// PID.14 - Phone Number - Business.
/// </summary>
public IEnumerable<ExtendedTelecommunicationNumber> PhoneNumberBusiness { get; set; }
/// <summary>
/// PID.15 - Primary Language.
/// <para>Suggested: 0296 Primary Language</para>
/// </summary>
public CodedElement PrimaryLanguage { get; set; }
/// <summary>
/// PID.16 - Marital Status.
/// <para>Suggested: 0002 Marital Status -> ClearHl7.Codes.V231.CodeMaritalStatus</para>
/// </summary>
public CodedElement MaritalStatus { get; set; }
/// <summary>
/// PID.17 - Religion.
/// <para>Suggested: 0006 Religion -> ClearHl7.Codes.V231.CodeReligion</para>
/// </summary>
public CodedElement Religion { get; set; }
/// <summary>
/// PID.18 - Patient Account Number.
/// </summary>
public ExtendedCompositeIdWithCheckDigit PatientAccountNumber { get; set; }
/// <summary>
/// PID.19 - SSN Number - Patient.
/// </summary>
public string SsnNumberPatient { get; set; }
/// <summary>
/// PID.20 - Driver's License Number - Patient.
/// </summary>
public DriversLicenseNumber DriversLicenseNumberPatient { get; set; }
/// <summary>
/// PID.21 - Mother's Identifier.
/// </summary>
public IEnumerable<ExtendedCompositeIdWithCheckDigit> MothersIdentifier { get; set; }
/// <summary>
/// PID.22 - Ethnic Group.
/// <para>Suggested: 0189 Ethnic Group</para>
/// </summary>
public IEnumerable<CodedElement> EthnicGroup { get; set; }
/// <summary>
/// PID.23 - Birth Place.
/// </summary>
public string BirthPlace { get; set; }
/// <summary>
/// PID.24 - Multiple Birth Indicator.
/// <para>Suggested: 0136 Yes/No Indicator -> ClearHl7.Codes.V231.CodeYesNoIndicator</para>
/// </summary>
public string MultipleBirthIndicator { get; set; }
/// <summary>
/// PID.25 - Birth Order.
/// </summary>
public decimal? BirthOrder { get; set; }
/// <summary>
/// PID.26 - Citizenship.
/// <para>Suggested: 0171 Citizenship</para>
/// </summary>
public IEnumerable<CodedElement> Citizenship { get; set; }
/// <summary>
/// PID.27 - Veterans Military Status.
/// <para>Suggested: 0172 Veterans Military Status</para>
/// </summary>
public CodedElement VeteransMilitaryStatus { get; set; }
/// <summary>
/// PID.28 - Nationality.
/// <para>Suggested: 0212 Nationality</para>
/// </summary>
public CodedElement Nationality { get; set; }
/// <summary>
/// PID.29 - Patient Death Date and Time.
/// </summary>
public DateTime? PatientDeathDateAndTime { get; set; }
/// <summary>
/// PID.30 - Patient Death Indicator.
/// <para>Suggested: 0136 Yes/No Indicator -> ClearHl7.Codes.V231.CodeYesNoIndicator</para>
/// </summary>
public string PatientDeathIndicator { get; set; }
/// <inheritdoc/>
public void FromDelimitedString(string delimitedString)
{
FromDelimitedString(delimitedString, null);
}
/// <inheritdoc/>
public void FromDelimitedString(string delimitedString, Separators separators)
{
Separators seps = separators ?? new Separators().UsingConfigurationValues();
string[] segments = delimitedString == null
? Array.Empty<string>()
: delimitedString.Split(seps.FieldSeparator, StringSplitOptions.None);
if (segments.Length > 0)
{
if (string.Compare(Id, segments[0], true, CultureInfo.CurrentCulture) != 0)
{
throw new ArgumentException($"{ nameof(delimitedString) } does not begin with the proper segment Id: '{ Id }{ seps.FieldSeparator }'.", nameof(delimitedString));
}
}
SetIdPid = segments.Length > 1 && segments[1].Length > 0 ? segments[1].ToNullableUInt() : null;
PatientId = segments.Length > 2 && segments[2].Length > 0 ? TypeSerializer.Deserialize<ExtendedCompositeIdWithCheckDigit>(segments[2], false, seps) : null;
PatientIdentifierList = segments.Length > 3 && segments[3].Length > 0 ? segments[3].Split(seps.FieldRepeatSeparator, StringSplitOptions.None).Select(x => TypeSerializer.Deserialize<ExtendedCompositeIdWithCheckDigit>(x, false, seps)) : null;
AlternatePatientIdPid = segments.Length > 4 && segments[4].Length > 0 ? segments[4].Split(seps.FieldRepeatSeparator, StringSplitOptions.None).Select(x => TypeSerializer.Deserialize<ExtendedCompositeIdWithCheckDigit>(x, false, seps)) : null;
PatientName = segments.Length > 5 && segments[5].Length > 0 ? segments[5].Split(seps.FieldRepeatSeparator, StringSplitOptions.None).Select(x => TypeSerializer.Deserialize<ExtendedPersonName>(x, false, seps)) : null;
MothersMaidenName = segments.Length > 6 && segments[6].Length > 0 ? segments[6].Split(seps.FieldRepeatSeparator, StringSplitOptions.None).Select(x => TypeSerializer.Deserialize<ExtendedPersonName>(x, false, seps)) : null;
DateTimeOfBirth = segments.Length > 7 && segments[7].Length > 0 ? segments[7].ToNullableDateTime() : null;
AdministrativeSex = segments.Length > 8 && segments[8].Length > 0 ? segments[8] : null;
PatientAlias = segments.Length > 9 && segments[9].Length > 0 ? segments[9].Split(seps.FieldRepeatSeparator, StringSplitOptions.None).Select(x => TypeSerializer.Deserialize<ExtendedPersonName>(x, false, seps)) : null;
Race = segments.Length > 10 && segments[10].Length > 0 ? segments[10].Split(seps.FieldRepeatSeparator, StringSplitOptions.None).Select(x => TypeSerializer.Deserialize<CodedElement>(x, false, seps)) : null;
PatientAddress = segments.Length > 11 && segments[11].Length > 0 ? segments[11].Split(seps.FieldRepeatSeparator, StringSplitOptions.None).Select(x => TypeSerializer.Deserialize<ExtendedAddress>(x, false, seps)) : null;
CountyCode = segments.Length > 12 && segments[12].Length > 0 ? segments[12] : null;
PhoneNumberHome = segments.Length > 13 && segments[13].Length > 0 ? segments[13].Split(seps.FieldRepeatSeparator, StringSplitOptions.None).Select(x => TypeSerializer.Deserialize<ExtendedTelecommunicationNumber>(x, false, seps)) : null;
PhoneNumberBusiness = segments.Length > 14 && segments[14].Length > 0 ? segments[14].Split(seps.FieldRepeatSeparator, StringSplitOptions.None).Select(x => TypeSerializer.Deserialize<ExtendedTelecommunicationNumber>(x, false, seps)) : null;
PrimaryLanguage = segments.Length > 15 && segments[15].Length > 0 ? TypeSerializer.Deserialize<CodedElement>(segments[15], false, seps) : null;
MaritalStatus = segments.Length > 16 && segments[16].Length > 0 ? TypeSerializer.Deserialize<CodedElement>(segments[16], false, seps) : null;
Religion = segments.Length > 17 && segments[17].Length > 0 ? TypeSerializer.Deserialize<CodedElement>(segments[17], false, seps) : null;
PatientAccountNumber = segments.Length > 18 && segments[18].Length > 0 ? TypeSerializer.Deserialize<ExtendedCompositeIdWithCheckDigit>(segments[18], false, seps) : null;
SsnNumberPatient = segments.Length > 19 && segments[19].Length > 0 ? segments[19] : null;
DriversLicenseNumberPatient = segments.Length > 20 && segments[20].Length > 0 ? TypeSerializer.Deserialize<DriversLicenseNumber>(segments[20], false, seps) : null;
MothersIdentifier = segments.Length > 21 && segments[21].Length > 0 ? segments[21].Split(seps.FieldRepeatSeparator, StringSplitOptions.None).Select(x => TypeSerializer.Deserialize<ExtendedCompositeIdWithCheckDigit>(x, false, seps)) : null;
EthnicGroup = segments.Length > 22 && segments[22].Length > 0 ? segments[22].Split(seps.FieldRepeatSeparator, StringSplitOptions.None).Select(x => TypeSerializer.Deserialize<CodedElement>(x, false, seps)) : null;
BirthPlace = segments.Length > 23 && segments[23].Length > 0 ? segments[23] : null;
MultipleBirthIndicator = segments.Length > 24 && segments[24].Length > 0 ? segments[24] : null;
BirthOrder = segments.Length > 25 && segments[25].Length > 0 ? segments[25].ToNullableDecimal() : null;
Citizenship = segments.Length > 26 && segments[26].Length > 0 ? segments[26].Split(seps.FieldRepeatSeparator, StringSplitOptions.None).Select(x => TypeSerializer.Deserialize<CodedElement>(x, false, seps)) : null;
VeteransMilitaryStatus = segments.Length > 27 && segments[27].Length > 0 ? TypeSerializer.Deserialize<CodedElement>(segments[27], false, seps) : null;
Nationality = segments.Length > 28 && segments[28].Length > 0 ? TypeSerializer.Deserialize<CodedElement>(segments[28], false, seps) : null;
PatientDeathDateAndTime = segments.Length > 29 && segments[29].Length > 0 ? segments[29].ToNullableDateTime() : null;
PatientDeathIndicator = segments.Length > 30 && segments[30].Length > 0 ? segments[30] : null;
}
/// <inheritdoc/>
public string ToDelimitedString()
{
CultureInfo culture = CultureInfo.CurrentCulture;
return string.Format(
culture,
StringHelper.StringFormatSequence(0, 31, Configuration.FieldSeparator),
Id,
SetIdPid.HasValue ? SetIdPid.Value.ToString(culture) : null,
PatientId?.ToDelimitedString(),
PatientIdentifierList != null ? string.Join(Configuration.FieldRepeatSeparator, PatientIdentifierList.Select(x => x.ToDelimitedString())) : null,
AlternatePatientIdPid != null ? string.Join(Configuration.FieldRepeatSeparator, AlternatePatientIdPid.Select(x => x.ToDelimitedString())) : null,
PatientName != null ? string.Join(Configuration.FieldRepeatSeparator, PatientName.Select(x => x.ToDelimitedString())) : null,
MothersMaidenName != null ? string.Join(Configuration.FieldRepeatSeparator, MothersMaidenName.Select(x => x.ToDelimitedString())) : null,
DateTimeOfBirth.HasValue ? DateTimeOfBirth.Value.ToString(Consts.DateTimeFormatPrecisionSecond, culture) : null,
AdministrativeSex,
PatientAlias != null ? string.Join(Configuration.FieldRepeatSeparator, PatientAlias.Select(x => x.ToDelimitedString())) : null,
Race != null ? string.Join(Configuration.FieldRepeatSeparator, Race.Select(x => x.ToDelimitedString())) : null,
PatientAddress != null ? string.Join(Configuration.FieldRepeatSeparator, PatientAddress.Select(x => x.ToDelimitedString())) : null,
CountyCode,
PhoneNumberHome != null ? string.Join(Configuration.FieldRepeatSeparator, PhoneNumberHome.Select(x => x.ToDelimitedString())) : null,
PhoneNumberBusiness != null ? string.Join(Configuration.FieldRepeatSeparator, PhoneNumberBusiness.Select(x => x.ToDelimitedString())) : null,
PrimaryLanguage?.ToDelimitedString(),
MaritalStatus?.ToDelimitedString(),
Religion?.ToDelimitedString(),
PatientAccountNumber?.ToDelimitedString(),
SsnNumberPatient,
DriversLicenseNumberPatient?.ToDelimitedString(),
MothersIdentifier != null ? string.Join(Configuration.FieldRepeatSeparator, MothersIdentifier.Select(x => x.ToDelimitedString())) : null,
EthnicGroup != null ? string.Join(Configuration.FieldRepeatSeparator, EthnicGroup.Select(x => x.ToDelimitedString())) : null,
BirthPlace,
MultipleBirthIndicator,
BirthOrder.HasValue ? BirthOrder.Value.ToString(Consts.NumericFormat, culture) : null,
Citizenship != null ? string.Join(Configuration.FieldRepeatSeparator, Citizenship.Select(x => x.ToDelimitedString())) : null,
VeteransMilitaryStatus?.ToDelimitedString(),
Nationality?.ToDelimitedString(),
PatientDeathDateAndTime.HasValue ? PatientDeathDateAndTime.Value.ToString(Consts.DateTimeFormatPrecisionSecond, culture) : null,
PatientDeathIndicator
).TrimEnd(Configuration.FieldSeparator.ToCharArray());
}
}
}
| 56.843972 | 252 | 0.610605 | [
"MIT"
] | kamlesh-microsoft/clear-hl7-net | src/ClearHl7/V231/Segments/PidSegment.cs | 16,032 | C# |
// *** WARNING: this file was generated by the Pulumi Terraform Bridge (tfgen) Tool. ***
// *** Do not edit by hand unless you're certain you know what you are doing! ***
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Threading.Tasks;
using Pulumi.Serialization;
namespace Pulumi.Datadog.Inputs
{
public sealed class DashboardWidgetDistributionDefinitionRequestLogQueryArgs : Pulumi.ResourceArgs
{
[Input("computeQuery")]
public Input<Inputs.DashboardWidgetDistributionDefinitionRequestLogQueryComputeQueryArgs>? ComputeQuery { get; set; }
[Input("groupBies")]
private InputList<Inputs.DashboardWidgetDistributionDefinitionRequestLogQueryGroupByArgs>? _groupBies;
public InputList<Inputs.DashboardWidgetDistributionDefinitionRequestLogQueryGroupByArgs> GroupBies
{
get => _groupBies ?? (_groupBies = new InputList<Inputs.DashboardWidgetDistributionDefinitionRequestLogQueryGroupByArgs>());
set => _groupBies = value;
}
[Input("index", required: true)]
public Input<string> Index { get; set; } = null!;
[Input("multiComputes")]
private InputList<Inputs.DashboardWidgetDistributionDefinitionRequestLogQueryMultiComputeArgs>? _multiComputes;
public InputList<Inputs.DashboardWidgetDistributionDefinitionRequestLogQueryMultiComputeArgs> MultiComputes
{
get => _multiComputes ?? (_multiComputes = new InputList<Inputs.DashboardWidgetDistributionDefinitionRequestLogQueryMultiComputeArgs>());
set => _multiComputes = value;
}
[Input("searchQuery")]
public Input<string>? SearchQuery { get; set; }
public DashboardWidgetDistributionDefinitionRequestLogQueryArgs()
{
}
}
}
| 40.777778 | 149 | 0.724251 | [
"ECL-2.0",
"Apache-2.0"
] | pulumi/pulumi-datadog | sdk/dotnet/Inputs/DashboardWidgetDistributionDefinitionRequestLogQueryArgs.cs | 1,835 | C# |
/**
* Copyright 2013 Canada Health Infoway, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* Author: $LastChangedBy: gng $
* Last modified: $LastChangedDate: 2015-11-19 18:20:12 -0500 (Fri, 30 Jan 2015) $
* Revision: $LastChangedRevision: 9755 $
*/
/* This class was auto-generated by the message builder generator tools. */
namespace Ca.Infoway.Messagebuilder.Model.Pcs_cda_r1_2.Merged {
using Ca.Infoway.Messagebuilder;
using Ca.Infoway.Messagebuilder.Annotation;
using Ca.Infoway.Messagebuilder.Datatype;
using Ca.Infoway.Messagebuilder.Datatype.Impl;
using Ca.Infoway.Messagebuilder.Datatype.Lang;
using Ca.Infoway.Messagebuilder.Model;
using Ca.Infoway.Messagebuilder.Model.Pcs_cda_r1_2.Basemodel;
using Ca.Infoway.Messagebuilder.Model.Pcs_cda_r1_2.Domainvalue;
using System.Collections.Generic;
[Hl7PartTypeMappingAttribute(new string[] {"BaseModel.Performer1","BaseModel.Performer2"})]
public class Performer2 : MessagePartBean {
private II typeId;
private LIST<II, Identifier> templateId;
private IVLTSCDAR1 time;
private CE modeCode;
private Ca.Infoway.Messagebuilder.Model.Pcs_cda_r1_2.Basemodel.AssignedEntity assignedEntity;
private CS typeCode;
private CE functionCode;
public Performer2() {
this.typeId = new IIImpl();
this.templateId = new LISTImpl<II, Identifier>(typeof(IIImpl));
this.time = new IVLTSCDAR1Impl();
this.modeCode = new CEImpl();
this.typeCode = new CSImpl();
this.functionCode = new CEImpl();
}
/**
* <summary>Un-merged Business Name: (no business name
* specified)</summary>
*
* <remarks>Relationship: BaseModel.Performer2.typeId
* Conformance/Cardinality: OPTIONAL (0-1) Un-merged Business
* Name: (no business name specified) Relationship:
* BaseModel.Performer1.typeId Conformance/Cardinality:
* OPTIONAL (0-1)</remarks>
*/
[Hl7XmlMappingAttribute(new string[] {"typeId"})]
public Identifier TypeId {
get { return this.typeId.Value; }
set { this.typeId.Value = value; }
}
/**
* <summary>Un-merged Business Name: (no business name
* specified)</summary>
*
* <remarks>Relationship: BaseModel.Performer2.templateId
* Conformance/Cardinality: OPTIONAL (0-*) Un-merged Business
* Name: (no business name specified) Relationship:
* BaseModel.Performer1.templateId Conformance/Cardinality:
* OPTIONAL (0-*)</remarks>
*/
[Hl7XmlMappingAttribute(new string[] {"templateId"})]
public IList<Identifier> TemplateId {
get { return this.templateId.RawList(); }
}
/**
* <summary>Un-merged Business Name: (no business name
* specified)</summary>
*
* <remarks>Relationship: BaseModel.Performer2.time
* Conformance/Cardinality: OPTIONAL (0-1) Un-merged Business
* Name: (no business name specified) Relationship:
* BaseModel.Performer1.time Conformance/Cardinality: OPTIONAL
* (0-1)</remarks>
*/
[Hl7XmlMappingAttribute(new string[] {"time"})]
public DateInterval Time {
get { return this.time.Value; }
set { this.time.Value = value; }
}
/**
* <summary>Un-merged Business Name: (no business name
* specified)</summary>
*
* <remarks>Relationship: BaseModel.Performer2.modeCode
* Conformance/Cardinality: OPTIONAL (0-1)</remarks>
*/
[Hl7XmlMappingAttribute(new string[] {"modeCode"})]
public Code ModeCode {
get { return (Code) this.modeCode.Value; }
set { this.modeCode.Value = value; }
}
/**
* <summary>Un-merged Business Name: (no business name
* specified)</summary>
*
* <remarks>Relationship: BaseModel.Performer2.assignedEntity
* Conformance/Cardinality: POPULATED (1) Un-merged Business
* Name: (no business name specified) Relationship:
* BaseModel.Performer1.assignedEntity Conformance/Cardinality:
* POPULATED (1)</remarks>
*/
[Hl7XmlMappingAttribute(new string[] {"assignedEntity"})]
public Ca.Infoway.Messagebuilder.Model.Pcs_cda_r1_2.Basemodel.AssignedEntity AssignedEntity {
get { return this.assignedEntity; }
set { this.assignedEntity = value; }
}
/**
* <summary>Un-merged Business Name: (no business name
* specified)</summary>
*
* <remarks>Relationship: BaseModel.Performer1.typeCode
* Conformance/Cardinality: MANDATORY (1)</remarks>
*/
[Hl7XmlMappingAttribute(new string[] {"typeCode"})]
public x_ServiceEventPerformer TypeCode {
get { return (x_ServiceEventPerformer) this.typeCode.Value; }
set { this.typeCode.Value = value; }
}
/**
* <summary>Un-merged Business Name: (no business name
* specified)</summary>
*
* <remarks>Relationship: BaseModel.Performer1.functionCode
* Conformance/Cardinality: OPTIONAL (0-1)</remarks>
*/
[Hl7XmlMappingAttribute(new string[] {"functionCode"})]
public Code FunctionCode {
get { return (Code) this.functionCode.Value; }
set { this.functionCode.Value = value; }
}
}
} | 40.132911 | 102 | 0.608264 | [
"ECL-2.0",
"Apache-2.0"
] | CanadaHealthInfoway/message-builder-dotnet | message-builder-pcs-cda-r1_2/Main/Ca/Infoway/Messagebuilder/Model/Pcs_cda_r1_2/Merged/Performer2.cs | 6,341 | C# |
using System.Collections.Generic;
using Essensoft.Paylink.Alipay.Response;
namespace Essensoft.Paylink.Alipay.Request
{
/// <summary>
/// zoloz.authentication.customer.faceability.identify
/// </summary>
public class ZolozAuthenticationCustomerFaceabilityIdentifyRequest : IAlipayRequest<ZolozAuthenticationCustomerFaceabilityIdentifyResponse>
{
/// <summary>
/// 人脸能力接口
/// </summary>
public string BizContent { get; set; }
#region IAlipayRequest Members
private bool needEncrypt = false;
private string apiVersion = "1.0";
private string terminalType;
private string terminalInfo;
private string prodCode;
private string notifyUrl;
private string returnUrl;
private AlipayObject bizModel;
public void SetNeedEncrypt(bool needEncrypt)
{
this.needEncrypt = needEncrypt;
}
public bool GetNeedEncrypt()
{
return needEncrypt;
}
public void SetNotifyUrl(string notifyUrl)
{
this.notifyUrl = notifyUrl;
}
public string GetNotifyUrl()
{
return notifyUrl;
}
public void SetReturnUrl(string returnUrl)
{
this.returnUrl = returnUrl;
}
public string GetReturnUrl()
{
return returnUrl;
}
public void SetTerminalType(string terminalType)
{
this.terminalType = terminalType;
}
public string GetTerminalType()
{
return terminalType;
}
public void SetTerminalInfo(string terminalInfo)
{
this.terminalInfo = terminalInfo;
}
public string GetTerminalInfo()
{
return terminalInfo;
}
public void SetProdCode(string prodCode)
{
this.prodCode = prodCode;
}
public string GetProdCode()
{
return prodCode;
}
public string GetApiName()
{
return "zoloz.authentication.customer.faceability.identify";
}
public void SetApiVersion(string apiVersion)
{
this.apiVersion = apiVersion;
}
public string GetApiVersion()
{
return apiVersion;
}
public IDictionary<string, string> GetParameters()
{
var parameters = new AlipayDictionary
{
{ "biz_content", BizContent }
};
return parameters;
}
public AlipayObject GetBizModel()
{
return bizModel;
}
public void SetBizModel(AlipayObject bizModel)
{
this.bizModel = bizModel;
}
#endregion
}
}
| 23.080645 | 143 | 0.555905 | [
"MIT"
] | fory77/paylink | src/Essensoft.Paylink.Alipay/Request/ZolozAuthenticationCustomerFaceabilityIdentifyRequest.cs | 2,876 | C# |
using System.Threading.Tasks;
using Microsoft.Extensions.Logging;
using ReactiveMvvm.Interfaces;
namespace ReactiveMvvm.Blazor.Services
{
public class LoggingSender : ISender
{
private readonly ILogger<LoggingSender> _logger;
public LoggingSender(ILogger<LoggingSender> logger) => _logger = logger;
public Task Send(string title, string message, int section, bool bug)
{
_logger.LogInformation($"Title: {title}");
_logger.LogInformation($"Message: {message}");
_logger.LogInformation($"Metadata: {section} {bug}");
return Task.CompletedTask;
}
}
} | 31 | 80 | 0.663594 | [
"MIT"
] | worldbeater/ReactiveMvvm | src/ReactiveMvvm.Blazor/Services/LoggingSender.cs | 653 | C# |
namespace BullsAndCows.Web.DataModels
{
using System;
using System.Linq;
using System.Linq.Expressions;
using BullsAndCows.Models;
public class GuessDataModel
{
public static Expression<Func<Guess, GuessDataModel>> FromGuess
{
get
{
return g => new GuessDataModel()
{
Id = g.Id,
UserId = g.UserId,
Username = g.User.UserName,
GameId = g.GameId,
Number = g.Number,
DateMade = g.DateMade,
CowsCount = g.CowsCount,
BullsCount = g.BullsCount
};
}
}
public int Id { get; set; }
public string UserId { get; set; }
public string Username { get; set; }
public int GameId { get; set; }
public string Number { get; set; }
public DateTime DateMade { get; set; }
public int CowsCount { get; set; }
public int BullsCount { get; set; }
}
}
| 23.847826 | 71 | 0.47949 | [
"MIT"
] | dzhenko/TelerikAcademy | WebServices/BullsAndCows/BullsAndCows.Web/DataModels/GuessDataModel.cs | 1,099 | C# |
// -----------------------------------------------------------------------
// <copyright file="IIdentityStorage.cs" company="Asynkron AB">
// Copyright (C) 2015-2022 Asynkron AB All rights reserved
// </copyright>
// -----------------------------------------------------------------------
using System;
using System.Threading;
using System.Threading.Tasks;
namespace Proto.Cluster.Identity;
public interface IIdentityStorage : IDisposable
{
public Task<StoredActivation?> TryGetExistingActivation(
ClusterIdentity clusterIdentity,
CancellationToken ct
);
public Task<SpawnLock?> TryAcquireLock(ClusterIdentity clusterIdentity, CancellationToken ct);
/// <summary>
/// Wait on lock, return activation when present. Responsible for deleting stale locks
/// </summary>
/// <param name="clusterIdentity"></param>
/// <param name="ct"></param>
/// <returns></returns>
public Task<StoredActivation?> WaitForActivation(ClusterIdentity clusterIdentity, CancellationToken ct);
public Task RemoveLock(SpawnLock spawnLock, CancellationToken ct);
public Task StoreActivation(string memberId, SpawnLock spawnLock, PID pid, CancellationToken ct);
public Task RemoveActivation(ClusterIdentity clusterIdentity, PID pid, CancellationToken ct);
public Task RemoveMember(string memberId, CancellationToken ct);
public Task Init();
}
public class SpawnLock
{
public SpawnLock(string lockId, ClusterIdentity clusterIdentity)
{
LockId = lockId;
ClusterIdentity = clusterIdentity;
}
public string LockId { get; }
public ClusterIdentity ClusterIdentity { get; }
}
public class StoredActivation
{
public StoredActivation(string memberId, PID pid)
{
MemberId = memberId;
Pid = pid;
}
public PID Pid { get; }
public string MemberId { get; }
}
public class StorageFailure : Exception
{
public StorageFailure(string message) : base(message)
{
}
public StorageFailure(string message, Exception innerException) : base(message, innerException)
{
}
}
public class LockNotFoundException : StorageFailure
{
public LockNotFoundException(string message) : base(message)
{
}
} | 28.1 | 108 | 0.665925 | [
"Apache-2.0"
] | BearerPipelineTest/protoactor-dotnet | src/Proto.Cluster/Identity/IIdentityStorage.cs | 2,250 | C# |
using System.Collections;
using System.ComponentModel;
using System.Management;
namespace Ouranos.NextBootOSSelector.BootConfigurationData {
// 関数 ShouldSerialize<PropertyName> は、特定のプロパティをシリアル化する必要があるかどうかを調べるために VS プロパティ ブラウザで使用される関数です。これらの関数はすべての ValueType プロパティに追加されます ( NULL に設定できない型のプロパティ、Int32, BOOLなど)。これらの関数は Is<PropertyName>Null 関数を使用します。これらの関数はまた、プロパティの NULL 値を調べるプロパティのための TypeConverter 実装でも使用され、Visual studio でドラッグ アンド ドロップをする場合は、プロパティ ブラウザに空の値が表示されるようにします。
// Functions Is<PropertyName>Null() は、プロパティが NULL かどうかを調べるために使用されます。
// 関数 Reset<PropertyName> は Null 許容を使用できる読み込み/書き込みプロパティに追加されます。これらの関数は、プロパティを NULL に設定するためにプロパティ ブラウザの VS デザイナによって使用されます。
// プロパティ用にクラスに追加されたすべてのプロパティは、Visual Studio デザイナ内での動作を定義するように、また使用する TypeConverter を定義するように設定されています。
// WMI クラス用に生成された事前バインディング クラスです。BcdDeviceLocateStringData
internal class BcdDeviceLocateStringData : Component {
// クラスが存在する場所にWMI 名前空間を保持するプライベート プロパティです。
private static string CreatedWmiNamespace = "root\\WMI";
// このクラスを作成した WMI クラスの名前を保持するプライベート プロパティです。
private static string CreatedClassName = "BcdDeviceLocateStringData";
// さまざまなメソッドで使用される ManagementScope を保持するプライベート メンバ変数です。
private static ManagementScope statMgmtScope;
private ManagementSystemProperties PrivateSystemProperties;
// 基になる LateBound WMI オブジェクトです。
private ManagementObject PrivateLateBoundObject;
// クラスの '自動コミット' 動作を保存するメンバ変数です。
private bool AutoCommitProp;
// インスタンスを表す埋め込みプロパティを保持するプライベート変数です。
private ManagementBaseObject embeddedObj;
// 現在使用されている WMI オブジェクトです。
private ManagementBaseObject curObj;
// インスタンスが埋め込みオブジェクトかどうかを示すフラグです。
private bool isEmbedded;
// 下記は WMI オブジェクトを使用してクラスのインスタンスを初期化するコンストラクタのオーバーロードです。
public BcdDeviceLocateStringData() {
this.InitializeObject(null, null, null);
}
public BcdDeviceLocateStringData(ManagementPath path, ObjectGetOptions getOptions) {
this.InitializeObject(null, path, getOptions);
}
public BcdDeviceLocateStringData(ManagementScope mgmtScope, ManagementPath path) {
this.InitializeObject(mgmtScope, path, null);
}
public BcdDeviceLocateStringData(ManagementPath path) {
this.InitializeObject(null, path, null);
}
public BcdDeviceLocateStringData(ManagementScope mgmtScope, ManagementPath path, ObjectGetOptions getOptions) {
this.InitializeObject(mgmtScope, path, getOptions);
}
public BcdDeviceLocateStringData(ManagementObject theObject) {
this.Initialize();
if (this.CheckIfProperClass(theObject)) {
this.PrivateLateBoundObject = theObject;
this.PrivateSystemProperties = new ManagementSystemProperties(this.PrivateLateBoundObject);
this.curObj = this.PrivateLateBoundObject;
}
else {
throw new System.ArgumentException("クラス名が一致しません。");
}
}
public BcdDeviceLocateStringData(ManagementBaseObject theObject) {
this.Initialize();
if (this.CheckIfProperClass(theObject)) {
this.embeddedObj = theObject;
this.PrivateSystemProperties = new ManagementSystemProperties(theObject);
this.curObj = this.embeddedObj;
this.isEmbedded = true;
}
else {
throw new System.ArgumentException("クラス名が一致しません。");
}
}
// WMI クラスの名前空間を返すプロパティです。
[Browsable(true)]
[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
public string OriginatingNamespace {
get {
return "root\\WMI";
}
}
[Browsable(true)]
[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
public string ManagementClassName {
get {
string strRet = CreatedClassName;
if ((this.curObj != null)) {
if ((this.curObj.ClassPath != null)) {
strRet = ((string)(this.curObj["__CLASS"]));
if (((strRet == null)
|| (strRet == string.Empty))) {
strRet = CreatedClassName;
}
}
}
return strRet;
}
}
// WMI オブジェクトのシステム プロパティを取得するための埋め込みオブジェクトをポイントするプロパティです。
[Browsable(true)]
[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
public ManagementSystemProperties SystemProperties {
get {
return this.PrivateSystemProperties;
}
}
// 基になる LateBound WMI オブジェクトを返すプロパティです。
[Browsable(false)]
[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
public ManagementBaseObject LateBoundObject {
get {
return this.curObj;
}
}
// オブジェクトの ManagementScope です。
[Browsable(true)]
[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
public ManagementScope Scope {
get
{
if ((this.isEmbedded == false)) {
return this.PrivateLateBoundObject.Scope;
}
return null;
}
set {
if ((this.isEmbedded == false)) {
this.PrivateLateBoundObject.Scope = value;
}
}
}
// WMI オブジェクトのコミット動作を表示するプロパティです。 これが true の場合、プロパティが変更するたびに WMI オブジェクトは自動的に保存されます (すなわち、プロパティを変更した後で Put() が呼び出されます)。
[Browsable(false)]
[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
public bool AutoCommit {
get {
return this.AutoCommitProp;
}
set {
this.AutoCommitProp = value;
}
}
// 基になる WMI オブジェクトの ManagementPath です。
[Browsable(true)]
public ManagementPath Path {
get
{
if ((this.isEmbedded == false)) {
return this.PrivateLateBoundObject.Path;
}
return null;
}
set {
if ((this.isEmbedded == false)) {
if ((this.CheckIfProperClass(null, value, null) != true)) {
throw new System.ArgumentException("クラス名が一致しません。");
}
this.PrivateLateBoundObject.Path = value;
}
}
}
// さまざまなメソッドで使用されるプライベート スタティック スコープ プロパティです。
[Browsable(true)]
[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
public static ManagementScope StaticScope {
get {
return statMgmtScope;
}
set {
statMgmtScope = value;
}
}
[Browsable(true)]
[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
public string AdditionalOptions {
get {
return ((string)(this.curObj["AdditionalOptions"]));
}
set {
this.curObj["AdditionalOptions"] = value;
if (((this.isEmbedded == false)
&& this.AutoCommitProp)) {
this.PrivateLateBoundObject.Put();
}
}
}
[Browsable(false)]
[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
public bool IsDeviceTypeNull {
get
{
if ((this.curObj["DeviceType"] == null)) {
return true;
}
return false;
}
}
[Browsable(true)]
[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
[TypeConverter(typeof(WMIValueTypeConverter))]
public uint DeviceType {
get {
if ((this.curObj["DeviceType"] == null)) {
return System.Convert.ToUInt32(0);
}
return ((uint)(this.curObj["DeviceType"]));
}
set {
this.curObj["DeviceType"] = value;
if (((this.isEmbedded == false)
&& this.AutoCommitProp)) {
this.PrivateLateBoundObject.Put();
}
}
}
[Browsable(true)]
[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
[Description("This provides the locate device element.")]
public string Path0 {
get {
return ((string)(this.curObj["Path"]));
}
set {
this.curObj["Path"] = value;
if (((this.isEmbedded == false)
&& this.AutoCommitProp)) {
this.PrivateLateBoundObject.Put();
}
}
}
[Browsable(false)]
[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
public bool IsTypeNull {
get
{
if ((this.curObj["Type"] == null)) {
return true;
}
return false;
}
}
[Browsable(true)]
[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
[TypeConverter(typeof(WMIValueTypeConverter))]
public uint Type {
get {
if ((this.curObj["Type"] == null)) {
return System.Convert.ToUInt32(0);
}
return ((uint)(this.curObj["Type"]));
}
set {
this.curObj["Type"] = value;
if (((this.isEmbedded == false)
&& this.AutoCommitProp)) {
this.PrivateLateBoundObject.Put();
}
}
}
private bool CheckIfProperClass(ManagementScope mgmtScope, ManagementPath path, ObjectGetOptions OptionsParam)
{
if (((path != null)
&& (string.Compare(path.ClassName, this.ManagementClassName, true, System.Globalization.CultureInfo.InvariantCulture) == 0))) {
return true;
}
return this.CheckIfProperClass(new ManagementObject(mgmtScope, path, OptionsParam));
}
private bool CheckIfProperClass(ManagementBaseObject theObj) {
if (((theObj != null)
&& (string.Compare(((string)(theObj["__CLASS"])), this.ManagementClassName, true, System.Globalization.CultureInfo.InvariantCulture) == 0))) {
return true;
}
System.Array parentClasses = ((System.Array)(theObj["__DERIVATION"]));
if ((parentClasses != null)) {
int count = 0;
for (count = 0; (count < parentClasses.Length); count = (count + 1)) {
if ((string.Compare(((string)(parentClasses.GetValue(count))), this.ManagementClassName, true, System.Globalization.CultureInfo.InvariantCulture) == 0)) {
return true;
}
}
}
return false;
}
private void ResetAdditionalOptions() {
this.curObj["AdditionalOptions"] = null;
if (((this.isEmbedded == false)
&& this.AutoCommitProp)) {
this.PrivateLateBoundObject.Put();
}
}
private bool ShouldSerializeDeviceType() {
if ((this.IsDeviceTypeNull == false)) {
return true;
}
return false;
}
private void ResetDeviceType() {
this.curObj["DeviceType"] = null;
if (((this.isEmbedded == false)
&& this.AutoCommitProp)) {
this.PrivateLateBoundObject.Put();
}
}
private void ResetPath0() {
this.curObj["Path"] = null;
if (((this.isEmbedded == false)
&& this.AutoCommitProp)) {
this.PrivateLateBoundObject.Put();
}
}
private bool ShouldSerializeType() {
if ((this.IsTypeNull == false)) {
return true;
}
return false;
}
private void ResetType() {
this.curObj["Type"] = null;
if (((this.isEmbedded == false)
&& this.AutoCommitProp)) {
this.PrivateLateBoundObject.Put();
}
}
[Browsable(true)]
public void CommitObject() {
if ((this.isEmbedded == false)) {
this.PrivateLateBoundObject.Put();
}
}
[Browsable(true)]
public void CommitObject(PutOptions putOptions) {
if ((this.isEmbedded == false)) {
this.PrivateLateBoundObject.Put(putOptions);
}
}
private void Initialize() {
this.AutoCommitProp = true;
this.isEmbedded = false;
}
private static string ConstructPath() {
string strPath = "root\\WMI:BcdDeviceLocateStringData";
return strPath;
}
private void InitializeObject(ManagementScope mgmtScope, ManagementPath path, ObjectGetOptions getOptions) {
this.Initialize();
if ((path != null)) {
if ((this.CheckIfProperClass(mgmtScope, path, getOptions) != true)) {
throw new System.ArgumentException("クラス名が一致しません。");
}
}
this.PrivateLateBoundObject = new ManagementObject(mgmtScope, path, getOptions);
this.PrivateSystemProperties = new ManagementSystemProperties(this.PrivateLateBoundObject);
this.curObj = this.PrivateLateBoundObject;
}
// WMI クラスのインスタンスを列挙する GetInstances() ヘルプのオーバーロードです。
public static BcdDeviceLocateStringDataCollection GetInstances() {
return GetInstances(null, null, null);
}
public static BcdDeviceLocateStringDataCollection GetInstances(string condition) {
return GetInstances(null, condition, null);
}
public static BcdDeviceLocateStringDataCollection GetInstances(string[] selectedProperties) {
return GetInstances(null, null, selectedProperties);
}
public static BcdDeviceLocateStringDataCollection GetInstances(string condition, string[] selectedProperties) {
return GetInstances(null, condition, selectedProperties);
}
public static BcdDeviceLocateStringDataCollection GetInstances(ManagementScope mgmtScope, EnumerationOptions enumOptions) {
if ((mgmtScope == null)) {
if ((statMgmtScope == null)) {
mgmtScope = new ManagementScope();
mgmtScope.Path.NamespacePath = "root\\WMI";
}
else {
mgmtScope = statMgmtScope;
}
}
ManagementPath pathObj = new ManagementPath();
pathObj.ClassName = "BcdDeviceLocateStringData";
pathObj.NamespacePath = "root\\WMI";
ManagementClass clsObject = new ManagementClass(mgmtScope, pathObj, null);
if ((enumOptions == null)) {
enumOptions = new EnumerationOptions();
enumOptions.EnsureLocatable = true;
}
return new BcdDeviceLocateStringDataCollection(clsObject.GetInstances(enumOptions));
}
public static BcdDeviceLocateStringDataCollection GetInstances(ManagementScope mgmtScope, string condition) {
return GetInstances(mgmtScope, condition, null);
}
public static BcdDeviceLocateStringDataCollection GetInstances(ManagementScope mgmtScope, string[] selectedProperties) {
return GetInstances(mgmtScope, null, selectedProperties);
}
public static BcdDeviceLocateStringDataCollection GetInstances(ManagementScope mgmtScope, string condition, string[] selectedProperties) {
if ((mgmtScope == null)) {
if ((statMgmtScope == null)) {
mgmtScope = new ManagementScope();
mgmtScope.Path.NamespacePath = "root\\WMI";
}
else {
mgmtScope = statMgmtScope;
}
}
ManagementObjectSearcher ObjectSearcher = new ManagementObjectSearcher(mgmtScope, new SelectQuery("BcdDeviceLocateStringData", condition, selectedProperties));
EnumerationOptions enumOptions = new EnumerationOptions();
enumOptions.EnsureLocatable = true;
ObjectSearcher.Options = enumOptions;
return new BcdDeviceLocateStringDataCollection(ObjectSearcher.Get());
}
[Browsable(true)]
public static BcdDeviceLocateStringData CreateInstance() {
ManagementScope mgmtScope = null;
if ((statMgmtScope == null)) {
mgmtScope = new ManagementScope();
mgmtScope.Path.NamespacePath = CreatedWmiNamespace;
}
else {
mgmtScope = statMgmtScope;
}
ManagementPath mgmtPath = new ManagementPath(CreatedClassName);
ManagementClass tmpMgmtClass = new ManagementClass(mgmtScope, mgmtPath, null);
return new BcdDeviceLocateStringData(tmpMgmtClass.CreateInstance());
}
[Browsable(true)]
public void Delete() {
this.PrivateLateBoundObject.Delete();
}
// クラスのインスタンスを列挙する列挙子の実装です。
internal class BcdDeviceLocateStringDataCollection : object, ICollection {
private ManagementObjectCollection privColObj;
public BcdDeviceLocateStringDataCollection(ManagementObjectCollection objCollection) {
this.privColObj = objCollection;
}
public virtual int Count {
get {
return this.privColObj.Count;
}
}
public virtual bool IsSynchronized {
get {
return this.privColObj.IsSynchronized;
}
}
public virtual object SyncRoot {
get {
return this;
}
}
public virtual void CopyTo(System.Array array, int index) {
this.privColObj.CopyTo(array, index);
int nCtr;
for (nCtr = 0; (nCtr < array.Length); nCtr = (nCtr + 1)) {
array.SetValue(new BcdDeviceLocateStringData(((ManagementObject)(array.GetValue(nCtr)))), nCtr);
}
}
public virtual IEnumerator GetEnumerator() {
return new BcdDeviceLocateStringDataEnumerator(this.privColObj.GetEnumerator());
}
internal class BcdDeviceLocateStringDataEnumerator : object, IEnumerator {
private ManagementObjectCollection.ManagementObjectEnumerator privObjEnum;
public BcdDeviceLocateStringDataEnumerator(ManagementObjectCollection.ManagementObjectEnumerator objEnum) {
this.privObjEnum = objEnum;
}
public virtual object Current {
get {
return new BcdDeviceLocateStringData(((ManagementObject)(this.privObjEnum.Current)));
}
}
public virtual bool MoveNext() {
return this.privObjEnum.MoveNext();
}
public virtual void Reset() {
this.privObjEnum.Reset();
}
}
}
// ValueType プロパティの NULL 値を扱う TypeConverter です。
internal class WMIValueTypeConverter : TypeConverter {
private TypeConverter baseConverter;
private System.Type baseType;
public WMIValueTypeConverter(System.Type inBaseType) {
this.baseConverter = TypeDescriptor.GetConverter(inBaseType);
this.baseType = inBaseType;
}
public override bool CanConvertFrom(ITypeDescriptorContext context, System.Type srcType) {
return this.baseConverter.CanConvertFrom(context, srcType);
}
public override bool CanConvertTo(ITypeDescriptorContext context, System.Type destinationType) {
return this.baseConverter.CanConvertTo(context, destinationType);
}
public override object ConvertFrom(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value) {
return this.baseConverter.ConvertFrom(context, culture, value);
}
public override object CreateInstance(ITypeDescriptorContext context, IDictionary dictionary) {
return this.baseConverter.CreateInstance(context, dictionary);
}
public override bool GetCreateInstanceSupported(ITypeDescriptorContext context) {
return this.baseConverter.GetCreateInstanceSupported(context);
}
public override PropertyDescriptorCollection GetProperties(ITypeDescriptorContext context, object value, System.Attribute[] attributeVar) {
return this.baseConverter.GetProperties(context, value, attributeVar);
}
public override bool GetPropertiesSupported(ITypeDescriptorContext context) {
return this.baseConverter.GetPropertiesSupported(context);
}
public override StandardValuesCollection GetStandardValues(ITypeDescriptorContext context) {
return this.baseConverter.GetStandardValues(context);
}
public override bool GetStandardValuesExclusive(ITypeDescriptorContext context) {
return this.baseConverter.GetStandardValuesExclusive(context);
}
public override bool GetStandardValuesSupported(ITypeDescriptorContext context) {
return this.baseConverter.GetStandardValuesSupported(context);
}
public override object ConvertTo(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, System.Type destinationType) {
if ((this.baseType.BaseType == typeof(System.Enum))) {
if ((value.GetType() == destinationType)) {
return value;
}
if ((((value == null)
&& (context != null))
&& (context.PropertyDescriptor.ShouldSerializeValue(context.Instance) == false))) {
return "NULL_ENUM_VALUE" ;
}
return this.baseConverter.ConvertTo(context, culture, value, destinationType);
}
if (((this.baseType == typeof(bool))
&& (this.baseType.BaseType == typeof(System.ValueType)))) {
if ((((value == null)
&& (context != null))
&& (context.PropertyDescriptor.ShouldSerializeValue(context.Instance) == false))) {
return "";
}
return this.baseConverter.ConvertTo(context, culture, value, destinationType);
}
if (((context != null)
&& (context.PropertyDescriptor.ShouldSerializeValue(context.Instance) == false))) {
return "";
}
return this.baseConverter.ConvertTo(context, culture, value, destinationType);
}
}
// WMI システム プロパティを表す埋め込みクラスです。
[TypeConverter(typeof(ExpandableObjectConverter))]
internal class ManagementSystemProperties {
private ManagementBaseObject PrivateLateBoundObject;
public ManagementSystemProperties(ManagementBaseObject ManagedObject) {
this.PrivateLateBoundObject = ManagedObject;
}
[Browsable(true)]
public int GENUS {
get {
return ((int)(this.PrivateLateBoundObject["__GENUS"]));
}
}
[Browsable(true)]
public string CLASS {
get {
return ((string)(this.PrivateLateBoundObject["__CLASS"]));
}
}
[Browsable(true)]
public string SUPERCLASS {
get {
return ((string)(this.PrivateLateBoundObject["__SUPERCLASS"]));
}
}
[Browsable(true)]
public string DYNASTY {
get {
return ((string)(this.PrivateLateBoundObject["__DYNASTY"]));
}
}
[Browsable(true)]
public string RELPATH {
get {
return ((string)(this.PrivateLateBoundObject["__RELPATH"]));
}
}
[Browsable(true)]
public int PROPERTY_COUNT {
get {
return ((int)(this.PrivateLateBoundObject["__PROPERTY_COUNT"]));
}
}
[Browsable(true)]
public string[] DERIVATION {
get {
return ((string[])(this.PrivateLateBoundObject["__DERIVATION"]));
}
}
[Browsable(true)]
public string SERVER {
get {
return ((string)(this.PrivateLateBoundObject["__SERVER"]));
}
}
[Browsable(true)]
public string NAMESPACE {
get {
return ((string)(this.PrivateLateBoundObject["__NAMESPACE"]));
}
}
[Browsable(true)]
public string PATH {
get {
return ((string)(this.PrivateLateBoundObject["__PATH"]));
}
}
}
}
}
| 39.494302 | 331 | 0.537313 | [
"MIT"
] | takuya-takeuchi/NextBootOSSelector | source/NextBootOSSelector.Core/BootConfigurationData/BcdDeviceLocateStringData.cs | 29,813 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
namespace BlazorWasmApp.AuthServer.Controllers
{
[ApiController]
[Route("[controller]")]
public class WeatherForecastController : ControllerBase
{
private static readonly string[] Summaries = new[]
{
"Freezing", "Bracing", "Chilly", "Cool", "Mild", "Warm", "Balmy", "Hot", "Sweltering", "Scorching"
};
private readonly ILogger<WeatherForecastController> _logger;
public WeatherForecastController(ILogger<WeatherForecastController> logger)
{
_logger = logger;
}
[HttpGet]
public IEnumerable<WeatherForecast> Get()
{
var rng = new Random();
return Enumerable.Range(1, 5).Select(index => new WeatherForecast
{
Date = DateTime.Now.AddDays(index),
TemperatureC = rng.Next(-20, 55),
Summary = Summaries[rng.Next(Summaries.Length)]
})
.ToArray();
}
}
}
| 28.9 | 110 | 0.603806 | [
"Apache-2.0"
] | mofajke/BlazorWasmApp | BlazorWasmApp.AuthServer/Controllers/WeatherForecastController.cs | 1,158 | C# |
// WinterLeaf Entertainment
// Copyright (c) 2014, WinterLeaf Entertainment LLC
//
// All rights reserved.
//
// The use of the WinterLeaf Entertainment LLC OMNI "Community Edition" is governed by this license agreement ("Agreement").
//
// These license terms are an agreement between WinterLeaf Entertainment LLC and you. Please read them. They apply to the source code and any other assets or works that are included with the product named above, which includes the media on which you received it, if any. These terms also apply to any updates, supplements, internet-based services, and support services for this software and its associated assets, unless other terms accompany those items. If so, those terms apply. You must read and agree to this Agreement terms BEFORE installing OMNI "Community Edition" to your hard drive or using OMNI in any way. If you do not agree to the license terms, do not download, install or use OMNI. Please make copies of this Agreement for all those in your organization who need to be familiar with the license terms.
//
// This license allows companies of any size, government entities or individuals to create, sell, rent, lease, or otherwise profit commercially from, games using executables created from the source code that accompanies OMNI "Community Edition".
//
// BY CLICKING THE ACCEPTANCE BUTTON AND/OR INSTALLING OR USING OMNI "Community Edition", THE INDIVIDUAL ACCESSING OMNI ("LICENSEE") IS CONSENTING TO BE BOUND BY AND BECOME A PARTY TO THIS AGREEMENT. IF YOU DO NOT ACCEPT THESE TERMS, DO NOT INSTALL OR USE OMNI. IF YOU COMPLY WITH THESE LICENSE TERMS, YOU HAVE THE RIGHTS BELOW:
//
// 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 all 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.
// With respect to any Product that the Licensee develop using the Software:
// Licensee shall:
// display the OMNI Logo, in the start-up sequence of the Product (unless waived by WinterLeaf Entertainment);
// display in the "About" box or in the credits screen of the Product the text "OMNI by WinterLeaf Entertainment";
// display the OMNI Logo, on all external Product packaging materials and the back cover of any printed instruction manual or the end of any electronic instruction manual;
// notify WinterLeaf Entertainment in writing that You are publicly releasing a Product that was developed using the Software within the first 30 days following the release; and
// the Licensee hereby grant WinterLeaf Entertainment permission to refer to the Licensee or the name of any Product the Licensee develops using the Software for marketing purposes. All goodwill in each party's trademarks and logos will inure to the sole benefit of that party.
// Neither the name of WinterLeaf Entertainment LLC or OMNI nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.
// The following restrictions apply to the use of OMNI "Community Edition":
// Licensee may not:
// create any derivative works of OMNI Engine, including but not limited to translations, localizations, or game making software other than Games;
// redistribute, encumber, sell, rent, lease, sublicense, or otherwise transfer rights to OMNI "Community Edition"; or
// remove or alter any trademark, logo, copyright or other proprietary notices, legends, symbols or labels in OMNI Engine; or
// use the Software to develop or distribute any software that competes with the Software without WinterLeaf Entertainment’s prior written consent; or
// use the Software for any illegal purpose.
//
// THIS SOFTWARE IS PROVIDED BY WINTERLEAF ENTERTAINMENT LLC ''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 WINTERLEAF ENTERTAINMENT LLC 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.Runtime.InteropServices;
namespace WinterLeaf.Engine.Classes.Helpers
{
/// <summary>
/// Internal Use.
/// </summary>
internal class LibraryManager
{
internal static bool IsLinux()
{
int p = (int) Environment.OSVersion.Platform;
return (p == 4) || (p == 6) || (p == 128);
}
internal interface DllLoadUtils
{
IntPtr LoadLibrary(string fileName);
void FreeLibrary(IntPtr handle);
IntPtr GetProcAddress(IntPtr dllHandle, string name);
}
internal class DllLoadUtilsLinux : DllLoadUtils
{
private const int RTLD_NOW = 2;
public IntPtr LoadLibrary(string fileName)
{
return dlopen(fileName, RTLD_NOW);
}
public void FreeLibrary(IntPtr handle)
{
dlclose(handle);
}
public IntPtr GetProcAddress(IntPtr dllHandle, string name)
{
// clear previous errors if any
dlerror();
IntPtr res = dlsym(dllHandle, name);
IntPtr errPtr = dlerror();
if (errPtr != IntPtr.Zero)
throw new Exception("dlsym: " + Marshal.PtrToStringAnsi(errPtr));
return res;
}
[DllImport("libdl.so")]
private static extern IntPtr dlopen(String fileName, int flags);
[DllImport("libdl.so")]
private static extern IntPtr dlsym(IntPtr handle, String symbol);
[DllImport("libdl.so")]
private static extern int dlclose(IntPtr handle);
[DllImport("libdl.so")]
private static extern IntPtr dlerror();
}
internal class DllLoadUtilsWindows : DllLoadUtils
{
void DllLoadUtils.FreeLibrary(IntPtr handle)
{
FreeLibrary(handle);
}
IntPtr DllLoadUtils.GetProcAddress(IntPtr dllHandle, string name)
{
return GetProcAddress(dllHandle, name);
}
IntPtr DllLoadUtils.LoadLibrary(string fileName)
{
return LoadLibrary(fileName);
}
[DllImport("kernel32")]
private static extern IntPtr LoadLibrary(string fileName);
[DllImport("kernel32.dll")]
private static extern int FreeLibrary(IntPtr handle);
[DllImport("kernel32.dll")]
private static extern IntPtr GetProcAddress(IntPtr handle, string procedureName);
}
}
} | 60.936 | 819 | 0.684128 | [
"MIT",
"Unlicense"
] | RichardRanft/OmniEngine.Net | Templates/C#-Empty/Winterleaf.Engine.Omni/Classes/Helpers/LibraryManager.cs | 7,497 | C# |
// Generated by the protocol buffer compiler. DO NOT EDIT!
// source: google/logging/v2/logging_metrics.proto
// Original file comments:
// Copyright 2017 Google 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.
//
#pragma warning disable 1591
#region Designer generated code
using System;
using System.Threading;
using System.Threading.Tasks;
using grpc = global::Grpc.Core;
namespace Google.Cloud.Logging.V2 {
/// <summary>
/// Service for configuring logs-based metrics.
/// </summary>
public static partial class MetricsServiceV2
{
static readonly string __ServiceName = "google.logging.v2.MetricsServiceV2";
static readonly grpc::Marshaller<global::Google.Cloud.Logging.V2.ListLogMetricsRequest> __Marshaller_ListLogMetricsRequest = grpc::Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::Google.Cloud.Logging.V2.ListLogMetricsRequest.Parser.ParseFrom);
static readonly grpc::Marshaller<global::Google.Cloud.Logging.V2.ListLogMetricsResponse> __Marshaller_ListLogMetricsResponse = grpc::Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::Google.Cloud.Logging.V2.ListLogMetricsResponse.Parser.ParseFrom);
static readonly grpc::Marshaller<global::Google.Cloud.Logging.V2.GetLogMetricRequest> __Marshaller_GetLogMetricRequest = grpc::Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::Google.Cloud.Logging.V2.GetLogMetricRequest.Parser.ParseFrom);
static readonly grpc::Marshaller<global::Google.Cloud.Logging.V2.LogMetric> __Marshaller_LogMetric = grpc::Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::Google.Cloud.Logging.V2.LogMetric.Parser.ParseFrom);
static readonly grpc::Marshaller<global::Google.Cloud.Logging.V2.CreateLogMetricRequest> __Marshaller_CreateLogMetricRequest = grpc::Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::Google.Cloud.Logging.V2.CreateLogMetricRequest.Parser.ParseFrom);
static readonly grpc::Marshaller<global::Google.Cloud.Logging.V2.UpdateLogMetricRequest> __Marshaller_UpdateLogMetricRequest = grpc::Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::Google.Cloud.Logging.V2.UpdateLogMetricRequest.Parser.ParseFrom);
static readonly grpc::Marshaller<global::Google.Cloud.Logging.V2.DeleteLogMetricRequest> __Marshaller_DeleteLogMetricRequest = grpc::Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::Google.Cloud.Logging.V2.DeleteLogMetricRequest.Parser.ParseFrom);
static readonly grpc::Marshaller<global::Google.Protobuf.WellKnownTypes.Empty> __Marshaller_Empty = grpc::Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::Google.Protobuf.WellKnownTypes.Empty.Parser.ParseFrom);
static readonly grpc::Method<global::Google.Cloud.Logging.V2.ListLogMetricsRequest, global::Google.Cloud.Logging.V2.ListLogMetricsResponse> __Method_ListLogMetrics = new grpc::Method<global::Google.Cloud.Logging.V2.ListLogMetricsRequest, global::Google.Cloud.Logging.V2.ListLogMetricsResponse>(
grpc::MethodType.Unary,
__ServiceName,
"ListLogMetrics",
__Marshaller_ListLogMetricsRequest,
__Marshaller_ListLogMetricsResponse);
static readonly grpc::Method<global::Google.Cloud.Logging.V2.GetLogMetricRequest, global::Google.Cloud.Logging.V2.LogMetric> __Method_GetLogMetric = new grpc::Method<global::Google.Cloud.Logging.V2.GetLogMetricRequest, global::Google.Cloud.Logging.V2.LogMetric>(
grpc::MethodType.Unary,
__ServiceName,
"GetLogMetric",
__Marshaller_GetLogMetricRequest,
__Marshaller_LogMetric);
static readonly grpc::Method<global::Google.Cloud.Logging.V2.CreateLogMetricRequest, global::Google.Cloud.Logging.V2.LogMetric> __Method_CreateLogMetric = new grpc::Method<global::Google.Cloud.Logging.V2.CreateLogMetricRequest, global::Google.Cloud.Logging.V2.LogMetric>(
grpc::MethodType.Unary,
__ServiceName,
"CreateLogMetric",
__Marshaller_CreateLogMetricRequest,
__Marshaller_LogMetric);
static readonly grpc::Method<global::Google.Cloud.Logging.V2.UpdateLogMetricRequest, global::Google.Cloud.Logging.V2.LogMetric> __Method_UpdateLogMetric = new grpc::Method<global::Google.Cloud.Logging.V2.UpdateLogMetricRequest, global::Google.Cloud.Logging.V2.LogMetric>(
grpc::MethodType.Unary,
__ServiceName,
"UpdateLogMetric",
__Marshaller_UpdateLogMetricRequest,
__Marshaller_LogMetric);
static readonly grpc::Method<global::Google.Cloud.Logging.V2.DeleteLogMetricRequest, global::Google.Protobuf.WellKnownTypes.Empty> __Method_DeleteLogMetric = new grpc::Method<global::Google.Cloud.Logging.V2.DeleteLogMetricRequest, global::Google.Protobuf.WellKnownTypes.Empty>(
grpc::MethodType.Unary,
__ServiceName,
"DeleteLogMetric",
__Marshaller_DeleteLogMetricRequest,
__Marshaller_Empty);
/// <summary>Service descriptor</summary>
public static global::Google.Protobuf.Reflection.ServiceDescriptor Descriptor
{
get { return global::Google.Cloud.Logging.V2.LoggingMetricsReflection.Descriptor.Services[0]; }
}
/// <summary>Base class for server-side implementations of MetricsServiceV2</summary>
public abstract partial class MetricsServiceV2Base
{
/// <summary>
/// Lists logs-based metrics.
/// </summary>
/// <param name="request">The request received from the client.</param>
/// <param name="context">The context of the server-side call handler being invoked.</param>
/// <returns>The response to send back to the client (wrapped by a task).</returns>
public virtual global::System.Threading.Tasks.Task<global::Google.Cloud.Logging.V2.ListLogMetricsResponse> ListLogMetrics(global::Google.Cloud.Logging.V2.ListLogMetricsRequest request, grpc::ServerCallContext context)
{
throw new grpc::RpcException(new grpc::Status(grpc::StatusCode.Unimplemented, ""));
}
/// <summary>
/// Gets a logs-based metric.
/// </summary>
/// <param name="request">The request received from the client.</param>
/// <param name="context">The context of the server-side call handler being invoked.</param>
/// <returns>The response to send back to the client (wrapped by a task).</returns>
public virtual global::System.Threading.Tasks.Task<global::Google.Cloud.Logging.V2.LogMetric> GetLogMetric(global::Google.Cloud.Logging.V2.GetLogMetricRequest request, grpc::ServerCallContext context)
{
throw new grpc::RpcException(new grpc::Status(grpc::StatusCode.Unimplemented, ""));
}
/// <summary>
/// Creates a logs-based metric.
/// </summary>
/// <param name="request">The request received from the client.</param>
/// <param name="context">The context of the server-side call handler being invoked.</param>
/// <returns>The response to send back to the client (wrapped by a task).</returns>
public virtual global::System.Threading.Tasks.Task<global::Google.Cloud.Logging.V2.LogMetric> CreateLogMetric(global::Google.Cloud.Logging.V2.CreateLogMetricRequest request, grpc::ServerCallContext context)
{
throw new grpc::RpcException(new grpc::Status(grpc::StatusCode.Unimplemented, ""));
}
/// <summary>
/// Creates or updates a logs-based metric.
/// </summary>
/// <param name="request">The request received from the client.</param>
/// <param name="context">The context of the server-side call handler being invoked.</param>
/// <returns>The response to send back to the client (wrapped by a task).</returns>
public virtual global::System.Threading.Tasks.Task<global::Google.Cloud.Logging.V2.LogMetric> UpdateLogMetric(global::Google.Cloud.Logging.V2.UpdateLogMetricRequest request, grpc::ServerCallContext context)
{
throw new grpc::RpcException(new grpc::Status(grpc::StatusCode.Unimplemented, ""));
}
/// <summary>
/// Deletes a logs-based metric.
/// </summary>
/// <param name="request">The request received from the client.</param>
/// <param name="context">The context of the server-side call handler being invoked.</param>
/// <returns>The response to send back to the client (wrapped by a task).</returns>
public virtual global::System.Threading.Tasks.Task<global::Google.Protobuf.WellKnownTypes.Empty> DeleteLogMetric(global::Google.Cloud.Logging.V2.DeleteLogMetricRequest request, grpc::ServerCallContext context)
{
throw new grpc::RpcException(new grpc::Status(grpc::StatusCode.Unimplemented, ""));
}
}
/// <summary>Client for MetricsServiceV2</summary>
public partial class MetricsServiceV2Client : grpc::ClientBase<MetricsServiceV2Client>
{
/// <summary>Creates a new client for MetricsServiceV2</summary>
/// <param name="channel">The channel to use to make remote calls.</param>
public MetricsServiceV2Client(grpc::Channel channel) : base(channel)
{
}
/// <summary>Creates a new client for MetricsServiceV2 that uses a custom <c>CallInvoker</c>.</summary>
/// <param name="callInvoker">The callInvoker to use to make remote calls.</param>
public MetricsServiceV2Client(grpc::CallInvoker callInvoker) : base(callInvoker)
{
}
/// <summary>Protected parameterless constructor to allow creation of test doubles.</summary>
protected MetricsServiceV2Client() : base()
{
}
/// <summary>Protected constructor to allow creation of configured clients.</summary>
/// <param name="configuration">The client configuration.</param>
protected MetricsServiceV2Client(ClientBaseConfiguration configuration) : base(configuration)
{
}
/// <summary>
/// Lists logs-based metrics.
/// </summary>
/// <param name="request">The request to send to the server.</param>
/// <param name="headers">The initial metadata to send with the call. This parameter is optional.</param>
/// <param name="deadline">An optional deadline for the call. The call will be cancelled if deadline is hit.</param>
/// <param name="cancellationToken">An optional token for canceling the call.</param>
/// <returns>The response received from the server.</returns>
public virtual global::Google.Cloud.Logging.V2.ListLogMetricsResponse ListLogMetrics(global::Google.Cloud.Logging.V2.ListLogMetricsRequest request, grpc::Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken))
{
return ListLogMetrics(request, new grpc::CallOptions(headers, deadline, cancellationToken));
}
/// <summary>
/// Lists logs-based metrics.
/// </summary>
/// <param name="request">The request to send to the server.</param>
/// <param name="options">The options for the call.</param>
/// <returns>The response received from the server.</returns>
public virtual global::Google.Cloud.Logging.V2.ListLogMetricsResponse ListLogMetrics(global::Google.Cloud.Logging.V2.ListLogMetricsRequest request, grpc::CallOptions options)
{
return CallInvoker.BlockingUnaryCall(__Method_ListLogMetrics, null, options, request);
}
/// <summary>
/// Lists logs-based metrics.
/// </summary>
/// <param name="request">The request to send to the server.</param>
/// <param name="headers">The initial metadata to send with the call. This parameter is optional.</param>
/// <param name="deadline">An optional deadline for the call. The call will be cancelled if deadline is hit.</param>
/// <param name="cancellationToken">An optional token for canceling the call.</param>
/// <returns>The call object.</returns>
public virtual grpc::AsyncUnaryCall<global::Google.Cloud.Logging.V2.ListLogMetricsResponse> ListLogMetricsAsync(global::Google.Cloud.Logging.V2.ListLogMetricsRequest request, grpc::Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken))
{
return ListLogMetricsAsync(request, new grpc::CallOptions(headers, deadline, cancellationToken));
}
/// <summary>
/// Lists logs-based metrics.
/// </summary>
/// <param name="request">The request to send to the server.</param>
/// <param name="options">The options for the call.</param>
/// <returns>The call object.</returns>
public virtual grpc::AsyncUnaryCall<global::Google.Cloud.Logging.V2.ListLogMetricsResponse> ListLogMetricsAsync(global::Google.Cloud.Logging.V2.ListLogMetricsRequest request, grpc::CallOptions options)
{
return CallInvoker.AsyncUnaryCall(__Method_ListLogMetrics, null, options, request);
}
/// <summary>
/// Gets a logs-based metric.
/// </summary>
/// <param name="request">The request to send to the server.</param>
/// <param name="headers">The initial metadata to send with the call. This parameter is optional.</param>
/// <param name="deadline">An optional deadline for the call. The call will be cancelled if deadline is hit.</param>
/// <param name="cancellationToken">An optional token for canceling the call.</param>
/// <returns>The response received from the server.</returns>
public virtual global::Google.Cloud.Logging.V2.LogMetric GetLogMetric(global::Google.Cloud.Logging.V2.GetLogMetricRequest request, grpc::Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken))
{
return GetLogMetric(request, new grpc::CallOptions(headers, deadline, cancellationToken));
}
/// <summary>
/// Gets a logs-based metric.
/// </summary>
/// <param name="request">The request to send to the server.</param>
/// <param name="options">The options for the call.</param>
/// <returns>The response received from the server.</returns>
public virtual global::Google.Cloud.Logging.V2.LogMetric GetLogMetric(global::Google.Cloud.Logging.V2.GetLogMetricRequest request, grpc::CallOptions options)
{
return CallInvoker.BlockingUnaryCall(__Method_GetLogMetric, null, options, request);
}
/// <summary>
/// Gets a logs-based metric.
/// </summary>
/// <param name="request">The request to send to the server.</param>
/// <param name="headers">The initial metadata to send with the call. This parameter is optional.</param>
/// <param name="deadline">An optional deadline for the call. The call will be cancelled if deadline is hit.</param>
/// <param name="cancellationToken">An optional token for canceling the call.</param>
/// <returns>The call object.</returns>
public virtual grpc::AsyncUnaryCall<global::Google.Cloud.Logging.V2.LogMetric> GetLogMetricAsync(global::Google.Cloud.Logging.V2.GetLogMetricRequest request, grpc::Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken))
{
return GetLogMetricAsync(request, new grpc::CallOptions(headers, deadline, cancellationToken));
}
/// <summary>
/// Gets a logs-based metric.
/// </summary>
/// <param name="request">The request to send to the server.</param>
/// <param name="options">The options for the call.</param>
/// <returns>The call object.</returns>
public virtual grpc::AsyncUnaryCall<global::Google.Cloud.Logging.V2.LogMetric> GetLogMetricAsync(global::Google.Cloud.Logging.V2.GetLogMetricRequest request, grpc::CallOptions options)
{
return CallInvoker.AsyncUnaryCall(__Method_GetLogMetric, null, options, request);
}
/// <summary>
/// Creates a logs-based metric.
/// </summary>
/// <param name="request">The request to send to the server.</param>
/// <param name="headers">The initial metadata to send with the call. This parameter is optional.</param>
/// <param name="deadline">An optional deadline for the call. The call will be cancelled if deadline is hit.</param>
/// <param name="cancellationToken">An optional token for canceling the call.</param>
/// <returns>The response received from the server.</returns>
public virtual global::Google.Cloud.Logging.V2.LogMetric CreateLogMetric(global::Google.Cloud.Logging.V2.CreateLogMetricRequest request, grpc::Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken))
{
return CreateLogMetric(request, new grpc::CallOptions(headers, deadline, cancellationToken));
}
/// <summary>
/// Creates a logs-based metric.
/// </summary>
/// <param name="request">The request to send to the server.</param>
/// <param name="options">The options for the call.</param>
/// <returns>The response received from the server.</returns>
public virtual global::Google.Cloud.Logging.V2.LogMetric CreateLogMetric(global::Google.Cloud.Logging.V2.CreateLogMetricRequest request, grpc::CallOptions options)
{
return CallInvoker.BlockingUnaryCall(__Method_CreateLogMetric, null, options, request);
}
/// <summary>
/// Creates a logs-based metric.
/// </summary>
/// <param name="request">The request to send to the server.</param>
/// <param name="headers">The initial metadata to send with the call. This parameter is optional.</param>
/// <param name="deadline">An optional deadline for the call. The call will be cancelled if deadline is hit.</param>
/// <param name="cancellationToken">An optional token for canceling the call.</param>
/// <returns>The call object.</returns>
public virtual grpc::AsyncUnaryCall<global::Google.Cloud.Logging.V2.LogMetric> CreateLogMetricAsync(global::Google.Cloud.Logging.V2.CreateLogMetricRequest request, grpc::Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken))
{
return CreateLogMetricAsync(request, new grpc::CallOptions(headers, deadline, cancellationToken));
}
/// <summary>
/// Creates a logs-based metric.
/// </summary>
/// <param name="request">The request to send to the server.</param>
/// <param name="options">The options for the call.</param>
/// <returns>The call object.</returns>
public virtual grpc::AsyncUnaryCall<global::Google.Cloud.Logging.V2.LogMetric> CreateLogMetricAsync(global::Google.Cloud.Logging.V2.CreateLogMetricRequest request, grpc::CallOptions options)
{
return CallInvoker.AsyncUnaryCall(__Method_CreateLogMetric, null, options, request);
}
/// <summary>
/// Creates or updates a logs-based metric.
/// </summary>
/// <param name="request">The request to send to the server.</param>
/// <param name="headers">The initial metadata to send with the call. This parameter is optional.</param>
/// <param name="deadline">An optional deadline for the call. The call will be cancelled if deadline is hit.</param>
/// <param name="cancellationToken">An optional token for canceling the call.</param>
/// <returns>The response received from the server.</returns>
public virtual global::Google.Cloud.Logging.V2.LogMetric UpdateLogMetric(global::Google.Cloud.Logging.V2.UpdateLogMetricRequest request, grpc::Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken))
{
return UpdateLogMetric(request, new grpc::CallOptions(headers, deadline, cancellationToken));
}
/// <summary>
/// Creates or updates a logs-based metric.
/// </summary>
/// <param name="request">The request to send to the server.</param>
/// <param name="options">The options for the call.</param>
/// <returns>The response received from the server.</returns>
public virtual global::Google.Cloud.Logging.V2.LogMetric UpdateLogMetric(global::Google.Cloud.Logging.V2.UpdateLogMetricRequest request, grpc::CallOptions options)
{
return CallInvoker.BlockingUnaryCall(__Method_UpdateLogMetric, null, options, request);
}
/// <summary>
/// Creates or updates a logs-based metric.
/// </summary>
/// <param name="request">The request to send to the server.</param>
/// <param name="headers">The initial metadata to send with the call. This parameter is optional.</param>
/// <param name="deadline">An optional deadline for the call. The call will be cancelled if deadline is hit.</param>
/// <param name="cancellationToken">An optional token for canceling the call.</param>
/// <returns>The call object.</returns>
public virtual grpc::AsyncUnaryCall<global::Google.Cloud.Logging.V2.LogMetric> UpdateLogMetricAsync(global::Google.Cloud.Logging.V2.UpdateLogMetricRequest request, grpc::Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken))
{
return UpdateLogMetricAsync(request, new grpc::CallOptions(headers, deadline, cancellationToken));
}
/// <summary>
/// Creates or updates a logs-based metric.
/// </summary>
/// <param name="request">The request to send to the server.</param>
/// <param name="options">The options for the call.</param>
/// <returns>The call object.</returns>
public virtual grpc::AsyncUnaryCall<global::Google.Cloud.Logging.V2.LogMetric> UpdateLogMetricAsync(global::Google.Cloud.Logging.V2.UpdateLogMetricRequest request, grpc::CallOptions options)
{
return CallInvoker.AsyncUnaryCall(__Method_UpdateLogMetric, null, options, request);
}
/// <summary>
/// Deletes a logs-based metric.
/// </summary>
/// <param name="request">The request to send to the server.</param>
/// <param name="headers">The initial metadata to send with the call. This parameter is optional.</param>
/// <param name="deadline">An optional deadline for the call. The call will be cancelled if deadline is hit.</param>
/// <param name="cancellationToken">An optional token for canceling the call.</param>
/// <returns>The response received from the server.</returns>
public virtual global::Google.Protobuf.WellKnownTypes.Empty DeleteLogMetric(global::Google.Cloud.Logging.V2.DeleteLogMetricRequest request, grpc::Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken))
{
return DeleteLogMetric(request, new grpc::CallOptions(headers, deadline, cancellationToken));
}
/// <summary>
/// Deletes a logs-based metric.
/// </summary>
/// <param name="request">The request to send to the server.</param>
/// <param name="options">The options for the call.</param>
/// <returns>The response received from the server.</returns>
public virtual global::Google.Protobuf.WellKnownTypes.Empty DeleteLogMetric(global::Google.Cloud.Logging.V2.DeleteLogMetricRequest request, grpc::CallOptions options)
{
return CallInvoker.BlockingUnaryCall(__Method_DeleteLogMetric, null, options, request);
}
/// <summary>
/// Deletes a logs-based metric.
/// </summary>
/// <param name="request">The request to send to the server.</param>
/// <param name="headers">The initial metadata to send with the call. This parameter is optional.</param>
/// <param name="deadline">An optional deadline for the call. The call will be cancelled if deadline is hit.</param>
/// <param name="cancellationToken">An optional token for canceling the call.</param>
/// <returns>The call object.</returns>
public virtual grpc::AsyncUnaryCall<global::Google.Protobuf.WellKnownTypes.Empty> DeleteLogMetricAsync(global::Google.Cloud.Logging.V2.DeleteLogMetricRequest request, grpc::Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken))
{
return DeleteLogMetricAsync(request, new grpc::CallOptions(headers, deadline, cancellationToken));
}
/// <summary>
/// Deletes a logs-based metric.
/// </summary>
/// <param name="request">The request to send to the server.</param>
/// <param name="options">The options for the call.</param>
/// <returns>The call object.</returns>
public virtual grpc::AsyncUnaryCall<global::Google.Protobuf.WellKnownTypes.Empty> DeleteLogMetricAsync(global::Google.Cloud.Logging.V2.DeleteLogMetricRequest request, grpc::CallOptions options)
{
return CallInvoker.AsyncUnaryCall(__Method_DeleteLogMetric, null, options, request);
}
/// <summary>Creates a new instance of client from given <c>ClientBaseConfiguration</c>.</summary>
protected override MetricsServiceV2Client NewInstance(ClientBaseConfiguration configuration)
{
return new MetricsServiceV2Client(configuration);
}
}
/// <summary>Creates service definition that can be registered with a server</summary>
/// <param name="serviceImpl">An object implementing the server-side handling logic.</param>
public static grpc::ServerServiceDefinition BindService(MetricsServiceV2Base serviceImpl)
{
return grpc::ServerServiceDefinition.CreateBuilder()
.AddMethod(__Method_ListLogMetrics, serviceImpl.ListLogMetrics)
.AddMethod(__Method_GetLogMetric, serviceImpl.GetLogMetric)
.AddMethod(__Method_CreateLogMetric, serviceImpl.CreateLogMetric)
.AddMethod(__Method_UpdateLogMetric, serviceImpl.UpdateLogMetric)
.AddMethod(__Method_DeleteLogMetric, serviceImpl.DeleteLogMetric).Build();
}
}
}
#endregion
| 65.405868 | 304 | 0.716235 | [
"Apache-2.0"
] | chrisdunelm/gcloud-dotnet | apis/Google.Cloud.Logging.V2/Google.Cloud.Logging.V2/LoggingMetricsGrpc.cs | 26,751 | C# |
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Threading.Tasks;
using System.Windows;
namespace SystemReinstallTool
{
/// <summary>
/// Interaction logic for App.xaml
/// </summary>
public partial class App : Application
{
}
}
| 18.5 | 42 | 0.711712 | [
"MIT"
] | Henry-T/LFTool | SystemReinstallTool/SystemReinstallTool/App.xaml.cs | 335 | C# |
using System.Collections.Generic;
using System.Linq;
namespace Gybs.Extensions
{
/// <summary>
/// <see cref="System.Linq"/> related extensions.
/// </summary>
public static class LinqExtensions
{
/// <summary>
/// Casts the <see cref="List{T}"/> type to the <see cref="IList{T}"/> type.
/// </summary>
/// <typeparam name="T">The type.</typeparam>
/// <param name="list">The list.</param>
/// <returns>The <see cref="IReadOnlyCollection{T}"/>.</returns>
public static IReadOnlyCollection<T> CastToReadOnly<T>(this List<T> list) => list;
/// <summary>
/// Casts the array to the <see cref="IReadOnlyList{T}"/> type.
/// </summary>
/// <typeparam name="T">The type.</typeparam>
/// <param name="array">The array..</param>
/// <returns>The <see cref="IReadOnlyCollection{T}"/>.</returns>
public static IReadOnlyCollection<T> CastToReadOnly<T>(this T[] array) => array;
/// <summary>
/// Flattens the enumerable of enumerables into a single enumerable.
/// </summary>
/// <typeparam name="T">The type.</typeparam>
/// <param name="enumerable">The enumerables.</param>
/// <returns>Enumerable.</returns>
public static IEnumerable<T> Flatten<T>(this IEnumerable<IEnumerable<T>> enumerable) => enumerable.SelectMany(e => e);
}
}
| 39.416667 | 126 | 0.592671 | [
"MIT"
] | wk0w/gybs | src/Gybs/Extensions/LinqExtensions.cs | 1,421 | C# |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class MenuController : MonoBehaviour
{
public GameObject newGame;
public GameObject character;
public GameObject options;
public GameObject credits;
private GameController gameController;
void Awake()
{
gameController = FindObjectOfType<GameController>();
}
private void Start()
{
if (gameController.GetLevelLoader() != null)
{
if (gameController.GetLevelLoader().isLoading())
{
gameController.GetLevelLoader().removeLoadingLayer(true);
}
}
showStartMenu();
}
public void quit()
{
Debug.Log("Exit application");
Application.Quit();
}
public void buttonClickedBehavior(string buttonText)
{
if (buttonText == "PLAY")
{
playGame();
}
if (buttonText == "OPTIONS")
{
showOptions();
}
if (buttonText == "CHARACTER")
{
showCharacterOptions();
}
if (buttonText == "QUESTION")
{
showCredit();
}
}
public void playGame()
{
gameController.GetLevelLoader().LoadLevel("Dungeon");
}
public void showStartMenu()
{
newGame.SetActive(true);
character.SetActive(true);
options.SetActive(true);
credits.SetActive(true);
}
public void showOptions()
{
}
public void showCharacterOptions()
{
}
public void showCredit()
{
}
}
| 19.678161 | 74 | 0.526285 | [
"MIT"
] | fedexu/NeverEndDungeon | Assets/scripts/UI/MenuController.cs | 1,714 | C# |
namespace GitVersion
{
using Configuration.Init.Wizard;
using GitVersion.Helpers;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
public class ConfigurationProvider
{
internal const string DefaultTagPrefix = "[vV]";
public const string DefaultConfigFileName = "GitVersion.yml";
public const string ObsoleteConfigFileName = "GitVersionConfig.yaml";
public const string ReleaseBranchRegex = "^releases?[/-]";
public const string FeatureBranchRegex = "^features?[/-]";
public const string PullRequestRegex = @"^(pull|pull\-requests|pr)[/-]";
public const string HotfixBranchRegex = "^hotfix(es)?[/-]";
public const string SupportBranchRegex = "^support[/-]";
public const string DevelopBranchRegex = "^dev(elop)?(ment)?$";
public const string MasterBranchRegex = "^master$";
public const string MasterBranchKey = "master";
public const string ReleaseBranchKey = "release";
public const string FeatureBranchKey = "feature";
public const string PullRequestBranchKey = "pull-request";
public const string HotfixBranchKey = "hotfix";
public const string SupportBranchKey = "support";
public const string DevelopBranchKey = "develop";
public static Dictionary<string, int> DefaultPreReleaseWeight =
new Dictionary<string, int>
{
{ DevelopBranchRegex, 0 },
{ HotfixBranchRegex, 30000 },
{ ReleaseBranchRegex, 30000 },
{ FeatureBranchRegex, 30000 },
{ PullRequestRegex, 30000 },
{ SupportBranchRegex, 55000 },
{ MasterBranchRegex, 55000 }
};
private const IncrementStrategy DefaultIncrementStrategy = IncrementStrategy.Inherit;
public static Config Provide(GitPreparer gitPreparer, IFileSystem fileSystem, bool applyDefaults = true, Config overrideConfig = null)
{
var workingDirectory = gitPreparer.WorkingDirectory;
var projectRootDirectory = gitPreparer.GetProjectRootDirectory();
if (HasConfigFileAt(workingDirectory, fileSystem))
{
return Provide(workingDirectory, fileSystem, applyDefaults, overrideConfig);
}
return Provide(projectRootDirectory, fileSystem, applyDefaults, overrideConfig);
}
public static string SelectConfigFilePath(GitPreparer gitPreparer, IFileSystem fileSystem)
{
var workingDirectory = gitPreparer.WorkingDirectory;
var projectRootDirectory = gitPreparer.GetProjectRootDirectory();
if (HasConfigFileAt(workingDirectory, fileSystem))
{
return GetConfigFilePath(workingDirectory, fileSystem);
}
return GetConfigFilePath(projectRootDirectory, fileSystem);
}
public static Config Provide(string workingDirectory, IFileSystem fileSystem, bool applyDefaults = true, Config overrideConfig = null)
{
var readConfig = ReadConfig(workingDirectory, fileSystem);
VerifyConfiguration(readConfig);
if (applyDefaults)
ApplyDefaultsTo(readConfig);
if (null != overrideConfig)
ApplyOverridesTo(readConfig, overrideConfig);
return readConfig;
}
static void VerifyConfiguration(Config readConfig)
{
// Verify no branches are set to mainline mode
if (readConfig.Branches.Any(b => b.Value.VersioningMode == VersioningMode.Mainline))
{
throw new GitVersionConfigurationException(@"Mainline mode only works at the repository level, a single branch cannot be put into mainline mode
This is because mainline mode treats your entire git repository as an event source with each merge into the 'mainline' incrementing the version.
If the docs do not help you decide on the mode open an issue to discuss what you are trying to do.");
}
}
public static void ApplyDefaultsTo(Config config)
{
config.AssemblyVersioningScheme = config.AssemblyVersioningScheme ?? AssemblyVersioningScheme.MajorMinorPatch;
config.AssemblyFileVersioningScheme = config.AssemblyFileVersioningScheme ?? AssemblyFileVersioningScheme.MajorMinorPatch;
config.AssemblyInformationalFormat = config.AssemblyInformationalFormat;
config.AssemblyVersioningFormat = config.AssemblyVersioningFormat;
config.AssemblyFileVersioningFormat = config.AssemblyFileVersioningFormat;
config.TagPrefix = config.TagPrefix ?? DefaultTagPrefix;
config.VersioningMode = config.VersioningMode ?? VersioningMode.ContinuousDelivery;
config.ContinuousDeploymentFallbackTag = config.ContinuousDeploymentFallbackTag ?? "ci";
config.MajorVersionBumpMessage = config.MajorVersionBumpMessage ?? IncrementStrategyFinder.DefaultMajorPattern;
config.MinorVersionBumpMessage = config.MinorVersionBumpMessage ?? IncrementStrategyFinder.DefaultMinorPattern;
config.PatchVersionBumpMessage = config.PatchVersionBumpMessage ?? IncrementStrategyFinder.DefaultPatchPattern;
config.NoBumpMessage = config.NoBumpMessage ?? IncrementStrategyFinder.DefaultNoBumpPattern;
config.CommitMessageIncrementing = config.CommitMessageIncrementing ?? CommitMessageIncrementMode.Enabled;
config.LegacySemVerPadding = config.LegacySemVerPadding ?? 4;
config.BuildMetaDataPadding = config.BuildMetaDataPadding ?? 4;
config.CommitsSinceVersionSourcePadding = config.CommitsSinceVersionSourcePadding ?? 4;
config.CommitDateFormat = config.CommitDateFormat ?? "yyyy-MM-dd";
var configBranches = config.Branches.ToList();
ApplyBranchDefaults(config,
GetOrCreateBranchDefaults(config, DevelopBranchKey),
DevelopBranchRegex,
new List<string>(),
defaultTag: "alpha",
defaultIncrementStrategy: IncrementStrategy.Minor,
defaultVersioningMode: config.VersioningMode == VersioningMode.Mainline? VersioningMode.Mainline : VersioningMode.ContinuousDeployment,
defaultTrackMergeTarget: true,
tracksReleaseBranches: true);
ApplyBranchDefaults(config,
GetOrCreateBranchDefaults(config, MasterBranchKey),
MasterBranchRegex,
new List<string> { "develop", "release" },
defaultTag: string.Empty,
defaultPreventIncrement: true,
defaultIncrementStrategy: IncrementStrategy.Patch,
isMainline: true);
ApplyBranchDefaults(config,
GetOrCreateBranchDefaults(config, ReleaseBranchKey),
ReleaseBranchRegex,
new List<string> { "develop", "master", "support", "release" },
defaultTag: "beta",
defaultPreventIncrement: true,
defaultIncrementStrategy: IncrementStrategy.Patch,
isReleaseBranch: true);
ApplyBranchDefaults(config,
GetOrCreateBranchDefaults(config, FeatureBranchKey),
FeatureBranchRegex,
new List<string> { "develop", "master", "release", "feature", "support", "hotfix" },
defaultIncrementStrategy: IncrementStrategy.Inherit);
ApplyBranchDefaults(config,
GetOrCreateBranchDefaults(config, PullRequestBranchKey),
PullRequestRegex,
new List<string> { "develop", "master", "release", "feature", "support", "hotfix" },
defaultTag: "PullRequest",
defaultTagNumberPattern: @"[/-](?<number>\d+)",
defaultIncrementStrategy: IncrementStrategy.Inherit);
ApplyBranchDefaults(config,
GetOrCreateBranchDefaults(config, HotfixBranchKey),
HotfixBranchRegex,
new List<string> { "develop", "master", "support" },
defaultTag: "beta",
defaultIncrementStrategy: IncrementStrategy.Patch);
ApplyBranchDefaults(config,
GetOrCreateBranchDefaults(config, SupportBranchKey),
SupportBranchRegex,
new List<string> { "master" },
defaultTag: string.Empty,
defaultPreventIncrement: true,
defaultIncrementStrategy: IncrementStrategy.Patch,
isMainline: true);
// Any user defined branches should have other values defaulted after known branches filled in.
// This allows users to override any of the value.
foreach (var branchConfig in configBranches)
{
var regex = branchConfig.Value.Regex;
if (regex == null)
{
throw new GitVersionConfigurationException($"Branch configuration '{branchConfig.Key}' is missing required configuration 'regex'\n\n" +
"See http://gitversion.readthedocs.io/en/latest/configuration/ for more info");
}
var sourceBranches = branchConfig.Value.SourceBranches;
if (sourceBranches == null)
{
throw new GitVersionConfigurationException($"Branch configuration '{branchConfig.Key}' is missing required configuration 'source-branches'\n\n" +
"See http://gitversion.readthedocs.io/en/latest/configuration/ for more info");
}
ApplyBranchDefaults(config, branchConfig.Value, regex, sourceBranches);
}
// This is a second pass to add additional sources, it has to be another pass to prevent ordering issues
foreach (var branchConfig in configBranches)
{
if (branchConfig.Value.IsSourceBranchFor == null) continue;
foreach (var isSourceBranch in branchConfig.Value.IsSourceBranchFor)
{
config.Branches[isSourceBranch].SourceBranches.Add(branchConfig.Key);
}
}
}
static void ApplyOverridesTo(Config config, Config overrideConfig)
{
config.TagPrefix = string.IsNullOrWhiteSpace(overrideConfig.TagPrefix) ? config.TagPrefix : overrideConfig.TagPrefix;
}
static BranchConfig GetOrCreateBranchDefaults(Config config, string branchKey)
{
if (!config.Branches.ContainsKey(branchKey))
{
var branchConfig = new BranchConfig {Name = branchKey};
config.Branches.Add(branchKey, branchConfig);
return branchConfig;
}
return config.Branches[branchKey];
}
public static void ApplyBranchDefaults(Config config,
BranchConfig branchConfig,
string branchRegex,
List<string> sourceBranches,
string defaultTag = "useBranchName",
IncrementStrategy? defaultIncrementStrategy = null, // Looked up from main config
bool defaultPreventIncrement = false,
VersioningMode? defaultVersioningMode = null, // Looked up from main config
bool defaultTrackMergeTarget = false,
string defaultTagNumberPattern = null,
bool tracksReleaseBranches = false,
bool isReleaseBranch = false,
bool isMainline = false)
{
branchConfig.Regex = string.IsNullOrEmpty(branchConfig.Regex) ? branchRegex : branchConfig.Regex;
branchConfig.SourceBranches = branchConfig.SourceBranches == null || !branchConfig.SourceBranches.Any()
? sourceBranches : branchConfig.SourceBranches;
branchConfig.Tag = branchConfig.Tag ?? defaultTag;
branchConfig.TagNumberPattern = branchConfig.TagNumberPattern ?? defaultTagNumberPattern;
branchConfig.Increment = branchConfig.Increment ?? defaultIncrementStrategy ?? config.Increment ?? DefaultIncrementStrategy;
branchConfig.PreventIncrementOfMergedBranchVersion = branchConfig.PreventIncrementOfMergedBranchVersion ?? defaultPreventIncrement;
branchConfig.TrackMergeTarget = branchConfig.TrackMergeTarget ?? defaultTrackMergeTarget;
branchConfig.VersioningMode = branchConfig.VersioningMode ?? defaultVersioningMode ?? config.VersioningMode;
branchConfig.TracksReleaseBranches = branchConfig.TracksReleaseBranches ?? tracksReleaseBranches;
branchConfig.IsReleaseBranch = branchConfig.IsReleaseBranch ?? isReleaseBranch;
branchConfig.IsMainline = branchConfig.IsMainline ?? isMainline;
int defaultPreReleaseNumber = 0;
DefaultPreReleaseWeight.TryGetValue(branchRegex, out defaultPreReleaseNumber);
branchConfig.PreReleaseWeight = branchConfig.PreReleaseWeight ?? defaultPreReleaseNumber;
}
static Config ReadConfig(string workingDirectory, IFileSystem fileSystem)
{
var configFilePath = GetConfigFilePath(workingDirectory, fileSystem);
if (fileSystem.Exists(configFilePath))
{
var readAllText = fileSystem.ReadAllText(configFilePath);
LegacyConfigNotifier.Notify(new StringReader(readAllText));
return ConfigSerialiser.Read(new StringReader(readAllText));
}
return new Config();
}
public static string GetEffectiveConfigAsString(string workingDirectory, IFileSystem fileSystem)
{
var config = Provide(workingDirectory, fileSystem);
var stringBuilder = new StringBuilder();
using (var stream = new StringWriter(stringBuilder))
{
ConfigSerialiser.Write(config, stream);
stream.Flush();
}
return stringBuilder.ToString();
}
public static void Verify(GitPreparer gitPreparer, IFileSystem fileSystem)
{
if (!string.IsNullOrWhiteSpace(gitPreparer.TargetUrl))
{
// Assuming this is a dynamic repository. At this stage it's unsure whether we have
// any .git info so we need to skip verification
return;
}
var workingDirectory = gitPreparer.WorkingDirectory;
var projectRootDirectory = gitPreparer.GetProjectRootDirectory();
Verify(workingDirectory, projectRootDirectory, fileSystem);
}
public static void Verify(string workingDirectory, string projectRootDirectory, IFileSystem fileSystem)
{
if (fileSystem.PathsEqual(workingDirectory, projectRootDirectory))
{
WarnAboutObsoleteConfigFile(workingDirectory, fileSystem);
return;
}
WarnAboutObsoleteConfigFile(workingDirectory, fileSystem);
WarnAboutObsoleteConfigFile(projectRootDirectory, fileSystem);
WarnAboutAmbiguousConfigFileSelection(workingDirectory, projectRootDirectory, fileSystem);
}
static void WarnAboutAmbiguousConfigFileSelection(string workingDirectory, string projectRootDirectory, IFileSystem fileSystem)
{
var workingConfigFile = GetConfigFilePath(workingDirectory, fileSystem);
var projectRootConfigFile = GetConfigFilePath(projectRootDirectory, fileSystem);
bool hasConfigInWorkingDirectory = fileSystem.Exists(workingConfigFile);
bool hasConfigInProjectRootDirectory = fileSystem.Exists(projectRootConfigFile);
if (hasConfigInProjectRootDirectory && hasConfigInWorkingDirectory)
{
throw new WarningException(string.Format("Ambiguous config file selection from '{0}' and '{1}'", workingConfigFile, projectRootConfigFile));
}
}
static string GetConfigFilePath(string workingDirectory, IFileSystem fileSystem)
{
var ymlPath = Path.Combine(workingDirectory, DefaultConfigFileName);
if (fileSystem.Exists(ymlPath))
{
return ymlPath;
}
var deprecatedPath = Path.Combine(workingDirectory, ObsoleteConfigFileName);
if (fileSystem.Exists(deprecatedPath))
{
return deprecatedPath;
}
return ymlPath;
}
static bool HasConfigFileAt(string workingDirectory, IFileSystem fileSystem)
{
var defaultConfigFilePath = Path.Combine(workingDirectory, DefaultConfigFileName);
if (fileSystem.Exists(defaultConfigFilePath))
{
return true;
}
var deprecatedConfigFilePath = Path.Combine(workingDirectory, ObsoleteConfigFileName);
if (fileSystem.Exists(deprecatedConfigFilePath))
{
return true;
}
return false;
}
static void WarnAboutObsoleteConfigFile(string workingDirectory, IFileSystem fileSystem)
{
var deprecatedConfigFilePath = Path.Combine(workingDirectory, ObsoleteConfigFileName);
if (!fileSystem.Exists(deprecatedConfigFilePath))
{
return;
}
var defaultConfigFilePath = Path.Combine(workingDirectory, DefaultConfigFileName);
if (fileSystem.Exists(defaultConfigFilePath))
{
Logger.WriteWarning(string.Format("Ambiguous config files at '{0}': '{1}' (deprecated) and '{2}'. Will be used '{2}'", workingDirectory, ObsoleteConfigFileName, DefaultConfigFileName));
return;
}
Logger.WriteWarning(string.Format("'{0}' is deprecated, use '{1}' instead.", deprecatedConfigFilePath, DefaultConfigFileName));
}
public static void Init(string workingDirectory, IFileSystem fileSystem, IConsole console)
{
var configFilePath = GetConfigFilePath(workingDirectory, fileSystem);
var currentConfiguration = Provide(workingDirectory, fileSystem, applyDefaults: false);
var config = new ConfigInitWizard(console, fileSystem).Run(currentConfiguration, workingDirectory);
if (config == null) return;
using (var stream = fileSystem.OpenWrite(configFilePath))
using (var writer = new StreamWriter(stream))
{
Logger.WriteInfo("Saving config file");
ConfigSerialiser.Write(config, writer);
stream.Flush();
}
}
}
}
| 49.909561 | 202 | 0.632617 | [
"MIT"
] | SeppPenner/GitVersion | src/GitVersionCore/Configuration/ConfigurationProvider.cs | 18,929 | C# |
using System.Threading.Tasks;
using Arbor.Hypermedia;
using MediatR;
using Microsoft.AspNetCore.Mvc;
using Milou.Deployer.Web.Agent;
using Milou.Deployer.Web.Core.Agents.Commands;
using Milou.Deployer.Web.IisHost.Controllers;
namespace Milou.Deployer.Web.IisHost.Areas.Agents
{
public class DisableAgentController : BaseApiController
{
//[ValidateAntiForgeryToken]
[Microsoft.AspNetCore.Mvc.HttpPost]
[Route(Core.Agents.Commands.DisableAgent.RouteTemplate, Name = Core.Agents.Commands.DisableAgent.RouteName)]
public async Task<ActionResult> DisableAgent([FromRoute] AgentId agentId,
[FromServices] IMediator mediator)
{
var result = await mediator.Send(new DisableAgent(agentId));
return Ok(result);
}
}
} | 33.541667 | 116 | 0.719255 | [
"MIT"
] | niklaslundberg/milou.deployer | src/Milou.Deployer.Web.IisHost/Areas/Agents/DisableAgentController.cs | 807 | C# |
// based on the FNA SpriteBatch implementation by Ethan Lee: https://github.com/FNA-XNA/FNA
using System;
using System.Collections.Generic;
using System.Runtime.InteropServices;
using System.Text;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework;
using Nez.BitmapFonts;
using System.Runtime.CompilerServices;
using Nez.Textures;
namespace Nez
{
public class Batcher : GraphicsResource
{
public Matrix transformMatrix { get { return _transformMatrix; } }
#region variables
// Buffer objects used for actual drawing
DynamicVertexBuffer _vertexBuffer;
IndexBuffer _indexBuffer;
// Local data stored before buffering to GPU
VertexPositionColorTexture4[] _vertexInfo;
Texture2D[] _textureInfo;
// Default SpriteEffect
SpriteEffect _spriteEffect;
EffectPass _spriteEffectPass;
// Tracks Begin/End calls
bool _beginCalled;
// Keep render state for non-Immediate modes.
BlendState _blendState;
SamplerState _samplerState;
DepthStencilState _depthStencilState;
RasterizerState _rasterizerState;
bool _disableBatching;
// How many sprites are in the current batch?
int _numSprites;
// Matrix to be used when creating the projection matrix
Matrix _transformMatrix;
// Matrix used internally to calculate the cameras projection
Matrix _projectionMatrix;
// this is the calculated MatrixTransform parameter in sprite shaders
Matrix _matrixTransformMatrix;
// User-provided Effect, if applicable
Effect _customEffect;
#endregion
#region static variables and constants
const int MAX_SPRITES = 2048;
const int MAX_VERTICES = MAX_SPRITES * 4;
const int MAX_INDICES = MAX_SPRITES * 6;
// Used to calculate texture coordinates
static readonly float[] _cornerOffsetX = new float[] { 0.0f, 1.0f, 0.0f, 1.0f };
static readonly float[] _cornerOffsetY = new float[] { 0.0f, 0.0f, 1.0f, 1.0f };
static readonly short[] _indexData = generateIndexArray();
#endregion
public Batcher( GraphicsDevice graphicsDevice )
{
Assert.isTrue( graphicsDevice != null );
this.graphicsDevice = graphicsDevice;
_vertexInfo = new VertexPositionColorTexture4[MAX_SPRITES];
_textureInfo = new Texture2D[MAX_SPRITES];
_vertexBuffer = new DynamicVertexBuffer( graphicsDevice, typeof( VertexPositionColorTexture ), MAX_VERTICES, BufferUsage.WriteOnly );
_indexBuffer = new IndexBuffer( graphicsDevice, IndexElementSize.SixteenBits, MAX_INDICES, BufferUsage.WriteOnly );
_indexBuffer.SetData( _indexData );
_spriteEffect = new SpriteEffect();
_spriteEffectPass = _spriteEffect.CurrentTechnique.Passes[0];
_projectionMatrix = new Matrix(
0f, //(float)( 2.0 / (double)viewport.Width ) is the actual value we will use
0.0f,
0.0f,
0.0f,
0.0f,
0f, //(float)( -2.0 / (double)viewport.Height ) is the actual value we will use
0.0f,
0.0f,
0.0f,
0.0f,
1.0f,
0.0f,
-1.0f,
1.0f,
0.0f,
1.0f
);
}
protected override void Dispose( bool disposing )
{
if( !isDisposed && disposing )
{
_spriteEffect.Dispose();
_indexBuffer.Dispose();
_vertexBuffer.Dispose();
}
base.Dispose( disposing );
}
#region Public begin/end methods
public void begin()
{
begin( BlendState.AlphaBlend, Core.defaultSamplerState, DepthStencilState.None, RasterizerState.CullCounterClockwise, null, Matrix.Identity, false );
}
public void begin( Effect effect )
{
begin( BlendState.AlphaBlend, Core.defaultSamplerState, DepthStencilState.None, RasterizerState.CullCounterClockwise, effect, Matrix.Identity, false );
}
public void begin( Material material )
{
begin( material.blendState, material.samplerState, material.depthStencilState, RasterizerState.CullCounterClockwise, material.effect );
}
public void begin( Matrix transformationMatrix )
{
begin( BlendState.AlphaBlend, Core.defaultSamplerState, DepthStencilState.None, RasterizerState.CullCounterClockwise, null, transformationMatrix, false );
}
public void begin( BlendState blendState )
{
begin( blendState, Core.defaultSamplerState, DepthStencilState.None, RasterizerState.CullCounterClockwise, null, Matrix.Identity, false );
}
public void begin( Material material, Matrix transformationMatrix )
{
begin( material.blendState, material.samplerState, material.depthStencilState, RasterizerState.CullCounterClockwise, material.effect, transformationMatrix, false );
}
public void begin( BlendState blendState, SamplerState samplerState, DepthStencilState depthStencilState, RasterizerState rasterizerState )
{
begin(
blendState,
samplerState,
depthStencilState,
rasterizerState,
null,
Matrix.Identity,
false
);
}
public void begin( BlendState blendState, SamplerState samplerState, DepthStencilState depthStencilState, RasterizerState rasterizerState, Effect effect )
{
begin(
blendState,
samplerState,
depthStencilState,
rasterizerState,
effect,
Matrix.Identity,
false
);
}
public void begin( BlendState blendState, SamplerState samplerState, DepthStencilState depthStencilState, RasterizerState rasterizerState,
Effect effect, Matrix transformationMatrix )
{
begin(
blendState,
samplerState,
depthStencilState,
rasterizerState,
effect,
transformationMatrix,
false
);
}
public void begin( BlendState blendState, SamplerState samplerState, DepthStencilState depthStencilState, RasterizerState rasterizerState,
Effect effect, Matrix transformationMatrix, bool disableBatching )
{
Assert.isFalse( _beginCalled, "Begin has been called before calling End after the last call to Begin. Begin cannot be called again until End has been successfully called." );
_beginCalled = true;
_blendState = blendState ?? BlendState.AlphaBlend;
_samplerState = samplerState ?? Core.defaultSamplerState;
_depthStencilState = depthStencilState ?? DepthStencilState.None;
_rasterizerState = rasterizerState ?? RasterizerState.CullCounterClockwise;
_customEffect = effect;
_transformMatrix = transformationMatrix;
_disableBatching = disableBatching;
if( _disableBatching )
prepRenderState();
}
public void end()
{
Assert.isTrue( _beginCalled, "End was called, but Begin has not yet been called. You must call Begin successfully before you can call End." );
_beginCalled = false;
if( !_disableBatching )
flushBatch();
_customEffect = null;
}
#endregion
#region Public draw methods
public void draw( Texture2D texture, Vector2 position )
{
checkBegin();
pushSprite( texture, null, position.X, position.Y, 1.0f, 1.0f,
Color.White, Vector2.Zero, 0.0f, 0.0f, 0, false, 0, 0, 0, 0 );
}
public void draw( Texture2D texture, Vector2 position, Color color )
{
checkBegin();
pushSprite( texture, null, position.X, position.Y, 1.0f, 1.0f,
color, Vector2.Zero, 0.0f, 0.0f, 0, false, 0, 0, 0, 0 );
}
public void draw( Texture2D texture, Rectangle destinationRectangle )
{
checkBegin();
pushSprite( texture, null, destinationRectangle.X, destinationRectangle.Y, destinationRectangle.Width, destinationRectangle.Height,
Color.White, Vector2.Zero, 0.0f, 0.0f, 0, true, 0, 0, 0, 0 );
}
public void draw( Texture2D texture, Rectangle destinationRectangle, Color color )
{
checkBegin();
pushSprite( texture, null, destinationRectangle.X, destinationRectangle.Y, destinationRectangle.Width, destinationRectangle.Height,
color, Vector2.Zero, 0.0f, 0.0f, 0, true, 0, 0, 0, 0 );
}
public void draw( Texture2D texture, Rectangle destinationRectangle, Rectangle? sourceRectangle, Color color )
{
checkBegin();
pushSprite( texture, sourceRectangle, destinationRectangle.X, destinationRectangle.Y, destinationRectangle.Width, destinationRectangle.Height,
color, Vector2.Zero, 0.0f, 0.0f, 0, true, 0, 0, 0, 0 );
}
public void draw( Texture2D texture, Rectangle destinationRectangle, Rectangle? sourceRectangle, Color color, SpriteEffects effects )
{
checkBegin();
pushSprite( texture, sourceRectangle, destinationRectangle.X, destinationRectangle.Y, destinationRectangle.Width, destinationRectangle.Height,
color, Vector2.Zero, 0.0f, 0.0f, (byte)( effects & (SpriteEffects)0x03 ), true, 0, 0, 0, 0 );
}
public void draw(
Texture2D texture,
Rectangle destinationRectangle,
Rectangle? sourceRectangle,
Color color,
float rotation,
SpriteEffects effects,
float layerDepth,
float skewTopX, float skewBottomX, float skewLeftY, float skewRightY
)
{
checkBegin();
pushSprite(
texture,
sourceRectangle,
destinationRectangle.X,
destinationRectangle.Y,
destinationRectangle.Width,
destinationRectangle.Height,
color,
Vector2.Zero,
rotation,
layerDepth,
(byte)( effects & (SpriteEffects)0x03 ),
true,
skewTopX, skewBottomX, skewLeftY, skewRightY
);
}
public void draw( Texture2D texture, Vector2 position, Rectangle? sourceRectangle, Color color )
{
checkBegin();
pushSprite(
texture,
sourceRectangle,
position.X,
position.Y,
1.0f,
1.0f,
color,
Vector2.Zero,
0.0f,
0.0f,
0,
false,
0, 0, 0, 0
);
}
public void draw(
Texture2D texture,
Vector2 position,
Rectangle? sourceRectangle,
Color color,
float rotation,
Vector2 origin,
float scale,
SpriteEffects effects,
float layerDepth
)
{
checkBegin();
pushSprite(
texture,
sourceRectangle,
position.X,
position.Y,
scale,
scale,
color,
origin,
rotation,
layerDepth,
(byte)( effects & (SpriteEffects)0x03 ),
false,
0, 0, 0, 0
);
}
public void draw(
Subtexture subtexture,
Vector2 position,
Color color,
float rotation,
Vector2 origin,
float scale,
SpriteEffects effects,
float layerDepth
)
{
checkBegin();
pushSprite(
subtexture,
position.X,
position.Y,
scale,
scale,
color,
origin,
rotation,
layerDepth,
(byte)( effects & (SpriteEffects)0x03 ),
0, 0, 0, 0
);
}
public void draw(
Texture2D texture,
Vector2 position,
Rectangle? sourceRectangle,
Color color,
float rotation,
Vector2 origin,
Vector2 scale,
SpriteEffects effects,
float layerDepth
)
{
checkBegin();
pushSprite(
texture,
sourceRectangle,
position.X,
position.Y,
scale.X,
scale.Y,
color,
origin,
rotation,
layerDepth,
(byte)( effects & (SpriteEffects)0x03 ),
false,
0, 0, 0, 0
);
}
public void draw(
Subtexture subtexture,
Vector2 position,
Color color,
float rotation,
Vector2 origin,
Vector2 scale,
SpriteEffects effects,
float layerDepth
)
{
checkBegin();
pushSprite(
subtexture,
position.X,
position.Y,
scale.X,
scale.Y,
color,
origin,
rotation,
layerDepth,
(byte)( effects & (SpriteEffects)0x03 ),
0, 0, 0, 0
);
}
public void draw(
Texture2D texture,
Vector2 position,
Rectangle? sourceRectangle,
Color color,
float rotation,
Vector2 origin,
Vector2 scale,
SpriteEffects effects,
float layerDepth,
float skewTopX, float skewBottomX, float skewLeftY, float skewRightY
)
{
checkBegin();
pushSprite(
texture,
sourceRectangle,
position.X,
position.Y,
scale.X,
scale.Y,
color,
origin,
rotation,
layerDepth,
(byte)( effects & (SpriteEffects)0x03 ),
false,
skewTopX, skewBottomX, skewLeftY, skewRightY
);
}
public void draw(
Texture2D texture,
Rectangle destinationRectangle,
Rectangle? sourceRectangle,
Color color,
float rotation,
Vector2 origin,
SpriteEffects effects,
float layerDepth
)
{
checkBegin();
pushSprite(
texture,
sourceRectangle,
destinationRectangle.X,
destinationRectangle.Y,
destinationRectangle.Width,
destinationRectangle.Height,
color,
origin,
rotation,
layerDepth,
(byte)( effects & (SpriteEffects)0x03 ),
true,
0, 0, 0, 0
);
}
/// <summary>
/// direct access to setting vert positions, UVs and colors. The order of elements is top-left, top-right, bottom-left, bottom-right
/// </summary>
/// <returns>The raw.</returns>
/// <param name="texture">Texture.</param>
/// <param name="verts">Verts.</param>
/// <param name="textureCoords">Texture coords.</param>
/// <param name="colors">Colors.</param>
public void drawRaw( Texture2D texture, Vector3[] verts, Vector2[] textureCoords, Color[] colors )
{
Assert.isTrue( verts.Length == 4, "there must be only 4 verts" );
Assert.isTrue( textureCoords.Length == 4, "there must be only 4 texture coordinates" );
Assert.isTrue( colors.Length == 4, "there must be only 4 colors" );
// we're out of space, flush
if( _numSprites >= MAX_SPRITES )
flushBatch();
_vertexInfo[_numSprites].position0 = verts[0];
_vertexInfo[_numSprites].position1 = verts[1];
_vertexInfo[_numSprites].position2 = verts[2];
_vertexInfo[_numSprites].position3 = verts[3];
_vertexInfo[_numSprites].textureCoordinate0 = textureCoords[0];
_vertexInfo[_numSprites].textureCoordinate1 = textureCoords[1];
_vertexInfo[_numSprites].textureCoordinate2 = textureCoords[2];
_vertexInfo[_numSprites].textureCoordinate3 = textureCoords[3];
_vertexInfo[_numSprites].color0 = colors[0];
_vertexInfo[_numSprites].color1 = colors[1];
_vertexInfo[_numSprites].color2 = colors[2];
_vertexInfo[_numSprites].color3 = colors[3];
if( _disableBatching )
{
_vertexBuffer.SetData( 0, _vertexInfo, 0, 1, VertexPositionColorTexture4.realStride, SetDataOptions.None );
drawPrimitives( texture, 0, 1 );
}
else
{
_textureInfo[_numSprites] = texture;
_numSprites += 1;
}
}
/// <summary>
/// direct access to setting vert positions, UVs and colors. The order of elements is top-left, top-right, bottom-left, bottom-right
/// </summary>
/// <returns>The raw.</returns>
/// <param name="texture">Texture.</param>
/// <param name="verts">Verts.</param>
/// <param name="textureCoords">Texture coords.</param>
/// <param name="color">Color.</param>
public void drawRaw( Texture2D texture, Vector3[] verts, Vector2[] textureCoords, Color color )
{
Assert.isTrue( verts.Length == 4, "there must be only 4 verts" );
Assert.isTrue( textureCoords.Length == 4, "there must be only 4 texture coordinates" );
// we're out of space, flush
if( _numSprites >= MAX_SPRITES )
flushBatch();
_vertexInfo[_numSprites].position0 = verts[0];
_vertexInfo[_numSprites].position1 = verts[1];
_vertexInfo[_numSprites].position2 = verts[2];
_vertexInfo[_numSprites].position3 = verts[3];
_vertexInfo[_numSprites].textureCoordinate0 = textureCoords[0];
_vertexInfo[_numSprites].textureCoordinate1 = textureCoords[1];
_vertexInfo[_numSprites].textureCoordinate2 = textureCoords[2];
_vertexInfo[_numSprites].textureCoordinate3 = textureCoords[3];
_vertexInfo[_numSprites].color0 = color;
_vertexInfo[_numSprites].color1 = color;
_vertexInfo[_numSprites].color2 = color;
_vertexInfo[_numSprites].color3 = color;
if( _disableBatching )
{
_vertexBuffer.SetData( 0, _vertexInfo, 0, 1, VertexPositionColorTexture4.realStride, SetDataOptions.None );
drawPrimitives( texture, 0, 1 );
}
else
{
_textureInfo[_numSprites] = texture;
_numSprites += 1;
}
}
#endregion
[System.Obsolete( "SpriteFont is too locked down to use directly. Wrap it in a NezSpriteFont" )]
public void DrawString( SpriteFont spriteFont, string text, Vector2 position, Color color, float rotation,
Vector2 origin, Vector2 scale, SpriteEffects effects, float layerDepth )
{
throw new NotImplementedException( "SpriteFont is too locked down to use directly. Wrap it in a NezSpriteFont" );
}
static short[] generateIndexArray()
{
var result = new short[MAX_INDICES];
for( int i = 0, j = 0; i < MAX_INDICES; i += 6, j += 4 )
{
result[i] = (short)( j );
result[i + 1] = (short)( j + 1 );
result[i + 2] = (short)( j + 2 );
result[i + 3] = (short)( j + 3 );
result[i + 4] = (short)( j + 2 );
result[i + 5] = (short)( j + 1 );
}
return result;
}
#region Methods
/// <summary>
/// the meat of the Batcher. This is where it all goes down
/// </summary>
[MethodImpl( MethodImplOptions.AggressiveInlining )]
void pushSprite( Texture2D texture, Rectangle? sourceRectangle, float destinationX, float destinationY, float destinationW, float destinationH, Color color, Vector2 origin,
float rotation, float depth, byte effects, bool destSizeInPixels, float skewTopX, float skewBottomX, float skewLeftY, float skewRightY )
{
// out of space, flush
if( _numSprites >= MAX_SPRITES )
flushBatch();
// Source/Destination/Origin Calculations
float sourceX, sourceY, sourceW, sourceH;
float originX, originY;
if( sourceRectangle.HasValue )
{
var inverseTexW = 1.0f / (float)texture.Width;
var inverseTexH = 1.0f / (float)texture.Height;
sourceX = sourceRectangle.Value.X * inverseTexW;
sourceY = sourceRectangle.Value.Y * inverseTexH;
sourceW = sourceRectangle.Value.Width * inverseTexW;
sourceH = sourceRectangle.Value.Height * inverseTexH;
originX = ( origin.X / sourceW ) * inverseTexW;
originY = ( origin.Y / sourceH ) * inverseTexH;
if( !destSizeInPixels )
{
destinationW *= sourceRectangle.Value.Width;
destinationH *= sourceRectangle.Value.Height;
}
}
else
{
sourceX = 0.0f;
sourceY = 0.0f;
sourceW = 1.0f;
sourceH = 1.0f;
originX = origin.X * ( 1.0f / texture.Width );
originY = origin.Y * ( 1.0f / texture.Height );
if( !destSizeInPixels )
{
destinationW *= texture.Width;
destinationH *= texture.Height;
}
}
// Rotation Calculations
float rotationMatrix1X;
float rotationMatrix1Y;
float rotationMatrix2X;
float rotationMatrix2Y;
if( !Mathf.withinEpsilon( rotation, 0 ) )
{
var sin = Mathf.sin( rotation );
var cos = Mathf.cos( rotation );
rotationMatrix1X = cos;
rotationMatrix1Y = sin;
rotationMatrix2X = -sin;
rotationMatrix2Y = cos;
}
else
{
rotationMatrix1X = 1.0f;
rotationMatrix1Y = 0.0f;
rotationMatrix2X = 0.0f;
rotationMatrix2Y = 1.0f;
}
// flip our skew values if we have a flipped sprite
if( effects != 0 )
{
skewTopX *= -1;
skewBottomX *= -1;
skewLeftY *= -1;
skewRightY *= -1;
}
// calculate vertices
// top-left
var cornerX = ( _cornerOffsetX[0] - originX ) * destinationW + skewTopX;
var cornerY = ( _cornerOffsetY[0] - originY ) * destinationH - skewLeftY;
_vertexInfo[_numSprites].position0.X = (
( rotationMatrix2X * cornerY ) +
( rotationMatrix1X * cornerX ) +
destinationX
);
_vertexInfo[_numSprites].position0.Y = (
( rotationMatrix2Y * cornerY ) +
( rotationMatrix1Y * cornerX ) +
destinationY
);
// top-right
cornerX = ( _cornerOffsetX[1] - originX ) * destinationW + skewTopX;
cornerY = ( _cornerOffsetY[1] - originY ) * destinationH - skewRightY;
_vertexInfo[_numSprites].position1.X = (
( rotationMatrix2X * cornerY ) +
( rotationMatrix1X * cornerX ) +
destinationX
);
_vertexInfo[_numSprites].position1.Y = (
( rotationMatrix2Y * cornerY ) +
( rotationMatrix1Y * cornerX ) +
destinationY
);
// bottom-left
cornerX = ( _cornerOffsetX[2] - originX ) * destinationW + skewBottomX;
cornerY = ( _cornerOffsetY[2] - originY ) * destinationH - skewLeftY;
_vertexInfo[_numSprites].position2.X = (
( rotationMatrix2X * cornerY ) +
( rotationMatrix1X * cornerX ) +
destinationX
);
_vertexInfo[_numSprites].position2.Y = (
( rotationMatrix2Y * cornerY ) +
( rotationMatrix1Y * cornerX ) +
destinationY
);
// bottom-right
cornerX = ( _cornerOffsetX[3] - originX ) * destinationW + skewBottomX;
cornerY = ( _cornerOffsetY[3] - originY ) * destinationH - skewRightY;
_vertexInfo[_numSprites].position3.X = (
( rotationMatrix2X * cornerY ) +
( rotationMatrix1X * cornerX ) +
destinationX
);
_vertexInfo[_numSprites].position3.Y = (
( rotationMatrix2Y * cornerY ) +
( rotationMatrix1Y * cornerX ) +
destinationY
);
_vertexInfo[_numSprites].textureCoordinate0.X = ( _cornerOffsetX[0 ^ effects] * sourceW ) + sourceX;
_vertexInfo[_numSprites].textureCoordinate0.Y = ( _cornerOffsetY[0 ^ effects] * sourceH ) + sourceY;
_vertexInfo[_numSprites].textureCoordinate1.X = ( _cornerOffsetX[1 ^ effects] * sourceW ) + sourceX;
_vertexInfo[_numSprites].textureCoordinate1.Y = ( _cornerOffsetY[1 ^ effects] * sourceH ) + sourceY;
_vertexInfo[_numSprites].textureCoordinate2.X = ( _cornerOffsetX[2 ^ effects] * sourceW ) + sourceX;
_vertexInfo[_numSprites].textureCoordinate2.Y = ( _cornerOffsetY[2 ^ effects] * sourceH ) + sourceY;
_vertexInfo[_numSprites].textureCoordinate3.X = ( _cornerOffsetX[3 ^ effects] * sourceW ) + sourceX;
_vertexInfo[_numSprites].textureCoordinate3.Y = ( _cornerOffsetY[3 ^ effects] * sourceH ) + sourceY;
_vertexInfo[_numSprites].position0.Z = depth;
_vertexInfo[_numSprites].position1.Z = depth;
_vertexInfo[_numSprites].position2.Z = depth;
_vertexInfo[_numSprites].position3.Z = depth;
_vertexInfo[_numSprites].color0 = color;
_vertexInfo[_numSprites].color1 = color;
_vertexInfo[_numSprites].color2 = color;
_vertexInfo[_numSprites].color3 = color;
if( _disableBatching )
{
_vertexBuffer.SetData( 0, _vertexInfo, 0, 1, VertexPositionColorTexture4.realStride, SetDataOptions.None );
drawPrimitives( texture, 0, 1 );
}
else
{
_textureInfo[_numSprites] = texture;
_numSprites += 1;
}
}
/// <summary>
/// Subtexture alternative to the old SpriteBatch pushSprite
/// </summary>
[MethodImpl( MethodImplOptions.AggressiveInlining )]
void pushSprite( Subtexture subtexture, float destinationX, float destinationY, float destinationW, float destinationH, Color color, Vector2 origin,
float rotation, float depth, byte effects, float skewTopX, float skewBottomX, float skewLeftY, float skewRightY )
{
// out of space, flush
if( _numSprites >= MAX_SPRITES )
flushBatch();
// Source/Destination/Origin Calculations. destinationW/H is the scale value so we multiply by the size of the texture region
var originX = ( origin.X / subtexture.uvs.width ) / subtexture.texture2D.Width;
var originY = ( origin.Y / subtexture.uvs.height ) / subtexture.texture2D.Height;
destinationW *= subtexture.sourceRect.Width;
destinationH *= subtexture.sourceRect.Height;
// Rotation Calculations
float rotationMatrix1X;
float rotationMatrix1Y;
float rotationMatrix2X;
float rotationMatrix2Y;
if( !Mathf.withinEpsilon( rotation, 0 ) )
{
var sin = Mathf.sin( rotation );
var cos = Mathf.cos( rotation );
rotationMatrix1X = cos;
rotationMatrix1Y = sin;
rotationMatrix2X = -sin;
rotationMatrix2Y = cos;
}
else
{
rotationMatrix1X = 1.0f;
rotationMatrix1Y = 0.0f;
rotationMatrix2X = 0.0f;
rotationMatrix2Y = 1.0f;
}
// flip our skew values if we have a flipped sprite
if( effects != 0 )
{
skewTopX *= -1;
skewBottomX *= -1;
skewLeftY *= -1;
skewRightY *= -1;
}
// calculate vertices
// top-left
var cornerX = ( _cornerOffsetX[0] - originX ) * destinationW + skewTopX;
var cornerY = ( _cornerOffsetY[0] - originY ) * destinationH - skewLeftY;
_vertexInfo[_numSprites].position0.X = (
( rotationMatrix2X * cornerY ) +
( rotationMatrix1X * cornerX ) +
destinationX
);
_vertexInfo[_numSprites].position0.Y = (
( rotationMatrix2Y * cornerY ) +
( rotationMatrix1Y * cornerX ) +
destinationY
);
// top-right
cornerX = ( _cornerOffsetX[1] - originX ) * destinationW + skewTopX;
cornerY = ( _cornerOffsetY[1] - originY ) * destinationH - skewRightY;
_vertexInfo[_numSprites].position1.X = (
( rotationMatrix2X * cornerY ) +
( rotationMatrix1X * cornerX ) +
destinationX
);
_vertexInfo[_numSprites].position1.Y = (
( rotationMatrix2Y * cornerY ) +
( rotationMatrix1Y * cornerX ) +
destinationY
);
// bottom-left
cornerX = ( _cornerOffsetX[2] - originX ) * destinationW + skewBottomX;
cornerY = ( _cornerOffsetY[2] - originY ) * destinationH - skewLeftY;
_vertexInfo[_numSprites].position2.X = (
( rotationMatrix2X * cornerY ) +
( rotationMatrix1X * cornerX ) +
destinationX
);
_vertexInfo[_numSprites].position2.Y = (
( rotationMatrix2Y * cornerY ) +
( rotationMatrix1Y * cornerX ) +
destinationY
);
// bottom-right
cornerX = ( _cornerOffsetX[3] - originX ) * destinationW + skewBottomX;
cornerY = ( _cornerOffsetY[3] - originY ) * destinationH - skewRightY;
_vertexInfo[_numSprites].position3.X = (
( rotationMatrix2X * cornerY ) +
( rotationMatrix1X * cornerX ) +
destinationX
);
_vertexInfo[_numSprites].position3.Y = (
( rotationMatrix2Y * cornerY ) +
( rotationMatrix1Y * cornerX ) +
destinationY
);
_vertexInfo[_numSprites].textureCoordinate0.X = ( _cornerOffsetX[0 ^ effects] * subtexture.uvs.width ) + subtexture.uvs.x;
_vertexInfo[_numSprites].textureCoordinate0.Y = ( _cornerOffsetY[0 ^ effects] * subtexture.uvs.height ) + subtexture.uvs.y;
_vertexInfo[_numSprites].textureCoordinate1.X = ( _cornerOffsetX[1 ^ effects] * subtexture.uvs.width ) + subtexture.uvs.x;
_vertexInfo[_numSprites].textureCoordinate1.Y = ( _cornerOffsetY[1 ^ effects] * subtexture.uvs.height ) + subtexture.uvs.y;
_vertexInfo[_numSprites].textureCoordinate2.X = ( _cornerOffsetX[2 ^ effects] * subtexture.uvs.width ) + subtexture.uvs.x;
_vertexInfo[_numSprites].textureCoordinate2.Y = ( _cornerOffsetY[2 ^ effects] * subtexture.uvs.height ) + subtexture.uvs.y;
_vertexInfo[_numSprites].textureCoordinate3.X = ( _cornerOffsetX[3 ^ effects] * subtexture.uvs.width ) + subtexture.uvs.x;
_vertexInfo[_numSprites].textureCoordinate3.Y = ( _cornerOffsetY[3 ^ effects] * subtexture.uvs.height ) + subtexture.uvs.y;
_vertexInfo[_numSprites].position0.Z = depth;
_vertexInfo[_numSprites].position1.Z = depth;
_vertexInfo[_numSprites].position2.Z = depth;
_vertexInfo[_numSprites].position3.Z = depth;
_vertexInfo[_numSprites].color0 = color;
_vertexInfo[_numSprites].color1 = color;
_vertexInfo[_numSprites].color2 = color;
_vertexInfo[_numSprites].color3 = color;
if( _disableBatching )
{
_vertexBuffer.SetData( 0, _vertexInfo, 0, 1, VertexPositionColorTexture4.realStride, SetDataOptions.None );
drawPrimitives( subtexture, 0, 1 );
}
else
{
_textureInfo[_numSprites] = subtexture;
_numSprites += 1;
}
}
public void flushBatch()
{
if( _numSprites == 0 )
return;
var offset = 0;
Texture2D curTexture = null;
prepRenderState();
_vertexBuffer.SetData( 0, _vertexInfo, 0, _numSprites, VertexPositionColorTexture4.realStride, SetDataOptions.None );
curTexture = _textureInfo[0];
for( var i = 1; i < _numSprites; i += 1 )
{
if( _textureInfo[i] != curTexture )
{
drawPrimitives( curTexture, offset, i - offset );
curTexture = _textureInfo[i];
offset = i;
}
}
drawPrimitives( curTexture, offset, _numSprites - offset );
_numSprites = 0;
}
/// <summary>
/// enables/disables scissor testing. If the RasterizerState changes it will cause a batch flush.
/// </summary>
/// <returns>The scissor test.</returns>
/// <param name="shouldEnable">Should enable.</param>
public void enableScissorTest( bool shouldEnable )
{
var currentValue = _rasterizerState.ScissorTestEnable;
if( currentValue == shouldEnable )
return;
flushBatch();
_rasterizerState = new RasterizerState
{
CullMode = _rasterizerState.CullMode,
DepthBias = _rasterizerState.DepthBias,
FillMode = _rasterizerState.FillMode,
MultiSampleAntiAlias = _rasterizerState.MultiSampleAntiAlias,
SlopeScaleDepthBias = _rasterizerState.SlopeScaleDepthBias,
ScissorTestEnable = shouldEnable
};
}
void prepRenderState()
{
graphicsDevice.BlendState = _blendState;
graphicsDevice.SamplerStates[0] = _samplerState;
graphicsDevice.DepthStencilState = _depthStencilState;
graphicsDevice.RasterizerState = _rasterizerState;
graphicsDevice.SetVertexBuffer( _vertexBuffer );
graphicsDevice.Indices = _indexBuffer;
var viewport = graphicsDevice.Viewport;
// inlined CreateOrthographicOffCenter
_projectionMatrix.M11 = (float)( 2.0 / (double)viewport.Width );
_projectionMatrix.M22 = (float)( -2.0 / (double)viewport.Height );
_projectionMatrix.M41 = -1 - 0.5f * _projectionMatrix.M11;
_projectionMatrix.M42 = 1 - 0.5f * _projectionMatrix.M22;
Matrix.Multiply( ref _transformMatrix, ref _projectionMatrix, out _matrixTransformMatrix );
_spriteEffect.setMatrixTransform( ref _matrixTransformMatrix );
// we have to Apply here because custom effects often wont have a vertex shader and we need the default SpriteEffect's
_spriteEffectPass.Apply();
}
void drawPrimitives( Texture texture, int baseSprite, int batchSize )
{
if( _customEffect != null )
{
foreach( var pass in _customEffect.CurrentTechnique.Passes )
{
pass.Apply();
// Whatever happens in pass.Apply, make sure the texture being drawn ends up in Textures[0].
graphicsDevice.Textures[0] = texture;
graphicsDevice.DrawIndexedPrimitives( PrimitiveType.TriangleList, baseSprite * 4, 0, batchSize * 2 );
}
}
else
{
graphicsDevice.Textures[0] = texture;
graphicsDevice.DrawIndexedPrimitives( PrimitiveType.TriangleList, baseSprite * 4, 0, batchSize * 2 );
}
}
[System.Diagnostics.Conditional( "DEBUG" )]
void checkBegin()
{
if( !_beginCalled )
throw new InvalidOperationException( "Begin has not been called. Begin must be called before you can draw" );
}
#endregion
#region Sprite Data Container Class
[StructLayout( LayoutKind.Sequential, Pack = 1 )]
struct VertexPositionColorTexture4 : IVertexType
{
public const int realStride = 96;
VertexDeclaration IVertexType.VertexDeclaration { get { throw new NotImplementedException(); } }
public Vector3 position0;
public Color color0;
public Vector2 textureCoordinate0;
public Vector3 position1;
public Color color1;
public Vector2 textureCoordinate1;
public Vector3 position2;
public Color color2;
public Vector2 textureCoordinate2;
public Vector3 position3;
public Color color3;
public Vector2 textureCoordinate3;
}
#endregion
}
}
| 28.774791 | 177 | 0.694827 | [
"MIT"
] | jkstrawn/gangsters | Nez/Nez.Portable/Graphics/Batcher/Batcher.cs | 31,048 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reactive;
using System.Reactive.Linq;
using System.Reactive.Subjects;
using System.Text;
using System.Threading.Tasks;
using slimCODE.Extensions;
using slimCODE.Models;
namespace Seclusion.Models
{
public class LandViewModel : BaseChildViewModel
{
public LandViewModel(Func<IObservable<Unit>> untapAllSelector, BaseViewModel parent)
: base (parent)
{
this.IsTappedObservable = this.CreateActiveProperty<bool>(
"IsTapped",
"Toggle",
"Tap",
(toggle, tap) => Observable
.Merge<bool?>(
untapAllSelector().Select(_ => false as bool?),
toggle.Select(_ => default(bool?)),
tap.Select(_ => true as bool?))
.Scan(false, (previous, isTapped) =>
isTapped.HasValue ? isTapped.Value : !previous),
false);
}
public IObservable<bool> IsTappedObservable { get; }
public void Tap()
{
(this["Tap"] as IObservableCommand<Unit>).OnNext(Unit.Default);
}
}
}
| 30.292683 | 92 | 0.561997 | [
"MIT"
] | slimCODE/slim-lib | src/samples/Seclusion/Seclusion.Shared/Models/LandViewModel.cs | 1,244 | C# |
/* Copyright (c) 1996-2019 The OPC Foundation. All rights reserved.
The source code in this file is covered under a dual-license scenario:
- RCL: for OPC Foundation members in good-standing
- GPL V2: everybody else
RCL license terms accompanied with this source code. See http://opcfoundation.org/License/RCL/1.00/
GNU General Public License as published by the Free Software Foundation;
version 2 of the License are accompanied with this source code. See http://opcfoundation.org/License/GPLv2
This source code is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
*/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.Security.Cryptography.X509Certificates;
namespace Opc.Ua
{
/// <summary>
/// Stores the configurable configuration information for a UA application.
/// </summary>
[DataContract(Namespace = Namespaces.OpcUaConfig)]
public partial class ApplicationConfiguration
{
#region Constructors
/// <summary>
/// The default constructor.
/// </summary>
public ApplicationConfiguration()
{
Initialize();
}
/// <summary>
/// Sets private members to default values.
/// </summary>
private void Initialize()
{
m_sourceFilePath = null;
m_securityConfiguration = new SecurityConfiguration();
m_transportConfigurations = new TransportConfigurationCollection();
m_disableHiResClock = true;
m_properties = new Dictionary<string, object>();
}
/// <summary>
/// Initializes the object during deserialization.
/// </summary>
/// <param name="context">The context.</param>
[OnDeserializing()]
public void Initialize(StreamingContext context)
{
Initialize();
}
#endregion
/// <summary>
/// Gets an object used to synchronize access to the properties dictionary.
/// </summary>
/// <value>
/// The object used to synchronize access to the properties dictionary.
/// </value>
public object PropertiesLock
{
get { return m_properties; }
}
/// <summary>
/// Gets a dictionary used to save state associated with the application.
/// </summary>
/// <value>
/// The dictionary used to save state associated with the application.
/// </value>
public IDictionary<string, object> Properties
{
get { return m_properties; }
}
#region Persistent Properties
/// <summary>
/// A descriptive name for the the application (not necessarily unique).
/// </summary>
/// <value>The name of the application.</value>
[DataMember(IsRequired = true, EmitDefaultValue = false, Order = 0)]
public string ApplicationName
{
get { return m_applicationName; }
set { m_applicationName = value; }
}
/// <summary>
/// A unique identifier for the application instance.
/// </summary>
/// <value>The application URI.</value>
[DataMember(IsRequired = true, EmitDefaultValue = false, Order = 1)]
public string ApplicationUri
{
get { return m_applicationUri; }
set { m_applicationUri = value; }
}
/// <summary>
/// A unique identifier for the product.
/// </summary>
/// <value>The product URI.</value>
[DataMember(IsRequired = false, Order = 2)]
public string ProductUri
{
get { return m_productUri; }
set { m_productUri = value; }
}
/// <summary>
/// The type of application.
/// </summary>
/// <value>The type of the application.</value>
[DataMember(IsRequired = true, Order = 3)]
public ApplicationType ApplicationType
{
get { return m_applicationType; }
set { m_applicationType = value; }
}
/// <summary>
/// The security configuration for the application.
/// </summary>
/// <value>The security configuration.</value>
[DataMember(IsRequired = false, EmitDefaultValue = true, Order = 4)]
public SecurityConfiguration SecurityConfiguration
{
get
{
return m_securityConfiguration;
}
set
{
m_securityConfiguration = value;
if (m_securityConfiguration == null)
{
m_securityConfiguration = new SecurityConfiguration();
}
}
}
/// <summary>
/// The transport configuration for the application.
/// </summary>
/// <value>The transport configurations.</value>
[DataMember(IsRequired = false, EmitDefaultValue = true, Order = 5)]
public TransportConfigurationCollection TransportConfigurations
{
get
{
return m_transportConfigurations;
}
set
{
m_transportConfigurations = value;
if (m_transportConfigurations == null)
{
m_transportConfigurations = new TransportConfigurationCollection();
}
}
}
/// <summary>
/// The quotas that are used at the transport layer.
/// </summary>
/// <value>The transport quotas.</value>
[DataMember(IsRequired = false, EmitDefaultValue = true, Order = 6)]
public TransportQuotas TransportQuotas
{
get { return m_transportQuotas; }
set { m_transportQuotas = value; }
}
/// <summary>
/// Additional configuration for server applications.
/// </summary>
/// <value>The server configuration.</value>
[DataMember(IsRequired = false, EmitDefaultValue = false, Order = 7)]
public ServerConfiguration ServerConfiguration
{
get { return m_serverConfiguration; }
set { m_serverConfiguration = value; }
}
/// <summary>
/// Additional configuration for client applications.
/// </summary>
/// <value>The client configuration.</value>
[DataMember(IsRequired = false, EmitDefaultValue = false, Order = 8)]
public ClientConfiguration ClientConfiguration
{
get { return m_clientConfiguration; }
set { m_clientConfiguration = value; }
}
/// <summary>
/// Additional configuration of the discovery server.
/// </summary>
/// <value>The discovery server configuration.</value>
[DataMember(IsRequired = false, EmitDefaultValue = false, Order = 9)]
public DiscoveryServerConfiguration DiscoveryServerConfiguration
{
get { return m_discoveryServerConfiguration; }
set { m_discoveryServerConfiguration = value; }
}
/// <summary>
/// A bucket to store additional application specific configuration data.
/// </summary>
/// <value>The extensions.</value>
[DataMember(IsRequired = false, EmitDefaultValue = false, Order = 10)]
public XmlElementCollection Extensions
{
get { return m_extensions; }
set { m_extensions = value; }
}
/// <summary>
/// Configuration of the trace and information about log file
/// </summary>
/// <value>The trace configuration.</value>
[DataMember(IsRequired = false, EmitDefaultValue = false, Order = 11)]
public TraceConfiguration TraceConfiguration
{
get { return m_traceConfiguration; }
set { m_traceConfiguration = value; }
}
/// <summary>
/// Disabling / enabling high resolution clock
/// </summary>
/// <value><c>true</c> if high resolutioin clock is disabled; otherwise, <c>false</c>.</value>
[DataMember(IsRequired = false, EmitDefaultValue = false, Order = 12)]
public bool DisableHiResClock
{
get { return m_disableHiResClock; }
set { m_disableHiResClock = value; }
}
#endregion
#region Private Fields
private string m_applicationName;
private string m_applicationUri;
private string m_productUri;
private ApplicationType m_applicationType;
private SecurityConfiguration m_securityConfiguration;
private TransportConfigurationCollection m_transportConfigurations;
private TransportQuotas m_transportQuotas;
private ServerConfiguration m_serverConfiguration;
private ClientConfiguration m_clientConfiguration;
private DiscoveryServerConfiguration m_discoveryServerConfiguration;
private TraceConfiguration m_traceConfiguration;
private bool m_disableHiResClock;
private XmlElementCollection m_extensions;
private string m_sourceFilePath;
private ServiceMessageContext m_messageContext;
private CertificateValidator m_certificateValidator;
private Dictionary<string, object> m_properties;
#endregion
}
#region TransportQuotas Class
/// <summary>
/// Specifies various limits that apply to the transport or secure channel layers.
/// </summary>
[DataContract(Namespace = Namespaces.OpcUaConfig)]
public class TransportQuotas
{
#region Constructors
/// <summary>
/// The default constructor.
/// </summary>
public TransportQuotas()
{
Initialize();
}
/// <summary>
/// Sets private members to default values.
/// </summary>
private void Initialize()
{
m_operationTimeout = 120000;
m_maxStringLength = 65535;
m_maxByteStringLength = 65535;
m_maxArrayLength = 65535;
m_maxMessageSize = 1048576;
m_maxBufferSize = 65535;
m_channelLifetime = 600000;
m_securityTokenLifetime = 3600000;
}
/// <summary>
/// Initializes the object during deserialization.
/// </summary>
/// <param name="context">The context.</param>
[OnDeserializing()]
public void Initialize(StreamingContext context)
{
Initialize();
}
#endregion
#region Persistent Properties
/// <summary>
/// The default timeout to use when sending requests.
/// </summary>
/// <value>The operation timeout.</value>
[DataMember(IsRequired = false, Order = 0)]
public int OperationTimeout
{
get { return m_operationTimeout; }
set { m_operationTimeout = value; }
}
/// <summary>
/// The maximum length of string encoded in a message body.
/// </summary>
/// <value>The max length of the string.</value>
[DataMember(IsRequired = false, Order = 1)]
public int MaxStringLength
{
get { return m_maxStringLength; }
set { m_maxStringLength = value; }
}
/// <summary>
/// The maximum length of a byte string encoded in a message body.
/// </summary>
/// <value>The max length of the byte string.</value>
[DataMember(IsRequired = false, Order = 2)]
public int MaxByteStringLength
{
get { return m_maxByteStringLength; }
set { m_maxByteStringLength = value; }
}
/// <summary>
/// The maximum length of an array encoded in a message body.
/// </summary>
/// <value>The max length of the array.</value>
[DataMember(IsRequired = false, Order = 3)]
public int MaxArrayLength
{
get { return m_maxArrayLength; }
set { m_maxArrayLength = value; }
}
/// <summary>
/// The maximum length of a message body.
/// </summary>
/// <value>The max size of the message.</value>
[DataMember(IsRequired = false, Order = 4)]
public int MaxMessageSize
{
get { return m_maxMessageSize; }
set { m_maxMessageSize = value; }
}
/// <summary>
/// The maximum size of the buffer to use when sending messages.
/// </summary>
/// <value>The max size of the buffer.</value>
[DataMember(IsRequired = false, Order = 5)]
public int MaxBufferSize
{
get { return m_maxBufferSize; }
set { m_maxBufferSize = value; }
}
/// <summary>
/// The lifetime of a secure channel.
/// </summary>
/// <value>The channel lifetime.</value>
[DataMember(IsRequired = false, Order = 6)]
public int ChannelLifetime
{
get { return m_channelLifetime; }
set { m_channelLifetime = value; }
}
/// <summary>
/// The lifetime of a security token.
/// </summary>
/// <value>The security token lifetime.</value>
[DataMember(IsRequired = false, Order = 7)]
public int SecurityTokenLifetime
{
get { return m_securityTokenLifetime; }
set { m_securityTokenLifetime = value; }
}
#endregion
#region Private Fields
private int m_operationTimeout;
private int m_maxStringLength;
private int m_maxByteStringLength;
private int m_maxArrayLength;
private int m_maxMessageSize;
private int m_maxBufferSize;
private int m_channelLifetime;
private int m_securityTokenLifetime;
#endregion
}
#endregion
#region TraceConfiguration Class
/// <summary>
/// Specifies parameters used for tracing.
/// </summary>
[DataContract(Namespace = Namespaces.OpcUaConfig)]
public partial class TraceConfiguration
{
#region Constructors
/// <summary>
/// The default constructor.
/// </summary>
public TraceConfiguration()
{
Initialize();
}
/// <summary>
/// Sets private members to default values.
/// </summary>
private void Initialize()
{
m_outputFilePath = null;
m_deleteOnLoad = false;
}
/// <summary>
/// Initializes the object during deserialization.
/// </summary>
/// <param name="context">The context.</param>
[OnDeserializing()]
public void Initialize(StreamingContext context)
{
Initialize();
}
#endregion
#region Persistent Properties
/// <summary>
/// The output file used to log the trace information.
/// </summary>
/// <value>The output file path.</value>
[DataMember(IsRequired = false, Order = 0)]
public string OutputFilePath
{
get { return m_outputFilePath; }
set { m_outputFilePath = value; }
}
/// <summary>
/// Whether the existing log file should be deleted when the application configuration is loaded.
/// </summary>
/// <value><c>true</c> if existing log file should be deleted when the application configuration is loaded; otherwise, <c>false</c>.</value>
[DataMember(IsRequired = false, Order = 1)]
public bool DeleteOnLoad
{
get { return m_deleteOnLoad; }
set { m_deleteOnLoad = value; }
}
/// <summary>
/// The masks used to select what is written to the output
/// Masks supported by the trace feature:
/// - Do not output any messages -None = 0x0;
/// - Output error messages - Error = 0x1;
/// - Output informational messages - Information = 0x2;
/// - Output stack traces - StackTrace = 0x4;
/// - Output basic messages for service calls - Service = 0x8;
/// - Output detailed messages for service calls - ServiceDetail = 0x10;
/// - Output basic messages for each operation - Operation = 0x20;
/// - Output detailed messages for each operation - OperationDetail = 0x40;
/// - Output messages related to application initialization or shutdown - StartStop = 0x80;
/// - Output messages related to a call to an external system - ExternalSystem = 0x100;
/// - Output messages related to security. - Security = 0x200;
/// </summary>
/// <value>The trace masks.</value>
[DataMember(IsRequired = false, Order = 2)]
public int TraceMasks
{
get { return m_traceMasks; }
set { m_traceMasks = value; }
}
#endregion
#region Private Fields
private string m_outputFilePath;
private bool m_deleteOnLoad;
private int m_traceMasks;
#endregion
}
#endregion
#region TransportConfiguration Class
/// <summary>
/// Specifies the configuration information for a transport protocol
/// </summary>
/// <remarks>
/// Each application is allows to have one transport configure per protocol type.
/// </remarks>
[DataContract(Namespace = Namespaces.OpcUaConfig)]
public class TransportConfiguration
{
#region Constructors
/// <summary>
/// The default constructor.
/// </summary>
public TransportConfiguration()
{
}
/// <summary>
/// The default constructor.
/// </summary>
/// <param name="urlScheme">The URL scheme.</param>
/// <param name="type">The type.</param>
public TransportConfiguration(string urlScheme, Type type)
{
m_uriScheme = urlScheme;
m_typeName = type.AssemblyQualifiedName;
}
#endregion
#region Persistent Properties
/// <summary>
/// The URL prefix used by the application (http, opc.tcp, net.tpc, etc.).
/// </summary>
/// <value>The URI scheme.</value>
[DataMember(IsRequired = true, EmitDefaultValue = false, Order = 0)]
public string UriScheme
{
get { return m_uriScheme; }
set { m_uriScheme = value; }
}
/// <summary>
/// The name of the class that defines the binding for the transport.
/// </summary>
/// <value>The name of the type.</value>
/// <remarks>
/// This can be any instance of the System.ServiceModel.Channels.Binding class
/// that implements these constructors:
///
/// XxxBinding(EndpointDescription description, EndpointConfiguration configuration);
/// XxxBinding(IList{EndpointDescription} descriptions, EndpointConfiguration configuration)
/// XxxBinding(EndpointConfiguration configuration)
/// </remarks>
[DataMember(IsRequired = true, EmitDefaultValue = false, Order = 1)]
public string TypeName
{
get { return m_typeName; }
set { m_typeName = value; }
}
#endregion
#region Private Fields
private string m_uriScheme;
private string m_typeName;
#endregion
}
#endregion
#region TransportConfigurationCollection Class
/// <summary>
/// A collection of TransportConfiguration objects.
/// </summary>
[CollectionDataContract(Name = "ListOfTransportConfiguration", Namespace = Namespaces.OpcUaConfig, ItemName = "TransportConfiguration")]
public partial class TransportConfigurationCollection : List<TransportConfiguration>
{
/// <summary>
/// Initializes an empty collection.
/// </summary>
public TransportConfigurationCollection() { }
/// <summary>
/// Initializes the collection from another collection.
/// </summary>
/// <param name="collection">A collection of values to add to this new collection</param>
/// <exception cref="T:System.ArgumentNullException">
/// <paramref name="collection"/> is null.
/// </exception>
public TransportConfigurationCollection(IEnumerable<TransportConfiguration> collection) : base(collection) { }
/// <summary>
/// Initializes the collection with the specified capacity.
/// </summary>
/// <param name="capacity">The capacity.</param>
public TransportConfigurationCollection(int capacity) : base(capacity) { }
}
#endregion
#region ServerSecurityPolicy Class
/// <summary>
/// A class that defines a group of sampling rates supported by the server.
/// </summary>
[DataContract(Namespace = Namespaces.OpcUaConfig)]
public class ServerSecurityPolicy
{
#region Constructors
/// <summary>
/// The default constructor.
/// </summary>
public ServerSecurityPolicy()
{
Initialize();
}
/// <summary>
/// Sets private members to default values.
/// </summary>
private void Initialize()
{
m_securityMode = MessageSecurityMode.SignAndEncrypt;
m_securityPolicyUri = SecurityPolicies.Basic256Sha256;
}
/// <summary>
/// Initializes the object during deserialization.
/// </summary>
/// <param name="context">The context.</param>
[OnDeserializing()]
public void Initialize(StreamingContext context)
{
Initialize();
}
#endregion
#region Public Properties
/// <summary>
/// Calculates the security level, given the security mode and policy
/// Invalid and none is discouraged
/// Just signing is always weaker than any use of encryption
/// </summary>
public static byte CalculateSecurityLevel(MessageSecurityMode mode, string policyUri)
{
if ((mode == MessageSecurityMode.Invalid) || (mode == MessageSecurityMode.None))
{
return 0;
}
byte result = 0;
switch (policyUri)
{
case SecurityPolicies.Basic128Rsa15: result = 2; break;
case SecurityPolicies.Basic256: result = 4; break;
case SecurityPolicies.Basic256Sha256: result = 6; break;
case SecurityPolicies.Aes128_Sha256_RsaOaep: result = 8; break;
case SecurityPolicies.Aes256_Sha256_RsaPss: result = 10; break;
case SecurityPolicies.None:
default: return 0;
}
if (mode == MessageSecurityMode.SignAndEncrypt)
{
result += 100;
}
return result;
}
/// <summary>
/// Specifies whether the messages are signed and encrypted or simply signed
/// </summary>
/// <value>The security mode.</value>
[DataMember(IsRequired = false, Order = 1)]
public MessageSecurityMode SecurityMode
{
get { return m_securityMode; }
set { m_securityMode = value; }
}
/// <summary>
/// The security policy to use.
/// </summary>
/// <value>The security policy URI.</value>
[DataMember(IsRequired = false, Order = 2)]
public string SecurityPolicyUri
{
get { return m_securityPolicyUri; }
set { m_securityPolicyUri = value; }
}
#endregion
#region Private Members
private MessageSecurityMode m_securityMode;
private string m_securityPolicyUri;
#endregion
}
#endregion
#region ServerSecurityPolicyCollection Class
/// <summary>
/// A collection of ServerSecurityPolicy objects.
/// </summary>
[CollectionDataContract(Name = "ListOfServerSecurityPolicy", Namespace = Namespaces.OpcUaConfig, ItemName = "ServerSecurityPolicy")]
public partial class ServerSecurityPolicyCollection : List<ServerSecurityPolicy>
{
/// <summary>
/// Initializes an empty collection.
/// </summary>
public ServerSecurityPolicyCollection() { }
/// <summary>
/// Initializes the collection from another collection.
/// </summary>
/// <param name="collection">A collection of values to add to this new collection</param>
/// <exception cref="T:System.ArgumentNullException">
/// <paramref name="collection"/> is null.
/// </exception>
public ServerSecurityPolicyCollection(IEnumerable<ServerSecurityPolicy> collection) : base(collection) { }
/// <summary>
/// Initializes the collection with the specified capacity.
/// </summary>
/// <param name="capacity">The capacity.</param>
public ServerSecurityPolicyCollection(int capacity) : base(capacity) { }
}
#endregion
#region SecurityConfiguration Class
/// <summary>
/// The security configuration for the application.
/// </summary>
[DataContract(Namespace = Namespaces.OpcUaConfig)]
public partial class SecurityConfiguration
{
#region Constructors
/// <summary>
/// The default constructor.
/// </summary>
public SecurityConfiguration()
{
Initialize();
}
/// <summary>
/// Sets private members to default values.
/// </summary>
private void Initialize()
{
m_trustedIssuerCertificates = new CertificateTrustList();
m_trustedPeerCertificates = new CertificateTrustList();
m_nonceLength = 32;
m_autoAcceptUntrustedCertificates = false;
m_rejectSHA1SignedCertificates = true;
m_minCertificateKeySize = CertificateFactory.defaultKeySize;
m_addAppCertToTrustedStore = true;
m_sendCertificateChain = false;
}
/// <summary>
/// Initializes the object during deserialization.
/// </summary>
[OnDeserializing()]
public void Initialize(StreamingContext context)
{
Initialize();
}
#endregion
#region Persistent Properties
/// <summary>
/// The application instance certificate.
/// </summary>
/// <value>The application certificate.</value>
/// <remarks>
/// This certificate must contain the application uri.
/// For servers, URLs for each supported protocol must also be present.
/// </remarks>
[DataMember(IsRequired = true, EmitDefaultValue = false, Order = 0)]
public CertificateIdentifier ApplicationCertificate
{
get { return m_applicationCertificate; }
set { m_applicationCertificate = value; }
}
/// <summary>
/// The store containing any additional issuer certificates.
/// </summary>
[DataMember(IsRequired = false, EmitDefaultValue = false, Order = 2)]
public CertificateTrustList TrustedIssuerCertificates
{
get
{
return m_trustedIssuerCertificates;
}
set
{
m_trustedIssuerCertificates = value;
if (m_trustedIssuerCertificates == null)
{
m_trustedIssuerCertificates = new CertificateTrustList();
}
}
}
/// <summary>
/// The trusted certificate store.
/// </summary>
[DataMember(IsRequired = false, EmitDefaultValue = false, Order = 4)]
public CertificateTrustList TrustedPeerCertificates
{
get
{
return m_trustedPeerCertificates;
}
set
{
m_trustedPeerCertificates = value;
if (m_trustedPeerCertificates == null)
{
m_trustedPeerCertificates = new CertificateTrustList();
}
}
}
/// <summary>
/// The length of nonce in the CreateSession service.
/// </summary>
/// <value>
/// The length of nonce in the CreateSession service.
/// </value>
[DataMember(IsRequired = false, EmitDefaultValue = false, Order = 6)]
public int NonceLength
{
get { return m_nonceLength; }
set { m_nonceLength = value; }
}
/// <summary>
/// A store where invalid certificates can be placed for later review by the administrator.
/// </summary>
/// <value>
/// A store where invalid certificates can be placed for later review by the administrator.
/// </value>
[DataMember(IsRequired = false, EmitDefaultValue = false, Order = 7)]
public CertificateStoreIdentifier RejectedCertificateStore
{
get { return m_rejectedCertificateStore; }
set { m_rejectedCertificateStore = value; }
}
/// <summary>
/// Gets or sets a value indicating whether untrusted certificates should be automatically accepted.
/// </summary>
/// <remarks>
/// This flag can be set to by servers that allow anonymous clients or use user credentials for authentication.
/// It can be set by clients that connect to URLs specified in configuration rather than with user entry.
/// </remarks>
[DataMember(IsRequired = false, EmitDefaultValue = false, Order = 8)]
public bool AutoAcceptUntrustedCertificates
{
get { return m_autoAcceptUntrustedCertificates; }
set { m_autoAcceptUntrustedCertificates = value; }
}
/// <summary>
/// Gets or sets a directory which contains files representing users roles.
/// </summary>
[DataMember(Order = 9)]
public string UserRoleDirectory
{
get { return m_userRoleDirectory; }
set { m_userRoleDirectory = value; }
}
/// <summary>
/// Gets or sets a value indicating whether SHA-1 signed certificates are accepted.
/// </summary>
/// <remarks>
/// This flag can be set to false by servers that accept SHA-1 signed certificates.
/// </remarks>
[DataMember(IsRequired = false, EmitDefaultValue = false, Order = 10)]
public bool RejectSHA1SignedCertificates
{
get { return m_rejectSHA1SignedCertificates; }
set { m_rejectSHA1SignedCertificates = value; }
}
/// <summary>
/// Gets or sets a value indicating which minimum certificate key strength is accepted.
/// </summary>
/// <remarks>
/// This value can be set to 1024, 2048 or 4096 by servers
/// </remarks>
[DataMember(IsRequired = false, EmitDefaultValue = false, Order = 11)]
public ushort MinimumCertificateKeySize
{
get { return m_minCertificateKeySize; }
set { m_minCertificateKeySize = value; }
}
/// <summary>
/// Gets or sets a value indicating whether the application cert should be copied to the trusted store.
/// </summary>
/// <remarks>
/// It is useful for client/server applications running on the same host and sharing the cert store to autotrust.
/// </remarks>
[DataMember(IsRequired = false, EmitDefaultValue = false, Order = 12)]
public bool AddAppCertToTrustedStore
{
get { return m_addAppCertToTrustedStore; }
set { m_addAppCertToTrustedStore = value; }
}
/// <summary>
/// Gets or sets a value indicating whether the application should send the complete certificate chain.
/// </summary>
/// <remarks>
/// If set to true the complete certificate chain will be sent for CA signed certificates.
/// </remarks>
[DataMember(IsRequired = false, EmitDefaultValue = false, Order = 13)]
public bool SendCertificateChain
{
get { return m_sendCertificateChain; }
set { m_sendCertificateChain = value; }
}
/// <summary>
/// The store containing additional user issuer certificates.
/// </summary>
[DataMember(IsRequired = false, EmitDefaultValue = false, Order = 14)]
public CertificateTrustList UserIssuerCertificates
{
get
{
return m_userIssuerCertificates;
}
set
{
m_userIssuerCertificates = value;
if (m_userIssuerCertificates == null)
{
m_userIssuerCertificates = new CertificateTrustList();
}
}
}
/// <summary>
/// The store containing trusted user certificates.
/// </summary>
[DataMember(IsRequired = false, EmitDefaultValue = false, Order = 15)]
public CertificateTrustList TrustedUserCertificates
{
get
{
return m_trustedUserCertificates;
}
set
{
m_trustedUserCertificates = value;
if (m_trustedUserCertificates == null)
{
m_trustedUserCertificates = new CertificateTrustList();
}
}
}
/// <summary>
/// The store containing additional Https issuer certificates.
/// </summary>
[DataMember(IsRequired = false, EmitDefaultValue = false, Order = 16)]
public CertificateTrustList HttpsIssuerCertificates
{
get
{
return m_httpsIssuerCertificates;
}
set
{
m_httpsIssuerCertificates = value;
if (m_httpsIssuerCertificates == null)
{
m_httpsIssuerCertificates = new CertificateTrustList();
}
}
}
/// <summary>
/// The store containing trusted Https certificates.
/// </summary>
[DataMember(IsRequired = false, EmitDefaultValue = false, Order = 17)]
public CertificateTrustList TrustedHttpsCertificates
{
get
{
return m_trustedHttpsCertificates;
}
set
{
m_trustedHttpsCertificates = value;
if (m_trustedHttpsCertificates == null)
{
m_trustedHttpsCertificates = new CertificateTrustList();
}
}
}
#endregion
#region Private Fields
private CertificateIdentifier m_applicationCertificate;
private CertificateTrustList m_trustedIssuerCertificates;
private CertificateTrustList m_trustedPeerCertificates;
private CertificateTrustList m_httpsIssuerCertificates;
private CertificateTrustList m_trustedHttpsCertificates;
private CertificateTrustList m_userIssuerCertificates;
private CertificateTrustList m_trustedUserCertificates;
private int m_nonceLength;
private CertificateStoreIdentifier m_rejectedCertificateStore;
private bool m_autoAcceptUntrustedCertificates;
private string m_userRoleDirectory;
private bool m_rejectSHA1SignedCertificates;
private ushort m_minCertificateKeySize;
private bool m_addAppCertToTrustedStore;
private bool m_sendCertificateChain;
#endregion
}
#endregion
#region SamplingRateGroup Class
/// <summary>
/// A class that defines a group of sampling rates supported by the server.
/// </summary>
[DataContract(Namespace = Namespaces.OpcUaConfig)]
public class SamplingRateGroup
{
#region Constructors
/// <summary>
/// The default constructor.
/// </summary>
public SamplingRateGroup()
{
Initialize();
}
/// <summary>
/// Creates a group with the specified settings.
/// </summary>
/// <param name="start">The start.</param>
/// <param name="increment">The increment.</param>
/// <param name="count">The count.</param>
public SamplingRateGroup(int start, int increment, int count)
{
m_start = start;
m_increment = increment;
m_count = count;
}
/// <summary>
/// Sets private members to default values.
/// </summary>
private void Initialize()
{
m_start = 1000;
m_increment = 0;
m_count = 0;
}
/// <summary>
/// Initializes the object during deserialization.
/// </summary>
/// <param name="context">The context.</param>
[OnDeserializing()]
public void Initialize(StreamingContext context)
{
Initialize();
}
#endregion
#region Public Properties
/// <summary>
/// The first sampling rate in the group (in milliseconds).
/// </summary>
/// <value>The first sampling rate in the group (in milliseconds).</value>
[DataMember(IsRequired = false, Order = 1)]
public double Start
{
get { return m_start; }
set { m_start = value; }
}
/// <summary>
/// The increment between sampling rates in the group (in milliseconds).
/// </summary>
/// <value>The increment.</value>
/// <remarks>
/// An increment of 0 means the group only contains one sampling rate equal to the start.
/// </remarks>
[DataMember(IsRequired = false, Order = 2)]
public double Increment
{
get { return m_increment; }
set { m_increment = value; }
}
/// <summary>
/// The number of sampling rates in the group.
/// </summary>
/// <value>The count.</value>
/// <remarks>
/// A count of 0 means there is no limit.
/// </remarks>
[DataMember(IsRequired = false, Order = 3)]
public int Count
{
get { return m_count; }
set { m_count = value; }
}
#endregion
#region Private Members
private double m_start;
private double m_increment;
private int m_count;
#endregion
}
#endregion
#region SamplingRateGroupCollection Class
/// <summary>
/// A collection of SamplingRateGroup objects.
/// </summary>
[CollectionDataContract(Name = "ListOfSamplingRateGroup", Namespace = Namespaces.OpcUaConfig, ItemName = "SamplingRateGroup")]
public partial class SamplingRateGroupCollection : List<SamplingRateGroup>
{
/// <summary>
/// Initializes an empty collection.
/// </summary>
public SamplingRateGroupCollection() { }
/// <summary>
/// Initializes the collection from another collection.
/// </summary>
/// <param name="collection">A collection of values to add to this new collection</param>
/// <exception cref="T:System.ArgumentNullException">
/// <paramref name="collection"/> is null.
/// </exception>
public SamplingRateGroupCollection(IEnumerable<SamplingRateGroup> collection) : base(collection) { }
/// <summary>
/// Initializes the collection with the specified capacity.
/// </summary>
/// <param name="capacity">The capacity.</param>
public SamplingRateGroupCollection(int capacity) : base(capacity) { }
}
#endregion
#region ServerBaseConfiguration Class
/// <summary>
/// Specifies the configuration for a server application.
/// </summary>
[DataContract(Namespace = Namespaces.OpcUaConfig)]
public partial class ServerBaseConfiguration
{
#region Constructors
/// <summary>
/// The default constructor.
/// </summary>
public ServerBaseConfiguration()
{
Initialize();
}
/// <summary>
/// Sets private members to default values.
/// </summary>
private void Initialize()
{
m_baseAddresses = new StringCollection();
m_alternateBaseAddresses = new StringCollection();
m_securityPolicies = new ServerSecurityPolicyCollection();
m_minRequestThreadCount = 10;
m_maxRequestThreadCount = 100;
m_maxQueuedRequestCount = 200;
}
/// <summary>
/// Initializes the object during deserialization.
/// </summary>
/// <param name="context">The context.</param>
[OnDeserializing()]
public void Initialize(StreamingContext context)
{
Initialize();
}
/// <summary>
/// Remove unsupported security policies and expand wild cards.
/// </summary>
[OnDeserialized()]
private void ValidateSecurityPolicyCollection(StreamingContext context)
{
var supportedPolicies = Opc.Ua.SecurityPolicies.GetDisplayNames();
var newPolicies = new ServerSecurityPolicyCollection();
foreach (var securityPolicy in m_securityPolicies)
{
if (String.IsNullOrWhiteSpace(securityPolicy.SecurityPolicyUri))
{
// add wild card policies
foreach (var policyUri in Opc.Ua.SecurityPolicies.GetDefaultUris())
{
var newPolicy = new ServerSecurityPolicy() {
SecurityMode = securityPolicy.SecurityMode,
SecurityPolicyUri = policyUri
};
if (newPolicies.Where(s =>
s.SecurityMode == newPolicy.SecurityMode &&
String.Compare(s.SecurityPolicyUri, newPolicy.SecurityPolicyUri) == 0
).FirstOrDefault() == null)
{
newPolicies.Add(newPolicy);
}
}
}
else
{
for (int i = 0; i < supportedPolicies.Length; i++)
{
if (securityPolicy.SecurityPolicyUri.Contains(supportedPolicies[i]))
{
if (newPolicies.Where(s =>
s.SecurityMode == securityPolicy.SecurityMode &&
String.Compare(s.SecurityPolicyUri, securityPolicy.SecurityPolicyUri) == 0
).FirstOrDefault() == null)
{
newPolicies.Add(securityPolicy);
}
break;
}
}
}
}
m_securityPolicies = newPolicies;
}
#endregion
#region Persistent Properties
/// <summary>
/// The base addresses for the server.
/// </summary>
/// <value>The base addresses.</value>
/// <remarks>
/// The actually endpoints are constructed from the security policies.
/// On one base address per supported transport protocol is allowed.
/// </remarks>
[DataMember(IsRequired = false, Order = 0)]
public StringCollection BaseAddresses
{
get
{
return m_baseAddresses;
}
set
{
m_baseAddresses = value;
if (m_baseAddresses == null)
{
m_baseAddresses = new StringCollection();
}
}
}
/// <summary>
/// Gets or sets the alternate base addresses.
/// </summary>
/// <value>The alternate base addresses.</value>
/// <remarks>
/// These addresses are used to specify alternate paths to ther via firewalls, proxies
/// or similar network infrastructure. If these paths are specified in the configuration
/// file then the server will use the domain of the URL used by the client to determine
/// which, if any, or the alternate addresses to use instead of the primary addresses.
/// </remarks>
[DataMember(IsRequired = false, Order = 1)]
public StringCollection AlternateBaseAddresses
{
get
{
return m_alternateBaseAddresses;
}
set
{
m_alternateBaseAddresses = value;
if (m_alternateBaseAddresses == null)
{
m_alternateBaseAddresses = new StringCollection();
}
}
}
/// <summary>
/// The security policies supported by the server.
/// </summary>
/// <value>The security policies.</value>
/// <remarks>
/// An endpoint description is created for each combination of base address and security policy.
/// </remarks>
[DataMember(IsRequired = false, Order = 2)]
public ServerSecurityPolicyCollection SecurityPolicies
{
get
{
return m_securityPolicies;
}
set
{
m_securityPolicies = value;
if (m_securityPolicies == null)
{
m_securityPolicies = new ServerSecurityPolicyCollection();
}
}
}
/// <summary>
/// Gets or sets the minimum number of threads assigned to processing requests.
/// </summary>
/// <value>The minimum request thread count.</value>
[DataMember(IsRequired = false, Order = 3)]
public int MinRequestThreadCount
{
get { return m_minRequestThreadCount; }
set { m_minRequestThreadCount = value; }
}
/// <summary>
/// Gets or sets the maximum number of threads assigned to processing requests.
/// </summary>
/// <value>The maximum request thread count.</value>
[DataMember(IsRequired = false, Order = 4)]
public int MaxRequestThreadCount
{
get { return m_maxRequestThreadCount; }
set { m_maxRequestThreadCount = value; }
}
/// <summary>
/// Gets or sets the maximum number of requests that will be queued waiting for a thread.
/// </summary>
/// <value>The maximum queued request count.</value>
[DataMember(IsRequired = false, Order = 5)]
public int MaxQueuedRequestCount
{
get { return m_maxQueuedRequestCount; }
set { m_maxQueuedRequestCount = value; }
}
#endregion
#region Private Members
private StringCollection m_baseAddresses;
private StringCollection m_alternateBaseAddresses;
private ServerSecurityPolicyCollection m_securityPolicies;
private int m_minRequestThreadCount;
private int m_maxRequestThreadCount;
private int m_maxQueuedRequestCount;
#endregion
}
#endregion
#region ServerConfiguration Class
/// <summary>
/// Specifies the configuration for a server application.
/// </summary>
[DataContract(Namespace = Namespaces.OpcUaConfig)]
public partial class ServerConfiguration : ServerBaseConfiguration
{
#region Constructors
/// <summary>
/// The default constructor.
/// </summary>
public ServerConfiguration()
{
Initialize();
}
/// <summary>
/// Sets private members to default values.
/// </summary>
private void Initialize()
{
m_userTokenPolicies = new UserTokenPolicyCollection();
m_diagnosticsEnabled = false;
m_maxSessionCount = 100;
m_maxSessionTimeout = 3600000;
m_minSessionTimeout = 10000;
m_maxBrowseContinuationPoints = 10;
m_maxQueryContinuationPoints = 10;
m_maxHistoryContinuationPoints = 100;
m_maxRequestAge = 600000;
m_minPublishingInterval = 100;
m_maxPublishingInterval = 3600000;
m_publishingResolution = 100;
m_minSubscriptionLifetime = 10000;
m_maxSubscriptionLifetime = 3600000;
m_maxMessageQueueSize = 10;
m_maxNotificationQueueSize = 100;
m_maxNotificationsPerPublish = 100;
m_minMetadataSamplingInterval = 1000;
m_availableSamplingRates = new SamplingRateGroupCollection();
m_registrationEndpoint = null;
m_maxRegistrationInterval = 30000;
m_maxPublishRequestCount = 20;
m_maxSubscriptionCount = 100;
m_maxEventQueueSize = 10000;
// see https://opcfoundation-onlineapplications.org/profilereporting/ for list of available profiles
m_serverProfileArray = new string[] { "Standard UA Server Profile" };
m_shutdownDelay = 5;
m_serverCapabilities = new string[] { "DA" };
m_supportedPrivateKeyFormats = new string[] { };
m_maxTrustListSize = 0;
m_multicastDnsEnabled = false;
}
/// <summary>
/// Initializes the object during deserialization.
/// </summary>
/// <param name="context">The context.</param>
[OnDeserializing()]
public new void Initialize(StreamingContext context)
{
Initialize();
}
#endregion
#region Persistent Properties
/// <summary>
/// The user tokens accepted by the server.
/// </summary>
/// <value>The user token policies.</value>
[DataMember(IsRequired = false, EmitDefaultValue = false, Order = 3)]
public UserTokenPolicyCollection UserTokenPolicies
{
get
{
return m_userTokenPolicies;
}
set
{
m_userTokenPolicies = value;
if (m_userTokenPolicies == null)
{
m_userTokenPolicies = new UserTokenPolicyCollection();
}
}
}
/// <summary>
/// Whether diagnostics are enabled.
/// </summary>
/// <value><c>true</c> if diagnostic is enabled; otherwise, <c>false</c>.</value>
[DataMember(IsRequired = false, Order = 4)]
public bool DiagnosticsEnabled
{
get { return m_diagnosticsEnabled; }
set { m_diagnosticsEnabled = value; }
}
/// <summary>
/// The maximum number of open sessions.
/// </summary>
/// <value>The maximum session count.</value>
[DataMember(IsRequired = false, Order = 5)]
public int MaxSessionCount
{
get { return m_maxSessionCount; }
set { m_maxSessionCount = value; }
}
/// <summary>
/// That minimum period of that a session is allowed to remain open without communication from the client (in milliseconds).
/// </summary>
/// <value>The minimum session timeout.</value>
[DataMember(IsRequired = false, Order = 6)]
public int MinSessionTimeout
{
get { return m_minSessionTimeout; }
set { m_minSessionTimeout = value; }
}
/// <summary>
/// That maximum period of that a session is allowed to remain open without communication from the client (in milliseconds).
/// </summary>
/// <value>The maximum session timeout.</value>
[DataMember(IsRequired = false, Order = 7)]
public int MaxSessionTimeout
{
get { return m_maxSessionTimeout; }
set { m_maxSessionTimeout = value; }
}
/// <summary>
/// The maximum number of continuation points used for Browse/BrowseNext operations.
/// </summary>
/// <value>The maximum number of continuation points used for Browse/BrowseNext operations</value>
[DataMember(IsRequired = false, Order = 8)]
public int MaxBrowseContinuationPoints
{
get { return m_maxBrowseContinuationPoints; }
set { m_maxBrowseContinuationPoints = value; }
}
/// <summary>
/// The maximum number of continuation points used for Query/QueryNext operations.
/// </summary>
/// <value>The maximum number of query continuation points.</value>
[DataMember(IsRequired = false, Order = 9)]
public int MaxQueryContinuationPoints
{
get { return m_maxQueryContinuationPoints; }
set { m_maxQueryContinuationPoints = value; }
}
/// <summary>
/// The maximum number of continuation points used for HistoryRead operations.
/// </summary>
/// <value>The maximum number of history continuation points.</value>
[DataMember(IsRequired = false, Order = 10)]
public int MaxHistoryContinuationPoints
{
get { return m_maxHistoryContinuationPoints; }
set { m_maxHistoryContinuationPoints = value; }
}
/// <summary>
/// The maximum age of an incoming request (old requests are rejected).
/// </summary>
/// <value>The maximum age of an incoming request.</value>
[DataMember(IsRequired = false, Order = 11)]
public int MaxRequestAge
{
get { return m_maxRequestAge; }
set { m_maxRequestAge = value; }
}
/// <summary>
/// The minimum publishing interval supported by the server (in milliseconds).
/// </summary>
/// <value>The minimum publishing interval.</value>
[DataMember(IsRequired = false, Order = 12)]
public int MinPublishingInterval
{
get { return m_minPublishingInterval; }
set { m_minPublishingInterval = value; }
}
/// <summary>
/// The maximum publishing interval supported by the server (in milliseconds).
/// </summary>
/// <value>The maximum publishing interval.</value>
[DataMember(IsRequired = false, Order = 13)]
public int MaxPublishingInterval
{
get { return m_maxPublishingInterval; }
set { m_maxPublishingInterval = value; }
}
/// <summary>
/// The minimum difference between supported publishing interval (in milliseconds).
/// </summary>
/// <value>The publishing resolution.</value>
[DataMember(IsRequired = false, Order = 14)]
public int PublishingResolution
{
get { return m_publishingResolution; }
set { m_publishingResolution = value; }
}
/// <summary>
/// How long the subscriptions will remain open without a publish from the client.
/// </summary>
/// <value>The maximum subscription lifetime.</value>
[DataMember(IsRequired = false, Order = 15)]
public int MaxSubscriptionLifetime
{
get { return m_maxSubscriptionLifetime; }
set { m_maxSubscriptionLifetime = value; }
}
/// <summary>
/// The maximum number of messages saved in the queue for each subscription.
/// </summary>
/// <value>The maximum size of the message queue.</value>
[DataMember(IsRequired = false, Order = 16)]
public int MaxMessageQueueSize
{
get { return m_maxMessageQueueSize; }
set { m_maxMessageQueueSize = value; }
}
/// <summary>
/// The maximum number of notificates saved in the queue for each monitored item.
/// </summary>
/// <value>The maximum size of the notification queue.</value>
[DataMember(IsRequired = false, Order = 17)]
public int MaxNotificationQueueSize
{
get { return m_maxNotificationQueueSize; }
set { m_maxNotificationQueueSize = value; }
}
/// <summary>
/// The maximum number of notifications per publish.
/// </summary>
/// <value>The maximum number of notifications per publish.</value>
[DataMember(IsRequired = false, Order = 18)]
public int MaxNotificationsPerPublish
{
get { return m_maxNotificationsPerPublish; }
set { m_maxNotificationsPerPublish = value; }
}
/// <summary>
/// The minimum sampling interval for metadata.
/// </summary>
/// <value>The minimum sampling interval for metadata.</value>
[DataMember(IsRequired = false, Order = 19)]
public int MinMetadataSamplingInterval
{
get { return m_minMetadataSamplingInterval; }
set { m_minMetadataSamplingInterval = value; }
}
/// <summary>
/// The available sampling rates.
/// </summary>
/// <value>The available sampling rates.</value>
[DataMember(IsRequired = false, EmitDefaultValue = false, Order = 20)]
public SamplingRateGroupCollection AvailableSamplingRates
{
get { return m_availableSamplingRates; }
set { m_availableSamplingRates = value; }
}
/// <summary>
/// The endpoint description for the registration endpoint.
/// </summary>
/// <value>The registration endpoint.</value>
[DataMember(IsRequired = false, EmitDefaultValue = false, Order = 21)]
public EndpointDescription RegistrationEndpoint
{
get { return m_registrationEndpoint; }
set { m_registrationEndpoint = value; }
}
/// <summary>
/// The maximum time between registration attempts (in milliseconds).
/// </summary>
/// <value>The maximum time between registration attempts (in milliseconds).</value>
[DataMember(IsRequired = false, Order = 22)]
public int MaxRegistrationInterval
{
get { return m_maxRegistrationInterval; }
set { m_maxRegistrationInterval = value; }
}
/// <summary>
/// The path to the file containing nodes persisted by the core node manager.
/// </summary>
/// <value>The path to the file containing nodes persisted by the core node manager.</value>
[DataMember(IsRequired = false, Order = 23)]
public string NodeManagerSaveFile
{
get { return m_nodeManagerSaveFile; }
set { m_nodeManagerSaveFile = value; }
}
/// <summary>
/// The minimum lifetime for a subscription.
/// </summary>
/// <value>The minimum lifetime for a subscription.</value>
[DataMember(IsRequired = false, Order = 24)]
public int MinSubscriptionLifetime
{
get { return m_minSubscriptionLifetime; }
set { m_minSubscriptionLifetime = value; }
}
/// <summary>
/// Gets or sets the max publish request count.
/// </summary>
/// <value>The max publish request count.</value>
[DataMember(IsRequired = false, Order = 25)]
public int MaxPublishRequestCount
{
get { return m_maxPublishRequestCount; }
set { m_maxPublishRequestCount = value; }
}
/// <summary>
/// Gets or sets the max subscription count.
/// </summary>
/// <value>The max subscription count.</value>
[DataMember(IsRequired = false, Order = 26)]
public int MaxSubscriptionCount
{
get { return m_maxSubscriptionCount; }
set { m_maxSubscriptionCount = value; }
}
/// <summary>
/// Gets or sets the max size of the event queue.
/// </summary>
/// <value>The max size of the event queue.</value>
[DataMember(IsRequired = false, Order = 27)]
public int MaxEventQueueSize
{
get { return m_maxEventQueueSize; }
set { m_maxEventQueueSize = value; }
}
/// <summary>
/// Gets or sets the server profile array.
/// </summary>
/// <value>The array of server profiles.</value>
[DataMember(IsRequired = false, Order = 28)]
public StringCollection ServerProfileArray
{
get { return m_serverProfileArray; }
set {
m_serverProfileArray = value;
if (m_serverProfileArray == null)
{
m_serverProfileArray = new StringCollection();
}
}
}
/// <summary>
/// Gets or sets the server shutdown delay.
/// </summary>
/// <value>The array of server profiles.</value>
[DataMember(IsRequired = false, Order = 29)]
public int ShutdownDelay
{
get { return m_shutdownDelay; }
set
{
m_shutdownDelay = value;
}
}
/// <summary>
/// Gets or sets the server capabilities.
/// </summary>
/// <value>The array of server profiles.</value>
[DataMember(IsRequired = false, Order = 30)]
public StringCollection ServerCapabilities
{
get { return m_serverCapabilities; }
set
{
m_serverCapabilities = value;
if (m_serverCapabilities == null)
{
m_serverCapabilities = new StringCollection();
}
}
}
/// <summary>
/// Gets or sets the supported private key format.
/// </summary>
/// <value>The array of server profiles.</value>
[DataMember(IsRequired = false, Order = 31)]
public StringCollection SupportedPrivateKeyFormats
{
get { return m_supportedPrivateKeyFormats; }
set
{
m_supportedPrivateKeyFormats = value;
if (m_supportedPrivateKeyFormats == null)
{
m_supportedPrivateKeyFormats = new StringCollection();
}
}
}
/// <summary>
/// Gets or sets the max size of the trust list.
/// </summary>
[DataMember(IsRequired = false, Order = 32)]
public int MaxTrustListSize
{
get { return m_maxTrustListSize; }
set { m_maxTrustListSize = value; }
}
/// <summary>
/// Gets or sets if multicast DNS is enabled.
/// </summary>
[DataMember(IsRequired = false, Order = 33)]
public bool MultiCastDnsEnabled
{
get { return m_multicastDnsEnabled; }
set { m_multicastDnsEnabled = value; }
}
#endregion
#region Private Members
private UserTokenPolicyCollection m_userTokenPolicies;
private bool m_diagnosticsEnabled;
private int m_maxSessionCount;
private int m_minSessionTimeout;
private int m_maxSessionTimeout;
private int m_maxBrowseContinuationPoints;
private int m_maxQueryContinuationPoints;
private int m_maxHistoryContinuationPoints;
private int m_maxRequestAge;
private int m_minPublishingInterval;
private int m_maxPublishingInterval;
private int m_publishingResolution;
private int m_minSubscriptionLifetime;
private int m_maxSubscriptionLifetime;
private int m_maxMessageQueueSize;
private int m_maxNotificationQueueSize;
private int m_maxNotificationsPerPublish;
private int m_minMetadataSamplingInterval;
private SamplingRateGroupCollection m_availableSamplingRates;
private EndpointDescription m_registrationEndpoint;
private int m_maxRegistrationInterval;
private string m_nodeManagerSaveFile;
private int m_maxPublishRequestCount;
private int m_maxSubscriptionCount;
private int m_maxEventQueueSize;
private StringCollection m_serverProfileArray;
private int m_shutdownDelay;
private StringCollection m_serverCapabilities;
private StringCollection m_supportedPrivateKeyFormats;
private int m_maxTrustListSize;
private bool m_multicastDnsEnabled;
#endregion
}
#endregion
#region ClientConfiguration Class
/// <summary>
/// The configuration for a client application.
/// </summary>
[DataContract(Namespace = Namespaces.OpcUaConfig)]
public partial class ClientConfiguration
{
#region Constructors
/// <summary>
/// The default constructor.
/// </summary>
public ClientConfiguration()
{
Initialize();
}
/// <summary>
/// Sets private members to default values.
/// </summary>
private void Initialize()
{
m_defaultSessionTimeout = 60000;
m_minSubscriptionLifetime = 10000;
m_wellKnownDiscoveryUrls = new StringCollection();
m_discoveryServers = new EndpointDescriptionCollection();
}
/// <summary>
/// Initializes the object during deserialization.
/// </summary>
/// <param name="context">The context.</param>
[OnDeserializing()]
public void Initialize(StreamingContext context)
{
Initialize();
}
#endregion
#region Persistent Properties
/// <summary>
/// The default session timeout.
/// </summary>
/// <value>The default session timeout.</value>
[DataMember(IsRequired = false, Order = 0)]
public int DefaultSessionTimeout
{
get { return m_defaultSessionTimeout; }
set { m_defaultSessionTimeout = value; }
}
/// <summary>
/// The well known URLs for the local discovery servers.
/// </summary>
/// <value>The well known discovery URLs.</value>
[DataMember(IsRequired = false, EmitDefaultValue = false, Order = 1)]
public StringCollection WellKnownDiscoveryUrls
{
get
{
return m_wellKnownDiscoveryUrls;
}
set
{
m_wellKnownDiscoveryUrls = value;
if (m_wellKnownDiscoveryUrls == null)
{
m_wellKnownDiscoveryUrls = new StringCollection();
}
}
}
/// <summary>
/// The endpoint descriptions for central discovery servers.
/// </summary>
/// <value>The endpoint descriptions for central discovery servers.</value>
[DataMember(IsRequired = false, EmitDefaultValue = false, Order = 2)]
public EndpointDescriptionCollection DiscoveryServers
{
get
{
return m_discoveryServers;
}
set
{
m_discoveryServers = value;
if (m_discoveryServers == null)
{
m_discoveryServers = new EndpointDescriptionCollection();
}
}
}
/// <summary>
/// The path to the file containing the cached endpoints.
/// </summary>
/// <value>The path to the file containing the cached endpoints.</value>
[DataMember(IsRequired = false, Order = 3)]
public string EndpointCacheFilePath
{
get { return m_endpointCacheFilePath; }
set { m_endpointCacheFilePath = value; }
}
/// <summary>
/// The minimum lifetime for a subscription.
/// </summary>
/// <value>The minimum lifetime for a subscription.</value>
[DataMember(IsRequired = false, Order = 4)]
public int MinSubscriptionLifetime
{
get { return m_minSubscriptionLifetime; }
set { m_minSubscriptionLifetime = value; }
}
#endregion
#region Private Members
private StringCollection m_wellKnownDiscoveryUrls;
private EndpointDescriptionCollection m_discoveryServers;
private int m_defaultSessionTimeout;
private string m_endpointCacheFilePath;
private int m_minSubscriptionLifetime;
#endregion
}
#endregion
#region DiscoveryServerConfiguration Class
/// <summary>
/// Specifies the configuration for a discovery server application.
/// </summary>
[DataContract(Namespace = Namespaces.OpcUaConfig)]
public class DiscoveryServerConfiguration : ServerBaseConfiguration
{
#region Constructors
/// <summary>
/// The default constructor.
/// </summary>
public DiscoveryServerConfiguration()
{
Initialize();
}
/// <summary>
/// Sets private members to default values.
/// </summary>
private void Initialize()
{
m_serverNames = new LocalizedTextCollection();
m_serverRegistrations = new ServerRegistrationCollection();
}
/// <summary>
/// Initializes the object during deserialization.
/// </summary>
/// <param name="context">The context.</param>
[OnDeserializing()]
public new void Initialize(StreamingContext context)
{
Initialize();
}
#endregion
#region Persistent Properties
/// <summary>
/// The localized names for the discovery server.
/// </summary>
/// <value>The server names.</value>
[DataMember(IsRequired = false, EmitDefaultValue = false, Order = 2)]
public LocalizedTextCollection ServerNames
{
get
{
return m_serverNames;
}
set
{
m_serverNames = value;
if (m_serverNames == null)
{
m_serverNames = new LocalizedTextCollection();
}
}
}
/// <summary>
/// The path to the file containing servers saved by the discovery server.
/// </summary>
/// <value>The discovery server cache file.</value>
[DataMember(IsRequired = false, Order = 3)]
public string DiscoveryServerCacheFile
{
get { return m_discoveryServerCacheFile; }
set { m_discoveryServerCacheFile = value; }
}
/// <summary>
/// Gets or sets the server registrations associated with the discovery server.
/// </summary>
/// <value>The server registrations.</value>
[DataMember(IsRequired = false, EmitDefaultValue = false, Order = 4)]
public ServerRegistrationCollection ServerRegistrations
{
get { return m_serverRegistrations; }
set { m_serverRegistrations = value; }
}
#endregion
#region Private Members
private LocalizedTextCollection m_serverNames;
private string m_discoveryServerCacheFile;
private ServerRegistrationCollection m_serverRegistrations;
#endregion
}
#endregion
#region ServerRegistration Class
/// <summary>
/// Specifies the configuration for a discovery server application.
/// </summary>
[DataContract(Namespace = Namespaces.OpcUaConfig)]
public class ServerRegistration
{
#region Constructors
/// <summary>
/// The default constructor.
/// </summary>
public ServerRegistration()
{
Initialize();
}
/// <summary>
/// Sets private members to default values.
/// </summary>
private void Initialize()
{
m_applicationUri = null;
m_alternateDiscoveryUrls = new StringCollection();
}
/// <summary>
/// Initializes the object during deserialization.
/// </summary>
/// <param name="context">The context.</param>
[OnDeserializing()]
public void Initialize(StreamingContext context)
{
Initialize();
}
#endregion
#region Persistent Properties
/// <summary>
/// Gets or sets the application URI of the server which the registration applies to.
/// </summary>
/// <value>The application uri.</value>
[DataMember(IsRequired = false, EmitDefaultValue = false, Order = 1)]
public string ApplicationUri
{
get
{
return m_applicationUri;
}
set
{
m_applicationUri = value;
}
}
/// <summary>
/// Gets or sets the alternate discovery urls.
/// </summary>
/// <value>The alternate discovery urls.</value>
/// <remarks>
/// These addresses are used to specify alternate paths to ther via firewalls, proxies
/// or similar network infrastructure. If these paths are specified in the configuration
/// file then the server will use the domain of the URL used by the client to determine
/// which, if any, or the alternate addresses to use instead of the primary addresses.
///
/// In the ideal world the server would provide these URLs during registration but this
/// table allows the administrator to provide the information to the disovery server
/// directly without requiring a patch to the server.
/// </remarks>
[DataMember(IsRequired = false, EmitDefaultValue = false, Order = 2)]
public StringCollection AlternateDiscoveryUrls
{
get
{
return m_alternateDiscoveryUrls;
}
set
{
m_alternateDiscoveryUrls = value;
if (m_alternateDiscoveryUrls == null)
{
m_alternateDiscoveryUrls = new StringCollection();
}
}
}
#endregion
#region Private Members
private string m_applicationUri;
private StringCollection m_alternateDiscoveryUrls;
#endregion
}
#endregion
#region ServerRegistrationCollection Class
/// <summary>
/// A collection of AdditionalServerRegistrationInfo objects.
/// </summary>
[CollectionDataContract(Name = "ListOfServerRegistration", Namespace = Namespaces.OpcUaConfig, ItemName = "ServerRegistration")]
public partial class ServerRegistrationCollection : List<ServerRegistration>
{
/// <summary>
/// Initializes an empty collection.
/// </summary>
public ServerRegistrationCollection() { }
/// <summary>
/// Initializes the collection from another collection.
/// </summary>
/// <param name="collection">A collection of values to add to this new collection</param>
/// <exception cref="T:System.ArgumentNullException">
/// <paramref name="collection"/> is null.
/// </exception>
public ServerRegistrationCollection(IEnumerable<ServerRegistration> collection) : base(collection) { }
/// <summary>
/// Initializes the collection with the specified capacity.
/// </summary>
/// <param name="capacity">The capacity.</param>
public ServerRegistrationCollection(int capacity) : base(capacity) { }
}
#endregion
#region CertificateStoreIdentifier Class
/// <summary>
/// Describes a certificate store.
/// </summary>
[DataContract(Namespace = Namespaces.OpcUaConfig)]
public partial class CertificateStoreIdentifier
{
#region Persistent Properties
/// <summary>
/// The type of certificate store.
/// </summary>
/// <value>
/// If the StoreName is not empty, the CertificateStoreType.X509Store is returned, otherwise the StoreType is returned.
/// </value>
[DataMember(IsRequired = false, EmitDefaultValue = false, Order = 0)]
public string StoreType
{
get
{
if (!String.IsNullOrEmpty(m_storeName))
{
return CertificateStoreType.X509Store;
}
return m_storeType;
}
set
{
m_storeType = value;
}
}
/// <summary>
/// The path that identifies the certificate store.
/// </summary>
/// <value>
/// If the StoreName is not empty and the StoreLocation is empty, the Utils.Format("LocalMachine\\{0}", m_storeName) is returned.
/// If the StoreName is not empty and the StoreLocation is not empty, the Utils.Format("{1}\\{0}", m_storeName, m_storeLocation) is returned.
/// If the StoreName is empty, the m_storePath is returned.
/// </value>
[DataMember(IsRequired = false, EmitDefaultValue = false, Order = 1)]
public string StorePath
{
get
{
if (!String.IsNullOrEmpty(m_storeName))
{
if (String.IsNullOrEmpty(m_storeLocation))
{
return Utils.Format("CurrentUser\\{0}", m_storeName);
}
return Utils.Format("{1}\\{0}", m_storeName, m_storeLocation);
}
return m_storePath;
}
set
{
m_storePath = value;
if (!String.IsNullOrEmpty(m_storePath))
{
if (String.IsNullOrEmpty(m_storeType))
{
if (m_storePath.StartsWith("LocalMachine", StringComparison.CurrentCultureIgnoreCase) || m_storePath.StartsWith("CurrentUser", StringComparison.CurrentCultureIgnoreCase))
{
m_storeType = CertificateStoreType.X509Store;
}
else
{
m_storeType = CertificateStoreType.Directory;
}
}
}
}
}
/// <summary>
/// The name of the certifcate store that contains the trusted certficates.
/// </summary>
[DataMember(IsRequired = false, EmitDefaultValue = false, Order = 2)]
[Obsolete("Use StoreType/StorePath instead")]
public string StoreName
{
get { return m_storeName; }
set { m_storeName = value; }
}
/// <summary>
/// The location of the certifcate store that contains the trusted certficates.
/// </summary>
[DataMember(IsRequired = false, EmitDefaultValue = false, Order = 3)]
[Obsolete("Use StoreType/StorePath instead")]
public string StoreLocation
{
get { return m_storeLocation; }
set { m_storeLocation = value; }
}
/// <summary>
/// Options that can be used to suppress certificate validation errors.
/// </summary>
[DataMember(Name = "ValidationOptions", IsRequired = false, EmitDefaultValue = false, Order = 4)]
private int XmlEncodedValidationOptions
{
get { return (int)m_validationOptions; }
set { m_validationOptions = (CertificateValidationOptions)value; }
}
#endregion
#region Private Fields
private string m_storeType;
private string m_storePath;
private string m_storeLocation;
private string m_storeName;
private CertificateValidationOptions m_validationOptions;
#endregion
}
#endregion
#region CertificateTrustList Class
[DataContract(Namespace = Namespaces.OpcUaConfig)]
public partial class CertificateTrustList : CertificateStoreIdentifier
{
#region Constructors
/// <summary>
/// The default constructor.
/// </summary>
public CertificateTrustList()
{
Initialize();
}
/// <summary>
/// Sets private members to default values.
/// </summary>
private void Initialize()
{
m_trustedCertificates = new CertificateIdentifierCollection();
}
/// <summary>
/// Initializes the object during deserialization.
/// </summary>
[OnDeserializing()]
public void Initialize(StreamingContext context)
{
Initialize();
}
#endregion
#region Persistent Properties
/// <summary>
/// The list of trusted certificates.
/// </summary>
/// <value>
/// The list of trusted certificates is set when TrustedCertificates is not a null value, otherwise new CertificateIdentifierCollection is set.
/// </value>
[DataMember(IsRequired = false, EmitDefaultValue = false, Order = 3)]
public CertificateIdentifierCollection TrustedCertificates
{
get
{
return m_trustedCertificates;
}
set
{
m_trustedCertificates = value;
if (m_trustedCertificates == null)
{
m_trustedCertificates = new CertificateIdentifierCollection();
}
}
}
#endregion
#region Private Fields
private CertificateIdentifierCollection m_trustedCertificates;
#endregion
}
#endregion
#region CertificateIdentifierCollection Class
[CollectionDataContract(Name = "ListOfCertificateIdentifier", Namespace = Namespaces.OpcUaConfig, ItemName = "CertificateIdentifier")]
public partial class CertificateIdentifierCollection : List<CertificateIdentifier>
{
/// <summary>
/// Initializes an empty collection.
/// </summary>
public CertificateIdentifierCollection() { }
/// <summary>
/// Initializes the collection from another collection.
/// </summary>
/// <param name="collection">A collection of values to add to this new collection</param>
public CertificateIdentifierCollection(IEnumerable<CertificateIdentifier> collection) : base(collection) { }
/// <summary>
/// Initializes the collection with the specified capacity.
/// </summary>
public CertificateIdentifierCollection(int capacity) : base(capacity) { }
}
#endregion
#region CertificateIdentifier Class
[DataContract(Namespace = Namespaces.OpcUaConfig)]
public partial class CertificateIdentifier
{
#region Constructors
/// <summary>
/// The default constructor.
/// </summary>
public CertificateIdentifier()
{
Initialize();
}
/// <summary>
/// Initializes the identifier with the raw data from a certificate.
/// </summary>
public CertificateIdentifier(X509Certificate2 certificate)
{
Initialize();
m_certificate = certificate;
}
/// <summary>
/// Initializes the identifier with the raw data from a certificate.
/// </summary>
public CertificateIdentifier(X509Certificate2 certificate, CertificateValidationOptions validationOptions)
{
Initialize();
m_certificate = certificate;
m_validationOptions = validationOptions;
}
/// <summary>
/// Initializes the identifier with the raw data from a certificate.
/// </summary>
public CertificateIdentifier(byte[] rawData)
{
Initialize();
m_certificate = CertificateFactory.Create(rawData, true);
}
/// <summary>
/// Sets private members to default values.
/// </summary>
private void Initialize()
{
}
/// <summary>
/// Initializes the object during deserialization.
/// </summary>
[OnDeserializing()]
public void Initialize(StreamingContext context)
{
Initialize();
}
#endregion
#region Public Properties
/// <summary>
/// The type of certificate store.
/// </summary>
/// <value>The type of the store - defined in the <see cref="CertificateStoreType"/>.</value>
[DataMember(IsRequired = false, EmitDefaultValue = false, Order = 0)]
public string StoreType
{
get
{
if (!String.IsNullOrEmpty(m_storeName))
{
return CertificateStoreType.X509Store;
}
return m_storeType;
}
set
{
m_storeType = value;
}
}
/// <summary>
/// The path that identifies the certificate store.
/// </summary>
/// <value>The store path in the form <c>StoreName\\Store Location</c> .</value>
[DataMember(IsRequired = false, EmitDefaultValue = false, Order = 1)]
public string StorePath
{
get
{
if (!String.IsNullOrEmpty(m_storeName))
{
if (String.IsNullOrEmpty(m_storeLocation))
{
return Utils.Format("LocalMachine\\{0}", m_storeName);
}
return Utils.Format("{1}\\{0}", m_storeName, m_storeLocation);
}
return m_storePath;
}
set
{
m_storePath = value;
if (!String.IsNullOrEmpty(m_storePath))
{
if (String.IsNullOrEmpty(m_storeType))
{
if (m_storePath.StartsWith("LocalMachine", StringComparison.CurrentCultureIgnoreCase) || m_storePath.StartsWith("CurrentUser", StringComparison.CurrentCultureIgnoreCase))
{
m_storeType = CertificateStoreType.X509Store;
}
else
{
m_storeType = CertificateStoreType.Directory;
}
}
}
}
}
/// <summary>
/// The name of the store that contains the certificate.
/// </summary>
/// <value>The name of the store.</value>
/// <seealso cref="System.Security.Cryptography.X509Certificates.StoreName"/>
[DataMember(IsRequired = false, EmitDefaultValue = false, Order = 2)]
[Obsolete("Use StoreType/StorePath instead")]
public string StoreName
{
get { return m_storeName; }
set { m_storeName = value; }
}
/// <summary>
/// The location of the store that contains the certificate.
/// </summary>
/// <value>The store location.</value>
/// <seealso cref="System.Security.Cryptography.X509Certificates.StoreLocation"/>
[DataMember(IsRequired = false, EmitDefaultValue = false, Order = 3)]
[Obsolete("Use StoreType/StorePath instead")]
public string StoreLocation
{
get { return m_storeLocation; }
set { m_storeLocation = value; }
}
/// <summary>
/// The certificate's subject name - the distinguished name of an X509 certificate.
/// </summary>
/// <value>
/// The distinguished name of an X509 certificate acording to the Abstract Syntax Notation One (ASN.1) syntax.
/// </value>
/// <remarks> The subject field identifies the entity associated with the public key stored in the subject public
/// key field. The subject name MAY be carried in the subject field and/or the subjectAltName extension.
/// Where it is non-empty, the subject field MUST contain an X.500 distinguished name (DN).
/// Name is defined by the following ASN.1 structures:
/// Name ::= CHOICE {RDNSequence }
/// RDNSequence ::= SEQUENCE OF RelativeDistinguishedName
/// RelativeDistinguishedName ::= SET OF AttributeTypeAndValue
/// AttributeTypeAndValue ::= SEQUENCE {type AttributeType, value AttributeValue }
/// AttributeType ::= OBJECT IDENTIFIER
/// AttributeValue ::= ANY DEFINED BY AttributeType
/// DirectoryString ::= CHOICE {
/// teletexString TeletexString (SIZE (1..MAX)),
/// printableString PrintableString (SIZE (1..MAX)),
/// universalString UniversalString (SIZE (1..MAX)),
/// utf8String UTF8String (SIZE (1..MAX)),
/// bmpString BMPString (SIZE (1..MAX)) }
/// The Name describes a hierarchical name composed of attributes, such as country name, and
/// corresponding values, such as US. The type of the component AttributeValue is determined by
/// the AttributeType; in general it will be a DirectoryString.
/// String X.500 AttributeType:
/// <list type="bullet">
/// <item>CN commonName</item>
/// <item>L localityName</item>
/// <item>ST stateOrProvinceName</item>
/// <item>O organizationName</item>
/// <item>OU organizationalUnitName</item>
/// <item>C countryName</item>
/// <item>STREET streetAddress</item>
/// <item>DC domainComponent</item>
/// <item>UID userid</item>
/// </list>
/// This notation is designed to be convenient for common forms of name. This section gives a few
/// examples of distinguished names written using this notation. First is a name containing three relative
/// distinguished names (RDNs):
/// <code>CN=Steve Kille,O=Isode Limited,C=GB</code>
///
/// RFC 3280 Internet X.509 Public Key Infrastructure, April 2002
/// RFC 2253 LADPv3 Distinguished Names, December 1997
/// </remarks>
/// <seealso cref="System.Security.Cryptography.X509Certificates.X500DistinguishedName"/>
/// <seealso cref="System.Security.Cryptography.AsnEncodedData"/>
[DataMember(IsRequired = false, EmitDefaultValue = false, Order = 4)]
public string SubjectName
{
get
{
if (m_certificate == null)
{
return m_subjectName;
}
return m_certificate.Subject;
}
set
{
if (m_certificate != null && !String.IsNullOrEmpty(value))
{
if (m_certificate.Subject != value)
{
throw new ArgumentException("SubjectName does not match the SubjectName of the current certificate.");
}
}
m_subjectName = value;
}
}
/// <summary>
/// The certificate's thumbprint.
/// </summary>
/// <value>The thumbprint of a certificate..</value>
/// <seealso cref="X509Certificate2"/>
[DataMember(IsRequired = false, EmitDefaultValue = false, Order = 5)]
public string Thumbprint
{
get
{
if (m_certificate == null)
{
return m_thumbprint;
}
return m_certificate.Thumbprint;
}
set
{
if (m_certificate != null)
{
if (!String.IsNullOrEmpty(value) && m_certificate.Thumbprint != value)
{
throw new ArgumentException("Thumbprint does not match the thumbprint of the current certificate.");
}
}
m_thumbprint = value;
}
}
/// <summary>
/// Gets the DER encoded certificate data or create emebeded in this instance certifcate using the DER encoded certificate data.
/// </summary>
/// <value>A byte array containing the X.509 certificate data.</value>
[DataMember(IsRequired = false, EmitDefaultValue = false, Order = 6)]
public byte[] RawData
{
get
{
if (m_certificate == null)
{
return null;
}
return m_certificate.RawData;
}
set
{
if (value == null || value.Length == 0)
{
m_certificate = null;
return;
}
m_certificate = CertificateFactory.Create(value, true);
m_subjectName = m_certificate.Subject;
m_thumbprint = m_certificate.Thumbprint;
}
}
/// <summary>
/// Gets or sets the XML encoded validation options - use to serialize the validation options.
/// </summary>
/// <value>The XML encoded validation options.</value>
[DataMember(Name = "ValidationOptions", IsRequired = false, EmitDefaultValue = false, Order = 7)]
private int XmlEncodedValidationOptions
{
get { return (int)m_validationOptions; }
set { m_validationOptions = (CertificateValidationOptions)value; }
}
#endregion
#region Private Fields
private string m_storeType;
private string m_storePath;
private string m_storeLocation;
private string m_storeName;
private string m_subjectName;
private string m_thumbprint;
private X509Certificate2 m_certificate;
private CertificateValidationOptions m_validationOptions;
#endregion
}
#endregion
#region ConfiguredEndpointCollection Class
/// <summary>
/// Stores a list of cached enpoints.
/// </summary>
[DataContract(Namespace = Namespaces.OpcUaConfig)]
public partial class ConfiguredEndpointCollection
{
#region Constructors
/// <summary>
/// The default constructor.
/// </summary>
public ConfiguredEndpointCollection()
{
Initialize();
}
/// <summary>
/// Called by the .NET framework during deserialization.
/// </summary>
[OnDeserializing]
public void Initialize(StreamingContext context)
{
Initialize();
}
/// <summary>
/// Sets private members to default values.
/// </summary>
private void Initialize()
{
m_knownHosts = new StringCollection();
m_discoveryUrls = new StringCollection(Utils.DiscoveryUrls);
m_endpoints = new List<ConfiguredEndpoint>();
m_defaultConfiguration = EndpointConfiguration.Create();
}
#endregion
#region Public Properties
/// <summary>
/// A list of known hosts that can be used for discovery.
/// </summary>
[DataMember(Name = "KnownHosts", IsRequired = false, Order = 1)]
public StringCollection KnownHosts
{
get
{
return m_knownHosts;
}
set
{
if (value == null)
{
m_knownHosts = new StringCollection();
}
else
{
m_knownHosts = value;
}
}
}
/// <summary>
/// The default configuration to use when connecting to an endpoint.
/// </summary>
[DataMember(Name = "Endpoints", IsRequired = false, Order = 2)]
public List<ConfiguredEndpoint> Endpoints
{
get
{
return m_endpoints;
}
private set
{
if (value == null)
{
m_endpoints = new List<ConfiguredEndpoint>();
}
else
{
m_endpoints = value;
}
foreach (ConfiguredEndpoint endpoint in m_endpoints)
{
endpoint.Collection = this;
}
}
}
/// <summary>
/// The URL of the UA TCP proxy server.
/// </summary>
[DataMember(Name = "TcpProxyUrl", EmitDefaultValue = false, Order = 3)]
public Uri TcpProxyUrl
{
get
{
return m_tcpProxyUrl;
}
set
{
m_tcpProxyUrl = value;
}
}
#endregion
#region Private Fields
private string m_filepath;
private StringCollection m_knownHosts;
private StringCollection m_discoveryUrls;
private EndpointConfiguration m_defaultConfiguration;
private List<ConfiguredEndpoint> m_endpoints;
private Uri m_tcpProxyUrl;
#endregion
}
#endregion
#region ConfiguredEndpoint Class
/// <summary>
/// Stores the configuration information for an endpoint.
/// </summary>
[DataContract(Namespace = Namespaces.OpcUaConfig)]
[KnownType(typeof(UserNameIdentityToken))]
[KnownType(typeof(X509IdentityToken))]
[KnownType(typeof(IssuedIdentityToken))]
public partial class ConfiguredEndpoint
{
#region Constructors
/// <summary>
/// The default constructor.
/// </summary>
public ConfiguredEndpoint()
{
Initialize();
}
/// <summary>
/// Called by the .NET framework during deserialization.
/// </summary>
[OnDeserializing]
public void Initialize(StreamingContext context)
{
Initialize();
}
/// <summary>
/// Sets private members to default values.
/// </summary>
private void Initialize()
{
m_collection = null;
m_description = new EndpointDescription();
m_configuration = null;
m_updateBeforeConnect = true;
m_binaryEncodingSupport = BinaryEncodingSupport.Optional;
m_selectedUserTokenPolicyIndex = 0;
m_userIdentity = null;
}
#endregion
#region Public Properties
/// <summary>
/// The description for the endpoint.
/// </summary>
[DataMember(Name = "Endpoint", Order = 1, IsRequired = true)]
public EndpointDescription Description
{
get
{
return m_description;
}
private set
{
if (value == null)
{
m_description = new EndpointDescription();
}
else
{
m_description = value;
}
}
}
/// <summary>
/// The configuration to use when connecting to an endpoint.
/// </summary>
[DataMember(Name = "Configuration", Order = 2, IsRequired = false)]
public EndpointConfiguration Configuration
{
get
{
return m_configuration;
}
set
{
m_configuration = value;
// copy default configuration if not already set.
if (m_configuration == null)
{
if (m_collection != null)
{
Update(m_collection.DefaultConfiguration);
}
else
{
Update(EndpointConfiguration.Create());
}
}
}
}
/// <summary>
/// Whether the endpoint information should be updated before connecting to the server.
/// </summary>
[DataMember(Name = "UpdateBeforeConnect", Order = 3, IsRequired = false)]
public bool UpdateBeforeConnect
{
get { return m_updateBeforeConnect; }
set { m_updateBeforeConnect = value; }
}
/// <summary>
/// The user identity to use when connecting to the endpoint.
/// </summary>
[DataMember(Name = "BinaryEncodingSupport", Order = 4, IsRequired = false)]
public BinaryEncodingSupport BinaryEncodingSupport
{
get { return m_binaryEncodingSupport; }
set { m_binaryEncodingSupport = value; }
}
/// <summary>
/// The user identity to use when connecting to the endpoint.
/// </summary>
[DataMember(Name = "SelectedUserTokenPolicy", Order = 5, IsRequired = false)]
public int SelectedUserTokenPolicyIndex
{
get { return m_selectedUserTokenPolicyIndex; }
set { m_selectedUserTokenPolicyIndex = value; }
}
/// <summary>
/// The user identity to use when connecting to the endpoint.
/// </summary>
[DataMember(Name = "UserIdentity", Order = 6, IsRequired = false)]
public UserIdentityToken UserIdentity
{
get { return m_userIdentity; }
set { m_userIdentity = value; }
}
/// <summary>
/// A list of COM identities associated with the endpoint.
/// </summary>
[DataMember(Name = "ComIdentity", Order = 7, IsRequired = false)]
public EndpointComIdentity ComIdentity
{
get { return m_comIdentity; }
set { m_comIdentity = value; }
}
/// <summary>
/// A bucket to store additional application specific configuration data.
/// </summary>
[DataMember(IsRequired = false, EmitDefaultValue = false, Order = 9)]
public XmlElementCollection Extensions
{
get { return m_extensions; }
set { m_extensions = value; }
}
#endregion
#region Private Fields
private ConfiguredEndpointCollection m_collection;
private EndpointDescription m_description;
private EndpointConfiguration m_configuration;
private bool m_updateBeforeConnect;
private BinaryEncodingSupport m_binaryEncodingSupport;
private int m_selectedUserTokenPolicyIndex;
private UserIdentityToken m_userIdentity;
private EndpointComIdentity m_comIdentity;
private XmlElementCollection m_extensions;
#endregion
}
#endregion
#region BinaryEncodingSupport Enumeration
/// <summary>
/// The type of binary encoding support allowed by a channel.
/// </summary>
[DataContract(Namespace = Namespaces.OpcUaConfig)]
public enum BinaryEncodingSupport
{
/// <summary>
/// The UA binary encoding may be used.
/// </summary>
[EnumMember()]
Optional,
/// <summary>
/// The UA binary encoding must be used.
/// </summary>
[EnumMember()]
Required,
/// <summary>
/// The UA binary encoding may not be used.
/// </summary>
[EnumMember()]
None
}
#endregion
#region EndpointComIdentity Class
/// <summary>
/// Stores the COM identity for an endpoint.
/// </summary>
[DataContract(Namespace = Namespaces.OpcUaConfig)]
public partial class EndpointComIdentity
{
#region Constructors
/// <summary>
/// The default constructor.
/// </summary>
public EndpointComIdentity()
{
}
/// <summary>
/// Called by the .NET framework during deserialization.
/// </summary>
[OnDeserializing]
public void Initialize(StreamingContext context)
{
Initialize();
}
/// <summary>
/// Sets private members to default values.
/// </summary>
private void Initialize()
{
m_clsid = Guid.Empty;
m_progId = null;
m_specification = ComSpecification.DA;
}
#endregion
#region Public Properties
/// <summary>
/// The CLSID for the COM server.
/// </summary>
[DataMember(Name = "Clsid", Order = 1, IsRequired = true)]
public Uuid XmlClsid
{
get { return new Uuid(m_clsid); }
set { m_clsid = (Guid)value; }
}
/// <summary>
/// The ProgID for the COM server.
/// </summary>
[DataMember(Name = "ProgId", Order = 2, IsRequired = true)]
public string ProgId
{
get { return m_progId; }
set { m_progId = value; }
}
/// <summary>
/// The COM specification supported by the COM server.
/// </summary>
[DataMember(Name = "Specification", Order = 3, IsRequired = true)]
public ComSpecification Specification
{
get { return m_specification; }
set { m_specification = value; }
}
#endregion
#region Private Fields
private Guid m_clsid;
private string m_progId;
private ComSpecification m_specification;
#endregion
}
#endregion
#region ComSpecification Enumeration
/// <summary>
/// The available COM specifications.
/// </summary>
[DataContract(Namespace = Namespaces.OpcUaConfig)]
public enum ComSpecification
{
/// <summary>
/// Data Access 2.05a and 3.00
/// </summary>
[EnumMember()]
DA,
/// <summary>
/// Alarms and Events 1.00
/// </summary>
[EnumMember()]
AE,
/// <summary>
/// Historical Data Access 1.20
/// </summary>
[EnumMember()]
HDA
}
#endregion
#region ApplicationAccessRule Class
/// <summary>
/// An access rule for an application.
/// </summary>
[DataContract(Namespace = Namespaces.OpcUaConfig)]
public partial class ApplicationAccessRule
{
#region Public Properties
/// <summary>
/// The type of access rule.
/// </summary>
[DataMember(Order = 1)]
public AccessControlType RuleType
{
get { return m_ruleType; }
set { m_ruleType = value; }
}
/// <summary>
/// The access right affected by the rule.
/// </summary>
[DataMember(Order = 2)]
public ApplicationAccessRight Right
{
get { return m_right; }
set { m_right = value; }
}
/// <summary>
/// The name of the NT account principal which the access rule applies to.
/// </summary>
[DataMember(Order = 3)]
public string IdentityName
{
get
{
return m_identityName;
}
set { m_identityName = value; }
}
#endregion
#region Private Fields
private AccessControlType m_ruleType;
private ApplicationAccessRight m_right;
private String m_identityName;
#endregion
}
#endregion
#region AccessControlType Enumeration
/// <summary>
/// The rights to an application that may be granted to the user.
/// </summary>
[DataContract(Namespace = Namespaces.OpcUaConfig)]
public enum AccessControlType
{
/// <summary>
/// Allows access to the specified account.
/// </summary>
[EnumMember]
Allow = 0x0,
/// <summary>
/// Denies access to the specified account.
/// </summary>
[EnumMember]
Deny = 0x1
}
#endregion
#region ApplicationAccessRight Enumeration
/// <summary>
/// The rights to an application that may be granted to the user.
/// </summary>
[DataContract(Namespace = Namespaces.OpcUaConfig)]
public enum ApplicationAccessRight
{
/// <summary>
/// The account has no access.
/// </summary>
[EnumMember]
None = 0x0,
/// <summary>
/// The account can run the application.
/// </summary>
[EnumMember]
Run = 0x1,
/// <summary>
/// The account can update the application configuration.
/// </summary>
[EnumMember]
Update = 0x2,
/// <summary>
/// The account can change the application access rights.
/// </summary>
[EnumMember]
Configure = 0x3
}
#endregion
#region ApplicationAccessRuleCollection Class
/// <summary>
/// A collection of ApplicationAccessRule objects.
/// </summary>
[CollectionDataContract(Name = "ListOfApplicationAccessRule", Namespace = Namespaces.OpcUaConfig, ItemName = "ApplicationAccessRule")]
public partial class ApplicationAccessRuleCollection : List<ApplicationAccessRule>
{
#region Constructors
/// <summary>
/// Initializes the collection with default values.
/// </summary>
public ApplicationAccessRuleCollection() { }
/// <summary>
/// Initializes the collection with an initial capacity.
/// </summary>
public ApplicationAccessRuleCollection(int capacity) : base(capacity) { }
/// <summary>
/// Initializes the collection with another collection.
/// </summary>
public ApplicationAccessRuleCollection(IEnumerable<ApplicationAccessRule> collection) : base(collection) { }
#endregion
}
#endregion
}
| 33.919732 | 194 | 0.561625 | [
"MIT"
] | Hpshboss/OpcuaCncControl | UANETStandardCNC/Stack/Opc.Ua.Core/Schema/ApplicationConfiguration.cs | 111,562 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using Telerik.Windows.Controls;
using Model.Extension;
using System.Collections.ObjectModel;
using Kernel;
using System.Transactions;
using DistributionModel;
using DBAccess;
using SysProcessModel;
using SysProcessViewModel;
using ERPModelBO;
namespace ERPViewModelBasic
{
public abstract class BillVMBase<TBill, TDetails, TItemShow> : ViewModelBase
where TBill : BillBase, new()
where TDetails : BillDetailBase
where TItemShow : ProductShow, new()
{
#region 属性
private LinqOPEncap _linqOP;
public string InputLabelString { get; private set; }
private TBill _master;
/// <summary>
/// 单据信息
/// </summary>
public TBill Master
{
get
{
if (_master == null)
_master = new TBill();
return _master;
}
set
{
if (_master != value)
{
_master = value;
OnPropertyChanged("Master");
}
}
}
/// <summary>
/// 单据明细
/// </summary>
public List<TDetails> Details { get; set; }
private ObservableCollection<TItemShow> _gridDataItems = new ObservableCollection<TItemShow>();
/// <summary>
/// 扫单产生的列表数据
/// </summary>
public ObservableCollection<TItemShow> GridDataItems { get { return _gridDataItems; } }
/// <summary>
/// 删除一条记录
/// </summary>
//public ICommand DeleteItemCommand
//{
// get
// {
// return new DelegateCommand(param =>
// {
// TItemShow item = (TItemShow)param;
// GridDataItems.Remove(item);
// });
// }
//}
#endregion
public BillVMBase(LinqOPEncap linqOP)
{
_linqOP = linqOP;
InputLabelString = "SKU码|款号";
}
/// <summary>
/// 生成单据编号
/// </summary>
protected abstract string GenerateBillCode();
/// <summary>
/// 初始化
/// </summary>
public virtual void Init()
{
this.Master = null;
this.Details = null;
GridDataItems.Clear();
}
/// <summary>
/// 款号或SKU码输入
/// </summary>
public virtual void ProductCodeInput(string pcode, Action<IEnumerable<TItemShow>> actionWhenMore)
{
if (GridDataItems.Count > 0)
{
foreach (var product in GridDataItems)
{
if (product.ProductCode == pcode)
{
product.Quantity += 1;
return;
}
}
}
var datas = this.GetProductForShow(pcode);
if (datas != null && datas.Count > 0)
{
if (datas.Count == 1 && pcode == datas[0].ProductCode)//是条形码
{
var item = GridDataItems.FirstOrDefault(o => o.ProductID == datas[0].ProductID);
if (item != null)
item.Quantity += 1;
else
{
datas[0].Quantity = 1;
GridDataItems.Add(datas[0]);
}
}
else
{
if (actionWhenMore != null)
actionWhenMore(datas);
}
}
else
{
throw new Exception("没有相关成品信息.");
}
}
public virtual void AddRangeToItems(IEnumerable<TItemShow> datas)
{
foreach (var data in datas)
{
if (data.Quantity != 0)
{
var item = GridDataItems.FirstOrDefault(o => o.ProductID == data.ProductID);
if (item != null)
item.Quantity += data.Quantity;
else
GridDataItems.Add(data);
}
}
}
/// <summary>
/// 遍历列表数据
/// </summary>
public virtual void TraverseGridDataItems(Action<TItemShow> action)
{
foreach (var item in GridDataItems)
{
if (item.Quantity != 0)
{
action(item);
}
}
}
public void DeleteItem(TItemShow item)
{
GridDataItems.Remove(item);
}
protected virtual List<TItemShow> GetProductForShow(string code)
{
var brandIDs = VMGlobal.PoweredBrands.Select(o => o.ID);
var products = VMGlobal.SysProcessQuery.LinqOP.GetDataContext<Product>();
var prostyles = VMGlobal.SysProcessQuery.LinqOP.GetDataContext<ProStyle>();
var byqs = VMGlobal.SysProcessQuery.LinqOP.GetDataContext<ProBYQ>();
var query = from s in prostyles
from byq in byqs
where s.BYQID == byq.ID && brandIDs.Contains(byq.BrandID)
from p in products
where p.StyleID == s.ID && (p.Code == code || s.Code == code) && p.Flag
select new
{
ProductID = p.ID,
ProductCode = p.Code,
BrandID = byq.BrandID,
StyleCode = s.Code,
ColorID = p.ColorID,
SizeID = p.SizeID,
Year = byq.Year,
Quarter = byq.Quarter,
Price = s.Price,
BYQID = s.BYQID
};
var ps = query.ToList();
if (ps.Count > 0)
{
return ps.Select(o => new TItemShow
{
ProductID = o.ProductID,
ProductCode = o.ProductCode,
BrandCode = VMGlobal.PoweredBrands.Find(b => b.ID == o.BrandID).Code,
StyleCode = o.StyleCode,
ColorCode = VMGlobal.Colors.Find(c => c.ID == o.ColorID).Code,
SizeCode = VMGlobal.Sizes.Find(s => s.ID == o.SizeID).Code,
SizeName = VMGlobal.Sizes.Find(s => s.ID == o.SizeID).Name,
BrandID = o.BrandID,
Year = o.Year,
Quarter = o.Quarter,
BYQID = o.BYQID,
Price = o.Price
}).ToList();
}
return null;
}
public virtual TItemShow GetProductForShow(int productID)
{
var brandIDs = VMGlobal.PoweredBrands.Select(o => o.ID);
var products = VMGlobal.SysProcessQuery.LinqOP.GetDataContext<Product>();
var prostyles = VMGlobal.SysProcessQuery.LinqOP.GetDataContext<ProStyle>();
var byqs = VMGlobal.SysProcessQuery.LinqOP.GetDataContext<ProBYQ>();
var query = from p in products
from s in prostyles
where p.StyleID == s.ID && p.ID == productID && p.Flag
from byq in byqs
where s.BYQID == byq.ID && brandIDs.Contains(byq.BrandID)
select new TItemShow
{
ProductID = productID,
ProductCode = p.Code,
BrandCode = VMGlobal.PoweredBrands.Find(b => b.ID == byq.BrandID).Code,
StyleCode = s.Code,
ColorCode = VMGlobal.Colors.Find(o => o.ID == p.ColorID).Code,
SizeCode = VMGlobal.Sizes.Find(o => o.ID == p.SizeID).Code,
SizeName = VMGlobal.Sizes.Find(o => o.ID == p.SizeID).Name,
BrandID = byq.BrandID,
Year = byq.Year,
Quarter = byq.Quarter,
BYQID = s.BYQID,
Price = s.Price
};
return query.FirstOrDefault();
}
#region 保存单据
/// <summary>
/// 保存单据
/// </summary>
public virtual OPResult Save()
{
var bill = Master;
bill.CreatorID = VMGlobal.CurrentUser.ID;
bill.Code = this.GenerateBillCode();
var details = Details;
using (TransactionScope scope = new TransactionScope())
{
try
{
bill.ID = _linqOP.Add<TBill, int>(bill, b => b.ID);
details.ForEach(d => d.BillID = bill.ID);
_linqOP.Add<TDetails>(details);
scope.Complete();
}
catch (Exception e)
{
return new OPResult { IsSucceed = false, Message = e.Message };
}
}
return new OPResult { IsSucceed = true, Message = "保存成功." };
}
/// <summary>
/// 保存单据(不经过事务和异常处理)
/// </summary>
public virtual void SaveWithNoTran()
{
var bill = Master;
bill.CreateTime = DateTime.Now;
bill.CreatorID = VMGlobal.CurrentUser.ID;
bill.Code = this.GenerateBillCode();
bill.ID = _linqOP.Add<TBill, int>(bill, b => b.ID);
Details.ForEach(d => d.BillID = bill.ID);
_linqOP.Add<TDetails>(Details);
}
#endregion
}
}
| 33.762712 | 105 | 0.444478 | [
"MIT"
] | tuoxieyz/fashionDRP | ViewModel/BillVMBase.cs | 10,136 | C# |
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace TrainConsole
{
public static class TimeTableLoader
{
public static void Load(string timeTableFilePath)
{
//var timeTable = new List<TimeTable>();
string[] lines = File.ReadAllLines(timeTableFilePath);
var timeTables = new List<TimeTable>();
foreach (var line in lines)
{
string[] parts = line.Split(',');
var trainId = int.Parse(parts[0]);
if (timeTables.TrueForAll(x => x.TrainId != trainId))
{
var newTable = new TimeTable() { TrainId = trainId };
timeTables.Add(newTable);
}
}
foreach (var line in lines)
{
string[] parts = line.Split(',');
var trainId = int.Parse(parts[0]);
var timeTable = timeTables.Find(x => x.TrainId == trainId);
timeTable.Stops.Add(new Stop()
{
Station = (Station)Railway.GetPartFromId(int.Parse(parts[1])),
DepartureTime = parts[2],
ArrivalTime = parts[3]
}); ;
}
Railway.timeTables.AddRange(timeTables);
}
}
}
| 30.212766 | 82 | 0.504225 | [
"MIT"
] | PGBSNH20/the-train-track-baristagroup2-0 | Source/TrainConsole/Input-output/TimeTableLoader.cs | 1,422 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace NWNOver
{
class FileStreamPool
{
}
}
| 13.615385 | 33 | 0.734463 | [
"MIT"
] | DaedalusGame/NWNOver | NWNOver/FileStreamPool.cs | 179 | C# |
namespace Ocelot.UnitTests.DependencyInjection
{
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Hosting.Internal;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Ocelot.Configuration.Setter;
using Ocelot.DependencyInjection;
using Ocelot.Requester;
using Shouldly;
using IdentityServer4.AccessTokenValidation;
using TestStack.BDDfy;
using Xunit;
using Ocelot.Middleware.Multiplexer;
using Ocelot.Administration;
public class OcelotBuilderTests
{
private readonly IServiceCollection _services;
private IServiceProvider _serviceProvider;
private readonly IConfiguration _configRoot;
private IOcelotBuilder _ocelotBuilder;
private Exception _ex;
public OcelotBuilderTests()
{
_configRoot = new ConfigurationRoot(new List<IConfigurationProvider>());
_services = new ServiceCollection();
_services.AddSingleton<IHostingEnvironment, HostingEnvironment>();
_services.AddSingleton(_configRoot);
}
//keep
[Fact]
public void should_set_up_administration_with_identity_server_options()
{
Action<IdentityServerAuthenticationOptions> options = o => {};
this.Given(x => WhenISetUpOcelotServices())
.When(x => WhenISetUpAdministration(options))
.Then(x => ThenAnExceptionIsntThrown())
.Then(x => ThenTheCorrectAdminPathIsRegitered())
.BDDfy();
}
//keep
[Fact]
public void should_set_up_administration()
{
this.Given(x => WhenISetUpOcelotServices())
.When(x => WhenISetUpAdministration())
.Then(x => ThenAnExceptionIsntThrown())
.Then(x => ThenTheCorrectAdminPathIsRegitered())
.BDDfy();
}
private void WhenISetUpAdministration()
{
_ocelotBuilder.AddAdministration("/administration", "secret");
}
private void WhenISetUpAdministration(Action<IdentityServerAuthenticationOptions> options)
{
_ocelotBuilder.AddAdministration("/administration", options);
}
private void ThenTheCorrectAdminPathIsRegitered()
{
_serviceProvider = _services.BuildServiceProvider();
var path = _serviceProvider.GetService<IAdministrationPath>();
path.Path.ShouldBe("/administration");
}
private void WhenISetUpOcelotServices()
{
try
{
_ocelotBuilder = _services.AddOcelot(_configRoot);
}
catch (Exception e)
{
_ex = e;
}
}
private void ThenAnExceptionIsntThrown()
{
_ex.ShouldBeNull();
}
}
}
| 31.43299 | 98 | 0.619219 | [
"MIT"
] | ThreeMammals/Ocelot.Administration | test/Ocelot.Administration.UnitTests/OcelotBuilderTests.cs | 3,049 | C# |
using Newtonsoft.Json;
using System;
namespace DotnetSpider.Extension.Model
{
/// <summary>
/// 爬虫实体类对应的表信息
/// </summary>
[AttributeUsage(AttributeTargets.Class)]
public class Schema : Attribute
{
/// <summary>
/// 重载是为了添加 JsonIgnore 标签
/// </summary>
[JsonIgnore]
public override object TypeId => base.TypeId;
/// <summary>
/// 数据库名
/// </summary>
public string Database { get; set; }
/// <summary>
/// 表名
/// </summary>
public string TableName { get; set; }
/// <summary>
/// 表名后缀
/// </summary>
public TableNamePostfix TableNamePostfix { get; set; }
public Schema()
{
}
/// <summary>
/// 构造方法
/// </summary>
/// <param name="database">数据库名</param>
/// <param name="tableName">表名</param>
/// <param name="postfix">表名后缀</param>
public Schema(string database, string tableName, TableNamePostfix postfix = TableNamePostfix.None)
{
Database = database;
TableName = tableName;
TableNamePostfix = postfix;
}
/// <summary>
/// 计算最终的表名
/// </summary>
/// <returns>表名</returns>
public string FullName
{
get
{
switch (TableNamePostfix)
{
case TableNamePostfix.FirstDayOfTheMonth:
{
var now = DateTime.Now;
return $"{TableName}_{now.AddDays(now.Day * -1 + 1):yyyy_MM_dd}";
}
case TableNamePostfix.Month:
{
var now = DateTime.Now;
return $"{TableName}_{now.AddDays(now.Day * -1 + 1):yyyy_MM}";
}
case TableNamePostfix.LastMonth:
{
var now = DateTime.Now;
return $"{TableName}_{now.AddDays(now.Day * -1 + 1).AddMonths(-1):yyyy_MM}";
}
case TableNamePostfix.Monday:
{
var now = DateTime.Now;
int i = now.DayOfWeek - DayOfWeek.Monday == -1 ? 6 : -1;
TimeSpan ts = new TimeSpan(i, 0, 0, 0);
return $"{TableName}_{DateTime.Now.Subtract(ts).Date:yyyy_MM_dd}";
}
case TableNamePostfix.Today:
{
var now = DateTime.Now;
return $"{TableName}_{now:yyyy_MM_dd}";
}
default:
{
return TableName;
}
}
}
}
}
}
| 21.822917 | 100 | 0.588544 | [
"MIT"
] | DavidAlphaFox/DotnetSpider | src/DotnetSpider.Extension/Model/Schema.cs | 2,203 | C# |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System;
using System.Collections.Generic;
using System.Diagnostics.Tracing;
using System.Linq;
using System.Threading;
using System.Reflection;
using TestLibrary;
namespace BinderTracingTests
{
internal class BindOperation
{
public AssemblyName AssemblyName { get; internal set; }
public string AssemblyPath { get; internal set; }
public AssemblyName RequestingAssembly { get; internal set; }
public string AssemblyLoadContext { get; internal set; }
public string RequestingAssemblyLoadContext { get; internal set; }
public bool Success { get; internal set; }
public AssemblyName ResultAssemblyName { get; internal set; }
public string ResultAssemblyPath { get; internal set; }
public bool Cached { get; internal set; }
public Guid ActivityId { get; internal set; }
public Guid ParentActivityId { get; internal set; }
public bool Completed { get; internal set; }
public bool Nested { get; internal set; }
public List<ResolutionAttempt> ResolutionAttempts { get; internal set; }
public List<HandlerInvocation> AssemblyLoadContextResolvingHandlers { get; internal set; }
public List<HandlerInvocation> AppDomainAssemblyResolveHandlers { get; internal set; }
public LoadFromHandlerInvocation AssemblyLoadFromHandler { get; internal set; }
public List<ProbedPath> ProbedPaths { get; internal set; }
public List<BindOperation> NestedBinds { get; internal set; }
public BindOperation()
{
ResolutionAttempts = new List<ResolutionAttempt>();
AssemblyLoadContextResolvingHandlers = new List<HandlerInvocation>();
AppDomainAssemblyResolveHandlers = new List<HandlerInvocation>();
ProbedPaths = new List<ProbedPath>();
NestedBinds = new List<BindOperation>();
}
public override string ToString()
{
var sb = new System.Text.StringBuilder();
sb.Append(AssemblyName);
sb.Append(
$" - Request: Path={AssemblyPath}, ALC={AssemblyLoadContext}, RequestingAssembly={RequestingAssembly}, RequestingALC={RequestingAssemblyLoadContext}"
);
sb.Append(
$" - Result: Success={Success}, Name={ResultAssemblyName}, Path={ResultAssemblyPath}, Cached={Cached}"
);
return sb.ToString();
}
}
internal class ResolutionAttempt
{
public enum ResolutionStage : ushort
{
FindInLoadContext,
AssemblyLoadContextLoad,
ApplicationAssemblies,
DefaultAssemblyLoadContextFallback,
ResolveSatelliteAssembly,
AssemblyLoadContextResolvingEvent,
AppDomainAssemblyResolveEvent,
}
public enum ResolutionResult : ushort
{
Success,
AssemblyNotFound,
IncompatibleVersion,
MismatchedAssemblyName,
Failure,
Exception,
}
public AssemblyName AssemblyName { get; internal set; }
public ResolutionStage Stage { get; internal set; }
public string AssemblyLoadContext { get; internal set; }
public ResolutionResult Result { get; internal set; }
public AssemblyName ResultAssemblyName { get; internal set; }
public string ResultAssemblyPath { get; internal set; }
public string ErrorMessage { get; internal set; }
public override string ToString()
{
var sb = new System.Text.StringBuilder();
sb.AppendLine(Stage.ToString());
sb.AppendLine($" AssemblyName={AssemblyName.FullName}");
sb.AppendLine($" ALC={AssemblyLoadContext}");
sb.AppendLine($" Result={Result}");
sb.AppendLine($" ResultAssemblyName={ResultAssemblyName?.FullName}");
sb.AppendLine($" ResultAssemblyPath={ResultAssemblyPath}");
sb.Append($" ErrorMessage={ErrorMessage}");
return sb.ToString();
}
}
internal class HandlerInvocation
{
public AssemblyName AssemblyName { get; internal set; }
public string HandlerName { get; internal set; }
public string AssemblyLoadContext { get; internal set; }
public AssemblyName ResultAssemblyName { get; internal set; }
public string ResultAssemblyPath { get; internal set; }
public override string ToString()
{
var sb = new System.Text.StringBuilder();
sb.Append($"{HandlerName} - ");
sb.Append($"Request: Name={AssemblyName.FullName}");
if (!string.IsNullOrEmpty(AssemblyLoadContext))
sb.Append($", ALC={AssemblyLoadContext}");
sb.Append($" - Result: Name={ResultAssemblyName?.FullName}, Path={ResultAssemblyPath}");
return sb.ToString();
}
}
internal class LoadFromHandlerInvocation
{
public AssemblyName AssemblyName { get; internal set; }
public bool IsTrackedLoad { get; internal set; }
public string RequestingAssemblyPath { get; internal set; }
public string ComputedRequestedAssemblyPath { get; internal set; }
}
internal class ProbedPath
{
public enum PathSource : ushort
{
ApplicationAssemblies,
AppNativeImagePaths,
AppPaths,
PlatformResourceRoots,
SatelliteSubdirectory
}
public string FilePath { get; internal set; }
public PathSource Source { get; internal set; }
public int Result { get; internal set; }
public override string ToString()
{
return $"{FilePath} - Source={Source}, Result={Result}";
}
}
internal sealed class BinderEventListener : EventListener
{
private const EventKeywords AssemblyLoaderKeyword = (EventKeywords)0x4;
private readonly object eventsLock = new object();
private readonly Dictionary<Guid, BindOperation> bindOperations = new Dictionary<
Guid,
BindOperation
>();
private readonly string[] loadsToTrack;
public BinderEventListener(string[] loadsToTrack, bool log = false)
{
this.loadsToTrack = loadsToTrack;
}
public BindOperation[] WaitAndGetEventsForAssembly(AssemblyName assemblyName)
{
Assert.IsTrue(
IsLoadToTrack(assemblyName.Name),
$"Waiting for load for untracked name: {assemblyName.Name}. Tracking loads for: {string.Join(", ", loadsToTrack)}"
);
const int waitIntervalInMs = 50;
int waitTimeoutInMs =
Environment.GetEnvironmentVariable("COMPlus_GCStress") == null
? 30 * 1000
: int.MaxValue;
int timeWaitedInMs = 0;
while (true)
{
lock (eventsLock)
{
var events = bindOperations.Values.Where(
e =>
e.Completed
&& Helpers.AssemblyNamesMatch(e.AssemblyName, assemblyName)
&& !e.Nested
);
if (events.Any())
{
return events.ToArray();
}
}
Thread.Sleep(waitIntervalInMs);
timeWaitedInMs += waitIntervalInMs;
if (timeWaitedInMs > waitTimeoutInMs)
{
var msg = new System.Text.StringBuilder(
$"Timed out waiting for bind events for {assemblyName}"
);
msg.AppendLine(GetReceivedEventsAsString());
throw new TimeoutException(msg.ToString());
}
}
}
protected override void OnEventSourceCreated(EventSource eventSource)
{
if (eventSource.Name == "Microsoft-Windows-DotNETRuntime")
{
EnableEvents(eventSource, EventLevel.Verbose, AssemblyLoaderKeyword);
}
}
protected override void OnEventWritten(EventWrittenEventArgs data)
{
if (data.EventSource.Name != "Microsoft-Windows-DotNETRuntime")
return;
object GetData(string name)
{
int index = data.PayloadNames.IndexOf(name);
return index >= 0 ? data.Payload[index] : null;
}
;
string GetDataString(string name) => GetData(name) as string;
switch (data.EventName)
{
case "AssemblyLoadStart":
{
BindOperation bindOperation = ParseAssemblyLoadStartEvent(data, GetDataString);
if (!IsLoadToTrack(bindOperation.AssemblyName.Name))
return;
lock (eventsLock)
{
Assert.IsTrue(
!bindOperations.ContainsKey(data.ActivityId),
"AssemblyLoadStart should not exist for same activity ID "
);
bindOperation.Nested = bindOperations.ContainsKey(data.RelatedActivityId);
bindOperations.Add(data.ActivityId, bindOperation);
if (bindOperation.Nested)
{
bindOperations[data.RelatedActivityId].NestedBinds.Add(bindOperation);
}
}
break;
}
case "AssemblyLoadStop":
{
string assemblyName = GetDataString("AssemblyName");
if (!IsLoadToTrack(new AssemblyName(assemblyName).Name))
return;
bool success = (bool)GetData("Success");
string resultName = GetDataString("ResultAssemblyName");
lock (eventsLock)
{
if (!bindOperations.ContainsKey(data.ActivityId))
Assert.Fail(
GetMissingAssemblyBindStartMessage(
data,
$"Success={success}, Name={resultName}"
)
);
BindOperation bind = bindOperations[data.ActivityId];
bind.Success = success;
if (!string.IsNullOrEmpty(resultName))
{
bind.ResultAssemblyName = new AssemblyName(resultName);
}
bind.ResultAssemblyPath = GetDataString("ResultAssemblyPath");
bind.Cached = (bool)GetData("Cached");
bind.Completed = true;
}
break;
}
case "ResolutionAttempted":
{
ResolutionAttempt attempt = ParseResolutionAttemptedEvent(
GetData,
GetDataString
);
if (!IsLoadToTrack(attempt.AssemblyName.Name))
return;
lock (eventsLock)
{
if (!bindOperations.ContainsKey(data.ActivityId))
Assert.Fail(
GetMissingAssemblyBindStartMessage(data, attempt.ToString())
);
BindOperation bind = bindOperations[data.ActivityId];
bind.ResolutionAttempts.Add(attempt);
}
break;
}
case "AssemblyLoadContextResolvingHandlerInvoked":
{
HandlerInvocation handlerInvocation = ParseHandlerInvokedEvent(GetDataString);
if (!IsLoadToTrack(handlerInvocation.AssemblyName.Name))
return;
lock (eventsLock)
{
if (!bindOperations.ContainsKey(data.ActivityId))
Assert.Fail(
GetMissingAssemblyBindStartMessage(
data,
handlerInvocation.ToString()
)
);
BindOperation bind = bindOperations[data.ActivityId];
bind.AssemblyLoadContextResolvingHandlers.Add(handlerInvocation);
}
break;
}
case "AppDomainAssemblyResolveHandlerInvoked":
{
HandlerInvocation handlerInvocation = ParseHandlerInvokedEvent(GetDataString);
if (!IsLoadToTrack(handlerInvocation.AssemblyName.Name))
return;
lock (eventsLock)
{
if (!bindOperations.ContainsKey(data.ActivityId))
Assert.Fail(
GetMissingAssemblyBindStartMessage(
data,
handlerInvocation.ToString()
)
);
BindOperation bind = bindOperations[data.ActivityId];
bind.AppDomainAssemblyResolveHandlers.Add(handlerInvocation);
}
break;
}
case "AssemblyLoadFromResolveHandlerInvoked":
{
LoadFromHandlerInvocation loadFrom = ParseLoadFromHandlerInvokedEvent(
GetData,
GetDataString
);
if (!IsLoadToTrack(loadFrom.AssemblyName.Name))
return;
lock (eventsLock)
{
if (!bindOperations.ContainsKey(data.ActivityId))
Assert.Fail(
GetMissingAssemblyBindStartMessage(data, loadFrom.ToString())
);
BindOperation bind = bindOperations[data.ActivityId];
bind.AssemblyLoadFromHandler = loadFrom;
}
break;
}
case "KnownPathProbed":
{
ProbedPath probedPath = ParseKnownPathProbedEvent(GetData, GetDataString);
string name = System.IO.Path.GetFileNameWithoutExtension(probedPath.FilePath);
if (!IsLoadToTrack(name.EndsWith(".ni") ? name.Remove(name.Length - 3) : name))
return;
lock (eventsLock)
{
if (!bindOperations.ContainsKey(data.ActivityId))
Assert.Fail(
GetMissingAssemblyBindStartMessage(data, probedPath.ToString())
);
BindOperation bind = bindOperations[data.ActivityId];
bind.ProbedPaths.Add(probedPath);
}
break;
}
}
}
private bool IsLoadToTrack(string name)
{
return this.loadsToTrack.Any(
n => n.Equals(name, StringComparison.InvariantCultureIgnoreCase)
);
}
private string GetMissingAssemblyBindStartMessage(
EventWrittenEventArgs data,
string parsedEventAsString
)
{
var msg = new System.Text.StringBuilder();
msg.AppendLine(
$"{data.EventName} (ActivityId: {data.ActivityId}) should have a matching AssemblyBindStart"
);
msg.AppendLine($"Parsed event: {parsedEventAsString}");
msg.AppendLine(GetReceivedEventsAsString());
return msg.ToString();
}
private string GetReceivedEventsAsString()
{
var msg = new System.Text.StringBuilder();
msg.AppendLine("Received events:");
lock (eventsLock)
{
foreach (BindOperation op in bindOperations.Values)
{
msg.AppendLine(op.ToString());
msg.AppendLine($" - ActivityId: {op.ActivityId}");
msg.AppendLine($" - Completed: {op.Completed}");
msg.AppendLine($" - Nested: {op.Nested}");
}
}
return msg.ToString();
}
private BindOperation ParseAssemblyLoadStartEvent(
EventWrittenEventArgs data,
Func<string, string> getDataString
)
{
var bindOperation = new BindOperation()
{
AssemblyName = new AssemblyName(getDataString("AssemblyName")),
AssemblyPath = getDataString("AssemblyPath"),
AssemblyLoadContext = getDataString("AssemblyLoadContext"),
RequestingAssemblyLoadContext = getDataString("RequestingAssemblyLoadContext"),
ActivityId = data.ActivityId,
ParentActivityId = data.RelatedActivityId,
};
string requestingAssembly = getDataString("RequestingAssembly");
if (!string.IsNullOrEmpty(requestingAssembly) && requestingAssembly != "NULL")
{
bindOperation.RequestingAssembly = new AssemblyName(requestingAssembly);
}
return bindOperation;
}
private ResolutionAttempt ParseResolutionAttemptedEvent(
Func<string, object> getData,
Func<string, string> getDataString
)
{
var attempt = new ResolutionAttempt()
{
AssemblyName = new AssemblyName(getDataString("AssemblyName")),
Stage = (ResolutionAttempt.ResolutionStage)getData("Stage"),
AssemblyLoadContext = getDataString("AssemblyLoadContext"),
Result = (ResolutionAttempt.ResolutionResult)getData("Result"),
ResultAssemblyPath = getDataString("ResultAssemblyPath"),
ErrorMessage = getDataString("ErrorMessage")
};
string resultName = getDataString("ResultAssemblyName");
if (!string.IsNullOrEmpty(resultName) && resultName != "NULL")
{
attempt.ResultAssemblyName = new AssemblyName(resultName);
}
return attempt;
}
private HandlerInvocation ParseHandlerInvokedEvent(Func<string, string> getDataString)
{
var handlerInvocation = new HandlerInvocation()
{
AssemblyName = new AssemblyName(getDataString("AssemblyName")),
HandlerName = getDataString("HandlerName"),
AssemblyLoadContext = getDataString("AssemblyLoadContext"),
ResultAssemblyPath = getDataString("ResultAssemblyPath")
};
string resultName = getDataString("ResultAssemblyName");
if (!string.IsNullOrEmpty(resultName) && resultName != "NULL")
{
handlerInvocation.ResultAssemblyName = new AssemblyName(resultName);
}
return handlerInvocation;
}
private LoadFromHandlerInvocation ParseLoadFromHandlerInvokedEvent(
Func<string, object> getData,
Func<string, string> getDataString
)
{
var loadFrom = new LoadFromHandlerInvocation()
{
AssemblyName = new AssemblyName(getDataString("AssemblyName")),
IsTrackedLoad = (bool)getData("IsTrackedLoad"),
RequestingAssemblyPath = getDataString("RequestingAssemblyPath"),
ComputedRequestedAssemblyPath = getDataString("ComputedRequestedAssemblyPath"),
};
return loadFrom;
}
private ProbedPath ParseKnownPathProbedEvent(
Func<string, object> getData,
Func<string, string> getDataString
)
{
var probedPath = new ProbedPath()
{
FilePath = getDataString("FilePath"),
Source = (ProbedPath.PathSource)getData("Source"),
Result = (int)getData("Result"),
};
return probedPath;
}
}
}
| 39.8 | 165 | 0.532711 | [
"MIT"
] | belav/runtime | src/tests/Loader/binding/tracing/BinderEventListener.cs | 21,094 | C# |
using Sitecore.Foundation.Import.Extensions;
using Sitecore.Foundation.Import.Map.CustomItems;
using Sitecore.Data;
using System.Linq;
using System;
using System.Collections.Generic;
namespace Sitecore.Foundation.Import.Map
{
public static class Factory
{
public static ItemImportMap BuildMapInfo(ID mapId)
{
var database = Sitecore.Configuration.Factory.GetDatabase("master");
var mapItem = database.GetItem(mapId);
var inputColumnsItem =
mapItem.FirstChildInheritingFrom(InputColumnCollectionItem.TemplateId);
var mapInfo = new ItemImportMap
{
InputFields = inputColumnsItem.Children.Select(c => new InputField {Name = c.Name}).ToList(),
OutputMaps = mapItem.Children
.Where(c => c.InheritsFrom(OutputMapTemplateItem.TemplateId))
.Select(om => CreateOutputMap(om, null))
.ToList()
};
return mapInfo;
}
public static ItemImportMap BuildMapInfo(MapItem mapItem, ID templateID, ContentType contentType)
{
var mapInfo = new ItemImportMap
{
InputFields = mapItem.InputFields.Select(fieldName => new InputField { Name = fieldName }).ToList(),
OutputMaps = new List<OutputMap>()
};
if (contentType == ContentType.Store)
mapInfo.OutputMaps = SetStoreMap(mapItem, templateID);
else if (contentType == ContentType.Banner)
mapInfo.OutputMaps = SetBannerMap(mapItem, templateID);
else if (contentType == ContentType.Event)
mapInfo.OutputMaps = SetEventMap(mapItem, templateID);
else if (contentType == ContentType.Article)
{
if (templateID == FrasersContent.Templates.SpecialEvent.ID)
mapInfo.OutputMaps = SetSpecialEventMap(mapItem, templateID);
else
mapInfo.OutputMaps = SetArticleMap(mapItem, templateID);
}
else if (contentType == ContentType.Blog)
{
mapInfo.OutputMaps = SetBlogMap(mapItem, templateID);
}
return mapInfo;
}
public static MapItem SetMapInputField(string contentType, ID templateID)
{
MapItem mapItem = new MapItem();
if (contentType == ContentType.Store.ToString())
{
mapItem.InputFields = Enum.GetNames(typeof(StoreInputField)).ToList();
mapItem.OutputFields = new DescriptionAttributes<StoreOutputField>().Descriptions.ToList();
}
else if (contentType == ContentType.Banner.ToString())
{
mapItem.InputFields = Enum.GetNames(typeof(BannerInputField)).ToList();
mapItem.OutputFields = new DescriptionAttributes<BannerOutputField>().Descriptions.ToList();
}
else if (contentType == ContentType.Event.ToString())
{
mapItem.InputFields = Enum.GetNames(typeof(EventInputField)).ToList();
mapItem.OutputFields = new DescriptionAttributes<EventOutputField>().Descriptions.ToList();
}
else if (contentType == ContentType.Article.ToString())
{
if (templateID == FrasersContent.Templates.SpecialEvent.ID)
{
mapItem.InputFields = Enum.GetNames(typeof(ArticleInputField)).ToList();
mapItem.OutputFields = new DescriptionAttributes<SpecialOutputField>().Descriptions.ToList();
}
else
{
mapItem.InputFields = Enum.GetNames(typeof(ArticleInputField)).ToList();
mapItem.OutputFields = new DescriptionAttributes<ArticleOutputField>().Descriptions.ToList();
}
}
else if (contentType == ContentType.Blog.ToString())
{
mapItem.InputFields = new DescriptionAttributes<BlogInputField>().Descriptions.ToList();
mapItem.OutputFields = new DescriptionAttributes<BlogOutputField>().Descriptions.ToList();
}
return mapItem;
}
private static OutputMap CreateOutputMap(Data.Items.Item item, OutputMap parentMap)
{
var outputMap = new OutputMap();
outputMap.ParentMap = parentMap;
var outputMapCustomItem = new OutputMapTemplateItem(item);
outputMap.TemplateId = outputMapCustomItem.TargetTemplate.ID;
outputMap.NameInputField = outputMapCustomItem.ItemNameField.Name;
var fieldsCollection =
item.Children.FirstOrDefault(c => c.InheritsFrom(OutputFieldCollectionItem.TemplateId));
if (fieldsCollection != null)
{
foreach (var field in fieldsCollection.Children.Where(c => c.InheritsFrom(OutputFieldItem.TemplateId)))
{
var fieldCustomItem = new OutputFieldItem(field);
outputMap.Fields.Add(new OutputField
{
SourceColumn = fieldCustomItem.InputField.Name,
TargetFieldName = fieldCustomItem.Name
});
}
}
if (!outputMap.Fields.Any())
{
outputMap.Fields.Add(new OutputField
{
SourceColumn = outputMap.NameInputField,
TargetFieldName = ""
});
}
if (parentMap != null &&
!outputMap.Fields.Any(f => f.SourceColumn == parentMap.NameInputField))
{
outputMap.Fields.Add(new OutputField
{
SourceColumn = parentMap.NameInputField,
TargetFieldName = ""
});
}
var childMapItems = item.Children.Where(c => c.InheritsFrom(OutputMapTemplateItem.TemplateId));
if (childMapItems != null &&
childMapItems.Any())
{
foreach (var childMapItem in childMapItems)
{
outputMap.ChildMaps.Add(CreateOutputMap(childMapItem, outputMap));
}
}
return outputMap;
}
private static List<OutputMap> SetStoreMap(MapItem mapItem, ID templateID)
{
var outputMaps = new List<OutputMap>();
var outputMap = new OutputMap();
foreach (string field in mapItem.OutputFields)
{
var outputField = MapStoreField(field);
outputMap.Fields.Add(outputField);
}
outputMap.TemplateId = templateID;
outputMaps.Add(outputMap);
return outputMaps;
}
private static OutputField MapStoreField(string field)
{
var outputField = new OutputField();
if (field == StoreOutputField.Store.GetDescription()
|| field == StoreOutputField.StoreOffers.GetDescription())
{
outputField.SourceColumn = StoreInputField.Store.ToString();
outputField.TargetFieldName = field;
}
else if (field == StoreOutputField.Logo.GetDescription())
{
outputField.SourceColumn = StoreInputField.Logo.ToString();
outputField.TargetFieldName = field;
}
else if (field == StoreOutputField.NewDate.GetDescription())
{
outputField.SourceColumn = StoreInputField.NewDate.ToString();
outputField.TargetFieldName = field;
}
else if (field == StoreOutputField.Category.GetDescription())
{
outputField.SourceColumn = StoreInputField.Category.ToString();
outputField.TargetFieldName = field;
}
else if (field == StoreOutputField.Description.GetDescription())
{
outputField.SourceColumn = StoreInputField.Description.ToString();
outputField.TargetFieldName = field;
}
else if (field == StoreOutputField.UnitNo.GetDescription())
{
outputField.SourceColumn = StoreInputField.UnitNo.ToString();
outputField.TargetFieldName = field;
}
else if (field == StoreOutputField.Contact.GetDescription()
|| field == StoreOutputField.PhoneNumber.GetDescription())
{
outputField.SourceColumn = StoreInputField.Contact.ToString();
outputField.TargetFieldName = field;
}
else if (field == StoreOutputField.OpeningHrs.GetDescription())
{
outputField.SourceColumn = StoreInputField.OpeningHrs.ToString();
outputField.TargetFieldName = field;
}
else if (field == StoreOutputField.Brands.GetDescription())
{
outputField.SourceColumn = StoreInputField.Brands.ToString();
outputField.TargetFieldName = field;
}
else if (field == StoreOutputField.Keywords.GetDescription())
{
outputField.SourceColumn = StoreInputField.Keywords.ToString();
outputField.TargetFieldName = field;
}
else if (field == StoreOutputField.UpcomingDate.GetDescription())
{
outputField.SourceColumn = StoreInputField.UpcomingDate.ToString();
outputField.TargetFieldName = field;
}
else if (field == StoreOutputField.ExpiryDate.GetDescription())
{
outputField.SourceColumn = StoreInputField.ExpiryDate.ToString();
outputField.TargetFieldName = field;
}
return outputField;
}
private static List<OutputMap> SetBannerMap(MapItem mapItem, ID templateID)
{
var outputMaps = new List<OutputMap>();
var outputMap = new OutputMap();
foreach (string field in mapItem.OutputFields)
{
var outputField = new OutputField();
if (field == BannerOutputField.Title.GetDescription())
{
outputField.SourceColumn = BannerInputField.Title.ToString();
outputField.TargetFieldName = field;
}
else if (field == BannerOutputField.Image.GetDescription())
{
outputField.SourceColumn = BannerInputField.Image.ToString();
outputField.TargetFieldName = field;
}
else if (field == BannerOutputField.Summary.GetDescription())
{
outputField.SourceColumn = BannerInputField.Summary.ToString();
outputField.TargetFieldName = field;
}
else if (field == BannerOutputField.Category.GetDescription())
{
outputField.SourceColumn = BannerInputField.Category.ToString();
outputField.TargetFieldName = field;
}
else if (field == BannerOutputField.Link.GetDescription())
{
outputField.SourceColumn = BannerInputField.Link.ToString();
outputField.TargetFieldName = field;
}
else if (field == BannerOutputField.PostDate.GetDescription())
{
outputField.SourceColumn = BannerInputField.PostDate.ToString();
outputField.TargetFieldName = field;
}
else if (field == BannerOutputField.ExpiryDate.GetDescription())
{
outputField.SourceColumn = BannerInputField.ExpiryDate.ToString();
outputField.TargetFieldName = field;
}
else if (field == BannerOutputField.ShowInMain.GetDescription())
{
outputField.SourceColumn = BannerInputField.ShowInMain.ToString();
outputField.TargetFieldName = field;
}
else if (field == BannerOutputField.ShowInMalls.GetDescription())
{
outputField.SourceColumn = BannerInputField.ShowInMalls.ToString();
outputField.TargetFieldName = field;
}
outputMap.Fields.Add(outputField);
}
outputMap.TemplateId = templateID;
outputMaps.Add(outputMap);
return outputMaps;
}
private static List<OutputMap> SetEventMap(MapItem mapItem, ID templateID)
{
var outputMaps = new List<OutputMap>();
var outputMap = new OutputMap();
foreach (string field in mapItem.OutputFields)
{
var outputField = new OutputField();
if (field == EventOutputField.Title.GetDescription())
{
outputField.SourceColumn = BannerInputField.Title.ToString();
outputField.TargetFieldName = field;
}
else if (field == EventOutputField.PostDate.GetDescription())
{
outputField.SourceColumn = EventInputField.PostDate.ToString();
outputField.TargetFieldName = field;
}
else if (field == EventOutputField.Store.GetDescription()
|| field == EventOutputField.AllStore.GetDescription())
{
outputField.SourceColumn = EventInputField.Store.ToString();
outputField.TargetFieldName = field;
}
else if (field == EventOutputField.Keywords.GetDescription())
{
outputField.SourceColumn = EventInputField.Keywords.ToString();
outputField.TargetFieldName = field;
}
else if (field == EventOutputField.StartDate.GetDescription())
{
outputField.SourceColumn = EventInputField.Start_Date.ToString();
outputField.TargetFieldName = field;
}
else if (field == EventOutputField.EndDate.GetDescription())
{
outputField.SourceColumn = EventInputField.End_Date.ToString();
outputField.TargetFieldName = field;
}
else if (field == EventOutputField.Image.GetDescription())
{
outputField.SourceColumn = EventInputField.Image.ToString();
outputField.TargetFieldName = field;
}
else if (field == EventOutputField.Summary.GetDescription())
{
outputField.SourceColumn = EventInputField.Summary.ToString();
outputField.TargetFieldName = field;
}
else if (field == EventOutputField.EventType.GetDescription())
{
outputField.SourceColumn = EventInputField.EventType.ToString();
outputField.TargetFieldName = field;
}
else if (field == EventOutputField.Thumbnail.GetDescription())
{
outputField.SourceColumn = EventInputField.Thumbnail.ToString();
outputField.TargetFieldName = field;
}
else if (field == EventOutputField.Description.GetDescription())
{
outputField.SourceColumn = EventInputField.Description.ToString();
outputField.TargetFieldName = field;
}
else if (field == EventOutputField.ShowInMalls.GetDescription())
{
outputField.SourceColumn = EventInputField.ShowInMalls.ToString();
outputField.TargetFieldName = field;
}
outputMap.Fields.Add(outputField);
}
outputMap.TemplateId = templateID;
outputMaps.Add(outputMap);
return outputMaps;
}
private static List<OutputMap> SetArticleMap(MapItem mapItem, ID templateID)
{
var outputMaps = new List<OutputMap>();
var outputMap = new OutputMap();
foreach (string field in mapItem.OutputFields)
{
var outputField = new OutputField();
if (field == ArticleOutputField.Title.GetDescription())
{
outputField.SourceColumn = ArticleInputField.Title.ToString();
outputField.TargetFieldName = field;
}
else if (field == ArticleOutputField.Thumbnail.GetDescription())
{
outputField.SourceColumn = ArticleInputField.Thumbnail.ToString();
outputField.TargetFieldName = field;
}
else if (field == ArticleOutputField.Banner.GetDescription())
{
outputField.SourceColumn = ArticleInputField.Banner.ToString();
outputField.TargetFieldName = field;
}
else if (field == ArticleOutputField.PostDate.GetDescription())
{
outputField.SourceColumn = ArticleInputField.PostDate.ToString();
outputField.TargetFieldName = field;
}
else if (field == ArticleOutputField.ExpiryDate.GetDescription())
{
outputField.SourceColumn = ArticleInputField.ExpiryDate.ToString();
outputField.TargetFieldName = field;
}
else if (field == ArticleOutputField.Summary.GetDescription())
{
outputField.SourceColumn = ArticleInputField.Summary.ToString();
outputField.TargetFieldName = field;
}
else if (field == ArticleOutputField.Description.GetDescription())
{
outputField.SourceColumn = ArticleInputField.Description.ToString();
outputField.TargetFieldName = field;
}
else if (field == ArticleOutputField.Store.GetDescription())
{
outputField.SourceColumn = ArticleInputField.Store.ToString();
outputField.TargetFieldName = field;
}
else if (field == ArticleOutputField.StartDate.GetDescription())
{
outputField.SourceColumn = ArticleInputField.StartDate.ToString();
outputField.TargetFieldName = field;
}
else if (field == ArticleOutputField.EndDate.GetDescription())
{
outputField.SourceColumn = ArticleInputField.EndDate.ToString();
outputField.TargetFieldName = field;
}
else if (field == ArticleOutputField.ShowInMalls.GetDescription())
{
outputField.SourceColumn = ArticleInputField.ShowInMalls.ToString();
outputField.TargetFieldName = field;
}
else if (field == ArticleOutputField.Category.GetDescription())
{
outputField.SourceColumn = ArticleInputField.Category.ToString();
outputField.TargetFieldName = field;
}
outputMap.Fields.Add(outputField);
}
outputMap.TemplateId = templateID;
outputMaps.Add(outputMap);
return outputMaps;
}
private static List<OutputMap> SetSpecialEventMap(MapItem mapItem, ID templateID)
{
var outputMaps = new List<OutputMap>();
var outputMap = new OutputMap();
foreach (string field in mapItem.OutputFields)
{
OutputField outputField = null;
if (field == SpecialOutputField.Title.GetDescription())
{
outputField = new OutputField(){SourceColumn = ArticleInputField.Title.ToString(), TargetFieldName = field};
}
else if (field == SpecialOutputField.Thumbnail.GetDescription())
{
outputField = new OutputField(){ SourceColumn = ArticleInputField.Thumbnail.ToString(), TargetFieldName = field };
}
else if (field == SpecialOutputField.Image.GetDescription())
{
outputField = new OutputField(){SourceColumn = ArticleInputField.Banner.ToString(), TargetFieldName = field};
}
else if (field == SpecialOutputField.PostDate.GetDescription())
{
outputField = new OutputField() {SourceColumn = ArticleInputField.PostDate.ToString(), TargetFieldName = field};
}
else if (field == SpecialOutputField.ExpiryDate.GetDescription())
{
outputField = new OutputField(){SourceColumn = ArticleInputField.ExpiryDate.ToString(), TargetFieldName = field};
}
else if (field == SpecialOutputField.Summary.GetDescription())
{
outputField = new OutputField() { SourceColumn = ArticleInputField.Summary.ToString(), TargetFieldName = field};
}
else if (field == SpecialOutputField.Description.GetDescription())
{
outputField = new OutputField() { SourceColumn = ArticleInputField.Description.ToString(), TargetFieldName = field };
}
else if (field == SpecialOutputField.Store.GetDescription())
{
outputField = new OutputField() { SourceColumn = ArticleInputField.Store.ToString(), TargetFieldName = field};
}
else if (field == SpecialOutputField.StartDate.GetDescription())
{
outputField = new OutputField(){SourceColumn = ArticleInputField.StartDate.ToString(), TargetFieldName = field };
}
else if (field == SpecialOutputField.EndDate.GetDescription())
{
outputField = new OutputField() { SourceColumn = ArticleInputField.EndDate.ToString(), TargetFieldName = field };
}
else if (field == SpecialOutputField.ShowInMalls.GetDescription()) {
outputField = new OutputField()
{
SourceColumn = ArticleInputField.ShowInMalls.ToString(),
TargetFieldName = field
};
}
if(outputField != null )
outputMap.Fields.Add(outputField);
}
outputMap.TemplateId = templateID;
outputMaps.Add(outputMap);
return outputMaps;
}
private static List<OutputMap> SetBlogMap(MapItem mapItem, ID templateID)
{
var outputMaps = new List<OutputMap>();
var outputMap = new OutputMap();
foreach (string field in mapItem.OutputFields)
{
var outputField = new OutputField();
if (field == BlogOutputField.Category.GetDescription())
{
outputField.SourceColumn = BlogInputField.Category.GetDescription();
outputField.TargetFieldName = field;
}
else if (field == BlogOutputField.Title.GetDescription())
{
outputField.SourceColumn = BlogInputField.Title.GetDescription();
outputField.TargetFieldName = field;
}
else if (field == BlogOutputField.Thumbnail.GetDescription())
{
outputField.SourceColumn = BlogInputField.Thumbnail.GetDescription();
outputField.TargetFieldName = field;
}
else if (field == BlogOutputField.Banner.GetDescription())
{
outputField.SourceColumn = BlogInputField.Banner.GetDescription();
outputField.TargetFieldName = field;
}
else if (field == BlogOutputField.Author.GetDescription())
{
outputField.SourceColumn = BlogInputField.AuthorName.GetDescription();
outputField.TargetFieldName = field;
}
else if (field == BlogOutputField.PostDate.GetDescription())
{
outputField.SourceColumn = BlogInputField.PostDate.GetDescription();
outputField.TargetFieldName = field;
}
else if (field == BlogOutputField.ExpiryDate.GetDescription())
{
outputField.SourceColumn = BlogInputField.ExpiryDate.GetDescription();
outputField.TargetFieldName = field;
}
else if (field == BlogOutputField.Summary.GetDescription())
{
outputField.SourceColumn = BlogInputField.Summary.GetDescription();
outputField.TargetFieldName = field;
}
else if (field == BlogOutputField.Body.GetDescription())
{
outputField.SourceColumn = BlogInputField.Body.ToString();
outputField.TargetFieldName = field;
}
outputMap.Fields.Add(outputField);
}
outputMap.TemplateId = templateID;
outputMaps.Add(outputMap);
return outputMaps;
}
}
} | 46.106643 | 137 | 0.547075 | [
"Apache-2.0"
] | jaydipkotadiya1605/Code | src/Foundation/Import/code/Map/Factory.cs | 26,375 | C# |
using Microsoft.AspNet.Identity;
using Microsoft.AspNet.Identity.EntityFramework;
using Microsoft.AspNet.Identity.Owin;
using Microsoft.Owin;
using Microsoft.Owin.Security.Cookies;
using Microsoft.Owin.Security.DataProtection;
using Microsoft.Owin.Security.Google;
using Owin;
using System;
using WebApplication1.Models;
namespace WebApplication1
{
public partial class Startup
{
// For more information on configuring authentication, please visit http://go.microsoft.com/fwlink/?LinkId=301864
public void ConfigureAuth(IAppBuilder app)
{
// Configure the db context and user manager to use a single instance per request
app.CreatePerOwinContext(ApplicationDbContext.Create);
app.CreatePerOwinContext<ApplicationUserManager>(ApplicationUserManager.Create);
// Enable the application to use a cookie to store information for the signed in user
// and to use a cookie to temporarily store information about a user logging in with a third party login provider
// Configure the sign in cookie
app.UseCookieAuthentication(new CookieAuthenticationOptions
{
AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
LoginPath = new PathString("/Account/Login"),
Provider = new CookieAuthenticationProvider
{
OnValidateIdentity = SecurityStampValidator.OnValidateIdentity<ApplicationUserManager, ApplicationUser>(
validateInterval: TimeSpan.FromMinutes(30),
regenerateIdentity: (manager, user) => user.GenerateUserIdentityAsync(manager))
}
});
app.UseExternalSignInCookie(DefaultAuthenticationTypes.ExternalCookie);
// Uncomment the following lines to enable logging in with third party login providers
//app.UseMicrosoftAccountAuthentication(
// clientId: "",
// clientSecret: "");
//app.UseTwitterAuthentication(
// consumerKey: "",
// consumerSecret: "");
//app.UseFacebookAuthentication(
// appId: "",
// appSecret: "");
//app.UseGoogleAuthentication(new GoogleOAuth2AuthenticationOptions()
//{
// ClientId = "",
// ClientSecret = ""
//});
}
}
} | 42.35 | 126 | 0.620228 | [
"MIT"
] | lbigay-wmsu/kisama00 | src/WebApplication1/App_Start/Startup.Auth.cs | 2,543 | C# |
using System.Text.RegularExpressions;
namespace SharePointPnP.PowerShell.Commands.Utilities
{
public static class StringExtensions
{
public static string ReplaceCaseInsensitive(this string input, string search, string replacement)
{
return Regex.Replace(
input,
Regex.Escape(search),
replacement.Replace("$", "$$"),
RegexOptions.IgnoreCase
);
}
}
} | 27.882353 | 105 | 0.588608 | [
"MIT"
] | Ashikpaul/PnP-PowerShell | Commands/Utilities/StringExtensions.cs | 476 | C# |
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using Discount.api.Extensions;
namespace Discount.api
{
public class Program
{
public static void Main(string[] args)
{
var host = CreateHostBuilder(args).Build();
host.MigrateDatabase<Program>();
host.Run();
}
public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.ConfigureWebHostDefaults(webBuilder =>
{
webBuilder.UseStartup<Startup>();
});
}
}
| 22.384615 | 64 | 0.738832 | [
"MIT"
] | Javen17/AspnetMicroservices | source/Services/Discount/Discount.api/Program.cs | 582 | C# |
namespace MyCookbook.Web.ViewModels.Administration.Cuisines.Manage
{
using System.Collections.Generic;
public class AdminCuisinesManageViewModel
{
public IEnumerable<AdminCuisinesAllViewModel> Cuisines { get; set; }
}
}
| 24.6 | 76 | 0.747967 | [
"MIT"
] | boyan-kolev/MyCookbook | Web/MyCookbook.Web.ViewModels/Administration/Cuisines/Manage/AdminCuisinesManageViewModel.cs | 248 | 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.
#pragma warning disable SA1512
// The portable implementation in this type is originally from CoreFX.
// See https://github.com/dotnet/corefx/blob/release/2.1/src/System.Memory/src/System/SpanHelpers.cs.
using System;
using System.Diagnostics.Contracts;
#if !SPAN_RUNTIME_SUPPORT
using System.Reflection;
#endif
using System.Runtime.CompilerServices;
namespace Microsoft.Toolkit.HighPerformance.Helpers.Internals
{
/// <summary>
/// A helper class that with utility methods for dealing with references, and other low-level details.
/// It also contains some APIs that act as polyfills for .NET Standard 2.0 and below.
/// </summary>
internal static class RuntimeHelpers
{
/// <summary>
/// Converts a length of items from one size to another (rounding towards zero).
/// </summary>
/// <typeparam name="TFrom">The source type of items.</typeparam>
/// <typeparam name="TTo">The target type of items.</typeparam>
/// <param name="length">The input length to convert.</param>
/// <returns>The converted length for the specified argument and types.</returns>
[Pure]
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static unsafe int ConvertLength<TFrom, TTo>(int length)
where TFrom : unmanaged
where TTo : unmanaged
{
if (sizeof(TFrom) == sizeof(TTo))
{
return length;
}
else if (sizeof(TFrom) == 1)
{
return (int)((uint)length / (uint)sizeof(TTo));
}
else
{
ulong targetLength = (ulong)(uint)length * (uint)sizeof(TFrom) / (uint)sizeof(TTo);
return checked((int)targetLength);
}
}
/// <summary>
/// Gets the length of a given array as a native integer.
/// </summary>
/// <typeparam name="T">The type of values in the array.</typeparam>
/// <param name="array">The input <see cref="Array"/> instance.</param>
/// <returns>The total length of <paramref name="array"/> as a native integer.</returns>
/// <remarks>
/// This method is needed because this expression is not inlined correctly if the target array
/// is only visible as a non-generic <see cref="Array"/> instance, because the C# compiler will
/// not be able to emit the <see langword="ldlen"/> opcode instead of calling the right method.
/// </remarks>
[Pure]
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static nint GetArrayNativeLength<T>(T[] array)
{
#if NETSTANDARD1_4
// .NET Standard 1.4 doesn't include the API to get the long length, so
// we just cast the length and throw in case the array is larger than
// int.MaxValue. There's not much we can do in this specific case.
return (nint)(uint)array.Length;
#else
return (nint)array.LongLength;
#endif
}
/// <summary>
/// Gets the length of a given array as a native integer.
/// </summary>
/// <param name="array">The input <see cref="Array"/> instance.</param>
/// <returns>The total length of <paramref name="array"/> as a native integer.</returns>
[Pure]
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static nint GetArrayNativeLength(Array array)
{
#if NETSTANDARD1_4
return (nint)(uint)array.Length;
#else
return (nint)array.LongLength;
#endif
}
/// <summary>
/// Gets the byte offset to the first <typeparamref name="T"/> element in a SZ array.
/// </summary>
/// <typeparam name="T">The type of values in the array.</typeparam>
/// <returns>The byte offset to the first <typeparamref name="T"/> element in a SZ array.</returns>
[Pure]
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static IntPtr GetArrayDataByteOffset<T>()
{
return TypeInfo<T>.ArrayDataByteOffset;
}
/// <summary>
/// Gets the byte offset to the first <typeparamref name="T"/> element in a 2D array.
/// </summary>
/// <typeparam name="T">The type of values in the array.</typeparam>
/// <returns>The byte offset to the first <typeparamref name="T"/> element in a 2D array.</returns>
[Pure]
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static IntPtr GetArray2DDataByteOffset<T>()
{
return TypeInfo<T>.Array2DDataByteOffset;
}
/// <summary>
/// Gets the byte offset to the first <typeparamref name="T"/> element in a 3D array.
/// </summary>
/// <typeparam name="T">The type of values in the array.</typeparam>
/// <returns>The byte offset to the first <typeparamref name="T"/> element in a 3D array.</returns>
[Pure]
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static IntPtr GetArray3DDataByteOffset<T>()
{
return TypeInfo<T>.Array3DDataByteOffset;
}
#if !SPAN_RUNTIME_SUPPORT
/// <summary>
/// Gets a byte offset describing a portable pinnable reference. This can either be an
/// interior pointer into some object data (described with a valid <see cref="object"/> reference
/// and a reference to some of its data), or a raw pointer (described with a <see langword="null"/>
/// reference to an <see cref="object"/>, and a reference that is assumed to refer to pinned data).
/// </summary>
/// <typeparam name="T">The type of field being referenced.</typeparam>
/// <param name="obj">The input <see cref="object"/> hosting the target field.</param>
/// <param name="data">A reference to a target field of type <typeparamref name="T"/> within <paramref name="obj"/>.</param>
/// <returns>
/// The <see cref="IntPtr"/> value representing the offset to the target field from the start of the object data
/// for the parameter <paramref name="obj"/>, or the value of the raw pointer passed as a tracked reference.
/// </returns>
[Pure]
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static unsafe IntPtr GetObjectDataOrReferenceByteOffset<T>(object? obj, ref T data)
{
if (obj is null)
{
return (IntPtr)Unsafe.AsPointer(ref data);
}
return ObjectMarshal.DangerousGetObjectDataByteOffset(obj, ref data);
}
/// <summary>
/// Gets a reference from data describing a portable pinnable reference. This can either be an
/// interior pointer into some object data (described with a valid <see cref="object"/> reference
/// and a byte offset into its data), or a raw pointer (described with a <see langword="null"/>
/// reference to an <see cref="object"/>, and a byte offset representing the value of the raw pointer).
/// </summary>
/// <typeparam name="T">The type of reference to retrieve.</typeparam>
/// <param name="obj">The input <see cref="object"/> hosting the target field.</param>
/// <param name="offset">The input byte offset for the <typeparamref name="T"/> reference to retrieve.</param>
/// <returns>A <typeparamref name="T"/> reference matching the given parameters.</returns>
[Pure]
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static unsafe ref T GetObjectDataAtOffsetOrPointerReference<T>(object? obj, IntPtr offset)
{
if (obj is null)
{
return ref Unsafe.AsRef<T>((void*)offset);
}
return ref ObjectMarshal.DangerousGetObjectDataReferenceAt<T>(obj, offset);
}
/// <summary>
/// Checks whether or not a given type is a reference type or contains references.
/// </summary>
/// <typeparam name="T">The type to check.</typeparam>
/// <returns>Whether or not <typeparamref name="T"/> respects the <see langword="unmanaged"/> constraint.</returns>
[Pure]
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static bool IsReferenceOrContainsReferences<T>()
{
return TypeInfo<T>.IsReferenceOrContainsReferences;
}
/// <summary>
/// Implements the logic for <see cref="IsReferenceOrContainsReferences{T}"/>.
/// </summary>
/// <param name="type">The current type to check.</param>
/// <returns>Whether or not <paramref name="type"/> is a reference type or contains references.</returns>
[Pure]
private static bool IsReferenceOrContainsReferences(Type type)
{
// Common case, for primitive types
if (type.GetTypeInfo().IsPrimitive)
{
return false;
}
if (!type.GetTypeInfo().IsValueType)
{
return true;
}
// Check if the type is Nullable<T>
if (Nullable.GetUnderlyingType(type) is Type nullableType)
{
type = nullableType;
}
if (type.GetTypeInfo().IsEnum)
{
return false;
}
// Complex struct, recursively inspect all fields
foreach (FieldInfo field in type.GetTypeInfo().DeclaredFields)
{
if (field.IsStatic)
{
continue;
}
if (IsReferenceOrContainsReferences(field.FieldType))
{
return true;
}
}
return false;
}
#endif
/// <summary>
/// A private generic class to preload type info for arbitrary runtime types.
/// </summary>
/// <typeparam name="T">The type to load info for.</typeparam>
private static class TypeInfo<T>
{
/// <summary>
/// The byte offset to the first <typeparamref name="T"/> element in a SZ array.
/// </summary>
public static readonly IntPtr ArrayDataByteOffset = MeasureArrayDataByteOffset();
/// <summary>
/// The byte offset to the first <typeparamref name="T"/> element in a 2D array.
/// </summary>
public static readonly IntPtr Array2DDataByteOffset = MeasureArray2DDataByteOffset();
/// <summary>
/// The byte offset to the first <typeparamref name="T"/> element in a 3D array.
/// </summary>
public static readonly IntPtr Array3DDataByteOffset = MeasureArray3DDataByteOffset();
#if !SPAN_RUNTIME_SUPPORT
/// <summary>
/// Indicates whether <typeparamref name="T"/> does not respect the <see langword="unmanaged"/> constraint.
/// </summary>
public static readonly bool IsReferenceOrContainsReferences = IsReferenceOrContainsReferences(typeof(T));
#endif
/// <summary>
/// Computes the value for <see cref="ArrayDataByteOffset"/>.
/// </summary>
/// <returns>The value of <see cref="ArrayDataByteOffset"/> for the current runtime.</returns>
[Pure]
private static IntPtr MeasureArrayDataByteOffset()
{
var array = new T[1];
return ObjectMarshal.DangerousGetObjectDataByteOffset(array, ref array[0]);
}
/// <summary>
/// Computes the value for <see cref="Array2DDataByteOffset"/>.
/// </summary>
/// <returns>The value of <see cref="Array2DDataByteOffset"/> for the current runtime.</returns>
[Pure]
private static IntPtr MeasureArray2DDataByteOffset()
{
var array = new T[1, 1];
return ObjectMarshal.DangerousGetObjectDataByteOffset(array, ref array[0, 0]);
}
/// <summary>
/// Computes the value for <see cref="Array3DDataByteOffset"/>.
/// </summary>
/// <returns>The value of <see cref="Array3DDataByteOffset"/> for the current runtime.</returns>
[Pure]
private static IntPtr MeasureArray3DDataByteOffset()
{
var array = new T[1, 1, 1];
return ObjectMarshal.DangerousGetObjectDataByteOffset(array, ref array[0, 0, 0]);
}
}
}
} | 42.404605 | 132 | 0.593592 | [
"MIT"
] | 47-studio-org/WindowsCommunityToolkit | Microsoft.Toolkit.HighPerformance/Helpers/Internals/RuntimeHelpers.cs | 12,891 | C# |
using System.Text.Json.Serialization;
namespace Essensoft.AspNetCore.Payment.Alipay.Domain
{
/// <summary>
/// PaytoolRequestDetail Data Structure.
/// </summary>
public class PaytoolRequestDetail : AlipayObject
{
/// <summary>
/// 支付工具金额。单位为元,精确到小数点后两位,取值范围[0.01,100000000]
/// </summary>
[JsonPropertyName("amount")]
public string Amount { get; set; }
/// <summary>
/// 付款方身份识别信息
/// </summary>
[JsonPropertyName("payer_identity")]
public UserIdentity PayerIdentity { get; set; }
/// <summary>
/// 定义为商户定制化的支付请求业务信息,由支付宝定义和管控,通常业务信息对于支付工具本身是弱依赖的。格式为json格式的字符串,需带上转移符。
/// </summary>
[JsonPropertyName("paytool_business_info")]
public string PaytoolBusinessInfo { get; set; }
/// <summary>
/// 商户支付工具单据号。注:不同的请求需更换不同的paytool_request_no,否则视为幂等请求
/// </summary>
[JsonPropertyName("paytool_request_no")]
public string PaytoolRequestNo { get; set; }
/// <summary>
/// 支付宝统一分配的支付工具编码; 现金:CASH;支付宝:ALIPAY,营销:TMARKETING;POS支付:POS,商户预付卡:MERCHANT_MCARD,OTHER:其他。注:通常情况下不传入OTHER,若需传入,请与接口owner联系确认
/// </summary>
[JsonPropertyName("tool_code")]
public string ToolCode { get; set; }
}
}
| 31.902439 | 136 | 0.616208 | [
"MIT"
] | LuohuaRain/payment | src/Essensoft.AspNetCore.Payment.Alipay/Domain/PaytoolRequestDetail.cs | 1,684 | C# |
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Management.Automation;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;
namespace PowerShellCourse
{
[Cmdlet(VerbsCommon.Find, "Duplicate")]
public class FindDuplicateCommand : PSCmdlet
{
[Parameter(Position = 1, Mandatory = true)]
public string Path { get; set; }
[Parameter(Position = 2, Mandatory = true)]
public string MD5Pattern { get; set; }
protected override void ProcessRecord()
{
WildcardPattern wildcard = new WildcardPattern(MD5Pattern, WildcardOptions.IgnoreCase);
ProviderInfo providerInfo = null;
var folder = GetResolvedProviderPathFromPSPath(Path, out providerInfo).FirstOrDefault();
foreach (var filePath in Directory.GetFiles(folder))
{
using (var md5 = MD5.Create())
{
using (var stream = File.OpenRead(filePath))
{
var md5sum = md5.ComputeHash(stream);
var calculatedMD5 = BitConverter.ToString(md5sum).Replace("-", "");
if (wildcard.IsMatch(calculatedMD5))
{
WriteObject(new { File = filePath, MD5 = calculatedMD5 });
}
}
}
}
}
}
}
| 27.744681 | 94 | 0.641104 | [
"MIT"
] | psymonn/myPowerShell | Sample Modules/extending-powershell/materials/3-extending-powershell-m2-parameters-processing-input-exercise-files/after/FindDuplicateCommand.cs | 1,306 | C# |
using GimmeMillions.Domain.Stocks.Data;
using System;
using System.Collections.Generic;
using System.Linq;
namespace GimmeMillions.Domain.Stocks
{
public enum StockDataPeriod
{
Week = 432000,
Day = 86400,
SixHour = 21600,
Hour = 3600,
FifteenMinute = 900,
FiveMinute = 300,
Minute = 60
};
public class StockData
{
public int Id { get; set; }
public StockSymbol Symbol { get; set; }
public DateTime Date { get; set; }
public StockDataPeriod Period { get; set; }
public decimal Open { get; set; }
public decimal High { get; set; }
public decimal Low { get; set; }
public decimal Close { get; set; }
public decimal AdjustedClose { get; set; }
public decimal Volume { get; set; }
public decimal PercentPeriodChange
{
get
{
if (Open == 0.0m)
return 0.0m;
return (decimal)100.0 * (Close - Open) / Open;
}
}
public decimal PercentPeriodRange
{
get
{
if (Low == 0.0m)
return 0.0m;
return (decimal)100.0 * (High - Low) / Low;
}
}
public decimal Range
{
get
{
return High - Low;
}
}
public decimal AveragePercentPeriodRange { get; set; }
public decimal PercentChangeHighToOpen
{
get
{
if (Open == 0.0m)
return 0.0m;
return 100.0m * (High - Open) / Open;
}
}
public decimal PercentHighToLow
{
get
{
if (Low == 0.0m)
return 0.0m;
return 100.0m * (High - Low) / Low;
}
}
public decimal PreviousClose { get; set; }
public decimal PercentChangeHighToPreviousClose
{
get
{
if (PreviousClose == 0.0m)
return 0.0m;
return 100.0m * (High - PreviousClose) / PreviousClose;
}
}
public decimal PercentChangeLowToPreviousClose
{
get
{
if (PreviousClose == 0.0m)
return 0.0m;
return 100.0m * (Low - PreviousClose) / PreviousClose;
}
}
public decimal PercentChangeOpenToPreviousClose
{
get
{
if (PreviousClose == 0.0m)
return 0.0m;
return 100.0m * (Open - PreviousClose) / PreviousClose;
}
}
public decimal PercentChangeFromPreviousClose
{
get
{
if (PreviousClose == 0.0m)
return 0.0m;
return 100.0m * (Close - PreviousClose) / PreviousClose;
}
}
public decimal AverageTrend
{
get
{
return (PercentChangeHighToPreviousClose +
PercentChangeLowToPreviousClose +
PercentChangeOpenToPreviousClose +
PercentChangeFromPreviousClose) / 4.0m;
}
}
public decimal Average
{
get
{
return (High + Low + Open + Close) / 4.0m;
}
}
public decimal TopWickPercent
{
get
{
if (Open == 0.0m)
{
return 0.0m;
}
if (PercentPeriodChange > 0.0m)
{
return 100.0m * (High - Close) / Open;
}
else
{
return 100.0m * (High - Open) / Open;
}
}
}
public decimal BottomWickPercent
{
get
{
if (Open == 0.0m)
{
return 0.0m;
}
if (PercentPeriodChange > 0.0m)
{
return 100.0m * (Open - Low) / Open;
}
else
{
return 100.0m * (Close - Low) / Open;
}
}
}
public decimal CMF
{
get
{
if (High == Low)
{
return 0.0m;
}
return ((Close - Low) - (High - Close)) / (High - Low);
}
}
public decimal PriceNormalizedVolume
{
get
{
return Math.Abs(Average * Volume);
}
}
public decimal Signal { get; set; }
public StockData(StockSymbol symbol, DateTime date, StockDataPeriod period,
decimal open, decimal high, decimal low, decimal close, decimal adjClose, decimal volume)
{
Symbol = symbol;
Date = date;
Period = period;
Open = open;
High = high;
Low = low;
Close = close;
AdjustedClose = adjClose;
PreviousClose = open;
Volume = volume + 1; //ensure volume is always at least 1
AveragePercentPeriodRange = PercentPeriodRange;
}
public StockData(StockSymbol symbol, DateTime date,
decimal open, decimal high, decimal low, decimal close, decimal adjClose, decimal volume,
decimal previousClose)
{
Symbol = symbol;
Date = date;
Open = open;
High = high;
Low = low;
Close = close;
AdjustedClose = adjClose;
PreviousClose = previousClose;
Volume = volume + 1; //ensure volume is always at least 1
AveragePercentPeriodRange = PercentPeriodRange;
Period = StockDataPeriod.Day;
}
public StockData(int id, StockSymbol symbol, DateTime date,
decimal open, decimal high, decimal low, decimal close, decimal adjClose, decimal volume,
decimal previousClose)
{
Id = id;
Symbol = symbol;
Date = date;
Open = open;
High = high;
Low = low;
Close = close;
AdjustedClose = adjClose;
PreviousClose = previousClose;
Volume = volume + 1; //ensure volume is always at least 1
AveragePercentPeriodRange = PercentPeriodRange;
Period = StockDataPeriod.Day;
}
public void ApplyScaling(decimal scale)
{
Open *= scale;
High *= scale;
Low *= scale;
Close *= scale;
AdjustedClose *= scale;
PreviousClose *= scale;
}
public void Invert()
{
Open *= -1.0m;
var newHigh = -1.0m * Low;
Low *= -1.0m * High;
High *= newHigh;
Close *= -1.0m;
AdjustedClose *= -1.0m;
PreviousClose *= -1.0m;
}
private StockData() { } //default constructor
public static StockData Combine(IEnumerable<StockData> stockDatas)
{
decimal high = stockDatas.Max(x => x.High);
decimal low = stockDatas.Min(x => x.Low);
decimal volume = stockDatas.Sum(x => x.Volume) + 1; //ensure volume is always at least 1
DateTime date = stockDatas.Min(x => x.Date);
DateTime endDate = stockDatas.Max(x => x.Date);
var first = stockDatas.First(x => x.Date == date);
var last = stockDatas.First(x => x.Date == endDate);
return new StockData(first.Symbol, date, first.Open, high, low, last.Close, last.AdjustedClose, volume, first.PreviousClose);
}
}
} | 27.787671 | 137 | 0.450826 | [
"BSD-3-Clause"
] | leblancdavid/GimmeMillions | Source/GimmeMillions.Domain/Stocks/Data/StockData.cs | 8,116 | C# |
using Microsoft.Extensions.DependencyInjection;
using System;
using System.Collections.Generic;
using System.Text;
namespace Threax.ReflectedServices
{
public interface IServiceSetup
{
void ConfigureServices(IServiceCollection services);
}
}
| 20.307692 | 60 | 0.776515 | [
"MIT"
] | threax/Threax.ReflectedServices | Threax.ReflectedServices/IServiceSetup.cs | 266 | C# |
using Xunit;
using System;
namespace Structurizr.Core.Tests
{
public class WorkspaceTests
{
private Workspace workspace = new Workspace("Name", "Description");
[Fact]
public void Test_SetApi_DoesNotThrowAnException_WhenANullUrlIsSpecified()
{
workspace.Api = null;
}
[Fact]
public void Test_SetApi_DoesNotThrowAnException_WhenAnEmptyUrlIsSpecified()
{
workspace.Api = "";
}
[Fact]
public void Test_SetApi_ThrowsAnException_WhenAnInvalidUrlIsSpecified()
{
try
{
workspace.Api = "www.somedomain.com";
throw new TestFailedException();
}
catch (Exception e)
{
Assert.Equal("www.somedomain.com is not a valid URL.", e.Message);
}
}
[Fact]
public void Test_SetApi_DoesNotThrowAnException_WhenAValidUrlIsSpecified()
{
workspace.Api = "http://www.somedomain.com";
Assert.Equal("http://www.somedomain.com", workspace.Api);
}
}
}
| 23.489796 | 83 | 0.560382 | [
"Apache-2.0"
] | kurattila/dotnet | Structurizr.Core.Tests/WorkspaceTests.cs | 1,153 | C# |
using System;
using System.ComponentModel;
using System.Xml.Serialization;
namespace Grauenwolf.TravellerTools.TradeCalculator
{
/// <remarks/>
[SerializableAttribute()]
[DesignerCategoryAttribute("code")]
[XmlTypeAttribute(AnonymousType = true)]
public class TradeGoodPurchase
{
/// <remarks/>
[XmlAttributeAttribute()]
public string Tag { get; set; }
/// <remarks/>
[XmlAttributeAttribute()]
public int Bonus { get; set; }
}
}
| 22.086957 | 51 | 0.641732 | [
"MIT"
] | Grauenwolf/TravellerTools | TravellerTools/Grauenwolf.TravellerTools.TradeCalculator/TradeGoodsTradeGoodPurchase.cs | 508 | C# |
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using System.Web;
using Azure;
using Azure.Storage.Blobs;
using Azure.Storage.Blobs.Models;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Azure.Cosmos.Table;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using Swashbuckle.AspNetCore.Annotations;
namespace MediaLibrary.Internet.Api.Controllers
{
[Route("/api/v1/[controller]")]
[ApiController]
[Authorize]
public class TransferController : ControllerBase
{
private static readonly string TransferPartitionKey = "transfer";
private readonly AppSettings _appSettings;
private readonly ILogger<TransferController> _logger;
public TransferController(IOptions<AppSettings> appSettings, ILogger<TransferController> logger)
{
_appSettings = appSettings.Value;
_logger = logger;
}
[HttpGet("mediaItems")]
[SwaggerOperation(
Summary = "Return list of media items that are pending transfer",
OperationId = "GetMediaItems"
)]
[Produces("application/json")]
[SwaggerResponse(StatusCodes.Status200OK, "Successful operation", typeof(IEnumerable<ImageEntity>))]
public async Task<IActionResult> GetAllAsync()
{
_logger.LogInformation("Listing all transfer items");
string tableName = _appSettings.TableName;
string tableConnectionString = _appSettings.TableConnectionString;
List<ImageEntity> listEntities = new List<ImageEntity>();
// Initialize table client
CloudStorageAccount storageAccount;
storageAccount = CloudStorageAccount.Parse(tableConnectionString);
CloudTableClient tableClient = storageAccount.CreateCloudTableClient(new TableClientConfiguration());
CloudTable table = tableClient.GetTableReference(tableName);
// Query by partition key
TableQuery<ImageEntity> partitionScanQuery = new TableQuery<ImageEntity>().Where(TableQuery.GenerateFilterCondition("PartitionKey", QueryComparisons.Equal, TransferPartitionKey));
TableContinuationToken token = null;
do
{
TableQuerySegment<ImageEntity> segment = await table.ExecuteQuerySegmentedAsync(partitionScanQuery, token);
token = segment.ContinuationToken;
foreach (ImageEntity entity in segment)
{
listEntities.Add(entity);
}
}
while (token != null);
return Ok(listEntities);
}
[HttpDelete("mediaItems/{id}")]
[SwaggerOperation(
Summary = "Removes a media transfer item by its ID",
OperationId = "DeleteMediaItem"
)]
[Produces("application/json")]
[SwaggerResponse(StatusCodes.Status204NoContent, "The media transfer item was removed")]
[SwaggerResponse(StatusCodes.Status404NotFound, "Media item not found")]
public async Task<IActionResult> DeleteItemAsync(string id)
{
_logger.LogInformation("Delete content for id {id}", id);
string tableName = _appSettings.TableName;
string tableConnectionString = _appSettings.TableConnectionString;
string containerName = _appSettings.MediaStorageContainer;
string storageConnectionString = _appSettings.MediaStorageConnectionString;
// Initialize table client
CloudStorageAccount storageAccount;
storageAccount = CloudStorageAccount.Parse(tableConnectionString);
CloudTableClient tableClient = storageAccount.CreateCloudTableClient(new TableClientConfiguration());
CloudTable table = tableClient.GetTableReference(tableName);
// Initialize blob container client
BlobContainerClient blobContainerClient = new BlobContainerClient(storageConnectionString, containerName);
string rowKey = id;
TableOperation retrieveOperation = TableOperation.Retrieve<ImageEntity>(TransferPartitionKey, rowKey);
TableResult result = await table.ExecuteAsync(retrieveOperation);
ImageEntity entity = result.Result as ImageEntity;
if (entity == null)
{
_logger.LogWarning("Item id {id} not found", id);
return NotFound();
}
var blobUriBuilder = new BlobUriBuilder(new Uri(entity.FileURL));
BlobClient blobClient = blobContainerClient.GetBlobClient(HttpUtility.UrlDecode(blobUriBuilder.BlobName));
await blobClient.DeleteIfExistsAsync();
blobUriBuilder = new BlobUriBuilder(new Uri(entity.ThumbnailURL));
blobClient = blobContainerClient.GetBlobClient(HttpUtility.UrlDecode(blobUriBuilder.BlobName));
await blobClient.DeleteIfExistsAsync();
TableOperation deleteOperation = TableOperation.Delete(entity);
result = await table.ExecuteAsync(deleteOperation);
return NoContent();
}
[HttpPost("fileContents")]
[SwaggerOperation(
Summary = "Retrieves file contents by path",
OperationId = "GetFileContents"
)]
[Consumes("application/json")]
[Produces("application/json", "image/jpeg", "image/png", "image/gif", "image/bmp")]
[SwaggerResponse(StatusCodes.Status200OK, "Successful operation", typeof(FileStreamResult))]
[SwaggerResponse(StatusCodes.Status404NotFound, "Path not found")]
public async Task<IActionResult> GetFileContentAsync(
[FromBody, SwaggerRequestBody("Path to the file", Required = true)] FileContentParams parms)
{
_logger.LogInformation("Getting content for file path: {path}", parms.Path);
string storageConnectionString = _appSettings.MediaStorageConnectionString;
string containerName = _appSettings.MediaStorageContainer;
// Authenticate with storage and download image via URL
var blobUriBuilder = new BlobUriBuilder(new Uri(parms.Path));
BlobClient blobClient = new BlobClient(storageConnectionString, containerName, HttpUtility.UrlDecode(blobUriBuilder.BlobName));
try
{
BlobDownloadInfo download = await blobClient.DownloadAsync();
return File(download.Content, download.ContentType);
}
catch (RequestFailedException e) when (e.ErrorCode == BlobErrorCode.BlobNotFound)
{
return NotFound();
}
}
public class FileContentParams
{
public string Path { get; set; }
}
}
}
| 42.374233 | 191 | 0.664398 | [
"MIT"
] | uraisg/media-library-azure | internet-webapp/MediaLibrary.Internet.Api/Controllers/TransferController.cs | 6,909 | C# |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See LICENSE in the project root for license information.
using UnityEngine;
using UnityEngine.EventSystems;
namespace Microsoft.MixedReality.Toolkit.Diagnostics
{
/// <summary>
/// The default implementation of the <see cref="Microsoft.MixedReality.Toolkit.Diagnostics.IMixedRealityDiagnosticsSystem"/>
/// </summary>
[HelpURL("https://microsoft.github.io/MixedRealityToolkit-Unity/Documentation/Diagnostics/DiagnosticsSystemGettingStarted.html")]
public class MixedRealityDiagnosticsSystem : BaseCoreSystem, IMixedRealityDiagnosticsSystem
{
public MixedRealityDiagnosticsSystem(
IMixedRealityServiceRegistrar registrar,
MixedRealityDiagnosticsProfile profile) : base(registrar, profile)
{ }
/// <inheritdoc/>
public override string Name { get; protected set; } = "Mixed Reality Diagnostics System";
/// <summary>
/// The parent object under which all visualization game objects will be placed.
/// </summary>
private GameObject diagnosticVisualizationParent = null;
/// <summary>
/// Creates the diagnostic visualizations and parents them so that the scene hierarchy does not get overly cluttered.
/// </summary>
private void CreateVisualizations()
{
diagnosticVisualizationParent = new GameObject("Diagnostics");
diagnosticVisualizationParent.AddComponent<DiagnosticsSystemVoiceControls>();
MixedRealityPlayspace.AddChild(diagnosticVisualizationParent.transform);
diagnosticVisualizationParent.SetActive(ShowDiagnostics);
// visual profiler settings
visualProfiler = diagnosticVisualizationParent.AddComponent<MixedRealityToolkitVisualProfiler>();
visualProfiler.WindowParent = diagnosticVisualizationParent.transform;
visualProfiler.IsVisible = ShowProfiler;
visualProfiler.FrameInfoVisible = ShowFrameInfo;
visualProfiler.MemoryStatsVisible = ShowMemoryStats;
visualProfiler.FrameSampleRate = FrameSampleRate;
visualProfiler.WindowAnchor = WindowAnchor;
visualProfiler.WindowOffset = WindowOffset;
visualProfiler.WindowScale = WindowScale;
visualProfiler.WindowFollowSpeed = WindowFollowSpeed;
}
private MixedRealityToolkitVisualProfiler visualProfiler = null;
#region IMixedRealityService
/// <inheritdoc />
public override void Initialize()
{
if (!Application.isPlaying) { return; }
MixedRealityDiagnosticsProfile profile = ConfigurationProfile as MixedRealityDiagnosticsProfile;
if (profile == null) { return; }
eventData = new DiagnosticsEventData(EventSystem.current);
// Apply profile settings
ShowDiagnostics = profile.ShowDiagnostics;
ShowProfiler = profile.ShowProfiler;
ShowFrameInfo = profile.ShowFrameInfo;
ShowMemoryStats = profile.ShowMemoryStats;
FrameSampleRate = profile.FrameSampleRate;
WindowAnchor = profile.WindowAnchor;
WindowOffset = profile.WindowOffset;
WindowScale = profile.WindowScale;
WindowFollowSpeed = profile.WindowFollowSpeed;
CreateVisualizations();
}
/// <inheritdoc />
public override void Destroy()
{
if (diagnosticVisualizationParent != null)
{
if (Application.isEditor)
{
Object.DestroyImmediate(diagnosticVisualizationParent);
}
else
{
diagnosticVisualizationParent.transform.DetachChildren();
Object.Destroy(diagnosticVisualizationParent);
}
diagnosticVisualizationParent = null;
}
}
#endregion IMixedRealityService
#region IMixedRealityDiagnosticsSystem
private MixedRealityDiagnosticsProfile diagnosticsSystemProfile = null;
/// <inheritdoc/>
public MixedRealityDiagnosticsProfile DiagnosticsSystemProfile
{
get
{
if (diagnosticsSystemProfile == null)
{
diagnosticsSystemProfile = ConfigurationProfile as MixedRealityDiagnosticsProfile;
}
return diagnosticsSystemProfile;
}
}
private bool showDiagnostics;
/// <inheritdoc />
public bool ShowDiagnostics
{
get { return showDiagnostics; }
set
{
if (value != showDiagnostics)
{
showDiagnostics = value;
// The voice commands are handled by the diagnosticVisualizationParent GameObject, we cannot disable the parent
// or we lose the ability to re-show the visualizations. Instead, disable each visualization as appropriate.
if (ShowProfiler)
{
visualProfiler.IsVisible = value;
}
}
}
}
private bool showProfiler;
/// <inheritdoc />
public bool ShowProfiler
{
get
{
return showProfiler;
}
set
{
if (value != showProfiler)
{
showProfiler = value;
if ((visualProfiler != null) && ShowDiagnostics)
{
visualProfiler.IsVisible = value;
}
}
}
}
private bool showFrameInfo;
/// <inheritdoc />
public bool ShowFrameInfo
{
get
{
return showFrameInfo;
}
set
{
if (value != showFrameInfo)
{
showFrameInfo = value;
if (visualProfiler != null)
{
visualProfiler.FrameInfoVisible = value;
}
}
}
}
private bool showMemoryStats;
/// <inheritdoc />
public bool ShowMemoryStats
{
get
{
return showMemoryStats;
}
set
{
if (value != showMemoryStats)
{
showMemoryStats = value;
if (visualProfiler != null)
{
visualProfiler.MemoryStatsVisible = value;
}
}
}
}
private float frameSampleRate = 0.1f;
/// <inheritdoc />
public float FrameSampleRate
{
get
{
return frameSampleRate;
}
set
{
if (!Mathf.Approximately(frameSampleRate, value))
{
frameSampleRate = value;
if (visualProfiler != null)
{
visualProfiler.FrameSampleRate = frameSampleRate;
}
}
}
}
#endregion IMixedRealityDiagnosticsSystem
#region IMixedRealityEventSource
private DiagnosticsEventData eventData;
/// <inheritdoc />
public uint SourceId => (uint)SourceName.GetHashCode();
/// <inheritdoc />
public string SourceName => "Mixed Reality Diagnostics System";
/// <inheritdoc />
public new bool Equals(object x, object y) => false;
/// <inheritdoc />
public int GetHashCode(object obj) => SourceName.GetHashCode();
private void RaiseDiagnosticsChanged()
{
eventData.Initialize(this);
HandleEvent(eventData, OnDiagnosticsChanged);
}
/// <summary>
/// Event sent whenever the diagnostics visualization changes.
/// </summary>
private static readonly ExecuteEvents.EventFunction<IMixedRealityDiagnosticsHandler> OnDiagnosticsChanged =
delegate (IMixedRealityDiagnosticsHandler handler, BaseEventData eventData)
{
var diagnosticsEventsData = ExecuteEvents.ValidateEventData<DiagnosticsEventData>(eventData);
handler.OnDiagnosticSettingsChanged(diagnosticsEventsData);
};
#endregion IMixedRealityEventSource
private TextAnchor windowAnchor = TextAnchor.LowerCenter;
/// <summary>
/// What part of the view port to anchor the window to.
/// </summary>
public TextAnchor WindowAnchor
{
get { return windowAnchor; }
set
{
if (value != windowAnchor)
{
windowAnchor = value;
if (visualProfiler != null)
{
visualProfiler.WindowAnchor = windowAnchor;
}
}
}
}
private Vector2 windowOffset = new Vector2(0.1f, 0.1f);
/// <summary>
/// The offset from the view port center applied based on the window anchor selection.
/// </summary>
public Vector2 WindowOffset
{
get { return windowOffset; }
set
{
if (value != windowOffset)
{
windowOffset = value;
if (visualProfiler != null)
{
visualProfiler.WindowOffset = windowOffset;
}
}
}
}
private float windowScale = 1.0f;
/// <summary>
/// Use to scale the window size up or down, can simulate a zooming effect.
/// </summary>
public float WindowScale
{
get { return windowScale; }
set
{
if (value != windowScale)
{
windowScale = value;
if (visualProfiler != null)
{
visualProfiler.WindowScale = windowScale;
}
}
}
}
private float windowFollowSpeed = 5.0f;
/// <summary>
/// How quickly to interpolate the window towards its target position and rotation.
/// </summary>
public float WindowFollowSpeed
{
get { return windowFollowSpeed; }
set
{
if (value != windowFollowSpeed)
{
windowFollowSpeed = value;
if (visualProfiler != null)
{
visualProfiler.WindowFollowSpeed = windowFollowSpeed;
}
}
}
}
}
}
| 31.160221 | 133 | 0.530674 | [
"MIT"
] | Bhaskers-Blu-Org2/MRDL_Unity_PeriodicTable | Assets/MixedRealityToolkit.Services/DiagnosticsSystem/MixedRealityDiagnosticsSystem.cs | 11,282 | C# |
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace OrderAutomationSystem
{
public partial class PaymentCredit : Form
{
Order order;
PictureBox selectedPicture;
Dictionary<Credit.CardType, PictureBox> pictures = new Dictionary<Credit.CardType, PictureBox>();
internal event callBack completed;
public PaymentCredit()
{
InitializeComponent();
selectedPicture = pictureAmericanEx;
pictures.Add(Credit.CardType.Visa, pictureVisa);
pictures.Add(Credit.CardType.MasterCard, pictureMaster);
pictures.Add(Credit.CardType.JCB, pictureJCB);
pictures.Add(Credit.CardType.Discover, pictureDiscover);
pictures.Add(Credit.CardType.AmericanExpress, pictureAmericanEx);
foreach(var item in pictures)
{
item.Value.Visible = false;
}
}
internal void getOrder(Order order)
{
this.order = order;
txtAmount.Text = order.Details.TotalAmount.ToString();
txtAmount.Enabled = false;
}
private void lblExit_Click(object sender, EventArgs e)
{
Buy pf = Application.OpenForms["PaymentForm"] as Buy;
pf.lblExit_Click(null, null);
}
private void btnPay_Click(object sender, EventArgs e)
{
ExpDate exp = new ExpDate();
exp.month = cmbMonth.SelectedItem.ToString();
exp.year = cmbYear.SelectedItem.ToString();
Credit crdt = new Credit(Convert.ToInt32(txtAmount.Text), txtNumber.Text, exp);
PaymentEvents pe = new PaymentEvents();
pe.Completed = true;
order.Details.Address = txtAdress.Text;
crdt.Name = txtName.Text;
crdt.Surname = txtSurname.Text;
pe.Order = order;
orderPayment op = new orderPayment();
op.Show();
this.completed(crdt, pe);
}
private void PaymentCredit_Load(object sender, EventArgs e)
{
}
private void txtNumber_TextChanged(object sender, EventArgs e)
{
selectedPicture.Visible = false;
Credit.CardType type = Credit.getCardType(txtNumber.Text);
if ( type != Credit.CardType.UnknownCard)
{
selectedPicture = pictures[type];
selectedPicture.Visible = true;
}
}
}
}
| 30.827586 | 105 | 0.596197 | [
"Apache-2.0"
] | GNFulLT/OrderAutomationSystem | OrderAutomationSystem/OrderAutomationSystem/PaymentCredit.cs | 2,684 | C# |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System;
using System.Collections.Generic;
using CoreWCF.Channels;
using CoreWCF.Description;
namespace CoreWCF.Configuration
{
public interface IServiceBuilder : ICommunicationObject
{
ICollection<Type> Services { get; }
ICollection<Uri> BaseAddresses { get; }
IServiceBuilder AddService<TService>() where TService : class;
IServiceBuilder AddService<TService>(Action<ServiceOptions> options) where TService : class;
IServiceBuilder AddService(Type service);
IServiceBuilder AddService(Type service, Action<ServiceOptions> options);
IServiceBuilder AddServiceEndpoint<TService, TContract>(Binding binding, string address);
IServiceBuilder AddServiceEndpoint<TService, TContract>(Binding binding, string address, Action<ServiceEndpoint> configureEndpoint);
IServiceBuilder AddServiceEndpoint<TService, TContract>(Binding binding, Uri address);
IServiceBuilder AddServiceEndpoint<TService, TContract>(Binding binding, Uri address, Action<ServiceEndpoint> configureEndpoint);
IServiceBuilder AddServiceEndpoint<TService, TContract>(Binding binding, string address, Uri listenUri);
IServiceBuilder AddServiceEndpoint<TService, TContract>(Binding binding, string address, Uri listenUri, Action<ServiceEndpoint> configureEndpoint);
IServiceBuilder AddServiceEndpoint<TService, TContract>(Binding binding, Uri address, Uri listenUri);
IServiceBuilder AddServiceEndpoint<TService, TContract>(Binding binding, Uri address, Uri listenUri, Action<ServiceEndpoint> configureEndpoint);
IServiceBuilder AddServiceEndpoint<TService>(Type implementedContract, Binding binding, string address);
IServiceBuilder AddServiceEndpoint<TService>(Type implementedContract, Binding binding, string address, Action<ServiceEndpoint> configureEndpoint);
IServiceBuilder AddServiceEndpoint<TService>(Type implementedContract, Binding binding, Uri address);
IServiceBuilder AddServiceEndpoint<TService>(Type implementedContract, Binding binding, Uri address, Action<ServiceEndpoint> configureEndpoint);
IServiceBuilder AddServiceEndpoint<TService>(Type implementedContract, Binding binding, string address, Uri listenUri);
IServiceBuilder AddServiceEndpoint<TService>(Type implementedContract, Binding binding, string address, Uri listenUri, Action<ServiceEndpoint> configureEndpoint);
IServiceBuilder AddServiceEndpoint<TService>(Type implementedContract, Binding binding, Uri address, Uri listenUri);
IServiceBuilder AddServiceEndpoint<TService>(Type implementedContract, Binding binding, Uri address, Uri listenUri, Action<ServiceEndpoint> configureEndpoint);
IServiceBuilder AddServiceEndpoint(Type service, Type implementedContract, Binding binding, Uri address, Uri listenUri);
IServiceBuilder AddServiceEndpoint(Type service, Type implementedContract, Binding binding, Uri address, Uri listenUri, Action<ServiceEndpoint> configureEndpoint);
}
}
| 79.3 | 171 | 0.792875 | [
"MIT"
] | JonathanHopeDMRC/CoreWCF | src/CoreWCF.Primitives/src/CoreWCF/Configuration/IServiceBuilder.cs | 3,172 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Eimbo.Dominio.Cadastro.Repositorio;
using Eimbo.Dominio.Comum.Entidade;
using Eimbo.Infraestrutura.Repositorio.NHibernate.Comum;
using NHibernate;
using NHibernate.Linq;
namespace Eimbo.Infraestrutura.Repositorio.NHibernate.Cadastro
{
public class FormaPagamentoRepositorioNHibernate :RepositorioNHibernate<FormaPagamento>,
IFormaPagamentoRepositorio
{
public FormaPagamentoRepositorioNHibernate(ISession _sessao) : base(_sessao) { }
public FormaPagamento ObterFormaPagamentoPorDescricao(String Descricao)
{
try {
return base._sessao.Query<FormaPagamento>().Where(f => (f.Descricao == Descricao)).FirstOrDefault();
}
catch (InvalidOperationException){
return null;
}
}
}
}
| 30.580645 | 116 | 0.669831 | [
"MIT"
] | RMedeirosCosta/eimbo | Eimbo.Infraestrutura.Repositorio.NHibernate/Cadastro/FormaPagamentoRepositorioNHibernate.cs | 950 | C# |
using System;
using System.Linq;
using Microsoft.Extensions.DependencyInjection;
using NUnit.Framework;
using TypedSql.InMemory;
using TypedSql.MySql;
using TypedSql.SqlServer;
using TypedSql.PostgreSql;
namespace TypedSql.Test
{
[TestFixture]
public class VariableTests : TestDataContextFixture
{
[Test]
[TestCase(typeof(MySqlQueryRunner))]
[TestCase(typeof(SqlServerQueryRunner))]
[TestCase(typeof(PostgreSqlQueryRunner))]
[TestCase(typeof(InMemoryQueryRunner))]
public void SetVariableTypes(Type runnerType)
{
var stmtList = new StatementList();
var intVar = stmtList.DeclareSqlVariable<int>("intVar");
stmtList.SetSqlVariable(intVar, ctx => 1);
var decimalVar = stmtList.DeclareSqlVariable<decimal>("decimalVar");
stmtList.SetSqlVariable(decimalVar, ctx => 2.23M);
var intNullableVar = stmtList.DeclareSqlVariable<int?>("intNullableVar");
stmtList.SetSqlVariable(intNullableVar, ctx => 42);
var stringVar = stmtList.DeclareSqlVariable<string>("stringVar");
stmtList.SetSqlVariable(stringVar, ctx => "test");
var select = stmtList.Select(ctx => new {
intVar = intVar.Value,
decimalVar = decimalVar.Value,
intNullableVar = intNullableVar.Value,
stringVar = stringVar.Value
});
var runner = (IQueryRunner)Provider.GetRequiredService(runnerType);
ResetDb(runner);
var results = runner.ExecuteQuery(select).ToList();
Assert.AreEqual(1, results.Count, "Should be 1 result");
Assert.AreEqual(1, results[0].intVar, "intVar should be 1");
Assert.AreEqual(42, results[0].intNullableVar, "intNullableVar should be 42");
Assert.AreEqual(2.23M, results[0].decimalVar, "decimalVar should be 2.23");
Assert.AreEqual("test", results[0].stringVar, "stringVar should be 'test'");
}
[Test]
[TestCase(typeof(MySqlQueryRunner))]
[TestCase(typeof(SqlServerQueryRunner))]
[TestCase(typeof(PostgreSqlQueryRunner))]
[TestCase(typeof(InMemoryQueryRunner))]
public void SetVariableFromSelect(Type runnerType)
{
var stmtList = new StatementList();
var testVariable = stmtList.DeclareSqlVariable<int>("test");
stmtList.SetSqlVariable(testVariable,
varctx => DB.Products.Where(p => p.ProductId == 1).Project((ctx, p) => p.ProductId).AsExpression(varctx));
var select = stmtList.Select(ctx => new { Result = testVariable.Value });
var runner = (IQueryRunner)Provider.GetRequiredService(runnerType);
ResetDb(runner);
var results = runner.ExecuteQuery(select).ToList();
Assert.AreEqual(1, results.Count, "Should be 1 result");
Assert.AreEqual(1, results[0].Result, "Selected variable should be 1");
}
[Test]
[TestCase(typeof(MySqlQueryRunner))]
[TestCase(typeof(SqlServerQueryRunner))]
[TestCase(typeof(PostgreSqlQueryRunner))]
[TestCase(typeof(InMemoryQueryRunner))]
public void SetVariableIdentityExpression(Type runnerType)
{
var stmtList = new StatementList();
stmtList.Insert(DB.Products, insert => insert.Value(p => p.Name, "test insert product"));
var identity = stmtList.DeclareSqlVariable<int>("myident");
stmtList.SetSqlVariable(identity, (ctx) => Function.LastInsertIdentity<int>(ctx));
var select = stmtList.Select(ctx => new { Identity = identity.Value });
var runner = (IQueryRunner)Provider.GetRequiredService(runnerType);
ResetDb(runner);
var results = runner.ExecuteQuery(select).ToList();
Assert.AreEqual(1, results.Count, "Should be 1 result");
Assert.AreEqual(3, results[0].Identity, "New identity should be 3");
}
}
}
| 41.530612 | 122 | 0.633661 | [
"MIT"
] | andersnm/TypedSql | TypedSql.Test/VariableTests.cs | 4,072 | 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: Microsoft.AspNetCore.Mvc.ApplicationParts.RelatedAssemblyAttribute("WepAPI_MVC_Sample.Views")]
[assembly: Microsoft.AspNetCore.Razor.Hosting.RazorLanguageVersionAttribute("2.1")]
[assembly: Microsoft.AspNetCore.Razor.Hosting.RazorConfigurationNameAttribute("MVC-2.1")]
[assembly: Microsoft.AspNetCore.Razor.Hosting.RazorExtensionAssemblyNameAttribute("MVC-2.1", "Microsoft.AspNetCore.Mvc.Razor.Extensions")]
// Generated by the MSBuild WriteCodeFragment class.
| 44.333333 | 139 | 0.627282 | [
"MIT"
] | manelperez/WepAPI_MVC_Sample | obj/Debug/netcoreapp2.1/WepAPI_MVC_Sample.RazorAssemblyInfo.cs | 931 | C# |
// Copyright (c) .NET Foundation and contributors. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System.CommandLine.Invocation;
using System.CommandLine.IO;
using System.CommandLine.Parsing;
using System.Threading.Tasks;
using FluentAssertions;
using Xunit;
namespace System.CommandLine.Suggest.Tests
{
public class SuggestionShellScriptHandlerTest
{
private readonly Parser _parser;
private readonly TestConsole _console;
public SuggestionShellScriptHandlerTest()
{
_parser = new SuggestionDispatcher(new TestSuggestionRegistration()).Parser;
_console = new TestConsole();
}
[Fact]
public async Task When_shell_type_is_not_supported_it_throws()
{
await _parser.InvokeAsync("script 123", _console);
_console.Error.ToString().Should().Contain("Shell '123' is not supported.");
}
[Fact]
public async Task It_should_print_bash_shell_script()
{
await _parser.InvokeAsync("script bash", _console);
_console.Out.ToString().Should().Contain("_dotnet_bash_complete()");
}
[Fact]
public async Task It_should_print_powershell_shell_script()
{
await _parser.InvokeAsync("script powershell", _console);
_console.Out.ToString().Should().Contain("Register-ArgumentCompleter");
}
}
}
| 30.734694 | 101 | 0.670651 | [
"MIT"
] | belav/command-line-api | src/System.CommandLine.Suggest.Tests/SuggestionShellScriptHandlerTest.cs | 1,508 | C# |
using System.Web.Mvc;
using Microsoft.Practices.Unity;
using VsixMvcAppResult.Models.Configuration.ConfigSections.ClientResources;
using VsixMvcAppResult.Models.Profile;
using VsixMvcAppResult.Models.Unity;
using VsixMvcAppResult.UI.Web.Areas.UserProfile.Models;
using VsixMvcAppResult.UI.Web.Controllers;
namespace VsixMvcAppResult.UI.Web.Areas.UserProfile.Controllers
{
[VsixMvcAppResult.UI.Web.Common.Mvc.Attributes.Authorize]
public class UserProfileController : Controller, IControllerWithClientResources
{
protected override void Dispose(bool disposing)
{
if (this.ProviderProfile != null)
{
this.ProviderProfile.Dispose();
}
base.Dispose(disposing);
}
public string[] GetControllerJavascriptResources
{
get { return new string[0]; }
}
public string[] GetControllerStyleSheetResources
{
get { return new string[0]; }
}
private IProfileProxy ProviderProfile;
public UserProfileController()
{
this.ProviderProfile = DependencyFactory.Resolve<IProfileProxy>();
}
[HttpGet]
public ActionResult Index()
{
UserProfileIndexModel model = new UserProfileIndexModel();
model.BaseViewModelInfo.Title = Resources.Account.AccountResources.UserProfile;
model.UserProfileResult = this.ProviderProfile.Get();
return View(model);
}
//[HttpPost]
//[ValidateAntiForgeryToken]
//public ActionResult Index(UserProfileIndexModel model)
//{
// model.BaseViewModelInfo.Title = Resources.Account.AccountResources.UserProfile;
// model.UserProfileResult = this.ProviderProfile.Get();
// return View(model);
//}
[HttpGet]
public ActionResult Edit()
{
UserProfileIndexModel model = new UserProfileIndexModel();
model.BaseViewModelInfo.Title = Resources.Account.AccountResources.UserProfile;
DataResultUserProfile userProfileResult = this.ProviderProfile.Get();
model.UserProfileResult = userProfileResult;
return View(model);
}
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Edit(UserProfileIndexModel model)
{
model.BaseViewModelInfo.Title = Resources.Account.AccountResources.UserProfile;
if (ModelState.IsValid)
{
// Set Culture & Theme values currently in use
model.UserProfileResult.Data.CultureName = MvcApplication.UserRequest.UserProfile.CultureName;
model.UserProfileResult.Data.Theme = MvcApplication.UserRequest.UserProfile.Theme;
DataResultUserProfile result = this.ProviderProfile.Update(model.UserProfileResult.Data);
model.UserProfileResultUpdated = result;
MvcApplication.UserRequest.UserProfile = result.Data;
MvcApplication.UserRequest.UserProfile.ApplyClientProperties();
model.BaseViewModelInfo.LocalizationResources = new LocalizationResourcesHelper(MvcApplication.UserRequest.UserProfile.Culture);
}
return View(model);
}
}
} | 35.595745 | 144 | 0.653915 | [
"MIT"
] | jordivila/Net_MVC_NLayer_Result | VsixMvcAppResult/VsixMvcAppResult.UI.Web.StandaloneSite/Areas/UserProfile/Controllers/UserProfileController.cs | 3,348 | 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.
#nullable disable
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Diagnostics;
using System.Linq;
using Microsoft.CodeAnalysis.CodeGen;
using Microsoft.CodeAnalysis.CSharp.Symbols;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.PooledObjects;
using Microsoft.CodeAnalysis.Symbols;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.CSharp
{
internal abstract class MethodToStateMachineRewriter : MethodToClassRewriter
{
internal readonly MethodSymbol OriginalMethod;
/// <summary>
/// True if we need to generate the code to do the bookkeeping so we can "finalize" the state machine
/// by executing code from its current state through the enclosing finally blocks. This is true for
/// iterators and false for async.
/// </summary>
private readonly bool _useFinalizerBookkeeping;
/// <summary>
/// Generate return statements from the state machine method body.
/// </summary>
protected abstract BoundStatement GenerateReturn(bool finished);
protected readonly SyntheticBoundNodeFactory F;
/// <summary>
/// The "state" of the state machine that is the translation of the iterator method.
/// </summary>
protected readonly FieldSymbol stateField;
/// <summary>
/// Cached "state" of the state machine within the MoveNext method. We work with a copy of
/// the state to avoid shared mutable state between threads. (Two threads can be executing
/// in a Task's MoveNext method because an awaited task may complete after the awaiter has
/// tested whether the subtask is complete but before the awaiter has returned)
/// </summary>
protected readonly LocalSymbol cachedState;
/// <summary>
/// Cached "this" local, used to store the captured "this", which is safe to cache locally since "this"
/// is semantically immutable.
/// It would be hard for such caching to happen at JIT level (since JIT does not know that it never changes).
/// NOTE: this field is null when we are not caching "this" which happens when
/// - not optimizing
/// - method is not capturing "this" at all
/// - containing type is a struct
/// (we could cache "this" as a ref local for struct containers,
/// but such caching would not save as much indirection and could actually
/// be done at JIT level, possibly more efficiently)
/// </summary>
protected readonly LocalSymbol cachedThis;
private int _nextState;
/// <summary>
/// For each distinct label, the set of states that need to be dispatched to that label.
/// Note that there is a dispatch occurring at every try-finally statement, so this
/// variable takes on a new set of values inside each try block.
/// </summary>
private Dictionary<LabelSymbol, List<int>> _dispatches = new Dictionary<
LabelSymbol,
List<int>
>();
/// <summary>
/// A try block might have no state (transitions) within it, in which case it does not need
/// to have a state to represent finalization. This flag tells us whether the current try
/// block that we are within has a finalizer state. Initially true as we have the (trivial)
/// finalizer state of -1 at the top level. Not used if !this.useFinalizerBookkeeping.
/// </summary>
private bool _hasFinalizerState = true;
/// <summary>
/// If hasFinalizerState is true, this is the state for finalization from anywhere in this
/// try block. Initially set to -1, representing the no-op finalization required at the top
/// level. Not used if !this.useFinalizerBookkeeping.
/// </summary>
private int _currentFinalizerState = -1;
/// <summary>
/// A pool of fields used to hoist locals. They appear in this set when not in scope,
/// so that members of this set may be allocated to locals when the locals come into scope.
/// </summary>
private Dictionary<
TypeSymbol,
ArrayBuilder<StateMachineFieldSymbol>
> _lazyAvailableReusableHoistedFields;
/// <summary>
/// Fields allocated for temporary variables are given unique names distinguished by a number at the end.
/// This counter ensures they are unique within a given translated method.
/// </summary>
private int _nextHoistedFieldId = 1;
/// <summary>
/// Used to enumerate the instance fields of a struct.
/// </summary>
private readonly EmptyStructTypeCache _emptyStructTypeCache =
EmptyStructTypeCache.CreateNeverEmpty();
/// <summary>
/// The set of local variables and parameters that were hoisted and need a proxy.
/// </summary>
private readonly IReadOnlySet<Symbol> _hoistedVariables;
private readonly SynthesizedLocalOrdinalsDispenser _synthesizedLocalOrdinals;
private int _nextFreeHoistedLocalSlot;
// new:
public MethodToStateMachineRewriter(
SyntheticBoundNodeFactory F,
MethodSymbol originalMethod,
FieldSymbol state,
IReadOnlySet<Symbol> hoistedVariables,
IReadOnlyDictionary<Symbol, CapturedSymbolReplacement> nonReusableLocalProxies,
SynthesizedLocalOrdinalsDispenser synthesizedLocalOrdinals,
VariableSlotAllocator slotAllocatorOpt,
int nextFreeHoistedLocalSlot,
BindingDiagnosticBag diagnostics,
bool useFinalizerBookkeeping
) : base(slotAllocatorOpt, F.CompilationState, diagnostics)
{
Debug.Assert(F != null);
Debug.Assert(originalMethod != null);
Debug.Assert(state != null);
Debug.Assert(nonReusableLocalProxies != null);
Debug.Assert(diagnostics != null);
Debug.Assert(hoistedVariables != null);
Debug.Assert(nextFreeHoistedLocalSlot >= 0);
this.F = F;
this.stateField = state;
this.cachedState = F.SynthesizedLocal(
F.SpecialType(SpecialType.System_Int32),
syntax: F.Syntax,
kind: SynthesizedLocalKind.StateMachineCachedState
);
_useFinalizerBookkeeping = useFinalizerBookkeeping;
_hasFinalizerState = useFinalizerBookkeeping;
this.OriginalMethod = originalMethod;
_hoistedVariables = hoistedVariables;
_synthesizedLocalOrdinals = synthesizedLocalOrdinals;
_nextFreeHoistedLocalSlot = nextFreeHoistedLocalSlot;
foreach (var proxy in nonReusableLocalProxies)
{
this.proxies.Add(proxy.Key, proxy.Value);
}
// create cache local for reference type "this" in Release
var thisParameter = originalMethod.ThisParameter;
CapturedSymbolReplacement thisProxy;
if (
(object)thisParameter != null
&& thisParameter.Type.IsReferenceType
&& proxies.TryGetValue(thisParameter, out thisProxy)
&& F.Compilation.Options.OptimizationLevel == OptimizationLevel.Release
)
{
BoundExpression thisProxyReplacement = thisProxy.Replacement(
F.Syntax,
frameType => F.This()
);
this.cachedThis = F.SynthesizedLocal(
thisProxyReplacement.Type,
syntax: F.Syntax,
kind: SynthesizedLocalKind.FrameCache
);
}
}
protected override bool NeedsProxy(Symbol localOrParameter)
{
Debug.Assert(
localOrParameter.Kind == SymbolKind.Local
|| localOrParameter.Kind == SymbolKind.Parameter
);
return _hoistedVariables.Contains(localOrParameter);
}
protected override TypeMap TypeMap
{
get { return ((SynthesizedContainer)F.CurrentType).TypeMap; }
}
protected override MethodSymbol CurrentMethod
{
get { return F.CurrentFunction; }
}
protected override NamedTypeSymbol ContainingType
{
get { return OriginalMethod.ContainingType; }
}
internal IReadOnlySet<Symbol> HoistedVariables
{
get { return _hoistedVariables; }
}
protected override BoundExpression FramePointer(
SyntaxNode syntax,
NamedTypeSymbol frameClass
)
{
var oldSyntax = F.Syntax;
F.Syntax = syntax;
var result = F.This();
Debug.Assert(
TypeSymbol.Equals(frameClass, result.Type, TypeCompareKind.ConsiderEverything2)
);
F.Syntax = oldSyntax;
return result;
}
protected void AddState(out int stateNumber, out GeneratedLabelSymbol resumeLabel)
{
stateNumber = _nextState++;
if (_useFinalizerBookkeeping && !_hasFinalizerState)
{
_currentFinalizerState = _nextState++;
_hasFinalizerState = true;
}
AddState(stateNumber, out resumeLabel);
}
protected void AddState(int stateNumber, out GeneratedLabelSymbol resumeLabel)
{
if (_dispatches == null)
{
_dispatches = new Dictionary<LabelSymbol, List<int>>();
}
resumeLabel = F.GenerateLabel("stateMachine");
var states = new List<int>();
states.Add(stateNumber);
_dispatches.Add(resumeLabel, states);
}
protected BoundStatement Dispatch()
{
return F.Switch(
F.Local(cachedState),
(
from kv in _dispatches
orderby kv.Value[0]
select F.SwitchSection(kv.Value, F.Goto(kv.Key))
).ToImmutableArray()
);
}
#if DEBUG
public override BoundNode VisitSequence(BoundSequence node)
{
// Spilled local temps do not appear here in a sequence expression, because any temps in a
// sequence expression that need to be spilled would have been moved up to the
// statement level by the AwaitLiftingRewriter.
foreach (var local in node.Locals)
{
Debug.Assert(!NeedsProxy(local) || proxies.ContainsKey(local));
}
return base.VisitSequence(node);
}
#endif
/// <summary>
/// Translate a statement that declares a given set of locals. Also allocates and frees hoisted temps as
/// required for the translation.
/// </summary>
/// <param name="locals">The set of locals declared in the original version of this statement</param>
/// <param name="wrapped">A delegate to return the translation of the body of this statement</param>
private BoundStatement PossibleIteratorScope(
ImmutableArray<LocalSymbol> locals,
Func<BoundStatement> wrapped
)
{
if (locals.IsDefaultOrEmpty)
{
return wrapped();
}
var hoistedLocalsWithDebugScopes = ArrayBuilder<StateMachineFieldSymbol>.GetInstance();
foreach (var local in locals)
{
if (!NeedsProxy(local))
{
continue;
}
// Ref synthesized variables have proxies that are allocated in VisitAssignmentOperator.
if (local.RefKind != RefKind.None)
{
Debug.Assert(local.SynthesizedKind == SynthesizedLocalKind.Spill);
continue;
}
CapturedSymbolReplacement proxy;
bool reused = false;
if (!proxies.TryGetValue(local, out proxy))
{
proxy = new CapturedToStateMachineFieldReplacement(
GetOrAllocateReusableHoistedField(
TypeMap.SubstituteType(local.Type).Type,
out reused,
local
),
isReusable: true
);
proxies.Add(local, proxy);
}
// We need to produce hoisted local scope debug information for user locals as well as
// lambda display classes, since Dev12 EE uses them to determine which variables are displayed
// in Locals window.
if (
(
local.SynthesizedKind == SynthesizedLocalKind.UserDefined
&& local.ScopeDesignatorOpt?.Kind() != SyntaxKind.SwitchSection
)
|| local.SynthesizedKind == SynthesizedLocalKind.LambdaDisplayClass
)
{
// NB: This is the case when the local backed by recycled field will not be visible in debugger.
// It may be possible in the future, but for now a backing field can be mapped only to a single local.
if (!reused)
{
hoistedLocalsWithDebugScopes.Add(
((CapturedToStateMachineFieldReplacement)proxy).HoistedField
);
}
}
}
var translatedStatement = wrapped();
var variableCleanup = ArrayBuilder<BoundAssignmentOperator>.GetInstance();
// produce cleanup code for all fields of locals defined by this block
// as well as all proxies allocated by VisitAssignmentOperator within this block:
foreach (var local in locals)
{
CapturedSymbolReplacement proxy;
if (!proxies.TryGetValue(local, out proxy))
{
continue;
}
var simpleProxy = proxy as CapturedToStateMachineFieldReplacement;
if (simpleProxy != null)
{
AddVariableCleanup(variableCleanup, simpleProxy.HoistedField);
if (proxy.IsReusable)
{
FreeReusableHoistedField(simpleProxy.HoistedField);
}
}
else
{
foreach (
var field in ((CapturedToExpressionSymbolReplacement)proxy).HoistedFields
)
{
AddVariableCleanup(variableCleanup, field);
if (proxy.IsReusable)
{
FreeReusableHoistedField(field);
}
}
}
}
if (variableCleanup.Count != 0)
{
translatedStatement = F.Block(
translatedStatement,
F.Block(
variableCleanup.SelectAsArray(
(e, f) => (BoundStatement)f.ExpressionStatement(e),
F
)
)
);
}
variableCleanup.Free();
// wrap the node in an iterator scope for debugging
if (hoistedLocalsWithDebugScopes.Count != 0)
{
translatedStatement = MakeStateMachineScope(
hoistedLocalsWithDebugScopes.ToImmutable(),
translatedStatement
);
}
hoistedLocalsWithDebugScopes.Free();
return translatedStatement;
}
/// <remarks>
/// Must remain in sync with <see cref="TryUnwrapBoundStateMachineScope"/>.
/// </remarks>
internal BoundBlock MakeStateMachineScope(
ImmutableArray<StateMachineFieldSymbol> hoistedLocals,
BoundStatement statement
)
{
return F.Block(new BoundStateMachineScope(F.Syntax, hoistedLocals, statement));
}
/// <remarks>
/// Must remain in sync with <see cref="MakeStateMachineScope"/>.
/// </remarks>
internal static bool TryUnwrapBoundStateMachineScope(
ref BoundStatement statement,
out ImmutableArray<StateMachineFieldSymbol> hoistedLocals
)
{
if (statement.Kind == BoundKind.Block)
{
var rewrittenBlock = (BoundBlock)statement;
var rewrittenStatements = rewrittenBlock.Statements;
if (
rewrittenStatements.Length == 1
&& rewrittenStatements[0].Kind == BoundKind.StateMachineScope
)
{
var stateMachineScope = (BoundStateMachineScope)rewrittenStatements[0];
statement = stateMachineScope.Statement;
hoistedLocals = stateMachineScope.Fields;
return true;
}
}
hoistedLocals = ImmutableArray<StateMachineFieldSymbol>.Empty;
return false;
}
private void AddVariableCleanup(
ArrayBuilder<BoundAssignmentOperator> cleanup,
FieldSymbol field
)
{
if (MightContainReferences(field.Type))
{
cleanup.Add(
F.AssignmentExpression(F.Field(F.This(), field), F.NullOrDefault(field.Type))
);
}
}
/// <summary>
/// Might the given type be, or contain, managed references? This is used to determine which
/// fields allocated to temporaries should be cleared when the underlying variable goes out of scope, so
/// that they do not cause unnecessary object retention.
/// </summary>
private bool MightContainReferences(TypeSymbol type)
{
if (type.IsReferenceType || type.TypeKind == TypeKind.TypeParameter)
return true; // type parameter or reference type
if (type.TypeKind != TypeKind.Struct)
return false; // enums, etc
if (type.SpecialType == SpecialType.System_TypedReference)
return true;
if (type.SpecialType != SpecialType.None)
return false; // int, etc
if (!type.IsFromCompilation(this.CompilationState.ModuleBuilderOpt.Compilation))
return true; // perhaps from ref assembly
foreach (var f in _emptyStructTypeCache.GetStructInstanceFields(type))
{
if (MightContainReferences(f.Type))
return true;
}
return false;
}
private StateMachineFieldSymbol GetOrAllocateReusableHoistedField(
TypeSymbol type,
out bool reused,
LocalSymbol local = null
)
{
ArrayBuilder<StateMachineFieldSymbol> fields;
if (
_lazyAvailableReusableHoistedFields != null
&& _lazyAvailableReusableHoistedFields.TryGetValue(type, out fields)
&& fields.Count > 0
)
{
var field = fields.Last();
fields.RemoveLast();
reused = true;
return field;
}
reused = false;
var slotIndex = _nextHoistedFieldId++;
if (local?.SynthesizedKind == SynthesizedLocalKind.UserDefined)
{
string fieldName = GeneratedNames.MakeHoistedLocalFieldName(
SynthesizedLocalKind.UserDefined,
slotIndex,
local.Name
);
return F.StateMachineField(
type,
fieldName,
SynthesizedLocalKind.UserDefined,
slotIndex
);
}
return F.StateMachineField(
type,
GeneratedNames.ReusableHoistedLocalFieldName(slotIndex)
);
}
private void FreeReusableHoistedField(StateMachineFieldSymbol field)
{
ArrayBuilder<StateMachineFieldSymbol> fields;
if (
_lazyAvailableReusableHoistedFields == null
|| !_lazyAvailableReusableHoistedFields.TryGetValue(field.Type, out fields)
)
{
if (_lazyAvailableReusableHoistedFields == null)
{
_lazyAvailableReusableHoistedFields = new Dictionary<
TypeSymbol,
ArrayBuilder<StateMachineFieldSymbol>
>(Symbols.SymbolEqualityComparer.IgnoringDynamicTupleNamesAndNullability);
}
_lazyAvailableReusableHoistedFields.Add(
field.Type,
fields = new ArrayBuilder<StateMachineFieldSymbol>()
);
}
fields.Add(field);
}
private BoundExpression HoistRefInitialization(
SynthesizedLocal local,
BoundAssignmentOperator node
)
{
Debug.Assert(local.SynthesizedKind == SynthesizedLocalKind.Spill);
Debug.Assert(local.SyntaxOpt != null);
Debug.Assert(this.OriginalMethod.IsAsync);
var right = (BoundExpression)Visit(node.Right);
var sideEffects = ArrayBuilder<BoundExpression>.GetInstance();
bool needsSacrificialEvaluation = false;
var hoistedFields = ArrayBuilder<StateMachineFieldSymbol>.GetInstance();
AwaitExpressionSyntax awaitSyntaxOpt;
int syntaxOffset;
if (F.Compilation.Options.OptimizationLevel == OptimizationLevel.Debug)
{
awaitSyntaxOpt = (AwaitExpressionSyntax)local.GetDeclaratorSyntax();
syntaxOffset = OriginalMethod.CalculateLocalSyntaxOffset(
LambdaUtilities.GetDeclaratorPosition(awaitSyntaxOpt),
awaitSyntaxOpt.SyntaxTree
);
}
else
{
// These are only used to calculate debug id for ref-spilled variables,
// no need to do so in release build.
awaitSyntaxOpt = null;
syntaxOffset = -1;
}
var replacement = HoistExpression(
right,
awaitSyntaxOpt,
syntaxOffset,
local.RefKind,
sideEffects,
hoistedFields,
ref needsSacrificialEvaluation
);
proxies.Add(
local,
new CapturedToExpressionSymbolReplacement(
replacement,
hoistedFields.ToImmutableAndFree(),
isReusable: true
)
);
if (needsSacrificialEvaluation)
{
var type = TypeMap.SubstituteType(local.Type).Type;
var sacrificialTemp = F.SynthesizedLocal(type, refKind: RefKind.Ref);
Debug.Assert(
TypeSymbol.Equals(type, replacement.Type, TypeCompareKind.ConsiderEverything2)
);
return F.Sequence(
ImmutableArray.Create(sacrificialTemp),
sideEffects.ToImmutableAndFree(),
F.AssignmentExpression(F.Local(sacrificialTemp), replacement, isRef: true)
);
}
if (sideEffects.Count == 0)
{
sideEffects.Free();
return null;
}
var last = sideEffects.Last();
sideEffects.RemoveLast();
return F.Sequence(
ImmutableArray<LocalSymbol>.Empty,
sideEffects.ToImmutableAndFree(),
last
);
}
private BoundExpression HoistExpression(
BoundExpression expr,
AwaitExpressionSyntax awaitSyntaxOpt,
int syntaxOffset,
RefKind refKind,
ArrayBuilder<BoundExpression> sideEffects,
ArrayBuilder<StateMachineFieldSymbol> hoistedFields,
ref bool needsSacrificialEvaluation
)
{
switch (expr.Kind)
{
case BoundKind.ArrayAccess:
{
var array = (BoundArrayAccess)expr;
BoundExpression expression = HoistExpression(
array.Expression,
awaitSyntaxOpt,
syntaxOffset,
RefKind.None,
sideEffects,
hoistedFields,
ref needsSacrificialEvaluation
);
var indices = ArrayBuilder<BoundExpression>.GetInstance();
foreach (var index in array.Indices)
{
indices.Add(
HoistExpression(
index,
awaitSyntaxOpt,
syntaxOffset,
RefKind.None,
sideEffects,
hoistedFields,
ref needsSacrificialEvaluation
)
);
}
needsSacrificialEvaluation = true; // need to force array index out of bounds exceptions
return array.Update(expression, indices.ToImmutableAndFree(), array.Type);
}
case BoundKind.FieldAccess:
{
var field = (BoundFieldAccess)expr;
if (field.FieldSymbol.IsStatic)
{
// the address of a static field, and the value of a readonly static field, is stable
if (refKind != RefKind.None || field.FieldSymbol.IsReadOnly)
return expr;
goto default;
}
if (refKind == RefKind.None)
{
goto default;
}
var isFieldOfStruct = !field.FieldSymbol.ContainingType.IsReferenceType;
var receiver = HoistExpression(
field.ReceiverOpt,
awaitSyntaxOpt,
syntaxOffset,
isFieldOfStruct ? refKind : RefKind.None,
sideEffects,
hoistedFields,
ref needsSacrificialEvaluation
);
if (receiver.Kind != BoundKind.ThisReference && !isFieldOfStruct)
{
needsSacrificialEvaluation = true; // need the null check in field receiver
}
return F.Field(receiver, field.FieldSymbol);
}
case BoundKind.ThisReference:
case BoundKind.BaseReference:
case BoundKind.DefaultExpression:
return expr;
case BoundKind.Call:
var call = (BoundCall)expr;
// NOTE: There are two kinds of 'In' arguments that we may see at this point:
// - `RefKindExtensions.StrictIn` (originally specified with 'In' modifier)
// - `RefKind.In` (specified with no modifiers and matched an 'In' parameter)
//
// It is allowed to spill ordinary `In` arguments by value if reference-preserving spilling is not possible.
// The "strict" ones do not permit implicit copying, so the same situation should result in an error.
if (refKind != RefKind.None && refKind != RefKind.In)
{
Debug.Assert(call.Method.RefKind != RefKind.None);
F.Diagnostics.Add(
ErrorCode.ERR_RefReturningCallAndAwait,
F.Syntax.Location,
call.Method
);
}
// method call is not referentially transparent, we can only spill the result value.
refKind = RefKind.None;
goto default;
case BoundKind.ConditionalOperator:
var conditional = (BoundConditionalOperator)expr;
// NOTE: There are two kinds of 'In' arguments that we may see at this point:
// - `RefKindExtensions.StrictIn` (originally specified with 'In' modifier)
// - `RefKind.In` (specified with no modifiers and matched an 'In' parameter)
//
// It is allowed to spill ordinary `In` arguments by value if reference-preserving spilling is not possible.
// The "strict" ones do not permit implicit copying, so the same situation should result in an error.
if (refKind != RefKind.None && refKind != RefKind.RefReadOnly)
{
Debug.Assert(conditional.IsRef);
F.Diagnostics.Add(ErrorCode.ERR_RefConditionalAndAwait, F.Syntax.Location);
}
// conditional expr is not referentially transparent, we can only spill the result value.
refKind = RefKind.None;
goto default;
default:
if (expr.ConstantValue != null)
{
return expr;
}
if (refKind != RefKind.None)
{
throw ExceptionUtilities.UnexpectedValue(expr.Kind);
}
TypeSymbol fieldType = expr.Type;
StateMachineFieldSymbol hoistedField;
if (F.Compilation.Options.OptimizationLevel == OptimizationLevel.Debug)
{
const SynthesizedLocalKind kind = SynthesizedLocalKind.AwaitByRefSpill;
Debug.Assert(awaitSyntaxOpt != null);
int ordinal = _synthesizedLocalOrdinals.AssignLocalOrdinal(
kind,
syntaxOffset
);
var id = new LocalDebugId(syntaxOffset, ordinal);
// Editing await expression is not allowed. Thus all spilled fields will be present in the previous state machine.
// However, it may happen that the type changes, in which case we need to allocate a new slot.
int slotIndex;
if (
slotAllocatorOpt == null
|| !slotAllocatorOpt.TryGetPreviousHoistedLocalSlotIndex(
awaitSyntaxOpt,
F.ModuleBuilderOpt.Translate(
fieldType,
awaitSyntaxOpt,
Diagnostics.DiagnosticBag
),
kind,
id,
Diagnostics.DiagnosticBag,
out slotIndex
)
)
{
slotIndex = _nextFreeHoistedLocalSlot++;
}
string fieldName = GeneratedNames.MakeHoistedLocalFieldName(
kind,
slotIndex
);
hoistedField = F.StateMachineField(
expr.Type,
fieldName,
new LocalSlotDebugInfo(kind, id),
slotIndex
);
}
else
{
hoistedField = GetOrAllocateReusableHoistedField(fieldType, reused: out _);
}
hoistedFields.Add(hoistedField);
var replacement = F.Field(F.This(), hoistedField);
sideEffects.Add(F.AssignmentExpression(replacement, expr));
return replacement;
}
}
#region Visitors
public override BoundNode Visit(BoundNode node)
{
if (node == null)
return node;
var oldSyntax = F.Syntax;
F.Syntax = node.Syntax;
var result = base.Visit(node);
F.Syntax = oldSyntax;
return result;
}
public override BoundNode VisitBlock(BoundBlock node)
{
return PossibleIteratorScope(node.Locals, () => (BoundStatement)base.VisitBlock(node));
}
public override BoundNode VisitScope(BoundScope node)
{
Debug.Assert(!node.Locals.IsEmpty);
var newLocalsBuilder = ArrayBuilder<LocalSymbol>.GetInstance();
var hoistedLocalsWithDebugScopes = ArrayBuilder<StateMachineFieldSymbol>.GetInstance();
bool localsRewritten = false;
foreach (var local in node.Locals)
{
// BoundScope is only used for switch
Debug.Assert(
local.SynthesizedKind == SynthesizedLocalKind.UserDefined
&& (
local.ScopeDesignatorOpt?.Kind() == SyntaxKind.SwitchSection
|| local.ScopeDesignatorOpt?.Kind() == SyntaxKind.SwitchExpressionArm
)
);
LocalSymbol localToUse;
if (TryRewriteLocal(local, out localToUse))
{
newLocalsBuilder.Add(localToUse);
localsRewritten |= ((object)local != localToUse);
continue;
}
hoistedLocalsWithDebugScopes.Add(
((CapturedToStateMachineFieldReplacement)proxies[local]).HoistedField
);
}
var statements = VisitList(node.Statements);
// wrap the node in an iterator scope for debugging
if (hoistedLocalsWithDebugScopes.Count != 0)
{
BoundStatement translated;
if (newLocalsBuilder.Count == 0)
{
newLocalsBuilder.Free();
translated = new BoundStatementList(node.Syntax, statements);
}
else
{
translated = node.Update(newLocalsBuilder.ToImmutableAndFree(), statements);
}
return MakeStateMachineScope(
hoistedLocalsWithDebugScopes.ToImmutable(),
translated
);
}
else
{
hoistedLocalsWithDebugScopes.Free();
ImmutableArray<LocalSymbol> newLocals;
if (localsRewritten)
{
newLocals = newLocalsBuilder.ToImmutableAndFree();
}
else
{
newLocalsBuilder.Free();
newLocals = node.Locals;
}
return node.Update(newLocals, statements);
}
}
public override BoundNode VisitForStatement(BoundForStatement node)
{
throw ExceptionUtilities.Unreachable; // for statements have been lowered away by now
}
public override BoundNode VisitUsingStatement(BoundUsingStatement node)
{
throw ExceptionUtilities.Unreachable; // using statements have been lowered away by now
}
public override BoundNode VisitExpressionStatement(BoundExpressionStatement node)
{
// ref assignments might be translated away (into nothing). If so just
// return no statement. The enclosing statement list will just omit it.
BoundExpression expression = (BoundExpression)this.Visit(node.Expression);
return (expression == null) ? null : node.Update(expression);
}
public override BoundNode VisitAssignmentOperator(BoundAssignmentOperator node)
{
if (node.Left.Kind != BoundKind.Local)
{
return base.VisitAssignmentOperator(node);
}
var leftLocal = ((BoundLocal)node.Left).LocalSymbol;
if (!NeedsProxy(leftLocal))
{
return base.VisitAssignmentOperator(node);
}
if (proxies.ContainsKey(leftLocal))
{
Debug.Assert(!node.IsRef);
return base.VisitAssignmentOperator(node);
}
// TODO (move to AsyncMethodToStateMachineRewriter, this is not applicable to iterators)
// User-declared variables are preassigned their proxies, and by-value synthesized variables
// are assigned proxies at the beginning of their scope by the enclosing construct.
// Here we handle ref temps. Ref synthesized variables are the target of a ref assignment operator before
// being used in any other way.
Debug.Assert(leftLocal.SynthesizedKind == SynthesizedLocalKind.Spill);
Debug.Assert(node.IsRef);
// We have an assignment to a variable that has not yet been assigned a proxy.
// So we assign the proxy before translating the assignment.
return HoistRefInitialization((SynthesizedLocal)leftLocal, node);
}
/// <summary>
/// The try statement is the most complex part of the state machine transformation.
/// Since the CLR will not allow a 'goto' into the scope of a try statement, we must
/// generate the dispatch to the state's label stepwise. That is done by translating
/// the try statements from the inside to the outside. Within a try statement, we
/// start with an empty dispatch table (representing the mapping from state numbers
/// to labels). During translation of the try statement's body, the dispatch table
/// will be filled in with the data necessary to dispatch once we're inside the try
/// block. We generate that at the head of the translated try statement. Then, we
/// copy all of the states from that table into the table for the enclosing construct,
/// but associate them with a label just before the translated try block. That way
/// the enclosing construct will generate the code necessary to get control into the
/// try block for all of those states.
/// </summary>
public override BoundNode VisitTryStatement(BoundTryStatement node)
{
var oldDispatches = _dispatches;
var oldFinalizerState = _currentFinalizerState;
var oldHasFinalizerState = _hasFinalizerState;
_dispatches = null;
_currentFinalizerState = -1;
_hasFinalizerState = false;
BoundBlock tryBlock = F.Block((BoundStatement)this.Visit(node.TryBlock));
GeneratedLabelSymbol dispatchLabel = null;
if (_dispatches != null)
{
dispatchLabel = F.GenerateLabel("tryDispatch");
if (_hasFinalizerState)
{
// cause the current finalizer state to arrive here and then "return false"
var finalizer = F.GenerateLabel("finalizer");
_dispatches.Add(finalizer, new List<int>() { _currentFinalizerState });
var skipFinalizer = F.GenerateLabel("skipFinalizer");
tryBlock = F.Block(
F.HiddenSequencePoint(),
Dispatch(),
F.Goto(skipFinalizer),
F.Label(finalizer), // code for the finalizer here
GenerateSetBothStates(StateMachineStates.NotStartedStateMachine),
GenerateReturn(false),
F.Label(skipFinalizer),
tryBlock
);
}
else
{
tryBlock = F.Block(F.HiddenSequencePoint(), Dispatch(), tryBlock);
}
if (oldDispatches == null)
{
Debug.Assert(!oldHasFinalizerState);
oldDispatches = new Dictionary<LabelSymbol, List<int>>();
}
oldDispatches.Add(
dispatchLabel,
new List<int>(from kv in _dispatches.Values from n in kv orderby n select n)
);
}
_hasFinalizerState = oldHasFinalizerState;
_currentFinalizerState = oldFinalizerState;
_dispatches = oldDispatches;
ImmutableArray<BoundCatchBlock> catchBlocks = this.VisitList(node.CatchBlocks);
BoundBlock finallyBlockOpt =
node.FinallyBlockOpt == null
? null
: F.Block(
F.HiddenSequencePoint(),
F.If(
condition: ShouldEnterFinallyBlock(),
thenClause: VisitFinally(node.FinallyBlockOpt)
),
F.HiddenSequencePoint()
);
BoundStatement result = node.Update(
tryBlock,
catchBlocks,
finallyBlockOpt,
node.FinallyLabelOpt,
node.PreferFaultHandler
);
if ((object)dispatchLabel != null)
{
result = F.Block(F.HiddenSequencePoint(), F.Label(dispatchLabel), result);
}
return result;
}
protected virtual BoundBlock VisitFinally(BoundBlock finallyBlock)
{
return (BoundBlock)this.Visit(finallyBlock);
}
protected virtual BoundBinaryOperator ShouldEnterFinallyBlock()
{
return F.IntLessThan(
F.Local(cachedState),
F.Literal(StateMachineStates.FirstUnusedState)
);
}
/// <summary>
/// Set the state field and the cached state
/// </summary>
protected BoundExpressionStatement GenerateSetBothStates(int stateNumber)
{
// this.state = cachedState = stateNumber;
return F.Assignment(
F.Field(F.This(), stateField),
F.AssignmentExpression(F.Local(cachedState), F.Literal(stateNumber))
);
}
protected BoundStatement CacheThisIfNeeded()
{
// restore "this" cache, if there is a cache
if ((object)this.cachedThis != null)
{
CapturedSymbolReplacement proxy = proxies[this.OriginalMethod.ThisParameter];
var fetchThis = proxy.Replacement(F.Syntax, frameType => F.This());
return F.Assignment(F.Local(this.cachedThis), fetchThis);
}
// do nothing
return F.StatementList();
}
public sealed override BoundNode VisitThisReference(BoundThisReference node)
{
// if "this" is cached, return it.
if ((object)this.cachedThis != null)
{
return F.Local(this.cachedThis);
}
var thisParameter = this.OriginalMethod.ThisParameter;
CapturedSymbolReplacement proxy;
if ((object)thisParameter == null || !proxies.TryGetValue(thisParameter, out proxy))
{
// This can occur in a delegate creation expression because the method group
// in the argument can have a "this" receiver even when "this"
// is not captured because a static method is selected. But we do preserve
// the method group and its receiver in the bound tree, so the "this"
// receiver must be rewritten.
//TODO: It seems we may capture more than needed here.
// TODO: Why don't we drop "this" while lowering if method is static?
// Actually, considering that method group expression does not evaluate to a particular value
// why do we have it in the lowered tree at all?
return node.Update(VisitType(node.Type));
}
else
{
Debug.Assert(proxy != null);
return proxy.Replacement(F.Syntax, frameType => F.This());
}
}
public override BoundNode VisitBaseReference(BoundBaseReference node)
{
// TODO: fix up the type of the resulting node to be the base type
// if "this" is cached, return it.
if ((object)this.cachedThis != null)
{
return F.Local(this.cachedThis);
}
CapturedSymbolReplacement proxy = proxies[this.OriginalMethod.ThisParameter];
Debug.Assert(proxy != null);
return proxy.Replacement(F.Syntax, frameType => F.This());
}
#endregion
}
}
| 40.576857 | 138 | 0.533881 | [
"MIT"
] | belav/roslyn | src/Compilers/CSharp/Portable/Lowering/StateMachineRewriter/MethodToStateMachineRewriter.cs | 46,990 | C# |
namespace MassTransit.EntityFrameworkIntegration.Configurators
{
using System;
using MassTransit.Saga;
using Registration;
public class EntityFrameworkSagaRepositoryRegistrationProvider :
ISagaRepositoryRegistrationProvider
{
readonly Action<IEntityFrameworkSagaRepositoryConfigurator> _configure;
public EntityFrameworkSagaRepositoryRegistrationProvider(Action<IEntityFrameworkSagaRepositoryConfigurator> configure)
{
_configure = configure;
}
public virtual void Configure<TSaga>(ISagaRegistrationConfigurator<TSaga> configurator)
where TSaga : class, ISaga
{
configurator.EntityFrameworkRepository(r => _configure?.Invoke(r));
}
}
}
| 30.56 | 126 | 0.721204 | [
"ECL-2.0",
"Apache-2.0"
] | Aerodynamite/MassTrans | src/Persistence/MassTransit.EntityFrameworkIntegration/Configuration/Configurators/EntityFrameworkSagaRepositoryRegistrationProvider.cs | 764 | C# |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using CUP;
public class Textpause : ChronoBehaviour
{
public Text text;
protected override void ChronoStart()
{
// Non safe method!!! If you realy need this, better use "ChronoBehavior.OnPauseAction += changeText", becouse it safe. NEVER CLEAN IT. You can break Phys2d and Animator Pause on this GameObject
Chronos.Main.event_WorldOnPause += changeText;
text.text = "Stop";
}
private void OnDestroy()
{
// Non safe method!!! "ChronoBehavior.OnPauseAction -= changeText" you dont need to use it, becouse it safe
Chronos.Main.event_WorldOnPause -= changeText;
}
void changeText(bool isPlay)
{
text.text = isPlay ? "Stop" : "Play";
}
} | 29.5 | 202 | 0.680387 | [
"Apache-2.0"
] | dimeodd/UnityCUP | Assets/Exemlpars/OtherStuff/Textpause.cs | 828 | C# |
//------------------------------------------------------------------------------
// <auto-generated>
// Dieser Code wurde von einem Tool generiert.
// Laufzeitversion:4.0.30319.42000
//
// Änderungen an dieser Datei können falsches Verhalten verursachen und gehen verloren, wenn
// der Code erneut generiert wird.
// </auto-generated>
//------------------------------------------------------------------------------
#pragma warning disable 1591
namespace SessionTracker {
/// <summary>
///Represents a strongly typed in-memory cache of data.
///</summary>
[global::System.Serializable()]
[global::System.ComponentModel.DesignerCategoryAttribute("code")]
[global::System.ComponentModel.ToolboxItem(true)]
[global::System.Xml.Serialization.XmlSchemaProviderAttribute("GetTypedDataSetSchema")]
[global::System.Xml.Serialization.XmlRootAttribute("TracksQuery")]
[global::System.ComponentModel.Design.HelpKeywordAttribute("vs.data.DataSet")]
public partial class TracksQuery : global::System.Data.DataSet {
private tracksDataTable tabletracks;
private global::System.Data.SchemaSerializationMode _schemaSerializationMode = global::System.Data.SchemaSerializationMode.IncludeSchema;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "15.0.0.0")]
public TracksQuery() {
this.BeginInit();
this.InitClass();
global::System.ComponentModel.CollectionChangeEventHandler schemaChangedHandler = new global::System.ComponentModel.CollectionChangeEventHandler(this.SchemaChanged);
base.Tables.CollectionChanged += schemaChangedHandler;
base.Relations.CollectionChanged += schemaChangedHandler;
this.EndInit();
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "15.0.0.0")]
protected TracksQuery(global::System.Runtime.Serialization.SerializationInfo info, global::System.Runtime.Serialization.StreamingContext context) :
base(info, context, false) {
if ((this.IsBinarySerialized(info, context) == true)) {
this.InitVars(false);
global::System.ComponentModel.CollectionChangeEventHandler schemaChangedHandler1 = new global::System.ComponentModel.CollectionChangeEventHandler(this.SchemaChanged);
this.Tables.CollectionChanged += schemaChangedHandler1;
this.Relations.CollectionChanged += schemaChangedHandler1;
return;
}
string strSchema = ((string)(info.GetValue("XmlSchema", typeof(string))));
if ((this.DetermineSchemaSerializationMode(info, context) == global::System.Data.SchemaSerializationMode.IncludeSchema)) {
global::System.Data.DataSet ds = new global::System.Data.DataSet();
ds.ReadXmlSchema(new global::System.Xml.XmlTextReader(new global::System.IO.StringReader(strSchema)));
if ((ds.Tables["tracks"] != null)) {
base.Tables.Add(new tracksDataTable(ds.Tables["tracks"]));
}
this.DataSetName = ds.DataSetName;
this.Prefix = ds.Prefix;
this.Namespace = ds.Namespace;
this.Locale = ds.Locale;
this.CaseSensitive = ds.CaseSensitive;
this.EnforceConstraints = ds.EnforceConstraints;
this.Merge(ds, false, global::System.Data.MissingSchemaAction.Add);
this.InitVars();
}
else {
this.ReadXmlSchema(new global::System.Xml.XmlTextReader(new global::System.IO.StringReader(strSchema)));
}
this.GetSerializationData(info, context);
global::System.ComponentModel.CollectionChangeEventHandler schemaChangedHandler = new global::System.ComponentModel.CollectionChangeEventHandler(this.SchemaChanged);
base.Tables.CollectionChanged += schemaChangedHandler;
this.Relations.CollectionChanged += schemaChangedHandler;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "15.0.0.0")]
[global::System.ComponentModel.Browsable(false)]
[global::System.ComponentModel.DesignerSerializationVisibility(global::System.ComponentModel.DesignerSerializationVisibility.Content)]
public tracksDataTable tracks {
get {
return this.tabletracks;
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "15.0.0.0")]
[global::System.ComponentModel.BrowsableAttribute(true)]
[global::System.ComponentModel.DesignerSerializationVisibilityAttribute(global::System.ComponentModel.DesignerSerializationVisibility.Visible)]
public override global::System.Data.SchemaSerializationMode SchemaSerializationMode {
get {
return this._schemaSerializationMode;
}
set {
this._schemaSerializationMode = value;
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "15.0.0.0")]
[global::System.ComponentModel.DesignerSerializationVisibilityAttribute(global::System.ComponentModel.DesignerSerializationVisibility.Hidden)]
public new global::System.Data.DataTableCollection Tables {
get {
return base.Tables;
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "15.0.0.0")]
[global::System.ComponentModel.DesignerSerializationVisibilityAttribute(global::System.ComponentModel.DesignerSerializationVisibility.Hidden)]
public new global::System.Data.DataRelationCollection Relations {
get {
return base.Relations;
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "15.0.0.0")]
protected override void InitializeDerivedDataSet() {
this.BeginInit();
this.InitClass();
this.EndInit();
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "15.0.0.0")]
public override global::System.Data.DataSet Clone() {
TracksQuery cln = ((TracksQuery)(base.Clone()));
cln.InitVars();
cln.SchemaSerializationMode = this.SchemaSerializationMode;
return cln;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "15.0.0.0")]
protected override bool ShouldSerializeTables() {
return false;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "15.0.0.0")]
protected override bool ShouldSerializeRelations() {
return false;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "15.0.0.0")]
protected override void ReadXmlSerializable(global::System.Xml.XmlReader reader) {
if ((this.DetermineSchemaSerializationMode(reader) == global::System.Data.SchemaSerializationMode.IncludeSchema)) {
this.Reset();
global::System.Data.DataSet ds = new global::System.Data.DataSet();
ds.ReadXml(reader);
if ((ds.Tables["tracks"] != null)) {
base.Tables.Add(new tracksDataTable(ds.Tables["tracks"]));
}
this.DataSetName = ds.DataSetName;
this.Prefix = ds.Prefix;
this.Namespace = ds.Namespace;
this.Locale = ds.Locale;
this.CaseSensitive = ds.CaseSensitive;
this.EnforceConstraints = ds.EnforceConstraints;
this.Merge(ds, false, global::System.Data.MissingSchemaAction.Add);
this.InitVars();
}
else {
this.ReadXml(reader);
this.InitVars();
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "15.0.0.0")]
protected override global::System.Xml.Schema.XmlSchema GetSchemaSerializable() {
global::System.IO.MemoryStream stream = new global::System.IO.MemoryStream();
this.WriteXmlSchema(new global::System.Xml.XmlTextWriter(stream, null));
stream.Position = 0;
return global::System.Xml.Schema.XmlSchema.Read(new global::System.Xml.XmlTextReader(stream), null);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "15.0.0.0")]
internal void InitVars() {
this.InitVars(true);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "15.0.0.0")]
internal void InitVars(bool initTable) {
this.tabletracks = ((tracksDataTable)(base.Tables["tracks"]));
if ((initTable == true)) {
if ((this.tabletracks != null)) {
this.tabletracks.InitVars();
}
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "15.0.0.0")]
private void InitClass() {
this.DataSetName = "TracksQuery";
this.Prefix = "";
this.Namespace = "http://tempuri.org/TracksQuery.xsd";
this.EnforceConstraints = true;
this.SchemaSerializationMode = global::System.Data.SchemaSerializationMode.IncludeSchema;
this.tabletracks = new tracksDataTable();
base.Tables.Add(this.tabletracks);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "15.0.0.0")]
private bool ShouldSerializetracks() {
return false;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "15.0.0.0")]
private void SchemaChanged(object sender, global::System.ComponentModel.CollectionChangeEventArgs e) {
if ((e.Action == global::System.ComponentModel.CollectionChangeAction.Remove)) {
this.InitVars();
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "15.0.0.0")]
public static global::System.Xml.Schema.XmlSchemaComplexType GetTypedDataSetSchema(global::System.Xml.Schema.XmlSchemaSet xs) {
TracksQuery ds = new TracksQuery();
global::System.Xml.Schema.XmlSchemaComplexType type = new global::System.Xml.Schema.XmlSchemaComplexType();
global::System.Xml.Schema.XmlSchemaSequence sequence = new global::System.Xml.Schema.XmlSchemaSequence();
global::System.Xml.Schema.XmlSchemaAny any = new global::System.Xml.Schema.XmlSchemaAny();
any.Namespace = ds.Namespace;
sequence.Items.Add(any);
type.Particle = sequence;
global::System.Xml.Schema.XmlSchema dsSchema = ds.GetSchemaSerializable();
if (xs.Contains(dsSchema.TargetNamespace)) {
global::System.IO.MemoryStream s1 = new global::System.IO.MemoryStream();
global::System.IO.MemoryStream s2 = new global::System.IO.MemoryStream();
try {
global::System.Xml.Schema.XmlSchema schema = null;
dsSchema.Write(s1);
for (global::System.Collections.IEnumerator schemas = xs.Schemas(dsSchema.TargetNamespace).GetEnumerator(); schemas.MoveNext(); ) {
schema = ((global::System.Xml.Schema.XmlSchema)(schemas.Current));
s2.SetLength(0);
schema.Write(s2);
if ((s1.Length == s2.Length)) {
s1.Position = 0;
s2.Position = 0;
for (; ((s1.Position != s1.Length)
&& (s1.ReadByte() == s2.ReadByte())); ) {
;
}
if ((s1.Position == s1.Length)) {
return type;
}
}
}
}
finally {
if ((s1 != null)) {
s1.Close();
}
if ((s2 != null)) {
s2.Close();
}
}
}
xs.Add(dsSchema);
return type;
}
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "15.0.0.0")]
public delegate void tracksRowChangeEventHandler(object sender, tracksRowChangeEvent e);
/// <summary>
///Represents the strongly named DataTable class.
///</summary>
[global::System.Serializable()]
[global::System.Xml.Serialization.XmlSchemaProviderAttribute("GetTypedTableSchema")]
public partial class tracksDataTable : global::System.Data.TypedTableBase<tracksRow> {
private global::System.Data.DataColumn columnstart;
private global::System.Data.DataColumn columnend;
private global::System.Data.DataColumn columndescription;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "15.0.0.0")]
public tracksDataTable() {
this.TableName = "tracks";
this.BeginInit();
this.InitClass();
this.EndInit();
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "15.0.0.0")]
internal tracksDataTable(global::System.Data.DataTable table) {
this.TableName = table.TableName;
if ((table.CaseSensitive != table.DataSet.CaseSensitive)) {
this.CaseSensitive = table.CaseSensitive;
}
if ((table.Locale.ToString() != table.DataSet.Locale.ToString())) {
this.Locale = table.Locale;
}
if ((table.Namespace != table.DataSet.Namespace)) {
this.Namespace = table.Namespace;
}
this.Prefix = table.Prefix;
this.MinimumCapacity = table.MinimumCapacity;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "15.0.0.0")]
protected tracksDataTable(global::System.Runtime.Serialization.SerializationInfo info, global::System.Runtime.Serialization.StreamingContext context) :
base(info, context) {
this.InitVars();
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "15.0.0.0")]
public global::System.Data.DataColumn startColumn {
get {
return this.columnstart;
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "15.0.0.0")]
public global::System.Data.DataColumn endColumn {
get {
return this.columnend;
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "15.0.0.0")]
public global::System.Data.DataColumn descriptionColumn {
get {
return this.columndescription;
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "15.0.0.0")]
[global::System.ComponentModel.Browsable(false)]
public int Count {
get {
return this.Rows.Count;
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "15.0.0.0")]
public tracksRow this[int index] {
get {
return ((tracksRow)(this.Rows[index]));
}
}
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "15.0.0.0")]
public event tracksRowChangeEventHandler tracksRowChanging;
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "15.0.0.0")]
public event tracksRowChangeEventHandler tracksRowChanged;
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "15.0.0.0")]
public event tracksRowChangeEventHandler tracksRowDeleting;
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "15.0.0.0")]
public event tracksRowChangeEventHandler tracksRowDeleted;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "15.0.0.0")]
public void AddtracksRow(tracksRow row) {
this.Rows.Add(row);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "15.0.0.0")]
public tracksRow AddtracksRow(System.DateTime start, System.DateTime end, string description) {
tracksRow rowtracksRow = ((tracksRow)(this.NewRow()));
object[] columnValuesArray = new object[] {
start,
end,
description};
rowtracksRow.ItemArray = columnValuesArray;
this.Rows.Add(rowtracksRow);
return rowtracksRow;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "15.0.0.0")]
public override global::System.Data.DataTable Clone() {
tracksDataTable cln = ((tracksDataTable)(base.Clone()));
cln.InitVars();
return cln;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "15.0.0.0")]
protected override global::System.Data.DataTable CreateInstance() {
return new tracksDataTable();
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "15.0.0.0")]
internal void InitVars() {
this.columnstart = base.Columns["start"];
this.columnend = base.Columns["end"];
this.columndescription = base.Columns["description"];
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "15.0.0.0")]
private void InitClass() {
this.columnstart = new global::System.Data.DataColumn("start", typeof(global::System.DateTime), null, global::System.Data.MappingType.Element);
base.Columns.Add(this.columnstart);
this.columnend = new global::System.Data.DataColumn("end", typeof(global::System.DateTime), null, global::System.Data.MappingType.Element);
base.Columns.Add(this.columnend);
this.columndescription = new global::System.Data.DataColumn("description", typeof(string), null, global::System.Data.MappingType.Element);
base.Columns.Add(this.columndescription);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "15.0.0.0")]
public tracksRow NewtracksRow() {
return ((tracksRow)(this.NewRow()));
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "15.0.0.0")]
protected override global::System.Data.DataRow NewRowFromBuilder(global::System.Data.DataRowBuilder builder) {
return new tracksRow(builder);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "15.0.0.0")]
protected override global::System.Type GetRowType() {
return typeof(tracksRow);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "15.0.0.0")]
protected override void OnRowChanged(global::System.Data.DataRowChangeEventArgs e) {
base.OnRowChanged(e);
if ((this.tracksRowChanged != null)) {
this.tracksRowChanged(this, new tracksRowChangeEvent(((tracksRow)(e.Row)), e.Action));
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "15.0.0.0")]
protected override void OnRowChanging(global::System.Data.DataRowChangeEventArgs e) {
base.OnRowChanging(e);
if ((this.tracksRowChanging != null)) {
this.tracksRowChanging(this, new tracksRowChangeEvent(((tracksRow)(e.Row)), e.Action));
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "15.0.0.0")]
protected override void OnRowDeleted(global::System.Data.DataRowChangeEventArgs e) {
base.OnRowDeleted(e);
if ((this.tracksRowDeleted != null)) {
this.tracksRowDeleted(this, new tracksRowChangeEvent(((tracksRow)(e.Row)), e.Action));
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "15.0.0.0")]
protected override void OnRowDeleting(global::System.Data.DataRowChangeEventArgs e) {
base.OnRowDeleting(e);
if ((this.tracksRowDeleting != null)) {
this.tracksRowDeleting(this, new tracksRowChangeEvent(((tracksRow)(e.Row)), e.Action));
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "15.0.0.0")]
public void RemovetracksRow(tracksRow row) {
this.Rows.Remove(row);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "15.0.0.0")]
public static global::System.Xml.Schema.XmlSchemaComplexType GetTypedTableSchema(global::System.Xml.Schema.XmlSchemaSet xs) {
global::System.Xml.Schema.XmlSchemaComplexType type = new global::System.Xml.Schema.XmlSchemaComplexType();
global::System.Xml.Schema.XmlSchemaSequence sequence = new global::System.Xml.Schema.XmlSchemaSequence();
TracksQuery ds = new TracksQuery();
global::System.Xml.Schema.XmlSchemaAny any1 = new global::System.Xml.Schema.XmlSchemaAny();
any1.Namespace = "http://www.w3.org/2001/XMLSchema";
any1.MinOccurs = new decimal(0);
any1.MaxOccurs = decimal.MaxValue;
any1.ProcessContents = global::System.Xml.Schema.XmlSchemaContentProcessing.Lax;
sequence.Items.Add(any1);
global::System.Xml.Schema.XmlSchemaAny any2 = new global::System.Xml.Schema.XmlSchemaAny();
any2.Namespace = "urn:schemas-microsoft-com:xml-diffgram-v1";
any2.MinOccurs = new decimal(1);
any2.ProcessContents = global::System.Xml.Schema.XmlSchemaContentProcessing.Lax;
sequence.Items.Add(any2);
global::System.Xml.Schema.XmlSchemaAttribute attribute1 = new global::System.Xml.Schema.XmlSchemaAttribute();
attribute1.Name = "namespace";
attribute1.FixedValue = ds.Namespace;
type.Attributes.Add(attribute1);
global::System.Xml.Schema.XmlSchemaAttribute attribute2 = new global::System.Xml.Schema.XmlSchemaAttribute();
attribute2.Name = "tableTypeName";
attribute2.FixedValue = "tracksDataTable";
type.Attributes.Add(attribute2);
type.Particle = sequence;
global::System.Xml.Schema.XmlSchema dsSchema = ds.GetSchemaSerializable();
if (xs.Contains(dsSchema.TargetNamespace)) {
global::System.IO.MemoryStream s1 = new global::System.IO.MemoryStream();
global::System.IO.MemoryStream s2 = new global::System.IO.MemoryStream();
try {
global::System.Xml.Schema.XmlSchema schema = null;
dsSchema.Write(s1);
for (global::System.Collections.IEnumerator schemas = xs.Schemas(dsSchema.TargetNamespace).GetEnumerator(); schemas.MoveNext(); ) {
schema = ((global::System.Xml.Schema.XmlSchema)(schemas.Current));
s2.SetLength(0);
schema.Write(s2);
if ((s1.Length == s2.Length)) {
s1.Position = 0;
s2.Position = 0;
for (; ((s1.Position != s1.Length)
&& (s1.ReadByte() == s2.ReadByte())); ) {
;
}
if ((s1.Position == s1.Length)) {
return type;
}
}
}
}
finally {
if ((s1 != null)) {
s1.Close();
}
if ((s2 != null)) {
s2.Close();
}
}
}
xs.Add(dsSchema);
return type;
}
}
/// <summary>
///Represents strongly named DataRow class.
///</summary>
public partial class tracksRow : global::System.Data.DataRow {
private tracksDataTable tabletracks;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "15.0.0.0")]
internal tracksRow(global::System.Data.DataRowBuilder rb) :
base(rb) {
this.tabletracks = ((tracksDataTable)(this.Table));
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "15.0.0.0")]
public System.DateTime start {
get {
try {
return ((global::System.DateTime)(this[this.tabletracks.startColumn]));
}
catch (global::System.InvalidCastException e) {
throw new global::System.Data.StrongTypingException("Der Wert für Spalte start in Tabelle tracks ist DBNull.", e);
}
}
set {
this[this.tabletracks.startColumn] = value;
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "15.0.0.0")]
public System.DateTime end {
get {
try {
return ((global::System.DateTime)(this[this.tabletracks.endColumn]));
}
catch (global::System.InvalidCastException e) {
throw new global::System.Data.StrongTypingException("Der Wert für Spalte end in Tabelle tracks ist DBNull.", e);
}
}
set {
this[this.tabletracks.endColumn] = value;
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "15.0.0.0")]
public string description {
get {
try {
return ((string)(this[this.tabletracks.descriptionColumn]));
}
catch (global::System.InvalidCastException e) {
throw new global::System.Data.StrongTypingException("Der Wert für Spalte description in Tabelle tracks ist DBNull.", e);
}
}
set {
this[this.tabletracks.descriptionColumn] = value;
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "15.0.0.0")]
public bool IsstartNull() {
return this.IsNull(this.tabletracks.startColumn);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "15.0.0.0")]
public void SetstartNull() {
this[this.tabletracks.startColumn] = global::System.Convert.DBNull;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "15.0.0.0")]
public bool IsendNull() {
return this.IsNull(this.tabletracks.endColumn);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "15.0.0.0")]
public void SetendNull() {
this[this.tabletracks.endColumn] = global::System.Convert.DBNull;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "15.0.0.0")]
public bool IsdescriptionNull() {
return this.IsNull(this.tabletracks.descriptionColumn);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "15.0.0.0")]
public void SetdescriptionNull() {
this[this.tabletracks.descriptionColumn] = global::System.Convert.DBNull;
}
}
/// <summary>
///Row event argument class
///</summary>
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "15.0.0.0")]
public class tracksRowChangeEvent : global::System.EventArgs {
private tracksRow eventRow;
private global::System.Data.DataRowAction eventAction;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "15.0.0.0")]
public tracksRowChangeEvent(tracksRow row, global::System.Data.DataRowAction action) {
this.eventRow = row;
this.eventAction = action;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "15.0.0.0")]
public tracksRow Row {
get {
return this.eventRow;
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "15.0.0.0")]
public global::System.Data.DataRowAction Action {
get {
return this.eventAction;
}
}
}
}
}
namespace SessionTracker.TracksQueryTableAdapters {
/// <summary>
///Represents the connection and commands used to retrieve and save data.
///</summary>
[global::System.ComponentModel.DesignerCategoryAttribute("code")]
[global::System.ComponentModel.ToolboxItem(true)]
[global::System.ComponentModel.DataObjectAttribute(true)]
[global::System.ComponentModel.DesignerAttribute("Microsoft.VSDesigner.DataSource.Design.TableAdapterDesigner, Microsoft.VSDesigner" +
", Version=10.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a")]
[global::System.ComponentModel.Design.HelpKeywordAttribute("vs.data.TableAdapter")]
public partial class tracksTableAdapter : global::System.ComponentModel.Component {
private global::Devart.Data.SQLite.SQLiteDataAdapter _adapter;
private global::Devart.Data.SQLite.SQLiteConnection _connection;
private global::System.Data.Common.DbTransaction _transaction;
private global::Devart.Data.SQLite.SQLiteCommand[] _commandCollection;
private bool _clearBeforeFill;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "15.0.0.0")]
public tracksTableAdapter() {
this.ClearBeforeFill = true;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "15.0.0.0")]
protected internal global::Devart.Data.SQLite.SQLiteDataAdapter Adapter {
get {
if ((this._adapter == null)) {
this.InitAdapter();
}
return this._adapter;
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "15.0.0.0")]
internal global::Devart.Data.SQLite.SQLiteConnection Connection {
get {
if ((this._connection == null)) {
this.InitConnection();
}
return this._connection;
}
set {
this._connection = value;
if ((this.Adapter.InsertCommand != null)) {
this.Adapter.InsertCommand.Connection = value;
}
if ((this.Adapter.DeleteCommand != null)) {
this.Adapter.DeleteCommand.Connection = value;
}
if ((this.Adapter.UpdateCommand != null)) {
this.Adapter.UpdateCommand.Connection = value;
}
for (int i = 0; (i < this.CommandCollection.Length); i = (i + 1)) {
if ((this.CommandCollection[i] != null)) {
((global::Devart.Data.SQLite.SQLiteCommand)(this.CommandCollection[i])).Connection = value;
}
}
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "15.0.0.0")]
internal global::System.Data.Common.DbTransaction Transaction {
get {
return this._transaction;
}
set {
this._transaction = value;
for (int i = 0; (i < this.CommandCollection.Length); i = (i + 1)) {
this.CommandCollection[i].Transaction = this._transaction;
}
if (((this.Adapter != null)
&& (this.Adapter.DeleteCommand != null))) {
this.Adapter.DeleteCommand.Transaction = this._transaction;
}
if (((this.Adapter != null)
&& (this.Adapter.InsertCommand != null))) {
this.Adapter.InsertCommand.Transaction = this._transaction;
}
if (((this.Adapter != null)
&& (this.Adapter.UpdateCommand != null))) {
this.Adapter.UpdateCommand.Transaction = this._transaction;
}
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "15.0.0.0")]
protected global::Devart.Data.SQLite.SQLiteCommand[] CommandCollection {
get {
if ((this._commandCollection == null)) {
this.InitCommandCollection();
}
return this._commandCollection;
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "15.0.0.0")]
public bool ClearBeforeFill {
get {
return this._clearBeforeFill;
}
set {
this._clearBeforeFill = value;
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "15.0.0.0")]
private void InitAdapter() {
this._adapter = new global::Devart.Data.SQLite.SQLiteDataAdapter();
global::System.Data.Common.DataTableMapping tableMapping = new global::System.Data.Common.DataTableMapping();
tableMapping.SourceTable = "Table";
tableMapping.DataSetTable = "tracks";
tableMapping.ColumnMappings.Add("start", "start");
tableMapping.ColumnMappings.Add("end", "end");
tableMapping.ColumnMappings.Add("description", "description");
this._adapter.TableMappings.Add(tableMapping);
this._adapter.InsertCommand = new global::Devart.Data.SQLite.SQLiteCommand();
this._adapter.InsertCommand.Connection = this.Connection;
this._adapter.InsertCommand.CommandText = "INSERT INTO \"main\".\"tracks\" (\"start\", \"end\", \"description\") VALUES (:start, :end," +
" :description)";
this._adapter.InsertCommand.CommandType = global::System.Data.CommandType.Text;
global::Devart.Data.SQLite.SQLiteParameter param = new global::Devart.Data.SQLite.SQLiteParameter();
param.ParameterName = "start";
param.DbType = global::System.Data.DbType.DateTime;
param.SQLiteType = global::Devart.Data.SQLite.SQLiteType.DateTime;
param.IsNullable = true;
param.SourceColumn = "start";
this._adapter.InsertCommand.Parameters.Add(param);
param = new global::Devart.Data.SQLite.SQLiteParameter();
param.ParameterName = "end";
param.DbType = global::System.Data.DbType.DateTime;
param.SQLiteType = global::Devart.Data.SQLite.SQLiteType.DateTime;
param.IsNullable = true;
param.SourceColumn = "end";
this._adapter.InsertCommand.Parameters.Add(param);
param = new global::Devart.Data.SQLite.SQLiteParameter();
param.ParameterName = "description";
param.SQLiteType = global::Devart.Data.SQLite.SQLiteType.Text;
param.IsNullable = true;
param.SourceColumn = "description";
this._adapter.InsertCommand.Parameters.Add(param);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "15.0.0.0")]
private void InitConnection() {
this._connection = new global::Devart.Data.SQLite.SQLiteConnection();
this._connection.ConnectionString = global::SessionTracker.Properties.Settings.Default.ConnectionString1;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "15.0.0.0")]
private void InitCommandCollection() {
this._commandCollection = new global::Devart.Data.SQLite.SQLiteCommand[1];
this._commandCollection[0] = new global::Devart.Data.SQLite.SQLiteCommand();
this._commandCollection[0].Connection = this.Connection;
this._commandCollection[0].CommandText = "SELECT start, \"end\", description FROM \"main\".tracks";
this._commandCollection[0].CommandType = global::System.Data.CommandType.Text;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "15.0.0.0")]
[global::System.ComponentModel.Design.HelpKeywordAttribute("vs.data.TableAdapter")]
[global::System.ComponentModel.DataObjectMethodAttribute(global::System.ComponentModel.DataObjectMethodType.Fill, true)]
public virtual int Fill(TracksQuery.tracksDataTable dataTable) {
this.Adapter.SelectCommand = this.CommandCollection[0];
if ((this.ClearBeforeFill == true)) {
dataTable.Clear();
}
int returnValue = this.Adapter.Fill(dataTable);
return returnValue;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "15.0.0.0")]
[global::System.ComponentModel.Design.HelpKeywordAttribute("vs.data.TableAdapter")]
[global::System.ComponentModel.DataObjectMethodAttribute(global::System.ComponentModel.DataObjectMethodType.Select, true)]
public virtual TracksQuery.tracksDataTable GetData() {
this.Adapter.SelectCommand = this.CommandCollection[0];
TracksQuery.tracksDataTable dataTable = new TracksQuery.tracksDataTable();
this.Adapter.Fill(dataTable);
return dataTable;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "15.0.0.0")]
[global::System.ComponentModel.Design.HelpKeywordAttribute("vs.data.TableAdapter")]
public virtual int Update(TracksQuery.tracksDataTable dataTable) {
return this.Adapter.Update(dataTable);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "15.0.0.0")]
[global::System.ComponentModel.Design.HelpKeywordAttribute("vs.data.TableAdapter")]
public virtual int Update(TracksQuery dataSet) {
return this.Adapter.Update(dataSet, "tracks");
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "15.0.0.0")]
[global::System.ComponentModel.Design.HelpKeywordAttribute("vs.data.TableAdapter")]
public virtual int Update(global::System.Data.DataRow dataRow) {
return this.Adapter.Update(new global::System.Data.DataRow[] {
dataRow});
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "15.0.0.0")]
[global::System.ComponentModel.Design.HelpKeywordAttribute("vs.data.TableAdapter")]
public virtual int Update(global::System.Data.DataRow[] dataRows) {
return this.Adapter.Update(dataRows);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "15.0.0.0")]
[global::System.ComponentModel.Design.HelpKeywordAttribute("vs.data.TableAdapter")]
[global::System.ComponentModel.DataObjectMethodAttribute(global::System.ComponentModel.DataObjectMethodType.Insert, true)]
public virtual int Insert(global::System.Nullable<global::System.DateTime> start, global::System.Nullable<global::System.DateTime> end, string description) {
if ((start.HasValue == true)) {
this.Adapter.InsertCommand.Parameters[0].Value = ((System.DateTime)(start.Value));
}
else {
this.Adapter.InsertCommand.Parameters[0].Value = global::System.DBNull.Value;
}
if ((end.HasValue == true)) {
this.Adapter.InsertCommand.Parameters[1].Value = ((System.DateTime)(end.Value));
}
else {
this.Adapter.InsertCommand.Parameters[1].Value = global::System.DBNull.Value;
}
if ((description == null)) {
this.Adapter.InsertCommand.Parameters[2].Value = global::System.DBNull.Value;
}
else {
this.Adapter.InsertCommand.Parameters[2].Value = ((string)(description));
}
global::System.Data.ConnectionState previousConnectionState = this.Adapter.InsertCommand.Connection.State;
if (((this.Adapter.InsertCommand.Connection.State & global::System.Data.ConnectionState.Open)
!= global::System.Data.ConnectionState.Open)) {
this.Adapter.InsertCommand.Connection.Open();
}
try {
int returnValue = this.Adapter.InsertCommand.ExecuteNonQuery();
return returnValue;
}
finally {
if ((previousConnectionState == global::System.Data.ConnectionState.Closed)) {
this.Adapter.InsertCommand.Connection.Close();
}
}
}
}
/// <summary>
///TableAdapterManager is used to coordinate TableAdapters in the dataset to enable Hierarchical Update scenarios
///</summary>
[global::System.ComponentModel.DesignerCategoryAttribute("code")]
[global::System.ComponentModel.ToolboxItem(true)]
[global::System.ComponentModel.DesignerAttribute("Microsoft.VSDesigner.DataSource.Design.TableAdapterManagerDesigner, Microsoft.VSD" +
"esigner, Version=10.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a")]
[global::System.ComponentModel.Design.HelpKeywordAttribute("vs.data.TableAdapterManager")]
public partial class TableAdapterManager : global::System.ComponentModel.Component {
private UpdateOrderOption _updateOrder;
private tracksTableAdapter _tracksTableAdapter;
private bool _backupDataSetBeforeUpdate;
private global::System.Data.IDbConnection _connection;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "15.0.0.0")]
public UpdateOrderOption UpdateOrder {
get {
return this._updateOrder;
}
set {
this._updateOrder = value;
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "15.0.0.0")]
[global::System.ComponentModel.EditorAttribute("Microsoft.VSDesigner.DataSource.Design.TableAdapterManagerPropertyEditor, Microso" +
"ft.VSDesigner, Version=10.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3" +
"a", "System.Drawing.Design.UITypeEditor")]
public tracksTableAdapter tracksTableAdapter {
get {
return this._tracksTableAdapter;
}
set {
this._tracksTableAdapter = value;
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "15.0.0.0")]
public bool BackupDataSetBeforeUpdate {
get {
return this._backupDataSetBeforeUpdate;
}
set {
this._backupDataSetBeforeUpdate = value;
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "15.0.0.0")]
[global::System.ComponentModel.Browsable(false)]
public global::System.Data.IDbConnection Connection {
get {
if ((this._connection != null)) {
return this._connection;
}
if (((this._tracksTableAdapter != null)
&& (this._tracksTableAdapter.Connection != null))) {
return this._tracksTableAdapter.Connection;
}
return null;
}
set {
this._connection = value;
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "15.0.0.0")]
[global::System.ComponentModel.Browsable(false)]
public int TableAdapterInstanceCount {
get {
int count = 0;
if ((this._tracksTableAdapter != null)) {
count = (count + 1);
}
return count;
}
}
/// <summary>
///Update rows in top-down order.
///</summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "15.0.0.0")]
private int UpdateUpdatedRows(TracksQuery dataSet, global::System.Collections.Generic.List<global::System.Data.DataRow> allChangedRows, global::System.Collections.Generic.List<global::System.Data.DataRow> allAddedRows) {
int result = 0;
if ((this._tracksTableAdapter != null)) {
global::System.Data.DataRow[] updatedRows = dataSet.tracks.Select(null, null, global::System.Data.DataViewRowState.ModifiedCurrent);
updatedRows = this.GetRealUpdatedRows(updatedRows, allAddedRows);
if (((updatedRows != null)
&& (0 < updatedRows.Length))) {
result = (result + this._tracksTableAdapter.Update(updatedRows));
allChangedRows.AddRange(updatedRows);
}
}
return result;
}
/// <summary>
///Insert rows in top-down order.
///</summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "15.0.0.0")]
private int UpdateInsertedRows(TracksQuery dataSet, global::System.Collections.Generic.List<global::System.Data.DataRow> allAddedRows) {
int result = 0;
if ((this._tracksTableAdapter != null)) {
global::System.Data.DataRow[] addedRows = dataSet.tracks.Select(null, null, global::System.Data.DataViewRowState.Added);
if (((addedRows != null)
&& (0 < addedRows.Length))) {
result = (result + this._tracksTableAdapter.Update(addedRows));
allAddedRows.AddRange(addedRows);
}
}
return result;
}
/// <summary>
///Delete rows in bottom-up order.
///</summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "15.0.0.0")]
private int UpdateDeletedRows(TracksQuery dataSet, global::System.Collections.Generic.List<global::System.Data.DataRow> allChangedRows) {
int result = 0;
if ((this._tracksTableAdapter != null)) {
global::System.Data.DataRow[] deletedRows = dataSet.tracks.Select(null, null, global::System.Data.DataViewRowState.Deleted);
if (((deletedRows != null)
&& (0 < deletedRows.Length))) {
result = (result + this._tracksTableAdapter.Update(deletedRows));
allChangedRows.AddRange(deletedRows);
}
}
return result;
}
/// <summary>
///Remove inserted rows that become updated rows after calling TableAdapter.Update(inserted rows) first
///</summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "15.0.0.0")]
private global::System.Data.DataRow[] GetRealUpdatedRows(global::System.Data.DataRow[] updatedRows, global::System.Collections.Generic.List<global::System.Data.DataRow> allAddedRows) {
if (((updatedRows == null)
|| (updatedRows.Length < 1))) {
return updatedRows;
}
if (((allAddedRows == null)
|| (allAddedRows.Count < 1))) {
return updatedRows;
}
global::System.Collections.Generic.List<global::System.Data.DataRow> realUpdatedRows = new global::System.Collections.Generic.List<global::System.Data.DataRow>();
for (int i = 0; (i < updatedRows.Length); i = (i + 1)) {
global::System.Data.DataRow row = updatedRows[i];
if ((allAddedRows.Contains(row) == false)) {
realUpdatedRows.Add(row);
}
}
return realUpdatedRows.ToArray();
}
/// <summary>
///Update all changes to the dataset.
///</summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "15.0.0.0")]
public virtual int UpdateAll(TracksQuery dataSet) {
if ((dataSet == null)) {
throw new global::System.ArgumentNullException("dataSet");
}
if ((dataSet.HasChanges() == false)) {
return 0;
}
if (((this._tracksTableAdapter != null)
&& (this.MatchTableAdapterConnection(this._tracksTableAdapter.Connection) == false))) {
throw new global::System.ArgumentException("Für alle von einem TableAdapterManager verwalteten Instanzen von TableAdapter mus" +
"s die gleiche Verbindungszeichenfolge verwendet werden.");
}
global::System.Data.IDbConnection workConnection = this.Connection;
if ((workConnection == null)) {
throw new global::System.ApplicationException("TableAdapterManager enthält keine Verbindungsinformationen. Legen Sie jede TableA" +
"dapterManager TableAdapter-Eigenschaft auf eine gültige TableAdapter-Instanz fes" +
"t.");
}
bool workConnOpened = false;
if (((workConnection.State & global::System.Data.ConnectionState.Broken)
== global::System.Data.ConnectionState.Broken)) {
workConnection.Close();
}
if ((workConnection.State == global::System.Data.ConnectionState.Closed)) {
workConnection.Open();
workConnOpened = true;
}
global::System.Data.IDbTransaction workTransaction = workConnection.BeginTransaction();
if ((workTransaction == null)) {
throw new global::System.ApplicationException("Die Transaktion kann nicht gestartet werden. Die aktuelle Datenverbindung unterst" +
"ützt keine Transaktionen, oder der aktuelle Zustand lässt den Start der Transakt" +
"ion nicht zu.");
}
global::System.Collections.Generic.List<global::System.Data.DataRow> allChangedRows = new global::System.Collections.Generic.List<global::System.Data.DataRow>();
global::System.Collections.Generic.List<global::System.Data.DataRow> allAddedRows = new global::System.Collections.Generic.List<global::System.Data.DataRow>();
global::System.Collections.Generic.List<global::System.Data.Common.DataAdapter> adaptersWithAcceptChangesDuringUpdate = new global::System.Collections.Generic.List<global::System.Data.Common.DataAdapter>();
global::System.Collections.Generic.Dictionary<object, global::System.Data.IDbConnection> revertConnections = new global::System.Collections.Generic.Dictionary<object, global::System.Data.IDbConnection>();
int result = 0;
global::System.Data.DataSet backupDataSet = null;
if (this.BackupDataSetBeforeUpdate) {
backupDataSet = new global::System.Data.DataSet();
backupDataSet.Merge(dataSet);
}
try {
// ---- Prepare for update -----------
//
if ((this._tracksTableAdapter != null)) {
revertConnections.Add(this._tracksTableAdapter, this._tracksTableAdapter.Connection);
this._tracksTableAdapter.Connection = ((global::Devart.Data.SQLite.SQLiteConnection)(workConnection));
this._tracksTableAdapter.Transaction = ((global::System.Data.Common.DbTransaction)(workTransaction));
if (this._tracksTableAdapter.Adapter.AcceptChangesDuringUpdate) {
this._tracksTableAdapter.Adapter.AcceptChangesDuringUpdate = false;
adaptersWithAcceptChangesDuringUpdate.Add(this._tracksTableAdapter.Adapter);
}
}
//
//---- Perform updates -----------
//
if ((this.UpdateOrder == UpdateOrderOption.UpdateInsertDelete)) {
result = (result + this.UpdateUpdatedRows(dataSet, allChangedRows, allAddedRows));
result = (result + this.UpdateInsertedRows(dataSet, allAddedRows));
}
else {
result = (result + this.UpdateInsertedRows(dataSet, allAddedRows));
result = (result + this.UpdateUpdatedRows(dataSet, allChangedRows, allAddedRows));
}
result = (result + this.UpdateDeletedRows(dataSet, allChangedRows));
//
//---- Commit updates -----------
//
workTransaction.Commit();
if ((0 < allAddedRows.Count)) {
global::System.Data.DataRow[] rows = new System.Data.DataRow[allAddedRows.Count];
allAddedRows.CopyTo(rows);
for (int i = 0; (i < rows.Length); i = (i + 1)) {
global::System.Data.DataRow row = rows[i];
row.AcceptChanges();
}
}
if ((0 < allChangedRows.Count)) {
global::System.Data.DataRow[] rows = new System.Data.DataRow[allChangedRows.Count];
allChangedRows.CopyTo(rows);
for (int i = 0; (i < rows.Length); i = (i + 1)) {
global::System.Data.DataRow row = rows[i];
row.AcceptChanges();
}
}
}
catch (global::System.Exception ex) {
workTransaction.Rollback();
// ---- Restore the dataset -----------
if (this.BackupDataSetBeforeUpdate) {
global::System.Diagnostics.Debug.Assert((backupDataSet != null));
dataSet.Clear();
dataSet.Merge(backupDataSet);
}
else {
if ((0 < allAddedRows.Count)) {
global::System.Data.DataRow[] rows = new System.Data.DataRow[allAddedRows.Count];
allAddedRows.CopyTo(rows);
for (int i = 0; (i < rows.Length); i = (i + 1)) {
global::System.Data.DataRow row = rows[i];
row.AcceptChanges();
row.SetAdded();
}
}
}
throw ex;
}
finally {
if (workConnOpened) {
workConnection.Close();
}
if ((this._tracksTableAdapter != null)) {
this._tracksTableAdapter.Connection = ((global::Devart.Data.SQLite.SQLiteConnection)(revertConnections[this._tracksTableAdapter]));
this._tracksTableAdapter.Transaction = null;
}
if ((0 < adaptersWithAcceptChangesDuringUpdate.Count)) {
global::System.Data.Common.DataAdapter[] adapters = new System.Data.Common.DataAdapter[adaptersWithAcceptChangesDuringUpdate.Count];
adaptersWithAcceptChangesDuringUpdate.CopyTo(adapters);
for (int i = 0; (i < adapters.Length); i = (i + 1)) {
global::System.Data.Common.DataAdapter adapter = adapters[i];
adapter.AcceptChangesDuringUpdate = true;
}
}
}
return result;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "15.0.0.0")]
protected virtual void SortSelfReferenceRows(global::System.Data.DataRow[] rows, global::System.Data.DataRelation relation, bool childFirst) {
global::System.Array.Sort<global::System.Data.DataRow>(rows, new SelfReferenceComparer(relation, childFirst));
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "15.0.0.0")]
protected virtual bool MatchTableAdapterConnection(global::System.Data.IDbConnection inputConnection) {
if ((this._connection != null)) {
return true;
}
if (((this.Connection == null)
|| (inputConnection == null))) {
return true;
}
if (string.Equals(this.Connection.ConnectionString, inputConnection.ConnectionString, global::System.StringComparison.Ordinal)) {
return true;
}
return false;
}
/// <summary>
///Update Order Option
///</summary>
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "15.0.0.0")]
public enum UpdateOrderOption {
InsertUpdateDelete = 0,
UpdateInsertDelete = 1,
}
/// <summary>
///Used to sort self-referenced table's rows
///</summary>
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "15.0.0.0")]
private class SelfReferenceComparer : object, global::System.Collections.Generic.IComparer<global::System.Data.DataRow> {
private global::System.Data.DataRelation _relation;
private int _childFirst;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "15.0.0.0")]
internal SelfReferenceComparer(global::System.Data.DataRelation relation, bool childFirst) {
this._relation = relation;
if (childFirst) {
this._childFirst = -1;
}
else {
this._childFirst = 1;
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "15.0.0.0")]
private global::System.Data.DataRow GetRoot(global::System.Data.DataRow row, out int distance) {
global::System.Diagnostics.Debug.Assert((row != null));
global::System.Data.DataRow root = row;
distance = 0;
global::System.Collections.Generic.IDictionary<global::System.Data.DataRow, global::System.Data.DataRow> traversedRows = new global::System.Collections.Generic.Dictionary<global::System.Data.DataRow, global::System.Data.DataRow>();
traversedRows[row] = row;
global::System.Data.DataRow parent = row.GetParentRow(this._relation, global::System.Data.DataRowVersion.Default);
for (
; ((parent != null)
&& (traversedRows.ContainsKey(parent) == false));
) {
distance = (distance + 1);
root = parent;
traversedRows[parent] = parent;
parent = parent.GetParentRow(this._relation, global::System.Data.DataRowVersion.Default);
}
if ((distance == 0)) {
traversedRows.Clear();
traversedRows[row] = row;
parent = row.GetParentRow(this._relation, global::System.Data.DataRowVersion.Original);
for (
; ((parent != null)
&& (traversedRows.ContainsKey(parent) == false));
) {
distance = (distance + 1);
root = parent;
traversedRows[parent] = parent;
parent = parent.GetParentRow(this._relation, global::System.Data.DataRowVersion.Original);
}
}
return root;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "15.0.0.0")]
public int Compare(global::System.Data.DataRow row1, global::System.Data.DataRow row2) {
if (object.ReferenceEquals(row1, row2)) {
return 0;
}
if ((row1 == null)) {
return -1;
}
if ((row2 == null)) {
return 1;
}
int distance1 = 0;
global::System.Data.DataRow root1 = this.GetRoot(row1, out distance1);
int distance2 = 0;
global::System.Data.DataRow root2 = this.GetRoot(row2, out distance2);
if (object.ReferenceEquals(root1, root2)) {
return (this._childFirst * distance1.CompareTo(distance2));
}
else {
global::System.Diagnostics.Debug.Assert(((root1.Table != null)
&& (root2.Table != null)));
if ((root1.Table.Rows.IndexOf(root1) < root2.Table.Rows.IndexOf(root2))) {
return -1;
}
else {
return 1;
}
}
}
}
}
}
#pragma warning restore 1591 | 53.270486 | 247 | 0.588946 | [
"Apache-2.0"
] | countadates/.netSessionTracker | SessionTracker/TracksQuery.Designer.cs | 73,472 | C# |
namespace SV.UPnPLite.Core
{
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
/// <summary>
/// Defines an error that occurred on a UPnP Service.
/// </summary>
public class UPnPServiceException : Exception
{
#region Constructors
/// <summary>
/// Initializes a new instance of the <see cref="UPnPServiceException"/> class.
/// </summary>
/// <param name="errorCode">
/// The error code which specifies an error.
/// </param>
/// <param name="message">
/// The message that describes an error.
/// </param>
public UPnPServiceException(int errorCode, string message)
: this(errorCode, message, null)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="UPnPServiceException"/> class.
/// </summary>
/// <param name="errorCode">
/// The error code which specifies an error.
/// </param>
/// <param name="message">
/// The message that describes an error.
/// </param>
/// <param name="innerException">
/// The exception that is the cause of the current exception, or a null reference (Nothing in Visual Basic) if no inner exception is specified.
/// </param>
public UPnPServiceException(int errorCode, string message, Exception innerException)
: base(message, innerException)
{
this.ErrorCode = errorCode;
}
#endregion
#region Properties
/// <summary>
/// Defines an error code which specifies an error.
/// </summary>
public int ErrorCode { get; private set; }
/// <summary>
/// Gets an action which caused an error.
/// </summary>
public string Action { get; internal set; }
/// <summary>
/// Gets an arguments which were passed into action.
/// </summary>
public IEnumerable<KeyValuePair<string, object>> Arguments { get; set; }
#endregion
#region Methods
/// <summary>
/// Returns a <see cref="System.String" /> that represents this instance.
/// </summary>
/// <returns>
/// A <see cref="System.String" /> that represents this instance.
/// </returns>
public override string ToString()
{
var description = new StringBuilder();
description.AppendLine("{0}: {1}".F(this.GetType(), this.Message));
if (string.IsNullOrEmpty(this.Action) == false)
{
var action = "Action: {0}".F(this.Action);
if (this.Arguments != null && this.Arguments.Any())
{
var arguments = string.Join(", ", this.Arguments.Select(a =>
{
var f = a.Value is string ? "{0}='{1}'" : "{0}={1}";
return f.F(a.Key, a.Value);
}));
action = string.Concat(action, " ({0})".F(arguments));
description.AppendLine(action);
}
}
if (this.InnerException != null)
{
description.AppendLine(" ---> {0}".F(this.InnerException));
}
if (this.StackTrace != null)
{
description.AppendLine();
description.AppendLine(this.StackTrace);
}
return description.ToString();
}
#endregion
}
}
| 25.982759 | 150 | 0.619774 | [
"Apache-2.0"
] | kinglionsoft/DlnaController | src/SV.UPnPLite.Core/Protocols/UPnP/UPnPServiceException.cs | 3,016 | C# |
// Copyright 2020 Energinet DataHub A/S
//
// Licensed under the Apache License, Version 2.0 (the "License2");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
using System;
using Energinet.DataHub.MeteringPoints.Contracts;
using Energinet.DataHub.MeteringPoints.Infrastructure.Transport.Protobuf;
using Google.Protobuf;
namespace Energinet.DataHub.MeteringPoints.Infrastructure.Ingestion.Mappers
{
public class MasterDataDocumentMapper : ProtobufOutboundMapper<Application.MarketDocuments.MasterDataDocument>
{
protected override IMessage Convert(Application.MarketDocuments.MasterDataDocument obj)
{
if (obj == null) throw new ArgumentNullException(nameof(obj));
return new MeteringPointEnvelope()
{
MasterDataDocument = new MasterDataDocument
{
ProcessType = obj.ProcessType,
GsrnNumber = obj.GsrnNumber,
TypeOfMeteringPoint = obj.TypeOfMeteringPoint,
SubTypeOfMeteringPoint = obj.MeteringMethod,
MeterReadingOccurrence = obj.MeterReadingOccurrence,
MaximumCurrent = obj.MaximumCurrent,
MaximumPower = obj.MaximumPower,
MeteringGridArea = obj.MeteringGridArea,
PowerPlant = obj.PowerPlant,
LocationDescription = obj.LocationDescription,
InstallationLocationAddress = new Address
{
StreetName = obj.StreetName,
PostCode = obj.PostCode,
CityName = obj.CityName,
CountryCode = obj.CountryCode,
ActualAddressIndicator = obj.IsActualAddress,
StreetCode = obj.StreetCode,
FloorIdentification = obj.FloorIdentification,
RoomIdentification = obj.RoomIdentification,
BuildingNumber = obj.BuildingNumber,
MunicipalityCode = obj.MunicipalityCode.ToString()!,
CityNameSubDivision = obj.CitySubDivisionName,
GeoInfoReference = obj.GeoInfoReference,
},
SettlementMethod = obj.SettlementMethod,
DisconnectionType = obj.DisconnectionType,
OccurenceDate = obj.EffectiveDate,
MeterNumber = obj.MeterNumber,
TransactionId = obj.TransactionId,
PhysicalStatusOfMeteringPoint = obj.PhysicalStatusOfMeteringPoint,
NetSettlementGroup = obj.NetSettlementGroup,
ConnectionType = obj.ConnectionType,
AssetType = obj.AssetType,
ParentRelatedMeteringPoint = obj.ParentRelatedMeteringPoint,
FromGrid = obj.FromGrid,
ToGrid = obj.ToGrid,
ProductType = obj.ProductType,
MeasureUnitType = obj.MeasureUnitType,
PhysicalConnectionCapacity = obj.PhysicalConnectionCapacity,
ScheduledMeterReadingDate = obj.ScheduledMeterReadingDate,
},
};
}
}
}
| 48.141026 | 114 | 0.602663 | [
"Apache-2.0"
] | Energinet-DataHub/geh-metering-point | source/Energinet.DataHub.MeteringPoints.Infrastructure/Ingestion/Mappers/MasterDataDocumentMapper.cs | 3,757 | 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("_04LargestArea")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("_04LargestArea")]
[assembly: AssemblyCopyright("Copyright © 2017")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("9eab4a79-9998-4de5-a8da-6a0376e42672")]
// 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.72973 | 84 | 0.748567 | [
"MIT"
] | dobri19/TelerikHomeWork | 03C#SDA/05-WorkShop01/04LargestArea/Properties/AssemblyInfo.cs | 1,399 | C# |
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using System.IO;
using Template.Dependency.Injection;
namespace Twitter.Feed.Reader.Worker.Service
{
public class Program
{
public static void Main(string[] args)
{
CreateHostBuilder(args).Build().Run();
}
public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.ConfigureWebHostDefaults(webBuilder =>
{
webBuilder.UseStartup<Startup>();
})
.ConfigureAppConfiguration((hostingContext, config) =>
{
config.SetBasePath(Directory.GetCurrentDirectory());
config.AddJsonFile("appsettings.json", true);
if (args != null) config.AddCommandLine(args);
})
.ConfigureServices((hostContext, services) =>
{
services.AddHostedService<Worker>();
});
}
}
| 32.885714 | 72 | 0.581234 | [
"MIT"
] | ongolenaveen/Read-Twitter-Feed-Azure-Logic-App | Feed.Worker.Service/Program.cs | 1,151 | C# |
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Threading.Tasks;
namespace Cashier.Models
{
public class Payment
{
[Key]
public int PayOrder { get; set; }
public int PayCustomer { get; set; }
public string PayMethod { get; set; }
public int PayQtdItems { get; set; }
public string PayPayDate { get; set; }
}
}
| 23.631579 | 46 | 0.652561 | [
"MIT"
] | Karla-Rodrigues/Cashier | Models/Payment.cs | 451 | C# |
// Copyright (c) 2016, SolidCP
// SolidCP is distributed under the Creative Commons Share-alike license
//
// SolidCP is a fork of WebsitePanel:
// Copyright (c) 2015, Outercurve Foundation.
// 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 Outercurve Foundation 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 HOLDER 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.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.DataVisualization.Charting;
using SolidCP.Providers.Virtualization;
namespace SolidCP.Portal.VPSForPC
{
public partial class MonitoringPage : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
ClientScriptManager cs = Page.ClientScript;
cs.RegisterClientScriptInclude("jquery", ResolveUrl("~/JavaScript/jquery-1.4.4.min.js"));
cs.RegisterClientScriptInclude("jqueryui", ResolveUrl("~/JavaScript/jquery-ui-1.8.9.min.js"));
if (Page.IsPostBack == false)
{
SetDefaultMonitoringTimeFrame();
BindPerformanceValues();
}
}
private void SetDefaultMonitoringTimeFrame()
{
if (String.IsNullOrEmpty(txtStartPeriod.Text))
{
txtStartPeriod.Text = DateTime.Now.AddDays(-1).ToShortDateString();
}
//
if (String.IsNullOrEmpty(txtEndPeriod.Text))
{
txtEndPeriod.Text = DateTime.Now.ToShortDateString();
}
}
private void BindPerformanceValues()
{
DateTime StartP = Convert.ToDateTime(txtStartPeriod.Text);
DateTime EndP = Convert.ToDateTime(txtEndPeriod.Text);
EndP = (EndP.CompareTo(DateTime.Now.Date) == 0 ? DateTime.Now : EndP);
PerformanceType pt = PerformanceType.Processor;
string charType = Page.Request.QueryString["chartType"];
InitControls(charType, StartP, EndP);
switch (charType)
{
case "Processor":
pt = PerformanceType.Processor;
break;
case "Network":
pt = PerformanceType.Network;
break;
case "Memory":
pt = PerformanceType.Memory;
break;
}
LoadChartData(ChartCounter, pt, StartP, EndP);
}
protected void operationTimer_Tick(object sender, EventArgs e)
{
BindPerformanceValues();
}
private void LoadChartData(Chart control, PerformanceType perfType, DateTime startPeriod, DateTime endPeriod)
{
PerformanceDataValue[] perfValues = ES.Services.VPSPC.GetPerfomanceValue(PanelRequest.ItemID, perfType, startPeriod, endPeriod);
if (perfValues != null)
{
foreach (PerformanceDataValue item in perfValues)
{
//
control.Series["series"].Points.AddXY(item.TimeSampled.ToString(), item.SampleValue);
}
}
}
private void InitControls(string charType, DateTime startPeriod, DateTime endPeriod)
{
ChartCounter.Titles.Add(charType);
ChartCounter.Series["series"].ChartType = (charType.Equals("Processor") ? SeriesChartType.Line : SeriesChartType.SplineArea);
//ChartCounter.Series["series"].IsValueShownAsLabel = true;
ChartCounter.Series["series"].Color = (!charType.Equals("Memory") ? System.Drawing.Color.FromArgb(220, 65, 140, 240) : ChartCounter.Series["series"].Color);
ChartCounter.Series["series"]["ShowMarkerLines"] = "True";
ChartCounter.ChartAreas["chartArea"].AxisX.IsMarginVisible = true;
}
}
}
| 36.992481 | 168 | 0.698374 | [
"BSD-3-Clause"
] | Alirexaa/SolidCP | SolidCP/Sources/SolidCP.WebPortal/DesktopModules/SolidCP/VPSForPC/MonitoringPage.aspx.cs | 4,920 | C# |
using Atc;
using Demo.Atc.Console.Spectre.Cli.Settings;
using Spectre.Console;
using Spectre.Console.Cli;
namespace Demo.Atc.Console.Spectre.Cli.Commands
{
public class HelloCommand : Command<HelloCommandSettings>
{
public override int Execute(CommandContext context, HelloCommandSettings settings)
{
AnsiConsole.MarkupLine(settings.Count > 0
? $"Hello, [blue]{Markup.Escape(settings.Name)}[/] - [red]{settings.Count}[/]"
: $"Hello, [blue]{Markup.Escape(settings.Name)}[/]");
return ConsoleExitStatusCodes.Success;
}
}
} | 32.315789 | 94 | 0.654723 | [
"MIT"
] | atc-net/atc | sample/Demo.Atc.Console.Spectre.Cli/Commands/HelloCommand.cs | 614 | C# |
using DotnetStack.Core.Entities;
using DotnetStack.Core.Interfaces;
namespace DotnetStack.DataAccessHandlers.Quotes
{
public interface IQuoteHandler : IBaseEntityHandler<Quote>
{
}
}
| 19.7 | 62 | 0.77665 | [
"MIT"
] | dteske25/dotnet-stack-template | DotnetStack.DataAccessHandlers/Quotes/IQuoteHandler.cs | 199 | C# |
using UnityEngine;
using System.Collections;
public class CrashMission : MissionTemplate
{
public enum CrashMissionTypes { CrashBefore, CrashBetween, CrashAfter };
public string description;
public CrashMissionTypes missionType;
public int minDistance;
public int maxDistance;
private bool isCompleted;
//Updates the mission
public override void UpdateMission(int missionValue)
{
if (missionType == CrashMissionTypes.CrashBefore && missionValue < minDistance)
isCompleted = true;
else if (missionType == CrashMissionTypes.CrashBetween && minDistance <= missionValue && maxDistance >= missionValue)
isCompleted = true;
else if (missionType == CrashMissionTypes.CrashAfter && missionValue > maxDistance)
isCompleted = true;
}
//Set mission completion
public override void SetCompletition(bool toValue)
{
isCompleted = toValue;
}
//Returns true, if the mission is completed
public override bool IsCompleted()
{
return isCompleted;
}
//Update the stored value
public override void SetStoredValue(int savedValue) { }
//Return the mission data to be saved
public override int MissionData()
{
return 0;
}
//Returns the mission description
public override string MissionDescription()
{
return description;
}
//Returns the mission status
public override string MissionStatus()
{
return "";
}
//Not implemented for this mission type
public override void UpdateMission(string missionValue)
{
throw new System.NotImplementedException();
}
//Not implemented for this mission type
public override void UpdateMission(int distance, int collectedCoins, bool powerupUsed)
{
throw new System.NotImplementedException();
}
}
| 29.590909 | 126 | 0.656938 | [
"MIT"
] | martinkro/tutorials-unity3d | Runner522/Assets/2DInfiniteRunnerToolkit/Scripts/C#/MissionTemplates/CrashMission.cs | 1,955 | C# |
using System;
using System.Linq.Expressions;
using Elsa.Models;
using LinqKit;
namespace Elsa.Persistence.Specifications.WorkflowDefinitions
{
public class WorkflowDefinitionIdSpecification : Specification<WorkflowDefinition>
{
public WorkflowDefinitionIdSpecification(string id, VersionOptions? versionOptions = default, string? tenantId = default)
{
Id = id;
VersionOptions = versionOptions;
}
public string Id { get; set; }
public VersionOptions? VersionOptions { get; }
public string? TenantId { get; set; }
public override Expression<Func<WorkflowDefinition, bool>> ToExpression()
{
Expression<Func<WorkflowDefinition, bool>> predicate = x => x.DefinitionId == Id;
if (!string.IsNullOrWhiteSpace(TenantId))
predicate = predicate.And(x => x.TenantId == TenantId);
if (VersionOptions != null)
predicate = predicate.WithVersion(VersionOptions.Value);
return predicate;
}
}
} | 32.454545 | 129 | 0.647059 | [
"MIT"
] | AgnesGray/elsa-core | src/core/Elsa.Core/Persistence/Specifications/WorkflowDefinitions/WorkflowDefinitionIdSpecification.cs | 1,073 | C# |
namespace MilitaryElite.Interfaces
{
public interface ISpy : ISoldier
{
int Code { get; }
}
}
| 14.375 | 36 | 0.6 | [
"MIT"
] | NikolaVodenicharov/OOP-Advanced | InterfacesAndAbstraction/MilitaryElite/Interfaces/ISpy.cs | 117 | 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.
// Description: Client-side wrapper for Scroll Pattern
using System;
using System.Windows.Automation.Provider;
using MS.Internal.Automation;
namespace System.Windows.Automation
{
/// <summary>
/// Represents UI elements that are expressing a value
/// </summary>
#if (INTERNAL_COMPILE)
internal class ScrollPattern: BasePattern
#else
public class ScrollPattern: BasePattern
#endif
{
//------------------------------------------------------
//
// Constructors
//
//------------------------------------------------------
#region Constructors
private ScrollPattern(AutomationElement el, SafePatternHandle hPattern, bool cached)
: base(el, hPattern)
{
_hPattern = hPattern;
_cached = cached;
}
#endregion Constructors
//------------------------------------------------------
//
// Public Constants / Readonly Fields
//
//------------------------------------------------------
#region Public Constants and Readonly Fields
/// <summary>Value used by SetSCrollPercent to indicate that no scrolling should take place in the specified direction</summary>
public const double NoScroll = -1.0;
/// <summary>Scroll pattern</summary>
public static readonly AutomationPattern Pattern = ScrollPatternIdentifiers.Pattern;
/// <summary>Property ID: HorizontalScrollPercent - Current horizontal scroll position</summary>
public static readonly AutomationProperty HorizontalScrollPercentProperty = ScrollPatternIdentifiers.HorizontalScrollPercentProperty;
/// <summary>Property ID: HorizontalViewSize - Minimum possible horizontal scroll position</summary>
public static readonly AutomationProperty HorizontalViewSizeProperty = ScrollPatternIdentifiers.HorizontalViewSizeProperty;
/// <summary>Property ID: VerticalScrollPercent - Current vertical scroll position</summary>
public static readonly AutomationProperty VerticalScrollPercentProperty = ScrollPatternIdentifiers.VerticalScrollPercentProperty;
/// <summary>Property ID: VerticalViewSize </summary>
public static readonly AutomationProperty VerticalViewSizeProperty = ScrollPatternIdentifiers.VerticalViewSizeProperty;
/// <summary>Property ID: HorizontallyScrollable</summary>
public static readonly AutomationProperty HorizontallyScrollableProperty = ScrollPatternIdentifiers.HorizontallyScrollableProperty;
/// <summary>Property ID: VerticallyScrollable</summary>
public static readonly AutomationProperty VerticallyScrollableProperty = ScrollPatternIdentifiers.VerticallyScrollableProperty;
#endregion Public Constants and Readonly Fields
//------------------------------------------------------
//
// Public Methods
//
//------------------------------------------------------
#region Public Methods
/// <summary> Request to set the current horizontal and Vertical scroll position
/// by percent (0-100). Passing in the value of "-1" will indicate that
/// scrolling in that direction should be ignored.
/// The ability to call this method and simultaneously scroll horizontally and
/// vertically provides simple panning support.</summary>
/// <param name="horizontalPercent">Amount to scroll by horizontally</param>
/// <param name="verticalPercent">Amount to scroll by vertically </param>
///
/// <outside_see conditional="false">
/// This API does not work inside the secure execution environment.
/// <exception cref="System.Security.Permissions.SecurityPermission"/>
/// </outside_see>
public void SetScrollPercent( double horizontalPercent, double verticalPercent )
{
UiaCoreApi.ScrollPattern_SetScrollPercent(_hPattern, horizontalPercent, verticalPercent);
}
/// <summary> Request to scroll horizontally and vertically by the specified amount.
/// The ability to call this method and simultaneously scroll horizontally
/// and vertically provides simple panning support. If only horizontal or vertical percent
/// needs to be changed the constant SetScrollPercentUnchanged can be used for
/// either parameter and that axis wil be unchanged.</summary>
///
/// <param name="horizontalAmount">amount to scroll by horizontally</param>
/// <param name="verticalAmount">amount to scroll by vertically </param>
///
/// <outside_see conditional="false">
/// This API does not work inside the secure execution environment.
/// <exception cref="System.Security.Permissions.SecurityPermission"/>
/// </outside_see>
public void Scroll( ScrollAmount horizontalAmount, ScrollAmount verticalAmount )
{
UiaCoreApi.ScrollPattern_Scroll(_hPattern, horizontalAmount, verticalAmount);
}
/// <summary>
/// Request to scroll horizontally by the specified amount
/// </summary>
/// <param name="amount">Amount to scroll by</param>
///
/// <outside_see conditional="false">
/// This API does not work inside the secure execution environment.
/// <exception cref="System.Security.Permissions.SecurityPermission"/>
/// </outside_see>
public void ScrollHorizontal( ScrollAmount amount )
{
UiaCoreApi.ScrollPattern_Scroll(_hPattern, amount, ScrollAmount.NoAmount);
}
/// <summary>
/// Request to scroll vertically by the specified amount
/// </summary>
/// <param name="amount">Amount to scroll by</param>
///
/// <outside_see conditional="false">
/// This API does not work inside the secure execution environment.
/// <exception cref="System.Security.Permissions.SecurityPermission"/>
/// </outside_see>
public void ScrollVertical( ScrollAmount amount )
{
UiaCoreApi.ScrollPattern_Scroll(_hPattern, ScrollAmount.NoAmount, amount);
}
#endregion Public Methods
//------------------------------------------------------
//
// Public Properties
//
//------------------------------------------------------
#region Public Properties
/// <summary>
/// This member allows access to previously requested
/// cached properties for this element. The returned object
/// has accessors for each property defined for this pattern.
/// </summary>
/// <remarks>
/// Cached property values must have been previously requested
/// using a CacheRequest. If you try to access a cached
/// property that was not previously requested, an InvalidOperation
/// Exception will be thrown.
///
/// To get the value of a property at the current point in time,
/// access the property via the Current accessor instead of
/// Cached.
/// </remarks>
public ScrollPatternInformation Cached
{
get
{
Misc.ValidateCached(_cached);
return new ScrollPatternInformation(_el, true);
}
}
/// <summary>
/// This member allows access to current property values
/// for this element. The returned object has accessors for
/// each property defined for this pattern.
/// </summary>
/// <remarks>
/// This pattern must be from an AutomationElement with a
/// Full reference in order to get current values. If the
/// AutomationElement was obtained using AutomationElementMode.None,
/// then it contains only cached data, and attempting to get
/// the current value of any property will throw an InvalidOperationException.
///
/// To get the cached value of a property that was previously
/// specified using a CacheRequest, access the property via the
/// Cached accessor instead of Current.
/// </remarks>
public ScrollPatternInformation Current
{
get
{
Misc.ValidateCurrent(_hPattern);
return new ScrollPatternInformation(_el, false);
}
}
#endregion Public Properties
//------------------------------------------------------
//
// Internal Methods
//
//------------------------------------------------------
#region Internal Methods
static internal object Wrap(AutomationElement el, SafePatternHandle hPattern, bool cached)
{
return new ScrollPattern(el, hPattern, cached);
}
#endregion Internal Methods
//------------------------------------------------------
//
// Private Fields
//
//------------------------------------------------------
#region Private Fields
SafePatternHandle _hPattern;
bool _cached;
#endregion Private Fields
//------------------------------------------------------
//
// Nested Classes
//
//------------------------------------------------------
#region Nested Classes
/// <summary>
/// This class provides access to either Cached or Current
/// properties on a pattern via the pattern's .Cached or
/// .Current accessors.
/// </summary>
public struct ScrollPatternInformation
{
//------------------------------------------------------
//
// Constructors
//
//------------------------------------------------------
#region Constructors
internal ScrollPatternInformation(AutomationElement el, bool useCache)
{
_el = el;
_useCache = useCache;
}
#endregion Constructors
//------------------------------------------------------
//
// Public Properties
//
//------------------------------------------------------
#region Public Properties
/// <summary>
/// Get the current horizontal scroll position
/// </summary>
///
/// <outside_see conditional="false">
/// This API does not work inside the secure execution environment.
/// <exception cref="System.Security.Permissions.SecurityPermission"/>
/// </outside_see>
public double HorizontalScrollPercent
{
get
{
return (double)_el.GetPatternPropertyValue(HorizontalScrollPercentProperty, _useCache);
}
}
/// <summary>
/// Get the current vertical scroll position
/// </summary>
///
/// <outside_see conditional="false">
/// This API does not work inside the secure execution environment.
/// <exception cref="System.Security.Permissions.SecurityPermission"/>
/// </outside_see>
public double VerticalScrollPercent
{
get
{
return (double)_el.GetPatternPropertyValue(VerticalScrollPercentProperty, _useCache);
}
}
/// <summary>
/// Equal to the horizontal percentage of the entire control that is currently viewable.
/// </summary>
///
/// <outside_see conditional="false">
/// This API does not work inside the secure execution environment.
/// <exception cref="System.Security.Permissions.SecurityPermission"/>
/// </outside_see>
public double HorizontalViewSize
{
get
{
return (double)_el.GetPatternPropertyValue(HorizontalViewSizeProperty, _useCache);
}
}
/// <summary>
/// Equal to the horizontal percentage of the entire control that is currently viewable.
/// </summary>
///
/// <outside_see conditional="false">
/// This API does not work inside the secure execution environment.
/// <exception cref="System.Security.Permissions.SecurityPermission"/>
/// </outside_see>
public double VerticalViewSize
{
get
{
return (double)_el.GetPatternPropertyValue(VerticalViewSizeProperty, _useCache);
}
}
/// <summary>
/// True if control can scroll horizontally
/// </summary>
///
/// <outside_see conditional="false">
/// This API does not work inside the secure execution environment.
/// <exception cref="System.Security.Permissions.SecurityPermission"/>
/// </outside_see>
public bool HorizontallyScrollable
{
get
{
return (bool)_el.GetPatternPropertyValue(HorizontallyScrollableProperty, _useCache);
}
}
/// <summary>
/// True if control can scroll vertically
/// </summary>
///
/// <outside_see conditional="false">
/// This API does not work inside the secure execution environment.
/// <exception cref="System.Security.Permissions.SecurityPermission"/>
/// </outside_see>
public bool VerticallyScrollable
{
get
{
return (bool)_el.GetPatternPropertyValue(VerticallyScrollableProperty, _useCache);
}
}
#endregion Public Properties
//------------------------------------------------------
//
// Private Fields
//
//------------------------------------------------------
#region Private Fields
private AutomationElement _el; // AutomationElement that contains the cache or live reference
private bool _useCache; // true to use cache, false to use live reference to get current values
#endregion Private Fields
}
#endregion Nested Classes
}
}
| 38.346939 | 141 | 0.545902 | [
"MIT"
] | KodamaSakuno/wpf | src/Microsoft.DotNet.Wpf/src/UIAutomation/UIAutomationClient/System/Windows/Automation/ScrollPattern.cs | 15,032 | C# |
namespace Blockfrost.Api
{
// TODO: review (obsolete?)
public partial class BlockContentTransactionIds : System.Collections.ObjectModel.Collection<string>
{
}
}
| 22.25 | 103 | 0.719101 | [
"Apache-2.0"
] | blockfrost/blockfrost-donet | src/Blockfrost.Api/Models/Cardano/Blocks/BlockContentTransactionIds.cs | 180 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using OpenCV.Net;
using OpenTK;
namespace Bonsai.Vision.Design
{
static class DrawingHelper
{
public static void DrawConnectedComponent(IplImage image, ConnectedComponent component)
{
DrawConnectedComponent(image, component, Point2f.Zero);
}
public static void DrawConnectedComponent(IplImage image, ConnectedComponent component, Point2f offset)
{
if (component.Area <= 0) return;
var centroid = component.Centroid + offset;
var orientation = component.Orientation;
var minorAxisOrientation = orientation + Math.PI / 2.0;
var halfMajorAxis = component.MajorAxisLength * 0.5;
var halfMinorAxis = component.MinorAxisLength * 0.5;
var major1 = new Point((int)(centroid.X + halfMajorAxis * Math.Cos(orientation)), (int)(centroid.Y + halfMajorAxis * Math.Sin(orientation)));
var major2 = new Point((int)(centroid.X - halfMajorAxis * Math.Cos(orientation)), (int)(centroid.Y - halfMajorAxis * Math.Sin(orientation)));
var minor1 = new Point((int)(centroid.X + halfMinorAxis * Math.Cos(minorAxisOrientation)), (int)(centroid.Y + halfMinorAxis * Math.Sin(minorAxisOrientation)));
var minor2 = new Point((int)(centroid.X - halfMinorAxis * Math.Cos(minorAxisOrientation)), (int)(centroid.Y - halfMinorAxis * Math.Sin(minorAxisOrientation)));
if (component.Patch != null)
{
var target = image;
var patch = component.Patch;
var mask = patch.Channels == 1 ? patch : null;
try
{
if (component.Contour != null)
{
var rect = component.Contour.Rect;
mask = new IplImage(patch.Size, patch.Depth, 1);
mask.SetZero();
CV.DrawContours(mask, component.Contour, Scalar.All(255), Scalar.All(0), 0, -1, LineFlags.Connected8, new Point(-rect.X, -rect.Y));
if (image.Width != rect.Width || image.Height != rect.Height)
{
target = image.GetSubRect(component.Contour.Rect);
}
}
if (patch.Channels != target.Channels)
{
var conversion = patch.Channels > image.Channels
? ColorConversion.Bgr2Gray
: ColorConversion.Gray2Bgr;
patch = new IplImage(patch.Size, patch.Depth, image.Channels);
CV.CvtColor(component.Patch, patch, conversion);
}
CV.Copy(patch, target, mask);
}
finally
{
if (patch != component.Patch) patch.Dispose();
if (mask != component.Patch) mask.Dispose();
if (target != image) target.Dispose();
}
}
else if (component.Contour != null)
{
CV.DrawContours(image, component.Contour, Scalar.All(255), Scalar.All(0), 0, -1, LineFlags.Connected8, new Point(offset));
}
if (component.Contour != null)
{
CV.DrawContours(image, component.Contour, Scalar.Rgb(255, 0, 0), Scalar.Rgb(0, 0, 255), 0, 1, LineFlags.Connected8, new Point(offset));
}
CV.Line(image, major1, major2, Scalar.Rgb(0, 0, 255));
CV.Line(image, minor1, minor2, Scalar.Rgb(255, 0, 0));
CV.Circle(image, new Point(centroid), 2, Scalar.Rgb(255, 0, 0), -1);
}
public static void DrawConvexityDefects(IplImage image, Seq convexityDefects, Scalar color, int thickness = 1)
{
DrawConvexityDefects(image, convexityDefects, color, thickness, Point.Zero);
}
public static void DrawConvexityDefects(IplImage image, Seq convexityDefects, Scalar color, int thickness, Point offset)
{
if (convexityDefects != null && convexityDefects.Count > 0)
{
var defects = convexityDefects.ToArray<ConvexityDefect>();
foreach (var defect in defects)
{
var startPoint = defect.Start;
var endPoint = defect.End;
var depthPoint = defect.DepthPoint;
var surfacePoint = new Point((startPoint.X + endPoint.X) / 2 + offset.X, (startPoint.Y + endPoint.Y) / 2 + offset.Y);
var depthOffset = new Point(depthPoint.X + offset.X, depthPoint.Y + offset.Y);
CV.Line(image, depthOffset, surfacePoint, color, thickness);
}
}
}
public static Vector2 NormalizePoint(Point point, Size imageSize)
{
return new Vector2(
(point.X * 2f / imageSize.Width) - 1,
-((point.Y * 2f / imageSize.Height) - 1));
}
}
}
| 47.792793 | 172 | 0.53082 | [
"MIT"
] | aalmada/bonsai | Bonsai.Vision.Design/DrawingHelper.cs | 5,307 | C# |
#region Copyright notice and license
// Copyright 2019 The gRPC Authors
//
// 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.
#endregion
using System;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Threading.Tasks;
using Greet;
using Grpc.AspNetCore.FunctionalTests.Infrastructure;
using Grpc.AspNetCore.Server.Internal;
using Grpc.Core;
using NUnit.Framework;
namespace Grpc.AspNetCore.FunctionalTests
{
[TestFixture]
public class UnaryMethodTests : FunctionalTestBase
{
[Test]
public async Task SendValidRequest_SuccessResponse()
{
// Arrange
var requestMessage = new HelloRequest
{
Name = "World"
};
var ms = new MemoryStream();
MessageHelpers.WriteMessage(ms, requestMessage);
// Act
var response = await Fixture.Client.PostAsync(
"Greet.Greeter/SayHello",
new StreamContent(ms)).DefaultTimeout();
// Assert
Assert.AreEqual(HttpStatusCode.OK, response.StatusCode);
Assert.AreEqual("identity", response.Headers.GetValues("grpc-encoding").Single());
Assert.AreEqual("application/grpc", response.Content.Headers.ContentType.MediaType);
var responseMessage = MessageHelpers.AssertReadMessage<HelloReply>(await response.Content.ReadAsByteArrayAsync().DefaultTimeout());
Assert.AreEqual("Hello World", responseMessage.Message);
Assert.AreEqual(StatusCode.OK.ToTrailerString(), Fixture.TrailersContainer.Trailers[GrpcProtocolConstants.StatusTrailer].Single());
}
[Test]
public async Task StreamedMessage_SuccessResponseAfterMessageReceived()
{
// Arrange
var requestMessage = new HelloRequest
{
Name = "World"
};
var ms = new MemoryStream();
MessageHelpers.WriteMessage(ms, requestMessage);
var requestStream = new SyncPointMemoryStream();
var httpRequest = new HttpRequestMessage(HttpMethod.Post, "Greet.Greeter/SayHello");
httpRequest.Content = new StreamContent(requestStream);
// Act
var responseTask = Fixture.Client.SendAsync(httpRequest, HttpCompletionOption.ResponseHeadersRead);
// Assert
Assert.IsFalse(responseTask.IsCompleted, "Server should wait for client to finish streaming");
await requestStream.AddDataAndWait(ms.ToArray()).DefaultTimeout();
await requestStream.AddDataAndWait(Array.Empty<byte>()).DefaultTimeout();
var response = await responseTask.DefaultTimeout();
Assert.AreEqual(HttpStatusCode.OK, response.StatusCode);
Assert.AreEqual("identity", response.Headers.GetValues("grpc-encoding").Single());
Assert.AreEqual("application/grpc", response.Content.Headers.ContentType.MediaType);
var responseMessage = MessageHelpers.AssertReadMessage<HelloReply>(await response.Content.ReadAsByteArrayAsync().DefaultTimeout());
Assert.AreEqual("Hello World", responseMessage.Message);
}
[Test]
public async Task AdditionalDataAfterStreamedMessage_ErrorResponse()
{
// Arrange
var requestMessage = new HelloRequest
{
Name = "World"
};
var ms = new MemoryStream();
MessageHelpers.WriteMessage(ms, requestMessage);
var requestStream = new SyncPointMemoryStream();
var httpRequest = new HttpRequestMessage(HttpMethod.Post, "Greet.Greeter/SayHello");
httpRequest.Content = new StreamContent(requestStream);
// Act
var responseTask = Fixture.Client.SendAsync(httpRequest, HttpCompletionOption.ResponseHeadersRead);
// Assert
Assert.IsFalse(responseTask.IsCompleted, "Server should wait for client to finish streaming");
await requestStream.AddDataAndWait(ms.ToArray()).DefaultTimeout();
await requestStream.AddDataAndWait(ms.ToArray()).DefaultTimeout();
// TODO - this should return a response with a gRPC status object
var ex = Assert.ThrowsAsync<InvalidDataException>(async () =>
{
await responseTask.DefaultTimeout();
});
Assert.AreEqual("Additional data after the message received.", ex.Message);
}
[Test]
public async Task MessageSentInMultipleChunks_SuccessResponse()
{
// Arrange
var requestMessage = new HelloRequest
{
Name = "World"
};
var ms = new MemoryStream();
MessageHelpers.WriteMessage(ms, requestMessage);
var requestStream = new SyncPointMemoryStream();
var httpRequest = new HttpRequestMessage(HttpMethod.Post, "Greet.Greeter/SayHello");
httpRequest.Content = new StreamContent(requestStream);
// Act
var responseTask = Fixture.Client.SendAsync(httpRequest, HttpCompletionOption.ResponseHeadersRead);
// Assert
Assert.IsFalse(responseTask.IsCompleted, "Server should wait for client to finish streaming");
// Send message one byte at a time then finish
foreach (var b in ms.ToArray())
{
await requestStream.AddDataAndWait(new[] { b }).DefaultTimeout();
}
await requestStream.AddDataAndWait(Array.Empty<byte>()).DefaultTimeout();
var response = await responseTask.DefaultTimeout();
Assert.AreEqual(HttpStatusCode.OK, response.StatusCode);
var responseMessage = MessageHelpers.AssertReadMessage<HelloReply>(await response.Content.ReadAsByteArrayAsync().DefaultTimeout());
Assert.AreEqual("Hello World", responseMessage.Message);
Assert.AreEqual(StatusCode.OK.ToTrailerString(), Fixture.TrailersContainer.Trailers[GrpcProtocolConstants.StatusTrailer].Single());
}
[Test]
public async Task SendHeadersTwice_ThrowsException()
{
// Arrange
var requestMessage = new HelloRequest
{
Name = "World"
};
var ms = new MemoryStream();
MessageHelpers.WriteMessage(ms, requestMessage);
// Act
var response = await Fixture.Client.PostAsync(
"Greet.Greeter/SayHelloSendHeadersTwice",
new StreamContent(ms)).DefaultTimeout();
// Assert
Assert.AreEqual(HttpStatusCode.OK, response.StatusCode);
Assert.AreEqual("identity", response.Headers.GetValues("grpc-encoding").Single());
Assert.AreEqual("application/grpc", response.Content.Headers.ContentType.MediaType);
var responseMessage = MessageHelpers.AssertReadMessage<HelloReply>(await response.Content.ReadAsByteArrayAsync().DefaultTimeout());
Assert.AreEqual("Exception validated", responseMessage.Message);
}
}
}
| 38.447761 | 143 | 0.644669 | [
"Apache-2.0"
] | awesomedotnetcore/grpc-dotnet | test/FunctionalTests/UnaryMethodTests.cs | 7,728 | C# |
using System;
using System.Windows;
using System.Windows.Controls;
/**
* ┌───────────────────────────────────────────────────────────────────────┐
* │Project : UrusUI
* │
* │Comment :
* │
* │Version : V1.0.0.0
* │Author : lanbery
* │CreatTime : 2019/3/7 17:20:35
* ├───────────────────────────────────────────────────────────────────────┤
* │Copyright © NBS-Tech Team 2019.All rights reserved.
* └───────────────────────────────────────────────────────────────────────┘
*/
namespace UrusUI
{
public class FMenuItem : MenuItem
{
static FMenuItem()
{
DefaultStyleKeyProperty.OverrideMetadata(typeof(FMenuItem), new FrameworkPropertyMetadata(typeof(FMenuItem)));
}
}
}
| 22.636364 | 122 | 0.424364 | [
"MIT"
] | DappNBS/WPFEstoque | Urus.UI/Urus.UI/FMenuItem.cs | 1,204 | 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.
/*=============================================================================
**
**
**
**
**
** Purpose: Get the underlying TypeInfo from a Type
**
**
=============================================================================*/
namespace System.Reflection
{
public static class IntrospectionExtensions
{
public static TypeInfo GetTypeInfo(this Type type)
{
if (type == null)
throw new ArgumentNullException(nameof(type));
var rcType=(IReflectableType)type;
return rcType.GetTypeInfo();
}
}
}
| 27.586207 | 79 | 0.50625 | [
"MIT"
] | guhuro/coreclr | src/mscorlib/src/System/Reflection/IntrospectionExtensions.cs | 800 | C# |
using Android.App;
using Android.Content.PM;
using MvvmCross.Droid.Views;
namespace ProgrammingSupport.Droid
{
[Activity(
Label = "ProgrammingSupport.Droid"
, MainLauncher = true
, Icon = "@mipmap/icon"
, Theme = "@style/Theme.Splash"
, NoHistory = true
, ScreenOrientation = ScreenOrientation.Portrait)]
public class SplashScreen : MvxSplashScreenActivity
{
public SplashScreen()
: base(Resource.Layout.SplashScreen)
{
}
}
}
| 23.681818 | 55 | 0.629559 | [
"MIT"
] | Xciles/programming.support | Appje/ProgrammingSupport/ProgrammingSupport.Droid/SplashScreen.cs | 521 | C# |
using Amazon.Lambda.AspNetCoreServer;
using Microsoft.AspNetCore.Hosting;
using System.IO;
namespace Estranged.Lfs.Hosting.Lambda
{
public class LambdaEntryPoint : APIGatewayProxyFunction
{
protected override void Init(IWebHostBuilder builder)
{
builder.UseContentRoot(Directory.GetCurrentDirectory())
.UseStartup<Startup>()
.UseLambdaServer();
}
}
}
| 26.352941 | 68 | 0.645089 | [
"MIT"
] | MineoGames/Estranged.Lfs | hosting/Estranged.Lfs.Hosting.Lambda/LambdaEntryPoint.cs | 448 | C# |
using Lucene.Net.Analysis.Util;
using System;
using System.IO;
using System.Text;
namespace Lucene.Net.Analysis.Ja
{
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/// <summary>Fake resource loader for tests: works if you want to fake reading a single file</summary>
internal class StringMockResourceLoader : IResourceLoader
{
String text;
public StringMockResourceLoader(String text)
{
this.text = text;
}
public virtual Type FindType(String cname)
{
try
{
//return Class.forName(cname).asSubclass(expectedType);
return Type.GetType(cname);
}
catch (Exception e)
{
throw new Exception("Cannot load class: " + cname, e);
}
}
public virtual T NewInstance<T>(String cname)
{
Type clazz = FindType(cname);
try
{
//return clazz.NewInstance();
return (T)Activator.CreateInstance(clazz);
}
catch (Exception e)
{
throw new Exception("Cannot create instance: " + cname, e);
}
}
public virtual Stream OpenResource(String resource)
{
return new MemoryStream(Encoding.UTF8.GetBytes(text));
}
}
}
| 32.455882 | 106 | 0.597191 | [
"Apache-2.0"
] | DiogenesPolanco/lucenenet | src/Lucene.Net.Tests.Analysis.Kuromoji/StringMockResourceLoader.cs | 2,209 | C# |
using UnityEngine;
using System.Collections;
namespace TMPro.Examples
{
public class CameraController : MonoBehaviour
{
public enum CameraModes { Follow, Isometric, Free }
private Transform cameraTransform;
private Transform dummyTarget;
public Transform CameraTarget;
public float FollowDistance = 30.0f;
public float MaxFollowDistance = 100.0f;
public float MinFollowDistance = 2.0f;
public float ElevationAngle = 30.0f;
public float MaxElevationAngle = 85.0f;
public float MinElevationAngle = 0f;
public float OrbitalAngle = 0f;
public CameraModes CameraMode = CameraModes.Follow;
public bool MovementSmoothing = true;
public bool RotationSmoothing = false;
private bool previousSmoothing;
public float MovementSmoothingValue = 25f;
public float RotationSmoothingValue = 5.0f;
public float MoveSensitivity = 2.0f;
private Vector3 currentVelocity = Vector3.zero;
private Vector3 desiredPosition;
private float mouseX;
private float mouseY;
private Vector3 moveVector;
private float mouseWheel;
// Controls for Touches on Mobile devices
//private float prev_ZoomDelta;
private const string event_SmoothingValue = "Slider - Smoothing Value";
private const string event_FollowDistance = "Slider - Camera Zoom";
void Awake()
{
if (QualitySettings.vSyncCount > 0)
Application.targetFrameRate = 60;
else
Application.targetFrameRate = -1;
if (Application.platform == RuntimePlatform.IPhonePlayer || Application.platform == RuntimePlatform.Android)
Input.simulateMouseWithTouches = false;
cameraTransform = transform;
previousSmoothing = MovementSmoothing;
}
// Use this for initialization
void Start()
{
if (CameraTarget == null)
{
// If we don't have a target (assigned by the player, create a dummy in the center of the scene).
dummyTarget = new GameObject("Camera Target").transform;
CameraTarget = dummyTarget;
}
}
// Update is called once per frame
void LateUpdate()
{
GetPlayerInput();
// Check if we still have a valid target
if (CameraTarget != null)
{
if (CameraMode == CameraModes.Isometric)
{
desiredPosition = CameraTarget.position + Quaternion.Euler(ElevationAngle, OrbitalAngle, 0f) * new Vector3(0, 0, -FollowDistance);
}
else if (CameraMode == CameraModes.Follow)
{
desiredPosition = CameraTarget.position + CameraTarget.TransformDirection(Quaternion.Euler(ElevationAngle, OrbitalAngle, 0f) * (new Vector3(0, 0, -FollowDistance)));
}
else
{
// Free Camera implementation
}
if (MovementSmoothing == true)
{
// Using Smoothing
cameraTransform.position = Vector3.SmoothDamp(cameraTransform.position, desiredPosition, ref currentVelocity, MovementSmoothingValue * Time.fixedDeltaTime);
//cameraTransform.position = Vector3.Lerp(cameraTransform.position, desiredPosition, Time.deltaTime * 5.0f);
}
else
{
// Not using Smoothing
cameraTransform.position = desiredPosition;
}
if (RotationSmoothing == true)
cameraTransform.rotation = Quaternion.Lerp(cameraTransform.rotation, Quaternion.LookRotation(CameraTarget.position - cameraTransform.position), RotationSmoothingValue * Time.deltaTime);
else
{
cameraTransform.LookAt(CameraTarget);
}
}
}
void GetPlayerInput()
{
moveVector = Vector3.zero;
// Check Mouse Wheel Input prior to Shift Key so we can apply multiplier on Shift for Scrolling
mouseWheel = Input.GetAxis("Mouse ScrollWheel");
float touchCount = Input.touchCount;
if (Input.GetKey(KeyCode.LeftShift) || Input.GetKey(KeyCode.RightShift) || touchCount > 0)
{
mouseWheel *= 10;
if (Input.GetKeyDown(KeyCode.I))
CameraMode = CameraModes.Isometric;
if (Input.GetKeyDown(KeyCode.F))
CameraMode = CameraModes.Follow;
if (Input.GetKeyDown(KeyCode.S))
MovementSmoothing = !MovementSmoothing;
// Check for right mouse button to change camera follow and elevation angle
if (Input.GetMouseButton(1))
{
mouseY = Input.GetAxis("Mouse Y");
mouseX = Input.GetAxis("Mouse X");
if (mouseY > 0.01f || mouseY < -0.01f)
{
ElevationAngle -= mouseY * MoveSensitivity;
// Limit Elevation angle between min & max values.
ElevationAngle = Mathf.Clamp(ElevationAngle, MinElevationAngle, MaxElevationAngle);
}
if (mouseX > 0.01f || mouseX < -0.01f)
{
OrbitalAngle += mouseX * MoveSensitivity;
if (OrbitalAngle > 360)
OrbitalAngle -= 360;
if (OrbitalAngle < 0)
OrbitalAngle += 360;
}
}
// Get Input from Mobile Device
if (touchCount == 1 && Input.GetTouch(0).phase == TouchPhase.Moved)
{
Vector2 deltaPosition = Input.GetTouch(0).deltaPosition;
// Handle elevation changes
if (deltaPosition.y > 0.01f || deltaPosition.y < -0.01f)
{
ElevationAngle -= deltaPosition.y * 0.1f;
// Limit Elevation angle between min & max values.
ElevationAngle = Mathf.Clamp(ElevationAngle, MinElevationAngle, MaxElevationAngle);
}
// Handle left & right
if (deltaPosition.x > 0.01f || deltaPosition.x < -0.01f)
{
OrbitalAngle += deltaPosition.x * 0.1f;
if (OrbitalAngle > 360)
OrbitalAngle -= 360;
if (OrbitalAngle < 0)
OrbitalAngle += 360;
}
}
// Check for left mouse button to select a new CameraTarget or to reset Follow position
if (Input.GetMouseButton(0))
{
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
RaycastHit hit;
if (Physics.Raycast(ray, out hit, 300, 1 << 10 | 1 << 11 | 1 << 12 | 1 << 14))
{
if (hit.transform == CameraTarget)
{
// Reset Follow Position
OrbitalAngle = 0;
}
else
{
CameraTarget = hit.transform;
OrbitalAngle = 0;
MovementSmoothing = previousSmoothing;
}
}
}
if (Input.GetMouseButton(2))
{
if (dummyTarget == null)
{
// We need a Dummy Target to anchor the Camera
dummyTarget = new GameObject("Camera Target").transform;
dummyTarget.position = CameraTarget.position;
dummyTarget.rotation = CameraTarget.rotation;
CameraTarget = dummyTarget;
previousSmoothing = MovementSmoothing;
MovementSmoothing = false;
}
else if (dummyTarget != CameraTarget)
{
// Move DummyTarget to CameraTarget
dummyTarget.position = CameraTarget.position;
dummyTarget.rotation = CameraTarget.rotation;
CameraTarget = dummyTarget;
previousSmoothing = MovementSmoothing;
MovementSmoothing = false;
}
mouseY = Input.GetAxis("Mouse Y");
mouseX = Input.GetAxis("Mouse X");
moveVector = cameraTransform.TransformDirection(mouseX, mouseY, 0);
dummyTarget.Translate(-moveVector, Space.World);
}
}
// Check Pinching to Zoom in - out on Mobile device
if (touchCount == 2)
{
Touch touch0 = Input.GetTouch(0);
Touch touch1 = Input.GetTouch(1);
Vector2 touch0PrevPos = touch0.position - touch0.deltaPosition;
Vector2 touch1PrevPos = touch1.position - touch1.deltaPosition;
float prevTouchDelta = (touch0PrevPos - touch1PrevPos).magnitude;
float touchDelta = (touch0.position - touch1.position).magnitude;
float zoomDelta = prevTouchDelta - touchDelta;
if (zoomDelta > 0.01f || zoomDelta < -0.01f)
{
FollowDistance += zoomDelta * 0.25f;
// Limit FollowDistance between min & max values.
FollowDistance = Mathf.Clamp(FollowDistance, MinFollowDistance, MaxFollowDistance);
}
}
// Check MouseWheel to Zoom in-out
if (mouseWheel < -0.01f || mouseWheel > 0.01f)
{
FollowDistance -= mouseWheel * 5.0f;
// Limit FollowDistance between min & max values.
FollowDistance = Mathf.Clamp(FollowDistance, MinFollowDistance, MaxFollowDistance);
}
}
}
} | 36.414384 | 205 | 0.508887 | [
"MIT"
] | rdutta1999/Stroop-and-Stop | Assets/TextMesh Pro/Examples & Extras/Scripts/CameraController.cs | 10,633 | C# |
// Fix for the RoR2 Class SearchableAttribute scanning modding core assemblies creating in-game stuttering.
// ReSharper disable InconsistentNaming
// ReSharper disable UnusedMember.Global
// ReSharper disable NotAccessedField.Local
#pragma warning disable IDE0052 // Remove unread private members
#pragma warning disable IDE1006 // Naming Styles
#pragma warning disable IDE0044 // Add readonly modifier
using System;
using System.Collections.Generic;
using MonoMod;
namespace RoR2 {
internal class patch_SearchableAttribute : Attribute {
[MonoModConstructor]
static patch_SearchableAttribute() {
instancesListsByType = new Dictionary<Type, List<SearchableAttribute>>();
assemblyBlacklist = new HashSet<string> {
"MMHOOK_Assembly-CSharp",
"BepInEx",
"BepInEx.Preloader",
"BepInEx.Harmony",
"BepInEx.MonoMod.Loader",
"0Harmony",
"Mono.Cecil",
"Mono.Cecil.Pdb",
"Mono.Cecil.Mdb",
"MonoMod",
"MonoMod.RuntimeDetour",
"MonoMod.RuntimeDetour.HarmonySharedState",
"MonoMod.Utils",
"MonoMod.Utils.GetManagedSizeHelper",
"MonoMod.Utils.Cil.ILGeneratorProxy",
"R2API",
"Assembly-CSharp.R2API.mm.MonoModRules [MMILRT, ID:0]",
"mscorlib",
"UnityEngine",
"UnityEngine.AIModule",
"UnityEngine.ARModule",
"UnityEngine.AccessibilityModule",
"UnityEngine.AnimationModule",
"UnityEngine.AssetBundleModule",
"UnityEngine.AudioModule",
"UnityEngine.BaselibModule",
"UnityEngine.ClothModule",
"UnityEngine.ClusterInputModule",
"UnityEngine.ClusterRendererModule",
"UnityEngine.CoreModule",
"UnityEngine.CrashReportingModule",
"UnityEngine.DirectorModule",
"UnityEngine.FileSystemHttpModule",
"UnityEngine.GameCenterModule",
"UnityEngine.GridModule",
"UnityEngine.HotReloadModule",
"UnityEngine.IMGUIModule",
"UnityEngine.ImageConversionModule",
"UnityEngine.InputModule",
"UnityEngine.JSONSerializeModule",
"UnityEngine.LocalizationModule",
"UnityEngine.ParticleSystemModule",
"UnityEngine.PerformanceReportingModule",
"UnityEngine.PhysicsModule",
"UnityEngine.Physics2DModule",
"UnityEngine.ProfilerModule",
"UnityEngine.ScreenCaptureModule",
"UnityEngine.SharedInternalsModule",
"UnityEngine.SpatialTrackingModule",
"UnityEngine.SpriteMaskModule",
"UnityEngine.SpriteShapeModule",
"UnityEngine.StreamingModule",
"UnityEngine.StyleSheetsModule",
"UnityEngine.SubstanceModule",
"UnityEngine.TLSModule",
"UnityEngine.TerrainModule",
"UnityEngine.TerrainPhysicsModule",
"UnityEngine.TextCoreModule",
"UnityEngine.TextRenderingModule",
"UnityEngine.TilemapModule",
"UnityEngine.TimelineModule",
"UnityEngine.UIModule",
"UnityEngine.UIElementsModule",
"UnityEngine.UNETModule",
"UnityEngine.UmbraModule",
"UnityEngine.UnityAnalyticsModule",
"UnityEngine.UnityConnectModule",
"UnityEngine.UnityTestProtocolModule",
"UnityEngine.UnityWebRequestModule",
"UnityEngine.UnityWebRequestAssetBundleModule",
"UnityEngine.UnityWebRequestAudioModule",
"UnityEngine.UnityWebRequestTextureModule",
"UnityEngine.UnityWebRequestWWWModule",
"UnityEngine.VFXModule",
"UnityEngine.VRModule",
"UnityEngine.VehiclesModule",
"UnityEngine.VideoModule",
"UnityEngine.WindModule",
"UnityEngine.XRModule",
"UnityEditor",
"Unity.Locator",
"System.Core",
"System",
"Mono.Security",
"System.Configuration",
"System.Xml",
"Unity.DataContract",
"Unity.PackageManager",
"UnityEngine.UI",
"UnityEditor.UI",
"UnityEditor.TestRunner",
"UnityEngine.TestRunner",
"nunit.framework",
"UnityEngine.Timeline",
"UnityEditor.Timeline",
"UnityEngine.Networking",
"UnityEditor.Networking",
"UnityEditor.GoogleAudioSpatializer",
"UnityEngine.GoogleAudioSpatializer",
"UnityEditor.SpatialTracking",
"UnityEngine.SpatialTracking",
"UnityEditor.VR",
"UnityEditor.Graphs",
"UnityEditor.WindowsStandalone.Extensions",
"SyntaxTree.VisualStudio.Unity.Bridge",
"Rewired_ControlMapper_CSharp_Editor",
"Rewired_CSharp_Editor",
"Unity.ProBuilder.AddOns.Editor",
"Wwise-Editor",
"Unity.RenderPipelines.Core.Editor",
"Unity.RenderPipelines.Core.Runtime",
"Unity.TextMeshPro.Editor",
"Unity.PackageManagerUI.Editor",
"Rewired_NintendoSwitch_CSharp",
"Unity.Postprocessing.Editor",
"Rewired_CSharp",
"Unity.Postprocessing.Runtime",
"Rewired_NintendoSwitch_CSharp_Editor",
"Wwise",
"Unity.RenderPipelines.Core.ShaderLibrary",
"Unity.TextMeshPro",
"Rewired_UnityUI_CSharp_Editor",
"Facepunch.Steamworks",
"Rewired_Editor",
"Rewired_Core",
"Rewired_Windows_Lib",
"Rewired_NintendoSwitch_Editor",
"Rewired_NintendoSwitch_EditorRuntime",
"Zio",
"AssetIdRemapUtility",
"ProBuilderCore",
"ProBuilderMeshOps",
"KdTreeLib",
"pb_Stl",
"Poly2Tri",
"ProBuilderEditor",
"netstandard",
"System.Xml.Linq",
"Unity.Cecil",
"Unity.SerializationLogic",
"Unity.Legacy.NRefactory",
"ExCSS.Unity",
"Unity.IvyParser",
"UnityEditor.iOS.Extensions.Xcode",
"SyntaxTree.VisualStudio.Unity.Messaging",
"Microsoft.GeneratedCode",
"Anonymously",
"Hosted",
"DynamicMethods",
"Assembly"
};
try {
typeof(SearchableAttribute).GetMethod("Scan", System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Static).Invoke(null,null);
}
catch (Exception ex) {
System.Console.WriteLine(ex.Message);
}
}
private static readonly Dictionary<Type, List<SearchableAttribute>> instancesListsByType;
private static HashSet<string> assemblyBlacklist;
}
}
#pragma warning restore IDE0052 // Remove unread private members
#pragma warning restore IDE1006 // Naming Styles
#pragma warning restore IDE0044 // Add readonly modifier
| 41.484211 | 162 | 0.548592 | [
"MIT"
] | Reinms/R2API | R2API.MonoMod/SearchableAttributeScanFix.cs | 7,884 | C# |
/* Yet Another Forum.NET
* Copyright (C) 2003-2005 Bjørnar Henden
* Copyright (C) 2006-2013 Jaben Cargman
* Copyright (C) 2014-2021 Ingo Herbote
* https://www.yetanotherforum.net/
*
* 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
* https://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
namespace YAF.Configuration
{
using System;
using System.Text;
using System.Web;
using YAF.Types;
using YAF.Types.Constants;
using YAF.Types.Objects;
/// <summary>
/// Class provides helper functions related to the forum path and URLs as well as forum version information.
/// </summary>
public static class BoardInfo
{
/// <summary>
/// Gets the forum path (client-side).
/// May not be the actual URL of the forum.
/// </summary>
public static string ForumClientFileRoot => BaseUrlBuilder.ClientFileRoot;
/// <summary>
/// Gets the forum path (server-side).
/// May not be the actual URL of the forum.
/// </summary>
public static string ForumServerFileRoot => BaseUrlBuilder.ServerFileRoot;
/// <summary>
/// Gets complete application external (client-side) URL of the forum. (e.g. http://domain.com/forum
/// </summary>
public static string ForumBaseUrl => $"{BaseUrlBuilder.BaseUrl}{BaseUrlBuilder.AppPath}";
/// <summary>
/// Gets a value indicating whether this instance is local.
/// </summary>
/// <value>
/// <c>true</c> if this instance is local; otherwise, <c>false</c>.
/// </value>
public static bool IsLocal
{
get
{
var serverName = HttpContext.Current.Request.ServerVariables["SERVER_NAME"];
return serverName != null && serverName.ToLower() == "localhost";
}
}
#region Version Information
/// <summary>
/// Gets the Current YAF Application Version string
/// </summary>
public static string AppVersionName => AppVersionNameFromCode();
/// <summary>
/// Gets the Current YAF Database Version
/// </summary>
public static int AppVersion => 80;
/// <summary>
/// Gets the Current YAF Build Date
/// </summary>
public static DateTime AppVersionDate => new(2021, 08, 15, 04, 55, 00);
/// <summary>
/// Creates a string that is the YAF Application Version from a long value
/// </summary>
/// <returns>
/// Application Version String
/// </returns>
public static string AppVersionNameFromCode()
{
var version = new YafVersion
{
Major = 3,
Minor = 0,
Build = 0,
ReleaseType = ReleaseType.RC,
ReleaseNumber = 2
};
var versionString = new StringBuilder();
versionString.AppendFormat("{0}.{1}.{2}", version.Major, version.Minor, version.Build);
if (version.ReleaseType == ReleaseType.Regular)
{
return versionString.ToString();
}
var number = version.ReleaseNumber >= 1
? version.ReleaseNumber.ToString()
: AppVersionDate.ToString("yyyyMMddHHmm");
versionString.AppendFormat(" {0} {1}", version.ReleaseType.ToString().ToUpper(), number);
return versionString.ToString();
}
#endregion
/// <summary>
/// Helper function that creates the URL to the Content folder.
/// </summary>
/// <param name="resourceName">Name of the resource.</param>
/// <returns>
/// Returns the URL including the Content path
/// </returns>
public static string GetURLToContent([NotNull] string resourceName)
{
CodeContracts.VerifyNotNull(resourceName);
return $"{ForumClientFileRoot}Content/{resourceName}";
}
/// <summary>
/// Helper function that creates the URL to the Content themes folder.
/// </summary>
/// <param name="resourceName">Name of the resource.</param>
/// <returns>
/// Returns the URL including the Content Themes path
/// </returns>
public static string GetURLToContentThemes([NotNull] string resourceName)
{
CodeContracts.VerifyNotNull(resourceName);
return $"{ForumClientFileRoot}Content/Themes/{resourceName}";
}
/// <summary>
/// Helper function that creates the URL to the Scripts folder.
/// </summary>
/// <param name="resourceName">Name of the resource.</param>
/// <returns>
/// Returns the URL including the Scripts path
/// </returns>
public static string GetURLToScripts([NotNull] string resourceName)
{
CodeContracts.VerifyNotNull(resourceName);
return $"{ForumClientFileRoot}Scripts/{resourceName}";
}
}
} | 35.625 | 113 | 0.578279 | [
"Apache-2.0"
] | thecarnie/YAFNET | yafsrc/YAF.Configuration/BoardInfo.cs | 5,821 | C# |
using CodingCompetition.Application.Interfaces;
using CodingCompetition.Application.Models.Competition;
using Microsoft.AspNetCore.Mvc;
using System.Threading.Tasks;
namespace CodingCompetition.Web.Controllers
{
public class CompetitionController : BaseApiController
{
private readonly ICompetitionService _competitionService;
public CompetitionController(ICompetitionService competitionService)
{
_competitionService = competitionService;
}
[HttpPost("RunSolution")]
public async Task<Result> RunSolution(RunRequest request)
{
return await _competitionService.RunSolution(request);
}
[HttpPost("SubmitSolution")]
public async Task<Result> SubmitSolution(SubmitRequest request)
{
return await _competitionService.SubmitSolution(request);
}
}
}
| 26.166667 | 70 | 0.805096 | [
"MIT"
] | andreyturkov/coding-competition | CodingCompetition/CodingCompetition.Web/Controllers/CompetitionController.cs | 787 | C# |
using System;
using System.Collections.Generic;
using System.Text;
public class ISceneState
{
private string mSceneName;
protected SceneStateController mController;
public ISceneState(string sceneName,SceneStateController controller)
{
mSceneName = sceneName;
mController = controller;
}
public string SceneName
{
get { return mSceneName; }
}
//每次进入到这个状态的时候调用
public virtual void StateStart() { }
public virtual void StateEnd() { }
public virtual void StateUpdate(){}
}
| 21.038462 | 72 | 0.687386 | [
"MIT"
] | WithoutUmbrella-Boy/Design-patterns-in-game-development | 源码工程、素材、UML图和笔记/源码工程、素材、UML图和笔记/源码工程和素材/RedAlertProject/RedAlertProject/Assets/Scripts/SceneState/ISceneState.cs | 577 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Pirate.Ldap.Data
{
public enum RequestParameter
{
Invalid = 0,
DeletePersonalData = 1,
DeleteUserAccount = 2
}
}
| 15.266667 | 33 | 0.716157 | [
"MIT"
] | ppschweiz/MemberDatabase | Organigram/Pirate.Ldap/Data/RequestParameter.cs | 231 | C# |
// --------------------------------------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT license.
// --------------------------------------------------------------------------------------------
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Options;
namespace Microsoft.Oryx.Detector
{
/// <summary>
/// Contains extensions to add services to <see cref="IServiceCollection"/>.
/// </summary>
public static class PlatformDetectorServiceCollection
{
/// <summary>
/// Adds services related to detection of platforms.
/// </summary>
/// <param name="services">The <see cref="IServiceCollection"/>.</param>
/// <returns>An instance of <see cref="IServiceCollection"/>.</returns>
public static IServiceCollection AddPlatformDetectorServices(this IServiceCollection services)
{
services.AddSingleton<IDetector, DefaultPlatformDetector>();
services
.AddLogging()
.AddOptions()
.AddDotNetCoreServices()
.AddNodeServices()
.AddPythonServices()
.AddPhpServices()
.AddHugoServices();
return services;
}
}
} | 37.675676 | 103 | 0.515065 | [
"MIT"
] | dbalabka/Oryx | src/Detector/PlatformDetectorServiceCollection.cs | 1,360 | C# |
/*
* Copyright (c) 2021 AoiKamishiro
*
* This code is provided under the MIT license.
*
*/
namespace Kamishiro.UnityEditor.CopyDynamicBones
{
internal static class Translate
{
private const string ContinueEN = "Continue";
private const string ContinueJP = "続行";
private const string CancelEN = "Cancel";
private const string CancelJP = "中止";
}
internal static class URL
{
public const string GIUHUB_REPOS = "https://github.com/AoiKamishiro/UnityCustomEditor_CopyDynamicBones";
public const string GITHUB_RELEASE = "https://github.com/AoiKamishiro/UnityCustomEditor_CopyDynamicBones/releases";
public const string GITHUB_VERCHECK = "https://api.github.com/repos/AoiKamishiro/UnityCustomEditor_CopyDynamicBones/releases/latest";
//public const string BOOTH_PAGE = "https://kamishirolab.booth.pm/items/";
}
internal static class UIText
{
public const string author = "AoiKamishiro";
//public const string
}
} | 34.333333 | 141 | 0.697087 | [
"MIT"
] | AoiKamishiro/UnityCustomEditor_CopyDynamicBones | Assets/00Kamishiro/CopyDynamicBones/Editor/DataStructure.cs | 1,038 | C# |
using FluentValidation;
using SFA.DAS.ProviderCommitments.Web.Models.Apprentice;
namespace SFA.DAS.ProviderCommitments.Web.Validators.Apprentice
{
public class DeleteConfirmationViewModelValidator : AbstractValidator<DeleteConfirmationViewModel>
{
public DeleteConfirmationViewModelValidator()
{
RuleFor(x => x.ProviderId).GreaterThan(0);
RuleFor(x => x.DraftApprenticeshipHashedId).NotEmpty();
RuleFor(x => x.CohortReference).NotEmpty();
RuleFor(x => x.DeleteConfirmed).NotNull().WithMessage("Confirm if you would like to delete this apprentice");
}
}
}
| 37.705882 | 121 | 0.705148 | [
"MIT"
] | SkillsFundingAgency/das-providercommitments | src/SFA.DAS.ProviderCommitments/SFA.DAS.ProviderCommitments.Web/Validators/Apprentice/DeleteConfirmationViewModelValidator.cs | 643 | C# |
using Discord.Net.Converters;
using Newtonsoft.Json;
using System.Linq;
using System;
namespace Discord.Rest
{
/// <summary>
/// Responsible for formatting certain entities as Json <see langword="string"/>, to reuse later on.
/// </summary>
public static class StringExtensions
{
private static Lazy<JsonSerializerSettings> _settings = new(() =>
{
var serializer = new JsonSerializerSettings()
{
ContractResolver = new DiscordContractResolver()
};
serializer.Converters.Add(new EmbedTypeConverter());
return serializer;
});
/// <summary>
/// Gets a Json formatted <see langword="string"/> from an <see cref="EmbedBuilder"/>.
/// </summary>
/// <remarks>
/// See <see cref="EmbedBuilder.TryParse(string, out EmbedBuilder)"/> to parse Json back into embed.
/// </remarks>
/// <param name="builder">The builder to format as Json <see langword="string"/>.</param>
/// <param name="formatting">The formatting in which the Json will be returned.</param>
/// <returns>A Json <see langword="string"/> containing the data from the <paramref name="builder"/>.</returns>
public static string ToJsonString(this EmbedBuilder builder, Formatting formatting = Formatting.Indented)
=> ToJsonString(builder.Build(), formatting);
/// <summary>
/// Gets a Json formatted <see langword="string"/> from an <see cref="Embed"/>.
/// </summary>
/// <remarks>
/// See <see cref="EmbedBuilder.TryParse(string, out EmbedBuilder)"/> to parse Json back into embed.
/// </remarks>
/// <param name="embed">The embed to format as Json <see langword="string"/>.</param>
/// <param name="formatting">The formatting in which the Json will be returned.</param>
/// <returns>A Json <see langword="string"/> containing the data from the <paramref name="embed"/>.</returns>
public static string ToJsonString(this Embed embed, Formatting formatting = Formatting.Indented)
=> JsonConvert.SerializeObject(embed.ToModel(), formatting, _settings.Value);
}
}
| 46.770833 | 119 | 0.622717 | [
"MIT"
] | Misha-133/Discord.Net | src/Discord.Net.Rest/Extensions/StringExtensions.cs | 2,245 | C# |
using Newtonsoft.Json.Linq;
using NUnit.Framework;
using System;
namespace Aqua.Tests
{
[TestFixture]
public sealed class JobFactoryTest
{
private JobFactory factory;
[Test]
public void RegisterJobTypeInputValidation()
{
Assert.Throws(Is.TypeOf<ArgumentNullException>().And.Property("ParamName").EqualTo("jobType"),
() => factory.RegisterJobType(null));
Assert.Throws(Is.TypeOf<ArgumentException>().And.Message.EqualTo("The jobType must implement the IJob interface."),
() => factory.RegisterJobType(typeof(JobFactoryTest)));
Assert.Throws(Is.TypeOf<ArgumentNullException>().And.Property("ParamName").EqualTo("jobName"),
() => factory.RegisterJobType(null, null));
Assert.Throws(Is.TypeOf<ArgumentNullException>().And.Property("ParamName").EqualTo("jobName"),
() => factory.RegisterJobType(String.Empty, null));
Assert.Throws(Is.TypeOf<ArgumentNullException>().And.Property("ParamName").EqualTo("jobName"),
() => factory.RegisterJobType(" ", null));
Assert.Throws(Is.TypeOf<ArgumentNullException>().And.Property("ParamName").EqualTo("jobType"),
() => factory.RegisterJobType("Blah", null));
Assert.Throws(Is.TypeOf<ArgumentException>().And.Message.EqualTo("The jobType must implement the IJob interface."),
() => factory.RegisterJobType("Blah", typeof(JobFactoryTest)));
}
[Test]
public void RegisterJobWithDifferentName()
{
factory.RegisterJobType("ThisIsAlsoHelloWorld", typeof(HelloWho));
JobDescriptor desc;
JToken token;
IJob job;
HelloWho helloJob;
// Create a descriptor and test it.
desc = factory.CreateDescriptor(new HelloWho() { Who = "RegisterJobWithDifferentName" });
Assert.That(desc.Job, Is.EqualTo("ThisIsAlsoHelloWorld"));
Assert.That(desc.Properties, Is.Not.Null.And.Count.EqualTo(1));
Assert.That(desc.Properties.TryGetValue("Who", out token), Is.True);
Assert.That(token, Is.TypeOf<JValue>().And.Property("Type").EqualTo(JTokenType.String));
Assert.That(token.ToObject<string>(), Is.EqualTo("RegisterJobWithDifferentName"));
// Use the descriptor to create a job, and test it.
job = factory.CreateJob(desc);
Assert.That(job, Is.Not.Null);
Assert.That(job, Is.InstanceOf<HelloWho>());
helloJob = (HelloWho)job;
Assert.That(helloJob.Who, Is.EqualTo("RegisterJobWithDifferentName"));
// Now use the descriptor with the original name to create a job, and test it.
desc.Job = "HelloWho";
job = factory.CreateJob(desc);
Assert.That(job, Is.Not.Null);
Assert.That(job, Is.InstanceOf<HelloWho>());
helloJob = (HelloWho)job;
Assert.That(helloJob.Who, Is.EqualTo("RegisterJobWithDifferentName"));
}
[Test]
public void CreateJobInputValidation()
{
Assert.Throws(Is.TypeOf<ArgumentNullException>().And.Property("ParamName").EqualTo("descriptor"),
() => factory.CreateJob(null));
}
[Test]
public void CreateDescriptorInputValidation()
{
Assert.Throws(Is.TypeOf<ArgumentNullException>().And.Property("ParamName").EqualTo("job"),
() => factory.CreateDescriptor(null));
Assert.Throws(Is.TypeOf<UnknownJobException>().And.Property("MessageId").Null
.And.Property("JobName").EqualTo("UnknownJob"),
() => factory.CreateDescriptor(new UnknownJob()));
}
[Test]
public void CreateDescriptor()
{
JobDescriptor desc;
JToken token;
// Property with value.
desc = factory.CreateDescriptor(new HelloWho() { Who = "CreateDescriptor" });
Assert.That(desc, Is.Not.Null);
Assert.That(desc.Job, Is.EqualTo("HelloWho"));
Assert.That(desc.Properties, Is.Not.Null.And.Count.EqualTo(1));
Assert.That(desc.Properties.TryGetValue("Who", out token), Is.True);
Assert.That(token, Is.TypeOf<JValue>().And.Property("Type").EqualTo(JTokenType.String));
Assert.That(token.ToObject<string>(), Is.EqualTo("CreateDescriptor"));
Assert.That(desc.QueueMessageId, Is.Null);
// Property with null value.
desc = factory.CreateDescriptor(new HelloWho() { Who = null });
Assert.That(desc, Is.Not.Null);
Assert.That(desc.Job, Is.EqualTo("HelloWho"));
Assert.That(desc.Properties, Is.Not.Null.And.Count.EqualTo(1));
Assert.That(desc.Properties.TryGetValue("Who", out token), Is.True);
Assert.That(token, Is.TypeOf<JValue>().And.Property("Type").EqualTo(JTokenType.Null));
Assert.That(token.ToObject<string>(), Is.Null);
Assert.That(desc.QueueMessageId, Is.Null);
// Job with no properties.
desc = factory.CreateDescriptor(new NoopJob());
Assert.That(desc, Is.Not.Null);
Assert.That(desc.Job, Is.EqualTo("NoopJob"));
Assert.That(desc.Properties, Is.Null);
Assert.That(desc.QueueMessageId, Is.Null);
// Job with value-type properties.
Guid guid = Guid.NewGuid();
desc = factory.CreateDescriptor(new MockJob() { Id = guid, Int32 = 123, });
Assert.That(desc, Is.Not.Null);
Assert.That(desc.Job, Is.EqualTo("MockJob"));
Assert.That(desc.Properties, Is.Not.Null.And.Count.EqualTo(2));
Assert.That(desc.Properties.TryGetValue("Id", out token), Is.True);
Assert.That(token, Is.TypeOf<JValue>().And.Property("Type").EqualTo(JTokenType.Guid));
Assert.That(token.ToObject<Guid>(), Is.EqualTo(guid));
Assert.That(desc.Properties.TryGetValue("Int32", out token), Is.True);
Assert.That(token, Is.TypeOf<JValue>().And.Property("Type").EqualTo(JTokenType.Integer));
Assert.That(token.ToObject<Int32>(), Is.EqualTo(123));
Assert.That(desc.QueueMessageId, Is.Null);
}
[Test]
public void Roundtrip()
{
MockJob job = new MockJob() { Id = Guid.NewGuid(), Int32 = 987 };
JobDescriptor desc = factory.CreateDescriptor(job);
JToken token;
Assert.That(desc, Is.Not.Null);
Assert.That(desc.Job, Is.EqualTo("MockJob"));
Assert.That(desc.Properties, Is.Not.Null.And.Count.EqualTo(2));
Assert.That(desc.Properties.TryGetValue("Id", out token), Is.True);
Assert.That(token, Is.TypeOf<JValue>().And.Property("Type").EqualTo(JTokenType.Guid));
Assert.That(token.ToObject<Guid>(), Is.EqualTo(job.Id));
Assert.That(desc.Properties.TryGetValue("Int32", out token), Is.True);
Assert.That(token, Is.TypeOf<JValue>().And.Property("Type").EqualTo(JTokenType.Integer));
Assert.That(token.ToObject<Int32>(), Is.EqualTo(987));
Assert.That(desc.QueueMessageId, Is.Null);
IJob job2 = factory.CreateJob(desc);
Assert.That(job2, Is.Not.Null.And.TypeOf<MockJob>());
MockJob mockJob2 = (MockJob)job2;
Assert.That(mockJob2.Id, Is.EqualTo(job.Id));
}
[SetUp]
public void Setup()
{
factory = new JobFactory();
factory.RegisterJobType(typeof(HelloWho));
factory.RegisterJobType(typeof(MockJob));
factory.RegisterJobType(typeof(NoopJob));
}
}
}
| 45.456647 | 127 | 0.599949 | [
"Apache-2.0"
] | rokeller/aqua | src/AzureQueueAgentLib.Tests/JobFactoryTest.cs | 7,866 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using Newtonsoft.Json;
using UnityEngine;
namespace LordAshes
{
public static class ReflectionObjectManipulator
{
public static bool showDiagnostics {get; set;} = false;
public static void BuildObjectsFromFile(ref Dictionary<string, object> target, string filename)
{
string[] contents = (System.IO.File.ReadAllText(filename)+"[]").Replace("\r","").Replace("\n","").Split(';');
List<string> pokes = new List<string>();
int pointer = 0;
string content = "";
while (pointer < contents.Length)
{
if (contents[pointer].Trim().StartsWith("//") || contents[pointer].Trim().StartsWith("#") || contents[pointer].Trim().StartsWith("'") || contents[pointer].Trim()=="")
{
// Skip Comment
}
else if (contents[pointer].StartsWith("["))
{
// Geneate Last Object
if (content != "")
{
string line = content.Replace("[", "").Replace("]", "");
string[] parts = line.Split(':');
// Create Corresponding Object
object obj = CreateObject(parts[1].Trim());
// Transfer Properties
pokes.Add(".name=" + parts[0].Trim());
Transfer(obj, pokes.ToArray());
// Add Object To Dictionary
target.Add(parts[0].Trim(), obj);
}
// Store Header For New Object
content = contents[pointer];
pokes.Clear();
}
else
{
// Add Entry To Current Object
pokes.Add(contents[pointer]);
}
pointer++;
}
}
public static void Transfer(object target, string[] pokes)
{
foreach (string poke in pokes)
{
try
{
if (poke.Trim() != "" && !poke.Trim().StartsWith("//") && !poke.Trim().StartsWith("#") && !poke.Trim().StartsWith("'"))
{
string[] kvp = null;
bool setProp = true;
// Set Property
if (poke.Contains("="))
{
// Set property with value
kvp = new string[] { poke.Substring(0, poke.IndexOf("=")).Trim(), poke.Substring(poke.IndexOf("=") + 1).Trim() };
setProp = true;
}
else
{
// Set property with new instance of specified class
kvp = new string[] { poke.Substring(0, poke.IndexOf(":")).Trim(), poke.Substring(poke.IndexOf(":") + 1).Trim() };
setProp = false;
}
string[] parts = kvp[0].Split('.');
object victim = target;
// Traverse object properties
for (int i = 1; i < parts.Length - 1; i++)
{
if (parts[i].StartsWith("{["))
{
// Traverse component by name
parts[i] = parts[i].Replace("{[", "").Replace("]}", "");
if (showDiagnostics) { Debug.Log("Light Plugin: Traversing From " + Convert.ToString(victim) + " To Component With Name " + parts[i]); }
foreach (Component comp in ((GameObject)victim).GetComponents<Component>())
{
if (comp.name == parts[i]) { victim = comp; break; }
}
}
else if (parts[i].StartsWith("{Child["))
{
// Traverse Transform's Children
parts[i] = parts[i].Replace("{Child[", "").Replace("]}", "");
if (showDiagnostics) { Debug.Log("Light Plugin: Tranversing From " + Convert.ToString(victim) + " To Child " + parts[i]); }
victim = ((Transform)victim).GetChild(int.Parse(parts[i]));
}
else if (parts[i].StartsWith("{"))
{
// Traverse component by type
parts[i] = parts[i].Replace("{", "").Replace("}", "");
if (showDiagnostics) { Debug.Log("Light Plugin: Tranversing From " + Convert.ToString(victim) + " To Component Of Type " + parts[i]); }
int index = 0;
if (parts[i].EndsWith("]"))
{
parts[i] = parts[i].Substring(0, parts[i].Length - 1);
index = int.Parse(parts[i].Substring(parts[i].LastIndexOf("[") + 1));
parts[i] = parts[i].Substring(0, parts[i].LastIndexOf("["));
}
List<Component> matches = new List<Component>();
foreach (Component comp in ((GameObject)victim).GetComponents<Component>())
{
if (comp.GetType().ToString().EndsWith(parts[i])) { matches.Add(comp); }
if (matches.Count > index) { break; }
}
if (matches.Count > index) { victim = matches[index]; }
}
else
{
// Traverse property
int index = -1;
if (parts[i].EndsWith("]"))
{
parts[i] = parts[i].Substring(0, parts[i].Length - 1);
index = int.Parse(parts[i].Substring(parts[i].LastIndexOf("[") + 1));
parts[i] = parts[i].Substring(0, parts[i].LastIndexOf("["));
}
PropertyInfo pr = victim.GetType().GetProperty(parts[i]);
if (pr != null)
{
if (showDiagnostics) { Debug.Log("Light Plugin: Traversing From " + Convert.ToString(victim) + " To Property " + parts[i]); }
victim = pr.GetValue(victim);
if (index > -1)
{
if (victim != null)
{
if (showDiagnostics) { Debug.Log("Light Plugin: Traversing From " + Convert.ToString(victim) + " To Property " + parts[i] + " Element " + index + " (of " + ((object[])victim).Length + ")"); }
victim = ((object[])victim)[index];
}
else
{
Debug.LogWarning("Light Plugin: Traversing From " + Convert.ToString(victim) + " To Property " + parts[i] + " Value Is Null");
}
}
}
else
{
Debug.LogWarning("Light Plugin: Traversing From " + Convert.ToString(victim) + " To Property " + parts[i] + " Is Null");
}
}
}
// Get property
int element = -1;
if (parts[parts.Length - 1].EndsWith("]"))
{
parts[parts.Length - 1] = parts[parts.Length - 1].Substring(0, parts[parts.Length - 1].Length - 1);
element = int.Parse(parts[parts.Length - 1].Substring(parts[parts.Length - 1].LastIndexOf("[") + 1));
parts[parts.Length - 1] = parts[parts.Length - 1].Substring(0, parts[parts.Length - 1].LastIndexOf("["));
}
PropertyInfo prop = victim.GetType().GetProperty(parts[parts.Length - 1]);
if (prop == null)
{
Debug.LogWarning("Light Plugin: Property '" + parts[parts.Length - 1]+"' not found. Valid properties are:");
foreach (PropertyInfo pr in victim.GetType().GetProperties())
{
Debug.LogWarning("Light Plugin: Property " + pr.Name + " : " + pr.PropertyType);
}
}
// Determine type
object value = null;
if (!setProp)
{
// Value is specified type instance
value = CreateObject(kvp[1]);
}
else if (prop.PropertyType != typeof(String))
{
// Value is converted from JSON string
object subObj = Activator.CreateInstance(prop.PropertyType);
MethodInfo mi = typeof(ReflectionObjectManipulator).GetMethod("ConvertType");
var typeRef = mi.MakeGenericMethod(prop.PropertyType);
value = typeRef.Invoke(null, new object[] { kvp[1] });
}
else
{
// Value is string
value = kvp[1];
}
// Set Property
if (element > -1)
{
// Process array element set
Debug.Log("Light Plugin: Setting Object " + Convert.ToString(victim) + " Property " + prop.Name + " Element " + element + " (" + prop.PropertyType + ") To " + Convert.ToString(value));
victim = victim.GetType().GetProperty(parts[parts.Length - 1]).GetValue(victim);
((Array)victim).SetValue(value, element);
}
else
{
// Check non-array set
Debug.Log("Light Plugin: Setting Object " + Convert.ToString(victim) + " Property " + prop.Name + " (" + prop.PropertyType + ") To " + Convert.ToString(value));
prop.SetValue(victim, value);
}
}
}
catch (Exception x) { Debug.LogWarning("Light Plugin: Unabled To Process '" + poke + "'"); Debug.LogWarning("Light Plugin: " + x); }
}
}
public static object CreateObject(string classType)
{
List<Type> types = new List<Type>();
try { types.AddRange(Assembly.GetCallingAssembly().GetTypes()); } catch (Exception) {; }
try { types.AddRange(Assembly.GetEntryAssembly().GetTypes()); } catch (Exception) {; }
try { types.AddRange(Assembly.GetExecutingAssembly().GetTypes()); } catch (Exception) {; }
foreach (System.Reflection.AssemblyName an in System.Reflection.Assembly.GetExecutingAssembly().GetReferencedAssemblies())
{
try
{
System.Reflection.Assembly asm = System.Reflection.Assembly.Load(an.ToString());
types.AddRange(asm.GetTypes());
}
catch (Exception) {; }
}
foreach (Type type in types)
{
if (type.Name == classType)
{
return Activator.CreateInstance(type);
}
}
Debug.LogWarning("Light Plugin: Didn't Find A Match For Type " + classType);
return null;
}
public static T ConvertType<T>(object value)
{
if (showDiagnostics) { Debug.Log("Light Plugin: Converting " + Convert.ToString(value) + " To " + typeof(T).ToString()); }
if (typeof(T) == typeof(UnityEngine.Color))
{
string[] parts = value.ToString().Split(',');
object c = null;
if (parts.Length == 3)
{
c = new UnityEngine.Color(float.Parse(parts[0]), float.Parse(parts[1]), float.Parse(parts[2]));
}
else if (parts.Length == 3)
{
c = new UnityEngine.Color(float.Parse(parts[0]), float.Parse(parts[1]), float.Parse(parts[2]), float.Parse(parts[3]));
}
return (T)c;
}
if (typeof(T) == typeof(UnityEngine.Vector3))
{
string[] parts = value.ToString().Split(',');
object v3 = new UnityEngine.Vector3(float.Parse(parts[0]), float.Parse(parts[1]), float.Parse(parts[2]));
return (T)v3;
}
if (typeof(T) == typeof(System.Boolean))
{
object b = false;
if((Convert.ToString(value)=="True") || (Convert.ToString(value) == "true") || (Convert.ToString(value) == "1") || (Convert.ToString(value) == "-1")) { b = true; }
return (T)b;
}
return JsonConvert.DeserializeObject<T>(value.ToString());
}
}
}
| 53.151079 | 236 | 0.395506 | [
"MIT"
] | LordAshes/TaleSpire-CustomMiniPlugin | TaleSpireContentPlugin/ReflectionObjectManipulator.cs | 14,778 | C# |
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using Npgsql;
namespace Discount.Grpc.Extensions
{
public static class HostExtension
{
public static IHost MigrateDatabase<TContext>(this IHost host, int? retry = 0)
{
int retryForAvailability = retry.Value;
using (var scope = host.Services.CreateScope())
{
var services = scope.ServiceProvider;
var configuration = services.GetRequiredService<IConfiguration>();
var logger = services.GetRequiredService<ILogger<TContext>>();
try
{
logger.LogInformation("Migrating postresql database.");
using var connection = new NpgsqlConnection
(configuration.GetValue<string>("DatabaseSettings:ConnectionString"));
connection.Open();
using var command = new NpgsqlCommand
{
Connection = connection
};
command.CommandText = "DROP TABLE IF EXISTS Coupon";
command.ExecuteNonQuery();
command.CommandText = @"CREATE TABLE Coupon(Id SERIAL PRIMARY KEY,
ProductName VARCHAR(24) NOT NULL,
Description TEXT,
Amount INT)";
command.ExecuteNonQuery();
command.CommandText = "INSERT INTO Coupon(ProductName, Description, Amount) VALUES('IPhone X', 'IPhone Discount', 150);";
command.ExecuteNonQuery();
command.CommandText = "INSERT INTO Coupon(ProductName, Description, Amount) VALUES('Samsung 10', 'Samsung Discount', 100);";
command.ExecuteNonQuery();
logger.LogInformation("Migrated postresql database.");
}
catch(NpgsqlException ex)
{
logger.LogError(ex, "An error occurred while migrating the postresql database");
if (retryForAvailability < 50)
{
retryForAvailability++;
System.Threading.Thread.Sleep(2000);
MigrateDatabase<TContext>(host, retryForAvailability);
}
}
}
return host;
}
}
}
| 39.955224 | 144 | 0.513635 | [
"MIT"
] | nagendra571/AspnetMicroservices | src/Services/Discount/Discount.Grpc/Extensions/HostExtension.cs | 2,679 | C# |
using System.Windows;
namespace Prism.Services.Dialogs.DefaultDialogs
{
/// <summary>
/// Interaction logic for DialogWindow.xaml
/// </summary>
public partial class DialogWindow : Window, IDialogWindow
{
public IDialogResult Result { get; set; }
public DialogWindow()
{
InitializeComponent();
}
}
}
| 20.611111 | 61 | 0.61186 | [
"MIT"
] | Pavel-Sulimau/Prism | Source/Wpf/Prism.Wpf/Services/Dialogs/DefaultDialogs/DialogWindow.xaml.cs | 373 | C# |
using System;
using System.Collections.Generic;
namespace Elders.Cronus.MessageProcessing
{
public interface ISubscriberFinder<T>
{
IEnumerable<Type> Find();
}
}
| 16.727273 | 41 | 0.706522 | [
"Apache-2.0"
] | Elders/Cronus | src/Elders.Cronus/MessageProcessing/ISubscriberFinder.cs | 186 | C# |
using UnityEngine;
public class CameraFollow : MonoBehaviour
{
[SerializeField]
private GameObject _follow;
private Vector3 _offset;
private void Start()
{
_offset = transform.position - _follow.transform.position;
}
private void Update()
{
transform.position = _offset + _follow.transform.position;
}
} | 18.947368 | 66 | 0.666667 | [
"MIT"
] | Xwilarg/ZeroHourGameJam | Assets/Scripts/CameraFollow.cs | 362 | 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 System.Collections.Generic;
using Aliyun.Acs.Core;
namespace Aliyun.Acs.Sas.Model.V20181203
{
public class OperateSuspiciousTargetConfigResponse : AcsResponse
{
private string requestId;
public string RequestId
{
get
{
return requestId;
}
set
{
requestId = value;
}
}
}
}
| 26.651163 | 66 | 0.720768 | [
"Apache-2.0"
] | AxiosCros/aliyun-openapi-net-sdk | aliyun-net-sdk-sas/Sas/Model/V20181203/OperateSuspiciousTargetConfigResponse.cs | 1,146 | 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 CompanySalesInvoicesCollectionRequest.
/// </summary>
public partial class CompanySalesInvoicesCollectionRequest : BaseRequest, ICompanySalesInvoicesCollectionRequest
{
/// <summary>
/// Constructs a new CompanySalesInvoicesCollectionRequest.
/// </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 CompanySalesInvoicesCollectionRequest(
string requestUrl,
IBaseClient client,
IEnumerable<Option> options)
: base(requestUrl, client, options)
{
}
/// <summary>
/// Adds the specified SalesInvoice to the collection via POST.
/// </summary>
/// <param name="salesInvoice">The SalesInvoice to add.</param>
/// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param>
/// <returns>The created SalesInvoice.</returns>
public System.Threading.Tasks.Task<SalesInvoice> AddAsync(SalesInvoice salesInvoice, CancellationToken cancellationToken = default)
{
this.ContentType = CoreConstants.MimeTypeNames.Application.Json;
this.Method = HttpMethods.POST;
return this.SendAsync<SalesInvoice>(salesInvoice, cancellationToken);
}
/// <summary>
/// Adds the specified SalesInvoice to the collection via POST and returns a <see cref="GraphResponse{SalesInvoice}"/> object of the request.
/// </summary>
/// <param name="salesInvoice">The SalesInvoice to add.</param>
/// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param>
/// <returns>The <see cref="GraphResponse{SalesInvoice}"/> object of the request.</returns>
public System.Threading.Tasks.Task<GraphResponse<SalesInvoice>> AddResponseAsync(SalesInvoice salesInvoice, CancellationToken cancellationToken = default)
{
this.ContentType = CoreConstants.MimeTypeNames.Application.Json;
this.Method = HttpMethods.POST;
return this.SendAsyncWithGraphResponse<SalesInvoice>(salesInvoice, 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<ICompanySalesInvoicesCollectionPage> GetAsync(CancellationToken cancellationToken = default)
{
this.Method = HttpMethods.GET;
var response = await this.SendAsync<CompanySalesInvoicesCollectionResponse>(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{CompanySalesInvoicesCollectionResponse}"/> object.
/// </summary>
/// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param>
/// <returns>The <see cref="GraphResponse{CompanySalesInvoicesCollectionResponse}"/> object.</returns>
public System.Threading.Tasks.Task<GraphResponse<CompanySalesInvoicesCollectionResponse>> GetResponseAsync(CancellationToken cancellationToken = default)
{
this.Method = HttpMethods.GET;
return this.SendAsyncWithGraphResponse<CompanySalesInvoicesCollectionResponse>(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 ICompanySalesInvoicesCollectionRequest 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 ICompanySalesInvoicesCollectionRequest Expand(Expression<Func<SalesInvoice, 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 ICompanySalesInvoicesCollectionRequest 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 ICompanySalesInvoicesCollectionRequest Select(Expression<Func<SalesInvoice, 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 ICompanySalesInvoicesCollectionRequest 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 ICompanySalesInvoicesCollectionRequest 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 ICompanySalesInvoicesCollectionRequest 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 ICompanySalesInvoicesCollectionRequest OrderBy(string value)
{
this.QueryOptions.Add(new QueryOption("$orderby", value));
return this;
}
}
}
| 44.014354 | 162 | 0.610501 | [
"MIT"
] | ScriptBox99/msgraph-beta-sdk-dotnet | src/Microsoft.Graph/Generated/requests/CompanySalesInvoicesCollectionRequest.cs | 9,199 | C# |
/*
* QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals.
* Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect Corporation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using System;
using System.Collections;
using System.Collections.Generic;
namespace QuantConnect.Data.Market
{
/// <summary>
/// Provides a base class for types holding base data instances keyed by symbol
/// </summary>
public class DataDictionary<T> : IDictionary<Symbol, T>
{
// storage for the data
private readonly IDictionary<Symbol, T> _data = new Dictionary<Symbol, T>();
/// <summary>
/// Initializes a new instance of the <see cref="QuantConnect.Data.Market.DataDictionary{T}"/> class.
/// </summary>
public DataDictionary()
{
}
/// <summary>
/// Initializes a new instance of the <see cref="QuantConnect.Data.Market.DataDictionary{T}"/> class
/// using the specified <paramref name="data"/> as a data source
/// </summary>
/// <param name="data">The data source for this data dictionary</param>
/// <param name="keySelector">Delegate used to select a key from the value</param>
public DataDictionary(IEnumerable<T> data, Func<T, Symbol> keySelector)
{
foreach (var datum in data)
{
this[keySelector(datum)] = datum;
}
}
/// <summary>
/// Initializes a new instance of the <see cref="QuantConnect.Data.Market.DataDictionary{T}"/> class.
/// </summary>
/// <param name="time">The time this data was emitted.</param>
public DataDictionary(DateTime time)
{
#pragma warning disable 618 // This assignment is left here until the Time property is removed.
Time = time;
#pragma warning restore 618
}
/// <summary>
/// Gets or sets the time associated with this collection of data
/// </summary>
[Obsolete("The DataDictionary<T> Time property is now obsolete. All algorithms should use algorithm.Time instead.")]
public DateTime Time { get; set; }
/// <summary>
/// Returns an enumerator that iterates through the collection.
/// </summary>
/// <returns>
/// A <see cref="T:System.Collections.Generic.IEnumerator`1"/> that can be used to iterate through the collection.
/// </returns>
/// <filterpriority>1</filterpriority>
public IEnumerator<KeyValuePair<Symbol, T>> GetEnumerator()
{
return _data.GetEnumerator();
}
/// <summary>
/// Returns an enumerator that iterates through a collection.
/// </summary>
/// <returns>
/// An <see cref="T:System.Collections.IEnumerator"/> object that can be used to iterate through the collection.
/// </returns>
/// <filterpriority>2</filterpriority>
IEnumerator IEnumerable.GetEnumerator()
{
return ((IEnumerable) _data).GetEnumerator();
}
/// <summary>
/// Adds an item to the <see cref="T:System.Collections.Generic.ICollection`1"/>.
/// </summary>
/// <param name="item">The object to add to the <see cref="T:System.Collections.Generic.ICollection`1"/>.</param><exception cref="T:System.NotSupportedException">The <see cref="T:System.Collections.Generic.ICollection`1"/> is read-only.</exception>
public void Add(KeyValuePair<Symbol, T> item)
{
_data.Add(item);
}
/// <summary>
/// Removes all items from the <see cref="T:System.Collections.Generic.ICollection`1"/>.
/// </summary>
/// <exception cref="T:System.NotSupportedException">The <see cref="T:System.Collections.Generic.ICollection`1"/> is read-only. </exception>
public void Clear()
{
_data.Clear();
}
/// <summary>
/// Determines whether the <see cref="T:System.Collections.Generic.ICollection`1"/> contains a specific value.
/// </summary>
/// <returns>
/// true if <paramref name="item"/> is found in the <see cref="T:System.Collections.Generic.ICollection`1"/>; otherwise, false.
/// </returns>
/// <param name="item">The object to locate in the <see cref="T:System.Collections.Generic.ICollection`1"/>.</param>
public bool Contains(KeyValuePair<Symbol, T> item)
{
return _data.Contains(item);
}
/// <summary>
/// Copies the elements of the <see cref="T:System.Collections.Generic.ICollection`1"/> to an <see cref="T:System.Array"/>, starting at a particular <see cref="T:System.Array"/> index.
/// </summary>
/// <param name="array">The one-dimensional <see cref="T:System.Array"/> that is the destination of the elements copied from <see cref="T:System.Collections.Generic.ICollection`1"/>. The <see cref="T:System.Array"/> must have zero-based indexing.</param><param name="arrayIndex">The zero-based index in <paramref name="array"/> at which copying begins.</param><exception cref="T:System.ArgumentNullException"><paramref name="array"/> is null.</exception><exception cref="T:System.ArgumentOutOfRangeException"><paramref name="arrayIndex"/> is less than 0.</exception><exception cref="T:System.ArgumentException">The number of elements in the source <see cref="T:System.Collections.Generic.ICollection`1"/> is greater than the available space from <paramref name="arrayIndex"/> to the end of the destination <paramref name="array"/>.</exception>
public void CopyTo(KeyValuePair<Symbol, T>[] array, int arrayIndex)
{
_data.CopyTo(array, arrayIndex);
}
/// <summary>
/// Removes the first occurrence of a specific object from the <see cref="T:System.Collections.Generic.ICollection`1"/>.
/// </summary>
/// <returns>
/// true if <paramref name="item"/> was successfully removed from the <see cref="T:System.Collections.Generic.ICollection`1"/>; otherwise, false. This method also returns false if <paramref name="item"/> is not found in the original <see cref="T:System.Collections.Generic.ICollection`1"/>.
/// </returns>
/// <param name="item">The object to remove from the <see cref="T:System.Collections.Generic.ICollection`1"/>.</param><exception cref="T:System.NotSupportedException">The <see cref="T:System.Collections.Generic.ICollection`1"/> is read-only.</exception>
public bool Remove(KeyValuePair<Symbol, T> item)
{
return _data.Remove(item);
}
/// <summary>
/// Gets the number of elements contained in the <see cref="T:System.Collections.Generic.ICollection`1"/>.
/// </summary>
/// <returns>
/// The number of elements contained in the <see cref="T:System.Collections.Generic.ICollection`1"/>.
/// </returns>
public int Count
{
get { return _data.Count; }
}
/// <summary>
/// Gets a value indicating whether the <see cref="T:System.Collections.Generic.ICollection`1"/> is read-only.
/// </summary>
/// <returns>
/// true if the <see cref="T:System.Collections.Generic.ICollection`1"/> is read-only; otherwise, false.
/// </returns>
public bool IsReadOnly
{
get { return _data.IsReadOnly; }
}
/// <summary>
/// Determines whether the <see cref="T:System.Collections.Generic.IDictionary`2"/> contains an element with the specified key.
/// </summary>
/// <returns>
/// true if the <see cref="T:System.Collections.Generic.IDictionary`2"/> contains an element with the key; otherwise, false.
/// </returns>
/// <param name="key">The key to locate in the <see cref="T:System.Collections.Generic.IDictionary`2"/>.</param><exception cref="T:System.ArgumentNullException"><paramref name="key"/> is null.</exception>
public bool ContainsKey(Symbol key)
{
return _data.ContainsKey(key);
}
/// <summary>
/// Adds an element with the provided key and value to the <see cref="T:System.Collections.Generic.IDictionary`2"/>.
/// </summary>
/// <param name="key">The object to use as the key of the element to add.</param><param name="value">The object to use as the value of the element to add.</param><exception cref="T:System.ArgumentNullException"><paramref name="key"/> is null.</exception><exception cref="T:System.ArgumentException">An element with the same key already exists in the <see cref="T:System.Collections.Generic.IDictionary`2"/>.</exception><exception cref="T:System.NotSupportedException">The <see cref="T:System.Collections.Generic.IDictionary`2"/> is read-only.</exception>
public void Add(Symbol key, T value)
{
_data.Add(key, value);
}
/// <summary>
/// Removes the element with the specified key from the <see cref="T:System.Collections.Generic.IDictionary`2"/>.
/// </summary>
/// <returns>
/// true if the element is successfully removed; otherwise, false. This method also returns false if <paramref name="key"/> was not found in the original <see cref="T:System.Collections.Generic.IDictionary`2"/>.
/// </returns>
/// <param name="key">The key of the element to remove.</param><exception cref="T:System.ArgumentNullException"><paramref name="key"/> is null.</exception><exception cref="T:System.NotSupportedException">The <see cref="T:System.Collections.Generic.IDictionary`2"/> is read-only.</exception>
public bool Remove(Symbol key)
{
return _data.Remove(key);
}
/// <summary>
/// Gets the value associated with the specified key.
/// </summary>
/// <returns>
/// true if the object that implements <see cref="T:System.Collections.Generic.IDictionary`2"/> contains an element with the specified key; otherwise, false.
/// </returns>
/// <param name="key">The key whose value to get.</param><param name="value">When this method returns, the value associated with the specified key, if the key is found; otherwise, the default value for the type of the <paramref name="value"/> parameter. This parameter is passed uninitialized.</param><exception cref="T:System.ArgumentNullException"><paramref name="key"/> is null.</exception>
public bool TryGetValue(Symbol key, out T value)
{
return _data.TryGetValue(key, out value);
}
/// <summary>
/// Gets or sets the element with the specified key.
/// </summary>
/// <returns>
/// The element with the specified key.
/// </returns>
/// <param name="symbol">The key of the element to get or set.</param>
/// <exception cref="T:System.ArgumentNullException"><paramref name="symbol"/> is null.</exception>
/// <exception cref="T:System.Collections.Generic.KeyNotFoundException">The property is retrieved and <paramref name="symbol"/> is not found.</exception>
/// <exception cref="T:System.NotSupportedException">The property is set and the <see cref="T:System.Collections.Generic.IDictionary`2"/> is read-only.</exception>
public T this[Symbol symbol]
{
get
{
T data;
if (TryGetValue(symbol, out data))
{
return data;
}
throw new KeyNotFoundException($"'{symbol}' wasn't found in the {GetType().GetBetterTypeName()} object, likely because there was no-data at this moment in time and it wasn't possible to fillforward historical data. Please check the data exists before accessing it with data.ContainsKey(\"{symbol}\")");
}
set
{
_data[symbol] = value;
}
}
/// <summary>
/// Gets or sets the element with the specified key.
/// </summary>
/// <returns>
/// The element with the specified key.
/// </returns>
/// <param name="ticker">The key of the element to get or set.</param>
/// <exception cref="T:System.ArgumentNullException"><paramref name="ticker"/> is null.</exception>
/// <exception cref="T:System.Collections.Generic.KeyNotFoundException">The property is retrieved and <paramref name="ticker"/> is not found.</exception>
/// <exception cref="T:System.NotSupportedException">The property is set and the <see cref="T:System.Collections.Generic.IDictionary`2"/> is read-only.</exception>
public T this[string ticker]
{
get
{
Symbol symbol;
if (!SymbolCache.TryGetSymbol(ticker, out symbol))
{
throw new KeyNotFoundException($"'{ticker}' wasn't found in the {GetType().GetBetterTypeName()} object, likely because there was no-data at this moment in time and it wasn't possible to fillforward historical data. Please check the data exists before accessing it with data.ContainsKey(\"{ticker}\")");
}
return this[symbol];
}
set
{
Symbol symbol;
if (!SymbolCache.TryGetSymbol(ticker, out symbol))
{
throw new KeyNotFoundException($"'{ticker}' wasn't found in the {GetType().GetBetterTypeName()} object, likely because there was no-data at this moment in time and it wasn't possible to fillforward historical data. Please check the data exists before accessing it with data.ContainsKey(\"{ticker}\")");
}
this[symbol] = value;
}
}
/// <summary>
/// Gets an <see cref="T:System.Collections.Generic.ICollection`1"/> containing the keys of the <see cref="T:System.Collections.Generic.IDictionary`2"/>.
/// </summary>
/// <returns>
/// An <see cref="T:System.Collections.Generic.ICollection`1"/> containing the keys of the object that implements <see cref="T:System.Collections.Generic.IDictionary`2"/>.
/// </returns>
public ICollection<Symbol> Keys
{
get { return _data.Keys; }
}
/// <summary>
/// Gets an <see cref="T:System.Collections.Generic.ICollection`1"/> containing the values in the <see cref="T:System.Collections.Generic.IDictionary`2"/>.
/// </summary>
/// <returns>
/// An <see cref="T:System.Collections.Generic.ICollection`1"/> containing the values in the object that implements <see cref="T:System.Collections.Generic.IDictionary`2"/>.
/// </returns>
public ICollection<T> Values
{
get { return _data.Values; }
}
/// <summary>
/// Gets the value associated with the specified key.
/// </summary>
/// <param name="key">The key whose value to get.</param>
/// <returns>
/// The value associated with the specified key, if the key is found; otherwise, the default value for the type of the <typeparamref name="T"/> parameter.
/// </returns>
public virtual T GetValue(Symbol key)
{
T value;
TryGetValue(key, out value);
return value;
}
}
/// <summary>
/// Provides extension methods for the DataDictionary class
/// </summary>
public static class DataDictionaryExtensions
{
/// <summary>
/// Provides a convenience method for adding a base data instance to our data dictionary
/// </summary>
public static void Add<T>(this DataDictionary<T> dictionary, T data)
where T : BaseData
{
dictionary.Add(data.Symbol, data);
}
}
} | 51.571875 | 851 | 0.623281 | [
"Apache-2.0"
] | AENotFound/Lean | Common/Data/Market/DataDictionary.cs | 16,503 | C# |
using Core.Models.Enums;
using System.ComponentModel.DataAnnotations;
namespace Core.Dtos.UserDtos
{
public class UserUpdateDto
{
[Display(Name = "شناسه", Prompt = "شناسه")]
public string Id { get; set; }
[Required(ErrorMessage = "{0} را وارد کنید")]
[Display(Name = "نام کاربری", Prompt = "نام کاربری")]
public string UserName { get; set; }
[Required(ErrorMessage = "{0} را وارد کنید")]
[EmailAddress(ErrorMessage = "{0} وارد شده معتبر نیست.")]
[Display(Name = "ایمیل", Prompt = "ایمیل")]
public string Email { get; set; }
[Required(ErrorMessage = "{0} را مشخص کنید")]
[Display(Name = "جنسیت", Prompt = "جنسیت")]
public Gender Gender { get; set; }
[Display(Name = "تلفن", Prompt = "تلفن")]
[Phone]
public string PhoneNumber { get; set; }
}
}
| 30.37931 | 65 | 0.580023 | [
"MIT"
] | Smahdie/Blog | src/Core/Dtos/UserDtos/UserUpdateDto.cs | 985 | C# |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Runtime.Serialization;
using System.Threading.Tasks;
using System.Xml;
using Microsoft.DotNet.XHarness.CLI.CommandArguments.Apple.Simulators;
using Microsoft.DotNet.XHarness.Common;
using Microsoft.DotNet.XHarness.Common.Execution;
using Microsoft.DotNet.XHarness.Common.Logging;
using Microsoft.DotNet.XHarness.iOS.Shared;
using Microsoft.DotNet.XHarness.iOS.Shared.Utilities;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
namespace Microsoft.DotNet.XHarness.CLI.Commands.Apple.Simulators
{
internal abstract class SimulatorsCommand : XHarnessCommand<SimulatorsCommandArguments>
{
private const string MAJOR_VERSION_PLACEHOLDER = "DOWNLOADABLE_VERSION_MAJOR";
private const string MINOR_VERSION_PLACEHOLDER = "DOWNLOADABLE_VERSION_MINOR";
private const string VERSION_PLACEHOLDER = "DOWNLOADABLE_VERSION";
private const string IDENTIFIER_PLACEHOLDER = "DOWNLOADABLE_IDENTIFIER";
private const string SimulatorIndexUrl = "https://devimages-cdn.apple.com/downloads/xcode/simulators/index-{0}-{1}.dvtdownloadableindex";
protected const string SimulatorHelpString =
"Accepts a list of simulator IDs to install. The ID can be a fully qualified string, " +
"e.g. com.apple.pkg.AppleTVSimulatorSDK14_2 or you can use the format in which you specify " +
"apple targets for XHarness tests (ios-simulator, tvos-simulator, watchos-simulator).";
private static readonly HttpClient s_client = new();
private readonly MacOSProcessManager _processManager = new();
protected ILogger Logger { get; set; } = null!;
protected SimulatorsCommand(string name, bool allowsExtraArgs, string help)
: base(TargetPlatform.Apple, name, allowsExtraArgs, new ServiceCollection(), help)
{
}
protected static string TempDirectory
{
get
{
var path = Path.Combine(Path.GetTempPath(), "simulator-installer");
if (!Directory.Exists(path))
{
Directory.CreateDirectory(path);
}
return path;
}
}
protected async Task<(bool Succeeded, string Stdout)> ExecuteCommand(
string filename,
TimeSpan? timeout = null,
params string[] arguments)
{
var stdoutLog = new MemoryLog() { Timestamp = false };
var stderrLog = new MemoryLog() { Timestamp = false };
var result = await _processManager.ExecuteCommandAsync(
filename,
arguments,
new CallbackLog(m => Logger.LogDebug(m)),
stdoutLog,
stderrLog,
timeout ?? TimeSpan.FromSeconds(30));
var stderr = stderrLog.ToString();
if (stderr.Length > 0)
{
Logger.LogDebug("Error output:" + Environment.NewLine + stderr);
}
return (result.Succeeded, stdoutLog.ToString());
}
protected async Task<IEnumerable<Simulator>> GetAvailableSimulators()
{
static string Replace(string value, Dictionary<string, string> replacements)
{
foreach (var kvp in replacements)
{
value = value.Replace($"$({kvp.Key})", kvp.Value);
}
return value;
}
var doc = new XmlDocument();
doc.LoadXml(await GetSimulatorIndexXml() ?? throw new FailedToGetIndexException());
var simulators = new List<Simulator>();
var downloadables = doc.SelectNodes("//plist/dict/key[text()='downloadables']/following-sibling::array/dict");
foreach (XmlNode? downloadable in downloadables!)
{
if (downloadable == null)
{
continue;
}
var nameNode = downloadable.SelectSingleNode("key[text()='name']/following-sibling::string") ?? throw new Exception("Name node not found");
var versionNode = downloadable.SelectSingleNode("key[text()='version']/following-sibling::string") ?? throw new Exception("Version node not found");
var sourceNode = downloadable.SelectSingleNode("key[text()='source']/following-sibling::string") ?? throw new Exception("Source node not found");
var identifierNode = downloadable.SelectSingleNode("key[text()='identifier']/following-sibling::string") ?? throw new Exception("Identifier node not found");
var fileSizeNode = downloadable.SelectSingleNode("key[text()='fileSize']/following-sibling::integer|key[text()='fileSize']/following-sibling::real");
var installPrefixNode = downloadable.SelectSingleNode("key[text()='userInfo']/following-sibling::dict/key[text()='InstallPrefix']/following-sibling::string") ?? throw new Exception("InstallPrefix node not found");
var version = versionNode.InnerText;
var versions = version.Split('.');
var versionMajor = versions[0];
var versionMinor = versions[1];
var dict = new Dictionary<string, string>() {
{ MAJOR_VERSION_PLACEHOLDER, versionMajor },
{ MINOR_VERSION_PLACEHOLDER, versionMinor },
{ VERSION_PLACEHOLDER, version },
};
var identifier = Replace(identifierNode.InnerText, dict);
dict.Add(IDENTIFIER_PLACEHOLDER, identifier);
_ = double.TryParse(fileSizeNode?.InnerText, out var parsedFileSize);
simulators.Add(new Simulator(
name: Replace(nameNode.InnerText, dict),
identifier: Replace(identifierNode.InnerText, dict),
version: versionNode.InnerText,
source: Replace(sourceNode.InnerText, dict),
installPrefix: Replace(installPrefixNode.InnerText, dict),
fileSize: (long)parsedFileSize));
}
return simulators;
}
protected async Task<Version?> IsInstalled(string identifier)
{
var (succeeded, pkgInfo) = await ExecuteCommand($"pkgutil", TimeSpan.FromMinutes(1), "--pkg-info", identifier);
if (!succeeded)
{
return null;
}
var lines = pkgInfo.Split('\n');
var version = lines.First(v => v.StartsWith("version: ", StringComparison.Ordinal)).Substring("version: ".Length);
return Version.Parse(version);
}
protected IEnumerable<string> ParseSimulatorIds()
{
var simulators = new List<string>();
foreach (string argument in ExtraArguments)
{
if (argument.StartsWith("com.apple.pkg."))
{
simulators.Add(argument);
continue;
}
TestTargetOs target;
try
{
target = argument.ParseAsAppRunnerTargetOs();
}
catch (ArgumentOutOfRangeException)
{
throw new ArgumentException(
$"Failed to parse simulator '{argument}'. Available values are ios-simulator, tvos-simulator and watchos-simulator." +
Environment.NewLine + Environment.NewLine +
"You need to also specify the version. Example: ios-simulator_13.4");
}
if (string.IsNullOrEmpty(target.OSVersion))
{
throw new ArgumentException($"Failed to parse simulator '{argument}'. " +
$"You need to specify the exact version. Example: ios-simulator_13.4");
}
string simulatorName = target.Platform switch
{
TestTarget.Simulator_iOS => "iPhone",
TestTarget.Simulator_iOS32 => "iPhone",
TestTarget.Simulator_iOS64 => "iPhone",
TestTarget.Simulator_tvOS => "AppleTV",
TestTarget.Simulator_watchOS => "Watch",
_ => throw new ArgumentException($"Failed to parse simulator '{argument}'. " +
"Available values are ios-simulator, tvos-simulator and watchos-simulator." +
Environment.NewLine + Environment.NewLine +
"You need to also specify the version. Example: ios-simulator_13.4"),
};
// e.g. com.apple.pkg.AppleTVSimulatorSDK14_3
simulators.Add($"com.apple.pkg.{simulatorName}SimulatorSDK{target.OSVersion.Replace(".", "_")}");
}
return simulators;
}
private async Task<string?> GetSimulatorIndexXml()
{
var (xcodeVersion, xcodeUuid) = await GetXcodeInformation();
var url = string.Format(SimulatorIndexUrl, xcodeVersion, xcodeUuid);
var uri = new Uri(url);
var tmpfile = Path.Combine(TempDirectory, Path.GetFileName(uri.LocalPath));
if (!File.Exists(tmpfile))
{
await DownloadFile(url, tmpfile);
}
else
{
Logger.LogInformation($"File '{tmpfile}' already exists, skipped download");
}
var (succeeded, xmlResult) = await ExecuteCommand("plutil", TimeSpan.FromSeconds(30), "-convert", "xml1", "-o", "-", tmpfile);
if (!succeeded)
{
return null;
}
return xmlResult;
}
private async Task DownloadFile(string url, string destinationPath)
{
try
{
Logger.LogInformation($"Downloading {url}...");
var downloadTask = s_client.GetStreamAsync(url);
using var fileStream = new FileStream(destinationPath, FileMode.Create);
using var bodyStream = await downloadTask;
await bodyStream.CopyToAsync(fileStream);
}
catch (HttpRequestException e)
{
// 403 means 404
if (e.StatusCode == HttpStatusCode.Forbidden)
{
// Apple's servers return a 403 if the file doesn't exist, which can be quite confusing, so show a better error.
Logger.LogWarning($"Failed to download {url}: Not found");
}
else
{
Logger.LogWarning($"Failed to download {url}: {e}");
}
throw;
}
}
private async Task<(string XcodeVersion, string XcodeUuid)> GetXcodeInformation()
{
string xcodeRoot = Arguments.XcodeRoot.Value ?? new MacOSProcessManager().XcodeRoot;
var plistPath = Path.Combine(xcodeRoot, "Contents", "Info.plist");
var (succeeded, xcodeVersion) = await ExecuteCommand("/usr/libexec/PlistBuddy", TimeSpan.FromSeconds(5), "-c", "Print :DTXcode", plistPath);
if (!succeeded)
{
throw new Exception("Failed to detect Xcode version!");
}
xcodeVersion = xcodeVersion.Trim();
string xcodeUuid;
(succeeded, xcodeUuid) = await ExecuteCommand("/usr/libexec/PlistBuddy", TimeSpan.FromSeconds(5), "-c", "Print :DVTPlugInCompatibilityUUID", plistPath);
if (!succeeded)
{
throw new Exception("Failed to detect Xcode UUID!");
}
xcodeUuid = xcodeUuid.Trim();
xcodeVersion = xcodeVersion.Insert(xcodeVersion.Length - 2, ".");
xcodeVersion = xcodeVersion.Insert(xcodeVersion.Length - 1, ".");
return (xcodeVersion, xcodeUuid);
}
[Serializable]
protected class FailedToGetIndexException : Exception
{
public FailedToGetIndexException() : this("Failed to download the list of available simulators from Apple")
{
}
public FailedToGetIndexException(string? message) : base(message)
{
}
public FailedToGetIndexException(string? message, Exception? innerException) : base(message, innerException)
{
}
protected FailedToGetIndexException(SerializationInfo info, StreamingContext context) : base(info, context)
{
}
}
}
}
| 41.321767 | 229 | 0.578517 | [
"MIT"
] | dotnet/xharness | src/Microsoft.DotNet.XHarness.CLI/Commands/Apple/Simulators/SimulatorsCommand.cs | 13,101 | C# |
namespace Mojito.Server {
using MvcTurbine.ComponentModel;
using MvcTurbine.Ninject;
using MvcTurbine.Web;
using MvcTurbine.Web.Config;
public class MojitoApp : TurbineApplication {
static MojitoApp() {
ServiceLocatorManager.SetLocatorProvider(() => new NinjectServiceLocator());
Engine.Initialize
.DisableHttpModuleRegistration();
}
}
}
| 26.3125 | 88 | 0.653207 | [
"Apache-2.0"
] | lozanotek/mojito | src/Mojito.Server/MojitoApp.cs | 423 | C# |
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the MIT license. See License.txt in the project root for license information.
using Microsoft.AspNetCore.Razor.LanguageServer.Common;
using OmniSharp.Extensions.JsonRpc;
namespace Microsoft.AspNetCore.Razor.LanguageServer.WrapWithTag
{
[Parallel, Method(LanguageServerConstants.RazorWrapWithTagEndpoint)]
internal interface IWrapWithTagHandler : IJsonRpcRequestHandler<WrapWithTagParams, WrapWithTagResponse?>
{
}
}
| 36.285714 | 108 | 0.805118 | [
"MIT"
] | 50Wliu/razor-tooling | src/Razor/src/Microsoft.AspNetCore.Razor.LanguageServer/WrapWithTag/IWrapWithTagHandler.cs | 510 | C# |
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System.Collections.Generic;
using System.ComponentModel;
using System.ServiceModel.Security;
using System.Web.Http;
using System.Web.Http.SelfHost;
namespace System.Net.Http
{
[EditorBrowsable(EditorBrowsableState.Never)]
public static class HttpRequestMessageExtensions
{
/// <summary>
/// Gets the current <see cref="T:System.ServiceModel.Security.SecurityMessageProperty"/>
/// stored in <see cref="M:HttpRequestMessage.Properties"/> for the given request.
/// </summary>
/// <param name="request">The HTTP request.</param>
/// <returns>The <see cref="SecurityMessageProperty"/>.</returns>
public static SecurityMessageProperty GetSecurityMessageProperty(
this HttpRequestMessage request
)
{
if (request == null)
{
throw Error.ArgumentNull("request");
}
return request.GetProperty<SecurityMessageProperty>(HttpSelfHostServer.SecurityKey);
}
private static T GetProperty<T>(this HttpRequestMessage request, string key)
{
T value;
request.Properties.TryGetValue(key, out value);
return value;
}
}
}
| 34.414634 | 111 | 0.652729 | [
"Apache-2.0"
] | belav/AspNetWebStack | src/System.Web.Http.SelfHost/HttpRequestMessageExtensions.cs | 1,413 | C# |
/*
* Copyright 2019 GridGain Systems, Inc. and Contributors.
*
* Licensed under the GridGain Community Edition License (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.gridgain.com/products/software/community-edition/gridgain-community-edition-license
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
namespace Apache.Ignite.Core.Tests.Binary.Serializable
{
using System;
using System.Runtime.Serialization;
using NUnit.Framework;
/// <summary>
/// Tests basic ISerializable scenarios.
/// </summary>
public class BasicSerializableObjectsTest
{
/// <summary>
/// Tests the object with no fields.
/// </summary>
[Test]
public void TestEmptyObject()
{
var res = TestUtils.SerializeDeserialize(new EmptyObject());
Assert.IsNotNull(res);
}
/// <summary>
/// Tests the object with no fields.
/// </summary>
[Test]
public void TestEmptyObjectOnline()
{
using (var ignite = Ignition.Start(TestUtils.GetTestConfiguration()))
using (var ignite2 = Ignition.Start(TestUtils.GetTestConfiguration(name: "1")))
{
var cache = ignite.CreateCache<int, EmptyObject>("c");
cache[1] = new EmptyObject();
var res = ignite2.GetCache<int, EmptyObject>("c")[1];
Assert.IsNotNull(res);
}
}
/// <summary>
/// Tests ISerializable without serialization ctor.
/// </summary>
[Test]
public void TestMissingCtor()
{
var ex = Assert.Throws<SerializationException>(() => TestUtils.SerializeDeserialize(new MissingCtor()));
Assert.AreEqual(string.Format("The constructor to deserialize an object of type '{0}' was not found.",
typeof(MissingCtor)), ex.Message);
}
/// <summary>
/// Tests <see cref="Type"/> serialization.
/// </summary>
[Test]
public void TestTypes()
{
var type = GetType();
var res = TestUtils.SerializeDeserialize(type);
Assert.AreEqual(type.AssemblyQualifiedName, res.AssemblyQualifiedName);
}
/// <summary>
/// Missing serialization ctor.
/// </summary>
private class MissingCtor : ISerializable
{
/** <inheritdoc /> */
public void GetObjectData(SerializationInfo info, StreamingContext context)
{
// No-op.
}
}
/// <summary>
/// Object with no fields.
/// </summary>
[Serializable]
private class EmptyObject : ISerializable
{
/// <summary>
/// Initializes a new instance of the <see cref="EmptyObject"/> class.
/// </summary>
public EmptyObject()
{
// No-op.
}
/// <summary>
/// Initializes a new instance of the <see cref="EmptyObject"/> class.
/// </summary>
private EmptyObject(SerializationInfo info, StreamingContext context)
{
Assert.AreEqual(StreamingContextStates.All, context.State);
Assert.IsNull(context.Context);
}
/** <inheritdoc /> */
public void GetObjectData(SerializationInfo info, StreamingContext context)
{
Assert.AreEqual(StreamingContextStates.All, context.State);
Assert.IsNull(context.Context);
}
}
}
}
| 31.952381 | 116 | 0.569051 | [
"CC0-1.0"
] | ciusji/gridgain | modules/platforms/dotnet/Apache.Ignite.Core.Tests/Binary/Serializable/BasicSerializableObjectsTest.cs | 4,028 | C# |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.