content stringlengths 5 1.04M | avg_line_length float64 1.75 12.9k | max_line_length int64 2 244k | alphanum_fraction float64 0 0.98 | licenses list | repository_name stringlengths 7 92 | path stringlengths 3 249 | size int64 5 1.04M | lang stringclasses 2
values |
|---|---|---|---|---|---|---|---|---|
using System;
using Microsoft.EntityFrameworkCore.Metadata;
using Microsoft.EntityFrameworkCore.Migrations;
namespace mtgdm.Data.Migrations
{
public partial class CreateIdentitySchema : Migration
{
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.CreateTable(
name: "AspNetRoles",
columns: table => new
{
Id = table.Column<string>(nullable: false),
Name = table.Column<string>(maxLength: 256, nullable: true),
NormalizedName = table.Column<string>(maxLength: 256, nullable: true),
ConcurrencyStamp = table.Column<string>(nullable: true)
},
constraints: table =>
{
table.PrimaryKey("PK_AspNetRoles", x => x.Id);
});
migrationBuilder.CreateTable(
name: "AspNetUsers",
columns: table => new
{
Id = table.Column<string>(nullable: false),
UserName = table.Column<string>(maxLength: 256, nullable: true),
NormalizedUserName = table.Column<string>(maxLength: 256, nullable: true),
Email = table.Column<string>(maxLength: 256, nullable: true),
NormalizedEmail = table.Column<string>(maxLength: 256, nullable: true),
EmailConfirmed = table.Column<bool>(nullable: false),
PasswordHash = table.Column<string>(nullable: true),
SecurityStamp = table.Column<string>(nullable: true),
ConcurrencyStamp = table.Column<string>(nullable: true),
PhoneNumber = table.Column<string>(nullable: true),
PhoneNumberConfirmed = table.Column<bool>(nullable: false),
TwoFactorEnabled = table.Column<bool>(nullable: false),
LockoutEnd = table.Column<DateTimeOffset>(nullable: true),
LockoutEnabled = table.Column<bool>(nullable: false),
AccessFailedCount = table.Column<int>(nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_AspNetUsers", x => x.Id);
});
migrationBuilder.CreateTable(
name: "AspNetRoleClaims",
columns: table => new
{
Id = table.Column<int>(nullable: false)
.Annotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn),
RoleId = table.Column<string>(nullable: false),
ClaimType = table.Column<string>(nullable: true),
ClaimValue = table.Column<string>(nullable: true)
},
constraints: table =>
{
table.PrimaryKey("PK_AspNetRoleClaims", x => x.Id);
table.ForeignKey(
name: "FK_AspNetRoleClaims_AspNetRoles_RoleId",
column: x => x.RoleId,
principalTable: "AspNetRoles",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
});
migrationBuilder.CreateTable(
name: "AspNetUserClaims",
columns: table => new
{
Id = table.Column<int>(nullable: false)
.Annotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn),
UserId = table.Column<string>(nullable: false),
ClaimType = table.Column<string>(nullable: true),
ClaimValue = table.Column<string>(nullable: true)
},
constraints: table =>
{
table.PrimaryKey("PK_AspNetUserClaims", x => x.Id);
table.ForeignKey(
name: "FK_AspNetUserClaims_AspNetUsers_UserId",
column: x => x.UserId,
principalTable: "AspNetUsers",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
});
migrationBuilder.CreateTable(
name: "AspNetUserLogins",
columns: table => new
{
LoginProvider = table.Column<string>(maxLength: 128, nullable: false),
ProviderKey = table.Column<string>(maxLength: 128, nullable: false),
ProviderDisplayName = table.Column<string>(nullable: true),
UserId = table.Column<string>(nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_AspNetUserLogins", x => new { x.LoginProvider, x.ProviderKey });
table.ForeignKey(
name: "FK_AspNetUserLogins_AspNetUsers_UserId",
column: x => x.UserId,
principalTable: "AspNetUsers",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
});
migrationBuilder.CreateTable(
name: "AspNetUserRoles",
columns: table => new
{
UserId = table.Column<string>(nullable: false),
RoleId = table.Column<string>(nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_AspNetUserRoles", x => new { x.UserId, x.RoleId });
table.ForeignKey(
name: "FK_AspNetUserRoles_AspNetRoles_RoleId",
column: x => x.RoleId,
principalTable: "AspNetRoles",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
table.ForeignKey(
name: "FK_AspNetUserRoles_AspNetUsers_UserId",
column: x => x.UserId,
principalTable: "AspNetUsers",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
});
migrationBuilder.CreateTable(
name: "AspNetUserTokens",
columns: table => new
{
UserId = table.Column<string>(nullable: false),
LoginProvider = table.Column<string>(maxLength: 128, nullable: false),
Name = table.Column<string>(maxLength: 128, nullable: false),
Value = table.Column<string>(nullable: true)
},
constraints: table =>
{
table.PrimaryKey("PK_AspNetUserTokens", x => new { x.UserId, x.LoginProvider, x.Name });
table.ForeignKey(
name: "FK_AspNetUserTokens_AspNetUsers_UserId",
column: x => x.UserId,
principalTable: "AspNetUsers",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
});
migrationBuilder.CreateIndex(
name: "IX_AspNetRoleClaims_RoleId",
table: "AspNetRoleClaims",
column: "RoleId");
migrationBuilder.CreateIndex(
name: "RoleNameIndex",
table: "AspNetRoles",
column: "NormalizedName",
unique: true,
filter: "[NormalizedName] IS NOT NULL");
migrationBuilder.CreateIndex(
name: "IX_AspNetUserClaims_UserId",
table: "AspNetUserClaims",
column: "UserId");
migrationBuilder.CreateIndex(
name: "IX_AspNetUserLogins_UserId",
table: "AspNetUserLogins",
column: "UserId");
migrationBuilder.CreateIndex(
name: "IX_AspNetUserRoles_RoleId",
table: "AspNetUserRoles",
column: "RoleId");
migrationBuilder.CreateIndex(
name: "EmailIndex",
table: "AspNetUsers",
column: "NormalizedEmail");
migrationBuilder.CreateIndex(
name: "UserNameIndex",
table: "AspNetUsers",
column: "NormalizedUserName",
unique: true,
filter: "[NormalizedUserName] IS NOT NULL");
}
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropTable(
name: "AspNetRoleClaims");
migrationBuilder.DropTable(
name: "AspNetUserClaims");
migrationBuilder.DropTable(
name: "AspNetUserLogins");
migrationBuilder.DropTable(
name: "AspNetUserRoles");
migrationBuilder.DropTable(
name: "AspNetUserTokens");
migrationBuilder.DropTable(
name: "AspNetRoles");
migrationBuilder.DropTable(
name: "AspNetUsers");
}
}
}
| 43.058824 | 122 | 0.498214 | [
"MIT"
] | ZombieFleshEaters/mtgdm | mtgdm/Data/Migrations/00000000000000_CreateIdentitySchema.cs | 9,518 | C# |
using System;
using System.Collections.Generic;
using System.Text;
namespace Axiom.Runtime.Builtins.Meta
{
// bound(Term)
public class BoundPredicate : AbstractPredicate
{
public override int Arity()
{
return 1;
}
public override string Name()
{
return "bound";
}
public override void Execute(AbstractMachineState state)
{
AMProgram program = (AMProgram)state.Program;
AbstractTerm X0 = ((AbstractTerm)state["X0"]).Dereference();
if (X0.IsReference && X0.Reference() == X0)
{
program.Next();
}
else
{
state.Backtrack();
}
}
}
}
| 20.368421 | 72 | 0.505168 | [
"MIT"
] | FacticiusVir/prologdotnet | Prolog.AbstractMachine/Builtins/Meta/BoundPredicate.cs | 774 | C# |
using System;
using System.Collections.Generic;
using System.Runtime.CompilerServices;
namespace Stl.Collections.Slim
{
public struct RefHashSetSlim2<T> : IRefHashSetSlim<T>
where T : class
{
private (T?, T?) _tuple;
private HashSet<T>? _set;
private bool HasSet {
[MethodImpl(MethodImplOptions.AggressiveInlining)]
get => _set != null;
}
public int Count {
get {
if (HasSet) return _set!.Count;
if (_tuple.Item1 == null) return 0;
if (_tuple.Item2 == null) return 1;
return 2;
}
}
public bool Contains(T item)
{
if (item == null)
throw new ArgumentNullException(nameof(item));
if (HasSet) return _set!.Contains(item);
if (_tuple.Item1 == item) return true;
if (_tuple.Item2 == item) return true;
return false;
}
public bool Add(T item)
{
if (item == null)
throw new ArgumentNullException(nameof(item));
if (HasSet) return _set!.Add(item);
// Item 1
if (_tuple.Item1 == null) {
_tuple.Item1 = item;
return true;
}
if (_tuple.Item1 == item) return false;
// Item 2
if (_tuple.Item2 == null) {
_tuple.Item2 = item;
return true;
}
if (_tuple.Item2 == item) return false;
_set = new HashSet<T>(ReferenceEqualityComparer<T>.Instance) {
_tuple.Item1, _tuple.Item2, item
};
_tuple = default;
return true;
}
public bool Remove(T item)
{
if (item == null)
throw new ArgumentNullException(nameof(item));
if (HasSet) return _set!.Remove(item);
// Item 1
if (_tuple.Item1 == null) return false;
if (_tuple.Item1 == item) {
_tuple = (_tuple.Item2, default!)!;
return true;
}
// Item 2
if (_tuple.Item2 == null) return false;
if (_tuple.Item2 == item) {
_tuple = (_tuple.Item1, default!)!;
return true;
}
return false;
}
public void Clear()
{
_set = null;
_tuple = default!;
}
public IEnumerable<T> Items {
get {
if (HasSet) {
foreach (var item in _set!)
yield return item;
yield break;
}
if (_tuple.Item1 == null) yield break;
yield return _tuple.Item1;
if (_tuple.Item2 == null) yield break;
yield return _tuple.Item2;
}
}
public void Apply<TState>(TState state, Action<TState, T> action)
{
if (HasSet) {
foreach (var item in _set!)
action(state, item);
return;
}
if (_tuple.Item1 == null) return;
action(state, _tuple.Item1);
if (_tuple.Item2 == null) return;
action(state, _tuple.Item2);
}
public void Aggregate<TState>(ref TState state, Aggregator<TState, T> aggregator)
{
if (HasSet) {
foreach (var item in _set!)
aggregator(ref state, item);
return;
}
if (_tuple.Item1 == null) return;
aggregator(ref state, _tuple.Item1);
if (_tuple.Item2 == null) return;
aggregator(ref state, _tuple.Item2);
}
public TState Aggregate<TState>(TState state, Func<TState, T, TState> aggregator)
{
if (HasSet) {
foreach (var item in _set!)
state = aggregator(state, item);
return state;
}
if (_tuple.Item1 == null) return state;
state = aggregator(state, _tuple.Item1);
if (_tuple.Item2 == null) return state;
state = aggregator(state, _tuple.Item2);
return state;
}
public void CopyTo(Span<T> target)
{
var index = 0;
if (HasSet) {
foreach (var item in _set!)
target[index++] = item;
return;
}
if (_tuple.Item1 == null) return;
target[index++] = _tuple.Item1;
if (_tuple.Item2 == null) return;
target[index] = _tuple.Item2;
}
}
}
| 29.060606 | 89 | 0.459437 | [
"MIT"
] | MessiDaGod/Stl.Fusion | src/Stl/Collections/Slim/RefHashSetSlim2.cs | 4,795 | C# |
/***************************************************************************************************************************************
* Copyright (C) 2001-2012 LearnLift USA *
* Contact: Learnlift USA, 12 Greenway Plaza, Suite 1510, Houston, Texas 77046, support@memorylifter.com *
* *
* This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License *
* as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. *
* *
* This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty *
* of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. *
* *
* You should have received a copy of the GNU Lesser General Public License along with this library; if not, *
* write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA *
***************************************************************************************************************************************/
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Xml;
using MLifter.DAL.DB.MsSqlCe;
using MLifter.DAL.DB.PostgreSQL;
using MLifter.DAL.Interfaces;
using MLifter.DAL.Tools;
using MLifter.DAL.Security;
namespace MLifter.DAL.DB
{
/// <summary>
/// Database implementation of ICard.
/// </summary>
/// <remarks>Documented by Dev05, 2008-07-25</remarks>
class DbCard : MLifter.DAL.Interfaces.ICard
{
private Interfaces.DB.IDbCardConnector connector
{
get
{
switch (parent.CurrentUser.ConnectionString.Typ)
{
case DatabaseType.PostgreSQL:
return MLifter.DAL.DB.PostgreSQL.PgSqlCardConnector.GetInstance(parent);
case DatabaseType.MsSqlCe:
return MLifter.DAL.DB.MsSqlCe.MsSqlCeCardConnector.GetInstance(parent);
default:
throw new UnsupportedDatabaseTypeException(parent.CurrentUser.ConnectionString.Typ);
}
}
}
private Interfaces.DB.IDbCardMediaConnector cardmediaconnector
{
get
{
switch (parent.CurrentUser.ConnectionString.Typ)
{
case DatabaseType.PostgreSQL:
return PgSqlCardMediaConnector.GetInstance(parent);
case DatabaseType.MsSqlCe:
switch (parent.CurrentUser.ConnectionString.SyncType)
{
case SyncType.NotSynchronized:
return MsSqlCeCardMediaConnector.GetInstance(parent);
case SyncType.HalfSynchronizedWithDbAccess:
return PgSqlCardMediaConnector.GetInstance(new ParentClass(parent.CurrentUser.ConnectionString.ServerUser, this));
case SyncType.FullSynchronized:
return MsSqlCeCardMediaConnector.GetInstance(parent);
case SyncType.HalfSynchronizedWithoutDbAccess:
default:
throw new NotAllowedInSyncedModeException();
}
default:
throw new UnsupportedDatabaseTypeException(parent.CurrentUser.ConnectionString.Typ);
}
}
}
protected Interfaces.DB.IDbCardMediaConnector cardmediaPropertiesConnector
{
get
{
switch (parent.CurrentUser.ConnectionString.Typ)
{
case DatabaseType.PostgreSQL:
return PgSqlCardMediaConnector.GetInstance(parent);
case DatabaseType.MsSqlCe:
return MsSqlCeCardMediaConnector.GetInstance(parent);
default:
throw new UnsupportedDatabaseTypeException(parent.CurrentUser.ConnectionString.Typ);
}
}
}
private Interfaces.DB.IDbCardStyleConnector cardstyleconnector
{
get
{
switch (parent.CurrentUser.ConnectionString.Typ)
{
case DatabaseType.PostgreSQL:
return PostgreSQL.PgSqlCardStyleConnector.GetInstance(parent);
case DatabaseType.MsSqlCe:
return MsSqlCe.MsSqlCeCardStyleConnector.GetInstance(parent);
default:
throw new UnsupportedDatabaseTypeException(parent.CurrentUser.ConnectionString.Typ);
}
}
}
/// <summary>
/// Initializes a new instance of the <see cref="DbCard"/> class.
/// </summary>
/// <param name="id">The id.</param>
/// <param name="parentClass">The parent class.</param>
/// <remarks>Documented by Dev03, 2009-01-13</remarks>
public DbCard(int id, ParentClass parentClass) : this(id, true, parentClass) { }
/// <summary>
/// Initializes a new instance of the <see cref="DbCard"/> class.
/// </summary>
/// <param name="id">The id.</param>
/// <param name="checkId">if set to <c>true</c> [check id].</param>
/// <param name="parentClass">The parent class.</param>
/// <remarks>Documented by Dev03, 2009-01-13</remarks>
public DbCard(int id, bool checkId, ParentClass parentClass)
{
parent = parentClass;
if (checkId)
connector.CheckCardId(id);
this.id = id;
question = new DbWords(id, Side.Question, WordType.Word, Parent.GetChildParentClass(this));
questionExample = new DbWords(id, Side.Question, WordType.Sentence, Parent.GetChildParentClass(this));
questionDistractors = new DbWords(id, Side.Question, WordType.Distractor, Parent.GetChildParentClass(this));
answer = new DbWords(id, Side.Answer, WordType.Word, Parent.GetChildParentClass(this));
answerExample = new DbWords(id, Side.Answer, WordType.Sentence, Parent.GetChildParentClass(this));
answerDistractors = new DbWords(id, Side.Answer, WordType.Distractor, Parent.GetChildParentClass(this));
}
/// <summary>
/// Returns a <see cref="T:System.String"/> that represents the current <see cref="T:System.Object"/>.
/// </summary>
/// <returns>
/// A <see cref="T:System.String"/> that represents the current <see cref="T:System.Object"/>.
/// </returns>
/// <remarks>Documented by Dev03, 2009-01-13</remarks>
public override string ToString()
{
return String.Format("{0} - {1} - {2}", Id, Question, Answer);
}
public override bool Equals(object card)
{
if (card as ICard == null)
return false;
return this.id == (card as ICard).Id;
}
public override int GetHashCode()
{
return this.id;
}
#region ICard Members
/// <summary>
/// Occurs when [create media progress changed].
/// </summary>
/// <remarks>Documented by Dev03, 2008-08-21</remarks>
public event StatusMessageEventHandler CreateMediaProgressChanged;
/// <summary>
/// Gets the card.
/// </summary>
/// <value>The card.</value>
/// <remarks>Documented by Dev03, 2007-09-03</remarks>
/// <remarks>Documented by Dev03, 2009-01-13</remarks>
public XmlElement Card
{
get
{
return Helper.GenerateXmlCard(this);
}
}
/// <summary>
/// Gets or sets a value indicating whether this <see cref="ICard"/> is active.
/// </summary>
/// <value><c>true</c> if active; otherwise, <c>false</c>.</value>
/// <remarks>Documented by Dev03, 2007-09-03</remarks>
/// <remarks>Documented by Dev03, 2009-01-13</remarks>
public bool Active
{
get
{
return connector.GetActive(id);
}
set
{
connector.SetActive(id, value);
}
}
private int id;
/// <summary>
/// Gets or sets the id.
/// </summary>
/// <value>The id.</value>
/// <remarks>Documented by Dev03, 2007-09-03</remarks>
/// <remarks>Documented by Dev03, 2009-01-13</remarks>
public int Id
{
get
{
return id;
}
}
/// <summary>
/// Gets or sets the box.
/// </summary>
/// <value>The box.</value>
/// <remarks>Documented by Dev03, 2007-09-03</remarks>
/// <remarks>Documented by Dev03, 2009-01-13</remarks>
public int Box
{
get
{
return connector.GetBox(id);
}
set
{
if (value < -1 || value > 10)
throw new InvalidBoxException(value);
connector.SetBox(id, value == -1 ? 0 : value);
}
}
/// <summary>
/// Gets or sets the chapter.
/// </summary>
/// <value>The chapter.</value>
/// <remarks>Documented by Dev03, 2007-09-03</remarks>
/// <remarks>Documented by Dev03, 2009-01-13</remarks>
public int Chapter
{
get
{
return connector.GetChapter(id);
}
set
{
DbChapter chapter = new DbChapter(value, Parent);
if (!chapter.HasPermission(PermissionTypes.CanModify))
throw new PermissionException();
connector.SetChapter(id, value);
}
}
/// <summary>
/// Gets or sets the timestamp.
/// </summary>
/// <value>The timestamp.</value>
/// <remarks>Documented by Dev03, 2007-09-03</remarks>
/// <remarks>Documented by Dev03, 2009-01-13</remarks>
public DateTime Timestamp
{
get
{
return connector.GetTimestamp(id);
}
set
{
connector.SetTimestamp(id, value);
}
}
private IWords question;
/// <summary>
/// Gets or sets the question.
/// </summary>
/// <value>The question.</value>
/// <remarks>Documented by Dev03, 2007-09-03</remarks>
/// <remarks>Documented by Dev03, 2009-01-13</remarks>
public IWords Question
{
get
{
return question;
}
set
{
question = value;
}
}
private IWords questionExample;
/// <summary>
/// Gets or sets the question example.
/// </summary>
/// <value>The question example.</value>
/// <remarks>Documented by Dev03, 2007-09-03</remarks>
/// <remarks>Documented by Dev03, 2009-01-13</remarks>
public IWords QuestionExample
{
get
{
return questionExample;
}
set
{
questionExample = value;
}
}
/// <summary>
/// Gets or sets the question stylesheet.
/// </summary>
/// <value>The question stylesheet.</value>
/// <remarks>Documented by Dev03, 2009-01-13</remarks>
public string QuestionStylesheet
{
get
{
Debug.WriteLine("The method or operation is not implemented.");
return string.Empty;
}
set
{
Debug.WriteLine("The method or operation is not implemented.");
}
}
/// <summary>
/// Gets or sets the question media.
/// </summary>
/// <value>The question media.</value>
/// <remarks>Documented by Dev03, 2007-09-03</remarks>
/// <remarks>Documented by Dev03, 2009-01-13</remarks>
public IList<IMedia> QuestionMedia
{
get
{
IList<int> ids = cardmediaPropertiesConnector.GetCardMedia(Id, Side.Question);
IList<IMedia> media = new List<IMedia>();
foreach (int cardid in ids)
media.Add(cardmediaPropertiesConnector.GetMedia(cardid, Id));
return media;
}
}
private IWords questionDistractors;
/// <summary>
/// Gets or sets the question distractors.
/// </summary>
/// <value>The question distractors.</value>
/// <remarks>Documented by Dev03, 2008-01-07</remarks>
/// <remarks>Documented by Dev03, 2009-01-13</remarks>
public IWords QuestionDistractors
{
get
{
return questionDistractors;
}
set
{
questionDistractors = value;
}
}
private IWords answer;
/// <summary>
/// Gets or sets the answer.
/// </summary>
/// <value>The answer.</value>
/// <remarks>Documented by Dev03, 2007-09-03</remarks>
/// <remarks>Documented by Dev03, 2009-01-13</remarks>
public IWords Answer
{
get
{
return answer;
}
set
{
answer = value;
}
}
private IWords answerExample;
/// <summary>
/// Gets or sets the answer example.
/// </summary>
/// <value>The answer example.</value>
/// <remarks>Documented by Dev03, 2007-09-03</remarks>
/// <remarks>Documented by Dev03, 2009-01-13</remarks>
public IWords AnswerExample
{
get
{
return answerExample;
}
set
{
answerExample = value;
}
}
/// <summary>
/// Gets or sets the answer stylesheet.
/// </summary>
/// <value>The answer stylesheet.</value>
/// <remarks>Documented by Dev03, 2009-01-13</remarks>
public string AnswerStylesheet
{
get
{
Debug.WriteLine("The method or operation is not implemented.");
return string.Empty;
}
set
{
Debug.WriteLine("The method or operation is not implemented.");
}
}
/// <summary>
/// Gets or sets the answer media.
/// </summary>
/// <value>The answer media.</value>
/// <remarks>Documented by Dev03, 2007-09-03</remarks>
/// <remarks>Documented by Dev03, 2009-01-13</remarks>
public IList<IMedia> AnswerMedia
{
get
{
IList<int> ids = cardmediaPropertiesConnector.GetCardMedia(Id, Side.Answer);
IList<IMedia> media = new List<IMedia>();
foreach (int cardid in ids)
media.Add(cardmediaPropertiesConnector.GetMedia(cardid, Id));
return media;
}
}
private IWords answerDistractors;
/// <summary>
/// Gets or sets the answer distractors.
/// </summary>
/// <value>The answer distractors.</value>
/// <remarks>Documented by Dev03, 2008-01-07</remarks>
/// <remarks>Documented by Dev03, 2009-01-13</remarks>
public IWords AnswerDistractors
{
get
{
return answerDistractors;
}
set
{
answerDistractors = value;
}
}
/// <summary>
/// Adds the media.
/// </summary>
/// <param name="media">The media.</param>
/// <param name="side">The side.</param>
/// <returns>The media object.</returns>
/// <remarks>Documented by Dev03, 2007-09-03</remarks>
/// <remarks>Documented by Dev03, 2008-08-25</remarks>
public IMedia AddMedia(IMedia media, Side side)
{
if (media == null)
throw new NullReferenceException("Media object must not be null!");
//[ML-1508] Can not add Media (images) to a LM:
if (media.Parent == null || media.Parent.CurrentUser.ConnectionString.ConnectionString != parent.CurrentUser.ConnectionString.ConnectionString)
media = CreateMedia(media.MediaType, media.Filename, media.Active.Value, media.Default.Value, media.Example.Value);
try
{
if (media.MediaType == EMedia.Audio)
{
cardmediaconnector.SetCardMedia(media.Id, Id, side,
media.Example.GetValueOrDefault() ? WordType.Sentence : WordType.Word, media.Default.GetValueOrDefault(), media.MediaType);
}
else
{
cardmediaconnector.SetCardMedia(media.Id, Id, side, WordType.Word, false, media.MediaType);
}
}
catch (Exception ex)
{
Debug.WriteLine(ex, "DbCard.AddMedia() throws an exception.");
return null;
}
return media;
}
/// <summary>
/// Removes the media.
/// </summary>
/// <param name="media">The media.</param>
/// <remarks>Documented by Dev03, 2007-09-03</remarks>
/// <remarks>Documented by Dev03, 2009-01-13</remarks>
public void RemoveMedia(IMedia media)
{
cardmediaconnector.ClearCardMedia(Id, media.Id);
}
/// <summary>
/// Creates the media.
/// </summary>
/// <param name="type">The type of the media file.</param>
/// <param name="path">The path to the media file.</param>
/// <param name="isActive">if set to <c>true</c> [is active].</param>
/// <param name="isDefault">if set to <c>true</c> [is default].</param>
/// <param name="isExample">if set to <c>true</c> [is example].</param>
/// <returns></returns>
/// <remarks>Documented by Dev03, 2007-09-03</remarks>
/// <remarks>Documented by Dev03, 2009-01-13</remarks>
public IMedia CreateMedia(EMedia type, string path, bool isActive, bool isDefault, bool isExample)
{
StatusMessageReportProgress rpu = new StatusMessageReportProgress(ReportProgressUpdate);
return (parent.GetParentDictionary() as DbDictionary).CreateNewMediaObject(this, rpu, type, path, isActive, isDefault, isExample);
}
/// <summary>
/// Sends the status message update.
/// </summary>
/// <param name="args">The <see cref="MLifter.DAL.Tools.StatusMessageEventArgs"/> instance containing the event data.</param>
/// <param name="caller">The caller.</param>
/// <returns>
/// [true] if the process should be canceled.
/// </returns>
/// <remarks>
/// Documented by AAB, 20.8.2008.
/// </remarks>
private bool ReportProgressUpdate(StatusMessageEventArgs args, object caller)
{
switch (args.MessageType)
{
case StatusMessageType.CreateMediaProgress:
if ((caller != null) && (caller is DbCard) && ((caller as DbCard).CreateMediaProgressChanged != null))
(caller as DbCard).CreateMediaProgressChanged(null, args);
break;
}
return true;
}
/// <summary>
/// Clears all media.
/// </summary>
/// <remarks>Documented by Dev03, 2007-09-03</remarks>
/// <remarks>Documented by Dev03, 2009-01-13</remarks>
public void ClearAllMedia()
{
ClearAllMedia(false);
}
/// <summary>
/// Clears all media.
/// </summary>
/// <param name="removeFiles">if set to <c>true</c> [remove files].</param>
/// <remarks>Documented by Dev03, 2007-09-03</remarks>
/// <remarks>Documented by Dev03, 2009-01-13</remarks>
public void ClearAllMedia(bool removeFiles)
{
cardmediaconnector.ClearCardMedia(Id);
}
/// <summary>
/// Creates and returns a card style.
/// </summary>
/// <returns></returns>
/// <remarks>Documented by Dev03, 2008-01-08</remarks>
/// <remarks>Documented by Dev03, 2009-01-13</remarks>
public ICardStyle CreateCardStyle()
{
if (Settings == null)
Settings = (parent.GetParentDictionary() as DbDictionary).CreateSettingsObject();
return new DbCardStyle((Settings.Style as DbCardStyle).Id, parent);
}
/// <summary>
/// Gets or sets the settings.
/// </summary>
/// <value>The settings.</value>
/// <remarks>Documented by Dev05, 2008-08-19</remarks>
/// <remarks>Documented by Dev03, 2009-01-13</remarks>
public ISettings Settings
{
get
{
return connector.GetSettings(id);
}
set
{
connector.SetSettings(id, value);
}
}
#endregion
#region IDisposable Members
/// <summary>
/// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
/// </summary>
/// <remarks>Documented by Dev03, 2009-01-13</remarks>
public void Dispose()
{
Debug.WriteLine("The method or operation is not implemented.");
}
#endregion
#region ICopy Members
/// <summary>
/// Copies to.
/// </summary>
/// <param name="target">The target.</param>
/// <param name="progressDelegate">The progress delegate.</param>
/// <remarks>Documented by Dev03, 2009-01-13</remarks>
public void CopyTo(ICopy target, CopyToProgress progressDelegate)
{
CopyBase.Copy(this, target, typeof(ICard), progressDelegate);
//copy media objects
ICard targetCard = target as ICard;
if (targetCard != null)
{
foreach (IMedia media in QuestionMedia)
targetCard.AddMedia(media, Side.Question);
foreach (IMedia media in AnswerMedia)
targetCard.AddMedia(media, Side.Answer);
try
{
if (targetCard is MLifter.DAL.XML.XmlCard)
(targetCard as MLifter.DAL.XML.XmlCard).Id = Id;
}
catch (Exception ex)
{
Trace.WriteLine("Tried to set the card id for XML but failed: " + ex.ToString());
}
}
}
#endregion
#region IParent Members
private ParentClass parent;
/// <summary>
/// Gets the parent.
/// </summary>
/// <value>The parent.</value>
/// <remarks>Documented by Dev03, 2009-01-13</remarks>
public ParentClass Parent { get { return parent; } }
#endregion
#region ISecurity Members
/// <summary>
/// Determines whether the object has the specified permission.
/// </summary>
/// <param name="permissionName">Name of the permission.</param>
/// <returns>
/// <c>true</c> if the object name has the specified permission; otherwise, <c>false</c>.
/// </returns>
/// <remarks>Documented by Dev03, 2009-01-15</remarks>
/// <remarks>Documented by Dev03, 2009-01-15</remarks>
public bool HasPermission(string permissionName)
{
return Parent.CurrentUser.HasPermission(this, permissionName);
}
/// <summary>
/// Gets the permissions for the object.
/// </summary>
/// <returns>A list of permissions for the object.</returns>
/// <remarks>Documented by Dev03, 2009-01-15</remarks>
/// <remarks>Documented by Dev03, 2009-01-15</remarks>
public List<SecurityFramework.PermissionInfo> GetPermissions()
{
return Parent.CurrentUser.GetPermissions(this);
}
#endregion
}
}
| 35.992826 | 155 | 0.523179 | [
"MIT"
] | hmehr/OSS | MemoryLifter/Development/Current/MLifter.DAL/DB/DbCard.cs | 25,087 | C# |
#pragma warning disable 1591
//------------------------------------------------------------------------------
// <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 ASP
{
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Web;
using System.Web.Helpers;
using System.Web.Mvc;
using System.Web.Mvc.Ajax;
using System.Web.Mvc.Html;
using System.Web.Routing;
using System.Web.Security;
using System.Web.UI;
using System.Web.WebPages;
#line 3 "..\..\Views\DeleteMatchLocation.cshtml"
using ClientDependency.Core.Mvc;
#line default
#line hidden
#line 6 "..\..\Views\DeleteMatchLocation.cshtml"
using Constants = Stoolball.Constants;
#line default
#line hidden
using Examine;
#line 2 "..\..\Views\DeleteMatchLocation.cshtml"
using Humanizer;
#line default
#line hidden
#line 5 "..\..\Views\DeleteMatchLocation.cshtml"
using Stoolball.Security;
#line default
#line hidden
#line 4 "..\..\Views\DeleteMatchLocation.cshtml"
using Stoolball.Web.MatchLocations;
#line default
#line hidden
using Umbraco.Core;
using Umbraco.Core.Models;
using Umbraco.Core.Models.PublishedContent;
using Umbraco.Web;
using Umbraco.Web.Mvc;
using Umbraco.Web.PublishedModels;
[System.CodeDom.Compiler.GeneratedCodeAttribute("RazorGenerator", "2.0.0.0")]
[System.Web.WebPages.PageVirtualPathAttribute("~/Views/DeleteMatchLocation.cshtml")]
public partial class _Views_DeleteMatchLocation_cshtml : Umbraco.Web.Mvc.UmbracoViewPage<Stoolball.Web.MatchLocations.DeleteMatchLocationViewModel>
{
public _Views_DeleteMatchLocation_cshtml()
{
}
public override void Execute()
{
#line 7 "..\..\Views\DeleteMatchLocation.cshtml"
Html.EnableClientValidation();
Html.EnableUnobtrusiveJavaScript();
Html.RequiresJs("~/scripts/jquery.validate.min.js");
Html.RequiresJs("~/scripts/jquery.validate.unobtrusive.min.js");
#line default
#line hidden
WriteLiteral("\r\n");
DefineSection("head", () => {
WriteLiteral("\r\n <meta");
WriteLiteral(" name=\"robots\"");
WriteLiteral(" content=\"noindex,follow\"");
WriteLiteral(" />\r\n");
});
WriteLiteral("<div");
WriteLiteral(" class=\"container-xl\"");
WriteLiteral(">\r\n <h1>Delete ");
#line 17 "..\..\Views\DeleteMatchLocation.cshtml"
Write(Model.MatchLocation.NameAndLocalityOrTownIfDifferent());
#line default
#line hidden
WriteLiteral("</h1>\r\n\r\n");
#line 19 "..\..\Views\DeleteMatchLocation.cshtml"
#line default
#line hidden
#line 19 "..\..\Views\DeleteMatchLocation.cshtml"
if (Model.IsAuthorized[AuthorizedAction.DeleteMatchLocation])
{
if (!Model.Deleted)
{
#line default
#line hidden
WriteLiteral(" <p>If you delete ");
#line 23 "..\..\Views\DeleteMatchLocation.cshtml"
Write(Model.MatchLocation.Name());
#line default
#line hidden
WriteLiteral(" you will:</p>\r\n");
WriteLiteral(" <ul>\r\n");
#line 25 "..\..\Views\DeleteMatchLocation.cshtml"
#line default
#line hidden
#line 25 "..\..\Views\DeleteMatchLocation.cshtml"
if (Model.TotalMatches > 0)
{
#line default
#line hidden
WriteLiteral(" <li>leave ");
#line 27 "..\..\Views\DeleteMatchLocation.cshtml"
Write("match".ToQuantity(Model.TotalMatches));
#line default
#line hidden
WriteLiteral(" with an unknown location</li>\r\n");
WriteLiteral(" <li>change statistics for the teams and players that have pla" +
"yed here</li>\r\n");
#line 29 "..\..\Views\DeleteMatchLocation.cshtml"
}
else
{
#line default
#line hidden
WriteLiteral(" <li>not affect any matches</li>\r\n");
WriteLiteral(" <li>not affect any statistics</li>\r\n");
#line 34 "..\..\Views\DeleteMatchLocation.cshtml"
}
#line default
#line hidden
WriteLiteral(" ");
#line 35 "..\..\Views\DeleteMatchLocation.cshtml"
if (Model.MatchLocation.Teams.Count > 0)
{
#line default
#line hidden
WriteLiteral(" <li>leave ");
#line 37 "..\..\Views\DeleteMatchLocation.cshtml"
Write(Model.MatchLocation.Teams.Humanize(x => x.TeamName));
#line default
#line hidden
WriteLiteral(" without their home ground or sports centre</li>\r\n");
#line 38 "..\..\Views\DeleteMatchLocation.cshtml"
}
else
{
#line default
#line hidden
WriteLiteral(" <li>not affect any teams</li>\r\n");
#line 42 "..\..\Views\DeleteMatchLocation.cshtml"
}
#line default
#line hidden
WriteLiteral(" </ul>\r\n");
WriteLiteral(" <p><strong><strong>You cannot undo this.</strong></strong></p>\r\n");
#line 45 "..\..\Views\DeleteMatchLocation.cshtml"
using (Html.BeginUmbracoForm<DeleteMatchLocationSurfaceController>
("DeleteMatchLocation"))
{
#line default
#line hidden
#line 49 "..\..\Views\DeleteMatchLocation.cshtml"
Write(Html.AntiForgeryToken());
#line default
#line hidden
#line 49 "..\..\Views\DeleteMatchLocation.cshtml"
#line default
#line hidden
#line 51 "..\..\Views\DeleteMatchLocation.cshtml"
Write(Html.HiddenFor(m => Model.ConfirmDeleteRequest.RequiredText));
#line default
#line hidden
#line 51 "..\..\Views\DeleteMatchLocation.cshtml"
#line default
#line hidden
WriteLiteral(" <div");
WriteLiteral(" class=\"form-group\"");
WriteLiteral(">\r\n");
WriteLiteral(" ");
#line 53 "..\..\Views\DeleteMatchLocation.cshtml"
Write(Html.LabelFor(m => Model.ConfirmDeleteRequest.ConfirmationText, $"If you're sure you wish to continue, type '{Model.MatchLocation.NameAndLocalityOrTownIfDifferent()}' into this box:"));
#line default
#line hidden
WriteLiteral("\r\n");
WriteLiteral(" ");
#line 54 "..\..\Views\DeleteMatchLocation.cshtml"
Write(Html.TextBoxFor(m => Model.ConfirmDeleteRequest.ConfirmationText, new { @class = "form-control", required = "required", aria_describedby = "validation", autocorrect = "off", autocapitalize = "off", autocomplete = "off", spellcheck = "false" }));
#line default
#line hidden
WriteLiteral("\r\n");
WriteLiteral(" ");
#line 55 "..\..\Views\DeleteMatchLocation.cshtml"
Write(Html.ValidationMessageFor(m => Model.ConfirmDeleteRequest.ConfirmationText, null, new { id = "validation" }));
#line default
#line hidden
WriteLiteral("\r\n </div>\r\n");
#line 57 "..\..\Views\DeleteMatchLocation.cshtml"
#line default
#line hidden
WriteLiteral(" <button");
WriteLiteral(" class=\"btn btn-danger btn-delete\"");
WriteLiteral(">Delete ");
#line 58 "..\..\Views\DeleteMatchLocation.cshtml"
Write(Model.MatchLocation.NameAndLocalityOrTownIfDifferent());
#line default
#line hidden
WriteLiteral("</button>\r\n");
#line 59 "..\..\Views\DeleteMatchLocation.cshtml"
}
}
else
{
#line default
#line hidden
WriteLiteral(" <p>");
#line 63 "..\..\Views\DeleteMatchLocation.cshtml"
Write(Model.MatchLocation.NameAndLocalityOrTownIfDifferent());
#line default
#line hidden
WriteLiteral(" has been deleted.</p>\r\n");
WriteLiteral(" <p><a");
WriteLiteral(" class=\"btn btn-primary btn-back\"");
WriteAttribute("href", Tuple.Create(" href=\"", 3004), Tuple.Create("\"", 3045)
#line 64 "..\..\Views\DeleteMatchLocation.cshtml"
, Tuple.Create(Tuple.Create("", 3011), Tuple.Create<System.Object, System.Int32>(Constants.Pages.MatchLocationsUrl
#line default
#line hidden
, 3011), false)
);
WriteLiteral(">Back to ");
#line 64 "..\..\Views\DeleteMatchLocation.cshtml"
Write(Constants.Pages.MatchLocations);
#line default
#line hidden
WriteLiteral("</a></p>\r\n");
#line 65 "..\..\Views\DeleteMatchLocation.cshtml"
}
}
else
{
#line default
#line hidden
#line 69 "..\..\Views\DeleteMatchLocation.cshtml"
Write(Html.Partial("_Login"));
#line default
#line hidden
#line 69 "..\..\Views\DeleteMatchLocation.cshtml"
}
#line default
#line hidden
WriteLiteral("</div>");
}
}
}
#pragma warning restore 1591
| 26.912833 | 266 | 0.497076 | [
"Apache-2.0"
] | stoolball-england/stoolball-org-uk | Stoolball.Web/Views/DeleteMatchLocation.generated.cs | 11,117 | C# |
using System;
using System.IO;
using System.Runtime.CompilerServices;
namespace FixMath.NET
{
/// <summary>
/// Represents a Q31.32 fixed-point number.
/// </summary>
public partial struct Fix64 : IEquatable<Fix64>, IComparable<Fix64>
{
readonly long m_rawValue;
// Precision of this type is 2^-32, that is 2,3283064365386962890625E-10
public static readonly decimal Precision = (decimal)(new Fix64(1L));//0.00000000023283064365386962890625m;
public static readonly Fix64 MaxValue = new Fix64(MAX_VALUE);
public static readonly Fix64 MinValue = new Fix64(MIN_VALUE);
public static readonly Fix64 One = new Fix64(ONE);
public static readonly Fix64 Zero = new Fix64();
/// <summary>
/// The value of Pi
/// </summary>
public static readonly Fix64 Pi = new Fix64(PI);
public static readonly Fix64 PiOver2 = new Fix64(PI_OVER_2);
public static readonly Fix64 PiTimes2 = new Fix64(PI_TIMES_2);
public static readonly Fix64 PiInv = (Fix64)0.3183098861837906715377675267M;
public static readonly Fix64 PiOver2Inv = (Fix64)0.6366197723675813430755350535M;
static readonly Fix64 Log2Max = new Fix64(LOG2MAX);
static readonly Fix64 Log2Min = new Fix64(LOG2MIN);
static readonly Fix64 Ln2 = new Fix64(LN2);
static readonly Fix64 LutInterval = (Fix64)(LUT_SIZE - 1) / PiOver2;
const long MAX_VALUE = long.MaxValue;
const long MIN_VALUE = long.MinValue;
const int NUM_BITS = 64;
const int FRACTIONAL_PLACES = 32;
const long ONE = 1L << FRACTIONAL_PLACES;
const long PI_TIMES_2 = 0x6487ED511;
const long PI = 0x3243F6A88;
const long PI_OVER_2 = 0x1921FB544;
const long LN2 = 0xB17217F7;
const long LOG2MAX = 0x1F00000000;
const long LOG2MIN = -0x2000000000;
const int LUT_SIZE = (int)(PI_OVER_2 >> 15);
/// <summary>
/// Returns a number indicating the sign of a Fix64 number.
/// Returns 1 if the value is positive, 0 if is 0, and -1 if it is negative.
/// </summary>
public static int Sign(Fix64 value)
{
return
value.m_rawValue < 0 ? -1 :
value.m_rawValue > 0 ? 1 :
0;
}
/// <summary>
/// Returns the absolute value of a Fix64 number.
/// Note: Abs(Fix64.MinValue) == Fix64.MaxValue.
/// </summary>
public static Fix64 Abs(Fix64 value)
{
if (value.m_rawValue == MIN_VALUE)
{
return MaxValue;
}
// branchless implementation, see http://www.strchr.com/optimized_abs_function
var mask = value.m_rawValue >> 63;
return new Fix64((value.m_rawValue + mask) ^ mask);
}
/// <summary>
/// Returns the absolute value of a Fix64 number.
/// FastAbs(Fix64.MinValue) is undefined.
/// </summary>
public static Fix64 FastAbs(Fix64 value)
{
// branchless implementation, see http://www.strchr.com/optimized_abs_function
var mask = value.m_rawValue >> 63;
return new Fix64((value.m_rawValue + mask) ^ mask);
}
/// <summary>
/// Returns the largest integer less than or equal to the specified number.
/// </summary>
public static Fix64 Floor(Fix64 value)
{
// Just zero out the fractional part
return new Fix64((long)((ulong)value.m_rawValue & 0xFFFFFFFF00000000));
}
/// <summary>
/// Returns the smallest integral value that is greater than or equal to the specified number.
/// </summary>
public static Fix64 Ceiling(Fix64 value)
{
var hasFractionalPart = (value.m_rawValue & 0x00000000FFFFFFFF) != 0;
return hasFractionalPart ? Floor(value) + One : value;
}
/// <summary>
/// Rounds a value to the nearest integral value.
/// If the value is halfway between an even and an uneven value, returns the even value.
/// </summary>
public static Fix64 Round(Fix64 value)
{
var fractionalPart = value.m_rawValue & 0x00000000FFFFFFFF;
var integralPart = Floor(value);
if (fractionalPart < 0x80000000)
{
return integralPart;
}
if (fractionalPart > 0x80000000)
{
return integralPart + One;
}
// if number is halfway between two values, round to the nearest even number
// this is the method used by System.Math.Round().
return (integralPart.m_rawValue & ONE) == 0
? integralPart
: integralPart + One;
}
/// <summary>
/// Adds x and y. Performs saturating addition, i.e. in case of overflow,
/// rounds to MinValue or MaxValue depending on sign of operands.
/// </summary>
public static Fix64 operator +(Fix64 x, Fix64 y)
{
var xl = x.m_rawValue;
var yl = y.m_rawValue;
var sum = xl + yl;
// if signs of operands are equal and signs of sum and x are different
if (((~(xl ^ yl) & (xl ^ sum)) & MIN_VALUE) != 0)
{
sum = xl > 0 ? MAX_VALUE : MIN_VALUE;
}
return new Fix64(sum);
}
/// <summary>
/// Adds x and y witout performing overflow checking. Should be inlined by the CLR.
/// </summary>
public static Fix64 FastAdd(Fix64 x, Fix64 y)
{
return new Fix64(x.m_rawValue + y.m_rawValue);
}
/// <summary>
/// Subtracts y from x. Performs saturating substraction, i.e. in case of overflow,
/// rounds to MinValue or MaxValue depending on sign of operands.
/// </summary>
public static Fix64 operator -(Fix64 x, Fix64 y)
{
var xl = x.m_rawValue;
var yl = y.m_rawValue;
var diff = xl - yl;
// if signs of operands are different and signs of sum and x are different
if ((((xl ^ yl) & (xl ^ diff)) & MIN_VALUE) != 0)
{
diff = xl < 0 ? MIN_VALUE : MAX_VALUE;
}
return new Fix64(diff);
}
/// <summary>
/// Subtracts y from x witout performing overflow checking. Should be inlined by the CLR.
/// </summary>
public static Fix64 FastSub(Fix64 x, Fix64 y)
{
return new Fix64(x.m_rawValue - y.m_rawValue);
}
static long AddOverflowHelper(long x, long y, ref bool overflow)
{
var sum = x + y;
// x + y overflows if sign(x) ^ sign(y) != sign(sum)
overflow |= ((x ^ y ^ sum) & MIN_VALUE) != 0;
return sum;
}
public static Fix64 operator *(Fix64 x, Fix64 y)
{
var xl = x.m_rawValue;
var yl = y.m_rawValue;
var xlo = (ulong)(xl & 0x00000000FFFFFFFF);
var xhi = xl >> FRACTIONAL_PLACES;
var ylo = (ulong)(yl & 0x00000000FFFFFFFF);
var yhi = yl >> FRACTIONAL_PLACES;
var lolo = xlo * ylo;
var lohi = (long)xlo * yhi;
var hilo = xhi * (long)ylo;
var hihi = xhi * yhi;
var loResult = lolo >> FRACTIONAL_PLACES;
var midResult1 = lohi;
var midResult2 = hilo;
var hiResult = hihi << FRACTIONAL_PLACES;
bool overflow = false;
var sum = AddOverflowHelper((long)loResult, midResult1, ref overflow);
sum = AddOverflowHelper(sum, midResult2, ref overflow);
sum = AddOverflowHelper(sum, hiResult, ref overflow);
bool opSignsEqual = ((xl ^ yl) & MIN_VALUE) == 0;
// if signs of operands are equal and sign of result is negative,
// then multiplication overflowed positively
// the reverse is also true
if (opSignsEqual)
{
if (sum < 0 || (overflow && xl > 0))
{
return MaxValue;
}
}
else
{
if (sum > 0)
{
return MinValue;
}
}
// if the top 32 bits of hihi (unused in the result) are neither all 0s or 1s,
// then this means the result overflowed.
var topCarry = hihi >> FRACTIONAL_PLACES;
if (topCarry != 0 && topCarry != -1 /*&& xl != -17 && yl != -17*/)
{
return opSignsEqual ? MaxValue : MinValue;
}
// If signs differ, both operands' magnitudes are greater than 1,
// and the result is greater than the negative operand, then there was negative overflow.
if (!opSignsEqual)
{
long posOp, negOp;
if (xl > yl)
{
posOp = xl;
negOp = yl;
}
else
{
posOp = yl;
negOp = xl;
}
if (sum > negOp && negOp < -ONE && posOp > ONE)
{
return MinValue;
}
}
return new Fix64(sum);
}
/// <summary>
/// Performs multiplication without checking for overflow.
/// Useful for performance-critical code where the values are guaranteed not to cause overflow
/// </summary>
public static Fix64 FastMul(Fix64 x, Fix64 y)
{
var xl = x.m_rawValue;
var yl = y.m_rawValue;
var xlo = (ulong)(xl & 0x00000000FFFFFFFF);
var xhi = xl >> FRACTIONAL_PLACES;
var ylo = (ulong)(yl & 0x00000000FFFFFFFF);
var yhi = yl >> FRACTIONAL_PLACES;
var lolo = xlo * ylo;
var lohi = (long)xlo * yhi;
var hilo = xhi * (long)ylo;
var hihi = xhi * yhi;
var loResult = lolo >> FRACTIONAL_PLACES;
var midResult1 = lohi;
var midResult2 = hilo;
var hiResult = hihi << FRACTIONAL_PLACES;
var sum = (long)loResult + midResult1 + midResult2 + hiResult;
return new Fix64(sum);
}
//[MethodImpl(MethodImplOptions.AggressiveInlining)]
static int CountLeadingZeroes(ulong x)
{
int result = 0;
while ((x & 0xF000000000000000) == 0) { result += 4; x <<= 4; }
while ((x & 0x8000000000000000) == 0) { result += 1; x <<= 1; }
return result;
}
public static Fix64 operator /(Fix64 x, Fix64 y)
{
var xl = x.m_rawValue;
var yl = y.m_rawValue;
if (yl == 0)
{
throw new DivideByZeroException();
}
var remainder = (ulong)(xl >= 0 ? xl : -xl);
var divider = (ulong)(yl >= 0 ? yl : -yl);
var quotient = 0UL;
var bitPos = NUM_BITS / 2 + 1;
// If the divider is divisible by 2^n, take advantage of it.
while ((divider & 0xF) == 0 && bitPos >= 4)
{
divider >>= 4;
bitPos -= 4;
}
while (remainder != 0 && bitPos >= 0)
{
int shift = CountLeadingZeroes(remainder);
if (shift > bitPos)
{
shift = bitPos;
}
remainder <<= shift;
bitPos -= shift;
var div = remainder / divider;
remainder = remainder % divider;
quotient += div << bitPos;
// Detect overflow
if ((div & ~(0xFFFFFFFFFFFFFFFF >> bitPos)) != 0)
{
return ((xl ^ yl) & MIN_VALUE) == 0 ? MaxValue : MinValue;
}
remainder <<= 1;
--bitPos;
}
// rounding
++quotient;
var result = (long)(quotient >> 1);
if (((xl ^ yl) & MIN_VALUE) != 0)
{
result = -result;
}
return new Fix64(result);
}
public static Fix64 operator %(Fix64 x, Fix64 y)
{
return new Fix64(
x.m_rawValue == MIN_VALUE & y.m_rawValue == -1 ?
0 :
x.m_rawValue % y.m_rawValue);
}
/// <summary>
/// Performs modulo as fast as possible; throws if x == MinValue and y == -1.
/// Use the operator (%) for a more reliable but slower modulo.
/// </summary>
public static Fix64 FastMod(Fix64 x, Fix64 y)
{
return new Fix64(x.m_rawValue % y.m_rawValue);
}
public static Fix64 operator -(Fix64 x)
{
return x.m_rawValue == MIN_VALUE ? MaxValue : new Fix64(-x.m_rawValue);
}
public static bool operator ==(Fix64 x, Fix64 y)
{
return x.m_rawValue == y.m_rawValue;
}
public static bool operator !=(Fix64 x, Fix64 y)
{
return x.m_rawValue != y.m_rawValue;
}
public static bool operator >(Fix64 x, Fix64 y)
{
return x.m_rawValue > y.m_rawValue;
}
public static bool operator <(Fix64 x, Fix64 y)
{
return x.m_rawValue < y.m_rawValue;
}
public static bool operator >=(Fix64 x, Fix64 y)
{
return x.m_rawValue >= y.m_rawValue;
}
public static bool operator <=(Fix64 x, Fix64 y)
{
return x.m_rawValue <= y.m_rawValue;
}
/// <summary>
/// Returns 2 raised to the specified power.
/// Provides at least 6 decimals of accuracy.
/// </summary>
internal static Fix64 Pow2(Fix64 x)
{
if (x.m_rawValue == 0)
{
return One;
}
// Avoid negative arguments by exploiting that exp(-x) = 1/exp(x).
bool neg = x.m_rawValue < 0;
if (neg)
{
x = -x;
}
if (x == One)
{
return neg ? One / (Fix64)2 : (Fix64)2;
}
if (x >= Log2Max)
{
return neg ? One / MaxValue : MaxValue;
}
if (x <= Log2Min)
{
return neg ? MaxValue : Zero;
}
/* The algorithm is based on the power series for exp(x):
* http://en.wikipedia.org/wiki/Exponential_function#Formal_definition
*
* From term n, we get term n+1 by multiplying with x/n.
* When the sum term drops to zero, we can stop summing.
*/
int integerPart = (int)Floor(x);
// Take fractional part of exponent
x = new Fix64(x.m_rawValue & 0x00000000FFFFFFFF);
var result = One;
var term = One;
int i = 1;
while (term.m_rawValue != 0)
{
term = FastMul(FastMul(x, term), Ln2) / (Fix64)i;
result += term;
i++;
}
result = FromRaw(result.m_rawValue << integerPart);
if (neg)
{
result = One / result;
}
return result;
}
/// <summary>
/// Returns the base-2 logarithm of a specified number.
/// Provides at least 9 decimals of accuracy.
/// </summary>
/// <exception cref="ArgumentOutOfRangeException">
/// The argument was non-positive
/// </exception>
internal static Fix64 Log2(Fix64 x)
{
if (x.m_rawValue <= 0)
{
throw new ArgumentOutOfRangeException("Non-positive value passed to Ln", "x");
}
// This implementation is based on Clay. S. Turner's fast binary logarithm
// algorithm (C. S. Turner, "A Fast Binary Logarithm Algorithm", IEEE Signal
// Processing Mag., pp. 124,140, Sep. 2010.)
long b = 1U << (FRACTIONAL_PLACES - 1);
long y = 0;
long rawX = x.m_rawValue;
while (rawX < ONE)
{
rawX <<= 1;
y -= ONE;
}
while (rawX >= (ONE << 1))
{
rawX >>= 1;
y += ONE;
}
var z = new Fix64(rawX);
for (int i = 0; i < FRACTIONAL_PLACES; i++)
{
z = FastMul(z, z);
if (z.m_rawValue >= (ONE << 1))
{
z = new Fix64(z.m_rawValue >> 1);
y += b;
}
b >>= 1;
}
return new Fix64(y);
}
/// <summary>
/// Returns the natural logarithm of a specified number.
/// Provides at least 7 decimals of accuracy.
/// </summary>
/// <exception cref="ArgumentOutOfRangeException">
/// The argument was non-positive
/// </exception>
public static Fix64 Ln(Fix64 x)
{
return FastMul(Log2(x), Ln2);
}
/// <summary>
/// Returns a specified number raised to the specified power.
/// Provides about 5 digits of accuracy for the result.
/// </summary>
/// <exception cref="DivideByZeroException">
/// The base was zero, with a negative exponent
/// </exception>
/// <exception cref="ArgumentOutOfRangeException">
/// The base was negative, with a non-zero exponent
/// </exception>
public static Fix64 Pow(Fix64 b, Fix64 exp)
{
if (b == One)
{
return One;
}
if (exp.m_rawValue == 0)
{
return One;
}
if (b.m_rawValue == 0)
{
if (exp.m_rawValue < 0)
{
throw new DivideByZeroException();
}
return Zero;
}
Fix64 log2 = Log2(b);
return Pow2(exp * log2);
}
/// <summary>
/// Returns the square root of a specified number.
/// </summary>
/// <exception cref="ArgumentOutOfRangeException">
/// The argument was negative.
/// </exception>
public static Fix64 Sqrt(Fix64 x)
{
var xl = x.m_rawValue;
if (xl < 0)
{
// We cannot represent infinities like Single and Double, and Sqrt is
// mathematically undefined for x < 0. So we just throw an exception.
throw new ArgumentOutOfRangeException("Negative value passed to Sqrt", "x");
}
var num = (ulong)xl;
var result = 0UL;
// second-to-top bit
var bit = 1UL << (NUM_BITS - 2);
while (bit > num)
{
bit >>= 2;
}
// The main part is executed twice, in order to avoid
// using 128 bit values in computations.
for (var i = 0; i < 2; ++i)
{
// First we get the top 48 bits of the answer.
while (bit != 0)
{
if (num >= result + bit)
{
num -= result + bit;
result = (result >> 1) + bit;
}
else
{
result = result >> 1;
}
bit >>= 2;
}
if (i == 0)
{
// Then process it again to get the lowest 16 bits.
if (num > (1UL << (NUM_BITS / 2)) - 1)
{
// The remainder 'num' is too large to be shifted left
// by 32, so we have to add 1 to result manually and
// adjust 'num' accordingly.
// num = a - (result + 0.5)^2
// = num + result^2 - (result + 0.5)^2
// = num - result - 0.5
num -= result;
num = (num << (NUM_BITS / 2)) - 0x80000000UL;
result = (result << (NUM_BITS / 2)) + 0x80000000UL;
}
else
{
num <<= (NUM_BITS / 2);
result <<= (NUM_BITS / 2);
}
bit = 1UL << (NUM_BITS / 2 - 2);
}
}
// Finally, if next bit would have been 1, round the result upwards.
if (num > result)
{
++result;
}
return new Fix64((long)result);
}
/// <summary>
/// Returns the Sine of x.
/// The relative error is less than 1E-10 for x in [-2PI, 2PI], and less than 1E-7 in the worst case.
/// </summary>
public static Fix64 Sin(Fix64 x)
{
bool flipHorizontal, flipVertical;
var clampedL = ClampSinValue(x.m_rawValue, out flipHorizontal, out flipVertical);
var clamped = new Fix64(clampedL);
// Find the two closest values in the LUT and perform linear interpolation
// This is what kills the performance of this function on x86 - x64 is fine though
var rawIndex = FastMul(clamped, LutInterval);
var roundedIndex = Round(rawIndex);
var indexError = FastSub(rawIndex, roundedIndex);
var nearestValue = new Fix64(SinLut[flipHorizontal ?
SinLut.Length - 1 - (int)roundedIndex :
(int)roundedIndex]);
var secondNearestValue = new Fix64(SinLut[flipHorizontal ?
SinLut.Length - 1 - (int)roundedIndex - Sign(indexError) :
(int)roundedIndex + Sign(indexError)]);
var delta = FastMul(indexError, FastAbs(FastSub(nearestValue, secondNearestValue))).m_rawValue;
var interpolatedValue = nearestValue.m_rawValue + (flipHorizontal ? -delta : delta);
var finalValue = flipVertical ? -interpolatedValue : interpolatedValue;
return new Fix64(finalValue);
}
/// <summary>
/// Returns a rough approximation of the Sine of x.
/// This is at least 3 times faster than Sin() on x86 and slightly faster than Math.Sin(),
/// however its accuracy is limited to 4-5 decimals, for small enough values of x.
/// </summary>
public static Fix64 FastSin(Fix64 x)
{
bool flipHorizontal, flipVertical;
var clampedL = ClampSinValue(x.m_rawValue, out flipHorizontal, out flipVertical);
// Here we use the fact that the SinLut table has a number of entries
// equal to (PI_OVER_2 >> 15) to use the angle to index directly into it
var rawIndex = (uint)(clampedL >> 15);
if (rawIndex >= LUT_SIZE)
{
rawIndex = LUT_SIZE - 1;
}
var nearestValue = SinLut[flipHorizontal ?
SinLut.Length - 1 - (int)rawIndex :
(int)rawIndex];
return new Fix64(flipVertical ? -nearestValue : nearestValue);
}
static long ClampSinValue(long angle, out bool flipHorizontal, out bool flipVertical)
{
var largePI = 7244019458077122842;
// Obtained from ((Fix64)1686629713.065252369824872831112M).m_rawValue
// This is (2^29)*PI, where 29 is the largest N such that (2^N)*PI < MaxValue.
// The idea is that this number contains way more precision than PI_TIMES_2,
// and (((x % (2^29*PI)) % (2^28*PI)) % ... (2^1*PI) = x % (2 * PI)
// In practice this gives us an error of about 1,25e-9 in the worst case scenario (Sin(MaxValue))
// Whereas simply doing x % PI_TIMES_2 is the 2e-3 range.
var clamped2Pi = angle;
for (int i = 0; i < 29; ++i)
{
clamped2Pi %= (largePI >> i);
}
if (angle < 0)
{
clamped2Pi += PI_TIMES_2;
}
// The LUT contains values for 0 - PiOver2; every other value must be obtained by
// vertical or horizontal mirroring
flipVertical = clamped2Pi >= PI;
// obtain (angle % PI) from (angle % 2PI) - much faster than doing another modulo
var clampedPi = clamped2Pi;
while (clampedPi >= PI)
{
clampedPi -= PI;
}
flipHorizontal = clampedPi >= PI_OVER_2;
// obtain (angle % PI_OVER_2) from (angle % PI) - much faster than doing another modulo
var clampedPiOver2 = clampedPi;
if (clampedPiOver2 >= PI_OVER_2)
{
clampedPiOver2 -= PI_OVER_2;
}
return clampedPiOver2;
}
/// <summary>
/// Returns the cosine of x.
/// The relative error is less than 1E-10 for x in [-2PI, 2PI], and less than 1E-7 in the worst case.
/// </summary>
public static Fix64 Cos(Fix64 x)
{
var xl = x.m_rawValue;
var rawAngle = xl + (xl > 0 ? -PI - PI_OVER_2 : PI_OVER_2);
return Sin(new Fix64(rawAngle));
}
/// <summary>
/// Returns a rough approximation of the cosine of x.
/// See FastSin for more details.
/// </summary>
public static Fix64 FastCos(Fix64 x)
{
var xl = x.m_rawValue;
var rawAngle = xl + (xl > 0 ? -PI - PI_OVER_2 : PI_OVER_2);
return FastSin(new Fix64(rawAngle));
}
/// <summary>
/// Returns the tangent of x.
/// </summary>
/// <remarks>
/// This function is not well-tested. It may be wildly inaccurate.
/// </remarks>
public static Fix64 Tan(Fix64 x)
{
var clampedPi = x.m_rawValue % PI;
var flip = false;
if (clampedPi < 0)
{
clampedPi = -clampedPi;
flip = true;
}
if (clampedPi > PI_OVER_2)
{
flip = !flip;
clampedPi = PI_OVER_2 - (clampedPi - PI_OVER_2);
}
var clamped = new Fix64(clampedPi);
// Find the two closest values in the LUT and perform linear interpolation
var rawIndex = FastMul(clamped, LutInterval);
var roundedIndex = Round(rawIndex);
var indexError = FastSub(rawIndex, roundedIndex);
var nearestValue = new Fix64(TanLut[(int)roundedIndex]);
var secondNearestValue = new Fix64(TanLut[(int)roundedIndex + Sign(indexError)]);
var delta = FastMul(indexError, FastAbs(FastSub(nearestValue, secondNearestValue))).m_rawValue;
var interpolatedValue = nearestValue.m_rawValue + delta;
var finalValue = flip ? -interpolatedValue : interpolatedValue;
return new Fix64(finalValue);
}
/// <summary>
/// Returns the arccos of of the specified number, calculated using Atan and Sqrt
/// This function has at least 7 decimals of accuracy.
/// </summary>
public static Fix64 Acos(Fix64 x)
{
if (x < -One || x > One)
{
throw new ArgumentOutOfRangeException("nameof(x)");
}
if (x.m_rawValue == 0) return PiOver2;
var result = Atan(Sqrt(One - x * x) / x);
return x.m_rawValue < 0 ? result + Pi : result;
}
/// <summary>
/// Returns the arctan of of the specified number, calculated using Euler series
/// This function has at least 7 decimals of accuracy.
/// </summary>
public static Fix64 Atan(Fix64 z)
{
if (z.m_rawValue == 0) return Zero;
// Force positive values for argument
// Atan(-z) = -Atan(z).
var neg = z.m_rawValue < 0;
if (neg)
{
z = -z;
}
Fix64 result;
var two = (Fix64)2;
var three = (Fix64)3;
bool invert = z > One;
if (invert) z = One / z;
result = One;
var term = One;
var zSq = z * z;
var zSq2 = zSq * two;
var zSqPlusOne = zSq + One;
var zSq12 = zSqPlusOne * two;
var dividend = zSq2;
var divisor = zSqPlusOne * three;
for (var i = 2; i < 30; ++i)
{
term *= dividend / divisor;
result += term;
dividend += zSq2;
divisor += zSq12;
if (term.m_rawValue == 0) break;
}
result = result * z / zSqPlusOne;
if (invert)
{
result = PiOver2 - result;
}
if (neg)
{
result = -result;
}
return result;
}
public static Fix64 Atan2(Fix64 y, Fix64 x)
{
var yl = y.m_rawValue;
var xl = x.m_rawValue;
if (xl == 0)
{
if (yl > 0)
{
return PiOver2;
}
if (yl == 0)
{
return Zero;
}
return -PiOver2;
}
Fix64 atan;
var z = y / x;
// Deal with overflow
if (One + (Fix64)0.28M * z * z == MaxValue)
{
return y < Zero ? -PiOver2 : PiOver2;
}
if (Abs(z) < One)
{
atan = z / (One + (Fix64)0.28M * z * z);
if (xl < 0)
{
if (yl < 0)
{
return atan - Pi;
}
return atan + Pi;
}
}
else
{
atan = PiOver2 - z / (z * z + (Fix64)0.28M);
if (yl < 0)
{
return atan - Pi;
}
}
return atan;
}
public static explicit operator Fix64(long value)
{
return new Fix64(value * ONE);
}
public static explicit operator long(Fix64 value)
{
return value.m_rawValue >> FRACTIONAL_PLACES;
}
public static explicit operator Fix64(float value)
{
return new Fix64((long)(value * ONE));
}
public static explicit operator float(Fix64 value)
{
return (float)value.m_rawValue / ONE;
}
public static explicit operator Fix64(double value)
{
return new Fix64((long)(value * ONE));
}
public static explicit operator double(Fix64 value)
{
return (double)value.m_rawValue / ONE;
}
public static explicit operator Fix64(decimal value)
{
return new Fix64((long)(value * ONE));
}
public static explicit operator decimal(Fix64 value)
{
return (decimal)value.m_rawValue / ONE;
}
public override bool Equals(object obj)
{
return obj is Fix64 && ((Fix64)obj).m_rawValue == m_rawValue;
}
public override int GetHashCode()
{
return m_rawValue.GetHashCode();
}
public bool Equals(Fix64 other)
{
return m_rawValue == other.m_rawValue;
}
public int CompareTo(Fix64 other)
{
return m_rawValue.CompareTo(other.m_rawValue);
}
public override string ToString()
{
// Up to 10 decimal places
return ((decimal)this).ToString("0.##########");
}
public static Fix64 FromRaw(long rawValue)
{
return new Fix64(rawValue);
}
internal static void GenerateSinLut()
{
using (var writer = new StreamWriter("Fix64SinLut.cs"))
{
writer.Write(
@"namespace FixMath.NET
{
partial struct Fix64
{
public static readonly long[] SinLut = new[]
{");
int lineCounter = 0;
for (int i = 0; i < LUT_SIZE; ++i)
{
var angle = i * Math.PI * 0.5 / (LUT_SIZE - 1);
if (lineCounter++ % 8 == 0)
{
writer.WriteLine();
writer.Write(" ");
}
var sin = Math.Sin(angle);
var rawValue = ((Fix64)sin).m_rawValue;
writer.Write(string.Format("0x{0:X}L, ", rawValue));
}
writer.Write(
@"
};
}
}");
}
}
internal static void GenerateTanLut()
{
using (var writer = new StreamWriter("Fix64TanLut.cs"))
{
writer.Write(
@"namespace FixMath.NET
{
partial struct Fix64
{
public static readonly long[] TanLut = new[]
{");
int lineCounter = 0;
for (int i = 0; i < LUT_SIZE; ++i)
{
var angle = i * Math.PI * 0.5 / (LUT_SIZE - 1);
if (lineCounter++ % 8 == 0)
{
writer.WriteLine();
writer.Write(" ");
}
var tan = Math.Tan(angle);
if (tan > (double)MaxValue || tan < 0.0)
{
tan = (double)MaxValue;
}
var rawValue = (((decimal)tan > (decimal)MaxValue || tan < 0.0) ? MaxValue : (Fix64)tan).m_rawValue;
writer.Write(string.Format("0x{0:X}L, ", rawValue));
}
writer.Write(
@"
};
}
}");
}
}
// turn into a Console Application and use this to generate the look-up tables
//static void Main(string[] args)
//{
// GenerateSinLut();
// GenerateTanLut();
//}
/// <summary>
/// The underlying integer representation
/// </summary>
//public long RawValue => m_rawValue;
public long RawValue
{
get
{
return m_rawValue;
}
}
/// <summary>
/// This is the constructor from raw value; it can only be used interally.
/// </summary>
/// <param name="rawValue"></param>
Fix64(long rawValue)
{
m_rawValue = rawValue;
}
public Fix64(int value)
{
m_rawValue = value * ONE;
}
}
}
| 32.970588 | 120 | 0.475301 | [
"Apache-2.0"
] | WeaponSoon/Fix64GameLogic | TopdownDll/fixed64/Fix64.cs | 35,874 | C# |
namespace FinancialSummaryApi.V1.Controllers
{
public static class Constants
{
public const string CorrelationId = "x-correlation-id";
}
}
| 19.875 | 63 | 0.698113 | [
"MIT"
] | HannaHolosova/financial-summary-api | FinancialSummaryApi/V1/Constants.cs | 159 | C# |
using System;
using ElmSharp;
namespace ElmSharp.Test
{
class EvasMapTest1 : TestCaseBase
{
public override string TestName => "EvasMapTest1";
public override string TestDescription => "Test EvasMap on different levels of hierarchy";
public override void Run(Window window)
{
var box = new Box(window)
{
IsHorizontal = false,
};
box.SetAlignment(-1.0, -1.0);
box.SetWeight(1.0, 1.0);
box.Show();
var text = new Label(box)
{
Text = "<span color=#ffffff font_size=30>Target</span>",
AlignmentX = -1.0,
AlignmentY = -1.0,
WeightX = 1.0,
WeightY = 1.0,
};
text.Show();
var textBox = new Box(box)
{
AlignmentX = -1.0,
WeightX = 1.0,
WeightY = 0.7,
};
textBox.PackEnd(text);
textBox.Show();
double angle = 0.0;
var reset = new Button(box)
{
Text = "Reset",
AlignmentX = -1.0,
WeightX = 1.0,
WeightY = 0.1,
};
reset.Show();
double zx = 1.0;
double zy = 1.0;
reset.Clicked += (object sender, EventArgs e) =>
{
text.IsMapEnabled = false;
angle = 0.0;
zx = 1.0;
zy = 1.0;
};
var zoom = new Button(box)
{
Text = "Zoom Target",
AlignmentX = -1.0,
WeightX = 1.0,
WeightY = 0.1,
};
zoom.Show();
zoom.Clicked += (object sender, EventArgs e) =>
{
zx += 0.1;
zy += 0.1;
var map = new EvasMap(4);
var g = text.Geometry;
map.PopulatePoints(g, 0);
map.Rotate3D(0, 0, angle, g.X + g.Width / 2, g.Y + g.Height / 2, 0);
map.Zoom(zx, zy, g.X, g.Y);
text.EvasMap = map;
text.IsMapEnabled = true;
};
var rotate = new Button(box)
{
Text = "Rotate Target",
AlignmentX = -1.0,
WeightX = 1.0,
WeightY = 0.1,
};
rotate.Show();
rotate.Clicked += (object sender, EventArgs e) =>
{
angle += 5.0;
var map = new EvasMap(4);
var g = text.Geometry;
map.PopulatePoints(g, 0);
map.Rotate3D(0, 0, angle, g.X + g.Width / 2, g.Y + g.Height / 2, 0);
map.Zoom(zx, zy, g.X, g.Y);
text.EvasMap = map;
text.IsMapEnabled = true;
};
box.PackEnd(textBox);
box.PackEnd(reset);
box.PackEnd(zoom);
box.PackEnd(rotate);
box.Resize(window.ScreenSize.Width, window.ScreenSize.Height);
box.Move(0, 0);
}
}
} | 28.557522 | 98 | 0.398822 | [
"Apache-2.0",
"MIT"
] | AchoWang/TizenFX | test/ElmSharp.Test/TC/EvasMapTest1.cs | 3,229 | C# |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class AIController : MonoBehaviour {
[System.Serializable]
public class MoveSettings
{
public float moveSpeed = 2f;
}
[System.Serializable]
public class AISettings
{
public float attackFrequency = 1f;
public float detectionRadius = 20f;
public float attack01Radius = 2f;
}
[System.Serializable]
public class LogicSettigs
{
public float health = 200f;
public float stamina = 400f;
public float damage = 150f;
}
public static float attack01Timestamp;
[HideInInspector]
public bool attacking = false;
[HideInInspector]
public bool invincible = false;
public MoveSettings move = new MoveSettings();
public AISettings AI = new AISettings();
public LogicSettigs logic = new LogicSettigs();
CharacterController charController;
Rigidbody rbody;
GameObject obj;
Vector3 velocity = new Vector3();
Vector3 direction = Vector3.zero;
public Transform target;
public Animator animator;
void Start()
{
rbody = GetComponent<Rigidbody>();
animator = GetComponentInChildren<Animator>();
obj = GetComponent<GameObject>();
SetTarget(target);
}
void Update()
{
Move();
Detect();
StartCoroutine(AttackCoroutine());
Rotate();
Die();
}
void SetTarget(Transform t)
{
target = t;
if (target != null)
{
if (target.GetComponent<CharacterController>())
{
charController = target.GetComponent<CharacterController>();
}
else
Debug.LogError("Need Character Contoller");
}
else
Debug.LogError("no target");
}
void Follow()
{
if (!attacking)
{
if (Detect())
{
velocity = transform.forward * move.moveSpeed;
}
else
{
velocity = Vector3.zero;
}
velocity.y = 0;
}
else
{
velocity = Vector3.zero;
}
}
bool Detect()
{
float distance;
float difX = target.position.x - transform.position.x;
float difZ = target.position.z - transform.position.z;
distance = Mathf.Sqrt(Mathf.Pow(difX, 2) + Mathf.Pow(difZ, 2));//Euclidian Distance formula
if (distance < AI.detectionRadius)
{
return true;
}
return false;
}
void Move()
{
Follow();
rbody.velocity = velocity;
}
IEnumerator AttackCoroutine()
{
bool close = false;
float distance;
float difX = target.position.x - transform.position.x;
float difZ = target.position.z - transform.position.z;
distance = Mathf.Sqrt(Mathf.Pow(difX, 2) + Mathf.Pow(difZ, 2));//Euclidian Distance formula
if (distance < AI.attack01Radius)
{
close = true;
}
else
{
close = false;
}
if (close)
{
if(Time.time >= attack01Timestamp)//2 second cooldown on basic attack
{
attacking = true;
animator.Play("Strike001", -1, 0f);
attack01Timestamp = Time.time + 2;
yield return new WaitForSeconds(1f);
attacking = false;
}
}
}
void Rotate()
{
if (Detect() && !attacking)
{
transform.LookAt(target);
}
}
private void OnTriggerEnter(Collider other)
{
BasicWeapon weapon;
if(other.tag == "Weapon")
{
weapon = other.gameObject.GetComponent<BasicWeapon>();
if (weapon.owner.GetComponentInChildren<CharacterController>().attacking && !invincible)
{
//Play take damage animation
logic.health -= weapon.stats.baseDamage;
StartCoroutine(InvincibleCoroutine());
}
}
}
IEnumerator InvincibleCoroutine()
{
invincible = true;
yield return new WaitForSeconds(.5f);
invincible = false;
}
void Die()
{
if(logic.health <= 0)
{
//Play Death animation
GameLogic.enemies.Remove(GetComponent<GameObject>());
gameObject.SetActive(false);
/* foreach(GameObject o in transform.GetComponentsInChildren<GameObject>())
{
Destroy(o);
}*/
// Destroy(this);
GameLogic.killCount++;
}
}
}
| 24.77561 | 101 | 0.503052 | [
"MIT"
] | AlreadyAsleep/unity-assets | AIController.cs | 5,081 | C# |
using Mirror;
using UnityEngine;
public class Platform : NetworkBehaviour
{
#region Public.
/// <summary>
/// True if moving up.
/// </summary>
public bool MovingUp { get; private set; } = true;
/// <summary>
/// Sets MovingUp value.
/// </summary>
/// <param name="value"></param>
public void SetMovingUp(bool value)
{
MovingUp = value;
}
#endregion
#region Serialized.
/// <summary>
/// Move rate for the platform.
/// </summary>
[Tooltip("Move rate for the platform.")]
[SerializeField]
private float _moveRate = 3f;
/// <summary>
/// How much to move up or down from starting position.
/// </summary>
[Tooltip("How much to move up or down from starting position.")]
[SerializeField]
private float _moveDistance = 3f;
#endregion
#region Private.
/// <summary>
/// Where the platform is when it loads on server.
/// </summary>
private Vector3 _startPosition;
#endregion
private void OnEnable()
{
FixedUpdateManager.OnFixedUpdate += FixedUpdateManager_OnFixedUpdate;
}
private void OnDisable()
{
FixedUpdateManager.OnFixedUpdate -= FixedUpdateManager_OnFixedUpdate;
}
public override bool OnSerialize(NetworkWriter writer, bool initialState)
{
if (initialState)
{
writer.WriteVector3(_startPosition);
writer.WriteBoolean(MovingUp);
}
return base.OnSerialize(writer, initialState);
}
public override void OnDeserialize(NetworkReader reader, bool initialState)
{
if (initialState)
{
_startPosition = reader.ReadVector3();
SetMovingUp(reader.ReadBoolean());
}
base.OnDeserialize(reader, initialState);
}
public override void OnStartServer()
{
base.OnStartServer();
_startPosition = transform.position;
}
/// <summary>
/// Received when a simulated fixed update occurs.
/// </summary>
private void FixedUpdateManager_OnFixedUpdate()
{
MovePlatform();
}
/// <summary>
/// Moves the platform.
/// </summary>
private void MovePlatform()
{
Vector3 upGoal = _startPosition + new Vector3(0f, _moveDistance, 0f);
Vector3 downGoal = _startPosition - new Vector3(0f, _moveDistance, 0f);
//Set move rate and which goal to move towards.
float rate = Time.fixedDeltaTime * _moveRate;
Vector3 goal = (MovingUp) ? upGoal : downGoal;
//Move towards goal.
transform.position = Vector3.MoveTowards(transform.position, goal, rate);
//If at goal inverse move direction to begin moving the other way.
if (transform.position == goal)
MovingUp = !MovingUp;
}
private void OnDrawGizmosSelected()
{
Gizmos.color = Color.green;
Gizmos.DrawLine(transform.position, transform.position + new Vector3(0f, _moveDistance, 0f));
Gizmos.DrawLine(transform.position, transform.position - new Vector3(0f, _moveDistance, 0f));
}
}
| 27.2 | 101 | 0.622762 | [
"Apache-2.0"
] | Levalego/SoulGate | Arena Game/Assets/Scripts/Movement/Platform/Platform.cs | 3,130 | C# |
/*
* Ory Kratos API
*
* Documentation for all public and administrative Ory Kratos APIs. Public and administrative APIs are exposed on different ports. Public APIs can face the public internet without any protection while administrative APIs should never be exposed without prior authorization. To protect the administative API port you should use something like Nginx, Ory Oathkeeper, or any other technology capable of authorizing incoming requests.
*
* The version of the OpenAPI document: v0.6.0-alpha.15
* Contact: hi@ory.sh
* Generated by: https://github.com/openapitools/openapi-generator.git
*/
using Xunit;
using System;
using System.Linq;
using System.IO;
using System.Collections.Generic;
using Ory.Kratos.Client.Api;
using Ory.Kratos.Client.Model;
using Ory.Kratos.Client.Client;
using System.Reflection;
using Newtonsoft.Json;
namespace Ory.Kratos.Client.Test.Model
{
/// <summary>
/// Class for testing KratosIdResponse
/// </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 KratosIdResponseTests : IDisposable
{
// TODO uncomment below to declare an instance variable for KratosIdResponse
//private KratosIdResponse instance;
public KratosIdResponseTests()
{
// TODO uncomment below to create an instance of KratosIdResponse
//instance = new KratosIdResponse();
}
public void Dispose()
{
// Cleanup when everything is done.
}
/// <summary>
/// Test an instance of KratosIdResponse
/// </summary>
[Fact]
public void KratosIdResponseInstanceTest()
{
// TODO uncomment below to test "IsType" KratosIdResponse
//Assert.IsType<KratosIdResponse>(instance);
}
/// <summary>
/// Test the property 'Id'
/// </summary>
[Fact]
public void IdTest()
{
// TODO unit test for the property 'Id'
}
}
}
| 30.055556 | 431 | 0.658041 | [
"Apache-2.0"
] | Stackwalkerllc/sdk | clients/kratos/dotnet/src/Ory.Kratos.Client.Test/Model/KratosIdResponseTests.cs | 2,164 | C# |
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
namespace wd_rencard.Models
{
public class ExternalLoginConfirmationViewModel
{
[Required]
[Display(Name = "Email")]
public string Email { get; set; }
}
public class ExternalLoginListViewModel
{
public string ReturnUrl { get; set; }
}
public class SendCodeViewModel
{
public string SelectedProvider { get; set; }
public ICollection<System.Web.Mvc.SelectListItem> Providers { get; set; }
public string ReturnUrl { get; set; }
public bool RememberMe { get; set; }
}
public class VerifyCodeViewModel
{
[Required]
public string Provider { get; set; }
[Required]
[Display(Name = "Code")]
public string Code { get; set; }
public string ReturnUrl { get; set; }
[Display(Name = "Remember this browser?")]
public bool RememberBrowser { get; set; }
public bool RememberMe { get; set; }
}
public class ForgotViewModel
{
[Required]
[Display(Name = "Email")]
public string Email { get; set; }
}
public class LoginViewModel
{
[Required]
[Display(Name = "Email")]
[EmailAddress]
public string Email { get; set; }
[Required]
[DataType(DataType.Password)]
[Display(Name = "Password")]
public string Password { get; set; }
[Display(Name = "Remember me?")]
public bool RememberMe { get; set; }
}
public class RegisterViewModel
{
[Required]
[EmailAddress]
[Display(Name = "Email")]
public string Email { get; set; }
[Required]
[StringLength(100, ErrorMessage = "The {0} must be at least {2} characters long.", MinimumLength = 6)]
[DataType(DataType.Password)]
[Display(Name = "Password")]
public string Password { get; set; }
[DataType(DataType.Password)]
[Display(Name = "Confirm password")]
[Compare("Password", ErrorMessage = "The password and confirmation password do not match.")]
public string ConfirmPassword { get; set; }
}
public class ResetPasswordViewModel
{
[Required]
[EmailAddress]
[Display(Name = "Email")]
public string Email { get; set; }
[Required]
[StringLength(100, ErrorMessage = "The {0} must be at least {2} characters long.", MinimumLength = 6)]
[DataType(DataType.Password)]
[Display(Name = "Password")]
public string Password { get; set; }
[DataType(DataType.Password)]
[Display(Name = "Confirm password")]
[Compare("Password", ErrorMessage = "The password and confirmation password do not match.")]
public string ConfirmPassword { get; set; }
public string Code { get; set; }
}
public class ForgotPasswordViewModel
{
[Required]
[EmailAddress]
[Display(Name = "Email")]
public string Email { get; set; }
}
}
| 27.513274 | 110 | 0.588292 | [
"MIT"
] | sjpence/wd-rencard | wd-rencard/Models/AccountViewModels.cs | 3,111 | C# |
using Lab06Zoo.MythologicalCreatures.Interface;
using System;
using System.Collections.Generic;
using System.Text;
namespace Lab06Zoo.MythologicalCreatures.Japanese
{
public abstract class Japanese : MythologicalCreature, IEat, IMakeSound
{
public virtual bool willMarryMe { get; set; } = false;
public abstract string Eats();
public abstract string MakeSound();
}
}
| 23.941176 | 75 | 0.72973 | [
"MIT"
] | mcbarnhart/Lab06SEIZMAKZoo | Lab06Zoo/Lab06Zoo/MythologicalCreatures/Japanese/Japanese.cs | 409 | C# |
// Copyright (c) .NET Foundation and Contributors (https://dotnetfoundation.org/ & https://stride3d.net) and Silicon Studio Corp. (https://www.siliconstudio.co.jp)
// Distributed under the MIT license. See the LICENSE.md file in the project root for more information.
using System;
using System.Collections;
using System.Collections.Generic;
using System.Dynamic;
using System.Linq;
using Stride.Core.Yaml.Serialization;
namespace Stride.Core.Yaml
{
/// <summary>
/// Dynamic version of <see cref="YamlSequenceNode"/>.
/// </summary>
public class DynamicYamlArray : DynamicYamlObject, IDynamicYamlNode, IEnumerable
{
internal YamlSequenceNode node;
public YamlSequenceNode Node => node;
public int Count => node.Children.Count;
YamlNode IDynamicYamlNode.Node => Node;
public DynamicYamlArray(YamlSequenceNode node)
{
if (node == null) throw new ArgumentNullException(nameof(node));
this.node = node;
}
IEnumerator IEnumerable.GetEnumerator()
{
return node.Children.Select(ConvertToDynamic).ToArray().GetEnumerator();
}
public override bool TryConvert(ConvertBinder binder, out object result)
{
if (binder.Type.IsAssignableFrom(node.GetType()))
{
result = node;
}
else
{
throw new InvalidOperationException();
}
return true;
}
public override bool TrySetIndex(SetIndexBinder binder, object[] indexes, object value)
{
var key = Convert.ToInt32(indexes[0]);
node.Children[key] = ConvertFromDynamic(value);
return true;
}
public override bool TryGetIndex(GetIndexBinder binder, object[] indexes, out object result)
{
var key = Convert.ToInt32(indexes[0]);
result = ConvertToDynamic(node.Children[key]);
return true;
}
public void Add(object value)
{
node.Children.Add(ConvertFromDynamic(value));
}
public void RemoveAt(int index)
{
node.Children.RemoveAt(index);
}
}
}
| 30.378378 | 163 | 0.609431 | [
"MIT"
] | Alan-love/xenko | sources/assets/Stride.Core.Assets.Yaml/DynamicYaml/DynamicYamlArray.cs | 2,248 | C# |
namespace Justwoken.CSharpCodingGuidelines.WpfApp.Interfaces
{
/// <summary>
/// Example interface.
/// </summary>
public interface IForExample<T, TResult>
{
/// <summary>
/// Executes the generic action with generic result.
/// </summary>
/// <param name="target">The target.</param>
/// <returns>Generic result.</returns>
TResult ExecuteGenericActionWithGenericResult(T target);
}
} | 30.466667 | 64 | 0.617068 | [
"Apache-2.0"
] | justwoken/CSharpCodingGuidelines | CSharpCodingGuidelines/CSharpCodingGuidelines/Interfaces/IForExample.cs | 459 | C# |
// --------------------------------------------------------------------------------------------------------------------
// <copyright file="ComponentImporterUnitTest.cs" company="DotnetScaffolder">
// MIT
// </copyright>
// --------------------------------------------------------------------------------------------------------------------
namespace DotNetScaffolder.Test.Components
{
#region Usings
using DotNetScaffolder.Components.Common;
using Microsoft.VisualStudio.TestTools.UnitTesting;
#endregion
/// <summary>
/// The component importer unit test.
/// </summary>
[TestClass]
public class ComponentImporterUnitTest
{
#region Public Methods And Operators
/// <summary>
/// Tests the Component Importer
/// </summary>
[TestMethod]
public void ComponentImporterUnitTest_Import()
{
ComponentImporter importer = new ComponentImporter();
importer.Import();
Assert.IsNotNull(importer.NamingConventions, "NamingConventions should not be null");
Assert.AreEqual(4, importer.NamingConventions.Length, "There should be 4 NamingConventions");
Assert.IsNotNull(importer.SourceTypes, "SourceTypes should not be null");
Assert.AreEqual(4, importer.SourceTypes.Length, "There should be 4 SourceTypes");
Assert.IsNotNull(importer.Drivers, "DriverTypes should not be null");
Assert.AreEqual(9, importer.Drivers.Length, "There should be 9 DriverType");
Assert.AreEqual(2, importer.LanguageOutputs.Length, "There should be 2 LanguageOutput");
Assert.AreEqual(1, importer.OutputGenerators.Length, "There should be 1 OutputGenerator");
Assert.AreEqual(9, importer.DataTypes.Length, "There should be 9 DataTypes");
}
#endregion
}
} | 40.085106 | 120 | 0.579618 | [
"MIT"
] | laredoza/.NetScaffolder | src/Tests/CodeGenerator/Components/ComponentImporterUnitTest.cs | 1,886 | C# |
using Sharpen;
namespace gov.nist.javax.sip.parser.ims
{
[Sharpen.NakedStub]
public class PAssertedIdentityParser
{
}
}
| 12.5 | 39 | 0.76 | [
"Apache-2.0"
] | Conceptengineai/XobotOS | android/naked-stubs/gov/nist/javax/sip/parser/ims/PAssertedIdentityParser.cs | 125 | C# |
// Copyright (c) 2007-2018 ppy Pty Ltd <contact@ppy.sh>.
// Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu/master/LICENCE
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using osu.Framework.Allocation;
using osu.Framework.Graphics;
using osu.Framework.Graphics.Containers;
using osu.Framework.Graphics.Sprites;
using osu.Framework.Graphics.Textures;
using osu.Framework.Logging;
using osu.Framework.Platform;
using osu.Game.Graphics.Sprites;
using osu.Game.Graphics.UserInterface;
using osu.Game.Screens.Backgrounds;
using osu.Game.Screens.Tournament.Components;
using osu.Game.Screens.Tournament.Teams;
using OpenTK;
using OpenTK.Graphics;
using osu.Framework.IO.Stores;
using osu.Framework.Graphics.Shapes;
namespace osu.Game.Screens.Tournament
{
public class Drawings : OsuScreen
{
private const string results_filename = "drawings_results.txt";
public override bool ShowOverlaysOnEnter => false;
protected override BackgroundScreen CreateBackground() => new BackgroundScreenDefault();
private ScrollingTeamContainer teamsContainer;
private GroupContainer groupsContainer;
private OsuSpriteText fullTeamNameText;
private readonly List<DrawingsTeam> allTeams = new List<DrawingsTeam>();
private DrawingsConfigManager drawingsConfig;
private Task writeOp;
private Storage storage;
public ITeamList TeamList;
private DependencyContainer dependencies;
protected override IReadOnlyDependencyContainer CreateLocalDependencies(IReadOnlyDependencyContainer parent) =>
dependencies = new DependencyContainer(base.CreateLocalDependencies(parent));
[BackgroundDependencyLoader]
private void load(TextureStore textures, Storage storage)
{
this.storage = storage;
TextureStore flagStore = new TextureStore();
// Local flag store
flagStore.AddStore(new RawTextureLoaderStore(new NamespacedResourceStore<byte[]>(new StorageBackedResourceStore(storage), "Drawings")));
// Default texture store
flagStore.AddStore(textures);
dependencies.Cache(flagStore);
if (TeamList == null)
TeamList = new StorageBackedTeamList(storage);
if (!TeamList.Teams.Any())
{
Exit();
return;
}
drawingsConfig = new DrawingsConfigManager(storage);
Children = new Drawable[]
{
new Box
{
RelativeSizeAxes = Axes.Both,
Colour = new Color4(77, 77, 77, 255)
},
new Sprite
{
RelativeSizeAxes = Axes.Both,
FillMode = FillMode.Fill,
Texture = textures.Get(@"Backgrounds/Drawings/background.png")
},
new FillFlowContainer
{
RelativeSizeAxes = Axes.Both,
Direction = FillDirection.Horizontal,
Children = new Drawable[]
{
// Main container
new Container
{
RelativeSizeAxes = Axes.Both,
Width = 0.85f,
Children = new Drawable[]
{
// Visualiser
new VisualiserContainer
{
Anchor = Anchor.Centre,
Origin = Anchor.Centre,
RelativeSizeAxes = Axes.X,
Size = new Vector2(1, 10),
Colour = new Color4(255, 204, 34, 255),
Lines = 6
},
// Groups
groupsContainer = new GroupContainer(drawingsConfig.Get<int>(DrawingsConfig.Groups), drawingsConfig.Get<int>(DrawingsConfig.TeamsPerGroup))
{
Anchor = Anchor.TopCentre,
Origin = Anchor.TopCentre,
RelativeSizeAxes = Axes.Y,
AutoSizeAxes = Axes.X,
Padding = new MarginPadding
{
Top = 35f,
Bottom = 35f
}
},
// Scrolling teams
teamsContainer = new ScrollingTeamContainer
{
Anchor = Anchor.Centre,
Origin = Anchor.Centre,
RelativeSizeAxes = Axes.X,
},
// Scrolling team name
fullTeamNameText = new OsuSpriteText
{
Anchor = Anchor.Centre,
Origin = Anchor.TopCentre,
Position = new Vector2(0, 45f),
Alpha = 0,
Font = "Exo2.0-Light",
TextSize = 42f
}
}
},
// Control panel container
new Container
{
RelativeSizeAxes = Axes.Both,
Width = 0.15f,
Children = new Drawable[]
{
new Box
{
RelativeSizeAxes = Axes.Both,
Colour = new Color4(54, 54, 54, 255)
},
new OsuSpriteText
{
Anchor = Anchor.TopCentre,
Origin = Anchor.TopCentre,
Text = "Control Panel",
TextSize = 22f,
Font = "Exo2.0-Bold"
},
new FillFlowContainer
{
Anchor = Anchor.TopCentre,
Origin = Anchor.TopCentre,
RelativeSizeAxes = Axes.X,
AutoSizeAxes = Axes.Y,
Width = 0.75f,
Position = new Vector2(0, 35f),
Direction = FillDirection.Vertical,
Spacing = new Vector2(0, 5f),
Children = new Drawable[]
{
new TriangleButton
{
RelativeSizeAxes = Axes.X,
Text = "Begin random",
Action = teamsContainer.StartScrolling,
},
new TriangleButton
{
RelativeSizeAxes = Axes.X,
Text = "Stop random",
Action = teamsContainer.StopScrolling,
},
new TriangleButton
{
RelativeSizeAxes = Axes.X,
Text = "Reload",
Action = reloadTeams
}
}
},
new FillFlowContainer
{
Anchor = Anchor.BottomCentre,
Origin = Anchor.BottomCentre,
RelativeSizeAxes = Axes.X,
AutoSizeAxes = Axes.Y,
Width = 0.75f,
Position = new Vector2(0, -5f),
Direction = FillDirection.Vertical,
Spacing = new Vector2(0, 5f),
Children = new Drawable[]
{
new TriangleButton
{
RelativeSizeAxes = Axes.X,
Text = "Reset",
Action = () => reset()
}
}
}
}
}
}
}
};
teamsContainer.OnSelected += onTeamSelected;
teamsContainer.OnScrollStarted += () => fullTeamNameText.FadeOut(200);
reset(true);
}
private void onTeamSelected(DrawingsTeam team)
{
groupsContainer.AddTeam(team);
fullTeamNameText.Text = team.FullName;
fullTeamNameText.FadeIn(200);
writeResults(groupsContainer.GetStringRepresentation());
}
private void writeResults(string text)
{
void writeAction()
{
try
{
// Write to drawings_results
using (Stream stream = storage.GetStream(results_filename, FileAccess.Write, FileMode.Create))
using (StreamWriter sw = new StreamWriter(stream))
{
sw.Write(text);
}
}
catch (Exception ex)
{
Logger.Error(ex, "Failed to write results.");
}
}
writeOp = writeOp?.ContinueWith(t => { writeAction(); }) ?? Task.Run((Action)writeAction);
}
private void reloadTeams()
{
teamsContainer.ClearTeams();
allTeams.Clear();
foreach (DrawingsTeam t in TeamList.Teams)
{
if (groupsContainer.ContainsTeam(t.FullName))
continue;
allTeams.Add(t);
teamsContainer.AddTeam(t);
}
}
private void reset(bool loadLastResults = false)
{
groupsContainer.ClearTeams();
reloadTeams();
if (!storage.Exists(results_filename))
return;
if (loadLastResults)
{
try
{
// Read from drawings_results
using (Stream stream = storage.GetStream(results_filename, FileAccess.Read, FileMode.Open))
using (StreamReader sr = new StreamReader(stream))
{
string line;
while ((line = sr.ReadLine()?.Trim()) != null)
{
if (string.IsNullOrEmpty(line))
continue;
if (line.ToUpper().StartsWith("GROUP"))
continue;
DrawingsTeam teamToAdd = allTeams.FirstOrDefault(t => t.FullName == line);
if (teamToAdd == null)
continue;
groupsContainer.AddTeam(teamToAdd);
teamsContainer.RemoveTeam(teamToAdd);
}
}
}
catch (Exception ex)
{
Logger.Error(ex, "Failed to read last drawings results.");
}
}
else
{
writeResults(string.Empty);
}
}
}
}
| 38.153846 | 172 | 0.38187 | [
"MIT"
] | StefanYohansson/osu | osu.Game/Screens/Tournament/Drawings.cs | 13,394 | C# |
using System;
using Xunit;
using Joakimsoftware.M26;
// Xunit test for class Constants.
// Chris Joakim, 2021/07/19
namespace Joakimsoftware.M26.Tests {
public class ConstantsTest {
[Fact]
public void TestUnitsOfMeasureConstants() {
Assert.Equal("m", Constants.UomMiles);
Assert.Equal("k", Constants.UomKilometers);
Assert.Equal("y", Constants.UomYards);
}
[Fact]
public void TestUnitsOfMeasureArray() {
string[] constants = Constants.UnitsOfMeasure();
Assert.Equal(3, constants.Length);
Assert.Equal(constants[0], Constants.UomMiles);
Assert.Equal(constants[1], Constants.UomKilometers);
Assert.Equal(constants[2], Constants.UomYards);
}
[Fact]
public void TestKilometersPerMile() {
double expected = 1.609344;
double tolerance = 0.000001;
Assert.True(expected + tolerance > Constants.KilometersPerMile);
Assert.True(expected - tolerance < Constants.KilometersPerMile);
}
[Fact]
public void TestMilesPerKilometer() {
double expected = 0.621371192237334;
double tolerance = 0.000000000000001;
Assert.True(expected + tolerance > Constants.MilesPerKilometer);
Assert.True(expected - tolerance < Constants.MilesPerKilometer);
}
[Fact]
public void TestYardsPerKilometer() {
double expected = 1093.6132983377076;
double tolerance = 0.000000000001;
Assert.True(expected + tolerance > Constants.YardsPerKilometer);
Assert.True(expected - tolerance < Constants.YardsPerKilometer);
}
[Fact]
public void TestFeetPerKilometer() {
double expected = 3280.839895013123;
double tolerance = 0.000000000001;
Assert.True(expected + tolerance > Constants.FeetPerKilometer);
Assert.True(expected - tolerance < Constants.FeetPerKilometer);
}
[Fact]
public void TestFeetPerMeter() {
double expected = 3.280839895013123;
double tolerance = 0.000000000000001;
Assert.True(expected + tolerance > Constants.FeetPerMeter);
Assert.True(expected - tolerance < Constants.FeetPerMeter);
}
[Fact]
public void TestYardsPerMile() {
long expected = 1760;
Assert.True(expected == Constants.YardsPerMile);
}
[Fact]
public void TestSecondsPerHour() {
long expected = 3600;
Assert.True(expected == Constants.SecondsPerHour);
}
[Fact]
public void TestSecondsPerMinute() {
long expected = 60;
Assert.True(expected == Constants.SecondsPerMinute);
}
[Fact]
public void TestSpeedFormulas() {
Assert.Equal("simple", Constants.SpeedFormulaSimple);
Assert.Equal("riegel", Constants.SpeedFormulaRiegel);
}
}
}
| 31.54902 | 77 | 0.574891 | [
"MIT"
] | cjoakim/oss | m26-cs/M26/Joakimsoftware.M26.Tests/src/ConstantsTest.cs | 3,218 | C# |
using MS.Lib.Data.Abstractions;
using System;
using System.Threading.Tasks;
namespace MS.Module.Admin.Domain.AccountConfig
{
/// <summary>
/// 账户配置仓储
/// </summary>
public interface IAccountConfigRepository : IRepository<AccountConfigEntity>
{
/// <summary>
/// 查询指定账户的配置信息
/// </summary>
/// <param name="accountId"></param>
/// <returns></returns>
Task<AccountConfigEntity> GetByAccount(Guid accountId);
}
} | 25.421053 | 80 | 0.625259 | [
"MIT"
] | billowliu2/MS | src/Admin/Library/Domain/AccountConfig/IAccountConfigRepository.cs | 519 | C# |
using System;
using System.Xml.Serialization;
using System.ComponentModel.DataAnnotations;
using BroadWorksConnector.Ocip.Validation;
using System.Collections.Generic;
namespace BroadWorksConnector.Ocip.Models
{
/// <summary>
/// Gets the Call Park Group settings.
/// The response is either GroupCallParkGetResponse or ErrorResponse.
/// <see cref="GroupCallParkGetResponse"/>
/// <see cref="ErrorResponse"/>
/// </summary>
[Serializable]
[XmlRoot(Namespace = "")]
[Groups(@"[{""__type"":""Sequence:#BroadWorksConnector.Ocip.Validation"",""id"":""ab0042aa512abc10edb3c55e4b416b0b:7439""}]")]
public class GroupCallParkGetRequest : BroadWorksConnector.Ocip.Models.C.OCIRequest
{
private string _serviceProviderId;
[XmlElement(ElementName = "serviceProviderId", IsNullable = false, Namespace = "")]
[Group(@"ab0042aa512abc10edb3c55e4b416b0b:7439")]
[MinLength(1)]
[MaxLength(30)]
public string ServiceProviderId
{
get => _serviceProviderId;
set
{
ServiceProviderIdSpecified = true;
_serviceProviderId = value;
}
}
[XmlIgnore]
protected bool ServiceProviderIdSpecified { get; set; }
private string _groupId;
[XmlElement(ElementName = "groupId", IsNullable = false, Namespace = "")]
[Group(@"ab0042aa512abc10edb3c55e4b416b0b:7439")]
[MinLength(1)]
[MaxLength(30)]
public string GroupId
{
get => _groupId;
set
{
GroupIdSpecified = true;
_groupId = value;
}
}
[XmlIgnore]
protected bool GroupIdSpecified { get; set; }
}
}
| 28.935484 | 130 | 0.605909 | [
"MIT"
] | Rogn/broadworks-connector-net | BroadworksConnector/Ocip/Models/GroupCallParkGetRequest.cs | 1,794 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace NuiEngine.NuiControl
{
/// <summary>
/// 弹出对话框Icon图标枚举
/// </summary>
public enum NuiMessageBoxIcon
{
/// <summary>
/// 错误
/// </summary>
Error,
/// <summary>
/// 提示
/// </summary>
Information,
/// <summary>
/// OK
/// </summary>
OK,
/// <summary>
/// 疑问
/// </summary>
Question,
/// <summary>
/// 警告
/// </summary>
Warning
}
}
| 15.74359 | 33 | 0.431596 | [
"Apache-2.0"
] | caojianagbocn/NuiEngine | src/NuiEngine/NuiControl/NuiMessageBox/NuiMessageBoxIcon.cs | 650 | C# |
using Microsoft.Xna.Framework;
using Myra.Graphics2D.UI;
using System.Collections.Generic;
namespace Myra.Utility
{
internal static class InputHelpers
{
private static bool CommonTouchCheck(this Widget w)
{
return w.Visible && w.Active && w.Enabled && w.ContainsMouse;
}
public static bool FallsThrough(this Widget w, Point p)
{
// Only containers can fall through
if (!(w is Grid ||
w is StackPanel ||
w is Panel ||
w is SplitPane ||
w is ScrollViewer))
{
return false;
}
// Real containers are solid only if backround is set
if (w.Background != null)
{
return false;
}
var asScrollViewer = w as ScrollViewer;
if (asScrollViewer != null)
{
// Special case
if (asScrollViewer._horizontalScrollingOn && asScrollViewer._horizontalScrollbarFrame.Contains(p) ||
asScrollViewer._verticalScrollingOn && asScrollViewer._verticalScrollbarFrame.Contains(p))
{
return false;
}
}
return true;
}
public static void ProcessTouchDown(this List<Widget> widgets)
{
for (var i = widgets.Count - 1; i >= 0; --i)
{
var w = widgets[i];
if (w.CommonTouchCheck())
{
w.OnTouchDown();
if (!w.FallsThrough(Desktop.TouchPosition))
{
break;
}
}
if (w.IsModal)
{
break;
}
}
}
public static void ProcessTouchUp(this List<Widget> widgets)
{
for (var i = widgets.Count - 1; i >= 0; --i)
{
var w = widgets[i];
if (w.IsTouchInside)
{
w.OnTouchUp();
}
}
}
public static void ProcessTouchDoubleClick(this List<Widget> widgets)
{
for (var i = widgets.Count - 1; i >= 0; --i)
{
var w = widgets[i];
if (w.CommonTouchCheck())
{
w.OnTouchDoubleClick();
if (!w.FallsThrough(Desktop.TouchPosition))
{
break;
}
}
if (w.IsModal)
{
break;
}
}
}
public static void ProcessMouseMovement(this List<Widget> widgets)
{
// First run: call on OnMouseLeft on all widgets if it is required
for (var i = widgets.Count - 1; i >= 0; --i)
{
var w = widgets[i];
if (!w.ContainsMouse && w.IsMouseInside)
{
w.OnMouseLeft();
}
}
// Second run: OnMouseEnter/OnMouseMoved
for (var i = widgets.Count - 1; i >= 0; --i)
{
var w = widgets[i];
if (w.CommonTouchCheck())
{
var isMouseOver = w.ContainsMouse;
var wasMouseOver = w.IsMouseInside;
if (isMouseOver && !wasMouseOver)
{
w.OnMouseEntered();
}
if (isMouseOver && wasMouseOver)
{
w.OnMouseMoved();
}
if (!w.FallsThrough(Desktop.MousePosition))
{
break;
}
}
if (w.IsModal)
{
break;
}
}
}
public static void ProcessTouchMovement(this List<Widget> widgets)
{
// First run: call on OnTouchLeft on all widgets if it is required
for (var i = widgets.Count - 1; i >= 0; --i)
{
var w = widgets[i];
if (!w.ContainsTouch && w.IsTouchInside)
{
w.OnTouchLeft();
}
}
// Second run: OnTouchEnter/OnTouchMoved
for (var i = widgets.Count - 1; i >= 0; --i)
{
var w = widgets[i];
if (w.CommonTouchCheck())
{
var isTouchOver = w.ContainsTouch;
var wasTouchOver = w.IsTouchInside;
if (isTouchOver && !wasTouchOver)
{
w.OnTouchEntered();
}
if (isTouchOver && wasTouchOver)
{
w.OnTouchMoved();
}
if (!w.FallsThrough(Desktop.TouchPosition))
{
break;
}
}
if (w.IsModal)
{
break;
}
}
}
}
} | 18.569948 | 104 | 0.578404 | [
"MIT"
] | bladecoder/Myra | src/Myra/Utility/InputHelpers.cs | 3,586 | C# |
//-----------------------------------------------------------------------------------------------------
// <copyright file="TypeExtensions.cs" company="Microsoft Open Technologies, Inc">
// Copyright (c) Microsoft Open Technologies, Inc. All rights reserved.
// </copyright>
//-----------------------------------------------------------------------------------------------------
namespace EntityFrameworkCore.Testing
{
using System;
using System.Collections.Generic;
using System.Reflection;
/// <summary>
/// Extension methods for <see cref="Type"/>.
/// </summary>
internal static class TypeExtensions
{
/// <summary>
/// Get declared methods.
/// </summary>
/// <param name="type">The <see cref="Type"/>.</param>
/// <returns>The methods.</returns>
public static IEnumerable<MethodInfo> GetDeclaredMethods(this Type type)
{
DebugCheck.NotNull(type);
return type.GetTypeInfo().DeclaredMethods;
}
}
} | 35.448276 | 104 | 0.495136 | [
"Apache-2.0"
] | mondeun/EntityFrameworkCore.Testing | src/EntityFrameworkCore.Testing/TypeExtensions.cs | 1,030 | C# |
/* Copyright (c) 1996-2016, OPC Foundation. All rights reserved.
The source code in this file is covered under a dual-license scenario:
- RCL: for OPC Foundation members in good-standing
- GPL V2: everybody else
RCL license terms accompanied with this source code. See http://opcfoundation.org/License/RCL/1.00/
GNU General Public License as published by the Free Software Foundation;
version 2 of the License are accompanied with this source code. See http://opcfoundation.org/License/GPLv2
This source code is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
*/
using System;
using System.Collections.Generic;
using System.ServiceModel;
using System.Runtime.Serialization;
using System.Security.Cryptography.X509Certificates;
namespace Opc.Ua
{
#region BrowsePath Class
public partial class BrowsePath
{
#region Supporting Properties and Methods
/// <summary>
/// A handle assigned to the item during processing.
/// </summary>
public object Handle
{
get { return m_handle; }
set { m_handle = value; }
}
#endregion
#region Private Fields
private object m_handle;
#endregion
}
#endregion
}
| 34.268293 | 109 | 0.679004 | [
"BSD-2-Clause"
] | EdmondQuinton/InContex | UA-.NETStandard/Opc.Ua.Core/Stack/Types/BrowsePath.cs | 1,405 | C# |
using HaRepacker.WindowsAPIImports;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace HaRepacker.GUI
{
/// <summary>
/// ZLZ WZ encryption keys
/// Credits: http://forum.ragezone.com/f921/release-gms-key-retriever-895646/index2.html
/// </summary>
public partial class ZLZPacketEncryptionKeyForm : Form
{
public ZLZPacketEncryptionKeyForm()
{
InitializeComponent();
}
/// <summary>
/// Opens the ZLZ.DLL file
/// Harepacker needs to be compiled under x86 for this to work!
/// </summary>
/// <returns></returns>
public bool OpenZLZDllFile()
{
if (IntPtr.Size != 4)
{
MessageBox.Show("Unable to load ZLZ.dll. Please ensure that you're running the x86 version (32-bit) of HaRepacker.", "Error");
return false;
}
// Create an instance of the open file dialog box.
OpenFileDialog openFileDialog1 = new OpenFileDialog();
// Set filter options and filter index.
openFileDialog1.Filter = "ZLZ file (.dll)|*.dll";
openFileDialog1.FilterIndex = 1;
openFileDialog1.Multiselect = false;
// Call the ShowDialog method to show the dialog box.
DialogResult userClickedOK = openFileDialog1.ShowDialog();
// Process input if the user clicked OK.
if (userClickedOK == DialogResult.OK)
{
FileInfo fileinfo = new FileInfo(openFileDialog1.FileName);
bool setDLLDirectory = kernel32.SetDllDirectory(fileinfo.Directory.FullName);
IntPtr module;
if (((int)(module = kernel32.LoadLibrary(fileinfo.FullName))) == 0)
{
uint lastError = kernel32.GetLastError();
MessageBox.Show("Unable to load DLL Library. Kernel32 GetLastError() : " + lastError, "Error");
}
else
{
try
{
var Method = Marshal.GetDelegateForFunctionPointer((IntPtr)(module.ToInt32() + 0x1340), typeof(GenerateKey)) as GenerateKey;
Method();
ShowKey(module);
return true;
}
catch (Exception exp)
{
MessageBox.Show("Invalid KeyGen position. This version of MapleStory may be unsupported.\r\n" + exp.ToString(), "Error");
}
finally
{
kernel32.FreeLibrary(module);
}
}
}
return false;
}
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
private delegate void GenerateKey();
/// <summary>
/// Display the Aes key used for the maplestory encryption.
/// </summary>
private void ShowKey(IntPtr module)
{
const int KeyPos = 0x14020;
const int KeyGen = 0x1340;
// OdinMS format
StringBuilder sb = new StringBuilder();
for (int i = 0; i < 128; i += 16)
{
short value = (short)Marshal.ReadInt32((IntPtr)(module.ToInt32() + KeyPos + i));
sb.Append("(byte) 0x" + value.ToString("X") + ", (byte) 0x00, (byte) 0x00, (byte) 0x00");
sb.Append(", ");
}
sb = sb.Remove(sb.Length - 2, 2);
// Mapleshark format
StringBuilder sb2 = new StringBuilder();
StringBuilder sb_sharkCombined = new StringBuilder();
for (int i = 0; i < 128; i += 4)
{
byte value = Marshal.ReadByte((IntPtr)(module.ToInt32() + KeyPos + i));
string hexValue = value.ToString("X").PadLeft(2, '0');
sb2.Append("0x" + hexValue);
sb2.Append(", ");
sb_sharkCombined.Append(hexValue);
}
sb2 = sb2.Remove(sb2.Length - 2, 2);
textBox_aesOdin.Text = sb.ToString();
textBox_aesOthers.Text = sb2.ToString()
+ Environment.NewLine + Environment.NewLine
+ sb_sharkCombined.ToString(); ;
}
}
}
| 34.931818 | 148 | 0.528085 | [
"MPL-2.0",
"MPL-2.0-no-copyleft-exception"
] | Bia10/Harepacker-resurrected | HaRepacker/GUI/ZLZPacketEncryptionKeyForm.cs | 4,613 | C# |
using LightDx.Natives;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace LightDx
{
public sealed class VertexBuffer : IDisposable
{
private readonly LightDevice _device;
private readonly IBufferUpdate _update;
//support only one buffer
private IntPtr _buffer;
private IntPtr _layout;
private uint _stride;
private int _vertexCount;
private bool _isDynamic;
private bool _disposed;
internal bool IsDynamic => _isDynamic;
internal uint Stride => _stride;
internal IntPtr BufferPtr => _buffer;
internal int VertexCount => _vertexCount;
internal VertexBuffer(LightDevice device, IBufferUpdate update, IntPtr buffer, IntPtr layout,
int stride, int vertexCount, bool isDynamic)
{
_device = device;
device.AddComponent(this);
_update = update;
_buffer = buffer;
_layout = layout;
_stride = (uint)stride;
_vertexCount = vertexCount;
_isDynamic = isDynamic;
}
~VertexBuffer()
{
Dispose(false);
}
public void Dispose()
{
Dispose(true);
}
private void Dispose(bool disposing)
{
if (_disposed)
{
return;
}
NativeHelper.Dispose(ref _buffer);
NativeHelper.Dispose(ref _layout);
if (disposing)
{
_device.RemoveComponent(this);
}
_disposed = true;
GC.SuppressFinalize(this);
}
internal unsafe void Bind()
{
DeviceContext.IASetInputLayout(_device.ContextPtr, _layout);
uint stride = _stride, offset = 0;
IntPtr buffer = _buffer;
DeviceContext.IASetVertexBuffers(_device.ContextPtr, 0, 1, &buffer, &stride, &offset);
}
public void Update(Array data, int start = 0, int length = -1)
{
_update.UpdateBuffer(this, data, start, length);
}
public void DrawAll()
{
Draw(0, _vertexCount);
}
public void Draw(int vertexOffset, int vertexCount)
{
Bind();
DeviceContext.Draw(_device.ContextPtr, (uint)vertexCount, (uint)vertexOffset);
}
}
}
| 25.96875 | 101 | 0.558363 | [
"MIT"
] | acaly/LightDX | LightDx/VertexBuffer.cs | 2,495 | C# |
using System;
using System.Collections.Generic;
using System.Windows.Forms;
namespace Project2_Random
{
static class Program
{
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new Form1());
}
}
}
| 22.142857 | 65 | 0.593548 | [
"MIT"
] | KvanTTT/BMSTU-Education | Modeling2/Project2_Random/Program.cs | 467 | C# |
namespace Nancy.Session.InProc.InProcSessionsManagement {
internal interface IInProcSessionFactory {
InProcSession Create(SessionId sessionId, ISession wrappedSession);
}
} | 36.2 | 71 | 0.81768 | [
"MIT"
] | DavidLievrouw/Nancy.Session.InProc | src/Nancy.Session.InProc/InProcSessionsManagement/IInProcSessionFactory.cs | 183 | C# |
using System;
using System.Collections.Generic;
using System.Text;
namespace PropertyClassExample
{
public class Properties
{
public string Name
{
get { return "I am a Name property"; }
}
public int Age
{
get
{
DateTime dateOfBirth = new DateTime(1996, 01, 04);
DateTime currentDate = DateTime.Now;
int age = currentDate.Year - dateOfBirth.Year;
Console.WriteLine("Get Age Called");
return age;
}
set
{
Console.WriteLine("Set Age called " + value);
}
}
}
}
| 21.272727 | 66 | 0.481481 | [
"MIT"
] | Firelexic/Learned | C#/From Books/Diving Into OOP - Akhil Mittal/PropertyClassExample/PropertyClassExample/Properties.cs | 704 | C# |
using System;
public class PointInsideACircleOutsideOfARectangle
{
public static void Main()
{
decimal centerX = 1.0m,
centerY = 1.0m,
radius = 1.5m;
decimal pointX = decimal.Parse(Console.ReadLine());
decimal pointY = decimal.Parse(Console.ReadLine());
decimal result = (pointX - centerX) * (pointX - centerX) + (pointY - centerY) * (pointY - centerY);
bool withinCircle = result <= radius * radius;
decimal leftX = -1m,
width = 6m,
rightX = leftX + width;
decimal topY = 1m,
height = 2m,
bottomY = topY - height;
bool inTheRect = (pointX >= leftX) && (pointX <= rightX) && (pointY >= bottomY) && (pointY <= topY);
if (withinCircle)
{
Console.Write("inside circle");
}
else
{
Console.Write("outside circle");
}
if (inTheRect)
{
Console.WriteLine(" inside rectangle");
}
else
{
Console.WriteLine(" outside rectangle");
}
}
} | 26.674419 | 108 | 0.499564 | [
"MIT"
] | TanyaRan/TelerikAcademy_2016-2017 | Module01_Basics/01.C#_Basics/03.Operators_and_Expressions/10.PointInsideACircleOutsideOfARectangle/PointInsideACircleOutsideOfARectangle.cs | 1,149 | C# |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class SkillTreeButton : MonoBehaviour
{
public int maxUses = 1;
public int currentUses = 0;
public string skillDescription;
private bool playedSound = false;
public Image highlight;
private void Start() {
highlight.enabled = false;
}
private void Update() {
if(currentUses == maxUses){
highlight.enabled = true;
if(!playedSound){
UI.instance.playMenuSound("addSkillPoint");
playedSound = true;
}
}
}
public void noSkillPoint(){
if(currentUses == 0 && GameMaster.instance.playerStats.skillPoints.Value == 0){
UI.instance.playMenuSound("noSkillPoint");
}
}
}
| 22.567568 | 87 | 0.613174 | [
"MIT"
] | ckhuang98/Hunting-the-Aurora | Assets/Scripts/UI/SkillTreeButton.cs | 837 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Hyperion.Core.BL
{
using Poseidon.Base.Framework;
using Hyperion.Core.DL;
using Hyperion.Core.IDAL;
/// <summary>
/// 设备业务类
/// </summary>
public class EquipmentBusiness : AbstractBusiness<Equipment, long>, IBaseBL<Equipment, long>
{
#region Constructor
/// <summary>
/// 设备业务类
/// </summary>
public EquipmentBusiness()
{
this.baseDal = RepositoryFactory<IEquipmentRepository>.Instance;
}
#endregion //Constructor
#region Method
/// <summary>
/// 按序列号查找设备
/// </summary>
/// <param name="serialNumber">序列号</param>
/// <returns></returns>
public Equipment FindBySerialNumber(string serialNumber)
{
return this.baseDal.FindOneByField("serial_number", serialNumber);
}
/// <summary>
/// 按厂商查找设备
/// </summary>
/// <param name="vendor">厂商</param>
/// <returns></returns>
public IEnumerable<Equipment> FindByVendor(string vendor)
{
return this.baseDal.FindListByField("vendor", vendor);
}
#endregion //Method
}
}
| 25.862745 | 96 | 0.579985 | [
"Apache-2.0"
] | robertzml/Hyperion | Hyperion.Core/BL/EquipmentBusiness.cs | 1,381 | C# |
using Abp.Application.Services.Dto;
namespace Dg.fifth.MultiTenancy.Dto
{
public class PagedTenantResultRequestDto : PagedResultRequestDto
{
public string Keyword { get; set; }
public bool? IsActive { get; set; }
}
}
| 20.666667 | 68 | 0.681452 | [
"MIT"
] | PowerDG/Dg.KMS.Web | Dg.fifth/4.8.0/aspnet-core/src/Dg.fifth.Application/MultiTenancy/Dto/PagedTenantResultRequestDto.cs | 250 | C# |
using System;
using System.Collections.Generic;
using System.Text;
using System.Xml.Serialization;
namespace DensoCreate.LightningReview.ReviewFile.Models.V18
{
/// <summary>
/// ドキュメントの一覧
/// </summary>
[XmlRoot]
public class Documents : EntityBase
{
#region プロパティ
/// <summary>
/// ドキュメントの一覧
/// </summary>
[XmlArray("List")]
[XmlArrayItem("Document")]
public List<Document> List { get; set; } = new List<Document>();
#endregion
}
}
| 20.423077 | 72 | 0.591337 | [
"MIT"
] | denso-create/LightningReview-ReviewFile | src/ReviewFile/Models/V18/Documents.cs | 579 | C# |
using NINA.WPF.Base.Interfaces.ViewModel;
namespace NINA.WPF.Base.Interfaces {
public interface IMeridianFlipVMFactory {
IMeridianFlipVM Create();
}
}
| 21.125 | 45 | 0.727811 | [
"MPL-2.0",
"MPL-2.0-no-copyleft-exception"
] | daleghent/NINA | NINA.Core.WPF/Interfaces/IMeridianFlipVMFactory.cs | 171 | C# |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using System.Collections.Immutable;
using System.Linq;
using System.Threading;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.CSharp.Test.Utilities;
using Microsoft.CodeAnalysis.Diagnostics;
using Microsoft.CodeAnalysis.Test.Utilities;
using Roslyn.Test.Utilities;
using Xunit;
using PublicNullableAnnotation = Microsoft.CodeAnalysis.NullableAnnotation;
using PublicNullableFlowState = Microsoft.CodeAnalysis.NullableFlowState;
namespace Microsoft.CodeAnalysis.CSharp.UnitTests
{
[CompilerTrait(CompilerFeature.NullableReferenceTypes)]
public class NullablePublicAPITests : CSharpTestBase
{
[Fact]
public void TestArrayNullability()
{
var source = @"
class C
{
void M(C?[] arr1)
{
C[] arr2 = (C[])arr1;
arr1[0].ToString();
arr2[0].ToString();
}
}
";
var comp = CreateCompilation(source, options: WithNonNullTypesTrue());
comp.VerifyDiagnostics(
// (6,20): warning CS8619: Nullability of reference types in value of type 'C?[]' doesn't match target type 'C[]'.
// C[] arr2 = (C[])arr1;
Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "(C[])arr1").WithArguments("C?[]", "C[]").WithLocation(6, 20),
// (7,9): warning CS8602: Possible dereference of a null reference.
// arr1[0].ToString();
Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "arr1[0]").WithLocation(7, 9));
var syntaxTree = comp.SyntaxTrees[0];
var root = syntaxTree.GetRoot();
var model = comp.GetSemanticModel(syntaxTree);
var arrayAccesses = root.DescendantNodes().OfType<ElementAccessExpressionSyntax>().ToList();
var arrayTypes = arrayAccesses.Select(arr => model.GetTypeInfoAndVerifyIOperation(arr.Expression).Type).Cast<IArrayTypeSymbol>().ToList();
Assert.Equal(PublicNullableAnnotation.Annotated, arrayTypes[0].ElementNullableAnnotation);
Assert.Equal(PublicNullableAnnotation.Annotated, arrayTypes[0].ElementType.NullableAnnotation);
Assert.Equal(PublicNullableAnnotation.NotAnnotated, arrayTypes[1].ElementNullableAnnotation);
Assert.Equal(PublicNullableAnnotation.NotAnnotated, arrayTypes[1].ElementType.NullableAnnotation);
}
[Fact]
public void TestTypeArgumentNullability()
{
var source = @"
class B<T> {}
class C
{
B<T> M<T>(T t) where T : C? { return default!; }
void M1(C? c)
{
M(new C());
M(c);
if (c == null) return;
M(c);
}
}";
var comp = CreateCompilation(source, options: WithNonNullTypesTrue());
comp.VerifyDiagnostics();
var syntaxTree = comp.SyntaxTrees[0];
var root = syntaxTree.GetRoot();
var model = comp.GetSemanticModel(syntaxTree);
var invocations = root.DescendantNodes().OfType<InvocationExpressionSyntax>().ToList();
var expressionTypes = invocations.Select(inv => model.GetTypeInfoAndVerifyIOperation(inv).Type).Cast<INamedTypeSymbol>().ToList();
Assert.Equal(PublicNullableAnnotation.NotAnnotated, expressionTypes[0].TypeArgumentNullableAnnotations.Single());
Assert.Equal(PublicNullableAnnotation.NotAnnotated, expressionTypes[0].TypeArgumentNullableAnnotations().Single());
Assert.Equal(PublicNullableAnnotation.Annotated, expressionTypes[1].TypeArgumentNullableAnnotations.Single());
Assert.Equal(PublicNullableAnnotation.Annotated, expressionTypes[1].TypeArgumentNullableAnnotations().Single());
Assert.Equal(PublicNullableAnnotation.NotAnnotated, expressionTypes[2].TypeArgumentNullableAnnotations.Single());
Assert.Equal(PublicNullableAnnotation.NotAnnotated, expressionTypes[2].TypeArgumentNullableAnnotations().Single());
}
[Fact]
[WorkItem(34412, "https://github.com/dotnet/roslyn/issues/34412")]
public void FieldDeclarations()
{
var source = @"
public struct S {}
public class C
{
#nullable enable
public C c1 = new C();
public C? c2 = null;
public S s1 = default;
public S? s2 = null;
#nullable disable
public C c3 = null;
public C? c4 = null;
public S s3 = default;
public S? s4 = null;
}
";
VerifyAcrossCompilations(
source,
new[]
{
// (13,13): warning CS8632: The annotation for nullable reference types should only be used in code within a '#nullable' context.
// public C? c4 = null;
Diagnostic(ErrorCode.WRN_MissingNonNullTypesContextForAnnotation, "?").WithLocation(13, 13)
},
new DiagnosticDescription[]
{
// (5,2): error CS8652: The feature 'nullable reference types' is not available in C# 7.3. Please use language version 8.0 or greater.
// #nullable enable
Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "nullable").WithArguments("nullable reference types", "8.0").WithLocation(5, 2),
// (7,13): error CS8652: The feature 'nullable reference types' is not available in C# 7.3. Please use language version 8.0 or greater.
// public C? c2 = null;
Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "?").WithArguments("nullable reference types", "8.0").WithLocation(7, 13),
// (11,2): error CS8652: The feature 'nullable reference types' is not available in C# 7.3. Please use language version 8.0 or greater.
// #nullable disable
Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "nullable").WithArguments("nullable reference types", "8.0").WithLocation(11, 2),
// (13,13): error CS8652: The feature 'nullable reference types' is not available in C# 7.3. Please use language version 8.0 or greater.
// public C? c4 = null;
Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "?").WithArguments("nullable reference types", "8.0").WithLocation(13, 13)
},
comp =>
{
var c = ((Compilation)comp).GetTypeByMetadataName("C");
return c.GetMembers().OfType<IFieldSymbol>().ToArray();
},
member =>
{
var result = member.Type.NullableAnnotation;
Assert.Equal(result, member.NullableAnnotation);
return member.Type.NullableAnnotation;
},
testMetadata: true,
PublicNullableAnnotation.NotAnnotated,
PublicNullableAnnotation.Annotated,
PublicNullableAnnotation.NotAnnotated,
PublicNullableAnnotation.Annotated,
PublicNullableAnnotation.None,
PublicNullableAnnotation.Annotated,
PublicNullableAnnotation.NotAnnotated,
PublicNullableAnnotation.Annotated);
}
[Fact]
[WorkItem(34412, "https://github.com/dotnet/roslyn/issues/34412")]
public void PropertyDeclarations()
{
var source = @"
public struct S {}
public class C
{
#nullable enable
public C C1 { get; set; } = new C();
public C? C2 { get; set; }
public S S1 { get; set; }
public S? S2 { get; set; }
#nullable disable
public C C3 { get; set; }
public C? C4 { get; set; }
public S S3 { get; set; }
public S? S4 { get; set; }
}
";
VerifyAcrossCompilations(
source,
new[]
{
// (13,13): warning CS8632: The annotation for nullable reference types should only be used in code within a '#nullable' context.
// public C? C4 { get; set; }
Diagnostic(ErrorCode.WRN_MissingNonNullTypesContextForAnnotation, "?").WithLocation(13, 13)
},
new[]
{
// (5,2): error CS8652: The feature 'nullable reference types' is not available in C# 7.3. Please use language version 8.0 or greater.
// #nullable enable
Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "nullable").WithArguments("nullable reference types", "8.0").WithLocation(5, 2),
// (7,13): error CS8652: The feature 'nullable reference types' is not available in C# 7.3. Please use language version 8.0 or greater.
// public C? C2 { get; set; }
Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "?").WithArguments("nullable reference types", "8.0").WithLocation(7, 13),
// (11,2): error CS8652: The feature 'nullable reference types' is not available in C# 7.3. Please use language version 8.0 or greater.
// #nullable disable
Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "nullable").WithArguments("nullable reference types", "8.0").WithLocation(11, 2),
// (13,13): error CS8652: The feature 'nullable reference types' is not available in C# 7.3. Please use language version 8.0 or greater.
// public C? C4 { get; set; }
Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "?").WithArguments("nullable reference types", "8.0").WithLocation(13, 13)
},
comp =>
{
var c = ((Compilation)comp).GetTypeByMetadataName("C");
return c.GetMembers().OfType<IPropertySymbol>().ToArray();
},
member =>
{
var result = member.Type.NullableAnnotation;
Assert.Equal(result, member.NullableAnnotation);
return result;
},
testMetadata: true,
PublicNullableAnnotation.NotAnnotated,
PublicNullableAnnotation.Annotated,
PublicNullableAnnotation.NotAnnotated,
PublicNullableAnnotation.Annotated,
PublicNullableAnnotation.None,
PublicNullableAnnotation.Annotated,
PublicNullableAnnotation.NotAnnotated,
PublicNullableAnnotation.Annotated);
}
[Fact]
[WorkItem(34412, "https://github.com/dotnet/roslyn/issues/34412")]
public void MethodReturnDeclarations()
{
var source = @"
public struct S {}
public class C
{
#nullable enable
public string M0() => string.Empty;
public string? M1() => null;
#nullable disable
public string M2() => null;
public string? M3() => null; // 1
#nullable enable
public S M4() => default;
public S? M5() => null;
#nullable disable
public S M6() => default;
public S? M7() => default;
}";
VerifyAcrossCompilations(
source,
new[]
{
// (10,18): warning CS8632: The annotation for nullable reference types should only be used in code within a '#nullable' context.
// public string? M3() => null; // 1
Diagnostic(ErrorCode.WRN_MissingNonNullTypesContextForAnnotation, "?").WithLocation(10, 18)
},
new[]
{
// (5,2): error CS8652: The feature 'nullable reference types' is not available in C# 7.3. Please use language version 8.0 or greater.
// #nullable enable
Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "nullable").WithArguments("nullable reference types", "8.0").WithLocation(5, 2),
// (7,18): error CS8652: The feature 'nullable reference types' is not available in C# 7.3. Please use language version 8.0 or greater.
// public string? M1() => null;
Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "?").WithArguments("nullable reference types", "8.0").WithLocation(7, 18),
// (8,2): error CS8652: The feature 'nullable reference types' is not available in C# 7.3. Please use language version 8.0 or greater.
// #nullable disable
Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "nullable").WithArguments("nullable reference types", "8.0").WithLocation(8, 2),
// (10,18): error CS8652: The feature 'nullable reference types' is not available in C# 7.3. Please use language version 8.0 or greater.
// public string? M3() => null; // 1
Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "?").WithArguments("nullable reference types", "8.0").WithLocation(10, 18),
// (12,2): error CS8652: The feature 'nullable reference types' is not available in C# 7.3. Please use language version 8.0 or greater.
// #nullable enable
Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "nullable").WithArguments("nullable reference types", "8.0").WithLocation(12, 2),
// (15,2): error CS8652: The feature 'nullable reference types' is not available in C# 7.3. Please use language version 8.0 or greater.
// #nullable disable
Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "nullable").WithArguments("nullable reference types", "8.0").WithLocation(15, 2)
},
compilation =>
{
var c = ((Compilation)compilation).GetTypeByMetadataName("C");
return c.GetMembers().OfType<IMethodSymbol>().Where(m => m.Name.StartsWith("M")).ToArray();
},
member =>
{
var result = member.ReturnType.NullableAnnotation;
Assert.Equal(result, member.ReturnNullableAnnotation);
return result;
},
testMetadata: true,
PublicNullableAnnotation.NotAnnotated,
PublicNullableAnnotation.Annotated,
PublicNullableAnnotation.None,
PublicNullableAnnotation.Annotated,
PublicNullableAnnotation.NotAnnotated,
PublicNullableAnnotation.Annotated,
PublicNullableAnnotation.NotAnnotated,
PublicNullableAnnotation.Annotated);
}
[Fact]
[WorkItem(34412, "https://github.com/dotnet/roslyn/issues/34412")]
public void ParameterDeclarations()
{
var source = @"
public struct S {}
public class C
{
public void M1(
#nullable enable
C c1,
#nullable disable
C c2,
#nullable enable
C? c3,
#nullable disable
C? c4,
#nullable enable
S s1,
#nullable disable
S s2,
#nullable enable
S? s3,
#nullable disable
S? s4) {}
}
";
VerifyAcrossCompilations(
source,
new[]
{
// (13,10): warning CS8632: The annotation for nullable reference types should only be used in code within a '#nullable' context.
// C? c4,
Diagnostic(ErrorCode.WRN_MissingNonNullTypesContextForAnnotation, "?").WithLocation(13, 10)
},
new[] {
// (6,2): error CS8652: The feature 'nullable reference types' is not available in C# 7.3. Please use language version 8.0 or greater.
// #nullable enable
Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "nullable").WithArguments("nullable reference types", "8.0").WithLocation(6, 2),
// (8,2): error CS8652: The feature 'nullable reference types' is not available in C# 7.3. Please use language version 8.0 or greater.
// #nullable disable
Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "nullable").WithArguments("nullable reference types", "8.0").WithLocation(8, 2),
// (10,2): error CS8652: The feature 'nullable reference types' is not available in C# 7.3. Please use language version 8.0 or greater.
// #nullable enable
Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "nullable").WithArguments("nullable reference types", "8.0").WithLocation(10, 2),
// (11,10): error CS8652: The feature 'nullable reference types' is not available in C# 7.3. Please use language version 8.0 or greater.
// C? c3,
Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "?").WithArguments("nullable reference types", "8.0").WithLocation(11, 10),
// (12,2): error CS8652: The feature 'nullable reference types' is not available in C# 7.3. Please use language version 8.0 or greater.
// #nullable disable
Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "nullable").WithArguments("nullable reference types", "8.0").WithLocation(12, 2),
// (13,10): error CS8652: The feature 'nullable reference types' is not available in C# 7.3. Please use language version 8.0 or greater.
// C? c4,
Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "?").WithArguments("nullable reference types", "8.0").WithLocation(13, 10),
// (14,2): error CS8652: The feature 'nullable reference types' is not available in C# 7.3. Please use language version 8.0 or greater.
// #nullable enable
Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "nullable").WithArguments("nullable reference types", "8.0").WithLocation(14, 2),
// (16,2): error CS8652: The feature 'nullable reference types' is not available in C# 7.3. Please use language version 8.0 or greater.
// #nullable disable
Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "nullable").WithArguments("nullable reference types", "8.0").WithLocation(16, 2),
// (18,2): error CS8652: The feature 'nullable reference types' is not available in C# 7.3. Please use language version 8.0 or greater.
// #nullable enable
Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "nullable").WithArguments("nullable reference types", "8.0").WithLocation(18, 2),
// (20,2): error CS8652: The feature 'nullable reference types' is not available in C# 7.3. Please use language version 8.0 or greater.
// #nullable disable
Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "nullable").WithArguments("nullable reference types", "8.0").WithLocation(20, 2)
},
compilation =>
{
var c = ((Compilation)compilation).GetTypeByMetadataName("C");
return c.GetMembers("M1").OfType<IMethodSymbol>().Single().Parameters.ToArray();
},
member =>
{
var result = member.Type.NullableAnnotation;
Assert.Equal(result, member.NullableAnnotation);
return result;
},
testMetadata: true,
PublicNullableAnnotation.NotAnnotated,
PublicNullableAnnotation.None,
PublicNullableAnnotation.Annotated,
PublicNullableAnnotation.Annotated,
PublicNullableAnnotation.NotAnnotated,
PublicNullableAnnotation.NotAnnotated,
PublicNullableAnnotation.Annotated,
PublicNullableAnnotation.Annotated);
}
[Fact]
[WorkItem(35034, "https://github.com/dotnet/roslyn/issues/35034")]
public void MethodDeclarationReceiver()
{
var source = @"
public class C
{
#nullable enable
public static void M1() {}
public void M2() {}
#nullable disable
public static void M3() {}
public void M4() {}
}
public static class Ext
{
#nullable enable
public static void M5(this C c) {}
public static void M6(this C? c) {}
public static void M7(this int i) {}
public static void M8(this int? i) {}
#nullable disable
public static void M9(this C c) {}
public static void M10(this C? c) {}
public static void M11(this int i) {}
public static void M12(this int? i) {}
}
";
var comp1 = CreateCompilation(source, options: WithNonNullTypesTrue());
comp1.VerifyDiagnostics(
// (22,34): warning CS8632: The annotation for nullable reference types should only be used in code within a '#nullable' annotations context.
// public static void M10(this C? c) {}
Diagnostic(ErrorCode.WRN_MissingNonNullTypesContextForAnnotation, "?").WithLocation(22, 34));
verifyCompilation(comp1);
var comp2 = CreateCompilation(source, options: WithNonNullTypesFalse());
comp2.VerifyDiagnostics(
// (22,34): warning CS8632: The annotation for nullable reference types should only be used in code within a '#nullable' annotations context.
// public static void M10(this C? c) {}
Diagnostic(ErrorCode.WRN_MissingNonNullTypesContextForAnnotation, "?").WithLocation(22, 34));
verifyCompilation(comp2);
var comp3 = CreateCompilation(source, parseOptions: TestOptions.Regular7_3, skipUsesIsNullable: true);
comp3.VerifyDiagnostics(
// (4,2): error CS8370: Feature 'nullable reference types' is not available in C# 7.3. Please use language version 8.0 or greater.
// #nullable enable
Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "nullable").WithArguments("nullable reference types", "8.0").WithLocation(4, 2),
// (8,2): error CS8370: Feature 'nullable reference types' is not available in C# 7.3. Please use language version 8.0 or greater.
// #nullable disable
Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "nullable").WithArguments("nullable reference types", "8.0").WithLocation(8, 2),
// (14,2): error CS8370: Feature 'nullable reference types' is not available in C# 7.3. Please use language version 8.0 or greater.
// #nullable enable
Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "nullable").WithArguments("nullable reference types", "8.0").WithLocation(14, 2),
// (16,33): error CS8370: Feature 'nullable reference types' is not available in C# 7.3. Please use language version 8.0 or greater.
// public static void M6(this C? c) {}
Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "?").WithArguments("nullable reference types", "8.0").WithLocation(16, 33),
// (20,2): error CS8370: Feature 'nullable reference types' is not available in C# 7.3. Please use language version 8.0 or greater.
// #nullable disable
Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "nullable").WithArguments("nullable reference types", "8.0").WithLocation(20, 2),
// (22,34): error CS8370: Feature 'nullable reference types' is not available in C# 7.3. Please use language version 8.0 or greater.
// public static void M10(this C? c) {}
Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "?").WithArguments("nullable reference types", "8.0").WithLocation(22, 34));
verifyCompilation(comp3);
var comp1Emit = comp1.EmitToImageReference();
var comp4 = CreateCompilation("", references: new[] { comp1Emit }, options: WithNonNullTypesTrue());
comp4.VerifyDiagnostics();
verifyCompilation(comp4);
var comp2Emit = comp2.EmitToImageReference();
var comp5 = CreateCompilation("", references: new[] { comp2Emit }, options: WithNonNullTypesFalse());
comp5.VerifyDiagnostics();
verifyCompilation(comp5);
var comp6 = CreateCompilation("", references: new[] { comp1Emit }, parseOptions: TestOptions.Regular7_3);
comp6.VerifyDiagnostics();
verifyCompilation(comp6);
void verifyCompilation(CSharpCompilation compilation)
{
var c = ((Compilation)compilation).GetTypeByMetadataName("C");
var members = c.GetMembers().OfType<IMethodSymbol>().Where(m => m.Name.StartsWith("M")).ToArray();
assertNullability(members,
PublicNullableAnnotation.None,
PublicNullableAnnotation.NotAnnotated,
PublicNullableAnnotation.None,
PublicNullableAnnotation.NotAnnotated);
var e = ((Compilation)compilation).GetTypeByMetadataName("Ext");
members = e.GetMembers().OfType<IMethodSymbol>().Where(m => m.Name.StartsWith("M")).Select(m => m.ReduceExtensionMethod(m.Parameters[0].Type)).ToArray();
assertNullability(members,
PublicNullableAnnotation.NotAnnotated,
PublicNullableAnnotation.Annotated,
PublicNullableAnnotation.NotAnnotated,
PublicNullableAnnotation.Annotated,
PublicNullableAnnotation.None,
PublicNullableAnnotation.Annotated,
PublicNullableAnnotation.NotAnnotated,
PublicNullableAnnotation.Annotated);
static void assertNullability(IMethodSymbol[] methods, params PublicNullableAnnotation[] expectedAnnotations)
{
var actualAnnotations = methods.Select(m =>
{
var result = m.ReceiverType.NullableAnnotation;
Assert.Equal(result, m.ReceiverNullableAnnotation);
return result;
});
AssertEx.Equal(expectedAnnotations, actualAnnotations);
}
}
}
[Fact]
public void LocalFunctions()
{
var source = @"
#pragma warning disable CS8321 // Unused local function
public struct S {}
public class C
{
void M1()
{
#nullable enable
C LM1(C c) => new C();
C? LM2(C? c) => null;
S LM3(S s) => default;
S? LM4(S? s) => null;
#nullable disable
C LM5(C c) => new C();
C? LM6(C? c) => null;
S LM7(S s) => default;
S? LM8(S? s) => null;
}
}
";
VerifyAcrossCompilations(
source,
new[] {
// (15,10): warning CS8632: The annotation for nullable reference types should only be used in code within a '#nullable' context.
// C? LM6(C? c) => null;
Diagnostic(ErrorCode.WRN_MissingNonNullTypesContextForAnnotation, "?").WithLocation(15, 10),
// (15,17): warning CS8632: The annotation for nullable reference types should only be used in code within a '#nullable' context.
// C? LM6(C? c) => null;
Diagnostic(ErrorCode.WRN_MissingNonNullTypesContextForAnnotation, "?").WithLocation(15, 17)
},
new[] {
// (8,2): error CS8652: The feature 'nullable reference types' is not available in C# 7.3. Please use language version 8.0 or greater.
// #nullable enable
Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "nullable").WithArguments("nullable reference types", "8.0").WithLocation(8, 2),
// (10,10): error CS8652: The feature 'nullable reference types' is not available in C# 7.3. Please use language version 8.0 or greater.
// C? LM2(C? c) => null;
Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "?").WithArguments("nullable reference types", "8.0").WithLocation(10, 10),
// (10,17): error CS8652: The feature 'nullable reference types' is not available in C# 7.3. Please use language version 8.0 or greater.
// C? LM2(C? c) => null;
Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "?").WithArguments("nullable reference types", "8.0").WithLocation(10, 17),
// (13,2): error CS8652: The feature 'nullable reference types' is not available in C# 7.3. Please use language version 8.0 or greater.
// #nullable disable
Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "nullable").WithArguments("nullable reference types", "8.0").WithLocation(13, 2),
// (15,10): error CS8652: The feature 'nullable reference types' is not available in C# 7.3. Please use language version 8.0 or greater.
// C? LM6(C? c) => null;
Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "?").WithArguments("nullable reference types", "8.0").WithLocation(15, 10),
// (15,17): error CS8652: The feature 'nullable reference types' is not available in C# 7.3. Please use language version 8.0 or greater.
// C? LM6(C? c) => null;
Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "?").WithArguments("nullable reference types", "8.0").WithLocation(15, 17)
},
comp =>
{
var syntaxTree = comp.SyntaxTrees[0];
var semanticModel = comp.GetSemanticModel(syntaxTree);
return syntaxTree.GetRoot().DescendantNodes().OfType<CSharp.Syntax.LocalFunctionStatementSyntax>().Select(func => semanticModel.GetDeclaredSymbol(func)).Cast<IMethodSymbol>().ToArray();
},
method =>
{
Assert.Equal(method.ReturnNullableAnnotation, method.Parameters[0].NullableAnnotation);
Assert.Equal(method.ReturnNullableAnnotation, method.Parameters[0].Type.NullableAnnotation);
Assert.Equal(PublicNullableAnnotation.None, method.ReceiverNullableAnnotation);
Assert.Equal(PublicNullableAnnotation.None, method.ReceiverType.NullableAnnotation);
var result = method.ReturnType.NullableAnnotation;
Assert.Equal(result, method.ReturnNullableAnnotation);
return result;
},
testMetadata: false,
PublicNullableAnnotation.NotAnnotated,
PublicNullableAnnotation.Annotated,
PublicNullableAnnotation.NotAnnotated,
PublicNullableAnnotation.Annotated,
PublicNullableAnnotation.None,
PublicNullableAnnotation.Annotated,
PublicNullableAnnotation.NotAnnotated,
PublicNullableAnnotation.Annotated);
}
[Fact]
public void EventDeclarations()
{
var source = @"
#pragma warning disable CS0067 // Unused event
public class C
{
public delegate void D();
#nullable enable
public event D D1;
public event D? D2;
#nullable disable
public event D D3;
public event D? D4;
}";
VerifyAcrossCompilations(
source,
new[] {
// (8,20): warning CS8618: Non-nullable event 'D1' is uninitialized. Consider declaring the event as nullable.
// public event D D1;
Diagnostic(ErrorCode.WRN_UninitializedNonNullableField, "D1").WithArguments("event", "D1").WithLocation(8, 20),
// (13,19): warning CS8632: The annotation for nullable reference types should only be used in code within a '#nullable' annotations context.
// public event D? D4;
Diagnostic(ErrorCode.WRN_MissingNonNullTypesContextForAnnotation, "?").WithLocation(13, 19)
},
new[] {
// (7,2): error CS8652: The feature 'nullable reference types' is not available in C# 7.3. Please use language version 8.0 or greater.
// #nullable enable
Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "nullable").WithArguments("nullable reference types", "8.0").WithLocation(7, 2),
// (9,19): error CS8652: The feature 'nullable reference types' is not available in C# 7.3. Please use language version 8.0 or greater.
// public event D? D2;
Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "?").WithArguments("nullable reference types", "8.0").WithLocation(9, 19),
// (11,2): error CS8652: The feature 'nullable reference types' is not available in C# 7.3. Please use language version 8.0 or greater.
// #nullable disable
Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "nullable").WithArguments("nullable reference types", "8.0").WithLocation(11, 2),
// (13,19): error CS8652: The feature 'nullable reference types' is not available in C# 7.3. Please use language version 8.0 or greater.
// public event D? D4;
Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "?").WithArguments("nullable reference types", "8.0").WithLocation(13, 19)
},
compilation =>
{
var c = ((Compilation)compilation).GetTypeByMetadataName("C");
return c.GetMembers().OfType<IEventSymbol>().ToArray();
},
member =>
{
var result = member.Type.NullableAnnotation;
Assert.Equal(result, member.NullableAnnotation);
return result;
},
testMetadata: true,
PublicNullableAnnotation.NotAnnotated,
PublicNullableAnnotation.Annotated,
PublicNullableAnnotation.None,
PublicNullableAnnotation.Annotated);
}
[Fact]
[WorkItem(34412, "https://github.com/dotnet/roslyn/issues/34412")]
public void ArrayElements()
{
var source =
@"public interface I
{
#nullable enable
object[] F1();
object?[] F2();
int[] F3();
int?[] F4();
#nullable disable
object[] F5();
object?[] F6();
int[] F7();
int?[] F8();
}";
VerifyAcrossCompilations(
source,
new[]
{
// (10,11): warning CS8632: The annotation for nullable reference types should only be used in code within a '#nullable' annotations context.
// object?[] F6();
Diagnostic(ErrorCode.WRN_MissingNonNullTypesContextForAnnotation, "?").WithLocation(10, 11)
},
new[]
{
// (3,2): error CS8370: Feature 'nullable reference types' is not available in C# 7.3. Please use language version 8.0 or greater.
// #nullable enable
Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "nullable").WithArguments("nullable reference types", "8.0").WithLocation(3, 2),
// (5,11): error CS8370: Feature 'nullable reference types' is not available in C# 7.3. Please use language version 8.0 or greater.
// object?[] F2();
Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "?").WithArguments("nullable reference types", "8.0").WithLocation(5, 11),
// (8,2): error CS8370: Feature 'nullable reference types' is not available in C# 7.3. Please use language version 8.0 or greater.
// #nullable disable
Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "nullable").WithArguments("nullable reference types", "8.0").WithLocation(8, 2),
// (10,11): error CS8370: Feature 'nullable reference types' is not available in C# 7.3. Please use language version 8.0 or greater.
// object?[] F6();
Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "?").WithArguments("nullable reference types", "8.0").WithLocation(10, 11)
},
comp => ((INamedTypeSymbol)((Compilation)comp).GetMember("I")).GetMembers().OfType<IMethodSymbol>().Where(m => m.Name.StartsWith("F")).ToArray(),
method =>
{
var array = (IArrayTypeSymbol)method.ReturnType;
var result = array.ElementType.NullableAnnotation;
Assert.Equal(result, array.ElementNullableAnnotation);
return result;
},
testMetadata: true,
PublicNullableAnnotation.NotAnnotated,
PublicNullableAnnotation.Annotated,
PublicNullableAnnotation.NotAnnotated,
PublicNullableAnnotation.Annotated,
PublicNullableAnnotation.None,
PublicNullableAnnotation.Annotated,
PublicNullableAnnotation.NotAnnotated,
PublicNullableAnnotation.Annotated);
}
[Fact]
[WorkItem(34412, "https://github.com/dotnet/roslyn/issues/34412")]
public void TypeParameters()
{
var source =
@"#nullable enable
public interface I<T, U, V>
where U : class
where V : struct
{
T F1();
U F2();
U? F3();
V F4();
V? F5();
#nullable disable
T F6();
U F7();
U? F8();
V F9();
V? F10();
}";
VerifyAcrossCompilations(
source,
new[]
{
// (14,6): warning CS8632: The annotation for nullable reference types should only be used in code within a '#nullable' annotations context.
// U? F8();
Diagnostic(ErrorCode.WRN_MissingNonNullTypesContextForAnnotation, "?").WithLocation(14, 6)
},
new[]
{
// (1,2): error CS8370: Feature 'nullable reference types' is not available in C# 7.3. Please use language version 8.0 or greater.
// #nullable enable
Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "nullable").WithArguments("nullable reference types", "8.0").WithLocation(1, 2),
// (8,6): error CS8370: Feature 'nullable reference types' is not available in C# 7.3. Please use language version 8.0 or greater.
// U? F3();
Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "?").WithArguments("nullable reference types", "8.0").WithLocation(8, 6),
// (11,2): error CS8370: Feature 'nullable reference types' is not available in C# 7.3. Please use language version 8.0 or greater.
// #nullable disable
Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "nullable").WithArguments("nullable reference types", "8.0").WithLocation(11, 2),
// (14,6): error CS8370: Feature 'nullable reference types' is not available in C# 7.3. Please use language version 8.0 or greater.
// U? F8();
Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "?").WithArguments("nullable reference types", "8.0").WithLocation(14, 6)
},
comp => ((INamedTypeSymbol)((Compilation)comp).GetMember("I")).GetMembers().OfType<IMethodSymbol>().Where(m => m.Name.StartsWith("F")).ToArray(),
method =>
{
var result = method.ReturnType.NullableAnnotation;
Assert.Equal(result, method.ReturnNullableAnnotation);
return result;
},
testMetadata: true,
PublicNullableAnnotation.NotAnnotated,
PublicNullableAnnotation.NotAnnotated,
PublicNullableAnnotation.Annotated,
PublicNullableAnnotation.NotAnnotated,
PublicNullableAnnotation.Annotated,
PublicNullableAnnotation.None,
PublicNullableAnnotation.None,
PublicNullableAnnotation.Annotated,
PublicNullableAnnotation.NotAnnotated,
PublicNullableAnnotation.Annotated);
}
[Fact]
[WorkItem(34412, "https://github.com/dotnet/roslyn/issues/34412")]
public void Constraints()
{
var source =
@"public class A<T>
{
public class B<U> where U : T { }
}
public interface I
{
#nullable enable
A<string> F1();
A<string?> F2();
A<int> F3();
A<int?> F4();
#nullable disable
A<string> F5();
A<string?> F6();
A<int> F7();
A<int?> F8();
}";
VerifyAcrossCompilations(
source,
new[]
{
// (14,13): warning CS8632: The annotation for nullable reference types should only be used in code within a '#nullable' annotations context.
// A<object?> F6();
Diagnostic(ErrorCode.WRN_MissingNonNullTypesContextForAnnotation, "?").WithLocation(14, 13)
},
new[]
{
// (7,2): error CS8370: Feature 'nullable reference types' is not available in C# 7.3. Please use language version 8.0 or greater.
// #nullable enable
Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "nullable").WithArguments("nullable reference types", "8.0").WithLocation(7, 2),
// (9,13): error CS8370: Feature 'nullable reference types' is not available in C# 7.3. Please use language version 8.0 or greater.
// A<string?> F2();
Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "?").WithArguments("nullable reference types", "8.0").WithLocation(9, 13),
// (12,2): error CS8370: Feature 'nullable reference types' is not available in C# 7.3. Please use language version 8.0 or greater.
// #nullable disable
Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "nullable").WithArguments("nullable reference types", "8.0").WithLocation(12, 2),
// (14,13): error CS8370: Feature 'nullable reference types' is not available in C# 7.3. Please use language version 8.0 or greater.
// A<string?> F6();
Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "?").WithArguments("nullable reference types", "8.0").WithLocation(14, 13)
},
comp => ((INamedTypeSymbol)((Compilation)comp).GetMember("I")).GetMembers().OfType<IMethodSymbol>().Where(m => m.Name.StartsWith("F")).ToArray(),
method =>
{
ITypeParameterSymbol typeParameterSymbol = ((INamedTypeSymbol)((INamedTypeSymbol)method.ReturnType).GetMembers("B").Single()).TypeParameters.Single();
var result = typeParameterSymbol.ConstraintTypes.Single().NullableAnnotation;
Assert.Equal(result, typeParameterSymbol.ConstraintNullableAnnotations.Single());
return result;
},
testMetadata: true,
PublicNullableAnnotation.NotAnnotated,
PublicNullableAnnotation.Annotated,
PublicNullableAnnotation.NotAnnotated,
PublicNullableAnnotation.Annotated,
PublicNullableAnnotation.None,
PublicNullableAnnotation.Annotated,
PublicNullableAnnotation.NotAnnotated,
PublicNullableAnnotation.Annotated);
}
[Fact]
[WorkItem(34412, "https://github.com/dotnet/roslyn/issues/34412")]
public void TypeArguments_01()
{
var source =
@"public interface IA<T>
{
}
#nullable enable
public interface IB<T, U, V>
where U : class
where V : struct
{
IA<T> F1();
IA<U> F2();
IA<U?> F3();
IA<V> F4();
IA<V?> F5();
#nullable disable
IA<T> F6();
IA<U> F7();
IA<U?> F8();
IA<V> F9();
IA<V?> F10();
}";
VerifyAcrossCompilations(
source,
new[]
{
// (17,9): warning CS8632: The annotation for nullable reference types should only be used in code within a '#nullable' annotations context.
// IA<U?> F8();
Diagnostic(ErrorCode.WRN_MissingNonNullTypesContextForAnnotation, "?").WithLocation(17, 9)
},
new[]
{
// (4,2): error CS8370: Feature 'nullable reference types' is not available in C# 7.3. Please use language version 8.0 or greater.
// #nullable enable
Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "nullable").WithArguments("nullable reference types", "8.0").WithLocation(4, 2),
// (11,9): error CS8370: Feature 'nullable reference types' is not available in C# 7.3. Please use language version 8.0 or greater.
// IA<U?> F3();
Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "?").WithArguments("nullable reference types", "8.0").WithLocation(11, 9),
// (14,2): error CS8370: Feature 'nullable reference types' is not available in C# 7.3. Please use language version 8.0 or greater.
// #nullable disable
Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "nullable").WithArguments("nullable reference types", "8.0").WithLocation(14, 2),
// (17,9): error CS8370: Feature 'nullable reference types' is not available in C# 7.3. Please use language version 8.0 or greater.
// IA<U?> F8();
Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "?").WithArguments("nullable reference types", "8.0").WithLocation(17, 9)
},
comp => ((INamedTypeSymbol)((Compilation)comp).GetMember("IB")).GetMembers().OfType<IMethodSymbol>().Where(m => m.Name.StartsWith("F")).ToArray(),
method =>
{
var result = ((INamedTypeSymbol)method.ReturnType).TypeArguments.Single().NullableAnnotation;
Assert.Equal(result, ((INamedTypeSymbol)method.ReturnType).TypeArgumentNullableAnnotations.Single());
Assert.Equal(result, ((INamedTypeSymbol)method.ReturnType).TypeArgumentNullableAnnotations().Single());
return result;
},
testMetadata: true,
PublicNullableAnnotation.NotAnnotated,
PublicNullableAnnotation.NotAnnotated,
PublicNullableAnnotation.Annotated,
PublicNullableAnnotation.NotAnnotated,
PublicNullableAnnotation.Annotated,
PublicNullableAnnotation.None,
PublicNullableAnnotation.None,
PublicNullableAnnotation.Annotated,
PublicNullableAnnotation.NotAnnotated,
PublicNullableAnnotation.Annotated);
}
[Fact]
[WorkItem(34412, "https://github.com/dotnet/roslyn/issues/34412")]
public void TypeArguments_02()
{
var source =
@"class C
{
static void F<T>()
{
}
#nullable enable
static void M<T, U, V>()
where U : class
where V : struct
{
F<T>();
F<U>();
F<U?>();
F<V>();
F<V?>();
#nullable disable
F<T>();
F<U>();
F<U?>();
F<V>();
F<V?>();
}
}";
var comp = CreateCompilation(source);
comp.VerifyDiagnostics(
// (19,12): warning CS8632: The annotation for nullable reference types should only be used in code within a '#nullable' annotations context.
// F<U?>();
Diagnostic(ErrorCode.WRN_MissingNonNullTypesContextForAnnotation, "?").WithLocation(19, 12));
var syntaxTree = comp.SyntaxTrees[0];
var model = comp.GetSemanticModel(syntaxTree);
var invocations = syntaxTree.GetRoot().DescendantNodes().OfType<InvocationExpressionSyntax>();
var actualAnnotations = invocations.Select(inv =>
{
var method = (IMethodSymbol)model.GetSymbolInfo(inv).Symbol;
var result = method.TypeArguments.Single().NullableAnnotation;
Assert.Equal(result, method.TypeArgumentNullableAnnotations.Single());
return result;
}).ToArray();
var expectedAnnotations = new[]
{
PublicNullableAnnotation.NotAnnotated,
PublicNullableAnnotation.NotAnnotated,
PublicNullableAnnotation.Annotated,
PublicNullableAnnotation.NotAnnotated,
PublicNullableAnnotation.Annotated,
PublicNullableAnnotation.None,
PublicNullableAnnotation.None,
PublicNullableAnnotation.Annotated,
PublicNullableAnnotation.NotAnnotated,
PublicNullableAnnotation.Annotated
};
AssertEx.Equal(expectedAnnotations, actualAnnotations);
}
[Fact]
[WorkItem(34412, "https://github.com/dotnet/roslyn/issues/34412")]
public void Locals()
{
var source =
@"#pragma warning disable 168
class C
{
#nullable enable
static void M<T, U, V>()
where U : class
where V : struct
{
T x1;
U x2;
U? x3;
V x4;
V? x5;
#nullable disable
T x6;
U x7;
U? x8;
V x9;
V? x10;
}
}";
var comp = CreateCompilation(source);
comp.VerifyDiagnostics(
// (17,10): warning CS8632: The annotation for nullable reference types should only be used in code within a '#nullable' annotations context.
// U? x8;
Diagnostic(ErrorCode.WRN_MissingNonNullTypesContextForAnnotation, "?").WithLocation(17, 10));
var syntaxTree = comp.SyntaxTrees[0];
var model = comp.GetSemanticModel(syntaxTree);
var variables = syntaxTree.GetRoot().DescendantNodes().OfType<VariableDeclaratorSyntax>();
var actualAnnotations = variables.Select(v =>
{
var localSymbol = (ILocalSymbol)model.GetDeclaredSymbol(v);
var result = localSymbol.Type.NullableAnnotation;
Assert.Equal(result, localSymbol.NullableAnnotation);
return result;
}).ToArray();
var expectedAnnotations = new[]
{
PublicNullableAnnotation.NotAnnotated,
PublicNullableAnnotation.NotAnnotated,
PublicNullableAnnotation.Annotated,
PublicNullableAnnotation.NotAnnotated,
PublicNullableAnnotation.Annotated,
PublicNullableAnnotation.None,
PublicNullableAnnotation.None,
PublicNullableAnnotation.Annotated,
PublicNullableAnnotation.NotAnnotated,
PublicNullableAnnotation.Annotated
};
AssertEx.Equal(expectedAnnotations, actualAnnotations);
}
private static void VerifyAcrossCompilations<T>(string source,
DiagnosticDescription[] nullableEnabledErrors,
DiagnosticDescription[] nullableDisabledErrors,
Func<CSharpCompilation, T[]> memberFunc,
Func<T, PublicNullableAnnotation> nullabilityFunc,
bool testMetadata,
params PublicNullableAnnotation[] expectedNullabilities)
{
var comp1 = CreateCompilation(source, options: WithNonNullTypesTrue());
comp1.VerifyDiagnostics(nullableEnabledErrors);
verifyCompilation(comp1);
var comp2 = CreateCompilation(source, options: WithNonNullTypesFalse());
comp2.VerifyDiagnostics(nullableEnabledErrors);
verifyCompilation(comp2);
var comp3 = CreateCompilation(source, parseOptions: TestOptions.Regular7_3, skipUsesIsNullable: true);
comp3.VerifyDiagnostics(nullableDisabledErrors);
verifyCompilation(comp3);
if (!testMetadata) return;
var comp1Emit = comp1.EmitToImageReference();
var comp4 = CreateCompilation("", references: new[] { comp1Emit }, options: WithNonNullTypesTrue());
comp4.VerifyDiagnostics();
verifyCompilation(comp4);
var comp2Emit = comp2.EmitToImageReference();
var comp5 = CreateCompilation("", references: new[] { comp2Emit }, options: WithNonNullTypesFalse());
comp5.VerifyDiagnostics();
verifyCompilation(comp5);
var comp6 = CreateCompilation("", references: new[] { comp1Emit }, parseOptions: TestOptions.Regular7_3);
comp6.VerifyDiagnostics();
verifyCompilation(comp6);
void verifyCompilation(CSharpCompilation compilation)
{
var members = memberFunc(compilation);
AssertEx.Equal(expectedNullabilities, members.Select(nullabilityFunc));
}
}
[Fact]
public void LambdaBody_01()
{
var source = @"
using System;
class C
{
void M(Action a)
{
M(() =>
{
object? o = null;
if (o == null) return;
o.ToString();
});
}
}
";
var comp = CreateCompilation(source, options: WithNonNullTypesTrue());
comp.VerifyDiagnostics();
var syntaxTree = comp.SyntaxTrees[0];
var root = syntaxTree.GetRoot();
var model = comp.GetSemanticModel(syntaxTree);
var invocation = root.DescendantNodes().OfType<InvocationExpressionSyntax>().Last();
var typeInfo = model.GetTypeInfoAndVerifyIOperation(((MemberAccessExpressionSyntax)invocation.Expression).Expression);
Assert.Equal(PublicNullableFlowState.NotNull, typeInfo.Nullability.FlowState);
// https://github.com/dotnet/roslyn/issues/34993: This is incorrect. o should be Annotated, as you can assign
// null without a warning.
Assert.Equal(PublicNullableAnnotation.NotAnnotated, typeInfo.Nullability.Annotation);
}
[Fact, WorkItem(34919, "https://github.com/dotnet/roslyn/issues/34919")]
public void EnumInitializer()
{
var source = @"
enum E1 : byte
{
A1
}
enum E2
{
A2 = E1.A1
}";
var comp = CreateCompilation(source, options: WithNonNullTypesTrue());
var syntaxTree = comp.SyntaxTrees[0];
var root = syntaxTree.GetRoot();
var model = comp.GetSemanticModel(syntaxTree);
_ = model.GetTypeInfoAndVerifyIOperation(root.DescendantNodes().OfType<EqualsValueClauseSyntax>().Single().Value);
}
[Fact]
public void AnalyzerTest()
{
var source = @"
class C
{
void M()
{
object? o = null;
var o1 = o;
if (o == null) return;
var o2 = o;
}
}";
var comp = CreateCompilation(source, options: WithNonNullTypesTrue());
comp.VerifyDiagnostics();
comp.VerifyAnalyzerDiagnostics(new[] { new NullabilityPrinter() }, null, null,
Diagnostic("CA9998_NullabilityPrinter", "o = null").WithArguments("o", "Annotated").WithLocation(6, 17),
Diagnostic("CA9998_NullabilityPrinter", "o1 = o").WithArguments("o1", "Annotated").WithLocation(7, 13),
Diagnostic("CA9999_NullabilityPrinter", "o").WithArguments("o", "MaybeNull", "Annotated", "MaybeNull").WithLocation(7, 18),
Diagnostic("CA9999_NullabilityPrinter", "o").WithArguments("o", "MaybeNull", "Annotated", "MaybeNull").WithLocation(8, 13),
Diagnostic("CA9998_NullabilityPrinter", "o2 = o").WithArguments("o2", "Annotated").WithLocation(9, 13),
Diagnostic("CA9999_NullabilityPrinter", "o").WithArguments("o", "NotNull", "NotAnnotated", "NotNull").WithLocation(9, 18));
}
private class NullabilityPrinter : DiagnosticAnalyzer
{
public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics => ImmutableArray.Create(s_descriptor1, s_descriptor2);
private static readonly DiagnosticDescriptor s_descriptor1 = new DiagnosticDescriptor(id: "CA9999_NullabilityPrinter", title: "CA9999_NullabilityPrinter", messageFormat: "Nullability of '{0}' is '{1}':'{2}'. Speculative flow state is '{3}'", category: "Test", defaultSeverity: DiagnosticSeverity.Warning, isEnabledByDefault: true);
private static readonly DiagnosticDescriptor s_descriptor2 = new DiagnosticDescriptor(id: "CA9998_NullabilityPrinter", title: "CA9998_NullabilityPrinter", messageFormat: "Declared nullability of '{0}' is '{1}'", category: "Test", defaultSeverity: DiagnosticSeverity.Warning, isEnabledByDefault: true);
public override void Initialize(AnalysisContext context)
{
var newSource = (ExpressionStatementSyntax)SyntaxFactory.ParseStatement("_ = o;");
var oReference = ((AssignmentExpressionSyntax)newSource.Expression).Right;
context.RegisterSyntaxNodeAction(syntaxContext =>
{
if (syntaxContext.Node.ToString() != "o") return;
var info = syntaxContext.SemanticModel.GetTypeInfoAndVerifyIOperation(syntaxContext.Node);
Assert.True(syntaxContext.SemanticModel.TryGetSpeculativeSemanticModel(syntaxContext.Node.SpanStart, newSource, out var specModel));
var specInfo = specModel.GetTypeInfoAndVerifyIOperation(oReference);
syntaxContext.ReportDiagnostic(CodeAnalysis.Diagnostic.Create(s_descriptor1, syntaxContext.Node.GetLocation(), syntaxContext.Node, info.Nullability.FlowState, info.Nullability.Annotation, specInfo.Nullability.FlowState));
}, SyntaxKind.IdentifierName);
context.RegisterSyntaxNodeAction(context =>
{
var declarator = (VariableDeclaratorSyntax)context.Node;
var declaredSymbol = (ILocalSymbol)context.SemanticModel.GetDeclaredSymbol(declarator);
Assert.Equal(declaredSymbol.Type.NullableAnnotation, declaredSymbol.NullableAnnotation);
context.ReportDiagnostic(CodeAnalysis.Diagnostic.Create(s_descriptor2, declarator.GetLocation(), declaredSymbol.Name, declaredSymbol.NullableAnnotation));
}, SyntaxKind.VariableDeclarator);
}
}
[Fact]
public void MultipleConversions()
{
var source = @"
class A { public static explicit operator C(A a) => new D(); }
class B : A { }
class C { }
class D : C { }
class E
{
void M()
{
var d = (D)(C?)new B();
}
}";
var comp = (Compilation)CreateCompilation(source, options: WithNonNullTypesTrue());
comp.VerifyDiagnostics(
// (10,17): warning CS8600: Converting null literal or possible null value to non-nullable type.
// var d = (D)(C?)new B();
Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "(D)(C?)new B()").WithLocation(10, 17));
var syntaxTree = comp.SyntaxTrees.First();
var root = syntaxTree.GetRoot();
var model = comp.GetSemanticModel(syntaxTree);
var aType = comp.GetTypeByMetadataName("A");
var bType = comp.GetTypeByMetadataName("B");
var cType = comp.GetTypeByMetadataName("C");
var dType = comp.GetTypeByMetadataName("D");
var nullable = new NullabilityInfo(PublicNullableAnnotation.Annotated, PublicNullableFlowState.MaybeNull);
var notNullable = new NullabilityInfo(PublicNullableAnnotation.NotAnnotated, PublicNullableFlowState.NotNull);
var dCast = (CastExpressionSyntax)root.DescendantNodes().OfType<EqualsValueClauseSyntax>().Single().Value;
var dInfo = model.GetTypeInfoAndVerifyIOperation(dCast);
Assert.Equal(dType, dInfo.Type);
Assert.Equal(dType, dInfo.ConvertedType);
Assert.Equal(nullable, dInfo.Nullability);
Assert.Equal(nullable, dInfo.ConvertedNullability);
var cCast = (CastExpressionSyntax)dCast.Expression;
var cInfo = model.GetTypeInfoAndVerifyIOperation(cCast);
Assert.Equal(cType, cInfo.Type);
Assert.Equal(cType, cInfo.ConvertedType);
Assert.Equal(nullable, cInfo.Nullability);
Assert.Equal(nullable, cInfo.ConvertedNullability);
var objectCreation = cCast.Expression;
var creationInfo = model.GetTypeInfoAndVerifyIOperation(objectCreation);
Assert.Equal(bType, creationInfo.Type);
Assert.Equal(aType, creationInfo.ConvertedType);
Assert.Equal(notNullable, creationInfo.Nullability);
Assert.Equal(nullable, creationInfo.ConvertedNullability);
}
[Fact]
public void ConditionalOperator_InvalidType()
{
var source = @"
class C
{
void M()
{
var x = new Undefined() ? new object() : null;
}
}";
var comp = CreateCompilation(source, options: WithNonNullTypesTrue());
comp.VerifyDiagnostics(
// (6,21): error CS0246: The type or namespace name 'Undefined' could not be found (are you missing a using directive or an assembly reference?)
// var x = new Undefined() ? new object() : null;
Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "Undefined").WithArguments("Undefined").WithLocation(6, 21));
var syntaxTree = comp.SyntaxTrees[0];
var root = syntaxTree.GetRoot();
var model = comp.GetSemanticModel(syntaxTree);
var conditional = root.DescendantNodes().OfType<ConditionalExpressionSyntax>().Single();
var notNull = new NullabilityInfo(PublicNullableAnnotation.NotAnnotated, PublicNullableFlowState.NotNull);
var @null = new NullabilityInfo(PublicNullableAnnotation.Annotated, PublicNullableFlowState.MaybeNull);
var leftInfo = model.GetTypeInfoAndVerifyIOperation(conditional.WhenTrue);
var rightInfo = model.GetTypeInfoAndVerifyIOperation(conditional.WhenFalse);
Assert.Equal(notNull, leftInfo.Nullability);
Assert.Equal(notNull, leftInfo.ConvertedNullability);
Assert.Equal(@null, rightInfo.Nullability);
Assert.Equal(@null, rightInfo.ConvertedNullability);
}
[Fact]
public void InferredDeclarationType()
{
var source =
@"
using System.Collections.Generic;
#nullable enable
class C : System.IDisposable
{
void M(C? x, C x2)
{
var /*T:C?*/ y = x;
var /*T:C?*/ y2 = x2;
using var /*T:C?*/ y3 = x;
using var /*T:C?*/ y4 = x2;
using (var /*T:C?*/ y5 = x) { }
using (var /*T:C?*/ y6 = x2) { }
ref var/*T:C?*/ y7 = ref x;
ref var/*T:C?*/ y8 = ref x2;
if (x == null)
return;
var /*T:C?*/ y9 = x;
using var /*T:C?*/ y10 = x;
ref var /*T:C?*/ y11 = ref x;
x = null;
var /*T:C?*/ y12 = x;
using var /*T:C?*/ y13 = x;
ref var /*T:C?*/ y14 = ref x;
x2 = null; // 1
var /*T:C?*/ y15 = x2;
using var /*T:C?*/ y16 = x2;
ref var /*T:C?*/ y17 = ref x2;
}
void M2(List<C?> l1, List<C> l2)
{
foreach (var /*T:C?*/ x in l1) { }
foreach (var /*T:C?*/ x in l2) { }
}
public void Dispose() { }
}";
var comp = CreateCompilation(source);
comp.VerifyDiagnostics(
// (31,14): warning CS8600: Converting null literal or possible null value to non-nullable type.
// x2 = null; // 1
Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "null").WithLocation(31, 14)
);
comp.VerifyTypes();
}
[Fact]
public void SpeculativeSemanticModel_BasicTest()
{
var source = @"
class C
{
void M(string? s1)
{
if (s1 != null)
{
s1.ToString();
}
s1?.ToString();
s1 = """";
var s2 = s1 == null ? """" : s1;
}
}";
var comp = CreateCompilation(source, options: WithNonNullTypesTrue());
comp.VerifyDiagnostics();
var syntaxTree = comp.SyntaxTrees[0];
var root = syntaxTree.GetRoot();
var model = comp.GetSemanticModel(syntaxTree);
var ifStatement = root.DescendantNodes().OfType<IfStatementSyntax>().Single();
var conditionalAccessExpression = root.DescendantNodes().OfType<ConditionalAccessExpressionSyntax>().Single();
var ternary = root.DescendantNodes().OfType<ConditionalExpressionSyntax>().Single();
var newSource = (BlockSyntax)SyntaxFactory.ParseStatement(@"{ string? s3 = null; _ = s1 == """" ? s1 : s1; }");
var newExprStatement = (ExpressionStatementSyntax)newSource.Statements[1];
var newTernary = (ConditionalExpressionSyntax)((AssignmentExpressionSyntax)newExprStatement.Expression).Right;
var inCondition = ((BinaryExpressionSyntax)newTernary.Condition).Left;
var whenTrue = newTernary.WhenTrue;
var whenFalse = newTernary.WhenFalse;
var newReference = (IdentifierNameSyntax)SyntaxFactory.ParseExpression(@"s1");
var newCoalesce = (AssignmentExpressionSyntax)SyntaxFactory.ParseExpression(@"s3 ??= s1", options: TestOptions.Regular8);
// Before the if statement
verifySpeculativeModel(ifStatement.SpanStart, PublicNullableFlowState.MaybeNull);
// In if statement consequence
verifySpeculativeModel(ifStatement.Statement.SpanStart, PublicNullableFlowState.NotNull);
// Before the conditional access
verifySpeculativeModel(conditionalAccessExpression.SpanStart, PublicNullableFlowState.MaybeNull);
// After the conditional access
verifySpeculativeModel(conditionalAccessExpression.WhenNotNull.SpanStart, PublicNullableFlowState.NotNull);
// In the conditional whenTrue
verifySpeculativeModel(ternary.WhenTrue.SpanStart, PublicNullableFlowState.MaybeNull);
// In the conditional whenFalse
verifySpeculativeModel(ternary.WhenFalse.SpanStart, PublicNullableFlowState.NotNull);
void verifySpeculativeModel(int spanStart, PublicNullableFlowState conditionFlowState)
{
Assert.True(model.TryGetSpeculativeSemanticModel(spanStart, newSource, out var speculativeModel));
var speculativeTypeInfo = speculativeModel.GetTypeInfoAndVerifyIOperation(inCondition);
Assert.Equal(conditionFlowState, speculativeTypeInfo.Nullability.FlowState);
speculativeTypeInfo = speculativeModel.GetTypeInfoAndVerifyIOperation(whenTrue);
Assert.Equal(PublicNullableFlowState.NotNull, speculativeTypeInfo.Nullability.FlowState);
var referenceTypeInfo = speculativeModel.GetSpeculativeTypeInfo(whenTrue.SpanStart, newReference, SpeculativeBindingOption.BindAsExpression);
Assert.Equal(PublicNullableFlowState.NotNull, referenceTypeInfo.Nullability.FlowState);
var coalesceTypeInfo = speculativeModel.GetSpeculativeTypeInfo(whenTrue.SpanStart, newCoalesce, SpeculativeBindingOption.BindAsExpression);
Assert.Equal(PublicNullableFlowState.NotNull, coalesceTypeInfo.Nullability.FlowState);
speculativeTypeInfo = speculativeModel.GetTypeInfoAndVerifyIOperation(whenFalse);
Assert.Equal(conditionFlowState, speculativeTypeInfo.Nullability.FlowState);
referenceTypeInfo = speculativeModel.GetSpeculativeTypeInfo(whenFalse.SpanStart, newReference, SpeculativeBindingOption.BindAsExpression);
Assert.Equal(conditionFlowState, referenceTypeInfo.Nullability.FlowState);
coalesceTypeInfo = speculativeModel.GetSpeculativeTypeInfo(whenFalse.SpanStart, newCoalesce, SpeculativeBindingOption.BindAsExpression);
Assert.Equal(conditionFlowState, coalesceTypeInfo.Nullability.FlowState);
}
}
[Fact]
public void SpeculativeModel_Properties()
{
var source = @"
class C
{
object? Foo
{
get
{
object? x = null;
return x;
}
}
}";
var comp = CreateCompilation(source, options: WithNonNullTypesTrue());
comp.VerifyDiagnostics();
var syntaxTree = comp.SyntaxTrees[0];
var root = syntaxTree.GetRoot();
var model = comp.GetSemanticModel(syntaxTree);
var returnStatement = root.DescendantNodes().OfType<ReturnStatementSyntax>().Single();
var newSource = (BlockSyntax)SyntaxFactory.ParseStatement("{ var y = x ?? new object(); y.ToString(); }");
var yReference = ((MemberAccessExpressionSyntax)newSource.DescendantNodes().OfType<InvocationExpressionSyntax>().Single().Expression).Expression;
Assert.True(model.TryGetSpeculativeSemanticModel(returnStatement.SpanStart, newSource, out var specModel));
var speculativeTypeInfo = specModel.GetTypeInfoAndVerifyIOperation(yReference);
Assert.Equal(PublicNullableFlowState.NotNull, speculativeTypeInfo.Nullability.FlowState);
}
[Fact]
public void TupleAssignment()
{
var source =
@"
#pragma warning disable CS0219
#nullable enable
class C
{
void M(C? x, C x2)
{
(C? a, C b) t = (x, x2) /*T:(C? x, C! x2)*/ /*CT:(C? a, C! b)*/;
(object a, int b) t2 = (x, (short)0)/*T:(C? x, short)*/ /*CT:(object! a, int b)*/; // 1
(object a, int b) t3 = (default, default) /*T:<null>!*/ /*CT:(object! a, int b)*/; // 2
(object a, int b) t4 = (default(object), default(int)) /*T:(object?, int)*/ /*CT:(object! a, int b)*/; // 3
}
}";
var comp = CreateCompilation(source);
comp.VerifyTypes();
comp.VerifyDiagnostics(
// (9,32): warning CS8619: Nullability of reference types in value of type '(object? x, int)' doesn't match target type '(object a, int b)'.
// (object a, int b) t2 = (x, (short)0)/*T:(C? x, short)*/ /*CT:(object! a, int b)*/; // 1
Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "(x, (short)0)").WithArguments("(object? x, int)", "(object a, int b)").WithLocation(9, 32),
// (10,32): warning CS8619: Nullability of reference types in value of type '(object?, int)' doesn't match target type '(object a, int b)'.
// (object a, int b) t3 = (default, default) /*T:<null>!*/ /*CT:(object! a, int b)*/; //2
Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "(default, default)").WithArguments("(object?, int)", "(object a, int b)").WithLocation(10, 32),
// (11,32): warning CS8619: Nullability of reference types in value of type '(object?, int)' doesn't match target type '(object a, int b)'.
// (object a, int b) t4 = (default(object), default(int)) /*T:(object?, int)*/ /*CT:(object! a, int b)*/; // 3
Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "(default(object), default(int))").WithArguments("(object?, int)", "(object a, int b)").WithLocation(11, 32)
);
}
[Fact]
public void SpeculativeGetTypeInfo_Basic()
{
var source = @"
class C
{
static object? staticField = null;
object field = staticField is null ? new object() : staticField;
string M(string? s1)
{
if (s1 != null)
{
s1.ToString();
}
s1?.ToString();
s1 = """";
var s2 = s1 == null ? """" : s1;
return null!;
}
}";
var comp = CreateCompilation(source, options: WithNonNullTypesTrue());
comp.VerifyDiagnostics();
var syntaxTree = comp.SyntaxTrees[0];
var root = syntaxTree.GetRoot();
var model = comp.GetSemanticModel(syntaxTree);
var ifStatement = root.DescendantNodes().OfType<IfStatementSyntax>().Single();
var conditionalAccessExpression = root.DescendantNodes().OfType<ConditionalAccessExpressionSyntax>().Single();
var ternary = root.DescendantNodes().OfType<ConditionalExpressionSyntax>().ElementAt(1);
var newReference = (IdentifierNameSyntax)SyntaxFactory.ParseExpression(@"s1");
var newCoalesce = (AssignmentExpressionSyntax)SyntaxFactory.ParseExpression(@"s1 ??= """"");
verifySpeculativeTypeInfo(ifStatement.SpanStart, PublicNullableFlowState.MaybeNull);
verifySpeculativeTypeInfo(ifStatement.Statement.SpanStart, PublicNullableFlowState.NotNull);
verifySpeculativeTypeInfo(conditionalAccessExpression.SpanStart, PublicNullableFlowState.MaybeNull);
verifySpeculativeTypeInfo(conditionalAccessExpression.WhenNotNull.SpanStart, PublicNullableFlowState.NotNull);
verifySpeculativeTypeInfo(ternary.WhenTrue.SpanStart, PublicNullableFlowState.MaybeNull);
verifySpeculativeTypeInfo(ternary.WhenFalse.SpanStart, PublicNullableFlowState.NotNull);
void verifySpeculativeTypeInfo(int position, PublicNullableFlowState expectedFlowState)
{
var specTypeInfo = model.GetSpeculativeTypeInfo(position, newReference, SpeculativeBindingOption.BindAsExpression);
Assert.Equal(expectedFlowState, specTypeInfo.Nullability.FlowState);
specTypeInfo = model.GetSpeculativeTypeInfo(position, newCoalesce, SpeculativeBindingOption.BindAsExpression);
Assert.Equal(PublicNullableFlowState.NotNull, specTypeInfo.Nullability.FlowState);
}
}
[Fact, WorkItem(48574, "https://github.com/dotnet/roslyn/issues/48574")]
public void SpeculativeGetTypeInfo_Constructor()
{
var source = @"
class C
{
public string Prop { get; set; }
public C()
{
if (Prop != null)
{
Prop.ToString();
}
Prop?.ToString();
Prop = """";
var s2 = Prop == null ? """" : Prop;
}
}";
var comp = CreateCompilation(source, options: WithNonNullTypesTrue());
comp.VerifyDiagnostics(
// (5,12): warning CS8618: Non-nullable property 'Prop' must contain a non-null value when exiting constructor. Consider declaring the property as nullable.
// public C()
Diagnostic(ErrorCode.WRN_UninitializedNonNullableField, "C").WithArguments("property", "Prop").WithLocation(5, 12));
var syntaxTree = comp.SyntaxTrees[0];
var root = syntaxTree.GetRoot();
var model = comp.GetSemanticModel(syntaxTree);
var ifStatement = root.DescendantNodes().OfType<IfStatementSyntax>().Single();
var conditionalAccessExpression = root.DescendantNodes().OfType<ConditionalAccessExpressionSyntax>().Single();
var ternary = root.DescendantNodes().OfType<ConditionalExpressionSyntax>().Single();
var newReference = (IdentifierNameSyntax)SyntaxFactory.ParseExpression(@"Prop");
var newCoalesce = (AssignmentExpressionSyntax)SyntaxFactory.ParseExpression(@"Prop ??= """"");
verifySpeculativeTypeInfo(ifStatement.SpanStart, PublicNullableFlowState.MaybeNull);
verifySpeculativeTypeInfo(ifStatement.Statement.SpanStart, PublicNullableFlowState.NotNull);
verifySpeculativeTypeInfo(conditionalAccessExpression.SpanStart, PublicNullableFlowState.MaybeNull);
verifySpeculativeTypeInfo(conditionalAccessExpression.WhenNotNull.SpanStart, PublicNullableFlowState.NotNull);
verifySpeculativeTypeInfo(ternary.WhenTrue.SpanStart, PublicNullableFlowState.MaybeNull);
verifySpeculativeTypeInfo(ternary.WhenFalse.SpanStart, PublicNullableFlowState.NotNull);
void verifySpeculativeTypeInfo(int position, PublicNullableFlowState expectedFlowState)
{
var specTypeInfo = model.GetSpeculativeTypeInfo(position, newReference, SpeculativeBindingOption.BindAsExpression);
Assert.Equal(expectedFlowState, specTypeInfo.Nullability.FlowState);
specTypeInfo = model.GetSpeculativeTypeInfo(position, newCoalesce, SpeculativeBindingOption.BindAsExpression);
Assert.Equal(PublicNullableFlowState.NotNull, specTypeInfo.Nullability.FlowState);
}
}
[Fact, WorkItem(45398, "https://github.com/dotnet/roslyn/issues/45398")]
public void VarInLambda_GetTypeInfo()
{
var source = @"
#nullable enable
using System;
class C
{
private static string s_data;
static void Main()
{
Action a = () => {
var v = s_data;
v = GetNullableString();
};
}
static string? GetNullableString() => null;
}";
var comp = CreateCompilation(source, options: WithNonNullTypesTrue());
comp.VerifyDiagnostics(
// (6,27): warning CS8618: Non-nullable field 's_data' is uninitialized. Consider declaring the field as nullable.
// private static string s_data;
Diagnostic(ErrorCode.WRN_UninitializedNonNullableField, "s_data").WithArguments("field", "s_data").WithLocation(6, 27),
// (6,27): warning CS0649: Field 'C.s_data' is never assigned to, and will always have its default value null
// private static string s_data;
Diagnostic(ErrorCode.WRN_UnassignedInternalField, "s_data").WithArguments("C.s_data", "null").WithLocation(6, 27));
var syntaxTree = comp.SyntaxTrees[0];
var root = syntaxTree.GetRoot();
var model = comp.GetSemanticModel(syntaxTree);
var lambda = root.DescendantNodes().OfType<LambdaExpressionSyntax>().Single();
var varDecl = lambda.DescendantNodes().OfType<VariableDeclarationSyntax>().Single();
var type = model.GetTypeInfo(varDecl.Type);
Assert.Equal(PublicNullableFlowState.MaybeNull, type.Nullability.FlowState);
Assert.Equal(PublicNullableAnnotation.Annotated, type.Nullability.Annotation);
}
[Fact, WorkItem(45398, "https://github.com/dotnet/roslyn/issues/45398")]
public void VarInLambda_ParameterMismatch_GetTypeInfo()
{
var source = @"
#nullable enable
using System;
class C
{
private static string s_data;
static void Main()
{
Action<string> a = () => {
var v = s_data;
v = GetNullableString();
};
}
static string? GetNullableString() => null;
}";
var comp = CreateCompilation(source, options: WithNonNullTypesTrue());
comp.VerifyDiagnostics(
// (6,27): warning CS8618: Non-nullable field 's_data' is uninitialized. Consider declaring the field as nullable.
// private static string s_data;
Diagnostic(ErrorCode.WRN_UninitializedNonNullableField, "s_data").WithArguments("field", "s_data").WithLocation(6, 27),
// (6,27): warning CS0649: Field 'C.s_data' is never assigned to, and will always have its default value null
// private static string s_data;
Diagnostic(ErrorCode.WRN_UnassignedInternalField, "s_data").WithArguments("C.s_data", "null").WithLocation(6, 27),
// (9,28): error CS1593: Delegate 'Action<string>' does not take 0 arguments
// Action<string> a = () => {
Diagnostic(ErrorCode.ERR_BadDelArgCount, @"() => {
var v = s_data;
v = GetNullableString();
}").WithArguments("System.Action<string>", "0").WithLocation(9, 28));
var syntaxTree = comp.SyntaxTrees[0];
var root = syntaxTree.GetRoot();
var model = comp.GetSemanticModel(syntaxTree);
var lambda = root.DescendantNodes().OfType<LambdaExpressionSyntax>().Single();
var varDecl = lambda.DescendantNodes().OfType<VariableDeclarationSyntax>().Single();
var type = model.GetTypeInfo(varDecl.Type);
Assert.Equal(PublicNullableFlowState.None, type.Nullability.FlowState);
Assert.Equal(PublicNullableAnnotation.None, type.Nullability.Annotation);
}
[Fact, WorkItem(45398, "https://github.com/dotnet/roslyn/issues/45398")]
public void VarInLambda_ErrorDelegateType_GetTypeInfo()
{
var source = @"
#nullable enable
class C
{
private static string s_data;
static void Main()
{
NonexistentDelegateType a = () => {
var v = s_data;
v = GetNullableString();
};
}
static string? GetNullableString() => null;
}";
var comp = CreateCompilation(source, options: WithNonNullTypesTrue());
comp.VerifyDiagnostics(
// (6,27): warning CS8618: Non-nullable field 's_data' is uninitialized. Consider declaring the field as nullable.
// private static string s_data;
Diagnostic(ErrorCode.WRN_UninitializedNonNullableField, "s_data").WithArguments("field", "s_data").WithLocation(6, 27),
// (6,27): warning CS0649: Field 'C.s_data' is never assigned to, and will always have its default value null
// private static string s_data;
Diagnostic(ErrorCode.WRN_UnassignedInternalField, "s_data").WithArguments("C.s_data", "null").WithLocation(6, 27),
// (9,9): error CS0246: The type or namespace name 'NonexistentDelegateType' could not be found (are you missing a using directive or an assembly reference?)
// NonexistentDelegateType a = () => {
Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "NonexistentDelegateType").WithArguments("NonexistentDelegateType").WithLocation(9, 9));
var syntaxTree = comp.SyntaxTrees[0];
var root = syntaxTree.GetRoot();
var model = comp.GetSemanticModel(syntaxTree);
var lambda = root.DescendantNodes().OfType<LambdaExpressionSyntax>().Single();
var varDecl = lambda.DescendantNodes().OfType<VariableDeclarationSyntax>().Single();
var type = model.GetTypeInfo(varDecl.Type);
Assert.Equal(PublicNullableFlowState.None, type.Nullability.FlowState);
Assert.Equal(PublicNullableAnnotation.None, type.Nullability.Annotation);
}
[Fact]
public void FeatureFlagTurnsOffNullableAnalysis()
{
var source =
@"
#nullable enable
class C
{
object field = null;
void M()
{
object o = null;
}
}
";
var featureFlagOff = TestOptions.Regular8.WithFeature("run-nullable-analysis", "never");
var comp = CreateCompilation(source, options: WithNonNullTypesTrue(), parseOptions: featureFlagOff);
comp.VerifyDiagnostics(
// (5,12): warning CS0414: The field 'C.field' is assigned but its value is never used
// object field = null;
Diagnostic(ErrorCode.WRN_UnreferencedFieldAssg, "field").WithArguments("C.field").WithLocation(5, 12),
// (9,16): warning CS0219: The variable 'o' is assigned but its value is never used
// object o = null;
Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "o").WithArguments("o").WithLocation(9, 16));
Assert.False(comp.IsNullableAnalysisEnabled);
comp = CreateCompilation(source, options: WithNonNullTypesTrue());
comp.VerifyDiagnostics(
// (5,12): warning CS0414: The field 'C.field' is assigned but its value is never used
// object field = null;
Diagnostic(ErrorCode.WRN_UnreferencedFieldAssg, "field").WithArguments("C.field").WithLocation(5, 12),
// (5,20): warning CS8625: Cannot convert null literal to non-nullable reference type.
// object field = null;
Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithLocation(5, 20),
// (9,16): warning CS0219: The variable 'o' is assigned but its value is never used
// object o = null;
Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "o").WithArguments("o").WithLocation(9, 16),
// (9,20): warning CS8600: Converting null literal or possible null value to non-nullable type.
// object o = null;
Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "null").WithLocation(9, 20));
Assert.True(comp.IsNullableAnalysisEnabled);
}
private class CSharp73ProvidesNullableSemanticInfo_Analyzer : DiagnosticAnalyzer
{
public int HitCount;
private static readonly DiagnosticDescriptor Descriptor =
new DiagnosticDescriptor("XY0000", "Test", "Test", "Test", DiagnosticSeverity.Warning, true, "Test", "Test");
public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics
=> ImmutableArray.Create(Descriptor);
public override void Initialize(AnalysisContext context)
{
context.RegisterSyntaxNodeAction(AnalyzeMemberAccess, SyntaxKind.SimpleMemberAccessExpression);
}
private void AnalyzeMemberAccess(SyntaxNodeAnalysisContext context)
{
var node = (MemberAccessExpressionSyntax)context.Node;
var model = context.SemanticModel;
var info = model.GetTypeInfo(node.Expression);
Assert.Equal(PublicNullableAnnotation.Annotated, info.Nullability.Annotation);
Assert.Equal(PublicNullableFlowState.MaybeNull, info.Nullability.FlowState);
Interlocked.Increment(ref HitCount);
}
}
[Fact]
public void CSharp73ProvidesNullableSemanticInfo()
{
var source = @"
class C
{
void M(string s)
{
if (s == null)
{
s.ToString();
}
}
}
";
var comp = CreateCompilation(source, options: WithNonNullTypesTrue(), parseOptions: TestOptions.Regular7_3, skipUsesIsNullable: true);
comp.VerifyDiagnostics(
// error CS8630: Invalid 'NullableContextOptions' value: 'Enable' for C# 7.3. Please use language version '8.0' or greater.
Diagnostic(ErrorCode.ERR_NullableOptionNotAvailable).WithArguments("NullableContextOptions", "Enable", "7.3", "8.0").WithLocation(1, 1)
);
var analyzer = new CSharp73ProvidesNullableSemanticInfo_Analyzer();
comp.GetAnalyzerDiagnostics(new[] { analyzer }).Verify();
Assert.Equal(1, analyzer.HitCount);
}
[Fact]
public void SymbolInfo_Invocation_InferredArguments()
{
var source = @"
class C
{
T Identity<T>(T t) => t;
void M(string? s)
{
_ = Identity(s);
if (s is null) return;
_ = Identity(s);
}
}";
var comp = CreateCompilation(source, options: WithNonNullTypesTrue());
comp.VerifyDiagnostics();
var syntaxTree = comp.SyntaxTrees[0];
var root = syntaxTree.GetRoot();
var model = comp.GetSemanticModel(syntaxTree);
var invocations = root.DescendantNodes().OfType<InvocationExpressionSyntax>().ToArray();
var symbolInfo = model.GetSymbolInfo(invocations[0]);
verifySymbolInfo((IMethodSymbol)symbolInfo.Symbol, PublicNullableAnnotation.Annotated);
symbolInfo = model.GetSymbolInfo(invocations[1]);
verifySymbolInfo((IMethodSymbol)symbolInfo.Symbol, PublicNullableAnnotation.NotAnnotated);
static void verifySymbolInfo(IMethodSymbol methodSymbol, PublicNullableAnnotation expectedAnnotation)
{
Assert.Equal(expectedAnnotation, methodSymbol.TypeArgumentNullableAnnotations.Single());
Assert.Equal(expectedAnnotation, methodSymbol.TypeArguments.Single().NullableAnnotation);
Assert.Equal(expectedAnnotation, methodSymbol.Parameters.Single().NullableAnnotation);
Assert.Equal(expectedAnnotation, methodSymbol.Parameters.Single().Type.NullableAnnotation);
Assert.Equal(expectedAnnotation, methodSymbol.ReturnNullableAnnotation);
Assert.Equal(expectedAnnotation, methodSymbol.ReturnType.NullableAnnotation);
}
}
[Fact]
public void SymbolInfo_Invocation_LocalFunction()
{
var source = @"
using System.Collections.Generic;
class C
{
void M(string? s)
{
_ = CreateList(s);
if (s is null) return;
_ = CreateList(s);
List<T> CreateList<T>(T t) => null!;
}
}";
var comp = CreateCompilation(source, options: WithNonNullTypesTrue());
comp.VerifyDiagnostics();
var syntaxTree = comp.SyntaxTrees[0];
var root = syntaxTree.GetRoot();
var model = comp.GetSemanticModel(syntaxTree);
var invocations = root.DescendantNodes().OfType<InvocationExpressionSyntax>().ToArray();
var symbolInfo = model.GetSymbolInfo(invocations[0]);
verifySymbolInfo((IMethodSymbol)symbolInfo.Symbol, PublicNullableAnnotation.Annotated);
symbolInfo = model.GetSymbolInfo(invocations[1]);
verifySymbolInfo((IMethodSymbol)symbolInfo.Symbol, PublicNullableAnnotation.NotAnnotated);
static void verifySymbolInfo(IMethodSymbol methodSymbol, PublicNullableAnnotation expectedAnnotation)
{
Assert.Equal(expectedAnnotation, methodSymbol.TypeArgumentNullableAnnotations.Single());
Assert.Equal(expectedAnnotation, methodSymbol.TypeArguments.Single().NullableAnnotation);
Assert.Equal(expectedAnnotation, methodSymbol.Parameters.Single().NullableAnnotation);
Assert.Equal(expectedAnnotation, methodSymbol.Parameters.Single().Type.NullableAnnotation);
Assert.Equal(expectedAnnotation, ((INamedTypeSymbol)methodSymbol.ReturnType).TypeArgumentNullableAnnotations.Single());
Assert.Equal(expectedAnnotation, ((INamedTypeSymbol)methodSymbol.ReturnType).TypeArgumentNullableAnnotations().Single());
}
}
[Fact]
public void GetDeclaredSymbol_Locals_Inference()
{
var source = @"
class C
{
void M(string? s1, string s2)
{
var o1 = s1;
var o2 = s2;
if (s1 == null) return;
var o3 = s1;
s2 = null;
var o4 = s2;
}
}";
var comp = CreateCompilation(source, options: WithNonNullTypesTrue());
comp.VerifyDiagnostics(
// (10,14): warning CS8600: Converting null literal or possible null value to non-nullable type.
// s2 = null;
Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "null").WithLocation(10, 14));
var syntaxTree = comp.SyntaxTrees[0];
var root = syntaxTree.GetRoot();
var model = comp.GetSemanticModel(syntaxTree);
var declarations = root.DescendantNodes().OfType<VariableDeclaratorSyntax>().ToList();
assertAnnotation(declarations[0]);
assertAnnotation(declarations[1]);
assertAnnotation(declarations[2]);
assertAnnotation(declarations[3]);
void assertAnnotation(VariableDeclaratorSyntax variable)
{
var symbol = (ILocalSymbol)model.GetDeclaredSymbol(variable);
Assert.Equal(PublicNullableAnnotation.Annotated, symbol.NullableAnnotation);
Assert.Equal(PublicNullableAnnotation.Annotated, symbol.Type.NullableAnnotation);
var typeInfo = model.GetTypeInfoAndVerifyIOperation(((VariableDeclarationSyntax)variable.Parent).Type);
Assert.Equal(PublicNullableFlowState.MaybeNull, typeInfo.Nullability.FlowState);
Assert.Equal(PublicNullableFlowState.MaybeNull, typeInfo.ConvertedNullability.FlowState);
Assert.Equal(CodeAnalysis.NullableAnnotation.Annotated, typeInfo.Nullability.Annotation);
Assert.Equal(CodeAnalysis.NullableAnnotation.Annotated, typeInfo.ConvertedNullability.Annotation);
}
}
[Fact]
public void GetDeclaredSymbol_Locals_NoInference()
{
// All declarations are the opposite of inference
var source = @"
#pragma warning disable CS8600
class C
{
void M(string? s1, string s2)
{
string o1 = s1;
string? o2 = s2;
if (s1 == null) return;
string? o3 = s1;
s2 = null;
string o4 = s2;
}
}";
var comp = CreateCompilation(source, options: WithNonNullTypesTrue());
comp.VerifyDiagnostics();
var syntaxTree = comp.SyntaxTrees[0];
var root = syntaxTree.GetRoot();
var model = comp.GetSemanticModel(syntaxTree);
var declarations = root.DescendantNodes().OfType<VariableDeclaratorSyntax>().ToList();
assertAnnotation(declarations[0], PublicNullableAnnotation.NotAnnotated);
assertAnnotation(declarations[1], PublicNullableAnnotation.Annotated);
assertAnnotation(declarations[2], PublicNullableAnnotation.Annotated);
assertAnnotation(declarations[3], PublicNullableAnnotation.NotAnnotated);
void assertAnnotation(VariableDeclaratorSyntax variable, PublicNullableAnnotation expectedAnnotation)
{
var symbol = (ILocalSymbol)model.GetDeclaredSymbol(variable);
Assert.Equal(expectedAnnotation, symbol.NullableAnnotation);
Assert.Equal(expectedAnnotation, symbol.Type.NullableAnnotation);
}
}
[Fact]
public void GetDeclaredSymbol_SingleVariableDeclaration_Inference()
{
var source1 = @"
#pragma warning disable CS8600
class C
{
void M(string? s1, string s2)
{
var (o1, o2) = (s1, s2);
var (o3, o4) = (s2, s1);
if (s1 == null) return;
var (o5, o6) = (s1, s2);
s2 = null;
var (o7, o8) = (s1, s2);
}
}";
verifyCompilation(source1);
var source2 = @"
#pragma warning disable CS8600
class C
{
void M(string? s1, string s2)
{
(var o1, var o2) = (s1, s2);
(var o3, var o4) = (s2, s1);
if (s1 == null) return;
(var o5, var o6) = (s1, s2);
s2 = null;
(var o7, var o8) = (s1, s2);
}
}";
verifyCompilation(source2);
void verifyCompilation(string source)
{
var comp = CreateCompilation(source, options: WithNonNullTypesTrue());
comp.VerifyDiagnostics();
var syntaxTree = comp.SyntaxTrees[0];
var root = syntaxTree.GetRoot();
var model = comp.GetSemanticModel(syntaxTree);
var declarations = root.DescendantNodes().OfType<AssignmentExpressionSyntax>().ToList();
assertAnnotation(declarations[0], PublicNullableAnnotation.Annotated, PublicNullableAnnotation.Annotated);
assertAnnotation(declarations[1], PublicNullableAnnotation.Annotated, PublicNullableAnnotation.Annotated);
assertAnnotation(declarations[2], PublicNullableAnnotation.Annotated, PublicNullableAnnotation.Annotated);
assertAnnotation(declarations[4], PublicNullableAnnotation.Annotated, PublicNullableAnnotation.Annotated);
void assertAnnotation(AssignmentExpressionSyntax variable, PublicNullableAnnotation expectedAnnotation1, PublicNullableAnnotation expectedAnnotation2)
{
var symbols = variable.DescendantNodes().OfType<SingleVariableDesignationSyntax>().Select(s => model.GetDeclaredSymbol(s)).Cast<ILocalSymbol>().ToList();
Assert.Equal(expectedAnnotation1, symbols[0].NullableAnnotation);
Assert.Equal(expectedAnnotation1, symbols[0].Type.NullableAnnotation);
Assert.Equal(expectedAnnotation2, symbols[1].NullableAnnotation);
Assert.Equal(expectedAnnotation2, symbols[1].Type.NullableAnnotation);
}
}
}
[Fact]
public void GetDeclaredSymbol_SingleVariableDeclaration_MixedInference()
{
var source = @"
#pragma warning disable CS8600
class C
{
void M(string? s1, string s2)
{
(string o1, var o2) = (s1, s2);
(string? o3, var o4) = (s2, s1);
if (s1 == null) return;
(var o5, string? o6) = (s1, s2);
s2 = null;
(var o7, string o8) = (s1, s2);
}
}";
var comp = CreateCompilation(source, options: WithNonNullTypesTrue());
comp.VerifyDiagnostics();
var syntaxTree = comp.SyntaxTrees[0];
var root = syntaxTree.GetRoot();
var model = comp.GetSemanticModel(syntaxTree);
var declarations = root.DescendantNodes().OfType<AssignmentExpressionSyntax>().ToList();
assertAnnotation(declarations[0], PublicNullableAnnotation.NotAnnotated, PublicNullableAnnotation.Annotated);
assertAnnotation(declarations[1], PublicNullableAnnotation.Annotated, PublicNullableAnnotation.Annotated);
assertAnnotation(declarations[2], PublicNullableAnnotation.Annotated, PublicNullableAnnotation.Annotated);
assertAnnotation(declarations[4], PublicNullableAnnotation.Annotated, PublicNullableAnnotation.NotAnnotated);
void assertAnnotation(AssignmentExpressionSyntax variable, PublicNullableAnnotation expectedAnnotation1, PublicNullableAnnotation expectedAnnotation2)
{
var symbols = variable.DescendantNodes().OfType<SingleVariableDesignationSyntax>().Select(s => model.GetDeclaredSymbol(s)).Cast<ILocalSymbol>().ToList();
Assert.Equal(expectedAnnotation1, symbols[0].NullableAnnotation);
Assert.Equal(expectedAnnotation1, symbols[0].Type.NullableAnnotation);
Assert.Equal(expectedAnnotation2, symbols[1].NullableAnnotation);
Assert.Equal(expectedAnnotation2, symbols[1].Type.NullableAnnotation);
}
}
[Fact]
public void GetDeclaredSymbol_SpeculativeModel()
{
// All declarations are the opposite of inference
var source = @"
#pragma warning disable CS8600
class C
{
void M(string? s1, string s2)
{
string o1 = s1;
string? o2 = s2;
if (s1 == null) return;
string? o3 = s1;
s2 = null;
string o4 = s2;
}
}";
var comp = CreateCompilation(source, options: WithNonNullTypesTrue());
comp.VerifyDiagnostics();
var syntaxTree = comp.SyntaxTrees[0];
var root = syntaxTree.GetRoot();
var model = comp.GetSemanticModel(syntaxTree);
var s2Assignment = root.DescendantNodes().OfType<AssignmentExpressionSyntax>().Single();
var lastDeclaration = root.DescendantNodes().OfType<VariableDeclaratorSyntax>().ElementAt(3);
var newDeclaration = SyntaxFactory.ParseStatement("var o5 = s2;");
var newDeclarator = newDeclaration.DescendantNodes().OfType<VariableDeclaratorSyntax>().Single();
Assert.True(model.TryGetSpeculativeSemanticModel(s2Assignment.SpanStart, newDeclaration, out var specModel));
Assert.Equal(PublicNullableAnnotation.Annotated, ((ILocalSymbol)specModel.GetDeclaredSymbol(newDeclarator)).NullableAnnotation);
Assert.Equal(PublicNullableAnnotation.Annotated, ((ILocalSymbol)specModel.GetDeclaredSymbol(newDeclarator)).Type.NullableAnnotation);
Assert.True(model.TryGetSpeculativeSemanticModel(lastDeclaration.SpanStart, newDeclaration, out specModel));
Assert.Equal(PublicNullableAnnotation.Annotated, ((ILocalSymbol)specModel.GetDeclaredSymbol(newDeclarator)).NullableAnnotation);
Assert.Equal(PublicNullableAnnotation.Annotated, ((ILocalSymbol)specModel.GetDeclaredSymbol(newDeclarator)).Type.NullableAnnotation);
}
[Fact]
public void GetDeclaredSymbol_Using()
{
var source = @"
using System;
using System.Threading.Tasks;
class C : IDisposable, IAsyncDisposable
{
public void Dispose() => throw null!;
public ValueTask DisposeAsync() => throw null!;
async void M(C? c1)
{
using var c2 = c1;
using var c3 = c1 ?? new C();
using (var c4 = c1) {}
using (var c5 = c1 ?? new C()) {}
await using (var c6 = c1) {}
await using (var c6 = c1 ?? new C()) {}
}
}
";
var comp = CreateCompilationWithTasksExtensions(new[] { source, s_IAsyncEnumerable }, options: WithNonNullTypesTrue());
comp.VerifyDiagnostics();
var syntaxTree = comp.SyntaxTrees[0];
var root = syntaxTree.GetRoot();
var model = comp.GetSemanticModel(syntaxTree);
var declarations = root.DescendantNodes().OfType<VariableDeclaratorSyntax>().ToList();
assertAnnotation(declarations[0], PublicNullableAnnotation.Annotated);
assertAnnotation(declarations[1], PublicNullableAnnotation.Annotated);
assertAnnotation(declarations[2], PublicNullableAnnotation.Annotated);
assertAnnotation(declarations[3], PublicNullableAnnotation.Annotated);
assertAnnotation(declarations[4], PublicNullableAnnotation.Annotated);
assertAnnotation(declarations[5], PublicNullableAnnotation.Annotated);
void assertAnnotation(VariableDeclaratorSyntax variable, PublicNullableAnnotation expectedAnnotation)
{
var symbol = (ILocalSymbol)model.GetDeclaredSymbol(variable);
Assert.Equal(expectedAnnotation, symbol.NullableAnnotation);
Assert.Equal(expectedAnnotation, symbol.Type.NullableAnnotation);
}
}
[Fact]
public void GetDeclaredSymbol_Fixed()
{
var source = @"
class C
{
unsafe void M(object? o)
{
fixed (var o1 = o ?? new object())
{
}
}
}
";
var comp = CreateCompilation(source, options: WithNonNullTypesTrue().WithAllowUnsafe(true));
comp.VerifyDiagnostics(
// (6,20): error CS0821: Implicitly-typed local variables cannot be fixed
// fixed (var o1 = o ?? new object())
Diagnostic(ErrorCode.ERR_ImplicitlyTypedLocalCannotBeFixed, "o1 = o ?? new object()").WithLocation(6, 20));
var syntaxTree = comp.SyntaxTrees[0];
var root = syntaxTree.GetRoot();
var model = comp.GetSemanticModel(syntaxTree);
var declaration = root.DescendantNodes().OfType<VariableDeclaratorSyntax>().Single();
var symbol = (ILocalSymbol)model.GetDeclaredSymbol(declaration);
Assert.Equal(PublicNullableAnnotation.Annotated, symbol.NullableAnnotation);
Assert.Equal(PublicNullableAnnotation.Annotated, symbol.Type.NullableAnnotation);
}
[Fact]
public void GetDeclaredSymbol_ForLoop()
{
var source = @"
class C
{
void M(object? o1, object o2)
{
for (var o3 = o1; false; ) {}
for (var o4 = o1 ?? o2; false; ) {}
for (var o5 = o1, o6 = o2; false; ) {}
}
}
";
var comp = CreateCompilation(source, options: WithNonNullTypesTrue());
comp.VerifyDiagnostics(
// (8,14): error CS0819: Implicitly-typed variables cannot have multiple declarators
// for (var o5 = o1, o6 = o2; false; ) {}
Diagnostic(ErrorCode.ERR_ImplicitlyTypedVariableMultipleDeclarator, "var o5 = o1, o6 = o2").WithLocation(8, 14));
var syntaxTree = comp.SyntaxTrees[0];
var root = syntaxTree.GetRoot();
var model = comp.GetSemanticModel(syntaxTree);
var declarations = root.DescendantNodes().OfType<VariableDeclaratorSyntax>().ToList();
assertAnnotation(declarations[0], PublicNullableAnnotation.Annotated);
assertAnnotation(declarations[1], PublicNullableAnnotation.Annotated);
assertAnnotation(declarations[2], PublicNullableAnnotation.Annotated);
assertAnnotation(declarations[3], PublicNullableAnnotation.Annotated);
void assertAnnotation(VariableDeclaratorSyntax variable, PublicNullableAnnotation expectedAnnotation)
{
var symbol = (ILocalSymbol)model.GetDeclaredSymbol(variable);
Assert.Equal(expectedAnnotation, symbol.NullableAnnotation);
Assert.Equal(expectedAnnotation, symbol.Type.NullableAnnotation);
}
}
[Fact]
public void GetDeclaredSymbol_OutVariable()
{
var source = @"
class C
{
void Out(out object? o1, out object o2) => throw null!;
void M()
{
Out(out var o1, out var o2);
}
}";
var comp = CreateCompilation(source, options: WithNonNullTypesTrue());
comp.VerifyDiagnostics();
var syntaxTree = comp.SyntaxTrees[0];
var root = syntaxTree.GetRoot();
var model = comp.GetSemanticModel(syntaxTree);
var declarations = root.DescendantNodes().OfType<SingleVariableDesignationSyntax>().ToList();
assertAnnotation(declarations[0], PublicNullableAnnotation.Annotated);
assertAnnotation(declarations[1], PublicNullableAnnotation.Annotated);
void assertAnnotation(SingleVariableDesignationSyntax variable, PublicNullableAnnotation expectedAnnotation)
{
var symbol = (ILocalSymbol)model.GetDeclaredSymbol(variable);
Assert.Equal(expectedAnnotation, symbol.NullableAnnotation);
Assert.Equal(expectedAnnotation, symbol.Type.NullableAnnotation);
var typeInfo = model.GetTypeInfoAndVerifyIOperation(((DeclarationExpressionSyntax)variable.Parent).Type);
Assert.Equal("System.Object?", typeInfo.Type.ToTestDisplayString());
Assert.Equal("System.Object?", typeInfo.ConvertedType.ToTestDisplayString());
Assert.Equal(PublicNullableAnnotation.Annotated, typeInfo.Nullability.Annotation);
Assert.Equal(PublicNullableFlowState.MaybeNull, typeInfo.Nullability.FlowState);
}
}
[Fact]
public void GetDeclaredSymbol_OutVariable_WithTypeInference()
{
var source = @"
#pragma warning disable CS8600
class C
{
void Out<T>(T o1, out T o2) => throw null!;
void M(object o1, object? o2)
{
Out(o1, out var o3);
Out(o2, out var o4);
o1 = null;
Out(o1, out var o5);
_ = o2 ?? throw null!;
Out(o2, out var o6);
}
}";
var comp = CreateCompilation(source, options: WithNonNullTypesTrue());
comp.VerifyDiagnostics();
var syntaxTree = comp.SyntaxTrees[0];
var root = syntaxTree.GetRoot();
var model = comp.GetSemanticModel(syntaxTree);
var declarations = root.DescendantNodes().OfType<SingleVariableDesignationSyntax>().ToList();
assertAnnotation(declarations[0], PublicNullableAnnotation.Annotated);
assertAnnotation(declarations[1], PublicNullableAnnotation.Annotated);
assertAnnotation(declarations[2], PublicNullableAnnotation.Annotated);
assertAnnotation(declarations[3], PublicNullableAnnotation.Annotated);
void assertAnnotation(SingleVariableDesignationSyntax variable, PublicNullableAnnotation expectedAnnotation)
{
var symbol = (ILocalSymbol)model.GetDeclaredSymbol(variable);
Assert.Equal(expectedAnnotation, symbol.NullableAnnotation);
Assert.Equal(expectedAnnotation, symbol.Type.NullableAnnotation);
}
}
[Fact]
public void GetDeclaredSymbol_Switch()
{
var source = @"
class C
{
void M(object? o)
{
switch (o)
{
case object o1:
break;
case var o2:
break;
}
_ = o switch { {} o1 => o1, var o2 => o2 };
}
}";
var comp = CreateCompilation(source, options: WithNonNullTypesTrue());
comp.VerifyDiagnostics();
var syntaxTree = comp.SyntaxTrees[0];
var root = syntaxTree.GetRoot();
var model = comp.GetSemanticModel(syntaxTree);
var declarations = root.DescendantNodes().OfType<SingleVariableDesignationSyntax>().ToList();
assertAnnotation(declarations[0], PublicNullableAnnotation.NotAnnotated);
assertAnnotation(declarations[1], PublicNullableAnnotation.Annotated);
assertAnnotation(declarations[2], PublicNullableAnnotation.Annotated);
assertAnnotation(declarations[3], PublicNullableAnnotation.Annotated);
void assertAnnotation(SingleVariableDesignationSyntax variable, PublicNullableAnnotation expectedAnnotation)
{
var symbol = (ILocalSymbol)model.GetDeclaredSymbol(variable);
Assert.Equal(expectedAnnotation, symbol.NullableAnnotation);
Assert.Equal(expectedAnnotation, symbol.Type.NullableAnnotation);
}
}
[Fact]
public void GetDeclaredSymbol_InLambda()
{
var source = @"
using System;
class C
{
void M(object? o)
{
Action a1 = () =>
{
var o1 = o;
};
if (o == null) return;
Action a2 = () =>
{
var o1 = o;
};
}
}";
var comp = CreateCompilation(source, options: WithNonNullTypesTrue());
comp.VerifyDiagnostics();
var syntaxTree = comp.SyntaxTrees[0];
var root = syntaxTree.GetRoot();
var model = comp.GetSemanticModel(syntaxTree);
var declarations = root.DescendantNodes().OfType<VariableDeclaratorSyntax>().ToList();
assertAnnotation(declarations[1], PublicNullableAnnotation.Annotated);
assertAnnotation(declarations[3], PublicNullableAnnotation.Annotated);
void assertAnnotation(VariableDeclaratorSyntax variable, PublicNullableAnnotation expectedAnnotation)
{
var symbol = (ILocalSymbol)model.GetDeclaredSymbol(variable);
Assert.Equal(expectedAnnotation, symbol.NullableAnnotation);
Assert.Equal(expectedAnnotation, symbol.Type.NullableAnnotation);
}
}
[Fact]
public void GetDeclaredSymbol_Foreach_Inferred()
{
var source = @"
#pragma warning disable CS8600
using System.Collections.Generic;
class C
{
List<T> GetList<T>(T t) => throw null!;
void M(object o1, object? o2)
{
foreach (var o in GetList(o1)) {}
foreach (var o in GetList(o2)) {}
o1 = null;
foreach (var o in GetList(o1)) {}
_ = o2 ?? throw null!;
foreach (var o in GetList(o2)) {}
}
}";
var comp = CreateCompilation(source, options: WithNonNullTypesTrue());
comp.VerifyDiagnostics();
var syntaxTree = comp.SyntaxTrees[0];
var root = syntaxTree.GetRoot();
var model = comp.GetSemanticModel(syntaxTree);
var declarations = root.DescendantNodes().OfType<ForEachStatementSyntax>().ToList();
assertAnnotation(declarations[0]);
assertAnnotation(declarations[1]);
assertAnnotation(declarations[2]);
assertAnnotation(declarations[3]);
void assertAnnotation(ForEachStatementSyntax foreachStatement)
{
var symbol = model.GetDeclaredSymbol(foreachStatement);
Assert.Equal(PublicNullableAnnotation.Annotated, symbol.NullableAnnotation);
Assert.Equal(PublicNullableAnnotation.Annotated, symbol.Type.NullableAnnotation);
var typeInfo = model.GetTypeInfoAndVerifyIOperation(foreachStatement.Type);
Assert.Equal(PublicNullableAnnotation.Annotated, typeInfo.Nullability.Annotation);
Assert.Equal(PublicNullableAnnotation.Annotated, typeInfo.ConvertedNullability.Annotation);
Assert.Equal(PublicNullableAnnotation.Annotated, typeInfo.Type.NullableAnnotation);
Assert.Equal(PublicNullableAnnotation.Annotated, typeInfo.ConvertedType.NullableAnnotation);
}
}
[Fact]
public void GetDeclaredSymbol_Foreach_NoInference()
{
var source = @"
#pragma warning disable CS8600
using System.Collections.Generic;
class C
{
List<T> GetList<T>(T t) => throw null!;
void M(object o1, object? o2)
{
foreach (object? o in GetList(o1)) {}
foreach (object o in GetList(o2)) {}
o1 = null;
foreach (object o in GetList(o1)) {}
_ = o2 ?? throw null!;
foreach (object? o in GetList(o2)) {}
}
}";
var comp = CreateCompilation(source, options: WithNonNullTypesTrue());
comp.VerifyDiagnostics();
var syntaxTree = comp.SyntaxTrees[0];
var root = syntaxTree.GetRoot();
var model = comp.GetSemanticModel(syntaxTree);
var declarations = root.DescendantNodes().OfType<ForEachStatementSyntax>().ToList();
assertAnnotation(declarations[0], PublicNullableAnnotation.Annotated);
assertAnnotation(declarations[1], PublicNullableAnnotation.NotAnnotated);
assertAnnotation(declarations[2], PublicNullableAnnotation.NotAnnotated);
assertAnnotation(declarations[3], PublicNullableAnnotation.Annotated);
void assertAnnotation(ForEachStatementSyntax variable, PublicNullableAnnotation expectedAnnotation)
{
var symbol = model.GetDeclaredSymbol(variable);
Assert.Equal(expectedAnnotation, symbol.NullableAnnotation);
Assert.Equal(expectedAnnotation, symbol.Type.NullableAnnotation);
}
}
[Fact]
public void GetDeclaredSymbol_Foreach_Tuples_MixedInference()
{
var source = @"
#pragma warning disable CS8600
using System.Collections.Generic;
class C
{
List<(T, T)> GetList<T>(T t) => throw null!;
void M(object o1, object? o2)
{
foreach ((var o3, object? o4) in GetList(o1)) {}
foreach ((var o3, object o4) in GetList(o2)) { o3.ToString(); }
o1 = null;
foreach ((var o3, object o4) in GetList(o1)) {}
_ = o2 ?? throw null!;
foreach ((var o3, object? o4) in GetList(o2)) {}
}
}";
var comp = CreateCompilation(source, options: WithNonNullTypesTrue());
comp.VerifyDiagnostics();
var syntaxTree = comp.SyntaxTrees[0];
var root = syntaxTree.GetRoot();
var model = comp.GetSemanticModel(syntaxTree);
var declarations = root.DescendantNodes().OfType<SingleVariableDesignationSyntax>().ToList();
// Some annotations are incorrect because of https://github.com/dotnet/roslyn/issues/37491
assertAnnotation(declarations[0], PublicNullableAnnotation.Annotated);
assertAnnotation(declarations[1], PublicNullableAnnotation.Annotated);
assertAnnotation(declarations[2], PublicNullableAnnotation.Annotated);
assertAnnotation(declarations[3], PublicNullableAnnotation.NotAnnotated);
assertAnnotation(declarations[4], PublicNullableAnnotation.Annotated);
assertAnnotation(declarations[5], PublicNullableAnnotation.NotAnnotated);
assertAnnotation(declarations[6], PublicNullableAnnotation.Annotated);
assertAnnotation(declarations[7], PublicNullableAnnotation.Annotated);
void assertAnnotation(SingleVariableDesignationSyntax variable, PublicNullableAnnotation expectedAnnotation)
{
var symbol = (ILocalSymbol)model.GetDeclaredSymbol(variable);
Assert.Equal(expectedAnnotation, symbol.NullableAnnotation);
Assert.Equal(expectedAnnotation, symbol.Type.NullableAnnotation);
var type = ((DeclarationExpressionSyntax)variable.Parent).Type;
if (type.IsVar)
{
var typeInfo = model.GetTypeInfoAndVerifyIOperation(type);
Assert.Equal(PublicNullableFlowState.MaybeNull, typeInfo.Nullability.FlowState);
Assert.Equal(PublicNullableFlowState.MaybeNull, typeInfo.ConvertedNullability.FlowState);
Assert.Equal(CodeAnalysis.NullableAnnotation.Annotated, typeInfo.Nullability.Annotation);
Assert.Equal(CodeAnalysis.NullableAnnotation.Annotated, typeInfo.ConvertedNullability.Annotation);
}
}
}
[InlineData("always")]
[InlineData("never")]
[Theory, WorkItem(37659, "https://github.com/dotnet/roslyn/issues/37659")]
public void InvalidCodeVar_GetsCorrectSymbol(string flagState)
{
var source = @"
public class C
{
public void M(string s)
{
s. // no completion
var o = new object;
}
}
";
var comp = CreateCompilation(source, parseOptions: TestOptions.Regular8.WithFeature("run-nullable-analysis", flagState));
var syntaxTree = comp.SyntaxTrees[0];
var root = syntaxTree.GetRoot();
var model = comp.GetSemanticModel(syntaxTree);
var sRef = root.DescendantNodes().OfType<IdentifierNameSyntax>().Where(n => n.Identifier.ValueText == "s").Single();
var info = model.GetSpeculativeSymbolInfo(sRef.Position, sRef, SpeculativeBindingOption.BindAsExpression);
IParameterSymbol symbol = (IParameterSymbol)info.Symbol;
Assert.True(info.CandidateSymbols.IsEmpty);
Assert.NotNull(symbol);
Assert.Equal("s", symbol.Name);
Assert.Equal(SpecialType.System_String, symbol.Type.SpecialType);
}
[Fact, WorkItem(37879, "https://github.com/dotnet/roslyn/issues/37879")]
public void MissingSymbols_ReinferredParent()
{
var source = @"
class C
{
public void A<T>(T t) where T:class
{
var c = new F<T>[] { }.Select(v => new { Value = v.Item }).ToArray();
}
private class F<T>
{
public F(T oldItem) => Item = oldItem;
public T Item { get; }
}
}";
var comp = CreateCompilation(source, options: WithNonNullTypesTrue());
var syntaxTree = comp.SyntaxTrees[0];
var root = syntaxTree.GetRoot();
var model = comp.GetSemanticModel(syntaxTree);
var select = root.DescendantNodes().OfType<IdentifierNameSyntax>().Where(i => i.Identifier.ValueText == "Select").Single();
var symbolInfo = model.GetSymbolInfo(select);
Assert.Null(symbolInfo.Symbol);
Assert.Empty(symbolInfo.CandidateSymbols);
}
[Fact, WorkItem(37879, "https://github.com/dotnet/roslyn/issues/37879")]
public void MultipleSymbols_ReinferredParent()
{
var source = @"
using System;
class C
{
public void A<T>(T t) where T : class
{
var c = new F<T>[] { }.Select(v => new { Value = v.Item }).ToArray();
}
private class F<T>
{
public F(T oldItem) => Item = oldItem;
public T Item { get; }
}
}
static class ArrayExtensions
{
public static U Select<T, U>(this T[] arr, Func<T, object, U> mapper, object arg) => throw null!;
public static U Select<T, U, V>(this T[] arr, Func<T, V, U> mapper, V arg) => throw null!;
public static U Select<T, U>(this T[] arr, C mapper) => throw null!;
public static U Select<T, U>(this T[] arr, string mapper) => throw null!;
}";
var comp = CreateCompilation(source, options: WithNonNullTypesTrue());
var syntaxTree = comp.SyntaxTrees[0];
var root = syntaxTree.GetRoot();
var model = comp.GetSemanticModel(syntaxTree);
var select = root.DescendantNodes().OfType<IdentifierNameSyntax>().Where(i => i.Identifier.ValueText == "Select").Single();
var symbolInfo = model.GetSymbolInfo(select);
Assert.Null(symbolInfo.Symbol);
Assert.Equal(4, symbolInfo.CandidateSymbols.Length);
}
[Fact]
public void GetSymbolInfo_PropertySymbols()
{
var source = @"
class C<T>
{
public T GetT { get; }
static C<U> Create<U>(U u) => new C<U>();
static void M(object? o)
{
var c1 = Create(o);
_ = c1.GetT;
if (o is null) return;
var c2 = Create(o);
_ = c2.GetT;
}
}";
var comp = CreateCompilation(source, options: WithNonNullTypesTrue());
comp.VerifyDiagnostics(
// (4,14): warning CS8618: Non-nullable property 'GetT' is uninitialized. Consider declaring the property as nullable.
// public T GetT { get; }
Diagnostic(ErrorCode.WRN_UninitializedNonNullableField, "GetT").WithArguments("property", "GetT").WithLocation(4, 14));
var syntaxTree = comp.SyntaxTrees[0];
var root = syntaxTree.GetRoot();
var model = comp.GetSemanticModel(syntaxTree);
var memberAccess = root.DescendantNodes().OfType<MemberAccessExpressionSyntax>().ToList();
var symInfo = model.GetSymbolInfo(memberAccess[0]);
Assert.Equal(PublicNullableAnnotation.Annotated, ((IPropertySymbol)symInfo.Symbol).NullableAnnotation);
Assert.Equal(PublicNullableAnnotation.Annotated, ((IPropertySymbol)symInfo.Symbol).Type.NullableAnnotation);
Assert.Equal(PublicNullableAnnotation.Annotated, symInfo.Symbol.ContainingType.TypeArgumentNullableAnnotations[0]);
Assert.Equal(PublicNullableAnnotation.Annotated, symInfo.Symbol.ContainingType.TypeArgumentNullableAnnotations().First());
symInfo = model.GetSymbolInfo(memberAccess[1]);
Assert.Equal(PublicNullableAnnotation.NotAnnotated, ((IPropertySymbol)symInfo.Symbol).NullableAnnotation);
Assert.Equal(PublicNullableAnnotation.NotAnnotated, ((IPropertySymbol)symInfo.Symbol).Type.NullableAnnotation);
Assert.Equal(PublicNullableAnnotation.NotAnnotated, symInfo.Symbol.ContainingType.TypeArgumentNullableAnnotations[0]);
Assert.Equal(PublicNullableAnnotation.NotAnnotated, symInfo.Symbol.ContainingType.TypeArgumentNullableAnnotations().First());
}
[Fact]
public void GetSymbolInfo_FieldSymbols()
{
var source = @"
class C<T>
{
public T GetT;
static C<U> Create<U>(U u) => new C<U>();
static void M(object? o)
{
var c1 = Create(o);
_ = c1.GetT;
if (o is null) return;
var c2 = Create(o);
_ = c2.GetT;
}
}";
var comp = CreateCompilation(source, options: WithNonNullTypesTrue());
comp.VerifyDiagnostics(
// (4,14): warning CS8618: Non-nullable field 'GetT' is uninitialized. Consider declaring the field as nullable.
// public T GetT;
Diagnostic(ErrorCode.WRN_UninitializedNonNullableField, "GetT").WithArguments("field", "GetT").WithLocation(4, 14),
// (4,14): warning CS0649: Field 'C<T>.GetT' is never assigned to, and will always have its default value
// public T GetT;
Diagnostic(ErrorCode.WRN_UnassignedInternalField, "GetT").WithArguments("C<T>.GetT", "").WithLocation(4, 14));
var syntaxTree = comp.SyntaxTrees[0];
var root = syntaxTree.GetRoot();
var model = comp.GetSemanticModel(syntaxTree);
var memberAccess = root.DescendantNodes().OfType<MemberAccessExpressionSyntax>().ToList();
var symInfo = model.GetSymbolInfo(memberAccess[0]);
Assert.Equal(PublicNullableAnnotation.Annotated, ((IFieldSymbol)symInfo.Symbol).NullableAnnotation);
Assert.Equal(PublicNullableAnnotation.Annotated, ((IFieldSymbol)symInfo.Symbol).Type.NullableAnnotation);
Assert.Equal(PublicNullableAnnotation.Annotated, symInfo.Symbol.ContainingType.TypeArgumentNullableAnnotations[0]);
Assert.Equal(PublicNullableAnnotation.Annotated, symInfo.Symbol.ContainingType.TypeArgumentNullableAnnotations().First());
symInfo = model.GetSymbolInfo(memberAccess[1]);
Assert.Equal(PublicNullableAnnotation.NotAnnotated, ((IFieldSymbol)symInfo.Symbol).NullableAnnotation);
Assert.Equal(PublicNullableAnnotation.NotAnnotated, ((IFieldSymbol)symInfo.Symbol).Type.NullableAnnotation);
Assert.Equal(PublicNullableAnnotation.NotAnnotated, symInfo.Symbol.ContainingType.TypeArgumentNullableAnnotations[0]);
Assert.Equal(PublicNullableAnnotation.NotAnnotated, symInfo.Symbol.ContainingType.TypeArgumentNullableAnnotations().First());
}
[Fact]
public void GetSymbolInfo_EventAdditionSymbols()
{
var source = @"
#pragma warning disable CS0067
using System;
class C<T>
{
public event EventHandler? Event;
static C<U> Create<U>(U u) => new C<U>();
static void M(object? o)
{
var c1 = Create(o);
c1.Event += (obj, sender) => {};
if (o is null) return;
var c2 = Create(o);
c2.Event += (obj, sender) => {};
c2.Event += c1.Event;
}
}";
var comp = CreateCompilation(source, options: WithNonNullTypesTrue());
comp.VerifyDiagnostics();
var syntaxTree = comp.SyntaxTrees[0];
var root = syntaxTree.GetRoot();
var model = comp.GetSemanticModel(syntaxTree);
var memberAccess = root.DescendantNodes().OfType<MemberAccessExpressionSyntax>().ToList();
var symInfo = model.GetSymbolInfo(memberAccess[0]);
Assert.Equal(PublicNullableAnnotation.Annotated, ((IEventSymbol)symInfo.Symbol).NullableAnnotation);
Assert.Equal(PublicNullableAnnotation.Annotated, ((IEventSymbol)symInfo.Symbol).Type.NullableAnnotation);
Assert.Equal(PublicNullableAnnotation.Annotated, symInfo.Symbol.ContainingType.TypeArgumentNullableAnnotations[0]);
Assert.Equal(PublicNullableAnnotation.Annotated, symInfo.Symbol.ContainingType.TypeArgumentNullableAnnotations().First());
symInfo = model.GetSymbolInfo(memberAccess[1]);
Assert.Equal(PublicNullableAnnotation.Annotated, ((IEventSymbol)symInfo.Symbol).NullableAnnotation);
Assert.Equal(PublicNullableAnnotation.Annotated, ((IEventSymbol)symInfo.Symbol).Type.NullableAnnotation);
Assert.Equal(PublicNullableAnnotation.NotAnnotated, symInfo.Symbol.ContainingType.TypeArgumentNullableAnnotations[0]);
Assert.Equal(PublicNullableAnnotation.NotAnnotated, symInfo.Symbol.ContainingType.TypeArgumentNullableAnnotations().First());
var event1 = model.GetSymbolInfo(memberAccess[2]).Symbol;
var event2 = model.GetSymbolInfo(memberAccess[3]).Symbol;
Assert.NotNull(event1);
Assert.NotNull(event2);
Assert.True(event1.Equals(event2, SymbolEqualityComparer.Default));
Assert.False(event1.Equals(event2, SymbolEqualityComparer.IncludeNullability));
}
[Fact]
public void GetSymbolInfo_EventAssignmentSymbols()
{
var source = @"
#pragma warning disable CS0067
using System;
class C<T>
{
public event EventHandler? Event;
static C<U> Create<U>(U u) => new C<U>();
static void M(object? o)
{
var c1 = Create(o);
c1.Event = (obj, sender) => {};
if (o is null) return;
var c2 = Create(o);
c2.Event = (obj, sender) => {};
}
}";
var comp = CreateCompilation(source, options: WithNonNullTypesTrue());
comp.VerifyDiagnostics();
var syntaxTree = comp.SyntaxTrees[0];
var root = syntaxTree.GetRoot();
var model = comp.GetSemanticModel(syntaxTree);
var memberAccess = root.DescendantNodes().OfType<MemberAccessExpressionSyntax>().ToList();
var symInfo = model.GetSymbolInfo(memberAccess[0]);
Assert.Equal(PublicNullableAnnotation.Annotated, ((IEventSymbol)symInfo.Symbol).NullableAnnotation);
Assert.Equal(PublicNullableAnnotation.Annotated, ((IEventSymbol)symInfo.Symbol).Type.NullableAnnotation);
Assert.Equal(PublicNullableAnnotation.Annotated, symInfo.Symbol.ContainingType.TypeArgumentNullableAnnotations[0]);
Assert.Equal(PublicNullableAnnotation.Annotated, symInfo.Symbol.ContainingType.TypeArgumentNullableAnnotations().First());
symInfo = model.GetSymbolInfo(memberAccess[1]);
Assert.Equal(PublicNullableAnnotation.Annotated, ((IEventSymbol)symInfo.Symbol).NullableAnnotation);
Assert.Equal(PublicNullableAnnotation.Annotated, ((IEventSymbol)symInfo.Symbol).Type.NullableAnnotation);
Assert.Equal(PublicNullableAnnotation.NotAnnotated, symInfo.Symbol.ContainingType.TypeArgumentNullableAnnotations[0]);
Assert.Equal(PublicNullableAnnotation.NotAnnotated, symInfo.Symbol.ContainingType.TypeArgumentNullableAnnotations().First());
}
[Fact]
public void GetSymbolInfo_EventAssignmentFlowState()
{
var source = @"
using System;
class C
{
event Action? Event;
void M(bool b)
{
if (b) Event.Invoke(); // 1
Event += () => { };
Event.Invoke();
}
}";
var comp = CreateCompilation(source, options: WithNonNullTypesTrue());
comp.VerifyDiagnostics(
// (9,16): warning CS8602: Dereference of a possibly null reference.
// if (b) Event.Invoke(); // 1
Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "Event").WithLocation(9, 16)
);
var syntaxTree = comp.SyntaxTrees[0];
var root = syntaxTree.GetRoot();
var model = comp.GetSemanticModel(syntaxTree);
var memberAccess = root.DescendantNodes().OfType<MemberAccessExpressionSyntax>().ToList();
Assert.Equal(2, memberAccess.Count);
var typeInfo = model.GetTypeInfo(memberAccess[0].Expression);
Assert.Equal(PublicNullableAnnotation.Annotated, typeInfo.Type.NullableAnnotation);
Assert.Equal(PublicNullableFlowState.MaybeNull, typeInfo.Nullability.FlowState);
typeInfo = model.GetTypeInfo(memberAccess[1].Expression);
Assert.Equal(PublicNullableAnnotation.NotAnnotated, typeInfo.Type.NullableAnnotation);
Assert.Equal(PublicNullableFlowState.NotNull, typeInfo.Nullability.FlowState);
var lhs = root.DescendantNodes().OfType<AssignmentExpressionSyntax>().Single().Left;
typeInfo = model.GetTypeInfo(lhs);
Assert.Equal(PublicNullableAnnotation.None, typeInfo.Type.NullableAnnotation);
Assert.Equal(PublicNullableFlowState.None, typeInfo.Nullability.FlowState);
}
[Fact]
public void GetSymbolInfo_ReinferredCollectionInitializerAdd_InstanceMethods()
{
var source = @"
using System.Collections;
class C : IEnumerable
{
public void Add<T>(T t) => throw null!;
public IEnumerator GetEnumerator() => throw null!;
public static T Identity<T>(T t) => t;
static void M(object? o1, string o2)
{
_ = new C() { o1, Identity(o1 ??= new object()), o1, o2 };
}
}
";
var comp = CreateCompilation(source, options: WithNonNullTypesTrue());
comp.VerifyDiagnostics();
var syntaxTree = comp.SyntaxTrees[0];
var root = syntaxTree.GetRoot();
var model = comp.GetSemanticModel(syntaxTree);
var collectionInitializer = root.DescendantNodes().OfType<InitializerExpressionSyntax>().Single();
verifyAnnotation(collectionInitializer.Expressions[0], PublicNullableAnnotation.Annotated);
verifyAnnotation(collectionInitializer.Expressions[1], PublicNullableAnnotation.NotAnnotated);
verifyAnnotation(collectionInitializer.Expressions[2], PublicNullableAnnotation.NotAnnotated);
verifyAnnotation(collectionInitializer.Expressions[3], PublicNullableAnnotation.NotAnnotated);
void verifyAnnotation(ExpressionSyntax expr, PublicNullableAnnotation expectedAnnotation)
{
var symbolInfo = model.GetCollectionInitializerSymbolInfo(expr);
Assert.Equal(expectedAnnotation, ((IMethodSymbol)symbolInfo.Symbol).TypeArgumentNullableAnnotations[0]);
Assert.Equal(expectedAnnotation, ((IMethodSymbol)symbolInfo.Symbol).TypeArguments[0].NullableAnnotation);
}
}
[Fact]
public void GetSymbolInfo_ReinferredCollectionInitializerAdd_ExtensionMethod01()
{
var source = @"
using System.Collections;
class C : IEnumerable
{
public IEnumerator GetEnumerator() => throw null!;
public static T Identity<T>(T t) => t;
static void M(object? o1, string o2)
{
_ = new C() { o1, Identity(o1 ??= new object()), o1, o2 };
}
}
static class CExt
{
public static void Add<T>(this C c, T t) => throw null!;
}
";
var comp = CreateCompilation(source, options: WithNonNullTypesTrue());
comp.VerifyDiagnostics();
var syntaxTree = comp.SyntaxTrees[0];
var root = syntaxTree.GetRoot();
var model = comp.GetSemanticModel(syntaxTree);
var collectionInitializer = root.DescendantNodes().OfType<InitializerExpressionSyntax>().Single();
verifyAnnotation(collectionInitializer.Expressions[0], PublicNullableAnnotation.Annotated);
verifyAnnotation(collectionInitializer.Expressions[1], PublicNullableAnnotation.NotAnnotated);
verifyAnnotation(collectionInitializer.Expressions[2], PublicNullableAnnotation.NotAnnotated);
verifyAnnotation(collectionInitializer.Expressions[3], PublicNullableAnnotation.NotAnnotated);
void verifyAnnotation(ExpressionSyntax expr, PublicNullableAnnotation expectedAnnotation)
{
var symbolInfo = model.GetCollectionInitializerSymbolInfo(expr);
Assert.Equal(expectedAnnotation, ((IMethodSymbol)symbolInfo.Symbol).TypeArgumentNullableAnnotations[0]);
Assert.Equal(expectedAnnotation, ((IMethodSymbol)symbolInfo.Symbol).TypeArguments[0].NullableAnnotation);
}
}
[Fact]
public void GetSymbolInfo_ReinferredCollectionInitializerAdd_ExtensionMethod02()
{
var source = @"
using System.Collections;
class C : IEnumerable
{
public IEnumerator GetEnumerator() => throw null!;
public static T Identity<T>(T t) => t;
static void M(object? o1, string o2)
{
_ = new C() { o1, Identity(o1 ??= new object()), o1, o2 };
}
}
static class CExt
{
public static void Add<T, U>(this T t, U u) => throw null!;
}
";
var comp = CreateCompilation(source, options: WithNonNullTypesTrue());
comp.VerifyDiagnostics();
var syntaxTree = comp.SyntaxTrees[0];
var root = syntaxTree.GetRoot();
var model = comp.GetSemanticModel(syntaxTree);
var collectionInitializer = root.DescendantNodes().OfType<InitializerExpressionSyntax>().Single();
verifyAnnotation(collectionInitializer.Expressions[0], PublicNullableAnnotation.Annotated);
verifyAnnotation(collectionInitializer.Expressions[1], PublicNullableAnnotation.NotAnnotated);
verifyAnnotation(collectionInitializer.Expressions[2], PublicNullableAnnotation.NotAnnotated);
verifyAnnotation(collectionInitializer.Expressions[3], PublicNullableAnnotation.NotAnnotated);
void verifyAnnotation(ExpressionSyntax expr, PublicNullableAnnotation expectedAnnotation)
{
var symbolInfo = model.GetCollectionInitializerSymbolInfo(expr);
Assert.Equal(PublicNullableAnnotation.NotAnnotated, ((IMethodSymbol)symbolInfo.Symbol).TypeArgumentNullableAnnotations[0]);
Assert.Equal(PublicNullableAnnotation.NotAnnotated, ((IMethodSymbol)symbolInfo.Symbol).TypeArguments[0].NullableAnnotation);
Assert.Equal(expectedAnnotation, ((IMethodSymbol)symbolInfo.Symbol).TypeArgumentNullableAnnotations[1]);
Assert.Equal(expectedAnnotation, ((IMethodSymbol)symbolInfo.Symbol).TypeArguments[1].NullableAnnotation);
}
}
[Fact]
public void GetSymbolInfo_ReinferredCollectionInitializerAdd_MultipleOverloads()
{
var source = @"
using System.Collections;
class C : IEnumerable
{
public IEnumerator GetEnumerator() => throw null!;
public static T Identity<T>(T t) => t;
static void M(object? o1, string o2)
{
_ = new C() { o1, Identity(o1 ??= new object()), o1, o2 };
}
}
static class CExt1
{
public static void Add<T>(this C c, T t) => throw null!;
}
static class CExt2
{
public static void Add<T>(this C c, T t) => throw null!;
}
";
var comp = CreateCompilation(source, options: WithNonNullTypesTrue());
comp.VerifyDiagnostics(
// (10,23): error CS0121: The call is ambiguous between the following methods or properties: 'CExt1.Add<T>(C, T)' and 'CExt2.Add<T>(C, T)'
// _ = new C() { o1, Identity(o1 ??= new object()), o1, o2 };
Diagnostic(ErrorCode.ERR_AmbigCall, "o1").WithArguments("CExt1.Add<T>(C, T)", "CExt2.Add<T>(C, T)").WithLocation(10, 23),
// (10,27): error CS0121: The call is ambiguous between the following methods or properties: 'CExt1.Add<T>(C, T)' and 'CExt2.Add<T>(C, T)'
// _ = new C() { o1, Identity(o1 ??= new object()), o1, o2 };
Diagnostic(ErrorCode.ERR_AmbigCall, "Identity(o1 ??= new object())").WithArguments("CExt1.Add<T>(C, T)", "CExt2.Add<T>(C, T)").WithLocation(10, 27),
// (10,58): error CS0121: The call is ambiguous between the following methods or properties: 'CExt1.Add<T>(C, T)' and 'CExt2.Add<T>(C, T)'
// _ = new C() { o1, Identity(o1 ??= new object()), o1, o2 };
Diagnostic(ErrorCode.ERR_AmbigCall, "o1").WithArguments("CExt1.Add<T>(C, T)", "CExt2.Add<T>(C, T)").WithLocation(10, 58),
// (10,62): error CS0121: The call is ambiguous between the following methods or properties: 'CExt1.Add<T>(C, T)' and 'CExt2.Add<T>(C, T)'
// _ = new C() { o1, Identity(o1 ??= new object()), o1, o2 };
Diagnostic(ErrorCode.ERR_AmbigCall, "o2").WithArguments("CExt1.Add<T>(C, T)", "CExt2.Add<T>(C, T)").WithLocation(10, 62));
var syntaxTree = comp.SyntaxTrees[0];
var root = syntaxTree.GetRoot();
var model = comp.GetSemanticModel(syntaxTree);
var collectionInitializer = root.DescendantNodes().OfType<InitializerExpressionSyntax>().Single();
verifyAnnotation(collectionInitializer.Expressions[0]);
verifyAnnotation(collectionInitializer.Expressions[1]);
verifyAnnotation(collectionInitializer.Expressions[2]);
verifyAnnotation(collectionInitializer.Expressions[3]);
void verifyAnnotation(ExpressionSyntax expr)
{
var symbolInfo = model.GetCollectionInitializerSymbolInfo(expr);
Assert.Null(symbolInfo.Symbol);
foreach (var symbol in symbolInfo.CandidateSymbols)
{
Assert.Equal(PublicNullableAnnotation.None, ((IMethodSymbol)symbol).TypeArgumentNullableAnnotations[0]);
Assert.Equal(PublicNullableAnnotation.None, ((IMethodSymbol)symbol).TypeArguments[0].NullableAnnotation);
}
}
}
[Fact]
public void GetSymbolInfo_ReinferredCollectionInitializerAdd_MultiElementAdds()
{
var source = @"
using System.Collections;
class C : IEnumerable
{
public IEnumerator GetEnumerator() => throw null!;
public static T Identity<T>(T t) => t;
static void M(object? o1, string o2)
{
_ = new C() { { o1, o2 }, { o2, o1 }, { Identity(o1 ??= new object()), o2 } };
}
}
static class CExt
{
public static void Add<T, U>(this C c, T t, U u) => throw null!;
}
";
var comp = CreateCompilation(source, options: WithNonNullTypesTrue());
comp.VerifyDiagnostics();
var syntaxTree = comp.SyntaxTrees[0];
var root = syntaxTree.GetRoot();
var model = comp.GetSemanticModel(syntaxTree);
var collectionInitializer = root.DescendantNodes().OfType<InitializerExpressionSyntax>().First();
verifyAnnotation(collectionInitializer.Expressions[0], PublicNullableAnnotation.Annotated, PublicNullableAnnotation.NotAnnotated);
verifyAnnotation(collectionInitializer.Expressions[1], PublicNullableAnnotation.NotAnnotated, PublicNullableAnnotation.Annotated);
verifyAnnotation(collectionInitializer.Expressions[2], PublicNullableAnnotation.NotAnnotated, PublicNullableAnnotation.NotAnnotated);
void verifyAnnotation(ExpressionSyntax expr, PublicNullableAnnotation annotation1, PublicNullableAnnotation annotation2)
{
var symbolInfo = model.GetCollectionInitializerSymbolInfo(expr);
var methodSymbol = ((IMethodSymbol)symbolInfo.Symbol);
Assert.Equal(annotation1, methodSymbol.TypeArgumentNullableAnnotations[0]);
Assert.Equal(annotation1, methodSymbol.TypeArguments[0].NullableAnnotation);
Assert.Equal(annotation2, methodSymbol.TypeArgumentNullableAnnotations[1]);
Assert.Equal(annotation2, methodSymbol.TypeArguments[1].NullableAnnotation);
}
}
[Fact]
public void GetSymbolInfo_ReinferredCollectionInitializerAdd_MultiElementAdds_LinkedTypes()
{
var source = @"
using System.Collections;
class C : IEnumerable
{
public IEnumerator GetEnumerator() => throw null!;
public static T Identity<T>(T t) => t;
static void M(object? o1, string o2)
{
_ = new C() { { o1, o2 }, { o2, o1 }, { Identity(o1 ??= new object()), o2 } };
}
}
static class CExt
{
public static void Add<T>(this C c, T t1, T t2) => throw null!;
}
";
var comp = CreateCompilation(source, options: WithNonNullTypesTrue());
comp.VerifyDiagnostics();
var syntaxTree = comp.SyntaxTrees[0];
var root = syntaxTree.GetRoot();
var model = comp.GetSemanticModel(syntaxTree);
var collectionInitializer = root.DescendantNodes().OfType<InitializerExpressionSyntax>().First();
verifyAnnotation(collectionInitializer.Expressions[0], PublicNullableAnnotation.Annotated);
verifyAnnotation(collectionInitializer.Expressions[1], PublicNullableAnnotation.Annotated);
verifyAnnotation(collectionInitializer.Expressions[2], PublicNullableAnnotation.NotAnnotated);
void verifyAnnotation(ExpressionSyntax expr, PublicNullableAnnotation annotation)
{
var symbolInfo = model.GetCollectionInitializerSymbolInfo(expr);
var methodSymbol = ((IMethodSymbol)symbolInfo.Symbol);
Assert.Equal(annotation, methodSymbol.TypeArgumentNullableAnnotations[0]);
Assert.Equal(annotation, methodSymbol.TypeArguments[0].NullableAnnotation);
}
}
[Fact]
public void GetSymbolInfo_ReinferredIndexer()
{
var source = @"
class C<T, U>
{
public T this[U u] { get => throw null!; set => throw null!; }
public static void M(bool b, object? o1, object o2)
{
var c1 = CExt.Create(o1, o2);
if (b) c1[o1] = o2;
if (b) _ = c1[o1];
var c2 = CExt.Create(o2, o1);
if (b) c2[o2] = o1;
if (b) _ = c2[o2];
var c3 = CExt.Create(o1 ?? o2, o2);
if (b) c3[o1] = o2;
if (b) _ = c3[o1];
}
}
static class CExt
{
public static C<T, U> Create<T, U>(T t, U u) => throw null!;
}";
var comp = CreateCompilation(source, options: WithNonNullTypesTrue());
comp.VerifyDiagnostics(
// (9,19): warning CS8604: Possible null reference argument for parameter 'u' in 'object? C<object?, object>.this[object u]'.
// if (b) c1[o1] = o2;
Diagnostic(ErrorCode.WRN_NullReferenceArgument, "o1").WithArguments("u", "object? C<object?, object>.this[object u]").WithLocation(9, 19),
// (10,23): warning CS8604: Possible null reference argument for parameter 'u' in 'object? C<object?, object>.this[object u]'.
// if (b) _ = c1[o1];
Diagnostic(ErrorCode.WRN_NullReferenceArgument, "o1").WithArguments("u", "object? C<object?, object>.this[object u]").WithLocation(10, 23),
// (13,25): warning CS8601: Possible null reference assignment.
// if (b) c2[o2] = o1;
Diagnostic(ErrorCode.WRN_NullReferenceAssignment, "o1").WithLocation(13, 25),
// (17,19): warning CS8604: Possible null reference argument for parameter 'u' in 'object C<object, object>.this[object u]'.
// if (b) c3[o1] = o2;
Diagnostic(ErrorCode.WRN_NullReferenceArgument, "o1").WithArguments("u", "object C<object, object>.this[object u]").WithLocation(17, 19),
// (18,23): warning CS8604: Possible null reference argument for parameter 'u' in 'object C<object, object>.this[object u]'.
// if (b) _ = c3[o1];
Diagnostic(ErrorCode.WRN_NullReferenceArgument, "o1").WithArguments("u", "object C<object, object>.this[object u]").WithLocation(18, 23));
var syntaxTree = comp.SyntaxTrees[0];
var root = syntaxTree.GetRoot();
var model = comp.GetSemanticModel(syntaxTree);
var indexers = root.DescendantNodes().OfType<ElementAccessExpressionSyntax>().ToArray().AsSpan();
verifyAnnotation(indexers.Slice(0, 2), PublicNullableAnnotation.Annotated, PublicNullableAnnotation.NotAnnotated);
verifyAnnotation(indexers.Slice(2, 2), PublicNullableAnnotation.NotAnnotated, PublicNullableAnnotation.Annotated);
verifyAnnotation(indexers.Slice(4, 2), PublicNullableAnnotation.NotAnnotated, PublicNullableAnnotation.NotAnnotated);
void verifyAnnotation(Span<ElementAccessExpressionSyntax> indexers, PublicNullableAnnotation firstAnnotation, PublicNullableAnnotation secondAnnotation)
{
var propertySymbol = (IPropertySymbol)model.GetSymbolInfo(indexers[0]).Symbol;
verifyIndexer(propertySymbol);
propertySymbol = (IPropertySymbol)model.GetSymbolInfo(indexers[1]).Symbol;
verifyIndexer(propertySymbol);
void verifyIndexer(IPropertySymbol propertySymbol)
{
Assert.True(propertySymbol.IsIndexer);
Assert.Equal(firstAnnotation, propertySymbol.NullableAnnotation);
Assert.Equal(firstAnnotation, propertySymbol.Type.NullableAnnotation);
Assert.Equal(secondAnnotation, propertySymbol.Parameters[0].NullableAnnotation);
Assert.Equal(secondAnnotation, propertySymbol.Parameters[0].Type.NullableAnnotation);
}
}
}
[Fact]
public void GetSymbolInfo_IndexReinferred()
{
var source = @"
class C<T>
{
public int Length { get; }
public T this[int i] { get => throw null!; set => throw null!; }
public static C<TT> Create<TT>(TT t) => throw null!;
public static void M(object? o)
{
var c1 = Create(o);
c1[^1] = new object();
_ = c1[^1];
var c2 = Create(o ?? new object());
c2[^1] = new object();
_ = c2[^1];
}
}";
var comp = CreateCompilationWithIndexAndRangeAndSpan(source, options: WithNonNullTypesTrue());
comp.VerifyDiagnostics();
var syntaxTree = comp.SyntaxTrees[0];
var root = syntaxTree.GetRoot();
var model = comp.GetSemanticModel(syntaxTree);
var elementAccesses = root.DescendantNodes().OfType<ElementAccessExpressionSyntax>().ToArray().AsSpan();
verifyAnnotation(elementAccesses.Slice(0, 2), PublicNullableAnnotation.Annotated);
verifyAnnotation(elementAccesses.Slice(2, 2), PublicNullableAnnotation.NotAnnotated);
void verifyAnnotation(Span<ElementAccessExpressionSyntax> indexers, PublicNullableAnnotation annotation)
{
var propertySymbol = (IPropertySymbol)model.GetSymbolInfo(indexers[0]).Symbol;
verifyIndexer(propertySymbol);
propertySymbol = (IPropertySymbol)model.GetSymbolInfo(indexers[1]).Symbol;
verifyIndexer(propertySymbol);
void verifyIndexer(IPropertySymbol propertySymbol)
{
Assert.True(propertySymbol.IsIndexer);
Assert.Equal(annotation, propertySymbol.NullableAnnotation);
Assert.Equal(annotation, propertySymbol.Type.NullableAnnotation);
}
}
}
[Fact]
public void GetSymbolInfo_RangeReinferred()
{
var source = @"
using System;
class C<T>
{
public int Length { get; }
public Span<T> Slice(int start, int length) => throw null!;
public static C<TT> Create<TT>(TT t) => throw null!;
public static void M(object? o)
{
var c1 = Create(o);
_ = c1[..^1];
var c2 = Create(o ?? new object());
_ = c2[..^1];
}
}";
var comp = CreateCompilationWithIndexAndRangeAndSpan(source, options: WithNonNullTypesTrue());
comp.VerifyDiagnostics();
var syntaxTree = comp.SyntaxTrees[0];
var root = syntaxTree.GetRoot();
var model = comp.GetSemanticModel(syntaxTree);
var elementAccesses = root.DescendantNodes().OfType<ElementAccessExpressionSyntax>().ToArray();
verifyAnnotation(elementAccesses[0], PublicNullableAnnotation.Annotated);
verifyAnnotation(elementAccesses[1], PublicNullableAnnotation.NotAnnotated);
void verifyAnnotation(ElementAccessExpressionSyntax indexer, PublicNullableAnnotation annotation)
{
var propertySymbol = (IMethodSymbol)model.GetSymbolInfo(indexer).Symbol;
Assert.NotNull(propertySymbol);
var spanType = (INamedTypeSymbol)propertySymbol.ReturnType;
Assert.Equal(annotation, spanType.TypeArgumentNullableAnnotations[0]);
Assert.Equal(annotation, spanType.TypeArgumentNullableAnnotations().First());
}
}
[Fact]
public void GetSymbolInfo_UnaryOperator()
{
var source =
@"#nullable enable
struct S<T>
{
public static S<T> operator~(S<T> s) => s;
}
class Program
{
static S<T> Create1<T>(T t) => new S<T>();
static S<T>? Create2<T>(T t) => null;
static void F<T>() where T : class, new()
{
T x = null;
var sx = Create1(x);
_ = ~sx;
T? y = new T();
var sy = Create2(y);
_ = ~sy;
}
}";
var comp = CreateCompilation(source);
comp.VerifyDiagnostics(
// (12,15): warning CS8600: Converting null literal or possible null value to non-nullable type.
// T x = null;
Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "null").WithLocation(12, 15));
var syntaxTree = comp.SyntaxTrees[0];
var root = syntaxTree.GetRoot();
var model = comp.GetSemanticModel(syntaxTree);
var operators = root.DescendantNodes().OfType<PrefixUnaryExpressionSyntax>().ToList();
verifyAnnotations(operators[0], PublicNullableAnnotation.Annotated, "S<T?> S<T?>.operator ~(S<T?> s)");
verifyAnnotations(operators[1], PublicNullableAnnotation.NotAnnotated, "S<T!> S<T!>.operator ~(S<T!> s)");
void verifyAnnotations(PrefixUnaryExpressionSyntax syntax, PublicNullableAnnotation annotation, string expected)
{
var method = (IMethodSymbol)model.GetSymbolInfo(syntax).Symbol;
Assert.Equal(expected, method.ToTestDisplayString(includeNonNullable: true));
Assert.Equal(annotation, method.ContainingType.TypeArgumentNullableAnnotations[0]);
Assert.Equal(annotation, method.ContainingType.TypeArgumentNullableAnnotations().First());
}
}
[Fact]
public void GetSymbolInfo_BinaryOperator()
{
var source =
@"#nullable enable
struct S<T>
{
public static S<T> operator+(S<T> x, S<T> y) => x;
}
class Program
{
static S<T> Create1<T>(T t) => new S<T>();
static S<T>? Create2<T>(T t) => null;
static void F<T>() where T : class, new()
{
T x = null;
var sx = Create1(x);
_ = sx + sx;
T? y = new T();
var sy = Create2(y);
_ = sy + sy;
}
}";
var comp = CreateCompilation(source);
comp.VerifyDiagnostics(
// (12,15): warning CS8600: Converting null literal or possible null value to non-nullable type.
// T x = null;
Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "null").WithLocation(12, 15));
var syntaxTree = comp.SyntaxTrees[0];
var root = syntaxTree.GetRoot();
var model = comp.GetSemanticModel(syntaxTree);
var operators = root.DescendantNodes().OfType<BinaryExpressionSyntax>().ToList();
verifyAnnotations(operators[0], PublicNullableAnnotation.Annotated, "S<T?> S<T?>.operator +(S<T?> x, S<T?> y)");
verifyAnnotations(operators[1], PublicNullableAnnotation.NotAnnotated, "S<T!> S<T!>.operator +(S<T!> x, S<T!> y)");
void verifyAnnotations(BinaryExpressionSyntax syntax, PublicNullableAnnotation annotation, string expected)
{
var method = (IMethodSymbol)model.GetSymbolInfo(syntax).Symbol;
Assert.Equal(expected, method.ToTestDisplayString(includeNonNullable: true));
Assert.Equal(annotation, method.ContainingType.TypeArgumentNullableAnnotations[0]);
Assert.Equal(annotation, method.ContainingType.TypeArgumentNullableAnnotations().First());
}
}
[Fact]
public void GetSymbolInfo_SimpleLambdaReinference()
{
var source = @"
using System;
class C
{
public static Action<T> Create<T>(T t, Action<T> a) => throw null!;
public static void M(object? o)
{
var a = Create(o, o1 => { _ = o1.ToString(); });
}
}";
var comp = CreateCompilation(source, options: WithNonNullTypesTrue());
comp.VerifyDiagnostics(
// (9,39): warning CS8602: Dereference of a possibly null reference.
// var a = Create(o, o1 => { _ = o1.ToString(); });
Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "o1").WithLocation(9, 39));
var syntaxTree = comp.SyntaxTrees[0];
var root = syntaxTree.GetRoot();
var model = comp.GetSemanticModel(syntaxTree);
var lambda = root.DescendantNodes().OfType<LambdaExpressionSyntax>().Single();
var lambdaSymbol = (IMethodSymbol)model.GetSymbolInfo(lambda).Symbol;
Assert.NotNull(lambdaSymbol);
Assert.Equal(MethodKind.LambdaMethod, lambdaSymbol.MethodKind);
Assert.Equal(PublicNullableAnnotation.Annotated, lambdaSymbol.Parameters[0].NullableAnnotation);
Assert.Equal(PublicNullableAnnotation.Annotated, lambdaSymbol.Parameters[0].Type.NullableAnnotation);
var o1Ref = lambda.DescendantNodes()
.OfType<AssignmentExpressionSyntax>()
.Single()
.DescendantNodes()
.OfType<IdentifierNameSyntax>()
.First(i => i.Identifier.ValueText == "o1");
var parameterSymbol = (IParameterSymbol)model.GetSymbolInfo(o1Ref).Symbol;
Assert.NotNull(parameterSymbol);
Assert.Equal(PublicNullableAnnotation.Annotated, parameterSymbol.NullableAnnotation);
Assert.Equal(PublicNullableAnnotation.Annotated, parameterSymbol.Type.NullableAnnotation);
var mDeclaration = root.DescendantNodes().OfType<MethodDeclarationSyntax>().First(m => m.Identifier.ValueText == "M");
var mSymbol = model.GetDeclaredSymbol(mDeclaration);
Assert.Equal(mSymbol, lambdaSymbol.ContainingSymbol, SymbolEqualityComparer.IncludeNullability);
}
[Fact]
public void NestedLambdaReinference_NestedReinferred()
{
var source = @"
using System;
class C
{
public static Action<T> Create<T>(T t, Action<T> a) => throw null!;
public static void M(object? o)
{
var a = Create(o, o1 => {
if (o1 == null) return;
Create(o1, o2 => { _ = o2; _ = o1; });
});
}
}";
var comp = CreateCompilation(source, options: WithNonNullTypesTrue());
comp.VerifyDiagnostics();
var syntaxTree = comp.SyntaxTrees[0];
var root = syntaxTree.GetRoot();
var model = comp.GetSemanticModel(syntaxTree);
var lambda = root.DescendantNodes().OfType<LambdaExpressionSyntax>().First();
var lambdaSymbol = model.GetSymbolInfo(lambda).Symbol;
var innerLambda = root.DescendantNodes().OfType<LambdaExpressionSyntax>().ElementAt(1);
var innerLambdaSymbol = (IMethodSymbol)model.GetSymbolInfo(innerLambda).Symbol;
Assert.NotNull(innerLambdaSymbol);
Assert.Equal(MethodKind.LambdaMethod, innerLambdaSymbol.MethodKind);
Assert.Equal(PublicNullableAnnotation.NotAnnotated, innerLambdaSymbol.Parameters[0].NullableAnnotation);
Assert.Equal(PublicNullableAnnotation.NotAnnotated, innerLambdaSymbol.Parameters[0].Type.NullableAnnotation);
Assert.Equal(lambdaSymbol, innerLambdaSymbol.ContainingSymbol, SymbolEqualityComparer.IncludeNullability);
var o1Ref = innerLambda.DescendantNodes()
.OfType<AssignmentExpressionSyntax>()
.ElementAt(1)
.DescendantNodes()
.OfType<IdentifierNameSyntax>()
.First(i => i.Identifier.ValueText == "o1");
var o1Symbol = (IParameterSymbol)model.GetSymbolInfo(o1Ref).Symbol;
Assert.Equal(PublicNullableAnnotation.Annotated, o1Symbol.NullableAnnotation);
Assert.Equal(PublicNullableAnnotation.Annotated, o1Symbol.Type.NullableAnnotation);
var o2Ref = innerLambda.DescendantNodes()
.OfType<AssignmentExpressionSyntax>()
.First()
.DescendantNodes()
.OfType<IdentifierNameSyntax>()
.First(i => i.Identifier.ValueText == "o2");
var o2Symbol = (IParameterSymbol)model.GetSymbolInfo(o2Ref).Symbol;
Assert.Equal(PublicNullableAnnotation.NotAnnotated, o2Symbol.NullableAnnotation);
Assert.Equal(PublicNullableAnnotation.NotAnnotated, o2Symbol.Type.NullableAnnotation);
Assert.Equal(innerLambdaSymbol, o2Symbol.ContainingSymbol, SymbolEqualityComparer.IncludeNullability);
}
[Fact]
public void NestedLambdaReinference_NestedNotReinferred()
{
var source = @"
using System;
class C
{
public static Action<T> Create<T>(T t, Action<T> a) => throw null!;
public static void M(object? o)
{
var a = Create(o, o1 => {
if (o1 == null) return;
Action<string> a = o2 => { _ = o2; _ = o1; };
});
}
}";
var comp = CreateCompilation(source, options: WithNonNullTypesTrue());
comp.VerifyDiagnostics();
var syntaxTree = comp.SyntaxTrees[0];
var root = syntaxTree.GetRoot();
var model = comp.GetSemanticModel(syntaxTree);
var lambda = root.DescendantNodes().OfType<LambdaExpressionSyntax>().First();
var lambdaSymbol = model.GetSymbolInfo(lambda).Symbol;
var innerLambda = root.DescendantNodes().OfType<LambdaExpressionSyntax>().ElementAt(1);
var innerLambdaSymbol = (IMethodSymbol)model.GetSymbolInfo(innerLambda).Symbol;
Assert.NotNull(innerLambdaSymbol);
Assert.Equal(MethodKind.LambdaMethod, innerLambdaSymbol.MethodKind);
Assert.Equal(PublicNullableAnnotation.NotAnnotated, innerLambdaSymbol.Parameters[0].NullableAnnotation);
Assert.Equal(PublicNullableAnnotation.NotAnnotated, innerLambdaSymbol.Parameters[0].Type.NullableAnnotation);
Assert.Equal(lambdaSymbol, innerLambdaSymbol.ContainingSymbol, SymbolEqualityComparer.IncludeNullability);
var o1Ref = innerLambda.DescendantNodes()
.OfType<AssignmentExpressionSyntax>()
.ElementAt(1)
.DescendantNodes()
.OfType<IdentifierNameSyntax>()
.First(i => i.Identifier.ValueText == "o1");
var o1Symbol = (IParameterSymbol)model.GetSymbolInfo(o1Ref).Symbol;
Assert.Equal(PublicNullableAnnotation.Annotated, o1Symbol.NullableAnnotation);
Assert.Equal(PublicNullableAnnotation.Annotated, o1Symbol.Type.NullableAnnotation);
var o2Ref = innerLambda.DescendantNodes()
.OfType<AssignmentExpressionSyntax>()
.First()
.DescendantNodes()
.OfType<IdentifierNameSyntax>()
.First(i => i.Identifier.ValueText == "o2");
var o2Symbol = (IParameterSymbol)model.GetSymbolInfo(o2Ref).Symbol;
Assert.Equal(PublicNullableAnnotation.NotAnnotated, o2Symbol.NullableAnnotation);
Assert.Equal(PublicNullableAnnotation.NotAnnotated, o2Symbol.Type.NullableAnnotation);
Assert.Equal(innerLambdaSymbol, o2Symbol.ContainingSymbol, SymbolEqualityComparer.IncludeNullability);
}
[Fact(Skip = "https://github.com/dotnet/roslyn/issues/38922")]
public void NestedLambdaReinference_LocalFunctionInLambda()
{
var source = @"
using System;
class C
{
public static Action<T> Create<T>(T t, Action<T> a) => throw null!;
public static void M(object? o)
{
var a = Create(o, o1 => {
LocalFunction(o1);
void LocalFunction(object? o2)
{
_ = o2;
}
});
}
}";
var comp = CreateCompilation(source, options: WithNonNullTypesTrue());
comp.VerifyDiagnostics();
var syntaxTree = comp.SyntaxTrees[0];
var root = syntaxTree.GetRoot();
var model = comp.GetSemanticModel(syntaxTree);
var lambda = root.DescendantNodes().OfType<LambdaExpressionSyntax>().Single();
var lambdaSymbol = (IMethodSymbol)model.GetSymbolInfo(lambda).Symbol;
var localFunction = lambda.DescendantNodes().OfType<LocalFunctionStatementSyntax>().Single();
var localFunctionSymbol = (IMethodSymbol)model.GetDeclaredSymbol(localFunction);
var o2Reference = localFunction.DescendantNodes().OfType<IdentifierNameSyntax>().Single(id => id.Identifier.ValueText == "o2");
var o2Symbol = model.GetSymbolInfo(o2Reference).Symbol;
Assert.Equal(lambdaSymbol, localFunctionSymbol.ContainingSymbol, SymbolEqualityComparer.IncludeNullability);
Assert.Equal(localFunctionSymbol, o2Symbol.ContainingSymbol, SymbolEqualityComparer.IncludeNullability);
}
[Fact, WorkItem(45825, "https://github.com/dotnet/roslyn/issues/45825")]
public void LocalFunctionReturnSpeculation()
{
var comp = CreateCompilation(@"
#nullable enable
class C
{
public static implicit operator C(string s) => null!;
C M()
{
string s = """";
local();
return null!;
string local()
{
s.ToString();
return s;
}
}
}");
comp.VerifyDiagnostics();
var tree = comp.SyntaxTrees[0];
var model = comp.GetSemanticModel(tree);
var localFunctionBody = tree.GetRoot().DescendantNodes().OfType<LocalFunctionStatementSyntax>().Single();
var typeInfo = model.GetTypeInfo(localFunctionBody.DescendantNodes().OfType<ReturnStatementSyntax>().Single().Expression!);
Assert.Equal("System.String!", typeInfo.ConvertedType.ToTestDisplayString(includeNonNullable: true));
var @return = (ReturnStatementSyntax)SyntaxFactory.ParseStatement("return s;");
Assert.True(model.TryGetSpeculativeSemanticModel(localFunctionBody.Body!.OpenBraceToken.SpanStart + 1, @return, out var specModel));
typeInfo = specModel!.GetTypeInfo(@return.Expression!);
// This behavior is broken. The return type here should be 'System.String!' because we are speculating within the local function.
// https://github.com/dotnet/roslyn/issues/45825
Assert.Equal("C!", typeInfo.ConvertedType.ToTestDisplayString(includeNonNullable: true));
}
[Fact, WorkItem(45825, "https://github.com/dotnet/roslyn/issues/45825")]
public void LambdaReturnSpeculation()
{
var comp = CreateCompilation(@"
#nullable enable
class C
{
public static implicit operator C(string s) => null!;
C M()
{
string s = """";
System.Func<string> local = () =>
{
s.ToString();
return s;
};
local();
return null!;
}
}");
comp.VerifyDiagnostics();
var tree = comp.SyntaxTrees[0];
var model = comp.GetSemanticModel(tree);
var localFunctionBody = tree.GetRoot().DescendantNodes().OfType<LambdaExpressionSyntax>().Single();
var typeInfo = model.GetTypeInfo(localFunctionBody.DescendantNodes().OfType<ReturnStatementSyntax>().Single().Expression!);
Assert.Equal("System.String!", typeInfo.ConvertedType.ToTestDisplayString(includeNonNullable: true));
var @return = (ReturnStatementSyntax)SyntaxFactory.ParseStatement("return s;");
Assert.True(model.TryGetSpeculativeSemanticModel(localFunctionBody.Block!.OpenBraceToken.SpanStart + 1, @return, out var specModel));
typeInfo = specModel!.GetTypeInfo(@return.Expression!);
// This behavior is broken. The return type here should be 'System.String!' because we are speculating within the local function.
// https://github.com/dotnet/roslyn/issues/45825
Assert.Equal("C!", typeInfo.ConvertedType.ToTestDisplayString(includeNonNullable: true));
}
[Fact]
public void NestedLambdaReinference_SpeculativeParamReference()
{
var source = @"
using System;
class C
{
public static Action<T> Create<T>(T t, Action<T> a) => throw null!;
public static void M(object? o)
{
var a = Create(o, o1 => { _ = o1.ToString(); });
}
}";
var comp = CreateCompilation(source, options: WithNonNullTypesTrue());
comp.VerifyDiagnostics(
// (9,39): warning CS8602: Dereference of a possibly null reference.
// var a = Create(o, o1 => { _ = o1.ToString(); });
Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "o1").WithLocation(9, 39));
var syntaxTree = comp.SyntaxTrees[0];
var root = syntaxTree.GetRoot();
var model = comp.GetSemanticModel(syntaxTree);
var lambda = root.DescendantNodes().OfType<LambdaExpressionSyntax>().Single();
var o1Ref = lambda.DescendantNodes()
.OfType<AssignmentExpressionSyntax>()
.Single()
.DescendantNodes()
.OfType<IdentifierNameSyntax>()
.First(i => i.Identifier.ValueText == "o1");
var parameterSymbol = (IParameterSymbol)model.GetSymbolInfo(o1Ref).Symbol;
var newStatement = (ExpressionStatementSyntax)SyntaxFactory.ParseStatement("_ = o1;");
var newReference = ((AssignmentExpressionSyntax)newStatement.Expression).Right;
Assert.True(model.TryGetSpeculativeSemanticModel(lambda.Body.SpanStart, newStatement, out var speculativeModel));
var info = speculativeModel.GetSymbolInfo(newReference);
Assert.Equal(parameterSymbol, info.Symbol, SymbolEqualityComparer.IncludeNullability);
}
[Fact]
public void NestedLambdaReinference_GetDeclaredSymbolParameter()
{
var source = @"
using System;
class C
{
public static Action<T> Create<T>(T t, Action<T> a) => throw null!;
public static void M(object? o)
{
var a = Create(o, o1 => { });
}
}";
var comp = CreateCompilation(source, options: WithNonNullTypesTrue());
comp.VerifyDiagnostics();
var syntaxTree = comp.SyntaxTrees[0];
var root = syntaxTree.GetRoot();
var model = comp.GetSemanticModel(syntaxTree);
var lambda = root.DescendantNodes().OfType<LambdaExpressionSyntax>().Single();
var lambdaSymbol = (IMethodSymbol)model.GetSymbolInfo(lambda).Symbol;
var parameter = lambda.DescendantNodes().OfType<ParameterSyntax>().Single();
var paramSymbol = model.GetDeclaredSymbol(parameter);
Assert.Equal(lambdaSymbol, paramSymbol.ContainingSymbol, SymbolEqualityComparer.IncludeNullability);
}
[Fact]
public void NestedLambdaReinference_NestedLocalDeclaration()
{
var source = @"
using System;
class C
{
public static Action<T> Create<T>(T t, Action<T> a) => throw null!;
public static void M(object? o)
{
var a = Create(o, o1 =>
{
var o2 = o1 ?? new object();
Action nested = () => { _ = o2; };
foreach (var o3 in new int[] {}) {}
foreach (var (o4, o5) in new (object, object)[]{}) {}
(var o6, var o7) = (new object(), new object());
void localFunc(out object? o)
{
o = null;
var o8 = new object();
}
});
}
}";
var comp = CreateCompilation(source, options: WithNonNullTypesTrue());
comp.VerifyDiagnostics(
// (18,18): warning CS8321: The local function 'localFunc' is declared but never used
// void localFunc(out object? o)
Diagnostic(ErrorCode.WRN_UnreferencedLocalFunction, "localFunc").WithArguments("localFunc").WithLocation(18, 18));
var syntaxTree = comp.SyntaxTrees[0];
var root = syntaxTree.GetRoot();
var model = comp.GetSemanticModel(syntaxTree);
var lambda = root.DescendantNodes().OfType<LambdaExpressionSyntax>().First();
var lambdaSymbol = model.GetSymbolInfo(lambda).Symbol;
var o2Declaration = lambda.DescendantNodes().OfType<VariableDeclaratorSyntax>().First();
var o2Symbol = model.GetDeclaredSymbol(o2Declaration);
Assert.NotNull(lambdaSymbol);
assertParent(o2Declaration);
var innerLambda = root.DescendantNodes().OfType<LambdaExpressionSyntax>().ElementAt(1);
var innerO2Reference = innerLambda.DescendantNodes().OfType<IdentifierNameSyntax>().Single(id => id.Identifier.ValueText == "o2");
var o2Ref = model.GetSymbolInfo(innerO2Reference);
Assert.Equal(o2Symbol, o2Ref.Symbol, SymbolEqualityComparer.IncludeNullability);
var @foreach = lambda.DescendantNodes().OfType<ForEachStatementSyntax>().Single();
assertParent(@foreach);
foreach (var singleVarDesignation in lambda.DescendantNodes().OfType<SingleVariableDesignationSyntax>())
{
assertParent(singleVarDesignation);
}
var localFunction = lambda.DescendantNodes().OfType<LocalFunctionStatementSyntax>().Single();
var localFunctionSymbol = model.GetDeclaredSymbol(localFunction);
var o8Declaration = localFunction.DescendantNodes().OfType<VariableDeclaratorSyntax>().Single();
Assert.Equal(localFunctionSymbol, model.GetDeclaredSymbol(o8Declaration).ContainingSymbol, SymbolEqualityComparer.IncludeNullability);
void assertParent(SyntaxNode node)
{
Assert.Equal(lambdaSymbol, model.GetDeclaredSymbol(node).ContainingSymbol, SymbolEqualityComparer.IncludeNullability);
}
}
[Fact]
public void NestedLambdaReinference_InInitializers()
{
var source = @"
using System;
class C
{
public static Action<T> Create<T>(T t, Action<T> a) => throw null!;
public static object? s_o = null;
public Action<object> f = Create(s_o ?? new object(), o1 => {
var o2 = o1;
});
public Action<object> Prop { get; } = Create(s_o ?? new object(), o3 => { var o4 = o3; });
}
";
var comp = CreateCompilation(source, options: WithNonNullTypesTrue());
comp.VerifyDiagnostics();
var syntaxTree = comp.SyntaxTrees[0];
var root = syntaxTree.GetRoot();
var model = comp.GetSemanticModel(syntaxTree);
var fieldLambda = root.DescendantNodes().OfType<LambdaExpressionSyntax>().First();
var fieldLambdaSymbol = model.GetSymbolInfo(fieldLambda).Symbol;
var o1Reference = fieldLambda.DescendantNodes().OfType<IdentifierNameSyntax>().Single(id => id.Identifier.ValueText == "o1");
var o1Symbol = (IParameterSymbol)model.GetSymbolInfo(o1Reference).Symbol;
var o2Decl = fieldLambda.DescendantNodes().OfType<VariableDeclaratorSyntax>().Single();
var o2Symbol = (ILocalSymbol)model.GetDeclaredSymbol(o2Decl);
Assert.Equal(PublicNullableAnnotation.NotAnnotated, o1Symbol.NullableAnnotation);
Assert.Equal(PublicNullableAnnotation.NotAnnotated, o1Symbol.Type.NullableAnnotation);
Assert.Equal(PublicNullableAnnotation.Annotated, o2Symbol.NullableAnnotation);
Assert.Equal(PublicNullableAnnotation.Annotated, o2Symbol.Type.NullableAnnotation);
Assert.Equal(fieldLambdaSymbol, o1Symbol.ContainingSymbol, SymbolEqualityComparer.IncludeNullability);
Assert.Equal(fieldLambdaSymbol, o2Symbol.ContainingSymbol, SymbolEqualityComparer.IncludeNullability);
var propertyLambda = root.DescendantNodes().OfType<LambdaExpressionSyntax>().ElementAt(1);
var propertyLambdaSymbol = model.GetSymbolInfo(propertyLambda).Symbol;
var o3Reference = propertyLambda.DescendantNodes().OfType<IdentifierNameSyntax>().Single(id => id.Identifier.ValueText == "o3");
var o3Symbol = (IParameterSymbol)model.GetSymbolInfo(o3Reference).Symbol;
var o4Decl = propertyLambda.DescendantNodes().OfType<VariableDeclaratorSyntax>().Single();
var o4Symbol = (ILocalSymbol)model.GetDeclaredSymbol(o4Decl);
Assert.Equal(PublicNullableAnnotation.NotAnnotated, o3Symbol.NullableAnnotation);
Assert.Equal(PublicNullableAnnotation.NotAnnotated, o3Symbol.Type.NullableAnnotation);
Assert.Equal(PublicNullableAnnotation.Annotated, o4Symbol.NullableAnnotation);
Assert.Equal(PublicNullableAnnotation.Annotated, o4Symbol.Type.NullableAnnotation);
Assert.Equal(propertyLambdaSymbol, o3Symbol.ContainingSymbol, SymbolEqualityComparer.IncludeNullability);
Assert.Equal(propertyLambdaSymbol, o4Symbol.ContainingSymbol, SymbolEqualityComparer.IncludeNullability);
}
[Fact]
public void NestedLambdaReinference_PartialExplicitTypes()
{
var source = @"
using System;
class C
{
public static Action<T> Create<T>(T t, Action<T> a) => throw null!;
public static Action<T> Create<T>(T t, Action<T, T, T> a) => throw null!;
public static void M(object? o)
{
var a = Create(o, o1 => {
if (o1 == null) return;
Create(o1, (o2, object o3, object? o4) => { });
Create(o1, (object o2, object? o3, o4) => { });
});
}
}";
var comp = CreateCompilation(source, options: WithNonNullTypesTrue());
comp.VerifyDiagnostics(
// (12,29): error CS0748: Inconsistent lambda parameter usage; parameter types must be all explicit or all implicit
// Create(o1, (o2, object o3, object? o4) => { });
Diagnostic(ErrorCode.ERR_InconsistentLambdaParameterUsage, "object").WithLocation(12, 29),
// (12,40): error CS0748: Inconsistent lambda parameter usage; parameter types must be all explicit or all implicit
// Create(o1, (o2, object o3, object? o4) => { });
Diagnostic(ErrorCode.ERR_InconsistentLambdaParameterUsage, "object?").WithLocation(12, 40),
// (13,48): error CS0748: Inconsistent lambda parameter usage; parameter types must be all explicit or all implicit
// Create(o1, (object o2, object? o3, o4) => { });
Diagnostic(ErrorCode.ERR_InconsistentLambdaParameterUsage, "o4").WithLocation(13, 48));
var syntaxTree = comp.SyntaxTrees[0];
var root = syntaxTree.GetRoot();
var model = comp.GetSemanticModel(syntaxTree);
var lambda = root.DescendantNodes().OfType<LambdaExpressionSyntax>().First();
var lambdaSymbol = model.GetSymbolInfo(lambda).Symbol;
var innerLambda1 = root.DescendantNodes().OfType<LambdaExpressionSyntax>().ElementAt(1);
var innerLambdaSymbol1 = (IMethodSymbol)model.GetSymbolInfo(innerLambda1).Symbol;
Assert.Equal(lambdaSymbol, innerLambdaSymbol1.ContainingSymbol, SymbolEqualityComparer.IncludeNullability);
Assert.Equal(PublicNullableAnnotation.NotAnnotated, innerLambdaSymbol1.Parameters[0].NullableAnnotation);
Assert.Equal(PublicNullableAnnotation.NotAnnotated, innerLambdaSymbol1.Parameters[0].Type.NullableAnnotation);
Assert.Equal(PublicNullableAnnotation.NotAnnotated, innerLambdaSymbol1.Parameters[1].NullableAnnotation);
Assert.Equal(PublicNullableAnnotation.NotAnnotated, innerLambdaSymbol1.Parameters[1].Type.NullableAnnotation);
Assert.Equal(PublicNullableAnnotation.NotAnnotated, innerLambdaSymbol1.Parameters[2].NullableAnnotation);
Assert.Equal(PublicNullableAnnotation.NotAnnotated, innerLambdaSymbol1.Parameters[2].Type.NullableAnnotation);
var innerLambda2 = root.DescendantNodes().OfType<LambdaExpressionSyntax>().ElementAt(1);
var innerLambdaSymbol2 = (IMethodSymbol)model.GetSymbolInfo(innerLambda2).Symbol;
Assert.Equal(lambdaSymbol, innerLambdaSymbol1.ContainingSymbol, SymbolEqualityComparer.IncludeNullability);
Assert.Equal(PublicNullableAnnotation.NotAnnotated, innerLambdaSymbol2.Parameters[0].NullableAnnotation);
Assert.Equal(PublicNullableAnnotation.NotAnnotated, innerLambdaSymbol2.Parameters[0].Type.NullableAnnotation);
Assert.Equal(PublicNullableAnnotation.NotAnnotated, innerLambdaSymbol2.Parameters[1].NullableAnnotation);
Assert.Equal(PublicNullableAnnotation.NotAnnotated, innerLambdaSymbol2.Parameters[1].Type.NullableAnnotation);
Assert.Equal(PublicNullableAnnotation.NotAnnotated, innerLambdaSymbol2.Parameters[2].NullableAnnotation);
Assert.Equal(PublicNullableAnnotation.NotAnnotated, innerLambdaSymbol2.Parameters[2].Type.NullableAnnotation);
}
[Fact]
public void NestedLambdaReinference_AttributeAndInitializers()
{
var source = @"
using System;
[AttributeUsage(AttributeTargets.All)]
class A : Attribute
{
public A(object a) {}
}
class C
{
public static Action<T> Create<T>(T t, Action<T> a) => throw null!;
public static void M(object? o)
{
var a = Create(o, o1 =>
{
var o2 = o1 ?? new object();
void localFunc([A(o1)] object o3 = o2)
{
o = null;
var o8 = new object();
}
});
}
}";
var comp = CreateCompilation(source, options: WithNonNullTypesTrue(), parseOptions: TestOptions.Regular9);
comp.VerifyDiagnostics(
// (18,18): warning CS8321: The local function 'localFunc' is declared but never used
// void localFunc([A(o1)] object o3 = o2)
Diagnostic(ErrorCode.WRN_UnreferencedLocalFunction, "localFunc").WithArguments("localFunc").WithLocation(18, 18),
// (18,31): error CS0182: An attribute argument must be a constant expression, typeof expression or array creation expression of an attribute parameter type
// void localFunc([A(o1)] object o3 = o2)
Diagnostic(ErrorCode.ERR_BadAttributeArgument, "o1").WithLocation(18, 31),
// (18,48): error CS1736: Default parameter value for 'o3' must be a compile-time constant
// void localFunc([A(o1)] object o3 = o2)
Diagnostic(ErrorCode.ERR_DefaultValueMustBeConstant, "o2").WithArguments("o3").WithLocation(18, 48));
var syntaxTree = comp.SyntaxTrees[0];
var root = syntaxTree.GetRoot();
var model = comp.GetSemanticModel(syntaxTree);
var lambda = root.DescendantNodes().OfType<SimpleLambdaExpressionSyntax>().First();
var o1Decl = lambda.Parameter;
var o1Symbol = model.GetDeclaredSymbol(o1Decl);
var o2Decl = root.DescendantNodes().OfType<VariableDeclaratorSyntax>().ElementAt(1);
var o2Symbol = model.GetDeclaredSymbol(o2Decl);
var o1Ref = root.DescendantNodes().OfType<AttributeArgumentSyntax>().Last().Expression;
var o1RefSymbol = model.GetSymbolInfo(o1Ref).Symbol;
var o2Ref = root.DescendantNodes().OfType<ParameterSyntax>().Last().Default.Value;
var o2RefSymbol = model.GetSymbolInfo(o2Ref).Symbol;
Assert.Equal(o1Symbol, o1RefSymbol, SymbolEqualityComparer.IncludeNullability);
Assert.Equal(o2Symbol, o2RefSymbol, SymbolEqualityComparer.IncludeNullability);
var localFunction = root.DescendantNodes().OfType<LocalFunctionStatementSyntax>().Single();
var speculativeAttribute = SyntaxFactory.Attribute(SyntaxFactory.ParseName("A"), SyntaxFactory.ParseAttributeArgumentList("(o2)"));
var speculativeO2Ref = speculativeAttribute.DescendantNodes().OfType<AttributeArgumentSyntax>().Single().Expression;
Assert.True(model.TryGetSpeculativeSemanticModel(localFunction.SpanStart, speculativeAttribute, out var speculativeModel));
Assert.Equal(o2Symbol, speculativeModel.GetSymbolInfo(speculativeO2Ref).Symbol, SymbolEqualityComparer.IncludeNullability);
var speculativeInitializer = SyntaxFactory.EqualsValueClause(SyntaxFactory.ParseExpression("o1"));
var speculativeO1Ref = speculativeInitializer.Value;
Assert.True(model.TryGetSpeculativeSemanticModel(localFunction.ParameterList.Parameters[0].Default.SpanStart, speculativeInitializer, out speculativeModel));
Assert.Equal(o1Symbol, speculativeModel.GetSymbolInfo(speculativeO1Ref).Symbol, SymbolEqualityComparer.IncludeNullability);
}
[Fact]
public void LookupSymbols_ReinferredSymbols()
{
var source = @"
using System;
class C
{
public static Action<T> Create<T>(T t, Action<T> a) => throw null!;
public static void M(object? o)
{
var a = Create(o, o1 =>
{
var o2 = o1 ?? new object();
Action nested = () => { _ = o2; };
foreach (var o3 in new int[] {}) {}
foreach (var (o4, o5) in new (object, object)[]{}) {}
(var o6, var o7) = (new object(), new object());
void localFunc(out object? o)
{
o = null;
var o8 = new object();
}
});
}
}";
var comp = CreateCompilation(source, options: WithNonNullTypesTrue());
comp.VerifyDiagnostics(
// (18,18): warning CS8321: The local function 'localFunc' is declared but never used
// void localFunc(out object? o)
Diagnostic(ErrorCode.WRN_UnreferencedLocalFunction, "localFunc").WithArguments("localFunc").WithLocation(18, 18));
var syntaxTree = comp.SyntaxTrees[0];
var root = syntaxTree.GetRoot();
var model = comp.GetSemanticModel(syntaxTree);
var lambda = root.DescendantNodes().OfType<LambdaExpressionSyntax>().First();
var lambdaSymbol = model.GetSymbolInfo(lambda).Symbol;
var innerLambda = root.DescendantNodes().OfType<LambdaExpressionSyntax>().ElementAt(1);
var localFunction = lambda.DescendantNodes().OfType<LocalFunctionStatementSyntax>().Single();
var localFunctionSymbol = model.GetDeclaredSymbol(localFunction);
var position = localFunction.DescendantNodes().OfType<VariableDeclarationSyntax>().Single().Span.End;
var lookupResults = model.LookupSymbols(position);
var o2Result = lookupResults.OfType<ILocalSymbol>().First(l => l.Name == "o2");
var o8Result = lookupResults.OfType<ILocalSymbol>().First(l => l.Name == "o8");
Assert.Equal(lambdaSymbol, o2Result.ContainingSymbol, SymbolEqualityComparer.IncludeNullability);
Assert.Equal(localFunctionSymbol, o8Result.ContainingSymbol, SymbolEqualityComparer.IncludeNullability);
var o1Result = lookupResults.OfType<IParameterSymbol>().First(p => p.Name == "o1");
var oResult = lookupResults.OfType<IParameterSymbol>().First(p => p.Name == "o");
Assert.Equal(lambdaSymbol, o1Result.ContainingSymbol, SymbolEqualityComparer.IncludeNullability);
Assert.Equal(localFunctionSymbol, oResult.ContainingSymbol, SymbolEqualityComparer.IncludeNullability);
var localFunctionResult = lookupResults.OfType<IMethodSymbol>().First(m => m.MethodKind == MethodKind.LocalFunction);
Assert.Equal(localFunctionSymbol, localFunctionResult, SymbolEqualityComparer.IncludeNullability);
}
[Fact(Skip = "https://github.com/dotnet/roslyn/issues/38922")]
public void LocalFunction_GenericTypeParameters()
{
var source = @"
using System;
class C
{
public static Action<T> Create<T>(T t, Action<T> a) => throw null!;
public static T[] Create<T>(T t) => throw null!;
public static void M(object? o)
{
var a = Create(o, o1 => {
LocalFunction(o1);
T LocalFunction<T>(T t)
{
_ = Create(t); // Type argument for Create needs to be reparented
var d = new D<T>(); // Type argument in D's substituted type needs to be reparented
d.DoSomething(t); // Argument of the function needs to be reparented
var f = SecondFunction(); // Return type of nested function needs to be reparented
return d.Prop; // Return type needs to be reparented
T SecondFunction() { return t; }
}
});
}
}
class D<T>
{
public void DoSomething(T t) => throw null!;
public T Prop { get; } = default!;
}";
var comp = CreateCompilation(source, options: WithNonNullTypesTrue());
comp.VerifyDiagnostics();
var syntaxTree = comp.SyntaxTrees[0];
var root = syntaxTree.GetRoot();
var model = comp.GetSemanticModel(syntaxTree);
var lambda = root.DescendantNodes().OfType<LambdaExpressionSyntax>().First();
var lambdaSymbol = model.GetSymbolInfo(lambda).Symbol;
var localFunction = lambda.DescendantNodes().OfType<LocalFunctionStatementSyntax>().First();
var localFunctionSymbol = (IMethodSymbol)model.GetDeclaredSymbol(localFunction);
var nestedLocalFunction = (IMethodSymbol)model.GetDeclaredSymbol(lambda.DescendantNodes().OfType<LocalFunctionStatementSyntax>().ElementAt(1));
var typeParameters = localFunctionSymbol.TypeParameters[0];
Assert.Same(localFunctionSymbol, typeParameters.ContainingSymbol);
}
[Fact]
public void SpeculativeModel_InAttribute()
{
var source = @"
using System;
[AttributeUsage(AttributeTargets.ReturnValue)]
class Attr : Attribute
{
public Attr(string Test) {}
}
class Test
{
const string Constant = ""Test"";
[return: Attr(""Test"")]
void M() {}
}
";
var comp = CreateCompilation(source, options: WithNonNullTypesTrue());
var syntaxTree = comp.SyntaxTrees[0];
var root = syntaxTree.GetRoot();
var model = comp.GetSemanticModel(syntaxTree);
var attributeUsage = root.DescendantNodes().OfType<AttributeSyntax>().ElementAt(1);
var newAttributeUsage = SyntaxFactory.Attribute(SyntaxFactory.ParseName("Attr"), SyntaxFactory.ParseAttributeArgumentList("(Constant)"));
Assert.True(model.TryGetSpeculativeSemanticModel(attributeUsage.SpanStart, newAttributeUsage, out var specModel));
Assert.NotNull(specModel);
var symbolInfo = specModel.GetSymbolInfo(newAttributeUsage.ArgumentList.Arguments[0].Expression);
Assert.Equal(SpecialType.System_String, ((IFieldSymbol)symbolInfo.Symbol).Type.SpecialType);
}
[Fact]
public void ParameterDefaultValue()
{
var source = @"
class Test
{
void M0(object obj = default) { } // 1
void M1(int i = default) { }
}
";
var comp = CreateCompilation(source, options: WithNonNullTypesTrue());
comp.VerifyDiagnostics(
// (4,26): warning CS8625: Cannot convert null literal to non-nullable reference type.
// void M0(object obj = default) { } // 1
Diagnostic(ErrorCode.WRN_NullAsNonNullable, "default").WithLocation(4, 26));
var syntaxTree = comp.SyntaxTrees[0];
var root = syntaxTree.GetRoot();
var model = comp.GetSemanticModel(syntaxTree);
var default0 = root.DescendantNodes().OfType<EqualsValueClauseSyntax>().ElementAt(0).Value;
Assert.Equal(PublicNullableFlowState.MaybeNull, model.GetTypeInfo(default0).Nullability.FlowState);
var default1 = root.DescendantNodes().OfType<EqualsValueClauseSyntax>().ElementAt(1).Value;
Assert.Equal(PublicNullableFlowState.NotNull, model.GetTypeInfo(default1).Nullability.FlowState);
}
[Fact]
public void AttributeDefaultValue()
{
var source = @"
using System;
class Attr : Attribute
{
public Attr(object obj, int i) { }
}
[Attr(default, default)] // 1
class Test
{
}
";
var comp = CreateCompilation(source, options: WithNonNullTypesTrue());
comp.VerifyDiagnostics(
// (9,7): warning CS8625: Cannot convert null literal to non-nullable reference type.
// [Attr(default, default)] // 1
Diagnostic(ErrorCode.WRN_NullAsNonNullable, "default").WithLocation(9, 7));
var syntaxTree = comp.SyntaxTrees[0];
var root = syntaxTree.GetRoot();
var model = comp.GetSemanticModel(syntaxTree);
var default0 = root.DescendantNodes().OfType<AttributeArgumentSyntax>().ElementAt(0).Expression;
Assert.Equal(PublicNullableFlowState.MaybeNull, model.GetTypeInfo(default0).Nullability.FlowState);
var default1 = root.DescendantNodes().OfType<AttributeArgumentSyntax>().ElementAt(1).Expression;
Assert.Equal(PublicNullableFlowState.NotNull, model.GetTypeInfo(default1).Nullability.FlowState);
}
[Fact]
[WorkItem(38638, "https://github.com/dotnet/roslyn/issues/38638")]
public void TypeParameter_Default()
{
var source =
@"#nullable enable
abstract class A<T>
{
internal abstract void F<U>() where U : T;
}
class B1<T> : A<T>
{
internal override void F<U>() { _ = default(U); }
}
class B2 : A<int?>
{
internal override void F<U>() { _ = default(U); }
}";
var comp = CreateCompilation(source);
comp.VerifyDiagnostics();
var tree = comp.SyntaxTrees[0];
var model = comp.GetSemanticModel(tree);
var exprs = tree.GetRoot().DescendantNodes().OfType<DefaultExpressionSyntax>().ToArray();
verify(exprs[0], PublicNullableAnnotation.Annotated, PublicNullableFlowState.MaybeNull);
verify(exprs[1], PublicNullableAnnotation.Annotated, PublicNullableFlowState.MaybeNull);
void verify(DefaultExpressionSyntax expr, PublicNullableAnnotation expectedAnnotation, PublicNullableFlowState expectedState)
{
var info = model.GetTypeInfoAndVerifyIOperation(expr).Nullability;
Assert.Equal(expectedAnnotation, info.Annotation);
Assert.Equal(expectedState, info.FlowState);
}
}
[Fact]
[WorkItem(40750, "https://github.com/dotnet/roslyn/issues/40750")]
public void SpeculativeSymbolInfo_OutVariableInDifferentContext_01()
{
var source =
@"#nullable enable
class C
{
void M(out C c2)
{
M(out global::C c);
c2 = c;
}
}";
var comp = CreateCompilation(source);
comp.VerifyDiagnostics();
var tree = comp.SyntaxTrees[0];
var model = comp.GetSemanticModel(tree);
var type = tree.GetRoot().DescendantNodes().OfType<DeclarationExpressionSyntax>().Single().Type;
var statement = SyntaxFactory.ParseStatement(@"M(out C c);");
Assert.True(model.TryGetSpeculativeSemanticModel(type.SpanStart, statement, out var speculativeModel));
var type2 = statement.DescendantNodes().OfType<DeclarationExpressionSyntax>().Single().Type;
var symbol2 = speculativeModel.GetSymbolInfo(type2);
Assert.Equal(PublicNullableAnnotation.NotAnnotated, ((ITypeSymbol)symbol2.Symbol).NullableAnnotation);
}
[Fact]
[WorkItem(40750, "https://github.com/dotnet/roslyn/issues/40750")]
public void SpeculativeSymbolInfo_OutVariableInDifferentContext_02()
{
var source =
@"#nullable disable
class C
{
void M(out C c2)
{
M(out global::C c);
c2 = c;
}
}";
var comp = CreateCompilation(source, options: WithNonNullTypesTrue());
comp.VerifyDiagnostics();
var tree = comp.SyntaxTrees[0];
var model = comp.GetSemanticModel(tree);
var type = tree.GetRoot().DescendantNodes().OfType<DeclarationExpressionSyntax>().Single().Type;
var statement = SyntaxFactory.ParseStatement(@"M(out C c);");
Assert.True(model.TryGetSpeculativeSemanticModel(type.SpanStart, statement, out var speculativeModel));
var type2 = statement.DescendantNodes().OfType<DeclarationExpressionSyntax>().Single().Type;
var symbol2 = speculativeModel.GetSymbolInfo(type2);
Assert.Equal(PublicNullableAnnotation.None, ((ITypeSymbol)symbol2.Symbol).NullableAnnotation);
}
[Fact]
[WorkItem(40750, "https://github.com/dotnet/roslyn/issues/40750")]
public void SpeculativeSymbolInfo_OutVariableInDifferentContext_03()
{
var source =
@"#nullable enable
class C
{
void M(out C c2)
{
M(out global::C c);
c2 = c;
}
}";
var comp = CreateCompilation(source);
comp.VerifyDiagnostics();
var tree = comp.SyntaxTrees[0];
var model = comp.GetSemanticModel(tree);
var type = tree.GetRoot().DescendantNodes().OfType<DeclarationExpressionSyntax>().Single().Type;
var statement = SyntaxFactory.ParseStatement(@"
#nullable disable
M(out C c);");
Assert.True(model.TryGetSpeculativeSemanticModel(type.SpanStart, statement, out var speculativeModel));
var type2 = statement.DescendantNodes().OfType<DeclarationExpressionSyntax>().Single().Type;
var symbol2 = speculativeModel.GetSymbolInfo(type2);
Assert.Equal(PublicNullableAnnotation.None, ((ITypeSymbol)symbol2.Symbol).NullableAnnotation);
}
[Fact]
[WorkItem(40750, "https://github.com/dotnet/roslyn/issues/40750")]
public void SpeculativeSymbolInfo_OutVariableInDifferentContext_04()
{
var source =
@"#nullable disable
class C
{
void M(out C c2)
{
M(out global::C c);
c2 = c;
}
}";
var comp = CreateCompilation(source, options: WithNonNullTypesTrue());
comp.VerifyDiagnostics();
var tree = comp.SyntaxTrees[0];
var model = comp.GetSemanticModel(tree);
var type = tree.GetRoot().DescendantNodes().OfType<DeclarationExpressionSyntax>().Single().Type;
var statement = SyntaxFactory.ParseStatement(@"
#nullable restore
M(out C c);");
Assert.True(model.TryGetSpeculativeSemanticModel(type.SpanStart, statement, out var speculativeModel));
var type2 = statement.DescendantNodes().OfType<DeclarationExpressionSyntax>().Single().Type;
var symbol2 = speculativeModel.GetSymbolInfo(type2);
Assert.Equal(PublicNullableAnnotation.NotAnnotated, ((ITypeSymbol)symbol2.Symbol).NullableAnnotation);
}
[Fact]
[WorkItem(40750, "https://github.com/dotnet/roslyn/issues/40750")]
public void SpeculativeSymbolInfo_OutVariableInDifferentContext_05()
{
var source =
@"#nullable disable annotations
class C
{
void M(out C c2)
{
M(out global::C c);
c2 = c;
}
}";
var comp = CreateCompilation(source, options: WithNonNullTypesTrue());
comp.VerifyDiagnostics();
var tree = comp.SyntaxTrees[0];
var model = comp.GetSemanticModel(tree);
var type = tree.GetRoot().DescendantNodes().OfType<DeclarationExpressionSyntax>().Single().Type;
var statement = SyntaxFactory.ParseStatement(@"
#nullable restore annotations
M(out C c);");
Assert.True(model.TryGetSpeculativeSemanticModel(type.SpanStart, statement, out var speculativeModel));
var type2 = statement.DescendantNodes().OfType<DeclarationExpressionSyntax>().Single().Type;
var symbol2 = speculativeModel.GetSymbolInfo(type2);
Assert.Equal(PublicNullableAnnotation.NotAnnotated, ((ITypeSymbol)symbol2.Symbol).NullableAnnotation);
}
[Fact]
[WorkItem(40750, "https://github.com/dotnet/roslyn/issues/40750")]
public void SpeculativeSymbolInfo_WholeBody_01()
{
var source =
@"#nullable enable
class C
{
void M(out C c2)
{
M(out global::C c);
c2 = c;
}
}";
var comp = CreateCompilation(source, options: WithNonNullTypesFalse());
comp.VerifyDiagnostics();
var tree = comp.SyntaxTrees[0];
var model = comp.GetSemanticModel(tree);
var type = tree.GetRoot().DescendantNodes().OfType<DeclarationExpressionSyntax>().Single().Type;
var methodDeclaration = (MethodDeclarationSyntax)SyntaxFactory.ParseMemberDeclaration(@"
void M2(out C c2)
{
M(out C c);
}");
Assert.True(model.TryGetSpeculativeSemanticModelForMethodBody(type.SpanStart, methodDeclaration, out var speculativeModel));
var type2 = methodDeclaration.DescendantNodes().OfType<DeclarationExpressionSyntax>().Single().Type;
var symbol2 = speculativeModel.GetSymbolInfo(type2);
Assert.Equal(PublicNullableAnnotation.NotAnnotated, ((ITypeSymbol)symbol2.Symbol).NullableAnnotation);
}
[Fact]
[WorkItem(40750, "https://github.com/dotnet/roslyn/issues/40750")]
public void SpeculativeSymbolInfo_WholeBody_02()
{
var source =
@"#nullable enable
class C
{
void M(out C c2)
{
M(out global::C c);
c2 = c;
}
}";
var comp = CreateCompilation(source, options: WithNonNullTypesFalse());
comp.VerifyDiagnostics();
var tree = comp.SyntaxTrees[0];
var model = comp.GetSemanticModel(tree);
var type = tree.GetRoot().DescendantNodes().OfType<DeclarationExpressionSyntax>().Single().Type;
var methodDeclaration = (MethodDeclarationSyntax)SyntaxFactory.ParseMemberDeclaration(@"
void M2(out C c2)
{
#nullable disable
M(out C c);
}");
Assert.True(model.TryGetSpeculativeSemanticModelForMethodBody(type.SpanStart, methodDeclaration, out var speculativeModel));
var type2 = methodDeclaration.DescendantNodes().OfType<DeclarationExpressionSyntax>().Single().Type;
var symbol2 = speculativeModel.GetSymbolInfo(type2);
Assert.Equal(PublicNullableAnnotation.None, ((ITypeSymbol)symbol2.Symbol).NullableAnnotation);
}
[Fact]
[WorkItem(40750, "https://github.com/dotnet/roslyn/issues/40750")]
public void SpeculativeSymbolInfo_ArrowExpression_01()
{
var source =
@"#nullable enable
class C
{
void M(out C c2)
{
M(out global::C c);
c2 = c;
}
}";
var comp = CreateCompilation(source, options: WithNonNullTypesFalse());
comp.VerifyDiagnostics();
var tree = comp.SyntaxTrees[0];
var model = comp.GetSemanticModel(tree);
var type = tree.GetRoot().DescendantNodes().OfType<DeclarationExpressionSyntax>().Single().Type;
var arrow = SyntaxFactory.ArrowExpressionClause(SyntaxFactory.ParseExpression(" M(out C c)"));
Assert.True(model.TryGetSpeculativeSemanticModel(type.SpanStart, arrow, out var speculativeModel));
var type2 = arrow.DescendantNodes().OfType<DeclarationExpressionSyntax>().Single().Type;
var symbol2 = speculativeModel.GetSymbolInfo(type2);
Assert.Equal(PublicNullableAnnotation.NotAnnotated, ((ITypeSymbol)symbol2.Symbol).NullableAnnotation);
}
[Fact]
[WorkItem(40750, "https://github.com/dotnet/roslyn/issues/40750")]
public void SpeculativeSymbolInfo_ArrowExpression_02()
{
var source =
@"#nullable enable
class C
{
void M(out C c2)
{
M(out global::C c);
c2 = c;
}
}";
var comp = CreateCompilation(source, options: WithNonNullTypesFalse());
comp.VerifyDiagnostics();
var tree = comp.SyntaxTrees[0];
var model = comp.GetSemanticModel(tree);
var type = tree.GetRoot().DescendantNodes().OfType<DeclarationExpressionSyntax>().Single().Type;
var arrow = SyntaxFactory.ArrowExpressionClause(SyntaxFactory.ParseExpression(@"
#nullable disable
M(out C c)"));
Assert.True(model.TryGetSpeculativeSemanticModel(type.SpanStart, arrow, out var speculativeModel));
var type2 = arrow.DescendantNodes().OfType<DeclarationExpressionSyntax>().Single().Type;
var symbol2 = speculativeModel.GetSymbolInfo(type2);
Assert.Equal(PublicNullableAnnotation.None, ((ITypeSymbol)symbol2.Symbol).NullableAnnotation);
}
[Fact]
[WorkItem(40750, "https://github.com/dotnet/roslyn/issues/40750")]
public void SpeculativeSymbolInfo_ConstructorInitializer_01()
{
var source =
@"#nullable enable
class C
{
C() : this("""") {}
C(string s) {}
string M(out C c2)
{
M(out global::C c);
c2 = c;
return """";
}
}";
var comp = CreateCompilation(source, options: WithNonNullTypesFalse());
comp.VerifyDiagnostics();
var tree = comp.SyntaxTrees[0];
var model = comp.GetSemanticModel(tree);
var initializer = tree.GetRoot().DescendantNodes().OfType<ConstructorInitializerSyntax>().Single();
var newInitializer = SyntaxFactory.ConstructorInitializer(SyntaxKind.ThisConstructorInitializer, SyntaxFactory.ParseArgumentList(@"(M(out C c))"));
Assert.True(model.TryGetSpeculativeSemanticModel(initializer.SpanStart, newInitializer, out var speculativeModel));
var type2 = newInitializer.DescendantNodes().OfType<DeclarationExpressionSyntax>().Single().Type;
var symbol2 = speculativeModel.GetSymbolInfo(type2);
Assert.Equal(PublicNullableAnnotation.NotAnnotated, ((ITypeSymbol)symbol2.Symbol).NullableAnnotation);
}
[Fact]
[WorkItem(40750, "https://github.com/dotnet/roslyn/issues/40750")]
public void SpeculativeSymbolInfo_ConstructorInitializer_02()
{
var source =
@"#nullable enable
class C
{
C() : this("""") {}
C(string s) {}
string M(out C c2)
{
M(out global::C c);
c2 = c;
return """";
}
}";
var comp = CreateCompilation(source, options: WithNonNullTypesFalse());
comp.VerifyDiagnostics();
var tree = comp.SyntaxTrees[0];
var model = comp.GetSemanticModel(tree);
var initializer = tree.GetRoot().DescendantNodes().OfType<ConstructorInitializerSyntax>().Single();
var newInitializer = SyntaxFactory.ConstructorInitializer(SyntaxKind.ThisConstructorInitializer, SyntaxFactory.ParseArgumentList(@"(
#nullable disable
M(out C c))"));
Assert.True(model.TryGetSpeculativeSemanticModel(initializer.SpanStart, newInitializer, out var speculativeModel));
var type2 = newInitializer.DescendantNodes().OfType<DeclarationExpressionSyntax>().Single().Type;
var symbol2 = speculativeModel.GetSymbolInfo(type2);
Assert.Equal(PublicNullableAnnotation.None, ((ITypeSymbol)symbol2.Symbol).NullableAnnotation);
}
[Fact]
[WorkItem(40750, "https://github.com/dotnet/roslyn/issues/40750"),
WorkItem(39993, "https://github.com/dotnet/roslyn/issues/39993")]
public void SpeculativeSymbolInfo_Expression()
{
var source =
@"#nullable enable
class C
{
void M(out C c2)
{
M(out global::C c);
c2 = c;
}
}";
var comp = CreateCompilation(source, options: WithNonNullTypesFalse());
comp.VerifyDiagnostics();
var tree = comp.SyntaxTrees[0];
var model = comp.GetSemanticModel(tree);
var initializer = tree.GetRoot().DescendantNodes().OfType<DeclarationExpressionSyntax>().Single();
var expression = SyntaxFactory.ParseExpression(@"M(out C c)");
var symbol2 = (IMethodSymbol)model.GetSpeculativeSymbolInfo(initializer.Position, expression, SpeculativeBindingOption.BindAsExpression).Symbol;
Assert.Equal(PublicNullableAnnotation.NotAnnotated, symbol2.Parameters.Single().Type.NullableAnnotation);
}
[Fact]
public void GetOperationOnNullableSuppression()
{
var source = @"
#pragma warning disable CS0219 // Unused local
#nullable enable
class C
{
void M(string p)
{
string l1 = default!;
M(null!);
C c = new C();
string l2 = c.M2()!;
}
string? M2() => null;
}";
var comp = CreateCompilation(source);
comp.VerifyDiagnostics();
var tree = comp.SyntaxTrees[0];
var model = comp.GetSemanticModel(tree);
var suppressions = tree.GetRoot().DescendantNodes().OfType<PostfixUnaryExpressionSyntax>().Where(p => p.IsKind(SyntaxKind.SuppressNullableWarningExpression)).ToList();
Assert.Equal(3, suppressions.Count);
foreach (var s in suppressions)
{
Assert.Null(model.GetOperation(s));
}
}
[Fact]
public void UnconstrainedTypeParameter()
{
var source =
@"#nullable enable
class Program
{
static T F<T>(T t) => t;
static T F1<T>(T? x1)
{
T y1 = F(x1); // 1
if (x1 == null) throw null!;
T z1 = F(x1);
return z1;
}
static T F2<T>(T x2)
{
T y2 = F(x2);
x2 = default; // 2
T z2 = F(x2); // 3
return z2; // 4
}
}";
var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9);
comp.VerifyDiagnostics(
// (7,16): warning CS8600: Converting null literal or possible null value to non-nullable type.
// T y1 = F(x1); // 1
Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "F(x1)").WithLocation(7, 16),
// (15,14): warning CS8600: Converting null literal or possible null value to non-nullable type.
// x2 = default; // 2
Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "default").WithLocation(15, 14),
// (16,16): warning CS8600: Converting null literal or possible null value to non-nullable type.
// T z2 = F(x2); // 3
Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "F(x2)").WithLocation(16, 16),
// (17,16): warning CS8603: Possible null reference return.
// return z2; // 4
Diagnostic(ErrorCode.WRN_NullReferenceReturn, "z2").WithLocation(17, 16));
var syntaxTree = comp.SyntaxTrees[0];
var model = comp.GetSemanticModel(syntaxTree);
var invocations = syntaxTree.GetRoot().DescendantNodes().OfType<InvocationExpressionSyntax>();
var actualAnnotations = invocations.Select(inv => (((IMethodSymbol)model.GetSymbolInfo(inv).Symbol)).TypeArguments[0].NullableAnnotation).ToArray();
var expectedAnnotations = new[]
{
PublicNullableAnnotation.Annotated,
PublicNullableAnnotation.NotAnnotated,
PublicNullableAnnotation.NotAnnotated,
PublicNullableAnnotation.Annotated,
};
AssertEx.Equal(expectedAnnotations, actualAnnotations);
}
[Fact]
public void AutoPropInitializer_01()
{
var source = @"
class C
{
public string Prop { get; set; } = ""a"";
public C()
{
Prop.ToString();
}
public C(string s) : this()
{
Prop.ToString();
}
}
";
var comp = CreateCompilation(source, options: WithNonNullTypesTrue());
comp.VerifyDiagnostics();
var tree = comp.SyntaxTrees.Single();
var model = comp.GetSemanticModel(tree);
var memberAccesses = tree.GetRoot().DescendantNodes().OfType<MemberAccessExpressionSyntax>().ToArray();
Assert.Equal(2, memberAccesses.Length);
var receiver = memberAccesses[0].Expression;
var info = model.GetTypeInfo(receiver);
Assert.Equal(PublicNullableAnnotation.NotAnnotated, info.Type.NullableAnnotation);
Assert.Equal(PublicNullableFlowState.NotNull, info.Nullability.FlowState);
receiver = memberAccesses[1].Expression;
info = model.GetTypeInfo(receiver);
Assert.Equal(PublicNullableAnnotation.NotAnnotated, info.Type.NullableAnnotation);
Assert.Equal(PublicNullableFlowState.NotNull, info.Nullability.FlowState);
}
private class AutoPropInitializer_02_Analyzer : DiagnosticAnalyzer
{
public int HitCount;
private static readonly DiagnosticDescriptor Descriptor =
new DiagnosticDescriptor("XY0000", "Test", "Test", "Test", DiagnosticSeverity.Warning, true, "Test", "Test");
public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics
=> ImmutableArray.Create(Descriptor);
public override void Initialize(AnalysisContext context)
{
context.RegisterSyntaxNodeAction(AnalyzeMemberAccess, SyntaxKind.SimpleMemberAccessExpression);
}
private void AnalyzeMemberAccess(SyntaxNodeAnalysisContext context)
{
var node = (MemberAccessExpressionSyntax)context.Node;
var model = context.SemanticModel;
var info = model.GetTypeInfo(node.Expression);
Assert.Equal(PublicNullableAnnotation.NotAnnotated, info.Nullability.Annotation);
Assert.Equal(PublicNullableFlowState.NotNull, info.Nullability.FlowState);
Interlocked.Increment(ref HitCount);
}
}
[Fact]
public void AutoPropInitializer_02()
{
var source = @"
class C
{
public string Prop { get; set; } = ""a"";
public C()
{
Prop.ToString();
}
public C(string s) : this()
{
Prop.ToString();
}
}
";
var comp = CreateCompilation(source, options: WithNonNullTypesTrue());
comp.VerifyDiagnostics();
var analyzer = new AutoPropInitializer_02_Analyzer();
comp.GetAnalyzerDiagnostics(new[] { analyzer }).Verify();
Assert.Equal(2, analyzer.HitCount);
}
[Fact]
public void AutoPropInitializer_Speculation()
{
var source = @"
class C
{
public string Prop { get; set; } = ""a"";
public C()
{
}
}
";
var comp = CreateCompilation(source, options: WithNonNullTypesTrue());
comp.VerifyDiagnostics();
var tree = comp.SyntaxTrees.Single();
var model = comp.GetSemanticModel(tree);
var ctorDecl = tree.GetRoot()
.DescendantNodes()
.OfType<ConstructorDeclarationSyntax>()
.Single();
var spanStart = ctorDecl
.Body
.OpenBraceToken
.SpanStart;
var newBody = SyntaxFactory.ParseStatement("Prop.ToString();");
Assert.True(model.TryGetSpeculativeSemanticModel(spanStart, newBody, out var speculativeModel));
var newAccess = newBody.DescendantNodes().OfType<MemberAccessExpressionSyntax>().Single();
var typeInfo = speculativeModel.GetTypeInfo(newAccess.Expression);
Assert.Equal(PublicNullableAnnotation.NotAnnotated, typeInfo.Type.NullableAnnotation);
Assert.Equal(PublicNullableFlowState.NotNull, typeInfo.Nullability.FlowState);
}
[Theory, WorkItem(47467, "https://github.com/dotnet/roslyn/issues/47467")]
[InlineData("void M() {}")]
[InlineData(@"void M() {}
M();")]
[InlineData(@"
// Comment
void M() {}
M();")]
public void GetDeclaredSymbolTopLevelStatementsWithLocalFunctionFirst(string code)
{
var comp = CreateCompilation(code, options: TestOptions.ReleaseExe.WithNullableContextOptions(NullableContextOptions.Enable));
var tree = comp.SyntaxTrees[0];
var localFunction = tree.GetRoot().DescendantNodes().OfType<LocalFunctionStatementSyntax>().Single();
var model = comp.GetSemanticModel(tree);
AssertEx.Equal("void M()", model.GetDeclaredSymbol(localFunction).ToTestDisplayString());
}
}
}
| 45.267077 | 343 | 0.624528 | [
"MIT"
] | HeyderElesgerov/roslyn | src/Compilers/CSharp/Test/Symbol/Symbols/Source/NullablePublicAPITests.cs | 220,679 | C# |
using ExcelDataReader;
using Newtonsoft.Json;
using SmICSCoreLib.JSONFileStream;
using SmICSCoreLib.StatistikDataModels;
using System;
using System.Collections;
using System.Data;
using System.IO;
using System.Linq;
using System.Net;
using Microsoft.Extensions.Logging;
namespace SmICSCoreLib.StatistikServices
{
public class RkiService
{
private readonly RestClient _client = new();
private readonly ILogger<RkiService> _logger;
public RkiService(ILogger<RkiService> logger)
{
_logger = logger;
}
//Get Data From RKI REST API
public StateData GetStateData(int blId)
{
try
{
_client.EndPoint = "https://services7.arcgis.com/mOBPykOjAyBO2ZKk/arcgis/rest/services/rki_key_data_hubv/FeatureServer/0/query?where=AdmUnitId ='" + blId +
"'&outFields=AnzFall,AnzTodesfall,AnzFallNeu,AnzTodesfallNeu,Inz7T&outSR=4326&f=json";
string response = _client.GetResponse();
var obj = JsonConvert.DeserializeObject<StateData>(response);
_logger.LogInformation("GetStateData");
return obj;
}
catch (Exception e)
{
_logger.LogWarning("GetStateData " + e.Message);
return null;
}
}
public State GetAllStates()
{
try
{
_client.EndPoint = "https://services7.arcgis.com/mOBPykOjAyBO2ZKk/arcgis/rest/services/Coronaf%C3%A4lle_in_den_Bundesl%C3%A4ndern/FeatureServer/0/query?" +
"where=1=1&outFields=OBJECTID_1, LAN_ew_GEN, LAN_ew_BEZ, LAN_ew_EWZ, Fallzahl, faelle_100000_EW, Death, cases7_bl_per_100k, Aktualisierung&returnGeometry=false&outSR=4326&f=json";
string response = _client.GetResponse();
var obj = JsonConvert.DeserializeObject<State>(response);
_logger.LogInformation("GetAllStates");
return obj;
}
catch (Exception e)
{
_logger.LogWarning("GetAllStates " + e.Message);
return null;
}
}
public State GetStateByName(string bl)
{
try
{
_client.EndPoint = "https://services7.arcgis.com/mOBPykOjAyBO2ZKk/arcgis/rest/services/Coronaf%C3%A4lle_in_den_Bundesl%C3%A4ndern/FeatureServer/0/query?where=LAN_ew_GEN='" +
bl + "'&outFields=OBJECTID_1, LAN_ew_GEN, LAN_ew_BEZ, LAN_ew_EWZ, Fallzahl,cases7_bl, faelle_100000_EW, Death, death7_bl, cases7_bl_per_100k, Aktualisierung&returnGeometry=false&outSR=4326&f=json";
string response = _client.GetResponse();
var obj = JsonConvert.DeserializeObject<State>(response);
_logger.LogInformation("GetStateByName");
return obj;
}
catch (Exception e)
{
_logger.LogWarning("GetStateByName " + e.Message);
return null;
}
}
public District GetDistrictsByStateName(string bl)
{
try
{
_client.EndPoint = "https://services7.arcgis.com/mOBPykOjAyBO2ZKk/arcgis/rest/services/RKI_Landkreisdaten/FeatureServer/0/query?where=BL='" +
bl + "'&outFields=*&outSR=4326&f=json&returnGeometry=false";
string response = _client.GetResponse();
var obj = JsonConvert.DeserializeObject<District>(response);
_logger.LogInformation("GetDistrictsByStateName");
return obj;
}
catch (Exception e)
{
_logger.LogWarning("GetDistrictsByStateName " + e.Message);
return null;
}
}
public District GetDcistrictByName(string gen)
{
try
{
_client.EndPoint = "https://services7.arcgis.com/mOBPykOjAyBO2ZKk/arcgis/rest/services/RKI_Landkreisdaten/FeatureServer/0/query?where=GEN='" +
gen + "'&outFields=*&outSR=4326&f=json&returnGeometry=false";
string response = _client.GetResponse();
var obj = JsonConvert.DeserializeObject<District>(response);
_logger.LogInformation("GetDcistrictByName");
return obj;
}
catch (Exception e)
{
_logger.LogWarning("GetDcistrictByName " + e.Message);
return null;
}
}
public DataSet GetDataSetFromLink(String url)
{
var client = new WebClient();
try
{
var fullPath = Path.GetTempFileName();
client.DownloadFile(url, fullPath);
System.Text.Encoding.RegisterProvider(System.Text.CodePagesEncodingProvider.Instance);
using var stream = File.Open(fullPath, FileMode.Open, FileAccess.Read);
using var reader = ExcelReaderFactory.CreateReader(stream);
var result = reader.AsDataSet();
_logger.LogInformation("GetDataSetFromLink");
return result;
}
catch (Exception e)
{
_logger.LogWarning("GetDataSetFromLink " + e.Message);
return null;
}
}
public DataSet GetCsvDataSet(String url)
{
var client = new WebClient();
try
{
var fullPath = Path.GetTempFileName();
client.DownloadFile(url, fullPath);
System.Text.Encoding.RegisterProvider(System.Text.CodePagesEncodingProvider.Instance);
using var stream = File.Open(fullPath, FileMode.Open, FileAccess.Read);
using var reader = ExcelReaderFactory.CreateCsvReader(stream);
var result = reader.AsDataSet();
_logger.LogInformation("GetCsvDataSet");
return result;
}
catch (Exception e)
{
_logger.LogWarning("GetCsvDataSet " + e.Message);
return null;
}
}
//Get Data From RKI Resources and write it as a DailyReport
public string GetRValue(int vlaue)
{
string rValu;
try
{
string url = "https://raw.githubusercontent.com/robert-koch-institut/SARS-CoV-2-Nowcasting_und_-R-Schaetzung/main/Nowcast_R_aktuell.csv";
var result = GetCsvDataSet(url);
var dataRows = result.Tables[0].Rows;
rValu = result.Tables[0].Rows[dataRows.Count - vlaue][9].ToString();
if (rValu.ElementAt(0) == '.')
{
rValu = rValu.Insert(0, "0");
}
_logger.LogInformation("GetRValue");
return rValu;
}
catch (Exception e)
{
_logger.LogWarning("GetRValue " + e.Message);
return null;
}
}
public Bericht GetBerichtFromUrl(string url)
{
Bericht bericht = new();
var result = GetDataSetFromLink(url);
if (result != null)
{
try
{
ArrayList bundeslaender = new();
ArrayList landkreise = new();
for (int i = 0; i < 16; i++)
{
Bundesland bundesland = new();
BlAttribute attr = new();
string[] bundes = new string[] { "Baden-Württemberg", "Bayern", "Berlin","Brandenburg", "Bremen", "Hamburg",
"Hessen", "Mecklenburg-Vorpommern", "Niedersachsen", "Nordrhein-Westfalen", "Rheinland-Pfalz", "Saarland",
"Sachsen", "Sachsen-Anhalt", "Schleswig-Holstein", "Thüringen"};
attr.Bundesland = bundes[i];
try
{
State state = GetStateByName(attr.Bundesland);
if (state.Features != null)
{
attr.FallzahlGesamt = state.Features[0].Attributes.Fallzahl.ToString("#,##");
attr.Faelle7BL = state.Features[0].Attributes.Cases7_bl.ToString("#,##");
attr.FaellePro100000Ew = state.Features[0].Attributes.FaellePro100000Ew.ToString("#,##");
attr.Todesfaelle = state.Features[0].Attributes.Todesfaelle.ToString("#,##");
attr.Todesfaelle7BL = state.Features[0].Attributes.Death7_bl.ToString("0.##");
attr.Inzidenz7Tage = (state.Features[0].Attributes.Faelle7BlPro100K).ToString("0.##").Replace(",", ".");
attr.Farbe = SetMapColor(attr.Inzidenz7Tage);
District district = GetDistrictsByStateName(attr.Bundesland);
if (district.Features != null && district.Features.Length != 0)
{
landkreise = new ArrayList();
foreach (var lk in district.Features)
{
Landkreis landkreisObj = new();
landkreisObj.LandkreisName = lk.DistrictAttributes.County;
landkreisObj.Stadt = lk.DistrictAttributes.GEN;
landkreisObj.FallzahlGesamt = lk.DistrictAttributes.Cases.ToString("#,##");
landkreisObj.Faelle7Lk = lk.DistrictAttributes.Cases7_lk.ToString("#,##");
landkreisObj.FaellePro100000Ew = lk.DistrictAttributes.Cases_per_100k.ToString("#,##");
landkreisObj.Inzidenz7Tage = lk.DistrictAttributes.Cases7_per_100k.ToString("0.##").Replace(",", ".");
landkreisObj.Todesfaelle = lk.DistrictAttributes.Deaths.ToString("#,##");
landkreisObj.Todesfaelle7Lk = lk.DistrictAttributes.Death7_lk.ToString("0.##");
landkreisObj.AdmUnitId = lk.DistrictAttributes.AdmUnitId;
landkreise.Add(landkreisObj);
}
}
bericht.BlStandAktuell = true;
}
}
catch (Exception)
{
bericht.BlStandAktuell = false;
}
Landkreis[] lkArray = (Landkreis[])landkreise.ToArray(typeof(Landkreis));
bundesland.Landkreise = lkArray;
bundesland.BlAttribute = attr;
bundeslaender.Add(bundesland);
}
Bundesland[] blArray = (Bundesland[])bundeslaender.ToArray(typeof(Bundesland));
bericht.Bundesland = blArray;
StateData stateData = GetStateData(0);
if (stateData != null)
{
try
{
bericht.Fallzahl = stateData.DataFeature[0].DataAttributes.AnzFall.ToString("#,##");
bericht.FallzahlVortag = stateData.DataFeature[0].DataAttributes.AnzFallNeu.ToString("#,##");
bericht.Todesfaelle = stateData.DataFeature[0].DataAttributes.AnzTodesfall.ToString("#,##");
bericht.TodesfaelleVortag = stateData.DataFeature[0].DataAttributes.AnzTodesfallNeu.ToString("#,##");
bericht.Inzidenz7Tage = stateData.DataFeature[0].DataAttributes.Inz7T.ToString();
bericht.Stand = DateTime.Now.Date.ToString("dd.MM.yyyy");
string wert = GetRValue(2);
if (wert == null)
{
bericht.RWert7Tage = ("k.A.");
bericht.RWert7TageVortag = ("k.A.");
}
else
{
bericht.RWert7Tage = GetRValue(2).Replace(",", ".");
bericht.RWert7TageVortag = GetRValue(3).Replace(",", ".");
}
}
catch (Exception)
{
bericht.StandAktuell = true;
return bericht;
}
}
String urlImpfung = "https://www.rki.de/DE/Content/InfAZ/N/Neuartiges_Coronavirus/Daten/Impfquotenmonitoring.xlsx?__blob=publicationFile";
var resultImpfung = GetDataSetFromLink(urlImpfung);
if (resultImpfung != null)
{
try
{
bericht.GesamtImpfung = Convert.ToDouble(resultImpfung.Tables[1].Rows[20][2]).ToString("#,##");
bericht.ErstImpfung = resultImpfung.Tables[1].Rows[20][6].ToString();
bericht.ZweitImpfung = resultImpfung.Tables[1].Rows[20][11].ToString();
bericht.ImpfStatus = true;
}
catch (Exception)
{
_logger.LogWarning("ImpfStatus is false");
bericht.ImpfStatus = false;
}
}
bericht.StandAktuell = true;
_logger.LogInformation("GetBerichtFromUrl");
return bericht;
}
catch (Exception e)
{
_logger.LogWarning("GetBerichtFromUrl " + e.Message);
bericht.StandAktuell = false;
return null;
}
}
else
{
_logger.LogWarning("GetDataSetFromLink Result is null");
return null;
}
}
public bool SerializeRkiData(string path)
{
try
{
if (!Directory.Exists(path))
{
Directory.CreateDirectory(path);
}
string filename = DateTime.Now.ToString("yyyy-MM-dd");
string filePath = path + "/" + filename + ".json";
bool status = false;
string url = "https://www.rki.de/DE/Content/InfAZ/N/Neuartiges_Coronavirus/Daten/Fallzahlen_Kum_Tab.xlsx?__blob=publicationFile";
if (!File.Exists(filePath))
{
DailyReport dailyReport = new();
Bericht bericht = GetBerichtFromUrl(url);
if (bericht != null)
{
dailyReport.Bericht = bericht;
JSONWriter.Write(dailyReport, path, filename);
status = true;
}
else
{
_logger.LogWarning("GetBerichtFromUrl Result is null");
status = false;
}
}
else
{
try
{
DailyReport lastReport = DeserializeRkiData(filePath);
bool standAktuell = lastReport.Bericht.StandAktuell;
string stand = lastReport.Bericht.Stand.Substring(0, 10);
string date = DateTime.Now.ToString("dd.MM.yyyy");
if (standAktuell == false)
{
DailyReport dailyReport = new();
Bericht bericht = GetBerichtFromUrl(url);
if (bericht != null)
{
dailyReport.Bericht = bericht;
JSONWriter.Write(dailyReport, path, filename);
status = true;
}
else
{
_logger.LogWarning("GetBerichtFromUrl Result is null");
status = false;
}
}
else if (stand != date)
{
DailyReport dailyReport = new();
Bericht bericht = GetBerichtFromUrl(url);
dailyReport.Bericht = bericht;
JSONWriter.Write(dailyReport, path, filename);
status = true;
}
else
{
status = true;
}
}
catch (Exception e)
{
_logger.LogWarning("SerializeRkiData " + e.Message);
status = false;
}
}
_logger.LogInformation("SerializeRkiData");
return status;
}
catch (Exception e)
{
_logger.LogWarning("SerializeRkiData " + e.Message);
return false;
}
}
public DailyReport DeserializeRkiData(string path)
{
try
{
DailyReport dailyReport = JSONReader<DailyReport>.ReadObject(path);
_logger.LogInformation("DeserializeRkiData");
return dailyReport;
}
catch (Exception e)
{
_logger.LogWarning("DeserializeRkiData " + e.Message);
return null;
}
}
public string SetMapColor(string inzidenz)
{
string farbe;
try
{
if (inzidenz.Contains("."))
{
int index = inzidenz.IndexOf(".");
if (index == 0)
{
inzidenz = "0";
}
else
{
inzidenz = inzidenz.Substring(0, index);
}
}
int zahl = (int)Convert.ToInt64(Math.Floor(Convert.ToDouble(inzidenz)));
if (zahl >= 100)
{
farbe = "#671212";
return farbe;
}
if (zahl < 100 && zahl >= 75)
{
farbe = "#951214";
return farbe;
}
if (zahl < 75 && zahl >= 50)
{
farbe = "#D43624";
return farbe;
}
if (zahl < 50 && zahl >= 25)
{
farbe = "#FFB534";
return farbe;
}
if (zahl < 25 && zahl >= 5)
{
farbe = "#FFF380";
return farbe;
}
if (zahl < 5 && zahl > 0)
{
farbe = "#FFFCCD";
return farbe;
}
else
{
farbe = "#FFFFFF";
return farbe;
}
}
catch (Exception e)
{
_logger.LogWarning("SetMapColor " + e.Message);
farbe = "#FFFFFF";
return farbe;
}
}
public string SetCaseColor(string tag, string vortag)
{
string color;
if (tag != null && vortag != null)
{
try
{
tag = tag.Replace(".", "").Trim();
vortag = vortag.Replace(".", "").Trim();
double tagToDouble = double.Parse(tag);
double vortagToDouble = double.Parse(vortag);
if (tagToDouble < vortagToDouble)
{
color = "#66C166";
return color;
}
if (tagToDouble == vortagToDouble)
{
color = "#FFC037";
return color;
}
if (tagToDouble > vortagToDouble)
{
color = "#F35C58";
return color;
}
else
{
color = "#8CA2AE";
return color;
}
}
catch (Exception e)
{
_logger.LogWarning("SetCaseColor " + e.Message);
color = "#b0bec5";
return color;
}
}
else
{
color = "#b0bec5";
return color;
}
}
//Get RKI Data from Excel to Json
public Report GetBLReport(string url, int tabelle, int zeileDatum, int zeileFahlahl, int spalte, int laenge)
{
try
{
Report report = new();
var result = GetDataSetFromLink(url);
if (result != null)
{
ArrayList reportArrayList = new();
for (int i = zeileFahlahl; i < 19; i++)
{
BLReport blReportObj = new();
blReportObj.BlName = result.Tables[tabelle].Rows[i][0].ToString();
ArrayList blReportArrayList = new();
for (int y = spalte; y < laenge; y++)
{
BLReportAttribute bLReportObj = new();
bLReportObj.Datum = result.Tables[tabelle].Rows[zeileDatum][y].ToString().Substring(0, 10);
try
{
bLReportObj.Fahlzahl = int.Parse(result.Tables[tabelle].Rows[i][y].ToString());
}
catch (Exception)
{
bLReportObj.Fahlzahl = 0;
}
blReportArrayList.Add(bLReportObj);
}
BLReportAttribute[] blReportAttributeArray = (BLReportAttribute[])blReportArrayList.ToArray(typeof(BLReportAttribute));
blReportObj.BLReportAttribute = blReportAttributeArray;
reportArrayList.Add(blReportObj);
}
BLReport[] blReportArray = (BLReport[])reportArrayList.ToArray(typeof(BLReport));
report.Datum = DateTime.Now.ToString("dd.MM.yyyy");
report.BLReport = blReportArray;
_logger.LogInformation("GetBLReport");
return report;
}
else
{
_logger.LogWarning("GetBLReport Result is null ");
return null;
}
}
catch (Exception e)
{
_logger.LogWarning("GetBLReport " + e.Message);
return null;
}
}
public LKReportJson GetLKReport(string url, int tabelle, int zeileDatum, int zeileFahlahl, int spalte, int laenge)
{
try
{
LKReportJson lkReportJson = new();
var result = GetDataSetFromLink(url);
if (result != null)
{
ArrayList reportArrayList = new();
for (int i = zeileFahlahl; i < 416; i++)
{
LKReport lkReportObj = new();
lkReportObj.LKName = result.Tables[tabelle].Rows[i][1].ToString();
lkReportObj.AdmUnitId = int.Parse(result.Tables[tabelle].Rows[i][2].ToString());
ArrayList blReportArrayList = new();
for (int y = spalte; y < laenge; y++)
{
LKReportAttribute reportAttribute = new();
reportAttribute.Datum = result.Tables[tabelle].Rows[zeileDatum][y].ToString().Substring(0, 10);
if (result.Tables[tabelle].Rows[i][y].ToString() != "")
{
reportAttribute.Fahlzahl = int.Parse(result.Tables[tabelle].Rows[i][y].ToString());
}
else
{
reportAttribute.Fahlzahl = 0;
}
blReportArrayList.Add(reportAttribute);
}
LKReportAttribute[] lkReportAttributeArray = (LKReportAttribute[])blReportArrayList.ToArray(typeof(LKReportAttribute));
lkReportObj.LKReportAttribute = lkReportAttributeArray;
reportArrayList.Add(lkReportObj);
}
LKReport[] blReportArray = (LKReport[])reportArrayList.ToArray(typeof(LKReport));
lkReportJson.Datum = DateTime.Now.ToString("dd.MM.yyyy");
lkReportJson.LKReport = blReportArray;
_logger.LogInformation("GetLKReport");
return lkReportJson;
}
else
{
_logger.LogWarning("GetLKReport Result is null");
return null;
}
}
catch (Exception e)
{
_logger.LogWarning("GetLKReport " + e.Message);
return null;
}
}
public bool BLReportSerialize(string path)
{
Report report = GetBLReport("https://www.rki.de/DE/Content/InfAZ/N/Neuartiges_Coronavirus/Daten/Fallzahlen_Kum_Tab.xlsx?__blob=publicationFile", 2, 2, 3, 1, 547);
try
{
if (!Directory.Exists(path))
{
Directory.CreateDirectory(path);
}
string filename = ("BLReport");
JSONWriter.Write(report, path, filename);
_logger.LogInformation("BLReportSerialize");
return true;
}
catch (Exception e)
{
_logger.LogWarning("BLReportSerialize " + e.Message);
return false;
}
}
public bool LKReportSerialize(string path)
{
LKReportJson lKReportJson = GetLKReport("https://www.rki.de/DE/Content/InfAZ/N/Neuartiges_Coronavirus/Daten/Fallzahlen_Kum_Tab.xlsx?__blob=publicationFile", 4, 4, 5, 3, 353);
try
{
if (!Directory.Exists(path))
{
Directory.CreateDirectory(path);
}
string filename = ("LKReport");
JSONWriter.Write(lKReportJson, path, filename);
_logger.LogInformation("LKReportSerialize");
return true;
}
catch (Exception e)
{
_logger.LogWarning("LKReportSerialize " + e.Message);
return false;
}
}
//Update RKI Data with a CronJob
public Report BLReportDeserialize(string filePath)
{
try
{
Report blReportJson = JSONReader<Report>.ReadObject(filePath);
_logger.LogInformation("BLReportDeserialize");
return blReportJson;
}
catch (Exception e)
{
_logger.LogWarning("BLReportDeserialize " + e.Message);
return null;
}
}
public LKReportJson LKReportDeserialize(string filePath)
{
try
{
LKReportJson lKReportJson = JSONReader<LKReportJson>.ReadObject(filePath);
_logger.LogInformation("LKReportDeserialize");
return lKReportJson;
}
catch (Exception e)
{
_logger.LogWarning("LKReportDeserialize " + e.Message);
return null;
}
}
public bool UpdateBlRkidata(string dailyReportPath, string blReportPath, string targetPath, string filename)
{
try
{
DailyReport dailyReport = DeserializeRkiData(dailyReportPath);
if (dailyReport != null)
{
Bundesland[] bundeslaender = dailyReport.Bericht.Bundesland;
Report report = new();
BLReportAttribute[] bLAttributeObj;
ArrayList reportArrayList = new();
ArrayList blAttributeArrayList = new();
BLReportAttribute[] blReportAttributeArray;
Report blReportJson = BLReportDeserialize(blReportPath);
if (blReportJson != null)
{
int count = 0;
foreach (var bl in blReportJson.BLReport)
{
BLReport blReport = new();
BLReportAttribute bLReportAttributeObj = new();
bLAttributeObj = bl.BLReportAttribute;
blAttributeArrayList = new ArrayList(bLAttributeObj);
bLReportAttributeObj.Datum = DateTime.Now.ToString("dd.MM.yyyy");
bLReportAttributeObj.Fahlzahl = (int)double.Parse(bundeslaender[count].BlAttribute.Faelle7BL);
blAttributeArrayList.Add(bLReportAttributeObj);
blReportAttributeArray = (BLReportAttribute[])blAttributeArrayList.ToArray(typeof(BLReportAttribute));
blReport.BLReportAttribute = blReportAttributeArray;
blReport.BlName = bl.BlName;
reportArrayList.Add(blReport);
count++;
}
BLReport[] blReportArray = (BLReport[])reportArrayList.ToArray(typeof(BLReport));
report.BLReport = blReportArray;
report.Datum = DateTime.Now.ToString("dd.MM.yyyy");
JSONWriter.Write(report, targetPath, filename);
_logger.LogInformation("UpdateBlRkidata");
return true;
}
else
{
_logger.LogWarning("UpdateBlRkidata Result is null ");
return false;
}
}
else
{
_logger.LogWarning("UpdateBlRkidata Result is null");
return false;
}
}
catch (Exception e)
{
_logger.LogWarning("UpdateBlRkidata " + e.Message);
return false;
}
}
public bool UpdateLklRkidata(string dailyReportPath, string lkReportPath, string targetPath, string filename)
{
try
{
DailyReport dailyReport = DeserializeRkiData(dailyReportPath);
if (dailyReport != null)
{
Bundesland[] bundeslaender = dailyReport.Bericht.Bundesland;
ArrayList allLkArrayList = new();
foreach (var blItem in bundeslaender)
{
Landkreis[] lk = blItem.Landkreise;
foreach (var lkItem in lk)
{
allLkArrayList.Add(lkItem);
}
}
Landkreis[] landkreise = (Landkreis[])allLkArrayList.ToArray(typeof(Landkreis));
Landkreis[] landkreiseSort = landkreise.OrderBy(c => c.LandkreisName).ToArray();
LKReportJson report = new();
LKReportAttribute[] lkAttributeObj;
ArrayList reportArrayList = new();
ArrayList lkAttributeArrayList = new();
LKReportAttribute[] lkReportAttributeArray;
LKReportJson lklReportJson = LKReportDeserialize(lkReportPath);
if (lklReportJson != null)
{
foreach (var lk in lklReportJson.LKReport)
{
foreach (var landkreis in landkreiseSort)
{
if (lk.AdmUnitId == landkreis.AdmUnitId)
{
LKReport lkReport = new();
LKReportAttribute lkReportAttributeObj = new();
lkAttributeObj = lk.LKReportAttribute;
lkAttributeArrayList = new ArrayList(lkAttributeObj);
lkReportAttributeObj.Datum = DateTime.Now.ToString("dd.MM.yyyy");
try
{
lkReportAttributeObj.Fahlzahl = (int)double.Parse(landkreis.Faelle7Lk);
}
catch
{
lkReportAttributeObj.Fahlzahl = 0;
}
lkAttributeArrayList.Add(lkReportAttributeObj);
lkReportAttributeArray = (LKReportAttribute[])lkAttributeArrayList.ToArray(typeof(LKReportAttribute));
lkReport.LKReportAttribute = lkReportAttributeArray;
if (lkReport.AdmUnitId == 5358)
{
lkReport.LKName = lk.LKName;
lkReport.AdmUnitId = lk.AdmUnitId;
}
lkReport.LKName = lk.LKName;
lkReport.AdmUnitId = lk.AdmUnitId;
reportArrayList.Add(lkReport);
}
}
}
LKReport[] lkReportArray = (LKReport[])reportArrayList.ToArray(typeof(LKReport));
report.LKReport = lkReportArray;
report.Datum = DateTime.Now.ToString("dd.MM.yyyy");
JSONWriter.Write(report, targetPath, filename);
_logger.LogInformation("UpdateLklRkidata");
return true;
}
else
{
_logger.LogWarning("UpdateLklRkidata Result is null");
return false;
}
}
else
{
_logger.LogWarning("UpdateLklRkidata Result is null");
return false;
}
}
catch (Exception e)
{
_logger.LogWarning("UpdateLklRkidata " + e.Message);
return false;
}
}
}
}
| 41.824601 | 213 | 0.446517 | [
"Apache-2.0"
] | highmed/SmICSCore | SmICSCoreLib/StatistikServices/RkiService.cs | 36,726 | C# |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
using Azure.Core;
using Azure.Core.Pipeline;
using Microsoft.Identity.Client;
using System;
using System.Threading;
using System.Threading.Tasks;
namespace Azure.Identity
{
/// <summary>
/// A <see cref="TokenCredential"/> implementation which launches the system default browser to interactively authenticate a user, and obtain an access token.
/// The browser will only be launched to authenticate the user once, then will silently acquire access tokens through the users refresh token as long as it's valid.
/// </summary>
public class InteractiveBrowserCredential : TokenCredential
{
internal string ClientId { get; }
internal MsalPublicClient Client {get;}
internal CredentialPipeline Pipeline { get; }
internal bool DisableAutomaticAuthentication { get; }
internal AuthenticationRecord Record { get; private set; }
private const string AuthenticationRequiredMessage = "Interactive authentication is needed to acquire token. Call Authenticate to interactively authenticate.";
private const string NoDefaultScopeMessage = "Authenticating in this environment requires specifying a TokenRequestContext.";
/// <summary>
/// Creates a new <see cref="InteractiveBrowserCredential"/> with the specified options, which will authenticate users.
/// </summary>
public InteractiveBrowserCredential()
: this(null, Constants.DeveloperSignOnClientId, null, null)
{
}
/// <summary>
/// Creates a new <see cref="InteractiveBrowserCredential"/> with the specified options, which will authenticate users with the specified application.
/// </summary>
/// <param name="options">The client options for the newly created <see cref="InteractiveBrowserCredential"/>.</param>
public InteractiveBrowserCredential(InteractiveBrowserCredentialOptions options)
: this(options?.TenantId, options?.ClientId ?? Constants.DeveloperSignOnClientId, options, null)
{
DisableAutomaticAuthentication = options?.DisableAutomaticAuthentication ?? false;
Record = options?.AuthenticationRecord;
}
/// <summary>
/// Creates a new <see cref="InteractiveBrowserCredential"/> with the specified options, which will authenticate users with the specified application.
/// </summary>
/// <param name="clientId">The client id of the application to which the users will authenticate</param>
public InteractiveBrowserCredential(string clientId)
: this(null, clientId, null, null)
{
}
/// <summary>
/// Creates a new <see cref="InteractiveBrowserCredential"/> with the specified options, which will authenticate users with the specified application.
/// </summary>
/// <param name="tenantId">The tenant id of the application and the users to authenticate. Can be null in the case of multi-tenant applications.</param>
/// <param name="clientId">The client id of the application to which the users will authenticate</param>
/// TODO: need to link to info on how the application has to be created to authenticate users, for multiple applications
/// <param name="options">The client options for the newly created <see cref="InteractiveBrowserCredential"/>.</param>
public InteractiveBrowserCredential(string tenantId, string clientId, TokenCredentialOptions options = default)
: this(tenantId, clientId, options, null, null)
{
}
internal InteractiveBrowserCredential(string tenantId, string clientId, TokenCredentialOptions options, CredentialPipeline pipeline)
: this(tenantId, clientId, options, pipeline, null)
{
}
internal InteractiveBrowserCredential(string tenantId, string clientId, TokenCredentialOptions options, CredentialPipeline pipeline, MsalPublicClient client)
{
ClientId = clientId ?? throw new ArgumentNullException(nameof(clientId));
Pipeline = pipeline ?? CredentialPipeline.GetInstance(options);
var redirectUrl = (options as InteractiveBrowserCredentialOptions)?.RedirectUri?.AbsoluteUri ?? Constants.DefaultRedirectUrl;
Client = client ?? new MsalPublicClient(Pipeline, tenantId, clientId, redirectUrl, options as ITokenCacheOptions);
}
/// <summary>
/// Interactively authenticates a user via the default browser.
/// </summary>
/// <param name="cancellationToken">A <see cref="CancellationToken"/> controlling the request lifetime.</param>
/// <returns>The result of the authentication request, containing the acquired <see cref="AccessToken"/>, and the <see cref="AuthenticationRecord"/> which can be used to silently authenticate the account.</returns>
public virtual AuthenticationRecord Authenticate(CancellationToken cancellationToken = default)
{
// get the default scope for the authority, throw if no default scope exists
string defaultScope = AzureAuthorityHosts.GetDefaultScope(Pipeline.AuthorityHost) ?? throw new CredentialUnavailableException(NoDefaultScopeMessage);
return Authenticate(new TokenRequestContext(new[] { defaultScope }), cancellationToken);
}
/// <summary>
/// Interactively authenticates a user via the default browser.
/// </summary>
/// <param name="cancellationToken">A <see cref="CancellationToken"/> controlling the request lifetime.</param>
/// <returns>The result of the authentication request, containing the acquired <see cref="AccessToken"/>, and the <see cref="AuthenticationRecord"/> which can be used to silently authenticate the account.</returns>
public virtual async Task<AuthenticationRecord> AuthenticateAsync(CancellationToken cancellationToken = default)
{
// get the default scope for the authority, throw if no default scope exists
string defaultScope = AzureAuthorityHosts.GetDefaultScope(Pipeline.AuthorityHost) ?? throw new CredentialUnavailableException(NoDefaultScopeMessage);
return await AuthenticateAsync(new TokenRequestContext(new string[] { defaultScope }), cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Interactively authenticates a user via the default browser.
/// </summary>
/// <param name="cancellationToken">A <see cref="CancellationToken"/> controlling the request lifetime.</param>
/// <param name="requestContext">The details of the authentication request.</param>
/// <returns>The <see cref="AuthenticationRecord"/> of the authenticated account.</returns>
public virtual AuthenticationRecord Authenticate(TokenRequestContext requestContext, CancellationToken cancellationToken = default)
{
return AuthenticateImplAsync(false, requestContext, cancellationToken).EnsureCompleted();
}
/// <summary>
/// Interactively authenticates a user via the default browser.
/// </summary>
/// <param name="cancellationToken">A <see cref="CancellationToken"/> controlling the request lifetime.</param>
/// <param name="requestContext">The details of the authentication request.</param>
/// <returns>The <see cref="AuthenticationRecord"/> of the authenticated account.</returns>
public virtual async Task<AuthenticationRecord> AuthenticateAsync(TokenRequestContext requestContext, CancellationToken cancellationToken = default)
{
return await AuthenticateImplAsync(true, requestContext, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Obtains an <see cref="AccessToken"/> token for a user account silently if the user has already authenticated, otherwise the default browser is launched to authenticate the user. This method is called automatically by Azure SDK client libraries. You may call this method directly, but you must also handle token caching and token refreshing.
/// </summary>
/// <param name="requestContext">The details of the authentication request.</param>
/// <param name="cancellationToken">A <see cref="CancellationToken"/> controlling the request lifetime.</param>
/// <returns>An <see cref="AccessToken"/> which can be used to authenticate service client calls.</returns>
public override AccessToken GetToken(TokenRequestContext requestContext, CancellationToken cancellationToken = default)
{
return GetTokenImplAsync(false, requestContext, cancellationToken).EnsureCompleted();
}
/// <summary>
/// Obtains an <see cref="AccessToken"/> token for a user account silently if the user has already authenticated, otherwise the default browser is launched to authenticate the user. This method is called automatically by Azure SDK client libraries. You may call this method directly, but you must also handle token caching and token refreshing.
/// </summary>
/// <param name="requestContext">The details of the authentication request.</param>
/// <param name="cancellationToken">A <see cref="CancellationToken"/> controlling the request lifetime.</param>
/// <returns>An <see cref="AccessToken"/> which can be used to authenticate service client calls.</returns>
public override async ValueTask<AccessToken> GetTokenAsync(TokenRequestContext requestContext, CancellationToken cancellationToken = default)
{
return await GetTokenImplAsync(true, requestContext, cancellationToken).ConfigureAwait(false);
}
private async Task<AuthenticationRecord> AuthenticateImplAsync(bool async, TokenRequestContext requestContext, CancellationToken cancellationToken)
{
using CredentialDiagnosticScope scope = Pipeline.StartGetTokenScope($"{nameof(InteractiveBrowserCredential)}.{nameof(Authenticate)}", requestContext);
try
{
scope.Succeeded(await GetTokenViaBrowserLoginAsync(requestContext.Scopes, async, cancellationToken).ConfigureAwait(false));
return Record;
}
catch (Exception e)
{
throw scope.FailWrapAndThrow(e);
}
}
private async ValueTask<AccessToken> GetTokenImplAsync(bool async, TokenRequestContext requestContext, CancellationToken cancellationToken)
{
using CredentialDiagnosticScope scope = Pipeline.StartGetTokenScope($"{nameof(InteractiveBrowserCredential)}.{nameof(GetToken)}", requestContext);
try
{
Exception inner = null;
if (Record != null)
{
try
{
AuthenticationResult result = await Client.AcquireTokenSilentAsync(requestContext.Scopes, (AuthenticationAccount)Record, async, cancellationToken).ConfigureAwait(false);
return scope.Succeeded(new AccessToken(result.AccessToken, result.ExpiresOn));
}
catch (MsalUiRequiredException e)
{
inner = e;
}
}
if (DisableAutomaticAuthentication)
{
throw new AuthenticationRequiredException(AuthenticationRequiredMessage, requestContext, inner);
}
return scope.Succeeded(await GetTokenViaBrowserLoginAsync(requestContext.Scopes, async, cancellationToken).ConfigureAwait(false));
}
catch (Exception e)
{
throw scope.FailWrapAndThrow(e);
}
}
private async Task<AccessToken> GetTokenViaBrowserLoginAsync(string[] scopes, bool async, CancellationToken cancellationToken)
{
AuthenticationResult result = await Client.AcquireTokenInteractiveAsync(scopes, Prompt.SelectAccount, async, cancellationToken).ConfigureAwait(false);
Record = new AuthenticationRecord(result, ClientId);
return new AccessToken(result.AccessToken, result.ExpiresOn);
}
}
}
| 57.253456 | 352 | 0.68915 | [
"MIT"
] | ChrisMissal/azure-sdk-for-net | sdk/identity/Azure.Identity/src/InteractiveBrowserCredential.cs | 12,426 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace VstsRestAPI.Viewmodel.Extractor
{
public class ProjectSetting
{
public string Description { get; set; }
public string Teams { get; set; }
public string SourceCode { get; set; }
public string CreateService { get; set; }
public string BoardColumns { get; set; }
public string ProjectSettings { get; set; }
public string CardStyle { get; set; }
public string CardField { get; set; }
public string PBIfromTemplate { get; set; }
public string BugfromTemplate { get; set; }
public string EpicfromTemplate { get; set; }
public string TaskfromTemplate { get; set; }
public string TestCasefromTemplate { get; set; }
public string FeaturefromTemplate { get; set; }
public string UserStoriesFromTemplate { get; set; }
public string SetEpic { get; set; }
public string BoardRows { get; set; }
public string Widget { get; set; }
public string Chart { get; set; }
public string TeamArea { get; set; }
public string IsPrivate { get; set; }
}
}
| 34.416667 | 59 | 0.635997 | [
"MIT"
] | 12920/AzureDevOpsDemoGenerator | src/VstsRestAPI/Viewmodel/Extractor/ProjectSetting.cs | 1,241 | 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 clouddirectory-2017-01-11.normal.json service model.
*/
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Text;
using System.Xml.Serialization;
using Amazon.CloudDirectory.Model;
using Amazon.Runtime;
using Amazon.Runtime.Internal;
using Amazon.Runtime.Internal.Transform;
using Amazon.Runtime.Internal.Util;
using ThirdParty.Json.LitJson;
namespace Amazon.CloudDirectory.Model.Internal.MarshallTransformations
{
/// <summary>
/// ListAttachedIndices Request Marshaller
/// </summary>
public class ListAttachedIndicesRequestMarshaller : IMarshaller<IRequest, ListAttachedIndicesRequest> , IMarshaller<IRequest,AmazonWebServiceRequest>
{
/// <summary>
/// Marshaller the request object to the HTTP request.
/// </summary>
/// <param name="input"></param>
/// <returns></returns>
public IRequest Marshall(AmazonWebServiceRequest input)
{
return this.Marshall((ListAttachedIndicesRequest)input);
}
/// <summary>
/// Marshaller the request object to the HTTP request.
/// </summary>
/// <param name="publicRequest"></param>
/// <returns></returns>
public IRequest Marshall(ListAttachedIndicesRequest publicRequest)
{
IRequest request = new DefaultRequest(publicRequest, "Amazon.CloudDirectory");
request.Headers["Content-Type"] = "application/x-amz-json-";
request.Headers[Amazon.Util.HeaderKeys.XAmzApiVersion] = "2017-01-11";
request.HttpMethod = "POST";
string uriResourcePath = "/amazonclouddirectory/2017-01-11/object/indices";
request.ResourcePath = uriResourcePath;
using (StringWriter stringWriter = new StringWriter(CultureInfo.InvariantCulture))
{
JsonWriter writer = new JsonWriter(stringWriter);
writer.WriteObjectStart();
var context = new JsonMarshallerContext(request, writer);
if(publicRequest.IsSetMaxResults())
{
context.Writer.WritePropertyName("MaxResults");
context.Writer.Write(publicRequest.MaxResults);
}
if(publicRequest.IsSetNextToken())
{
context.Writer.WritePropertyName("NextToken");
context.Writer.Write(publicRequest.NextToken);
}
if(publicRequest.IsSetTargetReference())
{
context.Writer.WritePropertyName("TargetReference");
context.Writer.WriteObjectStart();
var marshaller = ObjectReferenceMarshaller.Instance;
marshaller.Marshall(publicRequest.TargetReference, context);
context.Writer.WriteObjectEnd();
}
writer.WriteObjectEnd();
string snippet = stringWriter.ToString();
request.Content = System.Text.Encoding.UTF8.GetBytes(snippet);
}
if(publicRequest.IsSetConsistencyLevel())
request.Headers["x-amz-consistency-level"] = publicRequest.ConsistencyLevel;
if(publicRequest.IsSetDirectoryArn())
request.Headers["x-amz-data-partition"] = publicRequest.DirectoryArn;
return request;
}
private static ListAttachedIndicesRequestMarshaller _instance = new ListAttachedIndicesRequestMarshaller();
internal static ListAttachedIndicesRequestMarshaller GetInstance()
{
return _instance;
}
/// <summary>
/// Gets the singleton.
/// </summary>
public static ListAttachedIndicesRequestMarshaller Instance
{
get
{
return _instance;
}
}
}
} | 36.865079 | 153 | 0.623251 | [
"Apache-2.0"
] | Bio2hazard/aws-sdk-net | sdk/src/Services/CloudDirectory/Generated/Model/Internal/MarshallTransformations/ListAttachedIndicesRequestMarshaller.cs | 4,645 | C# |
namespace FaraMedia.FrontEnd.Administration.GridModels.Miscellaneous {
using System.Web.Mvc;
using FaraMedia.Data.Schemas.Layout.Sections;
using FaraMedia.Data.Schemas.Systematic;
using FaraMedia.FrontEnd.Administration.GridModels.Common;
using FaraMedia.FrontEnd.Administration.Models.Systematic;
using FaraMedia.Web.Framework.Mvc.Extensions;
using FaraMedia.Web.Framework.Routing;
public sealed class ActivityModelGrid : EntityModelGridBase<ActivityModel> {
public ActivityModelGrid(HtmlHelper htmlHelper, bool isSelected = true, bool id = true, bool isPublished = true, bool isDeleted = true, bool displayOrder = true, bool createdOn = true, bool lastModifiedOn = true, bool comment = true, bool activityType = true, bool user = true)
: base(htmlHelper, isSelected, false, null, id, isPublished, isDeleted, displayOrder, createdOn, lastModifiedOn) {
if (comment)
Column.For(alm => alm.Comment).Named(htmlHelper.T(ActivityConstants.Fields.Comment.Label));
if (activityType) {
Column.For(alm => htmlHelper.LocalizedRouteLinkWithId(alm.ActivityTypeName, SystematicSectionConstants.ActivityTypesController.Edit.RouteName, alm.ActivityTypeId, null, new {
@class = "btn secondary"
}, null, null, false, null)).Named(htmlHelper.T(ActivityConstants.Fields.Type.Label));
}
if (user) {
Column.For(alm => htmlHelper.LocalizedRouteLinkWithId(alm.UserFullName, SecuritySectionConstants.UsersController.Edit.RouteName, alm.UserId, null, new {
@class = "btn secondary"
}, null, null, false, null)).Named(htmlHelper.T(ActivityConstants.Fields.Activator.Label));
}
}
}
} | 60.133333 | 285 | 0.692905 | [
"MIT"
] | m-sadegh-sh/FaraMedia | src/Presentation/FaraMedia.FrontEnd.Administration/GridModels/System/ActivityLogModelGrid.cs | 1,804 | C# |
// <auto-generated />
using System;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Migrations;
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
using Modix.Data;
using Npgsql.EntityFrameworkCore.PostgreSQL.Metadata;
namespace Modix.Data.Migrations
{
[DbContext(typeof(ModixContext))]
[Migration("20180902092548_Issue100PromotionsRework")]
partial class Issue100PromotionsRework
{
protected override void BuildTargetModel(ModelBuilder modelBuilder)
{
#pragma warning disable 612, 618
modelBuilder
.HasAnnotation("Npgsql:ValueGenerationStrategy", NpgsqlValueGenerationStrategy.SerialColumn)
.HasAnnotation("ProductVersion", "2.1.1-rtm-30846")
.HasAnnotation("Relational:MaxIdentifierLength", 63);
modelBuilder.Entity("Modix.Data.Models.BehaviourConfiguration", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd();
b.Property<string>("Category")
.IsRequired();
b.Property<string>("Key")
.IsRequired();
b.Property<string>("Value")
.IsRequired();
b.HasKey("Id");
b.ToTable("BehaviourConfigurations");
});
modelBuilder.Entity("Modix.Data.Models.Core.ClaimMappingEntity", b =>
{
b.Property<long>("Id")
.ValueGeneratedOnAdd();
b.Property<string>("Claim")
.IsRequired();
b.Property<long>("CreateActionId");
b.Property<long?>("DeleteActionId");
b.Property<long>("GuildId");
b.Property<long?>("RoleId");
b.Property<string>("Type")
.IsRequired();
b.Property<long?>("UserId");
b.HasKey("Id");
b.HasIndex("CreateActionId")
.IsUnique();
b.HasIndex("DeleteActionId")
.IsUnique();
b.ToTable("ClaimMappings");
});
modelBuilder.Entity("Modix.Data.Models.Core.ConfigurationActionEntity", b =>
{
b.Property<long>("Id")
.ValueGeneratedOnAdd();
b.Property<long?>("ClaimMappingId");
b.Property<DateTimeOffset>("Created");
b.Property<long>("CreatedById");
b.Property<long?>("DesignatedChannelMappingId");
b.Property<long?>("DesignatedRoleMappingId");
b.Property<long>("GuildId");
b.Property<string>("Type")
.IsRequired();
b.HasKey("Id");
b.HasIndex("ClaimMappingId");
b.HasIndex("DesignatedChannelMappingId");
b.HasIndex("DesignatedRoleMappingId");
b.HasIndex("GuildId", "CreatedById");
b.ToTable("ConfigurationActions");
});
modelBuilder.Entity("Modix.Data.Models.Core.DesignatedChannelMappingEntity", b =>
{
b.Property<long>("Id")
.ValueGeneratedOnAdd();
b.Property<long>("ChannelId");
b.Property<long>("CreateActionId");
b.Property<long?>("DeleteActionId");
b.Property<long>("GuildId");
b.Property<string>("Type")
.IsRequired();
b.HasKey("Id");
b.HasIndex("ChannelId");
b.HasIndex("CreateActionId")
.IsUnique();
b.HasIndex("DeleteActionId")
.IsUnique();
b.ToTable("DesignatedChannelMappings");
});
modelBuilder.Entity("Modix.Data.Models.Core.DesignatedRoleMappingEntity", b =>
{
b.Property<long>("Id")
.ValueGeneratedOnAdd();
b.Property<long>("CreateActionId");
b.Property<long?>("DeleteActionId");
b.Property<long>("GuildId");
b.Property<long>("RoleId");
b.Property<string>("Type")
.IsRequired();
b.HasKey("Id");
b.HasIndex("CreateActionId")
.IsUnique();
b.HasIndex("DeleteActionId")
.IsUnique();
b.HasIndex("RoleId");
b.ToTable("DesignatedRoleMappings");
});
modelBuilder.Entity("Modix.Data.Models.Core.GuildChannelEntity", b =>
{
b.Property<long>("ChannelId")
.ValueGeneratedOnAdd();
b.Property<long>("GuildId");
b.Property<string>("Name")
.IsRequired();
b.HasKey("ChannelId");
b.ToTable("GuildChannels");
});
modelBuilder.Entity("Modix.Data.Models.Core.GuildRoleEntity", b =>
{
b.Property<long>("RoleId")
.ValueGeneratedOnAdd();
b.Property<long>("GuildId");
b.Property<string>("Name")
.IsRequired();
b.Property<int>("Position");
b.HasKey("RoleId");
b.ToTable("GuildRoles");
});
modelBuilder.Entity("Modix.Data.Models.Core.GuildUserEntity", b =>
{
b.Property<long>("GuildId");
b.Property<long>("UserId");
b.Property<DateTimeOffset>("FirstSeen");
b.Property<DateTimeOffset>("LastSeen");
b.Property<string>("Nickname");
b.HasKey("GuildId", "UserId");
b.HasIndex("UserId");
b.ToTable("GuildUsers");
});
modelBuilder.Entity("Modix.Data.Models.Core.UserEntity", b =>
{
b.Property<long>("Id")
.ValueGeneratedOnAdd();
b.Property<string>("Discriminator")
.IsRequired();
b.Property<string>("Username")
.IsRequired();
b.HasKey("Id");
b.ToTable("Users");
});
modelBuilder.Entity("Modix.Data.Models.Moderation.DeletedMessageEntity", b =>
{
b.Property<long>("MessageId")
.ValueGeneratedOnAdd();
b.Property<long>("AuthorId");
b.Property<long>("ChannelId");
b.Property<string>("Content")
.IsRequired();
b.Property<long>("CreateActionId");
b.Property<long>("GuildId");
b.Property<string>("Reason")
.IsRequired();
b.HasKey("MessageId");
b.HasIndex("ChannelId");
b.HasIndex("CreateActionId");
b.HasIndex("GuildId", "AuthorId");
b.ToTable("DeletedMessages");
});
modelBuilder.Entity("Modix.Data.Models.Moderation.InfractionEntity", b =>
{
b.Property<long>("Id")
.ValueGeneratedOnAdd();
b.Property<long>("CreateActionId");
b.Property<long?>("DeleteActionId");
b.Property<TimeSpan?>("Duration");
b.Property<long>("GuildId");
b.Property<string>("Reason")
.IsRequired();
b.Property<long?>("RescindActionId");
b.Property<long>("SubjectId");
b.Property<string>("Type")
.IsRequired();
b.HasKey("Id");
b.HasIndex("CreateActionId")
.IsUnique();
b.HasIndex("DeleteActionId")
.IsUnique();
b.HasIndex("RescindActionId")
.IsUnique();
b.HasIndex("GuildId", "SubjectId");
b.ToTable("Infractions");
});
modelBuilder.Entity("Modix.Data.Models.Moderation.ModerationActionEntity", b =>
{
b.Property<long>("Id")
.ValueGeneratedOnAdd();
b.Property<DateTimeOffset>("Created");
b.Property<long>("CreatedById");
b.Property<long?>("DeletedMessageId");
b.Property<long>("GuildId");
b.Property<long?>("InfractionId");
b.Property<string>("Type")
.IsRequired();
b.HasKey("Id");
b.HasIndex("DeletedMessageId");
b.HasIndex("InfractionId");
b.HasIndex("GuildId", "CreatedById");
b.ToTable("ModerationActions");
});
modelBuilder.Entity("Modix.Data.Models.Promotions.PromotionActionEntity", b =>
{
b.Property<long>("Id")
.ValueGeneratedOnAdd();
b.Property<long?>("CampaignId");
b.Property<long?>("CommentId");
b.Property<DateTimeOffset>("Created");
b.Property<long>("CreatedById");
b.Property<long>("GuildId");
b.Property<string>("Type")
.IsRequired();
b.HasKey("Id");
b.HasIndex("CampaignId");
b.HasIndex("CommentId");
b.HasIndex("GuildId", "CreatedById");
b.ToTable("PromotionActions");
});
modelBuilder.Entity("Modix.Data.Models.Promotions.PromotionCampaignEntity", b =>
{
b.Property<long>("Id")
.ValueGeneratedOnAdd();
b.Property<long?>("CloseActionId");
b.Property<long>("CreateActionId");
b.Property<long>("GuildId");
b.Property<string>("Outcome");
b.Property<long>("SubjectId");
b.Property<long>("TargetRoleId");
b.HasKey("Id");
b.HasIndex("CloseActionId")
.IsUnique();
b.HasIndex("CreateActionId")
.IsUnique();
b.HasIndex("TargetRoleId");
b.HasIndex("GuildId", "SubjectId");
b.ToTable("PromotionCampaigns");
});
modelBuilder.Entity("Modix.Data.Models.Promotions.PromotionCommentEntity", b =>
{
b.Property<long>("Id")
.ValueGeneratedOnAdd();
b.Property<long>("CampaignId");
b.Property<string>("Content")
.IsRequired();
b.Property<long>("CreateActionId");
b.Property<string>("Sentiment")
.IsRequired();
b.HasKey("Id");
b.HasIndex("CampaignId");
b.HasIndex("CreateActionId")
.IsUnique();
b.ToTable("PromotionComments");
});
modelBuilder.Entity("Modix.Data.Models.Core.ClaimMappingEntity", b =>
{
b.HasOne("Modix.Data.Models.Core.ConfigurationActionEntity", "CreateAction")
.WithOne()
.HasForeignKey("Modix.Data.Models.Core.ClaimMappingEntity", "CreateActionId")
.OnDelete(DeleteBehavior.Cascade);
b.HasOne("Modix.Data.Models.Core.ConfigurationActionEntity", "DeleteAction")
.WithOne()
.HasForeignKey("Modix.Data.Models.Core.ClaimMappingEntity", "DeleteActionId");
});
modelBuilder.Entity("Modix.Data.Models.Core.ConfigurationActionEntity", b =>
{
b.HasOne("Modix.Data.Models.Core.ClaimMappingEntity", "ClaimMapping")
.WithMany()
.HasForeignKey("ClaimMappingId");
b.HasOne("Modix.Data.Models.Core.DesignatedChannelMappingEntity", "DesignatedChannelMapping")
.WithMany()
.HasForeignKey("DesignatedChannelMappingId");
b.HasOne("Modix.Data.Models.Core.DesignatedRoleMappingEntity", "DesignatedRoleMapping")
.WithMany()
.HasForeignKey("DesignatedRoleMappingId");
b.HasOne("Modix.Data.Models.Core.GuildUserEntity", "CreatedBy")
.WithMany()
.HasForeignKey("GuildId", "CreatedById")
.OnDelete(DeleteBehavior.Cascade);
});
modelBuilder.Entity("Modix.Data.Models.Core.DesignatedChannelMappingEntity", b =>
{
b.HasOne("Modix.Data.Models.Core.GuildChannelEntity", "Channel")
.WithMany()
.HasForeignKey("ChannelId")
.OnDelete(DeleteBehavior.Cascade);
b.HasOne("Modix.Data.Models.Core.ConfigurationActionEntity", "CreateAction")
.WithOne()
.HasForeignKey("Modix.Data.Models.Core.DesignatedChannelMappingEntity", "CreateActionId")
.OnDelete(DeleteBehavior.Cascade);
b.HasOne("Modix.Data.Models.Core.ConfigurationActionEntity", "DeleteAction")
.WithOne()
.HasForeignKey("Modix.Data.Models.Core.DesignatedChannelMappingEntity", "DeleteActionId");
});
modelBuilder.Entity("Modix.Data.Models.Core.DesignatedRoleMappingEntity", b =>
{
b.HasOne("Modix.Data.Models.Core.ConfigurationActionEntity", "CreateAction")
.WithOne()
.HasForeignKey("Modix.Data.Models.Core.DesignatedRoleMappingEntity", "CreateActionId")
.OnDelete(DeleteBehavior.Cascade);
b.HasOne("Modix.Data.Models.Core.ConfigurationActionEntity", "DeleteAction")
.WithOne()
.HasForeignKey("Modix.Data.Models.Core.DesignatedRoleMappingEntity", "DeleteActionId");
b.HasOne("Modix.Data.Models.Core.GuildRoleEntity", "Role")
.WithMany()
.HasForeignKey("RoleId")
.OnDelete(DeleteBehavior.Cascade);
});
modelBuilder.Entity("Modix.Data.Models.Core.GuildUserEntity", b =>
{
b.HasOne("Modix.Data.Models.Core.UserEntity", "User")
.WithMany()
.HasForeignKey("UserId")
.OnDelete(DeleteBehavior.Cascade);
});
modelBuilder.Entity("Modix.Data.Models.Moderation.DeletedMessageEntity", b =>
{
b.HasOne("Modix.Data.Models.Core.GuildChannelEntity", "Channel")
.WithMany()
.HasForeignKey("ChannelId")
.OnDelete(DeleteBehavior.Cascade);
b.HasOne("Modix.Data.Models.Moderation.ModerationActionEntity", "CreateAction")
.WithMany()
.HasForeignKey("CreateActionId")
.OnDelete(DeleteBehavior.Cascade);
b.HasOne("Modix.Data.Models.Core.GuildUserEntity", "Author")
.WithMany()
.HasForeignKey("GuildId", "AuthorId")
.OnDelete(DeleteBehavior.Cascade);
});
modelBuilder.Entity("Modix.Data.Models.Moderation.InfractionEntity", b =>
{
b.HasOne("Modix.Data.Models.Moderation.ModerationActionEntity", "CreateAction")
.WithOne()
.HasForeignKey("Modix.Data.Models.Moderation.InfractionEntity", "CreateActionId")
.OnDelete(DeleteBehavior.Cascade);
b.HasOne("Modix.Data.Models.Moderation.ModerationActionEntity", "DeleteAction")
.WithOne()
.HasForeignKey("Modix.Data.Models.Moderation.InfractionEntity", "DeleteActionId");
b.HasOne("Modix.Data.Models.Moderation.ModerationActionEntity", "RescindAction")
.WithOne()
.HasForeignKey("Modix.Data.Models.Moderation.InfractionEntity", "RescindActionId");
b.HasOne("Modix.Data.Models.Core.GuildUserEntity", "Subject")
.WithMany()
.HasForeignKey("GuildId", "SubjectId")
.OnDelete(DeleteBehavior.Cascade);
});
modelBuilder.Entity("Modix.Data.Models.Moderation.ModerationActionEntity", b =>
{
b.HasOne("Modix.Data.Models.Moderation.DeletedMessageEntity", "DeletedMessage")
.WithMany()
.HasForeignKey("DeletedMessageId");
b.HasOne("Modix.Data.Models.Moderation.InfractionEntity", "Infraction")
.WithMany()
.HasForeignKey("InfractionId");
b.HasOne("Modix.Data.Models.Core.GuildUserEntity", "CreatedBy")
.WithMany()
.HasForeignKey("GuildId", "CreatedById")
.OnDelete(DeleteBehavior.Cascade);
});
modelBuilder.Entity("Modix.Data.Models.Promotions.PromotionActionEntity", b =>
{
b.HasOne("Modix.Data.Models.Promotions.PromotionCampaignEntity", "Campaign")
.WithMany()
.HasForeignKey("CampaignId");
b.HasOne("Modix.Data.Models.Promotions.PromotionCommentEntity", "Comment")
.WithMany()
.HasForeignKey("CommentId");
b.HasOne("Modix.Data.Models.Core.GuildUserEntity", "CreatedBy")
.WithMany()
.HasForeignKey("GuildId", "CreatedById")
.OnDelete(DeleteBehavior.Cascade);
});
modelBuilder.Entity("Modix.Data.Models.Promotions.PromotionCampaignEntity", b =>
{
b.HasOne("Modix.Data.Models.Promotions.PromotionActionEntity", "CloseAction")
.WithOne()
.HasForeignKey("Modix.Data.Models.Promotions.PromotionCampaignEntity", "CloseActionId");
b.HasOne("Modix.Data.Models.Promotions.PromotionActionEntity", "CreateAction")
.WithOne()
.HasForeignKey("Modix.Data.Models.Promotions.PromotionCampaignEntity", "CreateActionId")
.OnDelete(DeleteBehavior.Cascade);
b.HasOne("Modix.Data.Models.Core.GuildRoleEntity", "TargetRole")
.WithMany()
.HasForeignKey("TargetRoleId")
.OnDelete(DeleteBehavior.Cascade);
b.HasOne("Modix.Data.Models.Core.GuildUserEntity", "Subject")
.WithMany()
.HasForeignKey("GuildId", "SubjectId")
.OnDelete(DeleteBehavior.Cascade);
});
modelBuilder.Entity("Modix.Data.Models.Promotions.PromotionCommentEntity", b =>
{
b.HasOne("Modix.Data.Models.Promotions.PromotionCampaignEntity", "Campaign")
.WithMany("Comments")
.HasForeignKey("CampaignId")
.OnDelete(DeleteBehavior.Cascade);
b.HasOne("Modix.Data.Models.Promotions.PromotionActionEntity", "CreateAction")
.WithOne()
.HasForeignKey("Modix.Data.Models.Promotions.PromotionCommentEntity", "CreateActionId")
.OnDelete(DeleteBehavior.Cascade);
});
#pragma warning restore 612, 618
}
}
}
| 35.813333 | 114 | 0.473241 | [
"MIT"
] | 333fred/MODiX | Modix.Data/Migrations/20180902092548_Issue100PromotionsRework.Designer.cs | 21,490 | 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 iotsitewise-2019-12-02.normal.json service model.
*/
using System;
using System.Collections.Generic;
using System.Xml.Serialization;
using System.Text;
using System.IO;
using Amazon.Runtime;
using Amazon.Runtime.Internal;
namespace Amazon.IoTSiteWise.Model
{
/// <summary>
/// Contains a timestamp with optional nanosecond granularity.
/// </summary>
public partial class TimeInNanos
{
private int? _offsetInNanos;
private long? _timeInSeconds;
/// <summary>
/// Gets and sets the property OffsetInNanos.
/// <para>
/// The nanosecond offset from <code>timeInSeconds</code>.
/// </para>
/// </summary>
[AWSProperty(Min=0, Max=999999999)]
public int OffsetInNanos
{
get { return this._offsetInNanos.GetValueOrDefault(); }
set { this._offsetInNanos = value; }
}
// Check to see if OffsetInNanos property is set
internal bool IsSetOffsetInNanos()
{
return this._offsetInNanos.HasValue;
}
/// <summary>
/// Gets and sets the property TimeInSeconds.
/// <para>
/// The timestamp date, in seconds, in the Unix epoch format. Fractional nanosecond data
/// is provided by <code>offsetInNanos</code>.
/// </para>
/// </summary>
[AWSProperty(Required=true, Min=1, Max=31556889864403199)]
public long TimeInSeconds
{
get { return this._timeInSeconds.GetValueOrDefault(); }
set { this._timeInSeconds = value; }
}
// Check to see if TimeInSeconds property is set
internal bool IsSetTimeInSeconds()
{
return this._timeInSeconds.HasValue;
}
}
} | 31.24359 | 109 | 0.634797 | [
"Apache-2.0"
] | NGL321/aws-sdk-net | sdk/src/Services/IoTSiteWise/Generated/Model/TimeInNanos.cs | 2,437 | C# |
using System.ComponentModel.DataAnnotations;
using Domain;
namespace DTOs
{
public class ContactEntityDtoCreate
{
[Display(Name = "Contact Name"), Required, MinLength(2)]
public string ContactName { get; set; }
[Display(Name = "First Name"), MinLength(2)]
public string FirstName { get; set; }
[Display(Name = "Last Name"), MinLength(2)]
public string LastName { get; set; }
[Display(Name = "Email"), Required, DataType(DataType.EmailAddress)]
public string Email { get; set; }
[Display(Name = "Phone"), DataType(DataType.PhoneNumber)]
public string Phone { get; set; }
[Display(Name = "Contact Address"), MinLength(2), MaxLength(200)]
public string Address { get; set; }
[Display(Name = "Image")]
public string Image { get; set; } = "Default.png";
[Display(Name = "Is Checked")]
public bool IsChecked { get; set; } = false;
[Display(Name = "Category Name")]
public int ContactEntityCategoryId { get; set; } = (int)ContactCategoryType.Unspecified;
}
}
| 26.022222 | 97 | 0.584116 | [
"MIT"
] | pragmatic-applications/Contact_Book | Lib_Contact_Book_Domain/Contact_Book/DTOs/ContactEntityDtoCreate.cs | 1,173 | C# |
using System;
using System.Collections.Generic;
using System.Text;
using System.Linq;
using System.Runtime.Serialization;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using HuaweiCloud.SDK.Core;
namespace HuaweiCloud.SDK.Eps.v1.Model
{
/// <summary>
/// 企业项目详情
/// </summary>
public class EpDetail
{
/// <summary>
/// 项目类型: - prod:商用项目 - poc:测试项目
/// </summary>
/// <value>项目类型: - prod:商用项目 - poc:测试项目</value>
[JsonConverter(typeof(EnumClassConverter<TypeEnum>))]
public class TypeEnum
{
/// <summary>
/// Enum PROD for value: prod
/// </summary>
public static readonly TypeEnum PROD = new TypeEnum("prod");
/// <summary>
/// Enum POC for value: poc
/// </summary>
public static readonly TypeEnum POC = new TypeEnum("poc");
private static readonly Dictionary<string, TypeEnum> StaticFields =
new Dictionary<string, TypeEnum>()
{
{ "prod", PROD },
{ "poc", POC },
};
private string Value;
public TypeEnum(string value)
{
Value = value;
}
public static TypeEnum FromValue(string value)
{
if(value == null){
return null;
}
if (StaticFields.ContainsKey(value))
{
return StaticFields[value];
}
return null;
}
public string GetValue()
{
return Value;
}
public override string ToString()
{
return $"{Value}";
}
public override int GetHashCode()
{
return this.Value.GetHashCode();
}
public override bool Equals(object obj)
{
if (obj == null)
{
return false;
}
if (ReferenceEquals(this, obj))
{
return true;
}
if (this.Equals(obj as TypeEnum))
{
return true;
}
return false;
}
public bool Equals(TypeEnum obj)
{
if ((object)obj == null)
{
return false;
}
return StringComparer.OrdinalIgnoreCase.Equals(this.Value, obj.Value);
}
public static bool operator ==(TypeEnum a, TypeEnum b)
{
if (System.Object.ReferenceEquals(a, b))
{
return true;
}
if ((object)a == null)
{
return false;
}
return a.Equals(b);
}
public static bool operator !=(TypeEnum a, TypeEnum b)
{
return !(a == b);
}
}
/// <summary>
/// 企业项目ID
/// </summary>
[JsonProperty("id", NullValueHandling = NullValueHandling.Ignore)]
public string Id { get; set; }
/// <summary>
/// 企业项目名称
/// </summary>
[JsonProperty("name", NullValueHandling = NullValueHandling.Ignore)]
public string Name { get; set; }
/// <summary>
/// 企业项目描述
/// </summary>
[JsonProperty("description", NullValueHandling = NullValueHandling.Ignore)]
public string Description { get; set; }
/// <summary>
/// 企业项目状态。1启用,2停用
/// </summary>
[JsonProperty("status", NullValueHandling = NullValueHandling.Ignore)]
public int? Status { get; set; }
/// <summary>
/// 创建时间,格式为UTC格式。如:2018-05-18T06:49:06Z。
/// </summary>
[JsonProperty("created_at", NullValueHandling = NullValueHandling.Ignore)]
public DateTime? CreatedAt { get; set; }
/// <summary>
/// 修改时间,格式为UTC格式。如:2018-05-28T02:21:36Z。
/// </summary>
[JsonProperty("updated_at", NullValueHandling = NullValueHandling.Ignore)]
public DateTime? UpdatedAt { get; set; }
/// <summary>
/// 项目类型: - prod:商用项目 - poc:测试项目
/// </summary>
[JsonProperty("type", NullValueHandling = NullValueHandling.Ignore)]
public TypeEnum Type { get; set; }
/// <summary>
/// Get the string
/// </summary>
public override string ToString()
{
var sb = new StringBuilder();
sb.Append("class EpDetail {\n");
sb.Append(" id: ").Append(Id).Append("\n");
sb.Append(" name: ").Append(Name).Append("\n");
sb.Append(" description: ").Append(Description).Append("\n");
sb.Append(" status: ").Append(Status).Append("\n");
sb.Append(" createdAt: ").Append(CreatedAt).Append("\n");
sb.Append(" updatedAt: ").Append(UpdatedAt).Append("\n");
sb.Append(" type: ").Append(Type).Append("\n");
sb.Append("}\n");
return sb.ToString();
}
/// <summary>
/// Returns true if objects are equal
/// </summary>
public override bool Equals(object input)
{
return this.Equals(input as EpDetail);
}
/// <summary>
/// Returns true if objects are equal
/// </summary>
public bool Equals(EpDetail input)
{
if (input == null)
return false;
return
(
this.Id == input.Id ||
(this.Id != null &&
this.Id.Equals(input.Id))
) &&
(
this.Name == input.Name ||
(this.Name != null &&
this.Name.Equals(input.Name))
) &&
(
this.Description == input.Description ||
(this.Description != null &&
this.Description.Equals(input.Description))
) &&
(
this.Status == input.Status ||
(this.Status != null &&
this.Status.Equals(input.Status))
) &&
(
this.CreatedAt == input.CreatedAt ||
(this.CreatedAt != null &&
this.CreatedAt.Equals(input.CreatedAt))
) &&
(
this.UpdatedAt == input.UpdatedAt ||
(this.UpdatedAt != null &&
this.UpdatedAt.Equals(input.UpdatedAt))
) &&
(
this.Type == input.Type ||
(this.Type != null &&
this.Type.Equals(input.Type))
);
}
/// <summary>
/// Get hash code
/// </summary>
public override int GetHashCode()
{
unchecked // Overflow is fine, just wrap
{
int hashCode = 41;
if (this.Id != null)
hashCode = hashCode * 59 + this.Id.GetHashCode();
if (this.Name != null)
hashCode = hashCode * 59 + this.Name.GetHashCode();
if (this.Description != null)
hashCode = hashCode * 59 + this.Description.GetHashCode();
if (this.Status != null)
hashCode = hashCode * 59 + this.Status.GetHashCode();
if (this.CreatedAt != null)
hashCode = hashCode * 59 + this.CreatedAt.GetHashCode();
if (this.UpdatedAt != null)
hashCode = hashCode * 59 + this.UpdatedAt.GetHashCode();
if (this.Type != null)
hashCode = hashCode * 59 + this.Type.GetHashCode();
return hashCode;
}
}
}
}
| 30.583643 | 86 | 0.443783 | [
"Apache-2.0"
] | cnblogs/huaweicloud-sdk-net-v3 | Services/Eps/v1/Model/EpDetail.cs | 8,441 | C# |
#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
#pragma warning disable
using System;
using System.Collections;
using BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto;
using BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Modes;
using BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Parameters;
using BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities;
namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Macs
{
/// <summary>
/// The GMAC specialisation of Galois/Counter mode (GCM) detailed in NIST Special Publication
/// 800-38D.
/// </summary>
/// <remarks>
/// GMac is an invocation of the GCM mode where no data is encrypted (i.e. all input data to the Mac
/// is processed as additional authenticated data with the underlying GCM block cipher).
/// </remarks>
public class GMac
: IMac
{
private readonly GcmBlockCipher cipher;
private readonly int macSizeBits;
/// <summary>
/// Creates a GMAC based on the operation of a block cipher in GCM mode.
/// </summary>
/// <remarks>
/// This will produce an authentication code the length of the block size of the cipher.
/// </remarks>
/// <param name="cipher">the cipher to be used in GCM mode to generate the MAC.</param>
public GMac(GcmBlockCipher cipher)
: this(cipher, 128)
{
}
/// <summary>
/// Creates a GMAC based on the operation of a 128 bit block cipher in GCM mode.
/// </summary>
/// <remarks>
/// This will produce an authentication code the length of the block size of the cipher.
/// </remarks>
/// <param name="cipher">the cipher to be used in GCM mode to generate the MAC.</param>
/// <param name="macSizeBits">the mac size to generate, in bits. Must be a multiple of 8, between 32 and 128 (inclusive).
/// Sizes less than 96 are not recommended, but are supported for specialized applications.</param>
public GMac(GcmBlockCipher cipher, int macSizeBits)
{
this.cipher = cipher;
this.macSizeBits = macSizeBits;
}
/// <summary>
/// Initialises the GMAC - requires a <see cref="BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Parameters.ParametersWithIV"/>
/// providing a <see cref="BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Parameters.KeyParameter"/> and a nonce.
/// </summary>
public void Init(ICipherParameters parameters)
{
if (parameters is ParametersWithIV)
{
ParametersWithIV param = (ParametersWithIV)parameters;
byte[] iv = param.GetIV();
KeyParameter keyParam = (KeyParameter)param.Parameters;
// GCM is always operated in encrypt mode to calculate MAC
cipher.Init(true, new AeadParameters(keyParam, macSizeBits, iv));
}
else
{
throw new ArgumentException("GMAC requires ParametersWithIV");
}
}
public string AlgorithmName
{
get { return cipher.GetUnderlyingCipher().AlgorithmName + "-GMAC"; }
}
public int GetMacSize()
{
return macSizeBits / 8;
}
public void Update(byte input)
{
cipher.ProcessAadByte(input);
}
public void BlockUpdate(byte[] input, int inOff, int len)
{
cipher.ProcessAadBytes(input, inOff, len);
}
public int DoFinal(byte[] output, int outOff)
{
try
{
return cipher.DoFinal(output, outOff);
}
catch (InvalidCipherTextException e)
{
// Impossible in encrypt mode
throw new InvalidOperationException(e.ToString());
}
}
public void Reset()
{
cipher.Reset();
}
}
}
#pragma warning restore
#endif
| 35.769231 | 137 | 0.583035 | [
"Apache-2.0"
] | Cl0udG0d/Asteroid | Assets/Import/Best HTTP (Pro)/BestHTTP/SecureProtocol/crypto/macs/GMac.cs | 4,185 | C# |
using System.Windows;
using System.Windows.Media;
namespace Std.XpsTools
{
public class Annotation
{
/// <summary>
/// The text to be applied.
/// </summary>
public string Text { get; set; }
/// <summary>
/// Indicates the page number this annotation should be applied to.
/// <c>PageNumber</c> is optional, and if not specified
/// the annotation will be applied to every page in the document.
/// </summary>
public int? PageNumber { get; set; }
/// <summary>
/// The positioning method to use for
/// determining the position of this annotation.
/// </summary>
public PositioningMethod PositionMethod { get; set; }
/// <summary>
/// If <c>LabelRelative</c> positioning is used
/// <c>AnchorLabel</c> identifies the text to
/// use as the basis for anchoring this annotation.
/// </summary>
public string AnchorLabel { get; set; }
/// <summary>
/// If <c>LabelRelative</c> positioning is used
/// <c>MatchMethod</c> identifies the method to use
/// to locate the label text inside a page.
///
/// <c>MatchMethod</c> is optional, and if not specified
/// defaults to <c>ExactMatch</c>.
/// </summary>
public LabelMatchMethod? MatchMethod { get; set; }
/// <summary>
/// Position of the annotation.
/// For <c>LabelRelative</c> anchors the position
/// is relative to the starting position of the label.
/// For <c>Absolute</c> anchors the position
/// is relative to the upper left corner of the page.
/// </summary>
public Point Position { get; set; }
/// <summary>
/// An optional transformation that if provided
/// will be applied to the annotation.
/// </summary>
public Transform CustomTransform { get; set; }
/// <summary>
/// An optional foreground color to be aplied
/// to the annotation text. If not specified the
/// default is Black.
/// </summary>
public Color? ForegroundColor { get; set; }
/// <summary>
/// Size of the annotation text.
///
/// <c>TextSize</c> is specified in units of
/// 1/96 per inch.
/// </summary>
public double TextSize { get; set; }
/// <summary>
/// The font weight of the font used to render
/// the annotation text.
///
/// <c>TextWeight</c> is optional. If not provided
/// the default is <c>FontWeight.Normal</c>.
/// </summary>
public FontWeight? FontWeight { get; set; }
/// <summary>
/// Name of the font used to render
/// the annotation texxt.
///
/// <c>FontName</c> is optional. If not provided
/// the default is Arial.
/// </summary>
public string FontName { get; set; }
/// <summary>
/// Indicates that the annotation text should
/// be rendered italicized.
/// </summary>
public bool IsItalic { get; set; }
}
} | 28.247423 | 69 | 0.639781 | [
"MIT"
] | brunosaboia/xps-tools | XpsTools/Annotation.cs | 2,740 | C# |
using Markdig.Parsers;
using Markdig.Renderers;
using Markdig.Renderers.Html;
using Markdig.Syntax;
using System;
namespace Markdig.Extensions.Toc
{
public class HeadingIdExtension : IMarkdownExtension
{
private static void AddGuidIdAttribute(BlockProcessor blockProcessor, Block block)
{
var attrs = block.GetAttributes();
attrs.Id ??= Guid.NewGuid().ToString().Substring(0, 8);
}
public void Setup(MarkdownPipelineBuilder pipeline)
{
pipeline.BlockParsers.Find<HeadingBlockParser>()!
.Closed += AddGuidIdAttribute;
}
public void Setup(MarkdownPipeline pipeline, IMarkdownRenderer renderer)
{
}
}
}
| 26.428571 | 90 | 0.651351 | [
"MIT"
] | namofun/blogging | src/Markdig/TocExtensions/HeadingId.cs | 742 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace StrikingInvestigation.Utilities
{
public static class ScreenSizing
{
public static double DiameterScale(int browserWidth)
{
if (browserWidth < 576)
{
return 0.4;
}
else if (browserWidth < 768)
{
return 0.55;
}
else if (browserWidth < 992)
{
return 0.7;
}
else if (browserWidth < 1200)
{
return 0.85;
}
else
{
return 1;
}
}
public static double DiameterScaleAV(int browserWidth)
{
if (browserWidth < 576)
{
// *4
return 1.6;
}
else if (browserWidth < 768)
{
// *3.5
return 1.92;
}
else if (browserWidth < 992)
{
// *3
return 2.1;
}
else if (browserWidth < 1200)
{
// *2.5
return 2.12;
}
else
{
// *2
return 2;
}
}
public static double XScale(int browserWidth)
{
if (browserWidth < 576)
{
return 0.11;
}
else if (browserWidth < 768)
{
return 0.16;
}
else if (browserWidth < 992)
{
return 0.22;
}
else if (browserWidth < 1200)
{
return 0.29;
}
else
{
return 0.35;
}
}
public static int XMargin(int browserWidth)
{
if (browserWidth < 576)
{
return 30;
}
else if (browserWidth < 768)
{
return 35;
}
else if (browserWidth < 992)
{
return 42;
}
else if (browserWidth < 1200)
{
return 50;
}
else
{
return 60;
}
}
public static double YScale(int browserWidth)
{
if (browserWidth < 576)
{
return 50;
}
else if (browserWidth < 768)
{
return 58;
}
else if (browserWidth < 992)
{
return 66;
}
else if (browserWidth < 1200)
{
return 74;
}
else
{
return 82;
}
}
public static int YMargin(int browserWidth)
{
if (browserWidth < 576)
{
return 0;
}
else if (browserWidth < 768)
{
return 0;
}
else if (browserWidth < 992)
{
return 0;
}
else if (browserWidth < 1200)
{
return 0;
}
else
{
return 0;
}
}
public static int YMarginB(int browserWidth)
{
double margin;
double tenorDiameter;
margin = (YScale(browserWidth) * 4) + YMargin(browserWidth);
tenorDiameter = Diam.Diameter("T") * DiameterScale(browserWidth);
margin += (tenorDiameter / 2) + 1 + (FontSize(browserWidth) - 2) + FontPaddingTop(browserWidth) + 10 + 45;
return Convert.ToInt32(margin);
}
public static int BorderWidth(int browserWidth)
{
if (browserWidth < 576)
{
return 3;
}
else if (browserWidth < 768)
{
return 4;
}
else if (browserWidth < 992)
{
return 4;
}
else if (browserWidth < 1200)
{
return 5;
}
else
{
return 5;
}
}
public static int BorderWidthAV(int browserWidth)
{
if (browserWidth < 576)
{
return 6;
}
else if (browserWidth < 768)
{
return 6;
}
else if (browserWidth < 992)
{
return 7;
}
else if (browserWidth < 1200)
{
return 7;
}
else
{
return 7;
}
}
public static int FontSize(int browserWidth)
{
if (browserWidth < 576)
{
return 10;
}
else if (browserWidth < 768)
{
return 11;
}
else if (browserWidth < 992)
{
return 12;
}
else if (browserWidth < 1200)
{
return 13;
}
else
{
return 14;
}
}
public static int FontPaddingTop(int browserWidth)
{
// Font padding top is about 25% of font size
if (browserWidth < 576)
{
return 3;
}
else if (browserWidth < 768)
{
return 3;
}
else if (browserWidth < 992)
{
return 3;
}
else if (browserWidth < 1200)
{
return 3;
}
else
{
return 4;
}
}
public static int StrokeLabelXOffset(int browserWidth)
{
if (browserWidth < 576)
{
return -20;
}
else if (browserWidth < 768)
{
return -25;
}
else if (browserWidth < 992)
{
return -30;
}
else if (browserWidth < 1200)
{
return -35;
}
else
{
return -40;
}
}
public static int StrokeLabelYOffset(int browserWidth)
{
// Stroke label is 150% of font size. Fonts have a top padding of about 25% of the font size
// So StrokeLabelYOffset is 50% of (150% of font size) + 25% of (150 % of font size)
// = 112.5% of font size
if (browserWidth < 576)
{
// Font size is 10
return -10;
}
else if (browserWidth < 768)
{
// Font size is 11
return -11;
}
else if (browserWidth < 992)
{
// Font size is 12
return -13;
}
else if (browserWidth < 1200)
{
// Font size is 13
return -14;
}
else
{
// Font size is 14
return -15;
}
}
public static int RowStartLabelWidth(int browserWidth)
{
if (browserWidth < 576)
{
return 3;
}
else if (browserWidth < 768)
{
return 4;
}
else if (browserWidth < 992)
{
return 4;
}
else if (browserWidth < 1200)
{
return 5;
}
else
{
return 5;
}
}
public static int RowStartLabelHeight(int browserWidth)
{
double height;
// Row start label has the same height as the tenor
height = Diam.Diameter("T") * DiameterScale(browserWidth);
return Convert.ToInt32(height);
}
public static int ChangeLabelXOffset(int browserWidth)
{
double offset;
// ChangeLabelXOffset is (RowStartLabelWidth / 2) + 10
offset = (RowStartLabelWidth(browserWidth) / (double)2) + 10;
return Convert.ToInt32(offset);
}
public static int ChangeLabelYOffset(int browserWidth)
{
double offset;
// ChangeLabelYOffset is (50% of YScale) + (50% of font size) + FontPaddingTop
offset = (((YScale(browserWidth) + FontSize(browserWidth)) * 0.5) + FontPaddingTop(browserWidth)) * -1;
return Convert.ToInt32(offset);
}
}
}
| 24.07672 | 118 | 0.370069 | [
"MIT"
] | tjbarnes23/StrikingInvestigation | StrikingInvestigation/Utilities/ScreenSizing.cs | 9,103 | C# |
/*
* System.TimeZoneInfo Android Support
*
* Author(s)
* Jonathan Pryor <jpryor@novell.com>
* The Android Open Source Project
*
* 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.
*/
#if (INSIDE_CORLIB && MONODROID)
using System;
using System.Collections.Generic;
using System.IO;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Text;
namespace System {
partial class TimeZoneInfo {
/*
* Android Timezone support infrastructure.
*
* This is a C# port of org.apache.harmony.luni.internal.util.ZoneInfoDB:
*
* http://android.git.kernel.org/?p=platform/libcore.git;a=blob;f=luni/src/main/java/org/apache/harmony/luni/internal/util/ZoneInfoDB.java;h=3e7bdc3a952b24da535806d434a3a27690feae26;hb=HEAD
*
* From the ZoneInfoDB source:
*
* However, to conserve disk space the data for all time zones are
* concatenated into a single file, and a second file is used to indicate
* the starting position of each time zone record. A third file indicates
* the version of the zoneinfo databse used to generate the data.
*
* which succinctly describes why we can't just use the LIBC implementation in
* TimeZoneInfo.cs -- the "standard Unixy" directory structure is NOT used.
*/
static class ZoneInfoDB {
const int TimeZoneNameLength = 40;
const int TimeZoneIntSize = 4;
static readonly string ZoneDirectoryName = Environment.GetEnvironmentVariable ("ANDROID_ROOT") + "/usr/share/zoneinfo/";
static readonly string ZoneFileName = ZoneDirectoryName + "zoneinfo.dat";
static readonly string IndexFileName = ZoneDirectoryName + "zoneinfo.idx";
const string DefaultVersion = "2007h";
static readonly string VersionFileName = ZoneDirectoryName + "zoneinfo.version";
static readonly object _lock = new object ();
static readonly string version;
static readonly string[] names;
static readonly int[] starts;
static readonly int[] lengths;
static readonly int[] offsets;
static ZoneInfoDB ()
{
try {
version = ReadVersion ();
} catch {
version = DefaultVersion;
}
try {
ReadDatabase (out names, out starts, out lengths, out offsets);
} catch {
names = new string [0];
starts = new int [0];
lengths = new int [0];
offsets = new int [0];
}
}
static string ReadVersion ()
{
using (var file = new StreamReader (VersionFileName, Encoding.GetEncoding ("iso-8859-1"))) {
return file.ReadToEnd ().Trim ();
}
}
static void ReadDatabase (out string[] names, out int[] starts, out int[] lengths, out int[] offsets)
{
using (var file = File.OpenRead (IndexFileName)) {
var nbuf = new byte [TimeZoneNameLength];
int numEntries = (int) (file.Length / (TimeZoneNameLength + 3*TimeZoneIntSize));
char[] namebuf = new char [TimeZoneNameLength];
names = new string [numEntries];
starts = new int [numEntries];
lengths = new int [numEntries];
offsets = new int [numEntries];
for (int i = 0; i < numEntries; ++i) {
Fill (file, nbuf, nbuf.Length);
int namelen;
for (namelen = 0; namelen < nbuf.Length; ++namelen) {
if (nbuf [namelen] == '\0')
break;
namebuf [namelen] = (char) (nbuf [namelen] & 0xFF);
}
names [i] = new string (namebuf, 0, namelen);
starts [i] = ReadInt32 (file, nbuf);
lengths [i] = ReadInt32 (file, nbuf);
offsets [i] = ReadInt32 (file, nbuf);
}
}
}
static void Fill (Stream stream, byte[] nbuf, int required)
{
int read, offset = 0;
while (offset < required && (read = stream.Read (nbuf, offset, required - offset)) > 0)
offset += read;
if (read != required)
throw new EndOfStreamException ("Needed to read " + required + " bytes; read " + read + " bytes");
}
// From java.io.RandomAccessFioe.readInt(), as we need to use the same
// byte ordering as Java uses.
static int ReadInt32 (Stream stream, byte[] nbuf)
{
Fill (stream, nbuf, 4);
return ((nbuf [0] & 0xff) << 24) + ((nbuf [1] & 0xff) << 16) +
((nbuf [2] & 0xff) << 8) + (nbuf [3] & 0xff);
}
internal static string Version {
get {return version;}
}
internal static IEnumerable<string> GetAvailableIds ()
{
return GetAvailableIds (0, false);
}
internal static IEnumerable<string> GetAvailableIds (int rawOffset)
{
return GetAvailableIds (rawOffset, true);
}
static IEnumerable<string> GetAvailableIds (int rawOffset, bool checkOffset)
{
for (int i = 0; i < offsets.Length; ++i) {
if (!checkOffset || offsets [i] == rawOffset)
yield return names [i];
}
}
static TimeZoneInfo _GetTimeZone (string name)
{
int start, length;
using (var stream = GetTimeZoneData (name, out start, out length)) {
if (stream == null)
return null;
byte[] buf = new byte [length];
Fill (stream, buf, buf.Length);
return TimeZoneInfo.ParseTZBuffer (name, buf, length);
}
}
static FileStream GetTimeZoneData (string name, out int start, out int length)
{
var f = new FileInfo (Path.Combine (ZoneDirectoryName, name));
if (f.Exists) {
start = 0;
length = (int) f.Length;
return f.OpenRead ();
}
start = length = 0;
int i = Array.BinarySearch (names, name, StringComparer.Ordinal);
if (i < 0)
return null;
start = starts [i];
length = lengths [i];
var stream = File.OpenRead (ZoneFileName);
stream.Seek (start, SeekOrigin.Begin);
return stream;
}
internal static TimeZoneInfo GetTimeZone (string id)
{
if (id != null) {
if (id == "GMT" || id == "UTC")
return new TimeZoneInfo (id, TimeSpan.FromSeconds (0), id, id, id, null, true);
if (id.StartsWith ("GMT"))
return new TimeZoneInfo (id,
TimeSpan.FromSeconds (ParseNumericZone (id)),
id, id, id, null, true);
}
try {
return _GetTimeZone (id);
} catch (Exception e) {
return null;
}
}
static int ParseNumericZone (string name)
{
if (name == null || !name.StartsWith ("GMT") || name.Length <= 3)
return 0;
int sign;
if (name [3] == '+')
sign = 1;
else if (name [3] == '-')
sign = -1;
else
return 0;
int where;
int hour = 0;
bool colon = false;
for (where = 4; where < name.Length; where++) {
char c = name [where];
if (c == ':') {
where++;
colon = true;
break;
}
if (c >= '0' && c <= '9')
hour = hour * 10 + c - '0';
else
return 0;
}
int min = 0;
for (; where < name.Length; where++) {
char c = name [where];
if (c >= '0' && c <= '9')
min = min * 10 + c - '0';
else
return 0;
}
if (colon)
return sign * (hour * 60 + min) * 60;
else if (hour >= 100)
return sign * ((hour / 100) * 60 + (hour % 100)) * 60;
else
return sign * (hour * 60) * 60;
}
static TimeZoneInfo defaultZone;
internal static TimeZoneInfo Default {
get {
lock (_lock) {
if (defaultZone != null)
return defaultZone;
return defaultZone = GetTimeZone (GetDefaultTimeZoneName ());
}
}
}
// <sys/system_properties.h>
[DllImport ("/system/lib/libc.so")]
static extern int __system_property_get (string name, StringBuilder value);
const int MaxPropertyNameLength = 32; // <sys/system_properties.h>
const int MaxPropertyValueLength = 92; // <sys/system_properties.h>
static string GetDefaultTimeZoneName ()
{
var buf = new StringBuilder (MaxPropertyValueLength + 1);
int n = __system_property_get ("persist.sys.timezone", buf);
if (n > 0)
return buf.ToString ();
return null;
}
#if SELF_TEST
/*
* Compile:
* mcs /out:tzi.exe "/d:INSIDE_CORLIB;MONODROID;NET_4_0;LIBC;SELF_TEST" System/TimeZone*.cs ../../build/common/Consts.cs
* Prep:
* mkdir -p usr/share/zoneinfo
* android_root=`adb shell echo '$ANDROID_ROOT' | tr -d "\r"`
* adb pull $android_root/usr/share/zoneinfo usr/share/zoneinfo
* Run:
* ANDROID_ROOT=`pwd` mono tzi.exe
*/
static void Main (string[] args)
{
Console.WriteLine ("Version: {0}", version);
for (int i = 0; i < names.Length; ++i) {
Console.Write ("{0,3}\tname={1,-40} start={2,-10} length={3,-4} offset=0x{4,8}",
i, names [i], starts [i], lengths [i], offsets [i].ToString ("x8"));
try {
TimeZoneInfo zone = _GetTimeZone (names [i]);
if (zone != null)
Console.Write (" {0}", zone);
else {
Console.Write (" ERROR:null Index? {0}",
Array.BinarySearch (names, names [i], StringComparer.Ordinal));
}
} catch (Exception e) {
Console.WriteLine ();
Console.Write ("ERROR: {0}", e);
}
Console.WriteLine ();
}
}
#endif
}
}
}
#endif // MONODROID
| 28.565868 | 194 | 0.612724 | [
"Apache-2.0"
] | drewgreenwell/playscript-mono | mcs/class/System.Core/System/TimeZoneInfo.Android.cs | 9,541 | C# |
using System;
using System.Buffers;
using System.ComponentModel;
using System.Diagnostics;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
namespace DotNext.Buffers
{
/// <summary>
/// Represents unified representation of the memory rented using various
/// types of memory pools.
/// </summary>
/// <typeparam name="T">The type of the items in the memory pool.</typeparam>
[StructLayout(LayoutKind.Auto)]
public struct MemoryOwner<T> : IMemoryOwner<T>, ISupplier<Memory<T>>
{
// Of type ArrayPool<T> or IMemoryOwner<T>.
// If support of another type is needed then reconsider implementation
// of Memory, this[nint index] and Expand members
private readonly object? owner;
private readonly T[]? array; // not null only if owner is ArrayPool or null
private int length;
private MemoryOwner(IMemoryOwner<T> owner, int? length)
{
this.owner = owner;
this.length = length ?? owner.Memory.Length;
array = null;
}
internal MemoryOwner(ArrayPool<T>? pool, T[] array, int length)
{
Debug.Assert(array.Length >= length);
this.array = array;
owner = pool;
this.length = length;
}
internal MemoryOwner(ArrayPool<T> pool, int length, bool exactSize)
{
array = pool.Rent(length);
owner = pool;
this.length = exactSize ? length : array.Length;
}
/// <summary>
/// Rents the array from the pool.
/// </summary>
/// <param name="pool">The array pool.</param>
/// <param name="length">The length of the array.</param>
public MemoryOwner(ArrayPool<T> pool, int length)
: this(pool, length, true)
{
}
/// <summary>
/// Rents the memory from the pool.
/// </summary>
/// <param name="pool">The memory pool.</param>
/// <param name="length">The number of elements to rent; or <c>-1</c> to rent default amount of memory.</param>
public MemoryOwner(MemoryPool<T> pool, int length = -1)
{
array = null;
IMemoryOwner<T> owner;
this.owner = owner = pool.Rent(length);
this.length = length < 0 ? owner.Memory.Length : length;
}
/// <summary>
/// Retns the memory.
/// </summary>
/// <param name="provider">The memory provider.</param>
/// <param name="length">The number of elements to rent.</param>
public MemoryOwner(Func<int, IMemoryOwner<T>> provider, int length)
{
array = null;
IMemoryOwner<T> owner;
this.owner = owner = provider(length);
this.length = Math.Min(owner.Memory.Length, length);
}
/// <summary>
/// Rents the memory.
/// </summary>
/// <param name="provider">The memory provider.</param>
public MemoryOwner(Func<IMemoryOwner<T>> provider)
{
array = null;
IMemoryOwner<T> owner;
this.owner = owner = provider();
length = owner.Memory.Length;
}
/// <summary>
/// Wraps the array as if it was rented.
/// </summary>
/// <param name="array">The array to wrap.</param>
/// <param name="length">The length of the array.</param>
/// <exception cref="ArgumentOutOfRangeException"><paramref name="length"/> is less than 0 or greater than the length of <paramref name="array"/>.</exception>
public MemoryOwner(T[] array, int length)
{
if (length > array.Length || length < 0)
throw new ArgumentOutOfRangeException(nameof(length));
this.array = array;
this.length = length;
owner = null;
}
/// <summary>
/// Wraps the array as if it was rented.
/// </summary>
/// <param name="array">The array to wrap.</param>
public MemoryOwner(T[] array)
: this(array, array.Length)
{
}
/// <summary>
/// Rents the memory block and wrap it to the <see cref="MemoryOwner{T}"/> type.
/// </summary>
/// <typeparam name="TArg">The type of the argument to be passed to the provider.</typeparam>
/// <param name="provider">The provider that allows to rent the memory.</param>
/// <param name="length">The length of the memory block to rent.</param>
/// <param name="arg">The argument to be passed to the provider.</param>
/// <param name="exactSize">
/// <see langword="true"/> to preserve the requested length;
/// <see langword="false"/> to use actual length of the rented memory block.
/// </param>
/// <returns>Rented memory block.</returns>
/// <exception cref="ArgumentNullException"><paramref name="provider"/> is zero pointer.</exception>
[CLSCompliant(false)]
[EditorBrowsable(EditorBrowsableState.Advanced)]
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static unsafe MemoryOwner<T> Create<TArg>(delegate*<int, TArg, IMemoryOwner<T>> provider, int length, TArg arg, bool exactSize = true)
{
if (provider == null)
throw new ArgumentNullException(nameof(provider));
return new(provider(length, arg), exactSize ? length : null);
}
/// <summary>
/// Gets numbers of elements in the rented memory block.
/// </summary>
public readonly int Length => length;
internal void Expand() => length = RawLength;
[MethodImpl(MethodImplOptions.AggressiveInlining)]
internal void Truncate(int newLength)
{
Debug.Assert(newLength > 0);
Debug.Assert(newLength <= RawLength);
length = Math.Min(length, newLength);
}
private readonly int RawLength
{
get
{
int result;
if (array is not null)
result = array.Length;
else if (owner is not null)
result = Unsafe.As<IMemoryOwner<T>>(owner).Memory.Length;
else
result = 0;
return result;
}
}
/// <summary>
/// Attempts to resize this buffer without reallocation.
/// </summary>
/// <remarks>
/// This method always return <see langword="true"/> if <paramref name="newLength"/> is less than
/// or equal to <see cref="Length"/>.
/// </remarks>
/// <param name="newLength">The requested length of this buffer.</param>
/// <returns><see langword="true"/> if this buffer is resized successfully; otherwise, <see langword="false"/>.</returns>
/// <exception cref="ArgumentOutOfRangeException"><paramref name="newLength"/> is less than zero.</exception>
public bool TryResize(int newLength)
{
if (newLength < 0)
throw new ArgumentOutOfRangeException(nameof(newLength));
var result = true;
var rawLength = RawLength;
if (newLength == 0)
{
Dispose();
}
else if(rawLength == 0 || newLength > rawLength)
{
result = false;
}
else if (newLength < rawLength)
{
length = newLength;
}
return result;
}
/// <summary>
/// Determines whether this memory is empty.
/// </summary>
public readonly bool IsEmpty => length == 0;
/// <summary>
/// Gets the memory belonging to this owner.
/// </summary>
/// <value>The memory belonging to this owner.</value>
public readonly Memory<T> Memory
{
get
{
Memory<T> result;
if (array is not null)
result = new(array);
else if (owner is not null)
result = Unsafe.As<IMemoryOwner<T>>(owner).Memory;
else
result = default;
return result.Slice(0, length);
}
}
/// <summary>
/// Tries to get an array segment from the underlying memory buffer.
/// </summary>
/// <param name="segment">The array segment retrieved from the underlying memory buffer.</param>
/// <returns><see langword="true"/> if the method call succeeds; <see langword="false"/> otherwise.</returns>
public readonly bool TryGetArray(out ArraySegment<T> segment)
{
if (array is not null)
{
segment = new(array, 0, length);
return true;
}
if (owner is not null)
return MemoryMarshal.TryGetArray(Unsafe.As<IMemoryOwner<T>>(owner).Memory, out segment);
segment = default;
return false;
}
/// <inheritdoc/>
readonly Memory<T> ISupplier<Memory<T>>.Invoke() => Memory;
internal readonly ref T First
{
[MethodImpl(MethodImplOptions.AggressiveInlining)]
get
{
if (array is not null)
#if NETSTANDARD2_1
return ref array[0];
#else
return ref MemoryMarshal.GetArrayDataReference(array);
#endif
if (owner is not null)
return ref MemoryMarshal.GetReference(Unsafe.As<IMemoryOwner<T>>(owner).Memory.Span);
return ref Unsafe.NullRef<T>();
}
}
/// <summary>
/// Gets managed pointer to the item in the rented memory.
/// </summary>
/// <param name="index">The index of the element in memory.</param>
/// <value>The managed pointer to the item.</value>
/// <exception cref="ArgumentOutOfRangeException"><paramref name="index"/> is invalid.</exception>
public readonly ref T this[nint index]
{
get
{
if (index < 0 || index >= length)
throw new ArgumentOutOfRangeException(nameof(index));
Debug.Assert(owner is not null || array is not null);
return ref Unsafe.Add(ref First, index);
}
}
/// <summary>
/// Gets managed pointer to the item in the rented memory.
/// </summary>
/// <param name="index">The index of the element in memory.</param>
/// <value>The managed pointer to the item.</value>
/// <exception cref="ArgumentOutOfRangeException"><paramref name="index"/> is invalid.</exception>
public readonly ref T this[int index] => ref this[(nint)index];
internal void Clear(bool clearBuffer)
{
switch (owner)
{
case IDisposable disposable:
disposable.Dispose();
break;
case ArrayPool<T> pool:
Debug.Assert(array is not null);
pool.Return(array, clearBuffer);
break;
}
this = default;
}
/// <summary>
/// Releases rented memory.
/// </summary>
public void Dispose() => Clear(RuntimeHelpers.IsReferenceOrContainsReferences<T>());
}
} | 35.894737 | 166 | 0.541314 | [
"MIT"
] | NanoFabricFX/dotNext | src/DotNext/Buffers/MemoryOwner.cs | 11,594 | C# |
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
// Runtime Version:4.0.30319.42000
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
using System;
using System.Reflection;
[assembly: System.Reflection.AssemblyCompanyAttribute("NetCore.PDF.to.PNG.Single.Example")]
[assembly: System.Reflection.AssemblyConfigurationAttribute("Debug")]
[assembly: System.Reflection.AssemblyFileVersionAttribute("1.0.0.0")]
[assembly: System.Reflection.AssemblyInformationalVersionAttribute("1.0.0")]
[assembly: System.Reflection.AssemblyProductAttribute("NetCore.PDF.to.PNG.Single.Example")]
[assembly: System.Reflection.AssemblyTitleAttribute("NetCore.PDF.to.PNG.Single.Example")]
[assembly: System.Reflection.AssemblyVersionAttribute("1.0.0.0")]
// Generated by the MSBuild WriteCodeFragment class.
| 43.708333 | 91 | 0.655863 | [
"Apache-2.0"
] | Cloudmersive/NetCore.PDF.to.PNG.Single.Example | NetCore.PDF.to.PNG.Single.Example/NetCore.PDF.to.PNG.Single.Example/obj/Debug/netcoreapp3.1/NetCore.PDF.to.PNG.Single.Example.AssemblyInfo.cs | 1,049 | C# |
namespace ToNote.Controls
{
using System;
using System.Collections.Specialized;
using System.IO;
using System.Linq;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Threading;
using ToNote.Interfaces;
using ToNote.Logic;
using ToNote.Models;
using ToNote.ViewModels;
public class NotePanel : ItemsControl
{
public NotePanel()
{
// CTRL + Plus or CTRL + Minus Down navigates to an item that is above or below currently focused one, respectively.
this.PreviewKeyDown += (s, e) =>
{
if ((e.Key == Key.Subtract || e.Key == Key.OemMinus) && Keyboard.Modifiers == ModifierKeys.Control)
SwitchKeyboardFocusToNextETBC(this.Items.IndexOf(lastFocused));
if ((e.Key == Key.Add || e.Key == Key.OemPlus) && Keyboard.Modifiers == ModifierKeys.Control)
SwitchKeyboardFocusToNextETBC(this.Items.IndexOf(lastFocused), false);
};
// Tracks if new items have been added to the panel. If they were IExtendedTextBoxControls, sets up appropriate events.
((INotifyCollectionChanged)this.Items).CollectionChanged += (s, e) =>
{
if (e.NewItems == null) return;
foreach (var item in e.NewItems.OfType<IExtendedTextBoxControl>())
ConfigureExtendedTextBoxControlEvents(item);
};
Status = "No changes.";
dt = new DispatcherTimer();
dt.Tick += (o, a) =>
{
if (_unsavedChanges)
{
SaveContentsToFilesCommand.Execute(this);
Status = "Last autosaved at " + DateTime.Now.ToString("HH:mm:ss");
}
dt.Stop();
};
dt.Interval = new TimeSpan(0, 0, 5);
dt.Start();
}
private IExtendedTextBoxControl lastFocused;
private DispatcherTimer dt;
private bool _unsavedChanges = false;
public Note Note
{
get => (Note)GetValue(NoteProperty);
set => SetValue(NoteProperty, value);
}
public static readonly DependencyProperty StatusProperty = DependencyProperty.Register("Status",
typeof(string), typeof(NotePanel), new FrameworkPropertyMetadata(null));
public string Status
{
get => (string)GetValue(StatusProperty);
set => SetValue(StatusProperty, value);
}
public static readonly DependencyProperty MainWindowProperty = DependencyProperty.Register("MainWindow",
typeof(Window), typeof(NotePanel), new FrameworkPropertyMetadata(null) { PropertyChangedCallback = (s, e) =>
{
if (!(e.NewValue is Window window)) return;
var panel = (NotePanel)s;
window.Closing += (o, a) =>
{
if (((MainViewModel)window.DataContext).Notes.Contains(panel.Note))
panel.SaveContentsToFilesCommand.Execute(panel);
};
}
});
public Window MainWindow
{
get => (Window)GetValue(MainWindowProperty);
set => SetValue(MainWindowProperty, value);
}
// On a new value bound to Note, generates textboxes for each file or Todo the note has and fills them with their respective contents.
public static readonly DependencyProperty NoteProperty = DependencyProperty.Register("Note",
typeof(Note), typeof(NotePanel), new FrameworkPropertyMetadata(null)
{
PropertyChangedCallback = (s, e) =>
{
if (!(e.NewValue is Note newNoteValue) || newNoteValue == null) return;
var panel = (NotePanel)s;
panel.Items.Clear();
if (panel.ShowNotes)
{
foreach (var file in (newNoteValue.FileNames))
{
var rtb = new ExtendedRichTextBox();
rtb.ReadFromFile(file);
panel.Items.Add(rtb);
}
}
else
panel.dt.Interval = TimeSpan.FromMilliseconds(500);
int i = 0;
foreach (var todo in newNoteValue.Todos.OrderBy(x => x.Index))
{
TodoControl todoControl = new TodoControl(todo, panel.ShowNotes);
todoControl.ReadFromFile(todo.FileName);
if (!panel.ShowNotes)
{
panel.Items.Insert(i++, todoControl);
}
else
panel.Items.Insert(todo.Index, todoControl);
}
panel.SaveNoteEvent += (se, ev) =>
{
panel.SaveContentsToFilesCommand.Execute(panel);
};
}
});
//Command to add a new TextBox. Implemented so the command can be invoked from XAML instead of back-end;
public ICommand AddRichTextBoxCommand
{
get => (ICommand)GetValue(AddRichTextBoxCommandProperty);
set => SetValue(AddRichTextBoxCommandProperty, value);
}
public static readonly DependencyProperty AddRichTextBoxCommandProperty = DependencyProperty.Register("AddRichTextBoxCommand",
typeof(ICommand), typeof(NotePanel), new FrameworkPropertyMetadata(new RelayCommand<NotePanel>((panel) =>
{
var rtb = new ExtendedRichTextBox();
if (panel.lastFocused != null)
{
var index = panel.Items.IndexOf(panel.lastFocused) + 1;
panel.Items.Insert(index, rtb);
}
else
panel.Items.Add(rtb);
rtb.SetKeyboardFocus();
})));
//Command to save each IExtendedTextBoxControl's contents to a respective .rtf file
public ICommand SaveContentsToFilesCommand
{
get => (ICommand)GetValue(SaveContentsToFilesCommandProperty);
set => SetValue(SaveContentsToFilesCommandProperty, value);
}
public static readonly DependencyProperty SaveContentsToFilesCommandProperty = DependencyProperty.Register("SaveContentsToFilesCommand",
typeof(ICommand), typeof(NotePanel), new FrameworkPropertyMetadata(new RelayCommand<NotePanel>((panel) =>
{
var note = panel?.Note;
if (note == null) return;
IOHandler.SerializeNote(panel);
panel._unsavedChanges = false;
panel.Status = "Saved at " + DateTime.Now.ToString("HH:mm:ss");
})));
public ICommand AddTodoControlCommand
{
get => (ICommand)GetValue(AddTodoControlCommandProperty);
set => SetValue(AddTodoControlCommandProperty, value);
}
public static readonly DependencyProperty AddTodoControlCommandProperty = DependencyProperty.Register("AddTodoControlCommand",
typeof(ICommand), typeof(NotePanel), new FrameworkPropertyMetadata(new RelayCommand<NotePanel>((panel) =>
{
var todoControl = new TodoControl(new Todo(), true).SetKeyboardFocusAfterLoaded();
if (panel.lastFocused != null)
{
var index = panel.Items.IndexOf(panel.lastFocused) + 1;
panel.Items.Insert(index, todoControl);
}
else
{
panel.Items.Add(todoControl);
}
})));
/// <summary>
/// Applies appropriate events to the provided ExtendedRichTextBox control
/// </summary>
/// <param name="extendedTextBoxControl"></param>
private void ConfigureExtendedTextBoxControlEvents(IExtendedTextBoxControl extendedTextBoxControl)
{
extendedTextBoxControl.BackspacePressedWithAltShiftModifiers += (s, e) =>
{
var index = this.Items.IndexOf(lastFocused);
if (this.Items.Contains(extendedTextBoxControl))
this.Items.Remove(extendedTextBoxControl);
if (extendedTextBoxControl is ExtendedRichTextBox ertb)
Note?.DeleteFile(ertb.CurrentFile);
if (extendedTextBoxControl is TodoControl todoControl)
Note?.RemoveTodo(todoControl.Todo);
SwitchKeyboardFocusToNextETBC(index);
};
extendedTextBoxControl.GotKeyboardFocus += (s, e) =>
{
lastFocused = (IExtendedTextBoxControl)s;
};
//Insertion of a new ExtendedRichBox at the end with a /note command
extendedTextBoxControl.TrackKeyword("note", () =>
{
this.AddRichTextBoxCommand.Execute(this);
});
extendedTextBoxControl.TrackKeyword("todo", () =>
{
var todoControl = new TodoControl(new Todo(), true).SetKeyboardFocusAfterLoaded();
var index = this.Items.IndexOf(extendedTextBoxControl) + 1;
if (extendedTextBoxControl is ExtendedRichTextBox rtb)
{
var leftRange = new TextRange(rtb.Document.ContentStart, rtb.CommandExecutionPointer);
var rightRange = new TextRange(rtb.CommandExecutionPointer, rtb.Document.ContentEnd);
this.Items.Insert(index, todoControl);
if (rightRange.Text?.Length >= 2 && rightRange.Text[0] == '\r' && rightRange.Text[1] == '\n')
{
rightRange = new TextRange(rtb.CommandExecutionPointer.GetNextContextPosition(LogicalDirection.Forward).GetNextContextPosition(LogicalDirection.Forward), rtb.Document.ContentEnd);
}
var newRtb = new ExtendedRichTextBox();
using (var stream = new MemoryStream())
{
if (!String.IsNullOrWhiteSpace(rightRange.Text))
{
rightRange.Save(stream, DataFormats.Rtf);
newRtb.TextRange.Load(stream, DataFormats.Rtf);
this.Items.Insert(index + 1, newRtb);
stream.SetLength(0);
}
leftRange.Save(stream, DataFormats.Rtf);
rtb.TextRange.Load(stream, DataFormats.Rtf);
}
}
else
this.Items.Insert(index, todoControl);
});
extendedTextBoxControl.TextChanged += (s, e) =>
{
if (extendedTextBoxControl.Initializing != true)
{
InitializeAutosaveDispatcher();
}
};
extendedTextBoxControl.Drop += (s, e) =>
{
InitializeAutosaveDispatcher();
};
extendedTextBoxControl.LostKeyboardFocus += (s, e) =>
{
SaveContentsToFilesCommand.Execute(this);
};
}
private void InitializeAutosaveDispatcher()
{
Status = "Unsaved changes.";
_unsavedChanges = true;
if (!dt.IsEnabled)
dt.Start();
}
/// <summary>
/// Gives a neighbour IExtendedTextBoxControl keyboard focus.
/// </summary>
/// <param name="index">Index of current IExtendedTextBoxControl in the Items Array</param>
/// <param name="up">Whether to navigate up the list.</param>
private void SwitchKeyboardFocusToNextETBC(int index, bool up = true)
{
if (up)
{
var etbc = Items.Cast<object>().Take(index).OfType<IExtendedTextBoxControl>().LastOrDefault();
if (etbc != null)
etbc.SetKeyboardFocus();
}
else
{
var etbc = Items.Cast<object>().Skip(index + 1).OfType<IExtendedTextBoxControl>().FirstOrDefault();
if (etbc != null)
etbc.SetKeyboardFocus();
}
}
public bool ShowNotes
{
get => (bool)GetValue(ShowNotesProperty);
set => SetValue(ShowNotesProperty, value);
}
public static readonly DependencyProperty ShowNotesProperty = DependencyProperty.Register("ShowNotes",
typeof(bool), typeof(NotePanel), new FrameworkPropertyMetadata(true));
public RoutedEventHandler SaveNoteEvent;
}
}
| 37.481375 | 203 | 0.544683 | [
"MIT"
] | Kodnot/ToNote | ToNote/Controls/NotePanel.cs | 13,083 | C# |
using System.Globalization;
using bytePassion.Library.Essentials.WpfTools.ConverterBase;
using bytePassion.Library.Essentials.WpfTools.Positioning;
namespace bytePassion.Library.Essentials.WpfTools.Converter
{
public class InvertedAngleToDoubleConverter : GenericValueConverter<Angle, double>
{
protected override double Convert(Angle angle, CultureInfo culture)
{
return angle.Inverted.Value;
}
protected override Angle ConvertBack(double value, CultureInfo culture)
{
return new Angle(new Degree(value)).Inverted;
}
}
} | 31.789474 | 83 | 0.72351 | [
"Apache-2.0"
] | bytePassion/bytePassion.Library.Essentials | bytePassion.Library.Essentials/bytePassion.Library.Essentials.WpfTools/Converter/InvertedAngleToDoubleConverter.cs | 604 | C# |
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
namespace Microsoft.Azure.Gaming.VmAgent.Core.Interfaces
{
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using AgentInterfaces;
using Extensions;
using Microsoft.Azure.Gaming.VmAgent.Extensions;
using Microsoft.Extensions.Logging;
using Model;
using Newtonsoft.Json;
public abstract class SessionHostConfigurationBase : ISessionHostConfiguration
{
// The values prefixed with "PF" can potentially be used by game server.
// The values that are not prefixed with PF are used by GSDK and container startup script.
// Used by the GSDK and game start scripts to get the Title Id for this session host
public const string TitleIdEnvVariable = "PF_TITLE_ID";
// Used by the GSDK and game start scripts to get the Build Id for this session host
public const string BuildIdEnvVariable = "PF_BUILD_ID";
// Used by the GSDK and game start scripts to get the Azure Region for this session host
public const string RegionEnvVariable = "PF_REGION";
// The server instance number (1 to NumSessionsPerVm) for this session host.
private const string ServerInstanceNumberEnvVariable = "PF_SERVER_INSTANCE_NUMBER";
// The VmId of the VM that the session host is running on.
public const string VmIdEnvVariable = "PF_VM_ID";
// Used by the games to share user generated content (and other files that are downloaded once, used multiple times).
private const string SharedContentFolderEnvVariable = "PF_SHARED_CONTENT_FOLDER";
// Used by the GSDK to find the configuration file
private const string ConfigFileEnvVariable = "GSDK_CONFIG_FILE";
// Used by the startup script to install Game Certificates
private const string CertificateFolderEnvVariable = "CERTIFICATE_FOLDER";
// Some legacy games ping themselves over the internet for health monitoring.
// In order to set up etc\hosts file for those games, we provide the public IP via an
// environment variable.
private const string PublicIPv4AddressEnvVariable = "PUBLIC_IPV4_ADDRESS";
/// <summary>
/// An environment variable capturing the logs folder for a game server.
/// All logs written to this folder will be zipped and uploaded to a storage account and are available for download.
/// </summary>
private const string LogsDirectoryEnvVariable = "PF_SERVER_LOG_DIRECTORY";
/// <summary>
/// An environment variable capturing the crash dumps folder for a game server.
/// This folder is a subfolder of PF_SERVER_LOG_DIRECTORY.
/// </summary>
private const string DumpsDirectoryEnvVariable = "PF_SERVER_DUMP_DIRECTORY";
// Not sure if this is needed yet.
private const string DefaultExePath = @"C:\app\";
protected VmConfiguration VmConfiguration { get; }
private readonly ILogger _logger;
private readonly ISystemOperations _systemOperations;
protected readonly SessionHostsStartInfo _sessionHostsStartInfo;
protected abstract string GetGsdkConfigFilePath(string assignmentId, int instanceNumber);
protected abstract string GetCertificatesPath(string assignmentId);
protected abstract string GetSharedContentFolderPath();
protected SessionHostConfigurationBase(VmConfiguration vmConfiguration, MultiLogger logger, ISystemOperations systemOperations, SessionHostsStartInfo sessionHostsStartInfo)
{
_logger = logger;
VmConfiguration = vmConfiguration;
_systemOperations = systemOperations;
_sessionHostsStartInfo = sessionHostsStartInfo;
}
public IDictionary<string, string> GetEnvironmentVariablesForSessionHost(int instanceNumber, string logFolderId, VmAgentSettings agentSettings)
{
VmConfiguration.ParseAssignmentId(_sessionHostsStartInfo.AssignmentId, out Guid titleId, out Guid deploymentId, out string region);
// Note that most of these are being provided based on customer request
var environmentVariables = new Dictionary<string, string>()
{
{
ConfigFileEnvVariable, GetGsdkConfigFilePath(_sessionHostsStartInfo.AssignmentId, instanceNumber)
},
{
LogsDirectoryEnvVariable, GetLogFolder(logFolderId, VmConfiguration)
},
{
SharedContentFolderEnvVariable, GetSharedContentFolderPath()
},
{
CertificateFolderEnvVariable, GetCertificatesPath(_sessionHostsStartInfo.AssignmentId)
},
{
TitleIdEnvVariable, VmConfiguration.GetPlayFabTitleId(titleId)
},
{
BuildIdEnvVariable, deploymentId.ToString()
},
{
RegionEnvVariable, region
},
{
ServerInstanceNumberEnvVariable, instanceNumber.ToString()
},
{
VmIdEnvVariable, VmConfiguration.VmId
},
{
PublicIPv4AddressEnvVariable, _sessionHostsStartInfo.PublicIpV4Address
}
};
if (agentSettings.EnableCrashDumpProcessing)
{
environmentVariables.Add(DumpsDirectoryEnvVariable, GetDumpFolder(logFolderId, VmConfiguration));
}
return environmentVariables;
}
public void Create(int instanceNumber, string sessionHostUniqueId, string agentEndpoint, VmConfiguration vmConfiguration, string logFolderId)
{
Dictionary<string, string> certThumbprints =
_sessionHostsStartInfo.GameCertificates?.Where(x => x.Thumbprint != null).ToDictionary(x => x.Name, x => x.Thumbprint);
IDictionary<string, string> portMappings = GetPortMappingsDict(_sessionHostsStartInfo, instanceNumber);
if (_sessionHostsStartInfo.IsLegacy)
{
CreateLegacyGSDKConfigFile(instanceNumber, sessionHostUniqueId, certThumbprints, portMappings);
}
// If the title is marked as legacy GSDK, we support a smooth transition when they decide to use new GSDK
// A title can start using new GSDK even if it's a legacy title
CreateNewGSDKConfigFile(instanceNumber, sessionHostUniqueId, certThumbprints, portMappings, agentEndpoint, vmConfiguration, logFolderId);
}
private void CreateNewGSDKConfigFile(int instanceNumber, string sessionHostUniqueId, Dictionary<string, string> certThumbprints, IDictionary<string, string> portMappings, string agentEndpoint, VmConfiguration vmConfiguration, string logFolderId)
{
string configFilePath = Path.Combine(VmConfiguration.GetConfigRootFolderForSessionHost(instanceNumber),
VmDirectories.GsdkConfigFilename);
_logger.LogInformation($"Creating the configuration file at {configFilePath}");
GsdkConfiguration gsdkConfig = new GsdkConfiguration
{
HeartbeatEndpoint = $"{agentEndpoint}:{VmConfiguration.ListeningPort}",
SessionHostId = sessionHostUniqueId,
VmId = vmConfiguration.VmId,
LogFolder = GetLogFolder(logFolderId, vmConfiguration),
CertificateFolder = vmConfiguration.VmDirectories.CertificateRootFolderContainer,
SharedContentFolder = vmConfiguration.VmDirectories.GameSharedContentFolderContainer,
GameCertificates = certThumbprints,
BuildMetadata = _sessionHostsStartInfo.DeploymentMetadata,
GamePorts = portMappings,
PublicIpV4Address = _sessionHostsStartInfo.PublicIpV4Address,
FullyQualifiedDomainName = _sessionHostsStartInfo.FQDN,
ServerInstanceNumber = instanceNumber,
GameServerConnectionInfo = GetGameServerConnectionInfo(instanceNumber)
};
string outputJson = JsonConvert.SerializeObject(gsdkConfig, Formatting.Indented, CommonSettings.JsonSerializerSettings);
// This will overwrite the file if it was already there (which would happen when restarting containers for the same assignment)
_systemOperations.FileWriteAllText(configFilePath, outputJson);
}
protected abstract string GetLogFolder(string logFolderId, VmConfiguration vmConfiguration);
protected string GetDumpFolder(string logFolderId, VmConfiguration vmConfiguration)
{
return Path.Combine(GetLogFolder(logFolderId, vmConfiguration), VmDirectories.GameDumpsFolderName);
}
protected abstract string GetSharedContentFolder(VmConfiguration vmConfiguration);
protected abstract string GetCertificateFolder(VmConfiguration vmConfiguration);
private void CreateLegacyGSDKConfigFile(int instanceNumber, string sessionHostUniqueId, Dictionary<string, string> certThumbprints, IDictionary<string, string> portMappings)
{
// Legacy games are currently assumed to have only 1 asset.zip file which will have the game.exe as well
// as the assets. We just place ServiceDefinition.json in that folder itself (since it contains game.exe).
// This assumption will change later on and the code below will need to adapt.
string configFilePath =
Path.Combine(VmConfiguration.GetAssetExtractionFolderPathForSessionHost(instanceNumber, 0),
"ServiceDefinition.json");
ServiceDefinition serviceDefinition;
if (_systemOperations.FileExists(configFilePath))
{
_logger.LogInformation($"Parsing the existing service definition file at {configFilePath}.");
serviceDefinition = JsonConvert.DeserializeObject<ServiceDefinition>(File.ReadAllText(configFilePath));
serviceDefinition.JsonWorkerRole = serviceDefinition.JsonWorkerRole ?? new JsonWorkerRole();
}
else
{
_logger.LogInformation($"Creating the service definition file at {configFilePath}.");
serviceDefinition = new ServiceDefinition
{
JsonWorkerRole = new JsonWorkerRole()
};
}
SetUpLegacyConfigValues(serviceDefinition, sessionHostUniqueId, instanceNumber, GetVmAgentIpAddress());
certThumbprints?.ForEach(x => serviceDefinition.JsonWorkerRole.SetConfigValue(x.Key, x.Value));
portMappings?.ForEach(x => serviceDefinition.JsonWorkerRole.SetConfigValue(x.Key, x.Value));
_sessionHostsStartInfo.DeploymentMetadata?.ForEach(x => serviceDefinition.JsonWorkerRole.SetConfigValue(x.Key, x.Value));
string outputJson = JsonConvert.SerializeObject(serviceDefinition, Formatting.Indented, CommonSettings.JsonSerializerSettings);
// This will overwrite the file if it was already there (which would happen when restarting containers for the same assignment)
_systemOperations.FileWriteAllText(configFilePath, outputJson);
}
private void SetUpLegacyConfigValues(ServiceDefinition serviceDefinition, string sessionHostId, int instanceNumber, string vmAgentHeartbeatIpAddress)
{
VmConfiguration.ParseAssignmentId(_sessionHostsStartInfo.AssignmentId, out Guid titleId, out Guid deploymentId, out string region);
JsonWorkerRole workerRole = serviceDefinition.JsonWorkerRole;
workerRole.NoGSMS = false;
// Set the RoleInstanceId to vmId. Games like Activision's Call of Duty depend on this being unique per Vm in a cluster.
// In v3, the vmId is globally unique (and should satisfy the requirement).
serviceDefinition.CurrentRoleInstance = serviceDefinition.CurrentRoleInstance ?? new CurrentRoleInstance();
serviceDefinition.CurrentRoleInstance.Id = VmConfiguration.VmId;
// Not completely necessary, but avoids all VMs reporting the same deploymentId to the game server (and consequently to their lobby service potentially).
serviceDefinition.DeploymentId = Guid.NewGuid().ToString("N");
UpdateRoleInstanceEndpoints(serviceDefinition, instanceNumber);
if (LegacyTitleHelper.LegacyTitleMappings.TryGetValue(titleId, out LegacyTitleDetails titleDetails))
{
workerRole.TitleId = titleDetails.TitleId.ToString();
workerRole.GsiId = titleDetails.GsiId.ToString();
workerRole.GsiSetId = titleDetails.GsiSetId.ToString();
workerRole.ClusterId = GetHostNameFromFqdn(_sessionHostsStartInfo.FQDN);
}
else
{
workerRole.TitleId = VmConfiguration.GetPlayFabTitleId(titleId);
workerRole.GsiId = deploymentId.ToString();
workerRole.GsiSetId = deploymentId.ToString();
// Some legacy games, such as SunsetOverdrive append "cloudapp.net" to the clusterId value
// and try pinging that over the internet (essentially the server is pinging itself over the internet for
// health monitoring). Given that the FQDN in PlayFab doesn't necessarily end with cloudapp.net, we fake
// this by specifying a dummy value here and editing the etc\hosts file to point dummyValue.cloudapp.net to
// the publicIPAddress of the VM (available via environment variable).
workerRole.ClusterId = "dummyValue";
}
workerRole.GsmsBaseUrl =
$"http://{vmAgentHeartbeatIpAddress}:{VmConfiguration.ListeningPort}/v1";
workerRole.SessionHostId =
"r601y87miefd5ok8rdlgn-3b5np6glmoj4r24ymsk7gh7yhl-2019999738-wus.GSDKAgent_IN_0.Tenant_0.0";
workerRole.InstanceId = sessionHostId;
workerRole.ExeFolderPath = DefaultExePath;
workerRole.TenantCount = _sessionHostsStartInfo.Count;
workerRole.Location = LegacyAzureRegionHelper.GetRegionString(region);
workerRole.Datacenter = workerRole.Location.Replace(" ", string.Empty);
workerRole.XassBaseUrl = "https://service.auth.xboxlive.com/service/authenticate";
workerRole.XastBaseUrl = "https://title.auth.xboxlive.com:10443/title/authenticate";
workerRole.XstsBaseUrl = "https://xsts.auth.xboxlive.com/xsts/authorize";
// Legacy Agent wrote it in this format.
workerRole.TenantName = $"{instanceNumber,4:0000}";
CertificateDetail ipSecCertificate = _sessionHostsStartInfo.IpSecCertificate ?? _sessionHostsStartInfo.XblcCertificate;
if (!string.IsNullOrEmpty(_sessionHostsStartInfo.XblcCertificate?.Thumbprint))
{
// Halo GSDK needs both of these to start up properly.
workerRole.XblGameServerCertificateThumbprint = _sessionHostsStartInfo.XblcCertificate?.Thumbprint;
workerRole.XblIpsecCertificateThumbprint = ipSecCertificate?.Thumbprint;
}
// Add port mappings in the legacy format.
GetLegacyPortMapping(instanceNumber).ToList().ForEach(port => workerRole.SetConfigValue(port.Key, port.Value));
}
private void UpdateRoleInstanceEndpoints(ServiceDefinition serviceDefinition, int instanceNumber)
{
// Sample:
//"currentRoleInstance": {
// "id": "GSDKAgent_IN_0",
// "roleInstanceEndpoints": [
// {
// "name": "gametraffic",
// "internalPort": 7777,
// "externalPort": 31000,
// "maxPort": 30099,
// "minPort": 30000,
// "ipEndPoint": "10.26.114.84:7777",
// "publicIpEndPoint": "255.255.255.255:31000",
// "protocol": "udp"
// },
// {
// "name": "Microsoft.WindowsAzure.Plugins.RemoteAccess.Rdp",
// "internalPort": 3389,
// "externalPort": 3389,
// "maxPort": 30099,
// "minPort": 30000,
// "ipEndPoint": "10.26.114.84:3389",
// "publicIpEndPoint": "10.26.114.84:3389",
// "protocol": "tcp"
// },
// {
// "name": "Microsoft.WindowsAzure.Plugins.RemoteForwarder.RdpInput",
// "internalPort": 20000,
// "externalPort": 3389,
// "maxPort": 30099,
// "minPort": 30000,
// "ipEndPoint": "10.26.114.84:20000",
// "publicIpEndPoint": "255.255.255.255:3389",
// "protocol": "tcp"
// },
// {
// "name": "ShouldertapUdp",
// "internalPort": 10101,
// "externalPort": 30100,
// "maxPort": 30099,
// "minPort": 30000,
// "ipEndPoint": "10.26.114.84:10101",
// "publicIpEndPoint": "255.255.255.255:30100",
// "protocol": "udp"
// },
// {
// "name": "TCPEcho",
// "internalPort": 10100,
// "externalPort": 30000,
// "maxPort": 30099,
// "minPort": 30000,
// "ipEndPoint": "10.26.114.84:10100",
// "publicIpEndPoint": "255.255.255.255:30000",
// "protocol": "tcp"
// }
// ]
//},
serviceDefinition.CurrentRoleInstance.RoleInstanceEndpoints = new List<RoleInstanceEndpoint>();
IList<PortMapping> portMappings = GetPortMappings(instanceNumber);
foreach (PortMapping mapping in portMappings)
{
string internalServerListeningPort = GetLegacyServerListeningPort(mapping).ToString();
serviceDefinition.CurrentRoleInstance.RoleInstanceEndpoints.Add(new RoleInstanceEndpoint()
{
// The local ip can be a dummy value.
IpEndPoint = $"100.76.124.25:{internalServerListeningPort}",
Name = mapping.GamePort.Name,
Protocol = mapping.GamePort.Protocol.ToLower(),
PublicIpEndPoint = $"{_sessionHostsStartInfo.PublicIpV4Address}:{mapping.PublicPort}",
InternalPort = internalServerListeningPort,
ExternalPort = mapping.PublicPort.ToString()
});
}
string hostnameFilePath =
Path.Combine(VmConfiguration.GetAssetExtractionFolderPathForSessionHost(instanceNumber, 0),
"hostname");
_systemOperations.FileWriteAllText(hostnameFilePath, _sessionHostsStartInfo.FQDN);
if (_sessionHostsStartInfo.IpSecCertificate != null)
{
string ipsecFileNamePath =
Path.Combine(VmConfiguration.GetAssetExtractionFolderPathForSessionHost(instanceNumber, 0),
"ipsec_certificate_thumbprint");
_systemOperations.FileWriteAllText(ipsecFileNamePath, _sessionHostsStartInfo.IpSecCertificate.Thumbprint);
}
}
private string GetHostNameFromFqdn(string fqdn)
{
return fqdn.Split('.', StringSplitOptions.RemoveEmptyEntries)[0];
}
/// <summary>
/// Many of the legacy game servers require port mappings to be written in the config file in a specific format.
/// For example, if the build specifies a port as follows:
/// Name: GameUDP, port : 8080, Protocol: UDP
/// The legacy game servers would need two config values for this port:
/// "PortGameUDPInternal" - this is the port that game server should listen on within the VM.
/// "PortGameUDPExternal" - this is the port that clients can reach the game server on.
///
/// Essentially, the name is of the following format: "Port{name_in_build_configuration_}Internal" and "Port{name_in_build_configuration_}External".
/// </summary>
/// <param name="instanceNumber">The game server instance number (between 1 and number of servers per Vm).</param>
/// <returns></returns>
protected abstract Dictionary<string, string> GetLegacyPortMapping(int instanceNumber);
/// <summary>
/// Gets the port at which the game server should listen on (differs between containers and processes).
/// </summary>
/// <param name="portMapping"></param>
/// <returns></returns>
protected abstract int GetLegacyServerListeningPort(PortMapping portMapping);
public IList<PortMapping> GetPortMappings(int instanceNumber)
{
if (_sessionHostsStartInfo.PortMappingsList != null && _sessionHostsStartInfo.PortMappingsList.Count > 0)
{
return _sessionHostsStartInfo.PortMappingsList[instanceNumber];
}
return null;
}
/// <summary>
/// Gets the game server connection information (IP Address and ports of the server).
/// </summary>
/// <param name="instanceNumber">The instance of game server running on the VM.</param>
/// <returns></returns>
private GameServerConnectionInfo GetGameServerConnectionInfo(int instanceNumber)
{
return new GameServerConnectionInfo()
{
PublicIpV4Adress = _sessionHostsStartInfo.PublicIpV4Address,
GamePortsConfiguration = GetGamePortConfiguration(instanceNumber)
};
}
/// <summary>
/// Gets the ports assigned to the specific instance of the game server.
/// The ports include both, the port at which the game server listens on,
/// and the port to which the clients connect to (which internally maps to the server listening port).
/// </summary>
/// <param name="instanceNumber"></param>
/// <returns></returns>
protected abstract IEnumerable<GamePort> GetGamePortConfiguration(int instanceNumber);
private IDictionary<string, string> GetPortMappingsDict(SessionHostsStartInfo sessionHostsStartInfo, int instanceNumber)
{
if (sessionHostsStartInfo.PortMappingsList != null && sessionHostsStartInfo.PortMappingsList.Count > 0)
{
return GetPortMappingsInternal(sessionHostsStartInfo.PortMappingsList[instanceNumber]);
}
return null;
}
protected abstract IDictionary<string, string> GetPortMappingsInternal(List<PortMapping> portMappings);
private string GetVmAgentIpAddress()
{
return GetVmAgentIpAddressInternal();
}
protected abstract string GetVmAgentIpAddressInternal();
}
}
| 51.714912 | 253 | 0.639768 | [
"MIT"
] | lesterjackson/MpsAgent | VmAgent.Core/Interfaces/SessionHostConfigurationBase.cs | 23,584 | C# |
using System;
using System.Runtime.Serialization;
using System.Threading;
using System.Threading.Tasks;
namespace Consul
{
#if !(CORECLR || PORTABLE || PORTABLE40)
[Serializable]
#endif
public class LockHeldException : Exception
{
public LockHeldException()
{
}
public LockHeldException(string message)
: base(message)
{
}
public LockHeldException(string message, Exception inner)
: base(message, inner)
{
}
#if !(CORECLR || PORTABLE || PORTABLE40)
protected LockHeldException(
SerializationInfo info,
StreamingContext context) : base(info, context) { }
#endif
}
#if !(CORECLR || PORTABLE || PORTABLE40)
[Serializable]
#endif
public class LockNotHeldException : Exception
{
public LockNotHeldException()
{
}
public LockNotHeldException(string message)
: base(message)
{
}
public LockNotHeldException(string message, Exception inner)
: base(message, inner)
{
}
#if !(CORECLR || PORTABLE || PORTABLE40)
protected LockNotHeldException(
SerializationInfo info,
StreamingContext context) : base(info, context) { }
#endif
}
#if !(CORECLR || PORTABLE || PORTABLE40)
[Serializable]
#endif
public class LockInUseException : Exception
{
public LockInUseException()
{
}
public LockInUseException(string message)
: base(message)
{
}
public LockInUseException(string message, Exception inner)
: base(message, inner)
{
}
#if !(CORECLR || PORTABLE || PORTABLE40)
protected LockInUseException(
SerializationInfo info,
StreamingContext context) : base(info, context) { }
#endif
}
#if !(CORECLR || PORTABLE || PORTABLE40)
[Serializable]
#endif
public class LockConflictException : Exception
{
public LockConflictException()
{
}
public LockConflictException(string message)
: base(message)
{
}
public LockConflictException(string message, Exception inner)
: base(message, inner)
{
}
#if !(CORECLR || PORTABLE || PORTABLE40)
protected LockConflictException(
SerializationInfo info,
StreamingContext context) : base(info, context) { }
#endif
}
#if !(CORECLR || PORTABLE || PORTABLE40)
[Serializable]
#endif
public class LockMaxAttemptsReachedException : Exception
{
public LockMaxAttemptsReachedException() { }
public LockMaxAttemptsReachedException(string message) : base(message) { }
public LockMaxAttemptsReachedException(string message, Exception inner) : base(message, inner) { }
#if !(CORECLR || PORTABLE || PORTABLE40)
protected LockMaxAttemptsReachedException(
SerializationInfo info,
StreamingContext context) : base(info, context) { }
#endif
}
/// <summary>
/// Lock is used to implement client-side leader election. It is follows the algorithm as described here: https://consul.io/docs/guides/leader-election.html.
/// </summary>
public class Lock : IDistributedLock
{
/// <summary>
/// DefaultLockWaitTime is how long we block for at a time to check if lock acquisition is possible. This affects the minimum time it takes to cancel a Lock acquisition.
/// </summary>
public static readonly TimeSpan DefaultLockWaitTime = TimeSpan.FromSeconds(15);
/// <summary>
/// DefaultLockRetryTime is how long we wait after a failed lock acquisition before attempting
/// to do the lock again. This is so that once a lock-delay is in effect, we do not hot loop
/// retrying the acquisition.
/// </summary>
public static readonly TimeSpan DefaultLockRetryTime = TimeSpan.FromSeconds(5);
/// <summary>
/// DefaultMonitorRetryTime is how long we wait after a failed monitor check
/// of a lock (500 response code). This allows the monitor to ride out brief
/// periods of unavailability, subject to the MonitorRetries setting in the
/// lock options which is by default set to 0, disabling this feature.
/// </summary>
public static readonly TimeSpan DefaultMonitorRetryTime = TimeSpan.FromSeconds(2);
/// <summary>
/// LockFlagValue is a magic flag we set to indicate a key is being used for a lock. It is used to detect a potential conflict with a semaphore.
/// </summary>
private const ulong LockFlagValue = 0x2ddccbc058a50c18;
private readonly AsyncLock _mutex = new AsyncLock();
private bool _isheld;
private int _retries;
private CancellationTokenSource _cts;
private Task _sessionRenewTask;
private Task _monitorTask;
private readonly ConsulClient _client;
internal LockOptions Opts { get; set; }
internal string LockSession { get; set; }
/// <summary>
/// If the lock is held or not.
/// Users of the Lock object should check the IsHeld property before entering the critical section of their code, e.g. in a "while (myLock.IsHeld) {criticalsection}" block.
/// Calls to IsHeld are syncronized across threads using a lock, so multiple threads sharing a single Consul Lock will queue up reading the IsHeld property of the lock.
/// </summary>
public bool IsHeld
{
get
{
return _isheld;
}
private set
{
_isheld = value;
}
}
internal Lock(ConsulClient c)
{
_client = c;
_cts = new CancellationTokenSource();
}
/// <summary>
/// Lock attempts to acquire the lock and blocks while doing so. Not providing a CancellationToken means the thread can block indefinitely until the lock is acquired.
/// There is no notification that the lock has been lost, but it may be closed at any time due to session invalidation, communication errors, operator intervention, etc.
/// It is NOT safe to assume that the lock is held until Unlock() unless the Session is specifically created without any associated health checks.
/// Users of the Lock object should check the IsHeld property before entering the critical section of their code, e.g. in a "while (myLock.IsHeld) {criticalsection}" block.
/// By default Consul sessions prefer liveness over safety and an application must be able to handle the lock being lost.
/// </summary>
public Task<CancellationToken> Acquire()
{
return Acquire(CancellationToken.None);
}
/// <summary>
/// Lock attempts to acquire the lock and blocks while doing so.
/// Providing a CancellationToken can be used to abort the lock attempt.
/// There is no notification that the lock has been lost, but IsHeld may be set to False at any time due to session invalidation, communication errors, operator intervention, etc.
/// It is NOT safe to assume that the lock is held until Unlock() unless the Session is specifically created without any associated health checks.
/// Users of the Lock object should check the IsHeld property before entering the critical section of their code, e.g. in a "while (myLock.IsHeld) {criticalsection}" block.
/// By default Consul sessions prefer liveness over safety and an application must be able to handle the lock being lost.
/// </summary>
/// <param name="ct">The cancellation token to cancel lock acquisition</param>
public async Task<CancellationToken> Acquire(CancellationToken ct)
{
try
{
using (await _mutex.LockAsync().ConfigureAwait(false))
{
if (IsHeld)
{
// Check if we already hold the lock
throw new LockHeldException();
}
// Don't overwrite the CancellationTokenSource until AFTER we've tested for holding,
// since there might be tasks that are currently running for this lock.
DisposeCancellationTokenSource();
_cts = new CancellationTokenSource();
// Check if we need to create a session first
if (string.IsNullOrEmpty(Opts.Session))
{
LockSession = await CreateSession().ConfigureAwait(false);
_sessionRenewTask = _client.Session.RenewPeriodic(Opts.SessionTTL, LockSession,
WriteOptions.Default, _cts.Token);
}
else
{
LockSession = Opts.Session;
}
var qOpts = new QueryOptions()
{
WaitTime = Opts.LockWaitTime
};
var attempts = 0;
var start = DateTime.UtcNow;
while (!ct.IsCancellationRequested)
{
if (attempts > 0 && Opts.LockTryOnce)
{
var elapsed = DateTime.UtcNow.Subtract(start);
if (elapsed > qOpts.WaitTime)
{
DisposeCancellationTokenSource();
throw new LockMaxAttemptsReachedException("LockTryOnce is set and the lock is already held or lock delay is in effect");
}
qOpts.WaitTime -= elapsed;
}
attempts++;
QueryResult<KVPair> pair;
pair = await _client.KV.Get(Opts.Key, qOpts).ConfigureAwait(false);
if (pair.Response != null)
{
if (pair.Response.Flags != LockFlagValue)
{
DisposeCancellationTokenSource();
throw new LockConflictException();
}
// Already locked by this session
if (pair.Response.Session == LockSession)
{
// Don't restart MonitorLock if this session already holds the lock
if (IsHeld)
{
return _cts.Token;
}
IsHeld = true;
_monitorTask = MonitorLock();
return _cts.Token;
}
// If it's not empty, some other session must have the lock
if (!string.IsNullOrEmpty(pair.Response.Session))
{
qOpts.WaitIndex = pair.LastIndex;
continue;
}
}
// If the code executes this far, no other session has the lock, so try to lock it
var kvPair = LockEntry(LockSession);
var locked = (await _client.KV.Acquire(kvPair).ConfigureAwait(false)).Response;
// KV acquisition succeeded, so the session now holds the lock
if (locked)
{
IsHeld = true;
_monitorTask = MonitorLock();
return _cts.Token;
}
// Handle the case of not getting the lock
if (ct.IsCancellationRequested)
{
DisposeCancellationTokenSource();
throw new TaskCanceledException();
}
// Failed to get the lock, determine why by querying for the key again
qOpts.WaitIndex = 0;
pair = await _client.KV.Get(Opts.Key, qOpts).ConfigureAwait(false);
// If the session is not null, this means that a wait can safely happen using a long poll
if (pair.Response != null && pair.Response.Session != null)
{
qOpts.WaitIndex = pair.LastIndex;
continue;
}
// If the session is null and the lock failed to acquire, then it means
// a lock-delay is in effect and a timed wait must be used to avoid a hot loop.
try { await Task.Delay(Opts.LockRetryTime, ct).ConfigureAwait(false); }
catch (TaskCanceledException) { /* Ignore TaskTaskCanceledException */}
}
DisposeCancellationTokenSource();
throw new LockNotHeldException("Unable to acquire the lock with Consul");
}
}
finally
{
if (ct.IsCancellationRequested || (!IsHeld && !string.IsNullOrEmpty(Opts.Session)))
{
DisposeCancellationTokenSource();
if (_sessionRenewTask != null)
{
try
{
await _monitorTask.ConfigureAwait(false);
await _sessionRenewTask.ConfigureAwait(false);
}
catch (AggregateException)
{
// Ignore AggregateExceptions from the tasks during Release, since if the Renew task died, the developer will be Super Confused if they see the exception during Release.
}
}
}
}
}
/// <summary>
/// Unlock released the lock. It is an error to call this if the lock is not currently held.
/// </summary>
public async Task Release(CancellationToken ct = default(CancellationToken))
{
try
{
using (await _mutex.LockAsync().ConfigureAwait(false))
{
if (!IsHeld)
{
throw new LockNotHeldException();
}
IsHeld = false;
var lockEnt = LockEntry(LockSession);
await _client.KV.Release(lockEnt, ct).ConfigureAwait(false);
}
}
finally
{
DisposeCancellationTokenSource();
if (_sessionRenewTask != null)
{
try
{
await _sessionRenewTask.ConfigureAwait(false);
}
catch (Exception)
{
// Ignore Exceptions from the tasks during Release, since if the Renew task died, the developer will be Super Confused if they see the exception during Release.
}
}
}
}
/// <summary>
/// Destroy is used to cleanup the lock entry. It is not necessary to invoke. It will fail if the lock is in use.
/// </summary>
public async Task Destroy(CancellationToken ct = default(CancellationToken))
{
using (await _mutex.LockAsync().ConfigureAwait(false))
{
if (IsHeld)
{
throw new LockHeldException();
}
var pair = (await _client.KV.Get(Opts.Key, ct).ConfigureAwait(false)).Response;
if (pair == null)
{
return;
}
if (pair.Flags != LockFlagValue)
{
throw new LockConflictException();
}
if (!string.IsNullOrEmpty(pair.Session))
{
throw new LockInUseException();
}
var didRemove = (await _client.KV.DeleteCAS(pair, ct).ConfigureAwait(false)).Response;
if (!didRemove)
{
throw new LockInUseException();
}
}
}
private void DisposeCancellationTokenSource()
{
// Make a copy of the reference to the CancellationTokenSource in case it gets removed before we finish.
// It's okay to cancel and dispose of them twice, it doesn't cause exceptions.
var cts = _cts;
if (cts != null)
{
Interlocked.CompareExchange(ref _cts, null, cts);
cts.Cancel();
cts.Dispose();
}
}
/// <summary>
/// MonitorLock is a long running routine to monitor a lock ownership. It sets IsHeld to false if we lose our leadership.
/// </summary>
private Task MonitorLock()
{
return Task.Factory.StartNew(async () => {
// Copy a reference to _cts since we could end up destroying it before this method returns
var cts = _cts;
try
{
var opts = new QueryOptions() { Consistency = ConsistencyMode.Consistent };
_retries = Opts.MonitorRetries;
while (IsHeld && !cts.Token.IsCancellationRequested)
{
try
{
// Check to see if the current session holds the lock
var pair = await _client.KV.Get(Opts.Key, opts).ConfigureAwait(false);
if (pair.Response != null)
{
_retries = Opts.MonitorRetries;
// Lock is no longer held! Shut down everything.
if (pair.Response.Session != LockSession)
{
IsHeld = false;
DisposeCancellationTokenSource();
return;
}
// Lock is still held, start a blocking query
opts.WaitIndex = pair.LastIndex;
continue;
}
else
{
// Failsafe in case the KV store is unavailable
IsHeld = false;
DisposeCancellationTokenSource();
return;
}
}
catch (ConsulRequestException)
{
if (_retries > 0)
{
await Task.Delay(Opts.MonitorRetryTime, cts.Token).ConfigureAwait(false);
_retries--;
opts.WaitIndex = 0;
continue;
}
throw;
}
catch (OperationCanceledException)
{
// Ignore and retry since this could be the underlying HTTPClient being swapped out/disposed of.
}
catch (Exception)
{
throw;
}
}
}
finally
{
IsHeld = false;
DisposeCancellationTokenSource();
}
}, CancellationToken.None, TaskCreationOptions.LongRunning, TaskScheduler.Default).Unwrap();
}
/// <summary>
/// CreateSession is used to create a new managed session
/// </summary>
/// <returns>The session ID</returns>
private async Task<string> CreateSession()
{
var se = new SessionEntry
{
Name = Opts.SessionName,
TTL = Opts.SessionTTL
};
return (await _client.Session.Create(se).ConfigureAwait(false)).Response;
}
/// <summary>
/// LockEntry returns a formatted KVPair for the lock
/// </summary>
/// <param name="session">The session ID</param>
/// <returns>A KVPair with the lock flag set</returns>
private KVPair LockEntry(string session)
{
return new KVPair(Opts.Key)
{
Value = Opts.Value,
Session = session,
Flags = LockFlagValue
};
}
}
/// <summary>
/// LockOptions is used to parameterize the Lock behavior.
/// </summary>
public class LockOptions
{
/// <summary>
/// DefaultLockSessionName is the Session Name we assign if none is provided
/// </summary>
private const string DefaultLockSessionName = "Consul API Lock";
private static readonly TimeSpan LockRetryTimeMin = TimeSpan.FromMilliseconds(500);
/// <summary>
/// DefaultLockSessionTTL is the default session TTL if no Session is provided when creating a new Lock. This is used because we do not have another other check to depend upon.
/// </summary>
private static readonly TimeSpan DefaultLockSessionTTL = TimeSpan.FromSeconds(15);
private TimeSpan _lockRetryTime;
public string Key { get; set; }
public byte[] Value { get; set; }
public string Session { get; set; }
public string SessionName { get; set; }
public TimeSpan SessionTTL { get; set; }
public int MonitorRetries { get; set; }
public TimeSpan LockRetryTime
{
get { return _lockRetryTime; }
set
{
if (value < LockRetryTimeMin)
{
throw new ArgumentOutOfRangeException(nameof(LockRetryTime), $"The retry time must be greater than {LockRetryTimeMin.ToGoDuration()}.");
}
_lockRetryTime = value;
}
}
public TimeSpan LockWaitTime { get; set; }
public TimeSpan MonitorRetryTime { get; set; }
public bool LockTryOnce { get; set; }
public LockOptions(string key)
{
Key = key;
SessionName = DefaultLockSessionName;
SessionTTL = DefaultLockSessionTTL;
MonitorRetryTime = Lock.DefaultMonitorRetryTime;
LockWaitTime = Lock.DefaultLockWaitTime;
LockRetryTime = Lock.DefaultLockRetryTime;
}
}
public partial class ConsulClient : IConsulClient
{
/// <summary>
/// CreateLock returns an unlocked lock which can be used to acquire and release the mutex. The key used must have write permissions.
/// </summary>
/// <param name="key"></param>
/// <returns></returns>
public IDistributedLock CreateLock(string key)
{
if (string.IsNullOrEmpty(key))
{
throw new ArgumentNullException(nameof(key));
}
return CreateLock(new LockOptions(key));
}
/// <summary>
/// CreateLock returns an unlocked lock which can be used to acquire and release the mutex. The key used must have write permissions.
/// </summary>
/// <param name="opts"></param>
/// <returns></returns>
public IDistributedLock CreateLock(LockOptions opts)
{
if (opts == null)
{
throw new ArgumentNullException(nameof(opts));
}
return new Lock(this) { Opts = opts };
}
/// <summary>
/// AcquireLock creates a lock that is already acquired when this call returns.
/// </summary>
/// <param name="key"></param>
/// <param name="ct"></param>
/// <returns></returns>
public Task<IDistributedLock> AcquireLock(string key, CancellationToken ct = default(CancellationToken))
{
if (string.IsNullOrEmpty(key))
{
throw new ArgumentNullException(nameof(key));
}
return AcquireLock(new LockOptions(key), ct);
}
/// <summary>
/// AcquireLock creates a lock that is already acquired when this call returns.
/// </summary>
/// <param name="opts"></param>
/// <param name="ct"></param>
/// <returns></returns>
public async Task<IDistributedLock> AcquireLock(LockOptions opts, CancellationToken ct = default(CancellationToken))
{
if (opts == null)
{
throw new ArgumentNullException(nameof(opts));
}
var l = CreateLock(opts);
await l.Acquire(ct).ConfigureAwait(false);
return l;
}
/// <summary>
/// ExecuteLock accepts a delegate to execute in the context of a lock, releasing the lock when completed.
/// </summary>
/// <param name="key"></param>
/// <param name="action"></param>
/// <returns></returns>
public Task ExecuteLocked(string key, Action action, CancellationToken ct = default(CancellationToken))
{
if (string.IsNullOrEmpty(key))
{
throw new ArgumentNullException(nameof(key));
}
return ExecuteLocked(new LockOptions(key), action, ct);
}
/// <summary>
/// ExecuteLock accepts a delegate to execute in the context of a lock, releasing the lock when completed.
/// </summary>
/// <param name="opts"></param>
/// <param name="action"></param>
/// <returns></returns>
public async Task ExecuteLocked(LockOptions opts, Action action, CancellationToken ct = default(CancellationToken))
{
if (opts == null)
{
throw new ArgumentNullException(nameof(opts));
}
if (action == null)
{
throw new ArgumentNullException(nameof(action));
}
var l = await AcquireLock(opts, ct).ConfigureAwait(false);
try
{
if (!l.IsHeld)
{
throw new LockNotHeldException("Could not obtain the lock");
}
action();
}
finally
{
await l.Release().ConfigureAwait(false);
}
}
/// <summary>
/// ExecuteLock accepts a delegate to execute in the context of a lock, releasing the lock when completed.
/// </summary>
/// <param name="key"></param>
/// <param name="ct"></param>
/// <param name="action"></param>
/// <returns></returns>
[Obsolete("This method will be removed in 0.8.0. Replace calls with the method signature ExecuteLocked(string, Action, CancellationToken)")]
public Task ExecuteLocked(string key, CancellationToken ct, Action action)
{
if (string.IsNullOrEmpty(key))
{
throw new ArgumentNullException(nameof(key));
}
if (action == null)
{
throw new ArgumentNullException(nameof(action));
}
return ExecuteLocked(new LockOptions(key), action, ct);
}
/// <summary>
/// ExecuteLock accepts a delegate to execute in the context of a lock, releasing the lock when completed.
/// </summary>
/// <param name="opts"></param>
/// <param name="ct"></param>
/// <param name="action"></param>
/// <returns></returns>
[Obsolete("This method will be removed in 0.8.0. Replace calls with the method signature ExecuteLocked(LockOptions, Action, CancellationToken)")]
public Task ExecuteLocked(LockOptions opts, CancellationToken ct, Action action)
{
if (opts == null)
{
throw new ArgumentNullException(nameof(opts));
}
return ExecuteLocked(opts, action, ct);
}
}
} | 39.314016 | 197 | 0.514758 | [
"Apache-2.0"
] | jwkane/consuldotnet | Consul/Lock.cs | 29,173 | C# |
public interface IBuyer
{
string Name { get; }
int Age { get; }
int Food { get; }
void BuyFood();
} | 16.571429 | 24 | 0.551724 | [
"MIT"
] | maio246/CSharp-OOP-Advanced | Border Control/IBuyer.cs | 118 | C# |
using FluentAssertions;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Neo.IO;
using Neo.Ledger;
using Neo.SmartContract;
using Neo.SmartContract.Native;
using Neo.VM.Types;
using System;
using System.Collections.Generic;
using System.Numerics;
using VMArray = Neo.VM.Types.Array;
namespace Neo.UnitTests.SmartContract.Native
{
[TestClass]
public class UT_NativeContract
{
[TestInitialize]
public void TestSetup()
{
TestBlockchain.InitializeMockNeoSystem();
}
private static readonly TestNativeContract testNativeContract = new TestNativeContract();
[TestMethod]
public void TestInitialize()
{
ApplicationEngine ae = ApplicationEngine.Create(TriggerType.Application, null, null, 0);
testNativeContract.Initialize(ae);
}
private class DummyNative : NativeContract
{
public override string Name => "Dummy";
public override int Id => 1;
[ContractMethod(0, CallFlags.None)]
public void NetTypes(
bool p1, sbyte p2, byte p3, short p4, ushort p5, int p6, uint p7, long p8, ulong p9, BigInteger p10,
byte[] p11, string p12, IInteroperable p13, ISerializable p14, int[] p15, ContractParameterType p16,
object p17)
{ }
[ContractMethod(0, CallFlags.None)]
public void VMTypes(
VM.Types.Boolean p1, VM.Types.Integer p2, VM.Types.ByteString p3, VM.Types.Buffer p4,
VM.Types.Array p5, VM.Types.Struct p6, VM.Types.Map p7, VM.Types.StackItem p8
)
{ }
}
[TestMethod]
public void TestToParameter()
{
var manifest = new DummyNative().Manifest;
var netTypes = manifest.Abi.GetMethod("netTypes");
Assert.AreEqual(netTypes.ReturnType, ContractParameterType.Void);
Assert.AreEqual(netTypes.Parameters[0].Type, ContractParameterType.Boolean);
Assert.AreEqual(netTypes.Parameters[1].Type, ContractParameterType.Integer);
Assert.AreEqual(netTypes.Parameters[2].Type, ContractParameterType.Integer);
Assert.AreEqual(netTypes.Parameters[3].Type, ContractParameterType.Integer);
Assert.AreEqual(netTypes.Parameters[4].Type, ContractParameterType.Integer);
Assert.AreEqual(netTypes.Parameters[5].Type, ContractParameterType.Integer);
Assert.AreEqual(netTypes.Parameters[6].Type, ContractParameterType.Integer);
Assert.AreEqual(netTypes.Parameters[7].Type, ContractParameterType.Integer);
Assert.AreEqual(netTypes.Parameters[8].Type, ContractParameterType.Integer);
Assert.AreEqual(netTypes.Parameters[9].Type, ContractParameterType.Integer);
Assert.AreEqual(netTypes.Parameters[10].Type, ContractParameterType.ByteArray);
Assert.AreEqual(netTypes.Parameters[11].Type, ContractParameterType.String);
Assert.AreEqual(netTypes.Parameters[12].Type, ContractParameterType.Array);
Assert.AreEqual(netTypes.Parameters[13].Type, ContractParameterType.ByteArray);
Assert.AreEqual(netTypes.Parameters[14].Type, ContractParameterType.Array);
Assert.AreEqual(netTypes.Parameters[15].Type, ContractParameterType.Integer);
Assert.AreEqual(netTypes.Parameters[16].Type, ContractParameterType.Any);
var vmTypes = manifest.Abi.GetMethod("vMTypes");
Assert.AreEqual(vmTypes.ReturnType, ContractParameterType.Void);
Assert.AreEqual(vmTypes.Parameters[0].Type, ContractParameterType.Boolean);
Assert.AreEqual(vmTypes.Parameters[1].Type, ContractParameterType.Integer);
Assert.AreEqual(vmTypes.Parameters[2].Type, ContractParameterType.ByteArray);
Assert.AreEqual(vmTypes.Parameters[3].Type, ContractParameterType.ByteArray);
Assert.AreEqual(vmTypes.Parameters[4].Type, ContractParameterType.Array);
Assert.AreEqual(vmTypes.Parameters[5].Type, ContractParameterType.Array);
Assert.AreEqual(vmTypes.Parameters[6].Type, ContractParameterType.Map);
Assert.AreEqual(vmTypes.Parameters[7].Type, ContractParameterType.Any);
}
[TestMethod]
public void TestGetContract()
{
Assert.IsTrue(NativeContract.NEO == NativeContract.GetContract(NativeContract.NEO.Name));
Assert.IsTrue(NativeContract.NEO == NativeContract.GetContract(NativeContract.NEO.Hash));
}
[TestMethod]
public void TestInvoke()
{
var snapshot = Blockchain.Singleton.GetSnapshot();
ApplicationEngine engine = ApplicationEngine.Create(TriggerType.System, null, snapshot, 0);
engine.LoadScript(testNativeContract.Script);
ByteString method1 = new ByteString(System.Text.Encoding.Default.GetBytes("wrongMethod"));
VMArray args1 = new VMArray();
engine.CurrentContext.EvaluationStack.Push(args1);
engine.CurrentContext.EvaluationStack.Push(method1);
Assert.ThrowsException<KeyNotFoundException>(() => testNativeContract.Invoke(engine));
ByteString method2 = new ByteString(System.Text.Encoding.Default.GetBytes("onPersist"));
VMArray args2 = new VMArray();
engine.CurrentContext.EvaluationStack.Push(args2);
engine.CurrentContext.EvaluationStack.Push(method2);
testNativeContract.Invoke(engine);
}
[TestMethod]
public void TestOnPersistWithArgs()
{
var snapshot = Blockchain.Singleton.GetSnapshot();
ApplicationEngine engine1 = ApplicationEngine.Create(TriggerType.Application, null, snapshot, 0);
Assert.ThrowsException<InvalidOperationException>(() => testNativeContract.TestOnPersist(engine1));
ApplicationEngine engine2 = ApplicationEngine.Create(TriggerType.System, null, snapshot, 0);
testNativeContract.TestOnPersist(engine2);
}
[TestMethod]
public void TestTestCall()
{
ApplicationEngine engine = testNativeContract.TestCall("System.Blockchain.GetHeight", 0);
engine.ResultStack.Should().BeEmpty();
}
}
public class TestNativeContract : NativeContract
{
public override string Name => "test";
public override int Id => 0x10000006;
public void TestOnPersist(ApplicationEngine engine)
{
OnPersist(engine);
}
}
}
| 44.406667 | 120 | 0.665816 | [
"MIT"
] | Qiao-Jin/neo | tests/neo.UnitTests/SmartContract/Native/UT_NativeContract.cs | 6,661 | C# |
namespace CloudStack.Plugin.WmiWrappers.ROOT.CIMV2 {
using System;
using System.ComponentModel;
using System.Management;
using System.Collections;
using System.Globalization;
using System.ComponentModel.Design.Serialization;
using System.Reflection;
// Functions ShouldSerialize<PropertyName> are functions used by VS property browser to check if a particular property has to be serialized. These functions are added for all ValueType properties ( properties of type Int32, BOOL etc.. which cannot be set to null). These functions use Is<PropertyName>Null function. These functions are also used in the TypeConverter implementation for the properties to check for NULL value of property so that an empty value can be shown in Property browser in case of Drag and Drop in Visual studio.
// Functions Is<PropertyName>Null() are used to check if a property is NULL.
// Functions Reset<PropertyName> are added for Nullable Read/Write properties. These functions are used by VS designer in property browser to set a property to NULL.
// Every property added to the class for WMI property has attributes set to define its behavior in Visual Studio designer and also to define a TypeConverter to be used.
// An Early Bound class generated for the WMI class.Win32_PerfFormattedData_Counters_ProcessorInformation
public class PerfFormattedData_Counters_ProcessorInformation : System.ComponentModel.Component {
// Private property to hold the WMI namespace in which the class resides.
private static string CreatedWmiNamespace = "root\\CIMV2";
// Private property to hold the name of WMI class which created this class.
private static string CreatedClassName = "Win32_PerfFormattedData_Counters_ProcessorInformation";
// Private member variable to hold the ManagementScope which is used by the various methods.
private static System.Management.ManagementScope statMgmtScope = null;
private ManagementSystemProperties PrivateSystemProperties;
// Underlying lateBound WMI object.
private System.Management.ManagementObject PrivateLateBoundObject;
// Member variable to store the 'automatic commit' behavior for the class.
private bool AutoCommitProp;
// Private variable to hold the embedded property representing the instance.
private System.Management.ManagementBaseObject embeddedObj;
// The current WMI object used
private System.Management.ManagementBaseObject curObj;
// Flag to indicate if the instance is an embedded object.
private bool isEmbedded;
// Below are different overloads of constructors to initialize an instance of the class with a WMI object.
public PerfFormattedData_Counters_ProcessorInformation() {
this.InitializeObject(null, null, null);
}
public PerfFormattedData_Counters_ProcessorInformation(string keyName) {
this.InitializeObject(null, new System.Management.ManagementPath(PerfFormattedData_Counters_ProcessorInformation.ConstructPath(keyName)), null);
}
public PerfFormattedData_Counters_ProcessorInformation(System.Management.ManagementScope mgmtScope, string keyName) {
this.InitializeObject(((System.Management.ManagementScope)(mgmtScope)), new System.Management.ManagementPath(PerfFormattedData_Counters_ProcessorInformation.ConstructPath(keyName)), null);
}
public PerfFormattedData_Counters_ProcessorInformation(System.Management.ManagementPath path, System.Management.ObjectGetOptions getOptions) {
this.InitializeObject(null, path, getOptions);
}
public PerfFormattedData_Counters_ProcessorInformation(System.Management.ManagementScope mgmtScope, System.Management.ManagementPath path) {
this.InitializeObject(mgmtScope, path, null);
}
public PerfFormattedData_Counters_ProcessorInformation(System.Management.ManagementPath path) {
this.InitializeObject(null, path, null);
}
public PerfFormattedData_Counters_ProcessorInformation(System.Management.ManagementScope mgmtScope, System.Management.ManagementPath path, System.Management.ObjectGetOptions getOptions) {
this.InitializeObject(mgmtScope, path, getOptions);
}
public PerfFormattedData_Counters_ProcessorInformation(System.Management.ManagementObject theObject) {
Initialize();
if ((CheckIfProperClass(theObject) == true)) {
PrivateLateBoundObject = theObject;
PrivateSystemProperties = new ManagementSystemProperties(PrivateLateBoundObject);
curObj = PrivateLateBoundObject;
}
else {
throw new System.ArgumentException("Class name does not match.");
}
}
public PerfFormattedData_Counters_ProcessorInformation(System.Management.ManagementBaseObject theObject) {
Initialize();
if ((CheckIfProperClass(theObject) == true)) {
embeddedObj = theObject;
PrivateSystemProperties = new ManagementSystemProperties(theObject);
curObj = embeddedObj;
isEmbedded = true;
}
else {
throw new System.ArgumentException("Class name does not match.");
}
}
// Property returns the namespace of the WMI class.
[Browsable(true)]
[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
public string OriginatingNamespace {
get {
return "root\\CIMV2";
}
}
[Browsable(true)]
[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
public string ManagementClassName {
get {
string strRet = CreatedClassName;
if ((curObj != null)) {
if ((curObj.ClassPath != null)) {
strRet = ((string)(curObj["__CLASS"]));
if (((strRet == null)
|| (strRet == string.Empty))) {
strRet = CreatedClassName;
}
}
}
return strRet;
}
}
// Property pointing to an embedded object to get System properties of the WMI object.
[Browsable(true)]
[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
public ManagementSystemProperties SystemProperties {
get {
return PrivateSystemProperties;
}
}
// Property returning the underlying lateBound object.
[Browsable(false)]
[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
public System.Management.ManagementBaseObject LateBoundObject {
get {
return curObj;
}
}
// ManagementScope of the object.
[Browsable(true)]
[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
public System.Management.ManagementScope Scope {
get {
if ((isEmbedded == false)) {
return PrivateLateBoundObject.Scope;
}
else {
return null;
}
}
set {
if ((isEmbedded == false)) {
PrivateLateBoundObject.Scope = value;
}
}
}
// Property to show the commit behavior for the WMI object. If true, WMI object will be automatically saved after each property modification.(ie. Put() is called after modification of a property).
[Browsable(false)]
[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
public bool AutoCommit {
get {
return AutoCommitProp;
}
set {
AutoCommitProp = value;
}
}
// The ManagementPath of the underlying WMI object.
[Browsable(true)]
public System.Management.ManagementPath Path {
get {
if ((isEmbedded == false)) {
return PrivateLateBoundObject.Path;
}
else {
return null;
}
}
set {
if ((isEmbedded == false)) {
if ((CheckIfProperClass(null, value, null) != true)) {
throw new System.ArgumentException("Class name does not match.");
}
PrivateLateBoundObject.Path = value;
}
}
}
// Public static scope property which is used by the various methods.
[Browsable(true)]
[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
public static System.Management.ManagementScope StaticScope {
get {
return statMgmtScope;
}
set {
statMgmtScope = value;
}
}
[Browsable(false)]
[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
public bool IsAverageIdleTimeNull {
get {
if ((curObj["AverageIdleTime"] == null)) {
return true;
}
else {
return false;
}
}
}
[Browsable(true)]
[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
[Description("Average Idle Time is the average idle duration in 100ns units observed between th" +
"e last two samples.")]
[TypeConverter(typeof(WMIValueTypeConverter))]
public ulong AverageIdleTime {
get {
if ((curObj["AverageIdleTime"] == null)) {
return System.Convert.ToUInt64(0);
}
return ((ulong)(curObj["AverageIdleTime"]));
}
}
[Browsable(false)]
[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
public bool IsC1TransitionsPersecNull {
get {
if ((curObj["C1TransitionsPersec"] == null)) {
return true;
}
else {
return false;
}
}
}
[Browsable(true)]
[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
[Description(@"C1 Transitions/sec is the rate that the CPU enters the C1 low-power idle state. The CPU enters the C1 state when it is sufficiently idle and exits this state on any interrupt. This counter displays the difference between the values observed in the last two samples, divided by the duration of the sample interval.")]
[TypeConverter(typeof(WMIValueTypeConverter))]
public ulong C1TransitionsPersec {
get {
if ((curObj["C1TransitionsPersec"] == null)) {
return System.Convert.ToUInt64(0);
}
return ((ulong)(curObj["C1TransitionsPersec"]));
}
}
[Browsable(false)]
[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
public bool IsC2TransitionsPersecNull {
get {
if ((curObj["C2TransitionsPersec"] == null)) {
return true;
}
else {
return false;
}
}
}
[Browsable(true)]
[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
[Description(@"C2 Transitions/sec is the rate that the CPU enters the C2 low-power idle state. The CPU enters the C2 state when it is sufficiently idle and exits this state on any interrupt. This counter displays the difference between the values observed in the last two samples, divided by the duration of the sample interval.")]
[TypeConverter(typeof(WMIValueTypeConverter))]
public ulong C2TransitionsPersec {
get {
if ((curObj["C2TransitionsPersec"] == null)) {
return System.Convert.ToUInt64(0);
}
return ((ulong)(curObj["C2TransitionsPersec"]));
}
}
[Browsable(false)]
[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
public bool IsC3TransitionsPersecNull {
get {
if ((curObj["C3TransitionsPersec"] == null)) {
return true;
}
else {
return false;
}
}
}
[Browsable(true)]
[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
[Description(@"C3 Transitions/sec is the rate that the CPU enters the C3 low-power idle state. The CPU enters the C3 state when it is sufficiently idle and exits this state on any interrupt. This counter displays the difference between the values observed in the last two samples, divided by the duration of the sample interval.")]
[TypeConverter(typeof(WMIValueTypeConverter))]
public ulong C3TransitionsPersec {
get {
if ((curObj["C3TransitionsPersec"] == null)) {
return System.Convert.ToUInt64(0);
}
return ((ulong)(curObj["C3TransitionsPersec"]));
}
}
[Browsable(true)]
[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
[Description("A short textual description (one-line string) for the statistic or metric.")]
public string Caption {
get {
return ((string)(curObj["Caption"]));
}
}
[Browsable(false)]
[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
public bool IsClockInterruptsPersecNull {
get {
if ((curObj["ClockInterruptsPersec"] == null)) {
return true;
}
else {
return false;
}
}
}
[Browsable(true)]
[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
[Description(@"Clock Interrupts/sec is the average rate, in incidents per second, at which the processor received and serviced clock tick interrupts. This counter displays the difference between the values observed in the last two samples, divided by the duration of the sample interval.")]
[TypeConverter(typeof(WMIValueTypeConverter))]
public uint ClockInterruptsPersec {
get {
if ((curObj["ClockInterruptsPersec"] == null)) {
return System.Convert.ToUInt32(0);
}
return ((uint)(curObj["ClockInterruptsPersec"]));
}
}
[Browsable(true)]
[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
[Description("A textual description of the statistic or metric.")]
public string Description {
get {
return ((string)(curObj["Description"]));
}
}
[Browsable(false)]
[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
public bool IsDPCRateNull {
get {
if ((curObj["DPCRate"] == null)) {
return true;
}
else {
return false;
}
}
}
[Browsable(true)]
[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
[Description(@"DPC Rate is the rate at which deferred procedure calls (DPCs) were added to the processors DPC queues between the timer ticks of the processor clock. DPCs are interrupts that run at alower priority than standard interrupts. Each processor has its own DPC queue. This counter measures the rate that DPCs were added to the queue, not the number of DPCs in the queue. This counter displays the last observed value only; it is not an average.")]
[TypeConverter(typeof(WMIValueTypeConverter))]
public uint DPCRate {
get {
if ((curObj["DPCRate"] == null)) {
return System.Convert.ToUInt32(0);
}
return ((uint)(curObj["DPCRate"]));
}
}
[Browsable(false)]
[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
public bool IsDPCsQueuedPersecNull {
get {
if ((curObj["DPCsQueuedPersec"] == null)) {
return true;
}
else {
return false;
}
}
}
[Browsable(true)]
[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
[Description(@"DPCs Queued/sec is the average rate, in incidents per second, at which deferred procedure calls (DPCs) were added to the processor's DPC queue. DPCs are interrupts that run at a lower priority than standard interrupts. Each processor has its own DPC queue. This counter measures the rate that DPCs are added to the queue, not the number of DPCs in the queue. This counter displays the difference between the values observed in the last two samples, divided by the duration of the sample interval.")]
[TypeConverter(typeof(WMIValueTypeConverter))]
public uint DPCsQueuedPersec {
get {
if ((curObj["DPCsQueuedPersec"] == null)) {
return System.Convert.ToUInt32(0);
}
return ((uint)(curObj["DPCsQueuedPersec"]));
}
}
[Browsable(false)]
[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
public bool IsFrequency_ObjectNull {
get {
if ((curObj["Frequency_Object"] == null)) {
return true;
}
else {
return false;
}
}
}
[Browsable(true)]
[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
[TypeConverter(typeof(WMIValueTypeConverter))]
public ulong Frequency_Object {
get {
if ((curObj["Frequency_Object"] == null)) {
return System.Convert.ToUInt64(0);
}
return ((ulong)(curObj["Frequency_Object"]));
}
}
[Browsable(false)]
[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
public bool IsFrequency_PerfTimeNull {
get {
if ((curObj["Frequency_PerfTime"] == null)) {
return true;
}
else {
return false;
}
}
}
[Browsable(true)]
[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
[TypeConverter(typeof(WMIValueTypeConverter))]
public ulong Frequency_PerfTime {
get {
if ((curObj["Frequency_PerfTime"] == null)) {
return System.Convert.ToUInt64(0);
}
return ((ulong)(curObj["Frequency_PerfTime"]));
}
}
[Browsable(false)]
[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
public bool IsFrequency_Sys100NSNull {
get {
if ((curObj["Frequency_Sys100NS"] == null)) {
return true;
}
else {
return false;
}
}
}
[Browsable(true)]
[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
[TypeConverter(typeof(WMIValueTypeConverter))]
public ulong Frequency_Sys100NS {
get {
if ((curObj["Frequency_Sys100NS"] == null)) {
return System.Convert.ToUInt64(0);
}
return ((ulong)(curObj["Frequency_Sys100NS"]));
}
}
[Browsable(false)]
[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
public bool IsIdleBreakEventsPersecNull {
get {
if ((curObj["IdleBreakEventsPersec"] == null)) {
return true;
}
else {
return false;
}
}
}
[Browsable(true)]
[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
[Description("Idle Break Events/sec is the average rate, in incidents per second, at which the " +
"processor wakes from idle. This counter displays the difference between the val" +
"ues observed in the last two samples, divided by the duration of the sample inte" +
"rval.")]
[TypeConverter(typeof(WMIValueTypeConverter))]
public ulong IdleBreakEventsPersec {
get {
if ((curObj["IdleBreakEventsPersec"] == null)) {
return System.Convert.ToUInt64(0);
}
return ((ulong)(curObj["IdleBreakEventsPersec"]));
}
}
[Browsable(false)]
[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
public bool IsInterruptsPersecNull {
get {
if ((curObj["InterruptsPersec"] == null)) {
return true;
}
else {
return false;
}
}
}
[Browsable(true)]
[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
[Description(@"Interrupts/sec is the average rate, in incidents per second, at which the processor received and serviced hardware interrupts. It does not include deferred procedure calls (DPCs), which are counted separately. This value is an indirect indicator of the activity of devices that generate interrupts, such as the system clock, the mouse, disk drivers, data communication lines, network interface cards, and other peripheral devices. These devices normally interrupt the processor when they have completed a task or require attention. Normal thread execution is suspended. The system clock typically interrupts the processor every 10 milliseconds, creating a background of interrupt activity. This counter displays the difference between the values observed in the last two samples, divided by the duration of the sample interval.")]
[TypeConverter(typeof(WMIValueTypeConverter))]
public uint InterruptsPersec {
get {
if ((curObj["InterruptsPersec"] == null)) {
return System.Convert.ToUInt32(0);
}
return ((uint)(curObj["InterruptsPersec"]));
}
}
[Browsable(true)]
[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
[Description("The Name property defines the label by which the statistic or metric is known. Wh" +
"en subclassed, the property can be overridden to be a Key property. ")]
public string Name {
get {
return ((string)(curObj["Name"]));
}
}
[Browsable(false)]
[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
public bool IsParkingStatusNull {
get {
if ((curObj["ParkingStatus"] == null)) {
return true;
}
else {
return false;
}
}
}
[Browsable(true)]
[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
[Description("Parking Status represents whether a processor is parked or not.")]
[TypeConverter(typeof(WMIValueTypeConverter))]
public uint ParkingStatus {
get {
if ((curObj["ParkingStatus"] == null)) {
return System.Convert.ToUInt32(0);
}
return ((uint)(curObj["ParkingStatus"]));
}
}
[Browsable(false)]
[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
public bool IsPercentC1TimeNull {
get {
if ((curObj["PercentC1Time"] == null)) {
return true;
}
else {
return false;
}
}
}
[Browsable(true)]
[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
[Description(@"% C1 Time is the percentage of time the processor spends in the C1 low-power idle state. % C1 Time is a subset of the total processor idle time. C1 low-power idle state enables the processor to maintain its entire context and quickly return to the running state. Not all systems support the % C1 state.")]
[TypeConverter(typeof(WMIValueTypeConverter))]
public ulong PercentC1Time {
get {
if ((curObj["PercentC1Time"] == null)) {
return System.Convert.ToUInt64(0);
}
return ((ulong)(curObj["PercentC1Time"]));
}
}
[Browsable(false)]
[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
public bool IsPercentC2TimeNull {
get {
if ((curObj["PercentC2Time"] == null)) {
return true;
}
else {
return false;
}
}
}
[Browsable(true)]
[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
[Description(@"% C2 Time is the percentage of time the processor spends in the C2 low-power idle state. % C2 Time is a subset of the total processor idle time. C2 low-power idle state enables the processor to maintain the context of the system caches. The C2 power state is a lower power and higher exit latency state than C1. Not all systems support the C2 state.")]
[TypeConverter(typeof(WMIValueTypeConverter))]
public ulong PercentC2Time {
get {
if ((curObj["PercentC2Time"] == null)) {
return System.Convert.ToUInt64(0);
}
return ((ulong)(curObj["PercentC2Time"]));
}
}
[Browsable(false)]
[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
public bool IsPercentC3TimeNull {
get {
if ((curObj["PercentC3Time"] == null)) {
return true;
}
else {
return false;
}
}
}
[Browsable(true)]
[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
[Description(@"% C3 Time is the percentage of time the processor spends in the C3 low-power idle state. % C3 Time is a subset of the total processor idle time. When the processor is in the C3 low-power idle state it is unable to maintain the coherency of its caches. The C3 power state is a lower power and higher exit latency state than C2. Not all systems support the C3 state.")]
[TypeConverter(typeof(WMIValueTypeConverter))]
public ulong PercentC3Time {
get {
if ((curObj["PercentC3Time"] == null)) {
return System.Convert.ToUInt64(0);
}
return ((ulong)(curObj["PercentC3Time"]));
}
}
[Browsable(false)]
[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
public bool IsPercentDPCTimeNull {
get {
if ((curObj["PercentDPCTime"] == null)) {
return true;
}
else {
return false;
}
}
}
[Browsable(true)]
[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
[Description(@"% DPC Time is the percentage of time that the processor spent receiving and servicing deferred procedure calls (DPCs) during the sample interval. DPCs are interrupts that run at a lower priority than standard interrupts. % DPC Time is a component of % Privileged Time because DPCs are executed in privileged mode. They are counted separately and are not a component of the interrupt counters. This counter displays the average busy time as a percentage of the sample time.")]
[TypeConverter(typeof(WMIValueTypeConverter))]
public ulong PercentDPCTime {
get {
if ((curObj["PercentDPCTime"] == null)) {
return System.Convert.ToUInt64(0);
}
return ((ulong)(curObj["PercentDPCTime"]));
}
}
[Browsable(false)]
[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
public bool IsPercentIdleTimeNull {
get {
if ((curObj["PercentIdleTime"] == null)) {
return true;
}
else {
return false;
}
}
}
[Browsable(true)]
[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
[Description("% Idle Time is the percentage of time the processor is idle during the sample int" +
"erval")]
[TypeConverter(typeof(WMIValueTypeConverter))]
public ulong PercentIdleTime {
get {
if ((curObj["PercentIdleTime"] == null)) {
return System.Convert.ToUInt64(0);
}
return ((ulong)(curObj["PercentIdleTime"]));
}
}
[Browsable(false)]
[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
public bool IsPercentInterruptTimeNull {
get {
if ((curObj["PercentInterruptTime"] == null)) {
return true;
}
else {
return false;
}
}
}
[Browsable(true)]
[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
[Description(@"% Interrupt Time is the time the processor spends receiving and servicing hardware interrupts during sample intervals. This value is an indirect indicator of the activity of devices that generate interrupts, such as the system clock, the mouse, disk drivers, data communication lines, network interface cards and other peripheral devices. These devices normally interrupt the processor when they have completed a task or require attention. Normal thread execution is suspended during interrupts. Most system clocks interrupt the processor every 10 milliseconds, creating a background of interrupt activity. suspends normal thread execution during interrupts. This counter displays the average busy time as a percentage of the sample time.")]
[TypeConverter(typeof(WMIValueTypeConverter))]
public ulong PercentInterruptTime {
get {
if ((curObj["PercentInterruptTime"] == null)) {
return System.Convert.ToUInt64(0);
}
return ((ulong)(curObj["PercentInterruptTime"]));
}
}
[Browsable(false)]
[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
public bool IsPercentofMaximumFrequencyNull {
get {
if ((curObj["PercentofMaximumFrequency"] == null)) {
return true;
}
else {
return false;
}
}
}
[Browsable(true)]
[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
[Description("% of Maximum Frequency is the percentage of the current processor\'s maximum frequ" +
"ency.")]
[TypeConverter(typeof(WMIValueTypeConverter))]
public uint PercentofMaximumFrequency {
get {
if ((curObj["PercentofMaximumFrequency"] == null)) {
return System.Convert.ToUInt32(0);
}
return ((uint)(curObj["PercentofMaximumFrequency"]));
}
}
[Browsable(false)]
[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
public bool IsPercentPerformanceLimitNull {
get {
if ((curObj["PercentPerformanceLimit"] == null)) {
return true;
}
else {
return false;
}
}
}
[Browsable(true)]
[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
[Description(@"% Performance Limit is the performance the processor guarantees it can provide, as a percentage of the nominal performance of the processor. Performance can be limited by Windows power policy, or by the platform as a result of a power budget, overheating, or other hardware issues.")]
[TypeConverter(typeof(WMIValueTypeConverter))]
public uint PercentPerformanceLimit {
get {
if ((curObj["PercentPerformanceLimit"] == null)) {
return System.Convert.ToUInt32(0);
}
return ((uint)(curObj["PercentPerformanceLimit"]));
}
}
[Browsable(false)]
[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
public bool IsPercentPriorityTimeNull {
get {
if ((curObj["PercentPriorityTime"] == null)) {
return true;
}
else {
return false;
}
}
}
[Browsable(true)]
[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
[Description(@"% Priority Time is the percentage of elapsed time that the processor spends executing threads that are not low priority. It is calculated by measuring the percentage of time that the processor spends executing low priority threads or the idle thread and then subtracting that value from 100%. (Each processor has an idle thread to which time is accumulated when no other threads are ready to run). This counter displays the average percentage of busy time observed during the sample interval excluding low priority background work. It should be noted that the accounting calculation of whether the processor is idle is performed at an internal sampling interval of the system clock tick. % Priority Time can therefore underestimate the processor utilization as the processor may be spending a lot of time servicing threads between the system clock sampling interval. Workload based timer applications are one example of applications which are more likely to be measured inaccurately as timers are signaled just after the sample is taken.")]
[TypeConverter(typeof(WMIValueTypeConverter))]
public ulong PercentPriorityTime {
get {
if ((curObj["PercentPriorityTime"] == null)) {
return System.Convert.ToUInt64(0);
}
return ((ulong)(curObj["PercentPriorityTime"]));
}
}
[Browsable(false)]
[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
public bool IsPercentPrivilegedTimeNull {
get {
if ((curObj["PercentPrivilegedTime"] == null)) {
return true;
}
else {
return false;
}
}
}
[Browsable(true)]
[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
[Description(@"% Privileged Time is the percentage of elapsed time that the process threads spent executing code in privileged mode. When a Windows system service in called, the service will often run in privileged mode to gain access to system-private data. Such data is protected from access by threads executing in user mode. Calls to the system can be explicit or implicit, such as page faults or interrupts. Unlike some early operating systems, Windows uses process boundaries for subsystem protection in addition to the traditional protection of user and privileged modes. Some work done by Windows on behalf of the application might appear in other subsystem processes in addition to the privileged time in the process.")]
[TypeConverter(typeof(WMIValueTypeConverter))]
public ulong PercentPrivilegedTime {
get {
if ((curObj["PercentPrivilegedTime"] == null)) {
return System.Convert.ToUInt64(0);
}
return ((ulong)(curObj["PercentPrivilegedTime"]));
}
}
[Browsable(false)]
[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
public bool IsPercentPrivilegedUtilityNull {
get {
if ((curObj["PercentPrivilegedUtility"] == null)) {
return true;
}
else {
return false;
}
}
}
[Browsable(true)]
[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
[Description(@"Privileged Utility is the amount of work a processor is completing while executing in privileged mode, as a percentage of the amount of work the processor could complete if it were running at its nominal performance and never idle. On some processors, Privileged Utility may exceed 100%.")]
[TypeConverter(typeof(WMIValueTypeConverter))]
public ulong PercentPrivilegedUtility {
get {
if ((curObj["PercentPrivilegedUtility"] == null)) {
return System.Convert.ToUInt64(0);
}
return ((ulong)(curObj["PercentPrivilegedUtility"]));
}
}
[Browsable(false)]
[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
public bool IsPercentProcessorPerformanceNull {
get {
if ((curObj["PercentProcessorPerformance"] == null)) {
return true;
}
else {
return false;
}
}
}
[Browsable(true)]
[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
[Description("Processor Performance is the average performance of the processor while it is exe" +
"cuting instructions, as a percentage of the nominal performance of the processor" +
". On some processors, Processor Performance may exceed 100%.")]
[TypeConverter(typeof(WMIValueTypeConverter))]
public ulong PercentProcessorPerformance {
get {
if ((curObj["PercentProcessorPerformance"] == null)) {
return System.Convert.ToUInt64(0);
}
return ((ulong)(curObj["PercentProcessorPerformance"]));
}
}
[Browsable(false)]
[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
public bool IsPercentProcessorTimeNull {
get {
if ((curObj["PercentProcessorTime"] == null)) {
return true;
}
else {
return false;
}
}
}
[Browsable(true)]
[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
[Description(@"% Processor Time is the percentage of elapsed time that the processor spends to execute a non-Idle thread. It is calculated by measuring the percentage of time that the processor spends executing the idle thread and then subtracting that value from 100%. (Each processor has an idle thread to which time is accumulated when no other threads are ready to run). This counter is the primary indicator of processor activity, and displays the average percentage of busy time observed during the sample interval. It should be noted that the accounting calculation of whether the processor is idle is performed at an internal sampling interval of the system clock tick. On todays fast processors, % Processor Time can therefore underestimate the processor utilization as the processor may be spending a lot of time servicing threads between the system clock sampling interval. Workload based timer applications are one example of applications which are more likely to be measured inaccurately as timers are signaled just after the sample is taken.")]
[TypeConverter(typeof(WMIValueTypeConverter))]
public ulong PercentProcessorTime {
get {
if ((curObj["PercentProcessorTime"] == null)) {
return System.Convert.ToUInt64(0);
}
return ((ulong)(curObj["PercentProcessorTime"]));
}
}
[Browsable(false)]
[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
public bool IsPercentProcessorUtilityNull {
get {
if ((curObj["PercentProcessorUtility"] == null)) {
return true;
}
else {
return false;
}
}
}
[Browsable(true)]
[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
[Description("Processor Utility is the amount of work a processor is completing, as a percentag" +
"e of the amount of work the processor could complete if it were running at its n" +
"ominal performance and never idle. On some processors, Processor Utility may exc" +
"eed 100%.")]
[TypeConverter(typeof(WMIValueTypeConverter))]
public ulong PercentProcessorUtility {
get {
if ((curObj["PercentProcessorUtility"] == null)) {
return System.Convert.ToUInt64(0);
}
return ((ulong)(curObj["PercentProcessorUtility"]));
}
}
[Browsable(false)]
[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
public bool IsPercentUserTimeNull {
get {
if ((curObj["PercentUserTime"] == null)) {
return true;
}
else {
return false;
}
}
}
[Browsable(true)]
[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
[Description(@"% User Time is the percentage of elapsed time the processor spends in the user mode. User mode is a restricted processing mode designed for applications, environment subsystems, and integral subsystems. The alternative, privileged mode, is designed for operating system components and allows direct access to hardware and all memory. The operating system switches application threads to privileged mode to access operating system services. This counter displays the average busy time as a percentage of the sample time.")]
[TypeConverter(typeof(WMIValueTypeConverter))]
public ulong PercentUserTime {
get {
if ((curObj["PercentUserTime"] == null)) {
return System.Convert.ToUInt64(0);
}
return ((ulong)(curObj["PercentUserTime"]));
}
}
[Browsable(false)]
[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
public bool IsPerformanceLimitFlagsNull {
get {
if ((curObj["PerformanceLimitFlags"] == null)) {
return true;
}
else {
return false;
}
}
}
[Browsable(true)]
[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
[Description("Performance Limit Flags indicate reasons why the processor performance was limite" +
"d.")]
[TypeConverter(typeof(WMIValueTypeConverter))]
public uint PerformanceLimitFlags {
get {
if ((curObj["PerformanceLimitFlags"] == null)) {
return System.Convert.ToUInt32(0);
}
return ((uint)(curObj["PerformanceLimitFlags"]));
}
}
[Browsable(false)]
[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
public bool IsProcessorFrequencyNull {
get {
if ((curObj["ProcessorFrequency"] == null)) {
return true;
}
else {
return false;
}
}
}
[Browsable(true)]
[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
[Description("Processor Frequency is the frequency of the current processor in megahertz.")]
[TypeConverter(typeof(WMIValueTypeConverter))]
public uint ProcessorFrequency {
get {
if ((curObj["ProcessorFrequency"] == null)) {
return System.Convert.ToUInt32(0);
}
return ((uint)(curObj["ProcessorFrequency"]));
}
}
[Browsable(false)]
[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
public bool IsProcessorStateFlagsNull {
get {
if ((curObj["ProcessorStateFlags"] == null)) {
return true;
}
else {
return false;
}
}
}
[Browsable(true)]
[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
[Description("Processor State Flags")]
[TypeConverter(typeof(WMIValueTypeConverter))]
public uint ProcessorStateFlags {
get {
if ((curObj["ProcessorStateFlags"] == null)) {
return System.Convert.ToUInt32(0);
}
return ((uint)(curObj["ProcessorStateFlags"]));
}
}
[Browsable(false)]
[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
public bool IsTimestamp_ObjectNull {
get {
if ((curObj["Timestamp_Object"] == null)) {
return true;
}
else {
return false;
}
}
}
[Browsable(true)]
[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
[TypeConverter(typeof(WMIValueTypeConverter))]
public ulong Timestamp_Object {
get {
if ((curObj["Timestamp_Object"] == null)) {
return System.Convert.ToUInt64(0);
}
return ((ulong)(curObj["Timestamp_Object"]));
}
}
[Browsable(false)]
[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
public bool IsTimestamp_PerfTimeNull {
get {
if ((curObj["Timestamp_PerfTime"] == null)) {
return true;
}
else {
return false;
}
}
}
[Browsable(true)]
[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
[TypeConverter(typeof(WMIValueTypeConverter))]
public ulong Timestamp_PerfTime {
get {
if ((curObj["Timestamp_PerfTime"] == null)) {
return System.Convert.ToUInt64(0);
}
return ((ulong)(curObj["Timestamp_PerfTime"]));
}
}
[Browsable(false)]
[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
public bool IsTimestamp_Sys100NSNull {
get {
if ((curObj["Timestamp_Sys100NS"] == null)) {
return true;
}
else {
return false;
}
}
}
[Browsable(true)]
[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
[TypeConverter(typeof(WMIValueTypeConverter))]
public ulong Timestamp_Sys100NS {
get {
if ((curObj["Timestamp_Sys100NS"] == null)) {
return System.Convert.ToUInt64(0);
}
return ((ulong)(curObj["Timestamp_Sys100NS"]));
}
}
private bool CheckIfProperClass(System.Management.ManagementScope mgmtScope, System.Management.ManagementPath path, System.Management.ObjectGetOptions OptionsParam) {
if (((path != null)
&& (string.Compare(path.ClassName, this.ManagementClassName, true, System.Globalization.CultureInfo.InvariantCulture) == 0))) {
return true;
}
else {
return CheckIfProperClass(new System.Management.ManagementObject(mgmtScope, path, OptionsParam));
}
}
private bool CheckIfProperClass(System.Management.ManagementBaseObject theObj) {
if (((theObj != null)
&& (string.Compare(((string)(theObj["__CLASS"])), this.ManagementClassName, true, System.Globalization.CultureInfo.InvariantCulture) == 0))) {
return true;
}
else {
System.Array parentClasses = ((System.Array)(theObj["__DERIVATION"]));
if ((parentClasses != null)) {
int count = 0;
for (count = 0; (count < parentClasses.Length); count = (count + 1)) {
if ((string.Compare(((string)(parentClasses.GetValue(count))), this.ManagementClassName, true, System.Globalization.CultureInfo.InvariantCulture) == 0)) {
return true;
}
}
}
}
return false;
}
private bool ShouldSerializeAverageIdleTime() {
if ((this.IsAverageIdleTimeNull == false)) {
return true;
}
return false;
}
private bool ShouldSerializeC1TransitionsPersec() {
if ((this.IsC1TransitionsPersecNull == false)) {
return true;
}
return false;
}
private bool ShouldSerializeC2TransitionsPersec() {
if ((this.IsC2TransitionsPersecNull == false)) {
return true;
}
return false;
}
private bool ShouldSerializeC3TransitionsPersec() {
if ((this.IsC3TransitionsPersecNull == false)) {
return true;
}
return false;
}
private bool ShouldSerializeClockInterruptsPersec() {
if ((this.IsClockInterruptsPersecNull == false)) {
return true;
}
return false;
}
private bool ShouldSerializeDPCRate() {
if ((this.IsDPCRateNull == false)) {
return true;
}
return false;
}
private bool ShouldSerializeDPCsQueuedPersec() {
if ((this.IsDPCsQueuedPersecNull == false)) {
return true;
}
return false;
}
private bool ShouldSerializeFrequency_Object() {
if ((this.IsFrequency_ObjectNull == false)) {
return true;
}
return false;
}
private bool ShouldSerializeFrequency_PerfTime() {
if ((this.IsFrequency_PerfTimeNull == false)) {
return true;
}
return false;
}
private bool ShouldSerializeFrequency_Sys100NS() {
if ((this.IsFrequency_Sys100NSNull == false)) {
return true;
}
return false;
}
private bool ShouldSerializeIdleBreakEventsPersec() {
if ((this.IsIdleBreakEventsPersecNull == false)) {
return true;
}
return false;
}
private bool ShouldSerializeInterruptsPersec() {
if ((this.IsInterruptsPersecNull == false)) {
return true;
}
return false;
}
private bool ShouldSerializeParkingStatus() {
if ((this.IsParkingStatusNull == false)) {
return true;
}
return false;
}
private bool ShouldSerializePercentC1Time() {
if ((this.IsPercentC1TimeNull == false)) {
return true;
}
return false;
}
private bool ShouldSerializePercentC2Time() {
if ((this.IsPercentC2TimeNull == false)) {
return true;
}
return false;
}
private bool ShouldSerializePercentC3Time() {
if ((this.IsPercentC3TimeNull == false)) {
return true;
}
return false;
}
private bool ShouldSerializePercentDPCTime() {
if ((this.IsPercentDPCTimeNull == false)) {
return true;
}
return false;
}
private bool ShouldSerializePercentIdleTime() {
if ((this.IsPercentIdleTimeNull == false)) {
return true;
}
return false;
}
private bool ShouldSerializePercentInterruptTime() {
if ((this.IsPercentInterruptTimeNull == false)) {
return true;
}
return false;
}
private bool ShouldSerializePercentofMaximumFrequency() {
if ((this.IsPercentofMaximumFrequencyNull == false)) {
return true;
}
return false;
}
private bool ShouldSerializePercentPerformanceLimit() {
if ((this.IsPercentPerformanceLimitNull == false)) {
return true;
}
return false;
}
private bool ShouldSerializePercentPriorityTime() {
if ((this.IsPercentPriorityTimeNull == false)) {
return true;
}
return false;
}
private bool ShouldSerializePercentPrivilegedTime() {
if ((this.IsPercentPrivilegedTimeNull == false)) {
return true;
}
return false;
}
private bool ShouldSerializePercentPrivilegedUtility() {
if ((this.IsPercentPrivilegedUtilityNull == false)) {
return true;
}
return false;
}
private bool ShouldSerializePercentProcessorPerformance() {
if ((this.IsPercentProcessorPerformanceNull == false)) {
return true;
}
return false;
}
private bool ShouldSerializePercentProcessorTime() {
if ((this.IsPercentProcessorTimeNull == false)) {
return true;
}
return false;
}
private bool ShouldSerializePercentProcessorUtility() {
if ((this.IsPercentProcessorUtilityNull == false)) {
return true;
}
return false;
}
private bool ShouldSerializePercentUserTime() {
if ((this.IsPercentUserTimeNull == false)) {
return true;
}
return false;
}
private bool ShouldSerializePerformanceLimitFlags() {
if ((this.IsPerformanceLimitFlagsNull == false)) {
return true;
}
return false;
}
private bool ShouldSerializeProcessorFrequency() {
if ((this.IsProcessorFrequencyNull == false)) {
return true;
}
return false;
}
private bool ShouldSerializeProcessorStateFlags() {
if ((this.IsProcessorStateFlagsNull == false)) {
return true;
}
return false;
}
private bool ShouldSerializeTimestamp_Object() {
if ((this.IsTimestamp_ObjectNull == false)) {
return true;
}
return false;
}
private bool ShouldSerializeTimestamp_PerfTime() {
if ((this.IsTimestamp_PerfTimeNull == false)) {
return true;
}
return false;
}
private bool ShouldSerializeTimestamp_Sys100NS() {
if ((this.IsTimestamp_Sys100NSNull == false)) {
return true;
}
return false;
}
[Browsable(true)]
public void CommitObject() {
if ((isEmbedded == false)) {
PrivateLateBoundObject.Put();
}
}
[Browsable(true)]
public void CommitObject(System.Management.PutOptions putOptions) {
if ((isEmbedded == false)) {
PrivateLateBoundObject.Put(putOptions);
}
}
private void Initialize() {
AutoCommitProp = true;
isEmbedded = false;
}
private static string ConstructPath(string keyName) {
string strPath = "root\\CIMV2:Win32_PerfFormattedData_Counters_ProcessorInformation";
strPath = string.Concat(strPath, string.Concat(".Name=", string.Concat("\"", string.Concat(keyName, "\""))));
return strPath;
}
private void InitializeObject(System.Management.ManagementScope mgmtScope, System.Management.ManagementPath path, System.Management.ObjectGetOptions getOptions) {
Initialize();
if ((path != null)) {
if ((CheckIfProperClass(mgmtScope, path, getOptions) != true)) {
throw new System.ArgumentException("Class name does not match.");
}
}
PrivateLateBoundObject = new System.Management.ManagementObject(mgmtScope, path, getOptions);
PrivateSystemProperties = new ManagementSystemProperties(PrivateLateBoundObject);
curObj = PrivateLateBoundObject;
}
// Different overloads of GetInstances() help in enumerating instances of the WMI class.
public static PerfFormattedData_Counters_ProcessorInformationCollection GetInstances() {
return GetInstances(null, null, null);
}
public static PerfFormattedData_Counters_ProcessorInformationCollection GetInstances(string condition) {
return GetInstances(null, condition, null);
}
public static PerfFormattedData_Counters_ProcessorInformationCollection GetInstances(string[] selectedProperties) {
return GetInstances(null, null, selectedProperties);
}
public static PerfFormattedData_Counters_ProcessorInformationCollection GetInstances(string condition, string[] selectedProperties) {
return GetInstances(null, condition, selectedProperties);
}
public static PerfFormattedData_Counters_ProcessorInformationCollection GetInstances(System.Management.ManagementScope mgmtScope, System.Management.EnumerationOptions enumOptions) {
if ((mgmtScope == null)) {
if ((statMgmtScope == null)) {
mgmtScope = new System.Management.ManagementScope();
mgmtScope.Path.NamespacePath = "root\\CIMV2";
}
else {
mgmtScope = statMgmtScope;
}
}
System.Management.ManagementPath pathObj = new System.Management.ManagementPath();
pathObj.ClassName = "Win32_PerfFormattedData_Counters_ProcessorInformation";
pathObj.NamespacePath = "root\\CIMV2";
System.Management.ManagementClass clsObject = new System.Management.ManagementClass(mgmtScope, pathObj, null);
if ((enumOptions == null)) {
enumOptions = new System.Management.EnumerationOptions();
enumOptions.EnsureLocatable = true;
}
return new PerfFormattedData_Counters_ProcessorInformationCollection(clsObject.GetInstances(enumOptions));
}
public static PerfFormattedData_Counters_ProcessorInformationCollection GetInstances(System.Management.ManagementScope mgmtScope, string condition) {
return GetInstances(mgmtScope, condition, null);
}
public static PerfFormattedData_Counters_ProcessorInformationCollection GetInstances(System.Management.ManagementScope mgmtScope, string[] selectedProperties) {
return GetInstances(mgmtScope, null, selectedProperties);
}
public static PerfFormattedData_Counters_ProcessorInformationCollection GetInstances(System.Management.ManagementScope mgmtScope, string condition, string[] selectedProperties) {
if ((mgmtScope == null)) {
if ((statMgmtScope == null)) {
mgmtScope = new System.Management.ManagementScope();
mgmtScope.Path.NamespacePath = "root\\CIMV2";
}
else {
mgmtScope = statMgmtScope;
}
}
System.Management.ManagementObjectSearcher ObjectSearcher = new System.Management.ManagementObjectSearcher(mgmtScope, new SelectQuery("Win32_PerfFormattedData_Counters_ProcessorInformation", condition, selectedProperties));
System.Management.EnumerationOptions enumOptions = new System.Management.EnumerationOptions();
enumOptions.EnsureLocatable = true;
ObjectSearcher.Options = enumOptions;
return new PerfFormattedData_Counters_ProcessorInformationCollection(ObjectSearcher.Get());
}
[Browsable(true)]
public static PerfFormattedData_Counters_ProcessorInformation CreateInstance() {
System.Management.ManagementScope mgmtScope = null;
if ((statMgmtScope == null)) {
mgmtScope = new System.Management.ManagementScope();
mgmtScope.Path.NamespacePath = CreatedWmiNamespace;
}
else {
mgmtScope = statMgmtScope;
}
System.Management.ManagementPath mgmtPath = new System.Management.ManagementPath(CreatedClassName);
System.Management.ManagementClass tmpMgmtClass = new System.Management.ManagementClass(mgmtScope, mgmtPath, null);
return new PerfFormattedData_Counters_ProcessorInformation(tmpMgmtClass.CreateInstance());
}
[Browsable(true)]
public void Delete() {
PrivateLateBoundObject.Delete();
}
// Enumerator implementation for enumerating instances of the class.
public class PerfFormattedData_Counters_ProcessorInformationCollection : object, ICollection {
private ManagementObjectCollection privColObj;
public PerfFormattedData_Counters_ProcessorInformationCollection(ManagementObjectCollection objCollection) {
privColObj = objCollection;
}
public virtual int Count {
get {
return privColObj.Count;
}
}
public virtual bool IsSynchronized {
get {
return privColObj.IsSynchronized;
}
}
public virtual object SyncRoot {
get {
return this;
}
}
public virtual void CopyTo(System.Array array, int index) {
privColObj.CopyTo(array, index);
int nCtr;
for (nCtr = 0; (nCtr < array.Length); nCtr = (nCtr + 1)) {
array.SetValue(new PerfFormattedData_Counters_ProcessorInformation(((System.Management.ManagementObject)(array.GetValue(nCtr)))), nCtr);
}
}
public virtual System.Collections.IEnumerator GetEnumerator() {
return new PerfFormattedData_Counters_ProcessorInformationEnumerator(privColObj.GetEnumerator());
}
public class PerfFormattedData_Counters_ProcessorInformationEnumerator : object, System.Collections.IEnumerator {
private ManagementObjectCollection.ManagementObjectEnumerator privObjEnum;
public PerfFormattedData_Counters_ProcessorInformationEnumerator(ManagementObjectCollection.ManagementObjectEnumerator objEnum) {
privObjEnum = objEnum;
}
public virtual object Current {
get {
return new PerfFormattedData_Counters_ProcessorInformation(((System.Management.ManagementObject)(privObjEnum.Current)));
}
}
public virtual bool MoveNext() {
return privObjEnum.MoveNext();
}
public virtual void Reset() {
privObjEnum.Reset();
}
}
}
// TypeConverter to handle null values for ValueType properties
public class WMIValueTypeConverter : TypeConverter {
private TypeConverter baseConverter;
private System.Type baseType;
public WMIValueTypeConverter(System.Type inBaseType) {
baseConverter = TypeDescriptor.GetConverter(inBaseType);
baseType = inBaseType;
}
public override bool CanConvertFrom(System.ComponentModel.ITypeDescriptorContext context, System.Type srcType) {
return baseConverter.CanConvertFrom(context, srcType);
}
public override bool CanConvertTo(System.ComponentModel.ITypeDescriptorContext context, System.Type destinationType) {
return baseConverter.CanConvertTo(context, destinationType);
}
public override object ConvertFrom(System.ComponentModel.ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value) {
return baseConverter.ConvertFrom(context, culture, value);
}
public override object CreateInstance(System.ComponentModel.ITypeDescriptorContext context, System.Collections.IDictionary dictionary) {
return baseConverter.CreateInstance(context, dictionary);
}
public override bool GetCreateInstanceSupported(System.ComponentModel.ITypeDescriptorContext context) {
return baseConverter.GetCreateInstanceSupported(context);
}
public override PropertyDescriptorCollection GetProperties(System.ComponentModel.ITypeDescriptorContext context, object value, System.Attribute[] attributeVar) {
return baseConverter.GetProperties(context, value, attributeVar);
}
public override bool GetPropertiesSupported(System.ComponentModel.ITypeDescriptorContext context) {
return baseConverter.GetPropertiesSupported(context);
}
public override System.ComponentModel.TypeConverter.StandardValuesCollection GetStandardValues(System.ComponentModel.ITypeDescriptorContext context) {
return baseConverter.GetStandardValues(context);
}
public override bool GetStandardValuesExclusive(System.ComponentModel.ITypeDescriptorContext context) {
return baseConverter.GetStandardValuesExclusive(context);
}
public override bool GetStandardValuesSupported(System.ComponentModel.ITypeDescriptorContext context) {
return baseConverter.GetStandardValuesSupported(context);
}
public override object ConvertTo(System.ComponentModel.ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, System.Type destinationType) {
if ((baseType.BaseType == typeof(System.Enum))) {
if ((value.GetType() == destinationType)) {
return value;
}
if ((((value == null)
&& (context != null))
&& (context.PropertyDescriptor.ShouldSerializeValue(context.Instance) == false))) {
return "NULL_ENUM_VALUE" ;
}
return baseConverter.ConvertTo(context, culture, value, destinationType);
}
if (((baseType == typeof(bool))
&& (baseType.BaseType == typeof(System.ValueType)))) {
if ((((value == null)
&& (context != null))
&& (context.PropertyDescriptor.ShouldSerializeValue(context.Instance) == false))) {
return "";
}
return baseConverter.ConvertTo(context, culture, value, destinationType);
}
if (((context != null)
&& (context.PropertyDescriptor.ShouldSerializeValue(context.Instance) == false))) {
return "";
}
return baseConverter.ConvertTo(context, culture, value, destinationType);
}
}
// Embedded class to represent WMI system Properties.
[TypeConverter(typeof(System.ComponentModel.ExpandableObjectConverter))]
public class ManagementSystemProperties {
private System.Management.ManagementBaseObject PrivateLateBoundObject;
public ManagementSystemProperties(System.Management.ManagementBaseObject ManagedObject) {
PrivateLateBoundObject = ManagedObject;
}
[Browsable(true)]
public int GENUS {
get {
return ((int)(PrivateLateBoundObject["__GENUS"]));
}
}
[Browsable(true)]
public string CLASS {
get {
return ((string)(PrivateLateBoundObject["__CLASS"]));
}
}
[Browsable(true)]
public string SUPERCLASS {
get {
return ((string)(PrivateLateBoundObject["__SUPERCLASS"]));
}
}
[Browsable(true)]
public string DYNASTY {
get {
return ((string)(PrivateLateBoundObject["__DYNASTY"]));
}
}
[Browsable(true)]
public string RELPATH {
get {
return ((string)(PrivateLateBoundObject["__RELPATH"]));
}
}
[Browsable(true)]
public int PROPERTY_COUNT {
get {
return ((int)(PrivateLateBoundObject["__PROPERTY_COUNT"]));
}
}
[Browsable(true)]
public string[] DERIVATION {
get {
return ((string[])(PrivateLateBoundObject["__DERIVATION"]));
}
}
[Browsable(true)]
public string SERVER {
get {
return ((string)(PrivateLateBoundObject["__SERVER"]));
}
}
[Browsable(true)]
public string NAMESPACE {
get {
return ((string)(PrivateLateBoundObject["__NAMESPACE"]));
}
}
[Browsable(true)]
public string PATH {
get {
return ((string)(PrivateLateBoundObject["__PATH"]));
}
}
}
}
}
| 44.237629 | 1,069 | 0.557807 | [
"Apache-2.0"
] | lafferty/cshv3 | plugins/hypervisors/hyperv/DotNet/ServerResource/WmiWrappers/root.CIMV2.Win32_PerfFormattedData_Counters_ProcessorInformation.cs | 76,887 | C# |
using System;
using System.Collections.Generic;
namespace HotChocolate.Types.Sorting
{
public class SortVisitorContextBase
: ISortVisitorContextBase
{
protected SortVisitorContextBase(InputObjectType initialType)
{
if (initialType is null)
{
throw new ArgumentNullException(nameof(initialType));
}
Types.Push(initialType);
}
public Stack<IType> Types { get; } =
new Stack<IType>();
public Stack<IInputField> Operations { get; } =
new Stack<IInputField>();
}
}
| 24.44 | 69 | 0.592471 | [
"MIT"
] | Asshiah/hotchocolate | src/HotChocolate/Filters/src/Types.Sorting/SortVisitorContextBase.cs | 611 | C# |
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Threading.Tasks;
namespace TemperatureREST.Models
{
public enum TemperatureUnit
{
Fahrenheit, Celsius
}
public class Temperature
{
public int Id { get; set; }
[Required]
public DateTime? Time { get; set; }
[Required]
[Range(-200, 1000)]
public double? Value { get; set; }
[Required]
public TemperatureUnit? Unit { get; set; }
}
}
| 19.206897 | 50 | 0.61939 | [
"MIT"
] | 1811-nov27-net/TempRecords | TemperatureREST/TemperatureREST/Models/Temperature.cs | 559 | C# |
using System.Collections.Generic;
using System.Diagnostics;
namespace Demo.Module.Shell.ViewModels
{
class WelcomeVm
{
public WelcomeVm() { }
}
}
| 12.2 | 38 | 0.622951 | [
"Apache-2.0"
] | Pixytech/Frameworks | Demo.Module.Shell/ViewModels/WelcomeVm.cs | 185 | 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("Q07 Attempt 2")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Hewlett-Packard")]
[assembly: AssemblyProduct("Q07 Attempt 2")]
[assembly: AssemblyCopyright("Copyright © Hewlett-Packard 2018")]
[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("5350f7d1-4286-4ef3-8148-d8dc5fd67637")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| 38.486486 | 84 | 0.749298 | [
"MIT"
] | Uendy/Tech-Module | L05 Lists/L05 Lab Exercises/Q07 Attempt 2/Properties/AssemblyInfo.cs | 1,427 | C# |
using System;
namespace StructSamples
{
class Program
{
static void Main(string[] args)
{
PointStackOnly p = new PointStackOnly(100, 100);
// Compiler error: boxing not allowed!!!
// object obj = p;
}
private static void BoxingAndUnboxingStructs()
{
Point p = new Point(100, 100);
// boxing
object obj = p;
// unboxing
Point p2 = (Point)obj;
p2.Print();
// still boxing
IMovableObject mo = p.Move(50, 50);
// still unboxing
Point p3 = (Point)mo;
p3.Print();
}
private static void PointStructVsClass()
{
PointAsStruct ps1 = new PointAsStruct(100, 200);
PointAsStruct ps2 = ps1;
ps2.X = 200;
ps2.Y = 300;
ps1.Print(); // Point (struct) found at X=100, Y=200
ps2.Print(); // Point (struct) found at X=200, Y=300
// ---------------------- vs ----------------------
PointAsClass pc1 = new PointAsClass(100, 200);
PointAsClass pc2 = pc1;
pc2.X = 200;
pc2.Y = 300;
pc1.Print(); // Point(class) found at X=200, Y=300
pc2.Print(); // Point(class) found at X=200, Y=300
}
}
}
| 27.62 | 64 | 0.458364 | [
"MIT"
] | FastTrackIT-WON-1/structs | StructSamples/StructSamples/Program.cs | 1,383 | C# |
// Copyright (c) Microsoft Open Technologies, Inc. All rights reserved. See License.txt in the project root for license information.
namespace System.Data.Entity.Core.Common.CommandTrees.Internal
{
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Data.Entity.Utilities;
using System.Linq;
internal sealed class ParameterRetriever : BasicCommandTreeVisitor
{
private readonly Dictionary<string, DbParameterReferenceExpression> paramMappings =
new Dictionary<string, DbParameterReferenceExpression>();
private ParameterRetriever()
{
}
internal static ReadOnlyCollection<DbParameterReferenceExpression> GetParameters(DbCommandTree tree)
{
DebugCheck.NotNull(tree);
var retriever = new ParameterRetriever();
retriever.VisitCommandTree(tree);
return retriever.paramMappings.Values.ToList().AsReadOnly();
}
public override void Visit(DbParameterReferenceExpression expression)
{
Check.NotNull(expression, "expression");
paramMappings[expression.ParameterName] = expression;
}
}
}
| 34.555556 | 133 | 0.676045 | [
"Apache-2.0"
] | TerraVenil/entityframework | src/EntityFramework/Core/Common/CommandTrees/Internal/ParameterRetriever.cs | 1,244 | C# |
namespace OauthApp.Areas.HelpPage.ModelDescriptions
{
public class KeyValuePairModelDescription : ModelDescription
{
public ModelDescription KeyModelDescription { get; set; }
public ModelDescription ValueModelDescription { get; set; }
}
} | 29.666667 | 67 | 0.741573 | [
"MIT"
] | Derrick1908/OauthApp | OauthApp/Areas/HelpPage/ModelDescriptions/KeyValuePairModelDescription.cs | 267 | C# |
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;
namespace HedgeModManager
{
public static class CryptoProvider
{
public const string PublicModulus =
"1Zf2HKNkolr1CDKl4Y6FWkJlMu6SEHKc1lVTlHNtot1SJpwqCW9iKk3t80mOGhsv4Qc2ZEX2I0yKmRLmcnCSAXoBneyYTlE2yTWj1nI4iJv1x8PTWPiMZDnbljXj6rAIizbGoIgDx/xmmfIOCiIaS5c7A2CGnIHu+yLDlzG5gBU=";
public const string PublicExponent = "AQAB";
public static RSACryptoServiceProvider CryptoService = new RSACryptoServiceProvider(1024);
static CryptoProvider()
{
CryptoService.ImportParameters(new RSAParameters()
{
Modulus = Convert.FromBase64String(PublicModulus),
Exponent = Convert.FromBase64String(PublicExponent)
});
}
public static void ImportParameters(RSAParameters parameters)
=> CryptoService.ImportParameters(parameters);
public static byte[] Encrypt(byte[] data)
{
using (var source = new MemoryStream(data))
using (var destination = new MemoryStream())
{
Encrypt(source, destination);
return destination.ToArray();
}
}
public static void Encrypt(Stream source, Stream destination)
{
using (var writer = new BinaryWriter(destination))
using (var aes = new AesCryptoServiceProvider())
{
aes.GenerateKey();
aes.GenerateIV();
var encryptedKey = CryptoService.Encrypt(aes.Key, false);
writer.Write(encryptedKey.Length);
writer.Write(encryptedKey);
var encryptedIv = CryptoService.Encrypt(aes.IV, false);
writer.Write(encryptedIv.Length);
writer.Write(encryptedIv);
using (var enc = aes.CreateEncryptor())
using (var cryptoStream = new CryptoStream(destination, enc, CryptoStreamMode.Write))
{
source.CopyTo(cryptoStream);
}
}
}
public static byte[] Decrypt(byte[] data)
{
using (var source = new MemoryStream(data))
using (var destination = new MemoryStream())
{
Decrypt(source, destination);
return destination.ToArray();
}
}
public static void Decrypt(Stream source, Stream destination)
{
using (var reader = new BinaryReader(source))
using (var aes = new AesCryptoServiceProvider())
{
var encryptedKey = reader.ReadBytes(reader.ReadInt32());
var encryptedIv = reader.ReadBytes(reader.ReadInt32());
aes.Key = CryptoService.Decrypt(encryptedKey, false);
aes.IV = CryptoService.Decrypt(encryptedIv, false);
using (var dec = aes.CreateDecryptor())
using (var cryptoStream = new CryptoStream(source, dec, CryptoStreamMode.Read))
{
cryptoStream.CopyTo(destination);
}
}
}
}
}
| 34.520833 | 187 | 0.585094 | [
"MIT"
] | Ahremic/HedgeModManager | HedgeModManager/CryptoProvider.cs | 3,316 | C# |
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Runtime.Serialization;
using System.Web.Script.Serialization;
using System.Xml.Serialization;
using XCode;
using XCode.Configuration;
using XCode.DataAccessLayer;
namespace XUnitTest.XCode.TestEntity
{
/// <summary>用户</summary>
[Serializable]
[DataObject]
[Description("用户")]
[BindIndex("IU_User2_Name", true, "Name")]
[BindIndex("IX_User2_RoleID", false, "RoleID")]
[BindTable("User2", Description = "用户", ConnName = "test", DbType = DatabaseType.None)]
public partial class User2
{
#region 属性
private Int32 _ID;
/// <summary>编号</summary>
[DisplayName("编号")]
[Description("编号")]
[DataObjectField(true, true, false, 0)]
[BindColumn("ID", "编号", "")]
public Int32 ID { get => _ID; set { if (OnPropertyChanging("ID", value)) { _ID = value; OnPropertyChanged("ID"); } } }
private String _Name;
/// <summary>名称。登录用户名</summary>
[DisplayName("名称")]
[Description("名称。登录用户名")]
[DataObjectField(false, false, false, 50)]
[BindColumn("Name", "名称。登录用户名", "", Master = true)]
public String Name { get => _Name; set { if (OnPropertyChanging("Name", value)) { _Name = value; OnPropertyChanged("Name"); } } }
private String _Password;
/// <summary>密码</summary>
[DisplayName("密码")]
[Description("密码")]
[DataObjectField(false, false, true, 50)]
[BindColumn("Password", "密码", "")]
public String Password { get => _Password; set { if (OnPropertyChanging("Password", value)) { _Password = value; OnPropertyChanged("Password"); } } }
private String _DisplayName;
/// <summary>昵称</summary>
[DisplayName("昵称")]
[Description("昵称")]
[DataObjectField(false, false, true, 50)]
[BindColumn("DisplayName", "昵称", "")]
public String DisplayName { get => _DisplayName; set { if (OnPropertyChanging("DisplayName", value)) { _DisplayName = value; OnPropertyChanged("DisplayName"); } } }
private SexKinds _Sex;
/// <summary>性别。未知、男、女</summary>
[DisplayName("性别")]
[Description("性别。未知、男、女")]
[DataObjectField(false, false, false, 0)]
[BindColumn("Sex", "性别。未知、男、女", "")]
public SexKinds Sex { get => _Sex; set { if (OnPropertyChanging("Sex", value)) { _Sex = value; OnPropertyChanged("Sex"); } } }
private String _Mail;
/// <summary>邮件</summary>
[DisplayName("邮件")]
[Description("邮件")]
[DataObjectField(false, false, true, 50)]
[BindColumn("Mail", "邮件", "", ItemType = "mail")]
public String Mail { get => _Mail; set { if (OnPropertyChanging("Mail", value)) { _Mail = value; OnPropertyChanged("Mail"); } } }
private String _Mobile;
/// <summary>手机</summary>
[DisplayName("手机")]
[Description("手机")]
[DataObjectField(false, false, true, 50)]
[BindColumn("Mobile", "手机", "", ItemType = "mobile")]
public String Mobile { get => _Mobile; set { if (OnPropertyChanging("Mobile", value)) { _Mobile = value; OnPropertyChanged("Mobile"); } } }
private String _Code;
/// <summary>代码。身份证、员工编号等</summary>
[DisplayName("代码")]
[Description("代码。身份证、员工编号等")]
[DataObjectField(false, false, true, 50)]
[BindColumn("Code", "代码。身份证、员工编号等", "")]
public String Code { get => _Code; set { if (OnPropertyChanging("Code", value)) { _Code = value; OnPropertyChanged("Code"); } } }
private String _Avatar;
/// <summary>头像</summary>
[DisplayName("头像")]
[Description("头像")]
[DataObjectField(false, false, true, 200)]
[BindColumn("Avatar", "头像", "", ItemType = "image")]
public String Avatar { get => _Avatar; set { if (OnPropertyChanging("Avatar", value)) { _Avatar = value; OnPropertyChanged("Avatar"); } } }
private Int32 _RoleID;
/// <summary>角色。主要角色</summary>
[DisplayName("角色")]
[Description("角色。主要角色")]
[DataObjectField(false, false, false, 0)]
[BindColumn("RoleID", "角色。主要角色", "")]
public Int32 RoleID { get => _RoleID; set { if (OnPropertyChanging("RoleID", value)) { _RoleID = value; OnPropertyChanged("RoleID"); } } }
private String _RoleIds;
/// <summary>角色组。次要角色集合</summary>
[DisplayName("角色组")]
[Description("角色组。次要角色集合")]
[DataObjectField(false, false, true, 200)]
[BindColumn("RoleIds", "角色组。次要角色集合", "")]
public String RoleIds { get => _RoleIds; set { if (OnPropertyChanging("RoleIds", value)) { _RoleIds = value; OnPropertyChanged("RoleIds"); } } }
private Int32 _DepartmentID;
/// <summary>部门。组织机构</summary>
[DisplayName("部门")]
[Description("部门。组织机构")]
[DataObjectField(false, false, false, 0)]
[BindColumn("DepartmentID", "部门。组织机构", "")]
public Int32 DepartmentID { get => _DepartmentID; set { if (OnPropertyChanging("DepartmentID", value)) { _DepartmentID = value; OnPropertyChanged("DepartmentID"); } } }
private Boolean _Online;
/// <summary>在线</summary>
[DisplayName("在线")]
[Description("在线")]
[DataObjectField(false, false, false, 0)]
[BindColumn("Online", "在线", "")]
public Boolean Online { get => _Online; set { if (OnPropertyChanging("Online", value)) { _Online = value; OnPropertyChanged("Online"); } } }
private Boolean _Enable;
/// <summary>启用</summary>
[DisplayName("启用")]
[Description("启用")]
[DataObjectField(false, false, false, 0)]
[BindColumn("Enable", "启用", "")]
public Boolean Enable { get => _Enable; set { if (OnPropertyChanging("Enable", value)) { _Enable = value; OnPropertyChanged("Enable"); } } }
private Int32 _Logins;
/// <summary>登录次数</summary>
[DisplayName("登录次数")]
[Description("登录次数")]
[DataObjectField(false, false, false, 0)]
[BindColumn("Logins", "登录次数", "")]
public Int32 Logins { get => _Logins; set { if (OnPropertyChanging("Logins", value)) { _Logins = value; OnPropertyChanged("Logins"); } } }
private DateTime _LastLogin;
/// <summary>最后登录</summary>
[DisplayName("最后登录")]
[Description("最后登录")]
[DataObjectField(false, false, true, 0)]
[BindColumn("LastLogin", "最后登录", "")]
public DateTime LastLogin { get => _LastLogin; set { if (OnPropertyChanging("LastLogin", value)) { _LastLogin = value; OnPropertyChanged("LastLogin"); } } }
private String _LastLoginIP;
/// <summary>最后登录IP</summary>
[DisplayName("最后登录IP")]
[Description("最后登录IP")]
[DataObjectField(false, false, true, 50)]
[BindColumn("LastLoginIP", "最后登录IP", "")]
public String LastLoginIP { get => _LastLoginIP; set { if (OnPropertyChanging("LastLoginIP", value)) { _LastLoginIP = value; OnPropertyChanged("LastLoginIP"); } } }
private DateTime _RegisterTime;
/// <summary>注册时间</summary>
[DisplayName("注册时间")]
[Description("注册时间")]
[DataObjectField(false, false, true, 0)]
[BindColumn("RegisterTime", "注册时间", "")]
public DateTime RegisterTime { get => _RegisterTime; set { if (OnPropertyChanging("RegisterTime", value)) { _RegisterTime = value; OnPropertyChanged("RegisterTime"); } } }
private String _RegisterIP;
/// <summary>注册IP</summary>
[DisplayName("注册IP")]
[Description("注册IP")]
[DataObjectField(false, false, true, 50)]
[BindColumn("RegisterIP", "注册IP", "")]
public String RegisterIP { get => _RegisterIP; set { if (OnPropertyChanging("RegisterIP", value)) { _RegisterIP = value; OnPropertyChanged("RegisterIP"); } } }
private Int32 _Ex1;
/// <summary>扩展1</summary>
[DisplayName("扩展1")]
[Description("扩展1")]
[DataObjectField(false, false, false, 0)]
[BindColumn("Ex1", "扩展1", "")]
public Int32 Ex1 { get => _Ex1; set { if (OnPropertyChanging("Ex1", value)) { _Ex1 = value; OnPropertyChanged("Ex1"); } } }
private Int32 _Ex2;
/// <summary>扩展2</summary>
[DisplayName("扩展2")]
[Description("扩展2")]
[DataObjectField(false, false, false, 0)]
[BindColumn("Ex2", "扩展2", "")]
public Int32 Ex2 { get => _Ex2; set { if (OnPropertyChanging("Ex2", value)) { _Ex2 = value; OnPropertyChanged("Ex2"); } } }
private Double _Ex3;
/// <summary>扩展3</summary>
[DisplayName("扩展3")]
[Description("扩展3")]
[DataObjectField(false, false, false, 0)]
[BindColumn("Ex3", "扩展3", "")]
public Double Ex3 { get => _Ex3; set { if (OnPropertyChanging("Ex3", value)) { _Ex3 = value; OnPropertyChanged("Ex3"); } } }
private String _Ex4;
/// <summary>扩展4</summary>
[DisplayName("扩展4")]
[Description("扩展4")]
[DataObjectField(false, false, true, 50)]
[BindColumn("Ex4", "扩展4", "")]
public String Ex4 { get => _Ex4; set { if (OnPropertyChanging("Ex4", value)) { _Ex4 = value; OnPropertyChanged("Ex4"); } } }
private String _Ex5;
/// <summary>扩展5</summary>
[DisplayName("扩展5")]
[Description("扩展5")]
[DataObjectField(false, false, true, 50)]
[BindColumn("Ex5", "扩展5", "")]
public String Ex5 { get => _Ex5; set { if (OnPropertyChanging("Ex5", value)) { _Ex5 = value; OnPropertyChanged("Ex5"); } } }
private String _Ex6;
/// <summary>扩展6</summary>
[XmlIgnore, ScriptIgnore, IgnoreDataMember]
[DisplayName("扩展6")]
[Description("扩展6")]
[DataObjectField(false, false, true, 50)]
[BindColumn("Ex6", "扩展6", "")]
public String Ex6 { get => _Ex6; set { if (OnPropertyChanging("Ex6", value)) { _Ex6 = value; OnPropertyChanged("Ex6"); } } }
private String _UpdateUser;
/// <summary>更新者</summary>
[DisplayName("更新者")]
[Description("更新者")]
[DataObjectField(false, false, true, 50)]
[BindColumn("UpdateUser", "更新者", "")]
public String UpdateUser { get => _UpdateUser; set { if (OnPropertyChanging("UpdateUser", value)) { _UpdateUser = value; OnPropertyChanged("UpdateUser"); } } }
private Int32 _UpdateUserID;
/// <summary>更新用户</summary>
[DisplayName("更新用户")]
[Description("更新用户")]
[DataObjectField(false, false, false, 0)]
[BindColumn("UpdateUserID", "更新用户", "")]
public Int32 UpdateUserID { get => _UpdateUserID; set { if (OnPropertyChanging("UpdateUserID", value)) { _UpdateUserID = value; OnPropertyChanged("UpdateUserID"); } } }
private String _UpdateIP;
/// <summary>更新地址</summary>
[DisplayName("更新地址")]
[Description("更新地址")]
[DataObjectField(false, false, true, 50)]
[BindColumn("UpdateIP", "更新地址", "")]
public String UpdateIP { get => _UpdateIP; set { if (OnPropertyChanging("UpdateIP", value)) { _UpdateIP = value; OnPropertyChanged("UpdateIP"); } } }
private DateTime _UpdateTime;
/// <summary>更新时间</summary>
[DisplayName("更新时间")]
[Description("更新时间")]
[DataObjectField(false, false, false, 0)]
[BindColumn("UpdateTime", "更新时间", "")]
public DateTime UpdateTime { get => _UpdateTime; set { if (OnPropertyChanging("UpdateTime", value)) { _UpdateTime = value; OnPropertyChanged("UpdateTime"); } } }
private String _Remark;
/// <summary>备注</summary>
[DisplayName("备注")]
[Description("备注")]
[DataObjectField(false, false, true, 200)]
[BindColumn("Remark", "备注", "")]
public String Remark { get => _Remark; set { if (OnPropertyChanging("Remark", value)) { _Remark = value; OnPropertyChanged("Remark"); } } }
#endregion
#region 获取/设置 字段值
/// <summary>获取/设置 字段值</summary>
/// <param name="name">字段名</param>
/// <returns></returns>
public override Object this[String name]
{
get
{
switch (name)
{
case "ID": return _ID;
case "Name": return _Name;
case "Password": return _Password;
case "DisplayName": return _DisplayName;
case "Sex": return _Sex;
case "Mail": return _Mail;
case "Mobile": return _Mobile;
case "Code": return _Code;
case "Avatar": return _Avatar;
case "RoleID": return _RoleID;
case "RoleIds": return _RoleIds;
case "DepartmentID": return _DepartmentID;
case "Online": return _Online;
case "Enable": return _Enable;
case "Logins": return _Logins;
case "LastLogin": return _LastLogin;
case "LastLoginIP": return _LastLoginIP;
case "RegisterTime": return _RegisterTime;
case "RegisterIP": return _RegisterIP;
case "Ex1": return _Ex1;
case "Ex2": return _Ex2;
case "Ex3": return _Ex3;
case "Ex4": return _Ex4;
case "Ex5": return _Ex5;
case "Ex6": return _Ex6;
case "UpdateUser": return _UpdateUser;
case "UpdateUserID": return _UpdateUserID;
case "UpdateIP": return _UpdateIP;
case "UpdateTime": return _UpdateTime;
case "Remark": return _Remark;
default: return base[name];
}
}
set
{
switch (name)
{
case "ID": _ID = value.ToInt(); break;
case "Name": _Name = Convert.ToString(value); break;
case "Password": _Password = Convert.ToString(value); break;
case "DisplayName": _DisplayName = Convert.ToString(value); break;
case "Sex": _Sex = (SexKinds)value.ToInt(); break;
case "Mail": _Mail = Convert.ToString(value); break;
case "Mobile": _Mobile = Convert.ToString(value); break;
case "Code": _Code = Convert.ToString(value); break;
case "Avatar": _Avatar = Convert.ToString(value); break;
case "RoleID": _RoleID = value.ToInt(); break;
case "RoleIds": _RoleIds = Convert.ToString(value); break;
case "DepartmentID": _DepartmentID = value.ToInt(); break;
case "Online": _Online = value.ToBoolean(); break;
case "Enable": _Enable = value.ToBoolean(); break;
case "Logins": _Logins = value.ToInt(); break;
case "LastLogin": _LastLogin = value.ToDateTime(); break;
case "LastLoginIP": _LastLoginIP = Convert.ToString(value); break;
case "RegisterTime": _RegisterTime = value.ToDateTime(); break;
case "RegisterIP": _RegisterIP = Convert.ToString(value); break;
case "Ex1": _Ex1 = value.ToInt(); break;
case "Ex2": _Ex2 = value.ToInt(); break;
case "Ex3": _Ex3 = value.ToDouble(); break;
case "Ex4": _Ex4 = Convert.ToString(value); break;
case "Ex5": _Ex5 = Convert.ToString(value); break;
case "Ex6": _Ex6 = Convert.ToString(value); break;
case "UpdateUser": _UpdateUser = Convert.ToString(value); break;
case "UpdateUserID": _UpdateUserID = value.ToInt(); break;
case "UpdateIP": _UpdateIP = Convert.ToString(value); break;
case "UpdateTime": _UpdateTime = value.ToDateTime(); break;
case "Remark": _Remark = Convert.ToString(value); break;
default: base[name] = value; break;
}
}
}
#endregion
#region 字段名
/// <summary>取得用户字段信息的快捷方式</summary>
public partial class _
{
/// <summary>编号</summary>
public static readonly Field ID = FindByName("ID");
/// <summary>名称。登录用户名</summary>
public static readonly Field Name = FindByName("Name");
/// <summary>密码</summary>
public static readonly Field Password = FindByName("Password");
/// <summary>昵称</summary>
public static readonly Field DisplayName = FindByName("DisplayName");
/// <summary>性别。未知、男、女</summary>
public static readonly Field Sex = FindByName("Sex");
/// <summary>邮件</summary>
public static readonly Field Mail = FindByName("Mail");
/// <summary>手机</summary>
public static readonly Field Mobile = FindByName("Mobile");
/// <summary>代码。身份证、员工编号等</summary>
public static readonly Field Code = FindByName("Code");
/// <summary>头像</summary>
public static readonly Field Avatar = FindByName("Avatar");
/// <summary>角色。主要角色</summary>
public static readonly Field RoleID = FindByName("RoleID");
/// <summary>角色组。次要角色集合</summary>
public static readonly Field RoleIds = FindByName("RoleIds");
/// <summary>部门。组织机构</summary>
public static readonly Field DepartmentID = FindByName("DepartmentID");
/// <summary>在线</summary>
public static readonly Field Online = FindByName("Online");
/// <summary>启用</summary>
public static readonly Field Enable = FindByName("Enable");
/// <summary>登录次数</summary>
public static readonly Field Logins = FindByName("Logins");
/// <summary>最后登录</summary>
public static readonly Field LastLogin = FindByName("LastLogin");
/// <summary>最后登录IP</summary>
public static readonly Field LastLoginIP = FindByName("LastLoginIP");
/// <summary>注册时间</summary>
public static readonly Field RegisterTime = FindByName("RegisterTime");
/// <summary>注册IP</summary>
public static readonly Field RegisterIP = FindByName("RegisterIP");
/// <summary>扩展1</summary>
public static readonly Field Ex1 = FindByName("Ex1");
/// <summary>扩展2</summary>
public static readonly Field Ex2 = FindByName("Ex2");
/// <summary>扩展3</summary>
public static readonly Field Ex3 = FindByName("Ex3");
/// <summary>扩展4</summary>
public static readonly Field Ex4 = FindByName("Ex4");
/// <summary>扩展5</summary>
public static readonly Field Ex5 = FindByName("Ex5");
/// <summary>扩展6</summary>
public static readonly Field Ex6 = FindByName("Ex6");
/// <summary>更新者</summary>
public static readonly Field UpdateUser = FindByName("UpdateUser");
/// <summary>更新用户</summary>
public static readonly Field UpdateUserID = FindByName("UpdateUserID");
/// <summary>更新地址</summary>
public static readonly Field UpdateIP = FindByName("UpdateIP");
/// <summary>更新时间</summary>
public static readonly Field UpdateTime = FindByName("UpdateTime");
/// <summary>备注</summary>
public static readonly Field Remark = FindByName("Remark");
static Field FindByName(String name) => Meta.Table.FindByName(name);
}
/// <summary>取得用户字段名称的快捷方式</summary>
public partial class __
{
/// <summary>编号</summary>
public const String ID = "ID";
/// <summary>名称。登录用户名</summary>
public const String Name = "Name";
/// <summary>密码</summary>
public const String Password = "Password";
/// <summary>昵称</summary>
public const String DisplayName = "DisplayName";
/// <summary>性别。未知、男、女</summary>
public const String Sex = "Sex";
/// <summary>邮件</summary>
public const String Mail = "Mail";
/// <summary>手机</summary>
public const String Mobile = "Mobile";
/// <summary>代码。身份证、员工编号等</summary>
public const String Code = "Code";
/// <summary>头像</summary>
public const String Avatar = "Avatar";
/// <summary>角色。主要角色</summary>
public const String RoleID = "RoleID";
/// <summary>角色组。次要角色集合</summary>
public const String RoleIds = "RoleIds";
/// <summary>部门。组织机构</summary>
public const String DepartmentID = "DepartmentID";
/// <summary>在线</summary>
public const String Online = "Online";
/// <summary>启用</summary>
public const String Enable = "Enable";
/// <summary>登录次数</summary>
public const String Logins = "Logins";
/// <summary>最后登录</summary>
public const String LastLogin = "LastLogin";
/// <summary>最后登录IP</summary>
public const String LastLoginIP = "LastLoginIP";
/// <summary>注册时间</summary>
public const String RegisterTime = "RegisterTime";
/// <summary>注册IP</summary>
public const String RegisterIP = "RegisterIP";
/// <summary>扩展1</summary>
public const String Ex1 = "Ex1";
/// <summary>扩展2</summary>
public const String Ex2 = "Ex2";
/// <summary>扩展3</summary>
public const String Ex3 = "Ex3";
/// <summary>扩展4</summary>
public const String Ex4 = "Ex4";
/// <summary>扩展5</summary>
public const String Ex5 = "Ex5";
/// <summary>扩展6</summary>
public const String Ex6 = "Ex6";
/// <summary>更新者</summary>
public const String UpdateUser = "UpdateUser";
/// <summary>更新用户</summary>
public const String UpdateUserID = "UpdateUserID";
/// <summary>更新地址</summary>
public const String UpdateIP = "UpdateIP";
/// <summary>更新时间</summary>
public const String UpdateTime = "UpdateTime";
/// <summary>备注</summary>
public const String Remark = "Remark";
}
#endregion
}
} | 42.396296 | 179 | 0.55888 | [
"MIT"
] | NewLifeX/X | XUnitTest.XCode/TestEntity/用户.cs | 24,314 | C# |
using Elsa.Events;
using Elsa.Testing.Events;
using MediatR;
using System;
using System.Threading;
using System.Threading.Tasks;
namespace Elsa.Activities.RabbitMq.Testing
{
public class ConfigureRabbitMqActivitiesForTestHandler : INotificationHandler<WorkflowExecuting>, INotificationHandler<WorkflowFaulted>, INotificationHandler<WorkflowCompleted>, INotificationHandler<WorkflowTestExecutionStopped>
{
private readonly IRabbitMqTestQueueManager _rabbitMqTestQueueManager;
public ConfigureRabbitMqActivitiesForTestHandler(IRabbitMqTestQueueManager rabbitMqTestQueueManager)
{
_rabbitMqTestQueueManager = rabbitMqTestQueueManager;
}
public async Task Handle(WorkflowExecuting notification, CancellationToken cancellationToken)
{
var isTest = Convert.ToBoolean(notification.WorkflowExecutionContext.WorkflowInstance.GetMetadata("isTest"));
if (!isTest) return;
var workflowId = notification.WorkflowExecutionContext.WorkflowBlueprint.Id;
var workflowInstanceId = notification.WorkflowExecutionContext.WorkflowInstance.Id;
await _rabbitMqTestQueueManager.CreateTestWorkersAsync(workflowId, workflowInstanceId, cancellationToken);
}
public Task Handle(WorkflowFaulted notification, CancellationToken cancellationToken)
{
return HandleTesttWorkflowExecutionFinished(notification, cancellationToken);
}
public Task Handle(WorkflowCompleted notification, CancellationToken cancellationToken)
{
return HandleTesttWorkflowExecutionFinished(notification, cancellationToken);
}
public Task Handle(WorkflowTestExecutionStopped notification, CancellationToken cancellationToken)
{
_rabbitMqTestQueueManager.DisposeTestWorkersAsync(notification.WorkflowInstanceId);
return Task.CompletedTask;
}
private Task HandleTesttWorkflowExecutionFinished(WorkflowNotification notification, CancellationToken cancellationToken)
{
var isTest = Convert.ToBoolean(notification.WorkflowExecutionContext.WorkflowInstance.GetMetadata("isTest"));
if (!isTest) return Task.CompletedTask;
var workflowInstanceId = notification.WorkflowExecutionContext.WorkflowInstance.Id;
_rabbitMqTestQueueManager.DisposeTestWorkersAsync(workflowInstanceId);
return Task.CompletedTask;
}
}
} | 39.761905 | 232 | 0.752495 | [
"MIT"
] | MilkyWare/elsa-core | src/activities/Elsa.Activities.RabbitMq/Testing/Handlers/ConfigureRabbitMqActivitiesForTestHandler.cs | 2,505 | C# |
using System;
namespace WSCT.EMV.Security
{
// TODO: implement CDA
/// <summary>
/// Represents an EMV Combined Data Authentication certificate (CDA).
/// </summary>
public class SignedCombinedApplicationData : AbstractDataAuthenticationFormat05
{
#region >> AbstractSignatureContainer
/// <param name="privateKeyLength"></param>
/// <inheritdoc />
protected override byte[] GetDataToSign(int privateKeyLength)
{
// TODO : Build data to sign
throw new NotImplementedException();
}
#endregion
}
} | 26.391304 | 83 | 0.622735 | [
"MIT"
] | wsct/WSCT-EMV | EMV Library/Security/SignedCombinedApplicationData.cs | 609 | C# |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
namespace System.Device.Model
{
/// <summary>
/// Interface attribute
/// </summary>
[AttributeUsage(AttributeTargets.Class, Inherited = true, AllowMultiple = false)]
public class InterfaceAttribute : Attribute
{
/// <summary>
/// Display name of the interface
/// </summary>
public string DisplayName { get; }
/// <summary>
/// Constructs InterfaceAttrbute
/// </summary>
/// <param name="displayName">Display name of the interface</param>
public InterfaceAttribute(string displayName)
{
DisplayName = displayName;
}
}
}
| 29.259259 | 85 | 0.61519 | [
"MIT"
] | 0000duck/iot | src/devices/System.Device.Model/InterfaceAttribute.cs | 792 | C# |
using System;
using System.Collections.Generic;
using System.Text;
namespace Genesis.Cli.Extensions
{
//public static class GenesisExtensions
//{
// public static void Yes(this GenesisCommand command)
// {
// //just
// }
//}
}
| 18.2 | 61 | 0.608059 | [
"MIT"
] | AWHServiceAccount/genesis | src/Genesis.Cli.Extensions/GenesisExtensions.cs | 275 | C# |
using NDesk.Options;
using NetCoreServer;
using System;
using System.Collections.Generic;
using System.Net.Sockets;
using System.Security.Authentication;
using System.Security.Cryptography.X509Certificates;
using System.Text;
using System.Threading;
namespace WssMulticastClient
{
class MulticastClient : WssClient
{
public MulticastClient(SslContext context, string address, int port) : base(context, address, port)
{
}
public override void OnWsConnecting(HttpRequest request)
{
request.SetBegin("GET", "/");
request.SetHeader("Host", "localhost");
request.SetHeader("Origin", "http://localhost");
request.SetHeader("Upgrade", "websocket");
request.SetHeader("Connection", "Upgrade");
request.SetHeader("Sec-WebSocket-Key", Convert.ToBase64String(WsNonce));
request.SetHeader("Sec-WebSocket-Protocol", "chat, superchat");
request.SetHeader("Sec-WebSocket-Version", "13");
}
public override void OnWsReceived(byte[] buffer, long offset, long size)
{
Program.TotalBytes += size;
}
protected override void OnError(SocketError error)
{
Console.WriteLine($"Client caught an error with code {error}");
Program.TotalErrors++;
}
}
class Program
{
public static byte[] MessageToSend;
public static DateTime TimestampStart = DateTime.UtcNow;
public static DateTime TimestampStop = DateTime.UtcNow;
public static long TotalErrors;
public static long TotalBytes;
public static long TotalMessages;
static void Main(string[] args)
{
bool help = false;
string address = "127.0.0.1";
int port = 8443;
int clients = 100;
int size = 32;
int seconds = 10;
var options = new OptionSet()
{
{ "h|?|help", v => help = v != null },
{ "a|address=", v => address = v },
{ "p|port=", v => port = int.Parse(v) },
{ "c|clients=", v => clients = int.Parse(v) },
{ "s|size=", v => size = int.Parse(v) },
{ "z|seconds=", v => seconds = int.Parse(v) }
};
try
{
options.Parse(args);
}
catch (OptionException e)
{
Console.Write("Command line error: ");
Console.WriteLine(e.Message);
Console.WriteLine("Try `--help' to get usage information.");
return;
}
if (help)
{
Console.WriteLine("Usage:");
options.WriteOptionDescriptions(Console.Out);
return;
}
Console.WriteLine($"Server address: {address}");
Console.WriteLine($"Server port: {port}");
Console.WriteLine($"Working clients: {clients}");
Console.WriteLine($"Message size: {size}");
Console.WriteLine($"Seconds to benchmarking: {seconds}");
Console.WriteLine();
// Prepare a message to send
MessageToSend = new byte[size];
// Create and prepare a new SSL client context
var context = new SslContext(SslProtocols.Tls12, new X509Certificate2("client.pfx", "qwerty"), (sender, certificate, chain, sslPolicyErrors) => true);
// Create multicast clients
var multicastClients = new List<MulticastClient>();
for (int i = 0; i < clients; i++)
{
var client = new MulticastClient(context, address, port);
// client.OptionNoDelay = true;
multicastClients.Add(client);
}
TimestampStart = DateTime.UtcNow;
// Connect clients
Console.Write("Clients connecting...");
foreach (var client in multicastClients)
client.ConnectAsync();
Console.WriteLine("Done!");
foreach (var client in multicastClients)
while (!client.IsConnected)
Thread.Yield();
Console.WriteLine("All clients connected!");
// Wait for benchmarking
Console.Write("Benchmarking...");
Thread.Sleep(seconds * 1000);
Console.WriteLine("Done!");
// Disconnect clients
Console.Write("Clients disconnecting...");
foreach (var client in multicastClients)
client.CloseAsync(100);
Console.WriteLine("Done!");
foreach (var client in multicastClients)
while (client.IsConnected)
Thread.Yield();
Console.WriteLine("All clients disconnected!");
TimestampStop = DateTime.UtcNow;
Console.WriteLine();
Console.WriteLine($"Errors: {TotalErrors}");
Console.WriteLine();
TotalMessages = TotalBytes / size;
Console.WriteLine($"Total time: {Utilities.GenerateTimePeriod((TimestampStop - TimestampStart).TotalMilliseconds)}");
Console.WriteLine($"Total data: {Utilities.GenerateDataSize(TotalBytes)}");
Console.WriteLine($"Total messages: {TotalMessages}");
Console.WriteLine($"Data throughput: {Utilities.GenerateDataSize((long)(TotalBytes / (TimestampStop - TimestampStart).TotalSeconds))}/s");
if (TotalMessages > 0)
{
Console.WriteLine($"Message latency: {Utilities.GenerateTimePeriod((TimestampStop - TimestampStart).TotalMilliseconds / TotalMessages)}");
Console.WriteLine($"Message throughput: {(long)(TotalMessages / (TimestampStop - TimestampStart).TotalSeconds)} msg/s");
}
}
}
}
| 36.666667 | 162 | 0.559428 | [
"MIT"
] | GerHobbelt/NetCoreServer | performance/WssMulticastClient/Program.cs | 5,942 | C# |
#if WITH_EDITOR
#if PLATFORM_64BITS
using System;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
namespace UnrealEngine
{
/// <summary>Implements the settings for garbage collection.</summary>
public partial class UGarbageCollectionSettings
{
static readonly int TimeBetweenPurgingPendingKillObjects__Offset;
/// <summary>Time in seconds (game time) we should wait between purging object references to objects that are pending kill.</summary>
public float TimeBetweenPurgingPendingKillObjects
{
get{ CheckIsValid();return (float)Marshal.PtrToStructure(_this.Get()+TimeBetweenPurgingPendingKillObjects__Offset, typeof(float));}
set{ CheckIsValid();Marshal.StructureToPtr(value, _this.Get()+TimeBetweenPurgingPendingKillObjects__Offset, false);}
}
static readonly int FlushStreamingOnGC__Offset;
/// <summary>If enabled, streaming will be flushed each time garbage collection is triggered.</summary>
public bool FlushStreamingOnGC
{
get{ CheckIsValid();return BoolWrap.Get(_this.Get(), FlushStreamingOnGC__Offset, 1, 0, 1, 1);}
set{ CheckIsValid();BoolWrap.Set(value,_this.Get(), FlushStreamingOnGC__Offset, 1,0,1,1);}
}
static readonly int AllowParallelGC__Offset;
/// <summary>If enabled, garbage collection will use multiple threads.</summary>
public bool AllowParallelGC
{
get{ CheckIsValid();return BoolWrap.Get(_this.Get(), AllowParallelGC__Offset, 1, 0, 2, 2);}
set{ CheckIsValid();BoolWrap.Set(value,_this.Get(), AllowParallelGC__Offset, 1,0,2,2);}
}
static readonly int CreateGCClusters__Offset;
/// <summary>If true, the engine will attempt to create clusters of objects for better garbage collection performance.</summary>
public bool CreateGCClusters
{
get{ CheckIsValid();return BoolWrap.Get(_this.Get(), CreateGCClusters__Offset, 1, 0, 4, 4);}
set{ CheckIsValid();BoolWrap.Set(value,_this.Get(), CreateGCClusters__Offset, 1,0,4,4);}
}
static readonly int MergeGCClusters__Offset;
/// <summary>If true, when creating clusters, the clusters referenced from another cluster will get merged into one big cluster.</summary>
public bool MergeGCClusters
{
get{ CheckIsValid();return BoolWrap.Get(_this.Get(), MergeGCClusters__Offset, 1, 0, 8, 8);}
set{ CheckIsValid();BoolWrap.Set(value,_this.Get(), MergeGCClusters__Offset, 1,0,8,8);}
}
static readonly int NumRetriesBeforeForcingGC__Offset;
/// <summary>Maximum number of times GC can be skipped if worker threads are currently modifying UObject state. 0 = never force GC</summary>
public int NumRetriesBeforeForcingGC
{
get{ CheckIsValid();return (int)Marshal.PtrToStructure(_this.Get()+NumRetriesBeforeForcingGC__Offset, typeof(int));}
set{ CheckIsValid();Marshal.StructureToPtr(value, _this.Get()+NumRetriesBeforeForcingGC__Offset, false);}
}
static readonly int MaxObjectsNotConsideredByGC__Offset;
/// <summary>Maximum Object Count Not Considered By GC. Works only in cooked builds.</summary>
public int MaxObjectsNotConsideredByGC
{
get{ CheckIsValid();return (int)Marshal.PtrToStructure(_this.Get()+MaxObjectsNotConsideredByGC__Offset, typeof(int));}
set{ CheckIsValid();Marshal.StructureToPtr(value, _this.Get()+MaxObjectsNotConsideredByGC__Offset, false);}
}
static readonly int SizeOfPermanentObjectPool__Offset;
/// <summary>Size Of Permanent Object Pool (bytes). Works only in cooked builds.</summary>
public int SizeOfPermanentObjectPool
{
get{ CheckIsValid();return (int)Marshal.PtrToStructure(_this.Get()+SizeOfPermanentObjectPool__Offset, typeof(int));}
set{ CheckIsValid();Marshal.StructureToPtr(value, _this.Get()+SizeOfPermanentObjectPool__Offset, false);}
}
static readonly int MaxObjectsInGame__Offset;
/// <summary>Maximum number of UObjects that can exist in cooked game. Keep this as small as possible.</summary>
public int MaxObjectsInGame
{
get{ CheckIsValid();return (int)Marshal.PtrToStructure(_this.Get()+MaxObjectsInGame__Offset, typeof(int));}
set{ CheckIsValid();Marshal.StructureToPtr(value, _this.Get()+MaxObjectsInGame__Offset, false);}
}
static readonly int MaxObjectsInEditor__Offset;
/// <summary>Maximum number of UObjects that can exist in the editor game. Make sure this can hold enough objects for the editor and commadlets within reasonable limit.</summary>
public int MaxObjectsInEditor
{
get{ CheckIsValid();return (int)Marshal.PtrToStructure(_this.Get()+MaxObjectsInEditor__Offset, typeof(int));}
set{ CheckIsValid();Marshal.StructureToPtr(value, _this.Get()+MaxObjectsInEditor__Offset, false);}
}
static UGarbageCollectionSettings()
{
IntPtr NativeClassPtr=GetNativeClassFromName("GarbageCollectionSettings");
TimeBetweenPurgingPendingKillObjects__Offset=GetPropertyOffset(NativeClassPtr,"TimeBetweenPurgingPendingKillObjects");
FlushStreamingOnGC__Offset=GetPropertyOffset(NativeClassPtr,"FlushStreamingOnGC");
AllowParallelGC__Offset=GetPropertyOffset(NativeClassPtr,"AllowParallelGC");
CreateGCClusters__Offset=GetPropertyOffset(NativeClassPtr,"CreateGCClusters");
MergeGCClusters__Offset=GetPropertyOffset(NativeClassPtr,"MergeGCClusters");
NumRetriesBeforeForcingGC__Offset=GetPropertyOffset(NativeClassPtr,"NumRetriesBeforeForcingGC");
MaxObjectsNotConsideredByGC__Offset=GetPropertyOffset(NativeClassPtr,"MaxObjectsNotConsideredByGC");
SizeOfPermanentObjectPool__Offset=GetPropertyOffset(NativeClassPtr,"SizeOfPermanentObjectPool");
MaxObjectsInGame__Offset=GetPropertyOffset(NativeClassPtr,"MaxObjectsInGame");
MaxObjectsInEditor__Offset=GetPropertyOffset(NativeClassPtr,"MaxObjectsInEditor");
}
}
}
#endif
#endif
| 47.032787 | 180 | 0.780934 | [
"MIT"
] | RobertAcksel/UnrealCS | Engine/Plugins/UnrealCS/UECSharpDomain/UnrealEngine/GeneratedScriptFile_Editor_64bits/UGarbageCollectionSettings_FixSize.cs | 5,738 | C# |
/*
* Copyright (c) 2018 THL A29 Limited, a Tencent company. 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.
*/
namespace TencentCloud.Sms.V20190711.Models
{
using Newtonsoft.Json;
using System.Collections.Generic;
using TencentCloud.Common;
public class PullSmsSendStatus : AbstractModel
{
/// <summary>
/// 用户实际接收到短信的时间
/// </summary>
[JsonProperty("UserReceiveTime")]
public string UserReceiveTime{ get; set; }
/// <summary>
/// 国家(或地区)码
/// </summary>
[JsonProperty("NationCode")]
public string NationCode{ get; set; }
/// <summary>
/// 手机号码,e.164标准,+[国家或地区码][手机号] ,示例如:+8613711112222, 其中前面有一个+号 ,86为国家码,13711112222为手机号
/// </summary>
[JsonProperty("PurePhoneNumber")]
public string PurePhoneNumber{ get; set; }
/// <summary>
/// 手机号码,普通格式,示例如:13711112222
/// </summary>
[JsonProperty("PhoneNumber")]
public string PhoneNumber{ get; set; }
/// <summary>
/// 本次发送标识 ID
/// </summary>
[JsonProperty("SerialNo")]
public string SerialNo{ get; set; }
/// <summary>
/// 实际是否收到短信接收状态,SUCCESS(成功)、FAIL(失败)
/// </summary>
[JsonProperty("ReportStatus")]
public string ReportStatus{ get; set; }
/// <summary>
/// 用户接收短信状态描述
/// </summary>
[JsonProperty("Description")]
public string Description{ get; set; }
/// <summary>
/// 内部实现,用户禁止调用
/// </summary>
internal override void ToMap(Dictionary<string, string> map, string prefix)
{
this.SetParamSimple(map, prefix + "UserReceiveTime", this.UserReceiveTime);
this.SetParamSimple(map, prefix + "NationCode", this.NationCode);
this.SetParamSimple(map, prefix + "PurePhoneNumber", this.PurePhoneNumber);
this.SetParamSimple(map, prefix + "PhoneNumber", this.PhoneNumber);
this.SetParamSimple(map, prefix + "SerialNo", this.SerialNo);
this.SetParamSimple(map, prefix + "ReportStatus", this.ReportStatus);
this.SetParamSimple(map, prefix + "Description", this.Description);
}
}
}
| 32.651163 | 94 | 0.610399 | [
"Apache-2.0"
] | Darkfaker/tencentcloud-sdk-dotnet | TencentCloud/Sms/V20190711/Models/PullSmsSendStatus.cs | 3,054 | C# |
namespace Ateliex.Areas.Comercial.Enums
{
public enum PlanoComercialCustoTipo
{
Fixo = 1,
Variavel = 2,
}
}
| 15.222222 | 40 | 0.59854 | [
"MIT"
] | ateliex/MicrosoftDrivenDesign | src/Ateliex.Windows/Areas/Comercial/Enums/PlanoComercialCustoTipo.cs | 139 | C# |
/*
* US-Appends
*
* The US Appends service is a Quadient Cloud Data Services offering designed to help you improve and enhance the quality of your US-based contact data. The service can be used as a component of regular list cleansing and maintenance. The service flags contact records that match entries on do-not-mail and deceased person lists. It identifies addresses within correctional facilities. It also provides and corrects secondary data for an address, such as apartment number or floor number. This service can reduce mailing costs by identifying people that are unwilling or unable to respond or have an undeliverable address. It helps bring into focus for your assessment whether a potential communication recipient should be removed from a list. ## Key functionality: * Flags records that match entries on do-not-mail, deceased person, and correctional facility lists. * Appends missing apartment number unit information to an address to improve address quality. ## Job execution The general flow to execute a batch job is to: 1. Create a job, specifying its configuration properties, and upload and download schema (input fields and output fields). You cannot change the job's configuration after creation. 2. Upload records you want to process via one or more calls to the `/jobs/{job_id}/records` endpoint. Records are uploaded in blocks. The records are stored on the server for processing. 3. Initiate processing by calling the `/jobs/{job_id}/_run` endpoint. 4. Wait for the job status to be updated to `SUCCESS` or `FAILED`. 5. Download the records. 6. Delete job when you are done by requesting a `DELETE` on the `/jobs/{job_id}` endpoint, removing input and output records. ## Records The upload of records must be complete prior to running the service. Records are categorized as `input` or `output`. The schema (fields and order) of the records is defined via the job creation call. ## Pagination Records for a job are broken into pages (`page_id`) for retrieval. The collection of record page IDs is available via the `/jobs/{job_id}/records/pages` endpoint. Retrieve this collection as a precursor to downloading records. Each record page can then be retrieved by the client. Page IDs are immutable and can be retrieved in parallel. Record pages may also be retrieved multiple times if needed. ## Outcome codes ### Apartment Append `A1` - Apartment information confirmed to be correct for the individual. No changes made. `A2` - Apartment information present confirmed to be correct for the address. No changes made. `A4` - Not a highrise address. Address valid as input. `A5` - Multiple contact names in input. `C1` - Apartment information appended to address. `C4` - Lookup attempted. No apartment found. `E1` - Address was invalid as input. No changes made. `E2` - No contact name information supplied. No changes made. `E4` - No lookup attempted. ### Name Append `C1` - Name appended. `C4` - Name not appended. ### Gender Append `C1` - Gender added. `C2` - No gender added. `C3` - Multiple names. No gender assigned. `C4` - Ambiguous result. No gender assigned. ## Field value definitions ### Gender Append `gender`, possible values: `M` - Male `F` - Female `U` - Unable to assign / Ambiguous
*
* 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 = Quadient.DataServices.Model.Client.SwaggerDateConverter;
namespace Quadient.DataServices.Model.UsBatch
{
/// <summary>
/// Specifies the output fields that are populated.
/// </summary>
/// <value>Specifies the output fields that are populated.</value>
[JsonConverter(typeof(StringEnumConverter))]
public enum USAppendsOutputField
{
/// <summary>
/// Enum Id for value: id
/// </summary>
[EnumMember(Value = "id")]
Id = 1,
/// <summary>
/// Enum Isdonotmail for value: is_do_not_mail
/// </summary>
[EnumMember(Value = "is_do_not_mail")]
Isdonotmail = 2,
/// <summary>
/// Enum Isprison for value: is_prison
/// </summary>
[EnumMember(Value = "is_prison")]
Isprison = 3,
/// <summary>
/// Enum Isdeceased for value: is_deceased
/// </summary>
[EnumMember(Value = "is_deceased")]
Isdeceased = 4,
/// <summary>
/// Enum Isnursinghome for value: is_nursing_home
/// </summary>
[EnumMember(Value = "is_nursing_home")]
Isnursinghome = 5,
/// <summary>
/// Enum Deceaseddateofdeath for value: deceased_date_of_death
/// </summary>
[EnumMember(Value = "deceased_date_of_death")]
Deceaseddateofdeath = 6,
/// <summary>
/// Enum Deceaseddateofbirth for value: deceased_date_of_birth
/// </summary>
[EnumMember(Value = "deceased_date_of_birth")]
Deceaseddateofbirth = 7,
/// <summary>
/// Enum Apartmentunitinformation for value: apartment_unit_information
/// </summary>
[EnumMember(Value = "apartment_unit_information")]
Apartmentunitinformation = 8,
/// <summary>
/// Enum Apartmentaddressline for value: apartment_address_line
/// </summary>
[EnumMember(Value = "apartment_address_line")]
Apartmentaddressline = 9,
/// <summary>
/// Enum Apartmentappendcodes for value: apartment_append_codes
/// </summary>
[EnumMember(Value = "apartment_append_codes")]
Apartmentappendcodes = 10,
/// <summary>
/// Enum Namefullname for value: name_full_name
/// </summary>
[EnumMember(Value = "name_full_name")]
Namefullname = 11,
/// <summary>
/// Enum Namegivenname for value: name_given_name
/// </summary>
[EnumMember(Value = "name_given_name")]
Namegivenname = 12,
/// <summary>
/// Enum Namemiddlename for value: name_middle_name
/// </summary>
[EnumMember(Value = "name_middle_name")]
Namemiddlename = 13,
/// <summary>
/// Enum Namefamilyname for value: name_family_name
/// </summary>
[EnumMember(Value = "name_family_name")]
Namefamilyname = 14,
/// <summary>
/// Enum Nameappendcodes for value: name_append_codes
/// </summary>
[EnumMember(Value = "name_append_codes")]
Nameappendcodes = 15,
/// <summary>
/// Enum Gender for value: gender
/// </summary>
[EnumMember(Value = "gender")]
Gender = 16,
/// <summary>
/// Enum Gendercodes for value: gender_codes
/// </summary>
[EnumMember(Value = "gender_codes")]
Gendercodes = 17,
/// <summary>
/// Enum Custom1 for value: custom_1
/// </summary>
[EnumMember(Value = "custom_1")]
Custom1 = 18,
/// <summary>
/// Enum Custom2 for value: custom_2
/// </summary>
[EnumMember(Value = "custom_2")]
Custom2 = 19,
/// <summary>
/// Enum Custom3 for value: custom_3
/// </summary>
[EnumMember(Value = "custom_3")]
Custom3 = 20,
/// <summary>
/// Enum Custom4 for value: custom_4
/// </summary>
[EnumMember(Value = "custom_4")]
Custom4 = 21,
/// <summary>
/// Enum Custom5 for value: custom_5
/// </summary>
[EnumMember(Value = "custom_5")]
Custom5 = 22,
/// <summary>
/// Enum Custom6 for value: custom_6
/// </summary>
[EnumMember(Value = "custom_6")]
Custom6 = 23,
/// <summary>
/// Enum Custom7 for value: custom_7
/// </summary>
[EnumMember(Value = "custom_7")]
Custom7 = 24,
/// <summary>
/// Enum Custom8 for value: custom_8
/// </summary>
[EnumMember(Value = "custom_8")]
Custom8 = 25,
/// <summary>
/// Enum Custom9 for value: custom_9
/// </summary>
[EnumMember(Value = "custom_9")]
Custom9 = 26,
/// <summary>
/// Enum Custom10 for value: custom_10
/// </summary>
[EnumMember(Value = "custom_10")]
Custom10 = 27
}
}
| 40.964646 | 3,225 | 0.686845 | [
"MIT"
] | dagclo/data-services-client-dotnet | data-services-client-model/UsBatch/USAppendsOutputField.cs | 7,914 | 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.Runtime.InteropServices;
using System.Runtime.CompilerServices;
using System.Text;
using Silk.NET.Core;
using Silk.NET.Core.Native;
using Silk.NET.Core.Attributes;
using Silk.NET.Core.Contexts;
using Silk.NET.Core.Loader;
using Silk.NET.Vulkan;
using Extension = Silk.NET.Core.Attributes.ExtensionAttribute;
#pragma warning disable 1591
namespace Silk.NET.Vulkan.Extensions.KHR
{
[Extension("VK_KHR_external_semaphore_win32")]
public unsafe partial class KhrExternalSemaphoreWin32 : NativeExtension<Vk>
{
public const string ExtensionName = "VK_KHR_external_semaphore_win32";
/// <summary>To be documented.</summary>
[NativeApi(EntryPoint = "vkGetSemaphoreWin32HandleKHR", Convention = CallingConvention.Winapi)]
public unsafe partial Result GetSemaphoreWin32Handle([Count(Count = 0)] Device device, [Count(Count = 0), Flow(FlowDirection.In)] SemaphoreGetWin32HandleInfoKHR* pGetWin32HandleInfo, [Count(Count = 0), Flow(FlowDirection.Out)] nint* pHandle);
/// <summary>To be documented.</summary>
[NativeApi(EntryPoint = "vkGetSemaphoreWin32HandleKHR", Convention = CallingConvention.Winapi)]
public unsafe partial Result GetSemaphoreWin32Handle([Count(Count = 0)] Device device, [Count(Count = 0), Flow(FlowDirection.In)] SemaphoreGetWin32HandleInfoKHR* pGetWin32HandleInfo, [Count(Count = 0), Flow(FlowDirection.Out)] out nint pHandle);
/// <summary>To be documented.</summary>
[NativeApi(EntryPoint = "vkGetSemaphoreWin32HandleKHR", Convention = CallingConvention.Winapi)]
public unsafe partial Result GetSemaphoreWin32Handle([Count(Count = 0)] Device device, [Count(Count = 0), Flow(FlowDirection.In)] in SemaphoreGetWin32HandleInfoKHR pGetWin32HandleInfo, [Count(Count = 0), Flow(FlowDirection.Out)] nint* pHandle);
/// <summary>To be documented.</summary>
[NativeApi(EntryPoint = "vkGetSemaphoreWin32HandleKHR", Convention = CallingConvention.Winapi)]
public partial Result GetSemaphoreWin32Handle([Count(Count = 0)] Device device, [Count(Count = 0), Flow(FlowDirection.In)] in SemaphoreGetWin32HandleInfoKHR pGetWin32HandleInfo, [Count(Count = 0), Flow(FlowDirection.Out)] out nint pHandle);
/// <summary>To be documented.</summary>
[NativeApi(EntryPoint = "vkImportSemaphoreWin32HandleKHR", Convention = CallingConvention.Winapi)]
public unsafe partial Result ImportSemaphoreWin32Handle([Count(Count = 0)] Device device, [Count(Count = 0), Flow(FlowDirection.In)] ImportSemaphoreWin32HandleInfoKHR* pImportSemaphoreWin32HandleInfo);
/// <summary>To be documented.</summary>
[NativeApi(EntryPoint = "vkImportSemaphoreWin32HandleKHR", Convention = CallingConvention.Winapi)]
public partial Result ImportSemaphoreWin32Handle([Count(Count = 0)] Device device, [Count(Count = 0), Flow(FlowDirection.In)] in ImportSemaphoreWin32HandleInfoKHR pImportSemaphoreWin32HandleInfo);
public KhrExternalSemaphoreWin32(INativeContext ctx)
: base(ctx)
{
}
}
}
| 59.777778 | 253 | 0.749071 | [
"MIT"
] | Ar37-rs/Silk.NET | src/Vulkan/Extensions/Silk.NET.Vulkan.Extensions.KHR/KhrExternalSemaphoreWin32.gen.cs | 3,228 | 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("RB.Umbraco.CleanUpManager.Tests")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("RB.Umbraco.CleanUpManager.Tests")]
[assembly: AssemblyCopyright("Copyright © 2015")]
[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("2b6c50dd-f91e-4b37-85b9-3c6f9cd46633")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| 38.777778 | 84 | 0.744269 | [
"MIT",
"Unlicense"
] | NikRimington/umbraco-clean-up-manager | source/RB.Umbraco.CleanUpManager.Tests/Properties/AssemblyInfo.cs | 1,399 | C# |
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Http;
using Senparc.Core.Extensions;
using Senparc.Core.Models;
using Senparc.Core.Utility;
using Senparc.Log;
using Senparc.Repository;
using System;
using System.Collections.Generic;
using System.Security.Claims;
namespace Senparc.Service
{
public class AdminUserInfoService : BaseClientService<AdminUserInfo>
{
private readonly Lazy<IHttpContextAccessor> _contextAccessor;
public AdminUserInfoService(AdminUserInfoRepository repository, Lazy<IHttpContextAccessor> httpContextAccessor) : base(repository)
{
_contextAccessor = httpContextAccessor;
}
/// <summary>
///
/// </summary>
/// <param name="id"></param>
/// <param name="userName"></param>
/// <returns></returns>
public bool CheckUserNameExisted(long id, string userName)
{
return GetObject(z => z.Id != id && z.UserName.Equals(userName.Trim(), StringComparison.CurrentCultureIgnoreCase)) != null;
}
public AdminUserInfo GetUserInfo(string userName)
{
return GetObject(z => z.UserName.Equals(userName.Trim(), StringComparison.CurrentCultureIgnoreCase));
}
public AdminUserInfo GetUserInfo(string userName, string password)
{
AdminUserInfo userInfo = GetObject(z => z.UserName.Equals(userName, StringComparison.OrdinalIgnoreCase), null);
if (userInfo == null)
{
return null;
}
var codedPassword = GetPassword(password, userInfo.PasswordSalt, false);
return userInfo.Password == codedPassword ? userInfo : null;
}
public string GetPassword(string password, string salt, bool isMD5Password)
{
string md5 = password.ToUpper().Replace("-", "");
if (!isMD5Password)
{
md5 = MD5.GetMD5Code(password, "").Replace("-", ""); //原始MD5
}
return MD5.GetMD5Code(md5, salt).Replace("-", ""); //再加密
}
public void Logout()
{
try
{
_contextAccessor.Value.HttpContext.SignOutAsync(AdminAuthorizeAttribute.AuthenticationScheme);
}
catch (Exception ex)
{
LogUtility.AdminUserInfo.ErrorFormat("退出登录失败。", ex);
}
}
public virtual void Login(string userName, bool rememberMe)
{
#region 使用 .net core 的方法写入 cookie 验证信息
var claims = new List<Claim>
{
new Claim(ClaimTypes.Name, userName),
new Claim("AdminMember", "", ClaimValueTypes.String)
};
var identity = new ClaimsIdentity(AdminAuthorizeAttribute.AuthenticationScheme);
identity.AddClaims(claims);
var authProperties = new AuthenticationProperties
{
AllowRefresh = false,
ExpiresUtc = DateTimeOffset.UtcNow.AddMinutes(120),
IsPersistent = false,
};
Logout(); //退出登录
_contextAccessor.Value.HttpContext.SignInAsync(AdminAuthorizeAttribute.AuthenticationScheme, new ClaimsPrincipal(identity), authProperties);
#endregion
}
public bool CheckPassword(string userName, string password)
{
var userInfo = GetObject(z => z.UserName.Equals(userName, StringComparison.OrdinalIgnoreCase));
if (userInfo == null)
{
return false;
}
var codedPassword = GetPassword(password, userInfo.PasswordSalt, false);
return userInfo.Password == codedPassword;
}
public AdminUserInfo TryLogin(string userNameOrEmail, string password, bool rememberMe)
{
AdminUserInfo userInfo = GetUserInfo(userNameOrEmail, password);
if (userInfo != null)
{
Login(userInfo.UserName, rememberMe);
return userInfo;
}
else
{
return null;
}
}
public AdminUserInfo GetAdminUserInfo(int id, string[] includes = null)
{
return GetObject(z => z.Id == id, includes: includes);
}
public List<AdminUserInfo> GetAdminUserInfo(List<int> ids, string[] includes = null)
{
return GetFullList(z => ids.Contains(z.Id), z => z.Id, Core.Enums.OrderingType.Ascending, includes: includes);
}
/// <summary>
/// 初始化
/// </summary>
/// <returns></returns>
public AdminUserInfo Init(out string userName, out string password)
{
var oldAdminUserInfo = GetObject(z => true);
if (oldAdminUserInfo != null)
{
userName = null;
password = null;
return null;
}
var salt = DateTime.Now.Ticks.ToString();
userName = $"SenparcCoreAdmin{new Random().Next(100).ToString("00")}";
password = Guid.NewGuid().ToString("n").Substring(0, 8);
var adminUserInfo = new AdminUserInfo()
{
UserName = userName,
Password = GetPassword(password, salt, false),
PasswordSalt = salt,
Note = "初始化数据",
AddTime = DateTime.Now,
ThisLoginTime = DateTime.Now,
LastLoginTime = DateTime.Now,
};
SaveObject(adminUserInfo);
return adminUserInfo;
}
public override void SaveObject(AdminUserInfo obj)
{
var isInsert = base.IsInsert(obj);
base.SaveObject(obj);
LogUtility.WebLogger.InfoFormat("AdminUserInfo{2}:{0}(ID:{1})", obj.UserName, obj.Id, isInsert ? "新增" : "编辑");
}
public override void DeleteObject(AdminUserInfo obj)
{
base.DeleteObject(obj);
LogUtility.WebLogger.InfoFormat("AdminUserInfo被删除:{0}(ID:{1})", obj.UserName, obj.Id);
}
}
}
| 34.758427 | 152 | 0.56942 | [
"Apache-2.0"
] | xiaohai-xie-baal/SCF | src/Senparc.Service/AdminUserInfoService.cs | 6,289 | C# |
public enum InitialCursorPos // TypeDefIndex: 11465
{
// Fields
public int value__; // 0x0
public const InitialCursorPos First = 0;
public const InitialCursorPos Last = 1;
public const InitialCursorPos Max = 2;
}
| 21.9 | 51 | 0.748858 | [
"MIT"
] | SinsofSloth/RF5-global-metadata | nn/swkbd/InitialCursorPos.cs | 219 | C# |
using System;
using System.Collections.Generic;
using System.Diagnostics;
using ModestTree;
using Zenject.Internal;
using System.Linq;
using TypeExtensions = ModestTree.TypeExtensions;
#if !NOT_UNITY3D
using UnityEngine;
#if UNITY_EDITOR
using UnityEditor;
#endif
#endif
namespace Zenject
{
internal static class BindingUtil
{
#if !NOT_UNITY3D
#if ZEN_STRIP_ASSERTS_IN_BUILDS
[Conditional("UNITY_EDITOR")]
#endif
public static void AssertIsValidPrefab(UnityEngine.Object prefab)
{
Assert.That(!ZenUtilInternal.IsNull(prefab), "Received null prefab during bind command");
#if UNITY_EDITOR
// Unfortunately we can't do this check because asset bundles return PrefabType.None here
// as discussed here: https://github.com/modesttree/Zenject/issues/269#issuecomment-323419408
//Assert.That(PrefabUtility.GetPrefabType(prefab) == PrefabType.Prefab,
//"Expected prefab but found game object with name '{0}' during bind command", prefab.name);
#endif
}
#if ZEN_STRIP_ASSERTS_IN_BUILDS
[Conditional("UNITY_EDITOR")]
#endif
public static void AssertIsValidGameObject(GameObject gameObject)
{
Assert.That(!ZenUtilInternal.IsNull(gameObject), "Received null game object during bind command");
#if UNITY_EDITOR
// Unfortunately we can't do this check because asset bundles return PrefabType.None here
// as discussed here: https://github.com/modesttree/Zenject/issues/269#issuecomment-323419408
//Assert.That(PrefabUtility.GetPrefabType(gameObject) != PrefabType.Prefab,
//"Expected game object but found prefab instead with name '{0}' during bind command", gameObject.name);
#endif
}
#if ZEN_STRIP_ASSERTS_IN_BUILDS
[Conditional("UNITY_EDITOR")]
#endif
public static void AssertIsNotComponent(IEnumerable<Type> types)
{
foreach (var type in types)
{
AssertIsNotComponent(type);
}
}
#if ZEN_STRIP_ASSERTS_IN_BUILDS
[Conditional("UNITY_EDITOR")]
#endif
public static void AssertIsNotComponent<T>()
{
AssertIsNotComponent(typeof(T));
}
#if ZEN_STRIP_ASSERTS_IN_BUILDS
[Conditional("UNITY_EDITOR")]
#endif
public static void AssertIsNotComponent(Type type)
{
Assert.That(!type.DerivesFrom(typeof(Component)),
"Invalid type given during bind command. Expected type '{0}' to NOT derive from UnityEngine.Component", type);
}
#if ZEN_STRIP_ASSERTS_IN_BUILDS
[Conditional("UNITY_EDITOR")]
#endif
public static void AssertDerivesFromUnityObject(IEnumerable<Type> types)
{
foreach (var type in types)
{
AssertDerivesFromUnityObject(type);
}
}
#if ZEN_STRIP_ASSERTS_IN_BUILDS
[Conditional("UNITY_EDITOR")]
#endif
public static void AssertDerivesFromUnityObject<T>()
{
AssertDerivesFromUnityObject(typeof(T));
}
#if ZEN_STRIP_ASSERTS_IN_BUILDS
[Conditional("UNITY_EDITOR")]
#endif
public static void AssertDerivesFromUnityObject(Type type)
{
Assert.That(type.DerivesFrom<UnityEngine.Object>(),
"Invalid type given during bind command. Expected type '{0}' to derive from UnityEngine.Object", type);
}
#if ZEN_STRIP_ASSERTS_IN_BUILDS
[Conditional("UNITY_EDITOR")]
#endif
public static void AssertTypesAreNotComponents(IEnumerable<Type> types)
{
foreach (var type in types)
{
AssertIsNotComponent(type);
}
}
#if ZEN_STRIP_ASSERTS_IN_BUILDS
[Conditional("UNITY_EDITOR")]
#endif
public static void AssertIsValidResourcePath(string resourcePath)
{
Assert.That(!string.IsNullOrEmpty(resourcePath), "Null or empty resource path provided");
// We'd like to validate the path here but unfortunately there doesn't appear to be
// a way to do this besides loading it
}
#if ZEN_STRIP_ASSERTS_IN_BUILDS
[Conditional("UNITY_EDITOR")]
#endif
public static void AssertIsInterfaceOrScriptableObject(IEnumerable<Type> types)
{
foreach (var type in types)
{
AssertIsInterfaceOrScriptableObject(type);
}
}
#if ZEN_STRIP_ASSERTS_IN_BUILDS
[Conditional("UNITY_EDITOR")]
#endif
public static void AssertIsInterfaceOrScriptableObject<T>()
{
AssertIsInterfaceOrScriptableObject(typeof(T));
}
#if ZEN_STRIP_ASSERTS_IN_BUILDS
[Conditional("UNITY_EDITOR")]
#endif
public static void AssertIsInterfaceOrScriptableObject(Type type)
{
Assert.That(type.DerivesFrom(typeof(ScriptableObject)) || type.IsInterface(),
"Invalid type given during bind command. Expected type '{0}' to either derive from UnityEngine.ScriptableObject or be an interface", type);
}
#if ZEN_STRIP_ASSERTS_IN_BUILDS
[Conditional("UNITY_EDITOR")]
#endif
public static void AssertIsInterfaceOrComponent(IEnumerable<Type> types)
{
foreach (var type in types)
{
AssertIsInterfaceOrComponent(type);
}
}
#if ZEN_STRIP_ASSERTS_IN_BUILDS
[Conditional("UNITY_EDITOR")]
#endif
public static void AssertIsInterfaceOrComponent<T>()
{
AssertIsInterfaceOrComponent(typeof(T));
}
#if ZEN_STRIP_ASSERTS_IN_BUILDS
[Conditional("UNITY_EDITOR")]
#endif
public static void AssertIsInterfaceOrComponent(Type type)
{
Assert.That(type.DerivesFrom(typeof(Component)) || type.IsInterface(),
"Invalid type given during bind command. Expected type '{0}' to either derive from UnityEngine.Component or be an interface", type);
}
#if ZEN_STRIP_ASSERTS_IN_BUILDS
[Conditional("UNITY_EDITOR")]
#endif
public static void AssertIsComponent(IEnumerable<Type> types)
{
foreach (var type in types)
{
AssertIsComponent(type);
}
}
#if ZEN_STRIP_ASSERTS_IN_BUILDS
[Conditional("UNITY_EDITOR")]
#endif
public static void AssertIsComponent<T>()
{
AssertIsComponent(typeof(T));
}
#if ZEN_STRIP_ASSERTS_IN_BUILDS
[Conditional("UNITY_EDITOR")]
#endif
public static void AssertIsComponent(Type type)
{
Assert.That(type.DerivesFrom(typeof(Component)),
"Invalid type given during bind command. Expected type '{0}' to derive from UnityEngine.Component", type);
}
#else
public static void AssertTypesAreNotComponents(IEnumerable<Type> types)
{
}
public static void AssertIsNotComponent(Type type)
{
}
public static void AssertIsNotComponent<T>()
{
}
public static void AssertIsNotComponent(IEnumerable<Type> types)
{
}
#endif
#if ZEN_STRIP_ASSERTS_IN_BUILDS
[Conditional("UNITY_EDITOR")]
#endif
public static void AssertTypesAreNotAbstract(IEnumerable<Type> types)
{
foreach (var type in types)
{
AssertIsNotAbstract(type);
}
}
#if ZEN_STRIP_ASSERTS_IN_BUILDS
[Conditional("UNITY_EDITOR")]
#endif
public static void AssertIsNotAbstract(IEnumerable<Type> types)
{
foreach (var type in types)
{
AssertIsNotAbstract(type);
}
}
#if ZEN_STRIP_ASSERTS_IN_BUILDS
[Conditional("UNITY_EDITOR")]
#endif
public static void AssertIsNotAbstract<T>()
{
AssertIsNotAbstract(typeof(T));
}
#if ZEN_STRIP_ASSERTS_IN_BUILDS
[Conditional("UNITY_EDITOR")]
#endif
public static void AssertIsNotAbstract(Type type)
{
Assert.That(!type.IsAbstract(),
"Invalid type given during bind command. Expected type '{0}' to not be abstract.", type);
}
#if ZEN_STRIP_ASSERTS_IN_BUILDS
[Conditional("UNITY_EDITOR")]
#endif
public static void AssertIsDerivedFromType(Type concreteType, Type parentType)
{
#if !(UNITY_WSA && ENABLE_DOTNET)
// TODO: Is it possible to do this on WSA?
Assert.That(parentType.IsOpenGenericType() == concreteType.IsOpenGenericType(),
"Invalid type given during bind command. Expected type '{0}' and type '{1}' to both either be open generic types or not open generic types", parentType, concreteType);
if (parentType.IsOpenGenericType())
{
Assert.That(concreteType.IsOpenGenericType());
Assert.That(TypeExtensions.IsAssignableToGenericType(concreteType, parentType),
"Invalid type given during bind command. Expected open generic type '{0}' to derive from open generic type '{1}'", concreteType, parentType);
}
else
#endif
{
Assert.That(concreteType.DerivesFromOrEqual(parentType),
"Invalid type given during bind command. Expected type '{0}' to derive from type '{1}'", concreteType, parentType.PrettyName());
}
}
#if ZEN_STRIP_ASSERTS_IN_BUILDS
[Conditional("UNITY_EDITOR")]
#endif
public static void AssertConcreteTypeListIsNotEmpty(IEnumerable<Type> concreteTypes)
{
Assert.That(concreteTypes.Count() >= 1,
"Must supply at least one concrete type to the current binding");
}
#if ZEN_STRIP_ASSERTS_IN_BUILDS
[Conditional("UNITY_EDITOR")]
#endif
public static void AssertIsDerivedFromTypes(
IEnumerable<Type> concreteTypes, IEnumerable<Type> parentTypes, InvalidBindResponses invalidBindResponse)
{
if (invalidBindResponse == InvalidBindResponses.Assert)
{
AssertIsDerivedFromTypes(concreteTypes, parentTypes);
}
else
{
Assert.IsEqual(invalidBindResponse, InvalidBindResponses.Skip);
}
}
#if ZEN_STRIP_ASSERTS_IN_BUILDS
[Conditional("UNITY_EDITOR")]
#endif
public static void AssertIsDerivedFromTypes(IEnumerable<Type> concreteTypes, IEnumerable<Type> parentTypes)
{
foreach (var concreteType in concreteTypes)
{
AssertIsDerivedFromTypes(concreteType, parentTypes);
}
}
#if ZEN_STRIP_ASSERTS_IN_BUILDS
[Conditional("UNITY_EDITOR")]
#endif
public static void AssertIsDerivedFromTypes(Type concreteType, IEnumerable<Type> parentTypes)
{
foreach (var parentType in parentTypes)
{
AssertIsDerivedFromType(concreteType, parentType);
}
}
#if ZEN_STRIP_ASSERTS_IN_BUILDS
[Conditional("UNITY_EDITOR")]
#endif
public static void AssertInstanceDerivesFromOrEqual(object instance, IEnumerable<Type> parentTypes)
{
if (!ZenUtilInternal.IsNull(instance))
{
foreach (var baseType in parentTypes)
{
AssertInstanceDerivesFromOrEqual(instance, baseType);
}
}
}
#if ZEN_STRIP_ASSERTS_IN_BUILDS
[Conditional("UNITY_EDITOR")]
#endif
public static void AssertInstanceDerivesFromOrEqual(object instance, Type baseType)
{
if (!ZenUtilInternal.IsNull(instance))
{
Assert.That(instance.GetType().DerivesFromOrEqual(baseType),
"Invalid type given during bind command. Expected type '{0}' to derive from type '{1}'", instance.GetType(), baseType.PrettyName());
}
}
public static IProvider CreateCachedProvider(IProvider creator)
{
if (creator.TypeVariesBasedOnMemberType)
{
return new CachedOpenTypeProvider(creator);
}
return new CachedProvider(creator);
}
}
}
| 33.406824 | 185 | 0.612429 | [
"MIT"
] | AdJion/Zenject | UnityProject/Assets/Plugins/Zenject/Source/Binding/BindingUtil.cs | 12,728 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
using System.Web.Http;
namespace AInBox.Astove.Core.Results
{
public class ChallengeResult : IHttpActionResult
{
public ChallengeResult(string loginProvider, ApiController controller)
{
LoginProvider = loginProvider;
Request = controller.Request;
}
public string LoginProvider { get; set; }
public HttpRequestMessage Request { get; set; }
public Task<HttpResponseMessage> ExecuteAsync(CancellationToken cancellationToken)
{
Request.GetOwinContext().Authentication.Challenge(LoginProvider);
HttpResponseMessage response = new HttpResponseMessage(HttpStatusCode.Unauthorized);
response.RequestMessage = Request;
return Task.FromResult(response);
}
}
} | 30.125 | 96 | 0.695021 | [
"MIT"
] | leandrolustosa/notificationqueueservice | AInBox.Astove.Core/Results/ChallengeResult.cs | 966 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Cofoundry.Domain.Data;
using Cofoundry.Domain.CQS;
using Microsoft.EntityFrameworkCore;
using Cofoundry.Domain.QueryModels;
namespace Cofoundry.Domain
{
public class GetPageTemplateDetailsByIdQueryHandler
: IAsyncQueryHandler<GetPageTemplateDetailsByIdQuery, PageTemplateDetails>
, IPermissionRestrictedQueryHandler<GetPageTemplateDetailsByIdQuery, PageTemplateDetails>
{
#region constructor
private readonly CofoundryDbContext _dbContext;
private readonly IQueryExecutor _queryExecutor;
private readonly IPageTemplateDetailsMapper _pageTemplateDetailsMapper;
public GetPageTemplateDetailsByIdQueryHandler(
CofoundryDbContext dbContext,
IQueryExecutor queryExecutor,
IPageTemplateDetailsMapper pageTemplateDetailsMapper
)
{
_queryExecutor = queryExecutor;
_dbContext = dbContext;
_pageTemplateDetailsMapper = pageTemplateDetailsMapper;
}
#endregion
public async Task<PageTemplateDetails> ExecuteAsync(GetPageTemplateDetailsByIdQuery query, IExecutionContext executionContext)
{
var queryModel = new PageTemplateDetailsQueryModel();
queryModel.PageTemplate = await _dbContext
.PageTemplates
.AsNoTracking()
.Include(t => t.PageTemplateRegions)
.Where(l => l.PageTemplateId == query.PageTemplateId)
.SingleOrDefaultAsync();
if (queryModel.PageTemplate == null) return null;
if (!string.IsNullOrEmpty(queryModel.PageTemplate.CustomEntityDefinitionCode))
{
var definitionQuery = new GetCustomEntityDefinitionMicroSummaryByCodeQuery(queryModel.PageTemplate.CustomEntityDefinitionCode);
queryModel.CustomEntityDefinition = await _queryExecutor.ExecuteAsync(definitionQuery, executionContext);
}
queryModel.NumPages = await _dbContext
.PageVersions
.AsNoTracking()
.Where(v => v.PageTemplateId == query.PageTemplateId)
.GroupBy(v => v.PageId)
.CountAsync();
var template = _pageTemplateDetailsMapper.Map(queryModel);
return template;
}
#region Permission
public IEnumerable<IPermissionApplication> GetPermissions(GetPageTemplateDetailsByIdQuery query)
{
yield return new PageTemplateReadPermission();
}
#endregion
}
}
| 35.289474 | 143 | 0.674124 | [
"MIT"
] | CMSCollection/cofoundry | src/Cofoundry.Domain/Domain/PageTemplates/Queries/GetPageTemplateDetailsByIdQueryHandler.cs | 2,684 | C# |
using System;
using Microsoft.EntityFrameworkCore.Migrations;
namespace Godsend.Migrations
{
public partial class reworkComments : Migration
{
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropTable(
name: "LinkCommentEntity");
migrationBuilder.CreateTable(
name: "LinkCommentArticle",
columns: table => new
{
Id = table.Column<Guid>(nullable: false),
Comment = table.Column<string>(nullable: true),
EntityId1 = table.Column<Guid>(nullable: true),
BaseCommentId = table.Column<Guid>(nullable: true),
UserId = table.Column<string>(nullable: true)
},
constraints: table =>
{
table.PrimaryKey("PK_LinkCommentArticle", x => x.Id);
table.ForeignKey(
name: "FK_LinkCommentArticle_LinkCommentArticle_BaseCommentId",
column: x => x.BaseCommentId,
principalTable: "LinkCommentArticle",
principalColumn: "Id",
onDelete: ReferentialAction.Restrict);
table.ForeignKey(
name: "FK_LinkCommentArticle_Articles_EntityId1",
column: x => x.EntityId1,
principalTable: "Articles",
principalColumn: "Id",
onDelete: ReferentialAction.Restrict);
table.ForeignKey(
name: "FK_LinkCommentArticle_AspNetUsers_UserId",
column: x => x.UserId,
principalTable: "AspNetUsers",
principalColumn: "Id",
onDelete: ReferentialAction.Restrict);
});
migrationBuilder.CreateTable(
name: "LinkCommentProduct",
columns: table => new
{
Id = table.Column<Guid>(nullable: false),
Comment = table.Column<string>(nullable: true),
EntityId1 = table.Column<Guid>(nullable: true),
BaseCommentId = table.Column<Guid>(nullable: true),
UserId = table.Column<string>(nullable: true)
},
constraints: table =>
{
table.PrimaryKey("PK_LinkCommentProduct", x => x.Id);
table.ForeignKey(
name: "FK_LinkCommentProduct_LinkCommentProduct_BaseCommentId",
column: x => x.BaseCommentId,
principalTable: "LinkCommentProduct",
principalColumn: "Id",
onDelete: ReferentialAction.Restrict);
table.ForeignKey(
name: "FK_LinkCommentProduct_Products_EntityId1",
column: x => x.EntityId1,
principalTable: "Products",
principalColumn: "Id",
onDelete: ReferentialAction.Restrict);
table.ForeignKey(
name: "FK_LinkCommentProduct_AspNetUsers_UserId",
column: x => x.UserId,
principalTable: "AspNetUsers",
principalColumn: "Id",
onDelete: ReferentialAction.Restrict);
});
migrationBuilder.CreateTable(
name: "LinkCommentSupplier",
columns: table => new
{
Id = table.Column<Guid>(nullable: false),
Comment = table.Column<string>(nullable: true),
EntityId1 = table.Column<Guid>(nullable: true),
BaseCommentId = table.Column<Guid>(nullable: true),
UserId = table.Column<string>(nullable: true)
},
constraints: table =>
{
table.PrimaryKey("PK_LinkCommentSupplier", x => x.Id);
table.ForeignKey(
name: "FK_LinkCommentSupplier_LinkCommentSupplier_BaseCommentId",
column: x => x.BaseCommentId,
principalTable: "LinkCommentSupplier",
principalColumn: "Id",
onDelete: ReferentialAction.Restrict);
table.ForeignKey(
name: "FK_LinkCommentSupplier_Suppliers_EntityId1",
column: x => x.EntityId1,
principalTable: "Suppliers",
principalColumn: "Id",
onDelete: ReferentialAction.Restrict);
table.ForeignKey(
name: "FK_LinkCommentSupplier_AspNetUsers_UserId",
column: x => x.UserId,
principalTable: "AspNetUsers",
principalColumn: "Id",
onDelete: ReferentialAction.Restrict);
});
migrationBuilder.CreateIndex(
name: "IX_LinkCommentArticle_BaseCommentId",
table: "LinkCommentArticle",
column: "BaseCommentId");
migrationBuilder.CreateIndex(
name: "IX_LinkCommentArticle_EntityId1",
table: "LinkCommentArticle",
column: "EntityId1");
migrationBuilder.CreateIndex(
name: "IX_LinkCommentArticle_UserId",
table: "LinkCommentArticle",
column: "UserId");
migrationBuilder.CreateIndex(
name: "IX_LinkCommentProduct_BaseCommentId",
table: "LinkCommentProduct",
column: "BaseCommentId");
migrationBuilder.CreateIndex(
name: "IX_LinkCommentProduct_EntityId1",
table: "LinkCommentProduct",
column: "EntityId1");
migrationBuilder.CreateIndex(
name: "IX_LinkCommentProduct_UserId",
table: "LinkCommentProduct",
column: "UserId");
migrationBuilder.CreateIndex(
name: "IX_LinkCommentSupplier_BaseCommentId",
table: "LinkCommentSupplier",
column: "BaseCommentId");
migrationBuilder.CreateIndex(
name: "IX_LinkCommentSupplier_EntityId1",
table: "LinkCommentSupplier",
column: "EntityId1");
migrationBuilder.CreateIndex(
name: "IX_LinkCommentSupplier_UserId",
table: "LinkCommentSupplier",
column: "UserId");
}
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropTable(
name: "LinkCommentArticle");
migrationBuilder.DropTable(
name: "LinkCommentProduct");
migrationBuilder.DropTable(
name: "LinkCommentSupplier");
migrationBuilder.CreateTable(
name: "LinkCommentEntity",
columns: table => new
{
Id = table.Column<Guid>(nullable: false),
BaseCommentId = table.Column<Guid>(nullable: true),
Comment = table.Column<string>(nullable: true),
Discriminator = table.Column<string>(nullable: false),
UserId = table.Column<string>(nullable: true),
ArticleId = table.Column<Guid>(nullable: true),
ProductId = table.Column<Guid>(nullable: true),
SupplierId = table.Column<Guid>(nullable: true)
},
constraints: table =>
{
table.PrimaryKey("PK_LinkCommentEntity", x => x.Id);
table.ForeignKey(
name: "FK_LinkCommentEntity_Articles_ArticleId",
column: x => x.ArticleId,
principalTable: "Articles",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
table.ForeignKey(
name: "FK_LinkCommentEntity_LinkCommentEntity_BaseCommentId",
column: x => x.BaseCommentId,
principalTable: "LinkCommentEntity",
principalColumn: "Id",
onDelete: ReferentialAction.Restrict);
table.ForeignKey(
name: "FK_LinkCommentEntity_AspNetUsers_UserId",
column: x => x.UserId,
principalTable: "AspNetUsers",
principalColumn: "Id",
onDelete: ReferentialAction.Restrict);
table.ForeignKey(
name: "FK_LinkCommentEntity_Products_ProductId",
column: x => x.ProductId,
principalTable: "Products",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
table.ForeignKey(
name: "FK_LinkCommentEntity_Suppliers_SupplierId",
column: x => x.SupplierId,
principalTable: "Suppliers",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
});
migrationBuilder.CreateIndex(
name: "IX_LinkCommentEntity_ArticleId",
table: "LinkCommentEntity",
column: "ArticleId");
migrationBuilder.CreateIndex(
name: "IX_LinkCommentEntity_BaseCommentId",
table: "LinkCommentEntity",
column: "BaseCommentId");
migrationBuilder.CreateIndex(
name: "IX_LinkCommentEntity_UserId",
table: "LinkCommentEntity",
column: "UserId");
migrationBuilder.CreateIndex(
name: "IX_LinkCommentEntity_ProductId",
table: "LinkCommentEntity",
column: "ProductId");
migrationBuilder.CreateIndex(
name: "IX_LinkCommentEntity_SupplierId",
table: "LinkCommentEntity",
column: "SupplierId");
}
}
}
| 43.881148 | 89 | 0.496498 | [
"MIT"
] | 0legKot/Godsend | Godsend/Migrations/20181009130249_reworkComments.cs | 10,709 | C# |
using System;
namespace RethinkDb
{
public class QueryConverter : IQueryConverter
{
private IDatumConverterFactory delegatedDatumConverterFactory;
private IExpressionConverterFactory delegatedExpressionConverterFactory;
public QueryConverter(IDatumConverterFactory datumConverterFactory, IExpressionConverterFactory expressionConverterFactory)
{
this.delegatedDatumConverterFactory = datumConverterFactory;
this.delegatedExpressionConverterFactory = expressionConverterFactory;
}
#region IExpressionConverterFactory implementation
public IExpressionConverterZeroParameter<TReturn> CreateExpressionConverter<TReturn>(IDatumConverterFactory datumConverterFactory)
{
return delegatedExpressionConverterFactory.CreateExpressionConverter<TReturn>(datumConverterFactory);
}
public IExpressionConverterOneParameter<TParameter1, TReturn> CreateExpressionConverter<TParameter1, TReturn>(IDatumConverterFactory datumConverterFactory)
{
return delegatedExpressionConverterFactory.CreateExpressionConverter<TParameter1, TReturn>(datumConverterFactory);
}
public IExpressionConverterTwoParameter<TParameter1, TParameter2, TReturn> CreateExpressionConverter<TParameter1, TParameter2, TReturn>(IDatumConverterFactory datumConverterFactory)
{
return delegatedExpressionConverterFactory.CreateExpressionConverter<TParameter1, TParameter2, TReturn>(datumConverterFactory);
}
#endregion
#region IDatumConverterFactory implementation
public bool TryGet(Type datumType, IDatumConverterFactory rootDatumConverterFactory, out IDatumConverter datumConverter)
{
return delegatedDatumConverterFactory.TryGet(datumType, rootDatumConverterFactory, out datumConverter);
}
public bool TryGet<T>(IDatumConverterFactory rootDatumConverterFactory, out IDatumConverter<T> datumConverter)
{
return delegatedDatumConverterFactory.TryGet<T>(rootDatumConverterFactory, out datumConverter);
}
#endregion
}
}
| 44.244898 | 189 | 0.767989 | [
"Apache-2.0"
] | karlgrz/rethinkdb-net | rethinkdb-net/QueryConverter.cs | 2,170 | C# |
/* Yet Another Forum.NET
* Copyright (C) 2003-2005 Bjørnar Henden
* Copyright (C) 2006-2013 Jaben Cargman
* Copyright (C) 2014-2022 Ingo Herbote
* https://www.yetanotherforum.net/
*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
* https://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
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("YAF.Web")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("YetAnotherForum.NET")]
[assembly: AssemblyProduct("Yet Another Forum.NET")]
[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("7a2d4440-346c-4dd5-b8c9-5b05fe0e8248")]
[assembly: AssemblyDelaySign(false)]
[assembly: AssemblyKeyFile("..\\YetAnotherForum.NET.snk")] | 42.645833 | 85 | 0.745481 | [
"Apache-2.0"
] | correaAlex/YAFNET | yafsrc/YAF.Web/Properties/AssemblyInfo.cs | 2,003 | C# |
#pragma checksum "C:\dev\Fision\GestaoFluxoFinanceiro\GestaoFluxoFinanceiro.Aplicacao\Views\MovimentoFinanceiroProfissional\Index.cshtml" "{ff1816ec-aa5e-4d10-87f7-6f4963833460}" "fd6b8858b1557cc2aaef54efeb2cbd186aae911c"
// <auto-generated/>
#pragma warning disable 1591
[assembly: global::Microsoft.AspNetCore.Razor.Hosting.RazorCompiledItemAttribute(typeof(AspNetCore.Views_MovimentoFinanceiroProfissional_Index), @"mvc.1.0.view", @"/Views/MovimentoFinanceiroProfissional/Index.cshtml")]
namespace AspNetCore
{
#line hidden
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Rendering;
using Microsoft.AspNetCore.Mvc.ViewFeatures;
#nullable restore
#line 1 "C:\dev\Fision\GestaoFluxoFinanceiro\GestaoFluxoFinanceiro.Aplicacao\Views\_ViewImports.cshtml"
using GestaoFluxoFinanceiro.Aplicacao;
#line default
#line hidden
#nullable disable
[global::Microsoft.AspNetCore.Razor.Hosting.RazorSourceChecksumAttribute(@"SHA1", @"fd6b8858b1557cc2aaef54efeb2cbd186aae911c", @"/Views/MovimentoFinanceiroProfissional/Index.cshtml")]
[global::Microsoft.AspNetCore.Razor.Hosting.RazorSourceChecksumAttribute(@"SHA1", @"c080f270ca945005a9c841075672aa230114b2fb", @"/Views/_ViewImports.cshtml")]
public class Views_MovimentoFinanceiroProfissional_Index : global::Microsoft.AspNetCore.Mvc.Razor.RazorPage<IEnumerable<GestaoFluxoFinanceiro.Aplicacao.ViewModels.Financeiro.MovimentoProfissionalViewModel>>
{
private global::AspNetCore.Views_MovimentoFinanceiroProfissional_Index.__Generated__SummaryViewComponentTagHelper __SummaryViewComponentTagHelper;
private static readonly global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute __tagHelperAttribute_0 = new global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute("class", new global::Microsoft.AspNetCore.Html.HtmlString("btn btn-info"), global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes);
private static readonly global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute __tagHelperAttribute_1 = new global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute("asp-action", "Create", global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes);
private static readonly global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute __tagHelperAttribute_2 = new global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute("supress-by-claim-name", "Adm", global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes);
private static readonly global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute __tagHelperAttribute_3 = new global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute("supress-by-claim-value", "Adicionar", global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes);
private static readonly global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute __tagHelperAttribute_4 = new global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute("class", new global::Microsoft.AspNetCore.Html.HtmlString("btn btn-warning"), global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes);
private static readonly global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute __tagHelperAttribute_5 = new global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute("asp-controller", "MovimentoFinanceiroProfissional", global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes);
private static readonly global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute __tagHelperAttribute_6 = new global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute("asp-action", "Edit", global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes);
#line hidden
#pragma warning disable 0649
private global::Microsoft.AspNetCore.Razor.Runtime.TagHelpers.TagHelperExecutionContext __tagHelperExecutionContext;
#pragma warning restore 0649
private global::Microsoft.AspNetCore.Razor.Runtime.TagHelpers.TagHelperRunner __tagHelperRunner = new global::Microsoft.AspNetCore.Razor.Runtime.TagHelpers.TagHelperRunner();
#pragma warning disable 0169
private string __tagHelperStringValueBuffer;
#pragma warning restore 0169
private global::Microsoft.AspNetCore.Razor.Runtime.TagHelpers.TagHelperScopeManager __backed__tagHelperScopeManager = null;
private global::Microsoft.AspNetCore.Razor.Runtime.TagHelpers.TagHelperScopeManager __tagHelperScopeManager
{
get
{
if (__backed__tagHelperScopeManager == null)
{
__backed__tagHelperScopeManager = new global::Microsoft.AspNetCore.Razor.Runtime.TagHelpers.TagHelperScopeManager(StartTagHelperWritingScope, EndTagHelperWritingScope);
}
return __backed__tagHelperScopeManager;
}
}
private global::GestaoFluxoFinanceiro.Aplicacao.Extensions.ApagaElementoTagHelper __GestaoFluxoFinanceiro_Aplicacao_Extensions_ApagaElementoTagHelper;
private global::Microsoft.AspNetCore.Mvc.TagHelpers.AnchorTagHelper __Microsoft_AspNetCore_Mvc_TagHelpers_AnchorTagHelper;
#pragma warning disable 1998
public async override global::System.Threading.Tasks.Task ExecuteAsync()
{
#nullable restore
#line 2 "C:\dev\Fision\GestaoFluxoFinanceiro\GestaoFluxoFinanceiro.Aplicacao\Views\MovimentoFinanceiroProfissional\Index.cshtml"
ViewData["Title"] = "Index";
#line default
#line hidden
#nullable disable
WriteLiteral("\r\n<div class=\"album py-5 bg-light\">\r\n <div class=\"container\">\r\n ");
__tagHelperExecutionContext = __tagHelperScopeManager.Begin("vc:Summary", global::Microsoft.AspNetCore.Razor.TagHelpers.TagMode.StartTagAndEndTag, "fd6b8858b1557cc2aaef54efeb2cbd186aae911c6044", async() => {
}
);
__SummaryViewComponentTagHelper = CreateTagHelper<global::AspNetCore.Views_MovimentoFinanceiroProfissional_Index.__Generated__SummaryViewComponentTagHelper>();
__tagHelperExecutionContext.Add(__SummaryViewComponentTagHelper);
await __tagHelperRunner.RunAsync(__tagHelperExecutionContext);
if (!__tagHelperExecutionContext.Output.IsContentModified)
{
await __tagHelperExecutionContext.SetOutputContentAsync();
}
Write(__tagHelperExecutionContext.Output);
__tagHelperExecutionContext = __tagHelperScopeManager.End();
WriteLiteral(@"
<div class=""row"">
<div class=""col-md-12"">
<div class=""card"">
<div class=""card-header"">
<h4 class=""card-title"">Valores Mensais dos Profissionais</h4>
</div>
<div class=""card-body"">
<div class=""row"">
<div class=""col-md-6"">
");
__tagHelperExecutionContext = __tagHelperScopeManager.Begin("p", global::Microsoft.AspNetCore.Razor.TagHelpers.TagMode.StartTagAndEndTag, "fd6b8858b1557cc2aaef54efeb2cbd186aae911c7416", async() => {
WriteLiteral("\r\n ");
__tagHelperExecutionContext = __tagHelperScopeManager.Begin("a", global::Microsoft.AspNetCore.Razor.TagHelpers.TagMode.StartTagAndEndTag, "fd6b8858b1557cc2aaef54efeb2cbd186aae911c7707", async() => {
WriteLiteral("Novos Valores");
}
);
__Microsoft_AspNetCore_Mvc_TagHelpers_AnchorTagHelper = CreateTagHelper<global::Microsoft.AspNetCore.Mvc.TagHelpers.AnchorTagHelper>();
__tagHelperExecutionContext.Add(__Microsoft_AspNetCore_Mvc_TagHelpers_AnchorTagHelper);
__tagHelperExecutionContext.AddHtmlAttribute(__tagHelperAttribute_0);
__Microsoft_AspNetCore_Mvc_TagHelpers_AnchorTagHelper.Action = (string)__tagHelperAttribute_1.Value;
__tagHelperExecutionContext.AddTagHelperAttribute(__tagHelperAttribute_1);
await __tagHelperRunner.RunAsync(__tagHelperExecutionContext);
if (!__tagHelperExecutionContext.Output.IsContentModified)
{
await __tagHelperExecutionContext.SetOutputContentAsync();
}
Write(__tagHelperExecutionContext.Output);
__tagHelperExecutionContext = __tagHelperScopeManager.End();
WriteLiteral("\r\n ");
}
);
__GestaoFluxoFinanceiro_Aplicacao_Extensions_ApagaElementoTagHelper = CreateTagHelper<global::GestaoFluxoFinanceiro.Aplicacao.Extensions.ApagaElementoTagHelper>();
__tagHelperExecutionContext.Add(__GestaoFluxoFinanceiro_Aplicacao_Extensions_ApagaElementoTagHelper);
__GestaoFluxoFinanceiro_Aplicacao_Extensions_ApagaElementoTagHelper.IdentityClaimName = (string)__tagHelperAttribute_2.Value;
__tagHelperExecutionContext.AddTagHelperAttribute(__tagHelperAttribute_2);
__GestaoFluxoFinanceiro_Aplicacao_Extensions_ApagaElementoTagHelper.IdentityClaimValue = (string)__tagHelperAttribute_3.Value;
__tagHelperExecutionContext.AddTagHelperAttribute(__tagHelperAttribute_3);
await __tagHelperRunner.RunAsync(__tagHelperExecutionContext);
if (!__tagHelperExecutionContext.Output.IsContentModified)
{
await __tagHelperExecutionContext.SetOutputContentAsync();
}
Write(__tagHelperExecutionContext.Output);
__tagHelperExecutionContext = __tagHelperScopeManager.End();
WriteLiteral(@"
</div>
</div>
<div class=""row"">
<div class=""col-lg-12 feature_col"">
<table class=""table table-hover"" id=""tbl"">
<thead class=""thead-dark"">
<tr>
<th>
Nome
</th>
<th>
Valor Total
</th>
<th>
Valor a Receber
</th>
<th>
Valor do Profissional
</th>
");
WriteLiteral(@" <th>
Mês
</th>
<th>
Situação
</th>
<th>
</th>
</tr>
</thead>
<tbody>
");
#nullable restore
#line 53 "C:\dev\Fision\GestaoFluxoFinanceiro\GestaoFluxoFinanceiro.Aplicacao\Views\MovimentoFinanceiroProfissional\Index.cshtml"
foreach (var item in Model)
{
#line default
#line hidden
#nullable disable
WriteLiteral(" <tr>\r\n <td>\r\n ");
#nullable restore
#line 57 "C:\dev\Fision\GestaoFluxoFinanceiro\GestaoFluxoFinanceiro.Aplicacao\Views\MovimentoFinanceiroProfissional\Index.cshtml"
Write(Html.DisplayFor(itemmodel => item.Profissional));
#line default
#line hidden
#nullable disable
WriteLiteral("\r\n </td>\r\n <td>\r\n ");
#nullable restore
#line 60 "C:\dev\Fision\GestaoFluxoFinanceiro\GestaoFluxoFinanceiro.Aplicacao\Views\MovimentoFinanceiroProfissional\Index.cshtml"
Write(item.ValorTotal.ToString("C"));
#line default
#line hidden
#nullable disable
WriteLiteral("\r\n </td>\r\n <td>\r\n ");
#nullable restore
#line 63 "C:\dev\Fision\GestaoFluxoFinanceiro\GestaoFluxoFinanceiro.Aplicacao\Views\MovimentoFinanceiroProfissional\Index.cshtml"
Write(item.ValorReceber.ToString("C"));
#line default
#line hidden
#nullable disable
WriteLiteral("\r\n </td>\r\n <td>\r\n ");
#nullable restore
#line 66 "C:\dev\Fision\GestaoFluxoFinanceiro\GestaoFluxoFinanceiro.Aplicacao\Views\MovimentoFinanceiroProfissional\Index.cshtml"
Write(item.ValorProfissional.ToString("C"));
#line default
#line hidden
#nullable disable
WriteLiteral("\r\n </td>\r\n <td>\r\n ");
#nullable restore
#line 69 "C:\dev\Fision\GestaoFluxoFinanceiro\GestaoFluxoFinanceiro.Aplicacao\Views\MovimentoFinanceiroProfissional\Index.cshtml"
Write(Html.DisplayFor(itemmodel => item.CompetenciaCobranca));
#line default
#line hidden
#nullable disable
WriteLiteral("\r\n </td>\r\n\r\n");
#nullable restore
#line 72 "C:\dev\Fision\GestaoFluxoFinanceiro\GestaoFluxoFinanceiro.Aplicacao\Views\MovimentoFinanceiroProfissional\Index.cshtml"
if (item.Situacao == 3)
{
#line default
#line hidden
#nullable disable
WriteLiteral(" <td><p style=\"color:cornflowerblue\">Em aberto</p></td>\r\n");
#nullable restore
#line 75 "C:\dev\Fision\GestaoFluxoFinanceiro\GestaoFluxoFinanceiro.Aplicacao\Views\MovimentoFinanceiroProfissional\Index.cshtml"
}
#line default
#line hidden
#nullable disable
#nullable restore
#line 76 "C:\dev\Fision\GestaoFluxoFinanceiro\GestaoFluxoFinanceiro.Aplicacao\Views\MovimentoFinanceiroProfissional\Index.cshtml"
if (item.Situacao == 1)
{
#line default
#line hidden
#nullable disable
WriteLiteral(" <td><p style=\"color:darkgreen\"><strong>Quitado</strong></p></td>\r\n");
#nullable restore
#line 79 "C:\dev\Fision\GestaoFluxoFinanceiro\GestaoFluxoFinanceiro.Aplicacao\Views\MovimentoFinanceiroProfissional\Index.cshtml"
}
#line default
#line hidden
#nullable disable
WriteLiteral("\r\n <td class=\"text-right\">\r\n ");
__tagHelperExecutionContext = __tagHelperScopeManager.Begin("a", global::Microsoft.AspNetCore.Razor.TagHelpers.TagMode.StartTagAndEndTag, "fd6b8858b1557cc2aaef54efeb2cbd186aae911c16353", async() => {
WriteLiteral("<spam class=\"fas fa-money-bill-wave\"></spam> ");
}
);
__Microsoft_AspNetCore_Mvc_TagHelpers_AnchorTagHelper = CreateTagHelper<global::Microsoft.AspNetCore.Mvc.TagHelpers.AnchorTagHelper>();
__tagHelperExecutionContext.Add(__Microsoft_AspNetCore_Mvc_TagHelpers_AnchorTagHelper);
__tagHelperExecutionContext.AddHtmlAttribute(__tagHelperAttribute_4);
__Microsoft_AspNetCore_Mvc_TagHelpers_AnchorTagHelper.Controller = (string)__tagHelperAttribute_5.Value;
__tagHelperExecutionContext.AddTagHelperAttribute(__tagHelperAttribute_5);
__Microsoft_AspNetCore_Mvc_TagHelpers_AnchorTagHelper.Action = (string)__tagHelperAttribute_6.Value;
__tagHelperExecutionContext.AddTagHelperAttribute(__tagHelperAttribute_6);
if (__Microsoft_AspNetCore_Mvc_TagHelpers_AnchorTagHelper.RouteValues == null)
{
throw new InvalidOperationException(InvalidTagHelperIndexerAssignment("asp-route-id", "Microsoft.AspNetCore.Mvc.TagHelpers.AnchorTagHelper", "RouteValues"));
}
BeginWriteTagHelperAttribute();
#nullable restore
#line 82 "C:\dev\Fision\GestaoFluxoFinanceiro\GestaoFluxoFinanceiro.Aplicacao\Views\MovimentoFinanceiroProfissional\Index.cshtml"
WriteLiteral(item.Id);
#line default
#line hidden
#nullable disable
__tagHelperStringValueBuffer = EndWriteTagHelperAttribute();
__Microsoft_AspNetCore_Mvc_TagHelpers_AnchorTagHelper.RouteValues["id"] = __tagHelperStringValueBuffer;
__tagHelperExecutionContext.AddTagHelperAttribute("asp-route-id", __Microsoft_AspNetCore_Mvc_TagHelpers_AnchorTagHelper.RouteValues["id"], global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes);
await __tagHelperRunner.RunAsync(__tagHelperExecutionContext);
if (!__tagHelperExecutionContext.Output.IsContentModified)
{
await __tagHelperExecutionContext.SetOutputContentAsync();
}
Write(__tagHelperExecutionContext.Output);
__tagHelperExecutionContext = __tagHelperScopeManager.End();
WriteLiteral("\r\n </td>\r\n </tr>\r\n");
#nullable restore
#line 85 "C:\dev\Fision\GestaoFluxoFinanceiro\GestaoFluxoFinanceiro.Aplicacao\Views\MovimentoFinanceiroProfissional\Index.cshtml"
}
#line default
#line hidden
#nullable disable
WriteLiteral(" </tbody>\r\n </table>\r\n </div>\r\n </div>\r\n <a class=\"btn btn-info\"");
BeginWriteAttribute("href", " href=\"", 4868, "\"", 4908, 1);
#nullable restore
#line 90 "C:\dev\Fision\GestaoFluxoFinanceiro\GestaoFluxoFinanceiro.Aplicacao\Views\MovimentoFinanceiroProfissional\Index.cshtml"
WriteAttributeValue("", 4875, Url.Action("Index","Financeiro"), 4875, 33, false);
#line default
#line hidden
#nullable disable
EndWriteAttribute();
WriteLiteral(">Voltar</a>\r\n </div>\r\n </div>\r\n </div>\r\n </div>\r\n </div>\r\n</div>\r\n\r\n");
DefineSection("scripts", async() => {
WriteLiteral("\r\n\r\n");
#nullable restore
#line 100 "C:\dev\Fision\GestaoFluxoFinanceiro\GestaoFluxoFinanceiro.Aplicacao\Views\MovimentoFinanceiroProfissional\Index.cshtml"
await Html.RenderPartialAsync("_ValidationScriptsPartial");
#line default
#line hidden
#nullable disable
WriteLiteral(" <script type=\"text/javascript\" src=\"https://cdn.datatables.net/v/dt/dt-1.10.23/datatables.min.js\"></script>\r\n\r\n <script>\r\n $(document).ready(function () {\r\n Paginacao();\r\n });\r\n </script>\r\n ");
}
);
WriteLiteral("}\r\n\r\n\r\n\r\n\r\n");
}
#pragma warning restore 1998
[global::Microsoft.AspNetCore.Mvc.Razor.Internal.RazorInjectAttribute]
public global::Microsoft.AspNetCore.Mvc.ViewFeatures.IModelExpressionProvider ModelExpressionProvider { get; private set; }
[global::Microsoft.AspNetCore.Mvc.Razor.Internal.RazorInjectAttribute]
public global::Microsoft.AspNetCore.Mvc.IUrlHelper Url { get; private set; }
[global::Microsoft.AspNetCore.Mvc.Razor.Internal.RazorInjectAttribute]
public global::Microsoft.AspNetCore.Mvc.IViewComponentHelper Component { get; private set; }
[global::Microsoft.AspNetCore.Mvc.Razor.Internal.RazorInjectAttribute]
public global::Microsoft.AspNetCore.Mvc.Rendering.IJsonHelper Json { get; private set; }
[global::Microsoft.AspNetCore.Mvc.Razor.Internal.RazorInjectAttribute]
public global::Microsoft.AspNetCore.Mvc.Rendering.IHtmlHelper<IEnumerable<GestaoFluxoFinanceiro.Aplicacao.ViewModels.Financeiro.MovimentoProfissionalViewModel>> Html { get; private set; }
[Microsoft.AspNetCore.Razor.TagHelpers.HtmlTargetElementAttribute("vc:summary")]
public class __Generated__SummaryViewComponentTagHelper : Microsoft.AspNetCore.Razor.TagHelpers.TagHelper
{
private readonly global::Microsoft.AspNetCore.Mvc.IViewComponentHelper __helper = null;
public __Generated__SummaryViewComponentTagHelper(global::Microsoft.AspNetCore.Mvc.IViewComponentHelper helper)
{
__helper = helper;
}
[Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeNotBoundAttribute, global::Microsoft.AspNetCore.Mvc.ViewFeatures.ViewContextAttribute]
public global::Microsoft.AspNetCore.Mvc.Rendering.ViewContext ViewContext { get; set; }
public override async global::System.Threading.Tasks.Task ProcessAsync(Microsoft.AspNetCore.Razor.TagHelpers.TagHelperContext __context, Microsoft.AspNetCore.Razor.TagHelpers.TagHelperOutput __output)
{
(__helper as global::Microsoft.AspNetCore.Mvc.ViewFeatures.IViewContextAware)?.Contextualize(ViewContext);
var __helperContent = await __helper.InvokeAsync("Summary", new { });
__output.TagName = null;
__output.Content.SetHtmlContent(__helperContent);
}
}
}
}
#pragma warning restore 1591
| 67.426471 | 353 | 0.629836 | [
"MIT"
] | aldoluizmoura/Fision-GFF | GestaoFluxoFinanceiro.Aplicacao/obj/Release/net5.0/Razor/Views/MovimentoFinanceiroProfissional/Index.cshtml.g.cs | 22,928 | C# |
using EventStore.Core.LogAbstraction;
using EventStore.Core.Services;
using StreamId = System.UInt32;
namespace EventStore.Core.LogV3 {
public class LogV3SystemStreams : ISystemStreamLookup<StreamId> {
// Virtual streams are streams that exist without requiring a stream record.
// Essentially, they are hard coded.
// Reserving a thousand. Doubtful we will need many, but just in case.
// As an alternative to reserving virtual streams, we could add their stream records as part
// of the database bootstrapping. This would be odd for the AllStream
// but more appealing for the settings stream.
// Reservations are 2 apart to make room for their metastreams.
public static StreamId FirstRealStream { get; } = 1024;
// difference between each stream record (2 because of metastreams)
public static StreamId StreamInterval { get; } = 2;
// Even streams that dont exist can be normal/meta and user/system
// e.g. for default ACLs.
public const StreamId NoUserStream = 0;
public const StreamId NoUserMetastream = 1;
public const StreamId NoSystemStream = 2;
public const StreamId NoSystemMetastream = 3;
public const StreamId FirstVirtualStream = 4;
// virtual stream so that we can write metadata to $$$all
private const StreamId AllStreamNumber = 4;
// virtual stream so that we can index StreamRecords for looking up stream names
public const StreamId StreamsCreatedStreamNumber = 6;
// virtual stream for storing system settings
private const StreamId SettingsStreamNumber = 8;
// virtual stream so that we can index EventTypeRecords for looking up event type names
public const StreamId EventTypesStreamNumber = 10;
public const StreamId EpochInformationStreamNumber = 12;
public StreamId AllStream => AllStreamNumber;
public StreamId SettingsStream => SettingsStreamNumber;
private readonly IMetastreamLookup<StreamId> _metastreams;
private readonly INameLookup<StreamId> _streamNames;
public LogV3SystemStreams(
IMetastreamLookup<StreamId> metastreams,
INameLookup<StreamId> streamNames) {
_metastreams = metastreams;
_streamNames = streamNames;
}
public static bool TryGetVirtualStreamName(StreamId streamId, out string name) {
if (!IsVirtualStream(streamId)) {
name = null;
return false;
}
name = streamId switch {
AllStreamNumber => SystemStreams.AllStream,
EpochInformationStreamNumber => SystemStreams.EpochInformationStream,
EventTypesStreamNumber => SystemStreams.EventTypesStream,
SettingsStreamNumber => SystemStreams.SettingsStream,
StreamsCreatedStreamNumber => SystemStreams.StreamsCreatedStream,
_ => null,
};
return name != null;
}
public static bool TryGetVirtualStreamId(string name, out StreamId streamId) {
switch (name) {
case SystemStreams.AllStream:
streamId = AllStreamNumber;
return true;
case SystemStreams.EpochInformationStream:
streamId = EpochInformationStreamNumber;
return true;
case SystemStreams.EventTypesStream:
streamId = EventTypesStreamNumber;
return true;
case SystemStreams.StreamsCreatedStream:
streamId = StreamsCreatedStreamNumber;
return true;
case SystemStreams.SettingsStream:
streamId = SettingsStreamNumber;
return true;
default:
streamId = 0;
return false;
}
}
// in v2 this checks if the first character is '$'
// system streams can be created dynamically at runtime
// e.g. "$persistentsubscription-" + _eventStreamId + "::" + _groupName + "-parked"
// so we can either allocate a range of numbers (how many?) for them, or look up the name and see if it begins with $.
// for now do the latter because (1) allocating a range of numbers will probably get fiddly
// and (2) i expect we will find that at the point we are trying to determine if a stream is a system stream then
// we will have already looked up its info in the stream index, so this call will become trivial or unnecessary.
public bool IsSystemStream(StreamId streamId) {
if (IsVirtualStream(streamId) ||
_metastreams.IsMetaStream(streamId) ||
streamId == NoSystemStream)
return true;
if (streamId == NoUserStream)
return false;
var streamName = _streamNames.LookupName(streamId);
return SystemStreams.IsSystemStream(streamName);
}
private static bool IsVirtualStream(StreamId streamId) =>
FirstVirtualStream <= streamId && streamId < FirstRealStream;
public bool IsMetaStream(StreamId streamId) => _metastreams.IsMetaStream(streamId);
public StreamId MetaStreamOf(StreamId streamId) => _metastreams.MetaStreamOf(streamId);
public StreamId OriginalStreamOf(StreamId streamId) => _metastreams.OriginalStreamOf(streamId);
}
}
| 37.117188 | 120 | 0.750579 | [
"Apache-2.0",
"CC0-1.0"
] | BearerPipelineTest/EventStore | src/EventStore.Core/LogV3/LogV3SystemStreams.cs | 4,753 | C# |
// Accord Statistics Library
// The Accord.NET Framework
// http://accord-framework.net
//
// Copyright © César Souza, 2009-2015
// cesarsouza at gmail.com
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2.1 of the License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
//
namespace Accord.Statistics
{
using System;
using System.Collections.Generic;
using Accord.Math;
using Accord.Math.Decompositions;
using Accord.Statistics.Kernels;
using AForge;
/// <summary>
/// Set of statistics measures, such as <see cref="Mean(double[])"/>,
/// <see cref="Variance(double[])"/> and <see cref="StandardDeviation(double[], bool)"/>.
/// </summary>
///
public static partial class Measures
{
/// <summary>
/// Computes the mean of the given values.
/// </summary>
///
/// <param name="values">A double array containing the vector members.</param>
///
/// <returns>The mean of the given data.</returns>
///
public static double Mean(this double[] values)
{
double sum = 0.0;
for (int i = 0; i < values.Length; i++)
sum += values[i];
return sum / values.Length;
}
/// <summary>
/// Computes the mean of the given values.
/// </summary>
///
/// <param name="values">An integer array containing the vector members.</param>
///
/// <returns>The mean of the given data.</returns>
///
public static double Mean(this int[] values)
{
double sum = 0.0;
for (int i = 0; i < values.Length; i++)
sum += values[i];
return sum / values.Length;
}
/// <summary>
/// Computes the Geometric mean of the given values.
/// </summary>
///
/// <param name="values">A double array containing the vector members.</param>
///
/// <returns>The geometric mean of the given data.</returns>
///
public static double GeometricMean(this double[] values)
{
double sum = 1.0;
for (int i = 0; i < values.Length; i++)
sum *= values[i];
return Math.Pow(sum, 1.0 / values.Length);
}
/// <summary>
/// Computes the log geometric mean of the given values.
/// </summary>
///
/// <param name="values">A double array containing the vector members.</param>
///
/// <returns>The log geometric mean of the given data.</returns>
///
public static double LogGeometricMean(this double[] values)
{
double lnsum = 0;
for (int i = 0; i < values.Length; i++)
lnsum += Math.Log(values[i]);
return lnsum / values.Length;
}
/// <summary>
/// Computes the geometric mean of the given values.
/// </summary>
///
/// <param name="values">A double array containing the vector members.</param>
///
/// <returns>The geometric mean of the given data.</returns>
///
public static double GeometricMean(this int[] values)
{
double sum = 1.0;
for (int i = 0; i < values.Length; i++)
sum *= values[i];
return Math.Pow(sum, 1.0 / values.Length);
}
/// <summary>
/// Computes the log geometric mean of the given values.
/// </summary>
///
/// <param name="values">A double array containing the vector members.</param>
///
/// <returns>The log geometric mean of the given data.</returns>
///
public static double LogGeometricMean(this int[] values)
{
double lnsum = 0;
for (int i = 0; i < values.Length; i++)
lnsum += Math.Log(values[i]);
return lnsum / values.Length;
}
/// <summary>
/// Computes the (weighted) grand mean of a set of samples.
/// </summary>
///
/// <param name="means">A double array containing the sample means.</param>
/// <param name="samples">A integer array containing the sample's sizes.</param>
///
/// <returns>The grand mean of the samples.</returns>
///
public static double GrandMean(double[] means, int[] samples)
{
double sum = 0;
int n = 0;
for (int i = 0; i < means.Length; i++)
{
sum += samples[i] * means[i];
n += samples[i];
}
return sum / n;
}
/// <summary>
/// Computes the mean of the given values.
/// </summary>
///
/// <param name="values">A unsigned short array containing the vector members.</param>
///
/// <returns>The mean of the given data.</returns>
///
public static double Mean(this ushort[] values)
{
double sum = 0.0;
for (int i = 0; i < values.Length; i++)
sum += values[i];
return sum / values.Length;
}
/// <summary>
/// Computes the mean of the given values.
/// </summary>
///
/// <param name="values">A float array containing the vector members.</param>
///
/// <returns>The mean of the given data.</returns>
///
public static float Mean(this float[] values)
{
float sum = 0;
for (int i = 0; i < values.Length; i++)
sum += values[i];
return sum / values.Length;
}
/// <summary>
/// Computes the truncated (trimmed) mean of the given values.
/// </summary>
///
/// <param name="values">A double array containing the vector members.</param>
/// <param name="inPlace">Whether to perform operations in place, overwriting the original vector.</param>
/// <param name="alreadySorted">A boolean parameter informing if the given values have already been sorted.</param>
/// <param name="percent">The percentage of observations to drop from the sample.</param>
///
/// <returns>The mean of the given data.</returns>
///
public static double TruncatedMean(this double[] values, double percent, bool inPlace = false, bool alreadySorted = false)
{
if (!alreadySorted)
{
values = (inPlace) ? values : (double[])values.Clone();
Array.Sort(values);
}
int k = (int)Math.Floor(values.Length * percent);
double sum = 0;
for (int i = k; i < values.Length - k; i++)
sum += values[i];
return sum / (values.Length - 2 * k);
}
/// <summary>
/// Computes the contraharmonic mean of the given values.
/// </summary>
///
/// <param name="values">A unsigned short array containing the vector members.</param>
/// <param name="order">The order of the harmonic mean. Default is 1.</param>
///
/// <returns>The contraharmonic mean of the given data.</returns>
///
public static double ContraHarmonicMean(double[] values, int order)
{
double r1 = 0, r2 = 0;
for (int i = 0; i < values.Length; i++)
{
r1 += Math.Pow(values[i], order + 1);
r2 += Math.Pow(values[i], order);
}
return r1 / r2;
}
/// <summary>
/// Computes the contraharmonic mean of the given values.
/// </summary>
///
/// <param name="values">A unsigned short array containing the vector members.</param>
///
/// <returns>The contraharmonic mean of the given data.</returns>
///
public static double ContraHarmonicMean(double[] values)
{
double r1 = 0, r2 = 0;
for (int i = 0; i < values.Length; i++)
{
r1 += values[i] * values[i];
r2 += values[i];
}
return r1 / r2;
}
/// <summary>
/// Computes the Standard Deviation of the given values.
/// </summary>
///
/// <param name="values">A double array containing the vector members.</param>
/// <param name="unbiased">
/// Pass true to compute the standard deviation using the sample variance.
/// Pass false to compute it using the population variance. See remarks
/// for more details.</param>
/// <remarks>
/// <para>
/// Setting <paramref name="unbiased"/> to <c>true</c> will make this method
/// compute the standard deviation σ using the sample variance, which is an unbiased
/// estimator of the true population variance. Setting this parameter to true will
/// thus compute σ using the following formula:</para>
/// <code>
/// N
/// σ² = 1 / (N - 1) ∑ (x_i − μ)²
/// i=1
/// </code>
/// <para>
/// Setting <paramref name="unbiased"/> to <c>false</c> will assume the given values
/// already represent the whole population, and will compute the population variance
/// using the formula: </para>
/// <code>
/// N
/// σ² = (1 / N) ∑ (x_i − μ)²
/// i=1
/// </code>
/// </remarks>
///
/// <returns>The standard deviation of the given data.</returns>
///
public static double StandardDeviation(this double[] values, bool unbiased = true)
{
return StandardDeviation(values, Mean(values), unbiased);
}
/// <summary>
/// Computes the Standard Deviation of the given values.
/// </summary>
///
/// <param name="values">A double array containing the vector members.</param>
///
/// <returns>The standard deviation of the given data.</returns>
///
public static double StandardDeviation(this float[] values)
{
return StandardDeviation(values, Mean(values));
}
/// <summary>
/// Computes the Standard Deviation of the given values.
/// </summary>
///
/// <param name="values">A double array containing the vector members.</param>
/// <param name="mean">The mean of the vector, if already known.</param>
/// <param name="unbiased">
/// Pass true to compute the standard deviation using the sample variance.
/// Pass false to compute it using the population variance. See remarks
/// for more details.</param>
/// <remarks>
/// <para>
/// Setting <paramref name="unbiased"/> to <c>true</c> will make this method
/// compute the standard deviation σ using the sample variance, which is an unbiased
/// estimator of the true population variance. Setting this parameter to true will
/// thus compute σ using the following formula:</para>
/// <code>
/// N
/// σ² = 1 / (N - 1) ∑ (x_i − μ)²
/// i=1
/// </code>
/// <para>
/// Setting <paramref name="unbiased"/> to <c>false</c> will assume the given values
/// already represent the whole population, and will compute the population variance
/// using the formula: </para>
/// <code>
/// N
/// σ² = (1 / N) ∑ (x_i − μ)²
/// i=1
/// </code>
/// </remarks>
///
/// <returns>The standard deviation of the given data.</returns>
///
public static double StandardDeviation(this double[] values, double mean, bool unbiased = true)
{
return System.Math.Sqrt(Variance(values, mean, unbiased));
}
/// <summary>
/// Computes the Standard Deviation of the given values.
/// </summary>
/// <param name="values">A float array containing the vector members.</param>
/// <param name="mean">The mean of the vector, if already known.</param>
/// <returns>The standard deviation of the given data.</returns>
public static float StandardDeviation(this float[] values, float mean)
{
return (float)System.Math.Sqrt(Variance(values, mean));
}
/// <summary>
/// Computes the Standard Deviation of the given values.
/// </summary>
/// <param name="values">An integer array containing the vector members.</param>
/// <param name="mean">The mean of the vector, if already known.</param>
/// <returns>The standard deviation of the given data.</returns>
public static double StandardDeviation(this int[] values, double mean)
{
return System.Math.Sqrt(Variance(values, mean));
}
/// <summary>
/// Computes the Standard Error for a sample size, which estimates the
/// standard deviation of the sample mean based on the population mean.
/// </summary>
/// <param name="samples">The sample size.</param>
/// <param name="standardDeviation">The sample standard deviation.</param>
/// <returns>The standard error for the sample.</returns>
public static double StandardError(int samples, double standardDeviation)
{
return standardDeviation / System.Math.Sqrt(samples);
}
/// <summary>
/// Computes the Standard Error for a sample size, which estimates the
/// standard deviation of the sample mean based on the population mean.
/// </summary>
/// <param name="values">A double array containing the samples.</param>
/// <returns>The standard error for the sample.</returns>
public static double StandardError(double[] values)
{
return StandardError(values.Length, StandardDeviation(values));
}
/// <summary>
/// Computes the Median of the given values.
/// </summary>
/// <param name="values">A double array containing the vector members.</param>
/// <returns>The median of the given data.</returns>
public static double Median(this double[] values)
{
return Median(values, false);
}
/// <summary>
/// Computes the Median of the given values.
/// </summary>
///
/// <param name="values">An integer array containing the vector members.</param>
/// <param name="alreadySorted">A boolean parameter informing if the given values have already been sorted.</param>
/// <returns>The median of the given data.</returns>
///
public static double Median(this double[] values, bool alreadySorted)
{
return Median(values, 0, values.Length, alreadySorted);
}
/// <summary>
/// Computes the Median of the given values.
/// </summary>
///
/// <param name="values">An integer array containing the vector members.</param>
/// <param name="alreadySorted">A boolean parameter informing if the given values have already been sorted.</param>
/// <param name="length">The length of the subarray, starting at <paramref name="startIndex"/>.</param>
/// <param name="startIndex">The starting index of the array.</param>
///
/// <returns>The median of the given data.</returns>
///
public static double Median(this double[] values, int startIndex, int length, bool alreadySorted)
{
if (values.Length == 1)
return values[0];
if (!alreadySorted)
{
values = (double[])values.Clone();
Array.Sort(values);
}
int half = startIndex + length / 2;
if (length % 2 == 0)
return (values[half - 1] + values[half]) * 0.5; // N is even
else return values[half]; // N is odd
}
/// <summary>
/// Computes the Quartiles of the given values.
/// </summary>
///
/// <param name="values">An integer array containing the vector members.</param>
/// <param name="alreadySorted">A boolean parameter informing if the given values have already been sorted.</param>
/// <param name="range">The inter-quartile range for the values.</param>
/// <returns>The second quartile, the median of the given data.</returns>
///
public static double Quartiles(this double[] values, out DoubleRange range, bool alreadySorted)
{
double q1, q3;
double median = Quartiles(values, out q1, out q3, alreadySorted);
range = new DoubleRange(q1, q3);
return median;
}
/// <summary>
/// Computes the Quartiles of the given values.
/// </summary>
///
/// <param name="values">An integer array containing the vector members.</param>
/// <param name="q1">The first quartile.</param>
/// <param name="q3">The third quartile.</param>
/// <param name="alreadySorted">A boolean parameter informing if the given values have already been sorted.</param>
/// <returns>The second quartile, the median of the given data.</returns>
///
public static double Quartiles(this double[] values, out double q1, out double q3, bool alreadySorted)
{
double median;
if (values.Length == 1)
{
q1 = q3 = values[0];
return values[0];
}
else if (values.Length == 2)
{
median = values[0] + values[1];
q1 = (values[0] + median) / 2.0;
q3 = (median + values[1]) / 2.0;
return median;
}
if (!alreadySorted)
{
values = (double[])values.Clone();
Array.Sort(values);
}
int N = values.Length;
int half = N / 2;
if (N % 2 == 0)
{
// N is even
median = (values[half - 1] + values[half]) * 0.5;
// Separate data in half. Do not include data[half]
// and data[half - 1] in the halves.
int lowerStart = 0;
int lowerLength = half - 1;
int upperStart = half;
int upperLength = N - upperStart;
q1 = Median(values, lowerStart, lowerLength, alreadySorted: true);
q3 = Median(values, upperStart, upperLength, alreadySorted: true);
}
else
{
// N is odd
median = values[N / 2];
// Separate data in half. Do not include data[half]
// in the halves.
int lowerStart = 0;
int lowerLength = half;
int upperStart = half + 1;
int upperLength = N - upperStart;
q1 = Median(values, lowerStart, lowerLength, alreadySorted: true);
q3 = Median(values, upperStart, upperLength, alreadySorted: true);
}
return median;
}
/// <summary>
/// Computes the Variance of the given values.
/// </summary>
///
/// <param name="values">A double precision number array containing the vector members.</param>
/// <returns>The variance of the given data.</returns>
///
public static double Variance(this double[] values)
{
return Variance(values, Mean(values));
}
/// <summary>
/// Computes the Variance of the given values.
/// </summary>
///
/// <param name="values">A double precision number array containing the vector members.</param>
/// <param name="unbiased">
/// Pass true to compute the sample variance; or pass false to compute
/// the population variance. See remarks for more details.</param>
/// <remarks>
/// <para>
/// Setting <paramref name="unbiased"/> to <c>true</c> will make this method
/// compute the variance σ² using the sample variance, which is an unbiased
/// estimator of the true population variance. Setting this parameter to true
/// will thus compute σ² using the following formula:</para>
/// <code>
/// N
/// σ² = 1 / (N - 1) ∑ (x_i − μ)²
/// i=1
/// </code>
/// <para>
/// Setting <paramref name="unbiased"/> to <c>false</c> will assume the given values
/// already represent the whole population, and will compute the population variance
/// using the formula: </para>
/// <code>
/// N
/// σ² = (1 / N) ∑ (x_i − μ)²
/// i=1
/// </code>
/// </remarks>
///
/// <returns>The variance of the given data.</returns>
///
public static double Variance(this double[] values, bool unbiased)
{
return Variance(values, Mean(values), unbiased);
}
/// <summary>
/// Computes the Variance of the given values.
/// </summary>
///
/// <param name="values">An integer number array containing the vector members.</param>
///
/// <returns>The variance of the given data.</returns>
///
public static double Variance(this int[] values)
{
return Variance(values, Mean(values));
}
/// <summary>
/// Computes the Variance of the given values.
/// </summary>
///
/// <param name="values">An integer number array containing the vector members.</param>
///
/// <param name="unbiased">
/// Pass true to compute the sample variance; or pass false to compute
/// the population variance. See remarks for more details.</param>
/// <remarks>
/// <para>
/// Setting <paramref name="unbiased"/> to <c>true</c> will make this method
/// compute the variance σ² using the sample variance, which is an unbiased
/// estimator of the true population variance. Setting this parameter to true
/// will thus compute σ² using the following formula:</para>
/// <code>
/// N
/// σ² = 1 / (N - 1) ∑ (x_i − μ)²
/// i=1
/// </code>
/// <para>
/// Setting <paramref name="unbiased"/> to <c>false</c> will assume the given values
/// already represent the whole population, and will compute the population variance
/// using the formula: </para>
/// <code>
/// N
/// σ² = (1 / N) ∑ (x_i − μ)²
/// i=1
/// </code>
/// </remarks>
///
/// <returns>The variance of the given data.</returns>
///
public static double Variance(this int[] values, bool unbiased)
{
return Variance(values, Mean(values), unbiased);
}
/// <summary>
/// Computes the Variance of the given values.
/// </summary>
/// <param name="values">A single precision number array containing the vector members.</param>
/// <returns>The variance of the given data.</returns>
///
public static double Variance(this float[] values)
{
return Variance(values, Mean(values));
}
/// <summary>
/// Computes the Variance of the given values.
/// </summary>
///
/// <param name="values">A number array containing the vector members.</param>
/// <param name="mean">The mean of the array, if already known.</param>
///
/// <returns>The variance of the given data.</returns>
///
public static double Variance(this double[] values, double mean)
{
return Variance(values, mean, true);
}
/// <summary>
/// Computes the Variance of the given values.
/// </summary>
///
/// <param name="values">A number array containing the vector members.</param>
/// <param name="mean">The mean of the array, if already known.</param>
/// <param name="unbiased">
/// Pass true to compute the sample variance; or pass false to compute
/// the population variance. See remarks for more details.</param>
/// <remarks>
/// <para>
/// Setting <paramref name="unbiased"/> to <c>true</c> will make this method
/// compute the variance σ² using the sample variance, which is an unbiased
/// estimator of the true population variance. Setting this parameter to true
/// will thus compute σ² using the following formula:</para>
/// <code>
/// N
/// σ² = 1 / (N - 1) ∑ (x_i − μ)²
/// i=1
/// </code>
/// <para>
/// Setting <paramref name="unbiased"/> to <c>false</c> will assume the given values
/// already represent the whole population, and will compute the population variance
/// using the formula: </para>
/// <code>
/// N
/// σ² = (1 / N) ∑ (x_i − μ)²
/// i=1
/// </code>
/// </remarks>
///
///
/// <returns>The variance of the given data.</returns>
///
public static double Variance(this double[] values, double mean, bool unbiased = true)
{
double variance = 0.0;
for (int i = 0; i < values.Length; i++)
{
double x = values[i] - mean;
variance += x * x;
}
if (unbiased)
{
// Sample variance
return variance / (values.Length - 1);
}
else
{
// Population variance
return variance / values.Length;
}
}
/// <summary>
/// Computes the Variance of the given values.
/// </summary>
///
/// <param name="values">A number array containing the vector members.</param>
/// <param name="mean">The mean of the array, if already known.</param>
/// <param name="unbiased">
/// Pass true to compute the sample variance; or pass false to compute
/// the population variance. See remarks for more details.</param>
/// <remarks>
/// <para>
/// Setting <paramref name="unbiased"/> to <c>true</c> will make this method
/// compute the variance σ² using the sample variance, which is an unbiased
/// estimator of the true population variance. Setting this parameter to true
/// will thus compute σ² using the following formula:</para>
/// <code>
/// N
/// σ² = 1 / (N - 1) ∑ (x_i − μ)²
/// i=1
/// </code>
/// <para>
/// Setting <paramref name="unbiased"/> to <c>false</c> will assume the given values
/// already represent the whole population, and will compute the population variance
/// using the formula: </para>
/// <code>
/// N
/// σ² = (1 / N) ∑ (x_i − μ)²
/// i=1
/// </code>
/// </remarks>
///
///
/// <returns>The variance of the given data.</returns>
///
public static double Variance(this int[] values, double mean, bool unbiased = true)
{
double variance = 0.0;
for (int i = 0; i < values.Length; i++)
{
double x = values[i] - mean;
variance += x * x;
}
if (unbiased)
{
// Sample variance
return variance / (values.Length - 1);
}
else
{
// Population variance
return variance / values.Length;
}
}
/// <summary>
/// Computes the Variance of the given values.
/// </summary>
///
/// <param name="values">A number array containing the vector members.</param>
/// <param name="mean">The mean of the array, if already known.</param>
/// <returns>The variance of the given data.</returns>
///
public static float Variance(this float[] values, float mean)
{
float variance = 0;
for (int i = 0; i < values.Length; i++)
{
float x = values[i] - mean;
variance += x * x;
}
// Sample variance
return variance / (values.Length - 1);
}
/// <summary>
/// Computes the pooled standard deviation of the given values.
/// </summary>
///
/// <param name="samples">The grouped samples.</param>
/// <param name="unbiased">
/// True to compute a pooled standard deviation using unbiased estimates
/// of the population variance; false otherwise. Default is true.</param>
///
public static double PooledStandardDeviation(bool unbiased, params double[][] samples)
{
return Math.Sqrt(PooledVariance(unbiased, samples));
}
/// <summary>
/// Computes the pooled standard deviation of the given values.
/// </summary>
///
/// <param name="samples">The grouped samples.</param>
///
public static double PooledStandardDeviation(params double[][] samples)
{
return Math.Sqrt(PooledVariance(true, samples));
}
/// <summary>
/// Computes the pooled standard deviation of the given values.
/// </summary>
///
/// <param name="sizes">The number of samples used to compute the <paramref name="variances"/>.</param>
/// <param name="variances">The unbiased variances for the samples.</param>
/// <param name="unbiased">
/// True to compute a pooled standard deviation using unbiased estimates
/// of the population variance; false otherwise. Default is true.</param>
///
public static double PooledStandardDeviation(int[] sizes, double[] variances, bool unbiased = true)
{
return Math.Sqrt(PooledVariance(sizes, variances, unbiased));
}
/// <summary>
/// Computes the pooled variance of the given values.
/// </summary>
///
/// <param name="samples">The grouped samples.</param>
///
public static double PooledVariance(params double[][] samples)
{
return PooledVariance(true, samples);
}
/// <summary>
/// Computes the pooled variance of the given values.
/// </summary>
///
/// <param name="unbiased">
/// True to obtain an unbiased estimate of the population
/// variance; false otherwise. Default is true.</param>
///
/// <param name="samples">The grouped samples.</param>
///
public static double PooledVariance(bool unbiased, params double[][] samples)
{
if (samples == null)
throw new ArgumentNullException("samples");
double sum = 0;
int length = 0;
for (int i = 0; i < samples.Length; i++)
{
double[] values = samples[i];
double var = Variance(values);
sum += (values.Length - 1) * var;
if (unbiased)
{
length += values.Length - 1;
}
else
{
length += values.Length;
}
}
return sum / length;
}
/// <summary>
/// Computes the pooled variance of the given values.
/// </summary>
///
/// <param name="sizes">The number of samples used to compute the <paramref name="variances"/>.</param>
/// <param name="variances">The unbiased variances for the samples.</param>
/// <param name="unbiased">
/// True to obtain an unbiased estimate of the population
/// variance; false otherwise. Default is true.</param>
///
public static double PooledVariance(int[] sizes, double[] variances, bool unbiased = true)
{
if (sizes == null)
throw new ArgumentNullException("sizes");
if (variances == null)
throw new ArgumentNullException("variances");
if (sizes.Length != variances.Length)
throw new DimensionMismatchException("variances");
double sum = 0;
int length = 0;
for (int i = 0; i < variances.Length; i++)
{
double var = variances[i];
sum += (sizes[i] - 1) * var;
if (unbiased)
{
length += sizes[i] - 1;
}
else
{
length += sizes[i];
}
}
return sum / (double)length;
}
/// <summary>
/// Computes the Mode of the given values.
/// </summary>
///
/// <param name="values">A number array containing the vector values.</param>
///
/// <returns>The most common value in the given data.</returns>
///
public static T Mode<T>(this T[] values)
{
int bestCount;
return Mode<T>(values, out bestCount, inPlace: false, alreadySorted: false);
}
/// <summary>
/// Computes the Mode of the given values.
/// </summary>
///
/// <param name="values">A number array containing the vector values.</param>
/// <param name="count">Returns how many times the detected mode happens in the values.</param>
///
/// <returns>The most common value in the given data.</returns>
///
public static T Mode<T>(this T[] values, out int count)
{
return Mode<T>(values, out count, inPlace: false, alreadySorted: false);
}
/// <summary>
/// Computes the Mode of the given values.
/// </summary>
///
/// <param name="values">A number array containing the vector values.</param>
/// <param name="inPlace">True to perform the operation in place, altering the original input vector.</param>
/// <param name="alreadySorted">Pass true if the list of values is already sorted.</param>
///
/// <returns>The most common value in the given data.</returns>
///
public static T Mode<T>(this T[] values,
bool inPlace, bool alreadySorted = false)
{
int count;
return Mode<T>(values, out count, inPlace: inPlace, alreadySorted: alreadySorted);
}
/// <summary>
/// Computes the Mode of the given values.
/// </summary>
///
/// <param name="values">A number array containing the vector values.</param>
/// <param name="inPlace">True to perform the operation in place, altering the original input vector.</param>
/// <param name="alreadySorted">Pass true if the list of values is already sorted.</param>
/// <param name="count">Returns how many times the detected mode happens in the values.</param>
///
/// <returns>The most common value in the given data.</returns>
///
public static T Mode<T>(this T[] values, out int count,
bool inPlace, bool alreadySorted = false)
{
if (values.Length == 0)
throw new ArgumentException("The values vector cannot be empty.", "values");
if (values[0] is IComparable)
return mode_sort<T>(values, inPlace, alreadySorted, out count);
return mode_bag<T>(values, out count);
}
private static T mode_bag<T>(T[] values, out int bestCount)
{
var bestValue = values[0];
bestCount = 1;
var set = new Dictionary<T, int>();
foreach (var v in values)
{
int count;
if (!set.TryGetValue(v, out count))
count = 1;
else
count = count + 1;
set[v] = count;
if (count > bestCount)
{
bestCount = count;
bestValue = v;
}
}
return bestValue;
}
private static T mode_sort<T>(T[] values, bool inPlace, bool alreadySorted, out int bestCount)
{
if (!alreadySorted)
{
if (!inPlace)
values = (T[])values.Clone();
Array.Sort(values);
}
var currentValue = values[0];
var currentCount = 1;
var bestValue = currentValue;
bestCount = currentCount;
for (int i = 1; i < values.Length; i++)
{
if (currentValue.Equals(values[i]))
{
currentCount += 1;
}
else
{
currentValue = values[i];
currentCount = 1;
}
if (currentCount > bestCount)
{
bestCount = currentCount;
bestValue = currentValue;
}
}
return bestValue;
}
/// <summary>
/// Computes the Covariance between two arrays of values.
/// </summary>
///
/// <param name="vector1">A number array containing the first vector elements.</param>
/// <param name="vector2">A number array containing the second vector elements.</param>
/// <param name="unbiased">
/// Pass true to compute the sample variance; or pass false to compute
/// the population variance. See remarks for more details.</param>
/// <remarks>
/// <para>
/// Setting <paramref name="unbiased"/> to <c>true</c> will make this method
/// compute the variance σ² using the sample variance, which is an unbiased
/// estimator of the true population variance. Setting this parameter to true
/// will thus compute σ² using the following formula:</para>
/// <code>
/// N
/// σ² = 1 / (N - 1) ∑ (x_i − μ)²
/// i=1
/// </code>
/// <para>
/// Setting <paramref name="unbiased"/> to <c>false</c> will assume the given values
/// already represent the whole population, and will compute the population variance
/// using the formula: </para>
/// <code>
/// N
/// σ² = (1 / N) ∑ (x_i − μ)²
/// i=1
/// </code>
/// </remarks>
///
/// <returns>The variance of the given data.</returns>
///
public static double Covariance(this double[] vector1, double[] vector2, bool unbiased = true)
{
return Covariance(vector1, Mean(vector1), vector2, Mean(vector2), unbiased);
}
/// <summary>
/// Computes the Covariance between two arrays of values.
/// </summary>
///
/// <param name="vector1">A number array containing the first vector elements.</param>
/// <param name="vector2">A number array containing the second vector elements.</param>
/// <param name="mean1">The mean value of <paramref name="vector1"/>, if known.</param>
/// <param name="mean2">The mean value of <paramref name="vector2"/>, if known.</param>
/// <param name="unbiased">
/// Pass true to compute the sample variance; or pass false to compute
/// the population variance. See remarks for more details.</param>
/// <remarks>
/// <para>
/// Setting <paramref name="unbiased"/> to <c>true</c> will make this method
/// compute the variance σ² using the sample variance, which is an unbiased
/// estimator of the true population variance. Setting this parameter to true
/// will thus compute σ² using the following formula:</para>
/// <code>
/// N
/// σ² = 1 / (N - 1) ∑ (x_i − μ)²
/// i=1
/// </code>
/// <para>
/// Setting <paramref name="unbiased"/> to <c>false</c> will assume the given values
/// already represent the whole population, and will compute the population variance
/// using the formula: </para>
/// <code>
/// N
/// σ² = (1 / N) ∑ (x_i − μ)²
/// i=1
/// </code>
/// </remarks>
///
/// <returns>The variance of the given data.</returns>
///
public static double Covariance(this double[] vector1, double mean1, double[] vector2, double mean2, bool unbiased = true)
{
if (vector1 == null)
throw new ArgumentNullException("vector1");
if (vector2 == null)
throw new ArgumentNullException("vector2");
if (vector1.Length != vector2.Length)
throw new DimensionMismatchException("vector2");
double covariance = 0.0;
for (int i = 0; i < vector1.Length; i++)
{
double x = vector1[i] - mean1;
double y = vector2[i] - mean2;
covariance += x * y;
}
if (unbiased)
{
// Sample variance
return covariance / (vector1.Length - 1);
}
else
{
// Population variance
return covariance / vector1.Length;
}
}
/// <summary>
/// Computes the Skewness for the given values.
/// </summary>
///
/// <remarks>
/// Skewness characterizes the degree of asymmetry of a distribution
/// around its mean. Positive skewness indicates a distribution with
/// an asymmetric tail extending towards more positive values. Negative
/// skewness indicates a distribution with an asymmetric tail extending
/// towards more negative values.
/// </remarks>
///
/// <param name="values">A number array containing the vector values.</param>
///
/// <param name="unbiased">
/// True to compute the unbiased estimate of the population
/// skewness, false otherwise. Default is true (compute the
/// unbiased estimator).</param>
///
/// <returns>The skewness of the given data.</returns>
///
public static double Skewness(this double[] values, bool unbiased = true)
{
double mean = Mean(values);
return Skewness(values, mean, unbiased);
}
/// <summary>
/// Computes the Skewness for the given values.
/// </summary>
///
/// <remarks>
/// Skewness characterizes the degree of asymmetry of a distribution
/// around its mean. Positive skewness indicates a distribution with
/// an asymmetric tail extending towards more positive values. Negative
/// skewness indicates a distribution with an asymmetric tail extending
/// towards more negative values.
/// </remarks>
///
/// <param name="values">A number array containing the vector values.</param>
/// <param name="mean">The values' mean, if already known.</param>
/// <param name="unbiased">
/// True to compute the unbiased estimate of the population
/// skewness, false otherwise. Default is true (compute the
/// unbiased estimator).</param>
///
/// <returns>The skewness of the given data.</returns>
///
public static double Skewness(this double[] values, double mean, bool unbiased = true)
{
double n = values.Length;
double s2 = 0;
double s3 = 0;
for (int i = 0; i < values.Length; i++)
{
double dev = values[i] - mean;
s2 += dev * dev;
s3 += dev * dev * dev;
}
double m2 = s2 / n;
double m3 = s3 / n;
double g = m3 / (Math.Pow(m2, 3 / 2.0));
if (unbiased)
{
double a = Math.Sqrt(n * (n - 1));
double b = n - 2;
return (a / b) * g;
}
return g;
}
/// <summary>
/// Computes the Kurtosis for the given values.
/// </summary>
///
/// <remarks>
/// The framework uses the same definition used by default in SAS and SPSS.
/// </remarks>
///
/// <param name="values">A number array containing the vector values.</param>
/// <param name="unbiased">
/// True to compute the unbiased estimate of the population
/// kurtosis, false otherwise. Default is true (compute the
/// unbiased estimator).</param>
///
/// <returns>The kurtosis of the given data.</returns>
///
public static double Kurtosis(this double[] values, bool unbiased = true)
{
double mean = Mean(values);
return Kurtosis(values, mean, unbiased);
}
/// <summary>
/// Computes the Kurtosis for the given values.
/// </summary>
///
/// <remarks>
/// The framework uses the same definition used by default in SAS and SPSS.
/// </remarks>
///
/// <param name="values">A number array containing the vector values.</param>
/// <param name="mean">The values' mean, if already known.</param>
/// <param name="unbiased">
/// True to compute the unbiased estimate of the population
/// kurtosis, false otherwise. Default is true (compute the
/// unbiased estimator).</param>
///
/// <returns>The kurtosis of the given data.</returns>
///
public static double Kurtosis(this double[] values, double mean, bool unbiased = true)
{
// http://www.ats.ucla.edu/stat/mult_pkg/faq/general/kurtosis.htm
double n = values.Length;
double s2 = 0;
double s4 = 0;
for (int i = 0; i < values.Length; i++)
{
double dev = values[i] - mean;
s2 += dev * dev;
s4 += dev * dev * dev * dev;
}
double m2 = s2 / n;
double m4 = s4 / n;
if (unbiased)
{
double v = s2 / (n - 1);
double a = (n * (n + 1)) / ((n - 1) * (n - 2) * (n - 3));
double b = s4 / (v * v);
double c = ((n - 1) * (n - 1)) / ((n - 2) * (n - 3));
return a * b - 3 * c;
}
else
{
return m4 / (m2 * m2) - 3;
}
}
/// <summary>
/// Computes the entropy function for a set of numerical values in a
/// given <see cref="Accord.Statistics.Distributions.Univariate.UnivariateContinuousDistribution.ProbabilityDensityFunction(double)"/>.
/// </summary>
///
/// <param name="values">A number array containing the vector values.</param>
/// <param name="pdf">A probability distribution function.</param>
///
/// <returns>The distribution's entropy for the given values.</returns>
///
public static double Entropy(this double[] values, Func<double, double> pdf)
{
double sum = 0;
for (int i = 0; i < values.Length; i++)
{
double p = pdf(values[i]);
sum += p * Math.Log(p);
}
return sum;
}
/// <summary>
/// Computes the entropy function for a set of numerical values in a
/// given <see cref="Accord.Statistics.Distributions.Univariate.UnivariateContinuousDistribution.ProbabilityDensityFunction(double)"/>.
/// </summary>
///
/// <param name="values">A number array containing the vector values.</param>
/// <param name="pdf">A probability distribution function.</param>
/// <param name="weights">The importance for each sample.</param>
///
/// <returns>The distribution's entropy for the given values.</returns>
///
public static double WeightedEntropy(this double[] values, double[] weights, Func<double, double> pdf)
{
double sum = 0;
for (int i = 0; i < values.Length; i++)
{
double p = pdf(values[i]);
sum += p * Math.Log(p) * weights[i];
}
return sum;
}
/// <summary>
/// Computes the entropy function for a set of numerical values in a
/// given <see cref="Accord.Statistics.Distributions.Univariate.UnivariateContinuousDistribution.ProbabilityDensityFunction(double)"/>.
/// </summary>
///
/// <param name="values">A number array containing the vector values.</param>
/// <param name="pdf">A probability distribution function.</param>
/// <param name="weights">The repetition counts for each sample.</param>
///
/// <returns>The distribution's entropy for the given values.</returns>
///
public static double WeightedEntropy(this double[] values, int[] weights, Func<double, double> pdf)
{
double sum = 0;
for (int i = 0; i < values.Length; i++)
{
double p = pdf(values[i]);
sum += p * Math.Log(p) * weights[i];
}
return sum;
}
/// <summary>
/// Computes the entropy for the given values.
/// </summary>
///
/// <param name="values">A number array containing the vector values.</param>
///
/// <returns>The calculated entropy for the given values.</returns>
///
public static double Entropy(this double[] values)
{
double sum = 0;
foreach (double v in values)
sum += v * Math.Log(v);
return -sum;
}
/// <summary>
/// Computes the entropy for the given values.
/// </summary>
///
/// <param name="values">A number array containing the vector values.</param>
/// <param name="eps">A small constant to avoid <see cref="Double.NaN"/>s in
/// case the there is a zero between the given <paramref name="values"/>.</param>
///
/// <returns>The calculated entropy for the given values.</returns>
///
public static double Entropy(this double[] values, double eps = 0)
{
double sum = 0;
foreach (double v in values)
sum += v * Math.Log(v + eps);
return -sum;
}
/// <summary>
/// Computes the entropy for the given values.
/// </summary>
///
/// <param name="values">A number matrix containing the matrix values.</param>
/// <param name="eps">A small constant to avoid <see cref="Double.NaN"/>s in
/// case the there is a zero between the given <paramref name="values"/>.</param>
///
/// <returns>The calculated entropy for the given values.</returns>
///
public static double Entropy(this double[,] values, double eps = 0)
{
double sum = 0;
foreach (double v in values)
sum += v * Math.Log(v + eps);
return -sum;
}
/// <summary>
/// Computes the entropy for the given values.
/// </summary>
///
/// <param name="values">A number matrix containing the matrix values.</param>
///
/// <returns>The calculated entropy for the given values.</returns>
///
public static double Entropy(this double[,] values)
{
double sum = 0;
foreach (double v in values)
sum += v * Math.Log(v);
return -sum;
}
/// <summary>
/// Computes the entropy for the given values.
/// </summary>
///
/// <param name="values">An array of integer symbols.</param>
/// <param name="startValue">The starting symbol.</param>
/// <param name="endValue">The ending symbol.</param>
/// <returns>The evaluated entropy.</returns>
///
public static double Entropy(int[] values, int startValue, int endValue)
{
double entropy = 0;
// For each class
for (int c = startValue; c <= endValue; c++)
{
int count = 0;
// Count the number of instances inside
for (int i = 0; i < values.Length; i++)
if (values[i] == c) count++;
if (count > 0)
{
// Avoid situations limiting situations
// by forcing 0 * Math.Log(0) to be 0.
double p = (double)count / values.Length;
entropy -= p * Math.Log(p, 2);
}
}
return entropy;
}
/// <summary>
/// Computes the entropy for the given values.
/// </summary>
///
/// <param name="values">An array of integer symbols.</param>
/// <param name="startValue">The starting symbol.</param>
/// <param name="endValue">The ending symbol.</param>
/// <returns>The evaluated entropy.</returns>
///
public static double Entropy(IList<int> values, int startValue, int endValue)
{
double entropy = 0;
double total = values.Count;
// For each class
for (int c = startValue; c <= endValue; c++)
{
int count = 0;
// Count the number of instances inside
foreach (int v in values)
if (v == c) count++;
if (count > 0)
{
// Avoid situations limiting situations
// by forcing 0 * Math.Log(0) to be 0.
double p = count / total;
entropy -= p * Math.Log(p, 2);
}
}
return entropy;
}
/// <summary>
/// Computes the entropy for the given values.
/// </summary>
///
/// <param name="values">An array of integer symbols.</param>
/// <param name="valueRange">The range of symbols.</param>
/// <returns>The evaluated entropy.</returns>
///
public static double Entropy(int[] values, IntRange valueRange)
{
return Entropy(values, valueRange.Min, valueRange.Max);
}
/// <summary>
/// Computes the entropy for the given values.
/// </summary>
///
/// <param name="values">An array of integer symbols.</param>
/// <param name="classes">The number of distinct classes.</param>
/// <returns>The evaluated entropy.</returns>
///
public static double Entropy(int[] values, int classes)
{
return Entropy(values, 0, classes - 1);
}
/// <summary>
/// Computes the entropy for the given values.
/// </summary>
///
/// <param name="values">An array of integer symbols.</param>
/// <param name="classes">The number of distinct classes.</param>
/// <returns>The evaluated entropy.</returns>
///
public static double Entropy(IList<int> values, int classes)
{
return Entropy(values, 0, classes - 1);
}
}
}
| 38.290302 | 146 | 0.490766 | [
"MIT"
] | mastercs999/fn-trading | src/Accord/Accord.Statistics/Measures/Measures.Vectors.cs | 60,965 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Claims;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Rendering;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using ErrorLogging.Models;
using ErrorLogging.Models.AccountViewModels;
using ErrorLogging.Services;
namespace ErrorLogging.Controllers
{
[Authorize]
public class AccountController : Controller
{
private readonly UserManager<ApplicationUser> _userManager;
private readonly SignInManager<ApplicationUser> _signInManager;
private readonly IEmailSender _emailSender;
private readonly ISmsSender _smsSender;
private readonly ILogger _logger;
public AccountController(
UserManager<ApplicationUser> userManager,
SignInManager<ApplicationUser> signInManager,
IEmailSender emailSender,
ISmsSender smsSender,
ILoggerFactory loggerFactory)
{
_userManager = userManager;
_signInManager = signInManager;
_emailSender = emailSender;
_smsSender = smsSender;
_logger = loggerFactory.CreateLogger<AccountController>();
}
//
// GET: /Account/Login
[HttpGet]
[AllowAnonymous]
public async Task<IActionResult> Login(string returnUrl = null)
{
// Clear the existing external cookie to ensure a clean login process
await HttpContext.SignOutAsync(IdentityConstants.ExternalScheme);
ViewData["ReturnUrl"] = returnUrl;
return View();
}
//
// POST: /Account/Login
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Login(LoginViewModel model, string returnUrl = null)
{
ViewData["ReturnUrl"] = returnUrl;
if (ModelState.IsValid)
{
// This doesn't count login failures towards account lockout
// To enable password failures to trigger account lockout, set lockoutOnFailure: true
var result = await _signInManager.PasswordSignInAsync(model.Email, model.Password, model.RememberMe, lockoutOnFailure: false);
if (result.Succeeded)
{
_logger.LogInformation(1, "User logged in.");
return RedirectToLocal(returnUrl);
}
if (result.RequiresTwoFactor)
{
return RedirectToAction(nameof(SendCode), new { ReturnUrl = returnUrl, RememberMe = model.RememberMe });
}
if (result.IsLockedOut)
{
_logger.LogWarning(2, "User account locked out.");
return View("Lockout");
}
else
{
ModelState.AddModelError(string.Empty, "Invalid login attempt.");
return View(model);
}
}
// If we got this far, something failed, redisplay form
return View(model);
}
//
// GET: /Account/Register
[HttpGet]
[AllowAnonymous]
public IActionResult Register(string returnUrl = null)
{
ViewData["ReturnUrl"] = returnUrl;
return View();
}
//
// POST: /Account/Register
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Register(RegisterViewModel model, string returnUrl = null)
{
ViewData["ReturnUrl"] = returnUrl;
if (ModelState.IsValid)
{
var user = new ApplicationUser { UserName = model.Email, Email = model.Email };
var result = await _userManager.CreateAsync(user, model.Password);
if (result.Succeeded)
{
// For more information on how to enable account confirmation and password reset please visit https://go.microsoft.com/fwlink/?LinkID=532713
// Send an email with this link
//var code = await _userManager.GenerateEmailConfirmationTokenAsync(user);
//var callbackUrl = Url.Action(nameof(ConfirmEmail), "Account", new { userId = user.Id, code = code }, protocol: HttpContext.Request.Scheme);
//await _emailSender.SendEmailAsync(model.Email, "Confirm your account",
// $"Please confirm your account by clicking this link: <a href='{callbackUrl}'>link</a>");
await _signInManager.SignInAsync(user, isPersistent: false);
_logger.LogInformation(3, "User created a new account with password.");
return RedirectToLocal(returnUrl);
}
AddErrors(result);
}
// If we got this far, something failed, redisplay form
return View(model);
}
//
// POST: /Account/Logout
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Logout()
{
await _signInManager.SignOutAsync();
_logger.LogInformation(4, "User logged out.");
return RedirectToAction(nameof(HomeController.Index), "Home");
}
//
// POST: /Account/ExternalLogin
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public IActionResult ExternalLogin(string provider, string returnUrl = null)
{
// Request a redirect to the external login provider.
var redirectUrl = Url.Action(nameof(ExternalLoginCallback), "Account", new { ReturnUrl = returnUrl });
var properties = _signInManager.ConfigureExternalAuthenticationProperties(provider, redirectUrl);
return Challenge(properties, provider);
}
//
// GET: /Account/ExternalLoginCallback
[HttpGet]
[AllowAnonymous]
public async Task<IActionResult> ExternalLoginCallback(string returnUrl = null, string remoteError = null)
{
if (remoteError != null)
{
ModelState.AddModelError(string.Empty, $"Error from external provider: {remoteError}");
return View(nameof(Login));
}
var info = await _signInManager.GetExternalLoginInfoAsync();
if (info == null)
{
return RedirectToAction(nameof(Login));
}
// Sign in the user with this external login provider if the user already has a login.
var result = await _signInManager.ExternalLoginSignInAsync(info.LoginProvider, info.ProviderKey, isPersistent: false);
if (result.Succeeded)
{
_logger.LogInformation(5, "User logged in with {Name} provider.", info.LoginProvider);
return RedirectToLocal(returnUrl);
}
if (result.RequiresTwoFactor)
{
return RedirectToAction(nameof(SendCode), new { ReturnUrl = returnUrl });
}
if (result.IsLockedOut)
{
return View("Lockout");
}
else
{
// If the user does not have an account, then ask the user to create an account.
ViewData["ReturnUrl"] = returnUrl;
ViewData["LoginProvider"] = info.LoginProvider;
var email = info.Principal.FindFirstValue(ClaimTypes.Email);
return View("ExternalLoginConfirmation", new ExternalLoginConfirmationViewModel { Email = email });
}
}
//
// POST: /Account/ExternalLoginConfirmation
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public async Task<IActionResult> ExternalLoginConfirmation(ExternalLoginConfirmationViewModel model, string returnUrl = null)
{
if (ModelState.IsValid)
{
// Get the information about the user from the external login provider
var info = await _signInManager.GetExternalLoginInfoAsync();
if (info == null)
{
return View("ExternalLoginFailure");
}
var user = new ApplicationUser { UserName = model.Email, Email = model.Email };
var result = await _userManager.CreateAsync(user);
if (result.Succeeded)
{
result = await _userManager.AddLoginAsync(user, info);
if (result.Succeeded)
{
await _signInManager.SignInAsync(user, isPersistent: false);
_logger.LogInformation(6, "User created an account using {Name} provider.", info.LoginProvider);
return RedirectToLocal(returnUrl);
}
}
AddErrors(result);
}
ViewData["ReturnUrl"] = returnUrl;
return View(model);
}
// GET: /Account/ConfirmEmail
[HttpGet]
[AllowAnonymous]
public async Task<IActionResult> ConfirmEmail(string userId, string code)
{
if (userId == null || code == null)
{
return View("Error");
}
var user = await _userManager.FindByIdAsync(userId);
if (user == null)
{
return View("Error");
}
var result = await _userManager.ConfirmEmailAsync(user, code);
return View(result.Succeeded ? "ConfirmEmail" : "Error");
}
//
// GET: /Account/ForgotPassword
[HttpGet]
[AllowAnonymous]
public IActionResult ForgotPassword()
{
return View();
}
//
// POST: /Account/ForgotPassword
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public async Task<IActionResult> ForgotPassword(ForgotPasswordViewModel model)
{
if (ModelState.IsValid)
{
var user = await _userManager.FindByEmailAsync(model.Email);
if (user == null || !(await _userManager.IsEmailConfirmedAsync(user)))
{
// Don't reveal that the user does not exist or is not confirmed
return View("ForgotPasswordConfirmation");
}
// For more information on how to enable account confirmation and password reset please visit https://go.microsoft.com/fwlink/?LinkID=532713
// Send an email with this link
//var code = await _userManager.GeneratePasswordResetTokenAsync(user);
//var callbackUrl = Url.Action(nameof(ResetPassword), "Account", new { userId = user.Id, code = code }, protocol: HttpContext.Request.Scheme);
//await _emailSender.SendEmailAsync(model.Email, "Reset Password",
// $"Please reset your password by clicking here: <a href='{callbackUrl}'>link</a>");
//return View("ForgotPasswordConfirmation");
}
// If we got this far, something failed, redisplay form
return View(model);
}
//
// GET: /Account/ForgotPasswordConfirmation
[HttpGet]
[AllowAnonymous]
public IActionResult ForgotPasswordConfirmation()
{
return View();
}
//
// GET: /Account/ResetPassword
[HttpGet]
[AllowAnonymous]
public IActionResult ResetPassword(string code = null)
{
return code == null ? View("Error") : View();
}
//
// POST: /Account/ResetPassword
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public async Task<IActionResult> ResetPassword(ResetPasswordViewModel model)
{
if (!ModelState.IsValid)
{
return View(model);
}
var user = await _userManager.FindByEmailAsync(model.Email);
if (user == null)
{
// Don't reveal that the user does not exist
return RedirectToAction(nameof(AccountController.ResetPasswordConfirmation), "Account");
}
var result = await _userManager.ResetPasswordAsync(user, model.Code, model.Password);
if (result.Succeeded)
{
return RedirectToAction(nameof(AccountController.ResetPasswordConfirmation), "Account");
}
AddErrors(result);
return View();
}
//
// GET: /Account/ResetPasswordConfirmation
[HttpGet]
[AllowAnonymous]
public IActionResult ResetPasswordConfirmation()
{
return View();
}
//
// GET: /Account/SendCode
[HttpGet]
[AllowAnonymous]
public async Task<ActionResult> SendCode(string returnUrl = null, bool rememberMe = false)
{
var user = await _signInManager.GetTwoFactorAuthenticationUserAsync();
if (user == null)
{
return View("Error");
}
var userFactors = await _userManager.GetValidTwoFactorProvidersAsync(user);
var factorOptions = userFactors.Select(purpose => new SelectListItem { Text = purpose, Value = purpose }).ToList();
return View(new SendCodeViewModel { Providers = factorOptions, ReturnUrl = returnUrl, RememberMe = rememberMe });
}
//
// POST: /Account/SendCode
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public async Task<IActionResult> SendCode(SendCodeViewModel model)
{
if (!ModelState.IsValid)
{
return View();
}
var user = await _signInManager.GetTwoFactorAuthenticationUserAsync();
if (user == null)
{
return View("Error");
}
// Generate the token and send it
var code = await _userManager.GenerateTwoFactorTokenAsync(user, model.SelectedProvider);
if (string.IsNullOrWhiteSpace(code))
{
return View("Error");
}
var message = "Your security code is: " + code;
if (model.SelectedProvider == "Email")
{
await _emailSender.SendEmailAsync(await _userManager.GetEmailAsync(user), "Security Code", message);
}
else if (model.SelectedProvider == "Phone")
{
await _smsSender.SendSmsAsync(await _userManager.GetPhoneNumberAsync(user), message);
}
return RedirectToAction(nameof(VerifyCode), new { Provider = model.SelectedProvider, ReturnUrl = model.ReturnUrl, RememberMe = model.RememberMe });
}
//
// GET: /Account/VerifyCode
[HttpGet]
[AllowAnonymous]
public async Task<IActionResult> VerifyCode(string provider, bool rememberMe, string returnUrl = null)
{
// Require that the user has already logged in via username/password or external login
var user = await _signInManager.GetTwoFactorAuthenticationUserAsync();
if (user == null)
{
return View("Error");
}
return View(new VerifyCodeViewModel { Provider = provider, ReturnUrl = returnUrl, RememberMe = rememberMe });
}
//
// POST: /Account/VerifyCode
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public async Task<IActionResult> VerifyCode(VerifyCodeViewModel model)
{
if (!ModelState.IsValid)
{
return View(model);
}
// The following code protects for brute force attacks against the two factor codes.
// If a user enters incorrect codes for a specified amount of time then the user account
// will be locked out for a specified amount of time.
var result = await _signInManager.TwoFactorSignInAsync(model.Provider, model.Code, model.RememberMe, model.RememberBrowser);
if (result.Succeeded)
{
return RedirectToLocal(model.ReturnUrl);
}
if (result.IsLockedOut)
{
_logger.LogWarning(7, "User account locked out.");
return View("Lockout");
}
else
{
ModelState.AddModelError(string.Empty, "Invalid code.");
return View(model);
}
}
//
// GET: /Account/AccessDenied
[HttpGet]
public IActionResult AccessDenied()
{
return View();
}
#region Helpers
private void AddErrors(IdentityResult result)
{
foreach (var error in result.Errors)
{
ModelState.AddModelError(string.Empty, error.Description);
}
}
private IActionResult RedirectToLocal(string returnUrl)
{
if (Url.IsLocalUrl(returnUrl))
{
return Redirect(returnUrl);
}
else
{
return RedirectToAction(nameof(HomeController.Index), "Home");
}
}
#endregion
}
}
| 37.580713 | 161 | 0.565101 | [
"MIT"
] | PacktPublishing/ASPdotNET-High-Performance | Chapter10/ErrorLogging/Controllers/AccountController.cs | 17,928 | 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.Aws.KinesisAnalyticsV2.Inputs
{
public sealed class ApplicationApplicationConfigurationSqlApplicationConfigurationReferenceDataSourceArgs : Pulumi.ResourceArgs
{
[Input("referenceId")]
public Input<string>? ReferenceId { get; set; }
/// <summary>
/// Describes the format of the data in the streaming source, and how each data element maps to corresponding columns created in the in-application stream.
/// </summary>
[Input("referenceSchema", required: true)]
public Input<Inputs.ApplicationApplicationConfigurationSqlApplicationConfigurationReferenceDataSourceReferenceSchemaArgs> ReferenceSchema { get; set; } = null!;
/// <summary>
/// Identifies the S3 bucket and object that contains the reference data.
/// </summary>
[Input("s3ReferenceDataSource", required: true)]
public Input<Inputs.ApplicationApplicationConfigurationSqlApplicationConfigurationReferenceDataSourceS3ReferenceDataSourceArgs> S3ReferenceDataSource { get; set; } = null!;
/// <summary>
/// The name of the in-application table to create.
/// </summary>
[Input("tableName", required: true)]
public Input<string> TableName { get; set; } = null!;
public ApplicationApplicationConfigurationSqlApplicationConfigurationReferenceDataSourceArgs()
{
}
}
}
| 42.219512 | 180 | 0.71115 | [
"ECL-2.0",
"Apache-2.0"
] | RafalSumislawski/pulumi-aws | sdk/dotnet/KinesisAnalyticsV2/Inputs/ApplicationApplicationConfigurationSqlApplicationConfigurationReferenceDataSourceArgs.cs | 1,731 | C# |
using System.Text.Json;
using JT808.Protocol.Extensions;
using JT808.Protocol.Formatters;
using JT808.Protocol.Interfaces;
using JT808.Protocol.MessagePack;
namespace JT808.Protocol.MessageBody
{
/// <summary>
/// 报警屏蔽字,与位置信息汇报消息中的报警标志相对应,相应位为 1则相应报警被屏蔽
/// </summary>
public class JT808_0x8103_0x0050 : JT808_0x8103_BodyBase, IJT808MessagePackFormatter<JT808_0x8103_0x0050>, IJT808Analyze
{
/// <summary>
/// 0x0050
/// </summary>
public override uint ParamId { get; set; } = 0x0050;
/// <summary>
/// 数据长度
/// 4 byte
/// </summary>
public override byte ParamLength { get; set; } = 4;
/// <summary>
/// 报警屏蔽字,与位置信息汇报消息中的报警标志相对应,相应位为 1则相应报警被屏蔽
/// </summary>
public uint ParamValue { get; set; }
/// <summary>
/// 报警屏蔽字
/// </summary>
public override string Description => "报警屏蔽字";
/// <summary>
///
/// </summary>
/// <param name="reader"></param>
/// <param name="writer"></param>
/// <param name="config"></param>
public void Analyze(ref JT808MessagePackReader reader, Utf8JsonWriter writer, IJT808Config config)
{
JT808_0x8103_0x0050 jT808_0x8103_0x0050 = new JT808_0x8103_0x0050();
jT808_0x8103_0x0050.ParamId = reader.ReadUInt32();
jT808_0x8103_0x0050.ParamLength = reader.ReadByte();
jT808_0x8103_0x0050.ParamValue = reader.ReadUInt32();
writer.WriteNumber($"[{ jT808_0x8103_0x0050.ParamId.ReadNumber()}]参数ID", jT808_0x8103_0x0050.ParamId);
writer.WriteNumber($"[{jT808_0x8103_0x0050.ParamLength.ReadNumber()}]参数长度", jT808_0x8103_0x0050.ParamLength);
writer.WriteNumber($"[{ jT808_0x8103_0x0050.ParamValue.ReadNumber()}]参数值[报警屏蔽字,与位置信息汇报消息中的报警标志相对应]", jT808_0x8103_0x0050.ParamValue);
}
/// <summary>
///
/// </summary>
/// <param name="reader"></param>
/// <param name="config"></param>
/// <returns></returns>
public JT808_0x8103_0x0050 Deserialize(ref JT808MessagePackReader reader, IJT808Config config)
{
JT808_0x8103_0x0050 jT808_0x8103_0x0050 = new JT808_0x8103_0x0050();
jT808_0x8103_0x0050.ParamId = reader.ReadUInt32();
jT808_0x8103_0x0050.ParamLength = reader.ReadByte();
jT808_0x8103_0x0050.ParamValue = reader.ReadUInt32();
return jT808_0x8103_0x0050;
}
/// <summary>
///
/// </summary>
/// <param name="writer"></param>
/// <param name="value"></param>
/// <param name="config"></param>
public void Serialize(ref JT808MessagePackWriter writer, JT808_0x8103_0x0050 value, IJT808Config config)
{
writer.WriteUInt32(value.ParamId);
writer.WriteByte(value.ParamLength);
writer.WriteUInt32(value.ParamValue);
}
}
}
| 38.87013 | 145 | 0.612429 | [
"MIT"
] | jackyzcq/JT808 | src/JT808.Protocol/MessageBody/JT808_0x8103_0x0050.cs | 3,235 | C# |
using System;
namespace Semmle.Util
{
/// <summary>
/// An instance of this class is used to store the computed line count metrics (of
/// various different types) for a piece of text.
/// </summary>
public sealed class LineCounts
{
//#################### PROPERTIES ####################
#region
/// <summary>
/// The number of lines in the text that contain code.
/// </summary>
public int Code { get; set; }
/// <summary>
/// The number of lines in the text that contain comments.
/// </summary>
public int Comment { get; set; }
/// <summary>
/// The total number of lines in the text.
/// </summary>
public int Total { get; set; }
#endregion
//#################### PUBLIC METHODS ####################
#region
public override bool Equals(object? other)
{
return other is LineCounts rhs &&
Total == rhs.Total &&
Code == rhs.Code &&
Comment == rhs.Comment;
}
public override int GetHashCode()
{
return Total ^ Code ^ Comment;
}
public override string ToString()
{
return "Total: " + Total + " Code: " + Code + " Comment: " + Comment;
}
#endregion
}
/// <summary>
/// This class can be used to compute line count metrics of various different types
/// (code, comment and total) for a piece of text.
/// </summary>
public static class LineCounter
{
//#################### NESTED CLASSES ####################
#region
/// <summary>
/// An instance of this class keeps track of the contextual information required during line counting.
/// </summary>
private class Context
{
/// <summary>
/// The index of the current character under consideration.
/// </summary>
public int CurIndex { get; set; }
/// <summary>
/// Whether or not the current line under consideration contains any code.
/// </summary>
public bool HasCode { get; set; }
/// <summary>
/// Whether or not the current line under consideration contains a comment.
/// </summary>
public bool HasComment { get; set; }
}
#endregion
//#################### PUBLIC METHODS ####################
#region
/// <summary>
/// Computes line count metrics for the specified input text.
/// </summary>
/// <param name="input">The input text for which to compute line count metrics.</param>
/// <returns>The computed metrics.</returns>
public static LineCounts ComputeLineCounts(string input)
{
var counts = new LineCounts();
var context = new Context();
char? cur, prev = null;
while ((cur = GetNext(input, context)) is not null)
{
if (IsNewLine(cur))
{
RegisterNewLine(counts, context);
cur = null;
}
else if (cur == '*' && prev == '/')
{
ReadMultiLineComment(input, counts, context);
cur = null;
}
else if (cur == '/' && prev == '/')
{
ReadEOLComment(input, context);
context.HasComment = true;
cur = null;
}
else if (cur == '"')
{
ReadRestOfString(input, context);
context.HasCode = true;
cur = null;
}
else if (cur == '\'')
{
ReadRestOfChar(input, context);
context.HasCode = true;
cur = null;
}
else if (!IsWhitespace(cur) && cur != '/') // exclude '/' to avoid counting comments as code
{
context.HasCode = true;
}
prev = cur;
}
// The final line of text should always be counted, even if it's empty.
RegisterNewLine(counts, context);
return counts;
}
#endregion
//#################### PRIVATE METHODS ####################
#region
/// <summary>
/// Gets the next character to be considered from the input text and updates the current character index accordingly.
/// </summary>
/// <param name="input">The input text for which we are computing line count metrics.</param>
/// <param name="context">The contextual information required during line counting.</param>
/// <returns></returns>
private static char? GetNext(string input, Context context)
{
return input is null || context.CurIndex >= input.Length ?
(char?)null :
input[context.CurIndex++];
}
/// <summary>
/// Determines whether or not the specified character equals '\n'.
/// </summary>
/// <param name="c">The character to test.</param>
/// <returns>true, if the specified character equals '\n', or false otherwise.</returns>
private static bool IsNewLine(char? c)
{
return c == '\n';
}
/// <summary>
/// Determines whether or not the specified character should be considered to be whitespace.
/// </summary>
/// <param name="c">The character to test.</param>
/// <returns>true, if the specified character should be considered to be whitespace, or false otherwise.</returns>
private static bool IsWhitespace(char? c)
{
return c == ' ' || c == '\t' || c == '\r';
}
/// <summary>
/// Consumes the input text up to the end of the current line (not including any '\n').
/// This is used to consume an end-of-line comment (i.e. a //-style comment).
/// </summary>
/// <param name="input">The input text.</param>
/// <param name="context">The contextual information required during line counting.</param>
private static void ReadEOLComment(string input, Context context)
{
char? c;
do
{
c = GetNext(input, context);
} while (c is not null && !IsNewLine(c));
// If we reached the end of a line (as opposed to reaching the end of the text),
// put the '\n' back so that it can be handled by the normal newline processing
// code.
if (IsNewLine(c))
--context.CurIndex;
}
/// <summary>
/// Consumes the input text up to the end of a multi-line comment.
/// </summary>
/// <param name="input">The input text.</param>
/// <param name="counts">The line count metrics for the input text.</param>
/// <param name="context">The contextual information required during line counting.</param>
private static void ReadMultiLineComment(string input, LineCounts counts, Context context)
{
char? cur = '\0', prev = null;
context.HasComment = true;
while (cur is not null && ((cur = GetNext(input, context)) != '/' || prev != '*'))
{
if (IsNewLine(cur))
{
RegisterNewLine(counts, context);
context.HasComment = true;
}
prev = cur;
}
}
/// <summary>
/// Consumes the input text up to the end of a character literal, e.g. '\t'.
/// </summary>
/// <param name="input">The input text.</param>
/// <param name="context">The contextual information required during line counting.</param>
private static void ReadRestOfChar(string input, Context context)
{
if (GetNext(input, context) == '\\')
{
GetNext(input, context);
}
GetNext(input, context);
}
/// <summary>
/// Consumes the input text up to the end of a string literal, e.g. "Wibble".
/// </summary>
/// <param name="input">The input text.</param>
/// <param name="context">The contextual information required during line counting.</param>
private static void ReadRestOfString(string input, Context context)
{
char? cur = '\0';
var numSlashes = 0;
while (cur is not null && ((cur = GetNext(input, context)) != '"' || (numSlashes % 2 != 0)))
{
if (cur == '\\')
++numSlashes;
else
numSlashes = 0;
}
}
/// <summary>
/// Updates the line count metrics when a newline character is seen, and resets
/// the code and comment flags in the context ready to process the next line.
/// </summary>
/// <param name="counts">The line count metrics for the input text.</param>
/// <param name="context">The contextual information required during line counting.</param>
private static void RegisterNewLine(LineCounts counts, Context context)
{
++counts.Total;
if (context.HasCode)
{
++counts.Code;
context.HasCode = false;
}
if (context.HasComment)
{
++counts.Comment;
context.HasComment = false;
}
}
#endregion
}
}
| 35.085106 | 125 | 0.492622 | [
"MIT"
] | 00mjk/codeql | csharp/extractor/Semmle.Util/LineCounter.cs | 9,894 | C# |
// ------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
// ------------------------------------------------------------------------------
#nullable enable
#pragma warning disable CS1591
#pragma warning disable CS0108
#pragma warning disable 618
using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.ComponentModel.DataAnnotations;
using System.Globalization;
using System.Linq;
using System.Runtime.Serialization;
using System.Text.Json.Serialization;
using System.Threading;
using System.Threading.Tasks;
using JetBrains.Space.Common;
using JetBrains.Space.Common.Json.Serialization;
using JetBrains.Space.Common.Json.Serialization.Polymorphism;
using JetBrains.Space.Common.Types;
namespace JetBrains.Space.Client.M2ExternalStatusSucceedItemContentPartialBuilder
{
public static class M2ExternalStatusSucceedItemContentPartialExtensions
{
public static Partial<M2ExternalStatusSucceedItemContent> WithProjectId(this Partial<M2ExternalStatusSucceedItemContent> it)
=> it.AddFieldName("projectId");
public static Partial<M2ExternalStatusSucceedItemContent> WithRepository(this Partial<M2ExternalStatusSucceedItemContent> it)
=> it.AddFieldName("repository");
public static Partial<M2ExternalStatusSucceedItemContent> WithBranch(this Partial<M2ExternalStatusSucceedItemContent> it)
=> it.AddFieldName("branch");
public static Partial<M2ExternalStatusSucceedItemContent> WithRevisionInfo(this Partial<M2ExternalStatusSucceedItemContent> it)
=> it.AddFieldName("revisionInfo");
public static Partial<M2ExternalStatusSucceedItemContent> WithRevisionInfo(this Partial<M2ExternalStatusSucceedItemContent> it, Func<Partial<RevisionAuthorInfo>, Partial<RevisionAuthorInfo>> partialBuilder)
=> it.AddFieldName("revisionInfo", partialBuilder(new Partial<RevisionAuthorInfo>(it)));
public static Partial<M2ExternalStatusSucceedItemContent> WithChangesInfo(this Partial<M2ExternalStatusSucceedItemContent> it)
=> it.AddFieldName("changesInfo");
public static Partial<M2ExternalStatusSucceedItemContent> WithChangesInfo(this Partial<M2ExternalStatusSucceedItemContent> it, Func<Partial<LastChanges>, Partial<LastChanges>> partialBuilder)
=> it.AddFieldName("changesInfo", partialBuilder(new Partial<LastChanges>(it)));
public static Partial<M2ExternalStatusSucceedItemContent> WithUrl(this Partial<M2ExternalStatusSucceedItemContent> it)
=> it.AddFieldName("url");
public static Partial<M2ExternalStatusSucceedItemContent> WithExternalServiceName(this Partial<M2ExternalStatusSucceedItemContent> it)
=> it.AddFieldName("externalServiceName");
public static Partial<M2ExternalStatusSucceedItemContent> WithTaskName(this Partial<M2ExternalStatusSucceedItemContent> it)
=> it.AddFieldName("taskName");
public static Partial<M2ExternalStatusSucceedItemContent> WithTimestamp(this Partial<M2ExternalStatusSucceedItemContent> it)
=> it.AddFieldName("timestamp");
public static Partial<M2ExternalStatusSucceedItemContent> WithDescription(this Partial<M2ExternalStatusSucceedItemContent> it)
=> it.AddFieldName("description");
}
}
| 49.931507 | 214 | 0.723182 | [
"Apache-2.0"
] | PatrickRatzow/space-dotnet-sdk | src/JetBrains.Space.Client/Generated/Partials/M2ExternalStatusSucceedItemContentPartialBuilder.generated.cs | 3,645 | C# |
using Newtonsoft.Json;
using System.Collections.Generic;
using TMDb.Client.Entities.Things;
namespace TMDb.Client.Api.V3.Models
{
public class TranslationsResponse : TMDbResponse
{
[JsonProperty("id")]
public virtual int? Id { get; set; }
[JsonProperty("translations")]
public virtual IEnumerable<Translation> Translations { get; set; }
}
} | 25.8 | 74 | 0.684755 | [
"MIT"
] | joshuajones02/TMDb | TMDb.Client/API/V3/Models/TranslationsResponse.cs | 389 | C# |
using System;
using TMDB.Core.Attributes;
using TMDB.Core.Contracts;
namespace TMDB.Core.Api.V3.Models.GuestSessionRated
{
public abstract class GuestSessionRatedRequest : TMDbRequest, IGuestSession
{
[ApiParameter(
Name = "guest_session_id",
ParameterType = ParameterType.Path,
Option = SerializationOption.NoHyphen)]
public virtual Guid? GuestSessionId { get; set; }
/// <include file='tmdb-api-comments.xml' path='doc/members/member[@name="LanguageAbbreviation"]/*' />
[ApiParameter(
Name = "language",
ParameterType = ParameterType.Query)]
public virtual string LanguageAbbreviation { get; set; }
[ApiParameter(
Name = "sort_by",
ParameterType = ParameterType.Query)]
public virtual GuestSessionRatingSortyBy SortBy { get; set; }
}
} | 34.346154 | 110 | 0.646137 | [
"MIT"
] | JeremiSharkboy/TMDb.Client | TMDB.Core/API/V3/Models/GuestSessionRated/GuestSessionRatedRequest.cs | 895 | 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: MethodRequest.cs.tt
namespace Microsoft.Graph
{
using System;
using System.Collections.Generic;
using System.IO;
using System.Net.Http;
using System.Threading;
/// <summary>
/// The type EducationSynchronizationProfileResetRequest.
/// </summary>
public partial class EducationSynchronizationProfileResetRequest : BaseRequest, IEducationSynchronizationProfileResetRequest
{
/// <summary>
/// Constructs a new EducationSynchronizationProfileResetRequest.
/// </summary>
public EducationSynchronizationProfileResetRequest(
string requestUrl,
IBaseClient client,
IEnumerable<Option> options)
: base(requestUrl, client, options)
{
}
/// <summary>
/// Issues the POST request.
/// </summary>
public System.Threading.Tasks.Task PostAsync()
{
return this.PostAsync(CancellationToken.None);
}
/// <summary>
/// Issues the POST request.
/// </summary>
/// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param>
/// <returns>The task to await for async call.</returns>
public System.Threading.Tasks.Task PostAsync(
CancellationToken cancellationToken)
{
this.Method = "POST";
return this.SendAsync(null, cancellationToken);
}
/// <summary>
/// Adds the specified expand value to the request.
/// </summary>
/// <param name="value">The expand value.</param>
/// <returns>The request object to send.</returns>
public IEducationSynchronizationProfileResetRequest Expand(string value)
{
this.QueryOptions.Add(new QueryOption("$expand", value));
return this;
}
/// <summary>
/// Adds the specified select value to the request.
/// </summary>
/// <param name="value">The select value.</param>
/// <returns>The request object to send.</returns>
public IEducationSynchronizationProfileResetRequest Select(string value)
{
this.QueryOptions.Add(new QueryOption("$select", value));
return this;
}
}
}
| 34.3375 | 153 | 0.580269 | [
"MIT"
] | GeertVL/msgraph-beta-sdk-dotnet | src/Microsoft.Graph/Generated/requests/EducationSynchronizationProfileResetRequest.cs | 2,747 | C# |
using System;
using System.ComponentModel;
using System.Globalization;
using System.Windows.Data;
namespace WpfHelpers.WpfDataManipulation.XamlConverters
{
///http://www.codeproject.com/Articles/92944/A-Universal-Value-Converter-for-WPF
/// <summary>
/// Converts values by inner wpf Converter
/// <example>Color -> SolidColorBrush</example>
/// </summary>
public class UniversalValueConverter : IValueConverter
{
public object Convert(object value, Type targetType,
object parameter, CultureInfo culture)
{
// obtain the converter for the target type
TypeConverter converter = TypeDescriptor.GetConverter(targetType);
try
{
// determine if the supplied value is of a suitable type
if (converter.CanConvertFrom(value.GetType()))
{
// return the converted value
return converter.ConvertFrom(value);
}
else
{
// try to convert from the string representation
return converter.ConvertFrom(value.ToString());
}
}
catch (Exception)
{
return value;
}
}
public object ConvertBack
(object value, Type targetType, object parameter, CultureInfo culture)
{
throw new NotImplementedException();
}
}
} | 31.416667 | 84 | 0.566313 | [
"MIT"
] | Jambe/SMT | External/WpfHelpers/WpfDataManipulation/XamlConverters/UniversalValueConverter.cs | 1,510 | C# |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.