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.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;
namespace WebTests
{
public class RouteConfig
{
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
}
}
}
| 24 | 99 | 0.585069 | [
"MIT"
] | 1804-Apr-USFdotnet/monica-miller-project1 | RestuarantProject/WebTests/App_Start/RouteConfig.cs | 578 | C# |
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.Syntax;
namespace Exercism.Representers.CSharp.Normalization
{
internal class SimplifyBooleanEquality : CSharpSyntaxRewriter
{
public override SyntaxNode VisitBinaryExpression(BinaryExpressionSyntax node)
{
if (node.Left is LiteralExpressionSyntax leftLiteralExpression)
{
if (leftLiteralExpression.IsKind(SyntaxKind.TrueLiteralExpression))
return node.Right;
if (leftLiteralExpression.IsKind(SyntaxKind.FalseLiteralExpression))
return SyntaxFactory.PrefixUnaryExpression(SyntaxKind.LogicalNotExpression, node.Right);
}
if (node.Right is LiteralExpressionSyntax rightLiteralExpression)
{
if (rightLiteralExpression.IsKind(SyntaxKind.TrueLiteralExpression))
return node.Left;
if (rightLiteralExpression.IsKind(SyntaxKind.FalseLiteralExpression))
return SyntaxFactory.PrefixUnaryExpression(SyntaxKind.LogicalNotExpression, node.Left);
}
return base.VisitBinaryExpression(node);
}
}
} | 40.15625 | 108 | 0.661479 | [
"MIT"
] | ErikSchierboom/csharp-representer | src/Exercism.Representers.CSharp/Normalization/SimplifyBooleanEquality.cs | 1,285 | C# |
using System;
using System.Text;
using JulMar.Smpp.Utility;
namespace JulMar.Smpp.Elements
{
/// <summary>
/// The short_message parameter contains the user data. A maximum of 254 octets can be
/// sent. ESME's should use the optional message_payload parameter in submit_sm, submit_multi,
/// or deliver_sm to send larger data sizes.
///
/// NOTE: We deviate from the element definition slightly in that we include the "sm_length"
/// element as part of this element. They always go together in this instance.
/// </summary>
public class short_message : SmppOctetString
{
/// <summary>
/// The max length of a short-message data component.
/// </summary>
public const int MAX_LENGTH = 254;
/// <summary>
/// Default constructor
/// </summary>
public short_message() : base()
{
}
/// <summary>
/// Parameterized constructor
/// </summary>
/// <param name="s">Value</param>
public short_message(string s) : base(s)
{
}
/// <summary>
/// Returns the length of the data
/// </summary>
public int Length
{
get { return Value.Length; }
}
/// <summary>
/// Returns the base message value
/// </summary>
public string TextValue
{
get { return base.Value; }
set { base.Value = value; }
}
/// <summary>
/// Returns the message as an array of bytes
/// </summary>
public byte[] BinaryValue
{
get
{
return Encoding.ASCII.GetBytes(base.Value);
}
set
{
Value = Encoding.ASCII.GetString(value);
}
}
/// <summary>
/// This method validate the data in the element.
/// </summary>
protected override void ValidateData()
{
if (Value.Length > MAX_LENGTH)
throw new ArgumentException("short_message too long - it must be <= " + MAX_LENGTH.ToString());
}
/// <summary>
/// Override of the object.ToString method
/// </summary>
/// <returns></returns>
public override string ToString()
{
return string.Format("short_message: len={0}, \"{1}\"", Value.Length, Value);
}
}
}
| 22.629213 | 99 | 0.642006 | [
"MIT"
] | JackyChiou/smpp.net | Smpp.NET/Elements/short_message.cs | 2,014 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Syroot.BinaryData.Memory;
namespace GTAdhocTools.Instructions
{
public class OpIntConst : InstructionBase
{
public AdhocCallType CallType { get; set; } = AdhocCallType.INT_CONST;
public int Value { get; set; }
public override void Deserialize(AdhocFile parent, ref SpanReader sr)
{
Value = sr.ReadInt32();
}
public override string ToString()
=> $"{CallType}: {Value} (0x{Value:X2})";
public override void Decompile(CodeBuilder builder)
{
throw new NotImplementedException();
}
}
}
| 23.806452 | 78 | 0.632791 | [
"MIT"
] | Nenkai/GTAdhocParser | GTAdhocParser/Instructions/Variables/AdhocIntConst.cs | 740 | C# |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
namespace Microsoft.Store.PartnerCenter.PowerShell.Commands
{
using System.Management.Automation;
using Models.RateCards;
using PartnerCenter.Models.RateCards;
/// <summary>
/// Cmdlet that retrieves Azrue Rate Card details.
/// </summary>
[Cmdlet(VerbsCommon.Get, "PartnerAzureRateCard"), OutputType(typeof(PSAzureRateCard))]
public class GetPartnerAzureRateCard : PartnerCmdlet
{
/// <summary>
/// Gets or sets the identifier of the customer.
/// </summary>
[Parameter(Mandatory = false, HelpMessage = "An optional three letter ISO code for the currency in which the resource rates will be provided.")]
public string Currency { get; set; }
/// <summary>
/// Gets or sets the offer category.
/// </summary>
[Parameter(Mandatory = false, HelpMessage = "An optional two-letter ISO country/region code that indicates the market where the offer is purchased.")]
public string Region { get; set; }
/// <summary>
/// Gets or sets a flag indicating whether or not to retrieve the Azure Rate Card for Azure Partner Shared Services (APSS).
/// </summary>
[Parameter(Mandatory = false, HelpMessage = "Flag indicating whether or not to retrieve the Azure Rate Card for Azure Partner Shared Services (APSS).")]
public SwitchParameter SharedServices { get; set; }
/// <summary>
/// Executes the operations associated with the cmdlet.
/// </summary>
public override void ExecuteCmdlet()
{
AzureRateCard rateCard;
if (SharedServices.IsPresent && SharedServices.ToBool())
{
rateCard = Partner.RateCards.Azure.GetSharedAsync(Currency, Region).GetAwaiter().GetResult();
}
else
{
rateCard = Partner.RateCards.Azure.GetAsync(Currency, Region).GetAwaiter().GetResult();
}
WriteObject(new PSAzureRateCard(rateCard));
}
}
} | 41.660377 | 160 | 0.643569 | [
"MIT"
] | arjjsolutions/Partner-Center-PowerShell | src/PowerShell/Commands/GetPartnerAzureRateCard.cs | 2,210 | C# |
// ReSharper disable All
using PetaPoco;
using System;
namespace MixERP.Net.Entities.Office
{
[PrimaryKey("", autoIncrement = false)]
[TableName("office.store_scrud_view")]
[ExplicitColumns]
public sealed class StoreScrudView : PetaPocoDB.Record<StoreScrudView>, IPoco
{
[Column("store_id")]
[ColumnDbType("int4", 0, true, "")]
public int? StoreId { get; set; }
[Column("office")]
[ColumnDbType("text", 0, true, "")]
public string Office { get; set; }
[Column("store_code")]
[ColumnDbType("varchar", 12, true, "")]
public string StoreCode { get; set; }
[Column("store_name")]
[ColumnDbType("varchar", 50, true, "")]
public string StoreName { get; set; }
[Column("address")]
[ColumnDbType("varchar", 50, true, "")]
public string Address { get; set; }
[Column("store_type")]
[ColumnDbType("text", 0, true, "")]
public string StoreType { get; set; }
[Column("allow_sales")]
[ColumnDbType("bool", 0, true, "")]
public bool? AllowSales { get; set; }
[Column("sales_tax")]
[ColumnDbType("text", 0, true, "")]
public string SalesTax { get; set; }
[Column("default_cash_account")]
[ColumnDbType("text", 0, true, "")]
public string DefaultCashAccount { get; set; }
[Column("default_cash_repository")]
[ColumnDbType("text", 0, true, "")]
public string DefaultCashRepository { get; set; }
}
} | 29.903846 | 81 | 0.572347 | [
"MPL-2.0"
] | asine/mixerp | src/Libraries/Entities/Office/StoreScrudView.cs | 1,555 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Bridge.MessageSender
{
/// <summary>
/// Concrete implementor
/// </summary>
public class WebServiceSender : IMessageSender
{
public void SendMessage(string subjet, string body)
{
Console.WriteLine("Message type: Web Service");
Console.WriteLine($"Subject: {subjet} from Web Service Body: {body}");
}
}
}
| 24.047619 | 82 | 0.649505 | [
"MIT"
] | cesthus/consolepatterns | Bridge/MessageSender/WebServiceSender.cs | 507 | C# |
using System;
using System.Diagnostics;
using System.Globalization;
using System.Linq;
using System.Runtime.InteropServices;
using System.Windows;
using WindowsInstaller;
using WixSharp;
using WixSharp.Bootstrapper;
using WixSharp.CommonTasks;
using io = System.IO;
public static class Script
{
static void Main()
{
var project = new Project("MyProduct",
new Dir(@"%ProgramFiles%\My Company\My Product",
new File("Program.cs")));
project.GUID = new Guid("6fe30b47-2577-43ad-9095-1861ba25889b");
//project.SourceBaseDir = "<input dir path>";
//project.OutDir = "<output dir path>";
//project.BuildMsi();
project.Language = "en-US";
string productMsi = project.BuildMsi();
project.Language = "ru-RU";
string mstFile = project.BuildLanguageTransform(productMsi, "ru-RU");
productMsi.EmbedTransform(mstFile);
productMsi.SetPackageLanguages("en-US,ru-RU".ToLcidList());
}
static public void Main1()
{
var product =
new Project("My Product",
new Dir(@"%ProgramFiles%\My Company\My Product",
new File("readme.txt")));
product.InstallScope = InstallScope.perMachine;
product.Version = new Version("1.0.0.0");
product.GUID = new Guid("6f330b47-2577-43ad-9095-1861bb258771");
product.Language = BA.Languages; // "en-US,de-DE,ru-RU";
product.PreserveTempFiles = true;
product.OutFileName = $"{product.Name}.ml.v{product.Version}";
var msiFile = $"{product.OutFileName}.msi".PathGetFullPath();
//var msiFile = product.BuildMultilanguageMsi();
var bootstrapper =
new Bundle("My Product",
new PackageGroupRef("NetFx40Web"),
new MsiPackage(msiFile)
{
Id = BA.MainPackageId,
DisplayInternalUI = true,
Visible = true,
MsiProperties = "TRANSFORMS=[TRANSFORMS]"
});
bootstrapper.SetVersionFromFile(msiFile);
bootstrapper.UpgradeCode = new Guid("6f330b47-2577-43ad-9095-1861bb25889b");
bootstrapper.Application = new ManagedBootstrapperApplication("%this%", "BootstrapperCore.config");
bootstrapper.SuppressWixMbaPrereqVars = true;
bootstrapper.PreserveTempFiles = true;
bootstrapper.Build(msiFile.PathChangeExtension(".exe"));
}
} | 33.710526 | 107 | 0.603044 | [
"Apache-2.0"
] | BachLeFPT/SymphonyElectron | installer/win/WixSharpToolset/Samples/Bootstrapper/MultiLanguageSupport/setup.cs | 2,562 | C# |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.SceneManagement;
public class MusicController : MonoBehaviour
{
private static readonly string FirstPlay = "FirstPlay";
private static readonly string MusicPref = "MusicPref";
static MusicController Sounds = null;
public AnamenuKontrol AnamenuKontrol;
public GameObject MusicControl;
bool OnOff = true;
void Start()
{
if (PlayerPrefs.GetFloat("MusicPref") == 0)
{
GetComponent<AudioSource>().volume = 0;
MusicControl.GetComponent<Image>().sprite = AnamenuKontrol.ButtonImages[2];
OnOff = true;
}
else
{
GetComponent<AudioSource>().volume = 0.2f;
MusicControl.GetComponent<Image>().sprite = AnamenuKontrol.ButtonImages[3];
OnOff = false;
}
GetComponent<AudioSource>().Play();
if (PlayerPrefs.GetFloat(FirstPlay) == 0)
{
PlayerPrefs.SetFloat(MusicPref, 0.2f);
}
if (Sounds != null)
{
Destroy(gameObject);
}
else
{
Sounds = this;
GameObject.DontDestroyOnLoad(gameObject);
}
PlayerPrefs.SetFloat(FirstPlay, 1);
}
public void MusicOnOff()
{
if (OnOff)
{
MusicControl.GetComponent<Image>().sprite = AnamenuKontrol.ButtonImages[2];
PlayerPrefs.SetFloat(MusicPref, 0);
OnOff = false;
}
else
{
MusicControl.GetComponent<Image>().sprite = AnamenuKontrol.ButtonImages[3];
PlayerPrefs.SetFloat(MusicPref, 0.2f);
OnOff = true;
}
}
void Update()
{
if (AnamenuKontrol == null && MusicControl == null && SceneManager.GetActiveScene().name == "AnaMenu")
{
AnamenuKontrol = GameObject.Find("AnamenuKontrol").GetComponent<AnamenuKontrol>();
MusicControl = GameObject.Find("Canvas").transform.GetChild(2).GetChild(0).GetChild(0).gameObject;
}
if (PlayerPrefs.GetFloat("MusicPref") == 0)
{
GetComponent<AudioSource>().volume = 0;
}
else
{
GetComponent<AudioSource>().volume = 0.2f;
}
}
}
| 27.159091 | 110 | 0.568201 | [
"MIT"
] | elifoksas/DiamondRunner | Assets/Scripts/MusicController.cs | 2,390 | C# |
using System;
using System.Collections.Generic;
using System.Text;
namespace Discord.Menus.Elements
{
public class Button : GUIElement
{
private string EmojiTag { get; set; }
private string LabelText { get; set; }
private Action Action { get; set; }
private bool Inline { get; set; }
public Button(string EmojiTag, string LabelText, Action Action, bool Inline = false)
{
this.Type = GUIElementType.Button;
this.Action = Action;
this.EmojiTag = EmojiTag;
this.LabelText = LabelText;
this.Inline = Inline;
}
public Action GetAction()
{
return Action;
}
public string GetEmoji()
{
return EmojiTag;
}
public string GetLabelText()
{
return LabelText;
}
public bool GetInline()
{
return Inline;
}
}
}
| 22.136364 | 92 | 0.534908 | [
"MIT"
] | knexguy101/Discord.Menus | Elements/Button.cs | 976 | C# |
// <auto-generated />
using System;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Migrations;
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
using starbase_nexus_api.DbContexts;
namespace starbase_nexus_api.Migrations
{
[DbContext(typeof(MainDbContext))]
[Migration("20211012183203_RenameShipClassToRole")]
partial class RenameShipClassToRole
{
protected override void BuildTargetModel(ModelBuilder modelBuilder)
{
#pragma warning disable 612, 618
modelBuilder
.HasAnnotation("Relational:MaxIdentifierLength", 64)
.HasAnnotation("ProductVersion", "5.0.9");
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRoleClaim<string>", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int");
b.Property<string>("ClaimType")
.HasColumnType("longtext");
b.Property<string>("ClaimValue")
.HasColumnType("longtext");
b.Property<string>("RoleId")
.IsRequired()
.HasColumnType("varchar(255)");
b.HasKey("Id");
b.HasIndex("RoleId");
b.ToTable("AspNetRoleClaims");
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserClaim<string>", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int");
b.Property<string>("ClaimType")
.HasColumnType("longtext");
b.Property<string>("ClaimValue")
.HasColumnType("longtext");
b.Property<string>("UserId")
.IsRequired()
.HasColumnType("varchar(255)");
b.HasKey("Id");
b.HasIndex("UserId");
b.ToTable("AspNetUserClaims");
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserLogin<string>", b =>
{
b.Property<string>("LoginProvider")
.HasColumnType("varchar(255)");
b.Property<string>("ProviderKey")
.HasColumnType("varchar(255)");
b.Property<string>("ProviderDisplayName")
.HasColumnType("longtext");
b.Property<string>("UserId")
.IsRequired()
.HasColumnType("varchar(255)");
b.HasKey("LoginProvider", "ProviderKey");
b.HasIndex("UserId");
b.ToTable("AspNetUserLogins");
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserRole<string>", b =>
{
b.Property<string>("UserId")
.HasColumnType("varchar(255)");
b.Property<string>("RoleId")
.HasColumnType("varchar(255)");
b.HasKey("UserId", "RoleId");
b.HasIndex("RoleId");
b.ToTable("AspNetUserRoles");
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserToken<string>", b =>
{
b.Property<string>("UserId")
.HasColumnType("varchar(255)");
b.Property<string>("LoginProvider")
.HasColumnType("varchar(255)");
b.Property<string>("Name")
.HasColumnType("varchar(255)");
b.Property<string>("Value")
.HasColumnType("longtext");
b.HasKey("UserId", "LoginProvider", "Name");
b.ToTable("AspNetUserTokens");
});
modelBuilder.Entity("starbase_nexus_api.Entities.Authentication.RefreshToken", b =>
{
b.Property<Guid>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("char(36)");
b.Property<DateTimeOffset>("CreatedAt")
.ValueGeneratedOnAdd()
.HasColumnType("datetime(6)");
b.Property<DateTimeOffset>("ExpiresAt")
.HasColumnType("datetime(6)");
b.Property<string>("IpAddress")
.HasMaxLength(255)
.HasColumnType("varchar(255)");
b.Property<string>("Token")
.IsRequired()
.HasMaxLength(255)
.HasColumnType("varchar(255)");
b.Property<string>("UserId")
.IsRequired()
.HasMaxLength(255)
.HasColumnType("varchar(255)");
b.HasKey("Id");
b.HasIndex("UserId");
b.ToTable("Authentication_RefreshTokens");
});
modelBuilder.Entity("starbase_nexus_api.Entities.Constructions.Ship", b =>
{
b.Property<Guid>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("char(36)");
b.Property<Guid?>("ArmorMaterialId")
.HasColumnType("char(36)");
b.Property<int?>("BackwardThrustPower")
.HasColumnType("int");
b.Property<int?>("Batteries")
.HasColumnType("int");
b.Property<Guid?>("CompanyId")
.HasColumnType("char(36)");
b.Property<DateTimeOffset>("CreatedAt")
.HasColumnType("datetime(6)");
b.Property<string>("CreatorId")
.HasMaxLength(36)
.HasColumnType("varchar(36)");
b.Property<string>("Description")
.IsRequired()
.HasMaxLength(50000)
.HasColumnType("longtext");
b.Property<int?>("FlightTime")
.HasColumnType("int");
b.Property<int?>("ForwardThrustPower")
.HasColumnType("int");
b.Property<float?>("GeneratedPower")
.HasColumnType("float");
b.Property<float?>("Height")
.HasColumnType("float");
b.Property<string>("ImageUris")
.HasMaxLength(50000)
.HasColumnType("longtext");
b.Property<float?>("Length")
.HasColumnType("float");
b.Property<int?>("MiningLasers")
.HasColumnType("int");
b.Property<string>("Name")
.IsRequired()
.HasMaxLength(255)
.HasColumnType("varchar(255)");
b.Property<uint?>("OldId")
.HasColumnType("int unsigned");
b.Property<int?>("OreCollectors")
.HasColumnType("int");
b.Property<int?>("OreCrates")
.HasColumnType("int");
b.Property<string>("PreviewImageUri")
.IsRequired()
.HasMaxLength(255)
.HasColumnType("varchar(255)");
b.Property<double?>("PriceBlueprint")
.HasColumnType("double");
b.Property<double?>("PriceShip")
.HasColumnType("double");
b.Property<int?>("PrimaryWeaponsAutoCannons")
.HasColumnType("int");
b.Property<int?>("PrimaryWeaponsLaserCannons")
.HasColumnType("int");
b.Property<int?>("PrimaryWeaponsMissileLauncher")
.HasColumnType("int");
b.Property<int?>("PrimaryWeaponsPlasmaCannons")
.HasColumnType("int");
b.Property<int?>("PrimaryWeaponsRailCannons")
.HasColumnType("int");
b.Property<int?>("PrimaryWeaponsTorpedoLauncher")
.HasColumnType("int");
b.Property<int?>("PropellantCapacity")
.HasColumnType("int");
b.Property<int?>("Radiators")
.HasColumnType("int");
b.Property<int?>("ResourceBridges")
.HasColumnType("int");
b.Property<int?>("SpeedWithCargo")
.HasColumnType("int");
b.Property<int?>("SpeedWithoutCargo")
.HasColumnType("int");
b.Property<float?>("TotalMassWithoutCargo")
.HasColumnType("float");
b.Property<int?>("TurretWeaponsAutoCannons")
.HasColumnType("int");
b.Property<int?>("TurretWeaponsLaserCannons")
.HasColumnType("int");
b.Property<int?>("TurretWeaponsMissileLauncher")
.HasColumnType("int");
b.Property<int?>("TurretWeaponsPlasmaCannons")
.HasColumnType("int");
b.Property<int?>("TurretWeaponsRailCannons")
.HasColumnType("int");
b.Property<int?>("TurretWeaponsTorpedoLauncher")
.HasColumnType("int");
b.Property<DateTimeOffset?>("UpdatedAt")
.HasColumnType("datetime(6)");
b.Property<float?>("Width")
.HasColumnType("float");
b.Property<string>("YoutubeVideoUri")
.HasMaxLength(255)
.HasColumnType("varchar(255)");
b.HasKey("Id");
b.HasIndex("ArmorMaterialId");
b.HasIndex("CompanyId");
b.HasIndex("CreatorId");
b.ToTable("Constructions_Ships");
});
modelBuilder.Entity("starbase_nexus_api.Entities.Constructions.ShipMaterialCost", b =>
{
b.Property<Guid>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("char(36)");
b.Property<DateTimeOffset>("CreatedAt")
.HasColumnType("datetime(6)");
b.Property<Guid>("MaterialId")
.HasColumnType("char(36)");
b.Property<uint?>("OldId")
.HasColumnType("int unsigned");
b.Property<Guid>("ShipId")
.HasColumnType("char(36)");
b.Property<DateTimeOffset?>("UpdatedAt")
.HasColumnType("datetime(6)");
b.Property<float>("Voxels")
.HasColumnType("float");
b.HasKey("Id");
b.HasIndex("MaterialId");
b.HasIndex("ShipId");
b.ToTable("Constructions_ShipMaterialCosts");
});
modelBuilder.Entity("starbase_nexus_api.Entities.Constructions.ShipRole", b =>
{
b.Property<Guid>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("char(36)");
b.Property<DateTimeOffset>("CreatedAt")
.HasColumnType("datetime(6)");
b.Property<string>("Name")
.IsRequired()
.HasMaxLength(255)
.HasColumnType("varchar(255)");
b.Property<uint?>("OldId")
.HasColumnType("int unsigned");
b.Property<DateTimeOffset?>("UpdatedAt")
.HasColumnType("datetime(6)");
b.HasKey("Id");
b.ToTable("Constructions_ShipRoles");
});
modelBuilder.Entity("starbase_nexus_api.Entities.Constructions.ShipRoleReference", b =>
{
b.Property<Guid>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("char(36)");
b.Property<DateTimeOffset>("CreatedAt")
.HasColumnType("datetime(6)");
b.Property<uint?>("OldId")
.HasColumnType("int unsigned");
b.Property<Guid>("ShipId")
.HasColumnType("char(36)");
b.Property<Guid>("ShipRoleId")
.HasColumnType("char(36)");
b.Property<DateTimeOffset?>("UpdatedAt")
.HasColumnType("datetime(6)");
b.HasKey("Id");
b.HasIndex("ShipId");
b.HasIndex("ShipRoleId");
b.ToTable("Constructions_ShipRoleReference");
});
modelBuilder.Entity("starbase_nexus_api.Entities.Identity.Role", b =>
{
b.Property<string>("Id")
.HasColumnType("varchar(255)");
b.Property<string>("ConcurrencyStamp")
.IsConcurrencyToken()
.HasColumnType("longtext");
b.Property<DateTimeOffset>("CreatedAt")
.HasColumnType("datetime(6)");
b.Property<string>("Name")
.HasMaxLength(256)
.HasColumnType("varchar(256)");
b.Property<string>("NormalizedName")
.HasMaxLength(256)
.HasColumnType("varchar(256)");
b.Property<DateTimeOffset?>("UpdatedAt")
.HasColumnType("datetime(6)");
b.HasKey("Id");
b.HasIndex("NormalizedName")
.IsUnique()
.HasDatabaseName("RoleNameIndex");
b.ToTable("AspNetRoles");
});
modelBuilder.Entity("starbase_nexus_api.Entities.Identity.User", b =>
{
b.Property<string>("Id")
.HasColumnType("varchar(255)");
b.Property<string>("AboutMe")
.HasMaxLength(50000)
.HasColumnType("longtext");
b.Property<int>("AccessFailedCount")
.HasColumnType("int");
b.Property<string>("AvatarUri")
.HasMaxLength(255)
.HasColumnType("varchar(255)");
b.Property<string>("ConcurrencyStamp")
.IsConcurrencyToken()
.HasColumnType("longtext");
b.Property<DateTimeOffset>("CreatedAt")
.HasColumnType("datetime(6)");
b.Property<string>("DiscordDiscriminator")
.HasColumnType("longtext");
b.Property<string>("DiscordId")
.HasColumnType("varchar(255)");
b.Property<string>("Email")
.HasMaxLength(256)
.HasColumnType("varchar(256)");
b.Property<bool>("EmailConfirmed")
.HasColumnType("tinyint(1)");
b.Property<DateTimeOffset?>("LastLogin")
.HasColumnType("datetime(6)");
b.Property<bool>("LockoutEnabled")
.HasColumnType("tinyint(1)");
b.Property<DateTimeOffset?>("LockoutEnd")
.HasColumnType("datetime(6)");
b.Property<string>("NormalizedEmail")
.HasMaxLength(256)
.HasColumnType("varchar(256)");
b.Property<string>("NormalizedUserName")
.HasMaxLength(256)
.HasColumnType("varchar(256)");
b.Property<string>("PasswordHash")
.HasColumnType("longtext");
b.Property<string>("PhoneNumber")
.HasColumnType("longtext");
b.Property<bool>("PhoneNumberConfirmed")
.HasColumnType("tinyint(1)");
b.Property<string>("SecurityStamp")
.HasColumnType("longtext");
b.Property<bool>("TwoFactorEnabled")
.HasColumnType("tinyint(1)");
b.Property<DateTimeOffset?>("UpdatedAt")
.HasColumnType("datetime(6)");
b.Property<string>("UserName")
.HasMaxLength(256)
.HasColumnType("varchar(256)");
b.HasKey("Id");
b.HasIndex("DiscordId")
.IsUnique();
b.HasIndex("NormalizedEmail")
.HasDatabaseName("EmailIndex");
b.HasIndex("NormalizedUserName")
.IsUnique()
.HasDatabaseName("UserNameIndex");
b.ToTable("AspNetUsers");
});
modelBuilder.Entity("starbase_nexus_api.Entities.InGame.Item", b =>
{
b.Property<Guid>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("char(36)");
b.Property<string>("AdjacencyHeatValues")
.HasMaxLength(255)
.HasColumnType("varchar(255)");
b.Property<float?>("ChargeCapacity")
.HasColumnType("float");
b.Property<float?>("CoolantCapacity")
.HasColumnType("float");
b.Property<float?>("CoolantInput")
.HasColumnType("float");
b.Property<float?>("CoolantOutput")
.HasColumnType("float");
b.Property<float?>("CorrosionResistance")
.HasColumnType("float");
b.Property<DateTimeOffset>("CreatedAt")
.HasColumnType("datetime(6)");
b.Property<string>("Description")
.IsRequired()
.HasMaxLength(50000)
.HasColumnType("longtext");
b.Property<float?>("ElectricCapacity")
.HasColumnType("float");
b.Property<float?>("ElectricInput")
.HasColumnType("float");
b.Property<float?>("ElectricOutput")
.HasColumnType("float");
b.Property<float?>("ElectricityConversionBonusFactor")
.HasColumnType("float");
b.Property<float?>("ElectricityPerRecharge")
.HasColumnType("float");
b.Property<float?>("ElectricityPerShot")
.HasColumnType("float");
b.Property<float?>("FuelCapacity")
.HasColumnType("float");
b.Property<float?>("FuelInputRaw")
.HasColumnType("float");
b.Property<float?>("FuelOutputProcessed")
.HasColumnType("float");
b.Property<float?>("HeatDissipation")
.HasColumnType("float");
b.Property<float?>("HeatGeneration")
.HasColumnType("float");
b.Property<float?>("HeatGenerationPerShot")
.HasColumnType("float");
b.Property<string>("IconUri")
.HasMaxLength(255)
.HasColumnType("varchar(255)");
b.Property<Guid>("ItemCategoryId")
.HasColumnType("char(36)");
b.Property<float?>("MagazineCapacity")
.HasColumnType("float");
b.Property<float?>("Mass")
.HasColumnType("float");
b.Property<float?>("MaxMuzzleVelocity")
.HasColumnType("float");
b.Property<float?>("MinMuzzleVelocity")
.HasColumnType("float");
b.Property<string>("Name")
.IsRequired()
.HasMaxLength(255)
.HasColumnType("varchar(255)");
b.Property<uint?>("OldId")
.HasColumnType("int unsigned");
b.Property<Guid?>("PrimaryMaterialId")
.HasColumnType("char(36)");
b.Property<float?>("ProjectileEnergy")
.HasColumnType("float");
b.Property<float?>("ProjectileLifetime")
.HasColumnType("float");
b.Property<float?>("ProjectileMass")
.HasColumnType("float");
b.Property<float?>("PropellantCapacity")
.HasColumnType("float");
b.Property<float?>("PropellantConversionBonusFactor")
.HasColumnType("float");
b.Property<float?>("PropellantInput")
.HasColumnType("float");
b.Property<float?>("PropellantOutput")
.HasColumnType("float");
b.Property<float?>("RateOfFire")
.HasColumnType("float");
b.Property<float?>("ResearchPointsCube")
.HasColumnType("float");
b.Property<float?>("ResearchPointsGear")
.HasColumnType("float");
b.Property<float?>("ResearchPointsPower")
.HasColumnType("float");
b.Property<float?>("ResearchPointsShield")
.HasColumnType("float");
b.Property<float?>("ThrustPower")
.HasColumnType("float");
b.Property<int?>("Tier")
.HasColumnType("int");
b.Property<DateTimeOffset?>("UpdatedAt")
.HasColumnType("datetime(6)");
b.Property<float?>("WarmupTime")
.HasColumnType("float");
b.Property<string>("WikiUri")
.HasMaxLength(255)
.HasColumnType("varchar(255)");
b.HasKey("Id");
b.HasIndex("ItemCategoryId");
b.HasIndex("PrimaryMaterialId");
b.ToTable("InGame_Items");
});
modelBuilder.Entity("starbase_nexus_api.Entities.InGame.ItemCategory", b =>
{
b.Property<Guid>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("char(36)");
b.Property<DateTimeOffset>("CreatedAt")
.HasColumnType("datetime(6)");
b.Property<string>("Description")
.HasMaxLength(50000)
.HasColumnType("longtext");
b.Property<string>("Name")
.IsRequired()
.HasMaxLength(255)
.HasColumnType("varchar(255)");
b.Property<uint?>("OldId")
.HasColumnType("int unsigned");
b.Property<Guid?>("ParentId")
.HasColumnType("char(36)");
b.Property<DateTimeOffset?>("UpdatedAt")
.HasColumnType("datetime(6)");
b.HasKey("Id");
b.HasIndex("ParentId");
b.ToTable("InGame_ItemCategories");
});
modelBuilder.Entity("starbase_nexus_api.Entities.InGame.Material", b =>
{
b.Property<Guid>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("char(36)");
b.Property<double?>("Armor")
.HasColumnType("double");
b.Property<double?>("CorrosionResistance")
.HasColumnType("double");
b.Property<DateTimeOffset>("CreatedAt")
.HasColumnType("datetime(6)");
b.Property<double?>("Density")
.HasColumnType("double");
b.Property<string>("Description")
.IsRequired()
.HasMaxLength(50000)
.HasColumnType("longtext");
b.Property<string>("IconUriOreChunk")
.HasMaxLength(255)
.HasColumnType("varchar(255)");
b.Property<string>("IconUriRaw")
.HasMaxLength(255)
.HasColumnType("varchar(255)");
b.Property<string>("IconUriRefined")
.HasMaxLength(255)
.HasColumnType("varchar(255)");
b.Property<Guid>("MaterialCategoryId")
.HasColumnType("char(36)");
b.Property<double?>("MinArmor")
.HasColumnType("double");
b.Property<string>("Name")
.IsRequired()
.HasMaxLength(255)
.HasColumnType("varchar(255)");
b.Property<uint?>("OldId")
.HasColumnType("int unsigned");
b.Property<double?>("OreDensity")
.HasColumnType("double");
b.Property<double?>("StructuralDurability")
.HasColumnType("double");
b.Property<double?>("Transformability")
.HasColumnType("double");
b.Property<DateTimeOffset?>("UpdatedAt")
.HasColumnType("datetime(6)");
b.Property<double?>("VoxelPenetrationMultiplier")
.HasColumnType("double");
b.HasKey("Id");
b.HasIndex("MaterialCategoryId");
b.ToTable("InGame_Materials");
});
modelBuilder.Entity("starbase_nexus_api.Entities.InGame.MaterialCategory", b =>
{
b.Property<Guid>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("char(36)");
b.Property<DateTimeOffset>("CreatedAt")
.HasColumnType("datetime(6)");
b.Property<string>("Description")
.IsRequired()
.HasMaxLength(50000)
.HasColumnType("longtext");
b.Property<string>("Name")
.IsRequired()
.HasMaxLength(255)
.HasColumnType("varchar(255)");
b.Property<uint?>("OldId")
.HasColumnType("int unsigned");
b.Property<DateTimeOffset?>("UpdatedAt")
.HasColumnType("datetime(6)");
b.HasKey("Id");
b.ToTable("InGame_MaterialCategories");
});
modelBuilder.Entity("starbase_nexus_api.Entities.InGame.ShipShop", b =>
{
b.Property<Guid>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("char(36)");
b.Property<DateTimeOffset>("CreatedAt")
.HasColumnType("datetime(6)");
b.Property<string>("Description")
.IsRequired()
.HasMaxLength(255)
.HasColumnType("varchar(255)");
b.Property<int?>("Height")
.HasColumnType("int");
b.Property<string>("ImageUri")
.HasMaxLength(255)
.HasColumnType("varchar(255)");
b.Property<string>("Layout")
.IsRequired()
.HasMaxLength(255)
.HasColumnType("varchar(255)");
b.Property<int?>("Left")
.HasColumnType("int");
b.Property<string>("Name")
.IsRequired()
.HasMaxLength(255)
.HasColumnType("varchar(255)");
b.Property<uint?>("OldId")
.HasColumnType("int unsigned");
b.Property<int?>("Top")
.HasColumnType("int");
b.Property<DateTimeOffset?>("UpdatedAt")
.HasColumnType("datetime(6)");
b.Property<int?>("Width")
.HasColumnType("int");
b.HasKey("Id");
b.ToTable("InGame_ShipShops");
});
modelBuilder.Entity("starbase_nexus_api.Entities.InGame.ShipShopSpot", b =>
{
b.Property<Guid>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("char(36)");
b.Property<DateTimeOffset>("CreatedAt")
.HasColumnType("datetime(6)");
b.Property<int?>("Height")
.HasColumnType("int");
b.Property<int?>("Left")
.HasColumnType("int");
b.Property<uint?>("OldId")
.HasColumnType("int unsigned");
b.Property<int>("Position")
.HasColumnType("int");
b.Property<Guid?>("ShipId")
.IsRequired()
.HasColumnType("char(36)");
b.Property<Guid>("ShipShopId")
.HasColumnType("char(36)");
b.Property<int>("Size")
.HasColumnType("int");
b.Property<int?>("Top")
.HasColumnType("int");
b.Property<DateTimeOffset?>("UpdatedAt")
.HasColumnType("datetime(6)");
b.Property<int?>("Width")
.HasColumnType("int");
b.HasKey("Id");
b.HasIndex("ShipId");
b.HasIndex("ShipShopId");
b.ToTable("InGame_ShipShopSpots");
});
modelBuilder.Entity("starbase_nexus_api.Entities.Knowledge.Guide", b =>
{
b.Property<Guid>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("char(36)");
b.Property<string>("Bodytext")
.HasMaxLength(50000)
.HasColumnType("longtext");
b.Property<DateTimeOffset>("CreatedAt")
.HasColumnType("datetime(6)");
b.Property<string>("CreatorId")
.IsRequired()
.HasMaxLength(36)
.HasColumnType("varchar(36)");
b.Property<uint?>("OldId")
.HasColumnType("int unsigned");
b.Property<string>("Title")
.IsRequired()
.HasMaxLength(255)
.HasColumnType("varchar(255)");
b.Property<DateTimeOffset?>("UpdatedAt")
.HasColumnType("datetime(6)");
b.Property<string>("YoutubeVideoUri")
.HasMaxLength(50000)
.HasColumnType("longtext");
b.HasKey("Id");
b.HasIndex("CreatorId");
b.ToTable("Knowledge_Guides");
});
modelBuilder.Entity("starbase_nexus_api.Entities.Social.Company", b =>
{
b.Property<Guid>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("char(36)");
b.Property<string>("AboutUs")
.IsRequired()
.HasMaxLength(50000)
.HasColumnType("longtext");
b.Property<DateTimeOffset>("CreatedAt")
.HasColumnType("datetime(6)");
b.Property<string>("CreatorId")
.IsRequired()
.HasMaxLength(36)
.HasColumnType("varchar(36)");
b.Property<string>("DiscordUri")
.HasMaxLength(255)
.HasColumnType("varchar(255)");
b.Property<string>("LogoUri")
.HasMaxLength(255)
.HasColumnType("varchar(255)");
b.Property<string>("Name")
.IsRequired()
.HasMaxLength(255)
.HasColumnType("varchar(255)");
b.Property<uint?>("OldId")
.HasColumnType("int unsigned");
b.Property<string>("TwitchUri")
.HasMaxLength(255)
.HasColumnType("varchar(255)");
b.Property<DateTimeOffset?>("UpdatedAt")
.HasColumnType("datetime(6)");
b.Property<string>("WebsiteUri")
.HasMaxLength(255)
.HasColumnType("varchar(255)");
b.Property<string>("YoutubeUri")
.HasMaxLength(255)
.HasColumnType("varchar(255)");
b.HasKey("Id");
b.HasIndex("CreatorId");
b.ToTable("Social_Companies");
});
modelBuilder.Entity("starbase_nexus_api.Entities.Social.Like", b =>
{
b.Property<Guid>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("char(36)");
b.Property<DateTimeOffset>("CreatedAt")
.HasColumnType("datetime(6)");
b.Property<Guid?>("GuideId")
.HasColumnType("char(36)");
b.Property<uint?>("OldId")
.HasColumnType("int unsigned");
b.Property<DateTimeOffset?>("UpdatedAt")
.HasColumnType("datetime(6)");
b.Property<string>("UserId")
.HasMaxLength(36)
.HasColumnType("varchar(36)");
b.Property<Guid?>("YololProjectId")
.HasColumnType("char(36)");
b.HasKey("Id");
b.HasIndex("GuideId");
b.HasIndex("UserId");
b.HasIndex("YololProjectId");
b.ToTable("Social_Likes");
});
modelBuilder.Entity("starbase_nexus_api.Entities.Social.Rating", b =>
{
b.Property<Guid>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("char(36)");
b.Property<string>("Comment")
.HasMaxLength(50000)
.HasColumnType("longtext");
b.Property<DateTimeOffset>("CreatedAt")
.HasColumnType("datetime(6)");
b.Property<uint?>("OldId")
.HasColumnType("int unsigned");
b.Property<Guid>("ShipId")
.HasColumnType("char(36)");
b.Property<uint>("Stars")
.HasColumnType("int unsigned");
b.Property<DateTimeOffset?>("UpdatedAt")
.HasColumnType("datetime(6)");
b.Property<string>("UserId")
.IsRequired()
.HasMaxLength(36)
.HasColumnType("varchar(36)");
b.HasKey("Id");
b.HasIndex("ShipId");
b.HasIndex("UserId");
b.ToTable("Social_Ratings");
});
modelBuilder.Entity("starbase_nexus_api.Entities.Yolol.YololProject", b =>
{
b.Property<Guid>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("char(36)");
b.Property<DateTimeOffset>("CreatedAt")
.HasColumnType("datetime(6)");
b.Property<string>("CreatorId")
.IsRequired()
.HasMaxLength(36)
.HasColumnType("varchar(36)");
b.Property<string>("Documentation")
.IsRequired()
.HasMaxLength(50000)
.HasColumnType("longtext");
b.Property<string>("Name")
.IsRequired()
.HasMaxLength(255)
.HasColumnType("varchar(255)");
b.Property<uint?>("OldId")
.HasColumnType("int unsigned");
b.Property<string>("PreviewImageUri")
.HasMaxLength(50000)
.HasColumnType("longtext");
b.Property<DateTimeOffset?>("UpdatedAt")
.HasColumnType("datetime(6)");
b.Property<string>("YoutubeVideoUri")
.HasMaxLength(50000)
.HasColumnType("longtext");
b.HasKey("Id");
b.HasIndex("CreatorId");
b.ToTable("Yolol_YololProjects");
});
modelBuilder.Entity("starbase_nexus_api.Entities.Yolol.YololScript", b =>
{
b.Property<Guid>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("char(36)");
b.Property<string>("Code")
.IsRequired()
.HasMaxLength(50000)
.HasColumnType("longtext");
b.Property<DateTimeOffset>("CreatedAt")
.HasColumnType("datetime(6)");
b.Property<uint?>("OldId")
.HasColumnType("int unsigned");
b.Property<Guid>("ProjectId")
.HasColumnType("char(36)");
b.Property<DateTimeOffset?>("UpdatedAt")
.HasColumnType("datetime(6)");
b.HasKey("Id");
b.HasIndex("ProjectId");
b.ToTable("Yolol_YololScripts");
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRoleClaim<string>", b =>
{
b.HasOne("starbase_nexus_api.Entities.Identity.Role", null)
.WithMany()
.HasForeignKey("RoleId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserClaim<string>", b =>
{
b.HasOne("starbase_nexus_api.Entities.Identity.User", null)
.WithMany()
.HasForeignKey("UserId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserLogin<string>", b =>
{
b.HasOne("starbase_nexus_api.Entities.Identity.User", null)
.WithMany()
.HasForeignKey("UserId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserRole<string>", b =>
{
b.HasOne("starbase_nexus_api.Entities.Identity.Role", null)
.WithMany()
.HasForeignKey("RoleId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.HasOne("starbase_nexus_api.Entities.Identity.User", null)
.WithMany()
.HasForeignKey("UserId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserToken<string>", b =>
{
b.HasOne("starbase_nexus_api.Entities.Identity.User", null)
.WithMany()
.HasForeignKey("UserId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
});
modelBuilder.Entity("starbase_nexus_api.Entities.Authentication.RefreshToken", b =>
{
b.HasOne("starbase_nexus_api.Entities.Identity.User", "User")
.WithMany()
.HasForeignKey("UserId")
.OnDelete(DeleteBehavior.Restrict)
.IsRequired();
b.Navigation("User");
});
modelBuilder.Entity("starbase_nexus_api.Entities.Constructions.Ship", b =>
{
b.HasOne("starbase_nexus_api.Entities.InGame.Material", "ArmorMaterial")
.WithMany()
.HasForeignKey("ArmorMaterialId")
.OnDelete(DeleteBehavior.Restrict);
b.HasOne("starbase_nexus_api.Entities.Social.Company", "Company")
.WithMany()
.HasForeignKey("CompanyId")
.OnDelete(DeleteBehavior.Restrict);
b.HasOne("starbase_nexus_api.Entities.Identity.User", "Creator")
.WithMany()
.HasForeignKey("CreatorId")
.OnDelete(DeleteBehavior.Restrict);
b.Navigation("ArmorMaterial");
b.Navigation("Company");
b.Navigation("Creator");
});
modelBuilder.Entity("starbase_nexus_api.Entities.Constructions.ShipMaterialCost", b =>
{
b.HasOne("starbase_nexus_api.Entities.InGame.Material", "Material")
.WithMany()
.HasForeignKey("MaterialId")
.OnDelete(DeleteBehavior.Restrict)
.IsRequired();
b.HasOne("starbase_nexus_api.Entities.Constructions.Ship", "Ship")
.WithMany()
.HasForeignKey("ShipId")
.OnDelete(DeleteBehavior.Restrict)
.IsRequired();
b.Navigation("Material");
b.Navigation("Ship");
});
modelBuilder.Entity("starbase_nexus_api.Entities.Constructions.ShipRoleReference", b =>
{
b.HasOne("starbase_nexus_api.Entities.Constructions.Ship", "Ship")
.WithMany("ShipRoles")
.HasForeignKey("ShipId")
.OnDelete(DeleteBehavior.Restrict)
.IsRequired();
b.HasOne("starbase_nexus_api.Entities.Constructions.ShipRole", "ShipRole")
.WithMany()
.HasForeignKey("ShipRoleId")
.OnDelete(DeleteBehavior.Restrict)
.IsRequired();
b.Navigation("Ship");
b.Navigation("ShipRole");
});
modelBuilder.Entity("starbase_nexus_api.Entities.InGame.Item", b =>
{
b.HasOne("starbase_nexus_api.Entities.InGame.ItemCategory", "ItemCategory")
.WithMany()
.HasForeignKey("ItemCategoryId")
.OnDelete(DeleteBehavior.Restrict)
.IsRequired();
b.HasOne("starbase_nexus_api.Entities.InGame.Material", "PrimaryMaterial")
.WithMany()
.HasForeignKey("PrimaryMaterialId")
.OnDelete(DeleteBehavior.Restrict);
b.Navigation("ItemCategory");
b.Navigation("PrimaryMaterial");
});
modelBuilder.Entity("starbase_nexus_api.Entities.InGame.ItemCategory", b =>
{
b.HasOne("starbase_nexus_api.Entities.InGame.ItemCategory", "Parent")
.WithMany()
.HasForeignKey("ParentId")
.OnDelete(DeleteBehavior.Restrict);
b.Navigation("Parent");
});
modelBuilder.Entity("starbase_nexus_api.Entities.InGame.Material", b =>
{
b.HasOne("starbase_nexus_api.Entities.InGame.MaterialCategory", "MaterialCategory")
.WithMany()
.HasForeignKey("MaterialCategoryId")
.OnDelete(DeleteBehavior.Restrict)
.IsRequired();
b.Navigation("MaterialCategory");
});
modelBuilder.Entity("starbase_nexus_api.Entities.InGame.ShipShopSpot", b =>
{
b.HasOne("starbase_nexus_api.Entities.Constructions.Ship", "Ship")
.WithMany()
.HasForeignKey("ShipId")
.OnDelete(DeleteBehavior.Restrict)
.IsRequired();
b.HasOne("starbase_nexus_api.Entities.InGame.ShipShop", "ShipShop")
.WithMany()
.HasForeignKey("ShipShopId")
.OnDelete(DeleteBehavior.Restrict)
.IsRequired();
b.Navigation("Ship");
b.Navigation("ShipShop");
});
modelBuilder.Entity("starbase_nexus_api.Entities.Knowledge.Guide", b =>
{
b.HasOne("starbase_nexus_api.Entities.Identity.User", "Creator")
.WithMany()
.HasForeignKey("CreatorId")
.OnDelete(DeleteBehavior.Restrict)
.IsRequired();
b.Navigation("Creator");
});
modelBuilder.Entity("starbase_nexus_api.Entities.Social.Company", b =>
{
b.HasOne("starbase_nexus_api.Entities.Identity.User", "Creator")
.WithMany()
.HasForeignKey("CreatorId")
.OnDelete(DeleteBehavior.Restrict)
.IsRequired();
b.Navigation("Creator");
});
modelBuilder.Entity("starbase_nexus_api.Entities.Social.Like", b =>
{
b.HasOne("starbase_nexus_api.Entities.Knowledge.Guide", "Guide")
.WithMany()
.HasForeignKey("GuideId")
.OnDelete(DeleteBehavior.Restrict);
b.HasOne("starbase_nexus_api.Entities.Identity.User", "User")
.WithMany()
.HasForeignKey("UserId")
.OnDelete(DeleteBehavior.Restrict);
b.HasOne("starbase_nexus_api.Entities.Yolol.YololProject", "YololProject")
.WithMany()
.HasForeignKey("YololProjectId")
.OnDelete(DeleteBehavior.Restrict);
b.Navigation("Guide");
b.Navigation("User");
b.Navigation("YololProject");
});
modelBuilder.Entity("starbase_nexus_api.Entities.Social.Rating", b =>
{
b.HasOne("starbase_nexus_api.Entities.Constructions.Ship", "Ship")
.WithMany()
.HasForeignKey("ShipId")
.OnDelete(DeleteBehavior.Restrict)
.IsRequired();
b.HasOne("starbase_nexus_api.Entities.Identity.User", "User")
.WithMany()
.HasForeignKey("UserId")
.OnDelete(DeleteBehavior.Restrict)
.IsRequired();
b.Navigation("Ship");
b.Navigation("User");
});
modelBuilder.Entity("starbase_nexus_api.Entities.Yolol.YololProject", b =>
{
b.HasOne("starbase_nexus_api.Entities.Identity.User", "Creator")
.WithMany()
.HasForeignKey("CreatorId")
.OnDelete(DeleteBehavior.Restrict)
.IsRequired();
b.Navigation("Creator");
});
modelBuilder.Entity("starbase_nexus_api.Entities.Yolol.YololScript", b =>
{
b.HasOne("starbase_nexus_api.Entities.Yolol.YololProject", "Project")
.WithMany()
.HasForeignKey("ProjectId")
.OnDelete(DeleteBehavior.Restrict)
.IsRequired();
b.Navigation("Project");
});
modelBuilder.Entity("starbase_nexus_api.Entities.Constructions.Ship", b =>
{
b.Navigation("ShipRoles");
});
#pragma warning restore 612, 618
}
}
}
| 37.297429 | 104 | 0.422761 | [
"MIT"
] | WildChild85/starbase-nexus-api | starbase-nexus-api/Migrations/20211012183203_RenameShipClassToRole.Designer.cs | 53,673 | C# |
using System;
namespace MouseNet.Tools.Timers
{
/// <inheritdoc cref="INamedObject" />
/// <summary>
/// Represents the data associated with a timer's <c>Elapsed</c> event.
/// </summary>
/// <seealso cref="EventArgs" />
/// <seealso cref="INamedObject" />
public class ElapsedEventArgs : EventArgs, INamedObject
{
/// <summary>
/// Initializes a new instance of the <see cref="ElapsedEventArgs" /> class.
/// </summary>
/// <param name="name">The name of the elapsed timer.</param>
public ElapsedEventArgs
(string name)
{
Name = name;
}
/// <inheritdoc />
public object Value => this;
/// <inheritdoc />
public Type Type => GetType();
/// <inheritdoc />
public string Name { get; }
}
/// <inheritdoc />
/// <summary>
/// Represents the data associated with a <see cref="Counter" />'s <c>Tick</c> event.
/// </summary>
/// <seealso cref="ElapsedEventArgs" />
public class TickEventArgs : ElapsedEventArgs
{
/// <summary>
/// Initializes a new instance of the <see cref="T:MouseNet.Tools.Timers.TickEventArgs" /> class.
/// </summary>
/// <param name="timerName">Name of the timer.</param>
/// <param name="timeRemaining">The time remaining.</param>
public TickEventArgs
(string timerName,
TimeSpan timeRemaining)
: base(timerName)
{
TimeRemaining = timeRemaining;
}
/// <summary>
/// Gets the alarm's time remaining at the time of the
/// <c>Tick</c>.
/// </summary>
/// <value>
/// The time remaining.
/// </value>
public TimeSpan TimeRemaining { get; }
}
} | 31.333333 | 109 | 0.527128 | [
"MIT"
] | mousebyte/MouseNet | Tools/Timers/EventArgs.cs | 1,882 | C# |
using Xunit;
namespace SplitStringBalancedStrings.Tests
{
public class SolutionShould
{
[Theory]
[MemberData(nameof(SolutionShouldTestData.TestData), MemberType = typeof(SolutionShouldTestData))]
public void CountBalancedSubstrings(string inputString, int expectedNumbersOfBalancedSubstrings)
{
//Arrange
Solution sut = new Solution();
//Act
//Assert
Assert.Equal(expectedNumbersOfBalancedSubstrings, sut.BalancedStringSplit(inputString));
}
}
}
| 26.714286 | 106 | 0.659537 | [
"Apache-2.0"
] | codearchive/leetcode | Algorithms/Easy/1221/c-sharp/SplitStringBalancedStrings/SplitStringBalancedStrings.Tests/SolutionShould.cs | 561 | C# |
namespace Xtrimmer.SqlDatabaseBuilder
{
internal class Decimal : ExactFloatingPoint
{
internal Decimal()
{ }
internal Decimal(int precision)
{
Precision = precision;
}
internal Decimal(int precision, int scale) : this(precision)
{
Scale = scale;
}
protected override string TypeValue { get; } = "decimal";
}
}
| 19.227273 | 68 | 0.550827 | [
"Apache-2.0"
] | Xtrimmer/SqlDatabaseBuilder | src/SqlDatabaseBuilder/DataTypes/FloatingPoint/Decimal.cs | 425 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using AsyncGenerator.TestCases;
using NUnit.Framework;
namespace AsyncGenerator.Tests.Formatting.Input
{
public class Async
{
public void Test()
{
Assert.DoesNotThrow(
() =>
{
SimpleFile.Read();
SimpleFile.Read();
});
Assert.DoesNotThrow(
delegate ()
{
SimpleFile.Read();
SimpleFile.Read();
});
Runner.RunWithParameter(
obj =>
{
SimpleFile.Read();
SimpleFile.Read();
});
#pragma warning disable CS0168 // Variable is declared but never used
#pragma warning disable CS8321 // Local function is declared but never used
void LocalDoubleRead()
#pragma warning restore CS8321 // Local function is declared but never used
#pragma warning restore CS0168 // Variable is declared but never used
{
SimpleFile.Read();
SimpleFile.Read();
}
}
void DoubleRead()
{
SimpleFile.Read();
SimpleFile.Read();
}
static void StaticDoubleRead()
{
SimpleFile.Read();
SimpleFile.Read();
}
public void PublicDoubleRead()
{
SimpleFile.Read();
SimpleFile.Read();
}
}
}
| 18.19697 | 75 | 0.665279 | [
"MIT"
] | bubdm/AsyncGenerator | Source/AsyncGenerator.Tests/Formatting/Input/Async.cs | 1,203 | C# |
using System;
namespace Afonsoft.SetBox.Url
{
public class NullAppUrlService : IAppUrlService
{
public static IAppUrlService Instance { get; } = new NullAppUrlService();
private NullAppUrlService()
{
}
public string CreateEmailActivationUrlFormat(int? tenantId)
{
throw new NotImplementedException();
}
public string CreatePasswordResetUrlFormat(int? tenantId)
{
throw new NotImplementedException();
}
public string CreateEmailActivationUrlFormat(string tenancyName)
{
throw new NotImplementedException();
}
public string CreatePasswordResetUrlFormat(string tenancyName)
{
throw new NotImplementedException();
}
}
} | 24.205882 | 81 | 0.612394 | [
"Apache-2.0"
] | afonsoft/SetBox-VideoPlayer | SetBoxWebUI_New/src/Afonsoft.SetBox.Application/Url/NullAppUrlService.cs | 825 | C# |
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Net.Http.Headers;
using System.Web.Http.Description;
using IDTO.WebAPI.Areas.HelpPage.ModelDescriptions;
namespace IDTO.WebAPI.Areas.HelpPage.Models
{
/// <summary>
/// The model that represents an API displayed on the help page.
/// </summary>
public class HelpPageApiModel
{
/// <summary>
/// Initializes a new instance of the <see cref="HelpPageApiModel"/> class.
/// </summary>
public HelpPageApiModel()
{
UriParameters = new Collection<ParameterDescription>();
SampleRequests = new Dictionary<MediaTypeHeaderValue, object>();
SampleResponses = new Dictionary<MediaTypeHeaderValue, object>();
ErrorMessages = new Collection<string>();
}
/// <summary>
/// Gets or sets the <see cref="ApiDescription"/> that describes the API.
/// </summary>
public ApiDescription ApiDescription { get; set; }
/// <summary>
/// Gets or sets the <see cref="ParameterDescription"/> collection that describes the URI parameters for the API.
/// </summary>
public Collection<ParameterDescription> UriParameters { get; private set; }
/// <summary>
/// Gets or sets the documentation for the request.
/// </summary>
public string RequestDocumentation { get; set; }
/// <summary>
/// Gets or sets the <see cref="ModelDescription"/> that describes the request body.
/// </summary>
public ModelDescription RequestModelDescription { get; set; }
/// <summary>
/// Gets the request body parameter descriptions.
/// </summary>
public IList<ParameterDescription> RequestBodyParameters
{
get
{
return GetParameterDescriptions(RequestModelDescription);
}
}
/// <summary>
/// Gets or sets the <see cref="ModelDescription"/> that describes the resource.
/// </summary>
public ModelDescription ResourceDescription { get; set; }
/// <summary>
/// Gets the resource property descriptions.
/// </summary>
public IList<ParameterDescription> ResourceProperties
{
get
{
return GetParameterDescriptions(ResourceDescription);
}
}
/// <summary>
/// Gets the sample requests associated with the API.
/// </summary>
public IDictionary<MediaTypeHeaderValue, object> SampleRequests { get; private set; }
/// <summary>
/// Gets the sample responses associated with the API.
/// </summary>
public IDictionary<MediaTypeHeaderValue, object> SampleResponses { get; private set; }
/// <summary>
/// Gets the error messages associated with this model.
/// </summary>
public Collection<string> ErrorMessages { get; private set; }
private static IList<ParameterDescription> GetParameterDescriptions(ModelDescription modelDescription)
{
ComplexTypeModelDescription complexTypeModelDescription = modelDescription as ComplexTypeModelDescription;
if (complexTypeModelDescription != null)
{
return complexTypeModelDescription.Properties;
}
CollectionModelDescription collectionModelDescription = modelDescription as CollectionModelDescription;
if (collectionModelDescription != null)
{
complexTypeModelDescription = collectionModelDescription.ElementDescription as ComplexTypeModelDescription;
if (complexTypeModelDescription != null)
{
return complexTypeModelDescription.Properties;
}
}
return null;
}
}
} | 36.592593 | 123 | 0.614372 | [
"Apache-2.0"
] | OSADP/IDTO | IDTO Azure Hosted Systems/IDTO.WebAPI/Areas/HelpPage/Models/HelpPageApiModel.cs | 3,952 | C# |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See LICENSE in the project root for license information.
using HoloToolkit.Unity.InputModule;
using UnityEngine;
#if UNITY_EDITOR || UNITY_WSA
#endif
namespace HoloToolkit.Unity
{
/// <summary>
/// StabilizationPlaneModifier handles the setting of the stabilization plane in several ways.
/// </summary>
public class StabilizationPlaneModifier : Singleton<StabilizationPlaneModifier>
{
[Tooltip("Checking enables SetFocusPointForFrame to set the stabilization plane.")]
public bool SetStabilizationPlane = true;
[Tooltip("When lerping, use unscaled time. This is useful for games that have a pause mechanism or otherwise adjust the game timescale.")]
public bool UseUnscaledTime = true;
[Tooltip("Lerp speed when moving focus point closer.")]
public float LerpStabilizationPlanePowerCloser = 4.0f;
[Tooltip("Lerp speed when moving focus point farther away.")]
public float LerpStabilizationPlanePowerFarther = 7.0f;
[SerializeField, Tooltip("Used to temporarily override the location of the stabilization plane.")]
private Transform targetOverride;
public Transform TargetOverride
{
get
{
return targetOverride;
}
set
{
if (targetOverride != value)
{
targetOverride = value;
if (targetOverride)
{
targetOverridePreviousPosition = targetOverride.position;
}
}
}
}
[SerializeField, Tooltip("Keeps track of position-based velocity for the target object.")]
private bool trackVelocity;
public bool TrackVelocity
{
get
{
return trackVelocity;
}
set
{
trackVelocity = value;
if (TargetOverride)
{
targetOverridePreviousPosition = TargetOverride.position;
}
}
}
[Tooltip("Use the GazeManager class to set the plane to the gazed upon hologram. If disabled, the plane will always be at a constant distance.")]
public bool UseGazeManager = true;
[Tooltip("Default distance to set plane if plane is gaze-locked or if no object is hit.")]
public float DefaultPlaneDistance = 2.0f;
[Tooltip("Visualize the plane at runtime.")]
public bool DrawGizmos;
/// <summary>
/// Position of the plane in world space.
/// </summary>
private Vector3 planePosition;
/// <summary>
/// Current distance of the plane from the user's head. Only used when not using the target override
/// or the GazeManager to set the plane's position.
/// </summary>
private float currentPlaneDistance = 4.0f;
/// <summary>
/// Tracks the previous position of the target override object. Used if velocity is being tracked.
/// </summary>
private Vector3 targetOverridePreviousPosition;
/// <summary>
/// Updates the focus point for every frame after all objects have finished moving.
/// </summary>
private void LateUpdate()
{
if (SetStabilizationPlane)
{
float deltaTime = UseUnscaledTime
? Time.unscaledDeltaTime
: Time.deltaTime;
if (TargetOverride != null)
{
ConfigureTransformOverridePlane(deltaTime);
}
else if (UseGazeManager)
{
ConfigureGazeManagerPlane(deltaTime);
}
else
{
ConfigureFixedDistancePlane(deltaTime);
}
}
}
/// <summary>
/// Called by Unity when this script is loaded or a value is changed in the inspector.
/// Only called in editor, ensures that the property values always match the corresponding member variables.
/// </summary>
private void OnValidate()
{
TrackVelocity = trackVelocity;
TargetOverride = targetOverride;
}
/// <summary>
/// Gets the origin of the gaze for purposes of placing the stabilization plane
/// </summary>
private Vector3 GazeOrigin
{
get
{
if (GazeManager.Instance != null)
{
return GazeManager.Instance.GazeOrigin;
}
return Camera.main.transform.position;
}
}
/// <summary>
/// Gets the direction of the gaze for purposes of placing the stabilization plane
/// </summary>
private Vector3 GazeNormal
{
get
{
if (GazeManager.Instance != null)
{
return GazeManager.Instance.GazeNormal;
}
return Camera.main.transform.forward;
}
}
/// <summary>
/// Gets the position hit on the object the user is gazing at, if gaze tracking is supported.
/// </summary>
/// <param name="hitPosition">The position at which gaze ray intersects with an object.</param>
/// <returns>True if gaze is supported and an object was hit by gaze, otherwise false.</returns>
private bool TryGetGazeHitPosition(out Vector3 hitPosition)
{
if (GazeManager.Instance != null)
{
hitPosition = GazeManager.Instance.HitPosition;
return true;
}
hitPosition = Vector3.zero;
return false;
}
/// <summary>
/// Configures the stabilization plane to update its position based on an object in the scene.
/// </summary>
private void ConfigureTransformOverridePlane(float deltaTime)
{
planePosition = TargetOverride.position;
Vector3 velocity = Vector3.zero;
if (TrackVelocity)
{
velocity = UpdateVelocity(deltaTime);
}
#if UNITY_EDITOR || UNITY_WSA
// Place the plane at the desired depth in front of the user and billboard it to the gaze origin.
UnityEngine.XR.WSA.HolographicSettings.SetFocusPointForFrame(planePosition, -GazeNormal, velocity);
#endif
}
/// <summary>
/// Configures the stabilization plane to update its position based on what your gaze intersects in the scene.
/// </summary>
private void ConfigureGazeManagerPlane(float deltaTime)
{
Vector3 gazeOrigin = GazeOrigin;
Vector3 gazeDirection = GazeNormal;
// Calculate the delta between gaze origin's position and current hit position. If no object is hit, use default distance.
float focusPointDistance;
Vector3 gazeHitPosition;
if (TryGetGazeHitPosition(out gazeHitPosition))
{
focusPointDistance = (gazeOrigin - gazeHitPosition).magnitude;
}
else
{
focusPointDistance = DefaultPlaneDistance;
}
float lerpPower = focusPointDistance > currentPlaneDistance ? LerpStabilizationPlanePowerFarther
: LerpStabilizationPlanePowerCloser;
// Smoothly move the focus point from previous hit position to new position.
currentPlaneDistance = Mathf.Lerp(currentPlaneDistance, focusPointDistance, lerpPower * deltaTime);
planePosition = gazeOrigin + (gazeDirection * currentPlaneDistance);
#if UNITY_EDITOR || UNITY_WSA
UnityEngine.XR.WSA.HolographicSettings.SetFocusPointForFrame(planePosition, -gazeDirection, Vector3.zero);
#endif
}
/// <summary>
/// Configures the stabilization plane to update based on a fixed distance away from you.
/// </summary>
private void ConfigureFixedDistancePlane(float deltaTime)
{
Vector3 gazeOrigin = GazeOrigin;
Vector3 gazeNormal = GazeNormal;
float lerpPower = DefaultPlaneDistance > currentPlaneDistance ? LerpStabilizationPlanePowerFarther
: LerpStabilizationPlanePowerCloser;
// Smoothly move the focus point from previous hit position to new position.
currentPlaneDistance = Mathf.Lerp(currentPlaneDistance, DefaultPlaneDistance, lerpPower * deltaTime);
planePosition = gazeOrigin + (gazeNormal * currentPlaneDistance);
#if UNITY_EDITOR || UNITY_WSA
UnityEngine.XR.WSA.HolographicSettings.SetFocusPointForFrame(planePosition, -gazeNormal, Vector3.zero);
#endif
}
/// <summary>
/// Tracks the velocity of the target object to be used as a hint for the plane stabilization.
/// </summary>
private Vector3 UpdateVelocity(float deltaTime)
{
// Roughly calculate the velocity based on previous position, current position, and frame time.
Vector3 velocity = (TargetOverride.position - targetOverridePreviousPosition) / deltaTime;
targetOverridePreviousPosition = TargetOverride.position;
return velocity;
}
/// <summary>
/// When in editor, draws a magenta quad that visually represents the stabilization plane.
/// </summary>
private void OnDrawGizmos()
{
if (Application.isPlaying && DrawGizmos)
{
Vector3 focalPlaneNormal = -GazeNormal;
Vector3 planeUp = Vector3.Cross(Vector3.Cross(focalPlaneNormal, Vector3.up), focalPlaneNormal);
Gizmos.matrix = Matrix4x4.TRS(planePosition, Quaternion.LookRotation(focalPlaneNormal, planeUp), new Vector3(4.0f, 3.0f, 0.01f));
Color gizmoColor = Color.magenta;
gizmoColor.a = 0.5f;
Gizmos.color = gizmoColor;
Gizmos.DrawWireCube(Vector3.zero, Vector3.one);
Gizmos.DrawCube(Vector3.zero, Vector3.one);
}
}
}
} | 39.014337 | 154 | 0.569132 | [
"MIT"
] | AhmedAldahshoury/HololensApp | DesignLabs_Unity/Assets/HoloToolkit/Utilities/Scripts/StabilizationPlaneModifier.cs | 10,887 | C# |
// ------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License (MIT). See LICENSE in the repo root for license information.
// ------------------------------------------------------------
using System;
using System.Collections.Generic;
using System.Diagnostics;
using Microsoft.OData.Edm;
using Microsoft.OpenApi.Any;
using Microsoft.OpenApi.OData.Properties;
using Microsoft.OpenApi.Models;
using Microsoft.OpenApi.OData.Edm;
using Microsoft.OpenApi.OData.Common;
using Microsoft.OpenApi.Exceptions;
using System.Linq;
using Microsoft.OpenApi.Interfaces;
using Microsoft.OpenApi.OData.OpenApiExtensions;
namespace Microsoft.OpenApi.OData.Generator
{
/// <summary>
/// Extension methods to create <see cref="OpenApiSchema"/> by <see cref="IEdmModel"/>.
/// </summary>
internal static class OpenApiSchemaGenerator
{
/// <summary>
/// Create the dictionary of <see cref="OpenApiSchema"/> object.
/// The name of each pair is the namespace-qualified name of the type. It uses the namespace instead of the alias.
/// The value of each pair is a <see cref="OpenApiSchema"/>.
/// </summary>
/// <param name="context">The OData to Open API context.</param>
/// <returns>The string/schema dictionary.</returns>
public static IDictionary<string, OpenApiSchema> CreateSchemas(this ODataContext context)
{
Utils.CheckArgumentNull(context, nameof(context));
IDictionary<string, OpenApiSchema> schemas = new Dictionary<string, OpenApiSchema>();
// Each entity type, complex type, enumeration type, and type definition directly
// or indirectly used in the paths field is represented as a name / value pair of the schemas map.
// Ideally this would be driven off the types used in the paths, but in practice, it is simply
// all of the types present in the model.
IEnumerable<IEdmSchemaElement> elements = context.Model.GetAllElements();
foreach (var element in elements)
{
switch (element.SchemaElementKind)
{
case EdmSchemaElementKind.TypeDefinition: // Type definition
{
IEdmType reference = (IEdmType)element;
var fullTypeName = reference.FullTypeName();
if(reference is IEdmComplexType &&
fullTypeName.Split(new char[] {'.'}, StringSplitOptions.RemoveEmptyEntries)
.Last()
.Equals(context.Settings.InnerErrorComplexTypeName, StringComparison.Ordinal))
continue;
schemas.Add(fullTypeName, context.CreateSchemaTypeSchema(reference));
}
break;
}
}
// append the Edm.Spatial
foreach(var schema in context.CreateSpatialSchemas())
{
schemas[schema.Key] = schema.Value;
}
// append the OData errors
foreach(var schema in context.CreateODataErrorSchemas())
{
schemas[schema.Key] = schema.Value;
}
if(context.Settings.EnableDollarCountPath)
schemas[Constants.DollarCountSchemaName] = new OpenApiSchema {
Type = "integer",
Format = "int32"
};
schemas = schemas.Concat(context.GetAllCollectionEntityTypes()
.Select(x => new KeyValuePair<string, OpenApiSchema>(
$"{(x is IEdmEntityType eType ? eType.FullName() : x.FullTypeName())}{Constants.CollectionSchemaSuffix}",
CreateCollectionSchema(context, x)))
.Where(x => !schemas.ContainsKey(x.Key)))
.Concat(context.GetAllCollectionComplexTypes()
.Select(x => new KeyValuePair<string, OpenApiSchema>(
$"{x.FullTypeName()}{Constants.CollectionSchemaSuffix}",
CreateCollectionSchema(context, x)))
.Where(x => !schemas.ContainsKey(x.Key)))
.ToDictionary(x => x.Key, x => x.Value);
if(context.HasAnyNonContainedCollections())
{
schemas[$"String{Constants.CollectionSchemaSuffix}"] = CreateCollectionSchema(context, new OpenApiSchema { Type = "string" }, "string");
schemas[Constants.ReferenceUpdateSchemaName] = new()
{
Type = "object",
Properties = new Dictionary<string, OpenApiSchema>
{
{"@odata.id", new OpenApiSchema { Type = "string", Nullable = false }},
{"@odata.type", new OpenApiSchema { Type = "string", Nullable = true }},
}
};
}
return schemas;
}
internal static bool HasAnyNonContainedCollections(this ODataContext context)
{
return context.Model
.SchemaElements
.OfType<IEdmStructuredType>()
.SelectMany(x => x.NavigationProperties())
.Any(x => x.TargetMultiplicity() == EdmMultiplicity.Many && !x.ContainsTarget);
}
internal static IEnumerable<IEdmComplexType> GetAllCollectionComplexTypes(this ODataContext context)
{
return context.Model
.SchemaElements
.OfType<IEdmStructuredType>()
.SelectMany(x => x.StructuralProperties())
.Where(x => x.Type.IsCollection())
.Select(x => x.Type.Definition.AsElementType())
.OfType<IEdmComplexType>()
.Distinct()
.ToList();
}
internal static IEnumerable<IEdmStructuredType> GetAllCollectionEntityTypes(this ODataContext context)
{
var collectionEntityTypes = new HashSet<IEdmStructuredType>(
(context.EntityContainer?
.EntitySets()
.Select(x => x.EntityType()) ??
Enumerable.Empty<IEdmStructuredType>())
.Union(context.Model
.SchemaElements
.OfType<IEdmStructuredType>()
.SelectMany(x => x.NavigationProperties())
.Where(x => x.TargetMultiplicity() == EdmMultiplicity.Many)
.Select(x => x.Type.ToStructuredType()))
.Distinct()); // we could include actions and functions but actions are not pageable by nature (OData.NextLink) and functions might have specific annotations (deltalink)
var derivedCollectionTypes = collectionEntityTypes.SelectMany(x => context.Model.FindAllDerivedTypes(x).OfType<IEdmStructuredType>())
.Where(x => !collectionEntityTypes.Contains(x))
.Distinct()
.ToArray();
return collectionEntityTypes.Union(derivedCollectionTypes);
}
private static OpenApiSchema CreateCollectionSchema(ODataContext context, IEdmStructuredType structuredType)
{
OpenApiSchema schema = null;
var entityType = structuredType as IEdmEntityType;
if (context.Settings.EnableDerivedTypesReferencesForResponses && entityType != null)
{
schema = EdmModelHelper.GetDerivedTypesReferenceSchema(entityType, context.Model);
}
if (schema == null)
{
schema = new OpenApiSchema
{
UnresolvedReference = true,
Reference = new OpenApiReference
{
Type = ReferenceType.Schema,
Id = entityType?.FullName() ?? structuredType.FullTypeName()
}
};
}
return CreateCollectionSchema(context, schema, entityType?.Name ?? structuredType.FullTypeName());
}
private static OpenApiSchema CreateCollectionSchema(ODataContext context, OpenApiSchema schema, string typeName)
{
var properties = new Dictionary<string, OpenApiSchema>
{
{
"value",
new OpenApiSchema
{
Type = "array",
Items = schema
}
}
};
if (context.Settings.EnablePagination)
{
properties.Add(
"@odata.nextLink",
new OpenApiSchema
{
Type = "string"
});
}
return new OpenApiSchema
{
Title = $"Collection of {typeName}",
Type = "object",
Properties = properties
};
}
/// <summary>
/// Create a <see cref="OpenApiSchema"/> for a <see cref="IEdmEnumType"/>.
/// An enumeration type is represented as a Schema Object of type string containing the OpenAPI Specification enum keyword.
/// Its value is an array that contains a string with the member name for each enumeration member.
/// </summary>
/// <param name="context">The OData context.</param>
/// <param name="enumType">The Edm enum type.</param>
/// <returns>The created <see cref="OpenApiSchema"/>.</returns>
public static OpenApiSchema CreateEnumTypeSchema(this ODataContext context, IEdmEnumType enumType)
{
Utils.CheckArgumentNull(context, nameof(context));
Utils.CheckArgumentNull(enumType, nameof(enumType));
OpenApiSchema schema = new()
{
// An enumeration type is represented as a Schema Object of type string
Type = "string",
// containing the OpenAPI Specification enum keyword.
Enum = new List<IOpenApiAny>(),
// It optionally can contain the field description,
// whose value is the value of the unqualified annotation Core.Description of the enumeration type.
Description = context.Model.GetDescriptionAnnotation(enumType)
};
var extension = (context.Settings.OpenApiSpecVersion == OpenApiSpecVersion.OpenApi2_0 ||
context.Settings.OpenApiSpecVersion == OpenApiSpecVersion.OpenApi3_0 ) &&
context.Settings.AddEnumDescriptionExtension ?
new OpenApiEnumValuesDescriptionExtension {
EnumName = enumType.Name,
} :
null;
// Enum value is an array that contains a string with the member name for each enumeration member.
foreach (IEdmEnumMember member in enumType.Members)
{
schema.Enum.Add(new OpenApiString(member.Name));
AddEnumDescription(member, extension, context);
}
if(extension?.ValuesDescriptions.Any() ?? false)
schema.Extensions.Add(extension.Name, extension);
schema.Title = enumType.Name;
return schema;
}
private static void AddEnumDescription(IEdmEnumMember member, OpenApiEnumValuesDescriptionExtension target, ODataContext context)
{
if (target == null)
return;
var enumDescription = context.Model.GetDescriptionAnnotation(member);
if(!string.IsNullOrEmpty(enumDescription))
target.ValuesDescriptions.Add(new EnumDescription
{
Name = member.Name,
Value = member.Name,
Description = enumDescription
});
}
/// <summary>
/// Create a <see cref="OpenApiSchema"/> for a <see cref="IEdmStructuredType"/>.
/// </summary>
/// <param name="context">The OData context.</param>
/// <param name="structuredType">The Edm structured type.</param>
/// <returns>The created <see cref="OpenApiSchema"/>.</returns>
public static OpenApiSchema CreateStructuredTypeSchema(this ODataContext context, IEdmStructuredType structuredType)
{
Utils.CheckArgumentNull(context, nameof(context));
Utils.CheckArgumentNull(structuredType, nameof(structuredType));
return context.CreateStructuredTypeSchema(structuredType, true, true);
}
/// <summary>
/// Create a <see cref="OpenApiSchema"/> for a <see cref="IEdmProperty"/>.
/// Each structural property and navigation property is represented as a name/value pair of the
/// standard OpenAPI properties object. The name is the property name,
/// the value is a Schema Object describing the allowed values of the property.
/// </summary>
/// <param name="context">The OData context.</param>
/// <param name="property">The Edm property.</param>
/// <returns>The created <see cref="OpenApiSchema"/>.</returns>
public static OpenApiSchema CreatePropertySchema(this ODataContext context, IEdmProperty property)
{
Utils.CheckArgumentNull(context, nameof(context));
Utils.CheckArgumentNull(property, nameof(property));
OpenApiSchema schema = context.CreateEdmTypeSchema(property.Type);
switch (property.PropertyKind)
{
case EdmPropertyKind.Structural:
IEdmStructuralProperty structuralProperty = (IEdmStructuralProperty)property;
schema.Default = CreateDefault(structuralProperty);
break;
}
// The Schema Object for a property optionally can contain the field description,
// whose value is the value of the unqualified annotation Core.Description of the property.
schema.Description = context.Model.GetDescriptionAnnotation(property);
return schema;
}
/// <summary>
/// Create a map of string/<see cref="OpenApiSchema"/> map for a <see cref="IEdmStructuredType"/>'s all properties.
/// </summary>
/// <param name="context">The OData context.</param>
/// <param name="structuredType">The Edm structured type.</param>
/// <returns>The created map of <see cref="OpenApiSchema"/>.</returns>
public static IDictionary<string, OpenApiSchema> CreateStructuredTypePropertiesSchema(this ODataContext context, IEdmStructuredType structuredType)
{
Utils.CheckArgumentNull(context, nameof(context));
Utils.CheckArgumentNull(structuredType, nameof(structuredType));
// The name is the property name, the value is a Schema Object describing the allowed values of the property.
IDictionary<string, OpenApiSchema> properties = new Dictionary<string, OpenApiSchema>();
// structure properties
foreach (var property in structuredType.DeclaredStructuralProperties())
{
// OpenApiSchema propertySchema = property.Type.CreateSchema();
// propertySchema.Default = property.DefaultValueString != null ? new OpenApiString(property.DefaultValueString) : null;
properties.Add(property.Name, context.CreatePropertySchema(property));
}
// navigation properties
foreach (var property in structuredType.DeclaredNavigationProperties())
{
OpenApiSchema propertySchema = context.CreateEdmTypeSchema(property.Type);
propertySchema.Description = context.Model.GetDescriptionAnnotation(property);
properties.Add(property.Name, propertySchema);
}
return properties;
}
public static OpenApiSchema CreateSchemaTypeDefinitionSchema(this ODataContext context, IEdmTypeDefinition typeDefinition)
{
return context.CreateSchema(typeDefinition.UnderlyingType);
}
internal static OpenApiSchema CreateSchemaTypeSchema(this ODataContext context, IEdmType edmType)
{
Debug.Assert(context != null);
Debug.Assert(edmType != null);
switch (edmType.TypeKind)
{
case EdmTypeKind.Complex: // complex type
case EdmTypeKind.Entity: // entity type
return context.CreateStructuredTypeSchema((IEdmStructuredType)edmType, true, true);
case EdmTypeKind.Enum: // enum type
return context.CreateEnumTypeSchema((IEdmEnumType)edmType);
case EdmTypeKind.TypeDefinition: // type definition
return context.CreateSchemaTypeDefinitionSchema((IEdmTypeDefinition)edmType);
case EdmTypeKind.None:
default:
throw Error.NotSupported(String.Format(SRResource.NotSupportedEdmTypeKind, edmType.TypeKind));
}
}
private static OpenApiSchema CreateStructuredTypeSchema(this ODataContext context, IEdmStructuredType structuredType, bool processBase, bool processExample,
IEnumerable<IEdmEntityType> derivedTypes = null)
{
Debug.Assert(context != null);
Debug.Assert(structuredType != null);
IOpenApiAny example = null;
if (context.Settings.ShowSchemaExamples)
{
example = CreateStructuredTypePropertiesExample(context, structuredType);
}
if (context.Settings.EnableDiscriminatorValue && derivedTypes == null)
{
derivedTypes = context.Model.FindDirectlyDerivedTypes(structuredType).OfType<IEdmEntityType>();
}
if (processBase && structuredType.BaseType != null)
{
// The x-ms-discriminator-value extension is added to structured types which are derived types.
Dictionary<string, IOpenApiExtension> extension = null;
if (context.Settings.EnableDiscriminatorValue && !derivedTypes.Any())
{
extension = new Dictionary<string, IOpenApiExtension>
{
{ Constants.xMsDiscriminatorValue, new OpenApiString("#" + structuredType.FullTypeName()) }
};
}
// A structured type with a base type is represented as a Schema Object
// that contains the keyword allOf whose value is an array with two items:
return new OpenApiSchema
{
Extensions = extension,
AllOf = new List<OpenApiSchema>
{
// 1. a JSON Reference to the Schema Object of the base type
new OpenApiSchema
{
UnresolvedReference = true,
Reference = new OpenApiReference
{
Type = ReferenceType.Schema,
Id = structuredType.BaseType.FullTypeName()
}
},
// 2. a Schema Object describing the derived type
context.CreateStructuredTypeSchema(structuredType, false, false, derivedTypes)
},
AnyOf = null,
OneOf = null,
Properties = null,
Example = example
};
}
else
{
// The discriminator object is added to structured types which have derived types.
OpenApiDiscriminator discriminator = null;
if (context.Settings.EnableDiscriminatorValue && derivedTypes.Any() && structuredType.BaseType != null)
{
string v3RefIdentifier = new OpenApiSchema
{
Reference = new OpenApiReference
{
Type = ReferenceType.Schema,
Id = structuredType.FullTypeName()
}
}.Reference.ReferenceV3;
discriminator = new OpenApiDiscriminator
{
PropertyName = "@odata.type",
Mapping = new Dictionary<string, string>
{
{"#" + structuredType.FullTypeName(), v3RefIdentifier }
}
};
}
// A structured type without a base type is represented as a Schema Object of type object
OpenApiSchema schema = new OpenApiSchema
{
Title = (structuredType as IEdmSchemaElement)?.Name,
Type = "object",
Discriminator = discriminator,
// Each structural property and navigation property is represented
// as a name/value pair of the standard OpenAPI properties object.
Properties = context.CreateStructuredTypePropertiesSchema(structuredType),
// make others null
AllOf = null,
OneOf = null,
AnyOf = null
};
// It optionally can contain the field description,
// whose value is the value of the unqualified annotation Core.Description of the structured type.
if (structuredType.TypeKind == EdmTypeKind.Complex)
{
IEdmComplexType complex = (IEdmComplexType)structuredType;
schema.Description = context.Model.GetDescriptionAnnotation(complex);
}
else if (structuredType.TypeKind == EdmTypeKind.Entity)
{
IEdmEntityType entity = (IEdmEntityType)structuredType;
schema.Description = context.Model.GetDescriptionAnnotation(entity);
}
if (processExample)
{
schema.Example = example;
}
return schema;
}
}
private static IOpenApiAny CreateStructuredTypePropertiesExample(ODataContext context, IEdmStructuredType structuredType)
{
OpenApiObject example = new OpenApiObject();
IEdmEntityType entityType = structuredType as IEdmEntityType;
// properties
foreach (var property in structuredType.Properties())
{
// IOpenApiAny item;
IEdmTypeReference propertyType = property.Type;
IOpenApiAny item = GetTypeNameForExample(context, propertyType);
EdmTypeKind typeKind = propertyType.TypeKind();
if (typeKind == EdmTypeKind.Primitive && item is OpenApiString)
{
OpenApiString stringAny = item as OpenApiString;
string value = stringAny.Value;
if (entityType != null && entityType.Key().Any(k => k.Name == property.Name))
{
value += " (identifier)";
}
if (propertyType.IsDateTimeOffset() || propertyType.IsDate() || propertyType.IsTimeOfDay())
{
value += " (timestamp)";
}
item = new OpenApiString(value);
}
example.Add(property.Name, item);
}
return example;
}
private static IOpenApiAny GetTypeNameForExample(ODataContext context, IEdmTypeReference edmTypeReference)
{
switch (edmTypeReference.TypeKind())
{
case EdmTypeKind.Primitive:
IEdmPrimitiveType primitiveType = edmTypeReference.AsPrimitive().PrimitiveDefinition();
OpenApiSchema schema = context.CreateSchema(primitiveType);
if (edmTypeReference.IsBoolean())
{
return new OpenApiBoolean(true);
}
else
{
if (schema.Reference != null)
{
return new OpenApiString(schema.Reference.Id);
}
else
{
return new OpenApiString(schema.Type ?? schema.Format);
}
}
case EdmTypeKind.Entity:
case EdmTypeKind.Complex:
case EdmTypeKind.Enum:
OpenApiObject obj = new OpenApiObject();
obj["@odata.type"] = new OpenApiString(edmTypeReference.FullName());
return obj;
case EdmTypeKind.Collection:
OpenApiArray array = new OpenApiArray();
IEdmTypeReference elementType = edmTypeReference.AsCollection().ElementType();
array.Add(GetTypeNameForExample(context, elementType));
return array;
case EdmTypeKind.Untyped:
case EdmTypeKind.TypeDefinition:
case EdmTypeKind.EntityReference:
default:
throw new OpenApiException("Not support for the type kind " + edmTypeReference.TypeKind());
}
}
private static IOpenApiAny CreateDefault(this IEdmStructuralProperty property)
{
if (property == null ||
property.DefaultValueString == null)
{
return null;
}
if (property.Type.IsEnum())
{
return new OpenApiString(property.DefaultValueString);
}
if (!property.Type.IsPrimitive())
{
return null;
}
IEdmPrimitiveTypeReference primitiveTypeReference = property.Type.AsPrimitive();
switch (primitiveTypeReference.PrimitiveKind())
{
case EdmPrimitiveTypeKind.Boolean:
{
bool result;
if (Boolean.TryParse(property.DefaultValueString, out result))
{
return new OpenApiBoolean(result);
}
}
break;
case EdmPrimitiveTypeKind.Int16:
case EdmPrimitiveTypeKind.Int32:
{
int result;
if (Int32.TryParse(property.DefaultValueString, out result))
{
return new OpenApiInteger(result);
}
}
break;
case EdmPrimitiveTypeKind.Int64:
break;
// The type 'System.Double' is not supported in Open API document.
case EdmPrimitiveTypeKind.Double:
/*
{
double result;
if (Double.TryParse(property.DefaultValueString, out result))
{
return new OpenApiDouble((float)result);
}
}*/
break;
}
return new OpenApiString(property.DefaultValueString);
}
}
}
| 45.672387 | 217 | 0.524798 | [
"MIT"
] | Microsoft/OpenAPI.NET.OData | src/Microsoft.OpenApi.OData.Reader/Generator/OpenApiSchemaGenerator.cs | 29,278 | 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.Diagnostics;
using System.Text;
using Standard.Xaml;
using Standard.Xaml.MS.Impl;
using Standard.Xaml.Schema;
namespace MS.Internal.Xaml.Context
{
// Graph of unresolved forward references, and the objects that depend on them.
// The nodes are objects and names. The edges (NameFixupTokens) are dependencies from an object to
// a set of unresolved names, or from an object to another object that has unresolved dependencies.
internal class NameFixupGraph
{
// Node -> out-edges (other objects the parent is dependent on)
Dictionary<object, FrugalObjectList<NameFixupToken>> _dependenciesByParentObject;
// Node -> in-edge (other object that is dependent on this child)
Dictionary<object, NameFixupToken> _dependenciesByChildObject;
// Node -> in-edges (other objects that are dependent on this name)
Dictionary<string, FrugalObjectList<NameFixupToken>> _dependenciesByName;
// Queue of tokens whose dependencies have been resolved, and are awaiting processing
Queue<NameFixupToken> _resolvedTokensPendingProcessing;
// Token for a pending call to ProvideValue on the root object. Can't store this in
// _dependenciesByParentObject because it has no parent.
NameFixupToken _deferredRootProvideValue;
// At the end of the parse, we start running reparses on partially initialized objects,
// and remove those dependencies. But we still want to be able to inform MEs/TCs that
// the named objects they're getting aren't actually fully initialized. So we save this list
// of incompletely initialized objects at the point we start completing references.
HashSet <object> _uninitializedObjectsAtParseEnd;
public NameFixupGraph()
{
var referenceComparer = ReferenceEqualityComparer<object>.Singleton;
_dependenciesByChildObject = new Dictionary<object, NameFixupToken>(referenceComparer);
_dependenciesByName = new Dictionary<string, FrugalObjectList<NameFixupToken>>(StringComparer.Ordinal);
_dependenciesByParentObject = new Dictionary<object, FrugalObjectList<NameFixupToken>>(referenceComparer);
_resolvedTokensPendingProcessing = new Queue<NameFixupToken>();
_uninitializedObjectsAtParseEnd = new HashSet<object>(referenceComparer);
}
// Add an edge to the graph. We need to look up edges in both directions, so each edge is
// stored in two dictionaries.
public void AddDependency(NameFixupToken fixupToken)
{
// Need to special case a deferred ProvideValue at the root, because it has no parent
if (fixupToken.Target.Property == null)
{
Debug.Assert(fixupToken.Target.Instance == null &&
fixupToken.Target.InstanceType == null &&
fixupToken.FixupType == FixupType.MarkupExtensionFirstRun);
Debug.Assert(_deferredRootProvideValue == null);
_deferredRootProvideValue = fixupToken;
return;
}
object parentObject = fixupToken.Target.Instance;
// References aren't allowed in non-instantiating directives, except for:
// - Initialization, in which case FixupTarget.Instance is the object whose property the
// initialized object will be assigned to; and
// - Key, in which case the FixupTarget.Instance is the dictionary
Debug.Assert(parentObject != null);
AddToMultiDict(_dependenciesByParentObject, parentObject, fixupToken);
if (fixupToken.ReferencedObject != null)
{
Debug.Assert(fixupToken.FixupType == FixupType.UnresolvedChildren ||
fixupToken.FixupType == FixupType.MarkupExtensionFirstRun);
// These fixups are only used for the immediate parent of the object, so there can
// only be one per child instance
Debug.Assert(!_dependenciesByChildObject.ContainsKey(fixupToken.ReferencedObject));
_dependenciesByChildObject.Add(fixupToken.ReferencedObject, fixupToken);
}
else
{
Debug.Assert(fixupToken.FixupType != FixupType.UnresolvedChildren &&
fixupToken.FixupType != FixupType.MarkupExtensionFirstRun);
foreach (string name in fixupToken.NeededNames)
{
AddToMultiDict(_dependenciesByName, name, fixupToken);
}
}
}
public bool HasUnresolvedChildren(object parent)
{
if (parent == null)
{
return false;
}
return _dependenciesByParentObject.ContainsKey(parent);
}
public bool HasUnresolvedOrPendingChildren(object instance)
{
if (HasUnresolvedChildren(instance))
{
return true;
}
foreach (NameFixupToken pendingToken in _resolvedTokensPendingProcessing)
{
if (pendingToken.Target.Instance == instance)
{
return true;
}
}
return false;
}
public bool WasUninitializedAtEndOfParse(object instance)
{
return _uninitializedObjectsAtParseEnd.Contains(instance);
}
// Finds the names that this object's subtree is blocked on.
public void GetDependentNames(object instance, List<string> result)
{
// We're only interested in the immediate subtree, not named-references to other subtrees
// that might exist but not be fully initialized. So we only follow UnresolvedChildren and
// MarkupExtensionFirstRun edges, which means there is no risk of cycles
FrugalObjectList<NameFixupToken> dependencies;
if (!_dependenciesByParentObject.TryGetValue(instance, out dependencies))
{
return;
}
for (int i = 0; i < dependencies.Count; i++)
{
NameFixupToken token = dependencies[i];
if (token.FixupType == FixupType.MarkupExtensionFirstRun ||
token.FixupType == FixupType.UnresolvedChildren)
{
GetDependentNames(token.ReferencedObject, result);
}
else if (token.NeededNames != null)
{
foreach (string name in token.NeededNames)
{
if (!result.Contains(name))
{
result.Add(name);
}
}
}
}
}
// Remove a resolved dependency from the graph.
// Enqueues all removed edges so that the ObjectWriter can process the dependents
// (rerun converters, apply simple fixups, call EndInit on parent ojects, etc).
public void ResolveDependenciesTo(object instance, string name)
{
// Remove any dependency on this instance
NameFixupToken token = null;
if (instance != null)
{
if (_dependenciesByChildObject.TryGetValue(instance, out token))
{
_dependenciesByChildObject.Remove(instance);
RemoveTokenByParent(token);
_resolvedTokensPendingProcessing.Enqueue(token);
}
}
// Remove any dependencies on this name, and return any tokens whose dependencies
// have all been resolved.
FrugalObjectList<NameFixupToken> nameDependencies;
if (name != null && _dependenciesByName.TryGetValue(name, out nameDependencies))
{
int i = 0;
while (i < nameDependencies.Count)
{
token = nameDependencies[i];
// The same name can occur in multiple namescopes, so we need to make sure that
// this named object is visible in the scope of the token.
object resolvedName = token.ResolveName(name);
if (instance != resolvedName)
{
i++;
continue;
}
if (token.CanAssignDirectly)
{
// For simple fixups, we need to return the resolved object
token.ReferencedObject = instance;
}
token.NeededNames.Remove(name);
nameDependencies.RemoveAt(i);
if (nameDependencies.Count == 0)
{
_dependenciesByName.Remove(name);
}
if (token.NeededNames.Count == 0)
{
RemoveTokenByParent(token);
_resolvedTokensPendingProcessing.Enqueue(token);
}
}
}
}
public bool HasResolvedTokensPendingProcessing
{
get { return _resolvedTokensPendingProcessing.Count > 0; }
}
public NameFixupToken GetNextResolvedTokenPendingProcessing()
{
return _resolvedTokensPendingProcessing.Dequeue();
}
// ObjectWriter calls this whenever an object that has pending fixups goes off the stack.
public void IsOffTheStack(object instance, string name, int lineNumber, int linePosition)
{
FrugalObjectList<NameFixupToken> dependencies;
if (_dependenciesByParentObject.TryGetValue(instance, out dependencies))
{
for (int i = 0; i < dependencies.Count; i++)
{
dependencies[i].Target.InstanceIsOnTheStack = false;
dependencies[i].Target.InstanceName = name;
dependencies[i].Target.EndInstanceLineNumber = lineNumber;
dependencies[i].Target.EndInstanceLinePosition = linePosition;
}
}
}
public void AddEndOfParseDependency(object childThatHasUnresolvedChildren, FixupTarget parentObject)
{
NameFixupToken token = new NameFixupToken();
token.Target = parentObject;
token.FixupType = FixupType.UnresolvedChildren;
token.ReferencedObject = childThatHasUnresolvedChildren;
AddToMultiDict(_dependenciesByParentObject, parentObject.Instance, token);
// We don't add to the _dependenciesByChildObject, because at end-of-parse, a single
// child object can be a dependency of multiple parents
}
// At end of parse, removes and returns all remaining simple fixups, whether or not they
// are resolved
public IEnumerable<NameFixupToken> GetRemainingSimpleFixups()
{
foreach (object key in _dependenciesByParentObject.Keys)
{
_uninitializedObjectsAtParseEnd.Add(key);
}
List<string> names = new List<string>(_dependenciesByName.Keys);
foreach (string name in names)
{
FrugalObjectList<NameFixupToken> dependencies = _dependenciesByName[name];
int i = 0;
while (i < dependencies.Count)
{
NameFixupToken token = dependencies[i];
if (!token.CanAssignDirectly)
{
i++;
continue;
}
dependencies.RemoveAt(i);
if (dependencies.Count == 0)
{
_dependenciesByName.Remove(name);
}
RemoveTokenByParent(token);
yield return token;
}
}
}
// At end of parse, removes and returns all remaining reparse fixups, whether or not they
// are resolved. Assumes that all simple fixups have already been removed.
public IEnumerable<NameFixupToken> GetRemainingReparses()
{
List<object> parentObjs = new List<object>(_dependenciesByParentObject.Keys);
foreach (object parentObj in parentObjs)
{
FrugalObjectList<NameFixupToken> dependencies = _dependenciesByParentObject[parentObj];
int i = 0;
while (i < dependencies.Count)
{
NameFixupToken token = dependencies[i];
if (token.FixupType == FixupType.MarkupExtensionFirstRun ||
token.FixupType == FixupType.UnresolvedChildren)
{
i++;
continue;
}
// Remove this token from the _dependenciesByParentObject dictionary
dependencies.RemoveAt(i);
if (dependencies.Count == 0)
{
_dependenciesByParentObject.Remove(parentObj);
}
// Remove this token from the _dependenciesByName dictionary
foreach (string name in token.NeededNames)
{
FrugalObjectList<NameFixupToken> nameDependencies = _dependenciesByName[name];
if (nameDependencies.Count == 1)
{
nameDependencies.Remove(token);
}
else
{
_dependenciesByName.Remove(name);
}
}
yield return token;
}
}
}
// At end of parse, removes and returns all remaining MarkupExtensionFirstRun and UnresolvedChildren
// tokens, even if they are not fully initialized. Assumes that all simple fixups and reparses have
// already been removed.
public IEnumerable<NameFixupToken> GetRemainingObjectDependencies()
{
// We'd like to return dependencies in a topologically sorted order, but the graph is
// not acylic. (If it were, all references would have been resolved during the regular parse.)
// However, we don't allow ProvideValue cycles. So find a MarkupExtension that doesn't have
// dependencies on any other MarkupExtension.
// Note: at this point we can't use _dependenciesByChildObject for general traversal,
// because it's not updated by AddEndOfParseDependency. However, AddEndOfParseDependency
// doesn't add MarkupExtension edges, so we can still use _dependenciesByChildObject for that.
List<NameFixupToken> markupExtensionTokens = new List<NameFixupToken>();
foreach (NameFixupToken curToken in _dependenciesByChildObject.Values)
{
if (curToken.FixupType == FixupType.MarkupExtensionFirstRun)
{
markupExtensionTokens.Add(curToken);
}
}
while (markupExtensionTokens.Count > 0)
{
bool found = false;
int i = 0;
while (i < markupExtensionTokens.Count)
{
NameFixupToken meToken = markupExtensionTokens[i];
List<NameFixupToken> dependencies = new List<NameFixupToken>();
if (!FindDependencies(meToken, dependencies))
{
i++;
continue;
}
// Iterate the list in backwards order, so we return the deepest first
for (int j = dependencies.Count - 1; j >= 0; j--)
{
NameFixupToken token = dependencies[j];
RemoveTokenByParent(token);
yield return token;
}
found = true;
markupExtensionTokens.RemoveAt(i);
}
if (!found)
{
// We have MEs left, but they all have dependencies on other MEs.
// That means we have a cycle.
ThrowProvideValueCycle(markupExtensionTokens);
}
}
// For the remaining EndInits, we pick an arbitrary point and return a DFS of its dependencies
while (_dependenciesByParentObject.Count > 0)
{
FrugalObjectList<NameFixupToken> startNodeOutEdges = null;
foreach (FrugalObjectList<NameFixupToken> list in _dependenciesByParentObject.Values)
{
startNodeOutEdges = list;
break;
}
for (int i = 0; i < startNodeOutEdges.Count; i++)
{
List<NameFixupToken> dependencies = new List<NameFixupToken>();
FindDependencies(startNodeOutEdges[i], dependencies);
// Iterate the list in backwards order, so we return the deepest first
for (int j = dependencies.Count - 1; j >= 0; j--)
{
NameFixupToken token = dependencies[j];
RemoveTokenByParent(token);
yield return token;
}
}
}
// Finally, if there was a deferred ProvideValue at the root, return it
if (_deferredRootProvideValue != null)
{
yield return _deferredRootProvideValue;
}
}
// Depth-first traversal of the graph starting at a given edge. Ignores edges that would cause cycles.
// Returns true if the dependency list is complete, false if we aborted because we found an ME.
private bool FindDependencies(NameFixupToken inEdge, List<NameFixupToken> alreadyTraversed)
{
if (alreadyTraversed.Contains(inEdge))
{
// Cycle, skip it
return true;
}
alreadyTraversed.Add(inEdge);
FrugalObjectList<NameFixupToken> outEdges;
if (inEdge.ReferencedObject == null ||
!_dependenciesByParentObject.TryGetValue(inEdge.ReferencedObject, out outEdges))
{
// No dependencies, we're done with this subgraph
return true;
}
for (int i = 0; i < outEdges.Count; i++)
{
NameFixupToken outEdge = outEdges[i];
if (outEdge.FixupType == FixupType.MarkupExtensionFirstRun)
{
return false;
}
Debug.Assert(outEdge.FixupType == FixupType.UnresolvedChildren);
if (!FindDependencies(outEdge, alreadyTraversed))
{
return false;
}
}
return true;
}
private void RemoveTokenByParent(NameFixupToken token)
{
object parentInstance = token.Target.Instance;
FrugalObjectList<NameFixupToken> parentDependencies = _dependenciesByParentObject[parentInstance];
Debug.Assert(parentDependencies.Contains(token));
if (parentDependencies.Count == 1)
{
_dependenciesByParentObject.Remove(parentInstance);
}
else
{
parentDependencies.Remove(token);
}
}
private static void AddToMultiDict<TKey>(Dictionary<TKey, FrugalObjectList<NameFixupToken>> dict,
TKey key, NameFixupToken value)
{
FrugalObjectList<NameFixupToken> tokenList;
if (!dict.TryGetValue(key, out tokenList))
{
tokenList = new FrugalObjectList<NameFixupToken>(1);
dict.Add(key, tokenList);
}
tokenList.Add(value);
}
private static void ThrowProvideValueCycle(IEnumerable<NameFixupToken> markupExtensionTokens)
{
StringBuilder exceptionMessage = new StringBuilder();
exceptionMessage.Append(SR.Get(SRID.ProvideValueCycle));
foreach (NameFixupToken token in markupExtensionTokens)
{
exceptionMessage.AppendLine();
string meName = token.ReferencedObject.ToString();
if (token.LineNumber != 0)
{
if (token.LinePosition != 0)
{
exceptionMessage.Append(SR.Get(SRID.LineNumberAndPosition, meName, token.LineNumber, token.LinePosition));
}
else
{
exceptionMessage.Append(SR.Get(SRID.LineNumberOnly, meName, token.LineNumber));
}
}
else
{
exceptionMessage.Append(meName);
}
}
throw new XamlObjectWriterException(exceptionMessage.ToString());
}
}
}
| 43.639442 | 130 | 0.556534 | [
"MIT"
] | alexander-zhuravlev/Standard.Xaml | src/Standard.Xaml/Standard/Xaml/Context/NameFixupGraph.cs | 21,909 | 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.Net;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.TestHost;
using Microsoft.Extensions.Hosting;
using Xunit;
namespace Microsoft.AspNetCore.Diagnostics.HealthChecks
{
public class HealthCheckMiddlewareSampleTest
{
[Fact]
public async Task BasicStartup()
{
using var host = new HostBuilder()
.ConfigureWebHost(
webHostBuilder =>
{
webHostBuilder
.UseTestServer()
.UseStartup<HealthChecksSample.BasicStartup>();
}
)
.Build();
await host.StartAsync();
var server = host.GetTestServer();
var client = server.CreateClient();
var response = await client.GetAsync("/health");
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
Assert.Equal("text/plain", response.Content.Headers.ContentType.ToString());
Assert.Equal("Healthy", await response.Content.ReadAsStringAsync());
}
[Fact]
public async Task CustomWriterStartup()
{
using var host = new HostBuilder()
.ConfigureWebHost(
webHostBuilder =>
{
webHostBuilder
.UseTestServer()
.UseStartup<HealthChecksSample.CustomWriterStartup>();
}
)
.Build();
await host.StartAsync();
var server = host.GetTestServer();
var client = server.CreateClient();
var response = await client.GetAsync("/health");
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
Assert.Equal("application/json", response.Content.Headers.ContentType.ToString());
// Ignoring the body since it contains a bunch of statistics
}
[Fact]
public async Task LivenessProbeStartup_Liveness()
{
using var host = new HostBuilder()
.ConfigureWebHost(
webHostBuilder =>
{
webHostBuilder
.UseTestServer()
.UseStartup<HealthChecksSample.LivenessProbeStartup>();
}
)
.Build();
await host.StartAsync();
var server = host.GetTestServer();
var client = server.CreateClient();
var response = await client.GetAsync("/health/live");
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
Assert.Equal("text/plain", response.Content.Headers.ContentType.ToString());
Assert.Equal("Healthy", await response.Content.ReadAsStringAsync());
}
[Fact]
public async Task LivenessProbeStartup_Readiness()
{
using var host = new HostBuilder()
.ConfigureWebHost(
webHostBuilder =>
{
webHostBuilder
.UseTestServer()
.UseStartup<HealthChecksSample.LivenessProbeStartup>();
}
)
.Build();
await host.StartAsync();
var server = host.GetTestServer();
var client = server.CreateClient();
var response = await client.GetAsync("/health/ready");
Assert.Equal(HttpStatusCode.ServiceUnavailable, response.StatusCode);
Assert.Equal("text/plain", response.Content.Headers.ContentType.ToString());
Assert.Equal("Unhealthy", await response.Content.ReadAsStringAsync());
}
}
}
| 34.991379 | 111 | 0.533875 | [
"Apache-2.0"
] | belav/aspnetcore | src/Middleware/HealthChecks/test/UnitTests/HealthCheckMiddlewareSampleTest.cs | 4,059 | C# |
using System;
using System.Collections.Generic;
using System.IO;
using System.IO.Compression;
namespace PIToOcsOmfSample.DataIngress
{
/// <summary>
/// Contains a set of properties that map to the OMF message header values and a byte
/// array to hold the OMF message body. These properties and this message body contain all
/// the information needed to create an HTTP request containing an OMF message.
/// This class also supports compressing and decompressing of the OMF message body.
/// </summary>
public class OmfMessage
{
public const string HeaderKey_ProducerToken = "producertoken";
public const string HeaderKey_MessageType = "messagetype";
public const string HeaderKey_MessageFormat = "messageformat";
public const string HeaderKey_MessageCompression = "compression";
public const string HeaderKey_Action = "action";
public const string HeaderKey_Version = "omfversion";
public OmfMessage()
{
Headers = new Dictionary<string, string>();
}
public IDictionary<string, string> Headers { get; private set; }
public byte[] Body { get; set; }
public string ProducerToken
{
get
{
Headers.TryGetValue(HeaderKey_ProducerToken, out string token);
return token;
}
set
{
Headers[HeaderKey_ProducerToken] = value;
}
}
public MessageType MessageType
{
get
{
MessageType type = MessageType.Data;
if (Headers.TryGetValue(HeaderKey_MessageType, out string headerVal))
{
Enum.TryParse(headerVal, true, out type);
}
return type;
}
set
{
Headers[HeaderKey_MessageType] = value.ToString();
}
}
public MessageFormat MessageFormat
{
get
{
MessageFormat format = MessageFormat.JSON;
if (Headers.TryGetValue(HeaderKey_MessageFormat, out string headerVal))
{
Enum.TryParse(headerVal, true, out format);
}
return format;
}
set
{
Headers[HeaderKey_MessageFormat] = value.ToString();
}
}
public MessageCompression MessageCompression
{
get
{
MessageCompression compression = MessageCompression.None;
if (Headers.TryGetValue(HeaderKey_MessageCompression, out string headerVal))
{
Enum.TryParse(headerVal, true, out compression);
}
return compression;
}
set
{
Headers[HeaderKey_MessageCompression] = value.ToString();
}
}
public MessageAction Action
{
get
{
MessageAction action = MessageAction.Create;
if (Headers.TryGetValue(HeaderKey_Action, out string headerVal))
{
Enum.TryParse(headerVal, true, out action);
}
return action;
}
set
{
Headers[HeaderKey_Action] = value.ToString();
}
}
public string Version
{
get
{
Headers.TryGetValue(HeaderKey_Version, out string version);
return version;
}
set
{
Headers[HeaderKey_Version] = value;
}
}
public void Compress(MessageCompression compressionType)
{
if (compressionType != MessageCompression.GZip)
{
throw new NotImplementedException("Only GZip compression is currently supported.");
}
if (this.MessageCompression != MessageCompression.None)
{
throw new InvalidOperationException($"The message has already been compressed using {MessageCompression}");
}
Body = GZipCompress(Body);
MessageCompression = compressionType;
}
public void Decompress()
{
switch (MessageCompression)
{
case MessageCompression.None:
break;
case MessageCompression.GZip:
Body = GZipDecompress(Body);
break;
default:
throw new InvalidOperationException($"{nameof(MessageCompression)} has an unexpected value, {MessageCompression}.");
}
MessageCompression = MessageCompression.None;
}
private static byte[] GZipCompress(byte[] uncompressed)
{
using (var memory = new MemoryStream())
using (var gzip = new GZipStream(memory, CompressionMode.Compress, true))
{
gzip.Write(uncompressed, 0, uncompressed.Length);
return memory.ToArray();
}
}
private static byte[] GZipDecompress(byte[] compressed)
{
using (var memoryStream = new MemoryStream(compressed))
using (var stream = new GZipStream(memoryStream, CompressionMode.Decompress))
{
const int size = 4096;
byte[] buffer = new byte[size];
using (var memory = new MemoryStream())
{
int count = 0;
do
{
count = stream.Read(buffer, 0, size);
if (count > 0)
{
memory.Write(buffer, 0, count);
}
} while (count > 0);
return memory.ToArray();
}
}
}
}
public enum MessageType
{
Data = 0,
Container,
Type
}
public enum MessageFormat
{
JSON = 0
}
public enum MessageCompression
{
None = 0,
GZip
}
public enum MessageAction
{
Create = 0,
Update,
Delete
}
}
| 30.058559 | 137 | 0.487637 | [
"Apache-2.0"
] | GitVivianSo/Qi-Samples | Extended/PIToOcsOmfSample/DataIngress/OmfMessage.cs | 6,675 | C# |
namespace Esprima.Ast
{
public sealed class Directive : ExpressionStatement
{
public readonly string Directiv;
public Directive(Expression expression, string directive) : base(expression)
{
Directiv = directive;
}
}
}
| 21.230769 | 84 | 0.626812 | [
"MIT"
] | Bargest/LogicExtensions | Eprisma/Ast/Directive.cs | 278 | 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.AliCloud.Dcdn.Inputs
{
public sealed class DomainSourceGetArgs : Pulumi.ResourceArgs
{
/// <summary>
/// The origin address.
/// </summary>
[Input("content", required: true)]
public Input<string> Content { get; set; } = null!;
/// <summary>
/// The port number. Valid values: `443` and `80`. Default to `80`.
/// </summary>
[Input("port")]
public Input<int>? Port { get; set; }
/// <summary>
/// The priority of the origin if multiple origins are specified. Default to `20`.
/// </summary>
[Input("priority")]
public Input<string>? Priority { get; set; }
/// <summary>
/// The type of the origin. Valid values:
/// `ipaddr`: The origin is configured using an IP address.
/// `domain`: The origin is configured using a domain name.
/// `oss`: The origin is configured using the Internet domain name of an Alibaba Cloud Object Storage Service (OSS) bucket.
/// </summary>
[Input("type", required: true)]
public Input<string> Type { get; set; } = null!;
/// <summary>
/// The weight of the origin if multiple origins are specified. Default to `10`.
/// </summary>
[Input("weight")]
public Input<string>? Weight { get; set; }
public DomainSourceGetArgs()
{
}
}
}
| 33.150943 | 131 | 0.590211 | [
"ECL-2.0",
"Apache-2.0"
] | pulumi/pulumi-alicloud | sdk/dotnet/Dcdn/Inputs/DomainSourceGetArgs.cs | 1,757 | C# |
using Mixpanel.NET.Events;
using NSubstitute;
using NUnit.Framework;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Workshare.Mixpanel.NET.Tests
{
[TestFixture]
public class MixpanelServiceTests
{
[Test]
public void TrackEventSendsEventToTracker()
{
MixpanelOptions options = new MixpanelOptions
{
Enabled = true
};
var tracker = Substitute.For<IEventTracker>();
MixpanelService service = new MixpanelService(options, new NullPropertiesProvider(), null, tracker);
service.SendEvent("eventName");
tracker.Received().Track("eventName", Arg.Is<IDictionary<string, object>>(p => p.Count == 0));
}
[Test]
public void TrackEventSendsEventPropertyToTracker()
{
MixpanelOptions options = new MixpanelOptions
{
Enabled = true
};
var tracker = Substitute.For<IEventTracker>();
MixpanelService service = new MixpanelService(options, new NullPropertiesProvider(), null, tracker);
service.SendEvent("eventName", "property", 123);
tracker.Received().Track("eventName", Arg.Is<IDictionary<string, object>>(p => p.ContainsKey("property") && (int) p["property"] == 123));
}
[Test]
public void TrackEventSendsEventPropertiesToTracker()
{
MixpanelOptions options = new MixpanelOptions
{
Enabled = true
};
var tracker = Substitute.For<IEventTracker>();
MixpanelService service = new MixpanelService(options, new NullPropertiesProvider(), null, tracker);
service.SendEvent("eventName", new Dictionary<string, object> { { "property", 123 } });
tracker.Received().Track("eventName", Arg.Is<IDictionary<string, object>>(p => p.ContainsKey("property") && (int)p["property"] == 123));
}
}
}
| 27.107692 | 140 | 0.713961 | [
"Apache-2.0"
] | workshare/Mixpanel.NET | src/Workshare.Mixpanel.NET.Tests/MixpanelServiceTests.cs | 1,764 | C# |
// Copyright (c) Microsoft Open Technologies, Inc. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Collections.Generic;
namespace Microsoft.AspNet.Mvc.HeaderValueAbstractions
{
public class MediaTypeWithQualityHeaderValue : MediaTypeHeaderValue
{
public double? Quality { get; private set; }
public static new MediaTypeWithQualityHeaderValue Parse(string input)
{
var mediaTypeHeaderValue = MediaTypeHeaderValue.Parse(input);
if (mediaTypeHeaderValue == null)
{
return null;
}
var quality = FormattingUtilities.Match;
string qualityStringValue = null;
if (mediaTypeHeaderValue.Parameters.TryGetValue("q", out qualityStringValue))
{
if (!Double.TryParse(qualityStringValue, out quality))
{
return null;
}
}
return
new MediaTypeWithQualityHeaderValue()
{
MediaType = mediaTypeHeaderValue.MediaType,
MediaSubType = mediaTypeHeaderValue.MediaSubType,
MediaTypeRange = mediaTypeHeaderValue.MediaTypeRange,
Charset = mediaTypeHeaderValue.Charset,
Parameters = mediaTypeHeaderValue.Parameters,
Quality = quality,
};
}
}
}
| 35.204545 | 111 | 0.591995 | [
"Apache-2.0"
] | Shazwazza/Mvc | src/Microsoft.AspNet.Mvc.HeaderValueAbstractions/MediaTypeWithQualityHeaderValue.cs | 1,549 | C# |
// <auto-generated>
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for
// license information.
//
// Code generated by Microsoft (R) AutoRest Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
// </auto-generated>
namespace Microsoft.Azure.CognitiveServices.Vision.Face
{
using Microsoft.Rest;
using Models;
using Newtonsoft.Json;
/// <summary>
/// An API for face detection, verification, and identification.
/// </summary>
public partial interface IFaceClient : System.IDisposable
{
/// <summary>
/// The base URI of the service.
/// </summary>
System.Uri BaseUri { get; set; }
/// <summary>
/// Gets or sets json serialization settings.
/// </summary>
JsonSerializerSettings SerializationSettings { get; }
/// <summary>
/// Gets or sets json deserialization settings.
/// </summary>
JsonSerializerSettings DeserializationSettings { get; }
/// <summary>
/// Subscription credentials which uniquely identify client
/// subscription.
/// </summary>
ServiceClientCredentials Credentials { get; }
/// <summary>
/// Gets the IFaceOperations.
/// </summary>
IFaceOperations Face { get; }
/// <summary>
/// Gets the IPersonGroupPerson.
/// </summary>
IPersonGroupPerson PersonGroupPerson { get; }
/// <summary>
/// Gets the IPersonGroupOperations.
/// </summary>
IPersonGroupOperations PersonGroup { get; }
/// <summary>
/// Gets the IFaceListOperations.
/// </summary>
IFaceListOperations FaceList { get; }
}
}
| 28.121212 | 74 | 0.605603 | [
"MIT"
] | alexsaff/azure-sdk-for-net | src/SDKs/CognitiveServices/dataPlane/Vision/Face/Face/Generated/IFaceClient.cs | 1,856 | C# |
using System.Collections.Generic;
using System.Web.Mvc;
namespace PeanutButter.RandomGenerators.Tests.PerformanceTest
{
public class ReportScheduleViewModel : ViewModelBase
{
public ReportType ReportType { get; set; }
public SelectList Schedules { get; set; }
public SelectList ContactList { get; set; }
public string Contact { get; set; }
public string ReportTypeString { get; set; }
public string ReportMethodName { get; set; }
public List<ContactViewModel> Contacts { get; set; }
public List<ReportScheduleParameterViewModel> ReportScheduleParameters { get; set; }
public ScheduleViewModel Schedule { get; set; }
}
} | 39.166667 | 92 | 0.692199 | [
"BSD-3-Clause"
] | Geosong/PeanutButter | source/TestUtils/PeanutButter.RandomGenerators.Tests/PerformanceTest/ReportScheduleViewModel.cs | 707 | C# |
using System.Reflection;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("Paragon.GoogleAnalytics.Factory")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("Paragon.GoogleAnalytics.Factory")]
[assembly: AssemblyCopyright("Copyright © 2016")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("e74633a2-030f-4326-8873-7add99c47876")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| 38.777778 | 84 | 0.745702 | [
"Unlicense"
] | gillissm/Paragon.Sitecore.ChartByGoogle | src/Paragon.GoogleAnalytics.Factory/Properties/AssemblyInfo.cs | 1,399 | C# |
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// 有关程序集的常规信息通过下列特性集
// 控制。更改这些特性值可修改
// 与程序集关联的信息。
[assembly: AssemblyTitle("Utg.ServerWeb.Admin")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("Utg.ServerWeb.Admin")]
[assembly: AssemblyCopyright("版权所有(C) 2016")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// 将 ComVisible 设置为 false 会使此程序集中的类型
// 对 COM 组件不可见。如果需要从 COM 访问此程序集中的某个类型,
// 请针对该类型将 ComVisible 特性设置为 true。
[assembly: ComVisible(false)]
// 如果此项目向 COM 公开,则下列 GUID 用于类型库的 ID
[assembly: Guid("d1b23e25-35b6-40b6-9397-a077ce5310cd")]
// 程序集的版本信息由下列四个值组成:
//
// 主版本
// 次版本
// 内部版本号
// 修订号
//
// 可以指定所有这些值,也可以使用“修订号”和“内部版本号”的默认值,
// 方法是按如下所示使用“*”:
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| 25.694444 | 56 | 0.721081 | [
"Apache-2.0"
] | heqinghua/lottery-code-qq-814788821- | YtgProject/Utg.ServerWeb.Admin/Properties/AssemblyInfo.cs | 1,305 | C# |
using ActionsList;
using System.Collections.Generic;
using Upgrade;
namespace Ship
{
namespace SecondEdition.T70XWing
{
public class KareKun : T70XWing
{
public KareKun() : base()
{
PilotInfo = new PilotCardInfo(
"Kare Kun",
4,
52,
isLimited: true,
abilityType: typeof(Abilities.SecondEdition.KareKunAbility),
extraUpgradeIcon: UpgradeType.Talent
//seImageNumber: 93
);
//ModelInfo.SkinName = "Black One";
ImageUrl = "https://images-cdn.fantasyflightgames.com/filer_public/42/59/42597afe-f592-4bac-98ad-f70e876fb451/swz25_kare_a1.png";
}
}
}
}
namespace Abilities.SecondEdition
{
public class KareKunAbility : Abilities.SecondEdition.DareDevilAbility
{
public override void ActivateAbility()
{
HostShip.OnGetAvailableBoostTemplates += ChangeBoostTemplates;
}
public override void DeactivateAbility()
{
HostShip.OnGetAvailableBoostTemplates -= ChangeBoostTemplates;
}
private void ChangeBoostTemplates(List<BoostMove> availableMoves, GenericAction action)
{
availableMoves.Add(new BoostMove(ActionsHolder.BoostTemplates.LeftTurn1, false));
availableMoves.Add(new BoostMove(ActionsHolder.BoostTemplates.RightTurn1, false));
}
}
} | 30.156863 | 145 | 0.595579 | [
"MIT"
] | mattgoudge/FlyCasual | Assets/Scripts/Model/Content/SecondEdition/Pilots/T70XWing/KareKun.cs | 1,540 | C# |
using System;
using System.Collections;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.IO.MemoryMappedFiles;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;
using System.Runtime.CompilerServices;
using LinqToDB.Tools;
namespace LinqToDB.Expressions
{
using LinqToDB.Extensions;
using Linq;
using Linq.Builder;
using Mapping;
using System.Diagnostics.CodeAnalysis;
static class InternalExtensions
{
#region IsConstant
public static bool IsConstantable(this Type type, bool includingArrays)
{
if (type.IsEnum)
return true;
switch (type.GetTypeCodeEx())
{
case TypeCode.Int16 :
case TypeCode.Int32 :
case TypeCode.Int64 :
case TypeCode.UInt16 :
case TypeCode.UInt32 :
case TypeCode.UInt64 :
case TypeCode.SByte :
case TypeCode.Byte :
case TypeCode.Decimal :
case TypeCode.Double :
case TypeCode.Single :
case TypeCode.Boolean :
case TypeCode.String :
case TypeCode.Char : return true;
}
if (type.IsNullable())
return type.GetGenericArguments()[0].IsConstantable(includingArrays);
if (includingArrays && type.IsArray)
return type.GetElementType().IsConstantable(includingArrays);
return false;
}
#endregion
#region Caches
static readonly ConcurrentDictionary<MethodInfo,SqlQueryDependentAttribute[]?> _queryDependentMethods =
new ConcurrentDictionary<MethodInfo,SqlQueryDependentAttribute[]?>();
public static void ClearCaches()
{
_queryDependentMethods.Clear();
}
#endregion
#region EqualsTo
internal static bool EqualsTo(this Expression expr1, Expression expr2,
IDataContext dataContext,
Dictionary<Expression, QueryableAccessor> queryableAccessorDic,
Dictionary<MemberInfo, QueryableMemberAccessor>? queryableMemberAccessorDic,
Dictionary<Expression, Expression>? queryDependedObjects,
bool compareConstantValues = false)
{
return EqualsTo(expr1, expr2, new EqualsToInfo(dataContext, queryableAccessorDic, queryableMemberAccessorDic, queryDependedObjects, compareConstantValues));
}
class EqualsToInfo
{
public EqualsToInfo(
IDataContext dataContext,
Dictionary<Expression, QueryableAccessor> queryableAccessorDic,
Dictionary<MemberInfo, QueryableMemberAccessor>? queryableMemberAccessorDic,
Dictionary<Expression, Expression>? queryDependedObjects,
bool compareConstantValues)
{
DataContext = dataContext;
QueryableAccessorDic = queryableAccessorDic;
QueryableMemberAccessorDic = queryableMemberAccessorDic;
QueryDependedObjects = queryDependedObjects;
CompareConstantValues = compareConstantValues;
}
public HashSet<Expression> Visited { get; } = new HashSet<Expression>();
public IDataContext DataContext { get; }
public Dictionary<Expression, QueryableAccessor> QueryableAccessorDic { get; }
public Dictionary<MemberInfo, QueryableMemberAccessor>? QueryableMemberAccessorDic { get; }
public Dictionary<Expression, Expression>? QueryDependedObjects { get; }
public bool CompareConstantValues { get; }
public Dictionary<MemberInfo, bool>? MemberCompareCache;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
static bool CompareMemberExpression(MemberInfo memberInfo, EqualsToInfo info)
{
if (info.QueryableMemberAccessorDic == null ||
!info.QueryableMemberAccessorDic.TryGetValue(memberInfo, out var accessor))
return true;
if (info.MemberCompareCache == null ||
!info.MemberCompareCache.TryGetValue(memberInfo, out var compareResult))
{
compareResult = accessor.Expression.EqualsTo(accessor.Accessor(memberInfo, info.DataContext), info);
info.MemberCompareCache ??= new Dictionary<MemberInfo, bool>(MemberInfoComparer.Instance);
info.MemberCompareCache.Add(memberInfo, compareResult);
}
return compareResult;
}
static bool EqualsTo(this Expression? expr1, Expression? expr2, EqualsToInfo info)
{
if (expr1 == expr2)
{
if (info.QueryableMemberAccessorDic == null || expr1 == null)
return true;
}
if (expr1 == null || expr2 == null || expr1.NodeType != expr2.NodeType || expr1.Type != expr2.Type)
return false;
switch (expr1.NodeType)
{
case ExpressionType.Add:
case ExpressionType.AddChecked:
case ExpressionType.And:
case ExpressionType.AndAlso:
case ExpressionType.ArrayIndex:
case ExpressionType.Assign:
case ExpressionType.Coalesce:
case ExpressionType.Divide:
case ExpressionType.Equal:
case ExpressionType.ExclusiveOr:
case ExpressionType.GreaterThan:
case ExpressionType.GreaterThanOrEqual:
case ExpressionType.LeftShift:
case ExpressionType.LessThan:
case ExpressionType.LessThanOrEqual:
case ExpressionType.Modulo:
case ExpressionType.Multiply:
case ExpressionType.MultiplyChecked:
case ExpressionType.NotEqual:
case ExpressionType.Or:
case ExpressionType.OrElse:
case ExpressionType.Power:
case ExpressionType.RightShift:
case ExpressionType.Subtract:
case ExpressionType.SubtractChecked:
{
// var e1 = (BinaryExpression)expr1;
// var e2 = (BinaryExpression)expr2;
return
((BinaryExpression)expr1).Method == ((BinaryExpression)expr2).Method &&
((BinaryExpression)expr1).Conversion.EqualsTo(((BinaryExpression)expr2).Conversion, info) &&
((BinaryExpression)expr1).Left. EqualsTo(((BinaryExpression)expr2).Left, info) &&
((BinaryExpression)expr1).Right. EqualsTo(((BinaryExpression)expr2).Right, info);
}
case ExpressionType.ArrayLength:
case ExpressionType.Convert:
case ExpressionType.ConvertChecked:
case ExpressionType.Negate:
case ExpressionType.NegateChecked:
case ExpressionType.Not:
case ExpressionType.Quote:
case ExpressionType.TypeAs:
case ExpressionType.UnaryPlus:
{
// var e1 = (UnaryExpression)expr1;
// var e2 = (UnaryExpression)expr2;
return
((UnaryExpression)expr1).Method == ((UnaryExpression)expr2).Method &&
((UnaryExpression)expr1).Operand.EqualsTo(((UnaryExpression)expr2).Operand, info);
}
case ExpressionType.Conditional:
{
// var e1 = (ConditionalExpression)expr1;
// var e2 = (ConditionalExpression)expr2;
return
((ConditionalExpression)expr1).Test. EqualsTo(((ConditionalExpression)expr2).Test, info) &&
((ConditionalExpression)expr1).IfTrue. EqualsTo(((ConditionalExpression)expr2).IfTrue, info) &&
((ConditionalExpression)expr1).IfFalse.EqualsTo(((ConditionalExpression)expr2).IfFalse, info);
}
case ExpressionType.Call : return EqualsToX((MethodCallExpression)expr1, (MethodCallExpression)expr2, info);
case ExpressionType.Constant : return EqualsToX((ConstantExpression) expr1, (ConstantExpression) expr2, info);
case ExpressionType.Invoke : return EqualsToX((InvocationExpression)expr1, (InvocationExpression)expr2, info);
case ExpressionType.Lambda : return EqualsToX((LambdaExpression) expr1, (LambdaExpression) expr2, info);
case ExpressionType.ListInit : return EqualsToX((ListInitExpression) expr1, (ListInitExpression) expr2, info);
case ExpressionType.MemberAccess : return EqualsToX((MemberExpression) expr1, (MemberExpression) expr2, info);
case ExpressionType.MemberInit : return EqualsToX((MemberInitExpression)expr1, (MemberInitExpression)expr2, info);
case ExpressionType.New : return EqualsToX((NewExpression) expr1, (NewExpression) expr2, info);
case ExpressionType.NewArrayBounds:
case ExpressionType.NewArrayInit : return EqualsToX((NewArrayExpression) expr1, (NewArrayExpression) expr2, info);
case ExpressionType.Default : return true;
case ExpressionType.Parameter : return ((ParameterExpression) expr1).Name == ((ParameterExpression) expr2).Name;
case ExpressionType.TypeIs:
{
// var e1 = (TypeBinaryExpression)expr1;
// var e2 = (TypeBinaryExpression)expr2;
return
((TypeBinaryExpression)expr1).TypeOperand == ((TypeBinaryExpression)expr2).TypeOperand &&
((TypeBinaryExpression)expr1).Expression.EqualsTo(((TypeBinaryExpression)expr2).Expression, info);
}
case ExpressionType.Block:
return EqualsToX((BlockExpression)expr1, (BlockExpression)expr2, info);
}
throw new InvalidOperationException();
}
static bool EqualsToX(BlockExpression expr1, BlockExpression expr2, EqualsToInfo info)
{
for (var i = 0; i < expr1.Expressions.Count; i++)
if (!expr1.Expressions[i].EqualsTo(expr2.Expressions[i], info))
return false;
for (var i = 0; i < expr1.Variables.Count; i++)
if (!expr1.Variables[i].EqualsTo(expr2.Variables[i], info))
return false;
return true;
}
static bool EqualsToX(NewArrayExpression expr1, NewArrayExpression expr2, EqualsToInfo info)
{
if (expr1.Expressions.Count != expr2.Expressions.Count)
return false;
for (var i = 0; i < expr1.Expressions.Count; i++)
if (!expr1.Expressions[i].EqualsTo(expr2.Expressions[i], info))
return false;
return true;
}
static bool EqualsToX(NewExpression expr1, NewExpression expr2, EqualsToInfo info)
{
if (expr1.Arguments.Count != expr2.Arguments.Count)
return false;
if (expr1.Members == null && expr2.Members != null)
return false;
if (expr1.Members != null && expr2.Members == null)
return false;
if (expr1.Constructor != expr2.Constructor)
return false;
if (expr1.Members != null)
{
if (expr1.Members.Count != expr2.Members!.Count)
return false;
for (var i = 0; i < expr1.Members.Count; i++)
if (expr1.Members[i] != expr2.Members[i])
return false;
}
for (var i = 0; i < expr1.Arguments.Count; i++)
if (!expr1.Arguments[i].EqualsTo(expr2.Arguments[i], info))
return false;
return true;
}
static bool EqualsToX(MemberInitExpression expr1, MemberInitExpression expr2, EqualsToInfo info)
{
if (expr1.Bindings.Count != expr2.Bindings.Count || !expr1.NewExpression.EqualsTo(expr2.NewExpression, info))
return false;
bool CompareBindings(MemberBinding? b1, MemberBinding? b2)
{
if (b1 == b2)
return true;
if (b1 == null || b2 == null || b1.BindingType != b2.BindingType || b1.Member != b2.Member)
return false;
switch (b1.BindingType)
{
case MemberBindingType.Assignment:
return ((MemberAssignment)b1).Expression.EqualsTo(((MemberAssignment)b2).Expression, info);
case MemberBindingType.ListBinding:
var ml1 = (MemberListBinding)b1;
var ml2 = (MemberListBinding)b2;
if (ml1.Initializers.Count != ml2.Initializers.Count)
return false;
for (var i = 0; i < ml1.Initializers.Count; i++)
{
var ei1 = ml1.Initializers[i];
var ei2 = ml2.Initializers[i];
if (ei1.AddMethod != ei2.AddMethod || ei1.Arguments.Count != ei2.Arguments.Count)
return false;
for (var j = 0; j < ei1.Arguments.Count; j++)
if (!ei1.Arguments[j].EqualsTo(ei2.Arguments[j], info))
return false;
}
break;
case MemberBindingType.MemberBinding:
var mm1 = (MemberMemberBinding)b1;
var mm2 = (MemberMemberBinding)b2;
if (mm1.Bindings.Count != mm2.Bindings.Count)
return false;
for (var i = 0; i < mm1.Bindings.Count; i++)
if (!CompareBindings(mm1.Bindings[i], mm2.Bindings[i]))
return false;
break;
}
return true;
}
for (var i = 0; i < expr1.Bindings.Count; i++)
{
var b1 = expr1.Bindings[i];
var b2 = expr2.Bindings[i];
if (!CompareBindings(b1, b2))
return false;
}
return true;
}
static bool EqualsToX(MemberExpression expr1, MemberExpression expr2, EqualsToInfo info)
{
if (expr1.Member == expr2.Member)
{
if (expr1.Expression == expr2.Expression || expr1.Expression.Type == expr2.Expression.Type)
{
if (info.QueryableAccessorDic.Count > 0)
{
if (info.QueryableAccessorDic.TryGetValue(expr1, out var qa))
return
expr1.Expression.EqualsTo(expr2.Expression, info) &&
qa.Queryable.Expression.EqualsTo(qa.Accessor(expr2).Expression, info);
}
if (!CompareMemberExpression(expr1.Member, info))
return false;
}
return expr1.Expression.EqualsTo(expr2.Expression, info);
}
return false;
}
static bool EqualsToX(ListInitExpression expr1, ListInitExpression expr2, EqualsToInfo info)
{
if (expr1.Initializers.Count != expr2.Initializers.Count || !expr1.NewExpression.EqualsTo(expr2.NewExpression, info))
return false;
for (var i = 0; i < expr1.Initializers.Count; i++)
{
var i1 = expr1.Initializers[i];
var i2 = expr2.Initializers[i];
if (i1.Arguments.Count != i2.Arguments.Count || i1.AddMethod != i2.AddMethod)
return false;
for (var j = 0; j < i1.Arguments.Count; j++)
if (!i1.Arguments[j].EqualsTo(i2.Arguments[j], info))
return false;
}
return true;
}
static bool EqualsToX(LambdaExpression expr1, LambdaExpression expr2, EqualsToInfo info)
{
if (expr1.Parameters.Count != expr2.Parameters.Count || !expr1.Body.EqualsTo(expr2.Body, info))
return false;
for (var i = 0; i < expr1.Parameters.Count; i++)
if (!expr1.Parameters[i].EqualsTo(expr2.Parameters[i], info))
return false;
return true;
}
static bool EqualsToX(InvocationExpression expr1, InvocationExpression expr2, EqualsToInfo info)
{
if (expr1.Arguments.Count != expr2.Arguments.Count || !expr1.Expression.EqualsTo(expr2.Expression, info))
return false;
for (var i = 0; i < expr1.Arguments.Count; i++)
if (!expr1.Arguments[i].EqualsTo(expr2.Arguments[i], info))
return false;
return true;
}
static bool EqualsToX(ConstantExpression expr1, ConstantExpression expr2, EqualsToInfo info)
{
if (expr1.Value == null && expr2.Value == null)
return true;
if (IsConstantable(expr1.Type, false))
return Equals(expr1.Value, expr2.Value);
if (expr1.Value == null || expr2.Value == null)
return false;
if (expr1.Value is IQueryable queryable)
{
var eq1 = queryable.Expression;
var eq2 = ((IQueryable)expr2.Value).Expression;
if (!info.Visited.Contains(eq1))
{
info.Visited.Add(eq1);
return eq1.EqualsTo(eq2, info);
}
}
else if (expr1.Value is IEnumerable list1 && expr2.Value is IEnumerable list2)
{
var enum1 = list1.GetEnumerator();
var enum2 = list2.GetEnumerator();
using (enum1 as IDisposable)
using (enum2 as IDisposable)
{
while (enum1.MoveNext())
{
if (!enum2.MoveNext() || !object.Equals(enum1.Current, enum2.Current))
return false;
}
if (enum2.MoveNext())
return false;
}
return true;
}
return !info.CompareConstantValues || expr1.Value == expr2.Value;
}
static bool EqualsToX(MethodCallExpression expr1, MethodCallExpression expr2, EqualsToInfo info)
{
if (expr1.Arguments.Count != expr2.Arguments.Count || expr1.Method != expr2.Method)
return false;
if (!expr1.Object.EqualsTo(expr2.Object, info))
return false;
var dependentParameters = _queryDependentMethods.GetOrAdd(
expr1.Method, mi =>
{
var arr = mi
.GetParameters()
.Select(p => p.GetCustomAttributes(typeof(SqlQueryDependentAttribute), false).OfType<SqlQueryDependentAttribute>().FirstOrDefault())
.ToArray();
return arr.Any(a => a != null) ? arr : null;
});
bool DefaultCompareArguments(Expression arg1, Expression arg2)
{
if (typeof(Sql.IQueryableContainer).IsSameOrParentOf(arg1.Type))
{
if (arg1.NodeType == ExpressionType.Constant && arg2.NodeType == ExpressionType.Constant)
{
var query1 = ((Sql.IQueryableContainer)arg1.EvaluateExpression()!).Query;
var query2 = ((Sql.IQueryableContainer)arg2.EvaluateExpression()!).Query;
return EqualsTo(query1.Expression, query2.Expression, info);
}
}
if (!arg1.EqualsTo(arg2, info))
return false;
return true;
}
if (dependentParameters == null)
{
for (var i = 0; i < expr1.Arguments.Count; i++)
{
if (!DefaultCompareArguments(expr1.Arguments[i], expr2.Arguments[i]))
return false;
}
}
else
{
for (var i = 0; i < expr1.Arguments.Count; i++)
{
var dependentAttribute = dependentParameters[i];
if (dependentAttribute != null)
{
var enum1 = dependentAttribute.SplitExpression(expr1.Arguments[i]).GetEnumerator();
var enum2 = dependentAttribute.SplitExpression(expr2.Arguments[i]).GetEnumerator();
using (enum1 as IDisposable)
using (enum2 as IDisposable)
{
while (enum1.MoveNext())
{
if (!enum2.MoveNext())
return false;
var arg1 = enum1.Current;
var arg2 = enum2.Current;
if (info.QueryDependedObjects != null && info.QueryDependedObjects.TryGetValue(arg1, out var nevValue))
arg1 = nevValue;
if (!dependentAttribute.ExpressionsEqual(arg1, arg2, (e1, e2) => e1.EqualsTo(e2, info)))
return false;
}
if (enum2.MoveNext())
return false;
}
}
else
{
if (!DefaultCompareArguments(expr1.Arguments[i], expr2.Arguments[i]))
return false;
}
}
}
if (info.QueryableAccessorDic.Count > 0)
if (info.QueryableAccessorDic.TryGetValue(expr1, out var qa))
return qa.Queryable.Expression.EqualsTo(qa.Accessor(expr2).Expression, info);
if (!CompareMemberExpression(expr1.Method, info))
return false;
return true;
}
#endregion
#region Path
class PathInfo
{
public PathInfo(
HashSet<Expression> visited,
Action<Expression,Expression> func)
{
Visited = visited;
Func = func;
}
public HashSet<Expression> Visited;
public Action<Expression,Expression> Func;
}
static Expression ConvertTo(Expression expr, Type type)
{
return Expression.Convert(expr, type);
}
static void Path<T>(IEnumerable<T> source, Expression path, MethodInfo property, Action<T,Expression> func)
where T : class
{
#if DEBUG
_callCounter4++;
#endif
var prop = Expression.Property(path, property);
var i = 0;
foreach (var item in source)
func(item, Expression.Call(prop, ReflectionHelper.IndexExpressor<T>.Item, Expression.Constant(i++)));
}
static void Path<T>(PathInfo info, IEnumerable<T> source, Expression path, MethodInfo property)
where T : Expression
{
#if DEBUG
_callCounter3++;
#endif
var prop = Expression.Property(path, property);
var i = 0;
foreach (var item in source)
Path(info, item, Expression.Call(prop, ReflectionHelper.IndexExpressor<T>.Item, Expression.Constant(i++)));
}
static void Path(PathInfo info, Expression expr, Expression path, MethodInfo property)
{
#if DEBUG
_callCounter2++;
#endif
Path(info, expr, Expression.Property(path, property));
}
public static void Path(this Expression expr, Expression path, Action<Expression, Expression> func)
{
#if DEBUG
_callCounter1 = 0;
_callCounter2 = 0;
_callCounter3 = 0;
_callCounter4 = 0;
#endif
Path(new PathInfo(new HashSet<Expression>(), func), expr, path);
}
#if DEBUG
static int _callCounter1;
static int _callCounter2;
static int _callCounter3;
static int _callCounter4;
#endif
static void Path(PathInfo info, Expression? expr, Expression path)
{
#if DEBUG
_callCounter1++;
#endif
if (expr == null)
return;
switch (expr.NodeType)
{
case ExpressionType.Add:
case ExpressionType.AddChecked:
case ExpressionType.And:
case ExpressionType.AndAlso:
case ExpressionType.ArrayIndex:
case ExpressionType.Assign:
case ExpressionType.Coalesce:
case ExpressionType.Divide:
case ExpressionType.Equal:
case ExpressionType.ExclusiveOr:
case ExpressionType.GreaterThan:
case ExpressionType.GreaterThanOrEqual:
case ExpressionType.LeftShift:
case ExpressionType.LessThan:
case ExpressionType.LessThanOrEqual:
case ExpressionType.Modulo:
case ExpressionType.Multiply:
case ExpressionType.MultiplyChecked:
case ExpressionType.NotEqual:
case ExpressionType.Or:
case ExpressionType.OrElse:
case ExpressionType.Power:
case ExpressionType.RightShift:
case ExpressionType.Subtract:
case ExpressionType.SubtractChecked:
{
path = ConvertTo(path, typeof(BinaryExpression));
Path(info, ((BinaryExpression)expr).Conversion, Expression.Property(path, ReflectionHelper.Binary.Conversion));
Path(info, ((BinaryExpression)expr).Left, Expression.Property(path, ReflectionHelper.Binary.Left));
Path(info, ((BinaryExpression)expr).Right, Expression.Property(path, ReflectionHelper.Binary.Right));
break;
}
case ExpressionType.ArrayLength:
case ExpressionType.Convert:
case ExpressionType.ConvertChecked:
case ExpressionType.Negate:
case ExpressionType.NegateChecked:
case ExpressionType.Not:
case ExpressionType.Quote:
case ExpressionType.TypeAs:
case ExpressionType.UnaryPlus:
Path(
info,
((UnaryExpression)expr).Operand,
path = ConvertTo(path, typeof(UnaryExpression)),
ReflectionHelper.Unary.Operand);
break;
case ExpressionType.Call:
{
path = ConvertTo(path, typeof(MethodCallExpression));
Path(info, ((MethodCallExpression)expr).Object, path, ReflectionHelper.MethodCall.Object);
Path(info, ((MethodCallExpression)expr).Arguments, path, ReflectionHelper.MethodCall.Arguments);
break;
}
case ExpressionType.Conditional:
{
path = ConvertTo(path, typeof(ConditionalExpression));
Path(info, ((ConditionalExpression)expr).Test, path, ReflectionHelper.Conditional.Test);
Path(info, ((ConditionalExpression)expr).IfTrue, path, ReflectionHelper.Conditional.IfTrue);
Path(info, ((ConditionalExpression)expr).IfFalse, path, ReflectionHelper.Conditional.IfFalse);
break;
}
case ExpressionType.Invoke:
{
path = ConvertTo(path, typeof(InvocationExpression));
Path(info, ((InvocationExpression)expr).Expression, path, ReflectionHelper.Invocation.Expression);
Path(info, ((InvocationExpression)expr).Arguments, path, ReflectionHelper.Invocation.Arguments);
break;
}
case ExpressionType.Lambda:
{
path = ConvertTo(path, typeof(LambdaExpression));
Path(info, ((LambdaExpression)expr).Body, path, ReflectionHelper.LambdaExpr.Body);
Path(info, ((LambdaExpression)expr).Parameters, path, ReflectionHelper.LambdaExpr.Parameters);
break;
}
case ExpressionType.ListInit:
{
path = ConvertTo(path, typeof(ListInitExpression));
Path(info, ((ListInitExpression)expr).NewExpression, path, ReflectionHelper.ListInit.NewExpression);
Path( ((ListInitExpression)expr).Initializers, path, ReflectionHelper.ListInit.Initializers,
(ex, p) => Path(info, ex.Arguments, p, ReflectionHelper.ElementInit.Arguments));
break;
}
case ExpressionType.MemberAccess:
Path(
info,
((MemberExpression)expr).Expression,
path = ConvertTo(path, typeof(MemberExpression)),
ReflectionHelper.Member.Expression);
break;
case ExpressionType.MemberInit:
{
void Modify(MemberBinding b, Expression pinf)
{
switch (b.BindingType)
{
case MemberBindingType.Assignment:
Path(
info,
((MemberAssignment)b).Expression,
ConvertTo(pinf, typeof(MemberAssignment)),
ReflectionHelper.MemberAssignmentBind.Expression);
break;
case MemberBindingType.ListBinding:
Path(
((MemberListBinding)b).Initializers,
ConvertTo(pinf, typeof(MemberListBinding)),
ReflectionHelper.MemberListBind.Initializers,
(p, psi) => Path(info, p.Arguments, psi, ReflectionHelper.ElementInit.Arguments));
break;
case MemberBindingType.MemberBinding:
Path(
((MemberMemberBinding)b).Bindings,
ConvertTo(pinf, typeof(MemberMemberBinding)),
ReflectionHelper.MemberMemberBind.Bindings,
Modify);
break;
}
}
path = ConvertTo(path, typeof(MemberInitExpression));
Path(info, ((MemberInitExpression)expr).NewExpression, path, ReflectionHelper.MemberInit.NewExpression);
Path( ((MemberInitExpression)expr).Bindings, path, ReflectionHelper.MemberInit.Bindings, Modify);
break;
}
case ExpressionType.New:
Path(
info,
((NewExpression)expr).Arguments,
path = ConvertTo(path, typeof(NewExpression)),
ReflectionHelper.New.Arguments);
break;
case ExpressionType.NewArrayBounds:
Path(
info,
((NewArrayExpression)expr).Expressions,
path = ConvertTo(path, typeof(NewArrayExpression)),
ReflectionHelper.NewArray.Expressions);
break;
case ExpressionType.NewArrayInit:
Path(
info,
((NewArrayExpression)expr).Expressions,
path = ConvertTo(path, typeof(NewArrayExpression)),
ReflectionHelper.NewArray.Expressions);
break;
case ExpressionType.TypeIs:
Path(
info,
((TypeBinaryExpression)expr).Expression,
path = ConvertTo(path, typeof(TypeBinaryExpression)),
ReflectionHelper.TypeBinary.Expression);
break;
case ExpressionType.Block:
{
path = ConvertTo(path, typeof(BlockExpression));
Path(info,((BlockExpression)expr).Expressions, path, ReflectionHelper.Block.Expressions);
Path(info,((BlockExpression)expr).Variables, path, ReflectionHelper.Block.Variables); // ?
break;
}
case ExpressionType.Constant:
{
path = ConvertTo(path, typeof(ConstantExpression));
if (((ConstantExpression)expr).Value is IQueryable iq && !info.Visited.Contains(iq.Expression))
{
info.Visited.Add(iq.Expression);
Expression p = Expression.Property(path, ReflectionHelper.Constant.Value);
p = ConvertTo(p, typeof(IQueryable));
Path(info, iq.Expression, p, ReflectionHelper.QueryableInt.Expression);
}
break;
}
case ExpressionType.Parameter: path = ConvertTo(path, typeof(ParameterExpression)); break;
case ExpressionType.Extension:
{
if (expr.CanReduce)
{
expr = expr.Reduce();
Path(info, expr, path);
}
break;
}
}
info.Func(expr, path);
}
#endregion
#region Helpers
[return: NotNullIfNotNull("ex")]
public static Expression? Unwrap(this Expression? ex)
{
if (ex == null)
return null;
switch (ex.NodeType)
{
case ExpressionType.Quote :
case ExpressionType.ConvertChecked :
case ExpressionType.Convert :
return ((UnaryExpression)ex).Operand.Unwrap();
}
return ex;
}
[return: NotNullIfNotNull("ex")]
public static Expression? UnwrapConvert(this Expression? ex)
{
if (ex == null)
return null;
switch (ex.NodeType)
{
case ExpressionType.ConvertChecked :
case ExpressionType.Convert :
return ((UnaryExpression)ex).Operand.Unwrap();
}
return ex;
}
[return: NotNullIfNotNull("ex")]
public static Expression? UnwrapWithAs(this Expression? ex)
{
if (ex == null)
return null;
switch (ex.NodeType)
{
case ExpressionType.TypeAs:
return ((UnaryExpression)ex).Operand.Unwrap();
}
return ex.Unwrap();
}
public static Expression SkipPathThrough(this Expression expr)
{
while (expr is MethodCallExpression mce && mce.IsQueryable("AsQueryable"))
expr = mce.Arguments[0];
return expr;
}
public static Expression SkipMethodChain(this Expression expr, MappingSchema mappingSchema)
{
return Sql.ExtensionAttribute.ExcludeExtensionChain(mappingSchema, expr);
}
public static Dictionary<Expression,Expression> GetExpressionAccessors(this Expression expression, Expression path)
{
var accessors = new Dictionary<Expression,Expression>();
expression.Path(path, (e,p) =>
{
switch (e.NodeType)
{
case ExpressionType.Call :
case ExpressionType.MemberAccess :
case ExpressionType.New :
if (!accessors.ContainsKey(e))
accessors.Add(e, p);
break;
case ExpressionType.Constant :
if (!accessors.ContainsKey(e))
accessors.Add(e, Expression.Property(p, ReflectionHelper.Constant.Value));
break;
case ExpressionType.ConvertChecked :
case ExpressionType.Convert :
if (!accessors.ContainsKey(e))
{
var ue = (UnaryExpression)e;
switch (ue.Operand.NodeType)
{
case ExpressionType.Call :
case ExpressionType.MemberAccess :
case ExpressionType.New :
case ExpressionType.Constant :
accessors.Add(e, p);
break;
}
}
break;
}
});
return accessors;
}
[return: NotNullIfNotNull("expr")]
public static Expression? GetRootObject(this Expression? expr, MappingSchema mapping)
{
if (expr == null)
return null;
expr = expr.SkipMethodChain(mapping);
switch (expr.NodeType)
{
case ExpressionType.Call :
{
var e = (MethodCallExpression)expr;
if (e.Object != null)
return GetRootObject(e.Object, mapping);
if (e.Arguments?.Count > 0 &&
(e.IsQueryable() || e.IsAggregate(mapping) || e.IsAssociation(mapping) || e.Method.IsSqlPropertyMethodEx()))
return GetRootObject(e.Arguments[0], mapping);
break;
}
case ExpressionType.MemberAccess :
{
var e = (MemberExpression)expr;
if (e.Expression != null)
return GetRootObject(e.Expression.UnwrapWithAs(), mapping);
break;
}
}
return expr;
}
public static List<Expression> GetMembers(this Expression? expr)
{
if (expr == null)
return new List<Expression>();
List<Expression> list;
switch (expr.NodeType)
{
case ExpressionType.Call :
{
var e = (MethodCallExpression)expr;
if (e.Object != null)
list = GetMembers(e.Object);
else if (e.Arguments?.Count > 0 && e.IsQueryable())
list = GetMembers(e.Arguments[0]);
else
list = new List<Expression>();
break;
}
case ExpressionType.MemberAccess :
{
var e = (MemberExpression)expr;
list = e.Expression != null ? GetMembers(e.Expression.Unwrap()) : new List<Expression>();
break;
}
default :
list = new List<Expression>();
break;
}
list.Add(expr);
return list;
}
public static bool IsQueryable(this MethodCallExpression method, bool enumerable = true)
{
var type = method.Method.DeclaringType;
return type == typeof(Queryable) || (enumerable && type == typeof(Enumerable)) || type == typeof(LinqExtensions) || type == typeof(DataExtensions);
}
public static bool IsAsyncExtension(this MethodCallExpression method, bool enumerable = true)
{
var type = method.Method.DeclaringType;
return type == typeof(AsyncExtensions);
}
public static bool IsAggregate(this MethodCallExpression methodCall, MappingSchema mapping)
{
if (methodCall.IsQueryable(AggregationBuilder.MethodNames) || methodCall.IsQueryable(CountBuilder.MethodNames))
return true;
if (methodCall.Arguments.Count > 0)
{
var function = AggregationBuilder.GetAggregateDefinition(methodCall, mapping);
return function != null;
}
return false;
}
public static bool IsExtensionMethod(this MethodCallExpression methodCall, MappingSchema mapping)
{
var functions = mapping.GetAttributes<Sql.ExtensionAttribute>(methodCall.Method.ReflectedType,
methodCall.Method,
f => f.Configuration);
return functions.Any();
}
public static bool IsQueryable(this MethodCallExpression method, string name)
{
return method.Method.Name == name && method.IsQueryable();
}
public static bool IsQueryable(this MethodCallExpression method, params string[] names)
{
if (method.IsQueryable())
foreach (var name in names)
if (method.Method.Name == name)
return true;
return false;
}
public static bool IsAsyncExtension(this MethodCallExpression method, params string[] names)
{
if (method.IsAsyncExtension())
foreach (var name in names)
if (method.Method.Name == name + "Async")
return true;
return false;
}
public static bool IsSameGenericMethod(this MethodCallExpression method, MethodInfo genericMethodInfo)
{
if (!method.Method.IsGenericMethod)
return false;
return method.Method.GetGenericMethodDefinition() == genericMethodInfo;
}
public static bool IsSameGenericMethod(this MethodCallExpression method, params MethodInfo[] genericMethodInfo)
{
if (!method.Method.IsGenericMethod)
return false;
var genericDefinition = method.Method.GetGenericMethodDefinition();
return Array.IndexOf(genericMethodInfo, genericDefinition) >= 0;
}
public static bool IsAssociation(this MethodCallExpression method, MappingSchema mappingSchema)
{
return mappingSchema.GetAttribute<AssociationAttribute>(method.Method.DeclaringType, method.Method) != null;
}
public static bool IsCte(this MethodCallExpression method, MappingSchema mappingSchema)
{
return method.IsQueryable("AsCte", "GetCte");
}
static Expression FindLevel(Expression expression, MappingSchema mapping, int level, ref int current)
{
switch (expression.NodeType)
{
case ExpressionType.Call :
{
var call = (MethodCallExpression)expression;
var expr = ExtractMethodCallTunnelExpression(call, mapping);
if (expr != null)
{
var ex = FindLevel(expr, mapping, level, ref current);
if (level == current)
return ex;
current++;
}
break;
}
case ExpressionType.MemberAccess:
{
var e = ((MemberExpression)expression);
if (e.Expression != null)
{
var expr = FindLevel(e.Expression.UnwrapWithAs(), mapping, level, ref current);
if (level == current)
return expr;
current++;
}
break;
}
}
return expression;
}
/// <summary>
/// Returns part of expression based on its level.
/// </summary>
/// <param name="expression">Base expression that needs decomposition.</param>
/// <param name="mapping">Maping schema.</param>
/// <param name="level">Level that should be to be extracted.</param>
/// <returns>Exstracted expression.</returns>
/// <example>
/// This sample shows what method returns for expression [c.ParentId].
/// <code>
/// expression.GetLevelExpression(mapping, 0) == [c]
/// expression.GetLevelExpression(mapping, 1) == [c.ParentId]
/// </code>
/// </example>
public static Expression GetLevelExpression(this Expression expression, MappingSchema mapping, int level)
{
var current = 0;
var expr = FindLevel(expression, mapping, level, ref current);
if (expr == null || current != level)
throw new InvalidOperationException();
return expr;
}
static Expression? ExtractMethodCallTunnelExpression(MethodCallExpression call, MappingSchema mapping)
{
var expr = call.Object;
if (expr == null && call.Arguments.Count > 0 &&
(call.IsQueryable()
|| call.IsAggregate(mapping)
|| call.IsExtensionMethod(mapping)
|| call.IsAssociation(mapping)
|| call.Method.IsSqlPropertyMethodEx()))
{
expr = call.Arguments[0];
}
return expr;
}
public static int GetLevel(this Expression expression, MappingSchema mapping)
{
switch (expression.NodeType)
{
case ExpressionType.Call :
{
var call = (MethodCallExpression)expression;
var expr = ExtractMethodCallTunnelExpression(call, mapping);
if (expr != null)
{
return GetLevel(expr.UnwrapWithAs(), mapping) + 1;
}
break;
}
case ExpressionType.MemberAccess:
{
var e = ((MemberExpression)expression);
if (e.Expression != null)
return GetLevel(e.Expression.UnwrapWithAs(), mapping) + 1;
break;
}
}
return 0;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static T? EvaluateExpression<T>(this Expression? expr)
where T : class
{
return expr.EvaluateExpression() as T;
}
public static object? EvaluateExpression(this Expression? expr)
{
if (expr == null)
return null;
switch (expr.NodeType)
{
case ExpressionType.Constant:
return ((ConstantExpression)expr).Value;
case ExpressionType.MemberAccess:
{
var member = (MemberExpression) expr;
if (member.Member.IsFieldEx())
return ((FieldInfo)member.Member).GetValue(member.Expression.EvaluateExpression());
if (member.Member.IsPropertyEx())
return ((PropertyInfo)member.Member).GetValue(member.Expression.EvaluateExpression(), null);
break;
}
case ExpressionType.Call:
{
var mc = (MethodCallExpression)expr;
var arguments = mc.Arguments.Select(EvaluateExpression).ToArray();
var instance = mc.Object.EvaluateExpression();
return mc.Method.Invoke(instance, arguments);
}
}
var value = Expression.Lambda(expr).Compile().DynamicInvoke();
return value;
}
#endregion
public static bool IsEvaluable(Expression? expression)
{
if (expression == null)
return true;
switch (expression.NodeType)
{
case ExpressionType.Convert:
return IsEvaluable(((UnaryExpression) expression).Operand);
case ExpressionType.Constant:
return true;
case ExpressionType.MemberAccess:
return IsEvaluable(((MemberExpression) expression).Expression);
default:
return false;
}
}
/// <summary>
/// Optimizes expression context by evaluating constants and simplifying boolean operations.
/// </summary>
/// <param name="expression">Expression to optimize.</param>
/// <returns>Optimized expression.</returns>
public static Expression? OptimizeExpression(this Expression? expression)
{
var optimized = expression?.Transform(e =>
{
var newExpr = e;
if (e is BinaryExpression binary)
{
var left = OptimizeExpression(binary.Left)!;
var right = OptimizeExpression(binary.Right)!;
if (left.Type != binary.Left.Type)
left = Expression.Convert(left, binary.Left.Type);
if (right.Type != binary.Right.Type)
right = Expression.Convert(right, binary.Right.Type);
newExpr = binary.Update(left, OptimizeExpression(binary.Conversion) as LambdaExpression, right);
}
else if (e is UnaryExpression unaryExpression)
{
newExpr = unaryExpression.Update(OptimizeExpression(unaryExpression.Operand));
if (newExpr.NodeType == ExpressionType.Convert && ((UnaryExpression)newExpr).Operand.NodeType == ExpressionType.Convert)
{
// remove double convert
newExpr = Expression.Convert(
((UnaryExpression) ((UnaryExpression) newExpr).Operand).Operand, newExpr.Type);
}
}
if (IsEvaluable(newExpr))
{
newExpr = newExpr.NodeType == ExpressionType.Constant
? newExpr
: Expression.Constant(EvaluateExpression(newExpr));
}
else
{
switch (newExpr)
{
case NewArrayExpression _:
{
return new TransformInfo(newExpr, true);
}
case UnaryExpression unary when IsEvaluable(unary.Operand):
{
newExpr = Expression.Constant(EvaluateExpression(unary));
break;
}
case MemberExpression me when me.Expression?.NodeType == ExpressionType.Constant:
{
newExpr = Expression.Constant(EvaluateExpression(me));
break;
}
case BinaryExpression be when IsEvaluable(be.Left) && IsEvaluable(be.Right):
{
newExpr = Expression.Constant(EvaluateExpression(be));
break;
}
case BinaryExpression be when be.NodeType == ExpressionType.AndAlso:
{
if (IsEvaluable(be.Left))
{
var leftBool = EvaluateExpression(be.Left) as bool?;
if (leftBool == true)
e = be.Right;
else if (leftBool == false)
newExpr = Expression.Constant(false);
}
else if (IsEvaluable(be.Right))
{
var rightBool = EvaluateExpression(be.Right) as bool?;
if (rightBool == true)
newExpr = be.Left;
else if (rightBool == false)
newExpr = Expression.Constant(false);
}
break;
}
case BinaryExpression be when be.NodeType == ExpressionType.OrElse:
{
if (IsEvaluable(be.Left))
{
var leftBool = EvaluateExpression(be.Left) as bool?;
if (leftBool == false)
newExpr = be.Right;
else if (leftBool == true)
newExpr = Expression.Constant(true);
}
else if (IsEvaluable(be.Right))
{
var rightBool = EvaluateExpression(be.Right) as bool?;
if (rightBool == false)
newExpr = be.Left;
else if (rightBool == true)
newExpr = Expression.Constant(true);
}
break;
}
}
}
if (newExpr.Type != e.Type)
newExpr = Expression.Convert(newExpr, e.Type);
return new TransformInfo(newExpr);
}
);
return optimized;
}
public static Expression ApplyLambdaToExpression(LambdaExpression convertLambda, Expression expression)
{
// Replace multiple parameters with single variable or single parameter with the reader expression.
//
if (expression.NodeType != ExpressionType.Parameter && convertLambda.Body.GetCount(e => e == convertLambda.Parameters[0]) > 1)
{
var variable = Expression.Variable(expression.Type);
var assign = Expression.Assign(variable, expression);
expression = Expression.Block(new[] { variable }, assign, convertLambda.GetBody(variable));
}
else
{
expression = convertLambda.GetBody(expression);
}
return expression;
}
}
}
| 30.389726 | 160 | 0.645 | [
"MIT"
] | Feroks/linq2db | Source/LinqToDB/Expressions/InternalExtensions.cs | 42,912 | C# |
// Copyright 2016 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
using System;
using System.IO;
using System.Collections.Generic;
using System.Runtime.InteropServices;
using System.Linq;
namespace NtApiDotNet
{
/// <summary>
/// Static utility methods.
/// </summary>
public static class NtObjectUtils
{
internal static byte[] StructToBytes<T>(T value)
{
int length = Marshal.SizeOf(typeof(T));
byte[] ret = new byte[length];
IntPtr buffer = Marshal.AllocHGlobal(length);
try
{
Marshal.StructureToPtr(value, buffer, false);
Marshal.Copy(buffer, ret, 0, ret.Length);
}
finally
{
if (buffer != IntPtr.Zero)
{
Marshal.FreeHGlobal(buffer);
}
}
return ret;
}
/// <summary>
/// Convert the safe handle to an array of bytes.
/// </summary>
/// <returns>The data contained in the allocaiton.</returns>
internal static byte[] SafeHandleToArray(SafeHandle handle, int length)
{
byte[] ret = new byte[length];
Marshal.Copy(handle.DangerousGetHandle(), ret, 0, ret.Length);
return ret;
}
internal static byte[] ReadAllBytes(this BinaryReader reader, int length)
{
byte[] ret = reader.ReadBytes(length);
if (ret.Length != length)
{
throw new EndOfStreamException();
}
return ret;
}
/// <summary>
/// Convert an NtStatus to an exception if the status is an error
/// </summary>
/// <param name="status">The NtStatus</param>
/// <returns>The original NtStatus if not an error</returns>
/// <exception cref="NtException">Thrown if status is an error.</exception>
public static NtStatus ToNtException(this NtStatus status)
{
return status.ToNtException(true);
}
/// <summary>
/// Convert an NtStatus to an exception if the status is an error and throw_on_error is true.
/// </summary>
/// <param name="status">The NtStatus</param>
/// <param name="throw_on_error">True to throw an exception onerror.</param>
/// <returns>The original NtStatus if not thrown</returns>
/// <exception cref="NtException">Thrown if status is an error and throw_on_error is true.</exception>
public static NtStatus ToNtException(this NtStatus status, bool throw_on_error)
{
if (throw_on_error && !status.IsSuccess())
{
throw new NtException(status);
}
return status;
}
/// <summary>
/// Checks if the NtStatus value is a success
/// </summary>
/// <param name="status">The NtStatus value</param>
/// <returns>True if a success</returns>
public static bool IsSuccess(this NtStatus status)
{
return (int)status >= 0;
}
[DllImport("kernel32.dll", CharSet = CharSet.Unicode, SetLastError = true)]
private static extern IntPtr GetModuleHandle(string modulename);
[Flags]
enum FormatFlags
{
AllocateBuffer = 0x00000100,
FromHModule = 0x00000800,
FromSystem = 0x00001000,
IgnoreInserts = 0x00000200
}
[DllImport("kernel32.dll", CharSet = CharSet.Unicode, SetLastError = true)]
private static extern int FormatMessage(
FormatFlags dwFlags,
IntPtr lpSource,
uint dwMessageId,
int dwLanguageId,
out SafeLocalAllocHandle lpBuffer,
int nSize,
IntPtr Arguments
);
/// <summary>
/// Convert an NTSTATUS to a message description.
/// </summary>
/// <param name="status">The status to convert.</param>
/// <returns>The message description, or an empty string if not found.</returns>
public static string GetNtStatusMessage(NtStatus status)
{
IntPtr module_handle = IntPtr.Zero;
uint message_id = (uint)status;
if ((message_id & 0xFFFF0000) == DosErrorStatusCode)
{
message_id &= 0xFFFF;
module_handle = GetModuleHandle("kernel32.dll");
}
else
{
module_handle = GetModuleHandle("ntdll.dll");
}
if (FormatMessage(FormatFlags.AllocateBuffer | FormatFlags.FromHModule
| FormatFlags.FromSystem | FormatFlags.IgnoreInserts,
module_handle, message_id, 0, out SafeLocalAllocHandle buffer, 0, IntPtr.Zero) > 0)
{
using (buffer)
{
return Marshal.PtrToStringUni(buffer.DangerousGetHandle()).Trim();
}
}
return String.Empty;
}
/// <summary>
/// Convert an integer to an NtStatus code.
/// </summary>
/// <param name="status">The integer status.</param>
/// <returns>The converted code.</returns>
public static NtStatus ConvertIntToNtStatus(int status)
{
return (NtStatus)(uint)status;
}
internal static bool GetBit(this int result, int bit)
{
return (result & (1 << bit)) != 0;
}
internal static void CheckEnumType(Type t)
{
if (!t.IsEnum || t.GetEnumUnderlyingType() != typeof(uint))
{
throw new ArgumentException("Type must be an enumeration of unsigned int.");
}
}
internal static string ToHexString(this byte[] ba, int offset, int length)
{
return BitConverter.ToString(ba, offset, length).Replace("-", string.Empty);
}
internal static string ToHexString(this byte[] ba, int offset)
{
return BitConverter.ToString(ba, offset).Replace("-", string.Empty);
}
internal static string ToHexString(this byte[] ba)
{
return BitConverter.ToString(ba).Replace("-", string.Empty);
}
/// <summary>
/// Convert an access rights type to a string.
/// </summary>
/// <param name="t">The enumeration type for the string conversion</param>
/// <param name="access">The access mask to convert</param>
/// <returns>The string version of the access</returns>
internal static string AccessRightsToString(Type t, AccessMask access)
{
List<string> names = new List<string>();
uint remaining = access.Access;
// If the valid is explicitly defined return it.
if (Enum.IsDefined(t, remaining))
{
return Enum.GetName(t, remaining);
}
for (int i = 0; i < 32; ++i)
{
uint mask = 1U << i;
if (mask > remaining)
{
break;
}
if (mask == (uint)GenericAccessRights.MaximumAllowed)
{
continue;
}
if ((remaining & mask) == 0)
{
continue;
}
if (!Enum.IsDefined(t, mask))
{
continue;
}
names.Add(Enum.GetName(t, mask));
remaining = remaining & ~mask;
}
if (remaining != 0)
{
names.Add($"0x{remaining:X}");
}
if (names.Count == 0)
{
names.Add("None");
}
return string.Join("|", names);
}
/// <summary>
/// Convert an enumerable access rights to a string
/// </summary>
/// <param name="access">The access rights</param>
/// <returns>The string format of the access rights</returns>
internal static string AccessRightsToString(Enum access)
{
return AccessRightsToString(access.GetType(), access);
}
/// <summary>
/// Convert an enumerable access rights to a string
/// </summary>
/// <param name="granted_access">The granted access mask.</param>
/// <param name="generic_mapping">Generic mapping for object type.</param>
/// <param name="enum_type">Enum type to convert to string.</param>
/// <param name="map_to_generic">True to try and convert to generic rights where possible.</param>
/// <returns>The string format of the access rights</returns>
public static string GrantedAccessAsString(AccessMask granted_access, GenericMapping generic_mapping, Type enum_type, bool map_to_generic)
{
if (granted_access == 0)
{
return "None";
}
AccessMask mapped_access = generic_mapping.MapMask(granted_access);
if (map_to_generic)
{
mapped_access = generic_mapping.UnmapMask(mapped_access);
}
else if (generic_mapping.HasAll(granted_access))
{
return "Full Access";
}
return NtObjectUtils.AccessRightsToString(enum_type, mapped_access);
}
/// <summary>
/// Convert an IEnumerable to a Disposable List.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="list"></param>
/// <returns></returns>
public static DisposableList<T> ToDisposableList<T>(this IEnumerable<T> list) where T : IDisposable
{
return new DisposableList<T>(list);
}
/// <summary>
/// Run a function on an NtResult and dispose the result afterwards.
/// </summary>
/// <typeparam name="T">The underlying result type.</typeparam>
/// <typeparam name="S">The result of the function.</typeparam>
/// <param name="result">The result.</param>
/// <param name="func">The function to call.</param>
/// <returns>The result of func.</returns>
/// <remarks>If result is not a success then the function is not called.</remarks>
public static S RunAndDispose<T, S>(this NtResult<T> result, Func<T, S> func) where T : NtObject
{
if (!result.IsSuccess)
{
return default(S);
}
using (result)
{
return func(result.Result);
}
}
/// <summary>
/// Run an action on an NtResult and dispose the result afterwards.
/// </summary>
/// <typeparam name="T">The underlying result type.</typeparam>
/// <param name="result">The result.</param>
/// <param name="action">The action to call.</param>
/// <remarks>If result is not a success then the action is not called.</remarks>
public static void RunAndDispose<T>(this NtResult<T> result, Action<T> action) where T : NtObject
{
if (!result.IsSuccess)
{
return;
}
using (result)
{
action(result.Result);
}
}
/// <summary>
/// Run a function on an NtResult and dispose the result afterwards.
/// </summary>
/// <typeparam name="T">The underlying result type.</typeparam>
/// <typeparam name="S">The result of the function.</typeparam>
/// <param name="result">The result.</param>
/// <param name="func">The function to call.</param>
/// <returns>The result of func.</returns>
public static S RunAndDispose<T, S>(this T result, Func<T, S> func) where T : NtObject
{
using (result)
{
return func(result);
}
}
/// <summary>
/// Run an action on an NtResult and dispose the result afterwards.
/// </summary>
/// <typeparam name="T">The underlying result type.</typeparam>
/// <param name="result">The result.</param>
/// <param name="action">The action to call.</param>
public static void RunAndDispose<T>(this T result, Action<T> action) where T : NtObject
{
using (result)
{
action(result);
}
}
// A special "fake" status code to map DOS errors to NTSTATUS.
private const uint DosErrorStatusCode = 0xF00D0000;
internal static NtStatus MapDosErrorToStatus(int dos_error)
{
return (NtStatus)(DosErrorStatusCode | dos_error);
}
internal static NtStatus MapDosErrorToStatus()
{
return MapDosErrorToStatus(Marshal.GetLastWin32Error());
}
/// <summary>
/// Map a status to a DOS error code. Takes into account the fake
/// status codes.
/// </summary>
/// <param name="status">The status code.</param>
/// <returns>The mapped DOS error.</returns>
public static int MapNtStatusToDosError(NtStatus status)
{
uint value = (uint)status;
if ((value & 0xFFFF0000) == DosErrorStatusCode)
{
return (int)(value & 0xFFFF);
}
return NtRtl.RtlNtStatusToDosError(status);
}
/// <summary>
/// Create an NT result object. If status is successful then call function otherwise use default value.
/// </summary>
/// <typeparam name="T">The result type.</typeparam>
/// <param name="status">The associated status case.</param>
/// <param name="throw_on_error">Throw an exception on error.</param>
/// <param name="create_func">Function to call to create an instance of the result</param>
/// <returns>The created result.</returns>
internal static NtResult<T> CreateResult<T>(this NtStatus status, bool throw_on_error, Func<T> create_func)
{
return CreateResult(status, throw_on_error, s => create_func());
}
/// <summary>
/// Create an NT result object. If status is successful then call function otherwise use default value.
/// </summary>
/// <typeparam name="T">The result type.</typeparam>
/// <param name="status">The associated status case.</param>
/// <param name="throw_on_error">Throw an exception on error.</param>
/// <param name="create_func">Function to call to create an instance of the result</param>
/// <returns>The created result.</returns>
internal static NtResult<T> CreateResult<T>(this NtStatus status, bool throw_on_error, Func<NtStatus, T> create_func)
{
if (status.IsSuccess())
{
return new NtResult<T>(status, create_func(status));
}
if (throw_on_error)
{
throw new NtException(status);
}
return new NtResult<T>(status, default(T));
}
internal static NtResult<T> CreateResultFromError<T>(this NtStatus status, bool throw_on_error)
{
if (throw_on_error)
{
throw new NtException(status);
}
return new NtResult<T>(status, default(T));
}
internal static NtResult<T> CreateResultFromDosError<T>(int error, bool throw_on_error)
{
NtStatus status = MapDosErrorToStatus(error);
if (throw_on_error)
{
throw new NtException(status);
}
return new NtResult<T>(status, default(T));
}
internal static IEnumerable<T> SelectValidResults<T>(this IEnumerable<NtResult<T>> iterator)
{
return iterator.Where(r => r.IsSuccess).Select(r => r.Result);
}
internal static SafeKernelObjectHandle ToSafeKernelHandle(this SafeHandle handle)
{
if (handle is SafeKernelObjectHandle)
{
return (SafeKernelObjectHandle)handle;
}
return new SafeKernelObjectHandle(handle.DangerousGetHandle(), false);
}
internal static IEnumerable<T> ToCached<T>(this IEnumerable<T> enumerable)
{
return new CachedEnumerable<T>(enumerable);
}
internal static bool IsWindows7OrLess
{
get
{
return Environment.OSVersion.Version < new Version(6, 2);
}
}
internal static bool IsWindows8OrLess
{
get
{
return Environment.OSVersion.Version < new Version(6, 3);
}
}
internal static bool IsWindows81OrLess
{
get
{
return Environment.OSVersion.Version < new Version(6, 4);
}
}
}
}
| 35.011834 | 146 | 0.548814 | [
"Apache-2.0"
] | 1orenz0/sandbox-attacksurface-analysis-tools | NtApiDotNet/NtObjectUtils.cs | 17,753 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
namespace DotNetNuke.Extensions.Data
{
public static class DataExtensions
{
/// <summary>
/// Simple recordset field routines. Returns results as type value.
/// </summary>
/// <typeparam name="T">Type to return as.</typeparam>
/// <param name="rs">Datareader.</param>
/// <param name="fieldName">Fieldname to retrieve.</param>
/// <returns>Value of field.</returns>
public static T Field<T>(this IDataReader rs, string fieldName) where T : struct
{
int idx = rs.GetOrdinal(fieldName);
object returnValue = null;
if (typeof(T) == typeof(bool))
{
if (rs.IsDBNull(idx))
{
returnValue = false;
}
else
{
String s = rs[fieldName].ToString();
returnValue = (s.Equals("TRUE", StringComparison.InvariantCultureIgnoreCase) ||
s.Equals("YES", StringComparison.InvariantCultureIgnoreCase) ||
s.Equals("1", StringComparison.InvariantCultureIgnoreCase));
}
}
else if (typeof(T) == typeof(Guid))
{
if (rs.IsDBNull(idx))
returnValue = Guid.Empty;
else
returnValue = rs.GetGuid(idx);
}
else if (typeof(T) == typeof(int))
{
if (rs.IsDBNull(idx))
returnValue = 0;
else
returnValue = rs.GetInt32(idx);
}
else if (typeof(T) == typeof(double))
{
if (rs.IsDBNull(idx))
returnValue = 0.0F;
else
returnValue = rs.GetDouble(idx);
}
else if (typeof(T) == typeof(decimal))
{
if (rs.IsDBNull(idx))
returnValue = System.Decimal.Zero;
else
returnValue = rs.GetDecimal(idx);
}
else if (typeof(T) == typeof(DateTime))
{
if (rs.IsDBNull(idx))
returnValue = System.DateTime.MinValue;
else
returnValue = Convert.ToDateTime(rs[idx], System.Globalization.CultureInfo.InvariantCulture);
}
else
{
throw new ArgumentOutOfRangeException(string.Format("Provided type '{0}' is not implemented.", typeof(T).Name));
}
return (T)Convert.ChangeType(returnValue, typeof(T));
}
}
}
| 34.691358 | 128 | 0.476512 | [
"Unlicense"
] | JonHaywood/DotNetNuke.Extensions | DotNetNuke.Extensions/Data/DataExtensions.cs | 2,812 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using Framework.Core;
using Framework.Persistent;
using Framework.SecuritySystem.Exceptions;
namespace Framework.SecuritySystem
{
public class AccessDeniedExceptionService<TPersistentDomainObjectBase, TIdent> : IAccessDeniedExceptionService<TPersistentDomainObjectBase>
where TPersistentDomainObjectBase : class, IIdentityObject<TIdent>
{
public Exception GetAccessDeniedException(string message) =>
new AccessDeniedException<TIdent>(string.Empty, default, message);
public Exception GetAccessDeniedException<TDomainObject>(TDomainObject domainObject, IReadOnlyDictionary<string, object> extensions = null, Func<string, string> formatMessageFunc = null)
where TDomainObject : class, TPersistentDomainObjectBase =>
new AccessDeniedException<TIdent>(
typeof(TDomainObject).Name,
domainObject.Id,
this.GetAccessDeniedExceptionMessage(
domainObject,
extensions,
formatMessageFunc ?? (v => v)));
protected virtual string GetAccessDeniedExceptionMessage<TDomainObject>(TDomainObject domainObject, IReadOnlyDictionary<string, object> extensions = null, Func<string, string> formatMessageFunc = null)
where TDomainObject : class, TPersistentDomainObjectBase
{
if (domainObject == null) throw new ArgumentNullException(nameof(domainObject));
var displayExtensions = extensions.EmptyIfNull().Where(pair => !pair.Key.EndsWith("_Raw")).ToDictionary();
var elements = this.GetAccessDeniedExceptionMessageElements(domainObject).Concat(displayExtensions).ToDictionary();
return elements.GetByFirst((first, other) =>
{
var messagePrefix = domainObject.Id.IsDefault() ? "You have no permissions to create object"
: "You have no permissions to access object";
var messageBody = $" with {this.PrintElement(first.Key, first.Value)}";
var messagePostfix = other.Any() ? $" ({other.Join(", ", pair => this.PrintElement(pair.Key, pair.Value))})" : "";
var realFormatMessageFunc = formatMessageFunc ?? (v => v);
return realFormatMessageFunc(messagePrefix + messageBody + messagePostfix);
});
}
protected virtual string PrintElement(string key, object value)
{
return $"{key} = '{value}'";
}
protected virtual IEnumerable<KeyValuePair<string, object>> GetAccessDeniedExceptionMessageElements<TDomainObject>(TDomainObject domainObject)
where TDomainObject : class, TPersistentDomainObjectBase
{
if (domainObject is IVisualIdentityObject identityObject)
{
var name = identityObject.Name;
yield return new KeyValuePair<string, object>("name", name);
}
yield return new KeyValuePair<string, object>("type", typeof(TDomainObject).Name);
yield return new KeyValuePair<string, object>("id", domainObject.Id);
}
}
}
| 45.108108 | 210 | 0.641102 | [
"MIT"
] | Luxoft/BSSFramework | src/Framework.SecuritySystem/AccessDeniedExceptionService/AccessDeniedExceptionService.cs | 3,267 | C# |
using System;
using UnityEngine;
using uPalette.Runtime.Foundation.Observable.ObservableCollection;
using uPalette.Runtime.Foundation.Observable.ObservableProperty;
namespace uPalette.Runtime.Core
{
[Serializable]
public class UPaletteStore
{
[SerializeField] private ObservableList<ColorEntry> _entries = new ObservableList<ColorEntry>();
public ObservableList<ColorEntry> Entries => _entries;
public ObservableProperty<bool> IsDirty { get; } = new ObservableProperty<bool>();
}
} | 32.75 | 104 | 0.757634 | [
"MIT"
] | Haruma-K/uPalette | Assets/uPalette/Runtime/Core/UPaletteStore.cs | 526 | C# |
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using System.Collections.Generic;
using System.Linq;
using Moq;
using NUnit.Framework;
using osu.Game.Beatmaps;
using osu.Game.Rulesets.Edit;
using osu.Game.Rulesets.Objects;
using osu.Game.Rulesets.Objects.Types;
using osu.Game.Rulesets.Osu.Edit.Checks;
using osu.Game.Rulesets.Osu.Objects;
using osu.Game.Tests.Beatmaps;
using osuTK;
namespace osu.Game.Rulesets.Osu.Tests.Editor.Checks
{
[TestFixture]
public class CheckTimeDistanceEqualityTest
{
private CheckTimeDistanceEquality check;
[SetUp]
public void Setup()
{
check = new CheckTimeDistanceEquality();
}
[Test]
public void TestCirclesEquidistant()
{
assertOk(new Beatmap<HitObject>
{
HitObjects = new List<HitObject>
{
new HitCircle { StartTime = 0, Position = new Vector2(0) },
new HitCircle { StartTime = 500, Position = new Vector2(50, 0) },
new HitCircle { StartTime = 1000, Position = new Vector2(100, 0) },
new HitCircle { StartTime = 1500, Position = new Vector2(150, 0) }
}
});
}
[Test]
public void TestCirclesOneSlightlyOff()
{
assertWarning(new Beatmap<HitObject>
{
HitObjects = new List<HitObject>
{
new HitCircle { StartTime = 0, Position = new Vector2(0) },
new HitCircle { StartTime = 500, Position = new Vector2(50, 0) },
new HitCircle { StartTime = 1000, Position = new Vector2(80, 0) }, // Distance a quite low compared to previous.
new HitCircle { StartTime = 1500, Position = new Vector2(130, 0) }
}
});
}
[Test]
public void TestCirclesOneOff()
{
assertProblem(new Beatmap<HitObject>
{
HitObjects = new List<HitObject>
{
new HitCircle { StartTime = 0, Position = new Vector2(0) },
new HitCircle { StartTime = 500, Position = new Vector2(50, 0) },
new HitCircle { StartTime = 1000, Position = new Vector2(150, 0) }, // Twice the regular spacing.
new HitCircle { StartTime = 1500, Position = new Vector2(100, 0) }
}
});
}
[Test]
public void TestCirclesTwoOff()
{
assertProblem(new Beatmap<HitObject>
{
HitObjects = new List<HitObject>
{
new HitCircle { StartTime = 0, Position = new Vector2(0) },
new HitCircle { StartTime = 500, Position = new Vector2(50, 0) },
new HitCircle { StartTime = 1000, Position = new Vector2(150, 0) }, // Twice the regular spacing.
new HitCircle { StartTime = 1500, Position = new Vector2(250, 0) } // Also twice the regular spacing.
}
}, count: 2);
}
[Test]
public void TestCirclesStacked()
{
assertOk(new Beatmap<HitObject>
{
HitObjects = new List<HitObject>
{
new HitCircle { StartTime = 0, Position = new Vector2(0) },
new HitCircle { StartTime = 500, Position = new Vector2(50, 0) },
new HitCircle { StartTime = 1000, Position = new Vector2(50, 0) }, // Stacked, is fine.
new HitCircle { StartTime = 1500, Position = new Vector2(100, 0) }
}
});
}
[Test]
public void TestCirclesStacking()
{
assertWarning(new Beatmap<HitObject>
{
HitObjects = new List<HitObject>
{
new HitCircle { StartTime = 0, Position = new Vector2(0) },
new HitCircle { StartTime = 500, Position = new Vector2(50, 0) },
new HitCircle { StartTime = 1000, Position = new Vector2(50, 0), StackHeight = 1 },
new HitCircle { StartTime = 1500, Position = new Vector2(50, 0), StackHeight = 2 },
new HitCircle { StartTime = 2000, Position = new Vector2(50, 0), StackHeight = 3 },
new HitCircle { StartTime = 2500, Position = new Vector2(50, 0), StackHeight = 4 }, // Ends up far from (50; 0), causing irregular spacing.
new HitCircle { StartTime = 3000, Position = new Vector2(100, 0) }
}
});
}
[Test]
public void TestCirclesHalfStack()
{
assertOk(new Beatmap<HitObject>
{
HitObjects = new List<HitObject>
{
new HitCircle { StartTime = 0, Position = new Vector2(0) },
new HitCircle { StartTime = 500, Position = new Vector2(50, 0) },
new HitCircle { StartTime = 1000, Position = new Vector2(55, 0) }, // Basically stacked, so is fine.
new HitCircle { StartTime = 1500, Position = new Vector2(105, 0) }
}
});
}
[Test]
public void TestCirclesPartialOverlap()
{
assertProblem(new Beatmap<HitObject>
{
HitObjects = new List<HitObject>
{
new HitCircle { StartTime = 0, Position = new Vector2(0) },
new HitCircle { StartTime = 500, Position = new Vector2(50, 0) },
new HitCircle { StartTime = 1000, Position = new Vector2(65, 0) }, // Really low distance compared to previous.
new HitCircle { StartTime = 1500, Position = new Vector2(115, 0) }
}
});
}
[Test]
public void TestCirclesSlightlyDifferent()
{
assertOk(new Beatmap<HitObject>
{
HitObjects = new List<HitObject>
{
// Does not need to be perfect, as long as the distance is approximately correct it's sight-readable.
new HitCircle { StartTime = 0, Position = new Vector2(0) },
new HitCircle { StartTime = 500, Position = new Vector2(52, 0) },
new HitCircle { StartTime = 1000, Position = new Vector2(97, 0) },
new HitCircle { StartTime = 1500, Position = new Vector2(165, 0) }
}
});
}
[Test]
public void TestCirclesSlowlyChanging()
{
const float multiplier = 1.2f;
assertOk(new Beatmap<HitObject>
{
HitObjects = new List<HitObject>
{
new HitCircle { StartTime = 0, Position = new Vector2(0) },
new HitCircle { StartTime = 500, Position = new Vector2(50, 0) },
new HitCircle { StartTime = 1000, Position = new Vector2(50 + 50 * multiplier, 0) },
// This gap would be a warning if it weren't for the previous pushing the average spacing up.
new HitCircle { StartTime = 1500, Position = new Vector2(50 + 50 * multiplier + 50 * multiplier * multiplier, 0) }
}
});
}
[Test]
public void TestCirclesQuicklyChanging()
{
const float multiplier = 1.6f;
var beatmap = new Beatmap<HitObject>
{
HitObjects = new List<HitObject>
{
new HitCircle { StartTime = 0, Position = new Vector2(0) },
new HitCircle { StartTime = 500, Position = new Vector2(50, 0) },
new HitCircle { StartTime = 1000, Position = new Vector2(50 + 50 * multiplier, 0) }, // Warning
new HitCircle { StartTime = 1500, Position = new Vector2(50 + 50 * multiplier + 50 * multiplier * multiplier, 0) } // Problem
}
};
var context = new BeatmapVerifierContext(beatmap, new TestWorkingBeatmap(beatmap), DifficultyRating.Easy);
var issues = check.Run(context).ToList();
Assert.That(issues, Has.Count.EqualTo(2));
Assert.That(issues.First().Template is CheckTimeDistanceEquality.IssueTemplateIrregularSpacingWarning);
Assert.That(issues.Last().Template is CheckTimeDistanceEquality.IssueTemplateIrregularSpacingProblem);
}
[Test]
public void TestCirclesTooFarApart()
{
assertOk(new Beatmap<HitObject>
{
HitObjects = new List<HitObject>
{
new HitCircle { StartTime = 0, Position = new Vector2(0) },
new HitCircle { StartTime = 500, Position = new Vector2(50, 0) },
new HitCircle { StartTime = 4000, Position = new Vector2(200, 0) }, // 2 seconds apart from previous, so can start from wherever.
new HitCircle { StartTime = 4500, Position = new Vector2(250, 0) }
}
});
}
[Test]
public void TestCirclesOneOffExpert()
{
assertOk(new Beatmap<HitObject>
{
HitObjects = new List<HitObject>
{
new HitCircle { StartTime = 0, Position = new Vector2(0) },
new HitCircle { StartTime = 500, Position = new Vector2(50, 0) },
new HitCircle { StartTime = 1000, Position = new Vector2(150, 0) }, // Jumps are allowed in higher difficulties.
new HitCircle { StartTime = 1500, Position = new Vector2(100, 0) }
}
}, DifficultyRating.Expert);
}
[Test]
public void TestSpinner()
{
assertOk(new Beatmap<HitObject>
{
HitObjects = new List<HitObject>
{
new HitCircle { StartTime = 0, Position = new Vector2(0) },
new HitCircle { StartTime = 500, Position = new Vector2(50, 0) },
new Spinner { StartTime = 500, EndTime = 1000 }, // Distance to and from the spinner should be ignored. If it isn't this should give a problem.
new HitCircle { StartTime = 1500, Position = new Vector2(100, 0) },
new HitCircle { StartTime = 2000, Position = new Vector2(150, 0) }
}
});
}
[Test]
public void TestSliders()
{
assertOk(new Beatmap<HitObject>
{
HitObjects = new List<HitObject>
{
new HitCircle { StartTime = 0, Position = new Vector2(0) },
new HitCircle { StartTime = 500, Position = new Vector2(50, 0) },
getSliderMock(startTime: 1000, endTime: 1500, startPosition: new Vector2(100, 0), endPosition: new Vector2(150, 0)).Object,
getSliderMock(startTime: 2000, endTime: 2500, startPosition: new Vector2(200, 0), endPosition: new Vector2(250, 0)).Object,
new HitCircle { StartTime = 2500, Position = new Vector2(300, 0) }
}
});
}
[Test]
public void TestSlidersOneOff()
{
assertProblem(new Beatmap<HitObject>
{
HitObjects = new List<HitObject>
{
new HitCircle { StartTime = 0, Position = new Vector2(0) },
new HitCircle { StartTime = 500, Position = new Vector2(50, 0) },
getSliderMock(startTime: 1000, endTime: 1500, startPosition: new Vector2(100, 0), endPosition: new Vector2(150, 0)).Object,
getSliderMock(startTime: 2000, endTime: 2500, startPosition: new Vector2(250, 0), endPosition: new Vector2(300, 0)).Object, // Twice the spacing.
new HitCircle { StartTime = 2500, Position = new Vector2(300, 0) }
}
});
}
private Mock<Slider> getSliderMock(double startTime, double endTime, Vector2 startPosition, Vector2 endPosition)
{
var mockSlider = new Mock<Slider>();
mockSlider.SetupGet(s => s.StartTime).Returns(startTime);
mockSlider.SetupGet(s => s.Position).Returns(startPosition);
mockSlider.SetupGet(s => s.EndPosition).Returns(endPosition);
mockSlider.As<IHasDuration>().Setup(d => d.EndTime).Returns(endTime);
return mockSlider;
}
private void assertOk(IBeatmap beatmap, DifficultyRating difficultyRating = DifficultyRating.Easy)
{
var context = new BeatmapVerifierContext(beatmap, new TestWorkingBeatmap(beatmap), difficultyRating);
Assert.That(check.Run(context), Is.Empty);
}
private void assertWarning(IBeatmap beatmap, int count = 1)
{
var context = new BeatmapVerifierContext(beatmap, new TestWorkingBeatmap(beatmap), DifficultyRating.Easy);
var issues = check.Run(context).ToList();
Assert.That(issues, Has.Count.EqualTo(count));
Assert.That(issues.All(issue => issue.Template is CheckTimeDistanceEquality.IssueTemplateIrregularSpacingWarning));
}
private void assertProblem(IBeatmap beatmap, int count = 1)
{
var context = new BeatmapVerifierContext(beatmap, new TestWorkingBeatmap(beatmap), DifficultyRating.Easy);
var issues = check.Run(context).ToList();
Assert.That(issues, Has.Count.EqualTo(count));
Assert.That(issues.All(issue => issue.Template is CheckTimeDistanceEquality.IssueTemplateIrregularSpacingProblem));
}
}
}
| 44.366154 | 166 | 0.524863 | [
"MIT"
] | 02Naitsirk/osu | osu.Game.Rulesets.Osu.Tests/Editor/Checks/CheckTimeDistanceEqualityTest.cs | 14,095 | C# |
using System;
using System.Collections.Generic;
using System.IO;
using System.Reflection;
using System.Text;
using OpenTK;
using OpenTK.Graphics;
using OpenTK.Graphics.OpenGL;
namespace GameCore.Render.Materials
{
public class MateriaParamAttribute : Attribute
{
}
public abstract class MaterialBase
{
private readonly Dictionary<PropertyInfo, int> _paramLinks = new Dictionary<PropertyInfo, int>();
protected readonly int Handle;
public static string DefaultShaderName => null; //todo: заменить аттрибутом
public abstract void BindInVertexPosition();
public abstract void BindInVertexNormal();
public abstract void BindInVertexColor();
public abstract void BindInVertexTexcood();
public MaterialBase(string fsPath, string vsPath)
{
var fragmentShaderHandle = GL.CreateShader(ShaderType.FragmentShader);
var vertexShaderHandle = GL.CreateShader(ShaderType.VertexShader);
GL.ShaderSource(fragmentShaderHandle, File.ReadAllText(fsPath, Encoding.UTF8));
GL.ShaderSource(vertexShaderHandle, File.ReadAllText(vsPath, Encoding.UTF8));
GL.CompileShader(vertexShaderHandle);
GL.CompileShader(fragmentShaderHandle);
Handle = GL.CreateProgram();
GL.AttachShader(Handle, vertexShaderHandle);
GL.AttachShader(Handle, fragmentShaderHandle);
GL.LinkProgram(Handle);
LinkProps();
var log = GL.GetProgramInfoLog(Handle);
if (!string.IsNullOrWhiteSpace(log))
Console.WriteLine(log);
}
private void LinkProps()
{
var type = GetType();
foreach (var property in type.GetProperties())
{
var matParamAttr = property.GetCustomAttribute<MateriaParamAttribute>();
if (matParamAttr == null)
continue;
if (property.PropertyType != typeof(Texture))
{
var name = char.ToLower(property.Name[0]) + property.Name.Substring(1);
var location = GL.GetUniformLocation(Handle, name);
if (location == -1)
Console.WriteLine($"Failed link property {name} to shader in {GetType().Name}");
_paramLinks.Add(property, location);
}
else
{
_paramLinks.Add(property, -1);
}
}
}
public virtual void AppyGlobal()
{
}
//todo: update only changed params
public virtual void Use()
{
GL.UseProgram(Handle);
foreach (var link in _paramLinks)
{
var value = link.Key.GetValue(this);
switch (value)
{
case Matrix4 mtx4:
GL.UniformMatrix4(link.Value, false, ref mtx4);
break;
case Matrix3 mtx3:
GL.UniformMatrix3(link.Value, false, ref mtx3);
break;
case Matrix2 mtx2:
GL.UniformMatrix2(link.Value, false, ref mtx2);
break;
case Vector2 vec2:
GL.Uniform2(link.Value, ref vec2);
break;
case Vector3 vec3:
GL.Uniform3(link.Value, ref vec3);
break;
case Vector4 vec4:
GL.Uniform4(link.Value, ref vec4);
break;
case Color4 color4:
GL.Uniform4(link.Value, color4);
break;
case float num:
GL.Uniform1(link.Value, num);
break;
case int num:
GL.Uniform1(link.Value, num);
break;
case bool boolean:
GL.Uniform1(link.Value, boolean ? 1 : 0);
break;
case Texture texture:
GL.BindTexture(TextureTarget.Texture2D, texture.Handle);
break;
case null:
GL.Uniform1(link.Value, -1);
break;
default:
throw new NotSupportedException($"Type {value.GetType()} is not supported in shader programm");
}
}
}
}
} | 34.547445 | 119 | 0.499261 | [
"MIT"
] | mrkriv/VoxelWorld | GameCore/Render/Materials/MaterialBase.cs | 4,753 | C# |
namespace BUTR.CrashReportViewer.Shared.Models.API
{
public record PagingMetadata
{
public int CurrentPage { get; set; }
public int TotalPages { get; set; }
public int PageSize { get; set; }
public int TotalCount { get; set; }
public bool HasPrevious => CurrentPage > 1;
public bool HasNext => CurrentPage < TotalPages;
}
} | 32 | 56 | 0.627604 | [
"MIT"
] | BUTR/BUTR.CrashReportViewer | src/BUTR.CrashReportViewer/Shared/Models/API/PagingMetadata.cs | 386 | C# |
using System.IO;
namespace TeleSharp.TL
{
[TLObject(-1892568281)]
public class TLMessageActionPaymentSentMe : TLAbsMessageAction
{
public override int Constructor
{
get
{
return -1892568281;
}
}
public int Flags { get; set; }
public string Currency { get; set; }
public long TotalAmount { get; set; }
public byte[] Payload { get; set; }
public TLPaymentRequestedInfo Info { get; set; }
public string ShippingOptionId { get; set; }
public TLPaymentCharge Charge { get; set; }
public void ComputeFlags()
{
Flags = 0;
Flags = Info != null ? (Flags | 1) : (Flags & ~1);
Flags = ShippingOptionId != null ? (Flags | 2) : (Flags & ~2);
}
public override void DeserializeBody(BinaryReader br)
{
Flags = br.ReadInt32();
Currency = StringUtil.Deserialize(br);
TotalAmount = br.ReadInt64();
Payload = BytesUtil.Deserialize(br);
if ((Flags & 1) != 0)
{
Info = (TLPaymentRequestedInfo)ObjectUtils.DeserializeObject(br);
}
else
{
Info = null;
}
if ((Flags & 2) != 0)
{
ShippingOptionId = StringUtil.Deserialize(br);
}
else
{
ShippingOptionId = null;
}
Charge = (TLPaymentCharge)ObjectUtils.DeserializeObject(br);
}
public override void SerializeBody(BinaryWriter bw)
{
bw.Write(Constructor);
ComputeFlags();
bw.Write(Flags);
StringUtil.Serialize(Currency, bw);
bw.Write(TotalAmount);
BytesUtil.Serialize(Payload, bw);
if ((Flags & 1) != 0)
{
ObjectUtils.SerializeObject(Info, bw);
}
if ((Flags & 2) != 0)
{
StringUtil.Serialize(ShippingOptionId, bw);
}
ObjectUtils.SerializeObject(Charge, bw);
}
}
}
| 26.626506 | 81 | 0.48552 | [
"MIT"
] | cobra91/TelegramCSharpForward | TeleSharp.TL/TL/TLMessageActionPaymentSentMe.cs | 2,210 | 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.Cloudflare.Outputs
{
[OutputType]
public sealed class LoadBalancerPopPool
{
/// <summary>
/// A list of pool IDs in failover priority to use for traffic reaching the given PoP.
/// </summary>
public readonly ImmutableArray<string> PoolIds;
/// <summary>
/// A 3-letter code for the Point-of-Presence. Allowed values can be found in the list of datacenters on the [status page](https://www.cloudflarestatus.com/). Multiple entries should not be specified with the same PoP.
/// </summary>
public readonly string Pop;
[OutputConstructor]
private LoadBalancerPopPool(
ImmutableArray<string> poolIds,
string pop)
{
PoolIds = poolIds;
Pop = pop;
}
}
}
| 31.722222 | 226 | 0.648862 | [
"ECL-2.0",
"Apache-2.0"
] | pulumi/pulumi-cloudflare | sdk/dotnet/Outputs/LoadBalancerPopPool.cs | 1,142 | C# |
namespace DesignPatternStudy.Creational.Factory
{
public interface IApp
{
void Run();
}
} | 15.714286 | 48 | 0.636364 | [
"Unlicense"
] | guigsc/design-pattern-study | DesignPatternStudy/DesignPatternStudy.Creational.Factory/IApp.cs | 112 | C# |
/*
* Copyright 2010-2014 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
/*
* Do not modify this file. This file is generated from the es-2015-01-01.normal.json service model.
*/
using System;
using System.Collections.Generic;
using System.Xml.Serialization;
using System.Text;
using System.IO;
using System.Net;
using Amazon.Runtime;
using Amazon.Runtime.Internal;
namespace Amazon.Elasticsearch.Model
{
/// <summary>
/// Container for results from <code>DescribeReservedElasticsearchInstanceOfferings</code>
/// </summary>
public partial class DescribeReservedElasticsearchInstanceOfferingsResponse : AmazonWebServiceResponse
{
private string _nextToken;
private List<ReservedElasticsearchInstanceOffering> _reservedElasticsearchInstanceOfferings = new List<ReservedElasticsearchInstanceOffering>();
/// <summary>
/// Gets and sets the property NextToken.
/// <para>
/// Provides an identifier to allow retrieval of paginated results.
/// </para>
/// </summary>
public string NextToken
{
get { return this._nextToken; }
set { this._nextToken = value; }
}
// Check to see if NextToken property is set
internal bool IsSetNextToken()
{
return this._nextToken != null;
}
/// <summary>
/// Gets and sets the property ReservedElasticsearchInstanceOfferings.
/// <para>
/// List of reserved Elasticsearch instance offerings
/// </para>
/// </summary>
public List<ReservedElasticsearchInstanceOffering> ReservedElasticsearchInstanceOfferings
{
get { return this._reservedElasticsearchInstanceOfferings; }
set { this._reservedElasticsearchInstanceOfferings = value; }
}
// Check to see if ReservedElasticsearchInstanceOfferings property is set
internal bool IsSetReservedElasticsearchInstanceOfferings()
{
return this._reservedElasticsearchInstanceOfferings != null && this._reservedElasticsearchInstanceOfferings.Count > 0;
}
}
} | 35.144737 | 152 | 0.68289 | [
"Apache-2.0"
] | DetlefGolze/aws-sdk-net | sdk/src/Services/Elasticsearch/Generated/Model/DescribeReservedElasticsearchInstanceOfferingsResponse.cs | 2,671 | C# |
using Microsoft.AspNetCore;
using Microsoft.AspNetCore.Hosting;
namespace TomKerkhove.Demos.KeyVault.API
{
public class Program
{
public static IWebHost BuildWebHost(string[] args)
{
return WebHost.CreateDefaultBuilder(args)
.UseStartup<Startup>()
.UseApplicationInsights()
.Build();
}
public static void Main(string[] args)
{
BuildWebHost(args).Run();
}
}
} | 23.47619 | 58 | 0.56998 | [
"MIT"
] | tomkerkhove/demo-azure-key-vault-auth | src/TomKerkhove.Demos.KeyVault.API/Program.cs | 495 | C# |
/*
* The MIT License
*
* Copyright 2019 Palmtree Software.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
using System;
namespace Palmtree.Math.Core.Uint.Test.Plugin
{
class ComponentTestPlugin_op_LesserThan_I_X
: ComponentTestPluginBase_2_1
{
public ComponentTestPlugin_op_LesserThan_I_X()
: base("op_lesserthan_i_x", "test_data_lesserthan_i_x.xml")
{
}
protected override IDataItem TestFunc(IDataItem p1, IDataItem p2)
{
var u = p1.ToUInt32().Value;
var v = p2.ToUBigInt().Value;
var w = u < v;
return (new UInt32DataItem(w ? 1U : 0U));
}
}
}
/*
* END OF FILE
*/ | 34.039216 | 80 | 0.700461 | [
"MIT"
] | rougemeilland/Palmtree.Math.Core.Uint | Palmtree.Math.Core.Uint.Test/Plugin/ComponentTestPlugin_op_LesserThan_I_X.cs | 1,738 | 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.Collections.Immutable;
using System.Diagnostics;
using Microsoft.CodeAnalysis.EmbeddedLanguages.VirtualChars;
using Microsoft.CodeAnalysis.Text;
namespace Microsoft.CodeAnalysis.EmbeddedLanguages.Common
{
internal struct EmbeddedSyntaxToken<TSyntaxKind> where TSyntaxKind : struct
{
public readonly TSyntaxKind Kind;
public readonly ImmutableArray<EmbeddedSyntaxTrivia<TSyntaxKind>> LeadingTrivia;
public readonly VirtualCharSequence VirtualChars;
public readonly ImmutableArray<EmbeddedSyntaxTrivia<TSyntaxKind>> TrailingTrivia;
internal readonly ImmutableArray<EmbeddedDiagnostic> Diagnostics;
/// <summary>
/// Returns the value of the token. For example, if the token represents an integer capture,
/// then this property would return the actual integer.
/// </summary>
public readonly object Value;
public EmbeddedSyntaxToken(
TSyntaxKind kind,
ImmutableArray<EmbeddedSyntaxTrivia<TSyntaxKind>> leadingTrivia,
VirtualCharSequence virtualChars,
ImmutableArray<EmbeddedSyntaxTrivia<TSyntaxKind>> trailingTrivia,
ImmutableArray<EmbeddedDiagnostic> diagnostics, object value)
{
Debug.Assert(!leadingTrivia.IsDefault);
Debug.Assert(!virtualChars.IsDefault);
Debug.Assert(!trailingTrivia.IsDefault);
Debug.Assert(!diagnostics.IsDefault);
Kind = kind;
LeadingTrivia = leadingTrivia;
VirtualChars = virtualChars;
TrailingTrivia = trailingTrivia;
Diagnostics = diagnostics;
Value = value;
}
public bool IsMissing => VirtualChars.IsEmpty;
public EmbeddedSyntaxToken<TSyntaxKind> AddDiagnosticIfNone(EmbeddedDiagnostic diagnostic)
=> Diagnostics.Length > 0 ? this : WithDiagnostics(ImmutableArray.Create(diagnostic));
public EmbeddedSyntaxToken<TSyntaxKind> WithDiagnostics(ImmutableArray<EmbeddedDiagnostic> diagnostics)
=> With(diagnostics: diagnostics);
public EmbeddedSyntaxToken<TSyntaxKind> With(
Optional<TSyntaxKind> kind = default,
Optional<ImmutableArray<EmbeddedSyntaxTrivia<TSyntaxKind>>> leadingTrivia = default,
Optional<VirtualCharSequence> virtualChars = default,
Optional<ImmutableArray<EmbeddedSyntaxTrivia<TSyntaxKind>>> trailingTrivia = default,
Optional<ImmutableArray<EmbeddedDiagnostic>> diagnostics = default,
Optional<object> value = default)
{
return new EmbeddedSyntaxToken<TSyntaxKind>(
kind.HasValue ? kind.Value : Kind,
leadingTrivia.HasValue ? leadingTrivia.Value : LeadingTrivia,
virtualChars.HasValue ? virtualChars.Value : VirtualChars,
trailingTrivia.HasValue ? trailingTrivia.Value : TrailingTrivia,
diagnostics.HasValue ? diagnostics.Value : Diagnostics,
value.HasValue ? value.Value : Value);
}
public TextSpan GetSpan()
=> EmbeddedSyntaxHelpers.GetSpan(this.VirtualChars);
}
}
| 45.039474 | 111 | 0.69033 | [
"MIT"
] | BrianFreemanAtlanta/roslyn | src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/EmbeddedLanguages/Common/EmbeddedSyntaxToken.cs | 3,425 | C# |
namespace CoreLayer.Citrix.Adc.NitroClient.Api.Configuration.LoadBalancing.LbvserverBinding
{
public class LbvserverBindingGetServicegroupRequestOptions : NitroRequestOptions
{
public override string ToString()
{
return base.ToString() == string.Empty ? "?bulkbindings=yes" : base.ToString();
}
}
public enum LbvserverBindingGetServicegroupRequestOptionsProperties
{
}
} | 29.333333 | 91 | 0.697727 | [
"Apache-2.0"
] | CoreLayer/CoreLayer.Citrix.Adc.Nitro | src/CoreLayer.Citrix.Adc.NitroClient/Api/Configuration/LoadBalancing/LbvserverBinding/LbvserverBindingGetServicegroupRequestOptions.cs | 440 | C# |
//
// System.Data.Odbc.OdbcRowUpdatedEventHandler.cs
//
// Author:
// Rodrigo Moya (rodrigo@ximian.com)
// Daniel Morgan (danmorg@sc.rr.com)
//
// (C) Ximian, Inc 2002
//
//
// Copyright (C) 2004 Novell, Inc (http://www.novell.com)
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
using System;
namespace System.Data.Odbc {
public delegate void OdbcRowUpdatedEventHandler (object sender, OdbcRowUpdatedEventArgs e);
}
| 37.435897 | 92 | 0.749315 | [
"Apache-2.0"
] | 121468615/mono | mcs/class/System.Data/System.Data.Odbc/OdbcRowUpdatedEventHandler.cs | 1,460 | C# |
using System.Runtime.InteropServices;
using Modbus.Core.Converters;
namespace Modbus.Core.DataTypes
{
[StructLayout(LayoutKind.Sequential, Pack = 1)]
public struct RequestFunc06
{
[Endian(Endianness.BigEndian)]
public ushort registerAddress;
[Endian(Endianness.BigEndian)]
public short value;
}
} | 23.133333 | 51 | 0.694524 | [
"Apache-2.0"
] | sontx/modbus | Core/DataTypes/RequestFunc06.cs | 349 | C# |
using System;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using SimplCommerce.Infrastructure.Data;
using SimplCommerce.Infrastructure.Web.SmartTable;
using SimplCommerce.Module.Core.Extensions.Constants;
using SimplCommerce.Module.Core.Models;
using SimplCommerce.Module.Vendors.Services;
using SimplCommerce.Module.Vendors.ViewModels;
namespace SimplCommerce.Module.Vendors.Controllers
{
[Authorize(Policy = Policy.CanManageUser)]
[Route("api/vendors")]
public class VendorApiController : Controller
{
private readonly IRepository<Vendor> _vendorRepository;
private readonly IVendorService _vendorService;
public VendorApiController(IRepository<Vendor> vendorRepository, IVendorService vendorService)
{
_vendorRepository = vendorRepository;
_vendorService = vendorService;
}
[HttpPost("grid")]
public ActionResult List([FromBody] SmartTableParam param)
{
var query = _vendorRepository.Query()
.Where(x => !x.IsDeleted);
if (param.Search.PredicateObject != null)
{
dynamic search = param.Search.PredicateObject;
if (search.Email != null)
{
string email = search.Email;
query = query.Where(x => x.Email.Contains(email));
}
if (search.CreatedOn != null)
{
if (search.CreatedOn.before != null)
{
DateTimeOffset before = search.CreatedOn.before;
query = query.Where(x => x.CreatedOn <= before);
}
if (search.CreatedOn.after != null)
{
DateTimeOffset after = search.CreatedOn.after;
query = query.Where(x => x.CreatedOn >= after);
}
}
}
var vendors = query.ToSmartTableResult(
param,
x => new
{
Id = x.Id,
Name = x.Name,
Email = x.Email,
IsActive = x.IsActive,
SeoTitle = x.SeoTitle,
CreatedOn = x.CreatedOn
});
return Json(vendors);
}
public async Task<IActionResult> Get()
{
var vendors = await _vendorRepository.Query().Select(x => new
{
Id = x.Id,
Name = x.Name,
Slug = x.SeoTitle
}).ToListAsync();
return Json(vendors);
}
[HttpGet("{id}")]
public async Task<IActionResult> Get(long id)
{
var vendor = await _vendorRepository.Query().Include(x => x.Users).FirstOrDefaultAsync(x => x.Id == id);
if(vendor == null)
{
return NotFound();
}
var model = new VendorForm
{
Id = vendor.Id,
Name = vendor.Name,
Slug = vendor.SeoTitle,
Email = vendor.Email,
Description = vendor.Description,
IsActive = vendor.IsActive,
Managers = vendor.Users.Select(x => new VendorManager { UserId = x.Id, Email = x.Email }).ToList()
};
return Json(model);
}
[HttpPost]
public async Task<IActionResult> Post([FromBody] VendorForm model)
{
if (ModelState.IsValid)
{
var vendor = new Vendor
{
Name = model.Name,
SeoTitle = model.Slug,
Email = model.Email,
Description = model.Description,
IsActive = model.IsActive
};
await _vendorService.Create(vendor);
return CreatedAtAction(nameof(Get), new { id = vendor.Id }, null);
}
return BadRequest(ModelState);
}
[HttpPut("{id}")]
public async Task<IActionResult> Put(long id, [FromBody] VendorForm model)
{
if (ModelState.IsValid)
{
var vendor = _vendorRepository.Query().FirstOrDefault(x => x.Id == id);
vendor.Name = model.Name;
vendor.SeoTitle = model.Slug;
vendor.Email = model.Email;
vendor.Description = model.Description;
vendor.IsActive = model.IsActive;
vendor.UpdatedOn = DateTimeOffset.Now;
await _vendorService.Update(vendor);
return Accepted();
}
return BadRequest(ModelState);
}
[HttpDelete("{id}")]
public async Task<IActionResult> Delete(long id)
{
var vendor = await _vendorRepository.Query().FirstOrDefaultAsync(x => x.Id == id);
if (vendor == null)
{
return NotFound();
}
await _vendorService.Delete(vendor);
return NoContent();
}
}
}
| 32.387879 | 116 | 0.506737 | [
"Apache-2.0"
] | vtkhanh/SimplCommerce | src/Modules/SimplCommerce.Module.Vendors/Controllers/VendorApiController.cs | 5,346 | C# |
using System.Threading.Tasks;
using Abp.Application.Services;
using Abp.Authorization;
using Abp.BackgroundJobs;
using Abp.Runtime.Session;
using ABD.Hangfire.Dto;
using Microsoft.AspNetCore.Hosting;
using MimeKit;
namespace ABD.Hangfire
{
[AbpAuthorize]
public class EmailAppService : ApplicationService, IEmailAppService
{
private readonly IBackgroundJobManager _backgroundJobManager;
private readonly IHostingEnvironment _env;
public EmailAppService(IBackgroundJobManager backgroundJobManager,
IHostingEnvironment env)
{
_backgroundJobManager = backgroundJobManager;
_env = env;
}
public async Task SendEmail(SendEmailInput input)
{
await _backgroundJobManager.EnqueueAsync<SendEmailJob, SendEmailJobArgs>(
new SendEmailJobArgs
{
Subject = input.Subject,
Body = input.Body,
SenderUserId = AbpSession.GetUserId(),
TargetUser = input.TargetUser
});
}
}
}
| 29.410256 | 85 | 0.622493 | [
"MIT"
] | aansadiqul/New | aspnet-core/src/ABD.Application/Hangfire/EmailAppService.cs | 1,149 | C# |
////////////////////////////////////////////////////////////////////////////////
//NUnit tests for "EF Core Provider for LCPI OLE DB"
// IBProvider and Contributors. 04.07.2021.
using System;
using System.Data;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using Microsoft.EntityFrameworkCore;
using NUnit.Framework;
using xdb=lcpi.data.oledb;
namespace EFCore_LcpiOleDb_Tests.General.Work.DBMS.Firebird.V03_0_0.D1.Query.Operators.SET_001.NotEqual.Complete.NullableTimeOnly.NullableTimeOnly{
////////////////////////////////////////////////////////////////////////////////
using T_DATA1 =System.Nullable<System.TimeOnly>;
using T_DATA2 =System.Nullable<System.TimeOnly>;
using T_DATA1_U=System.TimeOnly;
using T_DATA2_U=System.TimeOnly;
////////////////////////////////////////////////////////////////////////////////
//class TestSet_504__param__01__VV
public static class TestSet_504__param__01__VV
{
private const string c_NameOf__TABLE ="DUAL";
private sealed class MyContext:TestBaseDbContext
{
[Table(c_NameOf__TABLE)]
public sealed class TEST_RECORD
{
[Key]
[Column("ID")]
public System.Int32? TEST_ID { get; set; }
};//class TEST_RECORD
//----------------------------------------------------------------------
public DbSet<TEST_RECORD> testTable { get; set; }
//----------------------------------------------------------------------
public MyContext(xdb.OleDbTransaction tr)
:base(tr)
{
}//MyContext
};//class MyContext
//-----------------------------------------------------------------------
[Test]
public static void Test_001__less()
{
using(var cn=LocalCnHelper.CreateCn())
{
cn.Open();
using(var tr=cn.BeginTransaction())
{
//insert new record in external transaction
using(var db=new MyContext(tr))
{
T_DATA1 vv1=new T_DATA1_U(12,14,34).Add(new System.TimeSpan(1000*1233)).Add(new System.TimeSpan(900));
T_DATA2 vv2=new T_DATA2_U(12,14,34).Add(new System.TimeSpan(1000*1234)).Add(new System.TimeSpan(0));
var recs=db.testTable.Where(r => vv1 /*OP{*/ != /*}OP*/ vv2);
int nRecs=0;
foreach(var r in recs)
{
Assert.AreEqual
(0,
nRecs);
++nRecs;
Assert.IsTrue
(r.TEST_ID.HasValue);
Assert.AreEqual
(1,
r.TEST_ID.Value);
}//foreach r
db.CheckTextOfLastExecutedCommand
(new TestSqlTemplate()
.T("SELECT ").N("d","ID").EOL()
.T("FROM ").N(c_NameOf__TABLE).T(" AS ").N("d").EOL()
.T("WHERE ").P_BOOL("__Exec_V_V_0"));
Assert.AreEqual
(1,
nRecs);
}//using db
tr.Commit();
}//using tr
}//using cn
}//Test_001__less
//-----------------------------------------------------------------------
[Test]
public static void Test_002__equal()
{
using(var cn=LocalCnHelper.CreateCn())
{
cn.Open();
using(var tr=cn.BeginTransaction())
{
//insert new record in external transaction
using(var db=new MyContext(tr))
{
T_DATA1 vv1=new T_DATA1_U(12,14,34).Add(new System.TimeSpan(1000*1234)).Add(new System.TimeSpan(0));
T_DATA2 vv2=new T_DATA2_U(12,14,34).Add(new System.TimeSpan(1000*1234)).Add(new System.TimeSpan(100));
var recs=db.testTable.Where(r => vv1 /*OP{*/ != /*}OP*/ vv2);
foreach(var r in recs)
{
TestServices.ThrowSelectedRow();
}//foreach r
db.CheckTextOfLastExecutedCommand
(new TestSqlTemplate()
.T("SELECT ").N("d","ID").EOL()
.T("FROM ").N(c_NameOf__TABLE).T(" AS ").N("d").EOL()
.T("WHERE ").P_BOOL("__Exec_V_V_0"));
}//using db
tr.Commit();
}//using tr
}//using cn
}//Test_002__equal
//-----------------------------------------------------------------------
[Test]
public static void Test_003__greater()
{
using(var cn=LocalCnHelper.CreateCn())
{
cn.Open();
using(var tr=cn.BeginTransaction())
{
//insert new record in external transaction
using(var db=new MyContext(tr))
{
T_DATA1 vv1=new T_DATA1_U(12,14,34).Add(new System.TimeSpan(1000*1235)).Add(new System.TimeSpan(0));
T_DATA2 vv2=new T_DATA2_U(12,14,34).Add(new System.TimeSpan(1000*1234)).Add(new System.TimeSpan(900));
var recs=db.testTable.Where(r => vv1 /*OP{*/ != /*}OP*/ vv2);
int nRecs=0;
foreach(var r in recs)
{
Assert.AreEqual
(0,
nRecs);
++nRecs;
Assert.IsTrue
(r.TEST_ID.HasValue);
Assert.AreEqual
(1,
r.TEST_ID.Value);
}//foreach r
db.CheckTextOfLastExecutedCommand
(new TestSqlTemplate()
.T("SELECT ").N("d","ID").EOL()
.T("FROM ").N(c_NameOf__TABLE).T(" AS ").N("d").EOL()
.T("WHERE ").P_BOOL("__Exec_V_V_0"));
Assert.AreEqual
(1,
nRecs);
}//using db
tr.Commit();
}//using tr
}//using cn
}//Test_003__greater
//-----------------------------------------------------------------------
[Test]
public static void Test_101__less()
{
using(var cn=LocalCnHelper.CreateCn())
{
cn.Open();
using(var tr=cn.BeginTransaction())
{
//insert new record in external transaction
using(var db=new MyContext(tr))
{
T_DATA1 vv1=new T_DATA1_U(12,14,34).Add(new System.TimeSpan(1000*1233)).Add(new System.TimeSpan(900));
T_DATA2 vv2=new T_DATA2_U(12,14,34).Add(new System.TimeSpan(1000*1234)).Add(new System.TimeSpan(0));
var recs=db.testTable.Where(r => !(vv1 /*OP{*/ != /*}OP*/ vv2));
foreach(var r in recs)
{
TestServices.ThrowSelectedRow();
}//foreach r
db.CheckTextOfLastExecutedCommand
(new TestSqlTemplate()
.T("SELECT ").N("d","ID").EOL()
.T("FROM ").N(c_NameOf__TABLE).T(" AS ").N("d").EOL()
.T("WHERE ").P_BOOL("__Exec_V_0"));
}//using db
tr.Commit();
}//using tr
}//using cn
}//Test_101__less
//-----------------------------------------------------------------------
[Test]
public static void Test_102__equal()
{
using(var cn=LocalCnHelper.CreateCn())
{
cn.Open();
using(var tr=cn.BeginTransaction())
{
//insert new record in external transaction
using(var db=new MyContext(tr))
{
T_DATA1 vv1=new T_DATA1_U(12,14,34).Add(new System.TimeSpan(1000*1234)).Add(new System.TimeSpan(0));
T_DATA2 vv2=new T_DATA2_U(12,14,34).Add(new System.TimeSpan(1000*1234)).Add(new System.TimeSpan(100));
var recs=db.testTable.Where(r => !(vv1 /*OP{*/ != /*}OP*/ vv2));
int nRecs=0;
foreach(var r in recs)
{
Assert.AreEqual
(0,
nRecs);
++nRecs;
Assert.IsTrue
(r.TEST_ID.HasValue);
Assert.AreEqual
(1,
r.TEST_ID.Value);
}//foreach r
db.CheckTextOfLastExecutedCommand
(new TestSqlTemplate()
.T("SELECT ").N("d","ID").EOL()
.T("FROM ").N(c_NameOf__TABLE).T(" AS ").N("d").EOL()
.T("WHERE ").P_BOOL("__Exec_V_0"));
Assert.AreEqual
(1,
nRecs);
}//using db
tr.Commit();
}//using tr
}//using cn
}//Test_102__equal
//-----------------------------------------------------------------------
[Test]
public static void Test_103__greater()
{
using(var cn=LocalCnHelper.CreateCn())
{
cn.Open();
using(var tr=cn.BeginTransaction())
{
//insert new record in external transaction
using(var db=new MyContext(tr))
{
T_DATA1 vv1=new T_DATA1_U(12,14,34).Add(new System.TimeSpan(1000*1235)).Add(new System.TimeSpan(0));
T_DATA2 vv2=new T_DATA2_U(12,14,34).Add(new System.TimeSpan(1000*1234)).Add(new System.TimeSpan(900));
var recs=db.testTable.Where(r => !(vv1 /*OP{*/ != /*}OP*/ vv2));
foreach(var r in recs)
{
TestServices.ThrowSelectedRow();
}//foreach r
db.CheckTextOfLastExecutedCommand
(new TestSqlTemplate()
.T("SELECT ").N("d","ID").EOL()
.T("FROM ").N(c_NameOf__TABLE).T(" AS ").N("d").EOL()
.T("WHERE ").P_BOOL("__Exec_V_0"));
}//using db
tr.Commit();
}//using tr
}//using cn
}//Test_103__greater
//-----------------------------------------------------------------------
[Test]
public static void Test_ZA01NV()
{
using(var cn=LocalCnHelper.CreateCn())
{
cn.Open();
using(var tr=cn.BeginTransaction())
{
//insert new record in external transaction
using(var db=new MyContext(tr))
{
object vv1__null_obj=null;
T_DATA2 vv2=new T_DATA2_U(12,14,34).Add(new System.TimeSpan(1000*1234)).Add(new System.TimeSpan(900));
var recs=db.testTable.Where(r => ((T_DATA1)(System.Object)vv1__null_obj) /*OP{*/ != /*}OP*/ vv2);
int nRecs=0;
foreach(var r in recs)
{
Assert.AreEqual
(0,
nRecs);
++nRecs;
Assert.IsTrue
(r.TEST_ID.HasValue);
Assert.AreEqual
(1,
r.TEST_ID.Value);
}//foreach r
db.CheckTextOfLastExecutedCommand
(new TestSqlTemplate()
.T("SELECT ").N("d","ID").EOL()
.T("FROM ").N(c_NameOf__TABLE).T(" AS ").N("d").EOL()
.T("WHERE ").P_BOOL("__Exec_V_V_0"));
Assert.AreEqual
(1,
nRecs);
}//using db
tr.Commit();
}//using tr
}//using cn
}//Test_ZA01NV
//-----------------------------------------------------------------------
[Test]
public static void Test_ZA02VN()
{
using(var cn=LocalCnHelper.CreateCn())
{
cn.Open();
using(var tr=cn.BeginTransaction())
{
//insert new record in external transaction
using(var db=new MyContext(tr))
{
T_DATA1 vv1=new T_DATA1_U(12,14,34).Add(new System.TimeSpan(1000*1234)).Add(new System.TimeSpan(900));
object vv2__null_obj=null;
var recs=db.testTable.Where(r => vv1 /*OP{*/ != /*}OP*/ ((T_DATA2)(System.Object)vv2__null_obj));
int nRecs=0;
foreach(var r in recs)
{
Assert.AreEqual
(0,
nRecs);
++nRecs;
Assert.IsTrue
(r.TEST_ID.HasValue);
Assert.AreEqual
(1,
r.TEST_ID.Value);
}//foreach r
db.CheckTextOfLastExecutedCommand
(new TestSqlTemplate()
.T("SELECT ").N("d","ID").EOL()
.T("FROM ").N(c_NameOf__TABLE).T(" AS ").N("d").EOL()
.T("WHERE ").P_BOOL("__Exec_V_V_0"));
Assert.AreEqual
(1,
nRecs);
}//using db
tr.Commit();
}//using tr
}//using cn
}//Test_ZA02VN
//-----------------------------------------------------------------------
[Test]
public static void Test_ZA03NN()
{
using(var cn=LocalCnHelper.CreateCn())
{
cn.Open();
using(var tr=cn.BeginTransaction())
{
//insert new record in external transaction
using(var db=new MyContext(tr))
{
object vv1__null_obj=null;
object vv2__null_obj=null;
var recs=db.testTable.Where(r => ((T_DATA1)(System.Object)vv1__null_obj) /*OP{*/ != /*}OP*/ ((T_DATA2)(System.Object)vv2__null_obj));
foreach(var r in recs)
{
TestServices.ThrowSelectedRow();
}//foreach r
db.CheckTextOfLastExecutedCommand
(new TestSqlTemplate()
.T("SELECT ").N("d","ID").EOL()
.T("FROM ").N(c_NameOf__TABLE).T(" AS ").N("d").EOL()
.T("WHERE ").P_BOOL("__Exec_V_V_0"));
}//using db
tr.Commit();
}//using tr
}//using cn
}//Test_ZA03NN
//-----------------------------------------------------------------------
[Test]
public static void Test_ZB01NV()
{
using(var cn=LocalCnHelper.CreateCn())
{
cn.Open();
using(var tr=cn.BeginTransaction())
{
//insert new record in external transaction
using(var db=new MyContext(tr))
{
object vv1__null_obj=null;
T_DATA2 vv2=new T_DATA2_U(12,14,34).Add(new System.TimeSpan(1000*1234)).Add(new System.TimeSpan(900));
var recs=db.testTable.Where(r => !(((T_DATA1)(System.Object)vv1__null_obj) /*OP{*/ != /*}OP*/ vv2));
foreach(var r in recs)
{
TestServices.ThrowSelectedRow();
}//foreach r
db.CheckTextOfLastExecutedCommand
(new TestSqlTemplate()
.T("SELECT ").N("d","ID").EOL()
.T("FROM ").N(c_NameOf__TABLE).T(" AS ").N("d").EOL()
.T("WHERE ").P_BOOL("__Exec_V_0"));
}//using db
tr.Commit();
}//using tr
}//using cn
}//Test_ZB01NV
//-----------------------------------------------------------------------
[Test]
public static void Test_ZB02VN()
{
using(var cn=LocalCnHelper.CreateCn())
{
cn.Open();
using(var tr=cn.BeginTransaction())
{
//insert new record in external transaction
using(var db=new MyContext(tr))
{
T_DATA1 vv1=new T_DATA1_U(12,14,34).Add(new System.TimeSpan(1000*1234)).Add(new System.TimeSpan(900));
object vv2__null_obj=null;
var recs=db.testTable.Where(r => !(vv1 /*OP{*/ != /*}OP*/ ((T_DATA2)(System.Object)vv2__null_obj)));
foreach(var r in recs)
{
TestServices.ThrowSelectedRow();
}//foreach r
db.CheckTextOfLastExecutedCommand
(new TestSqlTemplate()
.T("SELECT ").N("d","ID").EOL()
.T("FROM ").N(c_NameOf__TABLE).T(" AS ").N("d").EOL()
.T("WHERE ").P_BOOL("__Exec_V_0"));
}//using db
tr.Commit();
}//using tr
}//using cn
}//Test_ZB02VN
//-----------------------------------------------------------------------
[Test]
public static void Test_ZB03NN()
{
using(var cn=LocalCnHelper.CreateCn())
{
cn.Open();
using(var tr=cn.BeginTransaction())
{
//insert new record in external transaction
using(var db=new MyContext(tr))
{
object vv1__null_obj=null;
object vv2__null_obj=null;
var recs=db.testTable.Where(r => !(((T_DATA1)(System.Object)vv1__null_obj) /*OP{*/ != /*}OP*/ ((T_DATA2)(System.Object)vv2__null_obj)));
int nRecs=0;
foreach(var r in recs)
{
Assert.AreEqual
(0,
nRecs);
++nRecs;
Assert.IsTrue
(r.TEST_ID.HasValue);
Assert.AreEqual
(1,
r.TEST_ID.Value);
}//foreach r
db.CheckTextOfLastExecutedCommand
(new TestSqlTemplate()
.T("SELECT ").N("d","ID").EOL()
.T("FROM ").N(c_NameOf__TABLE).T(" AS ").N("d").EOL()
.T("WHERE ").P_BOOL("__Exec_V_0"));
Assert.AreEqual
(1,
nRecs);
}//using db
tr.Commit();
}//using tr
}//using cn
}//Test_ZB03NN
};//class TestSet_504__param__01__VV
////////////////////////////////////////////////////////////////////////////////
}//namespace EFCore_LcpiOleDb_Tests.General.Work.DBMS.Firebird.V03_0_0.D1.Query.Operators.SET_001.NotEqual.Complete.NullableTimeOnly.NullableTimeOnly
| 25.495652 | 149 | 0.550136 | [
"MIT"
] | ibprovider/Lcpi.EFCore.LcpiOleDb | Tests/General/Source/Work/DBMS/Firebird/V03_0_0/D1/Query/Operators/SET_001/NotEqual/Complete/NullableTimeOnly/NullableTimeOnly/TestSet_504__param__01__VV.cs | 14,662 | C# |
using Harmonic.Buffers;
using System;
using System.Collections.Generic;
using System.Text;
namespace Harmonic.Networking.Amf.Data
{
public interface IExternalizable
{
bool TryDecodeData(Span<byte> buffer, out int consumed);
bool TryEncodeData(ByteBuffer buffer);
}
}
| 19.866667 | 64 | 0.728188 | [
"MIT"
] | CoreDX9/Harmonic | Harmonic/Networking/Amf/Data/IExternalizable.cs | 300 | C# |
/*
* Copyright (c) Contributors, http://opensimulator.org/
* See CONTRIBUTORS.TXT for a full list of copyright holders.
*
* 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 OpenSimulator Project 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 DEVELOPERS ``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 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.Net;
using System.Xml;
using System.Reflection;
using System.Text;
using System.Threading;
using OpenSim.Framework;
using OpenSim.Framework.Capabilities;
using OpenSim.Framework.Client;
using OpenSim.Region.Framework.Interfaces;
using OpenSim.Region.Framework.Scenes;
using OpenSim.Region.Framework.Scenes.Serialization;
using OpenSim.Services.Interfaces;
using GridRegion = OpenSim.Services.Interfaces.GridRegion;
using OpenMetaverse;
using log4net;
using Nini.Config;
using Mono.Addins;
using PermissionMask = OpenSim.Framework.PermissionMask;
namespace OpenSim.Region.CoreModules.Framework.InventoryAccess
{
[Extension(Path = "/OpenSim/RegionModules", NodeName = "RegionModule", Id = "BasicInventoryAccessModule")]
public class BasicInventoryAccessModule : INonSharedRegionModule, IInventoryAccessModule
{
private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
protected bool m_Enabled = false;
protected Scene m_Scene;
protected IUserManagement m_UserManagement;
protected IUserManagement UserManagementModule
{
get
{
if (m_UserManagement == null)
m_UserManagement = m_Scene.RequestModuleInterface<IUserManagement>();
return m_UserManagement;
}
}
public bool CoalesceMultipleObjectsToInventory { get; set; }
#region INonSharedRegionModule
public Type ReplaceableInterface
{
get { return null; }
}
public virtual string Name
{
get { return "BasicInventoryAccessModule"; }
}
public virtual void Initialise(IConfigSource source)
{
IConfig moduleConfig = source.Configs["Modules"];
if (moduleConfig != null)
{
string name = moduleConfig.GetString("InventoryAccessModule", "");
if (name == Name)
{
m_Enabled = true;
InitialiseCommon(source);
m_log.InfoFormat("[INVENTORY ACCESS MODULE]: {0} enabled.", Name);
}
}
}
/// <summary>
/// Common module config for both this and descendant classes.
/// </summary>
/// <param name="source"></param>
protected virtual void InitialiseCommon(IConfigSource source)
{
IConfig inventoryConfig = source.Configs["Inventory"];
if (inventoryConfig != null)
CoalesceMultipleObjectsToInventory
= inventoryConfig.GetBoolean("CoalesceMultipleObjectsToInventory", true);
else
CoalesceMultipleObjectsToInventory = true;
}
public virtual void PostInitialise()
{
}
public virtual void AddRegion(Scene scene)
{
if (!m_Enabled)
return;
m_Scene = scene;
scene.RegisterModuleInterface<IInventoryAccessModule>(this);
scene.EventManager.OnNewClient += OnNewClient;
}
protected virtual void OnNewClient(IClientAPI client)
{
client.OnCreateNewInventoryItem += CreateNewInventoryItem;
}
public virtual void Close()
{
if (!m_Enabled)
return;
}
public virtual void RemoveRegion(Scene scene)
{
if (!m_Enabled)
return;
m_Scene = null;
}
public virtual void RegionLoaded(Scene scene)
{
if (!m_Enabled)
return;
}
#endregion
#region Inventory Access
/// <summary>
/// Create a new inventory item. Called when the client creates a new item directly within their
/// inventory (e.g. by selecting a context inventory menu option).
/// </summary>
/// <param name="remoteClient"></param>
/// <param name="transactionID"></param>
/// <param name="folderID"></param>
/// <param name="callbackID"></param>
/// <param name="description"></param>
/// <param name="name"></param>
/// <param name="invType"></param>
/// <param name="type"></param>
/// <param name="wearableType"></param>
/// <param name="nextOwnerMask"></param>
public void CreateNewInventoryItem(IClientAPI remoteClient, UUID transactionID, UUID folderID,
uint callbackID, string description, string name, sbyte invType,
sbyte assetType,
byte wearableType, uint nextOwnerMask, int creationDate)
{
m_log.DebugFormat("[INVENTORY ACCESS MODULE]: Received request to create inventory item {0} in folder {1}, transactionID {2}", name,
folderID, transactionID);
if (!m_Scene.Permissions.CanCreateUserInventory(invType, remoteClient.AgentId))
return;
InventoryFolderBase f = new InventoryFolderBase(folderID, remoteClient.AgentId);
InventoryFolderBase folder = m_Scene.InventoryService.GetFolder(f);
if (folder == null || folder.Owner != remoteClient.AgentId)
return;
if (transactionID != UUID.Zero)
{
IAgentAssetTransactions agentTransactions = m_Scene.AgentTransactionsModule;
if (agentTransactions != null)
{
if (agentTransactions.HandleItemCreationFromTransaction(
remoteClient, transactionID, folderID, callbackID, description,
name, invType, assetType, wearableType, nextOwnerMask))
return;
}
}
ScenePresence presence;
if (m_Scene.TryGetScenePresence(remoteClient.AgentId, out presence))
{
byte[] data = null;
if (invType == (sbyte)InventoryType.Landmark && presence != null)
{
string suffix = string.Empty, prefix = string.Empty;
string strdata = GenerateLandmark(presence, out prefix, out suffix);
data = Encoding.ASCII.GetBytes(strdata);
name = prefix + name;
description += suffix;
}
AssetBase asset = m_Scene.CreateAsset(name, description, assetType, data, remoteClient.AgentId);
m_Scene.AssetService.Store(asset);
m_Scene.CreateNewInventoryItem(
remoteClient, remoteClient.AgentId.ToString(), string.Empty, folderID,
name, description, 0, callbackID, asset.FullID, asset.Type, invType, nextOwnerMask, creationDate);
}
else
{
m_log.ErrorFormat(
"[INVENTORY ACCESS MODULE]: ScenePresence for agent uuid {0} unexpectedly not found in CreateNewInventoryItem",
remoteClient.AgentId);
}
}
protected virtual string GenerateLandmark(ScenePresence presence, out string prefix, out string suffix)
{
prefix = string.Empty;
suffix = string.Empty;
Vector3 pos = presence.AbsolutePosition;
return String.Format("Landmark version 2\nregion_id {0}\nlocal_pos {1} {2} {3}\nregion_handle {4}\n",
presence.Scene.RegionInfo.RegionID,
pos.X, pos.Y, pos.Z,
presence.RegionHandle);
}
/// <summary>
/// Capability originating call to update the asset of an item in an agent's inventory
/// </summary>
/// <param name="remoteClient"></param>
/// <param name="itemID"></param>
/// <param name="data"></param>
/// <returns></returns>
public virtual UUID CapsUpdateInventoryItemAsset(IClientAPI remoteClient, UUID itemID, byte[] data)
{
InventoryItemBase item = new InventoryItemBase(itemID, remoteClient.AgentId);
item = m_Scene.InventoryService.GetItem(item);
if (item.Owner != remoteClient.AgentId)
return UUID.Zero;
if (item != null)
{
if ((InventoryType)item.InvType == InventoryType.Notecard)
{
if (!m_Scene.Permissions.CanEditNotecard(itemID, UUID.Zero, remoteClient.AgentId))
{
remoteClient.SendAgentAlertMessage("Insufficient permissions to edit notecard", false);
return UUID.Zero;
}
remoteClient.SendAlertMessage("Notecard saved");
}
else if ((InventoryType)item.InvType == InventoryType.LSL)
{
if (!m_Scene.Permissions.CanEditScript(itemID, UUID.Zero, remoteClient.AgentId))
{
remoteClient.SendAgentAlertMessage("Insufficient permissions to edit script", false);
return UUID.Zero;
}
remoteClient.SendAlertMessage("Script saved");
}
else if ((CustomInventoryType)item.InvType == CustomInventoryType.AnimationSet)
{
AnimationSet animSet = new AnimationSet(data);
if (!animSet.Validate(x => {
int perms = m_Scene.InventoryService.GetAssetPermissions(remoteClient.AgentId, x);
int required = (int)(PermissionMask.Transfer | PermissionMask.Copy);
if ((perms & required) != required)
return false;
return true;
}))
{
data = animSet.ToBytes();
}
}
AssetBase asset =
CreateAsset(item.Name, item.Description, (sbyte)item.AssetType, data, remoteClient.AgentId.ToString());
item.AssetID = asset.FullID;
m_Scene.AssetService.Store(asset);
m_Scene.InventoryService.UpdateItem(item);
// remoteClient.SendInventoryItemCreateUpdate(item);
return (asset.FullID);
}
else
{
m_log.ErrorFormat(
"[INVENTORY ACCESS MODULE]: Could not find item {0} for caps inventory update",
itemID);
}
return UUID.Zero;
}
public virtual bool UpdateInventoryItemAsset(UUID ownerID, InventoryItemBase item, AssetBase asset)
{
if (item != null && item.Owner == ownerID && asset != null)
{
// m_log.DebugFormat(
// "[INVENTORY ACCESS MODULE]: Updating item {0} {1} with new asset {2}",
// item.Name, item.ID, asset.ID);
item.AssetID = asset.FullID;
item.Description = asset.Description;
item.Name = asset.Name;
item.AssetType = asset.Type;
item.InvType = (int)InventoryType.Object;
m_Scene.AssetService.Store(asset);
m_Scene.InventoryService.UpdateItem(item);
return true;
}
else
{
m_log.ErrorFormat("[INVENTORY ACCESS MODULE]: Given invalid item for inventory update: {0}",
(item == null || asset == null? "null item or asset" : "wrong owner"));
return false;
}
}
public virtual List<InventoryItemBase> CopyToInventory(
DeRezAction action, UUID folderID,
List<SceneObjectGroup> objectGroups, IClientAPI remoteClient, bool asAttachment)
{
List<InventoryItemBase> copiedItems = new List<InventoryItemBase>();
Dictionary<UUID, List<SceneObjectGroup>> bundlesToCopy = new Dictionary<UUID, List<SceneObjectGroup>>();
if (CoalesceMultipleObjectsToInventory)
{
// The following code groups the SOG's by owner. No objects
// belonging to different people can be coalesced, for obvious
// reasons.
foreach (SceneObjectGroup g in objectGroups)
{
if (!bundlesToCopy.ContainsKey(g.OwnerID))
bundlesToCopy[g.OwnerID] = new List<SceneObjectGroup>();
bundlesToCopy[g.OwnerID].Add(g);
}
}
else
{
// If we don't want to coalesce then put every object in its own bundle.
foreach (SceneObjectGroup g in objectGroups)
{
List<SceneObjectGroup> bundle = new List<SceneObjectGroup>();
bundle.Add(g);
bundlesToCopy[g.UUID] = bundle;
}
}
// m_log.DebugFormat(
// "[INVENTORY ACCESS MODULE]: Copying {0} object bundles to folder {1} action {2} for {3}",
// bundlesToCopy.Count, folderID, action, remoteClient.Name);
// Each iteration is really a separate asset being created,
// with distinct destinations as well.
foreach (List<SceneObjectGroup> bundle in bundlesToCopy.Values)
copiedItems.Add(CopyBundleToInventory(action, folderID, bundle, remoteClient, asAttachment));
return copiedItems;
}
/// <summary>
/// Copy a bundle of objects to inventory. If there is only one object, then this will create an object
/// item. If there are multiple objects then these will be saved as a single coalesced item.
/// </summary>
/// <param name="action"></param>
/// <param name="folderID"></param>
/// <param name="objlist"></param>
/// <param name="remoteClient"></param>
/// <param name="asAttachment">Should be true if the bundle is being copied as an attachment. This prevents
/// attempted serialization of any script state which would abort any operating scripts.</param>
/// <returns>The inventory item created by the copy</returns>
protected InventoryItemBase CopyBundleToInventory(
DeRezAction action, UUID folderID, List<SceneObjectGroup> objlist, IClientAPI remoteClient,
bool asAttachment)
{
CoalescedSceneObjects coa = new CoalescedSceneObjects(UUID.Zero);
Dictionary<UUID, Vector3> originalPositions = new Dictionary<UUID, Vector3>();
Dictionary<UUID, Quaternion> originalRotations = new Dictionary<UUID, Quaternion>();
// this possible is not needed if keyframes are saved
Dictionary<UUID, KeyframeMotion> originalKeyframes = new Dictionary<UUID, KeyframeMotion>();
foreach (SceneObjectGroup objectGroup in objlist)
{
if (objectGroup.RootPart.KeyframeMotion != null)
{
objectGroup.RootPart.KeyframeMotion.Suspend();
}
objectGroup.RootPart.SetForce(Vector3.Zero);
objectGroup.RootPart.SetAngularImpulse(Vector3.Zero, false);
originalKeyframes[objectGroup.UUID] = objectGroup.RootPart.KeyframeMotion;
objectGroup.RootPart.KeyframeMotion = null;
Vector3 inventoryStoredPosition = objectGroup.AbsolutePosition;
originalPositions[objectGroup.UUID] = inventoryStoredPosition;
Quaternion inventoryStoredRotation = objectGroup.GroupRotation;
originalRotations[objectGroup.UUID] = inventoryStoredRotation;
// Restore attachment data after trip through the sim
if (objectGroup.RootPart.AttachPoint > 0)
{
inventoryStoredPosition = objectGroup.RootPart.AttachedPos;
inventoryStoredRotation = objectGroup.RootPart.AttachRotation;
}
// Trees could be attached and it's been done, but it makes
// no sense. State must be preserved because it's the tree type
if (objectGroup.RootPart.Shape.PCode != (byte) PCode.Tree &&
objectGroup.RootPart.Shape.PCode != (byte) PCode.NewTree)
{
objectGroup.RootPart.Shape.State = objectGroup.RootPart.AttachPoint;
if (objectGroup.RootPart.AttachPoint > 0)
objectGroup.RootPart.Shape.LastAttachPoint = objectGroup.RootPart.AttachPoint;
}
objectGroup.AbsolutePosition = inventoryStoredPosition;
objectGroup.RootPart.RotationOffset = inventoryStoredRotation;
// Make sure all bits but the ones we want are clear
// on take.
// This will be applied to the current perms, so
// it will do what we want.
objectGroup.RootPart.NextOwnerMask &=
((uint)PermissionMask.Copy |
(uint)PermissionMask.Transfer |
(uint)PermissionMask.Modify |
(uint)PermissionMask.Export);
objectGroup.RootPart.NextOwnerMask |=
(uint)PermissionMask.Move;
coa.Add(objectGroup);
}
string itemXml;
// If we're being called from a script, then trying to serialize that same script's state will not complete
// in any reasonable time period. Therefore, we'll avoid it. The worst that can happen is that if
// the client/server crashes rather than logging out normally, the attachment's scripts will resume
// without state on relog. Arguably, this is what we want anyway.
if (objlist.Count > 1)
itemXml = CoalescedSceneObjectsSerializer.ToXml(coa, !asAttachment);
else
itemXml = SceneObjectSerializer.ToOriginalXmlFormat(objlist[0], !asAttachment);
// Restore the position of each group now that it has been stored to inventory.
foreach (SceneObjectGroup objectGroup in objlist)
{
objectGroup.AbsolutePosition = originalPositions[objectGroup.UUID];
objectGroup.RootPart.RotationOffset = originalRotations[objectGroup.UUID];
objectGroup.RootPart.KeyframeMotion = originalKeyframes[objectGroup.UUID];
if (objectGroup.RootPart.KeyframeMotion != null)
objectGroup.RootPart.KeyframeMotion.Resume();
}
InventoryItemBase item = CreateItemForObject(action, remoteClient, objlist[0], folderID);
// m_log.DebugFormat(
// "[INVENTORY ACCESS MODULE]: Created item is {0}",
// item != null ? item.ID.ToString() : "NULL");
if (item == null)
return null;
item.CreatorId = objlist[0].RootPart.CreatorID.ToString();
item.CreatorData = objlist[0].RootPart.CreatorData;
if (objlist.Count > 1)
{
item.Flags = (uint)InventoryItemFlags.ObjectHasMultipleItems;
// If the objects have different creators then don't specify a creator at all
foreach (SceneObjectGroup objectGroup in objlist)
{
if ((objectGroup.RootPart.CreatorID.ToString() != item.CreatorId)
|| (objectGroup.RootPart.CreatorData.ToString() != item.CreatorData))
{
item.CreatorId = UUID.Zero.ToString();
item.CreatorData = string.Empty;
break;
}
}
}
else
{
item.SaleType = objlist[0].RootPart.ObjectSaleType;
item.SalePrice = objlist[0].RootPart.SalePrice;
}
AssetBase asset = CreateAsset(
objlist[0].GetPartName(objlist[0].RootPart.LocalId),
objlist[0].GetPartDescription(objlist[0].RootPart.LocalId),
(sbyte)AssetType.Object,
Utils.StringToBytes(itemXml),
objlist[0].OwnerID.ToString());
m_Scene.AssetService.Store(asset);
item.AssetID = asset.FullID;
if (DeRezAction.SaveToExistingUserInventoryItem == action)
{
m_Scene.InventoryService.UpdateItem(item);
}
else
{
item.CreationDate = Util.UnixTimeSinceEpoch();
item.Description = asset.Description;
item.Name = asset.Name;
item.AssetType = asset.Type;
//preserve perms on return
if(DeRezAction.Return == action)
AddPermissions(item, objlist[0], objlist, null);
else
AddPermissions(item, objlist[0], objlist, remoteClient);
m_Scene.AddInventoryItem(item);
if (remoteClient != null && item.Owner == remoteClient.AgentId)
{
remoteClient.SendInventoryItemCreateUpdate(item, 0);
}
else
{
ScenePresence notifyUser = m_Scene.GetScenePresence(item.Owner);
if (notifyUser != null)
{
notifyUser.ControllingClient.SendInventoryItemCreateUpdate(item, 0);
}
}
}
// This is a hook to do some per-asset post-processing for subclasses that need that
if (remoteClient != null)
ExportAsset(remoteClient.AgentId, asset.FullID);
return item;
}
protected virtual void ExportAsset(UUID agentID, UUID assetID)
{
// nothing to do here
}
/// <summary>
/// Add relevant permissions for an object to the item.
/// </summary>
/// <param name="item"></param>
/// <param name="so"></param>
/// <param name="objsForEffectivePermissions"></param>
/// <param name="remoteClient"></param>
/// <returns></returns>
protected InventoryItemBase AddPermissions(
InventoryItemBase item, SceneObjectGroup so, List<SceneObjectGroup> objsForEffectivePermissions,
IClientAPI remoteClient)
{
uint effectivePerms = (uint)(PermissionMask.Copy | PermissionMask.Transfer | PermissionMask.Modify | PermissionMask.Move | PermissionMask.Export) | 7;
uint allObjectsNextOwnerPerms = 0x7fffffff;
// For the porposes of inventory, an object is modify if the prims
// are modify. This allows renaming an object that contains no
// mod items.
foreach (SceneObjectGroup grp in objsForEffectivePermissions)
{
uint groupPerms = grp.GetEffectivePermissions(true);
if ((grp.RootPart.BaseMask & (uint)PermissionMask.Modify) != 0)
groupPerms |= (uint)PermissionMask.Modify;
effectivePerms &= groupPerms;
}
effectivePerms |= (uint)PermissionMask.Move;
//PermissionsUtil.LogPermissions(item.Name, "Before AddPermissions", item.BasePermissions, item.CurrentPermissions, item.NextPermissions);
if (remoteClient != null && (remoteClient.AgentId != so.RootPart.OwnerID) && m_Scene.Permissions.PropagatePermissions())
{
// Changing ownership, so apply the "Next Owner" permissions to all of the
// inventory item's permissions.
uint perms = effectivePerms;
PermissionsUtil.ApplyFoldedPermissions(effectivePerms, ref perms);
item.BasePermissions = perms & so.RootPart.NextOwnerMask;
item.CurrentPermissions = item.BasePermissions;
item.NextPermissions = perms & so.RootPart.NextOwnerMask;
item.EveryOnePermissions = so.RootPart.EveryoneMask & so.RootPart.NextOwnerMask;
item.GroupPermissions = so.RootPart.GroupMask & so.RootPart.NextOwnerMask;
// apply next owner perms on rez
item.CurrentPermissions |= SceneObjectGroup.SLAM;
}
else
{
// Not changing ownership.
// In this case we apply the permissions in the object's items ONLY to the inventory
// item's "Next Owner" permissions, but NOT to its "Current", "Base", etc. permissions.
// E.g., if the object contains a No-Transfer item then the item's "Next Owner"
// permissions are also No-Transfer.
PermissionsUtil.ApplyFoldedPermissions(effectivePerms, ref allObjectsNextOwnerPerms);
item.BasePermissions = effectivePerms;
item.CurrentPermissions = effectivePerms;
item.NextPermissions = so.RootPart.NextOwnerMask & effectivePerms;
item.EveryOnePermissions = so.RootPart.EveryoneMask & effectivePerms;
item.GroupPermissions = so.RootPart.GroupMask & effectivePerms;
item.CurrentPermissions &=
((uint)PermissionMask.Copy |
(uint)PermissionMask.Transfer |
(uint)PermissionMask.Modify |
(uint)PermissionMask.Move |
(uint)PermissionMask.Export |
7); // Preserve folded permissions
}
//PermissionsUtil.LogPermissions(item.Name, "After AddPermissions", item.BasePermissions, item.CurrentPermissions, item.NextPermissions);
return item;
}
/// <summary>
/// Create an item using details for the given scene object.
/// </summary>
/// <param name="action"></param>
/// <param name="remoteClient"></param>
/// <param name="so"></param>
/// <param name="folderID"></param>
/// <returns></returns>
protected InventoryItemBase CreateItemForObject(
DeRezAction action, IClientAPI remoteClient, SceneObjectGroup so, UUID folderID)
{
// m_log.DebugFormat(
// "[BASIC INVENTORY ACCESS MODULE]: Creating item for object {0} {1} for folder {2}, action {3}",
// so.Name, so.UUID, folderID, action);
//
// Get the user info of the item destination
//
UUID userID = UUID.Zero;
if (action == DeRezAction.Take || action == DeRezAction.TakeCopy ||
action == DeRezAction.SaveToExistingUserInventoryItem)
{
// Take or take copy require a taker
// Saving changes requires a local user
//
if (remoteClient == null)
return null;
userID = remoteClient.AgentId;
// m_log.DebugFormat(
// "[INVENTORY ACCESS MODULE]: Target of {0} in CreateItemForObject() is {1} {2}",
// action, remoteClient.Name, userID);
}
else if (so.RootPart.OwnerID == so.RootPart.GroupID)
{
// Group owned objects go to the last owner before the object was transferred.
userID = so.RootPart.LastOwnerID;
}
else
{
// Other returns / deletes go to the object owner
//
userID = so.RootPart.OwnerID;
// m_log.DebugFormat(
// "[INVENTORY ACCESS MODULE]: Target of {0} in CreateItemForObject() is object owner {1}",
// action, userID);
}
if (userID == UUID.Zero) // Can't proceed
{
return null;
}
// If we're returning someone's item, it goes back to the
// owner's Lost And Found folder.
// Delete is treated like return in this case
// Deleting your own items makes them go to trash
//
InventoryFolderBase folder = null;
InventoryItemBase item = null;
if (DeRezAction.SaveToExistingUserInventoryItem == action)
{
item = new InventoryItemBase(so.RootPart.FromUserInventoryItemID, userID);
item = m_Scene.InventoryService.GetItem(item);
//item = userInfo.RootFolder.FindItem(
// objectGroup.RootPart.FromUserInventoryItemID);
if (null == item)
{
m_log.DebugFormat(
"[INVENTORY ACCESS MODULE]: Object {0} {1} scheduled for save to inventory has already been deleted.",
so.Name, so.UUID);
return null;
}
}
else
{
// Folder magic
//
if (action == DeRezAction.Delete)
{
// Deleting someone else's item
//
if (remoteClient == null ||
so.OwnerID != remoteClient.AgentId)
{
folder = m_Scene.InventoryService.GetFolderForType(userID, FolderType.LostAndFound);
}
else
{
folder = m_Scene.InventoryService.GetFolderForType(userID, FolderType.Trash);
}
}
else if (action == DeRezAction.Return)
{
// Dump to lost + found unconditionally
//
folder = m_Scene.InventoryService.GetFolderForType(userID, FolderType.LostAndFound);
}
if (folderID == UUID.Zero && folder == null)
{
if (action == DeRezAction.Delete)
{
// Deletes go to trash by default
//
folder = m_Scene.InventoryService.GetFolderForType(userID, FolderType.Trash);
}
else
{
if (remoteClient == null || so.RootPart.OwnerID != remoteClient.AgentId)
{
// Taking copy of another person's item. Take to
// Objects folder.
folder = m_Scene.InventoryService.GetFolderForType(userID, FolderType.Object);
so.FromFolderID = UUID.Zero;
}
else
{
// Catch all. Use lost & found
//
folder = m_Scene.InventoryService.GetFolderForType(userID, FolderType.LostAndFound);
}
}
}
// Override and put into where it came from, if it came
// from anywhere in inventory and the owner is taking it back.
//
if (action == DeRezAction.Take || action == DeRezAction.TakeCopy)
{
if (so.FromFolderID != UUID.Zero && so.RootPart.OwnerID == remoteClient.AgentId)
{
InventoryFolderBase f = new InventoryFolderBase(so.FromFolderID, userID);
if (f != null)
folder = m_Scene.InventoryService.GetFolder(f);
if(folder.Type == 14 || folder.Type == 16)
{
// folder.Type = 6;
folder = m_Scene.InventoryService.GetFolderForType(userID, FolderType.Object);
}
}
}
if (folder == null) // None of the above
{
folder = new InventoryFolderBase(folderID);
if (folder == null) // Nowhere to put it
{
return null;
}
}
item = new InventoryItemBase();
item.ID = UUID.Random();
item.InvType = (int)InventoryType.Object;
item.Folder = folder.ID;
item.Owner = userID;
}
return item;
}
public virtual SceneObjectGroup RezObject(
IClientAPI remoteClient, UUID itemID, Vector3 RayEnd, Vector3 RayStart,
UUID RayTargetID, byte BypassRayCast, bool RayEndIsIntersection,
bool RezSelected, bool RemoveItem, UUID fromTaskID, bool attachment)
{
// m_log.DebugFormat("[INVENTORY ACCESS MODULE]: RezObject for {0}, item {1}", remoteClient.Name, itemID);
InventoryItemBase item = new InventoryItemBase(itemID, remoteClient.AgentId);
item = m_Scene.InventoryService.GetItem(item);
if (item == null)
{
return null;
}
item.Owner = remoteClient.AgentId;
return RezObject(
remoteClient, item, item.AssetID,
RayEnd, RayStart, RayTargetID, BypassRayCast, RayEndIsIntersection,
RezSelected, RemoveItem, fromTaskID, attachment);
}
public virtual SceneObjectGroup RezObject(
IClientAPI remoteClient, InventoryItemBase item, UUID assetID, Vector3 RayEnd, Vector3 RayStart,
UUID RayTargetID, byte BypassRayCast, bool RayEndIsIntersection,
bool RezSelected, bool RemoveItem, UUID fromTaskID, bool attachment)
{
AssetBase rezAsset = m_Scene.AssetService.Get(assetID.ToString());
if (rezAsset == null)
{
if (item != null)
{
m_log.WarnFormat(
"[InventoryAccessModule]: Could not find asset {0} for item {1} {2} for {3} in RezObject()",
assetID, item.Name, item.ID, remoteClient.Name);
remoteClient.SendAgentAlertMessage(string.Format("Unable to rez: could not find asset {0} for item {1}.", assetID, item.Name), false);
}
else
{
m_log.WarnFormat(
"[INVENTORY ACCESS MODULE]: Could not find asset {0} for {1} in RezObject()",
assetID, remoteClient.Name);
remoteClient.SendAgentAlertMessage(string.Format("Unable to rez: could not find asset {0}.", assetID), false);
}
return null;
}
SceneObjectGroup group = null;
List<SceneObjectGroup> objlist;
List<Vector3> veclist;
Vector3 bbox;
float offsetHeight;
byte bRayEndIsIntersection = (byte)(RayEndIsIntersection ? 1 : 0);
Vector3 pos;
bool single
= m_Scene.GetObjectsToRez(
rezAsset.Data, attachment, out objlist, out veclist, out bbox, out offsetHeight);
if (single)
{
pos = m_Scene.GetNewRezLocation(
RayStart, RayEnd, RayTargetID, Quaternion.Identity,
BypassRayCast, bRayEndIsIntersection, true, bbox, false);
pos.Z += offsetHeight;
}
else
{
pos = m_Scene.GetNewRezLocation(RayStart, RayEnd,
RayTargetID, Quaternion.Identity,
BypassRayCast, bRayEndIsIntersection, true,
bbox, false);
pos -= bbox / 2;
}
int primcount = 0;
foreach (SceneObjectGroup g in objlist)
primcount += g.PrimCount;
if (!m_Scene.Permissions.CanRezObject(
primcount, remoteClient.AgentId, pos)
&& !attachment)
{
// The client operates in no fail mode. It will
// have already removed the item from the folder
// if it's no copy.
// Put it back if it's not an attachment
//
if (item != null)
{
if (((item.CurrentPermissions & (uint)PermissionMask.Copy) == 0) && (!attachment))
remoteClient.SendBulkUpdateInventory(item);
}
return null;
}
if (item != null && !DoPreRezWhenFromItem(remoteClient, item, objlist, pos, veclist, attachment))
return null;
for (int i = 0; i < objlist.Count; i++)
{
group = objlist[i];
SceneObjectPart rootPart = group.RootPart;
// m_log.DebugFormat(
// "[INVENTORY ACCESS MODULE]: Preparing to rez {0} {1} {2} ownermask={3:X} nextownermask={4:X} groupmask={5:X} everyonemask={6:X} for {7}",
// group.Name, group.LocalId, group.UUID,
// group.RootPart.OwnerMask, group.RootPart.NextOwnerMask, group.RootPart.GroupMask, group.RootPart.EveryoneMask,
// remoteClient.Name);
// Vector3 storedPosition = group.AbsolutePosition;
if (group.UUID == UUID.Zero)
{
m_log.Debug("[INVENTORY ACCESS MODULE]: Object has UUID.Zero! Position 3");
}
// if this was previously an attachment and is now being rezzed,
// save the old attachment info.
if (group.IsAttachment == false && group.RootPart.Shape.State != 0)
{
group.RootPart.AttachedPos = group.AbsolutePosition;
group.RootPart.Shape.LastAttachPoint = (byte)group.AttachmentPoint;
}
if (item == null)
{
// Change ownership. Normally this is done in DoPreRezWhenFromItem(), but in this case we must do it here.
foreach (SceneObjectPart part in group.Parts)
{
// Make the rezzer the owner, as this is not necessarily set correctly in the serialized asset.
part.LastOwnerID = part.OwnerID;
part.OwnerID = remoteClient.AgentId;
}
}
group.ResetIDs();
if (!attachment)
{
// If it's rezzed in world, select it. Much easier to
// find small items.
//
foreach (SceneObjectPart part in group.Parts)
{
part.CreateSelected = true;
}
if (rootPart.Shape.PCode == (byte)PCode.Prim)
group.ClearPartAttachmentData();
}
else
{
group.IsAttachment = true;
}
// If we're rezzing an attachment then don't ask
// AddNewSceneObject() to update the client since
// we'll be doing that later on. Scheduling more than
// one full update during the attachment
// process causes some clients to fail to display the
// attachment properly.
m_Scene.AddNewSceneObject(group, true, false);
if (!attachment)
group.AbsolutePosition = pos + veclist[i];
group.SetGroup(remoteClient.ActiveGroupId, remoteClient);
if (!attachment)
{
// Fire on_rez
group.CreateScriptInstances(0, true, m_Scene.DefaultScriptEngine, 1);
rootPart.ParentGroup.ResumeScripts();
group.ScheduleGroupForFullUpdate();
}
// m_log.DebugFormat(
// "[INVENTORY ACCESS MODULE]: Rezzed {0} {1} {2} ownermask={3:X} nextownermask={4:X} groupmask={5:X} everyonemask={6:X} for {7}",
// group.Name, group.LocalId, group.UUID,
// group.RootPart.OwnerMask, group.RootPart.NextOwnerMask, group.RootPart.GroupMask, group.RootPart.EveryoneMask,
// remoteClient.Name);
}
// group.SetGroup(remoteClient.ActiveGroupId, remoteClient);
if (item != null)
DoPostRezWhenFromItem(item, attachment);
return group;
}
/// <summary>
/// Do pre-rez processing when the object comes from an item.
/// </summary>
/// <param name="remoteClient"></param>
/// <param name="item"></param>
/// <param name="objlist"></param>
/// <param name="pos"></param>
/// <param name="veclist">
/// List of vector position adjustments for a coalesced objects. For ordinary objects
/// this list will contain just Vector3.Zero. The order of adjustments must match the order of objlist
/// </param>
/// <param name="isAttachment"></param>
/// <returns>true if we can processed with rezzing, false if we need to abort</returns>
private bool DoPreRezWhenFromItem(
IClientAPI remoteClient, InventoryItemBase item, List<SceneObjectGroup> objlist,
Vector3 pos, List<Vector3> veclist, bool isAttachment)
{
UUID fromUserInventoryItemId = UUID.Zero;
// If we have permission to copy then link the rezzed object back to the user inventory
// item that it came from. This allows us to enable 'save object to inventory'
if (!m_Scene.Permissions.BypassPermissions())
{
if ((item.CurrentPermissions & (uint)PermissionMask.Copy)
== (uint)PermissionMask.Copy && (item.Flags & (uint)InventoryItemFlags.ObjectHasMultipleItems) == 0)
{
fromUserInventoryItemId = item.ID;
}
}
else
{
if ((item.Flags & (uint)InventoryItemFlags.ObjectHasMultipleItems) == 0)
{
// Brave new fullperm world
fromUserInventoryItemId = item.ID;
}
}
for (int i = 0; i < objlist.Count; i++)
{
SceneObjectGroup g = objlist[i];
if (!m_Scene.Permissions.CanRezObject(
g.PrimCount, remoteClient.AgentId, pos + veclist[i])
&& !isAttachment)
{
// The client operates in no fail mode. It will
// have already removed the item from the folder
// if it's no copy.
// Put it back if it's not an attachment
//
if (((item.CurrentPermissions & (uint)PermissionMask.Copy) == 0) && (!isAttachment))
remoteClient.SendBulkUpdateInventory(item);
ILandObject land = m_Scene.LandChannel.GetLandObject(pos.X, pos.Y);
remoteClient.SendAlertMessage(string.Format(
"Can't rez object '{0}' at <{1:F3}, {2:F3}, {3:F3}> on parcel '{4}' in region {5}.",
item.Name, pos.X, pos.Y, pos.Z, land != null ? land.LandData.Name : "Unknown", m_Scene.Name));
return false;
}
}
for (int i = 0; i < objlist.Count; i++)
{
SceneObjectGroup so = objlist[i];
SceneObjectPart rootPart = so.RootPart;
// Since renaming the item in the inventory does not
// affect the name stored in the serialization, transfer
// the correct name from the inventory to the
// object itself before we rez.
//
// Only do these for the first object if we are rezzing a coalescence.
// nahh dont mess with coalescence objects,
// the name in inventory can be change for inventory purpuses only
if (objlist.Count == 1)
{
rootPart.Name = item.Name;
rootPart.Description = item.Description;
}
if ((item.Flags & (uint)InventoryItemFlags.ObjectSlamSale) != 0)
{
rootPart.ObjectSaleType = item.SaleType;
rootPart.SalePrice = item.SalePrice;
}
so.FromFolderID = item.Folder;
// m_log.DebugFormat(
// "[INVENTORY ACCESS MODULE]: rootPart.OwnedID {0}, item.Owner {1}, item.CurrentPermissions {2:X}",
// rootPart.OwnerID, item.Owner, item.CurrentPermissions);
if ((rootPart.OwnerID != item.Owner) ||
(item.CurrentPermissions & 16) != 0 ||
(item.Flags & (uint)InventoryItemFlags.ObjectSlamPerm) != 0)
{
//Need to kill the for sale here
rootPart.ObjectSaleType = 0;
rootPart.SalePrice = 10;
if (m_Scene.Permissions.PropagatePermissions())
{
foreach (SceneObjectPart part in so.Parts)
{
part.GroupMask = 0; // DO NOT propagate here
part.LastOwnerID = part.OwnerID;
part.OwnerID = item.Owner;
part.Inventory.ChangeInventoryOwner(item.Owner);
}
so.ApplyNextOwnerPermissions();
// In case the user has changed flags on a received item
// we have to apply those changes after the slam. Else we
// get a net loss of permissions
foreach (SceneObjectPart part in so.Parts)
{
if ((item.Flags & (uint)InventoryItemFlags.ObjectHasMultipleItems) == 0)
{
if ((item.Flags & (uint)InventoryItemFlags.ObjectOverwriteEveryone) != 0)
part.EveryoneMask = item.EveryOnePermissions & part.BaseMask;
if ((item.Flags & (uint)InventoryItemFlags.ObjectOverwriteNextOwner) != 0)
part.NextOwnerMask = item.NextPermissions & part.BaseMask;
}
}
}
}
else
{
foreach (SceneObjectPart part in so.Parts)
{
part.FromUserInventoryItemID = fromUserInventoryItemId;
if ((item.Flags & (uint)InventoryItemFlags.ObjectOverwriteEveryone) != 0)
part.EveryoneMask = item.EveryOnePermissions;
if ((item.Flags & (uint)InventoryItemFlags.ObjectOverwriteNextOwner) != 0)
part.NextOwnerMask = item.NextPermissions;
if ((item.Flags & (uint)InventoryItemFlags.ObjectOverwriteGroup) != 0)
part.GroupMask = item.GroupPermissions;
}
}
rootPart.TrimPermissions();
if (isAttachment)
so.FromItemID = item.ID;
}
return true;
}
/// <summary>
/// Do post-rez processing when the object comes from an item.
/// </summary>
/// <param name="item"></param>
/// <param name="isAttachment"></param>
private void DoPostRezWhenFromItem(InventoryItemBase item, bool isAttachment)
{
if (!m_Scene.Permissions.BypassPermissions())
{
if ((item.CurrentPermissions & (uint)PermissionMask.Copy) == 0)
{
// If this is done on attachments, no
// copy ones will be lost, so avoid it
//
if (!isAttachment)
{
List<UUID> uuids = new List<UUID>();
uuids.Add(item.ID);
m_Scene.InventoryService.DeleteItems(item.Owner, uuids);
}
}
}
}
protected void AddUserData(SceneObjectGroup sog)
{
UserManagementModule.AddUser(sog.RootPart.CreatorID, sog.RootPart.CreatorData);
foreach (SceneObjectPart sop in sog.Parts)
UserManagementModule.AddUser(sop.CreatorID, sop.CreatorData);
}
public virtual void TransferInventoryAssets(InventoryItemBase item, UUID sender, UUID receiver)
{
}
public virtual bool CanGetAgentInventoryItem(IClientAPI remoteClient, UUID itemID, UUID requestID)
{
InventoryItemBase assetRequestItem = GetItem(remoteClient.AgentId, itemID);
if (assetRequestItem == null)
{
ILibraryService lib = m_Scene.RequestModuleInterface<ILibraryService>();
if (lib != null)
assetRequestItem = lib.LibraryRootFolder.FindItem(itemID);
if (assetRequestItem == null)
return false;
}
// At this point, we need to apply perms
// only to notecards and scripts. All
// other asset types are always available
//
if (assetRequestItem.AssetType == (int)AssetType.LSLText)
{
if (!m_Scene.Permissions.CanViewScript(itemID, UUID.Zero, remoteClient.AgentId))
{
remoteClient.SendAgentAlertMessage("Insufficient permissions to view script", false);
return false;
}
}
else if (assetRequestItem.AssetType == (int)AssetType.Notecard)
{
if (!m_Scene.Permissions.CanViewNotecard(itemID, UUID.Zero, remoteClient.AgentId))
{
remoteClient.SendAgentAlertMessage("Insufficient permissions to view notecard", false);
return false;
}
}
if (assetRequestItem.AssetID != requestID)
{
m_log.WarnFormat(
"[INVENTORY ACCESS MODULE]: {0} requested asset {1} from item {2} but this does not match item's asset {3}",
Name, requestID, itemID, assetRequestItem.AssetID);
return false;
}
return true;
}
public virtual bool IsForeignUser(UUID userID, out string assetServerURL)
{
assetServerURL = string.Empty;
return false;
}
#endregion
#region Misc
/// <summary>
/// Create a new asset data structure.
/// </summary>
/// <param name="name"></param>
/// <param name="description"></param>
/// <param name="invType"></param>
/// <param name="assetType"></param>
/// <param name="data"></param>
/// <returns></returns>
private AssetBase CreateAsset(string name, string description, sbyte assetType, byte[] data, string creatorID)
{
AssetBase asset = new AssetBase(UUID.Random(), name, assetType, creatorID);
asset.Description = description;
asset.Data = (data == null) ? new byte[1] : data;
return asset;
}
protected virtual InventoryItemBase GetItem(UUID agentID, UUID itemID)
{
IInventoryService invService = m_Scene.RequestModuleInterface<IInventoryService>();
InventoryItemBase item = new InventoryItemBase(itemID, agentID);
item = invService.GetItem(item);
if (item != null && item.CreatorData != null && item.CreatorData != string.Empty)
UserManagementModule.AddUser(item.CreatorIdAsUuid, item.CreatorData);
return item;
}
#endregion
}
}
| 42.779753 | 162 | 0.533284 | [
"BSD-3-Clause"
] | TheSyncer/OpenSim | OpenSim/Region/CoreModules/Framework/InventoryAccess/InventoryAccessModule.cs | 55,357 | C# |
#pragma warning disable 108 // new keyword hiding
#pragma warning disable 114 // new keyword hiding
namespace Windows.UI.Xaml.Controls
{
#if false || false || false || false || false
[global::Uno.NotImplemented]
#endif
public partial class HyperlinkButton : global::Windows.UI.Xaml.Controls.Primitives.ButtonBase
{
// Skipping already declared property NavigateUri
// Skipping already declared property NavigateUriProperty
// Skipping already declared method Windows.UI.Xaml.Controls.HyperlinkButton.HyperlinkButton()
// Forced skipping of method Windows.UI.Xaml.Controls.HyperlinkButton.HyperlinkButton()
// Forced skipping of method Windows.UI.Xaml.Controls.HyperlinkButton.NavigateUri.get
// Forced skipping of method Windows.UI.Xaml.Controls.HyperlinkButton.NavigateUri.set
// Forced skipping of method Windows.UI.Xaml.Controls.HyperlinkButton.NavigateUriProperty.get
}
}
| 47.210526 | 96 | 0.793757 | [
"Apache-2.0"
] | 06needhamt/uno | src/Uno.UI/Generated/3.0.0.0/Windows.UI.Xaml.Controls/HyperlinkButton.cs | 897 | C# |
using System;
using System.Linq;
using System.Collections.Generic;
using System.Runtime.InteropServices;
using Unity.Collections;
namespace UniGLTF
{
public static class Pin
{
public static Pin<T> Create<T>(ArraySegment<T> src) where T : struct
{
return new Pin<T>(src);
}
public static Pin<T> Create<T>(T[] src) where T : struct
{
return Create(new ArraySegment<T>(src));
}
}
public class Pin<T> : IDisposable
where T : struct
{
GCHandle m_pinnedArray;
ArraySegment<T> m_src;
public int Length
{
get
{
return m_src.Count * Marshal.SizeOf(typeof(T));
}
}
public Pin(ArraySegment<T> src)
{
m_src = src;
m_pinnedArray = GCHandle.Alloc(src.Array, GCHandleType.Pinned);
}
public IntPtr Ptr
{
get
{
var ptr = m_pinnedArray.AddrOfPinnedObject();
return new IntPtr(ptr.ToInt64() + m_src.Offset);
}
}
#region IDisposable Support
private bool disposedValue = false; // 重複する呼び出しを検出するには
protected virtual void Dispose(bool disposing)
{
if (!disposedValue)
{
if (disposing)
{
// TODO: マネージ状態を破棄します (マネージ オブジェクト)。
}
// TODO: アンマネージ リソース (アンマネージ オブジェクト) を解放し、下のファイナライザーをオーバーライドします。
// TODO: 大きなフィールドを null に設定します。
if (m_pinnedArray.IsAllocated)
{
m_pinnedArray.Free();
}
disposedValue = true;
}
}
// TODO: 上の Dispose(bool disposing) にアンマネージ リソースを解放するコードが含まれる場合にのみ、ファイナライザーをオーバーライドします。
// ~Pin() {
// // このコードを変更しないでください。クリーンアップ コードを上の Dispose(bool disposing) に記述します。
// Dispose(false);
// }
// このコードは、破棄可能なパターンを正しく実装できるように追加されました。
public void Dispose()
{
// このコードを変更しないでください。クリーンアップ コードを上の Dispose(bool disposing) に記述します。
Dispose(true);
// TODO: 上のファイナライザーがオーバーライドされる場合は、次の行のコメントを解除してください。
// GC.SuppressFinalize(this);
}
#endregion
}
public static class ArrayExtensions
{
public static T[] SelectInplace<T>(this T[] src, Func<T, T> pred)
{
for (int i = 0; i < src.Length; ++i)
{
src[i] = pred(src[i]);
}
return src;
}
}
public static class ArraySegmentExtensions
{
public static ArraySegment<T> Slice<T>(this ArraySegment<T> self, int start, int length)
{
if (start + length > self.Count)
{
throw new ArgumentOutOfRangeException();
}
return new ArraySegment<T>(
self.Array,
self.Offset + start,
length
);
}
public static ArraySegment<T> Slice<T>(this ArraySegment<T> self, int start)
{
if (start > self.Count)
{
throw new ArgumentOutOfRangeException();
}
return self.Slice(start, self.Count - start);
}
}
}
| 26.061538 | 96 | 0.501476 | [
"MIT"
] | 0b5vr/UniVRM | Assets/UniGLTF/Runtime/Extensions/ArrayExtensions.cs | 4,006 | C# |
/***
* Author: Yunhan Li
* Any issue please contact yunhn.lee@gmail.com
***/
using UnityEngine;
using UnityEngine.UI;
using System.Collections;
namespace VRKeyboard.Utils
{
public class GazeRaycaster : MonoBehaviour
{
#region Public Variables
public float delayInSeconds = 0.5f;
public float loadingTime;
public Image circle;
#endregion
#region Private Variables
private string lastTargetName = "";
Coroutine gazeControl; // Keep a single gaze control coroutine for better performance.
#endregion
#region MonoBehaviour Callbacks
void FixedUpdate()
{
RaycastHit hit;
Vector3 fwd = transform.TransformDirection(Vector3.forward);
if (Physics.Raycast(transform.position, fwd, out hit))
{
// Trigger events only if we hit the keys or operation button
if (hit.transform.tag == "VRGazeInteractable")
{
// Check if we have already gazed over the object.
if (lastTargetName == hit.transform.name)
{
return;
}
// Set the last hit if last targer is empty
if (lastTargetName == "")
{
lastTargetName = hit.transform.name;
}
// Check if current hit is same with last one;
if (hit.transform.name != lastTargetName)
{
circle.fillAmount = 0f;
lastTargetName = hit.transform.name;
}
if (null != gazeControl)
{
StopCoroutine(gazeControl);
}
gazeControl = StartCoroutine(FillCircle(hit.transform));
return;
}
else
{
if (null != gazeControl)
{
StopCoroutine(gazeControl);
}
ResetGazer();
}
}
else
{
if (null != gazeControl)
{
StopCoroutine(gazeControl);
}
ResetGazer();
}
}
#endregion
#region Private Methods
private IEnumerator FillCircle(Transform target)
{
// When the circle starts to fill, reset the timer.
float timer = 0f;
circle.fillAmount = 0f;
yield return new WaitForSeconds(delayInSeconds);
while (timer < loadingTime)
{
timer += Time.deltaTime;
circle.fillAmount = timer / loadingTime;
yield return null;
}
circle.fillAmount = 1f;
if (target.GetComponent<Button>())
{
target.GetComponent<Button>().onClick.Invoke();
}
ResetGazer();
}
// Reset the loading circle to initial, and clear last detected target.
private void ResetGazer()
{
if (circle == null)
{
Debug.LogError("Please assign target loading image, (ie. circle image)");
return;
}
circle.fillAmount = 0f;
lastTargetName = "";
}
#endregion
}
} | 28.544 | 94 | 0.462164 | [
"MIT"
] | PieterQLovesu/UnityVREscapeRoom | Assets/VRKeyboard/Scripts/GazeRaycaster.cs | 3,570 | C# |
namespace Chocolatey.Explorer.Services.PackageVersionService
{
public interface IODataPackageVersionService : IPackageVersionService
{
}
} | 23 | 73 | 0.745342 | [
"Apache-2.0"
] | mwrock/ChocolateyGUI | Chocolatey.Explorer/Services/PackageVersionService/IODataPackageVersionService.cs | 163 | C# |
// <copyright file="SearchViewActivity.cs">
// Copyright (c) 2017 Jacob Ebey
// </copyright>
using Android.App;
using Android.Content.PM;
using Android.Widget;
using MovieExplorer.Droid.Adapters;
using MovieExplorer.Droid.Extensions;
using MovieExplorer.ViewModels;
namespace MovieExplorer.Droid.Activities
{
[Activity(Label = "Movie Explorer", Icon = "@drawable/icon", Theme = "@style/MyTheme", ConfigurationChanges = ConfigChanges.Orientation | ConfigChanges.ScreenSize | ConfigChanges.Keyboard | ConfigChanges.KeyboardHidden)]
public class SearchViewActivity : BaseActivity<SearchViewModel>
{
protected override void OnViewModelSet()
{
base.OnViewModelSet();
SetContentView(Resource.Layout.Search);
this.SetupToolbar(true);
var grid = FindViewById<GridView>(Resource.Id.results_grid);
grid.Adapter = new MovieAdapter(this, ViewModel.SearchResults) { ClickedCommand = ViewModel.NavigateToMovieDetailCommand };
}
}
}
| 35.413793 | 224 | 0.717624 | [
"MIT"
] | jacob-ebey/MovieExplorer | MovieExplorer.Droid/Activities/SearchViewActivity.cs | 1,029 | C# |
namespace Crash.UI
{
public sealed class NormalChunkController : EntryChunkController
{
public NormalChunkController(NSFController up,NormalChunk chunk) : base(up,chunk)
{
Chunk = chunk;
}
public new NormalChunk Chunk { get; }
public override string ToString() => Properties.Resources.NormalChunkController_Text;
}
}
| 26.466667 | 94 | 0.639798 | [
"MIT",
"BSD-3-Clause"
] | Aedhen/CrashEdit | Crash.UI/Controllers/Normal/NormalChunkController.cs | 397 | C# |
using PrivateSquareWeb.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace PrivateSquareWeb.Controllers
{
public class SidebarProfileController : Controller
{
JwtTokenManager _JwtTokenManager = new JwtTokenManager();
// GET: SidebarProfile
public ActionResult Index()
{
return View();
}
public PartialViewResult HeaderValue()
{
AddressModel objModel = new AddressModel();
LoginModel MdUser = Services.GetLoginUser(this.ControllerContext.HttpContext, _JwtTokenManager);
if (MdUser.Id != 0)
{
objModel.Name = MdUser.Name;
objModel.UserId = Convert.ToInt64(MdUser.Id);
objModel.ProfileImg = MdUser.ProfileImg;
}
else
{
}
return PartialView("~/Views/Shared/_Sidebar.cshtml", objModel);
}
}
} | 20.673469 | 108 | 0.595262 | [
"Unlicense"
] | amitjind/nearbycart | PrivateSquareWeb/Controllers/SidebarProfileController.cs | 1,015 | C# |
/* Yet Another Forum.NET
* Copyright (C) 2003-2005 Bjørnar Henden
* Copyright (C) 2006-2013 Jaben Cargman
* Copyright (C) 2014 Ingo Herbote
* http://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
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
namespace YAF.Types
{
using System;
/// <summary>
/// Provides functions used for code contracts.
/// </summary>
public static class CodeContracts
{
#region Public Methods and Operators
/// <summary>
/// Validates argument (obj) is not <see langword="null" />. Throws exception
/// if it is.
/// </summary>
/// <typeparam name="T">
/// type of the argument that's being verified
/// </typeparam>
/// <param name="obj">value of argument to verify not null</param>
/// <param name="argumentName">name of the argument</param>
/// <exception cref="ArgumentNullException">
/// <paramref name="obj" /> is
/// <c>null</c>.
/// </exception>
[ContractAnnotation("obj:null => halt")]
public static void VerifyNotNull<T>([CanBeNull] T obj, string argumentName) where T : class
{
if (obj == null)
{
throw new ArgumentNullException(argumentName, String.Format("{0} cannot be null", argumentName));
}
}
#endregion
}
} | 36.716667 | 114 | 0.618248 | [
"Apache-2.0"
] | azarbara/YAFNET | yafsrc/YAF.Types/CodeContracts.cs | 2,145 | C# |
using System;
using System.Linq;
using NUnit.Framework;
using Orchard.Logging;
namespace Orchard.Tests {
[TestFixture]
public class EventsTests {
[Test]
public void AllEventsAreCalled() {
var events = new ITestEvents[] { new FooSink(), new BarSink() };
events.Invoke(x => x.Hello("world"), NullLogger.Instance);
Assert.That(events.OfType<FooSink>().Single().Name, Is.EqualTo("world"));
Assert.That(events.OfType<BarSink>().Single().Name, Is.EqualTo("world"));
}
[Test]
public void AnExceptionShouldBeLoggedAndOtherEventsWillBeFired() {
var events = new ITestEvents[] { new FooSink(), new CrashSink(), new BarSink() };
var logger = new TestLogger();
events.Invoke(x => x.Hello("world"), logger);
Assert.That(events.OfType<FooSink>().Single().Name, Is.EqualTo("world"));
Assert.That(events.OfType<BarSink>().Single().Name, Is.EqualTo("world"));
Assert.That(logger.LogException, Is.TypeOf<ApplicationException>());
Assert.That(logger.LogException, Has.Property("Message").EqualTo("Illegal name 'world'"));
}
private class TestLogger : ILogger {
public bool IsEnabled(LogLevel level) {
return true;
}
public void Log(LogLevel level, Exception exception, string format, params object[] args) {
LogException = exception;
LogFormat = format;
LogArgs = args;
}
public Exception LogException { get; set; }
public string LogFormat { get; set; }
public object[] LogArgs { get; set; }
}
private interface ITestEvents : IDependency {
void Hello(string name);
}
private class FooSink : ITestEvents {
void ITestEvents.Hello(string name) {
Name = name;
}
public string Name { get; set; }
}
private class BarSink : ITestEvents {
void ITestEvents.Hello(string name) {
Name = name;
}
public string Name { get; set; }
}
private class CrashSink : ITestEvents {
void ITestEvents.Hello(string name) {
throw new ApplicationException("Illegal name '" + name + "'");
}
}
}
}
| 33.118421 | 104 | 0.540326 | [
"MIT"
] | AccentureRapid/OrchardCollaboration | src/Orchard.Tests/EventsTests.cs | 2,519 | C# |
namespace Cogs.ActiveExpressions.Tests;
class AsyncDisposableTestPerson : AsyncDisposable
{
public AsyncDisposableTestPerson()
{
}
public AsyncDisposableTestPerson(string name) => this.name = name;
string? name;
long nameGets;
protected override ValueTask<bool> DisposeAsync(bool disposing) => new ValueTask<bool>(true);
public override string ToString() => $"{{{name}}}";
public string? Name
{
get
{
OnPropertyChanging(nameof(NameGets));
Interlocked.Increment(ref nameGets);
OnPropertyChanged(nameof(NameGets));
return name;
}
set => SetBackedProperty(ref name, in value);
}
public long NameGets => Interlocked.Read(ref nameGets);
public static AsyncDisposableTestPerson CreateEmily() => new AsyncDisposableTestPerson { name = "Emily" };
public static AsyncDisposableTestPerson CreateJohn() => new AsyncDisposableTestPerson { name = "John" };
public static AsyncDisposableTestPerson operator +(AsyncDisposableTestPerson a, AsyncDisposableTestPerson b) => new AsyncDisposableTestPerson { name = $"{a.name} {b.name}" };
public static AsyncDisposableTestPerson operator -(AsyncDisposableTestPerson asyncDisposableTestPerson) => new AsyncDisposableTestPerson { name = new string(asyncDisposableTestPerson.name?.Reverse().ToArray()) };
}
| 34.725 | 216 | 0.705544 | [
"Apache-2.0"
] | Epiforge/Cogs | Cogs.ActiveExpressions.Tests/AsyncDisposableTestPerson.cs | 1,389 | C# |
using System;
using static Vanara.PInvoke.FirewallApi;
using WindowsFirewallHelper.InternalHelpers;
namespace WindowsFirewallHelper.FirewallRules
{
/// <inheritdoc cref="FirewallWASRuleWin7" />
/// <summary>
/// Contains properties of a Windows Firewall with Advanced Security rule in Windows 8 and above
/// </summary>
public class FirewallWASRuleWin8 : FirewallWASRuleWin7, IEquatable<FirewallWASRuleWin8>
{
/// <summary>
/// Creates a new application rule for Windows Firewall with Advanced Security
/// </summary>
/// <param name="name">Name of the rule</param>
/// <param name="filename">Address of the executable file</param>
/// <param name="action">Action that this rule defines</param>
/// <param name="direction">Data direction in which this rule applies to</param>
/// <param name="profiles">The profile that this rule belongs to</param>
// ReSharper disable once TooManyDependencies
public FirewallWASRuleWin8(
string name,
string filename,
FirewallAction action,
FirewallDirection direction,
FirewallProfiles profiles) : base(name, filename, action, direction, profiles)
{
}
/// <summary>
/// Creates a new port rule for Windows Firewall with Advanced Security
/// </summary>
/// <param name="name">Name of the rule</param>
/// <param name="port">Port number of the rule</param>
/// <param name="action">Action that this rule defines</param>
/// <param name="direction">Data direction in which this rule applies to</param>
/// <param name="profiles">The profile that this rule belongs to</param>
// ReSharper disable once TooManyDependencies
public FirewallWASRuleWin8(
string name,
ushort port,
FirewallAction action,
FirewallDirection direction,
FirewallProfiles profiles) : base(name, port, action, direction, profiles)
{
}
/// <summary>
/// Creates a new general rule for Windows Firewall with Advanced Security
/// </summary>
/// <param name="name">Name of the rule</param>
/// <param name="action">Action that this rule defines</param>
/// <param name="direction">Data direction in which this rule applies to</param>
/// <param name="profiles">The profile that this rule belongs to</param>
// ReSharper disable once TooManyDependencies
public FirewallWASRuleWin8(
string name,
FirewallAction action,
FirewallDirection direction,
FirewallProfiles profiles) :
base(name, action, direction, profiles)
{
}
// ReSharper disable once SuggestBaseTypeForParameter
internal FirewallWASRuleWin8(INetFwRule3 rule) : base(rule)
{
}
/// <summary>
/// Gets or sets the PackageId of the Windows Store Application that this rule applies to
/// </summary>
public string ApplicationPackageId
{
get => UnderlyingObject.LocalAppPackageId;
set => UnderlyingObject.LocalAppPackageId = value;
}
/// <summary>
/// Gets or sets the expected Internet Protocol Security level of this rule
/// </summary>
public IPSecSecurityLevel IPSecSecurityLevel
{
get
{
if (!Enum.IsDefined(typeof(NET_FW_AUTHENTICATE_TYPE), UnderlyingObject.SecureFlags))
{
throw new ArgumentOutOfRangeException();
}
return (IPSecSecurityLevel) UnderlyingObject.SecureFlags;
}
set
{
if (!Enum.IsDefined(typeof(IPSecSecurityLevel), value))
{
throw new ArgumentOutOfRangeException();
}
UnderlyingObject.SecureFlags = (NET_FW_AUTHENTICATE_TYPE) value;
}
}
/// <summary>
/// Returns a Boolean value indicating if these class is available in the current machine
/// </summary>
public new static bool IsSupported
{
get => FirewallWASRuleWin7.IsSupported && ComHelper.IsSupported<INetFwRule3>();
}
/// <summary>
/// Gets or sets the list of the authorized local users
/// </summary>
public string LocalUserAuthorizedList
{
get => UnderlyingObject.LocalUserAuthorizedList;
set => UnderlyingObject.LocalUserAuthorizedList = value;
}
/// <summary>
/// Gets or sets the list of the authorized remote machines
/// </summary>
public string RemoteMachineAuthorizedList
{
get => UnderlyingObject.RemoteMachineAuthorizedList;
set => UnderlyingObject.RemoteMachineAuthorizedList = value;
}
/// <summary>
/// Gets or sets the list of the authorized remote users
/// </summary>
public string RemoteUserAuthorizedList
{
get => UnderlyingObject.RemoteUserAuthorizedList;
set => UnderlyingObject.RemoteUserAuthorizedList = value;
}
/// <summary>
/// Returns the underlying Windows Firewall Object
/// </summary>
protected new INetFwRule3 UnderlyingObject
{
get => base.UnderlyingObject as INetFwRule3;
}
/// <summary>
/// Gets or sets the Domain and User Name of the user that owns this rule
/// </summary>
public string UserOwner
{
get => UnderlyingObject.LocalUserOwner;
set => UnderlyingObject.LocalUserOwner = value;
}
/// <inheritdoc />
public bool Equals(FirewallWASRuleWin8 other)
{
if (other == null)
{
return false;
}
if (ReferenceEquals(this, other))
{
return true;
}
if (!base.Equals(other))
{
return false;
}
return string.Equals(UnderlyingObject.LocalAppPackageId, other.UnderlyingObject.LocalAppPackageId) &&
string.Equals(UnderlyingObject.LocalUserAuthorizedList,
other.UnderlyingObject.LocalUserAuthorizedList) &&
string.Equals(UnderlyingObject.RemoteMachineAuthorizedList,
other.UnderlyingObject.RemoteMachineAuthorizedList) &&
string.Equals(UnderlyingObject.RemoteUserAuthorizedList,
other.UnderlyingObject.RemoteUserAuthorizedList) &&
string.Equals(UnderlyingObject.LocalUserOwner, other.UnderlyingObject.LocalUserOwner) &&
UnderlyingObject.SecureFlags == other.UnderlyingObject.SecureFlags;
}
/// <summary>
/// Compares two <see cref="FirewallWASRuleWin8" /> objects for equality
/// </summary>
/// <param name="left">A <see cref="FirewallWASRuleWin8" /> object</param>
/// <param name="right">A <see cref="FirewallWASRuleWin8" /> object</param>
/// <returns>true if two sides are equal; otherwise false</returns>
public static bool operator ==(FirewallWASRuleWin8 left, FirewallWASRuleWin8 right)
{
return Equals(left, right) || left?.Equals(right) == true;
}
/// <summary>
/// Compares two <see cref="FirewallWASRuleWin8" /> objects for inequality
/// </summary>
/// <param name="left">A <see cref="FirewallWASRuleWin8" /> object</param>
/// <param name="right">A <see cref="FirewallWASRuleWin8" /> object</param>
/// <returns>true if two sides are not equal; otherwise false</returns>
public static bool operator !=(FirewallWASRuleWin8 left, FirewallWASRuleWin8 right)
{
return !(left == right);
}
/// <inheritdoc />
public override bool Equals(object obj)
{
return Equals(obj as FirewallWASRuleWin8);
}
/// <inheritdoc />
public override int GetHashCode()
{
unchecked
{
var hashCode = base.GetHashCode();
hashCode = hashCode * 467 + (UnderlyingObject.LocalAppPackageId?.GetHashCode() ?? 0);
hashCode = hashCode * 467 + (UnderlyingObject.LocalUserAuthorizedList?.GetHashCode() ?? 0);
hashCode = hashCode * 467 + (UnderlyingObject.RemoteMachineAuthorizedList?.GetHashCode() ?? 0);
hashCode = hashCode * 467 + (UnderlyingObject.RemoteUserAuthorizedList?.GetHashCode() ?? 0);
hashCode = hashCode * 467 + (UnderlyingObject.LocalUserOwner?.GetHashCode() ?? 0);
hashCode = hashCode * 467 + (int)UnderlyingObject.SecureFlags;
return hashCode;
}
}
/// <summary>
/// Returns the underlying COM object
/// </summary>
/// <returns>The underlying COM object</returns>
public new INetFwRule3 GetCOMObject()
{
return UnderlyingObject;
}
}
} | 39.175 | 113 | 0.584556 | [
"MIT"
] | dahall/WindowsFirewallHelper | WindowsFirewallHelper/FirewallRules/FirewallWASRuleWin8.cs | 9,404 | C# |
using System;
using System.Collections.Generic;
using System.IO.Abstractions.TestingHelpers;
using EawModinfo.Spec;
using Moq;
using PetroGlyph.Games.EawFoc.Games;
using PetroGlyph.Games.EawFoc.Services.Language;
using Xunit;
namespace PetroGlyph.Games.EawFoc.Test.GameServices;
public class GameLanguageFinderTest
{
[Fact]
public void NullSp_Throws()
{
Assert.Throws<ArgumentNullException>(() => new GameLanguageFinder(null));
}
[Fact]
public void TestEmptyResult()
{
var fs = new MockFileSystem();
fs.AddDirectory("Game");
var game = new Mock<IGame>();
game.Setup(g => g.Directory).Returns(fs.DirectoryInfo.FromDirectoryName("Game"));
var languageHelper = new Mock<ILanguageFinder>();
languageHelper
.Setup(h => h.Merge(It.IsAny<IEnumerable<ILanguageInfo>[]>()))
.Returns(new HashSet<ILanguageInfo>());
var sp = new Mock<IServiceProvider>();
sp.Setup(p => p.GetService(typeof(ILanguageFinder))).Returns(languageHelper.Object);
var finder = new GameLanguageFinder(sp.Object);
var langs = finder.FindInstalledLanguages(game.Object);
Assert.Empty(langs);
}
[Fact]
public void TestSomeResult()
{
var fs = new MockFileSystem();
fs.AddDirectory("Game");
var game = new Mock<IGame>();
game.Setup(g => g.Directory).Returns(fs.DirectoryInfo.FromDirectoryName("Game"));
var langInfo = new Mock<ILanguageInfo>();
var languageHelper = new Mock<ILanguageFinder>();
languageHelper
.Setup(h => h.Merge(It.IsAny<IEnumerable<ILanguageInfo>[]>()))
.Returns(new HashSet<ILanguageInfo> { langInfo.Object });
var sp = new Mock<IServiceProvider>();
sp.Setup(p => p.GetService(typeof(ILanguageFinder))).Returns(languageHelper.Object);
var finder = new GameLanguageFinder(sp.Object);
var langs = finder.FindInstalledLanguages(game.Object);
Assert.Equal(1, langs.Count);
}
} | 31.584615 | 92 | 0.656113 | [
"MIT"
] | AlamoEngine-Tools/PetroglyphGameInfrastructure | src/PetroGlyph.Games.EawFoc/test/GameServices/GameLanguageFinderTest.cs | 2,055 | C# |
using MB.Business.Transaction;
using MB.Business.User;
using MB.Data.Entities;
using Microsoft.AspNet.OData.Query;
using Microsoft.AspNetCore.Mvc;
using Minded.Mediator;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace MB.Application.Api
{
[Route("api/[controller]")]
public class TransactionsController : BaseController
{
private readonly IMediator _mediator;
public TransactionsController(IMediator mediator)
{
_mediator = mediator;
}
[HttpPost]
public async Task<IActionResult> Post([FromBody] Transaction transaction)
{
var command = new CreateTransactionCommand(transaction);
var response = await _mediator.ProcessCommandAsync<int>(command);
if(!response.Successful)
{
return BadRequest(response.ValidationEntries.First()?.ToString() ?? "Operation not allowed");
}
return Created($"/api/Transactions/{transaction.ID}", transaction);
}
}
}
| 28.263158 | 109 | 0.662011 | [
"MIT"
] | norcino/MindedBanking | MB.Application.Api/Controllers/TransactionsController.cs | 1,076 | C# |
using EPlast.BLL.Interfaces.AzureStorage.Base;
using Microsoft.Azure.Storage;
using Microsoft.Azure.Storage.Blob;
using Microsoft.Extensions.Configuration;
using System;
using System.Threading.Tasks;
namespace EPlast.BLL.Services.AzureStorage.Base
{
public class AzureBlobConnectionFactory : IAzureBlobConnectionFactory
{
private readonly IConfiguration _configuration;
private CloudBlobClient _blobClient;
public AzureBlobConnectionFactory(IConfiguration configuration)
{
_configuration = configuration;
}
/// <inheritdoc />
public async Task<CloudBlobContainer> GetBlobContainer(string containerNameKey)
{
var containerName = _configuration.GetValue<string>(containerNameKey);
var blobClient = GetBlobClient();
CloudBlobContainer _blobContainer = blobClient.GetContainerReference(containerName);
if (await _blobContainer.CreateIfNotExistsAsync())
{
await _blobContainer.SetPermissionsAsync(new BlobContainerPermissions
{ PublicAccess = BlobContainerPublicAccessType.Blob });
}
return _blobContainer;
}
private CloudBlobClient GetBlobClient()
{
if (_blobClient != null)
{
return _blobClient;
}
var storageConnectionString = _configuration.GetValue<string>("StorageConnectionString");
if (!CloudStorageAccount.TryParse(storageConnectionString, out var storageAccount))
{
throw new ArgumentException("Could not create storage account with StorageConnectionString configuration");
}
_blobClient = storageAccount.CreateCloudBlobClient();
return _blobClient;
}
}
}
| 33.581818 | 123 | 0.664321 | [
"MIT"
] | Toxa2202/plast | EPlast/EPlast.BLL/Services/AzureStorage/Base/AzureBlobConnectionFactory.cs | 1,849 | C# |
// --------------------------------------------------------------------------------------------------------------------
// <copyright file="PlotModelExtensions.cs" company="OxyPlot">
// Copyright (c) 2014 OxyPlot contributors
// </copyright>
// <summary>
// Provides extension methods to the <see cref="PlotModel" />.
// </summary>
// --------------------------------------------------------------------------------------------------------------------
namespace OxyPlot.EtoForms
{
using System;
using Eto.Drawing;
/// <summary>
/// Provides extension methods to the <see cref="PlotModel" />.
/// </summary>
public static class PlotModelExtensions
{
/// <summary>
/// Creates an SVG string.
/// </summary>
/// <param name="model">The model.</param>
/// <param name="width">The width (points).</param>
/// <param name="height">The height (points).</param>
/// <param name="isDocument">if set to <c>true</c>, the xml headers will be included (?xml and !DOCTYPE).</param>
/// <returns>A <see cref="string" />.</returns>
public static string ToSvg(this PlotModel model, double width, double height, bool isDocument)
{
/* TODO Why is this needed at all? */
using (var g = new Graphics(new Bitmap(1, 1, PixelFormat.Format32bppRgba)))
{
using (var rc = new GraphicsRenderContext(g) { RendersToScreen = false })
{
return OxyPlot.SvgExporter.ExportToString(model, width, height, isDocument, rc);
}
}
}
}
}
| 39.95122 | 121 | 0.492063 | [
"MIT"
] | rafntor/OxyPlot.EtoForms | OxyPlot.EtoForms/PlotModelExtensions.cs | 1,638 | C# |
using System;
using System.Collections.Generic;
using Fhi.Controls.Wizard;
namespace Fhi.Controls.Indicators.Governance.Wizard
{
public class Step1ViewModel : WizardStepViewModel
{
private String _userColumn = ColumnChoices[0];
private String _questionColumn = ColumnChoices[10];
private String _lastQuestion = "Please provide";
public String UserColumn
{
get => _userColumn;
set => Set(ref _userColumn, value);
}
public String QuestionColumn
{
get => _questionColumn;
set => Set(ref _questionColumn, value);
}
public static List<String> ColumnChoices { get; }= new List<string>
{
"A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z"
};
public String LastQuestion
{
get => _lastQuestion;
set => Set(ref _lastQuestion, value);
}
public override Boolean ReadyForNext => true;
}
} | 28.5 | 140 | 0.542013 | [
"MIT"
] | sustainable-software/FHI-Toolbox | Desktop/Fhi/Controls/Indicators/Governance/Wizard/Step1ViewModel.cs | 1,083 | C# |
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
namespace DotNetNuke.Modules.Admin.Host {
public partial class HostSettings {
/// <summary>
/// valSummary control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.ValidationSummary valSummary;
/// <summary>
/// plProduct control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::DotNetNuke.UI.UserControls.LabelControl plProduct;
/// <summary>
/// lblProduct control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.Label lblProduct;
/// <summary>
/// plVersion control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::DotNetNuke.UI.UserControls.LabelControl plVersion;
/// <summary>
/// lblVersion control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.Label lblVersion;
/// <summary>
/// betaRow control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.HtmlControls.HtmlGenericControl betaRow;
/// <summary>
/// plBetaNotice control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::DotNetNuke.UI.UserControls.LabelControl plBetaNotice;
/// <summary>
/// chkBetaNotice control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.CheckBox chkBetaNotice;
/// <summary>
/// plUpgrade control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::DotNetNuke.UI.UserControls.LabelControl plUpgrade;
/// <summary>
/// chkUpgrade control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.CheckBox chkUpgrade;
/// <summary>
/// plAvailable control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::DotNetNuke.UI.UserControls.LabelControl plAvailable;
/// <summary>
/// hypUpgrade control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.HyperLink hypUpgrade;
/// <summary>
/// plDataProvider control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::DotNetNuke.UI.UserControls.LabelControl plDataProvider;
/// <summary>
/// lblDataProvider control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.Label lblDataProvider;
/// <summary>
/// plFramework control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::DotNetNuke.UI.UserControls.LabelControl plFramework;
/// <summary>
/// lblFramework control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.Label lblFramework;
/// <summary>
/// plIdentity control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::DotNetNuke.UI.UserControls.LabelControl plIdentity;
/// <summary>
/// lblIdentity control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.Label lblIdentity;
/// <summary>
/// plHostName control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::DotNetNuke.UI.UserControls.LabelControl plHostName;
/// <summary>
/// lblHostName control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.Label lblHostName;
/// <summary>
/// plIPAddress control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::DotNetNuke.UI.UserControls.LabelControl plIPAddress;
/// <summary>
/// lblIPAddress control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.Label lblIPAddress;
/// <summary>
/// plPermissions control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::DotNetNuke.UI.UserControls.LabelControl plPermissions;
/// <summary>
/// lblPermissions control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.Label lblPermissions;
/// <summary>
/// plApplicationPath control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::DotNetNuke.UI.UserControls.LabelControl plApplicationPath;
/// <summary>
/// lblApplicationPath control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.Label lblApplicationPath;
/// <summary>
/// plApplicationMapPath control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::DotNetNuke.UI.UserControls.LabelControl plApplicationMapPath;
/// <summary>
/// lblApplicationMapPath control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.Label lblApplicationMapPath;
/// <summary>
/// plServerTime control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::DotNetNuke.UI.UserControls.LabelControl plServerTime;
/// <summary>
/// lblServerTime control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.Label lblServerTime;
/// <summary>
/// plGUID control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::DotNetNuke.UI.UserControls.LabelControl plGUID;
/// <summary>
/// lblGUID control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.Label lblGUID;
/// <summary>
/// plWebFarm control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::DotNetNuke.UI.UserControls.LabelControl plWebFarm;
/// <summary>
/// chkWebFarm control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.HtmlControls.HtmlInputCheckBox chkWebFarm;
/// <summary>
/// plHostPortal control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::DotNetNuke.UI.UserControls.LabelControl plHostPortal;
/// <summary>
/// hostPortalsCombo control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::DotNetNuke.Web.UI.WebControls.DnnComboBox hostPortalsCombo;
/// <summary>
/// plHostTitle control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::DotNetNuke.UI.UserControls.LabelControl plHostTitle;
/// <summary>
/// txtHostTitle control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.TextBox txtHostTitle;
/// <summary>
/// plHostURL control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::DotNetNuke.UI.UserControls.LabelControl plHostURL;
/// <summary>
/// txtHostURL control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.TextBox txtHostURL;
/// <summary>
/// plHostEmail control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::DotNetNuke.UI.UserControls.LabelControl plHostEmail;
/// <summary>
/// txtHostEmail control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.TextBox txtHostEmail;
/// <summary>
/// valHostEmail control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.RegularExpressionValidator valHostEmail;
/// <summary>
/// plRememberMe control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::DotNetNuke.UI.UserControls.LabelControl plRememberMe;
/// <summary>
/// chkRemember control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.CheckBox chkRemember;
/// <summary>
/// plCopyright control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::DotNetNuke.UI.UserControls.LabelControl plCopyright;
/// <summary>
/// chkCopyright control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.CheckBox chkCopyright;
/// <summary>
/// plUseCustomErrorMessages control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::DotNetNuke.UI.UserControls.LabelControl plUseCustomErrorMessages;
/// <summary>
/// chkUseCustomErrorMessages control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.CheckBox chkUseCustomErrorMessages;
/// <summary>
/// plUseCustomModuleCssClass control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::DotNetNuke.UI.UserControls.LabelControl plUseCustomModuleCssClass;
/// <summary>
/// chkUseCustomModuleCssClass control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.CheckBox chkUseCustomModuleCssClass;
/// <summary>
/// plUpgradeForceSSL control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::DotNetNuke.UI.UserControls.LabelControl plUpgradeForceSSL;
/// <summary>
/// chkUpgradeForceSSL control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.CheckBox chkUpgradeForceSSL;
/// <summary>
/// plSSLDomain control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::DotNetNuke.UI.UserControls.LabelControl plSSLDomain;
/// <summary>
/// txtSSLDomain control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.TextBox txtSSLDomain;
/// <summary>
/// plHostSkin control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::DotNetNuke.UI.UserControls.LabelControl plHostSkin;
/// <summary>
/// hostSkinCombo control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::DotNetNuke.Web.UI.WebControls.DnnSkinComboBox hostSkinCombo;
/// <summary>
/// plHostContainer control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::DotNetNuke.UI.UserControls.LabelControl plHostContainer;
/// <summary>
/// hostContainerCombo control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::DotNetNuke.Web.UI.WebControls.DnnSkinComboBox hostContainerCombo;
/// <summary>
/// plAdminSkin control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::DotNetNuke.UI.UserControls.LabelControl plAdminSkin;
/// <summary>
/// editSkinCombo control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::DotNetNuke.Web.UI.WebControls.DnnSkinComboBox editSkinCombo;
/// <summary>
/// plAdminContainer control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::DotNetNuke.UI.UserControls.LabelControl plAdminContainer;
/// <summary>
/// editContainerCombo control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::DotNetNuke.Web.UI.WebControls.DnnSkinComboBox editContainerCombo;
/// <summary>
/// plHostDefaultDocType control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::DotNetNuke.UI.UserControls.LabelControl plHostDefaultDocType;
/// <summary>
/// docTypeCombo control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::DotNetNuke.Web.UI.WebControls.DnnComboBox docTypeCombo;
/// <summary>
/// plProcessor control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::DotNetNuke.UI.UserControls.LabelControl plProcessor;
/// <summary>
/// processorCombo control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::DotNetNuke.Web.UI.WebControls.DnnComboBox processorCombo;
/// <summary>
/// processorLink control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.HyperLink processorLink;
/// <summary>
/// plUserId control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::DotNetNuke.UI.UserControls.LabelControl plUserId;
/// <summary>
/// txtUserId control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.TextBox txtUserId;
/// <summary>
/// plPassword control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::DotNetNuke.UI.UserControls.LabelControl plPassword;
/// <summary>
/// txtPassword control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.TextBox txtPassword;
/// <summary>
/// plHostFee control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::DotNetNuke.UI.UserControls.LabelControl plHostFee;
/// <summary>
/// txtHostFee control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.TextBox txtHostFee;
/// <summary>
/// valHostFee control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.CompareValidator valHostFee;
/// <summary>
/// plHostCurrency control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::DotNetNuke.UI.UserControls.LabelControl plHostCurrency;
/// <summary>
/// currencyCombo control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::DotNetNuke.Web.UI.WebControls.DnnComboBox currencyCombo;
/// <summary>
/// plHostSpace control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::DotNetNuke.UI.UserControls.LabelControl plHostSpace;
/// <summary>
/// txtHostSpace control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.TextBox txtHostSpace;
/// <summary>
/// plPageQuota control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::DotNetNuke.UI.UserControls.LabelControl plPageQuota;
/// <summary>
/// txtPageQuota control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.TextBox txtPageQuota;
/// <summary>
/// plUserQuota control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::DotNetNuke.UI.UserControls.LabelControl plUserQuota;
/// <summary>
/// txtUserQuota control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.TextBox txtUserQuota;
/// <summary>
/// plDemoPeriod control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::DotNetNuke.UI.UserControls.LabelControl plDemoPeriod;
/// <summary>
/// txtDemoPeriod control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.TextBox txtDemoPeriod;
/// <summary>
/// lblDemoPeriod control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.Label lblDemoPeriod;
/// <summary>
/// plDemoSignup control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::DotNetNuke.UI.UserControls.LabelControl plDemoSignup;
/// <summary>
/// chkDemoSignup control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.CheckBox chkDemoSignup;
/// <summary>
/// FriendlyUrlsExtensionControl control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::DotNetNuke.ExtensionPoints.EditPagePanelExtensionControl FriendlyUrlsExtensionControl;
/// <summary>
/// plProxyServer control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::DotNetNuke.UI.UserControls.LabelControl plProxyServer;
/// <summary>
/// txtProxyServer control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.TextBox txtProxyServer;
/// <summary>
/// plProxyPort control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::DotNetNuke.UI.UserControls.LabelControl plProxyPort;
/// <summary>
/// txtProxyPort control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.TextBox txtProxyPort;
/// <summary>
/// plProxyUsername control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::DotNetNuke.UI.UserControls.LabelControl plProxyUsername;
/// <summary>
/// txtProxyUsername control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.TextBox txtProxyUsername;
/// <summary>
/// plProxyPassword control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::DotNetNuke.UI.UserControls.LabelControl plProxyPassword;
/// <summary>
/// txtProxyPassword control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.TextBox txtProxyPassword;
/// <summary>
/// plWebRequestTimeout control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::DotNetNuke.UI.UserControls.LabelControl plWebRequestTimeout;
/// <summary>
/// txtWebRequestTimeout control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.TextBox txtWebRequestTimeout;
/// <summary>
/// plSMTPServer control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::DotNetNuke.UI.UserControls.LabelControl plSMTPServer;
/// <summary>
/// txtSMTPServer control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.TextBox txtSMTPServer;
/// <summary>
/// plConnectionLimit control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::DotNetNuke.UI.UserControls.LabelControl plConnectionLimit;
/// <summary>
/// txtConnectionLimit control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.TextBox txtConnectionLimit;
/// <summary>
/// RegularExpressionValidator2 control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.RegularExpressionValidator RegularExpressionValidator2;
/// <summary>
/// rexNumber1 control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.RangeValidator rexNumber1;
/// <summary>
/// plMaxIdleTime control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::DotNetNuke.UI.UserControls.LabelControl plMaxIdleTime;
/// <summary>
/// txtMaxIdleTime control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.TextBox txtMaxIdleTime;
/// <summary>
/// rexNumber2 control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.RangeValidator rexNumber2;
/// <summary>
/// plSMTPAuthentication control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::DotNetNuke.UI.UserControls.LabelControl plSMTPAuthentication;
/// <summary>
/// optSMTPAuthentication control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.RadioButtonList optSMTPAuthentication;
/// <summary>
/// plSMTPEnableSSL control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::DotNetNuke.UI.UserControls.LabelControl plSMTPEnableSSL;
/// <summary>
/// chkSMTPEnableSSL control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.CheckBox chkSMTPEnableSSL;
/// <summary>
/// plSMTPUsername control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::DotNetNuke.UI.UserControls.LabelControl plSMTPUsername;
/// <summary>
/// txtSMTPUsername control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.TextBox txtSMTPUsername;
/// <summary>
/// plSMTPPassword control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::DotNetNuke.UI.UserControls.LabelControl plSMTPPassword;
/// <summary>
/// txtSMTPPassword control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.TextBox txtSMTPPassword;
/// <summary>
/// cmdEmail control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.LinkButton cmdEmail;
/// <summary>
/// plBatch control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::DotNetNuke.UI.UserControls.LabelControl plBatch;
/// <summary>
/// txtBatch control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.TextBox txtBatch;
/// <summary>
/// plPageState control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::DotNetNuke.UI.UserControls.LabelControl plPageState;
/// <summary>
/// cboPageState control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.RadioButtonList cboPageState;
/// <summary>
/// plPsWarning control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.Label plPsWarning;
/// <summary>
/// lblModuleCacheProvider control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::DotNetNuke.UI.UserControls.LabelControl lblModuleCacheProvider;
/// <summary>
/// cboModuleCacheProvider control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::DotNetNuke.Web.UI.WebControls.DnnComboBox cboModuleCacheProvider;
/// <summary>
/// PageCacheRow control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.HtmlControls.HtmlGenericControl PageCacheRow;
/// <summary>
/// lblPageCacheProvider control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::DotNetNuke.UI.UserControls.LabelControl lblPageCacheProvider;
/// <summary>
/// cboPageCacheProvider control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::DotNetNuke.Web.UI.WebControls.DnnComboBox cboPageCacheProvider;
/// <summary>
/// plPerformance control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::DotNetNuke.UI.UserControls.LabelControl plPerformance;
/// <summary>
/// cboPerformance control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::DotNetNuke.Web.UI.WebControls.DnnComboBox cboPerformance;
/// <summary>
/// plCacheability control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::DotNetNuke.UI.UserControls.LabelControl plCacheability;
/// <summary>
/// cboCacheability control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::DotNetNuke.Web.UI.WebControls.DnnComboBox cboCacheability;
/// <summary>
/// plcboUnauthCacheability control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::DotNetNuke.UI.UserControls.LabelControl plcboUnauthCacheability;
/// <summary>
/// cboUnauthCacheability control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::DotNetNuke.Web.UI.WebControls.DnnComboBox cboUnauthCacheability;
/// <summary>
/// plJQueryVersion control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::DotNetNuke.UI.UserControls.LabelControl plJQueryVersion;
/// <summary>
/// jQueryVersion control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.Label jQueryVersion;
/// <summary>
/// plJQueryUIVersion control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::DotNetNuke.UI.UserControls.LabelControl plJQueryUIVersion;
/// <summary>
/// jQueryUIVersion control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.Label jQueryUIVersion;
/// <summary>
/// plMsAjaxCdn control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::DotNetNuke.UI.UserControls.LabelControl plMsAjaxCdn;
/// <summary>
/// chkMsAjaxCdn control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.CheckBox chkMsAjaxCdn;
/// <summary>
/// plTelerikCdn control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::DotNetNuke.UI.UserControls.LabelControl plTelerikCdn;
/// <summary>
/// chkTelerikCdn control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.CheckBox chkTelerikCdn;
/// <summary>
/// plTelerikBasicUrl control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::DotNetNuke.UI.UserControls.LabelControl plTelerikBasicUrl;
/// <summary>
/// txtTelerikBasicUrl control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.TextBox txtTelerikBasicUrl;
/// <summary>
/// plTelerikSecureUrl control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::DotNetNuke.UI.UserControls.LabelControl plTelerikSecureUrl;
/// <summary>
/// txtTelerikSecureUrl control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.TextBox txtTelerikSecureUrl;
/// <summary>
/// plEnableCDN control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::DotNetNuke.UI.UserControls.LabelControl plEnableCDN;
/// <summary>
/// chkEnableCDN control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.CheckBox chkEnableCDN;
/// <summary>
/// DebugEnabledRow control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.HtmlControls.HtmlGenericControl DebugEnabledRow;
/// <summary>
/// CrmVersion control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.Label CrmVersion;
/// <summary>
/// IncrementCrmVersionButton control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.LinkButton IncrementCrmVersionButton;
/// <summary>
/// chkCrmEnableCompositeFiles control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.CheckBox chkCrmEnableCompositeFiles;
/// <summary>
/// chkCrmMinifyCss control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.CheckBox chkCrmMinifyCss;
/// <summary>
/// chkCrmMinifyJs control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.CheckBox chkCrmMinifyJs;
/// <summary>
/// plResetLinkValidity control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::DotNetNuke.UI.UserControls.LabelControl plResetLinkValidity;
/// <summary>
/// txtResetLinkValidity control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.TextBox txtResetLinkValidity;
/// <summary>
/// valResetLink control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.CompareValidator valResetLink;
/// <summary>
/// lblResetLinkValidity control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.Label lblResetLinkValidity;
/// <summary>
/// plAdminResetLinkValidity control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::DotNetNuke.UI.UserControls.LabelControl plAdminResetLinkValidity;
/// <summary>
/// txtAdminResetLinkValidity control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.TextBox txtAdminResetLinkValidity;
/// <summary>
/// valAdminResetLink control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.CompareValidator valAdminResetLink;
/// <summary>
/// lblAdminResetLinkValidity control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.Label lblAdminResetLinkValidity;
/// <summary>
/// plEnablePasswordHistory control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::DotNetNuke.UI.UserControls.LabelControl plEnablePasswordHistory;
/// <summary>
/// chkEnablePasswordHistory control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.CheckBox chkEnablePasswordHistory;
/// <summary>
/// plNumberPasswords control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::DotNetNuke.UI.UserControls.LabelControl plNumberPasswords;
/// <summary>
/// txtNumberPasswords control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.TextBox txtNumberPasswords;
/// <summary>
/// lblNumberPasswords control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.Label lblNumberPasswords;
/// <summary>
/// plEnableBannedList control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::DotNetNuke.UI.UserControls.LabelControl plEnableBannedList;
/// <summary>
/// chkBannedList control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.CheckBox chkBannedList;
/// <summary>
/// plEnableStrengthMeter control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::DotNetNuke.UI.UserControls.LabelControl plEnableStrengthMeter;
/// <summary>
/// chkStrengthMeter control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.CheckBox chkStrengthMeter;
/// <summary>
/// plEnableIPChecking control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::DotNetNuke.UI.UserControls.LabelControl plEnableIPChecking;
/// <summary>
/// chkIPChecking control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.CheckBox chkIPChecking;
/// <summary>
/// passwordSettings control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::DotNetNuke.UI.WebControls.PropertyEditorControl passwordSettings;
/// <summary>
/// divFiltersDisabled control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.HtmlControls.HtmlGenericControl divFiltersDisabled;
/// <summary>
/// IPFiltersRow control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.HtmlControls.HtmlGenericControl IPFiltersRow;
/// <summary>
/// IPFilters control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::DotNetNuke.Modules.Admin.Host.IPFilters IPFilters;
/// <summary>
/// plIndexWordMinLength control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::DotNetNuke.UI.UserControls.LabelControl plIndexWordMinLength;
/// <summary>
/// txtIndexWordMinLength control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.TextBox txtIndexWordMinLength;
/// <summary>
/// validatorIndexWordMinLengthRequired control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.RequiredFieldValidator validatorIndexWordMinLengthRequired;
/// <summary>
/// validatorIndexWordMinLengthCompared control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.CompareValidator validatorIndexWordMinLengthCompared;
/// <summary>
/// plIndexWordMaxLength control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::DotNetNuke.UI.UserControls.LabelControl plIndexWordMaxLength;
/// <summary>
/// txtIndexWordMaxLength control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.TextBox txtIndexWordMaxLength;
/// <summary>
/// validatorIndexWordMaxLengthRequired control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.RequiredFieldValidator validatorIndexWordMaxLengthRequired;
/// <summary>
/// validatorIndexWordMaxLengthCompared control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.CompareValidator validatorIndexWordMaxLengthCompared;
/// <summary>
/// allowLeadingWildcardSettingRow control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.HtmlControls.HtmlGenericControl allowLeadingWildcardSettingRow;
/// <summary>
/// lblAllowLeadingWildcard control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::DotNetNuke.UI.UserControls.LabelControl lblAllowLeadingWildcard;
/// <summary>
/// chkAllowLeadingWildcard control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.CheckBox chkAllowLeadingWildcard;
/// <summary>
/// plCustomAnalyzer control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::DotNetNuke.UI.UserControls.LabelControl plCustomAnalyzer;
/// <summary>
/// cbCustomAnalyzer control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::DotNetNuke.Web.UI.WebControls.DnnComboBox cbCustomAnalyzer;
/// <summary>
/// plTitleBoost control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::DotNetNuke.UI.UserControls.LabelControl plTitleBoost;
/// <summary>
/// txtTitleBoost control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.TextBox txtTitleBoost;
/// <summary>
/// plTagBoost control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::DotNetNuke.UI.UserControls.LabelControl plTagBoost;
/// <summary>
/// txtTagBoost control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.TextBox txtTagBoost;
/// <summary>
/// plContentBoost control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::DotNetNuke.UI.UserControls.LabelControl plContentBoost;
/// <summary>
/// txtContentBoost control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.TextBox txtContentBoost;
/// <summary>
/// plDescriptionBoost control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::DotNetNuke.UI.UserControls.LabelControl plDescriptionBoost;
/// <summary>
/// txtDescriptionBoost control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.TextBox txtDescriptionBoost;
/// <summary>
/// plAuthorBoost control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::DotNetNuke.UI.UserControls.LabelControl plAuthorBoost;
/// <summary>
/// txtAuthorBoost control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.TextBox txtAuthorBoost;
/// <summary>
/// plSearchIndexPath control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::DotNetNuke.UI.UserControls.LabelControl plSearchIndexPath;
/// <summary>
/// lblSearchIndexPath control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.Label lblSearchIndexPath;
/// <summary>
/// pnlSearchGetMoreButton control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.HtmlControls.HtmlGenericControl pnlSearchGetMoreButton;
/// <summary>
/// btnSearchGetMoreInfo control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.LinkButton btnSearchGetMoreInfo;
/// <summary>
/// pnlSearchStatistics control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.HtmlControls.HtmlGenericControl pnlSearchStatistics;
/// <summary>
/// plSearchIndexDbSize control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::DotNetNuke.UI.UserControls.LabelControl plSearchIndexDbSize;
/// <summary>
/// lblSearchIndexDbSize control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.Label lblSearchIndexDbSize;
/// <summary>
/// plSearchIndexTotalActiveDocuments control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::DotNetNuke.UI.UserControls.LabelControl plSearchIndexTotalActiveDocuments;
/// <summary>
/// lblSearchIndexTotalActiveDocuments control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.Label lblSearchIndexTotalActiveDocuments;
/// <summary>
/// plSearchIndexTotalDeletedDocuments control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::DotNetNuke.UI.UserControls.LabelControl plSearchIndexTotalDeletedDocuments;
/// <summary>
/// lblSearchIndexTotalDeletedDocuments control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.Label lblSearchIndexTotalDeletedDocuments;
/// <summary>
/// plSearchIndexLastModifiedOn control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::DotNetNuke.UI.UserControls.LabelControl plSearchIndexLastModifiedOn;
/// <summary>
/// lblSearchIndexLastModifedOn control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.Label lblSearchIndexLastModifedOn;
/// <summary>
/// btnCompactSearchIndex control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.LinkButton btnCompactSearchIndex;
/// <summary>
/// btnHostSearchReindex control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.LinkButton btnHostSearchReindex;
/// <summary>
/// FileCrawlerSettingsExtensionControl control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::DotNetNuke.ExtensionPoints.EditPagePanelExtensionControl FileCrawlerSettingsExtensionControl;
/// <summary>
/// plEnableRequestFilters control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::DotNetNuke.UI.UserControls.LabelControl plEnableRequestFilters;
/// <summary>
/// chkEnableRequestFilters control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.CheckBox chkEnableRequestFilters;
/// <summary>
/// requestFilters control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::DotNetNuke.Modules.Admin.Host.RequestFilters requestFilters;
/// <summary>
/// plControlPanel control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::DotNetNuke.UI.UserControls.LabelControl plControlPanel;
/// <summary>
/// cboControlPanel control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::DotNetNuke.Web.UI.WebControls.DnnComboBox cboControlPanel;
/// <summary>
/// plUsersOnline control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::DotNetNuke.UI.UserControls.LabelControl plUsersOnline;
/// <summary>
/// chkUsersOnline control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.CheckBox chkUsersOnline;
/// <summary>
/// plUsersOnlineTime control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::DotNetNuke.UI.UserControls.LabelControl plUsersOnlineTime;
/// <summary>
/// txtUsersOnlineTime control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.TextBox txtUsersOnlineTime;
/// <summary>
/// lblUsersOnlineTime control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.Label lblUsersOnlineTime;
/// <summary>
/// plAutoAccountUnlock control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::DotNetNuke.UI.UserControls.LabelControl plAutoAccountUnlock;
/// <summary>
/// txtAutoAccountUnlock control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.TextBox txtAutoAccountUnlock;
/// <summary>
/// lblAutoAccountUnlock control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.Label lblAutoAccountUnlock;
/// <summary>
/// plFileExtensions control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::DotNetNuke.UI.UserControls.LabelControl plFileExtensions;
/// <summary>
/// txtFileExtensions control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.TextBox txtFileExtensions;
/// <summary>
/// valFileExtensions control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.RegularExpressionValidator valFileExtensions;
/// <summary>
/// plLogBuffer control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::DotNetNuke.UI.UserControls.LabelControl plLogBuffer;
/// <summary>
/// chkLogBuffer control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.CheckBox chkLogBuffer;
/// <summary>
/// plHelpUrl control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::DotNetNuke.UI.UserControls.LabelControl plHelpUrl;
/// <summary>
/// txtHelpURL control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.TextBox txtHelpURL;
/// <summary>
/// plEnableHelp control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::DotNetNuke.UI.UserControls.LabelControl plEnableHelp;
/// <summary>
/// chkEnableHelp control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.CheckBox chkEnableHelp;
/// <summary>
/// plAutoSync control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::DotNetNuke.UI.UserControls.LabelControl plAutoSync;
/// <summary>
/// chkAutoSync control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.CheckBox chkAutoSync;
/// <summary>
/// plEnableContentLocalization control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::DotNetNuke.UI.UserControls.LabelControl plEnableContentLocalization;
/// <summary>
/// chkEnableContentLocalization control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.CheckBox chkEnableContentLocalization;
/// <summary>
/// plDebugMode control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::DotNetNuke.UI.UserControls.LabelControl plDebugMode;
/// <summary>
/// chkDebugMode control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.CheckBox chkDebugMode;
/// <summary>
/// plShowCriticalErrors control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::DotNetNuke.UI.UserControls.LabelControl plShowCriticalErrors;
/// <summary>
/// chkCriticalErrors control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.CheckBox chkCriticalErrors;
/// <summary>
/// plMaxUploadSize control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::DotNetNuke.UI.UserControls.LabelControl plMaxUploadSize;
/// <summary>
/// txtMaxUploadSize control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.TextBox txtMaxUploadSize;
/// <summary>
/// Label1 control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.Label Label1;
/// <summary>
/// rangeUploadSize control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.RangeValidator rangeUploadSize;
/// <summary>
/// plAsyncTimeout control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::DotNetNuke.UI.UserControls.LabelControl plAsyncTimeout;
/// <summary>
/// txtAsyncTimeout control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.TextBox txtAsyncTimeout;
/// <summary>
/// plEnableOAuth control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::DotNetNuke.UI.UserControls.LabelControl plEnableOAuth;
/// <summary>
/// chkEnableOAuth control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.CheckBox chkEnableOAuth;
/// <summary>
/// plLogs control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::DotNetNuke.UI.UserControls.LabelControl plLogs;
/// <summary>
/// ddlLogs control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::DotNetNuke.Web.UI.WebControls.DnnComboBox ddlLogs;
/// <summary>
/// txtLogContents control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.TextBox txtLogContents;
/// <summary>
/// plLog control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::DotNetNuke.UI.UserControls.LabelControl plLog;
/// <summary>
/// cboVersion control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::DotNetNuke.Web.UI.WebControls.DnnComboBox cboVersion;
/// <summary>
/// cmdUpgrade control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::DotNetNuke.UI.WebControls.CommandButton cmdUpgrade;
/// <summary>
/// lblUpgrade control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.Label lblUpgrade;
/// <summary>
/// cmdUpdate control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.LinkButton cmdUpdate;
/// <summary>
/// uploadSkinLink control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.HyperLink uploadSkinLink;
/// <summary>
/// cmdCache control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.LinkButton cmdCache;
/// <summary>
/// cmdRestart control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.LinkButton cmdRestart;
}
}
| 37.43311 | 119 | 0.570773 | [
"MIT"
] | INNO-Software/Dnn.Platform | Website/DesktopModules/Admin/HostSettings/HostSettings.ascx.designer.cs | 89,542 | C# |
using System.Collections.Generic;
using System.Collections.ObjectModel;
namespace FedtWebAPIService.Areas.HelpPage.ModelDescriptions
{
public class EnumTypeModelDescription : ModelDescription
{
public EnumTypeModelDescription()
{
Values = new Collection<EnumValueDescription>();
}
public Collection<EnumValueDescription> Values { get; private set; }
}
} | 27.4 | 76 | 0.712895 | [
"Unlicense"
] | vladandrei228/FedtFitness | FedtWebAPIService/Areas/HelpPage/ModelDescriptions/EnumTypeModelDescription.cs | 411 | C# |
using System;
using System.Collections.Generic;
using SystemsRx.Executor.Handlers;
using SystemsRx.Infrastructure.Dependencies;
using SystemsRx.Infrastructure.Extensions;
using SystemsRx.Infrastructure.Plugins;
using SystemsRx.Systems;
using EcsRx.Plugins.ReactiveSystems.Handlers;
namespace EcsRx.Plugins.ReactiveSystems
{
public class ReactiveSystemsPlugin : ISystemsRxPlugin
{
public string Name => "Reactive Systems";
public Version Version { get; } = new Version("1.0.0");
public void SetupDependencies(IDependencyContainer container)
{
container.Bind<IConventionalSystemHandler, ReactToEntitySystemHandler>();
container.Bind<IConventionalSystemHandler, ReactToGroupSystemHandler>();
container.Bind<IConventionalSystemHandler, ReactToDataSystemHandler>();
container.Bind<IConventionalSystemHandler, SetupSystemHandler>();
container.Bind<IConventionalSystemHandler, TeardownSystemHandler>();
}
public IEnumerable<ISystem> GetSystemsForRegistration(IDependencyContainer container) => new ISystem[0];
}
} | 40.607143 | 112 | 0.746702 | [
"MIT"
] | Fijo/ecsrx | src/EcsRx.Plugins.ReactiveSystems/ReactiveSystemsPlugin.cs | 1,137 | C# |
using System.Runtime.Serialization;
namespace Nest
{
public enum GeoPointFielddataFormat
{
[EnumMember(Value = "array")]
Array,
[EnumMember(Value = "doc_values")]
DocValues,
[EnumMember(Value = "compressed")]
Compressed,
[EnumMember(Value = "disabled")]
Disabled
}
}
| 16.941176 | 36 | 0.701389 | [
"Apache-2.0"
] | RossLieberman/NEST | src/Nest/Modules/Indices/Fielddata/GeoPoint/GeoPointFielddataFormat.cs | 290 | C# |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Text;
using Xamarin.Forms;
namespace Xamarin.CommunityToolkit.UI.Views
{
public class SemanticOrderView : ContentView
{
public static readonly BindableProperty ViewOrderProperty =
BindableProperty.Create(nameof(ViewOrder), typeof(IEnumerable), typeof(SemanticOrderView), new View[0]);
public IEnumerable ViewOrder
{
get => (IEnumerable)GetValue(ViewOrderProperty);
set => SetValue(ViewOrderProperty, value);
}
public SemanticOrderView()
{
}
}
} | 23.375 | 107 | 0.768271 | [
"MIT"
] | 3vilN355/XamarinCommunityToolkit | src/CommunityToolkit/Xamarin.CommunityToolkit/Views/SemanticOrderView/SemanticOrderView.shared.cs | 563 | C# |
using Cake.Core.Diagnostics;
using Moq;
using NUnit.Framework;
namespace Cake.Path.UnitTests.GivenAProcessPath
{
[TestFixture]
public class WhenFetching
{
[Test]
public void ThenTheCorrectPathIsReturned()
{
var environmentWrapper = new Mock<IEnvironmentWrapper>();
environmentWrapper.Setup(x => x.GetEnvironmentVariable("PATH", PathTarget.User, string.Empty)).Returns("us;er");
environmentWrapper.Setup(x => x.GetEnvironmentVariable("PATH", PathTarget.Machine, string.Empty)).Returns("mach;ine");
environmentWrapper.Setup(x => x.GetEnvironmentVariable("PATH", PathTarget.Process, string.Empty)).Returns("pro;cess");
var subject = new PathWrapper(new NullLog(), environmentWrapper.Object);
var result = subject.Get(new PathSettings { Target = PathTarget.Process });
Assert.That(result, Is.EqualTo("pro;cess"));
}
}
} | 39.625 | 130 | 0.669821 | [
"MIT"
] | CleanKludge/Cake | tests/Cake.Path.UnitTests/GivenAProcessPath/WhenFetching.cs | 953 | C# |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.SceneManagement;
public class ExitButtonScript : MonoBehaviour {
float pressed_for = 0f;
public Canvas levelCanvas;
public Button other_button;
bool isPressed = false;
public bool is_pre_level;
string default_scene = "MainApplication_HomeScreen"; // scene to load when the user exit from the pre level
// Use this for initialization
void Start() {
}
// Update is called once per frame
void Update() {
if (isPressed)
{
ExitProtocol();
}
//else if (!isPressed)
//{
// Reset();
//}
}
public void onPointerDownExitButton()
{
isPressed = true;
}
public void onPointerUpExitButton()
{
Reset();
isPressed = false;
}
public void ExitProtocol()
{
Debug.Log("called exit protocol");
pressed_for += Time.deltaTime;
//GetComponentInChildren<Text>().text = pressed_for + "secs";
if (IsPressedForLong() && other_button.GetComponent<ExitButtonScript>().IsPressedForLong())
{
if (!is_pre_level && !levelCanvas.gameObject.activeSelf)
{
ShowLevelScreen();
}
else
{
SceneManager.LoadScene(default_scene);
}
}
}
void ShowLevelScreen()
{
Reload();
}
public void Reset()
{
Debug.Log("time reset for " + name);
pressed_for = 0f;
}
void Reload()
{
//levelCanvas.gameObject.SetActive(true);
SceneManager.LoadScene(SceneManager.GetActiveScene().name);
}
public bool IsPressedForLong()
{
return pressed_for >= 3f;
}
IEnumerator ResetTime()
{
yield return new WaitForSeconds(5f);
pressed_for = 0f;
StartCoroutine(ResetTime());
}
}
| 23.388889 | 123 | 0.544893 | [
"MIT"
] | surbhit21/Autism-Games | Assets/Scripts/ShareAmongAllGames/ExitButtonScript.cs | 2,107 | C# |
using MinecraftTypes;
namespace SmartBlocks.Entities.Particles;
public class Sneeze : Particle
{
public override VarInt Id => 48;
public override Identifier Name => "sneeze";
} | 18.8 | 48 | 0.739362 | [
"MIT"
] | CopperPenguin96/SmartBlocks | SmartBlocks/Entities/Particles/Sneeze.cs | 190 | C# |
namespace LearningCenter.Web.Controllers
{
using LearningCenter.Data.Models;
using LearningCenter.Services.Data;
using LearningCenter.Web.ViewModels.Account;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Mvc;
public class AccountController : Controller
{
private readonly IAccountsService accountsService;
private readonly UserManager<ApplicationUser> userManager;
private readonly ICoursesService coursesService;
public AccountController(IAccountsService accountsService, UserManager<ApplicationUser> userManager, ICoursesService coursesService)
{
this.accountsService = accountsService;
this.userManager = userManager;
this.coursesService = coursesService;
}
[Authorize]
public IActionResult Index(string id, int page = 1)
{
const int itemsPerPage = 12;
var lecturerId = id == null ? this.userManager.GetUserId(this.User) : id;
var viewModel = this.accountsService.GetLecturerById<ProfileViewModel>(lecturerId);
viewModel.PageNumber = page;
viewModel.CoursesCount = this.coursesService.GetCountByAuthorId(id);
viewModel.ItemsPerPage = itemsPerPage;
return this.View(viewModel);
}
}
}
| 38.5 | 140 | 0.691198 | [
"MIT"
] | NikolayStefanov/Learning-Center | Web/LearningCenter.Web/Controllers/AccountController.cs | 1,388 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace AutoUpdateTool
{
/// <summary>
/// 项目信息
/// </summary>
public class RepositoryInfo
{
private const string UserName="li-zheng-hao";
private const string ProjectName="StickyNotes";
public static string RepositoryAddr = $"https://api.github.com/repos/li-zheng-hao/StickyNotes/releases/latest";
}
}
| 22.52381 | 119 | 0.689218 | [
"MIT"
] | dorisoy/StickyNotes | AutoUpdateTool/RepositoryInfo.cs | 483 | C# |
// *********************************************************************************
// Copyright @2021 Marcus Technical Services, Inc.
// <copyright
// file=Tests.cs
// company="Marcus Technical Services, Inc.">
// </copyright>
//
// MIT License
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
// *********************************************************************************
namespace ResponsiveTasks.UnitTests
{
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Reflection;
using System.Threading;
using System.Threading.Tasks;
using Bogus;
using Com.MarcusTS.ResponsiveTasks;
using Com.MarcusTS.SharedUtils.Interfaces;
using Com.MarcusTS.SharedUtils.Utils;
using Microsoft.VisualStudio.TestTools.UnitTesting;
[TestClass]
public class Tests
{
private const string DEFAULT_TEST_PREFIX = "Test";
private const int MAX_TEST_TASKS = 5;
private const int SOME_TIME = 250;
private const int A_LONG_TIME = SOME_TIME * 4;
public static readonly TimeSpan MAX_DEFAULT_TIME_TO_WAIT = TimeSpan.FromMilliseconds(2500);
public static readonly TimeSpan MIN_DEFAULT_TIME_TO_WAIT = TimeSpan.FromMilliseconds(100);
private static readonly Faker<object> _faker = new();
private static readonly Random _random = new((int) DateTime.Now.Ticks & 0x0000FFFF);
static Tests()
{
VerifyInterfaceCoverage<IResponsiveTasks, Tests>();
}
[TestMethod]
public Task TestAddIfNotAlreadyThere()
{
// Create generic responsive tasks
var respTask = new ResponsiveTasks();
// Verify that it has no hosts or members
Assert.IsTrue(respTask.IsAnEmptyList(),
"Newly created responsive tasks has unknown members for no apparent reason");
// Add ourselves and a fake handler
respTask.AddIfNotAlreadyThere(this, FakeResponsiveTasksHandler);
Assert.IsTrue(respTask.IsNotAnEmptyList() && (respTask.Count == 1),
"Added a single member to created responsive tasks and ended up with a count of ->" +
(respTask.IsAnEmptyList() ? 0 : respTask.Count));
return Task.CompletedTask;
}
[TestMethod]
public async Task TestAwaitAllTasksCollectively()
{
await AwaitAllHandlersUsingRandomTiming(HowToRun.AwaitAllCollectively, "collectively");
await AwaitAllHandlersUsingTimeoutMilliseconds(HowToRun.AwaitAllCollectively, "collectively");
}
[TestMethod]
public async Task TestAwaitAllTasksConsecutively()
{
await AwaitAllHandlersUsingRandomTiming(HowToRun.AwaitAllConsecutively_IgnoreFailures, "consecutively");
await AwaitAllHandlersUsingTimeoutMilliseconds(HowToRun.AwaitAllConsecutively_IgnoreFailures, "consecutively");
}
[TestMethod]
public async Task TestAwaitAllTasksSafelyFromVoid()
{
await AwaitAllHandlersUsingRandomTiming(HowToRun.AwaitAllSafelyFromVoid, "safely from void");
await AwaitAllHandlersUsingTimeoutMilliseconds(HowToRun.AwaitAllSafelyFromVoid, "safely from void");
}
[TestMethod]
public async Task TestCustomErrorHandler()
{
IResponsiveTasksThatOverridesIssueResponsiveError customTasks =
new ResponsiveTasksThatOverridesIssueResponsiveError();
// Do nothing
customTasks.AddIfNotAlreadyThere(this, FakeResponsiveTasksHandler);
ICustomErrorHandler customErrorHandler = new CustomErrorHandler();
customTasks.CustomErrorHandler = customErrorHandler;
customTasks.ParamsErrorLevel = ParamsErrorLevels.Custom;
// Force an error by sending in a param when the originally requested count is 0.
customTasks.RunAllTasksInParallelFromVoid(_faker.Generate());
await Task.Delay(SOME_TIME);
Assert.IsTrue(customErrorHandler.ReportedErrorLevel != ParamsErrorLevels.None,
"Custom error handler failed to receive a params error");
}
[TestMethod]
public async Task TestParams()
{
// Test default params (empty)
await TestParamDict(default).WithoutChangingContext();
// Test a few random params
await TestParamDict(Anything(4)).WithoutChangingContext();
// PRIVATE METHODS
async Task TestParamDict(object[] paramValues)
{
IResponsiveTasks task = default;
try
{
// Not using indexes for these
task = new ResponsiveTasks();
}
catch (Exception ex)
{
Assert.Fail("tried to create a task with params ->" + paramValues + "<- but caught an exception ->" +
ex.Message + "<-");
}
// ELSE
task.AddIfNotAlreadyThere(this, dict =>
{
Debug.Assert(dict.Values.ToArray().IsSameAs(paramValues),
"Raised parameters do not match those passed in");
return Task.CompletedTask;
});
// See if the raised Task provides the same params
await task.AwaitAllTasksConsecutively(paramValues).WithoutChangingContext();
}
}
/// <summary>
/// Tests how mismatched param counts get reported. Also verifies that the passed params count matches the
/// originally requested param count.
/// </summary>
/// <returns></returns>
[TestMethod]
public async Task TestParamsErrorLevel()
{
const int MAX_TEST_PARAM_COUNTS = 5;
for (var requestedParamCount = 0; requestedParamCount < MAX_TEST_PARAM_COUNTS; requestedParamCount++)
{
// NOTE Random never hits the upper bound, so increasing by 1
var publishedParamCount = _random.Next(0, MAX_TEST_PARAM_COUNTS + 1);
foreach (ParamsErrorLevels errorLevel in Enum.GetValues(typeof(ParamsErrorLevels)))
{
IResponsiveTasksThatOverridesIssueResponsiveError tasks =
new ResponsiveTasksThatOverridesIssueResponsiveError(requestedParamCount)
{ ParamsErrorLevel = errorLevel };
// The task doesn't do anything
tasks.AddIfNotAlreadyThere(this, FakeResponsiveTasksHandler);
var publishedParams = Anything(publishedParamCount);
// Run quick and disconneced so we can analyze the results immediately
tasks.RunAllTasksInParallelFromVoid(publishedParams);
await Task.Delay(SOME_TIME);
if (requestedParamCount == publishedParamCount)
{
// No error expected
Assert.IsTrue(tasks.ReportedErrorLevel == ParamsErrorLevels.None,
"Param counts matched but got a param error ->" +
tasks.ReportedErrorLevel +
"<- and string =>" +
tasks.ReportedErrorStr +
"<-");
}
else
{
// Error expected
Assert.IsTrue(tasks.ReportedErrorLevel == errorLevel,
"Params mis-matched. Expecting error level =>" +
errorLevel +
"<- but got =>" +
tasks.ReportedErrorLevel +
"<-");
}
}
}
}
[TestMethod]
public Task TestRemoveIfThere()
{
// Create generic responsive tasks
var respTask = new ResponsiveTasks();
respTask.AddIfNotAlreadyThere(this, FakeResponsiveTasksHandler);
Assert.IsTrue(respTask.IsNotAnEmptyList() && (respTask.Count == 1),
"Added a single member to created responsive tasks and ended up with a count of ->" +
(respTask.IsAnEmptyList() ? 0 : respTask.Count));
respTask.RemoveIfThere(this, FakeResponsiveTasksHandler);
Assert.IsTrue(respTask.IsAnEmptyList(), "Could not remove a task handler");
return Task.CompletedTask;
}
/// <remarks>Can only verify that all tasks were started -- this approach des not wait for anything to conclude</remarks>
[TestMethod]
public async Task TestRunAllTasksInParallelFromVoid()
{
var task = new ResponsiveTasks();
AddHandlersAndSetAllAreRunning<IHandlerWithExpiration, HandlerWithExpiration>(task);
task.RunAllTasksInParallelFromVoid();
// Verify that all tasks are still running
var handlers = task.OfType<IHandlerWithExpiration>().ToArray();
if (handlers.IsAnEmptyList())
{
Debug.WriteLine("No handlers of type ->" + nameof(IHandlerWithExpiration) + "<-");
return;
}
foreach (var handler in handlers)
{
Assert.IsTrue(handler.IsRunning.IsTrue(), "Handler has stopped running before cancellation");
}
// ELSE ready to start this test
// Cancel all tasks
foreach (var handler in handlers)
{
handler.CancelTokenSource.Cancel();
}
await Task.Delay(A_LONG_TIME);
// Verify that no task is still running
foreach (var handler in handlers)
{
Assert.IsTrue(handler.IsRunning.IsFalse(), "Handler running after cancellation");
}
}
[TestMethod]
public Task TestRunAllTasksUsingDefaults()
{
// HACK Redundant
return TestRunHowAndRunAllTasksUsingDefaults();
}
[TestMethod]
public Task TestRunHow()
{
// HACK Redundant
return TestRunHowAndRunAllTasksUsingDefaults();
}
[TestMethod]
public async Task TestTaskErrorBroadcaster()
{
IResponsiveTasksThatOverridesIssueResponsiveError customTasks =
new ResponsiveTasksThatOverridesIssueResponsiveError();
// Throw an error deliberately
customTasks.AddIfNotAlreadyThere(this, _ => throw new Exception());
ICustomErrorBroadcaster customErrorBroadcaster = new CustomErrorBroadcaster();
customTasks.TaskErrorBroadcaster = customErrorBroadcaster;
// The task will run and throw its own error
customTasks.RunAllTasksInParallelFromVoid(_faker.Generate());
await Task.Delay(SOME_TIME);
Assert.IsTrue(customErrorBroadcaster.ReportedErrorLevel != ParamsErrorLevels.None,
"Custom task broadcaster failed to report a task error");
}
/// <remarks>
/// Tests that these got set as expected. Actual timeout tests -- verifying tha the timeout occurs -- occur
/// throughout this set of unit tests. The number of milliseconds is not critical enough to warrant a special test
/// for the count.
/// </remarks>
/// <returns></returns>
[TestMethod]
public Task TestTimeoutMilliseconds()
{
const int MAX_TESTS = 5;
var tasks = new ResponsiveTasks();
for (var idx = 0; idx < MAX_TESTS; idx++)
{
var numberToTest = _random.Next();
tasks.TimeoutMilliseconds = numberToTest;
Assert.IsTrue(tasks.TimeoutMilliseconds == numberToTest, "Assigned time-out milliseconds got lost");
}
return Task.CompletedTask;
}
[TestMethod]
public Task TestUnsubscribeHost()
{
var tasks = new ResponsiveTasks();
// Add the fake handler
tasks.AddIfNotAlreadyThere(this, FakeResponsiveTasksHandler);
Assert.IsTrue(tasks.IsNotAnEmptyList(), "Failed to add a task in preparation for a unit test");
// Remove ourselves globally
tasks.UnsubscribeHost(this);
Assert.IsTrue(tasks.IsAnEmptyList(),
"Failed to remove a task handler using the global call to " +
nameof(ResponsiveTasks.UnsubscribeHost));
return Task.CompletedTask;
}
private static void VerifyInterfaceCoverage<InterfaceT, TestTypeT>(string testPrefix = DEFAULT_TEST_PREFIX)
{
var BINDING_FLAGS = BindingFlags.Public | BindingFlags.FlattenHierarchy | BindingFlags.Instance;
var testableInterfaceMethods =
typeof(InterfaceT).GetMethods(BINDING_FLAGS).Where(method => !method.IsSpecialName);
var testableInterfaceProperties = typeof(InterfaceT).GetProperties(BINDING_FLAGS);
var existingUnitTestNames = typeof(TestTypeT).GetMembers(BINDING_FLAGS)
.Where(propInfo => propInfo.Name.StartsWith(DEFAULT_TEST_PREFIX))
.Select(propInfo => propInfo.Name).ToArray();
foreach (var testableInterfaceMethod in testableInterfaceMethods)
{
if (!existingUnitTestNames.Contains(DEFAULT_TEST_PREFIX + testableInterfaceMethod.Name))
{
Debug.WriteLine(nameof(Tests) + ": Interface ->" + nameof(InterfaceT) + "<- method ->" +
testableInterfaceMethod.Name + "<- is not unit tested !!! ");
}
}
foreach (var testableInterfaceProperty in testableInterfaceProperties)
{
var baseName = testableInterfaceProperty.Name.Replace("get_", "").Replace("set_", "");
if (!existingUnitTestNames.Contains(DEFAULT_TEST_PREFIX + baseName))
{
Debug.WriteLine(nameof(Tests) + ": Interface ->" + nameof(InterfaceT) + "<- property ->" +
baseName + "<- is not unit tested !!! ");
}
}
}
private void AddHandlersAndSetAllAreRunning<InterfaceT, ClassT>(IResponsiveTasks targetTask, int count = MAX_TEST_TASKS)
where InterfaceT : IHandlerWithExpiration
where ClassT : HandlerWithExpiration, InterfaceT
{
for (var idx = 0; idx < count; idx++)
{
InterfaceT handlerHost = Activator.CreateInstance<ClassT>();
targetTask.AddIfNotAlreadyThere(this, paramDict => handlerHost.HandlerThatExpires(paramDict));
}
}
private void AddHandlersAndSetFixedTimeout(IResponsiveTasks targetTask, int timeToWaitMillisecdonds, int count = MAX_TEST_TASKS)
{
for (var idx = 0; idx < count; idx++)
{
IHandlerWithExpiration handlerHost = new HandlerWithExpiration()
{ TimeToWait = TimeSpan.FromMilliseconds(timeToWaitMillisecdonds) };
targetTask.AddIfNotAlreadyThere(this, paramDict => handlerHost.HandlerThatExpires(paramDict));
}
}
private object[] Anything(int count)
{
var retList = new List<object>();
for (var idx = 0; idx < count; idx++)
{
retList.Add(_faker.Generate());
}
return retList.ToArray<object>();
}
private async Task RunTaskForAllHandlers(IResponsiveTasks task, HowToRun runHow)
{
switch (runHow)
{
case HowToRun.AwaitAllConsecutively_IgnoreFailures:
case HowToRun.AwaitAllConsecutively_StopOnFirstFailure:
await task.AwaitAllTasksConsecutively(default);
break;
case HowToRun.AwaitAllCollectively:
await task.AwaitAllTasksCollectively(default);
break;
case HowToRun.AwaitAllSafelyFromVoid:
task.AwaitAllTasksSafelyFromVoid(default);
break;
default:
Debug.WriteLine(nameof(RunTaskForAllHandlers) + ": illegal run request ->" + runHow + "<-");
break;
}
}
private async Task AwaitAllHandlersUsingTimeoutMilliseconds(HowToRun runHow, string errorText)
{
var task = new ResponsiveTasks();
// Set this very early
task.TimeoutMilliseconds = 100;
// Set this after the timeout
AddHandlersAndSetFixedTimeout(task, task.TimeoutMilliseconds * 10);
await RunTaskForAllHandlers(task, runHow);
// Wait for the pre-set timeout on the parent task
// The handlers will continue running but should stop when they hit this timeout
await Task.Delay(task.TimeoutMilliseconds).WithoutChangingContext();
// Verify that all handlers have completed
foreach (var handler in task.OfType<IHandlerWithExpiration>())
{
Assert.IsTrue(handler.IsRunning.IsFalse(),
"Timed out all handlers " + errorText + " but afterwards at least one handler was still running");
}
}
private async Task AwaitAllHandlersUsingRandomTiming(HowToRun runHow, string errorText)
{
var task = new ResponsiveTasks();
AddHandlersAndSetAllAreRunning<IHandlerWithRandomExpiration, HandlerWithRandomExpiration>(task);
await RunTaskForAllHandlers(task, runHow);
// Verify that all handlers have completed
foreach (var handler in task.OfType<IHandlerWithExpiration>())
{
Assert.IsTrue(handler.IsRunning.IsFalse(),
"Awaited completion of all handlers " + errorText + " but afterwards at least one handler was still running");
}
}
/*
[TestMethod]
public async Task TestIsRunning()
{
var task = new ResponsiveTasks();
IHandlerThatWaitsForCancellation cancellableTask = new HandlerThatWaitsForCancellation();
task.AddIfNotAlreadyThere(this, cancellableTask.TaskThatWaitsForCancellation);
// If run parallel, sets IsRunning off immediately. If awaited, hangs because we are running but stuck inside
// the await.
???
await task.AwaitAllTasksConsecutively(default).WithoutChangingContext();
await Task.Delay(A_LONG_TIME).WithoutChangingContext();
Assert.IsTrue(task.IsRunning.IsTrue(), "Task was started but IsRunning is false");
cancellableTask.CancelTokenSource.Cancel();
await Task.Delay(A_LONG_TIME).WithoutChangingContext();
Assert.IsTrue(task.IsRunning.IsFalse(), "Cancelling task failed to switch IsRunning off");
}
*/
private Task FakeResponsiveTasksHandler(IResponsiveTaskParams paramDict)
{
// Does nothing
return Task.CompletedTask;
}
/// <remarks>Two unit tests require the same basic test.</remarks>
private async Task TestRunHowAndRunAllTasksUsingDefaults()
{
IResponsiveTasksThatOverridesRunAllTasksUsingDefaults tasks =
new ResponsiveTasksThatOverridesRunAllTasksUsingDefaults();
// Do nothing
tasks.AddIfNotAlreadyThere(this, FakeResponsiveTasksHandler);
foreach (HowToRun howToRun in Enum.GetValues(typeof(HowToRun)))
{
tasks.LastRunHow = HowToRun.NotSet;
tasks.RunHow = howToRun;
await tasks.RunAllTasksUsingDefaults().WithoutChangingContext();
Assert.IsTrue(tasks.LastRunHow == howToRun,
"Ran tasks using default with how to run ->" + howToRun + "<- but ran with ->" +
tasks.LastRunHow + "<-");
}
}
private interface ICustomErrorBroadcaster : IIssueResponsiveErrors, IReportErrorStatus
{
}
private interface ICustomErrorHandler : ICustomResponsiveParameterErrorHandler, IReportErrorStatus
{
}
private interface IHandlerWithExpiration : ICanRun
{
// Can wait for this time
TimeSpan TimeToWait { get; set; }
// Can be canceled
CancellationTokenSource CancelTokenSource { get; }
Task HandlerThatExpires(IResponsiveTaskParams paramDict);
}
private interface IHandlerWithRandomExpiration : IHandlerWithExpiration
{
}
private interface IReportErrorStatus
{
ParamsErrorLevels ReportedErrorLevel { get; set; }
string ReportedErrorStr { get; set; }
}
private interface IResponsiveTasksThatOverridesIssueResponsiveError : IReportErrorStatus, IResponsiveTasks
{
}
private interface IResponsiveTasksThatOverridesRunAllTasksUsingDefaults : IResponsiveTasks
{
HowToRun LastRunHow { get; set; }
}
private class CustomErrorBroadcaster : ICustomErrorBroadcaster
{
public ParamsErrorLevels ParamsErrorLevel { get; set; } = ParamsErrorLevels.DebugWriteLine;
public ParamsErrorLevels ReportedErrorLevel { get; set; } = ParamsErrorLevels.None;
public string ReportedErrorStr { get; set; }
public void IssueResponsiveError(ParamsErrorLevels paramsErrorLevel, string errorStr)
{
ReportedErrorLevel = paramsErrorLevel;
ReportedErrorStr = errorStr;
}
}
private class CustomErrorHandler : ICustomErrorHandler
{
public ParamsErrorLevels ReportedErrorLevel { get; set; } = ParamsErrorLevels.None;
public string ReportedErrorStr { get; set; }
public Task HandleErrorMessage(ParamsErrorLevels paramsErrorLevel, string errorStr)
{
ReportedErrorLevel = paramsErrorLevel;
ReportedErrorStr = errorStr;
return Task.CompletedTask;
}
}
private class HandlerWithExpiration : IHandlerWithExpiration
{
public IThreadSafeAccessor IsRunning { get; } = new ThreadSafeAccessor();
// Wait endlessly unless told otherwise
public TimeSpan TimeToWait { get; set; } = TimeSpan.MaxValue;
// Token can be used when TimeToWait is at its max
public CancellationTokenSource CancelTokenSource { get; } = new();
/// <remarks>Must match the signature of the <see cref="ResponsiveTaskBroadcastDelegate" />.</remarks>
public async Task HandlerThatExpires(IResponsiveTaskParams paramDict)
{
var endDateTime = DateTime.Now + TimeToWait;
IsRunning.SetTrue();
while ((DateTime.Now < endDateTime) && !CancelTokenSource.IsCancellationRequested)
{
await Task.Delay(SOME_TIME).WithoutChangingContext();
}
IsRunning.SetFalse();
}
}
private class HandlerWithRandomExpiration : HandlerWithExpiration, IHandlerWithRandomExpiration
{
public HandlerWithRandomExpiration()
{
TimeToWait =
TimeSpan.FromMilliseconds(_random.Next(MIN_DEFAULT_TIME_TO_WAIT.Milliseconds,
MAX_DEFAULT_TIME_TO_WAIT.Milliseconds + 1));
}
}
private class ResponsiveTasksThatOverridesIssueResponsiveError : ResponsiveTasks,
IResponsiveTasksThatOverridesIssueResponsiveError
{
public ResponsiveTasksThatOverridesIssueResponsiveError(params object[] paramKeys)
: base(paramKeys)
{
}
public ResponsiveTasksThatOverridesIssueResponsiveError(int paramCount = 0)
: base(paramCount)
{
}
public ParamsErrorLevels ReportedErrorLevel { get; set; } = ParamsErrorLevels.None;
public string ReportedErrorStr { get; set; }
public override void IssueResponsiveError(ParamsErrorLevels paramsErrorLevel, string errorStr)
{
ReportedErrorLevel = paramsErrorLevel;
ReportedErrorStr = errorStr;
// Allow custom to get through (otherwise, can't be unit tested)
if (ParamsErrorLevel == ParamsErrorLevels.Custom)
{
base.IssueResponsiveError(paramsErrorLevel, errorStr);
}
}
}
private class ResponsiveTasksThatOverridesRunAllTasksUsingDefaults : ResponsiveTasks,
IResponsiveTasksThatOverridesRunAllTasksUsingDefaults
{
public ResponsiveTasksThatOverridesRunAllTasksUsingDefaults(params object[] paramKeys)
: base(paramKeys)
{
}
public ResponsiveTasksThatOverridesRunAllTasksUsingDefaults(int paramCount = 0)
: base(paramCount)
{
}
public HowToRun LastRunHow { get; set; } = HowToRun.NotSet;
protected override Task<bool> RunAllTasksUsingDefaults_Internal(HowToRun runHow, params object[] paramValues)
{
LastRunHow = runHow;
return Task.FromResult(true);
}
}
}
} | 38.54848 | 136 | 0.612907 | [
"MIT"
] | marcusts/ResponsiveTasks.UnitTests | Tests.cs | 26,637 | C# |
using AutoMapper;
using Pds.Core.Utils.Helpers;
using Pds.Shared.Audit.Repository.Interfaces;
using Pds.Shared.Audit.Services.Interfaces;
using System;
using System.Threading.Tasks;
using DataModel = Pds.Shared.Audit.Repository.DataModels;
using ServiceModel = Pds.Shared.Audit.Services.Models;
namespace Pds.Shared.Audit.Services.Implementations
{
/// <summary>
/// Audit service.
/// </summary>
public class AuditService : IAuditService
{
private readonly IUnitOfWork _unitOfWork;
private readonly IMapper _mapper;
/// <summary>
/// Initializes a new instance of the <see cref="AuditService"/> class.
/// </summary>
/// <param name="unitOfWork">Unit of work.</param>
/// <param name="mapper">Auto mapper.</param>
public AuditService(IUnitOfWork unitOfWork, IMapper mapper)
{
_unitOfWork = unitOfWork;
_mapper = mapper;
}
/// <summary>
/// Create new Audit repository model and pass on to the repository.
/// </summary>
/// <param name="request">Audit entity.</param>
/// <returns>Returns void.</returns>
public async Task CreateAsync(ServiceModel.Audit request)
{
It.IsNull(request)
.AsGuard<ArgumentNullException>();
var dmAudit = _mapper.Map<ServiceModel.Audit, DataModel.Audit>(request);
dmAudit.CreatedAt = DateTime.UtcNow;
dmAudit.User = dmAudit.User ?? "AuditUser";
await _unitOfWork.AuditRepository.AddAsync(dmAudit);
await _unitOfWork.CommitAsync();
}
}
} | 34.375 | 84 | 0.632121 | [
"MIT"
] | SkillsFundingAgency/pds-shared-audit-api | Pds.Shared.Audit/Pds.Shared.Audit.Services/Implementations/AuditService.cs | 1,652 | C# |
using System;
using System.IO;
using System.Net;
using System.Text.Json;
namespace SpotiSharp
{
public static class DependencyHelpers
{
public static bool IsFFmpegPresent()
{
var files = Directory.GetFiles(Config.Properties.FFmpegPath, "*", SearchOption.TopDirectoryOnly);
foreach (var file in files)
{
if (Path.GetFileNameWithoutExtension(file).Equals("ffmpeg", StringComparison.InvariantCultureIgnoreCase))
return true;
}
return false;
}
public static string getFFmpegDownloadUrl(string input = "https://ffbinaries.com/api/v1/version/latest")
{
var result = new WebClient().DownloadString(input);
var parsedDocument = JsonDocument.Parse(result);
string architecture;
if (!Utilities.IsLinux)
architecture = "windows-64";
else
architecture = "linux-64";
var str = parsedDocument.RootElement.GetProperty("bin")
.GetProperty(architecture)
.GetProperty("ffmpeg")
.GetString();
parsedDocument.Dispose();
return str;
}
}
}
| 30.609756 | 121 | 0.575299 | [
"MIT"
] | L0um15/SpotiSharp | DependencyHelpers.cs | 1,257 | C# |
using System;
using Semmle.Util.Logging;
using System.Linq;
using Newtonsoft.Json.Linq;
using System.Collections.Generic;
using System.IO;
using Semmle.Util;
namespace Semmle.Autobuild
{
/// <summary>
/// A build rule where the build command is of the form "dotnet build".
/// Currently unused because the tracer does not work with dotnet.
/// </summary>
class DotNetRule : IBuildRule
{
public BuildScript Analyse(Autobuilder builder, bool auto)
{
if (!builder.ProjectsOrSolutionsToBuild.Any())
return BuildScript.Failure;
if (auto)
{
var notDotNetProject = builder.ProjectsOrSolutionsToBuild.
SelectMany(p => Enumerators.Singleton(p).Concat(p.IncludedProjects)).
OfType<Project>().
FirstOrDefault(p => !p.DotNetProject);
if (notDotNetProject != null)
{
builder.Log(Severity.Info, "Not using .NET Core because of incompatible project {0}", notDotNetProject);
return BuildScript.Failure;
}
builder.Log(Severity.Info, "Attempting to build using .NET Core");
}
return WithDotNet(builder, dotNet =>
{
var ret = GetInfoCommand(builder.Actions, dotNet);
foreach (var projectOrSolution in builder.ProjectsOrSolutionsToBuild)
{
var cleanCommand = GetCleanCommand(builder.Actions, dotNet);
cleanCommand.QuoteArgument(projectOrSolution.FullPath);
var clean = cleanCommand.Script;
var restoreCommand = GetRestoreCommand(builder.Actions, dotNet);
restoreCommand.QuoteArgument(projectOrSolution.FullPath);
var restore = restoreCommand.Script;
var buildCommand = GetBuildCommand(builder, dotNet);
buildCommand.QuoteArgument(projectOrSolution.FullPath);
var build = buildCommand.Script;
ret &= clean & BuildScript.Try(restore) & build;
}
return ret;
});
}
/// <summary>
/// Returns a script that attempts to download relevant version(s) of the
/// .NET Core SDK, followed by running the script generated by <paramref name="f"/>.
///
/// The first element <code>DotNetPath</code> of the argument to <paramref name="f"/>
/// is the path where .NET Core was installed, and the second element <code>Environment</code>
/// is any additional required environment variables. The tuple argument is <code>null</code>
/// when the installation failed.
/// </summary>
public static BuildScript WithDotNet(Autobuilder builder, Func<(string DotNetPath, IDictionary<string, string> Environment)?, BuildScript> f)
{
var installDir = builder.Actions.PathCombine(builder.Options.RootDirectory, ".dotnet");
var installScript = DownloadDotNet(builder, installDir);
return BuildScript.Bind(installScript, installed =>
{
if (installed == 0)
{
// The installation succeeded, so use the newly installed .NET Core
var path = builder.Actions.GetEnvironmentVariable("PATH");
var delim = builder.Actions.IsWindows() ? ";" : ":";
var env = new Dictionary<string, string>{
{ "DOTNET_MULTILEVEL_LOOKUP", "false" }, // prevent look up of other .NET Core SDKs
{ "DOTNET_SKIP_FIRST_TIME_EXPERIENCE", "true" },
{ "PATH", installDir + delim + path }
};
return f((installDir, env));
}
return f(null);
});
}
/// <summary>
/// Returns a script for downloading relevant versions of the
/// .NET Core SDK. The SDK(s) will be installed at <code>installDir</code>
/// (provided that the script succeeds).
/// </summary>
static BuildScript DownloadDotNet(Autobuilder builder, string installDir)
{
if (!string.IsNullOrEmpty(builder.Options.DotNetVersion))
// Specific version supplied in configuration: always use that
return DownloadDotNetVersion(builder, installDir, builder.Options.DotNetVersion);
// Download versions mentioned in `global.json` files
// See https://docs.microsoft.com/en-us/dotnet/core/tools/global-json
var installScript = BuildScript.Success;
var validGlobalJson = false;
foreach (var path in builder.Paths.Select(p => p.Item1).Where(p => p.EndsWith("global.json", StringComparison.Ordinal)))
{
string version;
try
{
var o = JObject.Parse(File.ReadAllText(path));
version = (string)o["sdk"]["version"];
}
catch // lgtm[cs/catch-of-all-exceptions]
{
// not a valid global.json file
continue;
}
installScript &= DownloadDotNetVersion(builder, installDir, version);
validGlobalJson = true;
}
return validGlobalJson ? installScript : BuildScript.Failure;
}
/// <summary>
/// Returns a script for downloading a specific .NET Core SDK version, if the
/// version is not already installed.
///
/// See https://docs.microsoft.com/en-us/dotnet/core/tools/dotnet-install-script.
/// </summary>
static BuildScript DownloadDotNetVersion(Autobuilder builder, string path, string version)
{
return BuildScript.Bind(GetInstalledSdksScript(builder.Actions), (sdks, sdksRet) =>
{
if (sdksRet == 0 && sdks.Count() == 1 && sdks[0].StartsWith(version + " ", StringComparison.Ordinal))
// The requested SDK is already installed (and no other SDKs are installed), so
// no need to reinstall
return BuildScript.Failure;
builder.Log(Severity.Info, "Attempting to download .NET Core {0}", version);
if (builder.Actions.IsWindows())
{
var psScript = @"param([string]$Version, [string]$InstallDir)
add-type @""
using System.Net;
using System.Security.Cryptography.X509Certificates;
public class TrustAllCertsPolicy : ICertificatePolicy
{
public bool CheckValidationResult(ServicePoint srvPoint, X509Certificate certificate, WebRequest request, int certificateProblem)
{
return true;
}
}
""@
$AllProtocols = [System.Net.SecurityProtocolType]'Ssl3,Tls,Tls11,Tls12'
[System.Net.ServicePointManager]::SecurityProtocol = $AllProtocols
[System.Net.ServicePointManager]::CertificatePolicy = New-Object TrustAllCertsPolicy
$Script = Invoke-WebRequest -useb 'https://dot.net/v1/dotnet-install.ps1'
$arguments = @{
Channel = 'release'
Version = $Version
InstallDir = $InstallDir
}
$ScriptBlock = [scriptblock]::create("".{$($Script)} $(&{$args} @arguments)"")
Invoke-Command -ScriptBlock $ScriptBlock";
var psScriptFile = builder.Actions.PathCombine(builder.Options.RootDirectory, "install-dotnet.ps1");
builder.Actions.WriteAllText(psScriptFile, psScript);
var install = new CommandBuilder(builder.Actions).
RunCommand("powershell").
Argument("-NoProfile").
Argument("-ExecutionPolicy").
Argument("unrestricted").
Argument("-file").
Argument(psScriptFile).
Argument("-Version").
Argument(version).
Argument("-InstallDir").
Argument(path);
var removeScript = new CommandBuilder(builder.Actions).
RunCommand("del").
Argument(psScriptFile);
return install.Script & BuildScript.Try(removeScript.Script);
}
else
{
var curl = new CommandBuilder(builder.Actions).
RunCommand("curl").
Argument("-sO").
Argument("https://dot.net/v1/dotnet-install.sh");
var chmod = new CommandBuilder(builder.Actions).
RunCommand("chmod").
Argument("u+x").
Argument("dotnet-install.sh");
var install = new CommandBuilder(builder.Actions).
RunCommand("./dotnet-install.sh").
Argument("--channel").
Argument("release").
Argument("--version").
Argument(version).
Argument("--install-dir").
Argument(path);
var removeScript = new CommandBuilder(builder.Actions).
RunCommand("rm").
Argument("dotnet-install.sh");
return curl.Script & chmod.Script & install.Script & BuildScript.Try(removeScript.Script);
}
});
}
static BuildScript GetInstalledSdksScript(IBuildActions actions)
{
var listSdks = new CommandBuilder(actions).
RunCommand("dotnet").
Argument("--list-sdks");
return listSdks.Script;
}
static string DotNetCommand(IBuildActions actions, string dotNetPath) =>
dotNetPath != null ? actions.PathCombine(dotNetPath, "dotnet") : "dotnet";
BuildScript GetInfoCommand(IBuildActions actions, (string DotNetPath, IDictionary<string, string> Environment)? arg)
{
var info = new CommandBuilder(actions, null, arg?.Environment).
RunCommand(DotNetCommand(actions, arg?.DotNetPath)).
Argument("--info");
return info.Script;
}
CommandBuilder GetCleanCommand(IBuildActions actions, (string DotNetPath, IDictionary<string, string> Environment)? arg)
{
var clean = new CommandBuilder(actions, null, arg?.Environment).
RunCommand(DotNetCommand(actions, arg?.DotNetPath)).
Argument("clean");
return clean;
}
CommandBuilder GetRestoreCommand(IBuildActions actions, (string DotNetPath, IDictionary<string, string> Environment)? arg)
{
var restore = new CommandBuilder(actions, null, arg?.Environment).
RunCommand(DotNetCommand(actions, arg?.DotNetPath)).
Argument("restore");
return restore;
}
CommandBuilder GetBuildCommand(Autobuilder builder, (string DotNetPath, IDictionary<string, string> Environment)? arg)
{
var build = new CommandBuilder(builder.Actions, null, arg?.Environment);
return builder.MaybeIndex(build, DotNetCommand(builder.Actions, arg?.DotNetPath)).
Argument("build").
Argument("--no-incremental").
Argument("/p:UseSharedCompilation=false").
Argument(builder.Options.DotNetArguments);
}
}
}
| 44.468635 | 149 | 0.547423 | [
"ECL-2.0",
"Apache-2.0"
] | educativ/ql | csharp/autobuilder/Semmle.Autobuild/DotNetRule.cs | 12,051 | C# |
using System;
using System.Collections.Generic;
using System.Configuration;
using System.IO;
using System.Net;
using System.Runtime.Serialization;
using System.Web;
using Funq;
using ServiceStack.Caching;
using ServiceStack.Configuration;
using ServiceStack.Host;
using ServiceStack.IO;
using ServiceStack.Metadata;
using ServiceStack.MiniProfiler;
using ServiceStack.Web;
using static System.String;
namespace ServiceStack
{
public static class HostContext
{
public static RequestContext RequestContext => RequestContext.Instance;
public static ServiceStackHost AppHost => ServiceStackHost.Instance;
public static AsyncContext Async = new AsyncContext();
private static ServiceStackHost AssertAppHost()
{
if (ServiceStackHost.Instance == null)
throw new ConfigurationErrorsException(
"ServiceStack: AppHost does not exist or has not been initialized. " +
"Make sure you have created an AppHost and started it with 'new AppHost().Init();' " +
" in your Global.asax Application_Start() or alternative Application StartUp");
return ServiceStackHost.Instance;
}
#if !NETSTANDARD1_6
public static bool IsAspNetHost => ServiceStackHost.Instance is AppHostBase;
public static bool IsHttpListenerHost => ServiceStackHost.Instance is Host.HttpListener.HttpListenerBase;
public static bool IsNetCore => false;
#else
public static bool IsAspNetHost => false;
public static bool IsHttpListenerHost => false;
public static bool IsNetCore => true;
#endif
public static T TryResolve<T>() => AssertAppHost().TryResolve<T>();
public static T Resolve<T>() => AssertAppHost().Resolve<T>();
public static Container Container => AssertAppHost().Container;
public static ServiceController ServiceController => AssertAppHost().ServiceController;
public static MetadataPagesConfig MetadataPagesConfig => AssertAppHost().MetadataPagesConfig;
public static IContentTypes ContentTypes => AssertAppHost().ContentTypes;
public static HostConfig Config => AssertAppHost().Config;
public static IAppSettings AppSettings => AssertAppHost().AppSettings;
public static ServiceMetadata Metadata => AssertAppHost().Metadata;
public static string ServiceName => AssertAppHost().ServiceName;
public static bool DebugMode => AppHost?.Config?.DebugMode == true;
public static bool TestMode
{
get { return ServiceStackHost.Instance != null && ServiceStackHost.Instance.TestMode; }
set { ServiceStackHost.Instance.TestMode = value; }
}
public static List<HttpHandlerResolverDelegate> CatchAllHandlers => AssertAppHost().CatchAllHandlers;
public static List<Func<IHttpRequest, IHttpHandler>> RawHttpHandlers => AssertAppHost().RawHttpHandlers;
public static List<Action<IRequest, IResponse, object>> GlobalRequestFilters => AssertAppHost().GlobalRequestFilters;
public static List<Action<IRequest, IResponse, object>> GlobalResponseFilters => AssertAppHost().GlobalResponseFilters;
public static List<Action<IRequest, IResponse, object>> GlobalMessageRequestFilters => AssertAppHost().GlobalMessageRequestFilters;
public static List<Action<IRequest, IResponse, object>> GlobalMessageResponseFilters => AssertAppHost().GlobalMessageResponseFilters;
public static bool ApplyCustomHandlerRequestFilters(IRequest httpReq, IResponse httpRes)
{
return AssertAppHost().ApplyCustomHandlerRequestFilters(httpReq, httpRes);
}
public static bool ApplyPreRequestFilters(IRequest httpReq, IResponse httpRes)
{
return AssertAppHost().ApplyPreRequestFilters(httpReq, httpRes);
}
public static bool ApplyRequestFilters(IRequest httpReq, IResponse httpRes, object requestDto)
{
return AssertAppHost().ApplyRequestFilters(httpReq, httpRes, requestDto);
}
public static bool ApplyResponseFilters(IRequest httpReq, IResponse httpRes, object response)
{
return AssertAppHost().ApplyResponseFilters(httpReq, httpRes, response);
}
/// <summary>
/// Read/Write Virtual FileSystem. Defaults to FileSystemVirtualPathProvider
/// </summary>
public static IVirtualFiles VirtualFiles => AssertAppHost().VirtualFiles;
/// <summary>
/// Cascading collection of virtual file sources, inc. Embedded Resources, File System, In Memory, S3
/// </summary>
public static IVirtualPathProvider VirtualFileSources => AssertAppHost().VirtualFileSources;
[Obsolete("Renamed to VirtualFileSources")]
public static IVirtualPathProvider VirtualPathProvider => AssertAppHost().VirtualFileSources;
public static ICacheClient Cache => TryResolve<ICacheClient>();
public static MemoryCacheClient LocalCache => TryResolve<MemoryCacheClient>();
/// <summary>
/// Call to signal the completion of a ServiceStack-handled Request
/// </summary>
internal static void CompleteRequest(IRequest request)
{
try
{
AssertAppHost().OnEndRequest(request);
}
catch (Exception) { }
}
public static IServiceRunner<TRequest> CreateServiceRunner<TRequest>(ActionContext actionContext)
{
return AssertAppHost().CreateServiceRunner<TRequest>(actionContext);
}
internal static object ExecuteService(object request, IRequest httpReq)
{
using (Profiler.Current.Step("Execute Service"))
{
return AssertAppHost().ServiceController.Execute(request, httpReq);
}
}
public static T GetPlugin<T>() where T : class, IPlugin
{
var appHost = AppHost;
return appHost?.GetPlugin<T>();
}
public static bool HasPlugin<T>() where T : class, IPlugin
{
var appHost = AppHost;
return appHost != null && appHost.HasPlugin<T>();
}
public static void Release(object service)
{
if (ServiceStackHost.Instance != null)
{
ServiceStackHost.Instance.Release(service);
}
else
{
using (service as IDisposable) { }
}
}
public static UnauthorizedAccessException UnauthorizedAccess(RequestAttributes requestAttrs)
{
return new UnauthorizedAccessException($"Request with '{requestAttrs}' is not allowed");
}
public static string ResolveLocalizedString(string text, IRequest request = null)
{
return AssertAppHost().ResolveLocalizedString(text, request);
}
public static string ResolveAbsoluteUrl(string virtualPath, IRequest httpReq)
{
return AssertAppHost().ResolveAbsoluteUrl(virtualPath, httpReq);
}
public static string ResolvePhysicalPath(string virtualPath, IRequest httpReq)
{
return AssertAppHost().ResolvePhysicalPath(virtualPath, httpReq);
}
public static IVirtualFile ResolveVirtualFile(string virtualPath, IRequest httpReq)
{
return AssertAppHost().ResolveVirtualFile(virtualPath, httpReq);
}
public static IVirtualDirectory ResolveVirtualDirectory(string virtualPath, IRequest httpReq)
{
return AssertAppHost().ResolveVirtualDirectory(virtualPath, httpReq);
}
public static IVirtualNode ResolveVirtualNode(string virtualPath, IRequest httpReq)
{
return AssertAppHost().ResolveVirtualNode(virtualPath, httpReq);
}
private static string defaultOperationNamespace;
public static string DefaultOperationNamespace
{
get { return defaultOperationNamespace ?? (defaultOperationNamespace = GetDefaultNamespace()); }
set { defaultOperationNamespace = value; }
}
public static string GetDefaultNamespace()
{
if (!IsNullOrEmpty(defaultOperationNamespace)) return null;
foreach (var operationType in Metadata.RequestTypes)
{
var attrs = operationType.AllAttributes<DataContractAttribute>();
if (attrs.Length <= 0) continue;
var attr = attrs[0];
if (IsNullOrEmpty(attr.Namespace)) continue;
return attr.Namespace;
}
return null;
}
public static object RaiseServiceException(IRequest httpReq, object request, Exception ex)
{
return AssertAppHost().OnServiceException(httpReq, request, ex);
}
public static void RaiseUncaughtException(IRequest httpReq, IResponse httpRes, string operationName, Exception ex)
{
AssertAppHost().OnUncaughtException(httpReq, httpRes, operationName, ex);
}
public static void RaiseAndHandleUncaughtException(IRequest httpReq, IResponse httpRes, string operationName, Exception ex)
{
AssertAppHost().OnUncaughtException(httpReq, httpRes, operationName, ex);
if (httpRes.IsClosed)
return;
AssertAppHost().HandleUncaughtException(httpReq, httpRes, operationName, ex);
}
#if !NETSTANDARD1_6
/// <summary>
/// Resolves and auto-wires a ServiceStack Service from a ASP.NET HttpContext.
/// </summary>
public static T ResolveService<T>(HttpContextBase httpCtx = null) where T : class, IRequiresRequest
{
var httpReq = httpCtx != null ? httpCtx.ToRequest() : GetCurrentRequest();
return ResolveService(httpReq, AssertAppHost().Container.Resolve<T>());
}
/// <summary>
/// Resolves and auto-wires a ServiceStack Service from a HttpListenerContext.
/// </summary>
public static T ResolveService<T>(HttpListenerContext httpCtx) where T : class, IRequiresRequest
{
return ResolveService(httpCtx.ToRequest(), AssertAppHost().Container.Resolve<T>());
}
#endif
/// <summary>
/// Resolves and auto-wires a ServiceStack Service.
/// </summary>
public static T ResolveService<T>(IRequest httpReq) where T : class, IRequiresRequest
{
return ResolveService(httpReq, AssertAppHost().Container.Resolve<T>());
}
public static T ResolveService<T>(IRequest httpReq, T service)
{
var hasRequest = service as IRequiresRequest;
if (hasRequest != null)
{
httpReq.SetInProcessRequest();
hasRequest.Request = httpReq;
}
return service;
}
public static bool HasValidAuthSecret(IRequest httpReq)
{
return AssertAppHost().HasValidAuthSecret(httpReq);
}
public static bool HasFeature(Feature feature)
{
return AssertAppHost().HasFeature(feature);
}
public static IRequest GetCurrentRequest()
{
var req = AssertAppHost().TryGetCurrentRequest();
if (req == null)
throw new NotImplementedException(ErrorMessages.HostDoesNotSupportSingletonRequest);
return req;
}
public static IRequest TryGetCurrentRequest()
{
return AssertAppHost().TryGetCurrentRequest();
}
public static int FindFreeTcpPort(int startingFrom=5000, int endingAt=65535)
{
var tcpEndPoints = System.Net.NetworkInformation.IPGlobalProperties.GetIPGlobalProperties().GetActiveTcpListeners();
var activePorts = new HashSet<int>();
foreach (var endPoint in tcpEndPoints)
{
activePorts.Add(endPoint.Port);
}
for (var port = startingFrom; port < endingAt; port++)
{
if (!activePorts.Contains(port))
return port;
}
return -1;
}
}
} | 38.10479 | 142 | 0.628271 | [
"Apache-2.0"
] | zengdl/ServiceStack | src/ServiceStack/HostContext.cs | 12,394 | C# |
using Silverpop.Core;
using System.Collections.Generic;
namespace Silverpop.Client.WebTester.Models
{
public class SendModel
{
public SendModel()
{
PersonalizationTags = new List<TransactMessageRecipientPersonalizationTag>();
}
public string CampaignId { get; set; }
public string ToAddress { get; set; }
public IEnumerable<TransactMessageRecipientPersonalizationTag> PersonalizationTags { get; set; }
}
} | 25.368421 | 104 | 0.680498 | [
"MIT"
] | Fbiss/silverpop-dotnet-api | samples/Silverpop.Client.WebTester/Models/SendModel.cs | 484 | C# |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEditor;
using System;
using System.Globalization;
public class SetDebugBuildDate : Editor
{
public class SceneViewExtenderEditorIOHooks : UnityEditor.AssetModificationProcessor
{
public static string[] OnWillSaveAssets(string[] paths)
{
string month = DateTime.Now.Month.ToString("D2");
string date = DateTime.Now.Day.ToString("D2");
string year = DateTime.Now.Year.ToString().Substring(2, 2);
Development.Debug devInstance = GameObject.FindObjectOfType<Development.Debug>();
if (devInstance != null)
devInstance.buildDate = string.Format("{0}_{1}_{2}", new object[] { month, date, year });
return paths;
}
}
}
| 28.033333 | 105 | 0.649227 | [
"MIT"
] | EchoArray/Numerous-Ninjas | Source/Editor/SetDebugBuildDate.cs | 843 | C# |
namespace LlamaUtilities.LlamaUtilities
{
partial class Utilities
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.components = new System.ComponentModel.Container();
this.tabControl1 = new System.Windows.Forms.TabControl();
this.tabRetainers = new System.Windows.Forms.TabPage();
this.btnRetainers = new System.Windows.Forms.Button();
this.pgRetainers = new System.Windows.Forms.PropertyGrid();
this.tabPage1 = new System.Windows.Forms.TabPage();
this.btnHuntStart = new System.Windows.Forms.Button();
this.pgHunts = new System.Windows.Forms.PropertyGrid();
this.tabMateria = new System.Windows.Forms.TabPage();
this.tabControlMateria = new System.Windows.Forms.TabControl();
this.tabPageRemove = new System.Windows.Forms.TabPage();
this.groupBoxRemoveFilter = new System.Windows.Forms.GroupBox();
this.filterCb = new System.Windows.Forms.ComboBox();
this.groupBox1 = new System.Windows.Forms.GroupBox();
this.btnRemoveMateria = new System.Windows.Forms.Button();
this.materiaListBox = new System.Windows.Forms.ListBox();
this.btnRefresh = new System.Windows.Forms.Button();
this.itemCb = new System.Windows.Forms.ComboBox();
this.tabAffix = new System.Windows.Forms.TabPage();
this.groupBox2 = new System.Windows.Forms.GroupBox();
this.buttonAffix = new System.Windows.Forms.Button();
this.MateriaCb5 = new System.Windows.Forms.ComboBox();
this.MateriaCb4 = new System.Windows.Forms.ComboBox();
this.MateriaCb3 = new System.Windows.Forms.ComboBox();
this.MateriaCb2 = new System.Windows.Forms.ComboBox();
this.MateriaCb1 = new System.Windows.Forms.ComboBox();
this.button3 = new System.Windows.Forms.Button();
this.affixCb = new System.Windows.Forms.ComboBox();
this.bindingSourceAffix = new System.Windows.Forms.BindingSource(this.components);
this.tabInventory = new System.Windows.Forms.TabPage();
this.lblDesynth = new System.Windows.Forms.Label();
this.pgInventory = new System.Windows.Forms.PropertyGrid();
this.btnDesynth = new System.Windows.Forms.Button();
this.btnCoffers = new System.Windows.Forms.Button();
this.btnExtract = new System.Windows.Forms.Button();
this.btnReduce = new System.Windows.Forms.Button();
this.tabCustom = new System.Windows.Forms.TabPage();
this.btnCustomDeliveries = new System.Windows.Forms.Button();
this.pgCustomDeliveries = new System.Windows.Forms.PropertyGrid();
this.tabGC = new System.Windows.Forms.TabPage();
this.btnGcTurin = new System.Windows.Forms.Button();
this.propertyGrid1 = new System.Windows.Forms.PropertyGrid();
this.tabHousing = new System.Windows.Forms.TabPage();
this.btnHousing = new System.Windows.Forms.Button();
this.tabFC = new System.Windows.Forms.TabPage();
this.btnFCWorkshop = new System.Windows.Forms.Button();
this.bindingSourceInventory = new System.Windows.Forms.BindingSource(this.components);
this.bindingSourceInventoryMateria = new System.Windows.Forms.BindingSource(this.components);
this.tabControl1.SuspendLayout();
this.tabRetainers.SuspendLayout();
this.tabPage1.SuspendLayout();
this.tabMateria.SuspendLayout();
this.tabControlMateria.SuspendLayout();
this.tabPageRemove.SuspendLayout();
this.groupBoxRemoveFilter.SuspendLayout();
this.groupBox1.SuspendLayout();
this.tabAffix.SuspendLayout();
this.groupBox2.SuspendLayout();
((System.ComponentModel.ISupportInitialize) (this.bindingSourceAffix)).BeginInit();
this.tabInventory.SuspendLayout();
this.tabCustom.SuspendLayout();
this.tabGC.SuspendLayout();
this.tabHousing.SuspendLayout();
this.tabFC.SuspendLayout();
((System.ComponentModel.ISupportInitialize) (this.bindingSourceInventory)).BeginInit();
((System.ComponentModel.ISupportInitialize) (this.bindingSourceInventoryMateria)).BeginInit();
this.SuspendLayout();
//
// tabControl1
//
this.tabControl1.Controls.Add(this.tabRetainers);
this.tabControl1.Controls.Add(this.tabPage1);
this.tabControl1.Controls.Add(this.tabMateria);
this.tabControl1.Controls.Add(this.tabInventory);
this.tabControl1.Controls.Add(this.tabCustom);
this.tabControl1.Controls.Add(this.tabGC);
this.tabControl1.Controls.Add(this.tabHousing);
this.tabControl1.Controls.Add(this.tabFC);
this.tabControl1.Dock = System.Windows.Forms.DockStyle.Fill;
this.tabControl1.Location = new System.Drawing.Point(0, 0);
this.tabControl1.Name = "tabControl1";
this.tabControl1.SelectedIndex = 0;
this.tabControl1.Size = new System.Drawing.Size(519, 385);
this.tabControl1.TabIndex = 0;
//
// tabRetainers
//
this.tabRetainers.Controls.Add(this.btnRetainers);
this.tabRetainers.Controls.Add(this.pgRetainers);
this.tabRetainers.Location = new System.Drawing.Point(4, 22);
this.tabRetainers.Name = "tabRetainers";
this.tabRetainers.Size = new System.Drawing.Size(511, 359);
this.tabRetainers.TabIndex = 7;
this.tabRetainers.Text = "Retainers";
this.tabRetainers.UseVisualStyleBackColor = true;
//
// btnRetainers
//
this.btnRetainers.Location = new System.Drawing.Point(283, 318);
this.btnRetainers.Name = "btnRetainers";
this.btnRetainers.Size = new System.Drawing.Size(94, 23);
this.btnRetainers.TabIndex = 1;
this.btnRetainers.Text = "Start";
this.btnRetainers.UseVisualStyleBackColor = true;
this.btnRetainers.Click += new System.EventHandler(this.btnRetainers_Click);
//
// pgRetainers
//
this.pgRetainers.Location = new System.Drawing.Point(8, 3);
this.pgRetainers.Name = "pgRetainers";
this.pgRetainers.Size = new System.Drawing.Size(369, 185);
this.pgRetainers.TabIndex = 0;
//
// tabPage1
//
this.tabPage1.Controls.Add(this.btnHuntStart);
this.tabPage1.Controls.Add(this.pgHunts);
this.tabPage1.Location = new System.Drawing.Point(4, 22);
this.tabPage1.Name = "tabPage1";
this.tabPage1.Padding = new System.Windows.Forms.Padding(3);
this.tabPage1.Size = new System.Drawing.Size(511, 359);
this.tabPage1.TabIndex = 0;
this.tabPage1.Text = "Daily Hunts";
this.tabPage1.UseVisualStyleBackColor = true;
//
// btnHuntStart
//
this.btnHuntStart.Location = new System.Drawing.Point(265, 321);
this.btnHuntStart.Name = "btnHuntStart";
this.btnHuntStart.Size = new System.Drawing.Size(95, 25);
this.btnHuntStart.TabIndex = 1;
this.btnHuntStart.Text = "Start";
this.btnHuntStart.UseVisualStyleBackColor = true;
this.btnHuntStart.Click += new System.EventHandler(this.btnHuntStart_Click);
//
// pgHunts
//
this.pgHunts.Location = new System.Drawing.Point(9, 12);
this.pgHunts.Name = "pgHunts";
this.pgHunts.Size = new System.Drawing.Size(352, 238);
this.pgHunts.TabIndex = 0;
//
// tabMateria
//
this.tabMateria.Controls.Add(this.tabControlMateria);
this.tabMateria.Location = new System.Drawing.Point(4, 22);
this.tabMateria.Name = "tabMateria";
this.tabMateria.Padding = new System.Windows.Forms.Padding(3);
this.tabMateria.Size = new System.Drawing.Size(511, 359);
this.tabMateria.TabIndex = 1;
this.tabMateria.Text = "Materia";
this.tabMateria.UseVisualStyleBackColor = true;
//
// tabControlMateria
//
this.tabControlMateria.Controls.Add(this.tabPageRemove);
this.tabControlMateria.Controls.Add(this.tabAffix);
this.tabControlMateria.Location = new System.Drawing.Point(8, 6);
this.tabControlMateria.Name = "tabControlMateria";
this.tabControlMateria.SelectedIndex = 0;
this.tabControlMateria.Size = new System.Drawing.Size(497, 345);
this.tabControlMateria.TabIndex = 1;
//
// tabPageRemove
//
this.tabPageRemove.Controls.Add(this.groupBoxRemoveFilter);
this.tabPageRemove.Controls.Add(this.groupBox1);
this.tabPageRemove.Location = new System.Drawing.Point(4, 22);
this.tabPageRemove.Name = "tabPageRemove";
this.tabPageRemove.Padding = new System.Windows.Forms.Padding(3);
this.tabPageRemove.Size = new System.Drawing.Size(489, 319);
this.tabPageRemove.TabIndex = 0;
this.tabPageRemove.Text = "Remove";
this.tabPageRemove.UseVisualStyleBackColor = true;
this.tabPageRemove.Click += new System.EventHandler(this.tabPageRemove_Click);
//
// groupBoxRemoveFilter
//
this.groupBoxRemoveFilter.Controls.Add(this.filterCb);
this.groupBoxRemoveFilter.Location = new System.Drawing.Point(346, 6);
this.groupBoxRemoveFilter.Name = "groupBoxRemoveFilter";
this.groupBoxRemoveFilter.Size = new System.Drawing.Size(137, 263);
this.groupBoxRemoveFilter.TabIndex = 1;
this.groupBoxRemoveFilter.TabStop = false;
this.groupBoxRemoveFilter.Text = "Inventory Filter";
//
// filterCb
//
this.filterCb.FormattingEnabled = true;
this.filterCb.Location = new System.Drawing.Point(6, 19);
this.filterCb.Name = "filterCb";
this.filterCb.Size = new System.Drawing.Size(125, 21);
this.filterCb.TabIndex = 0;
//
// groupBox1
//
this.groupBox1.Controls.Add(this.btnRemoveMateria);
this.groupBox1.Controls.Add(this.materiaListBox);
this.groupBox1.Controls.Add(this.btnRefresh);
this.groupBox1.Controls.Add(this.itemCb);
this.groupBox1.Location = new System.Drawing.Point(6, 6);
this.groupBox1.Name = "groupBox1";
this.groupBox1.Size = new System.Drawing.Size(334, 263);
this.groupBox1.TabIndex = 0;
this.groupBox1.TabStop = false;
this.groupBox1.Text = "Remove Materia";
//
// btnRemoveMateria
//
this.btnRemoveMateria.Location = new System.Drawing.Point(9, 185);
this.btnRemoveMateria.Name = "btnRemoveMateria";
this.btnRemoveMateria.Size = new System.Drawing.Size(142, 25);
this.btnRemoveMateria.TabIndex = 3;
this.btnRemoveMateria.Text = "Remove All Materia";
this.btnRemoveMateria.UseVisualStyleBackColor = true;
this.btnRemoveMateria.Click += new System.EventHandler(this.btnRemoveMateria_Click);
//
// materiaListBox
//
this.materiaListBox.FormattingEnabled = true;
this.materiaListBox.Location = new System.Drawing.Point(9, 45);
this.materiaListBox.Name = "materiaListBox";
this.materiaListBox.Size = new System.Drawing.Size(297, 134);
this.materiaListBox.TabIndex = 2;
//
// btnRefresh
//
this.btnRefresh.Location = new System.Drawing.Point(229, 17);
this.btnRefresh.Name = "btnRefresh";
this.btnRefresh.Size = new System.Drawing.Size(78, 21);
this.btnRefresh.TabIndex = 1;
this.btnRefresh.Text = "Refresh";
this.btnRefresh.UseVisualStyleBackColor = true;
this.btnRefresh.Click += new System.EventHandler(this.btnRefresh_Click);
//
// itemCb
//
this.itemCb.FormattingEnabled = true;
this.itemCb.Location = new System.Drawing.Point(9, 17);
this.itemCb.Name = "itemCb";
this.itemCb.Size = new System.Drawing.Size(209, 21);
this.itemCb.TabIndex = 0;
//
// tabAffix
//
this.tabAffix.Controls.Add(this.groupBox2);
this.tabAffix.Location = new System.Drawing.Point(4, 22);
this.tabAffix.Name = "tabAffix";
this.tabAffix.Padding = new System.Windows.Forms.Padding(3);
this.tabAffix.Size = new System.Drawing.Size(489, 319);
this.tabAffix.TabIndex = 1;
this.tabAffix.Text = "Affix";
this.tabAffix.UseVisualStyleBackColor = true;
//
// groupBox2
//
this.groupBox2.Controls.Add(this.buttonAffix);
this.groupBox2.Controls.Add(this.MateriaCb5);
this.groupBox2.Controls.Add(this.MateriaCb4);
this.groupBox2.Controls.Add(this.MateriaCb3);
this.groupBox2.Controls.Add(this.MateriaCb2);
this.groupBox2.Controls.Add(this.MateriaCb1);
this.groupBox2.Controls.Add(this.button3);
this.groupBox2.Controls.Add(this.affixCb);
this.groupBox2.Location = new System.Drawing.Point(8, 7);
this.groupBox2.Name = "groupBox2";
this.groupBox2.Size = new System.Drawing.Size(314, 285);
this.groupBox2.TabIndex = 0;
this.groupBox2.TabStop = false;
this.groupBox2.Text = "Affix";
//
// buttonAffix
//
this.buttonAffix.Location = new System.Drawing.Point(183, 191);
this.buttonAffix.Name = "buttonAffix";
this.buttonAffix.Size = new System.Drawing.Size(120, 23);
this.buttonAffix.TabIndex = 7;
this.buttonAffix.Text = "Affix";
this.buttonAffix.UseVisualStyleBackColor = true;
this.buttonAffix.Click += new System.EventHandler(this.buttonAffix_Click);
//
// MateriaCb5
//
this.MateriaCb5.FormattingEnabled = true;
this.MateriaCb5.Location = new System.Drawing.Point(12, 164);
this.MateriaCb5.Name = "MateriaCb5";
this.MateriaCb5.Size = new System.Drawing.Size(291, 21);
this.MateriaCb5.TabIndex = 6;
//
// MateriaCb4
//
this.MateriaCb4.FormattingEnabled = true;
this.MateriaCb4.Location = new System.Drawing.Point(12, 137);
this.MateriaCb4.Name = "MateriaCb4";
this.MateriaCb4.Size = new System.Drawing.Size(291, 21);
this.MateriaCb4.TabIndex = 5;
//
// MateriaCb3
//
this.MateriaCb3.FormattingEnabled = true;
this.MateriaCb3.Location = new System.Drawing.Point(12, 110);
this.MateriaCb3.Name = "MateriaCb3";
this.MateriaCb3.Size = new System.Drawing.Size(291, 21);
this.MateriaCb3.TabIndex = 4;
//
// MateriaCb2
//
this.MateriaCb2.FormattingEnabled = true;
this.MateriaCb2.Location = new System.Drawing.Point(12, 83);
this.MateriaCb2.Name = "MateriaCb2";
this.MateriaCb2.Size = new System.Drawing.Size(291, 21);
this.MateriaCb2.TabIndex = 3;
//
// MateriaCb1
//
this.MateriaCb1.FormattingEnabled = true;
this.MateriaCb1.Location = new System.Drawing.Point(12, 56);
this.MateriaCb1.Name = "MateriaCb1";
this.MateriaCb1.Size = new System.Drawing.Size(291, 21);
this.MateriaCb1.TabIndex = 2;
//
// button3
//
this.button3.Location = new System.Drawing.Point(233, 19);
this.button3.Name = "button3";
this.button3.Size = new System.Drawing.Size(70, 23);
this.button3.TabIndex = 1;
this.button3.Text = "Refresh";
this.button3.UseVisualStyleBackColor = true;
this.button3.Click += new System.EventHandler(this.button3_Click);
//
// affixCb
//
this.affixCb.DataSource = this.bindingSourceAffix;
this.affixCb.FormattingEnabled = true;
this.affixCb.Location = new System.Drawing.Point(12, 21);
this.affixCb.Name = "affixCb";
this.affixCb.Size = new System.Drawing.Size(215, 21);
this.affixCb.TabIndex = 0;
this.affixCb.SelectedIndexChanged += new System.EventHandler(this.affixCb_SelectedIndexChanged);
//
// tabInventory
//
this.tabInventory.Controls.Add(this.lblDesynth);
this.tabInventory.Controls.Add(this.pgInventory);
this.tabInventory.Controls.Add(this.btnDesynth);
this.tabInventory.Controls.Add(this.btnCoffers);
this.tabInventory.Controls.Add(this.btnExtract);
this.tabInventory.Controls.Add(this.btnReduce);
this.tabInventory.Location = new System.Drawing.Point(4, 22);
this.tabInventory.Name = "tabInventory";
this.tabInventory.Size = new System.Drawing.Size(511, 359);
this.tabInventory.TabIndex = 2;
this.tabInventory.Text = "Inventory";
this.tabInventory.UseVisualStyleBackColor = true;
//
// lblDesynth
//
this.lblDesynth.AutoSize = true;
this.lblDesynth.Location = new System.Drawing.Point(136, 234);
this.lblDesynth.Name = "lblDesynth";
this.lblDesynth.Size = new System.Drawing.Size(198, 13);
this.lblDesynth.TabIndex = 5;
this.lblDesynth.Text = "<- Desynth all trust gear and possibly fish";
//
// pgInventory
//
this.pgInventory.Location = new System.Drawing.Point(131, 14);
this.pgInventory.Name = "pgInventory";
this.pgInventory.Size = new System.Drawing.Size(372, 199);
this.pgInventory.TabIndex = 4;
//
// btnDesynth
//
this.btnDesynth.Location = new System.Drawing.Point(8, 228);
this.btnDesynth.Name = "btnDesynth";
this.btnDesynth.Size = new System.Drawing.Size(122, 24);
this.btnDesynth.TabIndex = 3;
this.btnDesynth.Text = "Desynth";
this.btnDesynth.UseVisualStyleBackColor = true;
this.btnDesynth.Click += new System.EventHandler(this.btnDesynth_Click);
//
// btnCoffers
//
this.btnCoffers.Location = new System.Drawing.Point(3, 74);
this.btnCoffers.Name = "btnCoffers";
this.btnCoffers.Size = new System.Drawing.Size(122, 24);
this.btnCoffers.TabIndex = 2;
this.btnCoffers.Text = "Open All Coffers";
this.btnCoffers.UseVisualStyleBackColor = true;
this.btnCoffers.Click += new System.EventHandler(this.btnCoffers_Click);
//
// btnExtract
//
this.btnExtract.Location = new System.Drawing.Point(3, 44);
this.btnExtract.Name = "btnExtract";
this.btnExtract.Size = new System.Drawing.Size(122, 24);
this.btnExtract.TabIndex = 1;
this.btnExtract.Text = "Extract Materia";
this.btnExtract.UseVisualStyleBackColor = true;
this.btnExtract.Click += new System.EventHandler(this.btnExtract_Click);
//
// btnReduce
//
this.btnReduce.Location = new System.Drawing.Point(3, 14);
this.btnReduce.Name = "btnReduce";
this.btnReduce.Size = new System.Drawing.Size(122, 24);
this.btnReduce.TabIndex = 0;
this.btnReduce.Text = "Reduce All";
this.btnReduce.UseVisualStyleBackColor = true;
this.btnReduce.Click += new System.EventHandler(this.btnReduce_Click);
//
// tabCustom
//
this.tabCustom.Controls.Add(this.btnCustomDeliveries);
this.tabCustom.Controls.Add(this.pgCustomDeliveries);
this.tabCustom.Location = new System.Drawing.Point(4, 22);
this.tabCustom.Name = "tabCustom";
this.tabCustom.Size = new System.Drawing.Size(511, 359);
this.tabCustom.TabIndex = 3;
this.tabCustom.Text = "Custom Deliveries";
this.tabCustom.UseVisualStyleBackColor = true;
//
// btnCustomDeliveries
//
this.btnCustomDeliveries.Location = new System.Drawing.Point(296, 328);
this.btnCustomDeliveries.Name = "btnCustomDeliveries";
this.btnCustomDeliveries.Size = new System.Drawing.Size(75, 23);
this.btnCustomDeliveries.TabIndex = 1;
this.btnCustomDeliveries.Text = "Start";
this.btnCustomDeliveries.UseVisualStyleBackColor = true;
this.btnCustomDeliveries.Click += new System.EventHandler(this.btnCustomDeliveries_Click);
//
// pgCustomDeliveries
//
this.pgCustomDeliveries.Location = new System.Drawing.Point(3, 3);
this.pgCustomDeliveries.Name = "pgCustomDeliveries";
this.pgCustomDeliveries.Size = new System.Drawing.Size(373, 220);
this.pgCustomDeliveries.TabIndex = 0;
//
// tabGC
//
this.tabGC.Controls.Add(this.btnGcTurin);
this.tabGC.Controls.Add(this.propertyGrid1);
this.tabGC.Location = new System.Drawing.Point(4, 22);
this.tabGC.Name = "tabGC";
this.tabGC.Size = new System.Drawing.Size(511, 359);
this.tabGC.TabIndex = 4;
this.tabGC.Text = "Gc Turnin";
this.tabGC.UseVisualStyleBackColor = true;
//
// btnGcTurin
//
this.btnGcTurin.Location = new System.Drawing.Point(288, 328);
this.btnGcTurin.Name = "btnGcTurin";
this.btnGcTurin.Size = new System.Drawing.Size(88, 23);
this.btnGcTurin.TabIndex = 1;
this.btnGcTurin.Text = "Start";
this.btnGcTurin.UseVisualStyleBackColor = true;
this.btnGcTurin.Click += new System.EventHandler(this.btnGcTurin_Click);
//
// propertyGrid1
//
this.propertyGrid1.Location = new System.Drawing.Point(3, 3);
this.propertyGrid1.Name = "propertyGrid1";
this.propertyGrid1.Size = new System.Drawing.Size(373, 219);
this.propertyGrid1.TabIndex = 0;
//
// tabHousing
//
this.tabHousing.Controls.Add(this.btnHousing);
this.tabHousing.Location = new System.Drawing.Point(4, 22);
this.tabHousing.Name = "tabHousing";
this.tabHousing.Padding = new System.Windows.Forms.Padding(3);
this.tabHousing.Size = new System.Drawing.Size(511, 359);
this.tabHousing.TabIndex = 5;
this.tabHousing.Text = "Housing";
this.tabHousing.UseVisualStyleBackColor = true;
//
// btnHousing
//
this.btnHousing.Location = new System.Drawing.Point(276, 307);
this.btnHousing.Name = "btnHousing";
this.btnHousing.Size = new System.Drawing.Size(95, 23);
this.btnHousing.TabIndex = 0;
this.btnHousing.Text = "Start";
this.btnHousing.UseVisualStyleBackColor = true;
this.btnHousing.Click += new System.EventHandler(this.btnHousing_Click);
//
// tabFC
//
this.tabFC.Controls.Add(this.btnFCWorkshop);
this.tabFC.Location = new System.Drawing.Point(4, 22);
this.tabFC.Name = "tabFC";
this.tabFC.Size = new System.Drawing.Size(511, 359);
this.tabFC.TabIndex = 6;
this.tabFC.Text = "FCWorkshop";
this.tabFC.UseVisualStyleBackColor = true;
//
// btnFCWorkshop
//
this.btnFCWorkshop.Location = new System.Drawing.Point(280, 327);
this.btnFCWorkshop.Name = "btnFCWorkshop";
this.btnFCWorkshop.Size = new System.Drawing.Size(84, 24);
this.btnFCWorkshop.TabIndex = 0;
this.btnFCWorkshop.Text = "Start";
this.btnFCWorkshop.UseVisualStyleBackColor = true;
this.btnFCWorkshop.Click += new System.EventHandler(this.btnFCWorkshop_Click);
//
// bindingSourceInventory
//
this.bindingSourceInventory.CurrentChanged += new System.EventHandler(this.bindingSourceInventory_CurrentChanged);
//
// Utilities
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(519, 385);
this.Controls.Add(this.tabControl1);
this.Name = "Utilities";
this.Text = "Utilities";
this.Load += new System.EventHandler(this.Utilities_Load);
this.tabControl1.ResumeLayout(false);
this.tabRetainers.ResumeLayout(false);
this.tabPage1.ResumeLayout(false);
this.tabMateria.ResumeLayout(false);
this.tabControlMateria.ResumeLayout(false);
this.tabPageRemove.ResumeLayout(false);
this.groupBoxRemoveFilter.ResumeLayout(false);
this.groupBox1.ResumeLayout(false);
this.tabAffix.ResumeLayout(false);
this.groupBox2.ResumeLayout(false);
((System.ComponentModel.ISupportInitialize) (this.bindingSourceAffix)).EndInit();
this.tabInventory.ResumeLayout(false);
this.tabInventory.PerformLayout();
this.tabCustom.ResumeLayout(false);
this.tabGC.ResumeLayout(false);
this.tabHousing.ResumeLayout(false);
this.tabFC.ResumeLayout(false);
((System.ComponentModel.ISupportInitialize) (this.bindingSourceInventory)).EndInit();
((System.ComponentModel.ISupportInitialize) (this.bindingSourceInventoryMateria)).EndInit();
this.ResumeLayout(false);
}
private System.Windows.Forms.ComboBox filterCb;
private System.Windows.Forms.GroupBox groupBoxRemoveFilter;
private System.Windows.Forms.Button buttonAffix;
private System.Windows.Forms.BindingSource bindingSourceInventoryMateria;
private System.Windows.Forms.ComboBox MateriaCb1;
private System.Windows.Forms.ComboBox MateriaCb2;
private System.Windows.Forms.ComboBox MateriaCb3;
private System.Windows.Forms.ComboBox MateriaCb4;
private System.Windows.Forms.ComboBox MateriaCb5;
private System.Windows.Forms.ComboBox affixCb;
private System.Windows.Forms.Button button3;
private System.Windows.Forms.ComboBox comboBox1;
private System.Windows.Forms.TabPage tabAffix;
private System.Windows.Forms.GroupBox groupBox2;
private System.Windows.Forms.TabControl tabControlMateria;
private System.Windows.Forms.PropertyGrid pgHunts;
private System.Windows.Forms.Button btnHuntStart;
private System.Windows.Forms.BindingSource bindingSourceInventory;
private System.Windows.Forms.BindingSource bindingSourceAffix;
#endregion
private System.Windows.Forms.TabControl tabControl1;
private System.Windows.Forms.TabPage tabPage1;
private System.Windows.Forms.TabPage tabMateria;
private System.Windows.Forms.GroupBox groupBox1;
private System.Windows.Forms.ComboBox itemCb;
private System.Windows.Forms.ListBox materiaListBox;
private System.Windows.Forms.Button btnRefresh;
private System.Windows.Forms.Button btnRemoveMateria;
private System.Windows.Forms.TabPage tabInventory;
private System.Windows.Forms.Button btnReduce;
private System.Windows.Forms.Button btnExtract;
private System.Windows.Forms.Button btnCoffers;
private System.Windows.Forms.TabPage tabCustom;
private System.Windows.Forms.TabPage tabGC;
private System.Windows.Forms.TabPage tabHousing;
private System.Windows.Forms.TabPage tabPageRemove;
private System.Windows.Forms.PropertyGrid pgCustomDeliveries;
private System.Windows.Forms.PropertyGrid propertyGrid1;
private System.Windows.Forms.Button btnCustomDeliveries;
private System.Windows.Forms.Button btnGcTurin;
private System.Windows.Forms.Button btnHousing;
private System.Windows.Forms.TabPage tabRetainers;
private System.Windows.Forms.Button btnRetainers;
private System.Windows.Forms.PropertyGrid pgRetainers;
private System.Windows.Forms.TabPage tabFC;
private System.Windows.Forms.Button btnFCWorkshop;
private System.Windows.Forms.Label lblDesynth;
private System.Windows.Forms.PropertyGrid pgInventory;
private System.Windows.Forms.Button btnDesynth;
}
} | 48.410296 | 126 | 0.60678 | [
"MIT"
] | nt153133/LlamaUtilities | LlamaUtilities/Utilities.Designer.cs | 31,033 | C# |
using System;
using System.Linq;
using System.Reflection;
using System.Collections.Generic;
namespace Discord.Commands.Builders
{
public class ParameterBuilder
{
private readonly List<ParameterPreconditionAttribute> _preconditions;
private readonly List<Attribute> _attributes;
public CommandBuilder Command { get; }
public string Name { get; internal set; }
public Type ParameterType { get; internal set; }
public TypeReader TypeReader { get; set; }
public bool IsOptional { get; set; }
public bool IsRemainder { get; set; }
public bool IsMultiple { get; set; }
public object DefaultValue { get; set; }
public string Summary { get; set; }
public IReadOnlyList<ParameterPreconditionAttribute> Preconditions => _preconditions;
public IReadOnlyList<Attribute> Attributes => _attributes;
//Automatic
internal ParameterBuilder(CommandBuilder command)
{
_preconditions = new List<ParameterPreconditionAttribute>();
_attributes = new List<Attribute>();
Command = command;
}
//User-defined
internal ParameterBuilder(CommandBuilder command, string name, Type type)
: this(command)
{
Discord.Preconditions.NotNull(name, nameof(name));
Name = name;
SetType(type);
}
internal void SetType(Type type)
{
TypeReader = GetReader(type);
if (type.GetTypeInfo().IsValueType)
DefaultValue = Activator.CreateInstance(type);
else if (type.IsArray)
type = ParameterType.GetElementType();
ParameterType = type;
}
private TypeReader GetReader(Type type)
{
CommandService commands = Command.Module.Service;
if (type.GetTypeInfo().GetCustomAttribute<NamedArgumentTypeAttribute>() != null)
{
IsRemainder = true;
TypeReader reader = commands.GetTypeReaders(type)?.FirstOrDefault().Value;
if (reader == null)
{
Type readerType;
try
{
readerType = typeof(NamedArgumentTypeReader<>).MakeGenericType(new[] { type });
}
catch (ArgumentException ex)
{
throw new InvalidOperationException($"Parameter type '{type.Name}' for command '{Command.Name}' must be a class with a public parameterless constructor to use as a NamedArgumentType.", ex);
}
reader = (TypeReader)Activator.CreateInstance(readerType, new[] { commands });
commands.AddTypeReader(type, reader);
}
return reader;
}
IDictionary<Type, TypeReader> readers = commands.GetTypeReaders(type);
if (readers != null)
return readers.FirstOrDefault().Value;
else
return commands.GetDefaultTypeReader(type);
}
public ParameterBuilder WithSummary(string summary)
{
Summary = summary;
return this;
}
public ParameterBuilder WithDefault(object defaultValue)
{
DefaultValue = defaultValue;
return this;
}
public ParameterBuilder WithIsOptional(bool isOptional)
{
IsOptional = isOptional;
return this;
}
public ParameterBuilder WithIsRemainder(bool isRemainder)
{
IsRemainder = isRemainder;
return this;
}
public ParameterBuilder WithIsMultiple(bool isMultiple)
{
IsMultiple = isMultiple;
return this;
}
public ParameterBuilder AddAttributes(params Attribute[] attributes)
{
_attributes.AddRange(attributes);
return this;
}
public ParameterBuilder AddPrecondition(ParameterPreconditionAttribute precondition)
{
_preconditions.Add(precondition);
return this;
}
internal ParameterInfo Build(CommandInfo info)
{
if ((TypeReader ?? (TypeReader = GetReader(ParameterType))) == null)
throw new InvalidOperationException($"No type reader found for type {ParameterType.Name}, one must be specified");
return new ParameterInfo(this, info, Command.Module.Service);
}
}
}
| 33.759124 | 213 | 0.577946 | [
"MIT"
] | KrAyXMaximum/DNetPlus | DNetPlus/Commands/Builders/ParameterBuilder.cs | 4,625 | C# |
using System;
using System.Diagnostics;
using System.Security.Cryptography;
using Lokad.Cqrs.Feature.TapeStorage;
using Microsoft.WindowsAzure;
using Microsoft.WindowsAzure.StorageClient;
using NUnit.Framework;
namespace Lokad.Cqrs.TapeStorage
{
[TestFixture]
public class BlobTapeStorageTests : TapeStorageTests
{
const string ContainerName = "blob-tape-test";
readonly CloudStorageAccount _cloudStorageAccount = CloudStorageAccount.DevelopmentStorageAccount;
ITapeContainer _storageFactory;
[Test, Explicit]
public void Performance_tests()
{
// random write.
var gen = new RNGCryptoServiceProvider();
var bytes = 1024;
var data = new byte[bytes];
gen.GetNonZeroBytes(data);
var stopwatch = Stopwatch.StartNew();
var records = 200;
var total = records * bytes;
Console.WriteLine("Data is {0} records of {1} bytes == {2} bytes or {3} MB", records, bytes, total, total / 1024 / 1024);
for (int i = 0; i < records; i++)
{
_stream.TryAppend(data);
}
var timeSpan = stopwatch.Elapsed;
Console.WriteLine("Writing one by one in {0}", timeSpan.TotalSeconds);
int counter = 0;
var reading = Stopwatch.StartNew();
foreach (var tapeRecord in _stream.ReadRecords(0, int.MaxValue))
{
counter += tapeRecord.Data.Length;
}
Console.WriteLine("Reading in {0} seconds", reading.Elapsed.TotalSeconds);
Console.WriteLine("Read {0} bytes of raw data", counter);
}
protected override void PrepareEnvironment()
{
var cloudBlobClient = _cloudStorageAccount.CreateCloudBlobClient();
try
{
cloudBlobClient.GetContainerReference(ContainerName).FetchAttributes();
throw new InvalidOperationException("Container '" + ContainerName + "' already exists!");
}
catch (StorageClientException e)
{
if (e.ErrorCode != StorageErrorCode.ResourceNotFound)
throw new InvalidOperationException("Container '" + ContainerName + "' already exists!");
}
}
protected override ITapeStream InitializeAndGetTapeStorage()
{
var config = AzureStorage.CreateConfig(_cloudStorageAccount);
_storageFactory = new BlobTapeStorageFactory(config, ContainerName);
_storageFactory.InitializeForWriting();
const string name = "test";
return _storageFactory.GetOrCreateStream(name);
}
protected override void FreeResources()
{
_storageFactory = null;
_storageFactory = null;
}
protected override void TearDownEnvironment()
{
var cloudBlobClient = _cloudStorageAccount.CreateCloudBlobClient();
var container = cloudBlobClient.GetContainerReference(ContainerName);
if (container.Exists())
container.Delete();
}
}
}
| 33.778947 | 133 | 0.603303 | [
"BSD-3-Clause"
] | EventDay/lokad-cqrs | Cqrs.Azure.Tests/TapeStorage/BlobTapeStorageTests.cs | 3,211 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using AdventureWorksCosmos.Core.Models.Inventory;
using AdventureWorksCosmos.Core.Models.Orders;
namespace AdventureWorksCosmos.Core.Models.Fulfillments
{
public class OrderSaga : DocumentBase
{
public Guid OrderId { get; set; }
public bool IsCancelled { get; set; }
public bool CancelOrderRequested { get; set; }
public List<LineItem> LineItems { get; set; }
public bool OrderApproved { get; set; }
public bool OrderRejected { get; set; }
public class LineItem
{
public int ProductId { get; set; }
public int AmountRequested { get; set; }
public bool StockConfirmed { get; set; }
public bool StockReturnRequested { get; set; }
}
public void Handle(OrderCreatedMessage message)
{
Process(message, m =>
{
if (IsCancelled)
return;
LineItems = m.LineItems.Select(li => new LineItem
{
ProductId = li.ProductId,
AmountRequested = li.Quantity
})
.ToList();
foreach (var lineItem in LineItems)
{
Send(new StockRequestMessage
{
Id = Guid.NewGuid(),
ProductId = lineItem.ProductId,
AmountRequested = lineItem.AmountRequested,
OrderFulfillmentId = Id
});
}
});
}
public void Handle(OrderApprovedMessage message)
{
Process(message, m =>
{
OrderApproved = true;
if (IsCancelled)
{
ProcessCancellation();
}
else
{
CheckForSuccess();
}
});
}
public void Handle(StockRequestConfirmedMessage message)
{
Process(message, m =>
{
var lineItem = LineItems.Single(li => li.ProductId == m.ProductId);
lineItem.StockConfirmed = true;
if (IsCancelled)
{
ReturnStock(lineItem);
}
else
{
CheckForSuccess();
}
});
}
public void Handle(StockRequestDeniedMessage message)
{
Process(message, m =>
{
Cancel();
});
}
public void Handle(OrderRejectedMessage message)
{
Process(message, m =>
{
OrderRejected = true;
Cancel();
});
}
private void CheckForSuccess()
{
if (IsCancelled)
return;
if (LineItems.All(li => li.StockConfirmed) && OrderApproved)
{
Send(new OrderFulfillmentSuccessfulMessage
{
Id = Guid.NewGuid(),
OrderId = OrderId
});
}
}
private void Cancel()
{
IsCancelled = true;
ProcessCancellation();
}
private void ProcessCancellation()
{
if (!CancelOrderRequested && !OrderRejected)
{
CancelOrderRequested = true;
Send(new CancelOrderRequestMessage
{
Id = Guid.NewGuid(),
OrderId = OrderId
});
}
foreach (var lineItem in LineItems.Where(li => li.StockConfirmed))
{
ReturnStock(lineItem);
}
}
private void ReturnStock(LineItem lineItem)
{
if (lineItem.StockReturnRequested)
return;
lineItem.StockReturnRequested = true;
Send(new StockReturnRequestedMessage
{
Id = Guid.NewGuid(),
ProductId = lineItem.ProductId,
AmountToReturn = lineItem.AmountRequested
});
}
}
} | 27.63125 | 83 | 0.444922 | [
"MIT"
] | rbmathis/AdventureWorksCosmos | AdventureWorksCosmos.Core/Models/OrderSaga.cs | 4,423 | C# |
using System;
using ZKWeb.Cache;
using ZKWeb.Cache.Policies;
using ZKWebStandard.Collections;
using ZKWebStandard.Extensions;
using ZKWebStandard.Testing;
using ZKWebStandard.Utils;
namespace ZKWeb.Tests.Cache {
[Tests]
class IsolatedKeyValueCacheTest {
public void All() {
var cache = new IsolatedKeyValueCache<string, string>(
new[] { new CacheIsolateByLocale() },
new MemoryCache<IsolatedCacheKey<string>, string>());
// Set
LocaleUtils.SetThreadLanguage("zh-CN");
cache.Put("Key", "ValueForCN", TimeSpan.FromSeconds(5));
LocaleUtils.SetThreadLanguage("en-US");
cache.Put("Key", "ValueForUS", TimeSpan.FromSeconds(5));
// Get
LocaleUtils.SetThreadLanguage("zh-CN");
Assert.Equals(cache.GetOrDefault("Key"), "ValueForCN");
LocaleUtils.SetThreadLanguage("en-US");
Assert.Equals(cache.GetOrDefault("Key"), "ValueForUS");
// Remove
LocaleUtils.SetThreadLanguage("zh-CN");
cache.Remove("Key");
Assert.Equals(cache.GetOrDefault("Key"), null);
LocaleUtils.SetThreadLanguage("en-US");
Assert.Equals(cache.GetOrDefault("Key"), "ValueForUS");
cache.Remove("Key");
Assert.Equals(cache.GetOrDefault("Key"), null);
}
}
}
| 33 | 60 | 0.696151 | [
"MIT"
] | 1306479602/ZKWeb | ZKWeb/ZKWeb/Tests/Cache/IsolatedKeyValueCacheTest.cs | 1,223 | C# |
using System;
using System.Collections.Generic;
using System.Text;
using System.Linq;
using System.Threading.Tasks;
using Xunit;
namespace DamienTheUnbeliever.System.Linq.Tests
{
public class ElementAtOrDefault
{
[Fact]
public void Eagerly_Validates_Source()
{
Assert.Throws<ArgumentNullException>(() =>
{
var iter = AsyncEnumerable.ElementAtOrDefault((IAsyncEnumerable<int>)null, 0);
});
}
[Fact]
public async Task Negative_Index_Returns_Default()
{
var source = Enumerable.Range(10, 10).AsAsyncEnumerable().WithTracking();
var actual = await source.ElementAtOrDefault(-5);
Assert.Equal(default, actual);
}
[Fact]
public async Task Excess_Index_Returns_Default()
{
var source = Enumerable.Range(10, 10).AsAsyncEnumerable().WithTracking();
var actual = await source.ElementAtOrDefault(25);
Assert.Equal(default, actual);
}
[Fact]
public async Task Can_Locate_Element()
{
var source = Enumerable.Range(10, 10).AsAsyncEnumerable();
var actual = await source.ElementAtOrDefault(3);
Assert.Equal(13, actual);
}
}
}
| 22.538462 | 86 | 0.673208 | [
"Apache-2.0"
] | Damien-The-Unbeliever/Linq.AsyncEnumerable | DamienTheUnbeliever.System.Linq.Tests/ElementAtOrDefault.cs | 1,174 | C# |
using CsvHelper;
using Microsoft.AspNetCore.Mvc;
using Nager.Date.WebsiteCore.Model;
using Nager.Date.WebsiteCore.Models;
using System;
using System.Globalization;
using System.IO;
using System.Linq;
namespace Nager.Date.WebsiteCore.Controllers
{
/// <summary>
/// Public Holiday
/// </summary>
[Route("[controller]")]
[ApiExplorerSettings(IgnoreApi = true)]
public class PublicHolidayController : Controller
{
[Route("Country/{countrycode}/{year}")]
[Route("Country/{countrycode}")]
public IActionResult Country(string countrycode, int year = 0)
{
if (year == 0)
{
year = DateTime.Now.Year;
}
if (!Enum.TryParse(countrycode, true, out CountryCode countryCode))
{
return NotFound();
}
var country = new Country.CountryProvider().GetCountry(countryCode.ToString());
var item = new PublicHolidayInfo
{
Country = country.CommonName,
CountryCode = countrycode,
Year = year
};
return View(item);
}
[Route("Country/{countrycode}/{year}/csv")]
public ActionResult DownloadCsv(string countrycode, int year = 0)
{
if (year == 0)
{
year = DateTime.Now.Year;
}
if (!Enum.TryParse(countrycode, true, out CountryCode countryCode))
{
return NotFound();
}
var items = DateSystem.GetPublicHoliday(year, countryCode).ToList();
if (items.Count > 0)
{
using (var memoryStream = new MemoryStream())
using (var streamWriter = new StreamWriter(memoryStream))
using (var csv = new CsvWriter(streamWriter, CultureInfo.InvariantCulture))
{
csv.WriteRecords(items.Select(o => new PublicHolidayCsv(o)));
streamWriter.Flush();
var csvData = memoryStream.ToArray();
var result = new FileContentResult(csvData, "application/octet-stream")
{
FileDownloadName = $"publicholiday.{countrycode}.{year}.csv"
};
return result;
}
}
return NotFound();
}
}
}
| 29.25 | 91 | 0.525438 | [
"MIT"
] | cgvdw/Nager.Date | Src/Nager.Date.WebsiteCore/Controllers/PublicHolidayController.cs | 2,459 | C# |
// <auto-generated />
using System;
using MRPanel.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Metadata;
using Microsoft.EntityFrameworkCore.Migrations;
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
namespace MRPanel.Migrations
{
[DbContext(typeof(MRPanelDbContext))]
[Migration("20180726102703_Upgrade_ABP_3.8.0")]
partial class Upgrade_ABP_380
{
protected override void BuildTargetModel(ModelBuilder modelBuilder)
{
#pragma warning disable 612, 618
modelBuilder
.HasAnnotation("ProductVersion", "2.1.1-rtm-30846")
.HasAnnotation("Relational:MaxIdentifierLength", 128)
.HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn);
modelBuilder.Entity("Abp.Application.Editions.Edition", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int")
.HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn);
b.Property<DateTime>("CreationTime")
.HasColumnType("datetime2");
b.Property<long?>("CreatorUserId")
.HasColumnType("bigint");
b.Property<long?>("DeleterUserId")
.HasColumnType("bigint");
b.Property<DateTime?>("DeletionTime")
.HasColumnType("datetime2");
b.Property<string>("DisplayName")
.IsRequired()
.HasColumnType("nvarchar(64)")
.HasMaxLength(64);
b.Property<bool>("IsDeleted")
.HasColumnType("bit");
b.Property<DateTime?>("LastModificationTime")
.HasColumnType("datetime2");
b.Property<long?>("LastModifierUserId")
.HasColumnType("bigint");
b.Property<string>("Name")
.IsRequired()
.HasColumnType("nvarchar(32)")
.HasMaxLength(32);
b.HasKey("Id");
b.ToTable("AbpEditions");
});
modelBuilder.Entity("Abp.Application.Features.FeatureSetting", b =>
{
b.Property<long>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("bigint")
.HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn);
b.Property<DateTime>("CreationTime")
.HasColumnType("datetime2");
b.Property<long?>("CreatorUserId")
.HasColumnType("bigint");
b.Property<string>("Discriminator")
.IsRequired()
.HasColumnType("nvarchar(max)");
b.Property<string>("Name")
.IsRequired()
.HasColumnType("nvarchar(128)")
.HasMaxLength(128);
b.Property<int?>("TenantId")
.HasColumnType("int");
b.Property<string>("Value")
.IsRequired()
.HasColumnType("nvarchar(2000)")
.HasMaxLength(2000);
b.HasKey("Id");
b.ToTable("AbpFeatures");
b.HasDiscriminator<string>("Discriminator").HasValue("FeatureSetting");
});
modelBuilder.Entity("Abp.Auditing.AuditLog", b =>
{
b.Property<long>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("bigint")
.HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn);
b.Property<string>("BrowserInfo")
.HasColumnType("nvarchar(512)")
.HasMaxLength(512);
b.Property<string>("ClientIpAddress")
.HasColumnType("nvarchar(64)")
.HasMaxLength(64);
b.Property<string>("ClientName")
.HasColumnType("nvarchar(128)")
.HasMaxLength(128);
b.Property<string>("CustomData")
.HasColumnType("nvarchar(2000)")
.HasMaxLength(2000);
b.Property<string>("Exception")
.HasColumnType("nvarchar(2000)")
.HasMaxLength(2000);
b.Property<int>("ExecutionDuration")
.HasColumnType("int");
b.Property<DateTime>("ExecutionTime")
.HasColumnType("datetime2");
b.Property<int?>("ImpersonatorTenantId")
.HasColumnType("int");
b.Property<long?>("ImpersonatorUserId")
.HasColumnType("bigint");
b.Property<string>("MethodName")
.HasColumnType("nvarchar(256)")
.HasMaxLength(256);
b.Property<string>("Parameters")
.HasColumnType("nvarchar(1024)")
.HasMaxLength(1024);
b.Property<string>("ServiceName")
.HasColumnType("nvarchar(256)")
.HasMaxLength(256);
b.Property<int?>("TenantId")
.HasColumnType("int");
b.Property<long?>("UserId")
.HasColumnType("bigint");
b.HasKey("Id");
b.HasIndex("TenantId", "ExecutionDuration");
b.HasIndex("TenantId", "ExecutionTime");
b.HasIndex("TenantId", "UserId");
b.ToTable("AbpAuditLogs");
});
modelBuilder.Entity("Abp.Authorization.PermissionSetting", b =>
{
b.Property<long>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("bigint")
.HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn);
b.Property<DateTime>("CreationTime")
.HasColumnType("datetime2");
b.Property<long?>("CreatorUserId")
.HasColumnType("bigint");
b.Property<string>("Discriminator")
.IsRequired()
.HasColumnType("nvarchar(max)");
b.Property<bool>("IsGranted")
.HasColumnType("bit");
b.Property<string>("Name")
.IsRequired()
.HasColumnType("nvarchar(128)")
.HasMaxLength(128);
b.Property<int?>("TenantId")
.HasColumnType("int");
b.HasKey("Id");
b.HasIndex("TenantId", "Name");
b.ToTable("AbpPermissions");
b.HasDiscriminator<string>("Discriminator").HasValue("PermissionSetting");
});
modelBuilder.Entity("Abp.Authorization.Roles.RoleClaim", b =>
{
b.Property<long>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("bigint")
.HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn);
b.Property<string>("ClaimType")
.HasColumnType("nvarchar(256)")
.HasMaxLength(256);
b.Property<string>("ClaimValue")
.HasColumnType("nvarchar(max)");
b.Property<DateTime>("CreationTime")
.HasColumnType("datetime2");
b.Property<long?>("CreatorUserId")
.HasColumnType("bigint");
b.Property<int>("RoleId")
.HasColumnType("int");
b.Property<int?>("TenantId")
.HasColumnType("int");
b.HasKey("Id");
b.HasIndex("RoleId");
b.HasIndex("TenantId", "ClaimType");
b.ToTable("AbpRoleClaims");
});
modelBuilder.Entity("Abp.Authorization.Users.UserAccount", b =>
{
b.Property<long>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("bigint")
.HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn);
b.Property<DateTime>("CreationTime")
.HasColumnType("datetime2");
b.Property<long?>("CreatorUserId")
.HasColumnType("bigint");
b.Property<long?>("DeleterUserId")
.HasColumnType("bigint");
b.Property<DateTime?>("DeletionTime")
.HasColumnType("datetime2");
b.Property<string>("EmailAddress")
.HasColumnType("nvarchar(256)")
.HasMaxLength(256);
b.Property<bool>("IsDeleted")
.HasColumnType("bit");
b.Property<DateTime?>("LastLoginTime")
.HasColumnType("datetime2");
b.Property<DateTime?>("LastModificationTime")
.HasColumnType("datetime2");
b.Property<long?>("LastModifierUserId")
.HasColumnType("bigint");
b.Property<int?>("TenantId")
.HasColumnType("int");
b.Property<long>("UserId")
.HasColumnType("bigint");
b.Property<long?>("UserLinkId")
.HasColumnType("bigint");
b.Property<string>("UserName")
.HasColumnType("nvarchar(256)")
.HasMaxLength(256);
b.HasKey("Id");
b.HasIndex("EmailAddress");
b.HasIndex("UserName");
b.HasIndex("TenantId", "EmailAddress");
b.HasIndex("TenantId", "UserId");
b.HasIndex("TenantId", "UserName");
b.ToTable("AbpUserAccounts");
});
modelBuilder.Entity("Abp.Authorization.Users.UserClaim", b =>
{
b.Property<long>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("bigint")
.HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn);
b.Property<string>("ClaimType")
.HasColumnType("nvarchar(256)")
.HasMaxLength(256);
b.Property<string>("ClaimValue")
.HasColumnType("nvarchar(max)");
b.Property<DateTime>("CreationTime")
.HasColumnType("datetime2");
b.Property<long?>("CreatorUserId")
.HasColumnType("bigint");
b.Property<int?>("TenantId")
.HasColumnType("int");
b.Property<long>("UserId")
.HasColumnType("bigint");
b.HasKey("Id");
b.HasIndex("UserId");
b.HasIndex("TenantId", "ClaimType");
b.ToTable("AbpUserClaims");
});
modelBuilder.Entity("Abp.Authorization.Users.UserLogin", b =>
{
b.Property<long>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("bigint")
.HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn);
b.Property<string>("LoginProvider")
.IsRequired()
.HasColumnType("nvarchar(128)")
.HasMaxLength(128);
b.Property<string>("ProviderKey")
.IsRequired()
.HasColumnType("nvarchar(256)")
.HasMaxLength(256);
b.Property<int?>("TenantId")
.HasColumnType("int");
b.Property<long>("UserId")
.HasColumnType("bigint");
b.HasKey("Id");
b.HasIndex("UserId");
b.HasIndex("TenantId", "UserId");
b.HasIndex("TenantId", "LoginProvider", "ProviderKey");
b.ToTable("AbpUserLogins");
});
modelBuilder.Entity("Abp.Authorization.Users.UserLoginAttempt", b =>
{
b.Property<long>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("bigint")
.HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn);
b.Property<string>("BrowserInfo")
.HasColumnType("nvarchar(512)")
.HasMaxLength(512);
b.Property<string>("ClientIpAddress")
.HasColumnType("nvarchar(64)")
.HasMaxLength(64);
b.Property<string>("ClientName")
.HasColumnType("nvarchar(128)")
.HasMaxLength(128);
b.Property<DateTime>("CreationTime")
.HasColumnType("datetime2");
b.Property<byte>("Result")
.HasColumnType("tinyint");
b.Property<string>("TenancyName")
.HasColumnType("nvarchar(64)")
.HasMaxLength(64);
b.Property<int?>("TenantId")
.HasColumnType("int");
b.Property<long?>("UserId")
.HasColumnType("bigint");
b.Property<string>("UserNameOrEmailAddress")
.HasColumnType("nvarchar(255)")
.HasMaxLength(255);
b.HasKey("Id");
b.HasIndex("UserId", "TenantId");
b.HasIndex("TenancyName", "UserNameOrEmailAddress", "Result");
b.ToTable("AbpUserLoginAttempts");
});
modelBuilder.Entity("Abp.Authorization.Users.UserOrganizationUnit", b =>
{
b.Property<long>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("bigint")
.HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn);
b.Property<DateTime>("CreationTime")
.HasColumnType("datetime2");
b.Property<long?>("CreatorUserId")
.HasColumnType("bigint");
b.Property<bool>("IsDeleted")
.HasColumnType("bit");
b.Property<long>("OrganizationUnitId")
.HasColumnType("bigint");
b.Property<int?>("TenantId")
.HasColumnType("int");
b.Property<long>("UserId")
.HasColumnType("bigint");
b.HasKey("Id");
b.HasIndex("TenantId", "OrganizationUnitId");
b.HasIndex("TenantId", "UserId");
b.ToTable("AbpUserOrganizationUnits");
});
modelBuilder.Entity("Abp.Authorization.Users.UserRole", b =>
{
b.Property<long>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("bigint")
.HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn);
b.Property<DateTime>("CreationTime")
.HasColumnType("datetime2");
b.Property<long?>("CreatorUserId")
.HasColumnType("bigint");
b.Property<int>("RoleId")
.HasColumnType("int");
b.Property<int?>("TenantId")
.HasColumnType("int");
b.Property<long>("UserId")
.HasColumnType("bigint");
b.HasKey("Id");
b.HasIndex("UserId");
b.HasIndex("TenantId", "RoleId");
b.HasIndex("TenantId", "UserId");
b.ToTable("AbpUserRoles");
});
modelBuilder.Entity("Abp.Authorization.Users.UserToken", b =>
{
b.Property<long>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("bigint")
.HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn);
b.Property<string>("LoginProvider")
.HasColumnType("nvarchar(64)")
.HasMaxLength(64);
b.Property<string>("Name")
.HasColumnType("nvarchar(128)")
.HasMaxLength(128);
b.Property<int?>("TenantId")
.HasColumnType("int");
b.Property<long>("UserId")
.HasColumnType("bigint");
b.Property<string>("Value")
.HasColumnType("nvarchar(512)")
.HasMaxLength(512);
b.HasKey("Id");
b.HasIndex("UserId");
b.HasIndex("TenantId", "UserId");
b.ToTable("AbpUserTokens");
});
modelBuilder.Entity("Abp.BackgroundJobs.BackgroundJobInfo", b =>
{
b.Property<long>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("bigint")
.HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn);
b.Property<DateTime>("CreationTime")
.HasColumnType("datetime2");
b.Property<long?>("CreatorUserId")
.HasColumnType("bigint");
b.Property<bool>("IsAbandoned")
.HasColumnType("bit");
b.Property<string>("JobArgs")
.IsRequired()
.HasColumnType("nvarchar(max)")
.HasMaxLength(1048576);
b.Property<string>("JobType")
.IsRequired()
.HasColumnType("nvarchar(512)")
.HasMaxLength(512);
b.Property<DateTime?>("LastTryTime")
.HasColumnType("datetime2");
b.Property<DateTime>("NextTryTime")
.HasColumnType("datetime2");
b.Property<byte>("Priority")
.HasColumnType("tinyint");
b.Property<short>("TryCount")
.HasColumnType("smallint");
b.HasKey("Id");
b.HasIndex("IsAbandoned", "NextTryTime");
b.ToTable("AbpBackgroundJobs");
});
modelBuilder.Entity("Abp.Configuration.Setting", b =>
{
b.Property<long>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("bigint")
.HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn);
b.Property<DateTime>("CreationTime")
.HasColumnType("datetime2");
b.Property<long?>("CreatorUserId")
.HasColumnType("bigint");
b.Property<DateTime?>("LastModificationTime")
.HasColumnType("datetime2");
b.Property<long?>("LastModifierUserId")
.HasColumnType("bigint");
b.Property<string>("Name")
.IsRequired()
.HasColumnType("nvarchar(256)")
.HasMaxLength(256);
b.Property<int?>("TenantId")
.HasColumnType("int");
b.Property<long?>("UserId")
.HasColumnType("bigint");
b.Property<string>("Value")
.HasColumnType("nvarchar(2000)")
.HasMaxLength(2000);
b.HasKey("Id");
b.HasIndex("UserId");
b.HasIndex("TenantId", "Name");
b.ToTable("AbpSettings");
});
modelBuilder.Entity("Abp.EntityHistory.EntityChange", b =>
{
b.Property<long>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("bigint")
.HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn);
b.Property<DateTime>("ChangeTime")
.HasColumnType("datetime2");
b.Property<byte>("ChangeType")
.HasColumnType("tinyint");
b.Property<long>("EntityChangeSetId")
.HasColumnType("bigint");
b.Property<string>("EntityId")
.HasColumnType("nvarchar(48)")
.HasMaxLength(48);
b.Property<string>("EntityTypeFullName")
.HasColumnType("nvarchar(192)")
.HasMaxLength(192);
b.Property<int?>("TenantId")
.HasColumnType("int");
b.HasKey("Id");
b.HasIndex("EntityChangeSetId");
b.HasIndex("EntityTypeFullName", "EntityId");
b.ToTable("AbpEntityChanges");
});
modelBuilder.Entity("Abp.EntityHistory.EntityChangeSet", b =>
{
b.Property<long>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("bigint")
.HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn);
b.Property<string>("BrowserInfo")
.HasColumnType("nvarchar(512)")
.HasMaxLength(512);
b.Property<string>("ClientIpAddress")
.HasColumnType("nvarchar(64)")
.HasMaxLength(64);
b.Property<string>("ClientName")
.HasColumnType("nvarchar(128)")
.HasMaxLength(128);
b.Property<DateTime>("CreationTime")
.HasColumnType("datetime2");
b.Property<string>("ExtensionData")
.HasColumnType("nvarchar(max)");
b.Property<int?>("ImpersonatorTenantId")
.HasColumnType("int");
b.Property<long?>("ImpersonatorUserId")
.HasColumnType("bigint");
b.Property<string>("Reason")
.HasColumnType("nvarchar(256)")
.HasMaxLength(256);
b.Property<int?>("TenantId")
.HasColumnType("int");
b.Property<long?>("UserId")
.HasColumnType("bigint");
b.HasKey("Id");
b.HasIndex("TenantId", "CreationTime");
b.HasIndex("TenantId", "Reason");
b.HasIndex("TenantId", "UserId");
b.ToTable("AbpEntityChangeSets");
});
modelBuilder.Entity("Abp.EntityHistory.EntityPropertyChange", b =>
{
b.Property<long>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("bigint")
.HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn);
b.Property<long>("EntityChangeId")
.HasColumnType("bigint");
b.Property<string>("NewValue")
.HasColumnType("nvarchar(512)")
.HasMaxLength(512);
b.Property<string>("OriginalValue")
.HasColumnType("nvarchar(512)")
.HasMaxLength(512);
b.Property<string>("PropertyName")
.HasColumnType("nvarchar(96)")
.HasMaxLength(96);
b.Property<string>("PropertyTypeFullName")
.HasColumnType("nvarchar(192)")
.HasMaxLength(192);
b.Property<int?>("TenantId")
.HasColumnType("int");
b.HasKey("Id");
b.HasIndex("EntityChangeId");
b.ToTable("AbpEntityPropertyChanges");
});
modelBuilder.Entity("Abp.Localization.ApplicationLanguage", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int")
.HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn);
b.Property<DateTime>("CreationTime")
.HasColumnType("datetime2");
b.Property<long?>("CreatorUserId")
.HasColumnType("bigint");
b.Property<long?>("DeleterUserId")
.HasColumnType("bigint");
b.Property<DateTime?>("DeletionTime")
.HasColumnType("datetime2");
b.Property<string>("DisplayName")
.IsRequired()
.HasColumnType("nvarchar(64)")
.HasMaxLength(64);
b.Property<string>("Icon")
.HasColumnType("nvarchar(128)")
.HasMaxLength(128);
b.Property<bool>("IsDeleted")
.HasColumnType("bit");
b.Property<bool>("IsDisabled")
.HasColumnType("bit");
b.Property<DateTime?>("LastModificationTime")
.HasColumnType("datetime2");
b.Property<long?>("LastModifierUserId")
.HasColumnType("bigint");
b.Property<string>("Name")
.IsRequired()
.HasColumnType("nvarchar(10)")
.HasMaxLength(10);
b.Property<int?>("TenantId")
.HasColumnType("int");
b.HasKey("Id");
b.HasIndex("TenantId", "Name");
b.ToTable("AbpLanguages");
});
modelBuilder.Entity("Abp.Localization.ApplicationLanguageText", b =>
{
b.Property<long>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("bigint")
.HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn);
b.Property<DateTime>("CreationTime")
.HasColumnType("datetime2");
b.Property<long?>("CreatorUserId")
.HasColumnType("bigint");
b.Property<string>("Key")
.IsRequired()
.HasColumnType("nvarchar(256)")
.HasMaxLength(256);
b.Property<string>("LanguageName")
.IsRequired()
.HasColumnType("nvarchar(10)")
.HasMaxLength(10);
b.Property<DateTime?>("LastModificationTime")
.HasColumnType("datetime2");
b.Property<long?>("LastModifierUserId")
.HasColumnType("bigint");
b.Property<string>("Source")
.IsRequired()
.HasColumnType("nvarchar(128)")
.HasMaxLength(128);
b.Property<int?>("TenantId")
.HasColumnType("int");
b.Property<string>("Value")
.IsRequired()
.HasColumnType("nvarchar(max)")
.HasMaxLength(67108864);
b.HasKey("Id");
b.HasIndex("TenantId", "Source", "LanguageName", "Key");
b.ToTable("AbpLanguageTexts");
});
modelBuilder.Entity("Abp.Notifications.NotificationInfo", b =>
{
b.Property<Guid>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("uniqueidentifier");
b.Property<DateTime>("CreationTime")
.HasColumnType("datetime2");
b.Property<long?>("CreatorUserId")
.HasColumnType("bigint");
b.Property<string>("Data")
.HasColumnType("nvarchar(max)")
.HasMaxLength(1048576);
b.Property<string>("DataTypeName")
.HasColumnType("nvarchar(512)")
.HasMaxLength(512);
b.Property<string>("EntityId")
.HasColumnType("nvarchar(96)")
.HasMaxLength(96);
b.Property<string>("EntityTypeAssemblyQualifiedName")
.HasColumnType("nvarchar(512)")
.HasMaxLength(512);
b.Property<string>("EntityTypeName")
.HasColumnType("nvarchar(250)")
.HasMaxLength(250);
b.Property<string>("ExcludedUserIds")
.HasColumnType("nvarchar(max)")
.HasMaxLength(131072);
b.Property<string>("NotificationName")
.IsRequired()
.HasColumnType("nvarchar(96)")
.HasMaxLength(96);
b.Property<byte>("Severity")
.HasColumnType("tinyint");
b.Property<string>("TenantIds")
.HasColumnType("nvarchar(max)")
.HasMaxLength(131072);
b.Property<string>("UserIds")
.HasColumnType("nvarchar(max)")
.HasMaxLength(131072);
b.HasKey("Id");
b.ToTable("AbpNotifications");
});
modelBuilder.Entity("Abp.Notifications.NotificationSubscriptionInfo", b =>
{
b.Property<Guid>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("uniqueidentifier");
b.Property<DateTime>("CreationTime")
.HasColumnType("datetime2");
b.Property<long?>("CreatorUserId")
.HasColumnType("bigint");
b.Property<string>("EntityId")
.HasColumnType("nvarchar(96)")
.HasMaxLength(96);
b.Property<string>("EntityTypeAssemblyQualifiedName")
.HasColumnType("nvarchar(512)")
.HasMaxLength(512);
b.Property<string>("EntityTypeName")
.HasColumnType("nvarchar(250)")
.HasMaxLength(250);
b.Property<string>("NotificationName")
.HasColumnType("nvarchar(96)")
.HasMaxLength(96);
b.Property<int?>("TenantId")
.HasColumnType("int");
b.Property<long>("UserId")
.HasColumnType("bigint");
b.HasKey("Id");
b.HasIndex("NotificationName", "EntityTypeName", "EntityId", "UserId");
b.HasIndex("TenantId", "NotificationName", "EntityTypeName", "EntityId", "UserId");
b.ToTable("AbpNotificationSubscriptions");
});
modelBuilder.Entity("Abp.Notifications.TenantNotificationInfo", b =>
{
b.Property<Guid>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("uniqueidentifier");
b.Property<DateTime>("CreationTime")
.HasColumnType("datetime2");
b.Property<long?>("CreatorUserId")
.HasColumnType("bigint");
b.Property<string>("Data")
.HasColumnType("nvarchar(max)")
.HasMaxLength(1048576);
b.Property<string>("DataTypeName")
.HasColumnType("nvarchar(512)")
.HasMaxLength(512);
b.Property<string>("EntityId")
.HasColumnType("nvarchar(96)")
.HasMaxLength(96);
b.Property<string>("EntityTypeAssemblyQualifiedName")
.HasColumnType("nvarchar(512)")
.HasMaxLength(512);
b.Property<string>("EntityTypeName")
.HasColumnType("nvarchar(250)")
.HasMaxLength(250);
b.Property<string>("NotificationName")
.IsRequired()
.HasColumnType("nvarchar(96)")
.HasMaxLength(96);
b.Property<byte>("Severity")
.HasColumnType("tinyint");
b.Property<int?>("TenantId")
.HasColumnType("int");
b.HasKey("Id");
b.HasIndex("TenantId");
b.ToTable("AbpTenantNotifications");
});
modelBuilder.Entity("Abp.Notifications.UserNotificationInfo", b =>
{
b.Property<Guid>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("uniqueidentifier");
b.Property<DateTime>("CreationTime")
.HasColumnType("datetime2");
b.Property<int>("State")
.HasColumnType("int");
b.Property<int?>("TenantId")
.HasColumnType("int");
b.Property<Guid>("TenantNotificationId")
.HasColumnType("uniqueidentifier");
b.Property<long>("UserId")
.HasColumnType("bigint");
b.HasKey("Id");
b.HasIndex("UserId", "State", "CreationTime");
b.ToTable("AbpUserNotifications");
});
modelBuilder.Entity("Abp.Organizations.OrganizationUnit", b =>
{
b.Property<long>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("bigint")
.HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn);
b.Property<string>("Code")
.IsRequired()
.HasColumnType("nvarchar(95)")
.HasMaxLength(95);
b.Property<DateTime>("CreationTime")
.HasColumnType("datetime2");
b.Property<long?>("CreatorUserId")
.HasColumnType("bigint");
b.Property<long?>("DeleterUserId")
.HasColumnType("bigint");
b.Property<DateTime?>("DeletionTime")
.HasColumnType("datetime2");
b.Property<string>("DisplayName")
.IsRequired()
.HasColumnType("nvarchar(128)")
.HasMaxLength(128);
b.Property<bool>("IsDeleted")
.HasColumnType("bit");
b.Property<DateTime?>("LastModificationTime")
.HasColumnType("datetime2");
b.Property<long?>("LastModifierUserId")
.HasColumnType("bigint");
b.Property<long?>("ParentId")
.HasColumnType("bigint");
b.Property<int?>("TenantId")
.HasColumnType("int");
b.HasKey("Id");
b.HasIndex("ParentId");
b.HasIndex("TenantId", "Code");
b.ToTable("AbpOrganizationUnits");
});
modelBuilder.Entity("MRPanel.Authorization.Roles.Role", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int")
.HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn);
b.Property<string>("ConcurrencyStamp")
.IsConcurrencyToken()
.HasColumnType("nvarchar(128)")
.HasMaxLength(128);
b.Property<DateTime>("CreationTime")
.HasColumnType("datetime2");
b.Property<long?>("CreatorUserId")
.HasColumnType("bigint");
b.Property<long?>("DeleterUserId")
.HasColumnType("bigint");
b.Property<DateTime?>("DeletionTime")
.HasColumnType("datetime2");
b.Property<string>("Description")
.HasColumnType("nvarchar(max)")
.HasMaxLength(5000);
b.Property<string>("DisplayName")
.IsRequired()
.HasColumnType("nvarchar(64)")
.HasMaxLength(64);
b.Property<bool>("IsDefault")
.HasColumnType("bit");
b.Property<bool>("IsDeleted")
.HasColumnType("bit");
b.Property<bool>("IsStatic")
.HasColumnType("bit");
b.Property<DateTime?>("LastModificationTime")
.HasColumnType("datetime2");
b.Property<long?>("LastModifierUserId")
.HasColumnType("bigint");
b.Property<string>("Name")
.IsRequired()
.HasColumnType("nvarchar(32)")
.HasMaxLength(32);
b.Property<string>("NormalizedName")
.IsRequired()
.HasColumnType("nvarchar(32)")
.HasMaxLength(32);
b.Property<int?>("TenantId")
.HasColumnType("int");
b.HasKey("Id");
b.HasIndex("CreatorUserId");
b.HasIndex("DeleterUserId");
b.HasIndex("LastModifierUserId");
b.HasIndex("TenantId", "NormalizedName");
b.ToTable("AbpRoles");
});
modelBuilder.Entity("MRPanel.Authorization.Users.User", b =>
{
b.Property<long>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("bigint")
.HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn);
b.Property<int>("AccessFailedCount")
.HasColumnType("int");
b.Property<string>("AuthenticationSource")
.HasColumnType("nvarchar(64)")
.HasMaxLength(64);
b.Property<string>("ConcurrencyStamp")
.IsConcurrencyToken()
.HasColumnType("nvarchar(128)")
.HasMaxLength(128);
b.Property<DateTime>("CreationTime")
.HasColumnType("datetime2");
b.Property<long?>("CreatorUserId")
.HasColumnType("bigint");
b.Property<long?>("DeleterUserId")
.HasColumnType("bigint");
b.Property<DateTime?>("DeletionTime")
.HasColumnType("datetime2");
b.Property<string>("EmailAddress")
.IsRequired()
.HasColumnType("nvarchar(256)")
.HasMaxLength(256);
b.Property<string>("EmailConfirmationCode")
.HasColumnType("nvarchar(328)")
.HasMaxLength(328);
b.Property<bool>("IsActive")
.HasColumnType("bit");
b.Property<bool>("IsDeleted")
.HasColumnType("bit");
b.Property<bool>("IsEmailConfirmed")
.HasColumnType("bit");
b.Property<bool>("IsLockoutEnabled")
.HasColumnType("bit");
b.Property<bool>("IsPhoneNumberConfirmed")
.HasColumnType("bit");
b.Property<bool>("IsTwoFactorEnabled")
.HasColumnType("bit");
b.Property<DateTime?>("LastLoginTime")
.HasColumnType("datetime2");
b.Property<DateTime?>("LastModificationTime")
.HasColumnType("datetime2");
b.Property<long?>("LastModifierUserId")
.HasColumnType("bigint");
b.Property<DateTime?>("LockoutEndDateUtc")
.HasColumnType("datetime2");
b.Property<string>("Name")
.IsRequired()
.HasColumnType("nvarchar(32)")
.HasMaxLength(32);
b.Property<string>("NormalizedEmailAddress")
.IsRequired()
.HasColumnType("nvarchar(256)")
.HasMaxLength(256);
b.Property<string>("NormalizedUserName")
.IsRequired()
.HasColumnType("nvarchar(256)")
.HasMaxLength(256);
b.Property<string>("Password")
.IsRequired()
.HasColumnType("nvarchar(128)")
.HasMaxLength(128);
b.Property<string>("PasswordResetCode")
.HasColumnType("nvarchar(328)")
.HasMaxLength(328);
b.Property<string>("PhoneNumber")
.HasColumnType("nvarchar(32)")
.HasMaxLength(32);
b.Property<string>("SecurityStamp")
.HasColumnType("nvarchar(128)")
.HasMaxLength(128);
b.Property<string>("Surname")
.IsRequired()
.HasColumnType("nvarchar(32)")
.HasMaxLength(32);
b.Property<int?>("TenantId")
.HasColumnType("int");
b.Property<string>("UserName")
.IsRequired()
.HasColumnType("nvarchar(256)")
.HasMaxLength(256);
b.HasKey("Id");
b.HasIndex("CreatorUserId");
b.HasIndex("DeleterUserId");
b.HasIndex("LastModifierUserId");
b.HasIndex("TenantId", "NormalizedEmailAddress");
b.HasIndex("TenantId", "NormalizedUserName");
b.ToTable("AbpUsers");
});
modelBuilder.Entity("MRPanel.MultiTenancy.Tenant", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int")
.HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn);
b.Property<string>("ConnectionString")
.HasColumnType("nvarchar(1024)")
.HasMaxLength(1024);
b.Property<DateTime>("CreationTime")
.HasColumnType("datetime2");
b.Property<long?>("CreatorUserId")
.HasColumnType("bigint");
b.Property<long?>("DeleterUserId")
.HasColumnType("bigint");
b.Property<DateTime?>("DeletionTime")
.HasColumnType("datetime2");
b.Property<int?>("EditionId")
.HasColumnType("int");
b.Property<bool>("IsActive")
.HasColumnType("bit");
b.Property<bool>("IsDeleted")
.HasColumnType("bit");
b.Property<DateTime?>("LastModificationTime")
.HasColumnType("datetime2");
b.Property<long?>("LastModifierUserId")
.HasColumnType("bigint");
b.Property<string>("Name")
.IsRequired()
.HasColumnType("nvarchar(128)")
.HasMaxLength(128);
b.Property<string>("TenancyName")
.IsRequired()
.HasColumnType("nvarchar(64)")
.HasMaxLength(64);
b.HasKey("Id");
b.HasIndex("CreatorUserId");
b.HasIndex("DeleterUserId");
b.HasIndex("EditionId");
b.HasIndex("LastModifierUserId");
b.HasIndex("TenancyName");
b.ToTable("AbpTenants");
});
modelBuilder.Entity("Abp.Application.Features.EditionFeatureSetting", b =>
{
b.HasBaseType("Abp.Application.Features.FeatureSetting");
b.Property<int>("EditionId")
.HasColumnType("int");
b.HasIndex("EditionId", "Name");
b.ToTable("AbpFeatures");
b.HasDiscriminator().HasValue("EditionFeatureSetting");
});
modelBuilder.Entity("Abp.MultiTenancy.TenantFeatureSetting", b =>
{
b.HasBaseType("Abp.Application.Features.FeatureSetting");
b.HasIndex("TenantId", "Name");
b.ToTable("AbpFeatures");
b.HasDiscriminator().HasValue("TenantFeatureSetting");
});
modelBuilder.Entity("Abp.Authorization.Roles.RolePermissionSetting", b =>
{
b.HasBaseType("Abp.Authorization.PermissionSetting");
b.Property<int>("RoleId")
.HasColumnType("int");
b.HasIndex("RoleId");
b.ToTable("AbpPermissions");
b.HasDiscriminator().HasValue("RolePermissionSetting");
});
modelBuilder.Entity("Abp.Authorization.Users.UserPermissionSetting", b =>
{
b.HasBaseType("Abp.Authorization.PermissionSetting");
b.Property<long>("UserId")
.HasColumnType("bigint");
b.HasIndex("UserId");
b.ToTable("AbpPermissions");
b.HasDiscriminator().HasValue("UserPermissionSetting");
});
modelBuilder.Entity("Abp.Authorization.Roles.RoleClaim", b =>
{
b.HasOne("MRPanel.Authorization.Roles.Role")
.WithMany("Claims")
.HasForeignKey("RoleId")
.OnDelete(DeleteBehavior.Cascade);
});
modelBuilder.Entity("Abp.Authorization.Users.UserClaim", b =>
{
b.HasOne("MRPanel.Authorization.Users.User")
.WithMany("Claims")
.HasForeignKey("UserId")
.OnDelete(DeleteBehavior.Cascade);
});
modelBuilder.Entity("Abp.Authorization.Users.UserLogin", b =>
{
b.HasOne("MRPanel.Authorization.Users.User")
.WithMany("Logins")
.HasForeignKey("UserId")
.OnDelete(DeleteBehavior.Cascade);
});
modelBuilder.Entity("Abp.Authorization.Users.UserRole", b =>
{
b.HasOne("MRPanel.Authorization.Users.User")
.WithMany("Roles")
.HasForeignKey("UserId")
.OnDelete(DeleteBehavior.Cascade);
});
modelBuilder.Entity("Abp.Authorization.Users.UserToken", b =>
{
b.HasOne("MRPanel.Authorization.Users.User")
.WithMany("Tokens")
.HasForeignKey("UserId")
.OnDelete(DeleteBehavior.Cascade);
});
modelBuilder.Entity("Abp.Configuration.Setting", b =>
{
b.HasOne("MRPanel.Authorization.Users.User")
.WithMany("Settings")
.HasForeignKey("UserId");
});
modelBuilder.Entity("Abp.EntityHistory.EntityChange", b =>
{
b.HasOne("Abp.EntityHistory.EntityChangeSet")
.WithMany("EntityChanges")
.HasForeignKey("EntityChangeSetId")
.OnDelete(DeleteBehavior.Cascade);
});
modelBuilder.Entity("Abp.EntityHistory.EntityPropertyChange", b =>
{
b.HasOne("Abp.EntityHistory.EntityChange")
.WithMany("PropertyChanges")
.HasForeignKey("EntityChangeId")
.OnDelete(DeleteBehavior.Cascade);
});
modelBuilder.Entity("Abp.Organizations.OrganizationUnit", b =>
{
b.HasOne("Abp.Organizations.OrganizationUnit", "Parent")
.WithMany("Children")
.HasForeignKey("ParentId");
});
modelBuilder.Entity("MRPanel.Authorization.Roles.Role", b =>
{
b.HasOne("MRPanel.Authorization.Users.User", "CreatorUser")
.WithMany()
.HasForeignKey("CreatorUserId");
b.HasOne("MRPanel.Authorization.Users.User", "DeleterUser")
.WithMany()
.HasForeignKey("DeleterUserId");
b.HasOne("MRPanel.Authorization.Users.User", "LastModifierUser")
.WithMany()
.HasForeignKey("LastModifierUserId");
});
modelBuilder.Entity("MRPanel.Authorization.Users.User", b =>
{
b.HasOne("MRPanel.Authorization.Users.User", "CreatorUser")
.WithMany()
.HasForeignKey("CreatorUserId");
b.HasOne("MRPanel.Authorization.Users.User", "DeleterUser")
.WithMany()
.HasForeignKey("DeleterUserId");
b.HasOne("MRPanel.Authorization.Users.User", "LastModifierUser")
.WithMany()
.HasForeignKey("LastModifierUserId");
});
modelBuilder.Entity("MRPanel.MultiTenancy.Tenant", b =>
{
b.HasOne("MRPanel.Authorization.Users.User", "CreatorUser")
.WithMany()
.HasForeignKey("CreatorUserId");
b.HasOne("MRPanel.Authorization.Users.User", "DeleterUser")
.WithMany()
.HasForeignKey("DeleterUserId");
b.HasOne("Abp.Application.Editions.Edition", "Edition")
.WithMany()
.HasForeignKey("EditionId");
b.HasOne("MRPanel.Authorization.Users.User", "LastModifierUser")
.WithMany()
.HasForeignKey("LastModifierUserId");
});
modelBuilder.Entity("Abp.Application.Features.EditionFeatureSetting", b =>
{
b.HasOne("Abp.Application.Editions.Edition", "Edition")
.WithMany()
.HasForeignKey("EditionId")
.OnDelete(DeleteBehavior.Cascade);
});
modelBuilder.Entity("Abp.Authorization.Roles.RolePermissionSetting", b =>
{
b.HasOne("MRPanel.Authorization.Roles.Role")
.WithMany("Permissions")
.HasForeignKey("RoleId")
.OnDelete(DeleteBehavior.Cascade);
});
modelBuilder.Entity("Abp.Authorization.Users.UserPermissionSetting", b =>
{
b.HasOne("MRPanel.Authorization.Users.User")
.WithMany("Permissions")
.HasForeignKey("UserId")
.OnDelete(DeleteBehavior.Cascade);
});
#pragma warning restore 612, 618
}
}
}
| 36.795322 | 125 | 0.444904 | [
"MIT"
] | iPazooki/MRPanel | aspnet-core/src/MRPanel.EntityFrameworkCore/Migrations/20180726102703_Upgrade_ABP_3.8.0.Designer.cs | 56,628 | C# |
// Copyright (c) Josef Pihrt. All rights reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
namespace Roslynator.CSharp.Refactorings.Test
{
internal class ExtractExpressionFromConditionRefactoring
{
public static void MethodName()
{
bool f = false;
bool f2 = false;
bool f3 = false;
bool f4 = false;
if (f && f2)
{
Do();
}
if (f && f2 && f3 && f4)
{
MethodName();
MethodName();
}
if (f && f2 && f3 && f4)
MethodName();
if (f || f2 || f3 || f4)
{
MethodName();
MethodName();
}
if (f || f2 || f3 || f4)
MethodName();
while (f && f2 && f3 && f4)
{
MethodName();
MethodName();
}
while (f && f2 && f3 && f4)
MethodName();
while (f || f2 || f3 || f4)
{
MethodName();
MethodName();
}
while (f || f2 || f3 || f4)
MethodName();
}
private static void Do()
{
}
}
}
| 22.111111 | 160 | 0.380474 | [
"Apache-2.0"
] | TechnoridersForks/Roslynator | source/Test/RefactoringsTest/ExtractExpressionFromConditionRefactoring.cs | 1,395 | C# |
using System;
using System.Web.UI;
using Umbraco.Web.Install;
namespace Umbraco.Web.UI.Install.Steps
{
public abstract class StepUserControl : UserControl
{
protected string GetCurrentStep()
{
var defaultPage = (Default) Page;
return defaultPage.step.Value;
}
protected virtual void GotoNextStep(object sender, EventArgs e)
{
InstallHelper.RedirectToNextStep(Page, GetCurrentStep());
}
}
} | 25.35 | 72 | 0.61144 | [
"MIT"
] | AndyButland/Umbraco-CMS | src/Umbraco.Web.UI/install/steps/StepUserControl.cs | 509 | C# |
// ------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License (MIT). See License.txt in the repo root for license information.
// ------------------------------------------------------------
namespace Microsoft.ServiceFabric.Actors.Generator
{
using System;
using System.Collections.Generic;
using System.Fabric.Management.ServiceModel;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Threading;
using System.Xml;
using Microsoft.ServiceFabric.Actors.Runtime;
using Microsoft.ServiceFabric.Services.Remoting;
using StartupServicesUtility;
/// <summary>
/// ServiceManifestEntryPointType decides which kind of service manifest exe host is generated. By default the existing behavior of serviceName.exe will be used.
/// </summary>
internal enum SvcManifestEntryPointType
{
/// <summary>
/// Default behavior of ServiceName.exe
/// </summary>
Exe,
/// <summary>
/// ServiceName without any extension is generated as the program in the exehost. This can be used on both windows/linux in a self contained deployment.
/// </summary>
NoExtension,
/// <summary>
/// ServiceName.dll with the external program "dotnet", is generated in the exehost. This can be used on both windows/linux in a framework dependant deployment.
/// </summary>
ExternalExecutable,
}
// generates the service manifest for the actor implementations
internal class ManifestGenerator
{
private const string DefaultPartitionCount = "10";
private const string NoneStatePersistenceTargetReplicaDefaultValue = "1";
private const string NoneStatePersistenceMinReplicaDefaultValue = "1";
private const string PersistedStateTargetReplicaDefaultValue = "3";
private const string PersistedStateMinReplicaDefaultValue = "3";
private const string ApplicationManifestFileName = "ApplicationManifest.xml";
private const string ServiceManifestFileName = "ServiceManifest.xml";
private const string ConfigSettingsFileName = "Settings.xml";
private const string ExtensionSchemaNamespace = @"http://schemas.microsoft.com/2015/03/fabact-no-schema";
private const string GeneratedServiceTypeExtensionName = "__GeneratedServiceType__";
private const string GeneratedNamesRootElementName = "GeneratedNames";
private const string GeneratedNamesAttributeName = "Name";
private const string GeneratedDefaultServiceName = "DefaultService";
private const string GeneratedServiceEndpointName = "ServiceEndpoint";
private const string GeneratedServiceEndpointV2Name = "ServiceEndpointV2";
private const string GeneratedServiceEndpointWrappedMessageStackName = "ServiceEndpointV2_1";
private const string GeneratedReplicatorEndpointName = "ReplicatorEndpoint";
private const string GeneratedReplicatorConfigSectionName = "ReplicatorConfigSection";
private const string GeneratedReplicatorSecurityConfigSectionName = "ReplicatorSecurityConfigSection";
private const string GeneratedStoreConfigSectionName = "StoreConfigSection";
private const string PartitionCountParamName = "PartitionCount";
private const string MinReplicaSetSizeParamName = "MinReplicaSetSize";
private const string TargetReplicaSetSizeParamName = "TargetReplicaSetSize";
private const string ParamNameFormat = "{0}_{1}";
private const string ParamNameUsageFormat = "[{0}_{1}]";
// Generated Id is of format Guid|StatePersistenceAttributeValue. This is to handle StatePersistenceAttribute changes and generate Target/Min replica set size parameters correctly.
private const string GeneratedIdFormat = "{0}|{1}";
private const char GeneratedIdDelimiter = '|';
private const string DefaultSemanticVersion = "1.0.0";
private static readonly Dictionary<string, Func<ActorTypeInformation, string>> GeneratedNameFunctions = new Dictionary
<string, Func<ActorTypeInformation, string>>
{
{ GeneratedDefaultServiceName, GetFabricServiceName },
{ GeneratedReplicatorEndpointName, GetFabricServiceReplicatorEndpointName },
{ GeneratedReplicatorConfigSectionName, GetFabricServiceReplicatorConfigSectionName },
{ GeneratedReplicatorSecurityConfigSectionName, GetFabricServiceReplicatorSecurityConfigSectionName },
{ GeneratedStoreConfigSectionName, GetLocalEseStoreConfigSectionName },
};
private static Context toolContext;
internal static void Generate(Arguments arguments)
{
toolContext = new Context(arguments);
toolContext.LoadExistingContents();
var serviceManifest = CreateServiceManifest(arguments.ServiceManifestEntryPointType);
var configSettings = CreateConfigSettings();
var mergedServiceManifest = MergeServiceManifest(serviceManifest);
InsertXmlCommentsAndWriteIfNeeded(
toolContext.ServiceManifestFilePath,
toolContext.ExistingServiceManifestContents,
mergedServiceManifest);
InsertXmlCommentsAndWriteIfNeeded(
toolContext.ConfigSettingsFilePath,
toolContext.ExistingConfigSettingsContents,
MergeConfigSettings(configSettings));
if (toolContext.ShouldGenerateApplicationManifest())
{
// If code enters here for ApplicationManifestGeneration.
// check if StartupServices.xml path is provided or not
// if provided add default services in StartupServices.xml
var applicationManifest = CreateApplicationManifest(mergedServiceManifest);
ApplicationManifestType latestApplicationManifestType = MergeApplicationManifest(applicationManifest);
if (toolContext.StartupServicesFlag)
{
toolContext.ExistingStartupServicesManifestType.DefaultServices
= latestApplicationManifestType.DefaultServices;
toolContext.ExistingStartupServicesManifestType.Parameters = latestApplicationManifestType.Parameters;
InsertXmlCommentsAndWriteIfNeeded(
toolContext.StartupServicesFilePath,
toolContext.ExistingStartupServicesContents,
toolContext.ExistingStartupServicesManifestType);
latestApplicationManifestType.DefaultServices = null;
latestApplicationManifestType.Parameters = null;
}
// This is existing code
InsertXmlCommentsAndWriteIfNeeded(
toolContext.ApplicationManifestFilePath,
toolContext.ExistingApplicationManifestContents,
latestApplicationManifestType);
}
}
#region Create and Merge Config Settings
private static SettingsType CreateConfigSettings()
{
var settings = new SettingsType();
var sections = new List<SettingsTypeSection>();
foreach (var actorTypeInfo in toolContext.Arguments.ActorTypes)
{
sections.AddRange(CreateConfigSections(actorTypeInfo));
}
settings.Section = sections.ToArray();
return settings;
}
private static SettingsType MergeConfigSettings(SettingsType configSettings)
{
if (string.IsNullOrEmpty(toolContext.ExistingConfigSettingsContents))
{
return configSettings;
}
var existingConfigSettings = XmlSerializationUtility.Deserialize<SettingsType>(
toolContext.ExistingConfigSettingsContents);
existingConfigSettings.Section = MergeConfigSections(existingConfigSettings.Section, configSettings.Section);
return existingConfigSettings;
}
private static IEnumerable<SettingsTypeSection> CreateConfigSections(
ActorTypeInformation actorTypeInfo)
{
var retval = new List<SettingsTypeSection>();
// add section for the replicator settings
var replicatorConfigSection = new SettingsTypeSection();
retval.Add(replicatorConfigSection);
replicatorConfigSection.Name = GetFabricServiceReplicatorConfigSectionName(actorTypeInfo);
var replicatorConfigSectionParameters = new List<SettingsTypeSectionParameter>
{
new SettingsTypeSectionParameter
{
Name = "ReplicatorEndpoint",
Value = GetFabricServiceReplicatorEndpointName(actorTypeInfo),
},
new SettingsTypeSectionParameter
{
Name = "BatchAcknowledgementInterval",
Value = "0.005", // in seconds, default to 5 milliseconds to match reliable services.
},
};
replicatorConfigSection.Parameter = replicatorConfigSectionParameters.ToArray();
// add section for the replicator security settings
var replicatorSecurityConfigSection = new SettingsTypeSection();
retval.Add(replicatorSecurityConfigSection);
replicatorSecurityConfigSection.Name = GetFabricServiceReplicatorSecurityConfigSectionName(actorTypeInfo);
var replicatorSecurityConfigParameters = new List<SettingsTypeSectionParameter>
{
new SettingsTypeSectionParameter
{
Name = ActorNameFormat.GetFabricServiceReplicatorSecurityCredentialTypeName(),
Value = "None",
},
};
replicatorSecurityConfigSection.Parameter = replicatorSecurityConfigParameters.ToArray();
return retval;
}
private static string GetLocalEseStoreConfigSectionName(ActorTypeInformation actorTypeInfo)
{
return ActorNameFormat.GetLocalEseStoreConfigSectionName(actorTypeInfo.ImplementationType);
}
private static string GetFabricServiceReplicatorConfigSectionName(ActorTypeInformation actorTypeInfo)
{
return ActorNameFormat.GetFabricServiceReplicatorConfigSectionName(actorTypeInfo.ImplementationType);
}
private static string GetFabricServiceReplicatorSecurityConfigSectionName(ActorTypeInformation actorTypeInfo)
{
return ActorNameFormat.GetFabricServiceReplicatorSecurityConfigSectionName(actorTypeInfo.ImplementationType);
}
private static SettingsTypeSection MergeConfigSection(
SettingsTypeSection existingItem,
SettingsTypeSection newItem)
{
existingItem.Parameter = MergeConfigParameters(existingItem.Parameter, newItem.Parameter);
return existingItem;
}
private static SettingsTypeSection[] MergeConfigSections(
IEnumerable<SettingsTypeSection> existingItems,
IEnumerable<SettingsTypeSection> newItems)
{
return MergeItems(
existingItems,
newItems,
(i1, i2) => (string.CompareOrdinal(i1.Name, i2.Name) == 0),
MergeConfigSection,
i1 => toolContext.ShouldKeepConfigSection(i1.Name));
}
private static SettingsTypeSectionParameter MergeConfigParameter(
SettingsTypeSectionParameter existingItem,
SettingsTypeSectionParameter newItem)
{
return existingItem;
}
private static SettingsTypeSectionParameter[] MergeConfigParameters(
IEnumerable<SettingsTypeSectionParameter> existingItems,
IEnumerable<SettingsTypeSectionParameter> newItems)
{
return MergeItems(
existingItems,
newItems,
(i1, i2) => (string.CompareOrdinal(i1.Name, i2.Name) == 0),
MergeConfigParameter);
}
#endregion
#region Create and Merge Service Manifest
private static ServiceManifestType CreateServiceManifest(SvcManifestEntryPointType serviceManifestEntryPointType)
{
var serviceManifest = new ServiceManifestType
{
Name = ActorNameFormat.GetFabricServicePackageName(toolContext.Arguments.ServicePackageNamePrefix),
Version = GetVersion(),
};
var serviceTypeList = new List<ServiceTypeType>();
var endpointResourceList = new List<EndpointType>();
foreach (var actorTypeInfo in toolContext.Arguments.ActorTypes)
{
serviceTypeList.Add(CreateServiceTypeType(actorTypeInfo));
endpointResourceList.AddRange(CreateEndpointResources(actorTypeInfo));
}
serviceManifest.ServiceTypes = new object[serviceTypeList.Count];
serviceTypeList.ToArray().CopyTo(serviceManifest.ServiceTypes, 0);
serviceManifest.CodePackage = new CodePackageType[1];
serviceManifest.CodePackage[0] = CreateCodePackage(serviceManifestEntryPointType);
serviceManifest.ConfigPackage = new ConfigPackageType[1];
serviceManifest.ConfigPackage[0] = CreateConfigPackage();
serviceManifest.Resources = new ResourcesType
{
Endpoints = endpointResourceList.ToArray(),
};
return serviceManifest;
}
private static ServiceManifestType MergeServiceManifest(ServiceManifestType serviceManifest)
{
if (string.IsNullOrEmpty(toolContext.ExistingServiceManifestContents))
{
return serviceManifest;
}
var existingServiceManifest = toolContext.ExistingServiceManifestType;
// basic properties of the service manifest
// Use new version, only when it doesn't exist.
if (string.IsNullOrEmpty(existingServiceManifest.Version))
{
existingServiceManifest.Version = serviceManifest.Version;
}
existingServiceManifest.Name = serviceManifest.Name;
// service types
existingServiceManifest.ServiceTypes = MergeServiceTypes(
existingServiceManifest,
serviceManifest);
existingServiceManifest.CodePackage = MergeCodePackages(
existingServiceManifest.CodePackage,
serviceManifest.CodePackage);
// config package
existingServiceManifest.ConfigPackage = MergeConfigPackages(
existingServiceManifest.ConfigPackage,
serviceManifest.ConfigPackage);
// endpoints
if (existingServiceManifest.Resources == null)
{
existingServiceManifest.Resources = serviceManifest.Resources;
}
else
{
existingServiceManifest.Resources.Endpoints = MergeEndpointResource(
existingServiceManifest.Resources.Endpoints,
serviceManifest.Resources.Endpoints);
}
return existingServiceManifest;
}
private static object[] MergeServiceTypes(
ServiceManifestType existingServiceManifest,
ServiceManifestType serviceManifest)
{
return MergeItems(
existingServiceManifest.ServiceTypes,
serviceManifest.ServiceTypes,
(i1, i2) =>
{
var casted1 = i1 as ServiceTypeType;
var casted2 = i2 as ServiceTypeType;
return (casted1 != null && casted2 != null) &&
string.CompareOrdinal(casted1.ServiceTypeName, casted2.ServiceTypeName) == 0;
},
MergeServiceType,
i1 => toolContext.ShouldKeepItem(GeneratedServiceTypeExtensionName, ((ServiceTypeType)i1).ServiceTypeName));
}
private static object MergeServiceType(
object existingItem,
object newItem)
{
var existingCasted = existingItem as ServiceTypeType;
var newCasted = newItem as ServiceTypeType;
if (newCasted == null)
{
return existingItem;
}
if (existingCasted == null)
{
return newItem;
}
var mergedExtensions = MergeItems(
existingCasted.Extensions,
newCasted.Extensions,
(i1, i2) => string.CompareOrdinal(i1.Name, i2.Name) == 0,
MergeExtension);
if (existingItem.GetType() != newItem.GetType())
{
newCasted.LoadMetrics = existingCasted.LoadMetrics;
newCasted.PlacementConstraints = existingCasted.PlacementConstraints;
newCasted.ServicePlacementPolicies = existingCasted.ServicePlacementPolicies;
existingCasted = newCasted;
}
var newStateful = newCasted as StatefulServiceTypeType;
if (existingCasted is StatefulServiceTypeType existingStateful && newStateful != null)
{
existingStateful.HasPersistedState = newStateful.HasPersistedState;
}
existingCasted.Extensions = mergedExtensions;
return existingCasted;
}
private static ExtensionsTypeExtension MergeExtension(
ExtensionsTypeExtension existingExtension,
ExtensionsTypeExtension newExtension)
{
if (existingExtension.GeneratedId != null)
{
// Only reuse from existing extension:
// 1. If existingExtension.GeneratedId has StatePersistence in it (as older service manifests didn't have StatePersistence in GeneratedId).
// 2. And StatePersistence in existingExtension.GeneratedId matches the StatePersistence in newExtension.GeneratedId
// Generated Id is of format Guid|StatePersistenceAttributeValue
var splitted = newExtension.GeneratedId.Split(GeneratedIdDelimiter);
if (splitted.Length == 2)
{
var newStatePersistenceValue = splitted[1];
if (existingExtension.GeneratedId.EndsWith(GeneratedIdDelimiter + newStatePersistenceValue))
{
newExtension.GeneratedId = existingExtension.GeneratedId;
}
}
}
return newExtension;
}
private static ServiceTypeType CreateServiceTypeType(
ActorTypeInformation actorTypeInfo)
{
// HasPersistedState flag in service manifest is set to true only when
// 1. Actor [StatePersistenceAttribute] attribute has StatePersistence.Persisted.
return new StatefulServiceTypeType
{
HasPersistedState = actorTypeInfo.StatePersistence.Equals(StatePersistence.Persisted),
ServiceTypeName = ActorNameFormat.GetFabricServiceTypeName(actorTypeInfo.ImplementationType),
Extensions = CreateServiceTypeExtensions(actorTypeInfo),
};
}
private static Dictionary<string, Func<ActorTypeInformation, string>> GetGeneratedNameFunctionForServiceEndpoint(ActorTypeInformation actorTypeInfo)
{
var generatedNameFunctions = new Dictionary<string, Func<ActorTypeInformation, string>>();
#if !DotNetCoreClr
if (Helper.IsRemotingV1(actorTypeInfo.RemotingListenerVersion))
{
generatedNameFunctions.Add(GeneratedServiceEndpointName, GetFabricServiceEndpointName);
}
#endif
if (Helper.IsRemotingV2(actorTypeInfo.RemotingListenerVersion))
{
generatedNameFunctions.Add(GeneratedServiceEndpointV2Name, GetFabricServiceV2EndpointName);
}
if (Helper.IsRemotingV2_1(actorTypeInfo.RemotingListenerVersion))
{
generatedNameFunctions.Add(GeneratedServiceEndpointWrappedMessageStackName, GetGeneratedServiceEndpointWrappedMessageStackName);
}
return generatedNameFunctions;
}
private static List<EndpointType> CreateEndpointResourceBasedOnRemotingServer(ActorTypeInformation actorTypeInfo)
{
var endpoints = new List<EndpointType>();
#if !DotNetCoreClr
if (Helper.IsRemotingV1(actorTypeInfo.RemotingListenerVersion))
{
endpoints.Add(
new EndpointType()
{
Name = GetFabricServiceEndpointName(actorTypeInfo),
});
}
#endif
if (Helper.IsRemotingV2(actorTypeInfo.RemotingListenerVersion))
{
endpoints.Add(
new EndpointType()
{
Name = GetFabricServiceV2EndpointName(actorTypeInfo),
});
}
if (Helper.IsRemotingV2_1(actorTypeInfo.RemotingListenerVersion))
{
endpoints.Add(
new EndpointType()
{
Name = GetGeneratedServiceEndpointWrappedMessageStackName(actorTypeInfo),
});
}
return endpoints;
}
private static ExtensionsTypeExtension[] CreateServiceTypeExtensions(ActorTypeInformation actorTypeInfo)
{
var generatedNameFunctions = GeneratedNameFunctions.Concat(GetGeneratedNameFunctionForServiceEndpoint(actorTypeInfo)).ToDictionary(d => d.Key, d => d.Value);
var xml = CreateServiceTypeExtension(actorTypeInfo, generatedNameFunctions);
var extension = new ExtensionsTypeExtension
{
Name = GeneratedServiceTypeExtensionName,
// GeneratedId is of format Guid|StatePersistenceAttributeValue.
GeneratedId =
string.Format(
GeneratedIdFormat,
Guid.NewGuid(),
actorTypeInfo.StatePersistence),
Any = xml.DocumentElement,
};
return new List<ExtensionsTypeExtension> { extension }.ToArray();
}
private static XmlDocument CreateServiceTypeExtension(ActorTypeInformation actorTypeInfo, Dictionary<string, Func<ActorTypeInformation, string>> generatedNameFunctions)
{
var xml = new XmlDocument();
xml.XmlResolver = null;
xml.AppendChild(xml.CreateElement(GeneratedNamesRootElementName, ExtensionSchemaNamespace));
foreach (var pair in generatedNameFunctions)
{
var elementName = pair.Key;
var attributeValue = pair.Value(actorTypeInfo);
var elem = xml.CreateElement(elementName, ExtensionSchemaNamespace);
elem.SetAttribute(GeneratedNamesAttributeName, attributeValue);
xml.DocumentElement.AppendChild(elem);
}
return xml;
}
#region CodePackage Create and Merge
private static CodePackageType CreateCodePackage(SvcManifestEntryPointType serviceManifestEntryPointType)
{
var assembly = toolContext.Arguments.InputAssembly;
var codePackage = new CodePackageType
{
Name = ActorNameFormat.GetCodePackageName(),
Version = GetVersion(),
EntryPoint = new EntryPointDescriptionType
{
Item = CreateExeHostEntryPoint(assembly, serviceManifestEntryPointType),
},
};
return codePackage;
}
private static EntryPointDescriptionTypeExeHost CreateExeHostEntryPoint(
Assembly assembly, SvcManifestEntryPointType serviceManifestEntryPointType)
{
if (serviceManifestEntryPointType == SvcManifestEntryPointType.NoExtension)
{
return new EntryPointDescriptionTypeExeHost
{
Program = Path.GetFileNameWithoutExtension(assembly.Location),
};
}
else if (serviceManifestEntryPointType == SvcManifestEntryPointType.ExternalExecutable)
{
return new EntryPointDescriptionTypeExeHost
{
IsExternalExecutable = true,
Program = "dotnet",
Arguments = Path.GetFileNameWithoutExtension(assembly.Location) + ".dll",
WorkingFolder = ExeHostEntryPointTypeWorkingFolder.CodePackage,
};
}
else
{
return new EntryPointDescriptionTypeExeHost
{
Program = Path.GetFileNameWithoutExtension(assembly.Location) + ".exe",
};
}
}
private static CodePackageType MergeCodePackage(
CodePackageType existingItem,
CodePackageType newItem)
{
// Use new version, only when it doesn't exist.
if (string.IsNullOrEmpty(existingItem.Version))
{
existingItem.Version = newItem.Version;
}
if ((existingItem.EntryPoint == null) ||
(existingItem.EntryPoint.Item == null) ||
(existingItem.EntryPoint.Item.GetType() != newItem.EntryPoint.Item.GetType()))
{
existingItem.EntryPoint = newItem.EntryPoint;
}
else
{
var existingExeHost = (ExeHostEntryPointType)existingItem.EntryPoint.Item;
var newExeHost = (ExeHostEntryPointType)newItem.EntryPoint.Item;
existingExeHost.Program = newExeHost.Program;
}
return existingItem;
}
private static CodePackageType[] MergeCodePackages(
IEnumerable<CodePackageType> existingItems,
IEnumerable<CodePackageType> newItems)
{
return MergeItems(
existingItems,
newItems,
(i1, i2) => (string.CompareOrdinal(i1.Name, i2.Name) == 0),
MergeCodePackage);
}
#endregion
#region ConfigPackage Create and Merge
private static ConfigPackageType CreateConfigPackage()
{
var configPackage = new ConfigPackageType
{
Name = ActorNameFormat.GetConfigPackageName(),
Version = GetVersion(),
};
return configPackage;
}
private static ConfigPackageType MergeConfigPackage(
ConfigPackageType existingItem,
ConfigPackageType newItem)
{
// Use new version, only when it doesn't exist.
if (string.IsNullOrEmpty(existingItem.Version))
{
existingItem.Version = newItem.Version;
}
return existingItem;
}
private static ConfigPackageType[] MergeConfigPackages(
IEnumerable<ConfigPackageType> existingItems,
IEnumerable<ConfigPackageType> newItems)
{
return MergeItems(
existingItems,
newItems,
(i1, i2) => (string.CompareOrdinal(i1.Name, i2.Name) == 0),
MergeConfigPackage);
}
#endregion
#region EndpointResource Create and Merge
private static IEnumerable<EndpointType> CreateEndpointResources(
ActorTypeInformation actorTypeInfo)
{
var endpoints = CreateEndpointResourceBasedOnRemotingServer(actorTypeInfo);
endpoints.Add(
new EndpointType
{
Name = GetFabricServiceReplicatorEndpointName(actorTypeInfo),
});
return endpoints;
}
private static string GetFabricServiceReplicatorEndpointName(ActorTypeInformation actorTypeInfo)
{
return ActorNameFormat.GetFabricServiceReplicatorEndpointName(actorTypeInfo.ImplementationType);
}
private static string GetFabricServiceEndpointName(ActorTypeInformation actorTypeInfo)
{
return ActorNameFormat.GetFabricServiceEndpointName(actorTypeInfo.ImplementationType);
}
private static string GetFabricServiceV2EndpointName(ActorTypeInformation actorTypeInfo)
{
return ActorNameFormat.GetFabricServiceV2EndpointName(actorTypeInfo.ImplementationType);
}
private static string GetGeneratedServiceEndpointWrappedMessageStackName(ActorTypeInformation actorTypeInfo)
{
return ActorNameFormat.GetFabricServiceWrappedMessageEndpointName(actorTypeInfo.ImplementationType);
}
private static EndpointType MergeEndpointResource(
EndpointType existingItem,
EndpointType newItem)
{
return existingItem;
}
private static EndpointType[] MergeEndpointResource(
IEnumerable<EndpointType> existingItems,
IEnumerable<EndpointType> newItems)
{
return MergeItems(
existingItems,
newItems,
(i1, i2) => (string.CompareOrdinal(i1.Name, i2.Name) == 0),
MergeEndpointResource,
i1 => toolContext.ShouldKeepEndpointResource(i1.Name));
}
#endregion
#endregion
#region Create And Merge Application Manifest
private static ApplicationManifestType CreateApplicationManifest(ServiceManifestType serviceManifest)
{
// application manifest properties
var applicationManifest = new ApplicationManifestType
{
ApplicationTypeName = ActorNameFormat.GetFabricApplicationTypeName(toolContext.Arguments.ApplicationPrefix),
ApplicationTypeVersion = GetVersion(),
ServiceManifestImport = new ApplicationManifestTypeServiceManifestImport[1],
};
// service manifest import
applicationManifest.ServiceManifestImport[0] = new ApplicationManifestTypeServiceManifestImport
{
ServiceManifestRef = new ServiceManifestRefType
{
ServiceManifestName = serviceManifest.Name,
ServiceManifestVersion = serviceManifest.Version,
},
};
// default parameters
var defaultParameters = CreateDefaultParameter();
if (defaultParameters != null && defaultParameters.Count > 0)
{
applicationManifest.Parameters = defaultParameters.ToArray();
}
// default services
var defaultServices = CreateDefaultServices(serviceManifest);
applicationManifest.DefaultServices = new DefaultServicesType
{
Items = new object[defaultServices.Count],
};
defaultServices.ToArray().CopyTo(applicationManifest.DefaultServices.Items, 0);
return applicationManifest;
}
private static ApplicationManifestType MergeApplicationManifest(ApplicationManifestType applicationManifest)
{
if (string.IsNullOrEmpty(toolContext.ExistingApplicationManifestContents))
{
return applicationManifest;
}
var existingApplicationManifest = toolContext.ExistingApplicationManifestType;
// Use new version, only when it doesn't exist.
if (string.IsNullOrEmpty(existingApplicationManifest.ApplicationTypeVersion))
{
existingApplicationManifest.ApplicationTypeVersion = applicationManifest.ApplicationTypeVersion;
}
existingApplicationManifest.ServiceManifestImport = MergeServiceManifestImports(
existingApplicationManifest.ServiceManifestImport,
applicationManifest.ServiceManifestImport);
existingApplicationManifest.DefaultServices = MergeDefaultServices(
existingApplicationManifest.DefaultServices,
applicationManifest.DefaultServices);
existingApplicationManifest.Parameters = MergeParameters(
existingApplicationManifest.Parameters,
applicationManifest.Parameters);
return existingApplicationManifest;
}
private static IList<DefaultServicesTypeService> CreateDefaultServices(ServiceManifestType serviceManifest)
{
return toolContext.Arguments.ActorTypes.Select(x => CreateDefaultService(x, serviceManifest)).ToList();
}
private static IList<ApplicationManifestTypeParameter> CreateDefaultParameter()
{
var parameterlists = toolContext.Arguments.ActorTypes.Select(
CreateDefaultParameter).ToList();
var parametes = new List<ApplicationManifestTypeParameter>();
foreach (var paramlist in parameterlists)
{
parametes.AddRange(paramlist);
}
return parametes;
}
private static DefaultServicesType MergeDefaultServices(
DefaultServicesType existingItem,
DefaultServicesType newItem)
{
if (existingItem == null)
{
existingItem = new DefaultServicesType();
existingItem.Items = newItem.Items;
}
else if (existingItem.Items == null)
{
existingItem.Items = newItem.Items;
}
else
{
existingItem.Items = MergeItems(
existingItem.Items,
newItem.Items,
(i1, i2) =>
{
return ((i1.GetType() == i2.GetType()) &&
(i1.GetType() == typeof(DefaultServicesTypeService)) &&
(string.CompareOrdinal(
((DefaultServicesTypeService)i1).Name,
((DefaultServicesTypeService)i2).Name) == 0));
},
(i1, i2) =>
{
return MergeDefaultService(
(DefaultServicesTypeService)i1,
(DefaultServicesTypeService)i2);
},
i1 =>
{
return toolContext.ShouldKeepItem(
GeneratedDefaultServiceName,
((DefaultServicesTypeService)i1).Name);
});
}
return existingItem;
}
private static DefaultServicesTypeService CreateDefaultService(
ActorTypeInformation actorTypeInfo, ServiceManifestType serviceManifest)
{
var defaultService = new DefaultServicesTypeService
{
Name = GetFabricServiceName(actorTypeInfo),
};
var partition = new ServiceTypeUniformInt64Partition
{
LowKey = long.MinValue.ToString(CultureInfo.InvariantCulture),
HighKey = long.MaxValue.ToString(CultureInfo.InvariantCulture),
PartitionCount = string.Format(ParamNameUsageFormat, defaultService.Name, PartitionCountParamName),
};
var service = CreateStatefulDefaultService(actorTypeInfo);
var serviceTypeName = ActorNameFormat.GetFabricServiceTypeName(actorTypeInfo.ImplementationType);
defaultService.Item = service;
defaultService.Item.ServiceTypeName = serviceTypeName;
defaultService.Item.UniformInt64Partition = partition;
// Get GeneratedId from service manifest for the ServiceTypeName
var serviceType = (ServiceTypeType)serviceManifest.ServiceTypes.First(x => ((ServiceTypeType)x).ServiceTypeName.Equals(serviceTypeName));
var extension = serviceType.Extensions.First(x => x.Name.Equals(GeneratedServiceTypeExtensionName));
defaultService.GeneratedIdRef = extension.GeneratedId;
return defaultService;
}
private static IList<ApplicationManifestTypeParameter> CreateDefaultParameter(ActorTypeInformation actorTypeInfo)
{
var applicationManifestTypeParameterList = new List<ApplicationManifestTypeParameter>();
CreateStatefulDefaultServiceParameters(actorTypeInfo, applicationManifestTypeParameterList);
return applicationManifestTypeParameterList;
}
private static ApplicationManifestTypeParameter GetApplicationManifestTypeParameter(string name, string defaultValue)
{
return new ApplicationManifestTypeParameter() { Name = name, DefaultValue = defaultValue };
}
private static string GetFabricServiceName(ActorTypeInformation actorTypeInfo)
{
return ActorNameFormat.GetFabricServiceName(actorTypeInfo.InterfaceTypes.First(), actorTypeInfo.ServiceName);
}
private static ServiceType CreateStatefulDefaultService(
ActorTypeInformation actorTypeInfo)
{
var name = GetFabricServiceName(actorTypeInfo);
return new StatefulServiceType
{
MinReplicaSetSize = string.Format(ParamNameUsageFormat, name, MinReplicaSetSizeParamName),
TargetReplicaSetSize = string.Format(ParamNameUsageFormat, name, TargetReplicaSetSizeParamName),
};
}
private static void CreateStatefulDefaultServiceParameters(
ActorTypeInformation actorTypeInfo, IList<ApplicationManifestTypeParameter> applicationManifestTypeParameters)
{
var name = GetFabricServiceName(actorTypeInfo);
applicationManifestTypeParameters.Add(
GetApplicationManifestTypeParameter(
string.Format(ParamNameFormat, name, PartitionCountParamName),
DefaultPartitionCount));
applicationManifestTypeParameters.Add(
GetApplicationManifestTypeParameter(
string.Format(ParamNameFormat, name, MinReplicaSetSizeParamName),
GetMinReplicaSetSize(actorTypeInfo)));
applicationManifestTypeParameters.Add(
GetApplicationManifestTypeParameter(
string.Format(ParamNameFormat, name, TargetReplicaSetSizeParamName),
GetTargetReplicaSetSize(actorTypeInfo)));
}
private static string GetMinReplicaSetSize(ActorTypeInformation actorTypeInfo)
{
// MinReplicaSetSize is 1 when:
// 1. Actor has no [StatePersistenceAttribute] attribute. OR
// 2. Actor [StatePersistenceAttribute] attribute has StatePersistence.None.
// MinReplicaSetSize is 3 when:
// 1. Actor [StatePersistenceAttribute] attribute has StatePersistence.Volatile OR
// 2. Actor [StatePersistenceAttribute] attribute has StatePersistence.Persisted.
if (actorTypeInfo.StatePersistence.Equals(StatePersistence.None))
{
return NoneStatePersistenceMinReplicaDefaultValue;
}
else
{
return PersistedStateMinReplicaDefaultValue;
}
}
private static string GetTargetReplicaSetSize(ActorTypeInformation actorTypeInfo)
{
// TargetReplicaSetSize is 1 when:
// 1. Actor has no [StatePersistenceAttribute] attribute. OR
// 2. Actor [StatePersistenceAttribute] attribute has StatePersistence.None.
// TargetReplicaSetSize is 3 when:
// 1. Actor [StatePersistenceAttribute] attribute has StatePersistence.Volatile OR
// 2. Actor [StatePersistenceAttribute] attribute has StatePersistence.Persisted.
if (actorTypeInfo.StatePersistence.Equals(StatePersistence.None))
{
return NoneStatePersistenceTargetReplicaDefaultValue;
}
else
{
return PersistedStateTargetReplicaDefaultValue;
}
}
private static DefaultServicesTypeService MergeDefaultService(
DefaultServicesTypeService existingItem,
DefaultServicesTypeService newItem)
{
if (existingItem.Item == null)
{
existingItem.Item = newItem.Item;
return existingItem;
}
var existingService = existingItem.Item;
var newService = newItem.Item;
// merge GeneratedIdRef
existingItem.GeneratedIdRef = newItem.GeneratedIdRef;
// Merged type-agnostic values before (potentially) swapping the type
var mergedPartition = MergeDefaultServicePartition(
existingService.UniformInt64Partition,
newService.UniformInt64Partition);
existingService.ServiceTypeName = newService.ServiceTypeName;
if (existingService.GetType() != newService.GetType())
{
newService.LoadMetrics = existingService.LoadMetrics;
newService.PlacementConstraints = existingService.PlacementConstraints;
newService.ServiceCorrelations = existingService.ServiceCorrelations;
newService.ServicePlacementPolicies = existingService.ServicePlacementPolicies;
// Type-specific values are lost
existingService = newService;
existingItem.Item = existingService;
}
existingService.UniformInt64Partition = mergedPartition;
existingService.SingletonPartition = null;
existingService.NamedPartition = null;
return existingItem;
}
private static ServiceTypeUniformInt64Partition MergeDefaultServicePartition(
ServiceTypeUniformInt64Partition existingItem,
ServiceTypeUniformInt64Partition newItem)
{
if (existingItem == null)
{
return newItem;
}
else
{
existingItem.LowKey = newItem.LowKey;
existingItem.HighKey = newItem.HighKey;
return existingItem;
}
}
private static ApplicationManifestTypeServiceManifestImport MergeServiceManifestImport(
ApplicationManifestTypeServiceManifestImport existingItem,
ApplicationManifestTypeServiceManifestImport newItem)
{
// Use new version, only when it doesn't exist.
if (string.IsNullOrEmpty(existingItem.ServiceManifestRef.ServiceManifestVersion))
{
existingItem.ServiceManifestRef.ServiceManifestVersion = newItem.ServiceManifestRef.ServiceManifestVersion;
}
return existingItem;
}
private static ApplicationManifestTypeServiceManifestImport[]
MergeServiceManifestImports(
IEnumerable<ApplicationManifestTypeServiceManifestImport> existingItems,
IEnumerable<ApplicationManifestTypeServiceManifestImport> newItems)
{
return MergeItems(
existingItems,
newItems,
(i1, i2) =>
((i1.ServiceManifestRef != null) && (i2.ServiceManifestRef != null) &&
(string.CompareOrdinal(
i1.ServiceManifestRef.ServiceManifestName,
i2.ServiceManifestRef.ServiceManifestName) == 0)),
MergeServiceManifestImport);
}
private static ApplicationManifestTypeParameter MergeParameters(
ApplicationManifestTypeParameter existingItem,
ApplicationManifestTypeParameter newItem)
{
// Following scenario must be handled while merging parameters values for TargetReplicaSetSize and MinReplicaSetSize
// 1. User could change StatePrersistence from Persisted/Volatile to None, in this case
// overwrite the existing parameter value.
foreach (var actorTypeInfo in toolContext.Arguments.ActorTypes)
{
var name = GetFabricServiceName(actorTypeInfo);
if (existingItem.Name.Equals(string.Format(ParamNameFormat, name, MinReplicaSetSizeParamName)) ||
existingItem.Name.Equals(string.Format(ParamNameFormat, name, TargetReplicaSetSizeParamName)))
{
// Get GeneratedId Ref from the Default services for this actor.
if (toolContext.TryGetGeneratedIdRefForActorService(name, out var generatedIdRef))
{
// GeneratedIdRef is of format "Guid|StatePersistenceAttributeValue"
// If StatePersistence Value from GeneratedIdRef is different from the current value then override the param value.
var splitted = generatedIdRef.Split(GeneratedIdDelimiter);
if (splitted.Length == 2)
{
var statePersistenceValue = splitted[1];
var newPersistenceValue = actorTypeInfo.StatePersistence.ToString();
if (!statePersistenceValue.Equals(newPersistenceValue))
{
existingItem.DefaultValue = newItem.DefaultValue;
}
}
}
break;
}
}
return existingItem;
}
private static ApplicationManifestTypeParameter[] MergeParameters(
IEnumerable<ApplicationManifestTypeParameter> existingItems,
IEnumerable<ApplicationManifestTypeParameter> newItems)
{
return MergeItems(
existingItems,
newItems,
(i1, i2) =>
(string.CompareOrdinal(
i1.Name,
i2.Name) == 0),
MergeParameters);
}
#endregion
private static T[] MergeItems<T>(
IEnumerable<T> existingItems,
IEnumerable<T> newItems,
Func<T, T, bool> isEquals,
Func<T, T, T> itemMerge)
{
return MergeItems(
existingItems,
newItems,
isEquals,
itemMerge,
t => true);
}
private static T[] MergeItems<T>(
IEnumerable<T> existingItems,
IEnumerable<T> newItems,
Func<T, T, bool> isEquals,
Func<T, T, T> itemMerge,
Func<T, bool> shouldKeep)
{
var list1 = (existingItems == null ? new List<T>() : existingItems.ToList());
var list2 = (newItems == null ? new List<T>() : newItems.ToList());
var mergedList = new List<T>();
// Order must be of existing list during merge.
// If existing is 1,2,4,5 and new is 2,3 merged list should be 1,2,4,5,3 and not 2,3,1,4,5
foreach (var item1 in list1)
{
// if its in list2, keep the merge
var idx2 = list2.FindIndex(i => isEquals(i, item1));
if (idx2 >= 0)
{
mergedList.Add(itemMerge(item1, list2[idx2]));
list2.RemoveAt(idx2);
}
else
{
// only keep it, if specified.
if (shouldKeep.Invoke(item1))
{
mergedList.Add(item1);
}
}
}
mergedList.AddRange(list2);
return mergedList.ToArray();
}
private static void InsertXmlCommentsAndWriteIfNeeded<T>(string filePath, string existingContents, T value)
where T : class
{
var newContent = XmlSerializationUtility.InsertXmlComments(existingContents, value);
Utility.WriteIfNeeded(filePath, existingContents, newContent);
}
private static string GetVersion()
{
return !string.IsNullOrEmpty(toolContext.Arguments.Version)
? toolContext.Arguments.Version
: DefaultSemanticVersion;
}
private static string GetStatePersistenceValueForActorService(string actorService)
{
foreach (var actorTypeInfo in toolContext.Arguments.ActorTypes)
{
var serviceName = GetFabricServiceName(actorTypeInfo);
if (serviceName.Equals(actorService))
{
return actorTypeInfo.StatePersistence.ToString();
}
}
return null;
}
public class Arguments
{
public string ApplicationPrefix { get; set; }
public string ServicePackageNamePrefix { get; set; }
public string OutputPath { get; set; }
public string ApplicationPackagePath { get; set; }
public string ServicePackagePath { get; set; }
public Assembly InputAssembly { get; set; }
public IList<ActorTypeInformation> ActorTypes { get; set; }
public string Version { get; set; }
public SvcManifestEntryPointType ServiceManifestEntryPointType { get; set; }
public string StartupServicesFilePath { get; set; }
}
private class Context
{
private readonly Dictionary<string, HashSet<string>> existingGeneratedNames;
private readonly Dictionary<string, string> existingActorServiceGeneratedIdRefNamesMap;
public Context(Arguments arguments)
{
this.Arguments = arguments;
if (this.ShouldGenerateApplicationManifest())
{
this.ApplicationManifestFilePath = this.GetApplicationManifestFilePath();
this.StartupServicesFilePath = this.GetStartupServicesFilePath();
}
this.ServiceManifestFilePath = this.GetServiceManifestFilePath();
this.ConfigSettingsFilePath = this.GetConfigSettingsFilePath();
this.existingGeneratedNames = new Dictionary<string, HashSet<string>>();
this.existingActorServiceGeneratedIdRefNamesMap = new Dictionary<string, string>();
}
public string ApplicationManifestFilePath { get; private set; }
public string ServiceManifestFilePath { get; private set; }
public string ConfigSettingsFilePath { get; private set; }
public string ExistingApplicationManifestContents { get; private set; }
public string ExistingServiceManifestContents { get; private set; }
public string ExistingConfigSettingsContents { get; private set; }
public ApplicationManifestType ExistingApplicationManifestType { get; private set; }
public ServiceManifestType ExistingServiceManifestType { get; private set; }
public StartupServicesManifestType ExistingStartupServicesManifestType { get; private set; }
public string StartupServicesFilePath { get; private set; }
public string ExistingStartupServicesContents { get; private set; }
public bool StartupServicesFlag { get; private set; } = false;
public Arguments Arguments { get; private set; }
public void LoadExistingContents()
{
// Load AppManifest
if (this.ShouldGenerateApplicationManifest())
{
Utility.EnsureParentFolder(this.ApplicationManifestFilePath);
this.ExistingApplicationManifestContents = Utility.LoadContents(this.ApplicationManifestFilePath).Trim();
this.ExistingApplicationManifestType = XmlSerializationUtility
.Deserialize<ApplicationManifestType>(
this.ExistingApplicationManifestContents);
// read startupServices.xml and merge default services
if (!string.IsNullOrEmpty(this.StartupServicesFilePath))
{
this.ExistingStartupServicesContents = Utility.LoadContents(this.StartupServicesFilePath).Trim();
this.ExistingStartupServicesManifestType = XmlSerializationUtility
.Deserialize<StartupServicesManifestType>(this.ExistingStartupServicesContents);
this.MergeDefaultServicesFromManifestAndStartupServices();
this.MergeParametersFromManifestAndStartupServices();
this.StartupServicesFlag = true;
}
// Create ActorService name and GeneratedIdRef map to be used while merging parameters later.
if (this.ExistingApplicationManifestType != null
&& this.ExistingApplicationManifestType.DefaultServices != null
&& this.ExistingApplicationManifestType.DefaultServices.Items != null)
{
foreach (var defaultService in this.ExistingApplicationManifestType.DefaultServices.Items)
{
var castedType = defaultService as DefaultServicesTypeService;
this.existingActorServiceGeneratedIdRefNamesMap.Add(castedType.Name, castedType.GeneratedIdRef);
}
}
}
// Load Service Manifest
Utility.EnsureParentFolder(this.ServiceManifestFilePath);
this.ExistingServiceManifestContents = Utility.LoadContents(this.ServiceManifestFilePath).Trim();
this.ExistingServiceManifestType = XmlSerializationUtility
.Deserialize<ServiceManifestType>(
this.ExistingServiceManifestContents);
// Load Config.
Utility.EnsureParentFolder(this.ConfigSettingsFilePath);
this.ExistingConfigSettingsContents = Utility.LoadContents(this.ConfigSettingsFilePath).Trim();
this.LoadExistingGeneratedNames();
}
public void LoadExistingGeneratedNames()
{
if (this.ExistingServiceManifestType == null || this.ExistingServiceManifestType.ServiceTypes == null)
{
return;
}
foreach (var serviceType in this.ExistingServiceManifestType.ServiceTypes)
{
if (serviceType is ServiceTypeType castedServiceType)
{
if (castedServiceType.Extensions == null)
{
// Not a FabAct generated type
continue;
}
foreach (var extension in castedServiceType.Extensions)
{
if (extension.Name == GeneratedServiceTypeExtensionName)
{
if (!this.existingGeneratedNames.TryGetValue(extension.Name, out var existingTypes))
{
existingTypes = new HashSet<string>();
this.existingGeneratedNames.Add(
extension.Name,
existingTypes);
}
existingTypes.Add(castedServiceType.ServiceTypeName);
var xmlEnumerator = extension.Any.ChildNodes.GetEnumerator();
while (xmlEnumerator.MoveNext())
{
var xml = xmlEnumerator.Current as XmlElement;
if (xml == null)
{
continue;
}
if (!this.existingGeneratedNames.TryGetValue(xml.Name, out var existingNames))
{
existingNames = new HashSet<string>();
this.existingGeneratedNames.Add(
xml.Name,
existingNames);
}
existingNames.Add(xml.GetAttribute(GeneratedNamesAttributeName));
}
break;
}
}
}
}
}
public bool ShouldKeepItem(
string name,
string value)
{
return !this.IsExistingGeneratedName(name, value);
}
public bool ShouldKeepConfigSection(
string value)
{
return
!(this.IsExistingGeneratedName(GeneratedStoreConfigSectionName, value) ||
this.IsExistingGeneratedName(GeneratedReplicatorConfigSectionName, value) ||
this.IsExistingGeneratedName(GeneratedReplicatorSecurityConfigSectionName, value));
}
public bool ShouldKeepEndpointResource(
string value)
{
return
!(this.IsExistingGeneratedName(GeneratedServiceEndpointName, value) ||
this.IsExistingGeneratedName(GeneratedReplicatorEndpointName, value));
}
public bool ShouldGenerateApplicationManifest()
{
// Generates application manifest only when ApplicationPackagePath is non-empty,
// or ApplicationPackagePath and ServicePackagePath are both empty.
return
!string.IsNullOrEmpty(this.Arguments.ApplicationPackagePath) ||
string.IsNullOrEmpty(this.Arguments.ServicePackagePath);
}
public bool TryGetGeneratedIdRefForActorService(string actorService, out string generatedIdRef)
{
if (this.existingActorServiceGeneratedIdRefNamesMap.TryGetValue(actorService, out generatedIdRef))
{
return true;
}
else
{
generatedIdRef = null;
return false;
}
}
private bool IsExistingGeneratedName(
string name,
string value)
{
if (this.existingGeneratedNames.TryGetValue(name, out var existingValues))
{
return existingValues.Contains(value);
}
else
{
return false;
}
}
private string GetApplicationManifestFilePath()
{
if (!string.IsNullOrEmpty(this.Arguments.ApplicationPackagePath))
{
return Path.Combine(this.Arguments.ApplicationPackagePath, ApplicationManifestFileName);
}
else if (this.ShouldGenerateApplicationManifest())
{
var appManifestFilePath = Path.Combine(this.Arguments.OutputPath, ApplicationManifestFileName);
if (!File.Exists(appManifestFilePath))
{
appManifestFilePath = Path.Combine(
this.Arguments.OutputPath,
ActorNameFormat.GetFabricApplicationPackageName(this.Arguments.ApplicationPrefix),
ApplicationManifestFileName);
}
return appManifestFilePath;
}
return string.Empty;
}
private string GetStartupServicesFilePath()
{
if (!string.IsNullOrEmpty(this.Arguments.StartupServicesFilePath))
{
return this.Arguments.StartupServicesFilePath;
}
return string.Empty;
}
private string GetServiceManifestFilePath()
{
var servicePackagePath = this.Arguments.ServicePackagePath;
if (string.IsNullOrEmpty(servicePackagePath))
{
var appManifestFilePath = this.GetApplicationManifestFilePath();
var appPackageFolder = Path.GetDirectoryName(appManifestFilePath) ??
Path.Combine(
this.Arguments.OutputPath,
ActorNameFormat.GetFabricApplicationPackageName(
this.Arguments.ApplicationPrefix));
servicePackagePath = Path.Combine(
appPackageFolder,
ActorNameFormat.GetFabricServicePackageName(this.Arguments.ServicePackageNamePrefix));
}
var manifestFilePath = Path.Combine(
servicePackagePath,
ServiceManifestFileName);
return manifestFilePath;
}
private string GetConfigSettingsFilePath()
{
var manifestFilePath = this.GetServiceManifestFilePath();
var sevicePackageFolder = Path.GetDirectoryName(manifestFilePath) ??
Path.Combine(
this.Arguments.OutputPath,
ActorNameFormat.GetFabricApplicationPackageName(
this.Arguments.ApplicationPrefix),
ActorNameFormat.GetFabricServicePackageName(
this.Arguments.ServicePackageNamePrefix));
var settingsFilePath = Path.Combine(
sevicePackageFolder,
ActorNameFormat.GetConfigPackageName(),
ConfigSettingsFileName);
return settingsFilePath;
}
private void MergeDefaultServicesFromManifestAndStartupServices()
{
if (this.ExistingStartupServicesManifestType == null)
{
this.ExistingStartupServicesManifestType = new StartupServicesManifestType();
this.ExistingStartupServicesManifestType.DefaultServices = new DefaultServicesType();
return;
}
else if (this.ExistingStartupServicesManifestType.DefaultServices == null)
{
this.ExistingStartupServicesManifestType.DefaultServices = new DefaultServicesType();
return;
}
if (this.ExistingApplicationManifestType.DefaultServices == null)
{
this.ExistingApplicationManifestType.DefaultServices = new DefaultServicesType();
this.ExistingApplicationManifestType.DefaultServices.Items = this.ExistingStartupServicesManifestType.DefaultServices.Items;
}
else if (this.ExistingApplicationManifestType.DefaultServices.Items == null)
{
this.ExistingApplicationManifestType.DefaultServices.Items = this.ExistingStartupServicesManifestType.DefaultServices.Items;
}
else
{
var servicesFromStartupServices = this.ExistingStartupServicesManifestType.DefaultServices.Items.OfType<DefaultServicesTypeService>();
var servicesFromApplicationManifest = this.ExistingApplicationManifestType.DefaultServices.Items.OfType<DefaultServicesTypeService>();
var servicesMasterListName = new List<string>();
var serviceMasterList = new List<DefaultServicesTypeService>();
foreach (var service in servicesFromStartupServices)
{
servicesMasterListName.Add(service.Item.ServiceTypeName);
serviceMasterList.Add(service);
}
foreach (var service in servicesFromApplicationManifest)
{
if (!servicesMasterListName.Contains(service.Item.ServiceTypeName))
{
serviceMasterList.Add(service);
}
}
this.ExistingApplicationManifestType.DefaultServices.Items = serviceMasterList.ToArray();
}
}
private void MergeParametersFromManifestAndStartupServices()
{
if (this.ExistingStartupServicesManifestType == null)
{
this.ExistingStartupServicesManifestType = new StartupServicesManifestType();
return;
}
else if (this.ExistingStartupServicesManifestType.Parameters == null)
{
return;
}
if (this.ExistingApplicationManifestType.Parameters == null)
{
this.ExistingApplicationManifestType.Parameters = this.ExistingStartupServicesManifestType.Parameters;
return;
}
else
{
var parametersFromStartupServices = this.ExistingStartupServicesManifestType.Parameters;
var parametersFromApplicationManifest = this.ExistingApplicationManifestType.Parameters;
var paramsMasterList = new List<ApplicationManifestTypeParameter>();
var paramsNameMasterList = new List<string>();
foreach (var param in parametersFromStartupServices)
{
paramsMasterList.Add(param);
paramsNameMasterList.Add(param.Name);
}
foreach (var param in parametersFromApplicationManifest)
{
if (!paramsNameMasterList.Contains(param.Name))
{
paramsMasterList.Add(param);
}
}
this.ExistingApplicationManifestType.Parameters = paramsMasterList.ToArray();
}
}
}
}
}
| 43.270087 | 189 | 0.579823 | [
"MIT"
] | sunil-indoria/service-fabric-services-and-actors-dotnet | src/Microsoft.ServiceFabric.Actors/Generator/ManifestGenerator.cs | 70,011 | C# |
namespace FitnessBuddy.Web.Controllers
{
using FitnessBuddy.Web.Infrastructure.Filters;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
[Authorize]
[TypeFilter(typeof(RestrictBannedUsersAttribute))]
public class BaseController : Controller
{
}
}
| 23.538462 | 54 | 0.745098 | [
"MIT"
] | beshev/FitnessBuddy | src/Web/FitnessBuddy.Web/Controllers/BaseController.cs | 308 | C# |
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
// Runtime Version:4.0.30319.42000
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
using System;
using System.Reflection;
[assembly: System.Reflection.AssemblyCompanyAttribute("Chapter8.Xamarin.iOSLib")]
[assembly: System.Reflection.AssemblyConfigurationAttribute("Debug")]
[assembly: System.Reflection.AssemblyFileVersionAttribute("1.0.0.0")]
[assembly: System.Reflection.AssemblyInformationalVersionAttribute("1.0.0")]
[assembly: System.Reflection.AssemblyProductAttribute("Chapter8.Xamarin.iOSLib")]
[assembly: System.Reflection.AssemblyTitleAttribute("Chapter8.Xamarin.iOSLib")]
[assembly: System.Reflection.AssemblyVersionAttribute("1.0.0.0")]
// Generated by the MSBuild WriteCodeFragment class.
| 42.458333 | 81 | 0.654563 | [
"MIT"
] | PacktPublishing/DotNET-Standard-2-Cookbook | Chapter08/Chapter8.Xamarin/Chapter8.Xamarin.iOSLib/obj/Debug/netstandard2.0/Chapter8.Xamarin.iOSLib.AssemblyInfo.cs | 1,019 | C# |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.