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 |
|---|---|---|---|---|---|---|---|---|
//
// System.Web.Mail.MailAttachment.cs
//
// Author:
// Lawrence Pit (loz@cable.a2000.nl)
// Per Arneng (pt99par@student.bth.se)
// Sebastien Pouliot <sebastien@ximian.com>
//
// Copyright (C) 2005 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.IO;
using System.Security;
using System.Security.Permissions;
namespace System.Web.Mail
{
[Obsolete ("The recommended alternative is System.Net.Mail.Attachment. http://go.microsoft.com/fwlink/?linkid=14202")]
public class MailAttachment
{
string filename;
MailEncoding encoding;
public MailAttachment (string filename) :
this (filename, MailEncoding.Base64)
{
}
public MailAttachment (string filename, MailEncoding encoding)
{
if (SecurityManager.SecurityEnabled) {
new FileIOPermission (FileIOPermissionAccess.Read, filename).Demand ();
}
if (!File.Exists (filename)) {
string msg = Locale.GetText ("Cannot find file: '{0}'.");
throw new HttpException (String.Format (msg, filename));
}
this.filename = filename;
this.encoding = encoding;
}
// Properties
public string Filename
{
get { return filename; }
}
public MailEncoding Encoding
{
get { return encoding; }
}
}
}
| 30.733333 | 119 | 0.721909 | [
"Apache-2.0"
] | AvolitesMarkDaniel/mono | mcs/class/System.Web/System.Web.Mail/MailAttachment.cs | 2,305 | C# |
using UnityEngine;
using System.Collections;
/*
* A large ring that, when passed through, loses its glow and turns on in the node.
*/
public class TargetRing : Source {
protected virtual void OnTriggerEnter(Collider other) {
if (Player.IsPlayerTrigger(other)) {
if(!On) {
On = true;
GetComponent<Renderer>().material.CopyPropertiesFromMaterial(GameManager.Material_MARLmetal_unlit);
GetComponent<AudioSource>().Play();
}
}
}
}
| 27.789474 | 115 | 0.621212 | [
"Apache-2.0",
"MIT"
] | austin-j-taylor/Invested | Assets/Scripts/Environment/Circuits/TargetRing.cs | 530 | C# |
using System.Web.Mvc.Filters;
namespace mr.cooper.mrtwit.services.Interface.Concrete
{
public class MrAuthenticationFilter : IAuthenticationFilter
{
public void OnAuthentication(AuthenticationContext filterContext)
{
throw new System.NotImplementedException();
}
public void OnAuthenticationChallenge(AuthenticationChallengeContext filterContext)
{
throw new System.NotImplementedException();
}
}
}
| 27 | 91 | 0.695473 | [
"Unlicense"
] | yathrikash/mr_twit_api | mr.cooper.mrtwit.api/mr.cooper.mrtwit.services/Interface/Concrete/MrAuthenticationFilter.cs | 488 | C# |
// ----------------------------------------------------------------------------
// <copyright file="PhotonTransformViewScaleControl.cs" company="Exit Games GmbH">
// PhotonNetwork Framework for Unity - Copyright (C) 2016 Exit Games GmbH
// </copyright>
// <summary>
// Component to synchronize scale via PUN PhotonView.
// </summary>
// <author>developer@exitgames.com</author>
// ----------------------------------------------------------------------------
using UnityEngine;
using System.Collections;
public class PhotonTransformViewScaleControl
{
PhotonTransformViewScaleModel m_Model;
Vector3 m_NetworkScale = Vector3.one;
public PhotonTransformViewScaleControl( PhotonTransformViewScaleModel model )
{
m_Model = model;
}
/// <summary>
/// Gets the last scale that was received through the network
/// </summary>
/// <returns></returns>
public Vector3 GetNetworkScale()
{
return m_NetworkScale;
}
public Vector3 GetScale( Vector3 currentScale )
{
switch( m_Model.InterpolateOption )
{
default:
case PhotonTransformViewScaleModel.InterpolateOptions.Disabled:
return m_NetworkScale;
case PhotonTransformViewScaleModel.InterpolateOptions.MoveTowards:
return Vector3.MoveTowards( currentScale, m_NetworkScale, m_Model.InterpolateMoveTowardsSpeed * Time.deltaTime );
case PhotonTransformViewScaleModel.InterpolateOptions.Lerp:
return Vector3.Lerp( currentScale, m_NetworkScale, m_Model.InterpolateLerpSpeed * Time.deltaTime );
}
}
public void OnPhotonSerializeView( Vector3 currentScale, PhotonStream stream, PhotonMessageInfo info )
{
if( m_Model.SynchronizeEnabled == false )
{
return;
}
if( stream.isWriting == true )
{
stream.SendNext( currentScale );
m_NetworkScale = currentScale;
}
else
{
m_NetworkScale = (Vector3)stream.ReceiveNext();
}
}
} | 32.75 | 126 | 0.606393 | [
"Apache-2.0"
] | lorenchorley/StrangeIoC-Updated | Assets/xtra/Photon Unity Networking/Plugins/PhotonNetwork/Views/PhotonTransformViewScaleControl.cs | 2,096 | C# |
namespace Models
{
public interface ISuperGame
{
string Id { get; set; }
int Price { get; set; }
int MaxPlayers { get; set; }
int CurrentPlayers { get; set; }
}
} | 20.7 | 40 | 0.531401 | [
"MIT"
] | gellios3/Simple-Battle-Cards-Server | Assets/Scripts/Models/SuperGame/ISuperGame.cs | 209 | C# |
using System;
using System.Collections;
namespace Checkers
{
public class TcpClientCollection : CollectionBase, IEnumerable
{
public int Add(TcpClient item)
{
return InnerList.Add(item);
}
public void AddRange(TcpClient[] items)
{
foreach(TcpClient item in items)
Add(item);
}
public void Insert(int index, TcpClient item)
{
InnerList.Insert(index, item);
}
public void Remove(TcpClient item)
{
InnerList.Remove(item);
}
public bool Contains(TcpClient item)
{
return InnerList.Contains(item);
}
public int IndexOf(TcpClient item)
{
return InnerList.IndexOf(item);
}
public void CopyTo(TcpClient[] array, int index)
{
InnerList.CopyTo(array, index);
}
public TcpClient this[int index]
{
get
{
return (TcpClient)InnerList[index];
}
set
{
InnerList[index] = value;
}
}
public TcpClient[] ToArray()
{
return (TcpClient[])InnerList.ToArray(typeof(TcpClient));
}
}
}
| 21.546875 | 70 | 0.472806 | [
"MIT"
] | joeyespo/checkers | Checkers/TcpClientCollection.cs | 1,379 | C# |
// <auto-generated />
using System;
using Futbol3.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Metadata;
using Microsoft.EntityFrameworkCore.Migrations;
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
namespace Futbol3.Migrations
{
[DbContext(typeof(Futbol3DbContext))]
[Migration("20201112121732_Upgraded_To_ABP_6_0")]
partial class Upgraded_To_ABP_6_0
{
protected override void BuildTargetModel(ModelBuilder modelBuilder)
{
#pragma warning disable 612, 618
modelBuilder
.UseIdentityColumns()
.HasAnnotation("Relational:MaxIdentifierLength", 128)
.HasAnnotation("ProductVersion", "5.0.0");
modelBuilder.Entity("Abp.Application.Editions.Edition", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int")
.UseIdentityColumn();
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()
.HasMaxLength(64)
.HasColumnType("nvarchar(64)");
b.Property<bool>("IsDeleted")
.HasColumnType("bit");
b.Property<DateTime?>("LastModificationTime")
.HasColumnType("datetime2");
b.Property<long?>("LastModifierUserId")
.HasColumnType("bigint");
b.Property<string>("Name")
.IsRequired()
.HasMaxLength(32)
.HasColumnType("nvarchar(32)");
b.HasKey("Id");
b.ToTable("AbpEditions");
});
modelBuilder.Entity("Abp.Application.Features.FeatureSetting", b =>
{
b.Property<long>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("bigint")
.UseIdentityColumn();
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()
.HasMaxLength(128)
.HasColumnType("nvarchar(128)");
b.Property<int?>("TenantId")
.HasColumnType("int");
b.Property<string>("Value")
.IsRequired()
.HasMaxLength(2000)
.HasColumnType("nvarchar(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")
.UseIdentityColumn();
b.Property<string>("BrowserInfo")
.HasMaxLength(512)
.HasColumnType("nvarchar(512)");
b.Property<string>("ClientIpAddress")
.HasMaxLength(64)
.HasColumnType("nvarchar(64)");
b.Property<string>("ClientName")
.HasMaxLength(128)
.HasColumnType("nvarchar(128)");
b.Property<string>("CustomData")
.HasMaxLength(2000)
.HasColumnType("nvarchar(2000)");
b.Property<string>("Exception")
.HasMaxLength(2000)
.HasColumnType("nvarchar(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")
.HasMaxLength(256)
.HasColumnType("nvarchar(256)");
b.Property<string>("Parameters")
.HasMaxLength(1024)
.HasColumnType("nvarchar(1024)");
b.Property<string>("ReturnValue")
.HasColumnType("nvarchar(max)");
b.Property<string>("ServiceName")
.HasMaxLength(256)
.HasColumnType("nvarchar(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")
.UseIdentityColumn();
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()
.HasMaxLength(128)
.HasColumnType("nvarchar(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")
.UseIdentityColumn();
b.Property<string>("ClaimType")
.HasMaxLength(256)
.HasColumnType("nvarchar(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")
.UseIdentityColumn();
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")
.HasMaxLength(256)
.HasColumnType("nvarchar(256)");
b.Property<bool>("IsDeleted")
.HasColumnType("bit");
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")
.HasMaxLength(256)
.HasColumnType("nvarchar(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")
.UseIdentityColumn();
b.Property<string>("ClaimType")
.HasMaxLength(256)
.HasColumnType("nvarchar(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")
.UseIdentityColumn();
b.Property<string>("LoginProvider")
.IsRequired()
.HasMaxLength(128)
.HasColumnType("nvarchar(128)");
b.Property<string>("ProviderKey")
.IsRequired()
.HasMaxLength(256)
.HasColumnType("nvarchar(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")
.UseIdentityColumn();
b.Property<string>("BrowserInfo")
.HasMaxLength(512)
.HasColumnType("nvarchar(512)");
b.Property<string>("ClientIpAddress")
.HasMaxLength(64)
.HasColumnType("nvarchar(64)");
b.Property<string>("ClientName")
.HasMaxLength(128)
.HasColumnType("nvarchar(128)");
b.Property<DateTime>("CreationTime")
.HasColumnType("datetime2");
b.Property<byte>("Result")
.HasColumnType("tinyint");
b.Property<string>("TenancyName")
.HasMaxLength(64)
.HasColumnType("nvarchar(64)");
b.Property<int?>("TenantId")
.HasColumnType("int");
b.Property<long?>("UserId")
.HasColumnType("bigint");
b.Property<string>("UserNameOrEmailAddress")
.HasMaxLength(256)
.HasColumnType("nvarchar(256)");
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")
.UseIdentityColumn();
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")
.UseIdentityColumn();
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")
.UseIdentityColumn();
b.Property<DateTime?>("ExpireDate")
.HasColumnType("datetime2");
b.Property<string>("LoginProvider")
.HasMaxLength(128)
.HasColumnType("nvarchar(128)");
b.Property<string>("Name")
.HasMaxLength(128)
.HasColumnType("nvarchar(128)");
b.Property<int?>("TenantId")
.HasColumnType("int");
b.Property<long>("UserId")
.HasColumnType("bigint");
b.Property<string>("Value")
.HasMaxLength(512)
.HasColumnType("nvarchar(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")
.UseIdentityColumn();
b.Property<DateTime>("CreationTime")
.HasColumnType("datetime2");
b.Property<long?>("CreatorUserId")
.HasColumnType("bigint");
b.Property<bool>("IsAbandoned")
.HasColumnType("bit");
b.Property<string>("JobArgs")
.IsRequired()
.HasMaxLength(1048576)
.HasColumnType("nvarchar(max)");
b.Property<string>("JobType")
.IsRequired()
.HasMaxLength(512)
.HasColumnType("nvarchar(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")
.UseIdentityColumn();
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()
.HasMaxLength(256)
.HasColumnType("nvarchar(256)");
b.Property<int?>("TenantId")
.HasColumnType("int");
b.Property<long?>("UserId")
.HasColumnType("bigint");
b.Property<string>("Value")
.HasColumnType("nvarchar(max)");
b.HasKey("Id");
b.HasIndex("UserId");
b.HasIndex("TenantId", "Name", "UserId")
.IsUnique();
b.ToTable("AbpSettings");
});
modelBuilder.Entity("Abp.DynamicEntityProperties.DynamicEntityProperty", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int")
.UseIdentityColumn();
b.Property<int>("DynamicPropertyId")
.HasColumnType("int");
b.Property<string>("EntityFullName")
.HasColumnType("nvarchar(450)");
b.Property<int?>("TenantId")
.HasColumnType("int");
b.HasKey("Id");
b.HasIndex("DynamicPropertyId");
b.HasIndex("EntityFullName", "DynamicPropertyId", "TenantId")
.IsUnique()
.HasFilter("[EntityFullName] IS NOT NULL AND [TenantId] IS NOT NULL");
b.ToTable("AbpDynamicEntityProperties");
});
modelBuilder.Entity("Abp.DynamicEntityProperties.DynamicEntityPropertyValue", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int")
.UseIdentityColumn();
b.Property<int>("DynamicEntityPropertyId")
.HasColumnType("int");
b.Property<string>("EntityId")
.HasColumnType("nvarchar(max)");
b.Property<int?>("TenantId")
.HasColumnType("int");
b.Property<string>("Value")
.IsRequired()
.HasColumnType("nvarchar(max)");
b.HasKey("Id");
b.HasIndex("DynamicEntityPropertyId");
b.ToTable("AbpDynamicEntityPropertyValues");
});
modelBuilder.Entity("Abp.DynamicEntityProperties.DynamicProperty", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int")
.UseIdentityColumn();
b.Property<string>("DisplayName")
.HasColumnType("nvarchar(max)");
b.Property<string>("InputType")
.HasColumnType("nvarchar(max)");
b.Property<string>("Permission")
.HasColumnType("nvarchar(max)");
b.Property<string>("PropertyName")
.HasColumnType("nvarchar(450)");
b.Property<int?>("TenantId")
.HasColumnType("int");
b.HasKey("Id");
b.HasIndex("PropertyName", "TenantId")
.IsUnique()
.HasFilter("[PropertyName] IS NOT NULL AND [TenantId] IS NOT NULL");
b.ToTable("AbpDynamicProperties");
});
modelBuilder.Entity("Abp.DynamicEntityProperties.DynamicPropertyValue", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int")
.UseIdentityColumn();
b.Property<int>("DynamicPropertyId")
.HasColumnType("int");
b.Property<int?>("TenantId")
.HasColumnType("int");
b.Property<string>("Value")
.IsRequired()
.HasColumnType("nvarchar(max)");
b.HasKey("Id");
b.HasIndex("DynamicPropertyId");
b.ToTable("AbpDynamicPropertyValues");
});
modelBuilder.Entity("Abp.EntityHistory.EntityChange", b =>
{
b.Property<long>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("bigint")
.UseIdentityColumn();
b.Property<DateTime>("ChangeTime")
.HasColumnType("datetime2");
b.Property<byte>("ChangeType")
.HasColumnType("tinyint");
b.Property<long>("EntityChangeSetId")
.HasColumnType("bigint");
b.Property<string>("EntityId")
.HasMaxLength(48)
.HasColumnType("nvarchar(48)");
b.Property<string>("EntityTypeFullName")
.HasMaxLength(192)
.HasColumnType("nvarchar(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")
.UseIdentityColumn();
b.Property<string>("BrowserInfo")
.HasMaxLength(512)
.HasColumnType("nvarchar(512)");
b.Property<string>("ClientIpAddress")
.HasMaxLength(64)
.HasColumnType("nvarchar(64)");
b.Property<string>("ClientName")
.HasMaxLength(128)
.HasColumnType("nvarchar(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")
.HasMaxLength(256)
.HasColumnType("nvarchar(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")
.UseIdentityColumn();
b.Property<long>("EntityChangeId")
.HasColumnType("bigint");
b.Property<string>("NewValue")
.HasMaxLength(512)
.HasColumnType("nvarchar(512)");
b.Property<string>("NewValueHash")
.HasColumnType("nvarchar(max)");
b.Property<string>("OriginalValue")
.HasMaxLength(512)
.HasColumnType("nvarchar(512)");
b.Property<string>("OriginalValueHash")
.HasColumnType("nvarchar(max)");
b.Property<string>("PropertyName")
.HasMaxLength(96)
.HasColumnType("nvarchar(96)");
b.Property<string>("PropertyTypeFullName")
.HasMaxLength(192)
.HasColumnType("nvarchar(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")
.UseIdentityColumn();
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()
.HasMaxLength(64)
.HasColumnType("nvarchar(64)");
b.Property<string>("Icon")
.HasMaxLength(128)
.HasColumnType("nvarchar(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()
.HasMaxLength(128)
.HasColumnType("nvarchar(128)");
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")
.UseIdentityColumn();
b.Property<DateTime>("CreationTime")
.HasColumnType("datetime2");
b.Property<long?>("CreatorUserId")
.HasColumnType("bigint");
b.Property<string>("Key")
.IsRequired()
.HasMaxLength(256)
.HasColumnType("nvarchar(256)");
b.Property<string>("LanguageName")
.IsRequired()
.HasMaxLength(128)
.HasColumnType("nvarchar(128)");
b.Property<DateTime?>("LastModificationTime")
.HasColumnType("datetime2");
b.Property<long?>("LastModifierUserId")
.HasColumnType("bigint");
b.Property<string>("Source")
.IsRequired()
.HasMaxLength(128)
.HasColumnType("nvarchar(128)");
b.Property<int?>("TenantId")
.HasColumnType("int");
b.Property<string>("Value")
.IsRequired()
.HasMaxLength(67108864)
.HasColumnType("nvarchar(max)");
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")
.HasMaxLength(1048576)
.HasColumnType("nvarchar(max)");
b.Property<string>("DataTypeName")
.HasMaxLength(512)
.HasColumnType("nvarchar(512)");
b.Property<string>("EntityId")
.HasMaxLength(96)
.HasColumnType("nvarchar(96)");
b.Property<string>("EntityTypeAssemblyQualifiedName")
.HasMaxLength(512)
.HasColumnType("nvarchar(512)");
b.Property<string>("EntityTypeName")
.HasMaxLength(250)
.HasColumnType("nvarchar(250)");
b.Property<string>("ExcludedUserIds")
.HasMaxLength(131072)
.HasColumnType("nvarchar(max)");
b.Property<string>("NotificationName")
.IsRequired()
.HasMaxLength(96)
.HasColumnType("nvarchar(96)");
b.Property<byte>("Severity")
.HasColumnType("tinyint");
b.Property<string>("TenantIds")
.HasMaxLength(131072)
.HasColumnType("nvarchar(max)");
b.Property<string>("UserIds")
.HasMaxLength(131072)
.HasColumnType("nvarchar(max)");
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")
.HasMaxLength(96)
.HasColumnType("nvarchar(96)");
b.Property<string>("EntityTypeAssemblyQualifiedName")
.HasMaxLength(512)
.HasColumnType("nvarchar(512)");
b.Property<string>("EntityTypeName")
.HasMaxLength(250)
.HasColumnType("nvarchar(250)");
b.Property<string>("NotificationName")
.HasMaxLength(96)
.HasColumnType("nvarchar(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")
.HasMaxLength(1048576)
.HasColumnType("nvarchar(max)");
b.Property<string>("DataTypeName")
.HasMaxLength(512)
.HasColumnType("nvarchar(512)");
b.Property<string>("EntityId")
.HasMaxLength(96)
.HasColumnType("nvarchar(96)");
b.Property<string>("EntityTypeAssemblyQualifiedName")
.HasMaxLength(512)
.HasColumnType("nvarchar(512)");
b.Property<string>("EntityTypeName")
.HasMaxLength(250)
.HasColumnType("nvarchar(250)");
b.Property<string>("NotificationName")
.IsRequired()
.HasMaxLength(96)
.HasColumnType("nvarchar(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")
.UseIdentityColumn();
b.Property<string>("Code")
.IsRequired()
.HasMaxLength(95)
.HasColumnType("nvarchar(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()
.HasMaxLength(128)
.HasColumnType("nvarchar(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("Abp.Organizations.OrganizationUnitRole", b =>
{
b.Property<long>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("bigint")
.UseIdentityColumn();
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>("RoleId")
.HasColumnType("int");
b.Property<int?>("TenantId")
.HasColumnType("int");
b.HasKey("Id");
b.HasIndex("TenantId", "OrganizationUnitId");
b.HasIndex("TenantId", "RoleId");
b.ToTable("AbpOrganizationUnitRoles");
});
modelBuilder.Entity("Abp.Webhooks.WebhookEvent", b =>
{
b.Property<Guid>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("uniqueidentifier");
b.Property<DateTime>("CreationTime")
.HasColumnType("datetime2");
b.Property<string>("Data")
.HasColumnType("nvarchar(max)");
b.Property<DateTime?>("DeletionTime")
.HasColumnType("datetime2");
b.Property<bool>("IsDeleted")
.HasColumnType("bit");
b.Property<int?>("TenantId")
.HasColumnType("int");
b.Property<string>("WebhookName")
.IsRequired()
.HasColumnType("nvarchar(max)");
b.HasKey("Id");
b.ToTable("AbpWebhookEvents");
});
modelBuilder.Entity("Abp.Webhooks.WebhookSendAttempt", b =>
{
b.Property<Guid>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("uniqueidentifier");
b.Property<DateTime>("CreationTime")
.HasColumnType("datetime2");
b.Property<DateTime?>("LastModificationTime")
.HasColumnType("datetime2");
b.Property<string>("Response")
.HasColumnType("nvarchar(max)");
b.Property<int?>("ResponseStatusCode")
.HasColumnType("int");
b.Property<int?>("TenantId")
.HasColumnType("int");
b.Property<Guid>("WebhookEventId")
.HasColumnType("uniqueidentifier");
b.Property<Guid>("WebhookSubscriptionId")
.HasColumnType("uniqueidentifier");
b.HasKey("Id");
b.HasIndex("WebhookEventId");
b.ToTable("AbpWebhookSendAttempts");
});
modelBuilder.Entity("Abp.Webhooks.WebhookSubscriptionInfo", b =>
{
b.Property<Guid>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("uniqueidentifier");
b.Property<DateTime>("CreationTime")
.HasColumnType("datetime2");
b.Property<long?>("CreatorUserId")
.HasColumnType("bigint");
b.Property<string>("Headers")
.HasColumnType("nvarchar(max)");
b.Property<bool>("IsActive")
.HasColumnType("bit");
b.Property<string>("Secret")
.IsRequired()
.HasColumnType("nvarchar(max)");
b.Property<int?>("TenantId")
.HasColumnType("int");
b.Property<string>("WebhookUri")
.IsRequired()
.HasColumnType("nvarchar(max)");
b.Property<string>("Webhooks")
.HasColumnType("nvarchar(max)");
b.HasKey("Id");
b.ToTable("AbpWebhookSubscriptions");
});
modelBuilder.Entity("Futbol3.Authorization.Roles.Role", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int")
.UseIdentityColumn();
b.Property<string>("ConcurrencyStamp")
.IsConcurrencyToken()
.HasMaxLength(128)
.HasColumnType("nvarchar(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")
.HasMaxLength(5000)
.HasColumnType("nvarchar(max)");
b.Property<string>("DisplayName")
.IsRequired()
.HasMaxLength(64)
.HasColumnType("nvarchar(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()
.HasMaxLength(32)
.HasColumnType("nvarchar(32)");
b.Property<string>("NormalizedName")
.IsRequired()
.HasMaxLength(32)
.HasColumnType("nvarchar(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("Futbol3.Authorization.Users.User", b =>
{
b.Property<long>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("bigint")
.UseIdentityColumn();
b.Property<int>("AccessFailedCount")
.HasColumnType("int");
b.Property<string>("AuthenticationSource")
.HasMaxLength(64)
.HasColumnType("nvarchar(64)");
b.Property<string>("ConcurrencyStamp")
.IsConcurrencyToken()
.HasMaxLength(128)
.HasColumnType("nvarchar(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()
.HasMaxLength(256)
.HasColumnType("nvarchar(256)");
b.Property<string>("EmailConfirmationCode")
.HasMaxLength(328)
.HasColumnType("nvarchar(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?>("LastModificationTime")
.HasColumnType("datetime2");
b.Property<long?>("LastModifierUserId")
.HasColumnType("bigint");
b.Property<DateTime?>("LockoutEndDateUtc")
.HasColumnType("datetime2");
b.Property<string>("Name")
.IsRequired()
.HasMaxLength(64)
.HasColumnType("nvarchar(64)");
b.Property<string>("NormalizedEmailAddress")
.IsRequired()
.HasMaxLength(256)
.HasColumnType("nvarchar(256)");
b.Property<string>("NormalizedUserName")
.IsRequired()
.HasMaxLength(256)
.HasColumnType("nvarchar(256)");
b.Property<string>("Password")
.IsRequired()
.HasMaxLength(128)
.HasColumnType("nvarchar(128)");
b.Property<string>("PasswordResetCode")
.HasMaxLength(328)
.HasColumnType("nvarchar(328)");
b.Property<string>("PhoneNumber")
.HasMaxLength(32)
.HasColumnType("nvarchar(32)");
b.Property<string>("SecurityStamp")
.HasMaxLength(128)
.HasColumnType("nvarchar(128)");
b.Property<string>("Surname")
.IsRequired()
.HasMaxLength(64)
.HasColumnType("nvarchar(64)");
b.Property<int?>("TenantId")
.HasColumnType("int");
b.Property<string>("UserName")
.IsRequired()
.HasMaxLength(256)
.HasColumnType("nvarchar(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("Futbol3.MultiTenancy.Tenant", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int")
.UseIdentityColumn();
b.Property<string>("ConnectionString")
.HasMaxLength(1024)
.HasColumnType("nvarchar(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()
.HasMaxLength(128)
.HasColumnType("nvarchar(128)");
b.Property<string>("TenancyName")
.IsRequired()
.HasMaxLength(64)
.HasColumnType("nvarchar(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("Futbol3.Authorization.Roles.Role", null)
.WithMany("Claims")
.HasForeignKey("RoleId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
});
modelBuilder.Entity("Abp.Authorization.Users.UserClaim", b =>
{
b.HasOne("Futbol3.Authorization.Users.User", null)
.WithMany("Claims")
.HasForeignKey("UserId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
});
modelBuilder.Entity("Abp.Authorization.Users.UserLogin", b =>
{
b.HasOne("Futbol3.Authorization.Users.User", null)
.WithMany("Logins")
.HasForeignKey("UserId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
});
modelBuilder.Entity("Abp.Authorization.Users.UserRole", b =>
{
b.HasOne("Futbol3.Authorization.Users.User", null)
.WithMany("Roles")
.HasForeignKey("UserId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
});
modelBuilder.Entity("Abp.Authorization.Users.UserToken", b =>
{
b.HasOne("Futbol3.Authorization.Users.User", null)
.WithMany("Tokens")
.HasForeignKey("UserId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
});
modelBuilder.Entity("Abp.Configuration.Setting", b =>
{
b.HasOne("Futbol3.Authorization.Users.User", null)
.WithMany("Settings")
.HasForeignKey("UserId");
});
modelBuilder.Entity("Abp.DynamicEntityProperties.DynamicEntityProperty", b =>
{
b.HasOne("Abp.DynamicEntityProperties.DynamicProperty", "DynamicProperty")
.WithMany()
.HasForeignKey("DynamicPropertyId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("DynamicProperty");
});
modelBuilder.Entity("Abp.DynamicEntityProperties.DynamicEntityPropertyValue", b =>
{
b.HasOne("Abp.DynamicEntityProperties.DynamicEntityProperty", "DynamicEntityProperty")
.WithMany()
.HasForeignKey("DynamicEntityPropertyId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("DynamicEntityProperty");
});
modelBuilder.Entity("Abp.DynamicEntityProperties.DynamicPropertyValue", b =>
{
b.HasOne("Abp.DynamicEntityProperties.DynamicProperty", "DynamicProperty")
.WithMany("DynamicPropertyValues")
.HasForeignKey("DynamicPropertyId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("DynamicProperty");
});
modelBuilder.Entity("Abp.EntityHistory.EntityChange", b =>
{
b.HasOne("Abp.EntityHistory.EntityChangeSet", null)
.WithMany("EntityChanges")
.HasForeignKey("EntityChangeSetId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
});
modelBuilder.Entity("Abp.EntityHistory.EntityPropertyChange", b =>
{
b.HasOne("Abp.EntityHistory.EntityChange", null)
.WithMany("PropertyChanges")
.HasForeignKey("EntityChangeId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
});
modelBuilder.Entity("Abp.Organizations.OrganizationUnit", b =>
{
b.HasOne("Abp.Organizations.OrganizationUnit", "Parent")
.WithMany("Children")
.HasForeignKey("ParentId");
b.Navigation("Parent");
});
modelBuilder.Entity("Abp.Webhooks.WebhookSendAttempt", b =>
{
b.HasOne("Abp.Webhooks.WebhookEvent", "WebhookEvent")
.WithMany()
.HasForeignKey("WebhookEventId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("WebhookEvent");
});
modelBuilder.Entity("Futbol3.Authorization.Roles.Role", b =>
{
b.HasOne("Futbol3.Authorization.Users.User", "CreatorUser")
.WithMany()
.HasForeignKey("CreatorUserId");
b.HasOne("Futbol3.Authorization.Users.User", "DeleterUser")
.WithMany()
.HasForeignKey("DeleterUserId");
b.HasOne("Futbol3.Authorization.Users.User", "LastModifierUser")
.WithMany()
.HasForeignKey("LastModifierUserId");
b.Navigation("CreatorUser");
b.Navigation("DeleterUser");
b.Navigation("LastModifierUser");
});
modelBuilder.Entity("Futbol3.Authorization.Users.User", b =>
{
b.HasOne("Futbol3.Authorization.Users.User", "CreatorUser")
.WithMany()
.HasForeignKey("CreatorUserId");
b.HasOne("Futbol3.Authorization.Users.User", "DeleterUser")
.WithMany()
.HasForeignKey("DeleterUserId");
b.HasOne("Futbol3.Authorization.Users.User", "LastModifierUser")
.WithMany()
.HasForeignKey("LastModifierUserId");
b.Navigation("CreatorUser");
b.Navigation("DeleterUser");
b.Navigation("LastModifierUser");
});
modelBuilder.Entity("Futbol3.MultiTenancy.Tenant", b =>
{
b.HasOne("Futbol3.Authorization.Users.User", "CreatorUser")
.WithMany()
.HasForeignKey("CreatorUserId");
b.HasOne("Futbol3.Authorization.Users.User", "DeleterUser")
.WithMany()
.HasForeignKey("DeleterUserId");
b.HasOne("Abp.Application.Editions.Edition", "Edition")
.WithMany()
.HasForeignKey("EditionId");
b.HasOne("Futbol3.Authorization.Users.User", "LastModifierUser")
.WithMany()
.HasForeignKey("LastModifierUserId");
b.Navigation("CreatorUser");
b.Navigation("DeleterUser");
b.Navigation("Edition");
b.Navigation("LastModifierUser");
});
modelBuilder.Entity("Abp.Application.Features.EditionFeatureSetting", b =>
{
b.HasOne("Abp.Application.Editions.Edition", "Edition")
.WithMany()
.HasForeignKey("EditionId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("Edition");
});
modelBuilder.Entity("Abp.Authorization.Roles.RolePermissionSetting", b =>
{
b.HasOne("Futbol3.Authorization.Roles.Role", null)
.WithMany("Permissions")
.HasForeignKey("RoleId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
});
modelBuilder.Entity("Abp.Authorization.Users.UserPermissionSetting", b =>
{
b.HasOne("Futbol3.Authorization.Users.User", null)
.WithMany("Permissions")
.HasForeignKey("UserId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
});
modelBuilder.Entity("Abp.DynamicEntityProperties.DynamicProperty", b =>
{
b.Navigation("DynamicPropertyValues");
});
modelBuilder.Entity("Abp.EntityHistory.EntityChange", b =>
{
b.Navigation("PropertyChanges");
});
modelBuilder.Entity("Abp.EntityHistory.EntityChangeSet", b =>
{
b.Navigation("EntityChanges");
});
modelBuilder.Entity("Abp.Organizations.OrganizationUnit", b =>
{
b.Navigation("Children");
});
modelBuilder.Entity("Futbol3.Authorization.Roles.Role", b =>
{
b.Navigation("Claims");
b.Navigation("Permissions");
});
modelBuilder.Entity("Futbol3.Authorization.Users.User", b =>
{
b.Navigation("Claims");
b.Navigation("Logins");
b.Navigation("Permissions");
b.Navigation("Roles");
b.Navigation("Settings");
b.Navigation("Tokens");
});
#pragma warning restore 612, 618
}
}
}
| 35.445493 | 106 | 0.429336 | [
"MIT"
] | marcoscolombo66/6.0.0 | aspnet-core/src/Futbol3.EntityFrameworkCore/Migrations/20201112121732_Upgraded_To_ABP_6_0.Designer.cs | 67,632 | C# |
using Microsoft.EntityFrameworkCore;
using System.ComponentModel.DataAnnotations;
using System.Collections.Generic;
using System.Linq;
using System;
namespace my_new_app.Context
{
public class DataContext : DbContext
{
public DbSet<Card> Card { get; set; }
public DbSet<Enemy> Enemy { get; set; }
public DbSet<Relic> Relic { get; set;}
public DbSet<Event> Event { get; set; }
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
optionsBuilder.UseMySQL("server=localhost;database=stsclone;user=root;password=root;port=8889;");
}
}
public class Card
{
public int Id { get; set; }
public string Name { get; set; }
public int Cost { get; set; }
public string Type { get; set; }
public string Effects { get; set; }
public string CardText { get; set; }
public string Color { get; set; }
public int Upgraded { get; set; }
public int Rarity { get; set; }
}
public class Enemy
{
public int Id { get; set; }
public string Attacks { get; set; }
public int RewardClass { get; set; }
public int HP { get; set; }
}
public class Relic
{
public int Id { get; set; }
public string Name { get; set; }
public int Value { get; set; }
public string Effects {get; set; }
}
public class Event
{
public int Id { get; set; }
public string Description { get; set; }
public int RewardClass { get; set; }
}
}
| 23.15 | 100 | 0.680346 | [
"MIT"
] | j-farkas/stsclone | Controllers/Efdata.cs | 1,389 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml.Linq;
using static System.Environment;
namespace MixinRefactoring
{
/// <summary>
/// stores the document comment of a class member.
/// </summary>
public class DocumentationComment
{
/// <summary>
/// store the documentation as string
/// used for easier validation during tests
/// </summary>
private string _documentationString;
/// <summary>
/// stores the documentation, every xml node
/// is stored in one element.
/// </summary>
private List<DocumentationElement> _elements =
new List<DocumentationElement>();
public DocumentationComment(string comment)
{
if (string.IsNullOrEmpty(comment))
return;
var xmlComment = XDocument.Parse(comment);
// comments can either have a "member" or a "doc" element enclosing them
var contentElement = xmlComment.Elements("member").FirstOrDefault();
if (contentElement == null)
contentElement = xmlComment.Elements("doc").FirstOrDefault();
if (contentElement == null)
return;
var xmlElements = contentElement
.Descendants()
.ToList();
// create the string representation of the documentation
var stringBuilder = new StringBuilder();
// create a string for every new line in the comment
// and add a "///" in front of the line
var lines = xmlElements
.SelectMany(x => x.ToString().Split(new[] { NewLine }, StringSplitOptions.RemoveEmptyEntries))
.Select(x => x.Trim())
.ToList();
lines.ForEach(x => stringBuilder.AppendLine($"/// {x.ToString()}"));
_documentationString = stringBuilder.ToString();
_elements.AddRange(
xmlElements
.Select(x => new DocumentationElement(
x.Name.LocalName,
x.Value,
x.Attributes().Select(a => new Attribute(a.Name.LocalName,a.Value)))));
}
public bool HasSummary => _elements.Any();
public IEnumerable<DocumentationElement> Elements => _elements;
public override string ToString() => _documentationString;
/// <summary>
/// stores an xml document element.
/// </summary>
public class DocumentationElement
{
private readonly List<Attribute> _attributes = new List<Attribute>();
public DocumentationElement(string tag,string content, IEnumerable<Attribute> attributes)
{
Tag = tag;
Content = content;
_attributes.AddRange(attributes);
}
public string Tag { get; }
public string Content { get; }
public override string ToString() => $"<{Tag}> {Content} </{Tag}>";
public IEnumerable<Tuple<string, string>> Attributes => _attributes.Select(x => Tuple.Create(x.Name, x.Value));
}
/// <summary>
/// represents an attribute in an xml comment
/// </summary>
public class Attribute
{
public Attribute(string name, string value)
{
Name = name;
Value = value;
}
public string Name { get; }
public string Value { get; }
public override string ToString() => $"{Name}=\"{Value}\"";
}
}
}
| 35.701923 | 129 | 0.556154 | [
"MIT"
] | pgenfer/mixinSharp | MixinRefactoring/MetaData/DocumentationComment.cs | 3,715 | C# |
namespace OpenVIII.Fields.Scripts.Instructions
{
internal sealed class KILLBAR : JsmInstruction
{
#region Fields
private readonly IJsmExpression _arg0;
#endregion Fields
#region Constructors
public KILLBAR(IJsmExpression arg0) => _arg0 = arg0;
public KILLBAR(int parameter, IStack<IJsmExpression> stack)
: this(
arg0: stack.Pop())
{
}
#endregion Constructors
#region Methods
public override string ToString() => $"{nameof(KILLBAR)}({nameof(_arg0)}: {_arg0})";
#endregion Methods
}
} | 21.655172 | 92 | 0.595541 | [
"MIT"
] | FlameHorizon/OpenVIII-monogame | Core/Field/JSM/Instructions/KILLBAR.cs | 630 | C# |
/* Copyright (C) <2009-2011> <Thorben Linneweber, Jitter Physics>
*
* This software is provided 'as-is', without any express or implied
* warranty. In no event will the authors be held liable for any damages
* arising from the use of this software.
*
* Permission is granted to anyone to use this software for any purpose,
* including commercial applications, and to alter it and redistribute it
* freely, subject to the following restrictions:
*
* 1. The origin of this software must not be misrepresented; you must not
* claim that you wrote the original software. If you use this software
* in a product, an acknowledgment in the product documentation would be
* appreciated but is not required.
* 2. Altered source versions must be plainly marked as such, and must not be
* misrepresented as being the original software.
* 3. This notice may not be removed or altered from any source distribution.
*/
#region Using Statements
using System;
using System.Collections.Generic;
using Jitter.Dynamics;
using Jitter.LinearMath;
using Jitter.Collision.Shapes;
#endregion
namespace Jitter.Collision
{
/// <summary>
/// structure used to set up the mesh
/// </summary>
#region public struct TriangleVertexIndices
public struct TriangleVertexIndices
{
/// <summary>
/// The first index.
/// </summary>
public int I0;
/// <summary>
/// The second index.
/// </summary>
public int I1;
/// <summary>
/// The third index.
/// </summary>
public int I2;
/// <summary>
/// Initializes a new instance of the TriangleVertexIndex structure.
/// </summary>
/// <param name="i0">The index of the first vertex.</param>
/// <param name="i1">The index of the second vertex.</param>
/// <param name="i2">The index of the third vertex.</param>
public TriangleVertexIndices(int i0, int i1, int i2)
{
this.I0 = i0;
this.I1 = i1;
this.I2 = i2;
}
/// <summary>
/// Sets the values for the indices.
/// </summary>
/// <param name="i0">The index of the first vertex.</param>
/// <param name="i1">The index of the second vertex.</param>
/// <param name="i2">The index of the third vertex.</param>
public void Set(int i0, int i1, int i2)
{
I0 = i0; I1 = i1; I2 = i2;
}
}
#endregion
/// <summary>
/// An octree implementation.
/// </summary>
public class Octree
{
/// <summary>
/// endices into the children - P means "plus" and M means "minus" and the
/// letters are xyz. So PPM means +ve x, +ve y, -ve z
/// </summary>
[Flags]
private enum EChild
{
XP = 0x1,
YP = 0x2,
ZP = 0x4,
PPP = XP | YP | ZP,
PPM = XP | YP,
PMP = XP | ZP,
PMM = XP,
MPP = YP | ZP,
MPM = YP,
MMP = ZP,
MMM = 0x0,
}
private struct Node
{
public UInt16[] nodeIndices;
public int[] triIndices;
public JBBox box;
}
private class BuildNode
{
public int childType; // will default to MMM (usually ECHild but can also be -1)
public List<int> nodeIndices = new List<int>();
public List<int> triIndices = new List<int>();
public JBBox box;
}
private JVector[] positions;
private JBBox[] triBoxes;
private Node[] nodes;
//private UInt16[] nodeStack;
internal TriangleVertexIndices[] tris;
internal JBBox rootNodeBox;
/// <summary>
/// Gets the root node box containing the whole octree.
/// </summary>
public JBBox RootNodeBox { get { return rootNodeBox; } }
/// <summary>
/// Clears the octree.
/// </summary>
#region public void Clear()
public void Clear()
{
positions = null;
triBoxes = null;
tris = null;
nodes = null;
nodeStackPool.ResetResourcePool();
}
#endregion
/// <summary>
/// Sets new triangles.
/// </summary>
/// <param name="positions">Vertices.</param>
/// <param name="tris">Indices.</param>
#region public void AddTriangles(List<JVector> positions, List<TriangleVertexIndices> tris)
public void SetTriangles(List<JVector> positions, List<TriangleVertexIndices> tris)
{
// copy the position data into a array
this.positions = new JVector[positions.Count];
positions.CopyTo(this.positions);
// copy the triangles
this.tris = new TriangleVertexIndices[tris.Count];
tris.CopyTo(this.tris);
}
#endregion
/// <summary>
/// Builds the octree.
/// </summary>
#region public void BuildOctree()
public void BuildOctree()
{
// create tri and tri bounding box arrays
triBoxes = new JBBox[tris.Length];
// create an infinite size root box
rootNodeBox = new JBBox(new JVector(float.PositiveInfinity, float.PositiveInfinity, float.PositiveInfinity),
new JVector(float.NegativeInfinity, float.NegativeInfinity, float.NegativeInfinity));
for (int i = 0; i < tris.Length; i++)
{
JVector.Min(ref positions[tris[i].I1], ref positions[tris[i].I2], out triBoxes[i].Min);
JVector.Min(ref positions[tris[i].I0], ref triBoxes[i].Min, out triBoxes[i].Min);
JVector.Max(ref positions[tris[i].I1], ref positions[tris[i].I2], out triBoxes[i].Max);
JVector.Max(ref positions[tris[i].I0], ref triBoxes[i].Max, out triBoxes[i].Max);
// get size of the root box
JVector.Min(ref rootNodeBox.Min, ref triBoxes[i].Min, out rootNodeBox.Min);
JVector.Max(ref rootNodeBox.Max, ref triBoxes[i].Max, out rootNodeBox.Max);
}
List<BuildNode> buildNodes = new List<BuildNode>();
buildNodes.Add(new BuildNode());
buildNodes[0].box = rootNodeBox;
JBBox[] children = new JBBox[8];
for (int triNum = 0; triNum < tris.Length; triNum++)
{
int nodeIndex = 0;
JBBox box = rootNodeBox;
while (box.Contains(ref triBoxes[triNum]) == JBBox.ContainmentType.Contains)
{
int childCon = -1;
for (int i = 0; i < 8; ++i)
{
CreateAABox(ref box, (EChild)i,out children[i]);
if (children[i].Contains(ref triBoxes[triNum]) == JBBox.ContainmentType.Contains)
{
// this box contains the tri, it can be the only one that does,
// so we can stop our child search now and recurse into it
childCon = i;
break;
}
}
// no child contains this tri completely, so it belong in this node
if (childCon == -1)
{
buildNodes[nodeIndex].triIndices.Add(triNum);
break;
}
else
{
// do we already have this child
int childIndex = -1;
for (int index = 0; index < buildNodes[nodeIndex].nodeIndices.Count; ++index)
{
if (buildNodes[buildNodes[nodeIndex].nodeIndices[index]].childType == childCon)
{
childIndex = index;
break;
}
}
if (childIndex == -1)
{
// nope create child
BuildNode parentNode = buildNodes[nodeIndex];
BuildNode newNode = new BuildNode();
newNode.childType = childCon;
newNode.box = children[childCon];
buildNodes.Add(newNode);
nodeIndex = buildNodes.Count - 1;
box = children[childCon];
parentNode.nodeIndices.Add(nodeIndex);
}
else
{
nodeIndex = buildNodes[nodeIndex].nodeIndices[childIndex];
box = children[childCon];
}
}
}
}
// now convert to the tighter Node from BuildNodes
nodes = new Node[buildNodes.Count];
nodeStackPool = new ArrayResourcePool<ushort>(buildNodes.Count);
//nodeStack = new UInt16[buildNodes.Count];
for (int i = 0; i < nodes.Length; i++)
{
nodes[i].nodeIndices = new UInt16[buildNodes[i].nodeIndices.Count];
for (int index = 0; index < nodes[i].nodeIndices.Length; ++index)
{
nodes[i].nodeIndices[index] = (UInt16)buildNodes[i].nodeIndices[index];
}
nodes[i].triIndices = new int[buildNodes[i].triIndices.Count];
buildNodes[i].triIndices.CopyTo(nodes[i].triIndices);
nodes[i].box = buildNodes[i].box;
}
buildNodes.Clear(); buildNodes = null;
}
#endregion
/// <summary>
/// Initializes a new instance of the Octree class.
/// </summary>
/// <param name="positions">Vertices.</param>
/// <param name="tris">Indices.</param>
#region Constructor
public Octree(List<JVector> positions, List<TriangleVertexIndices> tris)
{
SetTriangles(positions, tris);
BuildOctree();
}
#endregion
/// <summary>
/// Create a bounding box appropriate for a child, based on a parents AABox
/// </summary>
/// <param name="aabb"></param>
/// <param name="child"></param>
/// <param name="result"></param>
#region private void CreateAABox(ref JBBox aabb, EChild child,out JBBox result)
private void CreateAABox(ref JBBox aabb, EChild child,out JBBox result)
{
JVector dims;
JVector.Subtract(ref aabb.Max, ref aabb.Min, out dims);
JVector.Multiply(ref dims, 0.5f, out dims);
JVector offset = JVector.Zero;
switch (child)
{
case EChild.PPP: offset = new JVector(1, 1, 1); break;
case EChild.PPM: offset = new JVector(1, 1, 0); break;
case EChild.PMP: offset = new JVector(1, 0, 1); break;
case EChild.PMM: offset = new JVector(1, 0, 0); break;
case EChild.MPP: offset = new JVector(0, 1, 1); break;
case EChild.MPM: offset = new JVector(0, 1, 0); break;
case EChild.MMP: offset = new JVector(0, 0, 1); break;
case EChild.MMM: offset = new JVector(0, 0, 0); break;
default:
System.Diagnostics.Debug.WriteLine("Octree.CreateAABox got impossible child");
break;
}
result = new JBBox();
result.Min = new JVector(offset.X * dims.X, offset.Y * dims.Y, offset.Z * dims.Z);
JVector.Add(ref result.Min, ref aabb.Min, out result.Min);
JVector.Add(ref result.Min, ref dims, out result.Max);
// expand it just a tiny bit just to be safe!
float extra = 0.00001f;
JVector temp; JVector.Multiply(ref dims, extra, out temp);
JVector.Subtract(ref result.Min, ref temp, out result.Min);
JVector.Add(ref result.Max, ref temp, out result.Max);
}
#endregion
#region private void GatherTriangles(int nodeIndex, ref List<int> tris)
private void GatherTriangles(int nodeIndex, ref List<int> tris)
{
// add this nodes triangles
tris.AddRange(nodes[nodeIndex].triIndices);
// recurse into this nodes children
int numChildren = nodes[nodeIndex].nodeIndices.Length;
for (int i = 0; i < numChildren; ++i)
{
int childNodeIndex = nodes[nodeIndex].nodeIndices[i];
GatherTriangles(childNodeIndex, ref tris);
}
}
#endregion
/// <summary>
/// Returns all triangles which intersect the given axis aligned bounding box.
/// </summary>
/// <param name="triangles">The list to add the triangles to.</param>
/// <param name="testBox">The axis alignes bounding box.</param>
/// <returns></returns>
#region public int GetTrianglesIntersectingtAABox(List<int> triangles, ref JBBox testBox)
public int GetTrianglesIntersectingtAABox(List<int> triangles, ref JBBox testBox)
{
if (nodes.Length == 0)
return 0;
int curStackIndex = 0;
int endStackIndex = 1;
UInt16[] nodeStack = nodeStackPool.GetNew();
nodeStack[0] = 0;
int triCount = 0;
while (curStackIndex < endStackIndex)
{
UInt16 nodeIndex = nodeStack[curStackIndex];
curStackIndex++;
if (nodes[nodeIndex].box.Contains(ref testBox) != JBBox.ContainmentType.Disjoint)
{
for (int i = 0; i < nodes[nodeIndex].triIndices.Length; ++i)
{
if (triBoxes[nodes[nodeIndex].triIndices[i]].Contains(ref testBox) != JBBox.ContainmentType.Disjoint)
{
triangles.Add(nodes[nodeIndex].triIndices[i]);
triCount++;
}
}
int numChildren = nodes[nodeIndex].nodeIndices.Length;
for (int i = 0; i < numChildren; ++i)
{
nodeStack[endStackIndex++] = nodes[nodeIndex].nodeIndices[i];
}
}
}
nodeStackPool.GiveBack(nodeStack);
return triCount;
}
#endregion
private ArrayResourcePool<UInt16> nodeStackPool;
/// <summary>
/// Returns all triangles which intersect the given axis aligned bounding box.
/// </summary>
/// <param name="rayOrigin"></param>
/// <param name="rayDelta"></param>
/// <param name="triangles"></param>
/// <returns></returns>
#region public int GetTrianglesIntersectingtRay(JVector rayOrigin, JVector rayDelta)
public int GetTrianglesIntersectingRay(List<int> triangles, JVector rayOrigin, JVector rayDelta)
{
if (nodes.Length == 0)
return 0;
int curStackIndex = 0;
int endStackIndex = 1;
UInt16[] nodeStack = nodeStackPool.GetNew();
nodeStack[0] = 0;
int triCount = 0;
while (curStackIndex < endStackIndex)
{
UInt16 nodeIndex = nodeStack[curStackIndex];
curStackIndex++;
if (nodes[nodeIndex].box.SegmentIntersect(ref rayOrigin, ref rayDelta))
{
for (int i = 0; i < nodes[nodeIndex].triIndices.Length; ++i)
{
if (triBoxes[nodes[nodeIndex].triIndices[i]].SegmentIntersect(ref rayOrigin, ref rayDelta))
{
triangles.Add(nodes[nodeIndex].triIndices[i]);
triCount++;
}
}
int numChildren = nodes[nodeIndex].nodeIndices.Length;
for (int i = 0; i < numChildren; ++i)
{
nodeStack[endStackIndex++] = nodes[nodeIndex].nodeIndices[i];
}
}
}
nodeStackPool.GiveBack(nodeStack);
return triCount;
}
#endregion
/// <summary>
/// Gets the indices of a triangle by index.
/// </summary>
/// <param name="index">The index.</param>
/// <returns>The indices of a triangle.</returns>
#region public TriangleVertexIndices GetTriangleVertexIndex(int index)
public TriangleVertexIndices GetTriangleVertexIndex(int index)
{
return tris[index];
}
#endregion
/// <summary>
/// Gets a vertex from the vertex list.
/// </summary>
/// <param name="vertex">The index of the vertex</param>
/// <returns></returns>
#region public JVector GetVertex(int vertex)
public JVector GetVertex(int vertex)
{
return positions[vertex];
}
/// <summary>
/// Gets a vertex from the vertex list.
/// </summary>
/// <param name="vertex">The index of the vertex</param>
/// <param name="result"></param>
public void GetVertex(int vertex, out JVector result)
{
result = positions[vertex];
}
#endregion
/// <summary>
/// Gets the number of triangles within this octree.
/// </summary>
#region public int NumTriangles
public int NumTriangles
{
get { return tris.Length; }
}
#endregion
}
}
| 36.75 | 128 | 0.514099 | [
"Apache-2.0"
] | 365082218/meteor_original_ios | Assets/ThirdParty/Jitter/Collision/Octree.cs | 18,230 | C# |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class WheelRotation : MonoBehaviour {
public Movement movement;
public float rotation;
/// <summary>
/// Call method to rotate wheels
/// </summary>
void Update ()
{
Rotate();
}
/// <summary>
/// Based on which truck way the truck is facing rotate the wheels in the approriapte directions around the Z axis
/// </summary>
void Rotate()
{
bool movementRight = Input.GetKey(KeyCode.RightArrow);
bool movementLeft = Input.GetKey(KeyCode.LeftArrow);
if (movementRight)
{
transform.Rotate(new Vector3(0, 0, -rotation));
}
if (movementLeft)
{
transform.Rotate(new Vector3(0, 0, rotation));
}
}
}
| 23.459459 | 119 | 0.577189 | [
"MIT"
] | N8STROMO/2D-RocketLeague | Assets/Scripts/WheelRotation.cs | 870 | C# |
namespace API.DTOs
{
public class MemberDTO
{
public int Id { get; set; }
public string Username { get; set; }
public string PhotoUrl { get; set; }
public int Age { get; set; }
public string KnowAs { get; set; }
public DateTime Created { get; set; }
public DateTime LastActive { get; set; }
public string Gender { get; set; }
public string Introduction { get; set; }
public string LookinFor { get; set; }
public string Interests { get; set; }
public string City { get; set; }
public string Country { get; set; }
public ICollection<PhotoDTO> Photos { get; set; }
}
}
| 29.952381 | 53 | 0.629571 | [
"MIT"
] | FernandoDevBh/DattingApp | API/DTOs/MemberDTO.cs | 631 | C# |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using Iot.Device.Mcp25xxx.Register;
using Iot.Device.Mcp25xxx.Register.Interrupt;
using Xunit;
namespace Iot.Device.Mcp25xxx.Tests.Register.Interrupt
{
public class CanIntFTests
{
[Fact]
public void Get_Address()
{
Assert.Equal(Address.CanIntF, new CanIntF(false, false, false, false, false, false, false, false).Address);
}
[Theory]
[InlineData(false, false, false, false, false, false, false, false, 0b0000_0000)]
[InlineData(true, false, false, false, false, false, false, false, 0b0000_0001)]
[InlineData(false, true, false, false, false, false, false, false, 0b0000_0010)]
[InlineData(false, false, true, false, false, false, false, false, 0b0000_0100)]
[InlineData(false, false, false, true, false, false, false, false, 0b0000_1000)]
[InlineData(false, false, false, false, true, false, false, false, 0b0001_0000)]
[InlineData(false, false, false, false, false, true, false, false, 0b0010_0000)]
[InlineData(false, false, false, false, false, false, true, false, 0b0100_0000)]
[InlineData(false, false, false, false, false, false, false, true, 0b1000_0000)]
public void From_To_Byte(
bool receiveBuffer0FullInterruptFlag,
bool receiveBuffer1FullInterruptFlag,
bool transmitBuffer0EmptyInterruptFlag,
bool transmitBuffer1EmptyInterruptFlag,
bool transmitBuffer2EmptyInterruptFlag,
bool errorInterruptFlag,
bool wakeUpInterruptFlag,
bool messageErrorInterruptFlag,
byte expectedByte)
{
var canIntF = new CanIntF(
receiveBuffer0FullInterruptFlag,
receiveBuffer1FullInterruptFlag,
transmitBuffer0EmptyInterruptFlag,
transmitBuffer1EmptyInterruptFlag,
transmitBuffer2EmptyInterruptFlag,
errorInterruptFlag,
wakeUpInterruptFlag,
messageErrorInterruptFlag);
Assert.Equal(receiveBuffer0FullInterruptFlag, canIntF.ReceiveBuffer0FullInterruptFlag);
Assert.Equal(receiveBuffer1FullInterruptFlag, canIntF.ReceiveBuffer1FullInterruptFlag);
Assert.Equal(transmitBuffer0EmptyInterruptFlag, canIntF.TransmitBuffer0EmptyInterruptFlag);
Assert.Equal(transmitBuffer1EmptyInterruptFlag, canIntF.TransmitBuffer1EmptyInterruptFlag);
Assert.Equal(transmitBuffer2EmptyInterruptFlag, canIntF.TransmitBuffer2EmptyInterruptFlag);
Assert.Equal(errorInterruptFlag, canIntF.ErrorInterruptFlag);
Assert.Equal(wakeUpInterruptFlag, canIntF.WakeUpInterruptFlag);
Assert.Equal(messageErrorInterruptFlag, canIntF.MessageErrorInterruptFlag);
Assert.Equal(expectedByte, canIntF.ToByte());
Assert.Equal(expectedByte, new CanIntF(expectedByte).ToByte());
}
}
}
| 51.721311 | 120 | 0.672583 | [
"MIT"
] | gukoff/nanoFramework.IoT.Device | src/devices_generated/Mcp25xxx/tests/Register/Interrupt/CanIntFTests.cs | 3,155 | C# |
//----------------------------------------------
// NGUI: Next-Gen UI kit
// Copyright © 2011-2012 Tasharen Entertainment
//----------------------------------------------
using UnityEngine;
/// <summary>
/// Convenience script that resizes the camera's orthographic size to match the screen size.
/// This script can be used to create pixel-perfect UI, however it's usually more convenient
/// to create the UI that stays proportional as the screen scales. If that is what you
/// want, you don't need this script (or at least don't need it to be active).
/// </summary>
[ExecuteInEditMode]
[RequireComponent(typeof(Camera))]
[AddComponentMenu("NGUI/UI/Orthographic Camera")]
public class UIOrthoCamera : MonoBehaviour
{
Camera mCam;
Transform mTrans;
void Start ()
{
mCam = camera;
mTrans = transform;
mCam.orthographic = true;
}
void Update ()
{
float y0 = mCam.rect.yMin * Screen.height;
float y1 = mCam.rect.yMax * Screen.height;
float size = (y1 - y0) * 0.5f * mTrans.lossyScale.y;
if (!Mathf.Approximately(mCam.orthographicSize, size)) mCam.orthographicSize = size;
}
} | 29.342105 | 92 | 0.649327 | [
"MIT"
] | Maeloo/BehindTheMoon | Assets/NGUI/Scripts/UI/UIOrthoCamera.cs | 1,118 | C# |
using System;
namespace Student
{
public class Student
{
public int id { get; }
public string GivenName { get; set; }
public string Surname { get; set; }
public DateTime StartDate { get; set; }
public DateTime EndDate { get; set; }
public DateTime GraduationDate { get; set; }
public Status Status { get {
if(EndDate < GraduationDate){
return Status.Dropout;
}
else if(GraduationDate > DateTime.Now && EndDate > DateTime.Now ){
if(DateTime.Now.Subtract(StartDate) < new TimeSpan(365,0,0,0)){
return Status.New;
}
else{
return Status.Active;
}
}
//else if (GraduationDate <= DateTime.Now && GraduationDate == EndDate){
return Status.Graduated;
//}
}}
public Student(int id){
this.id = id;
}
public string ToString(){
return "ID: " + id + ", Name: " + GivenName + " " + Surname + ", StartDate: " + StartDate.ToString("MM/dd/yyyy") + ", EndDate: " + EndDate.ToString("MM/dd/yyyy") + ", GraduationDate: " + GraduationDate.ToString("MM/dd/yyyy") + ", Status: " + Status;
}
}
}
| 30.043478 | 262 | 0.48191 | [
"MIT"
] | Kobo-coder/Assignment2 | Student/Class1.cs | 1,384 | C# |
namespace Abc.LuckyStar2.Shared.Entities
{
public partial class MailboxStatistics
{
#region --- PROPERTIES ---
//public DateTime? DateTime { get { return GetAliasedValue<DateTime?>("c.birthdate"); } }
#endregion
#region --- STATIC METHODS ---
#endregion
}
}
| 18.588235 | 97 | 0.594937 | [
"MIT"
] | Kayserheimer/Dynamics-Crm-DevKit | test/v.2.10.31/Abc.LuckyStar2/Abc.LuckyStar2.Shared/Entities/MailboxStatistics.cs | 318 | C# |
/**
* Copyright 2018 IBM Corp. 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 Newtonsoft.Json;
namespace IBM.WatsonDeveloperCloud.Conversation.v1.Model
{
/// <summary>
/// CreateCounterexample.
/// </summary>
public class CreateCounterexample : BaseModel
{
/// <summary>
/// The text of a user input marked as irrelevant input. This string must conform to the following restrictions:
///
/// - It cannot contain carriage return, newline, or tab characters
/// - It cannot consist of only whitespace characters
/// - It must be no longer than 1024 characters.
/// </summary>
/// <value>
/// The text of a user input marked as irrelevant input. This string must conform to the following restrictions:
///
/// - It cannot contain carriage return, newline, or tab characters
/// - It cannot consist of only whitespace characters
/// - It must be no longer than 1024 characters.
/// </value>
[JsonProperty("text", NullValueHandling = NullValueHandling.Ignore)]
public string Text { get; set; }
}
}
| 36.521739 | 120 | 0.672024 | [
"Apache-2.0"
] | johnpisg/dotnet-standard-sdk | src/IBM.WatsonDeveloperCloud.Conversation.v1/Model/CreateCounterexample.cs | 1,680 | C# |
using System;
using System.Linq;
using OrleansDashboard;
using OrleansDashboard.History;
using Xunit;
namespace UnitTests
{
public class TraceHistoryTests
{
DateTime startTime = DateTime.UtcNow;
int seconds = 0;
void Add(ITraceHistory history, int count)
{
for (var i = 0; i < count; i++)
{
history.Add(startTime.AddSeconds(seconds), "SILO1", new SiloGrainTraceEntry[]{ new SiloGrainTraceEntry {
Grain = "GRAIN1",
Method = "METHOD1",
Count = 1,
ExceptionCount = 0,
ElapsedTime = 10
}});
history.Add(startTime.AddSeconds(seconds), "SILO2", new SiloGrainTraceEntry[]{ new SiloGrainTraceEntry {
Grain = "GRAIN1",
Method = "METHOD1",
Count = 100,
ExceptionCount = 10,
ElapsedTime = 200
}});
seconds++;
}
}
[Fact]
public void TestTraceHistoryIsLimitedTo100()
{
var history = new TraceHistory() as ITraceHistory;
// seed with 100 values
Add(history, 100);
// check there are 100 values in the results
var grainTraceDictionary = history.QueryAll();
Assert.Equal(100, grainTraceDictionary.Keys.Count);
// add another 10 values
Add(history, 10);
var grainTraceDictionary2 = history.QueryAll();
Assert.Equal(100, grainTraceDictionary2.Keys.Count);
}
[Fact]
public void TestTraceHistoryQueryAll()
{
var history = new TraceHistory() as ITraceHistory;
Add(history, 100);
var silo1History = history.QuerySilo("SILO1");
Assert.Equal(100, silo1History.Keys.Count);
}
[Fact]
public void TestTraceHistoryQueryGrain()
{
var history = new TraceHistory() as ITraceHistory;
Add(history, 100);
var grainDictionary = history.QueryGrain("GRAIN1");
Assert.Single(grainDictionary.Keys);
Assert.Equal("GRAIN1.METHOD1", grainDictionary.Keys.First());
Assert.Equal(100, grainDictionary["GRAIN1.METHOD1"].Keys.Count);
}
[Fact]
public void TestTraceHistoryGroupByGrainAndSilo()
{
var history = new TraceHistory() as ITraceHistory;
Add(history, 100);
var traceAggregate = history.GroupByGrainAndSilo().ToList();
Assert.Equal(2, traceAggregate.Count);
var silo1Aggregate = traceAggregate.FirstOrDefault(x => x.SiloAddress == "SILO1");
Assert.Equal("SILO1", silo1Aggregate.SiloAddress);
Assert.Equal("GRAIN1", silo1Aggregate.Grain);
Assert.Equal(100, silo1Aggregate.Count);
Assert.Equal(0, silo1Aggregate.ExceptionCount);
Assert.Equal(1000, silo1Aggregate.ElapsedTime);
var silo2Aggregate = traceAggregate.FirstOrDefault(x => x.SiloAddress == "SILO2");
Assert.Equal("SILO2", silo2Aggregate.SiloAddress);
Assert.Equal("GRAIN1", silo2Aggregate.Grain);
Assert.Equal(100 * 100, silo2Aggregate.Count);
Assert.Equal(10 * 100, silo2Aggregate.ExceptionCount);
Assert.Equal(200 * 100, silo2Aggregate.ElapsedTime);
}
[Fact]
public void TestTraceHistoryTopGrainMethods()
{
var history = new TraceHistory() as ITraceHistory;
Add(history, 100);
var results = history.AggregateByGrainMethod().ToList();
Assert.Single(results);
Assert.Equal(100 + (100 * 100), results.First().Count);
Assert.Equal(10 * 100, results.First().ExceptionCount);
Assert.Equal(1000 + (200 * 100), results.First().ElapsedTime);
}
}
} | 32.063492 | 120 | 0.561881 | [
"MIT"
] | carloslazo/OrleansDashboard | UnitTests/HistoryTests.cs | 4,042 | C# |
// *** WARNING: this file was generated by the Pulumi SDK Generator. ***
// *** Do not edit by hand unless you're certain you know what you are doing! ***
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Threading.Tasks;
using Pulumi.Serialization;
namespace Pulumi.AzureNative.Network.V20191001.Outputs
{
[OutputType]
public sealed class ManagedRuleOverrideResponse
{
/// <summary>
/// Describes the override action to be applied when rule matches.
/// </summary>
public readonly string? Action;
/// <summary>
/// Describes if the managed rule is in enabled or disabled state. Defaults to Disabled if not specified.
/// </summary>
public readonly string? EnabledState;
/// <summary>
/// Describes the exclusions that are applied to this specific rule.
/// </summary>
public readonly ImmutableArray<Outputs.ManagedRuleExclusionResponse> Exclusions;
/// <summary>
/// Identifier for the managed rule.
/// </summary>
public readonly string RuleId;
[OutputConstructor]
private ManagedRuleOverrideResponse(
string? action,
string? enabledState,
ImmutableArray<Outputs.ManagedRuleExclusionResponse> exclusions,
string ruleId)
{
Action = action;
EnabledState = enabledState;
Exclusions = exclusions;
RuleId = ruleId;
}
}
}
| 30.88 | 113 | 0.632772 | [
"Apache-2.0"
] | pulumi-bot/pulumi-azure-native | sdk/dotnet/Network/V20191001/Outputs/ManagedRuleOverrideResponse.cs | 1,544 | C# |
using System;
using System.Runtime.InteropServices;
using System.Security;
using System.Text;
using System.Windows;
using System.Windows.Automation.Provider;
using System.Windows.Controls;
using System.Windows.Controls.Primitives;
using System.Windows.Interop;
using System.Windows.Media;
using MS.Internal;
using MS.Win32;
namespace System.Windows.Automation.Peers
{
///
public class GroupBoxAutomationPeer : FrameworkElementAutomationPeer
{
///
public GroupBoxAutomationPeer(GroupBox owner): base(owner)
{}
///
override protected string GetClassNameCore()
{
return "GroupBox";
}
///
override protected AutomationControlType GetAutomationControlTypeCore()
{
return AutomationControlType.Group;
}
// Return the base without the AccessKey character
///
override protected string GetNameCore()
{
string result = base.GetNameCore();
if (!string.IsNullOrEmpty(result))
{
GroupBox groupBox = (GroupBox)Owner;
if (groupBox.Header is string)
{
return AccessText.RemoveAccessKeyMarker(result);
}
}
return result;
}
}
}
| 23.438596 | 79 | 0.604042 | [
"Apache-2.0"
] | 295007712/295007712.github.io | sourceCode/dotNet4.6/wpf/src/Framework/System/Windows/Automation/Peers/GroupBoxAutomationPeer.cs | 1,336 | C# |
using System.Threading;
using System.Threading.Tasks;
namespace Bewit
{
internal class DefaultNonceRepository : INonceRepository
{
private static readonly ValueTask EmptyTask = new ValueTask();
private static readonly ValueTask<Token> EmptyToken = new ValueTask<Token>(Token.Empty);
public ValueTask InsertOneAsync(Token token, CancellationToken cancellationToken)
{
return EmptyTask;
}
public ValueTask<Token> TakeOneAsync(string token, CancellationToken cancellationToken)
{
return EmptyToken;
}
}
}
| 27.5 | 96 | 0.684298 | [
"MIT"
] | SwissLife-OSS/bewit | src/Core/DefaultNonceRepository.cs | 605 | C# |
using System;
using System.Xml.Serialization;
using System.Collections.Generic;
namespace Aop.Api.Domain
{
/// <summary>
/// HitDialogue Data Structure.
/// </summary>
[Serializable]
public class HitDialogue : AopObject
{
/// <summary>
/// 命中结果高亮
/// </summary>
[XmlArray("key_words")]
[XmlArrayItem("dialogue_key_word")]
public List<DialogueKeyWord> KeyWords { get; set; }
/// <summary>
/// 对话句子唯一标识
/// </summary>
[XmlElement("pid")]
public long Pid { get; set; }
}
}
| 21.777778 | 59 | 0.557823 | [
"Apache-2.0"
] | alipay/alipay-sdk-net | AlipaySDKNet.Standard/Domain/HitDialogue.cs | 616 | C# |
// The MIT License (MIT)
//
// Copyright (c) 2015 Microsoft
//
// 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.
namespace MetricSystem.Utilities.UnitTests
{
using System;
using System.Collections.Generic;
using NUnit.Framework;
[TestFixture]
public class HistogramExtensionMethodTests
{
[SetUp]
public void SetUp()
{
this.histogram.Clear();
}
private readonly Dictionary<long, uint> histogram = new Dictionary<long, uint>();
private void InitializeHistogramWithUniformValues(int min, int max)
{
for (var i = min; i <= max; i++)
{
this.histogram[i] = 1;
}
}
private static void VerifyThrows<T>(Action a) where T : Exception
{
try
{
a();
Assert.Fail("Should have thrown. Did not. Enter failman: " + typeof(T));
}
catch (T)
{
//hooray
}
catch (Exception e)
{
Assert.AreEqual(typeof(T), e.GetType());
}
}
[Test]
public void AverageAvoidsOverflow()
{
this.histogram[int.MaxValue / 2] = 10;
this.histogram[int.MaxValue / 3] = 1;
var avg = this.histogram.GetAverageValue();
Assert.IsTrue(avg > 0.0);
this.histogram.Clear();
this.histogram[int.MaxValue] = 100;
Assert.AreEqual(int.MaxValue, this.histogram.GetAverageValue());
}
[Test]
public void AverageIsCorrectForUniformDistribution()
{
// 55 / 11 = 5.0
this.InitializeHistogramWithUniformValues(0, 10);
Assert.AreEqual(5.0, this.histogram.GetAverageValue());
}
[Test]
public void AverageIsCorrectWithUnevenDistribution()
{
this.histogram[100] = 100;
this.histogram[0] = 100;
Assert.AreEqual(50, this.histogram.GetAverageValue());
}
[Test]
public void EmptyHistogramsAreHandledCorrectly()
{
Assert.AreEqual(0, this.histogram.GetMaximumValue());
Assert.AreEqual(0, this.histogram.GetMinimumValue());
Assert.AreEqual(0, this.histogram.GetAverageValue());
Assert.AreEqual(0, this.histogram.GetValueAtPercentile(12));
Assert.AreEqual(0, this.histogram.GetValueAtPercentile(99.999));
}
[Test]
public void MaximumCalculatedCorrectly()
{
this.InitializeHistogramWithUniformValues(100, 10000);
Assert.AreEqual(10000, this.histogram.GetMaximumValue());
}
[Test]
public void MethodsCheckForNull()
{
Assert.AreEqual(0, (null as IDictionary<long, uint>).GetValueAtPercentile(10));
Assert.AreEqual(0, (null as IDictionary<long, uint>).GetAverageValue(10));
Assert.AreEqual(0, (null as IDictionary<long, uint>).GetMaximumValue());
Assert.AreEqual(0, (null as IDictionary<long, uint>).GetMinimumValue());
Assert.AreEqual(0, (null as IDictionary<long, uint>).GetValueAtPercentile(10, 10));
}
[Test]
public void MinimumCalculatedCorrectly()
{
this.InitializeHistogramWithUniformValues(100, 10000);
Assert.AreEqual(100, this.histogram.GetMinimumValue());
}
[Test]
public void PercentileCalculatedCorrectlyForUnevenDistribution()
{
this.histogram[0] = 999;
this.histogram[8675309] = 1;
Assert.AreEqual(0, this.histogram.GetValueAtPercentile(44));
Assert.AreEqual(0, this.histogram.GetValueAtPercentile(88));
Assert.AreEqual(0, this.histogram.GetValueAtPercentile(99));
Assert.AreEqual(0, this.histogram.GetValueAtPercentile(99.9));
Assert.AreEqual(8675309, this.histogram.GetValueAtPercentile(99.99));
Assert.AreEqual(8675309, this.histogram.GetValueAtPercentile(100));
}
[Test]
public void PercentileCalculatedCorrectlyForUniformDistribution()
{
this.InitializeHistogramWithUniformValues(1, 100);
for (var i = 1; i < 100; i++)
{
Assert.AreEqual(i, this.histogram.GetValueAtPercentile(i));
}
}
[Test]
public void PercentileIsCalculatedCorrectlyAtDecimalPercentiles()
{
this.InitializeHistogramWithUniformValues(1, 1000);
Assert.AreEqual(333, this.histogram.GetValueAtPercentile(33.3));
Assert.AreEqual(666, this.histogram.GetValueAtPercentile(66.6));
Assert.AreEqual(999, this.histogram.GetValueAtPercentile(99.9));
}
[Test]
public void PercentilesAreValidated()
{
VerifyThrows<ArgumentException>(() => this.histogram.GetValueAtPercentile(200));
}
}
}
| 35.705882 | 95 | 0.612026 | [
"MIT"
] | Bhaskers-Blu-Org2/MetricSystem | unittest/Utilities/HistogramExtensionMethodTests.cs | 6,072 | C# |
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Transactions;
using Dapper;
using Microsoft.AspNet.Identity;
using iRocks.DataLayer.Helpers;
namespace iRocks.DataLayer
{
public class UserDapperRepository : DapperRepositoryBase, IUserRepository
{
private bool disposed = false;
public UserDapperRepository()
: base(ConfigurationManager.ConnectionStrings["iRocksDB"].ConnectionString)
{
}
/*public IEnumerable<AppUser> GetItems(DephtLevel dephtLevel, CommandType commandType, string sql, dynamic parameters = null)
{
IEnumerable<AppUser> AppUsers = base.GetItems<AppUser>(commandType, sql, (DynamicParameters)parameters);
return DependenciesAffectation(dephtLevel, AppUsers);
}*/
public IEnumerable<AppUser> Select(DephtLevel dephtLevel, object criteria = null, SQLKeyWord ConditionalKeyWord = null)
{
var postRepository = new PostDapperRepository();
var skillRepository = new SkillDapperRepository();
var newsfeedRepository = new NewsfeedDapperRepository();
var notificationRepository = new NotificationDapperRepository();
var badgeRepository = new BadgeDapperRepository();
var badgeCollectedRepository = new BadgeCollectedDapperRepository();
var voteRepository = new VoteDapperRepository();
var friendshipRepository = new FriendshipDapperRepository();
var lookup = new Dictionary<int, AppUser>();
//var friendships = new Dictionary<int, Friendship>();
//var postIds = new List<int>();
//var skillIds = new List<int>();
var NewsfeedMapping = new List<Newsfeed>();
var NewsfeedPosts = new List<Post>();
var NewsfeedPosters = new List<AppUser>();
var Newsfeeds = new List<Publication>();
var users = base.Select<AppUser, FacebookUserDetail, TwitterUserDetail, ExternalLogin, AppUser>(
@"SELECT * FROM AppUser LEFT OUTER JOIN FacebookUserDetail ON AppUser.AppUserId = FacebookUserDetail.AppUserId
LEFT OUTER JOIN TwitterUserDetail ON AppUser.AppUserId = TwitterUserDetail.AppUserId
LEFT OUTER JOIN ExternalLogin ON AppUser.AppUserId = ExternalLogin.AppUserId ",
(user, facebookDetail, twitterDetail, externalLogin) =>
{
return MatchBasics(user, facebookDetail, twitterDetail, externalLogin, lookup);
},
criteria,
ConditionalKeyWord,
splitOn: "FacebookUserDetailId, TwitterUserDetailId, ExternalLoginId"
);
var userIds = lookup.Values.Select(u => u.AppUserId).ToList();
if (dephtLevel >= DephtLevel.UserFootprint)
{
var skills = skillRepository.Select(new { AppUserId = userIds });
foreach (var user in lookup.Values)
{
user.Footprint.AddRange(skills.Where(s => s.AppUserId == user.AppUserId));
}
}
if (dephtLevel >= DephtLevel.UserProfile)
{
var notifications = notificationRepository.Select(new { AppUserId = userIds });
var badgesCollected = badgeCollectedRepository.Select(new { AppUserId = userIds });
foreach (var user in lookup.Values)
{
user.Badges = badgesCollected.Where(b => b.AppUserId == user.AppUserId).OrderBy(b => b.Badge.Level).ToList();
user.Notifications = notifications.Where(n => n.AppUserId == user.AppUserId).ToList();
}
}
if (dephtLevel >= DephtLevel.Friends)
{
List<AppUser> allUsers = new List<AppUser>();
var missingUserIds = new List<int>();
var friendsByUser = new Dictionary<int, List<int>>();
var friendships = friendshipRepository.Select(new { AppUserAId = userIds, AppUserBId = userIds }, SQLKeyWord.Or);
foreach (var frienship in friendships)
{
if (!userIds.Contains(frienship.AppUserAId) && !missingUserIds.Contains(frienship.AppUserAId))
missingUserIds.Add(frienship.AppUserAId);
if (!userIds.Contains(frienship.AppUserBId) && !missingUserIds.Contains(frienship.AppUserBId))
missingUserIds.Add(frienship.AppUserBId);
if (friendsByUser.Keys.Contains(frienship.AppUserAId))
friendsByUser[frienship.AppUserAId].Add(frienship.AppUserBId);
else
friendsByUser.Add(frienship.AppUserAId, new List<int>() { frienship.AppUserBId });
if (friendsByUser.Keys.Contains(frienship.AppUserBId))
friendsByUser[frienship.AppUserBId].Add(frienship.AppUserAId);
else
friendsByUser.Add(frienship.AppUserBId, new List<int>() { frienship.AppUserAId });
}
allUsers.AddRange(lookup.Values.Select(x => x.DeepClone()));
allUsers.AddRange(Select(DephtLevel.UserBasic, new { AppUserId = missingUserIds }));
var posts = postRepository.Select(new { AppUserId = userIds });
var votes = voteRepository.Select(new { AppUserId = userIds });
foreach (var user in lookup.Values)
{
user.Posts.AddRange(posts.Where(p => p.AppUserId == user.AppUserId));
user.Votes.AddRange(votes.Where(s => s.AppUserId == user.AppUserId));
if (friendsByUser.ContainsKey(user.AppUserId))
user.Friends.AddRange(allUsers.Where(u => friendsByUser[user.AppUserId].Contains(u.AppUserId)));
}
}
if (dephtLevel >= DephtLevel.NewsFeed)
{
NewsfeedMapping = newsfeedRepository.Select(new { AppUserId = userIds.ToList() }).ToList();
NewsfeedPosts = postRepository.Select(new { PostId = NewsfeedMapping.Select(n => n.PostId).ToList() }).ToList();
NewsfeedPosters = Select(DephtLevel.UserProfile, new { AppUserId = NewsfeedPosts.Select(p => p.AppUserId).ToList() }).ToList();
NewsfeedPosts.ForEach(
p => Newsfeeds.Add(
new Publication(
p,
NewsfeedPosters.Where(user => user.AppUserId == p.AppUserId).First()
)));
foreach (var user in lookup.Values)
{
var newsfeedPostIds = NewsfeedMapping.Where(n => n.AppUserId == user.AppUserId).Select(n => n.PostId);
user.Newsfeed.AddRange(
Newsfeeds.Where(p => newsfeedPostIds.Contains(p.Post.PostId))
);
}
}
return lookup.Values;
}
public void Save(DephtLevel dephtLevel, AppUser user)
{
List<AppUser> users = new List<AppUser>();
users.Add(user);
Save(dephtLevel, users);
}
// /!\DELETE Operations have been disabled since the CleanDbUser is not implemented in FacebookDataFeed.
public void Save(DephtLevel dephtLevel, List<AppUser> users)
{
ISkillRepository SkillRepository = new SkillDapperRepository();
IVoteRepository VoteRepository = new VoteDapperRepository();
IPostRepository PostRepository = new PostDapperRepository();
IFriendshipRepository FriendshipRepository = new FriendshipDapperRepository();
IFacebookUserDetailRepository FacebookUserDetailRepository = new FacebookUserDetailDapperRepository();
ITwitterUserDetailRepository TwitterUserDetailRepository = new TwitterUserDetailDapperRepository();
IExternalLoginRepository ExternalLoginRepository = new ExternalLoginDapperRepository();
INewsfeedRepository NewsfeedRepository = new NewsfeedDapperRepository();
INotificationRepository notificationRepository = new NotificationDapperRepository();
IBadgeCollectedRepository badgeCollectedRepository = new BadgeCollectedDapperRepository();
var alreadySavedUsers = new List<AppUser>();
var WholeFriendships = FriendshipRepository.Select(new { AppUserAId = users.Select(c => c.AppUserId).Distinct().ToList(), AppUserBId = users.Select(c => c.AppUserId).Distinct().ToList() }, SQLKeyWord.Or);
IEnumerable<Newsfeed> WholeNewsfeedMatching = new List<Newsfeed>();
if (dephtLevel == DephtLevel.NewsFeed)
{
WholeNewsfeedMatching = NewsfeedRepository.Select(new { AppUserId = users.Select(c => c.AppUserId).ToList() });
}
foreach (var user in users)
{
using (var transaction = new TransactionScope())
{
//Should not create new Skill to existing user !
if (!user.IsNew && user.Footprint.Where(s => s.IsNew).Any())
{
var dbFootprint = SkillRepository.Select(new { AppUserId = user.AppUserId });
foreach (var skill in user.Footprint.Where(s => s.IsNew))
{
var existingSkill = dbFootprint.Where(s => s.CategoryId == skill.CategoryId).SingleOrDefault();
if (existingSkill != null)
skill.SkillId = existingSkill.SkillId;
}
}
if (user.IsNew)
base.Insert<AppUser>(user);
else
base.Update<AppUser>(user);
alreadySavedUsers.Add(user);
if (user.IsProvidedBy(Provider.Facebook))
{
if (user.FacebookDetail.IsNew)
{
user.FacebookDetail.AppUserId = user.AppUserId;
FacebookUserDetailRepository.Insert(user.FacebookDetail);
}
//else if (user.FacebookDetail.IsDeleted)
// FacebookUserDetailRepository.Delete(user.FacebookDetail);
else
FacebookUserDetailRepository.Update(user.FacebookDetail);
}
if (user.IsProvidedBy(Provider.Twitter))
{
if (user.TwitterDetail.IsNew)
{
user.TwitterDetail.AppUserId = user.AppUserId;
TwitterUserDetailRepository.Insert(user.TwitterDetail);
}
else
TwitterUserDetailRepository.Update(user.TwitterDetail);
}
foreach (var externalLogin in user.ExternalLogins)
{
if (externalLogin.IsNew)
{
externalLogin.AppUserId = user.AppUserId;
ExternalLoginRepository.Insert(externalLogin);
}
//else if (externalLogin.IsDeleted)
// ExternalLoginRepository.Delete(externalLogin);
else
ExternalLoginRepository.Update(externalLogin);
}
if (dephtLevel >= DephtLevel.UserFootprint)
{
foreach (var skill in user.Footprint)
{
if (skill.IsNew)
{
skill.AppUserId = user.AppUserId;
SkillRepository.Insert(skill);
}
//else if (skill.IsDeleted)
// SkillRepository.Delete(skill);
else
SkillRepository.Update(skill);
}
}
if (dephtLevel >= DephtLevel.UserProfile)
{
foreach (var notification in user.Notifications)
{
if (notification.IsNew)
{
notification.AppUserId = user.AppUserId;
notificationRepository.Insert(notification);
}
//else if (vote.IsDeleted)
// VoteRepository.Delete(vote);
else
notificationRepository.Update(notification);
}
foreach (var badge in user.Badges)
{
if (badge.IsNew)
{
badge.AppUserId = user.AppUserId;
badgeCollectedRepository.Insert(badge);
}
//else if (vote.IsDeleted)
// VoteRepository.Delete(vote);
else
badgeCollectedRepository.Update(badge);
}
}
if (dephtLevel >= DephtLevel.Friends)
{
foreach (var post in user.Posts)
{
if (post.IsNew)
{
post.AppUserId = user.AppUserId;
PostRepository.Insert(post);
}
else
PostRepository.Update(post);
alreadySavedUsers.AddRange(ImbricatedObjectFinder.GetImbricatedUsers(post));
}
foreach (var vote in user.Votes)
{
if (vote.IsNew)
{
vote.AppUserId = user.AppUserId;
VoteRepository.Insert(vote);
}
//else if (vote.IsDeleted)
// VoteRepository.Delete(vote);
else
VoteRepository.Update(vote);
}
var friendships = WholeFriendships.Where(f => f.AppUserAId == user.AppUserId || f.AppUserBId == user.AppUserId);
foreach (var friend in user.Friends)
{
if (friend.IsNew)
base.Insert<AppUser>(friend);
else
Save(DephtLevel.UserBasic, friend);
alreadySavedUsers.Add(friend);
if (!friendships.Where(f => f.AppUserAId == friend.AppUserId || f.AppUserBId == friend.AppUserId).Any())
{
FriendshipRepository.Insert(new Friendship() { AppUserAId = user.AppUserId, AppUserBId = friend.AppUserId });
}
}
foreach (var friendship in friendships)
{
if (!user.Friends.Where(f => f.AppUserId == friendship.AppUserAId || f.AppUserId == friendship.AppUserBId).Any())
{
//FriendshipRepository.Delete(friendship);
}
}
}
transaction.Complete();
}
}
foreach (var user in users)//On rentre le newsfeed en dernier afin de s'assurer que l'ensemble des AppUsers ait été entré auparavant et ne pas faire de doublons
{
using (var transaction = new TransactionScope())
{
if (dephtLevel == DephtLevel.NewsFeed)
{
var implicatedUsers = ImbricatedObjectFinder.GetImbricatedUsers(user); // get all users to be saved for newsfeed
//parse them
var usersToBeSaved = ImbricatedObjectFinder.GetUsersToBeSaved(implicatedUsers, alreadySavedUsers);
var newsfeedMatchings = WholeNewsfeedMatching.Where(f => f.AppUserId == user.AppUserId);
Save(DephtLevel.UserProfile, usersToBeSaved);
foreach (var pair in user.Newsfeed)
{
var post = pair.Post;
if (post.IsNew)
{
post.AppUserId = pair.User.AppUserId;
if (pair.User.AppUserId == 0)
{
if (pair.User.IsProvidedBy(Provider.Facebook))
{
post.AppUserId = user.Newsfeed.Select(p => p.User).Where(u => u.FacebookDetail.FacebookUserId == pair.User.FacebookDetail.FacebookUserId && u.AppUserId != 0).First().AppUserId;
}
if (pair.User.IsProvidedBy(Provider.Twitter))
{
post.AppUserId = user.Newsfeed.Select(p => p.User).Where(u => u.TwitterDetail.TwitterUserId == pair.User.TwitterDetail.TwitterUserId && u.AppUserId != 0).First().AppUserId;
}
}
PostRepository.Insert(post);
}
else
PostRepository.Update(post);
if (!newsfeedMatchings.Where(f => f.PostId == post.PostId).Any())
{
NewsfeedRepository.Insert(new Newsfeed() { AppUserId = user.AppUserId, PostId = post.PostId });
}
}
}
transaction.Complete();
}
}
}
private AppUser MatchBasics(AppUser user, FacebookUserDetail facebookDetail, TwitterUserDetail twitterDetail, ExternalLogin externalLogin, Dictionary<int, AppUser> lookup)
{
AppUser aUser;
if (!lookup.TryGetValue(user.AppUserId, out aUser))
{
lookup.Add(user.AppUserId, aUser = user);
if (facebookDetail != null)
{
facebookDetail.SetSnapshot(facebookDetail);
aUser.FacebookDetail = facebookDetail;
}
if (twitterDetail != null)
{
twitterDetail.SetSnapshot(twitterDetail);
aUser.TwitterDetail = twitterDetail;
}
}
if (externalLogin != null && !aUser.ExternalLogins.Where(el => el.ExternalLoginId == externalLogin.ExternalLoginId).Any())
{
externalLogin.SetSnapshot(externalLogin);
aUser.ExternalLogins.Add(externalLogin);
}
return aUser;
}
public void Delete(AppUser obj)
{
using (var transaction = new TransactionScope())
{
ISkillRepository SkillRepository = new SkillDapperRepository();
IVoteRepository VoteRepository = new VoteDapperRepository();
IPostRepository PostRepository = new PostDapperRepository();
IFriendshipRepository FriendshipRepository = new FriendshipDapperRepository();
IFacebookUserDetailRepository FacebookUserDetailRepository = new FacebookUserDetailDapperRepository();
ITwitterUserDetailRepository TwitterUserDetailRepository = new TwitterUserDetailDapperRepository();
IExternalLoginRepository ExternalLoginRepository = new ExternalLoginDapperRepository();
if (obj.FacebookDetail != null)
FacebookUserDetailRepository.Delete(obj.FacebookDetail);
if (obj.TwitterDetail != null)
TwitterUserDetailRepository.Delete(obj.TwitterDetail);
foreach (Post aPost in obj.Posts)
{
PostRepository.Delete(aPost);
}
foreach (Vote aVote in obj.Votes)
{
VoteRepository.Delete(aVote);
}
foreach (ExternalLogin anExternalLogin in obj.ExternalLogins)
{
ExternalLoginRepository.Delete(anExternalLogin);
}
foreach (Skill aSkill in obj.Footprint)
{
SkillRepository.Delete(aSkill);
}
var Parameters = new DynamicParameters();
Parameters.Add("@AppUserId", obj.AppUserId);
base.Execute(CommandType.Text, "DELETE FROM Friendship WHERE AppUserAId = @AppUserId OR AppUserBId = @AppUserId");
base.Delete<AppUser>(obj);
transaction.Complete();
}
}
#region IUserStore Implementation
public Task CreateAsync(AppUser user)
{
if (user == null)
throw new ArgumentNullException("user");
return Task.Factory.StartNew(() =>
{
var existingUser = Select(DephtLevel.Friends, new { UserName = user.UserName }).FirstOrDefault();
if (existingUser != null)
{
user.ExternalLogins.ForEach(c => c.AppUserId = existingUser.AppUserId);
existingUser.ExternalLogins.AddRange(user.ExternalLogins);
user = existingUser;
}
else
{
if (user.IsProvidedBy(Provider.Facebook))
{
FacebookUserDetailDapperRepository FacebookUserDetailRepository = new FacebookUserDetailDapperRepository();
var FacebookDetails = FacebookUserDetailRepository.Select(new { FacebookUserId = user.FacebookDetail.FacebookUserId });
if (FacebookDetails.Any())
{
var tempUser = Select(DephtLevel.Friends, new { AppUserId = FacebookDetails.SingleOrDefault().AppUserId }).SingleOrDefault();
tempUser.ExternalLogins.AddRange(user.ExternalLogins);
if (tempUser.FacebookDetail != null)
{
user.FacebookDetail.FacebookUserDetailId = tempUser.FacebookDetail.FacebookUserDetailId;
user.FacebookDetail.AppUserId = tempUser.FacebookDetail.AppUserId;
tempUser.FacebookDetail = user.FacebookDetail;
}
else
{
tempUser.FacebookDetail = user.FacebookDetail;
tempUser.FacebookDetail.AppUserId = user.AppUserId;
}
tempUser.UserName = user.UserName;
tempUser.ReturnUrl = user.ReturnUrl;
tempUser.Activated = user.Activated;
user = tempUser;
//user.AppUserId = tempUser.AppUserId;
}
}
if (user.IsProvidedBy(Provider.Twitter))
{
TwitterUserDetailDapperRepository TwitterUserDetailRepository = new TwitterUserDetailDapperRepository();
var TwitterDetails = TwitterUserDetailRepository.Select(new { TwitterUserId = user.TwitterDetail.TwitterUserId });
if (TwitterDetails.Any())
{
var tempUser = Select(DephtLevel.Friends, new { AppUserId = TwitterDetails.SingleOrDefault().AppUserId }).SingleOrDefault();
tempUser.ExternalLogins.AddRange(user.ExternalLogins);
if (tempUser.TwitterDetail != null)
{
user.TwitterDetail.TwitterUserDetailId = tempUser.TwitterDetail.TwitterUserDetailId;
user.TwitterDetail.AppUserId = tempUser.TwitterDetail.AppUserId;
tempUser.TwitterDetail = user.TwitterDetail;
}
else
{
tempUser.TwitterDetail = user.TwitterDetail;
tempUser.TwitterDetail.AppUserId = user.AppUserId;
}
tempUser.UserName = user.UserName;
tempUser.ReturnUrl = user.ReturnUrl;
tempUser.Activated = user.Activated;
user = tempUser;
//user.AppUserId = tempUser.AppUserId;
}
}
}
Save(DephtLevel.Friends, user);
});
}
public Task DeleteAsync(AppUser user)
{
if (user == null)
throw new ArgumentNullException("user");
return Task.Factory.StartNew(() =>
{
Delete(user);
});
}
public Task<AppUser> FindByIdAsync(string userId)
{
if (string.IsNullOrWhiteSpace(userId))
throw new ArgumentNullException("userId");
return Task.Factory.StartNew(() =>
{
return Select(DephtLevel.UserBasic, new { AppUserId = userId }).SingleOrDefault();
});
}
public Task<AppUser> FindByNameAsync(string userName)
{
if (string.IsNullOrWhiteSpace(userName))
throw new ArgumentNullException("userName");
return Task.Factory.StartNew(() =>
{
return Select(DephtLevel.UserBasic, new { UserName = userName }).SingleOrDefault();
});
}
public Task UpdateAsync(AppUser user)
{
if (user == null)
throw new ArgumentNullException("user");
return Task.Factory.StartNew(() =>
{
Save(DephtLevel.Friends, user);
});
}
#endregion
#region IUserLoginStore Implementation
public Task AddLoginAsync(AppUser user, UserLoginInfo login)
{
if (user == null)
throw new ArgumentNullException("user");
if (login == null)
throw new ArgumentNullException("login");
return Task.Factory.StartNew(() =>
{
ExternalLoginDapperRepository ExternalLoginRepository = new ExternalLoginDapperRepository();
var loginInfo = new ExternalLogin
{
AppUserId = user.AppUserId,
LoginProvider = login.LoginProvider,
ProviderKey = login.ProviderKey
};
ExternalLoginRepository.Insert(loginInfo);
if (user.IsProvidedBy(Provider.Facebook))
{
IFacebookUserDetailRepository FacebookDetailRepository = new FacebookUserDetailDapperRepository();
FacebookDetailRepository.Insert(user.FacebookDetail);
}
if (user.IsProvidedBy(Provider.Twitter))
{
ITwitterUserDetailRepository TwitterDetailRepository = new TwitterUserDetailDapperRepository();
TwitterDetailRepository.Insert(user.TwitterDetail);
}
});
}
public Task<AppUser> FindAsync(UserLoginInfo login)
{
if (login == null)
throw new ArgumentNullException("login");
return Task.Factory.StartNew(() =>
{
ExternalLoginDapperRepository ExternalLoginRepository = new ExternalLoginDapperRepository();
var loginInfos = ExternalLoginRepository.Select(new { LoginProvider = login.LoginProvider, ProviderKey = login.ProviderKey });
if (loginInfos.Any())
return Select(DephtLevel.UserBasic, new { AppUserId = loginInfos.SingleOrDefault().AppUserId }).SingleOrDefault();
return null;
});
}
public Task<IList<UserLoginInfo>> GetLoginsAsync(AppUser user)
{
if (user == null)
throw new ArgumentNullException("user");
return Task.Factory.StartNew(() =>
{
ExternalLoginDapperRepository ExternalLoginRepository = new ExternalLoginDapperRepository();
return (IList<UserLoginInfo>)ExternalLoginRepository.Select(new { AppUserId = user.AppUserId }).Select(p => new UserLoginInfo(p.LoginProvider, p.ProviderKey));
});
}
public Task RemoveLoginAsync(AppUser user, UserLoginInfo login)
{
if (user == null)
throw new ArgumentNullException("user");
if (login == null)
throw new ArgumentNullException("login");
return Task.Factory.StartNew(() =>
{
ExternalLoginDapperRepository ExternalLoginRepository = new ExternalLoginDapperRepository();
ExternalLoginRepository.Delete(ExternalLoginRepository.Select(new { AppUserId = user.AppUserId, LoginProvider = login.LoginProvider, ProviderKey = login.ProviderKey }).SingleOrDefault());
});
}
#endregion
#region IUserPasswordStore
public Task<string> GetPasswordHashAsync(AppUser user)
{
if (user == null)
throw new ArgumentNullException("user");
return Task.FromResult(user.PasswordHash);
}
public Task<bool> HasPasswordAsync(AppUser user)
{
return Task.FromResult(!string.IsNullOrEmpty(user.PasswordHash));
}
public Task SetPasswordHashAsync(AppUser user, string passwordHash)
{
if (user == null)
throw new ArgumentNullException("user");
user.PasswordHash = passwordHash;
return Task.FromResult(0);
}
#endregion
#region IUserSecurityStampStore
public Task<string> GetSecurityStampAsync(AppUser user)
{
if (user == null)
throw new ArgumentNullException("user");
return Task.FromResult(user.SecurityStamp);
}
public Task SetSecurityStampAsync(AppUser user, string stamp)
{
if (user == null)
throw new ArgumentNullException("user");
user.SecurityStamp = stamp;
return Task.FromResult(0);
}
#endregion
// Public implementation of Dispose pattern callable by consumers.
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
// Protected implementation of Dispose pattern.
protected virtual void Dispose(bool disposing)
{
if (disposed)
return;
if (disposing)
{
// Free any other managed objects here.
//
}
// Free any unmanaged objects here.
//
disposed = true;
}
~UserDapperRepository()
{
Dispose(false);
}
#region IUserEmailStore implementation
public Task<AppUser> FindByEmailAsync(string email)
{
if (string.IsNullOrWhiteSpace(email))
throw new ArgumentNullException("email");
return Task.Factory.StartNew(() =>
{
return Select(DephtLevel.UserBasic, new { EmailAddress = email }).SingleOrDefault();
});
}
public Task<string> GetEmailAsync(AppUser user)
{
if (user == null)
throw new ArgumentNullException("user");
return Task.FromResult(user.EmailAddress);
}
public Task<bool> GetEmailConfirmedAsync(AppUser user)
{
if (user == null)
throw new ArgumentNullException("user");
//not implemented yet
return Task.FromResult(true);
}
public Task SetEmailAsync(AppUser user, string email)
{
if (user == null)
throw new ArgumentNullException("user");
user.EmailAddress = email;
return Task.FromResult(0);
}
public Task SetEmailConfirmedAsync(AppUser user, bool confirmed)
{
//not implemented yet
return Task.FromResult(0);
}
#endregion
#region IUserLockoutStore implementation
public Task<int> GetAccessFailedCountAsync(AppUser user)
{
//not implemented yet
return Task.FromResult(0);
}
public Task<bool> GetLockoutEnabledAsync(AppUser user)
{
//not implemented yet
return Task.FromResult(false);
}
public Task<DateTimeOffset> GetLockoutEndDateAsync(AppUser user)
{
//not implemented yet
return Task.FromResult(DateTimeOffset.Now);
}
public Task<int> IncrementAccessFailedCountAsync(AppUser user)
{
//not implemented yet
return Task.FromResult(0);
}
public Task ResetAccessFailedCountAsync(AppUser user)
{
//not implemented yet
return Task.FromResult(0);
}
public Task SetLockoutEnabledAsync(AppUser user, bool enabled)
{
//not implemented yet
return Task.FromResult(0);
}
public Task SetLockoutEndDateAsync(AppUser user, DateTimeOffset lockoutEnd)
{
//not implemented yet
return Task.FromResult(0);
}
#endregion
#region IUserTwoFactorStore implementation
public Task<bool> GetTwoFactorEnabledAsync(AppUser user)
{
//not implemented yet
return Task.FromResult(false);
}
public Task SetTwoFactorEnabledAsync(AppUser user, bool enabled)
{
//not implemented yet
return Task.FromResult(0);
}
#endregion
}
}
| 40.724294 | 216 | 0.513138 | [
"MIT"
] | pyDez/SocialFootprintAPI | Data/iRocks.DataLayer/DapperRepositories/UserDapperRepository.cs | 36,046 | C# |
// <copyright file="Milu0.cs" company="Math.NET">
// Math.NET Numerics, part of the Math.NET Project
// http://numerics.mathdotnet.com
// http://github.com/mathnet/mathnet-numerics
//
// Copyright (c) 2009-2013 Math.NET
//
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the "Software"), to deal in the Software without
// restriction, including without limitation the rights to use,
// copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following
// conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
// OTHER DEALINGS IN THE SOFTWARE.
// </copyright>
using System;
using MathNet.Numerics.LinearAlgebra.Solvers;
using MathNet.Numerics.LinearAlgebra.Storage;
using MathNet.Numerics.Properties;
namespace MathNet.Numerics.LinearAlgebra.Double.Solvers
{
/// <summary>
/// A simple milu(0) preconditioner.
/// </summary>
/// <remarks>
/// Original Fortran code by Yousef Saad (07 January 2004)
/// </remarks>
public sealed class MILU0Preconditioner : IPreconditioner<double>
{
// Matrix stored in Modified Sparse Row (MSR) format containing the L and U
// factors together.
// The diagonal (stored in alu(0:n-1) ) is inverted. Each i-th row of the matrix
// contains the i-th row of L (excluding the diagonal entry = 1) followed by
// the i-th row of U.
private double[] _alu;
// The row pointers (stored in jlu(0:n) ) and column indices to off-diagonal elements.
private int[] _jlu;
// Pointer to the diagonal elements in MSR storage (for faster LU solving).
private int[] _diag;
/// <param name="modified">Use modified or standard ILU(0)</param>
public MILU0Preconditioner(bool modified = true)
{
UseModified = modified;
}
/// <summary>
/// Gets or sets a value indicating whether to use modified or standard ILU(0).
/// </summary>
public bool UseModified { get; set; }
/// <summary>
/// Gets a value indicating whether the preconditioner is initialized.
/// </summary>
public bool IsInitialized { get; private set; }
/// <summary>
/// Initializes the preconditioner and loads the internal data structures.
/// </summary>
/// <param name="matrix">The matrix upon which the preconditioner is based. </param>
/// <exception cref="ArgumentNullException">If <paramref name="matrix"/> is <see langword="null" />.</exception>
/// <exception cref="ArgumentException">If <paramref name="matrix"/> is not a square or is not an
/// instance of SparseCompressedRowMatrixStorage.</exception>
public void Initialize(Matrix<double> matrix)
{
var csr = matrix.Storage as SparseCompressedRowMatrixStorage<double>;
if (csr == null)
{
throw new ArgumentException(Resources.MatrixMustBeSparse, nameof(matrix));
}
// Dimension of matrix
int n = csr.RowCount;
if (n != csr.ColumnCount)
{
throw new ArgumentException(Resources.ArgumentMatrixSquare, nameof(matrix));
}
// Original matrix compressed sparse row storage.
double[] a = csr.Values;
int[] ja = csr.ColumnIndices;
int[] ia = csr.RowPointers;
_alu = new double[ia[n] + 1];
_jlu = new int[ia[n] + 1];
_diag = new int[n];
int code = Compute(n, a, ja, ia, _alu, _jlu, _diag, UseModified);
if (code > -1)
{
throw new NumericalBreakdownException("Zero pivot encountered on row " + code + " during ILU process");
}
IsInitialized = true;
}
/// <summary>
/// Approximates the solution to the matrix equation <b>Ax = b</b>.
/// </summary>
/// <param name="input">The right hand side vector b.</param>
/// <param name="result">The left hand side vector x.</param>
public void Approximate(Vector<double> input, Vector<double> result)
{
if (_alu == null)
{
throw new ArgumentException(Resources.ArgumentMatrixDoesNotExist);
}
if ((result.Count != input.Count) || (result.Count != _diag.Length))
{
throw new ArgumentException(Resources.ArgumentVectorsSameLength);
}
int n = _diag.Length;
// Forward solve.
for (int i = 0; i < n; i++)
{
result[i] = input[i];
for (int k = _jlu[i]; k < _diag[i]; k++)
{
result[i] = result[i] - _alu[k] * result[_jlu[k]];
}
}
// Backward solve.
for (int i = n - 1; i >= 0; i--)
{
for (int k = _diag[i]; k < _jlu[i + 1]; k++)
{
result[i] = result[i] - _alu[k] * result[_jlu[k]];
}
result[i] = _alu[i] * result[i];
}
}
/// <summary>
/// MILU0 is a simple milu(0) preconditioner.
/// </summary>
/// <param name="n">Order of the matrix.</param>
/// <param name="a">Matrix values in CSR format (input).</param>
/// <param name="ja">Column indices (input).</param>
/// <param name="ia">Row pointers (input).</param>
/// <param name="alu">Matrix values in MSR format (output).</param>
/// <param name="jlu">Row pointers and column indices (output).</param>
/// <param name="ju">Pointer to diagonal elements (output).</param>
/// <param name="modified">True if the modified/MILU algorithm should be used (recommended)</param>
/// <returns>Returns 0 on success or k > 0 if a zero pivot was encountered at step k.</returns>
private int Compute(int n, double[] a, int[] ja, int[] ia, double[] alu, int[] jlu, int[] ju, bool modified)
{
var iw = new int[n];
int i;
// Set initial pointer value.
int p = n + 1;
jlu[0] = p;
// Initialize work vector.
for (i = 0; i < n; i++)
{
iw[i] = -1;
}
// The main loop.
for (i = 0; i < n; i++)
{
int pold = p;
// Generating row i of L and U.
int j;
for (j = ia[i]; j < ia[i + 1]; j++)
{
// Copy row i of A, JA, IA into row i of ALU, JLU (LU matrix).
int jcol = ja[j];
if (jcol == i)
{
alu[i] = a[j];
iw[jcol] = i;
ju[i] = p;
}
else
{
alu[p] = a[j];
jlu[p] = ja[j];
iw[jcol] = p;
p = p + 1;
}
}
jlu[i + 1] = p;
double s = 0.0;
int k;
for (j = pold; j < ju[i]; j++)
{
int jrow = jlu[j];
double tl = alu[j] * alu[jrow];
alu[j] = tl;
// Perform linear combination.
for (k = ju[jrow]; k < jlu[jrow + 1]; k++)
{
int jw = iw[jlu[k]];
if (jw != -1)
{
alu[jw] = alu[jw] - tl * alu[k];
}
else
{
// Accumulate fill-in values.
s = s + tl * alu[k];
}
}
}
if (modified)
{
alu[i] = alu[i] - s;
}
if (alu[i] == 0.0)
{
return i;
}
// Invert and store diagonal element.
alu[i] = 1.0 / alu[i];
// Reset pointers in work array.
iw[i] = -1;
for (k = pold; k < p; k++)
{
iw[jlu[k]] = -1;
}
}
return -1;
}
}
}
| 35.624521 | 120 | 0.491826 | [
"MIT"
] | AlexHild/mathnet-numerics | src/Numerics/LinearAlgebra/Double/Solvers/MILU0Preconditioner.cs | 9,300 | C# |
using Kloc.Common.Excepting;
using System;
using System.Collections.Generic;
namespace Kloc.Common.Domain
{
/// <summary>
/// Base class for an <see cref="IAggregateRoot"/> implementation.
/// </summary>
public abstract class AggregateRootBase : AggregateRootBase<Guid>, IAggregateRoot<Guid>
{
private readonly HashSet<IDomainEvent> domainEvents = new HashSet<IDomainEvent>();
/// <summary>
///
/// </summary>
/// <param name="id"></param>
protected AggregateRootBase(Guid id) : base(id)
{
Guard.ForDefault(id, nameof(id));
}
/// <summary>
/// Compares this entity to another.
/// </summary>
/// <param name="obj">The entity to compare.</param>
/// <returns>True if both references or keys are equal.</returns>
public override bool Equals(object obj)
{
var other = obj as AggregateRootBase;
if (other is null)
return false;
if (ReferenceEquals(this, other))
return true;
if (GetType() != other.GetType())
return false;
return Id.Equals(other.Id);
}
/// <summary>
/// Compares two entities.
/// </summary>
/// <param name="a">The first entity to compare.</param>
/// <param name="b">The second entity to compare.</param>
/// <returns>True if equal.</returns>
public static bool operator ==(AggregateRootBase a, AggregateRootBase b)
{
if (a is null && b is null)
return true;
if (a is null || b is null)
return false;
return a.Equals(b);
}
/// <summary>
/// Compares two entities.
/// </summary>
/// <param name="a">The first entity to compare.</param>
/// <param name="b">The second entity to compare.</param>
/// <returns>True if not equal.</returns>
public static bool operator !=(AggregateRootBase a, AggregateRootBase b)
{
return !(a == b);
}
/// <summary>
/// Gets the hash code for the entity.
/// </summary>
/// <returns>The hash code.</returns>
public override int GetHashCode()
{
return (GetType().ToString() + Id.ToString()).GetHashCode();
}
}
}
| 29.670732 | 91 | 0.531032 | [
"MIT"
] | xKloc/Common | Domain/AggregateRootBase.cs | 2,435 | C# |
// Lucene version compatibility level 4.8.1
using Lucene.Net.Analysis.Core;
using Lucene.Net.Analysis.Miscellaneous;
using Lucene.Net.Analysis.Standard;
using Lucene.Net.Analysis.Util;
using Lucene.Net.Util;
using System;
using System.IO;
namespace Lucene.Net.Analysis.Bg
{
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/// <summary>
/// <see cref="Analyzer"/> for Bulgarian.
/// <para>
/// This analyzer implements light-stemming as specified by: <i> Searching
/// Strategies for the Bulgarian Language </i>
/// http://members.unine.ch/jacques.savoy/Papers/BUIR.pdf
/// </para>
/// </summary>
public sealed class BulgarianAnalyzer : StopwordAnalyzerBase
{
/// <summary>
/// File containing default Bulgarian stopwords.
///
/// Default stopword list is from
/// http://members.unine.ch/jacques.savoy/clef/index.html The stopword list is
/// BSD-Licensed.
/// </summary>
public const string DEFAULT_STOPWORD_FILE = "stopwords.txt";
/// <summary>
/// Returns an unmodifiable instance of the default stop-words set.
/// </summary>
/// <returns> an unmodifiable instance of the default stop-words set. </returns>
public static CharArraySet DefaultStopSet => DefaultSetHolder.DEFAULT_STOP_SET;
/// <summary>
/// Atomically loads the DEFAULT_STOP_SET in a lazy fashion once the outer
/// class accesses the static final set the first time.;
/// </summary>
private class DefaultSetHolder
{
internal static readonly CharArraySet DEFAULT_STOP_SET = LoadDefaultStopSet();
private static CharArraySet LoadDefaultStopSet() // LUCENENET: Avoid static constructors (see https://github.com/apache/lucenenet/pull/224#issuecomment-469284006)
{
try
{
return LoadStopwordSet(false, typeof(BulgarianAnalyzer), DEFAULT_STOPWORD_FILE, "#");
}
catch (Exception ex) when (ex.IsIOException())
{
// default set should always be present as it is part of the
// distribution (JAR)
throw RuntimeException.Create("Unable to load default stopword set", ex);
}
}
}
private readonly CharArraySet stemExclusionSet;
/// <summary>
/// Builds an analyzer with the default stop words:
/// <see cref="DEFAULT_STOPWORD_FILE"/>.
/// </summary>
public BulgarianAnalyzer(LuceneVersion matchVersion)
: this(matchVersion, DefaultSetHolder.DEFAULT_STOP_SET)
{
}
/// <summary>
/// Builds an analyzer with the given stop words.
/// </summary>
public BulgarianAnalyzer(LuceneVersion matchVersion, CharArraySet stopwords)
: this(matchVersion, stopwords, CharArraySet.EMPTY_SET)
{
}
/// <summary>
/// Builds an analyzer with the given stop words and a stem exclusion set.
/// If a stem exclusion set is provided this analyzer will add a <see cref="SetKeywordMarkerFilter"/>
/// before <see cref="BulgarianStemFilter"/>.
/// </summary>
public BulgarianAnalyzer(LuceneVersion matchVersion, CharArraySet stopwords, CharArraySet stemExclusionSet)
: base(matchVersion, stopwords)
{
this.stemExclusionSet = CharArraySet.UnmodifiableSet(CharArraySet.Copy(matchVersion, stemExclusionSet));
}
/// <summary>
/// Creates a
/// <see cref="TokenStreamComponents"/>
/// which tokenizes all the text in the provided <see cref="TextReader"/>.
/// </summary>
/// <returns> A
/// <see cref="TokenStreamComponents"/>
/// built from an <see cref="StandardTokenizer"/> filtered with
/// <see cref="StandardFilter"/>, <see cref="LowerCaseFilter"/>, <see cref="StopFilter"/>,
/// <see cref="SetKeywordMarkerFilter"/> if a stem exclusion set is
/// provided and <see cref="BulgarianStemFilter"/>. </returns>
protected internal override TokenStreamComponents CreateComponents(string fieldName, TextReader reader)
{
Tokenizer source = new StandardTokenizer(m_matchVersion, reader);
TokenStream result = new StandardFilter(m_matchVersion, source);
result = new LowerCaseFilter(m_matchVersion, result);
result = new StopFilter(m_matchVersion, result, m_stopwords);
if (stemExclusionSet.Count > 0)
{
result = new SetKeywordMarkerFilter(result, stemExclusionSet);
}
result = new BulgarianStemFilter(result);
return new TokenStreamComponents(source, result);
}
}
} | 43.560606 | 174 | 0.627304 | [
"Apache-2.0"
] | 10088/lucenenet | src/Lucene.Net.Analysis.Common/Analysis/Bg/BulgarianAnalyzer.cs | 5,752 | C# |
using System;
using System.Collections.Generic;
using System.IO;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using Terraria;
using Terraria.ID;
using Terraria.Localization;
using Terraria.ModLoader;
using Terraria.Utilities;
namespace HavenMod.Items.Consumables
{
public class KnightCrest: ModItem
{
public override void SetStaticDefaults()
{
DisplayName.SetDefault("Knight's Crest");
Tooltip.SetDefault("Summons Kingsbane");
}
public override void SetDefaults()
{
item.width = 30;
item.height = 58;
item.maxStack = 20;
item.value = 100;
item.rare = 1;
item.useAnimation = 40;
item.useTime = 45;
item.consumable = true;
item.useStyle = 4;
}
public override bool CanUseItem(Player player)
{
return !NPC.AnyNPCs(mod.NPCType("Kingsbane"));
}
public override bool UseItem(Player player)
{
NPC.SpawnOnPlayer(player.whoAmI, mod.NPCType("Kingsbane"));
Main.PlaySound(SoundID.Roar, player.position, 0);
return true;
}
public override void AddRecipes()
{
ModRecipe recipe = new ModRecipe(mod);
recipe.AddIngredient(ItemID.GoldBroadsword);
recipe.AddIngredient(ItemID.Bone, 50);
recipe.AddIngredient(ItemID.HellstoneBar, 15);
recipe.SetResult(this);
recipe.AddTile(TileID.Anvils);
recipe.AddRecipe();
recipe = new ModRecipe(mod);
recipe.AddIngredient(ItemID.PlatinumBroadsword);
recipe.AddIngredient(ItemID.Bone, 50);
recipe.AddIngredient(ItemID.HellstoneBar, 15);
recipe.SetResult(this);
recipe.AddTile(TileID.Anvils);
recipe.AddRecipe();
}
}
} | 27.828571 | 71 | 0.589836 | [
"MIT"
] | Fortanono/HavenMod | Items/Consumables/KnightCrest.cs | 1,948 | C# |
using UIKit;
namespace ChipmunkDemo.iOS
{
public class Application
{
// This is the main entry point of the application.
private static void Main(string[] args)
{
// if you want to use a different Application Delegate class from "AppDelegate"
// you can specify it here.
UIApplication.Main(args, null, typeof(AppDelegate));
}
}
} | 27.4 | 91 | 0.608273 | [
"MIT"
] | codefoco/ChipmunkBinding | ChipmunkDemo.iOS/Main.cs | 413 | 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("AWSSDK.CloudFront")]
[assembly: AssemblyDescription("The Amazon Web Services SDK for .NET (3.5) - Amazon CloudFront. Amazon CloudFront is a content delivery web service. It integrates with other Amazon Web Services products to give developers and businesses an easy way to distribute content to end users with low latency, high data transfer speeds, and no minimum usage commitments.")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyProduct("Amazon Web Services SDK for .NET")]
[assembly: AssemblyCompany("Amazon.com, Inc")]
[assembly: AssemblyCopyright("Copyright 2009-2020 Amazon.com, Inc. or its affiliates. All Rights Reserved.")]
[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)]
// 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("3.3.4.0")]
[assembly: AssemblyFileVersion("3.3.101.89")] | 51.40625 | 365 | 0.758055 | [
"Apache-2.0"
] | tmlife485/myawskendra | sdk/code-analysis/ServiceAnalysis/CloudFront/Properties/AssemblyInfo.cs | 1,645 | C# |
using System;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Localization;
using Newtonsoft.Json.Linq;
using OrchardCore.ContentManagement;
using OrchardCore.ContentManagement.Display;
using OrchardCore.ContentManagement.Metadata;
using OrchardCore.ContentManagement.Metadata.Settings;
using OrchardCore.DisplayManagement.ModelBinding;
using OrchardCore.DisplayManagement.Notify;
using OrchardCore.Taxonomies.Models;
using YesSql;
namespace OrchardCore.Taxonomies.Controllers
{
public class AdminController : Controller
{
private readonly IContentManager _contentManager;
private readonly IAuthorizationService _authorizationService;
private readonly IContentItemDisplayManager _contentItemDisplayManager;
private readonly IContentDefinitionManager _contentDefinitionManager;
private readonly ISession _session;
private readonly IHtmlLocalizer H;
private readonly INotifier _notifier;
private readonly IUpdateModelAccessor _updateModelAccessor;
public AdminController(
ISession session,
IContentManager contentManager,
IAuthorizationService authorizationService,
IContentItemDisplayManager contentItemDisplayManager,
IContentDefinitionManager contentDefinitionManager,
INotifier notifier,
IHtmlLocalizer<AdminController> localizer,
IUpdateModelAccessor updateModelAccessor)
{
_contentManager = contentManager;
_authorizationService = authorizationService;
_contentItemDisplayManager = contentItemDisplayManager;
_contentDefinitionManager = contentDefinitionManager;
_session = session;
_notifier = notifier;
_updateModelAccessor = updateModelAccessor;
H = localizer;
}
public async Task<IActionResult> Create(string id, string taxonomyContentItemId, string taxonomyItemId)
{
if (String.IsNullOrWhiteSpace(id))
{
return NotFound();
}
if (!await _authorizationService.AuthorizeAsync(User, Permissions.ManageTaxonomies))
{
return Forbid();
}
var contentItem = await _contentManager.NewAsync(id);
contentItem.Weld<TermPart>();
contentItem.Alter<TermPart>(t => t.TaxonomyContentItemId = taxonomyContentItemId);
dynamic model = await _contentItemDisplayManager.BuildEditorAsync(contentItem, _updateModelAccessor.ModelUpdater, true);
model.TaxonomyContentItemId = taxonomyContentItemId;
model.TaxonomyItemId = taxonomyItemId;
return View(model);
}
[HttpPost]
[ActionName("Create")]
public async Task<IActionResult> CreatePost(string id, string taxonomyContentItemId, string taxonomyItemId)
{
if (!await _authorizationService.AuthorizeAsync(User, Permissions.ManageTaxonomies))
{
return Forbid();
}
ContentItem taxonomy;
var contentTypeDefinition = _contentDefinitionManager.GetTypeDefinition("Taxonomy");
if (!contentTypeDefinition.GetSettings<ContentTypeSettings>().Draftable)
{
taxonomy = await _contentManager.GetAsync(taxonomyContentItemId, VersionOptions.Latest);
}
else
{
taxonomy = await _contentManager.GetAsync(taxonomyContentItemId, VersionOptions.DraftRequired);
}
if (taxonomy == null)
{
return NotFound();
}
var contentItem = await _contentManager.NewAsync(id);
contentItem.Weld<TermPart>();
contentItem.Alter<TermPart>(t => t.TaxonomyContentItemId = taxonomyContentItemId);
dynamic model = await _contentItemDisplayManager.UpdateEditorAsync(contentItem, _updateModelAccessor.ModelUpdater, true);
if (!ModelState.IsValid)
{
model.TaxonomyContentItemId = taxonomyContentItemId;
model.TaxonomyItemId = taxonomyItemId;
return View(model);
}
if (taxonomyItemId == null)
{
// Use the taxonomy as the parent if no target is specified
taxonomy.Alter<TaxonomyPart>(part => part.Terms.Add(contentItem));
}
else
{
// Look for the target taxonomy item in the hierarchy
var parentTaxonomyItem = FindTaxonomyItem(taxonomy.As<TaxonomyPart>().Content, taxonomyItemId);
// Couldn't find targeted taxonomy item
if (parentTaxonomyItem == null)
{
return NotFound();
}
var taxonomyItems = parentTaxonomyItem?.Terms as JArray;
if (taxonomyItems == null)
{
parentTaxonomyItem["Terms"] = taxonomyItems = new JArray();
}
taxonomyItems.Add(JObject.FromObject(contentItem));
}
_session.Save(taxonomy);
return RedirectToAction(nameof(Edit), "Admin", new { area = "OrchardCore.Contents", contentItemId = taxonomyContentItemId });
}
public async Task<IActionResult> Edit(string taxonomyContentItemId, string taxonomyItemId)
{
var taxonomy = await _contentManager.GetAsync(taxonomyContentItemId, VersionOptions.Latest);
if (taxonomy == null)
{
return NotFound();
}
if (!await _authorizationService.AuthorizeAsync(User, Permissions.ManageTaxonomies, taxonomy))
{
return Forbid();
}
// Look for the target taxonomy item in the hierarchy
JObject taxonomyItem = FindTaxonomyItem(taxonomy.As<TaxonomyPart>().Content, taxonomyItemId);
// Couldn't find targeted taxonomy item
if (taxonomyItem == null)
{
return NotFound();
}
var contentItem = taxonomyItem.ToObject<ContentItem>();
contentItem.Weld<TermPart>();
contentItem.Alter<TermPart>(t => t.TaxonomyContentItemId = taxonomyContentItemId);
dynamic model = await _contentItemDisplayManager.BuildEditorAsync(contentItem, _updateModelAccessor.ModelUpdater, false);
model.TaxonomyContentItemId = taxonomyContentItemId;
model.TaxonomyItemId = taxonomyItemId;
return View(model);
}
[HttpPost]
[ActionName("Edit")]
public async Task<IActionResult> EditPost(string taxonomyContentItemId, string taxonomyItemId)
{
if (!await _authorizationService.AuthorizeAsync(User, Permissions.ManageTaxonomies))
{
return Forbid();
}
ContentItem taxonomy;
var contentTypeDefinition = _contentDefinitionManager.GetTypeDefinition("Taxonomy");
if (!contentTypeDefinition.GetSettings<ContentTypeSettings>().Draftable)
{
taxonomy = await _contentManager.GetAsync(taxonomyContentItemId, VersionOptions.Latest);
}
else
{
taxonomy = await _contentManager.GetAsync(taxonomyContentItemId, VersionOptions.DraftRequired);
}
if (taxonomy == null)
{
return NotFound();
}
// Look for the target taxonomy item in the hierarchy
JObject taxonomyItem = FindTaxonomyItem(taxonomy.As<TaxonomyPart>().Content, taxonomyItemId);
// Couldn't find targeted taxonomy item
if (taxonomyItem == null)
{
return NotFound();
}
var existing = taxonomyItem.ToObject<ContentItem>();
// Create a new item to take into account the current type definition.
var contentItem = await _contentManager.NewAsync(existing.ContentType);
contentItem.ContentItemId = existing.ContentItemId;
contentItem.Merge(existing);
contentItem.Weld<TermPart>();
contentItem.Alter<TermPart>(t => t.TaxonomyContentItemId = taxonomyContentItemId);
dynamic model = await _contentItemDisplayManager.UpdateEditorAsync(contentItem, _updateModelAccessor.ModelUpdater, false);
if (!ModelState.IsValid)
{
model.TaxonomyContentItemId = taxonomyContentItemId;
model.TaxonomyItemId = taxonomyItemId;
return View(model);
}
taxonomyItem.Merge(contentItem.Content, new JsonMergeSettings
{
MergeArrayHandling = MergeArrayHandling.Replace,
MergeNullValueHandling = MergeNullValueHandling.Merge
});
// Merge doesn't copy the properties
taxonomyItem[nameof(ContentItem.DisplayText)] = contentItem.DisplayText;
_session.Save(taxonomy);
return RedirectToAction(nameof(Edit), "Admin", new { area = "OrchardCore.Contents", contentItemId = taxonomyContentItemId });
}
[HttpPost]
public async Task<IActionResult> Delete(string taxonomyContentItemId, string taxonomyItemId)
{
if (!await _authorizationService.AuthorizeAsync(User, Permissions.ManageTaxonomies))
{
return Forbid();
}
ContentItem taxonomy;
var contentTypeDefinition = _contentDefinitionManager.GetTypeDefinition("Taxonomy");
if (!contentTypeDefinition.GetSettings<ContentTypeSettings>().Draftable)
{
taxonomy = await _contentManager.GetAsync(taxonomyContentItemId, VersionOptions.Latest);
}
else
{
taxonomy = await _contentManager.GetAsync(taxonomyContentItemId, VersionOptions.DraftRequired);
}
if (taxonomy == null)
{
return NotFound();
}
// Look for the target taxonomy item in the hierarchy
var taxonomyItem = FindTaxonomyItem(taxonomy.As<TaxonomyPart>().Content, taxonomyItemId);
// Couldn't find targeted taxonomy item
if (taxonomyItem == null)
{
return NotFound();
}
taxonomyItem.Remove();
_session.Save(taxonomy);
_notifier.Success(H["Taxonomy item deleted successfully."]);
return RedirectToAction(nameof(Edit), "Admin", new { area = "OrchardCore.Contents", contentItemId = taxonomyContentItemId });
}
private JObject FindTaxonomyItem(JObject contentItem, string taxonomyItemId)
{
if (contentItem["ContentItemId"]?.Value<string>() == taxonomyItemId)
{
return contentItem;
}
if (contentItem.GetValue("Terms") == null)
{
return null;
}
var taxonomyItems = (JArray)contentItem["Terms"];
JObject result;
foreach (JObject taxonomyItem in taxonomyItems)
{
// Search in inner taxonomy items
result = FindTaxonomyItem(taxonomyItem, taxonomyItemId);
if (result != null)
{
return result;
}
}
return null;
}
}
}
| 36.33642 | 137 | 0.61004 | [
"BSD-3-Clause"
] | 861191244/OrchardCore | src/OrchardCore.Modules/OrchardCore.Taxonomies/Controllers/AdminController.cs | 11,773 | C# |
/*
* MailSlurp API
*
* MailSlurp is an API for sending and receiving emails from dynamically allocated email addresses. It's designed for developers and QA teams to test applications, process inbound emails, send templated notifications, attachments, and more. ## Resources - [Homepage](https://www.mailslurp.com) - Get an [API KEY](https://app.mailslurp.com/sign-up/) - Generated [SDK Clients](https://www.mailslurp.com/docs/) - [Examples](https://github.com/mailslurp/examples) repository
*
* The version of the OpenAPI document: 6.5.2
* Contact: contact@mailslurp.dev
* Generated by: https://github.com/openapitools/openapi-generator.git
*/
using Xunit;
using System;
using System.Linq;
using System.IO;
using System.Collections.Generic;
using mailslurp_netstandard_2x.Api;
using mailslurp_netstandard_2x.Model;
using mailslurp_netstandard_2x.Client;
using System.Reflection;
using Newtonsoft.Json;
namespace mailslurp_netstandard_2x.Test.Model
{
/// <summary>
/// Class for testing DomainPreview
/// </summary>
/// <remarks>
/// This file is automatically generated by OpenAPI Generator (https://openapi-generator.tech).
/// Please update the test case below to test the model.
/// </remarks>
public class DomainPreviewTests : IDisposable
{
// TODO uncomment below to declare an instance variable for DomainPreview
//private DomainPreview instance;
public DomainPreviewTests()
{
// TODO uncomment below to create an instance of DomainPreview
//instance = new DomainPreview();
}
public void Dispose()
{
// Cleanup when everything is done.
}
/// <summary>
/// Test an instance of DomainPreview
/// </summary>
[Fact]
public void DomainPreviewInstanceTest()
{
// TODO uncomment below to test "IsType" DomainPreview
//Assert.IsType<DomainPreview>(instance);
}
/// <summary>
/// Test the property 'Id'
/// </summary>
[Fact]
public void IdTest()
{
// TODO unit test for the property 'Id'
}
/// <summary>
/// Test the property 'Domain'
/// </summary>
[Fact]
public void DomainTest()
{
// TODO unit test for the property 'Domain'
}
/// <summary>
/// Test the property 'CatchAllInboxId'
/// </summary>
[Fact]
public void CatchAllInboxIdTest()
{
// TODO unit test for the property 'CatchAllInboxId'
}
/// <summary>
/// Test the property 'CreatedAt'
/// </summary>
[Fact]
public void CreatedAtTest()
{
// TODO unit test for the property 'CreatedAt'
}
/// <summary>
/// Test the property 'DomainType'
/// </summary>
[Fact]
public void DomainTypeTest()
{
// TODO unit test for the property 'DomainType'
}
/// <summary>
/// Test the property 'IsVerified'
/// </summary>
[Fact]
public void IsVerifiedTest()
{
// TODO unit test for the property 'IsVerified'
}
}
}
| 29.473214 | 472 | 0.590427 | [
"MIT"
] | mailslurp/mailslurp-client-csharp-netstandard-2x | src/mailslurp_netstandard_2x.Test/Model/DomainPreviewTests.cs | 3,301 | C# |
namespace Microsoft.Azure.PowerShell.Cmdlets.Migrate.Models.Api20180110
{
using static Microsoft.Azure.PowerShell.Cmdlets.Migrate.Runtime.Extensions;
/// <summary>Azure specific reprotect input.</summary>
public partial class HyperVReplicaAzureReprotectInput
{
/// <summary>
/// <c>AfterFromJson</c> will be called after the json deserialization has finished, allowing customization of the object
/// before it is returned. Implement this method in a partial class to enable this behavior
/// </summary>
/// <param name="json">The JsonNode that should be deserialized into this object.</param>
partial void AfterFromJson(Microsoft.Azure.PowerShell.Cmdlets.Migrate.Runtime.Json.JsonObject json);
/// <summary>
/// <c>AfterToJson</c> will be called after the json erialization has finished, allowing customization of the <see cref="Microsoft.Azure.PowerShell.Cmdlets.Migrate.Runtime.Json.JsonObject"
/// /> before it is returned. Implement this method in a partial class to enable this behavior
/// </summary>
/// <param name="container">The JSON container that the serialization result will be placed in.</param>
partial void AfterToJson(ref Microsoft.Azure.PowerShell.Cmdlets.Migrate.Runtime.Json.JsonObject container);
/// <summary>
/// <c>BeforeFromJson</c> will be called before the json deserialization has commenced, allowing complete customization of
/// the object before it is deserialized.
/// If you wish to disable the default deserialization entirely, return <c>true</c> in the <see "returnNow" /> output parameter.
/// Implement this method in a partial class to enable this behavior.
/// </summary>
/// <param name="json">The JsonNode that should be deserialized into this object.</param>
/// <param name="returnNow">Determines if the rest of the deserialization should be processed, or if the method should return
/// instantly.</param>
partial void BeforeFromJson(Microsoft.Azure.PowerShell.Cmdlets.Migrate.Runtime.Json.JsonObject json, ref bool returnNow);
/// <summary>
/// <c>BeforeToJson</c> will be called before the json serialization has commenced, allowing complete customization of the
/// object before it is serialized.
/// If you wish to disable the default serialization entirely, return <c>true</c> in the <see "returnNow" /> output parameter.
/// Implement this method in a partial class to enable this behavior.
/// </summary>
/// <param name="container">The JSON container that the serialization result will be placed in.</param>
/// <param name="returnNow">Determines if the rest of the serialization should be processed, or if the method should return
/// instantly.</param>
partial void BeforeToJson(ref Microsoft.Azure.PowerShell.Cmdlets.Migrate.Runtime.Json.JsonObject container, ref bool returnNow);
/// <summary>
/// Deserializes a <see cref="Microsoft.Azure.PowerShell.Cmdlets.Migrate.Runtime.Json.JsonNode"/> into an instance of Microsoft.Azure.PowerShell.Cmdlets.Migrate.Models.Api20180110.IHyperVReplicaAzureReprotectInput.
/// </summary>
/// <param name="node">a <see cref="Microsoft.Azure.PowerShell.Cmdlets.Migrate.Runtime.Json.JsonNode" /> to deserialize from.</param>
/// <returns>
/// an instance of Microsoft.Azure.PowerShell.Cmdlets.Migrate.Models.Api20180110.IHyperVReplicaAzureReprotectInput.
/// </returns>
public static Microsoft.Azure.PowerShell.Cmdlets.Migrate.Models.Api20180110.IHyperVReplicaAzureReprotectInput FromJson(Microsoft.Azure.PowerShell.Cmdlets.Migrate.Runtime.Json.JsonNode node)
{
return node is Microsoft.Azure.PowerShell.Cmdlets.Migrate.Runtime.Json.JsonObject json ? new HyperVReplicaAzureReprotectInput(json) : null;
}
/// <summary>
/// Deserializes a Microsoft.Azure.PowerShell.Cmdlets.Migrate.Runtime.Json.JsonObject into a new instance of <see cref="HyperVReplicaAzureReprotectInput" />.
/// </summary>
/// <param name="json">A Microsoft.Azure.PowerShell.Cmdlets.Migrate.Runtime.Json.JsonObject instance to deserialize from.</param>
internal HyperVReplicaAzureReprotectInput(Microsoft.Azure.PowerShell.Cmdlets.Migrate.Runtime.Json.JsonObject json)
{
bool returnNow = false;
BeforeFromJson(json, ref returnNow);
if (returnNow)
{
return;
}
__reverseReplicationProviderSpecificInput = new Microsoft.Azure.PowerShell.Cmdlets.Migrate.Models.Api20180110.ReverseReplicationProviderSpecificInput(json);
{_hvHostVMId = If( json?.PropertyT<Microsoft.Azure.PowerShell.Cmdlets.Migrate.Runtime.Json.JsonString>("hvHostVmId"), out var __jsonHvHostVMId) ? (string)__jsonHvHostVMId : (string)HvHostVMId;}
{_logStorageAccountId = If( json?.PropertyT<Microsoft.Azure.PowerShell.Cmdlets.Migrate.Runtime.Json.JsonString>("logStorageAccountId"), out var __jsonLogStorageAccountId) ? (string)__jsonLogStorageAccountId : (string)LogStorageAccountId;}
{_oSType = If( json?.PropertyT<Microsoft.Azure.PowerShell.Cmdlets.Migrate.Runtime.Json.JsonString>("osType"), out var __jsonOSType) ? (string)__jsonOSType : (string)OSType;}
{_storageAccountId = If( json?.PropertyT<Microsoft.Azure.PowerShell.Cmdlets.Migrate.Runtime.Json.JsonString>("storageAccountId"), out var __jsonStorageAccountId) ? (string)__jsonStorageAccountId : (string)StorageAccountId;}
{_vHdId = If( json?.PropertyT<Microsoft.Azure.PowerShell.Cmdlets.Migrate.Runtime.Json.JsonString>("vHDId"), out var __jsonVHdId) ? (string)__jsonVHdId : (string)VHdId;}
{_vMName = If( json?.PropertyT<Microsoft.Azure.PowerShell.Cmdlets.Migrate.Runtime.Json.JsonString>("vmName"), out var __jsonVMName) ? (string)__jsonVMName : (string)VMName;}
AfterFromJson(json);
}
/// <summary>
/// Serializes this instance of <see cref="HyperVReplicaAzureReprotectInput" /> into a <see cref="Microsoft.Azure.PowerShell.Cmdlets.Migrate.Runtime.Json.JsonNode" />.
/// </summary>
/// <param name="container">The <see cref="Microsoft.Azure.PowerShell.Cmdlets.Migrate.Runtime.Json.JsonObject"/> container to serialize this object into. If the caller
/// passes in <c>null</c>, a new instance will be created and returned to the caller.</param>
/// <param name="serializationMode">Allows the caller to choose the depth of the serialization. See <see cref="Microsoft.Azure.PowerShell.Cmdlets.Migrate.Runtime.SerializationMode"/>.</param>
/// <returns>
/// a serialized instance of <see cref="HyperVReplicaAzureReprotectInput" /> as a <see cref="Microsoft.Azure.PowerShell.Cmdlets.Migrate.Runtime.Json.JsonNode" />.
/// </returns>
public Microsoft.Azure.PowerShell.Cmdlets.Migrate.Runtime.Json.JsonNode ToJson(Microsoft.Azure.PowerShell.Cmdlets.Migrate.Runtime.Json.JsonObject container, Microsoft.Azure.PowerShell.Cmdlets.Migrate.Runtime.SerializationMode serializationMode)
{
container = container ?? new Microsoft.Azure.PowerShell.Cmdlets.Migrate.Runtime.Json.JsonObject();
bool returnNow = false;
BeforeToJson(ref container, ref returnNow);
if (returnNow)
{
return container;
}
__reverseReplicationProviderSpecificInput?.ToJson(container, serializationMode);
AddIf( null != (((object)this._hvHostVMId)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.Migrate.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.Migrate.Runtime.Json.JsonString(this._hvHostVMId.ToString()) : null, "hvHostVmId" ,container.Add );
AddIf( null != (((object)this._logStorageAccountId)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.Migrate.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.Migrate.Runtime.Json.JsonString(this._logStorageAccountId.ToString()) : null, "logStorageAccountId" ,container.Add );
AddIf( null != (((object)this._oSType)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.Migrate.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.Migrate.Runtime.Json.JsonString(this._oSType.ToString()) : null, "osType" ,container.Add );
AddIf( null != (((object)this._storageAccountId)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.Migrate.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.Migrate.Runtime.Json.JsonString(this._storageAccountId.ToString()) : null, "storageAccountId" ,container.Add );
AddIf( null != (((object)this._vHdId)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.Migrate.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.Migrate.Runtime.Json.JsonString(this._vHdId.ToString()) : null, "vHDId" ,container.Add );
AddIf( null != (((object)this._vMName)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.Migrate.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.Migrate.Runtime.Json.JsonString(this._vMName.ToString()) : null, "vmName" ,container.Add );
AfterToJson(ref container);
return container;
}
}
} | 84.079646 | 303 | 0.705715 | [
"MIT"
] | Click4PV/azure-powershell | src/Migrate/generated/api/Models/Api20180110/HyperVReplicaAzureReprotectInput.json.cs | 9,389 | C# |
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated from a template.
//
// Manual changes to this file may cause unexpected behavior in your application.
// Manual changes to this file will be overwritten if the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
namespace MarketPlace.ExistingDb
{
using System;
using System.Collections.Generic;
public partial class Shipper
{
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")]
public Shipper()
{
this.ItemProducts = new HashSet<ItemProduct>();
}
public int Id { get; set; }
public string Name { get; set; }
public int AddressId { get; set; }
public int ContactId { get; set; }
public string ImageLink { get; set; }
public string LogoLink { get; set; }
public string Specials { get; set; }
public string FoodSafetyDocumentLink { get; set; }
public bool IsPriceAvailableToPrivateUsers { get; set; }
public string BillingName { get; set; }
public string BillingAddressId { get; set; }
public bool IsDeleted { get; set; }
public string CreatedBy { get; set; }
public System.DateTime CreatedOn { get; set; }
public string LastModifiedBy { get; set; }
public string LastModifiedOn { get; set; }
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
public virtual ICollection<ItemProduct> ItemProducts { get; set; }
}
}
| 40.477273 | 128 | 0.592925 | [
"MIT"
] | patrickCode/EntityFramework | EF6/EF6/MarketPlace.ExistingDb/Shipper.cs | 1,781 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using Benday.EasyAuthDemo.Api.ServiceLayers;
using Benday.EasyAuthDemo.Api.DomainModels;
using Benday.EasyAuthDemo.WebUi.Models;
using Benday.EasyAuthDemo.WebUi.Models.Adapters;
using Microsoft.AspNetCore.Mvc.Rendering;
using Microsoft.Extensions.Logging;
using Benday.Common;
using Benday.EasyAuthDemo.Api;
namespace Benday.EasyAuthDemo.WebUi.Controllers
{
public partial class UserClaimController : MvcControllerBase<UserClaimEditorViewModel>
{
private readonly IValidatorStrategy<UserClaimEditorViewModel> _Validator;
private readonly ILookupService _LookupService;
private readonly IUserClaimService _Service;
private readonly ILogger<UserClaimController> _Logger;
public UserClaimController(
IUserClaimService service,
IValidatorStrategy<UserClaimEditorViewModel> validator,
ILogger<UserClaimController> logger,
ILookupService lookupService)
{
if (service == null)
throw new ArgumentNullException(nameof(service), "service is null.");
if (validator == null)
{
throw new ArgumentNullException(nameof(validator), "Argument cannot be null.");
}
_Validator = validator;
_Logger = logger;
_Service = service;
_LookupService = lookupService;
}
public ActionResult Index()
{
var items = _Service.GetAll();
return View(items);
}
[Route("/[controller]/[action]/{id}")]
public ActionResult Details(int? id)
{
if (id == null || id.HasValue == false)
{
return new BadRequestResult();
}
var item = _Service.GetById(id.Value);
if (item == null)
{
return NotFound();
}
else
{
}
return View(item);
}
public ActionResult Create()
{
return RedirectToAction("Edit", new { id = ApiConstants.UnsavedId });
}
public ActionResult Edit(int? id)
{
if (id == null)
{
return new BadRequestResult();
}
UserClaim item;
UserClaimEditorViewModel viewModel;
if (id.Value == ApiConstants.UnsavedId)
{
// create new
viewModel = new UserClaimEditorViewModel();
PopulateLookups(viewModel);
return View(viewModel);
}
else
{
item = _Service.GetById(id.Value);
if (item == null)
{
return NotFound();
}
else
{
viewModel = new UserClaimEditorViewModel();
var adapter = new UserClaimEditorViewModelAdapter();
adapter.Adapt(item, viewModel);
PopulateLookups(viewModel);
}
}
BeforeReturnFromEdit(id, viewModel);
return View(viewModel);
}
private void PopulateLookups(UserClaimEditorViewModel viewModel)
{
viewModel.ClaimNames = WebUiUtilities.ToSelectListItems(
_LookupService.GetAllByType("System.UserClaim.PermissionTypes"));
viewModel.ClaimLogicTypes = WebUiUtilities.ToSelectListItems(
_LookupService.GetAllByType("System.UserClaim.ClaimLogicTypes"));
viewModel.Statuses = WebUiUtilities.ToSelectListItems(
_LookupService.GetAllByType("System.Lookup.StatusValues"));
}
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Edit(UserClaimEditorViewModel item)
{
if (_Validator.IsValid(item) == true)
{
UserClaim toValue;
if (item.Id == ApiConstants.UnsavedId)
{
toValue = new UserClaim();
}
else
{
toValue =
_Service.GetById(item.Id);
if (toValue == null)
{
return NotFound();
}
}
var adapter = new UserClaimEditorViewModelAdapter();
adapter.Adapt(item, toValue);
_Service.Save(toValue);
return RedirectToAction("Edit", new { id = toValue.Id });
}
else
{
return View(item);
}
}
public ActionResult Search()
{
var viewModel = new UserClaimSearchViewModel();
return View(viewModel);
}
[HttpGet]
public ActionResult Search(UserClaimSearchViewModel item, string pageNumber, string sortBy)
{
if (item == null)
{
return View(new UserClaimSearchViewModel());
}
else if (item.IsSimpleSearch == true)
{
return RunSimpleSearch(item, pageNumber, sortBy);
}
else
{
return RunDetailedSearch(item, pageNumber, sortBy);
}
}
private ActionResult RunDetailedSearch(UserClaimSearchViewModel item, string pageNumber, string sortBy)
{
var sortDirection = GetSortDirection(item, sortBy);
ModelState.Clear();
var results = _Service.Search(
searchValueUsername: item.Username,
searchValueClaimName: item.ClaimName,
searchValueClaimLogicType: item.ClaimLogicType,
searchValueStatus: item.Status,
searchValueCreatedBy: item.CreatedBy,
searchValueLastModifiedBy: item.LastModifiedBy,
sortBy: sortBy, sortByDirection: sortDirection);
var pageableResults = new PageableResults<UserClaim>();
pageableResults.Initialize(results);
pageableResults.CurrentPage = pageNumber.SafeToInt32(0);
item.Results = pageableResults;
item.CurrentSortDirection = sortDirection;
item.CurrentSortProperty = sortBy;
return View(item);
}
private ActionResult RunSimpleSearch(
UserClaimSearchViewModel item, string pageNumber, string sortBy)
{
ModelState.Clear();
string sortDirection;
if (sortBy == null)
{
// the value didn't change because of HTTP POST
sortBy = item.CurrentSortProperty;
sortDirection = item.CurrentSortDirection;
}
else
{
sortDirection = GetSortDirection(item, sortBy);
}
var results = _Service.SimpleSearch(item.SimpleSearchValue,
sortBy, sortDirection);
var pageableResults = new PageableResults<UserClaim>();
pageableResults.Initialize(results);
pageableResults.CurrentPage = pageNumber.SafeToInt32(0);
item.Results = pageableResults;
item.CurrentSortDirection = sortDirection;
item.CurrentSortProperty = sortBy;
return View(item);
}
private string GetSortDirection(ISortableResult viewModel, string sortBy)
{
if (String.IsNullOrWhiteSpace(sortBy) == true)
{
return SearchConstants.SortDirectionAscending;
}
else
{
if (String.Compare(sortBy, viewModel.CurrentSortProperty, true) == 0)
{
if (viewModel.CurrentSortDirection == SearchConstants.SortDirectionAscending)
{
return SearchConstants.SortDirectionDescending;
}
else
{
return SearchConstants.SortDirectionAscending;
}
}
else
{
return SearchConstants.SortDirectionAscending;
}
}
}
public ActionResult Delete(int? id)
{
if (id == null)
{
return new BadRequestResult();
}
UserClaim item;
item = _Service.GetById(id.Value);
if (item == null)
{
return NotFound();
}
return View(item);
}
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Delete(UserClaim item)
{
var deleteThis =
_Service.GetById(item.Id);
if (deleteThis == null)
{
return NotFound();
}
_Service.DeleteById(item.Id);
return RedirectToAction("Index");
}
}
}
| 31.111455 | 111 | 0.492387 | [
"MIT"
] | benday-inc/azure-app-service-security | dotnet5.0/Benday.EasyAuthDemo/src/Benday.EasyAuthDemo.WebUi/Controllers/UserClaimController.generated.cs | 10,049 | C# |
namespace OpenVIII.Fields.Scripts.Instructions
{
internal sealed class CMOVE : JsmInstruction
{
#region Fields
private readonly IJsmExpression _arg0;
private readonly IJsmExpression _arg1;
private readonly IJsmExpression _arg2;
private readonly IJsmExpression _arg3;
#endregion Fields
#region Constructors
public CMOVE(IJsmExpression arg0, IJsmExpression arg1, IJsmExpression arg2, IJsmExpression arg3)
{
_arg0 = arg0;
_arg1 = arg1;
_arg2 = arg2;
_arg3 = arg3;
}
public CMOVE(int parameter, IStack<IJsmExpression> stack)
: this(
arg3: stack.Pop(),
arg2: stack.Pop(),
arg1: stack.Pop(),
arg0: stack.Pop())
{
}
#endregion Constructors
#region Methods
public override string ToString() => $"{nameof(CMOVE)}({nameof(_arg0)}: {_arg0}, {nameof(_arg1)}: {_arg1}, {nameof(_arg2)}: {_arg2}, {nameof(_arg3)}: {_arg3})";
#endregion Methods
}
} | 27.170732 | 168 | 0.568223 | [
"MIT"
] | FlameHorizon/OpenVIII-monogame | Core/Field/JSM/Instructions/CMOVE.cs | 1,116 | C# |
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;
using Microsoft.WindowsAzure.Storage;
using Microsoft.WindowsAzure.Storage.Blob;
using Vt.Platform.Domain.Services;
namespace Vt.Platform.AzureDataTables.BlobStorage
{
public class StaticSiteBlobStorageService : IStaticSiteStorageService
{
static StaticSiteBlobStorageService()
{
BlobClient = CreateClient();
}
public async Task StoreContent(string path, string contentType, byte[] content)
{
path = path.Substring(1, path.Length - 1);
var container = Environment.GetEnvironmentVariable("Blob.WebContainer");
CloudBlobContainer cloudBlobContainer = BlobClient.GetContainerReference(container);
CloudBlockBlob cloudBlockBlob = cloudBlobContainer.GetBlockBlobReference(path.ToLowerInvariant());
cloudBlockBlob.Properties.ContentType = contentType;
await cloudBlockBlob.UploadFromByteArrayAsync(content, 0, content.Length);
}
private static readonly CloudBlobClient BlobClient;
private static CloudBlobClient CreateClient()
{
var connectionString = Environment.GetEnvironmentVariable("TableStorage");
var cloudStorageAccount = CloudStorageAccount.Parse(connectionString);
return cloudStorageAccount.CreateCloudBlobClient();
}
}
}
| 37.921053 | 110 | 0.714781 | [
"MIT"
] | UC-MSIS-WEBDEV/volteer | Vt.Platform.AzureDataTables/BlobStorage/StaticSiteBlobStorageService.cs | 1,443 | C# |
#region License
// FreeBSD License
// Copyright (c) 2010 - 2013, Andrew Trevarrow and Derek Wilson
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
//
// Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
//
// Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED
// WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
// PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
// ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
// TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
// HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
// NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
// POSSIBILITY OF SUCH DAMAGE.
#endregion
using System;
using System.ComponentModel;
using NUnit.Framework;
using Rhino.Mocks;
namespace PodcastUtilities.Common.Tests.Feeds.EpisodeDownloaderTests.WebClientEvent.DownloadFileCompleted
{
public class WhenTheDownloaderReportsANestedError : WhenTestingTheDownloaderCompletedMechanism
{
protected override void When()
{
_webClient.Raise(client => client.DownloadFileCompleted += null, this,
new AsyncCompletedEventArgs(new Exception("OUTER ERROR", _reportedError), false, _syncItem));
}
[Test]
public void ItShouldComplete()
{
Assert.That(_downloader.IsStarted(), Is.True);
Assert.That(_downloader.IsComplete(), Is.True);
}
[Test]
public void ItShouldSendTheCorrectStatus()
{
Assert.That(_statusUpdateArgs.Exception, Is.SameAs(_reportedError));
Assert.That(_statusUpdateArgs.MessageLevel, Is.EqualTo(StatusUpdateLevel.Error));
Assert.That(_statusUpdateArgs.Message, Is.StringContaining("Error in: title")); // error should show the episode title
}
[Test]
public void ItShouldTidyUp()
{
_webClient.AssertWasCalled(client => client.Dispose());
}
}
} | 48.614035 | 206 | 0.708409 | [
"BSD-2-Clause"
] | derekwilson/PodcastUtilities | PodcastUtilities.Common.Tests/Feeds/EpisodeDownloaderTests/WebClientEvent/DownloadFileCompleted/WhenTheDownloaderReportsANestedError.cs | 2,773 | C# |
using System;
using System.Collections.Generic;
using ExBancoDeDados.Repositorio;
using ExBancoDeDados.Utils;
using ExBancoDeDados.ViewModel;
using Spire.Doc;
using Spire.Doc.Documents;
namespace ExBancoDeDados.ViewController {
public class UsuarioViewController {
static UsuarioRepositorio usuarioRepositorio = new UsuarioRepositorio ();
public static void CadastrarUsuario() {
string nome, email, senha;
DateTime dataNascimento;
do {
System.Console.WriteLine("Insira o nome do usuário");
nome = Console.ReadLine();
if (string.IsNullOrEmpty(nome)) {
Console.ForegroundColor = ConsoleColor.Red;
System.Console.WriteLine("Por favor digite seu nome");
Console.ResetColor();
}
} while (string.IsNullOrEmpty(nome));
do {
System.Console.WriteLine("Digite o seu email");
email = Console.ReadLine();
if (!ValidacaoUtil.ValidarEmail(email)) {
Console.ForegroundColor = ConsoleColor.Red;
System.Console.WriteLine("Email inválido, coloque @ e .com");
Console.ResetColor();
}
} while (!ValidacaoUtil.ValidarEmail(email));
do {
System.Console.WriteLine("Digite sua senha");
senha = Console.ReadLine();
if (!ValidacaoUtil.ValidarSenha(senha)) {
Console.ForegroundColor = ConsoleColor.Red;
System.Console.WriteLine("Digite sua senha novamente");
Console.ResetColor();
}
} while (!ValidacaoUtil.ValidarSenha(senha));
System.Console.WriteLine("Insira sua data de nascimento {dd/mm/yyyy}");
dataNascimento = DateTime.Parse(Console.ReadLine());
UsuarioViewModel usuarioViewModel = new UsuarioViewModel ();
usuarioViewModel.Nome = nome;
usuarioViewModel.Email = email;
usuarioViewModel.Senha = senha;
usuarioViewModel.DataNascimento = dataNascimento;
usuarioRepositorio.Inserir(usuarioViewModel);
Console.ForegroundColor = ConsoleColor.Green;
System.Console.WriteLine("Usuário cadastrado com sucesso!");
Console.ResetColor();
}
public static void ListarUsuario(){
List<UsuarioViewModel> listaDeUsuarios = usuarioRepositorio.Listar();
foreach (var item in listaDeUsuarios) {
System.Console.WriteLine($"Id: {item.Id} - Nome do usuário: {item.Nome} - Email: {item.Email} - Data de nascimento: {item.DataNascimento} - Data de Criação: {item.DataCriacao}");
}
}
public static UsuarioViewModel EfetuarLogin() {
string email, senha;
do {
Console.WriteLine("Insira o email");
email = Console.ReadLine();
if (!ValidacaoUtil.ValidarEmail(email)) {
Console.WriteLine("Email Inválido");
}
} while (!ValidacaoUtil.ValidarEmail(email));
do {
Console.WriteLine("Insira a senha do usuário");
senha = Console.ReadLine();
if (!ValidacaoUtil.ValidarSenha(senha)) {
Console.WriteLine("Email Inválido");
}
} while (!ValidacaoUtil.ValidarSenha(senha));
UsuarioViewModel usuarioRecuperado = usuarioRepositorio.BuscarUusuario(email, senha);
if (usuarioRecuperado != null) {
return usuarioRecuperado;
} else {
Console.WriteLine("Email ou senha inválido");
return null;
}
}
}
} | 38.294118 | 194 | 0.56682 | [
"MIT"
] | leozitop/CShar | ExBancoDeDados/ViewController/UsuarioViewController.cs | 3,916 | C# |
using UnityEngine;
namespace Libraries.Standard_Assets.Effects.ImageEffects.Scripts
{
[ExecuteInEditMode]
[RequireComponent(typeof(Camera))]
[AddComponentMenu("Image Effects/Camera/Depth of Field (Lens Blur, Scatter, DX11)")]
public class DepthOfField : PostEffectsBase
{
public bool visualizeFocus = false;
public float focalLength = 10.0f;
public float focalSize = 0.05f;
public float aperture = 0.5f;
public Transform focalTransform = null;
public float maxBlurSize = 2.0f;
public bool highResolution = false;
public enum BlurType
{
DiscBlur = 0,
DX11 = 1,
}
public enum BlurSampleCount
{
Low = 0,
Medium = 1,
High = 2,
}
public BlurType blurType = BlurType.DiscBlur;
public BlurSampleCount blurSampleCount = BlurSampleCount.High;
public bool nearBlur = false;
public float foregroundOverlap = 1.0f;
public Shader dofHdrShader;
private Material dofHdrMaterial = null;
public Shader dx11BokehShader;
private Material dx11bokehMaterial;
public float dx11BokehThreshold = 0.5f;
public float dx11SpawnHeuristic = 0.0875f;
public Texture2D dx11BokehTexture = null;
public float dx11BokehScale = 1.2f;
public float dx11BokehIntensity = 2.5f;
private float focalDistance01 = 10.0f;
private ComputeBuffer cbDrawArgs;
private ComputeBuffer cbPoints;
private float internalBlurWidth = 1.0f;
private Camera cachedCamera;
public override bool CheckResources()
{
CheckSupport(true); // only requires depth, not HDR
dofHdrMaterial = CheckShaderAndCreateMaterial(dofHdrShader, dofHdrMaterial);
if (supportDX11 && blurType == BlurType.DX11)
{
dx11bokehMaterial = CheckShaderAndCreateMaterial(dx11BokehShader, dx11bokehMaterial);
CreateComputeResources();
}
if (!isSupported)
ReportAutoDisable();
return isSupported;
}
void OnEnable()
{
cachedCamera = GetComponent<Camera>();
cachedCamera.depthTextureMode |= DepthTextureMode.Depth;
}
void OnDisable()
{
ReleaseComputeResources();
if (dofHdrMaterial) DestroyImmediate(dofHdrMaterial);
dofHdrMaterial = null;
if (dx11bokehMaterial) DestroyImmediate(dx11bokehMaterial);
dx11bokehMaterial = null;
}
void ReleaseComputeResources()
{
if (cbDrawArgs != null) cbDrawArgs.Release();
cbDrawArgs = null;
if (cbPoints != null) cbPoints.Release();
cbPoints = null;
}
void CreateComputeResources()
{
if (cbDrawArgs == null)
{
cbDrawArgs = new ComputeBuffer(1, 16, ComputeBufferType.IndirectArguments);
var args = new int[4];
args[0] = 0;
args[1] = 1;
args[2] = 0;
args[3] = 0;
cbDrawArgs.SetData(args);
}
if (cbPoints == null)
{
cbPoints = new ComputeBuffer(90000, 12 + 16, ComputeBufferType.Append);
}
}
float FocalDistance01(float worldDist)
{
return cachedCamera.WorldToViewportPoint((worldDist - cachedCamera.nearClipPlane) * cachedCamera.transform.forward +
cachedCamera.transform.position).z / (cachedCamera.farClipPlane - cachedCamera.nearClipPlane);
}
private void WriteCoc(RenderTexture fromTo, bool fgDilate)
{
dofHdrMaterial.SetTexture("_FgOverlap", null);
if (nearBlur && fgDilate)
{
int rtW = fromTo.width / 2;
int rtH = fromTo.height / 2;
// capture fg coc
RenderTexture temp2 = RenderTexture.GetTemporary(rtW, rtH, 0, fromTo.format);
Graphics.Blit(fromTo, temp2, dofHdrMaterial, 4);
// special blur
float fgAdjustment = internalBlurWidth * foregroundOverlap;
dofHdrMaterial.SetVector("_Offsets", new Vector4(0.0f, fgAdjustment, 0.0f, fgAdjustment));
RenderTexture temp1 = RenderTexture.GetTemporary(rtW, rtH, 0, fromTo.format);
Graphics.Blit(temp2, temp1, dofHdrMaterial, 2);
RenderTexture.ReleaseTemporary(temp2);
dofHdrMaterial.SetVector("_Offsets", new Vector4(fgAdjustment, 0.0f, 0.0f, fgAdjustment));
temp2 = RenderTexture.GetTemporary(rtW, rtH, 0, fromTo.format);
Graphics.Blit(temp1, temp2, dofHdrMaterial, 2);
RenderTexture.ReleaseTemporary(temp1);
// "merge up" with background COC
dofHdrMaterial.SetTexture("_FgOverlap", temp2);
fromTo.MarkRestoreExpected(); // only touching alpha channel, RT restore expected
Graphics.Blit(fromTo, fromTo, dofHdrMaterial, 13);
RenderTexture.ReleaseTemporary(temp2);
}
else
{
// capture full coc in alpha channel (fromTo is not read, but bound to detect screen flip)
fromTo.MarkRestoreExpected(); // only touching alpha channel, RT restore expected
Graphics.Blit(fromTo, fromTo, dofHdrMaterial, 0);
}
}
void OnRenderImage(RenderTexture source, RenderTexture destination)
{
if (!CheckResources())
{
Graphics.Blit(source, destination);
return;
}
// clamp & prepare values so they make sense
if (aperture < 0.0f) aperture = 0.0f;
if (maxBlurSize < 0.1f) maxBlurSize = 0.1f;
focalSize = Mathf.Clamp(focalSize, 0.0f, 2.0f);
internalBlurWidth = Mathf.Max(maxBlurSize, 0.0f);
// focal & coc calculations
focalDistance01 = (focalTransform)
? (cachedCamera.WorldToViewportPoint(focalTransform.position)).z / (cachedCamera.farClipPlane)
: FocalDistance01(focalLength);
dofHdrMaterial.SetVector("_CurveParams", new Vector4(1.0f, focalSize, (1.0f / (1.0f - aperture) - 1.0f), focalDistance01));
// possible render texture helpers
RenderTexture rtLow = null;
RenderTexture rtLow2 = null;
RenderTexture rtSuperLow1 = null;
RenderTexture rtSuperLow2 = null;
float fgBlurDist = internalBlurWidth * foregroundOverlap;
if (visualizeFocus)
{
//
// 2.
// visualize coc
//
//
WriteCoc(source, true);
Graphics.Blit(source, destination, dofHdrMaterial, 16);
}
else if ((blurType == BlurType.DX11) && dx11bokehMaterial)
{
//
// 1.
// optimized dx11 bokeh scatter
//
//
if (highResolution)
{
internalBlurWidth = internalBlurWidth < 0.1f ? 0.1f : internalBlurWidth;
fgBlurDist = internalBlurWidth * foregroundOverlap;
rtLow = RenderTexture.GetTemporary(source.width, source.height, 0, source.format);
var dest2 = RenderTexture.GetTemporary(source.width, source.height, 0, source.format);
// capture COC
WriteCoc(source, false);
// blur a bit so we can do a frequency check
rtSuperLow1 = RenderTexture.GetTemporary(source.width >> 1, source.height >> 1, 0, source.format);
rtSuperLow2 = RenderTexture.GetTemporary(source.width >> 1, source.height >> 1, 0, source.format);
Graphics.Blit(source, rtSuperLow1, dofHdrMaterial, 15);
dofHdrMaterial.SetVector("_Offsets", new Vector4(0.0f, 1.5f, 0.0f, 1.5f));
Graphics.Blit(rtSuperLow1, rtSuperLow2, dofHdrMaterial, 19);
dofHdrMaterial.SetVector("_Offsets", new Vector4(1.5f, 0.0f, 0.0f, 1.5f));
Graphics.Blit(rtSuperLow2, rtSuperLow1, dofHdrMaterial, 19);
// capture fg coc
if (nearBlur)
Graphics.Blit(source, rtSuperLow2, dofHdrMaterial, 4);
dx11bokehMaterial.SetTexture("_BlurredColor", rtSuperLow1);
dx11bokehMaterial.SetFloat("_SpawnHeuristic", dx11SpawnHeuristic);
dx11bokehMaterial.SetVector("_BokehParams",
new Vector4(dx11BokehScale, dx11BokehIntensity, Mathf.Clamp(dx11BokehThreshold, 0.005f, 4.0f), internalBlurWidth));
dx11bokehMaterial.SetTexture("_FgCocMask", nearBlur ? rtSuperLow2 : null);
// collect bokeh candidates and replace with a darker pixel
Graphics.SetRandomWriteTarget(1, cbPoints);
Graphics.Blit(source, rtLow, dx11bokehMaterial, 0);
Graphics.ClearRandomWriteTargets();
// fg coc blur happens here (after collect!)
if (nearBlur)
{
dofHdrMaterial.SetVector("_Offsets", new Vector4(0.0f, fgBlurDist, 0.0f, fgBlurDist));
Graphics.Blit(rtSuperLow2, rtSuperLow1, dofHdrMaterial, 2);
dofHdrMaterial.SetVector("_Offsets", new Vector4(fgBlurDist, 0.0f, 0.0f, fgBlurDist));
Graphics.Blit(rtSuperLow1, rtSuperLow2, dofHdrMaterial, 2);
// merge fg coc with bg coc
Graphics.Blit(rtSuperLow2, rtLow, dofHdrMaterial, 3);
}
// NEW: LAY OUT ALPHA on destination target so we get nicer outlines for the high rez version
Graphics.Blit(rtLow, dest2, dofHdrMaterial, 20);
// box blur (easier to merge with bokeh buffer)
dofHdrMaterial.SetVector("_Offsets", new Vector4(internalBlurWidth, 0.0f, 0.0f, internalBlurWidth));
Graphics.Blit(rtLow, source, dofHdrMaterial, 5);
dofHdrMaterial.SetVector("_Offsets", new Vector4(0.0f, internalBlurWidth, 0.0f, internalBlurWidth));
Graphics.Blit(source, dest2, dofHdrMaterial, 21);
// apply bokeh candidates
Graphics.SetRenderTarget(dest2);
ComputeBuffer.CopyCount(cbPoints, cbDrawArgs, 0);
dx11bokehMaterial.SetBuffer("pointBuffer", cbPoints);
dx11bokehMaterial.SetTexture("_MainTex", dx11BokehTexture);
dx11bokehMaterial.SetVector("_Screen",
new Vector3(1.0f / (1.0f * source.width), 1.0f / (1.0f * source.height), internalBlurWidth));
dx11bokehMaterial.SetPass(2);
Graphics.DrawProceduralIndirectNow(MeshTopology.Points, cbDrawArgs, 0);
Graphics.Blit(dest2, destination); // hackaround for DX11 high resolution flipfun (OPTIMIZEME)
RenderTexture.ReleaseTemporary(dest2);
RenderTexture.ReleaseTemporary(rtSuperLow1);
RenderTexture.ReleaseTemporary(rtSuperLow2);
}
else
{
rtLow = RenderTexture.GetTemporary(source.width >> 1, source.height >> 1, 0, source.format);
rtLow2 = RenderTexture.GetTemporary(source.width >> 1, source.height >> 1, 0, source.format);
fgBlurDist = internalBlurWidth * foregroundOverlap;
// capture COC & color in low resolution
WriteCoc(source, false);
source.filterMode = FilterMode.Bilinear;
Graphics.Blit(source, rtLow, dofHdrMaterial, 6);
// blur a bit so we can do a frequency check
rtSuperLow1 = RenderTexture.GetTemporary(rtLow.width >> 1, rtLow.height >> 1, 0, rtLow.format);
rtSuperLow2 = RenderTexture.GetTemporary(rtLow.width >> 1, rtLow.height >> 1, 0, rtLow.format);
Graphics.Blit(rtLow, rtSuperLow1, dofHdrMaterial, 15);
dofHdrMaterial.SetVector("_Offsets", new Vector4(0.0f, 1.5f, 0.0f, 1.5f));
Graphics.Blit(rtSuperLow1, rtSuperLow2, dofHdrMaterial, 19);
dofHdrMaterial.SetVector("_Offsets", new Vector4(1.5f, 0.0f, 0.0f, 1.5f));
Graphics.Blit(rtSuperLow2, rtSuperLow1, dofHdrMaterial, 19);
RenderTexture rtLow3 = null;
if (nearBlur)
{
// capture fg coc
rtLow3 = RenderTexture.GetTemporary(source.width >> 1, source.height >> 1, 0, source.format);
Graphics.Blit(source, rtLow3, dofHdrMaterial, 4);
}
dx11bokehMaterial.SetTexture("_BlurredColor", rtSuperLow1);
dx11bokehMaterial.SetFloat("_SpawnHeuristic", dx11SpawnHeuristic);
dx11bokehMaterial.SetVector("_BokehParams",
new Vector4(dx11BokehScale, dx11BokehIntensity, Mathf.Clamp(dx11BokehThreshold, 0.005f, 4.0f), internalBlurWidth));
dx11bokehMaterial.SetTexture("_FgCocMask", rtLow3);
// collect bokeh candidates and replace with a darker pixel
Graphics.SetRandomWriteTarget(1, cbPoints);
Graphics.Blit(rtLow, rtLow2, dx11bokehMaterial, 0);
Graphics.ClearRandomWriteTargets();
RenderTexture.ReleaseTemporary(rtSuperLow1);
RenderTexture.ReleaseTemporary(rtSuperLow2);
// fg coc blur happens here (after collect!)
if (nearBlur)
{
dofHdrMaterial.SetVector("_Offsets", new Vector4(0.0f, fgBlurDist, 0.0f, fgBlurDist));
Graphics.Blit(rtLow3, rtLow, dofHdrMaterial, 2);
dofHdrMaterial.SetVector("_Offsets", new Vector4(fgBlurDist, 0.0f, 0.0f, fgBlurDist));
Graphics.Blit(rtLow, rtLow3, dofHdrMaterial, 2);
// merge fg coc with bg coc
Graphics.Blit(rtLow3, rtLow2, dofHdrMaterial, 3);
}
// box blur (easier to merge with bokeh buffer)
dofHdrMaterial.SetVector("_Offsets", new Vector4(internalBlurWidth, 0.0f, 0.0f, internalBlurWidth));
Graphics.Blit(rtLow2, rtLow, dofHdrMaterial, 5);
dofHdrMaterial.SetVector("_Offsets", new Vector4(0.0f, internalBlurWidth, 0.0f, internalBlurWidth));
Graphics.Blit(rtLow, rtLow2, dofHdrMaterial, 5);
// apply bokeh candidates
Graphics.SetRenderTarget(rtLow2);
ComputeBuffer.CopyCount(cbPoints, cbDrawArgs, 0);
dx11bokehMaterial.SetBuffer("pointBuffer", cbPoints);
dx11bokehMaterial.SetTexture("_MainTex", dx11BokehTexture);
dx11bokehMaterial.SetVector("_Screen",
new Vector3(1.0f / (1.0f * rtLow2.width), 1.0f / (1.0f * rtLow2.height), internalBlurWidth));
dx11bokehMaterial.SetPass(1);
Graphics.DrawProceduralIndirectNow(MeshTopology.Points, cbDrawArgs, 0);
// upsample & combine
dofHdrMaterial.SetTexture("_LowRez", rtLow2);
dofHdrMaterial.SetTexture("_FgOverlap", rtLow3);
dofHdrMaterial.SetVector("_Offsets", ((1.0f * source.width) / (1.0f * rtLow2.width)) * internalBlurWidth * Vector4.one);
Graphics.Blit(source, destination, dofHdrMaterial, 9);
if (rtLow3) RenderTexture.ReleaseTemporary(rtLow3);
}
}
else
{
//
// 2.
// poisson disc style blur in low resolution
//
//
source.filterMode = FilterMode.Bilinear;
if (highResolution) internalBlurWidth *= 2.0f;
WriteCoc(source, true);
rtLow = RenderTexture.GetTemporary(source.width >> 1, source.height >> 1, 0, source.format);
rtLow2 = RenderTexture.GetTemporary(source.width >> 1, source.height >> 1, 0, source.format);
int blurPass = (blurSampleCount == BlurSampleCount.High || blurSampleCount == BlurSampleCount.Medium) ? 17 : 11;
if (highResolution)
{
dofHdrMaterial.SetVector("_Offsets", new Vector4(0.0f, internalBlurWidth, 0.025f, internalBlurWidth));
Graphics.Blit(source, destination, dofHdrMaterial, blurPass);
}
else
{
dofHdrMaterial.SetVector("_Offsets", new Vector4(0.0f, internalBlurWidth, 0.1f, internalBlurWidth));
// blur
Graphics.Blit(source, rtLow, dofHdrMaterial, 6);
Graphics.Blit(rtLow, rtLow2, dofHdrMaterial, blurPass);
// cheaper blur in high resolution, upsample and combine
dofHdrMaterial.SetTexture("_LowRez", rtLow2);
dofHdrMaterial.SetTexture("_FgOverlap", null);
dofHdrMaterial.SetVector("_Offsets", Vector4.one * ((1.0f * source.width) / (1.0f * rtLow2.width)) * internalBlurWidth);
Graphics.Blit(source, destination, dofHdrMaterial, blurSampleCount == BlurSampleCount.High ? 18 : 12);
}
}
if (rtLow) RenderTexture.ReleaseTemporary(rtLow);
if (rtLow2) RenderTexture.ReleaseTemporary(rtLow2);
}
}
} | 44.731235 | 147 | 0.558839 | [
"BSD-2-Clause"
] | MrJiggers/osm-architect | Assets/Libraries/Standard Assets/Effects/ImageEffects/Scripts/DepthOfField.cs | 18,474 | 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("AWSSDK.IoT1ClickDevicesService")]
[assembly: AssemblyDescription("The Amazon Web Services SDK for .NET (3.5) - AWS IoT 1-Click Devices Service. AWS IoT 1-Click makes it easy for customers to incorporate simple ready-to-use IoT devices into their workflows. These devices can trigger AWS Lambda functions that implement business logic. In order to build applications using AWS IoT 1-Click devices, programmers can use the AWS IoT 1-Click Devices API and the AWS IoT 1-Click Projects API. Learn more at https://aws.amazon.com/documentation/iot-1-click/")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyProduct("Amazon Web Services SDK for .NET")]
[assembly: AssemblyCompany("Amazon.com, Inc")]
[assembly: AssemblyCopyright("Copyright 2009-2020 Amazon.com, Inc. or its affiliates. All Rights Reserved.")]
[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)]
// 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("3.3")]
[assembly: AssemblyFileVersion("3.3.101.137")] | 56.53125 | 519 | 0.761194 | [
"Apache-2.0"
] | lukeenterprise/aws-sdk-net | sdk/code-analysis/ServiceAnalysis/IoT1ClickDevicesService/Properties/AssemblyInfo.cs | 1,809 | C# |
using System.Collections.Generic;
using System.Text;
namespace BTDB.EventStoreLayer;
public class HashSetWithDescriptor<T> : HashSet<T>, IKnowDescriptor
{
readonly ITypeDescriptor _descriptor;
public HashSetWithDescriptor(int capacity, ITypeDescriptor descriptor)
: base(capacity)
{
_descriptor = descriptor;
}
public ITypeDescriptor GetDescriptor()
{
return _descriptor;
}
public override string ToString()
{
var sb = new StringBuilder();
sb.Append("[ ");
var first = true;
foreach (var o in this)
{
if (first) first = false; else sb.Append(", ");
sb.AppendJsonLike(o);
}
sb.Append(" ]");
return sb.ToString();
}
}
| 22.085714 | 74 | 0.601552 | [
"MIT"
] | Jumik/BTDB | BTDB/EventStoreLayer/HashSetWithDescriptor.cs | 773 | C# |
using UnityEditor;
using UnityEngine;
namespace ScriptableObjects.ScriptableArchitecture.Framework.Utility.Editor
{
public static class MeshSaverEditor
{
#region Public
public static void SaveMesh( Mesh mesh, string name, bool makeNewInstance, bool optimizeMesh )
{
string path = EditorUtility.SaveFilePanel( "Save Separate Mesh Asset", "Assets/", name, "asset" );
if ( string.IsNullOrEmpty( path ) )
{
return;
}
path = FileUtil.GetProjectRelativePath( path );
Mesh meshToSave = makeNewInstance ? Object.Instantiate( mesh ) as Mesh : mesh;
if ( optimizeMesh )
{
MeshUtility.Optimize( meshToSave );
}
AssetDatabase.CreateAsset( meshToSave, path );
AssetDatabase.SaveAssets();
}
[MenuItem( "CONTEXT/MeshFilter/Save Mesh..." )]
public static void SaveMeshInPlace( MenuCommand menuCommand )
{
MeshFilter mf = menuCommand.context as MeshFilter;
Mesh m = mf.sharedMesh;
SaveMesh( m, m.name, false, true );
}
[MenuItem( "CONTEXT/MeshFilter/Save Mesh As New Instance..." )]
public static void SaveMeshNewInstanceItem( MenuCommand menuCommand )
{
MeshFilter mf = menuCommand.context as MeshFilter;
Mesh m = mf.sharedMesh;
SaveMesh( m, m.name, true, true );
}
#endregion
}
}
| 26.207547 | 106 | 0.642909 | [
"MIT"
] | Maximilian-Winter/CSCS-Unity | Assets/Scripts/ScriptableObjects/ScriptableArchitecture/Framework/Utility/Editor/MeshSaverEditor.cs | 1,389 | C# |
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("BotCoinEvents")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("BotCoinEvents")]
[assembly: AssemblyCopyright("Copyright © 2017")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("8be44358-0fe7-4585-b76b-67c2b9282bd6")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| 37.675676 | 84 | 0.748207 | [
"Unlicense"
] | hbbq/BotCoin | src/BotCoinEvents/Properties/AssemblyInfo.cs | 1,397 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Otter {
/// <summary>
/// Class that is used for debug input. Wraps the Input class but only works when debug input
/// is enabled.
/// </summary>
public class DebugInput {
#region Static Fields
/// <summary>
/// The active instance of DebugInput.
/// </summary>
public static DebugInput Instance;
#endregion
#region Public Fields
/// <summary>
/// Determines if debug input will be used. If false all checks will return false.
/// </summary>
public bool Enabled;
/// <summary>
/// The parent Game.
/// </summary>
public Game Game;
#endregion
#region Public Methods
/// <summary>
/// Check if a key was pressed.
/// </summary>
/// <param name="k">The key to check.</param>
/// <returns>True if that key was pressed.</returns>
public bool KeyPressed(Key k) {
if (!Enabled) return false;
return Game.Input.KeyPressed(k);
}
/// <summary>
/// Check if a key was released.
/// </summary>
/// <param name="k">The key to check.</param>
/// <returns>True if that key was released.</returns>
public bool KeyReleased(Key k) {
if (!Enabled) return false;
return Game.Input.KeyReleased(k);
}
/// <summary>
/// Check if a key is down.
/// </summary>
/// <param name="k">The key to check.</param>
/// <returns>True if that key is down.</returns>
public bool KeyDown(Key k) {
if (!Enabled) return false;
return Game.Input.KeyDown(k);
}
/// <summary>
/// Check if a key is up.
/// </summary>
/// <param name="k">The key to check.</param>
/// <returns>True if that key is up.</returns>
public bool KeyUp(Key k) {
if (!Enabled) return false;
return Game.Input.KeyUp(k);
}
#endregion
#region Internal
internal DebugInput(Game game) {
Game = game;
Instance = this;
}
#endregion
}
}
| 24.239583 | 97 | 0.518694 | [
"MIT",
"Unlicense"
] | holymoo/OtterSpaceInvaders | Src/Otter/Utility/DebugInput.cs | 2,329 | C# |
// *** WARNING: this file was generated by the Pulumi SDK Generator. ***
// *** Do not edit by hand unless you're certain you know what you are doing! ***
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Threading.Tasks;
using Pulumi.Serialization;
namespace Pulumi.AzureNextGen.CustomerInsights.Latest.Outputs
{
[OutputType]
public sealed class AssignmentPrincipalResponse
{
/// <summary>
/// The principal id being assigned to.
/// </summary>
public readonly string PrincipalId;
/// <summary>
/// Other metadata for the principal.
/// </summary>
public readonly ImmutableDictionary<string, string>? PrincipalMetadata;
/// <summary>
/// The Type of the principal ID.
/// </summary>
public readonly string PrincipalType;
[OutputConstructor]
private AssignmentPrincipalResponse(
string principalId,
ImmutableDictionary<string, string>? principalMetadata,
string principalType)
{
PrincipalId = principalId;
PrincipalMetadata = principalMetadata;
PrincipalType = principalType;
}
}
}
| 29.093023 | 81 | 0.639488 | [
"Apache-2.0"
] | pulumi/pulumi-azure-nextgen | sdk/dotnet/CustomerInsights/Latest/Outputs/AssignmentPrincipalResponse.cs | 1,251 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Charlotte
{
/// <summary>
/// Confused by ConfuserElsa
/// </summary>
public abstract class OverwriteLocalContinentalService
{
/// <summary>
/// Confused by ConfuserElsa
/// </summary>
public int ModifyInitialGanymedeConfiguration()
{
return ShowNullMoonlightSearch() != 1 ? 0 : DestroySpecificMetisCommunication;
}
/// <summary>
/// Confused by ConfuserElsa
/// </summary>
public void LockUnableTungstenRemoval(int EnterCustomHegemoneSystem)
{
TransferTrueHermippeLatency = EnterCustomHegemoneSystem;
}
/// <summary>
/// Confused by ConfuserElsa
/// </summary>
public int ShowNullMoonlightSearch()
{
return IndicateOpenPalleneCache() == 0 ? 1 : RestoreExpectedCordeliaObject;
}
/// <summary>
/// Confused by ConfuserElsa
/// </summary>
public abstract IEnumerable<bool> ProtectExistingEinsteiniumPriority();
/// <summary>
/// Confused by ConfuserElsa
/// </summary>
public bool EncodeEmptyNarviVersion()
{
return this.TransferEqualGalateaString();
}
/// <summary>
/// Confused by ConfuserElsa
/// </summary>
public void SeeFinalHeleneTimeout(int IncludeBooleanNitrogenMethod)
{
this.SerializeRemoteDreamEntry(IncludeBooleanNitrogenMethod, this.PermitConditionalHassiumProcess());
}
/// <summary>
/// Confused by ConfuserElsa
/// </summary>
public void LockFinalVanadiumConstructor()
{
this.LockUnableTungstenRemoval(0);
}
/// <summary>
/// Confused by ConfuserElsa
/// </summary>
public int RunCompleteTelluriumMenu()
{
return ImplementSecureNarviConsole() == 0 ? 0 : PermitFinalTomorrowString;
}
/// <summary>
/// Confused by ConfuserElsa
/// </summary>
public void NotifyValidPraseodymiumEncryption(SimplifyDecimalAegirOwner NotifyAnonymousCaliforniumCore)
{
ReloadPreferredBoronCrash = NotifyAnonymousCaliforniumCore;
}
/// <summary>
/// Confused by ConfuserElsa
/// </summary>
public void PrepareValidMarsMigration(int IncludeBooleanNitrogenMethod, int SupportVisibleBerkeliumForm, int RestartInvalidFeliceArray, int EmitGeneralErsaBrowser, int RespondMockMakemakePrefix, int AssertExecutableOganessonUnit)
{
var HideMatchingMarineDeveloper = new[]
{
new
{
VisitInnerLedaRequest = IncludeBooleanNitrogenMethod, DecodeCompleteJupiterCache = EmitGeneralErsaBrowser
},
new
{
VisitInnerLedaRequest = SupportVisibleBerkeliumForm, DecodeCompleteJupiterCache = EmitGeneralErsaBrowser
},
new
{
VisitInnerLedaRequest = RestartInvalidFeliceArray, DecodeCompleteJupiterCache = EmitGeneralErsaBrowser
},
};
this.NotifyValidPraseodymiumEncryption(new SimplifyDecimalAegirOwner()
{
SubmitNextTenderCase = IncludeBooleanNitrogenMethod,
IterateUnableHyrrokkinInformation = SupportVisibleBerkeliumForm,
ChangeMinimumPeaceCharacter = RestartInvalidFeliceArray,
});
if (HideMatchingMarineDeveloper[0].VisitInnerLedaRequest == EmitGeneralErsaBrowser) this.CaptureVerboseIsonoeShutdown(HideMatchingMarineDeveloper[0].DecodeCompleteJupiterCache);
if (HideMatchingMarineDeveloper[1].VisitInnerLedaRequest == RespondMockMakemakePrefix) this.CaptureVerboseIsonoeShutdown(HideMatchingMarineDeveloper[1].DecodeCompleteJupiterCache);
if (HideMatchingMarineDeveloper[2].VisitInnerLedaRequest == AssertExecutableOganessonUnit) this.CaptureVerboseIsonoeShutdown(HideMatchingMarineDeveloper[2].DecodeCompleteJupiterCache);
}
/// <summary>
/// Confused by ConfuserElsa
/// </summary>
public static int PermitFinalTomorrowString;
/// <summary>
/// Confused by ConfuserElsa
/// </summary>
public int IgnoreAccessibleRosalindColumn()
{
return TransferTrueHermippeLatency;
}
/// <summary>
/// Confused by ConfuserElsa
/// </summary>
public int StartStandaloneCarbonOption()
{
return ModifyInitialGanymedeConfiguration() == 0 ? 0 : BrowseExpectedDionePatch;
}
/// <summary>
/// Confused by ConfuserElsa
/// </summary>
public void RunRedundantMacaronDuration(int IncludeBooleanNitrogenMethod, int SupportVisibleBerkeliumForm, int RestartInvalidFeliceArray)
{
this.PrepareValidMarsMigration(IncludeBooleanNitrogenMethod, SupportVisibleBerkeliumForm, RestartInvalidFeliceArray, this.TransformDedicatedCarpoRevision().SubmitNextTenderCase, this.TransformDedicatedCarpoRevision().IterateUnableHyrrokkinInformation, this.TransformDedicatedCarpoRevision().ChangeMinimumPeaceCharacter);
}
/// <summary>
/// Confused by ConfuserElsa
/// </summary>
public void SuppressMatchingErriapusPerformance()
{
this.SeeFinalHeleneTimeout(this.PermitConditionalHassiumProcess());
}
/// <summary>
/// Confused by ConfuserElsa
/// </summary>
public SimplifyDecimalAegirOwner TransformDedicatedCarpoRevision()
{
return ReloadPreferredBoronCrash;
}
/// <summary>
/// Confused by ConfuserElsa
/// </summary>
public int PermitConditionalHassiumProcess()
{
return TransferTrueHermippeLatency++;
}
/// <summary>
/// Confused by ConfuserElsa
/// </summary>
public static int RestoreExpectedCordeliaObject;
/// <summary>
/// Confused by ConfuserElsa
/// </summary>
public void SerializeRemoteDreamEntry(int IncludeBooleanNitrogenMethod, int SupportVisibleBerkeliumForm)
{
this.RunRedundantMacaronDuration(IncludeBooleanNitrogenMethod, SupportVisibleBerkeliumForm, this.PermitConditionalHassiumProcess());
}
/// <summary>
/// Confused by ConfuserElsa
/// </summary>
public void CaptureVerboseIsonoeShutdown(int ReturnUnsupportedHyperionCompletion)
{
if (ReturnUnsupportedHyperionCompletion != this.IgnoreAccessibleRosalindColumn())
this.LockUnableTungstenRemoval(ReturnUnsupportedHyperionCompletion);
else
this.SeeFinalHeleneTimeout(ReturnUnsupportedHyperionCompletion);
}
/// <summary>
/// Confused by ConfuserElsa
/// </summary>
public static int FilterMaximumSherryProtocol;
/// <summary>
/// Confused by ConfuserElsa
/// </summary>
public int IndicateOpenPalleneCache()
{
return TypeCoreKiviuqPlugin() == 0 ? 1 : ViewFreeNarviSchema;
}
/// <summary>
/// Confused by ConfuserElsa
/// </summary>
public static int TransferTrueHermippeLatency;
private Func<bool> ReferenceExtraOxygenCharacter = null;
/// <summary>
/// Confused by ConfuserElsa
/// </summary>
public static int DestroySpecificMetisCommunication;
/// <summary>
/// Confused by ConfuserElsa
/// </summary>
public int TypeCoreKiviuqPlugin()
{
return RunCompleteTelluriumMenu() == 0 ? 0 : FilterMaximumSherryProtocol;
}
/// <summary>
/// Confused by ConfuserElsa
/// </summary>
public static SimplifyDecimalAegirOwner ReloadPreferredBoronCrash;
/// <summary>
/// Confused by ConfuserElsa
/// </summary>
public int ImplementSecureNarviConsole()
{
return ProcessMatchingFleroviumWhitespace;
}
/// <summary>
/// Confused by ConfuserElsa
/// </summary>
public class SimplifyDecimalAegirOwner
{
public int SubmitNextTenderCase;
public int IterateUnableHyrrokkinInformation;
public int ChangeMinimumPeaceCharacter;
}
/// <summary>
/// Confused by ConfuserElsa
/// </summary>
public static int ViewFreeNarviSchema;
/// <summary>
/// Confused by ConfuserElsa
/// </summary>
public static int BrowseExpectedDionePatch;
/// <summary>
/// Confused by ConfuserElsa
/// </summary>
public Func<bool> TransferEqualGalateaString
{
get
{
if (ReferenceExtraOxygenCharacter == null)
ReferenceExtraOxygenCharacter = StopNestedOganessonRegistry.EncounterValidUranusProblem(this.ProtectExistingEinsteiniumPriority());
return ReferenceExtraOxygenCharacter;
}
}
/// <summary>
/// Confused by ConfuserElsa
/// </summary>
public static int ProcessMatchingFleroviumWhitespace;
}
}
| 28.25 | 323 | 0.748167 | [
"MIT"
] | soleil-taruto/Hatena | a20201226/Confused_02/tmpsol/Elsa20200001/SubmitUnableIodineModifier.cs | 7,912 | C# |
namespace WildFarm.Models.Foods
{
public class Meat : Food
{
public Meat(int quantity)
: base(quantity)
{
}
}
} | 16.1 | 34 | 0.496894 | [
"MIT"
] | SonicTheCat/CSharp-OOP-Basics | 12.Polymorphism - Exercise/03.WildFarm/Models/Foods/Meat.cs | 163 | C# |
using holonsoft.FastProtocolConverter.Abstractions.Enums;
using System.Reflection;
namespace holonsoft.FastProtocolConverter.Abstractions.Delegates
{
/// <summary>
/// Defines a delegate for handling range check violations
/// hint: you can define ranges via attribute for a field in a POCO
/// </summary>
public delegate void OnRangeViolationDelegate(FieldInfo fieldInfo, out ConverterRangeViolationBehaviour converterRangeViolationBehaviour);
} | 41.272727 | 139 | 0.817181 | [
"Apache-2.0"
] | holonsoft/FastProtocolConverter | holonsoft.FastProtocolConverter.Abstractions/Delegates/OnRangeViolationDelegate.cs | 456 | C# |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Weapon : BoardPiece
{
// Author - Daniel Kean
/// <summary>
/// This represents all the weapons that will be present
/// on the game board.
///
/// Author - Daniel Kean
/// </summary>
#region Inspector Variables
[SerializeField] private string weaponName = "Default Weapon Name";
#endregion
} | 20.571429 | 71 | 0.659722 | [
"MIT"
] | JellyMoonGames/clue | Clue/Assets/Scripts/Weapon.cs | 434 | C# |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
// <auto-generated/>
#nullable disable
using System.Text.Json;
using Azure.Core;
namespace Azure.ResourceManager.MachineLearningServices.Models
{
public partial class AKSReplicaStatus
{
internal static AKSReplicaStatus DeserializeAKSReplicaStatus(JsonElement element)
{
Optional<int> desiredReplicas = default;
Optional<int> updatedReplicas = default;
Optional<int> availableReplicas = default;
Optional<AKSReplicaStatusError> error = default;
foreach (var property in element.EnumerateObject())
{
if (property.NameEquals("desiredReplicas"))
{
if (property.Value.ValueKind == JsonValueKind.Null)
{
property.ThrowNonNullablePropertyIsNull();
continue;
}
desiredReplicas = property.Value.GetInt32();
continue;
}
if (property.NameEquals("updatedReplicas"))
{
if (property.Value.ValueKind == JsonValueKind.Null)
{
property.ThrowNonNullablePropertyIsNull();
continue;
}
updatedReplicas = property.Value.GetInt32();
continue;
}
if (property.NameEquals("availableReplicas"))
{
if (property.Value.ValueKind == JsonValueKind.Null)
{
property.ThrowNonNullablePropertyIsNull();
continue;
}
availableReplicas = property.Value.GetInt32();
continue;
}
if (property.NameEquals("error"))
{
if (property.Value.ValueKind == JsonValueKind.Null)
{
property.ThrowNonNullablePropertyIsNull();
continue;
}
error = AKSReplicaStatusError.DeserializeAKSReplicaStatusError(property.Value);
continue;
}
}
return new AKSReplicaStatus(Optional.ToNullable(desiredReplicas), Optional.ToNullable(updatedReplicas), Optional.ToNullable(availableReplicas), error.Value);
}
}
}
| 37.602941 | 169 | 0.513883 | [
"MIT"
] | 93mishra/azure-sdk-for-net | sdk/machinelearningservices/Azure.ResourceManager.MachineLearningServices/src/Generated/Models/AKSReplicaStatus.Serialization.cs | 2,557 | 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 budgets-2016-10-20.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.Budgets.Model
{
/// <summary>
/// We can’t locate the resource that you specified.
/// </summary>
#if !NETSTANDARD
[Serializable]
#endif
public partial class NotFoundException : AmazonBudgetsException
{
/// <summary>
/// Constructs a new NotFoundException with the specified error
/// message.
/// </summary>
/// <param name="message">
/// Describes the error encountered.
/// </param>
public NotFoundException(string message)
: base(message) {}
/// <summary>
/// Construct instance of NotFoundException
/// </summary>
/// <param name="message"></param>
/// <param name="innerException"></param>
public NotFoundException(string message, Exception innerException)
: base(message, innerException) {}
/// <summary>
/// Construct instance of NotFoundException
/// </summary>
/// <param name="innerException"></param>
public NotFoundException(Exception innerException)
: base(innerException) {}
/// <summary>
/// Construct instance of NotFoundException
/// </summary>
/// <param name="message"></param>
/// <param name="innerException"></param>
/// <param name="errorType"></param>
/// <param name="errorCode"></param>
/// <param name="requestId"></param>
/// <param name="statusCode"></param>
public NotFoundException(string message, Exception innerException, ErrorType errorType, string errorCode, string requestId, HttpStatusCode statusCode)
: base(message, innerException, errorType, errorCode, requestId, statusCode) {}
/// <summary>
/// Construct instance of NotFoundException
/// </summary>
/// <param name="message"></param>
/// <param name="errorType"></param>
/// <param name="errorCode"></param>
/// <param name="requestId"></param>
/// <param name="statusCode"></param>
public NotFoundException(string message, ErrorType errorType, string errorCode, string requestId, HttpStatusCode statusCode)
: base(message, errorType, errorCode, requestId, statusCode) {}
#if !NETSTANDARD
/// <summary>
/// Constructs a new instance of the NotFoundException class with serialized data.
/// </summary>
/// <param name="info">The <see cref="T:System.Runtime.Serialization.SerializationInfo" /> that holds the serialized object data about the exception being thrown.</param>
/// <param name="context">The <see cref="T:System.Runtime.Serialization.StreamingContext" /> that contains contextual information about the source or destination.</param>
/// <exception cref="T:System.ArgumentNullException">The <paramref name="info" /> parameter is null. </exception>
/// <exception cref="T:System.Runtime.Serialization.SerializationException">The class name is null or <see cref="P:System.Exception.HResult" /> is zero (0). </exception>
protected NotFoundException(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context)
: base(info, context)
{
}
/// <summary>
/// Sets the <see cref="T:System.Runtime.Serialization.SerializationInfo" /> with information about the exception.
/// </summary>
/// <param name="info">The <see cref="T:System.Runtime.Serialization.SerializationInfo" /> that holds the serialized object data about the exception being thrown.</param>
/// <param name="context">The <see cref="T:System.Runtime.Serialization.StreamingContext" /> that contains contextual information about the source or destination.</param>
/// <exception cref="T:System.ArgumentNullException">The <paramref name="info" /> parameter is a null reference (Nothing in Visual Basic). </exception>
#if BCL35
[System.Security.Permissions.SecurityPermission(
System.Security.Permissions.SecurityAction.LinkDemand,
Flags = System.Security.Permissions.SecurityPermissionFlag.SerializationFormatter)]
#endif
[System.Security.SecurityCritical]
// These FxCop rules are giving false-positives for this method
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Security", "CA2123:OverrideLinkDemandsShouldBeIdenticalToBase")]
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Security", "CA2134:MethodsMustOverrideWithConsistentTransparencyFxCopRule")]
public override void GetObjectData(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context)
{
base.GetObjectData(info, context);
}
#endif
}
} | 46.298387 | 178 | 0.674447 | [
"Apache-2.0"
] | DetlefGolze/aws-sdk-net | sdk/src/Services/Budgets/Generated/Model/NotFoundException.cs | 5,743 | C# |
namespace NStuff.RasterGraphics
{
/// <summary>
/// Lists the image formats.
/// </summary>
public enum RasterImageFormat
{
/// <summary>
/// Pixels are in the red format.
/// </summary>
GreyscaleAlpha,
/// <summary>
/// Pixels are in the red-alpha format.
/// </summary>
Greyscale,
/// <summary>
/// Pixels are in red-green-blue format.
/// </summary>
TrueColor,
/// <summary>
/// Pixels are in red-green-blue-alpha format.
/// </summary>
TrueColorAlpha
}
}
| 21.206897 | 54 | 0.497561 | [
"Apache-2.0"
] | n-stuff/window-system | src/RasterGraphics/RasterImageFormat.cs | 617 | C# |
#nullable enable
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Threading.Tasks;
namespace DotVVM.Framework.ResourceManagement
{
public class ReflectionAssemblyJsonConverter : JsonConverter
{
public override bool CanConvert(Type objectType) => typeof(Assembly).IsAssignableFrom(objectType);
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
if (reader.Value is string name)
{
return Assembly.Load(new AssemblyName(name));
}
else throw new NotSupportedException();
}
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
writer.WriteValue(((Assembly)value).GetName().ToString());
}
}
}
| 30.733333 | 124 | 0.684382 | [
"Apache-2.0"
] | AMBULATUR/dotvvm | src/DotVVM.Framework/ResourceManagement/ReflectionAssemblyJsonConverter.cs | 924 | C# |
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
// Runtime Version:4.0.30319.42000
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
namespace MigratorGUI.Properties {
using System;
/// <summary>
/// A strongly-typed resource class, for looking up localized strings, etc.
/// </summary>
// This class was auto-generated by the StronglyTypedResourceBuilder
// class via a tool like ResGen or Visual Studio.
// To add or remove a member, edit your .ResX file then rerun ResGen
// with the /str option, or rebuild your VS project.
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "4.0.0.0")]
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
internal class Resources {
private static global::System.Resources.ResourceManager resourceMan;
private static global::System.Globalization.CultureInfo resourceCulture;
[global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
internal Resources() {
}
/// <summary>
/// Returns the cached ResourceManager instance used by this class.
/// </summary>
[global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
internal static global::System.Resources.ResourceManager ResourceManager {
get {
if (object.ReferenceEquals(resourceMan, null)) {
global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("MigratorGUI.Properties.Resources", typeof(Resources).Assembly);
resourceMan = temp;
}
return resourceMan;
}
}
/// <summary>
/// Overrides the current thread's CurrentUICulture property for all
/// resource lookups using this strongly typed resource class.
/// </summary>
[global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
internal static global::System.Globalization.CultureInfo Culture {
get {
return resourceCulture;
}
set {
resourceCulture = value;
}
}
}
}
| 44.5 | 178 | 0.599719 | [
"MIT"
] | saturdaymp/Migrator | Source/MigratorGUI/Properties/Resources.Designer.cs | 2,850 | C# |
namespace Core.UnitTests
{
using Crest.Core;
using FluentAssertions;
using Xunit;
public class PutAttributeTests
{
public sealed class CanReadBody : PutAttributeTests
{
[Fact]
public void ShouldReturnTrue()
{
var attribute = new PutAttribute(string.Empty);
attribute.CanReadBody.Should().BeTrue();
}
}
public sealed class Route : PutAttributeTests
{
private const string ExampleRoute = "example/route";
[Fact]
public void ShouldReturnTheRoutePassedInToTheConstructor()
{
var attribute = new PutAttribute(ExampleRoute);
attribute.Route.Should().Be(ExampleRoute);
}
}
public sealed class Verb : PutAttributeTests
{
[Fact]
public void ShouldReturnPUT()
{
var attribute = new PutAttribute(string.Empty);
attribute.Verb.Should().Be("PUT");
}
}
}
}
| 24.422222 | 70 | 0.528662 | [
"MIT"
] | samcragg/Crest | test/Core.UnitTests/PutAttributeTests.cs | 1,101 | C# |
using MediatR;
using System;
using System.Net.Http;
using System.Threading.Tasks;
using System.Web.Http;
using System.Web.Http.Description;
using NoDaysOffApp.Features.Core;
namespace NoDaysOffApp.Features.Tiles
{
[Authorize]
[RoutePrefix("api/tiles")]
public class TileController : BaseApiController
{
public TileController(IMediator mediator)
:base(mediator) { }
[Route("add")]
[HttpPost]
[ResponseType(typeof(AddOrUpdateTileCommand.Response))]
public async Task<IHttpActionResult> Add(AddOrUpdateTileCommand.Request request) => Ok(await Send(request));
[Route("update")]
[HttpPut]
[ResponseType(typeof(AddOrUpdateTileCommand.Response))]
public async Task<IHttpActionResult> Update(AddOrUpdateTileCommand.Request request) => Ok(await Send(request));
[Route("get")]
[AllowAnonymous]
[HttpGet]
[ResponseType(typeof(GetTilesQuery.Response))]
public async Task<IHttpActionResult> Get() => Ok(await Send(new GetTilesQuery.Request()));
[Route("getById")]
[HttpGet]
[ResponseType(typeof(GetTileByIdQuery.Response))]
public async Task<IHttpActionResult> GetById([FromUri]GetTileByIdQuery.Request request) => Ok(await Send(request));
[Route("remove")]
[HttpDelete]
[ResponseType(typeof(RemoveTileCommand.Response))]
public async Task<IHttpActionResult> Remove([FromUri]RemoveTileCommand.Request request) => Ok(await Send(request));
}
}
| 33.73913 | 123 | 0.680412 | [
"MIT"
] | QuinntyneBrown/no-days-off-app | Features/Tiles/TilesController.cs | 1,552 | C# |
////////////////////////////////
//
// Copyright 2021 Battelle Energy Alliance, LLC
//
//
////////////////////////////////
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Net.Http.Headers;
namespace CSETWeb_Api.Areas.HelpPage
{
/// <summary>
/// This is used to identify the place where the sample should be applied.
/// </summary>
public class HelpPageSampleKey
{
/// <summary>
/// Creates a new <see cref="HelpPageSampleKey"/> based on media type.
/// </summary>
/// <param name="mediaType">The media type.</param>
public HelpPageSampleKey(MediaTypeHeaderValue mediaType)
{
if (mediaType == null)
{
throw new ArgumentNullException("mediaType");
}
ActionName = String.Empty;
ControllerName = String.Empty;
MediaType = mediaType;
ParameterNames = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
}
/// <summary>
/// Creates a new <see cref="HelpPageSampleKey"/> based on media type and CLR type.
/// </summary>
/// <param name="mediaType">The media type.</param>
/// <param name="type">The CLR type.</param>
public HelpPageSampleKey(MediaTypeHeaderValue mediaType, Type type)
: this(mediaType)
{
if (type == null)
{
throw new ArgumentNullException("type");
}
ParameterType = type;
}
/// <summary>
/// Creates a new <see cref="HelpPageSampleKey"/> based on <see cref="SampleDirection"/>, controller name, action name and parameter names.
/// </summary>
/// <param name="sampleDirection">The <see cref="SampleDirection"/>.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
public HelpPageSampleKey(SampleDirection sampleDirection, string controllerName, string actionName, IEnumerable<string> parameterNames)
{
if (!Enum.IsDefined(typeof(SampleDirection), sampleDirection))
{
throw new InvalidEnumArgumentException("sampleDirection", (int)sampleDirection, typeof(SampleDirection));
}
if (controllerName == null)
{
throw new ArgumentNullException("controllerName");
}
if (actionName == null)
{
throw new ArgumentNullException("actionName");
}
if (parameterNames == null)
{
throw new ArgumentNullException("parameterNames");
}
ControllerName = controllerName;
ActionName = actionName;
ParameterNames = new HashSet<string>(parameterNames, StringComparer.OrdinalIgnoreCase);
SampleDirection = sampleDirection;
}
/// <summary>
/// Creates a new <see cref="HelpPageSampleKey"/> based on media type, <see cref="SampleDirection"/>, controller name, action name and parameter names.
/// </summary>
/// <param name="mediaType">The media type.</param>
/// <param name="sampleDirection">The <see cref="SampleDirection"/>.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
public HelpPageSampleKey(MediaTypeHeaderValue mediaType, SampleDirection sampleDirection, string controllerName, string actionName, IEnumerable<string> parameterNames)
: this(sampleDirection, controllerName, actionName, parameterNames)
{
if (mediaType == null)
{
throw new ArgumentNullException("mediaType");
}
MediaType = mediaType;
}
/// <summary>
/// Gets the name of the controller.
/// </summary>
/// <value>
/// The name of the controller.
/// </value>
public string ControllerName { get; private set; }
/// <summary>
/// Gets the name of the action.
/// </summary>
/// <value>
/// The name of the action.
/// </value>
public string ActionName { get; private set; }
/// <summary>
/// Gets the media type.
/// </summary>
/// <value>
/// The media type.
/// </value>
public MediaTypeHeaderValue MediaType { get; private set; }
/// <summary>
/// Gets the parameter names.
/// </summary>
public HashSet<string> ParameterNames { get; private set; }
public Type ParameterType { get; private set; }
/// <summary>
/// Gets the <see cref="SampleDirection"/>.
/// </summary>
public SampleDirection? SampleDirection { get; private set; }
public override bool Equals(object obj)
{
HelpPageSampleKey otherKey = obj as HelpPageSampleKey;
if (otherKey == null)
{
return false;
}
return String.Equals(ControllerName, otherKey.ControllerName, StringComparison.OrdinalIgnoreCase) &&
String.Equals(ActionName, otherKey.ActionName, StringComparison.OrdinalIgnoreCase) &&
(MediaType == otherKey.MediaType || (MediaType != null && MediaType.Equals(otherKey.MediaType))) &&
ParameterType == otherKey.ParameterType &&
SampleDirection == otherKey.SampleDirection &&
ParameterNames.SetEquals(otherKey.ParameterNames);
}
public override int GetHashCode()
{
int hashCode = ControllerName.ToUpperInvariant().GetHashCode() ^ ActionName.ToUpperInvariant().GetHashCode();
if (MediaType != null)
{
hashCode ^= MediaType.GetHashCode();
}
if (SampleDirection != null)
{
hashCode ^= SampleDirection.GetHashCode();
}
if (ParameterType != null)
{
hashCode ^= ParameterType.GetHashCode();
}
foreach (string parameterName in ParameterNames)
{
hashCode ^= parameterName.ToUpperInvariant().GetHashCode();
}
return hashCode;
}
}
}
| 36.513812 | 175 | 0.563928 | [
"MIT"
] | PinkDev1/cset | CSETWebApi/CSETWeb_Api/CSETWeb_Api/Areas/HelpPage/SampleGeneration/HelpPageSampleKey.cs | 6,609 | C# |
using System.Web.Http.ExceptionHandling;
using NLog;
namespace UnityPoc.Infrastructure
{
public class NLogExceptionLogger : ExceptionLogger
{
private readonly ILogger _logger;
public NLogExceptionLogger(ILogger logger)
{
_logger = logger;
}
public override void Log(ExceptionLoggerContext context)
{
_logger.Log(LogLevel.Error, context.Exception);
}
}
} | 22.45 | 64 | 0.643653 | [
"MIT"
] | tonysneed/Demo.UnityPocWithNLog | UnityPoc/Infrastructure/NLogExceptionLogger.cs | 451 | C# |
using System;
namespace FluentAssertions.Formatting;
public class MaxLinesExceededException : Exception
{
public MaxLinesExceededException(string message, Exception innerException)
: base(message, innerException)
{
}
public MaxLinesExceededException(string message)
: base(message)
{
}
public MaxLinesExceededException()
{
}
}
| 18.285714 | 78 | 0.700521 | [
"Apache-2.0"
] | IT-VBFK/fluentassertions | Src/FluentAssertions/Formatting/MaxLinesExceededException.cs | 386 | C# |
/*
* Intersight REST API
*
* This is Intersight REST API
*
* OpenAPI spec version: 0.1.0-559
*
* Generated by: https://github.com/swagger-api/swagger-codegen.git
*/
using System;
using System.Linq;
using System.IO;
using System.Text;
using System.Text.RegularExpressions;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Runtime.Serialization;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using System.ComponentModel.DataAnnotations;
using SwaggerDateConverter = intersight.Client.SwaggerDateConverter;
namespace intersight.Model
{
/// <summary>
/// Base message for connector messages that require authentication to be passed from cloud services.
/// </summary>
[DataContract]
public partial class ConnectorAuthMessage : IEquatable<ConnectorAuthMessage>, IValidatableObject
{
/// <summary>
/// Initializes a new instance of the <see cref="ConnectorAuthMessage" /> class.
/// </summary>
/// <param name="RemoteUserLocale">The platform locale to assign user. A locale defines one or more organizations (domains) the user is allowed access, and access is limited to the organizations specified in the locale. .</param>
/// <param name="RemoteUserName">User name passed to the platform for use in platform audit logs. .</param>
/// <param name="RemoteUserRoles">List of roles to pass to the platform to validate the action against .</param>
/// <param name="RemoteUserSessionId">Session Id passed to the platform for use in platforms auditing. .</param>
public ConnectorAuthMessage(string RemoteUserLocale = default(string), string RemoteUserName = default(string), string RemoteUserRoles = default(string), string RemoteUserSessionId = default(string))
{
this.RemoteUserLocale = RemoteUserLocale;
this.RemoteUserName = RemoteUserName;
this.RemoteUserRoles = RemoteUserRoles;
this.RemoteUserSessionId = RemoteUserSessionId;
}
/// <summary>
/// The platform locale to assign user. A locale defines one or more organizations (domains) the user is allowed access, and access is limited to the organizations specified in the locale.
/// </summary>
/// <value>The platform locale to assign user. A locale defines one or more organizations (domains) the user is allowed access, and access is limited to the organizations specified in the locale. </value>
[DataMember(Name="RemoteUserLocale", EmitDefaultValue=false)]
public string RemoteUserLocale { get; set; }
/// <summary>
/// User name passed to the platform for use in platform audit logs.
/// </summary>
/// <value>User name passed to the platform for use in platform audit logs. </value>
[DataMember(Name="RemoteUserName", EmitDefaultValue=false)]
public string RemoteUserName { get; set; }
/// <summary>
/// List of roles to pass to the platform to validate the action against
/// </summary>
/// <value>List of roles to pass to the platform to validate the action against </value>
[DataMember(Name="RemoteUserRoles", EmitDefaultValue=false)]
public string RemoteUserRoles { get; set; }
/// <summary>
/// Session Id passed to the platform for use in platforms auditing.
/// </summary>
/// <value>Session Id passed to the platform for use in platforms auditing. </value>
[DataMember(Name="RemoteUserSessionId", EmitDefaultValue=false)]
public string RemoteUserSessionId { get; set; }
/// <summary>
/// Returns the string presentation of the object
/// </summary>
/// <returns>String presentation of the object</returns>
public override string ToString()
{
var sb = new StringBuilder();
sb.Append("class ConnectorAuthMessage {\n");
sb.Append(" RemoteUserLocale: ").Append(RemoteUserLocale).Append("\n");
sb.Append(" RemoteUserName: ").Append(RemoteUserName).Append("\n");
sb.Append(" RemoteUserRoles: ").Append(RemoteUserRoles).Append("\n");
sb.Append(" RemoteUserSessionId: ").Append(RemoteUserSessionId).Append("\n");
sb.Append("}\n");
return sb.ToString();
}
/// <summary>
/// Returns the JSON string presentation of the object
/// </summary>
/// <returns>JSON string presentation of the object</returns>
public string ToJson()
{
return JsonConvert.SerializeObject(this, Formatting.Indented);
}
/// <summary>
/// Returns true if objects are equal
/// </summary>
/// <param name="obj">Object to be compared</param>
/// <returns>Boolean</returns>
public override bool Equals(object obj)
{
// credit: http://stackoverflow.com/a/10454552/677735
return this.Equals(obj as ConnectorAuthMessage);
}
/// <summary>
/// Returns true if ConnectorAuthMessage instances are equal
/// </summary>
/// <param name="other">Instance of ConnectorAuthMessage to be compared</param>
/// <returns>Boolean</returns>
public bool Equals(ConnectorAuthMessage other)
{
// credit: http://stackoverflow.com/a/10454552/677735
if (other == null)
return false;
return
(
this.RemoteUserLocale == other.RemoteUserLocale ||
this.RemoteUserLocale != null &&
this.RemoteUserLocale.Equals(other.RemoteUserLocale)
) &&
(
this.RemoteUserName == other.RemoteUserName ||
this.RemoteUserName != null &&
this.RemoteUserName.Equals(other.RemoteUserName)
) &&
(
this.RemoteUserRoles == other.RemoteUserRoles ||
this.RemoteUserRoles != null &&
this.RemoteUserRoles.Equals(other.RemoteUserRoles)
) &&
(
this.RemoteUserSessionId == other.RemoteUserSessionId ||
this.RemoteUserSessionId != null &&
this.RemoteUserSessionId.Equals(other.RemoteUserSessionId)
);
}
/// <summary>
/// Gets the hash code
/// </summary>
/// <returns>Hash code</returns>
public override int GetHashCode()
{
// credit: http://stackoverflow.com/a/263416/677735
unchecked // Overflow is fine, just wrap
{
int hash = 41;
// Suitable nullity checks etc, of course :)
if (this.RemoteUserLocale != null)
hash = hash * 59 + this.RemoteUserLocale.GetHashCode();
if (this.RemoteUserName != null)
hash = hash * 59 + this.RemoteUserName.GetHashCode();
if (this.RemoteUserRoles != null)
hash = hash * 59 + this.RemoteUserRoles.GetHashCode();
if (this.RemoteUserSessionId != null)
hash = hash * 59 + this.RemoteUserSessionId.GetHashCode();
return hash;
}
}
/// <summary>
/// To validate all properties of the instance
/// </summary>
/// <param name="validationContext">Validation context</param>
/// <returns>Validation Result</returns>
IEnumerable<System.ComponentModel.DataAnnotations.ValidationResult> IValidatableObject.Validate(ValidationContext validationContext)
{
yield break;
}
}
}
| 43.657459 | 238 | 0.606935 | [
"Apache-2.0"
] | CiscoUcs/intersight-powershell | csharp/swaggerClient/src/intersight/Model/ConnectorAuthMessage.cs | 7,902 | C# |
using System;
using System.IO;
using System.Collections.Generic;
using Commons;
namespace ATL.benchmark
{
public class FileFinder
{
static ICollection<Format> supportedFormats;
static FileFinder()
{
supportedFormats = AudioData.AudioDataIOFactory.GetInstance().getFormats();
}
private bool isFormatSupported(string filePath)
{
bool result = false;
foreach (Format f in supportedFormats)
{
if (f.IsValidExtension(Path.GetExtension(filePath)))
{
result = true;
break;
}
}
return result;
}
private string lookForLyrics(Track t, string key)
{
string value = t.AdditionalFields[key];
if (value.Length > 50) return key; else return "";
}
public void FF_RecursiveExplore(string dirName, string filter)
{
DirectoryInfo dirInfo = new DirectoryInfo(dirName);
foreach (FileInfo f in dirInfo.EnumerateFiles(filter, SearchOption.AllDirectories))
{
Track t = new Track(f.FullName);
string found = "";
if (t.AdditionalFields != null)
{
if (t.AdditionalFields.Keys.Contains("uslt")) found = lookForLyrics(t, "uslt");
if (t.AdditionalFields.Keys.Contains("USLT")) found = lookForLyrics(t, "USLT");
if (t.AdditionalFields.Keys.Contains("sylt")) found = lookForLyrics(t, "sylt");
if (t.AdditionalFields.Keys.Contains("SYLT")) found = lookForLyrics(t, "uslt");
if (found.Length > 0) Console.WriteLine("FOUND " + found + " IN " + f.FullName);
}
}
}
public void FF_ReadOneFile()
{
//Track t = new Track(@"E:\temp\wma\a.wma");
//Track t = new Track(TestUtils.GetResourceLocationRoot() + "/OGG/ogg_bigPicture.ogg");
}
public void FF_FilterAndDisplayAudioFiles()
{
FF_BrowseATLAudioFiles(null);
}
public void FF_BrowseATLAudioFiles(string path, bool fetchPicture = false, bool display = true)
{
//string folder = TestUtils.GetResourceLocationRoot();
string folder = (null == path) ? @"E:\temp\wma" : path;
string[] files = Directory.GetFiles(folder);
IList<PictureInfo> pictures;
Track t;
foreach (string file in files)
{
if (isFormatSupported(file))
{
t = new Track(file);
if (fetchPicture) pictures = t.EmbeddedPictures;
if (display)
{
Console.WriteLine(t.Path + "......." + Commons.Utils.EncodeTimecode_s(t.Duration) + " | " + t.SampleRate + " (" + t.Bitrate + " kpbs" + (t.IsVBR ? " VBR)" : ")"));
Console.WriteLine(Utils.BuildStrictLengthString("", t.Path.Length, '.') + "......." + t.DiscNumber + " | " + t.TrackNumber + " | " + t.Title + " | " + t.Artist + " | " + t.Album + " | " + t.Year + ((t.PictureTokens != null && t.PictureTokens.Count > 0) ? " (" + t.PictureTokens.Count + " picture(s))" : ""));
}
}
}
}
public void FF_BrowseTagLibAudioFiles(string path, bool fetchPicture = false, bool display = true)
{
string folder = (null == path) ? @"E:\temp\wma" : path;
string[] files = Directory.GetFiles(folder);
TagLib.File tagFile;
foreach (string file in files)
{
if (isFormatSupported(file))
{
tagFile = TagLib.File.Create(file);
if (display)
{
Console.WriteLine(tagFile.Name + "......." + tagFile.Properties.Duration + " | " + tagFile.Properties.AudioSampleRate + " (" + tagFile.Properties.AudioBitrate + " kpbs)");// + (tagFile. ? " VBR)" : ")"));
Console.WriteLine(Utils.BuildStrictLengthString("", tagFile.Name.Length, '.') + "......." + tagFile.Tag.Disc + " | " + tagFile.Tag.Track + " | " + tagFile.Tag.Title + " | " + tagFile.Tag.FirstPerformer + " | " + tagFile.Tag.Album + " | " + tagFile.Tag.Year + ((tagFile.Tag.Pictures != null && tagFile.Tag.Pictures.Length > 0) ? " (" + tagFile.Tag.Pictures.Length + " picture(s))" : ""));
}
}
}
}
}
}
| 39.466102 | 411 | 0.50977 | [
"MIT"
] | Piorosen/atldotnet | ATL.benchmark/Information/FileFinder.cs | 4,659 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Identity;
using Microsoft.EntityFrameworkCore;
using Abp.Authorization.Users;
using Abp.Domain.Services;
using Abp.IdentityFramework;
using Abp.Runtime.Session;
using Abp.UI;
using ThinkSites.Authorization.Roles;
using ThinkSites.MultiTenancy;
namespace ThinkSites.Authorization.Users
{
public class UserRegistrationManager : DomainService
{
public IAbpSession AbpSession { get; set; }
private readonly TenantManager _tenantManager;
private readonly UserManager _userManager;
private readonly RoleManager _roleManager;
private readonly IPasswordHasher<User> _passwordHasher;
public UserRegistrationManager(
TenantManager tenantManager,
UserManager userManager,
RoleManager roleManager,
IPasswordHasher<User> passwordHasher)
{
_tenantManager = tenantManager;
_userManager = userManager;
_roleManager = roleManager;
_passwordHasher = passwordHasher;
AbpSession = NullAbpSession.Instance;
}
public async Task<User> RegisterAsync(string name, string surname, string emailAddress, string userName, string plainPassword, bool isEmailConfirmed)
{
CheckForTenant();
var tenant = await GetActiveTenantAsync();
var user = new User
{
TenantId = tenant.Id,
Name = name,
Surname = surname,
EmailAddress = emailAddress,
IsActive = true,
UserName = userName,
IsEmailConfirmed = isEmailConfirmed,
Roles = new List<UserRole>()
};
user.SetNormalizedNames();
foreach (var defaultRole in await _roleManager.Roles.Where(r => r.IsDefault).ToListAsync())
{
user.Roles.Add(new UserRole(tenant.Id, user.Id, defaultRole.Id));
}
await _userManager.InitializeOptionsAsync(tenant.Id);
CheckErrors(await _userManager.CreateAsync(user, plainPassword));
await CurrentUnitOfWork.SaveChangesAsync();
return user;
}
private void CheckForTenant()
{
if (!AbpSession.TenantId.HasValue)
{
throw new InvalidOperationException("Can not register host users!");
}
}
private async Task<Tenant> GetActiveTenantAsync()
{
if (!AbpSession.TenantId.HasValue)
{
return null;
}
return await GetActiveTenantAsync(AbpSession.TenantId.Value);
}
private async Task<Tenant> GetActiveTenantAsync(int tenantId)
{
var tenant = await _tenantManager.FindByIdAsync(tenantId);
if (tenant == null)
{
throw new UserFriendlyException(L("UnknownTenantId{0}", tenantId));
}
if (!tenant.IsActive)
{
throw new UserFriendlyException(L("TenantIdIsNotActive{0}", tenantId));
}
return tenant;
}
protected virtual void CheckErrors(IdentityResult identityResult)
{
identityResult.CheckErrors(LocalizationManager);
}
}
}
| 30.610619 | 157 | 0.602775 | [
"MIT"
] | ThinkAM/ThinkSites | aspnet-core/src/ThinkSites.Core/Authorization/Users/UserRegistrationManager.cs | 3,461 | C# |
namespace Unity.VisualScripting.Community
{
[Editor(typeof(BindFuncNode))]
public sealed class BindFuncNodeEditor : BindDelegateNodeEditor<BindFuncNode, IFunc>
{
public BindFuncNodeEditor(Metadata metadata) : base(metadata)
{
}
protected override string DefaultName => "Bind";
}
} | 27.5 | 88 | 0.684848 | [
"MIT"
] | Fitz-YM/Bolt.Addons.Community | Editor/Fundamentals/Editors/Delegates/BindFuncNodeEditor.cs | 332 | C# |
using System.Linq;
using UnityEngine;
using UnityEngine.Experimental.UIElements;
namespace UnityEditor.PackageManager.UI
{
#if !UNITY_2018_3_OR_NEWER
internal class PackageManangerToolbarFactory : UxmlFactory<PackageManagerToolbar>
{
protected override PackageManagerToolbar DoCreate(IUxmlAttributes bag, CreationContext cc)
{
return new PackageManagerToolbar();
}
}
#endif
internal class PackageManagerToolbar : VisualElement
{
#if UNITY_2018_3_OR_NEWER
internal new class UxmlFactory : UxmlFactory<PackageManagerToolbar> { }
#endif
private readonly VisualElement root;
[SerializeField]
private PackageFilter selectedFilter = PackageFilter.All;
public PackageManagerToolbar()
{
root = Resources.GetTemplate("PackageManagerToolbar.uxml");
Add(root);
root.StretchToParentSize();
SetFilter(PackageCollection.Instance.Filter);
RegisterCallback<AttachToPanelEvent>(OnEnterPanel);
RegisterCallback<DetachFromPanelEvent>(OnLeavePanel);
}
public void GrabFocus()
{
SearchToolbar.GrabFocus();
}
public new void SetEnabled(bool enable)
{
base.SetEnabled(enable);
FilterButton.SetEnabled(enable);
AdvancedButton.SetEnabled(enable);
SearchToolbar.SetEnabled(enable);
}
private static string GetFilterDisplayName(PackageFilter filter)
{
switch (filter)
{
case PackageFilter.All:
return "All packages";
case PackageFilter.Local:
return "In Project";
case PackageFilter.Modules:
return "Built-in packages";
case PackageFilter.None:
return "None";
default:
return filter.ToString();
}
}
private void SetFilter(object obj)
{
var previouSelectedFilter = selectedFilter;
selectedFilter = (PackageFilter) obj;
FilterButton.text = string.Format("{0} ▾", GetFilterDisplayName(selectedFilter));
if (selectedFilter != previouSelectedFilter)
PackageCollection.Instance.SetFilter(selectedFilter);
}
private void OnFilterButtonMouseDown(MouseDownEvent evt)
{
if (evt.propagationPhase != PropagationPhase.AtTarget)
return;
var menu = new GenericMenu();
menu.AddItem(new GUIContent(GetFilterDisplayName(PackageFilter.All)),
selectedFilter == PackageFilter.All,
SetFilter, PackageFilter.All);
menu.AddItem(new GUIContent(GetFilterDisplayName(PackageFilter.Local)),
selectedFilter == PackageFilter.Local,
SetFilter, PackageFilter.Local);
menu.AddSeparator("");
menu.AddItem(new GUIContent(GetFilterDisplayName(PackageFilter.Modules)),
selectedFilter == PackageFilter.Modules,
SetFilter, PackageFilter.Modules);
var menuPosition = new Vector2(FilterButton.layout.xMin, FilterButton.layout.center.y);
menuPosition = this.LocalToWorld(menuPosition);
var menuRect = new Rect(menuPosition, Vector2.zero);
menu.DropDown(menuRect);
}
private void OnAdvancedButtonMouseDown(MouseDownEvent evt)
{
if (evt.propagationPhase != PropagationPhase.AtTarget)
return;
var menu = new GenericMenu();
menu.AddItem(new GUIContent("Show preview packages"), PackageManagerPrefs.ShowPreviewPackages, TogglePreviewPackages);
//menu.AddItem(new GUIContent("Reset to defaults"), false, ResetToDefaultsClick);
var menuPosition = new Vector2(AdvancedButton.layout.xMax + 30, AdvancedButton.layout.center.y);
menuPosition = this.LocalToWorld(menuPosition);
var menuRect = new Rect(menuPosition, Vector2.zero);
menu.DropDown(menuRect);
}
private static void TogglePreviewPackages()
{
var showPreviewPackages = PackageManagerPrefs.ShowPreviewPackages;
if (!showPreviewPackages && PackageManagerPrefs.ShowPreviewPackagesWarning)
{
const string message = "Preview packages are not verified with Unity, may be unstable, and are unsupported in production. Are you sure you want to show preview packages?";
if (!EditorUtility.DisplayDialog("", message, "Yes", "No"))
return;
PackageManagerPrefs.ShowPreviewPackagesWarning = false;
}
PackageManagerPrefs.ShowPreviewPackages = !showPreviewPackages;
PackageCollection.Instance.UpdatePackageCollection(true);
}
private void ResetToDefaultsClick()
{
if (!EditorUtility.DisplayDialog("", "Operation will reset all your packages to Editor defaults. Do you want to continue?", "Yes", "No"))
return;
// Registered on callback
AssemblyReloadEvents.beforeAssemblyReload += PackageManagerWindow.ShowPackageManagerWindow;
Client.ResetToEditorDefaults();
var windows = UnityEngine.Resources.FindObjectsOfTypeAll<PackageManagerWindow>();
if (windows.Length > 0)
{
windows[0].Close();
}
}
private void OnEnterPanel(AttachToPanelEvent evt)
{
FilterButton.RegisterCallback<MouseDownEvent>(OnFilterButtonMouseDown);
AdvancedButton.RegisterCallback<MouseDownEvent>(OnAdvancedButtonMouseDown);
}
private void OnLeavePanel(DetachFromPanelEvent evt)
{
FilterButton.UnregisterCallback<MouseDownEvent>(OnFilterButtonMouseDown);
AdvancedButton.UnregisterCallback<MouseDownEvent>(OnAdvancedButtonMouseDown);
}
private Label FilterButton { get { return root.Q<Label>("toolbarFilterButton"); } }
private Label AdvancedButton { get { return root.Q<Label>("toolbarAdvancedButton"); } }
internal PackageSearchToolbar SearchToolbar { get { return root.Q<PackageSearchToolbar>("toolbarSearch"); } }
}
} | 39.310976 | 187 | 0.629285 | [
"MIT"
] | qcoronia/a-cat-in-space-game | src/Library/PackageCache/com.unity.package-manager-ui@2.0.0-preview.7/Editor/Sources/UI/PackageManagerToolbar.cs | 6,451 | C# |
using System.Threading.Tasks;
using Altinn.Platform.Storage.Interface.Models;
namespace Altinn.Platform.Authorization.Repositories.Interface
{
/// <summary>
/// Interface for operations on instance information
/// </summary>
public interface IPolicyInformationRepository
{
/// <summary>
/// Gets the information of a given instance
/// </summary>
/// <param name="instanceId">the instance id</param>
/// <param name="instanceOwnerId">the instance owner</param>
/// <returns></returns>
Task<Instance> GetInstance(string instanceId, int instanceOwnerId);
/// <summary>
/// Gets the information of a given instance
/// </summary>
/// <param name="instanceId">the instance id</param>
/// <returns></returns>
Task<Instance> GetInstance(string instanceId);
/// <summary>
/// Gets the application information of a given instance
/// </summary>
/// <param name="app">Application identifier which is unique within an organisation.</param>
/// <param name="org">Unique identifier of the organisation responsible for the app.</param>
/// <returns></returns>
Task<Application> GetApplication(string app, string org);
}
}
| 37.028571 | 100 | 0.635031 | [
"BSD-3-Clause"
] | Altinn/altinn-studio | src/development/LocalTest/Services/Authorization/Interface/IPolicyInformationRepository.cs | 1,296 | C# |
using System;
using System.Linq;
using System.Linq.Expressions;
using System.Web.Mvc;
using Agridea.Web.Mvc.Grid;
using System.Collections.Generic;
namespace Agridea.Web.Mvc
{
public static class GridHelper
{
public static Grid<T> Grid<T>(this HtmlHelper helper)
{
return new Grid<T>(helper, helper.ViewData.Model as IQueryable<T>);
}
public static Grid<T> Grid<T>(this HtmlHelper helper, IQueryable<T> model, string bindingListName = null)
{
return new Grid<T>(helper, model, bindingListName);
}
public static Grid<T> Grid<T>(this Controller controller, IQueryable<T> model)
{
return new Grid<T>(model, controller.ViewData, controller.ControllerContext, controller.TempData);
}
public static Grid<T> Grid<TModel, T>(this HtmlHelper helper, Func<TModel, IQueryable<T>> func) where TModel : class
{
var model = (func(helper.ViewData.Model as TModel));
return new Grid<T>(helper, model);
}
public static Grid<T> Grid<TModel, T>(this HtmlHelper helper, Func<TModel, IQueryable<T>> func, Expression<Func<TModel, IList<T>>> bindingListExpression)
where TModel : class
{
var bindingListName = ExpressionHelper.GetExpressionText(bindingListExpression);
var model = (func(helper.ViewData.Model as TModel));
return new Grid<T>(helper, model, bindingListName);
}
}
}
| 37.525 | 161 | 0.646236 | [
"MIT"
] | ni11c/AkkaJobs | AgrideaCore/Web/Mvc/Grid/Fluent/GridHelper.cs | 1,503 | C# |
using System.Text.RegularExpressions;
namespace CoreRCON.Parsers.Standard
{
public class PlayerDisconnected : IParseable
{
public string Reason { get; set; }
public Player Player { get; set; }
}
public class PlayerDisconnectedParser : DefaultParser<PlayerDisconnected>
{
public override string Pattern { get; } = $"(?<Player>{playerParser.Pattern}) disconnected\\s?(\\(reason \"(?<Reason>.*)\"\\))?";
private static PlayerParser playerParser { get; } = new PlayerParser();
public override PlayerDisconnected Load(GroupCollection groups)
{
return new PlayerDisconnected
{
Player = playerParser.Parse(groups["Player"]),
Reason = groups["Reason"].Value
};
}
}
} | 32.4 | 137 | 0.611111 | [
"MIT"
] | Challengermode/CoreRcon | src/CoreRCON/Parsers/Standard/PlayerDisconnected.cs | 812 | C# |
#region
using System.Xml.Linq;
#endregion
namespace AntiShaun
{
public interface IXDocumentParserService
{
XDocument Parse(string text);
}
public class XDocumentParserService : IXDocumentParserService
{
public XDocument Parse(string text)
{
return XDocument.Parse(text);
}
}
} | 14.190476 | 62 | 0.748322 | [
"Apache-2.0"
] | EventBooking/AntiShaun | AntiShaun/IXDocumentParserService.cs | 300 | C# |
using System.Collections.Generic;
using Armory.Shared.Domain.Bus.Query;
namespace Armory.Troopers.Application.SearchAll
{
public class SearchAllTroopersQuery : Query<IEnumerable<TroopResponse>>
{
}
}
| 21.3 | 75 | 0.774648 | [
"MIT"
] | cantte/Armory.Api | src/Armory/Troopers/Application/SearchAll/SearchAllTroopersQuery.cs | 213 | C# |
using System;
using System.Diagnostics;
using System.Reflection;
using System.Runtime.Serialization;
using System.Text.RegularExpressions;
using Umbraco.Core.Models.EntityBase;
using Umbraco.Core.PropertyEditors;
using Umbraco.Core.Strings;
namespace Umbraco.Core.Models
{
/// <summary>
/// Defines the type of a <see cref="Property"/> object
/// </summary>
[Serializable]
[DataContract(IsReference = true)]
[DebuggerDisplay("Id: {Id}, Name: {Name}, Alias: {Alias}")]
public class PropertyType : Entity, IEquatable<PropertyType>
{
private readonly bool _isExplicitDbType;
private string _name;
private string _alias;
private string _description;
private int _dataTypeDefinitionId;
private Lazy<int> _propertyGroupId;
private string _propertyEditorAlias;
private DataTypeDatabaseType _dataTypeDatabaseType;
private bool _mandatory;
private string _helpText;
private int _sortOrder;
private string _validationRegExp;
public PropertyType(IDataTypeDefinition dataTypeDefinition)
{
if (dataTypeDefinition == null) throw new ArgumentNullException("dataTypeDefinition");
if(dataTypeDefinition.HasIdentity)
_dataTypeDefinitionId = dataTypeDefinition.Id;
_propertyEditorAlias = dataTypeDefinition.PropertyEditorAlias;
_dataTypeDatabaseType = dataTypeDefinition.DatabaseType;
}
public PropertyType(IDataTypeDefinition dataTypeDefinition, string propertyTypeAlias)
: this(dataTypeDefinition)
{
_alias = GetAlias(propertyTypeAlias);
}
public PropertyType(string propertyEditorAlias, DataTypeDatabaseType dataTypeDatabaseType)
: this(propertyEditorAlias, dataTypeDatabaseType, false)
{
}
public PropertyType(string propertyEditorAlias, DataTypeDatabaseType dataTypeDatabaseType, string propertyTypeAlias)
: this(propertyEditorAlias, dataTypeDatabaseType, false, propertyTypeAlias)
{
}
/// <summary>
/// Used internally to assign an explicity database type for this property type regardless of what the underlying data type/property editor is.
/// </summary>
/// <param name="propertyEditorAlias"></param>
/// <param name="dataTypeDatabaseType"></param>
/// <param name="isExplicitDbType"></param>
internal PropertyType(string propertyEditorAlias, DataTypeDatabaseType dataTypeDatabaseType, bool isExplicitDbType)
{
_isExplicitDbType = isExplicitDbType;
_propertyEditorAlias = propertyEditorAlias;
_dataTypeDatabaseType = dataTypeDatabaseType;
}
/// <summary>
/// Used internally to assign an explicity database type for this property type regardless of what the underlying data type/property editor is.
/// </summary>
/// <param name="propertyEditorAlias"></param>
/// <param name="dataTypeDatabaseType"></param>
/// <param name="isExplicitDbType"></param>
/// <param name="propertyTypeAlias"></param>
internal PropertyType(string propertyEditorAlias, DataTypeDatabaseType dataTypeDatabaseType, bool isExplicitDbType, string propertyTypeAlias)
{
_isExplicitDbType = isExplicitDbType;
_propertyEditorAlias = propertyEditorAlias;
_dataTypeDatabaseType = dataTypeDatabaseType;
_alias = GetAlias(propertyTypeAlias);
}
private static readonly Lazy<PropertySelectors> Ps = new Lazy<PropertySelectors>();
private class PropertySelectors
{
public readonly PropertyInfo NameSelector = ExpressionHelper.GetPropertyInfo<PropertyType, string>(x => x.Name);
public readonly PropertyInfo AliasSelector = ExpressionHelper.GetPropertyInfo<PropertyType, string>(x => x.Alias);
public readonly PropertyInfo DescriptionSelector = ExpressionHelper.GetPropertyInfo<PropertyType, string>(x => x.Description);
public readonly PropertyInfo DataTypeDefinitionIdSelector = ExpressionHelper.GetPropertyInfo<PropertyType, int>(x => x.DataTypeDefinitionId);
public readonly PropertyInfo PropertyEditorAliasSelector = ExpressionHelper.GetPropertyInfo<PropertyType, string>(x => x.PropertyEditorAlias);
public readonly PropertyInfo DataTypeDatabaseTypeSelector = ExpressionHelper.GetPropertyInfo<PropertyType, DataTypeDatabaseType>(x => x.DataTypeDatabaseType);
public readonly PropertyInfo MandatorySelector = ExpressionHelper.GetPropertyInfo<PropertyType, bool>(x => x.Mandatory);
public readonly PropertyInfo HelpTextSelector = ExpressionHelper.GetPropertyInfo<PropertyType, string>(x => x.HelpText);
public readonly PropertyInfo SortOrderSelector = ExpressionHelper.GetPropertyInfo<PropertyType, int>(x => x.SortOrder);
public readonly PropertyInfo ValidationRegExpSelector = ExpressionHelper.GetPropertyInfo<PropertyType, string>(x => x.ValidationRegExp);
public readonly PropertyInfo PropertyGroupIdSelector = ExpressionHelper.GetPropertyInfo<PropertyType, Lazy<int>>(x => x.PropertyGroupId);
}
/// <summary>
/// Gets of Sets the Name of the PropertyType
/// </summary>
[DataMember]
public string Name
{
get { return _name; }
set { SetPropertyValueAndDetectChanges(value, ref _name, Ps.Value.NameSelector); }
}
/// <summary>
/// Gets of Sets the Alias of the PropertyType
/// </summary>
[DataMember]
public string Alias
{
get { return _alias; }
set { SetPropertyValueAndDetectChanges(GetAlias(value), ref _alias, Ps.Value.AliasSelector); }
}
/// <summary>
/// Gets of Sets the Description for the PropertyType
/// </summary>
[DataMember]
public string Description
{
get { return _description; }
set { SetPropertyValueAndDetectChanges(value, ref _description, Ps.Value.DescriptionSelector); }
}
/// <summary>
/// Gets of Sets the Id of the DataType (Definition), which the PropertyType is "wrapping"
/// </summary>
/// <remarks>This is actually the Id of the <see cref="IDataTypeDefinition"/></remarks>
[DataMember]
public int DataTypeDefinitionId
{
get { return _dataTypeDefinitionId; }
set { SetPropertyValueAndDetectChanges(value, ref _dataTypeDefinitionId, Ps.Value.DataTypeDefinitionIdSelector); }
}
[DataMember]
public string PropertyEditorAlias
{
get { return _propertyEditorAlias; }
set { SetPropertyValueAndDetectChanges(value, ref _propertyEditorAlias, Ps.Value.PropertyEditorAliasSelector); }
}
/// <summary>
/// Gets of Sets the Id of the DataType control
/// </summary>
/// <remarks>This is the Id of the actual DataType control</remarks>
[Obsolete("Property editor's are defined by a string alias from version 7 onwards, use the PropertyEditorAlias property instead. This method will return a generated GUID for any property editor alias not explicitly mapped to a legacy ID")]
public Guid DataTypeId
{
get
{
return LegacyPropertyEditorIdToAliasConverter.GetLegacyIdFromAlias(
_propertyEditorAlias, LegacyPropertyEditorIdToAliasConverter.NotFoundLegacyIdResponseBehavior.GenerateId).Value;
}
set
{
var alias = LegacyPropertyEditorIdToAliasConverter.GetAliasFromLegacyId(value, true);
PropertyEditorAlias = alias;
}
}
/// <summary>
/// Gets or Sets the DatabaseType for which the DataType's value is saved as
/// </summary>
[DataMember]
internal DataTypeDatabaseType DataTypeDatabaseType
{
get { return _dataTypeDatabaseType; }
set
{
//don't allow setting this if an explicit declaration has been made in the ctor
if (_isExplicitDbType) return;
SetPropertyValueAndDetectChanges(value, ref _dataTypeDatabaseType, Ps.Value.DataTypeDatabaseTypeSelector);
}
}
/// <summary>
/// Gets or sets the identifier of the PropertyGroup this PropertyType belongs to.
/// </summary>
/// <remarks>For generic properties, the value is <c>null</c>.</remarks>
[DataMember]
internal Lazy<int> PropertyGroupId
{
get { return _propertyGroupId; }
set { SetPropertyValueAndDetectChanges(value, ref _propertyGroupId, Ps.Value.PropertyGroupIdSelector); }
}
/// <summary>
/// Gets of Sets the Boolean indicating whether a value for this PropertyType is required
/// </summary>
[DataMember]
public bool Mandatory
{
get { return _mandatory; }
set { SetPropertyValueAndDetectChanges(value, ref _mandatory, Ps.Value.MandatorySelector); }
}
/// <summary>
/// Gets of Sets the Help text for the current PropertyType
/// </summary>
[DataMember]
[Obsolete("Not used anywhere, will be removed in future versions")]
public string HelpText
{
get { return _helpText; }
set { SetPropertyValueAndDetectChanges(value, ref _helpText, Ps.Value.HelpTextSelector); }
}
/// <summary>
/// Gets of Sets the Sort order of the PropertyType, which is used for sorting within a group
/// </summary>
[DataMember]
public int SortOrder
{
get { return _sortOrder; }
set { SetPropertyValueAndDetectChanges(value, ref _sortOrder, Ps.Value.SortOrderSelector); }
}
/// <summary>
/// Gets or Sets the RegEx for validation of legacy DataTypes
/// </summary>
[DataMember]
public string ValidationRegExp
{
get { return _validationRegExp; }
set { SetPropertyValueAndDetectChanges(value, ref _validationRegExp, Ps.Value.ValidationRegExpSelector); }
}
private string GetAlias(string value)
{
//NOTE: WE are doing this because we don't want to do a ToSafeAlias when the alias is the special case of
// being prefixed with Constants.PropertyEditors.InternalGenericPropertiesPrefix
// which is used internally
return value.StartsWith(Constants.PropertyEditors.InternalGenericPropertiesPrefix)
? value
: value.ToCleanString(CleanStringType.Alias | CleanStringType.UmbracoCase);
}
/// <summary>
/// Create a new Property object from a "raw" database value.
/// </summary>
/// <remarks>Can be used for the "old" values where no serialization type exists</remarks>
/// <param name="value"></param>
/// <param name="version"> </param>
/// <param name="id"> </param>
/// <returns></returns>
internal Property CreatePropertyFromRawValue(object value, Guid version, int id)
{
return new Property(id, version, this, value);
}
/// <summary>
/// Create a new Property object from a "raw" database value.
/// In some cases the value will need to be deserialized.
/// </summary>
/// <param name="value"></param>
/// <param name="serializationType"> </param>
/// <returns></returns>
internal Property CreatePropertyFromRawValue(object value, string serializationType)
{
//The value from the db needs to be deserialized and then added to the property
//if its not a simple type (Integer, Date, Nvarchar, Ntext)
/*if (DataTypeDatabaseType == DataTypeDatabaseType.Object)
{
Type type = Type.GetType(serializationType);
var stream = new MemoryStream(Encoding.UTF8.GetBytes(value.ToString()));
var objValue = _service.FromStream(stream, type);
return new Property(this, objValue);
}*/
return new Property(this, value);
}
/// <summary>
/// Create a new Property object that conforms to the Type of the DataType
/// and can be validated according to DataType validation / Mandatory-check.
/// </summary>
/// <param name="value"></param>
/// <returns></returns>
public Property CreatePropertyFromValue(object value)
{
//Note that validation will occur when setting the value on the Property
return new Property(this, value);
}
/// <summary>
/// Gets a value indicating whether the value is of the expected type
/// for the property, and can be assigned to the property "as is".
/// </summary>
/// <param name="value">The value.</param>
/// <returns>True if the value is of the expected type for the property,
/// and can be assigned to the property "as is". Otherwise, false, to indicate
/// that some conversion is required.</returns>
public bool IsPropertyTypeValid(object value)
{
// null values are assumed to be ok
if (value == null)
return true;
// check if the type of the value matches the type from the DataType/PropertyEditor
var valueType = value.GetType();
//TODO Add PropertyEditor Type validation when its relevant to introduce
/*bool isEditorModel = value is IEditorModel;
if (isEditorModel && DataTypeControlId != Guid.Empty)
{
//Find PropertyEditor by Id
var propertyEditor = PropertyEditorResolver.Current.GetById(DataTypeControlId);
if (propertyEditor == null)
return false;//Throw exception instead?
//Get the generic parameter of the PropertyEditor and check it against the type of the passed in (object) value
Type argument = propertyEditor.GetType().BaseType.GetGenericArguments()[0];
return argument == type;
}*/
if (PropertyEditorAlias.IsNullOrWhiteSpace() == false) // fixme - always true?
{
// simple validation using the DatabaseType from the DataTypeDefinition
// and the Type of the passed in value
switch (DataTypeDatabaseType)
{
// fixme breaking!
case DataTypeDatabaseType.Integer:
return valueType == typeof(int);
case DataTypeDatabaseType.Decimal:
return valueType == typeof(decimal);
case DataTypeDatabaseType.Date:
return valueType == typeof(DateTime);
case DataTypeDatabaseType.Nvarchar:
return valueType == typeof(string);
case DataTypeDatabaseType.Ntext:
return valueType == typeof(string);
}
}
// fixme - never reached + makes no sense?
// fallback for simple value types when no Control Id or Database Type is set
if (valueType.IsPrimitive || value is string)
return true;
return false;
}
/// <summary>
/// Validates the Value from a Property according to the validation settings
/// </summary>
/// <param name="value"></param>
/// <returns>True if valid, otherwise false</returns>
public bool IsPropertyValueValid(object value)
{
//If the Property is mandatory and value is null or empty, return false as the validation failed
if (Mandatory && (value == null || string.IsNullOrEmpty(value.ToString())))
return false;
//Check against Regular Expression for Legacy DataTypes - Validation exists and value is not null:
if(string.IsNullOrEmpty(ValidationRegExp) == false && (value != null && string.IsNullOrEmpty(value.ToString()) == false))
{
try
{
var regexPattern = new Regex(ValidationRegExp);
return regexPattern.IsMatch(value.ToString());
}
catch
{
throw new Exception(string .Format("Invalid validation expression on property {0}",this.Alias));
}
}
//TODO: We must ensure that the property value can actually be saved based on the specified database type
//TODO Add PropertyEditor validation when its relevant to introduce
/*if (value is IEditorModel && DataTypeControlId != Guid.Empty)
{
//Find PropertyEditor by Id
var propertyEditor = PropertyEditorResolver.Current.GetById(DataTypeControlId);
//TODO Get the validation from the PropertyEditor if a validation attribute exists
//Will probably need to reflect the PropertyEditor in order to apply the validation
}*/
return true;
}
public bool Equals(PropertyType other)
{
if (base.Equals(other)) return true;
//Check whether the PropertyType's properties are equal.
return Alias.InvariantEquals(other.Alias);
}
public override int GetHashCode()
{
//Get hash code for the Name field if it is not null.
int baseHash = base.GetHashCode();
//Get hash code for the Alias field.
int hashAlias = Alias.ToLowerInvariant().GetHashCode();
//Calculate the hash code for the product.
return baseHash ^ hashAlias;
}
public override object DeepClone()
{
var clone = (PropertyType)base.DeepClone();
//turn off change tracking
clone.DisableChangeTracking();
//need to manually assign the Lazy value as it will not be automatically mapped
if (PropertyGroupId != null)
{
clone._propertyGroupId = new Lazy<int>(() => PropertyGroupId.Value);
}
//this shouldn't really be needed since we're not tracking
clone.ResetDirtyProperties(false);
//re-enable tracking
clone.EnableChangeTracking();
return clone;
}
}
}
| 44.284738 | 248 | 0.60357 | [
"MIT"
] | AzzA-D/Umbraco-CMS | src/Umbraco.Core/Models/PropertyType.cs | 19,443 | C# |
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Threading.Tasks;
namespace FlowrouteApi.DataModels
{
[Table("Role")]
public class Role
{
[Key, Required]
public int Id { get; set; }
[Required]
public string Name { get; set; }
public virtual ICollection<UserRole> UserRoles { get; set; }
}
}
| 22.727273 | 69 | 0.652 | [
"MIT"
] | mws-dev/flowroute-api-email-text | src/FlowrouteApi/DataModels/Role.cs | 502 | C# |
using BooksApp.Services;
using BooksApp.Views;
using BooksLib.Services;
using Framework.Services;
using Framework.ViewModels;
using System;
using System.Collections.Generic;
using Windows.UI.Xaml.Controls;
namespace BooksApp.ViewModels
{
public class MainPageViewModel : ViewModelBase
{
private Dictionary<string, Type> _pages = new Dictionary<string, Type>
{
[PageNames.BooksPage] = typeof(BooksPage),
[PageNames.BookDetailPage] = typeof(BookDetailPage)
};
private readonly INavigationService _navigationService;
private readonly UWPInitializeNavigationService _initializeNavigationService;
public MainPageViewModel(INavigationService navigationService, UWPInitializeNavigationService initializeNavigationService)
{
_navigationService = navigationService ?? throw new ArgumentNullException(nameof(navigationService));
_initializeNavigationService = initializeNavigationService ?? throw new ArgumentNullException(nameof(initializeNavigationService));
}
public void SetNavigationFrame(Frame frame) => _initializeNavigationService.Initialize(frame, _pages);
public void UseNavigation(bool navigation)
{
_navigationService.UseNavigation = navigation;
}
public void OnNavigationSelectionChanged(NavigationView sender, NavigationViewSelectionChangedEventArgs args)
{
if (args.SelectedItem is NavigationViewItem navigationItem)
{
switch (navigationItem.Tag)
{
case "books":
_navigationService.NavigateToAsync(PageNames.BooksPage);
break;
default:
break;
}
}
}
}
}
| 36.313725 | 143 | 0.665767 | [
"MIT"
] | Bazzaware/ProfessionalCSharp7 | Patterns/BooksSample/BooksApp/ViewModels/MainPageViewModel.cs | 1,854 | C# |
// ------------------------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License in the project root for license information.
// ------------------------------------------------------------------------------
// **NOTE** This file was generated by a tool and any changes will be overwritten.
// <auto-generated/>
// Template Source: Templates\CSharp\Model\ComplexType.cs.tt
namespace Microsoft.Graph
{
using System;
using System.Collections.Generic;
using System.IO;
using System.Runtime.Serialization;
using Newtonsoft.Json;
/// <summary>
/// The type TeleconferenceDeviceVideoQuality.
/// </summary>
[JsonObject(MemberSerialization = MemberSerialization.OptIn)]
public partial class TeleconferenceDeviceVideoQuality : TeleconferenceDeviceMediaQuality
{
/// <summary>
/// Initializes a new instance of the <see cref="TeleconferenceDeviceVideoQuality"/> class.
/// </summary>
public TeleconferenceDeviceVideoQuality()
{
this.ODataType = "microsoft.graph.teleconferenceDeviceVideoQuality";
}
/// <summary>
/// Gets or sets averageInboundBitRate.
/// The average inbound stream video bit rate per second.
/// </summary>
[JsonProperty(NullValueHandling = NullValueHandling.Ignore, PropertyName = "averageInboundBitRate", Required = Newtonsoft.Json.Required.Default)]
public double? AverageInboundBitRate { get; set; }
/// <summary>
/// Gets or sets averageInboundFrameRate.
/// The average inbound stream video frame rate per second.
/// </summary>
[JsonProperty(NullValueHandling = NullValueHandling.Ignore, PropertyName = "averageInboundFrameRate", Required = Newtonsoft.Json.Required.Default)]
public double? AverageInboundFrameRate { get; set; }
/// <summary>
/// Gets or sets averageOutboundBitRate.
/// The average outbound stream video bit rate per second.
/// </summary>
[JsonProperty(NullValueHandling = NullValueHandling.Ignore, PropertyName = "averageOutboundBitRate", Required = Newtonsoft.Json.Required.Default)]
public double? AverageOutboundBitRate { get; set; }
/// <summary>
/// Gets or sets averageOutboundFrameRate.
/// The average outbound stream video frame rate per second.
/// </summary>
[JsonProperty(NullValueHandling = NullValueHandling.Ignore, PropertyName = "averageOutboundFrameRate", Required = Newtonsoft.Json.Required.Default)]
public double? AverageOutboundFrameRate { get; set; }
}
}
| 44.33871 | 156 | 0.641688 | [
"MIT"
] | andrueastman/msgraph-sdk-dotnet | src/Microsoft.Graph/Generated/model/TeleconferenceDeviceVideoQuality.cs | 2,749 | C# |
using AutoMapper;
using Checklist.Application.Common.Exceptions;
using Checklist.Application.Common.Interfaces;
using Checklist.Domain.Entities;
using MediatR;
namespace Checklist.Application.UseCases.Items.Commands;
public class UpdateItemCommand : IRequest<Item>
{
public int Id { get; set; }
public string? Name { get; set; }
}
public class UpdateTodoHandler : IRequestHandler<UpdateItemCommand, Item>
{
private readonly IMapper _mapper;
private readonly IItemRepository _itemRepository;
public UpdateTodoHandler(IItemRepository itemRepository, IMapper mapper)
{
_itemRepository = itemRepository;
_mapper = mapper;
}
public async Task<Item> Handle(UpdateItemCommand request, CancellationToken cancellationToken)
{
var isItem = await _itemRepository.GetByIdAsync(request.Id);
if (isItem == null) throw new ApiException("Item Not Found.");
var item = _mapper.Map<Item>(request);
return await _itemRepository.UpdateAsync(item);
}
} | 30.264706 | 98 | 0.735666 | [
"MIT"
] | emmysteven/checklist | src/Application/UseCases/Items/Commands/UpdateItemCommand.cs | 1,029 | C# |
// *** WARNING: this file was generated by the Pulumi SDK Generator. ***
// *** Do not edit by hand unless you're certain you know what you are doing! ***
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Threading.Tasks;
using Pulumi.Serialization;
namespace Pulumi.AzureNextGen.Compute.V20160330.Inputs
{
/// <summary>
/// The API entity reference.
/// </summary>
public sealed class ApiEntityReferenceArgs : Pulumi.ResourceArgs
{
/// <summary>
/// The ARM resource id in the form of /subscriptions/{SubscriptionId}/resourceGroups/{ResourceGroupName}/...
/// </summary>
[Input("id")]
public Input<string>? Id { get; set; }
public ApiEntityReferenceArgs()
{
}
}
}
| 27.724138 | 117 | 0.652985 | [
"Apache-2.0"
] | pulumi/pulumi-azure-nextgen | sdk/dotnet/Compute/V20160330/Inputs/ApiEntityReferenceArgs.cs | 804 | 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.Net.WebSockets;
using System.Security.Principal;
using System.Threading.Tasks;
namespace System.Net
{
public sealed unsafe partial class HttpListenerContext
{
private HttpListenerRequest _request;
private HttpListenerResponse _response;
private IPrincipal _user;
private HttpConnection _connection;
private string _error;
private int _err_status = 400;
internal HttpListener Listener;
internal HttpListenerContext(HttpConnection cnc)
{
_connection = cnc;
_request = new HttpListenerRequest(this);
_response = new HttpListenerResponse(this);
}
internal int ErrorStatus
{
get { return _err_status; }
set { _err_status = value; }
}
internal string ErrorMessage
{
get { return _error; }
set { _error = value; }
}
internal bool HaveError
{
get { return (_error != null); }
}
internal HttpConnection Connection
{
get { return _connection; }
}
public HttpListenerRequest Request
{
get { return _request; }
}
public HttpListenerResponse Response
{
get { return _response; }
}
public IPrincipal User
{
get { return _user; }
}
internal void ParseAuthentication(AuthenticationSchemes expectedSchemes)
{
if (expectedSchemes == AuthenticationSchemes.Anonymous)
return;
string header = _request.Headers[HttpHeaderStrings.Authorization];
if (header == null || header.Length < 2)
return;
string[] authenticationData = header.Split(new char[] { ' ' }, 2);
if (string.Compare(authenticationData[0], AuthenticationTypes.Basic, true) == 0)
{
_user = ParseBasicAuthentication(authenticationData[1]);
}
}
internal IPrincipal ParseBasicAuthentication(string authData)
{
try
{
// Basic AUTH Data is a formatted Base64 String
string user = null;
string password = null;
int pos = -1;
string authString = Text.Encoding.Default.GetString(Convert.FromBase64String(authData));
// The format is DOMAIN\username:password
// Domain is optional
pos = authString.IndexOf(':');
// parse the password off the end
password = authString.Substring(pos + 1);
// discard the password
authString = authString.Substring(0, pos);
// check if there is a domain
pos = authString.IndexOf('\\');
if (pos > 0)
{
user = authString.Substring(pos);
}
else
{
user = authString;
}
HttpListenerBasicIdentity identity = new HttpListenerBasicIdentity(user, password);
return new GenericPrincipal(identity, new string[0]);
}
catch (Exception)
{
// Invalid auth data is swallowed silently
return null;
}
}
public Task<HttpListenerWebSocketContext> AcceptWebSocketAsync(string subProtocol)
{
throw new NotImplementedException();
}
public Task<HttpListenerWebSocketContext> AcceptWebSocketAsync(string subProtocol, TimeSpan keepAliveInterval)
{
throw new NotImplementedException();
}
public Task<HttpListenerWebSocketContext> AcceptWebSocketAsync(string subProtocol, int receiveBufferSize, TimeSpan keepAliveInterval)
{
throw new NotImplementedException();
}
public Task<HttpListenerWebSocketContext> AcceptWebSocketAsync(string subProtocol, int receiveBufferSize, TimeSpan keepAliveInterval, ArraySegment<byte> internalBuffer)
{
throw new NotImplementedException();
}
}
}
| 30.875862 | 176 | 0.569131 | [
"MIT"
] | FrancisFYK/corefx | src/System.Net.HttpListener/src/System/Net/Unix/HttpListenerContext.Unix.cs | 4,477 | C# |
// Copyright © Tanner Gooding and Contributors. Licensed under the MIT License (MIT). See License.md in the repository root for more information.
// Ported from um/ShObjIdl_core.h in the Windows SDK for Windows 10.0.22000.0
// Original source is Copyright © Microsoft. All rights reserved.
using NUnit.Framework;
using System;
using System.Runtime.InteropServices;
using static TerraFX.Interop.Windows.IID;
namespace TerraFX.Interop.Windows.UnitTests;
/// <summary>Provides validation of the <see cref="ISharingConfigurationManager" /> struct.</summary>
public static unsafe partial class ISharingConfigurationManagerTests
{
/// <summary>Validates that the <see cref="Guid" /> of the <see cref="ISharingConfigurationManager" /> struct is correct.</summary>
[Test]
public static void GuidOfTest()
{
Assert.That(typeof(ISharingConfigurationManager).GUID, Is.EqualTo(IID_ISharingConfigurationManager));
}
/// <summary>Validates that the <see cref="ISharingConfigurationManager" /> struct is blittable.</summary>
[Test]
public static void IsBlittableTest()
{
Assert.That(Marshal.SizeOf<ISharingConfigurationManager>(), Is.EqualTo(sizeof(ISharingConfigurationManager)));
}
/// <summary>Validates that the <see cref="ISharingConfigurationManager" /> struct has the right <see cref="LayoutKind" />.</summary>
[Test]
public static void IsLayoutSequentialTest()
{
Assert.That(typeof(ISharingConfigurationManager).IsLayoutSequential, Is.True);
}
/// <summary>Validates that the <see cref="ISharingConfigurationManager" /> struct has the correct size.</summary>
[Test]
public static void SizeOfTest()
{
if (Environment.Is64BitProcess)
{
Assert.That(sizeof(ISharingConfigurationManager), Is.EqualTo(8));
}
else
{
Assert.That(sizeof(ISharingConfigurationManager), Is.EqualTo(4));
}
}
}
| 38.352941 | 145 | 0.713701 | [
"MIT"
] | reflectronic/terrafx.interop.windows | tests/Interop/Windows/Windows/um/ShObjIdl_core/ISharingConfigurationManagerTests.cs | 1,958 | 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.Nsxt.Inputs
{
public sealed class PolicyGatewayPrefixListPrefixGetArgs : Pulumi.ResourceArgs
{
[Input("action")]
public Input<string>? Action { get; set; }
[Input("ge")]
public Input<int>? Ge { get; set; }
[Input("le")]
public Input<int>? Le { get; set; }
[Input("network")]
public Input<string>? Network { get; set; }
public PolicyGatewayPrefixListPrefixGetArgs()
{
}
}
}
| 25.3125 | 88 | 0.635802 | [
"ECL-2.0",
"Apache-2.0"
] | nvpnathan/pulumi-nsxt | sdk/dotnet/Inputs/PolicyGatewayPrefixListPrefixGetArgs.cs | 810 | C# |
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using Microsoft.CodeAnalysis.Diagnostics;
using Microsoft.CodeAnalysis.UnitTests;
namespace System.Runtime.Analyzers.UnitTests
{
public class SpecifyStringComparisonTests : DiagnosticAnalyzerTestBase
{
protected override DiagnosticAnalyzer GetBasicDiagnosticAnalyzer()
{
return new BasicSpecifyStringComparisonAnalyzer();
}
protected override DiagnosticAnalyzer GetCSharpDiagnosticAnalyzer()
{
return new CSharpSpecifyStringComparisonAnalyzer();
}
}
} | 34.95 | 160 | 0.736767 | [
"Apache-2.0"
] | jcouv/roslyn-analyzers | src/System.Runtime.Analyzers/UnitTests/SpecifyStringComparisonTests.cs | 699 | C# |
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace MasterChefInfo
{
/// <summary>
/// Classe du chef de section
/// </summary>
class SectionChef : ISubject
{
List<IObserver> observers;
public bool isAvailable { get; set; }
public int ID;
public SectionChef(int ID)
{
observers = new List<IObserver>();
isAvailable = true;
this.ID = ID;
}
public void RegisterObserver(IObserver observer)
{
observers.Add(observer);
}
public void UnregisterObserver(IObserver observer)
{
observers.Remove(observer);
}
public void NotifyObservers(List<Point> track)
{
foreach (IObserver observer in observers)
{
observer.Update("sectionChef", ID, track);
}
}
public void NotifyObservers(List<Point> track, Table table)
{
throw new NotImplementedException();
}
public void NotifyObservers(Table table, string type)
{
throw new NotImplementedException();
}
}
}
| 22.732143 | 67 | 0.564022 | [
"MIT"
] | HugoLA1/Projet-programmation-systeme | MasterChefInfo/MasterChefInfo/Model/Kitchen/SectionChef.cs | 1,275 | C# |
using System.Data;
using System.Data.Common;
namespace FluentData.Providers.Common
{
internal class ConnectionFactory
{
public static IDbConnection CreateConnection(string providerName, string connectionString)
{
var factory = DbProviderFactories.GetFactory(providerName);
var connection = factory.CreateConnection();
connection.ConnectionString = connectionString;
return connection;
}
}
}
| 23.055556 | 92 | 0.785542 | [
"MIT"
] | shuaiagain/orm-fluentdata | FluentData/sourceCode/sourceCode/Source/Main/FluentData/Providers/Common/ConnectionFactory.cs | 417 | C# |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System;
using System.Collections.Generic;
using Microsoft.AspNetCore.Mvc.ModelBinding;
using Microsoft.AspNetCore.Mvc.Rendering;
using Microsoft.AspNetCore.Mvc.ViewFeatures;
using Xunit;
namespace Microsoft.AspNetCore.Mvc.Core;
public class HtmlHelperListBoxExtensionsTest
{
private static readonly List<SelectListItem> BasicSelectList = new List<SelectListItem>
{
new SelectListItem("Zero", "0"),
new SelectListItem("One", "1"),
new SelectListItem("Two", "2"),
new SelectListItem("Three", "3"),
};
[Fact]
public void ListBox_FindsSelectList()
{
// Arrange
var expectedHtml = "<select id=\"HtmlEncode[[Property1]]\" multiple=\"HtmlEncode[[multiple]]\" name=\"HtmlEncode[[Property1]]\">" +
"<option value=\"HtmlEncode[[0]]\">HtmlEncode[[Zero]]</option>" + Environment.NewLine +
"<option value=\"HtmlEncode[[1]]\">HtmlEncode[[One]]</option>" + Environment.NewLine +
"<option selected=\"HtmlEncode[[selected]]\" value=\"HtmlEncode[[2]]\">HtmlEncode[[Two]]</option>" + Environment.NewLine +
"<option value=\"HtmlEncode[[3]]\">HtmlEncode[[Three]]</option>" + Environment.NewLine +
"</select>";
var metadataProvider = new EmptyModelMetadataProvider();
var helper = DefaultTemplatesUtilities.GetHtmlHelper(new ViewDataDictionary<TestModel>(metadataProvider));
helper.ViewContext.ClientValidationEnabled = false;
helper.ViewData.ModelState.SetModelValue("Property1", 2, "2");
helper.ViewData["Property1"] = BasicSelectList;
// Act
var listBoxResult = helper.ListBox("Property1");
// Assert
Assert.Equal(expectedHtml, HtmlContentUtilities.HtmlContentToString(listBoxResult));
}
[Fact]
public void ListBox_UsesSpecifiedExpressionAndSelectList()
{
// Arrange
var expectedHtml = "<select id=\"HtmlEncode[[Property3]]\" multiple=\"HtmlEncode[[multiple]]\" name=\"HtmlEncode[[Property3]]\">" +
"<option selected=\"HtmlEncode[[selected]]\" value=\"HtmlEncode[[4]]\">HtmlEncode[[Four]]</option>" + Environment.NewLine +
"<option value=\"HtmlEncode[[5]]\">HtmlEncode[[Five]]</option>" + Environment.NewLine +
"</select>";
var selectList = new List<SelectListItem>
{
new SelectListItem("Four", "4"),
new SelectListItem("Five", "5"),
};
var metadataProvider = new EmptyModelMetadataProvider();
var helper = DefaultTemplatesUtilities.GetHtmlHelper(new ViewDataDictionary<TestModel>(metadataProvider));
helper.ViewContext.ClientValidationEnabled = false;
helper.ViewData.Model = new TestModel { Property3 = new List<string> { "4" } };
// Act
var listBoxResult = helper.ListBox("Property3", selectList);
// Assert
Assert.Equal(expectedHtml, HtmlContentUtilities.HtmlContentToString(listBoxResult));
}
[Fact]
public void ListBox_UsesSpecifiedSelectExpressionAndListAndHtmlAttributes()
{
// Arrange
var expectedHtml = "<select id=\"HtmlEncode[[Property2]]\" Key=\"HtmlEncode[[Value]]\" multiple=\"HtmlEncode[[multiple]]\" name=\"HtmlEncode[[Property2]]\">" +
"<option value=\"HtmlEncode[[4]]\">HtmlEncode[[Four]]</option>" + Environment.NewLine +
"<option selected=\"HtmlEncode[[selected]]\" value=\"HtmlEncode[[5]]\">HtmlEncode[[Five]]</option>" + Environment.NewLine +
"</select>";
var selectList = new List<SelectListItem>
{
new SelectListItem("Four", "4"),
new SelectListItem("Five", "5"),
};
var metadataProvider = new EmptyModelMetadataProvider();
var helper = DefaultTemplatesUtilities.GetHtmlHelper(new ViewDataDictionary<TestModel>(metadataProvider));
helper.ViewContext.ClientValidationEnabled = false;
helper.ViewData["Property2"] = new List<string> { "1", "2", "5" };
// Act
var listBoxResult = helper.ListBox("Property2", selectList, new { Key = "Value", name = "CustomName" });
// Assert
Assert.Equal(expectedHtml, HtmlContentUtilities.HtmlContentToString(listBoxResult));
}
[Fact]
public void ListBoxFor_NullSelectListFindsListFromViewData()
{
// Arrange
var expectedHtml = "<select id=\"HtmlEncode[[Property1]]\" multiple=\"HtmlEncode[[multiple]]\" name=\"HtmlEncode[[Property1]]\">" +
"<option value=\"HtmlEncode[[0]]\">HtmlEncode[[Zero]]</option>" + Environment.NewLine +
"<option value=\"HtmlEncode[[1]]\">HtmlEncode[[One]]</option>" + Environment.NewLine +
"<option value=\"HtmlEncode[[2]]\">HtmlEncode[[Two]]</option>" + Environment.NewLine +
"<option value=\"HtmlEncode[[3]]\">HtmlEncode[[Three]]</option>" + Environment.NewLine +
"</select>";
var metadataProvider = new EmptyModelMetadataProvider();
var helper = DefaultTemplatesUtilities.GetHtmlHelper(new ViewDataDictionary<TestModel>(metadataProvider));
helper.ViewContext.ClientValidationEnabled = false;
helper.ViewData["Property1"] = BasicSelectList;
// Act
var listBoxForResult = helper.ListBoxFor(m => m.Property1, null);
// Assert
Assert.Equal(expectedHtml, HtmlContentUtilities.HtmlContentToString(listBoxForResult));
}
[Fact]
public void ListBoxFor_UsesSpecifiedExpressionAndSelectList()
{
// Arrange
var expectedHtml = "<select id=\"HtmlEncode[[Property3]]\" multiple=\"HtmlEncode[[multiple]]\" name=\"HtmlEncode[[Property3]]\">" +
"<option selected=\"HtmlEncode[[selected]]\" value=\"HtmlEncode[[4]]\">HtmlEncode[[Four]]</option>" + Environment.NewLine +
"<option selected=\"HtmlEncode[[selected]]\" value=\"HtmlEncode[[5]]\">HtmlEncode[[Five]]</option>" + Environment.NewLine +
"</select>";
var selectList = new List<SelectListItem>
{
new SelectListItem("Four", "4"),
new SelectListItem("Five", "5"),
};
var metadataProvider = new EmptyModelMetadataProvider();
var helper = DefaultTemplatesUtilities.GetHtmlHelper(new ViewDataDictionary<TestModel>(metadataProvider));
helper.ViewContext.ClientValidationEnabled = false;
helper.ViewData.Model = new TestModel { Property3 = new List<string> { "0", "4", "5" } };
// Act
var listBoxForResult = helper.ListBoxFor(m => m.Property3, selectList);
// Assert
Assert.Equal(expectedHtml, HtmlContentUtilities.HtmlContentToString(listBoxForResult));
}
[Fact]
public void ListBoxFor_UsesSpecifiedExpressionAndSelectListAndHtmlAttributes()
{
// Arrange
var expectedHtml = "<select id=\"HtmlEncode[[Property3]]\" Key=\"HtmlEncode[[Value]]\" multiple=\"HtmlEncode[[multiple]]\" name=\"HtmlEncode[[Property3]]\">" +
"<option value=\"HtmlEncode[[4]]\">HtmlEncode[[Four]]</option>" + Environment.NewLine +
"<option value=\"HtmlEncode[[5]]\">HtmlEncode[[Five]]</option>" + Environment.NewLine +
"</select>";
var selectList = new List<SelectListItem>
{
new SelectListItem("Four", "4"),
new SelectListItem("Five", "5"),
};
var metadataProvider = new EmptyModelMetadataProvider();
var helper = DefaultTemplatesUtilities.GetHtmlHelper(new ViewDataDictionary<TestModel>(metadataProvider));
helper.ViewContext.ClientValidationEnabled = false;
helper.ViewData["Property3"] = new List<string> { "0", "2" };
// Act
var listBoxForResult = helper.ListBoxFor(m => m.Property3, selectList, new { Key = "Value", name = "CustomName" });
// Assert
Assert.Equal(expectedHtml, HtmlContentUtilities.HtmlContentToString(listBoxForResult));
}
private class TestModel
{
public int Property1 { get; set; }
public string Property2 { get; set; }
public List<string> Property3 { get; set; }
}
}
| 47.101695 | 167 | 0.638839 | [
"MIT"
] | AndrewTriesToCode/aspnetcore | src/Mvc/Mvc.ViewFeatures/test/Rendering/HtmlHelperListBoxExtensionsTest.cs | 8,339 | C# |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Events;
using UnityStandardAssets.CrossPlatformInput;
using RedRunner.Utilities;
using System;
namespace RedRunner.Characters
{
public class RedCharacter : Character
{
public override event DeadHandler OnDead;
#region Public Methods
public virtual void PlayFootstepSound ()
{
if ( m_GroundCheck.IsGrounded )
{
AudioManager.Singleton.PlayFootstepSound ( m_FootstepAudioSource, ref m_CurrentFootstepSoundIndex );
}
}
public override void Move ( float horizontalAxis )
{
if ( !m_IsDead )
{
float speed = m_CurrentRunSpeed * (m_GroundCheck.IsSnow ? m_snowSpeed : 1.0f);
// if ( CrossPlatformInputManager.GetButton ( "Walk" ) )
// {
// speed = m_WalkSpeed;
// }
Vector2 velocity = m_Rigidbody2D.velocity;
velocity.x = speed * horizontalAxis;
m_Rigidbody2D.velocity = velocity;
if ( horizontalAxis > 0f )
{
Vector3 scale = transform.localScale;
scale.x = Mathf.Sign ( horizontalAxis );
transform.localScale = scale;
}
else if ( horizontalAxis < 0f )
{
Vector3 scale = transform.localScale;
scale.x = Mathf.Sign ( horizontalAxis );
transform.localScale = scale;
}
}
}
public override void Jump ()
{
if ( !m_IsDead )
{
if ( m_GroundCheck.IsGrounded )
{
Vector2 velocity = m_Rigidbody2D.velocity;
velocity.y = m_JumpStrength;
m_Rigidbody2D.velocity = velocity;
m_Animator.ResetTrigger ( "Jump" );
m_Animator.SetTrigger ( "Jump" );
m_JumpParticleSystem.Play ();
AudioManager.Singleton.PlayJumpSound ( m_JumpAndGroundedAudioSource );
}
}
}
public override void Die ()
{
Die ( false );
}
public override void Die ( bool blood )
{
if ( !m_IsDead )
{
if ( OnDead != null )
{
OnDead ();
}
m_IsDead = true;
m_Skeleton.SetActive ( true, m_Rigidbody2D.velocity );
if ( blood )
{
ParticleSystem particle = Instantiate<ParticleSystem> (
m_BloodParticleSystem,
transform.position,
Quaternion.identity );
var main = particle.main;
main.startColor = m_Color;
particle.GetComponent<Rigidbody2D>().velocity = m_Rigidbody2D.velocity * 0.5f;
Destroy ( particle.gameObject, particle.main.duration );
}
m_OnCharacterDead.Invoke ();
CameraController.Singleton.fastMove = true;
}
}
public override void EmitRunParticle ()
{
if ( !m_IsDead )
{
m_RunParticleSystem.Emit ( 1 );
}
}
public override void Reset ()
{
m_IsDead = false;
m_ClosingEye = false;
m_Guard = false;
m_Block = false;
m_CurrentFootstepSoundIndex = 0;
transform.localScale = m_InitialScale;
m_Rigidbody2D.velocity = Vector2.zero;
m_Skeleton.SetActive ( false, m_Rigidbody2D.velocity );
m_Skeleton.Reset();
m_timeLeft = m_freezeTime;
m_freezers.Clear();
m_fires.Clear();
}
#endregion
}
} | 24.257576 | 104 | 0.622423 | [
"MIT"
] | jlfurtado/RedRunner | Assets/Scripts/RedRunner/Characters/RedCharacter.cs | 3,204 | C# |
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace NetOffice.DeveloperToolbox.ToolboxControls.OfficeUI
{
/// <summary>
/// A wait panel while office application is creating and fetching the ui object model
/// </summary>
public partial class WaitControl : UserControl
{
#region Fields
private int _currentLanguageID;
#endregion
#region Ctor
/// <summary>
/// Creates an instance of the class
/// </summary>
/// <param name="currentLanguageID">current user language id</param>
public WaitControl(int currentLanguageID)
{
InitializeComponent();
ResizeControls();
_currentLanguageID = currentLanguageID;
Translation.Translator.TranslateControls(this, "ToolboxControls.OfficeUI.WaitControlTable.txt", _currentLanguageID);
}
#endregion
#region Properties
/// <summary>
/// Current user language id
/// </summary>
public int CurrentLanguageID
{
get
{
return _currentLanguageID;
}
set
{
_currentLanguageID = value;
Translation.Translator.TranslateControls(this, "ToolboxControls.OfficeUI.WaitControlTable.txt", _currentLanguageID);
}
}
#endregion
#region Methods
/// <summary>
/// Bring control in front
/// </summary>
public new void Show()
{
labelWaitMessage.Visible = false;
base.Show();
ResizeControls();
}
/// <summary>
/// Report current action
/// </summary>
/// <param name="message">current action to display for the user</param>
public void ReportProgress(string message)
{
labelWaitMessage.Text = message;
labelWaitMessage.Visible = true;
labelWaitMessage.Refresh();
}
private void ResizeControls()
{
pictureBoxLogo.Left = (this.Width / 2) - (pictureBoxLogo.Width / 2);
pictureBoxLogo.Top = (this.Height / 2) - (pictureBoxLogo.Height / 2);
labelHeader.Left = (this.Width / 2) - (labelHeader.Width / 2);
labelHeader.Top = pictureBoxLogo.Top - 50;
labelWaitMessage.Left = (this.Width / 2) - (labelHeader.Width / 2);
labelWaitMessage.Top = pictureBoxLogo.Top + pictureBoxLogo.Height + 50;
}
#endregion
#region Trigger
private void WaitControl_Resize(object sender, EventArgs e)
{
ResizeControls();
}
#endregion
}
}
| 27.084906 | 132 | 0.575061 | [
"MIT"
] | Engineerumair/NetOffice | Toolbox/Toolbox/ToolboxControls/OfficeUI/WaitControl.cs | 2,873 | C# |
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
[RequireComponent(typeof(DotCollision))]
public class Egg : MonoBehaviour {
public float speed = 0f;
public DotCollision col;
private Material material;
public float xv = 0;
public float gv = 0;
public int animindex = 0;
private int break_egg = -1;
public bool jump = false;
private int rn;
private int life_counter = 600;
// Use this for initialization
void Start() {
this.col = this.gameObject.GetComponent<DotCollision>();
this.material = this.transform.GetChild(0).transform.GetComponent<MeshRenderer>().material;
this.rn = Random.Range(0, 7);
}
// Update is called once per frame
void Update() {
if (this.gv > 0) {
this.col.gravity = this.gv;
this.gv = 0;
}
this.Animation();
if (!this.col.isground) {
this.speed = 0;
this.jump = true;
} else {
if (this.jump) {
this.jump = false;
this.Damage();
}
}
this.xv *= 0.99f;
this.xv += Input.acceleration.x * 0.003f;
if (this.col.isground) {
var r = ((Mathf.Abs(this.col.dpx % 16 + 16) + 8) % 16);
var l = ((Mathf.Abs(this.col.dpx % 16 + 16) + 7) % 16);
if (this.col.Test(16 - r, -1).Count == 0) {
this.xv += 0.0005f;
} else if (this.col.Test(-(16 - (16 - l - 1)), -1).Count == 0) {
this.xv += -0.0005f;
}
}
this.life_counter -= 1;
if (this.life_counter < 0) {
GameObject.Destroy(this.gameObject.GetComponentInChildren<MeshFilter>().mesh);
GameObject.Destroy(this.gameObject);
}
if (this.break_egg > 6) { this.xv = 0; }
if (this.col.Test(1, 0).Count > 0 && this.col.Test(-1, 0).Count > 0) { this.xv = 0; }
if (this.Reflect()) {
if (Mathf.Abs(this.xv) > 0.01) { this.Damage(); }
}
this.col.MoveXDeltaTime(this.xv);
this.col.GravityDeltaTime(0.02f);
}
private void Animation () {
int n = ((this.col.dpx - 4) % 64 + 64) / 8;
this.material.SetInt("_X", (n + this.rn) % 8);
this.material.SetInt("_Y", Mathf.Min(Mathf.Max(this.break_egg, 0), 7));
}
private bool Reflect () {
if (this.xv > 0) {
var c = this.col.Test(1, 0);
if (c.Count > 0) {
if (Mathf.Abs(this.xv) > 0.1) {
this.col.map.SetTile(c[0], 23, 0);
this.col.map.FixAutoTile(c[0], 0, true);
}
this.xv *= -0.8f;
this.xv = Mathf.Clamp(this.xv, -0.5f, 0.5f);
return true;
}
}
if (this.xv < 0) {
var c = this.col.Test(-1, 0);
if (c.Count > 0) {
if (Mathf.Abs(this.xv) > 0.1) {
this.col.map.SetTile(c[0], 23, 0);
this.col.map.FixAutoTile(c[0], 0, true);
}
this.xv *= -0.8f;
this.xv = Mathf.Clamp(this.xv, -0.5f, 0.5f);
return true;
}
}
return false;
}
private void Damage () {
this.break_egg += 1;
}
List<E512Pos> lights = new List<E512Pos>();
private void Light () {
var cpos = this.col.CPos();
int d = 10;
int mu = cpos.y + d;
int mr = cpos.x + d;
int ml = cpos.x - d;
int md = cpos.y - d;
for (int i = md; i <= mu; ++i) {
for (int j = ml; j <= mr; ++j) {
var p = new E512Pos(j, i);
var v = -(int)Vector2.Distance(new Vector2(cpos.x, cpos.y), new Vector2(p.x, p.y));
this.col.map.SetTileLight(p, Mathf.Max(Mathf.Max(v, -10), this.col.map.GetTileLight(p)));
this.lights.Add(p);
}
}
}
}
| 29.391304 | 105 | 0.470414 | [
"MIT"
] | ebicochineal/E512TileMap | E512TileMap/Assets/E512TileMap/Script/Demo/Egg.cs | 4,058 | C# |
#if MIGRATION
namespace System.Windows
#else
namespace Windows.UI.Xaml
#endif
{
public enum FontFraction
{
/// <summary>Default style is used.</summary>
Normal,
/// <summary>Stacked fraction style is used.</summary>
Stacked,
/// <summary>Slashed fraction style is used.</summary>
Slashed
}
}
| 18.117647 | 56 | 0.707792 | [
"MIT"
] | Barjonp/OpenSilver | src/Runtime/Runtime/System.Windows/WORKINPROGRESS/FontFraction.cs | 310 | C# |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System.Collections;
using System.Xml;
namespace Microsoft.Build.BuildEngine.Shared
{
/// <summary>
/// Contains the names of the known elements in the XML project file.
/// </summary>
/// <owner>RGoel</owner>
internal static class XMakeElements
{
internal const string project = "Project";
internal const string visualStudioProject = "VisualStudioProject";
internal const string target = "Target";
internal const string propertyGroup = "PropertyGroup";
internal const string output = "Output";
internal const string itemGroup = "ItemGroup";
internal const string itemDefinitionGroup = "ItemDefinitionGroup";
internal const string usingTask = "UsingTask";
internal const string projectExtensions = "ProjectExtensions";
internal const string onError = "OnError";
internal const string error = "Error";
internal const string warning = "Warning";
internal const string message = "Message";
internal const string import = "Import";
internal const string importGroup = "ImportGroup";
internal const string choose = "Choose";
internal const string when = "When";
internal const string otherwise = "Otherwise";
internal const string usingTaskParameterGroup = "ParameterGroup";
internal const string usingTaskParameter = "Parameter";
internal const string usingTaskBody = "Task";
/// <summary>
/// Indicates if the given node is valid as a child of a task element.
/// </summary>
/// <owner>SumedhK</owner>
/// <param name="childNode"></param>
/// <returns>true, if specified node can be a child of a task element</returns>
internal static bool IsValidTaskChildNode(XmlNode childNode)
{
return (childNode.Name == output) ||
(childNode.NodeType == XmlNodeType.Comment) ||
(childNode.NodeType == XmlNodeType.Whitespace);
}
internal static readonly char[] illegalTargetNameCharacters = new char[] { '$', '@', '(', ')', '%', '*', '?', '.' };
// Names that cannot be used as property or item names because they are reserved
internal static readonly string[] illegalPropertyOrItemNames = new string[] {
// XMakeElements.project, // "Project" is not reserved, because unfortunately ProjectReference items
// already use it as metadata name.
XMakeElements.visualStudioProject,
XMakeElements.target,
XMakeElements.propertyGroup,
XMakeElements.output,
XMakeElements.itemGroup,
XMakeElements.usingTask,
XMakeElements.projectExtensions,
XMakeElements.onError,
// XMakeElements.import, // "Import" items are used by Visual Basic projects
XMakeElements.importGroup,
XMakeElements.choose,
XMakeElements.when,
XMakeElements.otherwise
};
// The set of XMake reserved item/property names (e.g. Choose, Message etc.)
private static Hashtable illegalItemOrPropertyNamesHashtable;
/// <summary>
/// Read-only internal accessor for the hashtable containing
/// MSBuild reserved item/property names (like "Choose", for example).
/// </summary>
/// <owner>LukaszG</owner>
internal static Hashtable IllegalItemPropertyNames
{
get
{
// Lazy creation
if (illegalItemOrPropertyNamesHashtable == null)
{
illegalItemOrPropertyNamesHashtable = new Hashtable(XMakeElements.illegalPropertyOrItemNames.Length);
foreach (string reservedName in XMakeElements.illegalPropertyOrItemNames)
{
illegalItemOrPropertyNamesHashtable.Add(reservedName, string.Empty);
}
}
return illegalItemOrPropertyNamesHashtable;
}
}
}
}
| 43.353535 | 124 | 0.621855 | [
"MIT"
] | 0xced/msbuild | src/Deprecated/Engine/Shared/XMakeElements.cs | 4,292 | C# |
namespace Dalmatian.Web.ViewModels.Persons
{
using System.Collections.Generic;
using Dalmatian.Data.Models;
using Dalmatian.Data.Models.Enum;
using Dalmatian.Services.Mapping;
public class PersonViewModel : IMapFrom<Person>
{
public int Id { get; set; }
public string Firstname { get; set; }
public string Middlename { get; set; }
public string Lastname { get; set; }
public string UserId { get; set; }
public string Email { get; set; }
public string Phone { get; set; }
public string Website { get; set; }
public Country Country { get; set; }
public string City { get; set; }
public string Address { get; set; }
public string Facebook { get; set; }
public string Twitter { get; set; }
public string Instagram { get; set; }
public string Linkedin { get; set; }
}
}
| 22.142857 | 51 | 0.6 | [
"MIT"
] | angelneychev/Dalmatian | src/Web/Dalmatian.Web.ViewModels/Persons/PersonViewModel.cs | 932 | C# |
/* Copyright 2013-present MongoDB Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using System;
using System.IO;
using FluentAssertions;
using MongoDB.Bson;
using MongoDB.Bson.IO;
using MongoDB.Driver.Core.WireProtocol.Messages;
using MongoDB.Driver.Core.WireProtocol.Messages.Encoders.JsonEncoders;
using Xunit;
namespace MongoDB.Driver.Core.WireProtocol.Messages.Encoders.JsonEncoders
{
public class UpdateMessageJsonEncoderTests
{
#region static
// static fields
private static readonly CollectionNamespace __collectionNamespace = new CollectionNamespace("d", "c");
private static readonly bool __isMulti = true;
private static readonly bool __isUpsert = true;
private static readonly MessageEncoderSettings __messageEncoderSettings = new MessageEncoderSettings();
private static readonly BsonDocument __query = new BsonDocument("x", 1);
private static readonly int __requestId = 1;
private static readonly UpdateMessage __testMessage;
private static readonly string __testMessageJson;
private static readonly BsonDocument __update = new BsonDocument("y", 1);
private static readonly IElementNameValidator _updateValidator = NoOpElementNameValidator.Instance;
// static constructor
static UpdateMessageJsonEncoderTests()
{
__testMessage = new UpdateMessage(__requestId, __collectionNamespace, __query, __update, _updateValidator, __isMulti, __isUpsert);
__testMessageJson =
"{ " +
"\"opcode\" : \"update\", " +
"\"requestId\" : 1, " +
"\"database\" : \"d\", " +
"\"collection\" : \"c\", " +
"\"isMulti\" : true, " +
"\"isUpsert\" : true, " +
"\"query\" : { \"x\" : 1 }, " +
"\"update\" : { \"y\" : 1 }" +
" }";
}
#endregion
[Fact]
public void Constructor_should_not_throw_if_textReader_and_textWriter_are_both_provided()
{
using (var textReader = new StringReader(""))
using (var textWriter = new StringWriter())
{
Action action = () => new UpdateMessageJsonEncoder(textReader, textWriter, __messageEncoderSettings);
action.ShouldNotThrow();
}
}
[Fact]
public void Constructor_should_not_throw_if_only_textReader_is_provided()
{
using (var textReader = new StringReader(""))
{
Action action = () => new UpdateMessageJsonEncoder(textReader, null, __messageEncoderSettings);
action.ShouldNotThrow();
}
}
[Fact]
public void Constructor_should_not_throw_if_only_textWriter_is_provided()
{
using (var textWriter = new StringWriter())
{
Action action = () => new UpdateMessageJsonEncoder(null, textWriter, __messageEncoderSettings);
action.ShouldNotThrow();
}
}
[Fact]
public void Constructor_should_throw_if_textReader_and_textWriter_are_both_null()
{
Action action = () => new UpdateMessageJsonEncoder(null, null, __messageEncoderSettings);
action.ShouldThrow<ArgumentException>();
}
[Fact]
public void ReadMessage_should_read_a_message()
{
using (var textReader = new StringReader(__testMessageJson))
{
var subject = new UpdateMessageJsonEncoder(textReader, null, __messageEncoderSettings);
var message = subject.ReadMessage();
message.CollectionNamespace.Should().Be(__collectionNamespace);
message.IsMulti.Should().Be(__isMulti);
message.IsUpsert.Should().Be(__isUpsert);
message.Query.Should().Be(__query);
message.RequestId.Should().Be(__requestId);
message.Update.Should().Be(__update);
}
}
[Fact]
public void ReadMessage_should_throw_if_textReader_was_not_provided()
{
using (var textWriter = new StringWriter())
{
var subject = new UpdateMessageJsonEncoder(null, textWriter, __messageEncoderSettings);
Action action = () => subject.ReadMessage();
action.ShouldThrow<InvalidOperationException>();
}
}
[Fact]
public void WriteMessage_should_throw_if_textWriter_was_not_provided()
{
using (var textReader = new StringReader(""))
{
var subject = new UpdateMessageJsonEncoder(textReader, null, __messageEncoderSettings);
Action action = () => subject.WriteMessage(__testMessage);
action.ShouldThrow<InvalidOperationException>();
}
}
[Fact]
public void WriteMessage_should_throw_if_message_is_null()
{
using (var textWriter = new StringWriter())
{
var subject = new UpdateMessageJsonEncoder(null, textWriter, __messageEncoderSettings);
Action action = () => subject.WriteMessage(null);
action.ShouldThrow<ArgumentNullException>();
}
}
[Fact]
public void WriteMessage_should_write_a_message()
{
using (var textWriter = new StringWriter())
{
var subject = new UpdateMessageJsonEncoder(null, textWriter, __messageEncoderSettings);
subject.WriteMessage(__testMessage);
var json = textWriter.ToString();
json.Should().Be(__testMessageJson);
}
}
}
}
| 39.559006 | 142 | 0.609044 | [
"Apache-2.0"
] | 591094733/mongo-csharp-driver | tests/MongoDB.Driver.Core.Tests/Core/WireProtocol/Messages/Encoders/JsonEncoders/UpdateMessageJsonEncoderTests.cs | 6,371 | C# |
using System;
using System.Collections.Generic;
using System.Linq.Expressions;
using System.Net;
using System.Reflection;
using System.Text;
using System.Linq;
using Newtonsoft.Json;
using SevenShadow.Core.Entities.News;
namespace SevenShadow.Benzinga
{
public class BenzingaHelper
{
private const string BENZINGA_NEWS_API_URL = "http://api.benzinga.com/api/v2/";
private string AuthToken;
public BenzingaHelper(string authenticationToken = "")
{
AuthToken = authenticationToken;
}
public void SetAuthToken(string token)
{
AuthToken = token;
}
public string GetRawData(string dataset, IDictionary<string, string> settings, string format = "json")
{
/* This is just to get the ticks to send to benzing.
*
*
double javascriptTicks = (DateTime.UtcNow.Subtract(new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc))).TotalMilliseconds;
long javascriptTicksLong = (long)javascriptTicks;
javascriptTicksLong = javascriptTicksLong;
*/
string requestUrl = "";
string rawData = "";
var requestData = new StringBuilder(settings.Count());
if (string.IsNullOrEmpty(AuthToken))
{
throw new Exception("Benzinga Token Not Set.");
}
else
{
requestUrl = BENZINGA_NEWS_API_URL + String.Format("{0}/?token={1}", dataset, AuthToken);
}
foreach (KeyValuePair<string, string> kvp in settings)
{
requestData.Append(String.Format("&{0}={1}", kvp.Key, kvp.Value));
}
requestUrl = requestUrl + requestData.ToString();
try
{
//Prevent 404 Errors:
WebClient client = new WebClient();
if (format == "json")
client.Headers.Add("Accept: application/json");
rawData = client.DownloadString(requestUrl);
}
catch (Exception err)
{
throw new Exception("Sorry there was an error and we could not connect to Benzinga: " + err.Message);
}
return rawData;
}
public List<NewsItem> GetNews()
{
string rawData = GetRawData("news", new Dictionary<string, string>());
List<BenzingaNewsItem> benzingaNewsItems = (List<BenzingaNewsItem>)JsonConvert.DeserializeObject(rawData, typeof(List<BenzingaNewsItem>));
List<NewsItem> translatedItems = TranslateNewsItems(benzingaNewsItems);
return translatedItems;
}
public List<NewsItem> GetNewsByDate(DateTime fromDate, bool includeStoryText = false)
{
Dictionary<string, string> settings = new Dictionary<string,string>();
settings.Add("publishedSince", ConvertToTimestamp(fromDate).ToString());
settings.Add("pageSize", "100");
settings.Add("date", fromDate.ToString("yyyy-MM-dd"));
if (includeStoryText)
settings.Add("displayOutput", "full");
string rawData = GetRawData("news", settings);
List<BenzingaNewsItem> benzingaNewsItems = (List<BenzingaNewsItem>)JsonConvert.DeserializeObject(rawData, typeof(List<BenzingaNewsItem>));
List<NewsItem> translatedItems = TranslateNewsItems(benzingaNewsItems);
return translatedItems;
}
private double ConvertToTimestamp(DateTime value)
{
//create Timespan by subtracting the value provided from
//the Unix Epoch
TimeSpan span = (value - new DateTime(1970, 1, 1, 0, 0, 0, 0).ToLocalTime());
//return the total seconds (which is a UNIX timestamp)
return (double)span.TotalSeconds;
}
public List<NewsItem> GetNews(List<string> tickers)
{
Dictionary<string, string> dic = new Dictionary<string, string>();
dic.Add("tickers", string.Join(",", tickers));
string rawData = GetRawData("news", dic);
List<BenzingaNewsItem> benzingaNewsItems = (List<BenzingaNewsItem>)JsonConvert.DeserializeObject(rawData, typeof(List<BenzingaNewsItem>));
List<NewsItem> translatedItems = TranslateNewsItems(benzingaNewsItems);
return translatedItems;
}
#region Private Methods
private List<NewsItem> TranslateNewsItems(List<BenzingaNewsItem> items)
{
List<NewsItem> translatedItems = (from x in items
select new NewsItem()
{
ExternalId = x.id.ToString(),
Headline = x.title,
Author = x.author,
URL = x.url,
Teaser = x.teaser,
Body = x.body,
Tickers = (from y in x.stocks
select y.name).ToList(),
Tags = (from y in x.tags
select y.name).ToList(),
Channels = (from y in x.stocks
select y.name).ToList(),
TickerListString = string.Join("|", (from y in x.stocks
select y.name).ToArray()),
DateCreated = DateTime.Parse(x.created),
DateModified = DateTime.Parse(x.updated)
}
).ToList();
return translatedItems;
}
#endregion
}
}
| 39.35 | 150 | 0.504288 | [
"MIT"
] | sevenshadow/sevenshadow-benzinga | BenzingaHelper.cs | 6,298 | C# |
/*
* Copyright (c) 2019-2022, Sjofn LLC
* All rights reserved.
*
* - Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* - Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
* - Neither the name of the openmetaverse.co nor the names
* of its contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
using System.IO;
namespace LibreMetaverse.LslTools
{
internal class ReUStr : ReStr
{
public ReUStr(TokensGen tks, string str)
{
this.m_str = str;
foreach (var c in str)
{
tks.m_tokens.UsingChar(char.ToLower(c));
tks.m_tokens.UsingChar(char.ToUpper(c));
}
}
public ReUStr(TokensGen tks, char ch)
{
this.m_str = new string(ch, 1);
tks.m_tokens.UsingChar(char.ToLower(ch));
tks.m_tokens.UsingChar(char.ToUpper(ch));
}
public override void Print(TextWriter s)
{
s.Write($"(U\"{(object)this.m_str}\")");
}
public override int Match(string str, int pos, int max)
{
int length = this.m_str.Length;
if (length > max || length > max - pos)
return -1;
for (int index = 0; index < length; ++index)
{
if ((int) char.ToUpper(str[index]) != (int) char.ToUpper(this.m_str[index]))
return -1;
}
return length;
}
public override void Build(Nfa nfa)
{
int length = this.m_str.Length;
NfaNode nfaNode = (NfaNode) nfa;
for (int index = 0; index < length; ++index)
{
NfaNode next = new NfaNode(nfa.m_tks);
nfaNode.AddUArc(this.m_str[index], next);
nfaNode = next;
}
nfaNode.AddEps(nfa.m_end);
}
}
}
| 33.04878 | 84 | 0.6631 | [
"BSD-3-Clause"
] | adversinc/libremetaverse | LibreMetaverse.LslTools/Tools/ReUStr.cs | 2,712 | C# |
//------------------------------------------------------------------------------
// <auto-generated>
// このコードはツールによって生成されました。
// ランタイム バージョン:4.0.30319.42000
//
// このファイルへの変更は、以下の状況下で不正な動作の原因になったり、
// コードが再生成されるときに損失したりします
// </auto-generated>
//------------------------------------------------------------------------------
namespace Calculator_01.Properties
{
/// <summary>
/// ローカライズされた文字列などを検索するための、厳密に型指定されたリソース クラスです。
/// </summary>
// このクラスは StronglyTypedResourceBuilder クラスが ResGen
// または Visual Studio のようなツールを使用して自動生成されました。
// メンバーを追加または削除するには、.ResX ファイルを編集して、/str オプションと共に
// ResGen を実行し直すか、または VS プロジェクトをリビルドします。
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "4.0.0.0")]
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
internal class Resources
{
private static global::System.Resources.ResourceManager resourceMan;
private static global::System.Globalization.CultureInfo resourceCulture;
[global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
internal Resources()
{
}
/// <summary>
/// このクラスで使用されるキャッシュされた ResourceManager インスタンスを返します。
/// </summary>
[global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
internal static global::System.Resources.ResourceManager ResourceManager
{
get
{
if ((resourceMan == null))
{
global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("Calculator_01.Properties.Resources", typeof(Resources).Assembly);
resourceMan = temp;
}
return resourceMan;
}
}
/// <summary>
/// すべてについて、現在のスレッドの CurrentUICulture プロパティをオーバーライドします
/// 現在のスレッドの CurrentUICulture プロパティをオーバーライドします。
/// </summary>
[global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
internal static global::System.Globalization.CultureInfo Culture
{
get
{
return resourceCulture;
}
set
{
resourceCulture = value;
}
}
}
}
| 37.591549 | 180 | 0.586737 | [
"MIT"
] | miyuki-31270/SimpleCalculator | Calculator_01/Calculator_01/Properties/Resources.Designer.cs | 3,293 | C# |
using Newtonsoft.Json;
using Oxide.Core;
using Oxide.Core.Configuration;
using Oxide.Core.Libraries.Covalence;
using Oxide.Core.Plugins;
using System.Collections;
using System.Collections.Generic;
using System.Globalization;
using System.Threading.Tasks;
using System;
using System.IO;
using System.Linq;
using UnityEngine;
namespace Oxide.Plugins
{
[Info("Lights On", "mspeedie", "1.4.2")]
[Description("Toggle lights on/off either as configured or by name.")]
public class LightsOn : CovalencePlugin
//RustPlugin
{
const string perm_lightson = "lightson.allowed";
const string perm_freelights = "lightson.freelights";
private bool InitialPassNight = true;
private bool NightToggleactive = false;
private bool nightcross24 = false;
private bool config_changed = false;
private Timer Nighttimer;
private Timer Alwaystimer;
private Timer Devicetimer;
private Configuration config;
// strings to compare to check object names
const string bbq_name = "bbq";
const string campfire_name = "campfire";
const string ceilinglight_name = "ceilinglight";
const string chineselantern_name = "chineselantern";
const string cursedcauldron_name = "cursedcauldron";
const string fireplace_name = "fireplace";
const string fogmachine_name = "fogmachine";
const string furnace_name = "furnace";
const string furnace_large_name = "furnace.large";
const string hobobarrel_name = "hobobarrel";
const string jackolanternangry_name = "jackolantern.angry";
const string jackolanternhappy_name = "jackolantern.happy";
const string lantern_name = "lantern";
const string largecandleset_name = "largecandleset";
const string refinerysmall_name = "small_refinery";
const string searchlight_name = "searchlight";
const string simplelight_name = "simplelight";
const string skullfirepit_name = "skull_fire_pit";
const string smallrefinery_name = "small.oil.refinery";
const string smallcandleset_name = "smallcandleset";
const string snowmachine_name = "snowmachine";
const string spookyspeaker_name = "spookyspeaker";
const string strobelight_name = "strobelight";
const string tunalight_name = "tunalight";
const string hatminer_name = "hat.miner";
const string hatcandle_name = "hat.candle";
public class Configuration
{
// True means turn them on
[JsonProperty(PropertyName = "Hats do not use fuel (true/false)")]
public bool Hats { get; set; } = true;
[JsonProperty(PropertyName = "BBQs (true/false)")]
public bool BBQs { get; set; } = false;
[JsonProperty(PropertyName = "Campfires (true/false)")]
public bool Campfires { get; set; } = false;
[JsonProperty(PropertyName = "Candles (true/false)")]
public bool Candles { get; set; } = true;
[JsonProperty(PropertyName = "Cauldrons (true/false)")]
public bool Cauldrons { get; set; } = false;
[JsonProperty(PropertyName = "Ceiling Lights (true/false)")]
public bool CeilingLights { get; set; } = true;
[JsonProperty(PropertyName = "Fire Pits (true/false)")]
public bool FirePits { get; set; } = false;
[JsonProperty(PropertyName = "Fireplaces (true/false)")]
public bool Fireplaces { get; set; } = true;
[JsonProperty(PropertyName = "Fog Machines (true/false)")]
public bool Fog_Machines { get; set; } = true;
[JsonProperty(PropertyName = "Furnaces (true/false)")]
public bool Furnaces { get; set; } = false;
[JsonProperty(PropertyName = "Hobo Barrels (true/false)")]
public bool HoboBarrels { get; set; } = true;
[JsonProperty(PropertyName = "Lanterns (true/false)")]
public bool Lanterns { get; set; } = true;
[JsonProperty(PropertyName = "Refineries (true/false)")]
public bool Refineries { get; set; } = false;
[JsonProperty(PropertyName = "Search Lights (true/false)")]
public bool SearchLights { get; set; } = true;
[JsonProperty(PropertyName = "Simple Lights (true/false)")]
public bool SimpleLights { get; set; } = false;
[JsonProperty(PropertyName = "SpookySpeakers (true/false)")]
public bool Speakers { get; set; } = false;
[JsonProperty(PropertyName = "Strobe Lights (true/false)")]
public bool StrobeLights { get; set; } = false;
[JsonProperty(PropertyName = "SnowMachines (true/false)")]
public bool Snow_Machines { get; set; } = true;
[JsonProperty(PropertyName = "Protect BBQs (true/false)")]
public bool ProtectBBQs { get; set; } = true;
[JsonProperty(PropertyName = "Protect Campfires (true/false)")]
public bool ProtectCampfires { get; set; } = true;
[JsonProperty(PropertyName = "Protect Cauldron (true/false)")]
public bool ProtectCauldrons { get; set; } = true;
[JsonProperty(PropertyName = "Protect Fire Pits (true/false)")]
public bool ProtectFirePits { get; set; } = true;
[JsonProperty(PropertyName = "Protect Fireplaces (true/false)")]
public bool ProtectFireplaces { get; set; } = true;
[JsonProperty(PropertyName = "Protect Furnaces (true/false)")]
public bool ProtectFurnaces { get; set; } = true;
[JsonProperty(PropertyName = "Protect Hobo Barrels (true/false)")]
public bool ProtectHoboBarrels { get; set; } = false;
[JsonProperty(PropertyName = "Protect Refineries (true/false)")]
public bool ProtectRefineries { get; set; } = true;
[JsonProperty(PropertyName = "Devices Always On (true/false)")]
public bool DevicesAlwaysOn { get; set; } = true;
[JsonProperty(PropertyName = "Always On (true/false)")]
public bool AlwaysOn { get; set; } = false;
[JsonProperty(PropertyName = "Night Toggle (true/false)")]
public bool NightToggle { get; set; } = true;
[JsonProperty(PropertyName = "Console Output (true/false)")]
public bool ConsoleMsg { get; set; } = true;
// this is checked more frequently to get the lights on/off closer to the time the operator sets
[JsonProperty(PropertyName = "Night Toggle Check Frequency (in seconds)")]
public int NightCheckFrequency { get; set; } = 30;
// these less frequent checks as most devices will be on when placed
[JsonProperty(PropertyName = "Always On Check Frequency (in seconds)")]
public int AlwaysCheckFrequency { get; set; } = 300;
// these less frequent checks as most devices will be on when placed
[JsonProperty(PropertyName = "Device Check Frequency (in seconds)")]
public int DeviceCheckFrequency { get; set; } = 300;
[JsonProperty(PropertyName = "Dusk Time (HH in a 24 hour clock)")]
public float DuskTime { get; set; } = 17.5f;
[JsonProperty(PropertyName = "Dawn Time (HH in a 24 hour clock)")]
public float DawnTime { get; set; } = 09.0f;
}
string Lang(string key, string id = null, params object[] args) => string.Format(lang.GetMessage(key, this, id), args);
protected override void LoadDefaultMessages()
{
lang.RegisterMessages(new Dictionary<string, string>
{
["bad check frequency"] = "Check frequency must be between 10 and 600",
["bad check frequency2"] = "Check frequency must be between 60 and 6000",
["bad prefab"] = "Bad Prefab Name, not found in devices or lights: ",
["bad dusk time"] = "Dusk time must be between 0 and 24",
["bad dawn time"] = "Dawn time must be between 0 and 24",
["dawn=dusk"] = "Dawn can't be the same value as dusk",
["dawn"] = "Lights going off. Next lights on at ",
["default"] = "Loading default config for LightsOn",
["dusk"] = "Lights coming on. Ending at ",
["lights off"] = "Lights Off",
["lights on"] = "Lights On",
["nopermission"] = "You do not have permission to use that command.",
["one or the other"] = "Please select one (and only one) of Always On or Night Toggle",
["prefix"] = "LightsOn: ",
["state"] = "unknown state: please use on or off",
["syntax"] = "syntax: Lights State (on/off) Optional: prefabshortname (part of the prefab name) to change their state, use all to force all lights' state",
}, this);
}
protected override void LoadConfig()
{
config_changed = false;
base.LoadConfig();
try
{
config = Config.ReadObject<Configuration>();
if (config == null)
{
if (config.ConsoleMsg)
Puts(Lang("default"));
LoadDefaultConfig();
config_changed = true;
}
}
catch
{
if (config.ConsoleMsg)
Puts(Lang("default"));
LoadDefaultConfig();
config_changed = true;
}
// check data is ok because people can make mistakes
if (config.AlwaysOn && config.NightToggle)
{
Puts(Lang("one or the other"));
config.NightToggle = false;
config_changed = true;
}
if (config.DuskTime < 0f || config.DuskTime > 24f)
{
Puts(Lang("bad dusk time"));
config.DuskTime = 17f;
config_changed = true;
}
if (config.DawnTime < 0f || config.DawnTime > 24f)
{
Puts(Lang("bad dawn time"));
config.DawnTime = 9f;
config_changed = true;
}
if (config.DawnTime == config.DuskTime)
{
Puts(Lang("dawn=dusk"));
config.DawnTime = 9f;
config.DuskTime = 17f;
config_changed = true;
}
if (config.NightCheckFrequency < 10 || config.NightCheckFrequency > 600)
{
Puts(Lang("bad check frequency"));
config.NightCheckFrequency = 30;
config_changed = true;
}
if (config.AlwaysCheckFrequency < 60 || config.AlwaysCheckFrequency > 6000)
{
Puts(Lang("bad check frequency2"));
config.AlwaysCheckFrequency = 300;
config_changed = true;
}
if (config.DeviceCheckFrequency < 60 || config.DeviceCheckFrequency > 6000)
{
Puts(Lang("bad check frequency2"));
config.DeviceCheckFrequency = 300;
config_changed = true;
}
// determine correct light timing logic
if (config.DuskTime > config.DawnTime)
nightcross24 = true;
else
nightcross24 = false;
if (config.AlwaysOn)
{
// start timer to lights always on
Alwaystimer = timer.Once(config.AlwaysCheckFrequency, AlwaysTimerProcess);
}
else if (config.NightToggle)
{
// start timer to toggle lights based on time
InitialPassNight = true;
Nighttimer = timer.Once(config.NightCheckFrequency, NightTimerProcess);
}
if (config.DevicesAlwaysOn)
{
// start timer to toggle devices
Devicetimer = timer.Once(config.DeviceCheckFrequency, DeviceTimerProcess);
}
if (config_changed)
SaveConfig();
}
protected override void LoadDefaultConfig()
{
config = new Configuration();
}
protected override void SaveConfig() => Config.WriteObject(config);
private void OnServerInitialized()
{
permission.RegisterPermission(perm_freelights,this);
}
string CleanedName(string prefabName)
{
if (string.IsNullOrEmpty(prefabName))
return prefabName;
string CleanedString = prefabName;
int clean_loc = CleanedString.IndexOf("deployed");
if (clean_loc > 1)
CleanedString = CleanedString.Remove(clean_loc-1);
clean_loc = CleanedString.IndexOf("static");
if (clean_loc > 1)
CleanedString = CleanedString.Remove(clean_loc-1);
return CleanedString;
}
bool IsOvenPrefabName(string prefabName)
{
if (furnace_name.Contains(prefabName))
return true;
else if (furnace_large_name.Contains(prefabName))
return true;
else if (bbq_name.Contains(prefabName))
return true;
else if (campfire_name.Contains(prefabName))
return true;
else if (chineselantern_name.Contains(prefabName))
return true;
else if (fireplace_name.Contains(prefabName))
return true;
else if (hobobarrel_name.Contains(prefabName))
return true;
else if (lantern_name.Contains(prefabName))
return true;
else if (tunalight_name.Contains(prefabName))
return true;
else if (cursedcauldron_name.Contains(prefabName))
return true;
else if (skullfirepit_name.Contains(prefabName))
return true;
else if (refinerysmall_name.Contains(prefabName))
return true;
else if (smallrefinery_name.Contains(prefabName))
return true;
else if (jackolanternangry_name.Contains(prefabName))
return true;
else if (jackolanternhappy_name.Contains(prefabName))
return true;
else
return false;
}
bool IsLightToggle(string prefabName)
{
if (lantern_name.Contains(prefabName))
return true;
else if (tunalight_name.Contains(prefabName))
return true;
else if (chineselantern_name.Contains(prefabName))
return true;
//else if (jackolanternangry_name.Contains(prefabName))
// return true;
//else if (jackolanternhappy_name.Contains(prefabName))
// return true;
//else if (largecandleset_name.Contains(prefabName))
// return true;
//else if (smallcandleset_name.Contains(prefabName))
// return true;
//else if (searchlight_name.Contains(prefabName))
// return true;
//else if (simplelight_name.Contains(prefabName))
// return true;
else
return false;
}
bool IsLightPrefabName(string prefabName)
{
if (ceilinglight_name.Contains(prefabName))
return true;
else if (lantern_name.Contains(prefabName))
return true;
else if (tunalight_name.Contains(prefabName))
return true;
else if (jackolanternangry_name.Contains(prefabName))
return true;
else if (jackolanternhappy_name.Contains(prefabName))
return true;
else if (chineselantern_name.Contains(prefabName))
return true;
else if (largecandleset_name.Contains(prefabName))
return true;
else if (smallcandleset_name.Contains(prefabName))
return true;
else if (searchlight_name.Contains(prefabName))
return true;
else if (simplelight_name.Contains(prefabName))
return true;
else
return false;
}
bool IsHatPrefabName(string prefabName)
{
// this uses only internal names so do not need the Contains logic
switch (prefabName)
{
case hatminer_name: return true;
case hatcandle_name: return true;
default: return false;
}
}
bool IsDevicePrefabName(string prefabName)
{
if (fogmachine_name.Contains(prefabName))
return true;
else if (snowmachine_name.Contains(prefabName))
return true;
else if (strobelight_name.Contains(prefabName))
return true;
else if (spookyspeaker_name.Contains(prefabName))
return true;
else
return false;
}
bool CanCookShortPrefabName(string prefabName)
{
if (furnace_name.Contains(prefabName))
return true;
else if (furnace_large_name.Contains(prefabName))
return true;
else if (campfire_name.Contains(prefabName))
return true;
else if (bbq_name.Contains(prefabName))
return true;
else if (fireplace_name.Contains(prefabName))
return true;
else if (refinerysmall_name.Contains(prefabName))
return true;
else if (smallrefinery_name.Contains(prefabName))
return true;
else if (skullfirepit_name.Contains(prefabName))
return true;
else if (hobobarrel_name.Contains(prefabName))
return true;
else if (cursedcauldron_name.Contains(prefabName))
return true;
else
return false;
}
bool ProtectShortPrefabName(string prefabName)
{
switch (CleanedName(prefabName))
{
case "bbq": return config.ProtectBBQs;
case "campfire": return config.ProtectCampfires;
case "cursedcauldron": return config.ProtectCauldrons;
case "fireplace": return config.ProtectFireplaces;
case "furnace": return config.ProtectFurnaces;
case "furnace.large": return config.ProtectFurnaces;
case "hobobarrel": return config.ProtectHoboBarrels;
case "refinery_small": return config.ProtectRefineries;
case "small.oil.refinery": return config.ProtectRefineries;
case "skull_fire_pit": return config.ProtectFirePits;
default:
{
return false;
}
}
}
bool ProcessShortPrefabName(string prefabName)
{
switch (CleanedName(prefabName))
{
case "bbq": return config.BBQs;
case "campfire": return config.Campfires;
case "ceilinglight": return config.CeilingLights;
case "cursedcauldron": return config.Cauldrons;
case "fireplace": return config.Fireplaces;
case "fogmachine": return config.Fog_Machines;
case "furnace": return config.Furnaces;
case "furnace.large": return config.Furnaces;
case "hobobarrel": return config.HoboBarrels;
case "jackolantern.angry": return config.Lanterns;
case "jackolantern.happy": return config.Lanterns;
case "lantern": return config.Lanterns;
case "chineselantern": return config.Lanterns;
case "largecandleset": return config.Candles;
case "refinery_small": return config.Refineries;
case "searchlight": return config.SearchLights;
case "simplelight": return config.SimpleLights;
case "skull_fire_pit": return config.FirePits;
case "small.oil.refinery": return config.Refineries;
case "smallcandleset": return config.Candles;
case "snowmachine": return config.Snow_Machines;
case "spookyspeaker": return config.Speakers;
case "strobelight": return config.StrobeLights;
case "tunalight": return config.Lanterns;
case "hat.miner": return config.Hats;
case "hat.candle": return config.Hats;
default:
{
return false;
}
}
}
private void AlwaysTimerProcess()
{
if (config.AlwaysOn)
{
ProcessLights(true, "all");
// submit for the next pass
Alwaystimer = timer.Once(config.AlwaysCheckFrequency, AlwaysTimerProcess);
}
}
private void DeviceTimerProcess()
{
if (config.DevicesAlwaysOn)
{
ProcessDevices(true, "all");
// submit for the next pass
Devicetimer = timer.Once(config.DeviceCheckFrequency, DeviceTimerProcess);
}
}
private void NightTimerProcess()
{
if (config.NightToggle)
{
ProcessNight();
// clear the Inital flag as we now accurately know the state
InitialPassNight = false;
// submit for the next pass
Nighttimer = timer.Once(config.NightCheckFrequency, NightTimerProcess);
}
}
private void ProcessNight()
{
var gtime = TOD_Sky.Instance.Cycle.Hour;
if ((nightcross24 == false && gtime >= config.DuskTime && gtime < config.DawnTime) ||
(nightcross24 && ((gtime >= config.DuskTime && gtime < 24) || gtime < config.DawnTime))
&& (!NightToggleactive || InitialPassNight))
{
NightToggleactive = true;
ProcessLights(true,"all");
if (!config.DevicesAlwaysOn)
ProcessDevices(true,"all");
if (config.ConsoleMsg)
Puts(Lang("dusk") + config.DawnTime);
}
else if ((nightcross24 == false && gtime >= config.DawnTime) ||
(nightcross24 && (gtime < config.DuskTime && gtime >= config.DawnTime))
&& (NightToggleactive || InitialPassNight))
{
NightToggleactive = false;
ProcessLights(false,"all");
if (!config.DevicesAlwaysOn)
ProcessDevices(false,"all");
if (config.ConsoleMsg)
Puts(Lang("dawn") + config.DuskTime);
}
}
private void ProcessLights(bool state, string prefabName)
{
if (prefabName == "all" || IsOvenPrefabName(prefabName))
{
//if (string.IsNullOrEmpty(prefabName) || prefabName == "all")
// Puts("all lights");
//else
// Puts("turing on: " + prefabName);
BaseOven[] ovens = UnityEngine.Object.FindObjectsOfType<BaseOven>() as BaseOven[];
foreach (BaseOven oven in ovens)
{
if (oven == null || oven.IsDestroyed || oven.IsOn() == state)
continue;
else if (state == false && ProtectShortPrefabName(prefabName))
continue;
// not super efficient find a better way
if (prefabName != "all" &&
(furnace_name.Contains(prefabName) ||
furnace_large_name.Contains(prefabName) ||
lantern_name.Contains(prefabName) ||
tunalight_name.Contains(prefabName) ||
jackolanternangry_name.Contains(prefabName) ||
jackolanternhappy_name.Contains(prefabName) ||
campfire_name.Contains(prefabName) ||
fireplace_name.Contains(prefabName) ||
bbq_name.Contains(prefabName) ||
cursedcauldron_name.Contains(prefabName) ||
skullfirepit_name.Contains(prefabName) ||
hobobarrel_name.Contains(prefabName) ||
smallrefinery_name.Contains(prefabName) ||
refinerysmall_name.Contains(prefabName) ||
chineselantern_name.Contains(prefabName)
))
{
oven.SetFlag(BaseEntity.Flags.On, state);
}
// not super efficient find a better way
else
{
string oven_name = CleanedName(oven.ShortPrefabName);
if ((config.Furnaces && (furnace_name.Contains(oven_name) ||
furnace_large_name.Contains(oven_name))) ||
(config.Lanterns && (lantern_name.Contains(oven_name) ||
chineselantern_name.Contains(oven_name) ||
tunalight_name.Contains(oven_name) ||
jackolanternangry_name.Contains(oven_name) ||
jackolanternhappy_name.Contains(oven_name))) ||
(config.Campfires && campfire_name.Contains(oven_name)) ||
(config.Fireplaces && fireplace_name.Contains(oven_name)) ||
(config.BBQs && bbq_name.Contains(oven_name)) ||
(config.Cauldrons && cursedcauldron_name.Contains(oven_name)) ||
(config.FirePits && skullfirepit_name.Contains(oven_name)) ||
(config.HoboBarrels && hobobarrel_name.Contains(oven_name)) ||
(config.Refineries && (smallrefinery_name.Contains(oven_name) || refinerysmall_name.Contains(oven_name)))
)
{
oven.SetFlag(BaseEntity.Flags.On, state);
}
}
}
}
if ((prefabName == "all" && config.SearchLights) || searchlight_name.Contains(prefabName))
{
SearchLight[] searchlights = UnityEngine.Object.FindObjectsOfType<SearchLight>() as SearchLight[];
foreach (SearchLight search_light in searchlights)
{
if (search_light != null && !search_light.IsDestroyed && search_light.IsOn() != state)
{
search_light.SetFlag(BaseEntity.Flags.On, state);
}
}
}
if ((prefabName == "all" && config.Candles) || (largecandleset_name.Contains(prefabName) || smallcandleset_name.Contains(prefabName)))
{
Candle[] candles = UnityEngine.Object.FindObjectsOfType<Candle>() as Candle[];
foreach (Candle candle in candles)
{
if (candle != null && !candle.IsDestroyed && candle.IsOn() != state)
{
candle.SetFlag(BaseEntity.Flags.On, state);
}
}
}
if ((prefabName == "all" && config.CeilingLights) || ceilinglight_name.Contains(prefabName))
{
CeilingLight[] ceilinglights = UnityEngine.Object.FindObjectsOfType<CeilingLight>() as CeilingLight[];
foreach (CeilingLight ceiling_light in ceilinglights)
{
if (ceiling_light != null && !ceiling_light.IsDestroyed && ceiling_light.IsOn() != state)
{
ceiling_light.SetFlag(BaseEntity.Flags.On, state);
}
}
}
if ((prefabName == "all" && config.SimpleLights) || simplelight_name.Contains(prefabName))
{
SimpleLight[] simplelights = UnityEngine.Object.FindObjectsOfType<SimpleLight>() as SimpleLight[];
foreach (SimpleLight simple_light in simplelights)
{
if (simple_light != null && !simple_light.IsDestroyed && simple_light.IsOn() != state)
{
simple_light.SetFlag(BaseEntity.Flags.On, state);
}
}
}
}
private void ProcessDevices(bool state, string prefabName)
{
//Puts("In ProcessDevices ");
if ((prefabName == "all" && config.Fog_Machines) || fogmachine_name.Contains(prefabName))
{
FogMachine[] fogmachines = UnityEngine.Object.FindObjectsOfType<FogMachine>() as FogMachine[];
foreach (FogMachine fog_machine in fogmachines)
{
if (!(fog_machine == null || fog_machine.IsDestroyed))
{
// there is bug with IsOn so force state
if (state) // if (fogmachine.IsOn() != state)
{
fog_machine.SetFlag(BaseEntity.Flags.On, state);
fog_machine.EnableFogField();
fog_machine.StartFogging();
fog_machine.SetFlag(BaseEntity.Flags.On, state);
}
else
{
fog_machine.SetFlag(BaseEntity.Flags.On, state);
fog_machine.FinishFogging();
fog_machine.DisableNozzle();
fog_machine.SetFlag(BaseEntity.Flags.On, state);
}
}
}
}
//if (!string.IsNullOrEmpty(prefabName) && snowmachine_name.Contains(prefabName)) Puts ("Snow machine"); else Puts("Not snow: " + prefabName);
//if (config.Snow_Machines) Puts("Snow is configure"); else Puts("Snow is not active");
if ((prefabName == "all" && config.Snow_Machines) || snowmachine_name.Contains(prefabName))
{
//if (state) Puts("Snow On"); else Puts("Snow Off");
SnowMachine[] snowmachines = UnityEngine.Object.FindObjectsOfType<SnowMachine>() as SnowMachine[];
foreach (SnowMachine snow_machine in snowmachines)
{
if (!(snow_machine == null || snow_machine.IsDestroyed))
{
// there is bug with IsOn so force state
if (state) // if (fogmachine.IsOn() != state)
{
snow_machine.SetFlag(BaseEntity.Flags.On, state);
snow_machine.EnableFogField();
snow_machine.StartFogging();
snow_machine.SetFlag(BaseEntity.Flags.On, state);
}
else
{
snow_machine.SetFlag(BaseEntity.Flags.On, state);
snow_machine.FinishFogging();
snow_machine.DisableNozzle();
snow_machine.SetFlag(BaseEntity.Flags.On, state);
}
}
}
}
if ((prefabName == "all" && config.StrobeLights) || strobelight_name.Contains(prefabName))
{
StrobeLight[] strobelights = UnityEngine.Object.FindObjectsOfType<StrobeLight>() as StrobeLight[];
foreach (StrobeLight strobelight in strobelights)
{
if (!(strobelight == null || strobelight.IsDestroyed) && strobelight.IsOn() != state)
strobelight.SetFlag(BaseEntity.Flags.On, state);
}
}
if ((prefabName == "all" && config.Speakers) || spookyspeaker_name.Contains(prefabName))
{
SpookySpeaker[] spookyspeakers = UnityEngine.Object.FindObjectsOfType<SpookySpeaker>() as SpookySpeaker[];
foreach (SpookySpeaker spookyspeaker in spookyspeakers)
{
if (!(spookyspeaker == null || spookyspeaker.IsDestroyed) && spookyspeaker.IsOn() != state)
{
spookyspeaker.SetFlag(BaseEntity.Flags.On, state);
spookyspeaker.SendPlaySound();
}
}
}
}
private object OnFindBurnable(BaseOven oven)
{
bool hasperm = false;
if (oven == null || string.IsNullOrEmpty(oven.ShortPrefabName) ||
oven.OwnerID == null || oven.OwnerID == 0U || oven.OwnerID.ToString() == null)
return null;
else
hasperm = permission.UserHasPermission(oven.OwnerID.ToString(), perm_freelights);
if (hasperm != true ||
!ProcessShortPrefabName(oven.ShortPrefabName) ||
!IsLightPrefabName(oven.ShortPrefabName))
return null;
else
{
//Puts("OnFindBurnable: " + oven.ShortPrefabName + " : " + oven.cookingTemperature);
oven.StopCooking();
oven.allowByproductCreation = false;
oven.SetFlag(BaseEntity.Flags.On, true);
if (oven.fuelType != null && oven.fuelType.itemid != null)
return ItemManager.CreateByItemID(oven.fuelType.itemid);
else
return null;
}
// catch all
return null;
}
// for jack o laterns
private void OnConsumeFuel(BaseOven oven, Item fuel, ItemModBurnable burnable)
{
if (oven == null || string.IsNullOrEmpty(oven.ShortPrefabName) ||
oven.OwnerID == null || oven.OwnerID == 0U || oven.OwnerID.ToString() == null)
return;
if (!permission.UserHasPermission(oven.OwnerID.ToString(), perm_freelights) ||
!ProcessShortPrefabName(oven.ShortPrefabName) ||
!IsLightPrefabName(oven.ShortPrefabName))
return;
else
{
fuel.amount += 1;
oven.StopCooking();
oven.allowByproductCreation = false;
oven.SetFlag(BaseEntity.Flags.On, true);
}
// catch all
return;
}
// for hats
private void OnItemUse(Item item, int amount)
{
string ShortPrefabName = item?.parent?.parent?.info?.shortname ?? item?.GetRootContainer()?.entityOwner?.ShortPrefabName;
BasePlayer player = null;
if (string.IsNullOrEmpty(ShortPrefabName) || !(IsHatPrefabName(ShortPrefabName)))
{
if (IsHatPrefabName(ShortPrefabName)) Puts ("Hat but no prefabname");
return;
}
else
{
try
{
player = item?.GetRootContainer()?.playerOwner;
}
catch
{
player = null;
}
if (player == null && string.IsNullOrEmpty(player.UserIDString))
{
return; // no owner so no permission
}
if (permission.UserHasPermission(player.UserIDString, perm_freelights))
{
item.amount += amount;
}
}
return;
}
object OnOvenToggle(BaseOven oven, BasePlayer player)
{
string cleanedname = null;
if (oven == null || string.IsNullOrEmpty(oven.ShortPrefabName) ||
player == null || player.UserIDString == null)
return null;
else
{
cleanedname = CleanedName(oven.ShortPrefabName);
//Puts(oven.ShortPrefabName + " : " + cleanedname + " : " + oven.IsOn());
}
if (!permission.UserHasPermission(player.UserIDString, perm_freelights) ||
!IsLightToggle(cleanedname)
//(!IsLightPrefabName(cleanedname)) // && !(IsOvenPrefabName(cleanedname) && ProcessShortPrefabName(oven.ShortPrefabName))))
)
{
return null;
}
else if (oven.IsOn() != true)
{
//Puts("off going on and allowed " + oven.temperature.ToString() + " : " + oven.cookingTemperature);
oven.SetFlag(BaseEntity.Flags.On, true);
oven.StopCooking();
oven.allowByproductCreation = false;
oven.SetFlag(BaseEntity.Flags.On, true);
}
else
{
//Puts("on going off and allowed " + oven.temperature.ToString() + " : " + oven.cookingTemperature);
oven.SetFlag(BaseEntity.Flags.On, false);
oven.StopCooking();
oven.SetFlag(BaseEntity.Flags.On, false);
}
// catch all
return null;
}
// automatically set lights on that are deployed if the lights are in the on state
private void OnEntitySpawned(BaseNetworkable entity)
{
// Puts(entity.ShortPrefabName);
// will turn the light on during a lights on phase or if neither is set to on
if ((config.AlwaysOn || NightToggleactive) &&
ProcessShortPrefabName(entity.ShortPrefabName))
{
if (entity is BaseOven)
{
var bo = entity as BaseOven;
bo.SetFlag(BaseEntity.Flags.On, true);
}
else if (entity is CeilingLight)
{
var cl = entity as CeilingLight;
cl.SetFlag(BaseEntity.Flags.On, true);
}
else if (entity is SimpleLight)
{
var sl = entity as SimpleLight;
sl.SetFlag(BaseEntity.Flags.On, true);
}
else if (entity is SearchLight)
{
var sl = entity as SearchLight;
sl.SetFlag(BaseEntity.Flags.On, true);
sl.secondsRemaining = 99999999;
}
else if (entity is Candle)
{
var ca = entity as Candle;
ca.SetFlag(BaseEntity.Flags.On, true);
}
}
if ((config.DevicesAlwaysOn || NightToggleactive) &&
ProcessShortPrefabName(entity.ShortPrefabName))
{
if (entity is FogMachine)
{
var fm = entity as FogMachine;
fm.SetFlag(BaseEntity.Flags.On, true);
fm.EnableFogField();
fm.StartFogging();
}
else if (entity is SnowMachine)
{
var sl = entity as SnowMachine;
sl.SetFlag(BaseEntity.Flags.On, true);
}
else if (entity is StrobeLight)
{
var sl = entity as StrobeLight;
sl.SetFlag(BaseEntity.Flags.On, true);
}
else if (entity is SpookySpeaker)
{
var ss = entity as SpookySpeaker;
ss.SetFlag(BaseEntity.Flags.On, true);
ss.SendPlaySound();
}
}
}
[Command("lights"), Permission(perm_lightson)]
private void ChatCommandlo(IPlayer player, string cmd, string[] args)
{
bool state = false;
string statestring = null;
string prefabName = null;
if (args == null || args.Length < 1)
{
player.Message(String.Concat(Lang("prefix", player.Id), Lang("syntax", player.Id)));
return;
}
else
{
// set the parameters
statestring = args[0].ToLower();
// make sure we have something to process default to all on
if (string.IsNullOrEmpty(statestring))
state = true;
else if (statestring == "off" || statestring == "false" || statestring == "0" || statestring == "out")
state = false;
else if (statestring == "on" || statestring == "true" || statestring == "1" || statestring == "go")
state = true;
else
{
player.Message(String.Concat(Lang("prefix", player.Id), Lang("state", player.Id)) + " " + statestring);
return;
}
// see if there is a prefabname specified and if so that it is valid
if (args.Length > 1)
{
prefabName = CleanedName(args[1].ToLower());
if(string.IsNullOrEmpty(prefabName))
prefabName = "all";
else if (prefabName != "all" &&
!IsLightPrefabName(prefabName) &&
!CanCookShortPrefabName(prefabName) &&
!IsDevicePrefabName(prefabName)
)
{
player.Message(String.Concat(Lang("prefix") , Lang("bad prefab", player.Id))+ " " + prefabName);
return;
}
}
else
prefabName = "all";
if (prefabName == "all")
{
ProcessLights(state, prefabName);
ProcessDevices(state, prefabName);
}
else
{
if (IsDevicePrefabName(prefabName))
ProcessDevices(state, prefabName);
if (IsLightPrefabName(prefabName) || CanCookShortPrefabName(CleanedName(prefabName)))
ProcessLights(state, prefabName);
}
if (state)
player.Message(String.Concat(Lang("prefix") , Lang("lights on", player.Id)) + " " + prefabName);
else
player.Message(String.Concat(Lang("prefix") , Lang("lights off", player.Id)) + " " + prefabName);
}
}
}
}
| 33.51489 | 171 | 0.650492 | [
"MIT"
] | john-clark/rust-oxide-umod | oxide/plugins/rust/LightsOn.cs | 34,889 | C# |
using Farming.WpfClient.Models;
using System.Collections.Generic;
using System.Linq;
using System.Windows;
using System.Windows.Controls;
namespace Farming.WpfClient.Controls
{
public abstract class PageView : UserControl
{
public static readonly DependencyProperty ActionContentProperty =
DependencyProperty.Register("ActionContent", typeof(object), typeof(PageView), new PropertyMetadata(null));
public object ActionContent
{
get { return GetValue(ActionContentProperty); }
set { SetValue(ActionContentProperty, value); }
}
public List<ICommandItem> ActionItems { get; }
public PageView()
{
ActionItems = new List<ICommandItem>();
}
private void DeactivatedItemsBesides(ActionItem item)
{
var items = ActionItems.OfType<ActionItem>();
if (items != null && items.Any())
{
foreach (var _item in items)
{
if (_item.Title != item.Title)
{
_item.IsActive = false;
}
}
}
}
protected virtual void UpdateContent(ActionItem currentActionItem, object content)
{
if (currentActionItem.IsActive)
{
DeactivatedItemsBesides(currentActionItem);
ActionContent = content;
}
else
{
ActionContent = null;
}
}
}
}
| 27.189655 | 119 | 0.543437 | [
"MIT"
] | holydk/Farming | Farming/Farming.WpfClient/Controls/PageView.cs | 1,579 | C# |
using System;
using System.Windows.Forms;
using Microsoft.Win32.TaskScheduler;
using System.IO;
using Tulpep.NotificationWindow;
namespace shshPatri0tS {
public partial class frmAutosaves : Form {
public static string taskName = "shsh Patri0tS AutoChecking";
private string taskExecPath = Path.Combine(Directory.GetCurrentDirectory(), System.AppDomain.CurrentDomain.FriendlyName);
public frmAutosaves() {
InitializeComponent();
}
private void frmAutosaves_Load(object sender, EventArgs e) {
using (TaskService ts = new TaskService()) {
Task t = ts.GetTask(taskName);
if (t != null) {
TaskDefinition td = t.Definition;
string[] tAction = td.Actions[0].ToString().Split(' ');
chkEnable.Checked = true;
chkCondesneNotifications.Checked = (tAction[tAction.Length - 1] == "1");
dtpStartTime.Value = td.Triggers[0].StartBoundary;
} else {
chkEnable_CheckedChanged(null, null);
Random rnd = new Random();
dtpStartTime.Value = DateTime.Parse(rnd.Next(7, 11) + ":" + (rnd.Next(0, 2) == 1 ? "3" : "0") + "0pm");
}
}
}
private void chkEnable_CheckedChanged(object sender, EventArgs e) {
// chkCondesneNotifications.Enabled = chkEnable.Checked;
gbCheckInterval.Enabled = chkEnable.Checked;
}
private void dtpStartTime_ValueChanged(object sender, EventArgs e) {
dtpEndTime.Value = dtpStartTime.Value.AddMinutes(30);
}
private void btnCancel_Click(object sender, EventArgs e) {
this.Close();
}
private void btnSave_Click(object sender, EventArgs e) {
try {
using (TaskService ts = new TaskService()) {
if (chkEnable.Checked) { // Autosaving is being enabled
TaskDefinition td = ts.NewTask(); // We do not need to lookup & delete previous task given how RegisterTaskDefinition() works below
td.RegistrationInfo.Description = "Automatically check for and download shsh blobs for all enabled profiles.";
td.Triggers.Add(new DailyTrigger { DaysInterval = 1, StartBoundary = dtpStartTime.Value });
td.Actions.Add(new ExecAction(taskExecPath, (chkCondesneNotifications.Checked ? "1" : "0"), Directory.GetCurrentDirectory()));
ts.RootFolder.RegisterTaskDefinition(taskName, td); // This will overwrite any previous task with the given name
} else { // Autosaving is being disabled
ts.RootFolder.DeleteTask(taskName);
}
}
PopupNotifier popup = PopupHelper.GeneratePopup("Autosave Settings were updated successfully.");
popup.Popup();
this.Close();
} catch (Exception ex) {
MessageBox.Show("Error: " + ex.Message + "\n\n" + ex.StackTrace);
}
}
}
}
| 29.823009 | 156 | 0.547774 | [
"MIT"
] | Xerotherm1c/JailbreakTools | shshPatri0tS/src/frmAutosaves.cs | 3,372 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
namespace _02._Integer_Insertion
{
class Program
{
static void Main(string[] args)
{
List<int> nums = Console.ReadLine().Split().Select(int.Parse).ToList();
string num = Console.ReadLine();
while (num != "end")
{
int position = num[0] - 48;
nums.Insert(position, int.Parse(num));
num = Console.ReadLine();
}
Console.WriteLine(string.Join(" ", nums));
}
}
}
| 21.703704 | 83 | 0.513652 | [
"MIT"
] | Svetloslav15/Softuni-Programming-Fundamentals | Extended Lists More Exercises/02. Integer Insertion/Program.cs | 588 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Amazon.Lambda.Core;
// Assembly attribute to enable the Lambda function's JSON input to be converted into a .NET class.
[assembly: LambdaSerializer(typeof(Amazon.Lambda.Serialization.Json.JsonSerializer))]
namespace NpgsqlExample
{
public class Function
{
/// <summary>
/// A simple function that takes a string and does a ToUpper
/// </summary>
/// <param name="input"></param>
/// <param name="context"></param>
/// <returns></returns>
public string FunctionHandler(string input, ILambdaContext context)
{
return input?.ToUpper();
}
}
}
| 26.785714 | 99 | 0.645333 | [
"Apache-2.0"
] | AbubakerB/aws-extensions-for-dotnet-cli | testapps/FlattenDependencyTestProjects/NpgsqlExample/Function.cs | 750 | C# |
using CarDealer.Models;
using JetBrains.Annotations;
using Microsoft.EntityFrameworkCore;
using System;
namespace CarDealer.Data
{
public class CarDealerContext : DbContext
{
public CarDealerContext(DbContextOptions options)
: base(options)
{
}
public CarDealerContext()
{
}
public DbSet<Car> Cars { get; set; }
public DbSet<Customer> Customers { get; set; }
public DbSet<Part> Parts { get; set; }
public DbSet<PartCar> PartCars { get; set; }
public DbSet<Sale> Sales { get; set; }
public DbSet<Supplier> Suppliers { get; set; }
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
if (!optionsBuilder.IsConfigured)
{
optionsBuilder.UseSqlServer("Server=DESKTOP-CUCRL15\\SQLEXPRESS;Database=CarDealer;Integrated Security=True;");
}
}
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<PartCar>(e =>
{
e.HasKey(k => new { k.CarId, k.PartId });
});
}
}
}
| 28.069767 | 127 | 0.584093 | [
"MIT"
] | RosenDev/Softuni-Problems | CarDealer/Data/CarDealerContext.cs | 1,209 | C# |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.