content
stringlengths
5
1.04M
avg_line_length
float64
1.75
12.9k
max_line_length
int64
2
244k
alphanum_fraction
float64
0
0.98
licenses
list
repository_name
stringlengths
7
92
path
stringlengths
3
249
size
int64
5
1.04M
lang
stringclasses
2 values
using System; using System.Collections.Generic; using System.Text; namespace Futura.Engine.ECS { public abstract class EcsSystem { public uint ExecutionOrder { get; private set; } = 100; protected EcsWorld World { get; private set; } = null; internal void Setup(EcsWorld world, uint execOrder) { this.World = world; this.ExecutionOrder = execOrder; OnSetup(); } public virtual void OnSetup() { } public virtual void OnInit() { } /// <summary> /// DeltaTime in seconds /// </summary> /// <param name="deltaTime"></param> public virtual void OnTick(float deltaTime) { } /// <summary> /// DeltaTime in seconds /// </summary> /// <param name="deltaTime"></param> public virtual void OnEditorTick(float deltaTime) { } } }
25.914286
63
0.566703
[ "MIT" ]
Lama96103/Futura
Source/Futura.Engine/ECS/EcsSystem.cs
909
C#
//----------------------------------------------// // Gamelogic Grids // // http://www.gamelogic.co.za // // Copyright (c) 2013 Gamelogic (Pty) Ltd // //----------------------------------------------// using System; namespace Gamelogic.Grids { /** Represents a rectangular grid. @copyright Gamelogic. @author Herman Tulleken @since 1.0 @ingroup Grids */ [Serializable] public partial class RectGrid<TCell> : AbstractUniformGrid<TCell, RectPoint> { #region Properties public int Width { get { return width; } } public int Height { get { return height; } } #endregion #region Neighbors public RectGrid<TCell> SetNeighborsMain() { neighborDirections = new PointList<RectPoint> { RectPoint.East, RectPoint.North, RectPoint.West, RectPoint.South }; return this; } public RectGrid<TCell> SetNeighborsDiagonals() { neighborDirections = new PointList<RectPoint> { RectPoint.NorthEast, RectPoint.NorthWest, RectPoint.SouthWest, RectPoint.SouthEast }; return this; } public RectGrid<TCell> SetNeighborsMainAndDiagonals() { neighborDirections = new PointList<RectPoint> { RectPoint.East, RectPoint.NorthEast, RectPoint.North, RectPoint.NorthWest, RectPoint.West, RectPoint.SouthWest, RectPoint.South, RectPoint.SouthEast }; return this; } protected override void InitNeighbors() { SetNeighborsMain(); } #endregion #region Storage public static ArrayPoint ArrayPointFromGridPoint(RectPoint point) { return new ArrayPoint(point.X, point.Y); } public static RectPoint GridPointFromArrayPoint(ArrayPoint point) { return new RectPoint(point.X, point.Y); } //TODO do we still need these? override protected ArrayPoint ArrayPointFromPoint(RectPoint point) { return ArrayPointFromGridPoint(point); } override protected ArrayPoint ArrayPointFromPoint(int x, int y) { return new ArrayPoint(x, y); } override protected RectPoint PointFromArrayPoint(int x, int y) { return new RectPoint(x, y); } #endregion } }
19.341667
69
0.602757
[ "Apache-2.0" ]
jvlppm/ggj-2017-abaiara
Assets/3rdParty/GamelogicGrids/Plugins/Gamelogic/Grids/GridTypes/Rect/RectGrid.cs
2,321
C#
// /************************************************************ // * // * Copyright (c) 2010 Dave Dolan. All Rights Reserved // * // * Author: Dave Dolan // * // ************************************************************/ using System; using bsn.GoldParser.Semantic; namespace SimpleREPL.Simple3{ public class WhileStatement : Statement{ private readonly Expression _test; private readonly Sequence<Statement> _trueStatements; [Rule(@"<Statement> ::= ~while <Expression> ~do <Statements> ~end")] public WhileStatement(Expression test, Sequence<Statement> trueStatements){ _test = test; _trueStatements = trueStatements; } public override void Execute(Simple3ExecutionContext ctx){ while (Convert.ToBoolean(_test.GetValue(ctx))){ foreach (Statement stmt in _trueStatements){ stmt.Execute(ctx); } } } } }
33.666667
84
0.508911
[ "Apache-2.0" ]
dolan/simple3-interpreter
bsn.Simple3/Simple2REPL/Simple3/WhileStatement.cs
1,012
C#
using System.ComponentModel; namespace Mkh.Mod.Admin.Core.Domain.Menu { /// <summary> /// 菜单类型 /// </summary> public enum MenuType { /// <summary> /// 未知 /// </summary> [Description("未知")] UnKnown = -1, /// <summary> /// 节点 /// </summary> [Description("节点")] Node, /// <summary> /// 路由菜单 /// </summary> [Description("路由")] Route, /// <summary> /// 链接菜单 /// </summary> [Description("链接")] Link, /// <summary> /// 自定义脚本 /// </summary> [Description("自定义脚本")] CustomJs } }
18.783784
40
0.401439
[ "MIT" ]
HmmmWoo/Mkh
modules/00_Admin/Admin.Core/Domain/Menu/MenuType.cs
765
C#
// *** WARNING: this file was generated by the Pulumi SDK Generator. *** // *** Do not edit by hand unless you're certain you know what you are doing! *** using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Threading.Tasks; using Pulumi.Serialization; namespace Pulumi.AzureNative.EnterpriseKnowledgeGraph.Outputs { [OutputType] public sealed class SkuResponse { /// <summary> /// The sku name /// </summary> public readonly string Name; [OutputConstructor] private SkuResponse(string name) { Name = name; } } }
23.321429
81
0.644717
[ "Apache-2.0" ]
pulumi-bot/pulumi-azure-native
sdk/dotnet/EnterpriseKnowledgeGraph/Outputs/SkuResponse.cs
653
C#
using System; using essentialMix.Patterns.Object; namespace essentialMix.Threading.Other.JonSkeet.MiscUtil; /// <summary> /// Type of buffer returned by BufferManager. /// </summary> public class Buffer : Disposable, IBuffer { private readonly bool _clearOnDispose; private bool _available; internal Buffer(int size, bool clearOnDispose) { Bytes = new byte[size]; _clearOnDispose = clearOnDispose; } internal bool Available { get => _available; set => _available = value; } public byte[] Bytes { get; } protected override void Dispose(bool disposing) { if (disposing) { if (_clearOnDispose) Array.Clear(Bytes, 0, Bytes.Length); _available = true; } base.Dispose(disposing); } }
19.378378
60
0.718271
[ "MIT" ]
asm2025/essentialMix
Standard/essentialMix.Threading/Other/JonSkeet/MiscUtil/Buffer.cs
717
C#
// CodeContracts // // Copyright (c) Microsoft Corporation // // All rights reserved. // // MIT License // // Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // File System.Windows.Media.Media3D.Converters.Vector3DValueSerializer.cs // Automatically generated contract file. using System.Collections.Generic; using System.IO; using System.Text; using System.Diagnostics.Contracts; using System; // Disable the "this variable is not used" warning as every field would imply it. #pragma warning disable 0414 // Disable the "this variable is never assigned to". #pragma warning disable 0067 // Disable the "this event is never assigned to". #pragma warning disable 0649 // Disable the "this variable is never used". #pragma warning disable 0169 // Disable the "new keyword not required" warning. #pragma warning disable 0109 // Disable the "extern without DllImport" warning. #pragma warning disable 0626 // Disable the "could hide other member" warning, can happen on certain properties. #pragma warning disable 0108 namespace System.Windows.Media.Media3D.Converters { public partial class Vector3DValueSerializer : System.Windows.Markup.ValueSerializer { #region Methods and constructors public override bool CanConvertFromString(string value, System.Windows.Markup.IValueSerializerContext context) { return default(bool); } public override bool CanConvertToString(Object value, System.Windows.Markup.IValueSerializerContext context) { return default(bool); } public override Object ConvertFromString(string value, System.Windows.Markup.IValueSerializerContext context) { return default(Object); } public override string ConvertToString(Object value, System.Windows.Markup.IValueSerializerContext context) { return default(string); } public Vector3DValueSerializer() { } #endregion } }
41.185714
463
0.768644
[ "MIT" ]
Acidburn0zzz/CodeContracts
Microsoft.Research/Contracts/PresentationCore/Sources/System.Windows.Media.Media3D.Converters.Vector3DValueSerializer.cs
2,883
C#
namespace UnityToolBox.Utils { using UnityEngine; public static class PooledGameObjectExtension { public static void ReturnToPool(this GameObject gameObject) { PooledObject pooledObject = gameObject.GetComponent<PooledObject>(); if (pooledObject == null) { Debug.LogErrorFormat("Cannot return this object to the pool because it was not created using the pool"); } pooledObject.Owner.ReturnObject(gameObject); } } }
28.052632
120
0.628518
[ "MIT" ]
davidejones88/unity-common-utils
Assets/unitytoolbox-utils/ObjectPool/Utils/PooledGameObjectExtension.cs
533
C#
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace VSTSCore.Models { public class Team { public Guid id; public string name; public string url; public string description; public string identityUrl; } }
19.294118
35
0.631098
[ "MIT" ]
rbnswartz/VSTSCore
Models/Team.cs
330
C#
using PieShop.Core.Models; using System; using System.Collections.Generic; namespace PieShop.Data.Repository.Intefaces { public interface IShoppingCartRepository { List<ShoppingCartItem> ShoppingCartItems { get; set; } void AddToCart(Pie pie, int amount); int RemoveFromCart(Pie pie); List<ShoppingCartItem> GetShoppingCartItems(); void ClearCart(); decimal GetShoppingCartTotal(); } }
22.55
62
0.694013
[ "MIT" ]
ikenb/ShopCollections
src/PieShop/PieShopApplication/Data/PieShop.Data/Repository/Interfaces/IShoppingCart.cs
453
C#
/* Copyright 2010-2014 MongoDB Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ using MongoDB.Bson; using MongoDB.Driver.Builders; using NUnit.Framework; namespace MongoDB.Driver.Tests.Jira.CSharp93 { [TestFixture] public class CSharp93Tests { [Test] public void TestDropAllIndexes() { var server = LegacyTestConfiguration.Server; var database = LegacyTestConfiguration.Database; var collection = LegacyTestConfiguration.Collection; if (collection.Exists()) { collection.DropAllIndexes(); } else { collection.Insert(new BsonDocument()); // make sure collection exists } collection.CreateIndex("x", "y"); collection.DropIndex("x", "y"); collection.CreateIndex(IndexKeys.Ascending("x", "y")); collection.DropIndex(IndexKeys.Ascending("x", "y")); } [Test] public void CreateIndex_SetUniqueTrue_Success() { var server = LegacyTestConfiguration.Server; var database = LegacyTestConfiguration.Database; var collection = LegacyTestConfiguration.Collection; if (collection.Exists()) { collection.DropAllIndexes(); } else { collection.Insert(new BsonDocument()); // make sure collection exists } collection.CreateIndex(IndexKeys.Ascending("x"), IndexOptions.SetUnique(true)); collection.CreateIndex(IndexKeys.Ascending("y"), IndexOptions.SetUnique(false)); } } }
32.279412
92
0.622323
[ "Apache-2.0" ]
mfloryan/mongo-csharp-driver
src/MongoDB.Driver.Legacy.Tests/Jira/CSharp93Tests.cs
2,197
C#
// This Source Code Form is subject to the terms of the Mozilla Public // License, v. 2.0. If a copy of the MPL was not distributed with this // file, You can obtain one at http://mozilla.org/MPL/2.0/. namespace ServiceStack.IntroSpec.Enrichers.Interfaces { /// <summary> /// Marker interface showing that class provides some kind of enriching functionality /// </summary> public interface IEnrich { } }
38.272727
89
0.714964
[ "MPL-2.0" ]
wwwlicious/servicestack-introspec
src/ServiceStack.IntroSpec/ServiceStack.IntroSpec/Enrichers/Interfaces/IEnrich.cs
421
C#
using System; using System.Collections.Generic; using System.Data; using System.Configuration; using System.Linq; using System.Web; using System.Web.Security; using System.Web.UI; using System.Web.UI.HtmlControls; using System.Web.UI.WebControls; using System.Web.UI.WebControls.WebParts; using System.Xml.Linq; public class Pos_ProductTransactionMasterManager { public Pos_ProductTransactionMasterManager() { } public static List<Pos_ProductTransactionMaster> GetAllPos_ProductTransactionMasters() { List<Pos_ProductTransactionMaster> pos_ProductTransactionMasters = new List<Pos_ProductTransactionMaster>(); SqlPos_ProductTransactionMasterProvider sqlPos_ProductTransactionMasterProvider = new SqlPos_ProductTransactionMasterProvider(); pos_ProductTransactionMasters = sqlPos_ProductTransactionMasterProvider.GetAllPos_ProductTransactionMasters(); return pos_ProductTransactionMasters; } public static Pos_ProductTransactionMaster GetPos_ProductTransactionMasterByID(int id) { Pos_ProductTransactionMaster pos_ProductTransactionMaster = new Pos_ProductTransactionMaster(); SqlPos_ProductTransactionMasterProvider sqlPos_ProductTransactionMasterProvider = new SqlPos_ProductTransactionMasterProvider(); pos_ProductTransactionMaster = sqlPos_ProductTransactionMasterProvider.GetPos_ProductTransactionMasterByID(id); return pos_ProductTransactionMaster; } public static int InsertPos_ProductTransactionMaster(Pos_ProductTransactionMaster pos_ProductTransactionMaster) { SqlPos_ProductTransactionMasterProvider sqlPos_ProductTransactionMasterProvider = new SqlPos_ProductTransactionMasterProvider(); return sqlPos_ProductTransactionMasterProvider.InsertPos_ProductTransactionMaster(pos_ProductTransactionMaster); } public static bool UpdatePos_ProductTransactionMaster(Pos_ProductTransactionMaster pos_ProductTransactionMaster) { SqlPos_ProductTransactionMasterProvider sqlPos_ProductTransactionMasterProvider = new SqlPos_ProductTransactionMasterProvider(); return sqlPos_ProductTransactionMasterProvider.UpdatePos_ProductTransactionMaster(pos_ProductTransactionMaster); } public static bool DeletePos_ProductTransactionMaster(int pos_ProductTransactionMasterID) { SqlPos_ProductTransactionMasterProvider sqlPos_ProductTransactionMasterProvider = new SqlPos_ProductTransactionMasterProvider(); return sqlPos_ProductTransactionMasterProvider.DeletePos_ProductTransactionMaster(pos_ProductTransactionMasterID); } }
45.54386
136
0.838213
[ "MPL-2.0", "MPL-2.0-no-copyleft-exception" ]
anam/abs
V1/App_Code/BLL/Manager/Pos_ProductTransactionMasterManager.cs
2,596
C#
namespace Sharpen { using System; using System.Text.RegularExpressions; public class Matcher { private int current; private MatchCollection matches; private Regex regex; private string str; public Matcher (Regex regex, string str) { this.regex = regex; this.str = str; } public int End () { if ((matches == null) || (current >= matches.Count)) { throw new InvalidOperationException (); } return (matches[current].Index + matches[current].Length); } public bool Find () { if (matches == null) { matches = regex.Matches (str); current = 0; } return (current < matches.Count); } public bool Find (int index) { matches = regex.Matches (str, index); current = 0; return (matches.Count > 0); } public string Group (int n) { if ((matches == null) || (current >= matches.Count)) { throw new InvalidOperationException (); } Group grp = matches[current].Groups[n]; return grp.Success ? grp.Value : null; } public bool Matches () { matches = null; return Find (); } public string ReplaceFirst (string txt) { return regex.Replace (str, txt, 1); } public Matcher Reset (CharSequence str) { return Reset (str.ToString ()); } public Matcher Reset (string str) { matches = null; this.str = str; return this; } public int Start () { if ((matches == null) || (current >= matches.Count)) { throw new InvalidOperationException (); } return matches[current].Index; } } }
18.238095
61
0.619452
[ "BSD-3-Clause" ]
renaud91/n-metadata-extractor
Sharpen/Sharpen/Matcher.cs
1,532
C#
using System; using System.Collections; using UnityEngine; namespace Scripts.Level.Dialogue { [RequireComponent(typeof(DialogueIndicator))] public class DialogueTalkerDirect : DialogueTalker { public bool FacePlayer = false; protected DialogueIndicator Indicator; private Quaternion InitialRotation; private const float RotationSpeed = 1.0f; void Start() { InitialRotation = transform.rotation; Indicator = GetComponent<DialogueIndicator>(); } public override void OnStartTalk() { Indicator.HideIndicator(); if (FacePlayer) { RotateFacePlayer(); } } public override void OnEndTalk() { Indicator.ShowIndicator(); if (FacePlayer) { RotateFaceBack(); } } public override void OnPlayerAway() { Indicator.HideIndicator(); } public override void OnSelected() { Indicator.ShowIndicator(); } public override void OnDeselected() { Indicator.HideIndicator(); } protected void RotateFacePlayer() { StopAllCoroutines(); Vector3 playerPosition = LevelManager.GetPlayerManager().Player.transform.position; Quaternion toPlayerRotation = Quaternion.LookRotation(playerPosition - transform.position); StartCoroutine(DoRotateTowards(toPlayerRotation)); } protected void RotateFaceBack() { StopAllCoroutines(); StartCoroutine(DoRotateTowards(InitialRotation)); } private IEnumerator DoRotateTowards(Quaternion rotation) { rotation.x = 0.0f; rotation.z = 0.0f; while (transform.rotation != rotation) { transform.rotation = Quaternion.Slerp(transform.rotation, rotation, RotationSpeed * Time.deltaTime); yield return new WaitForFixedUpdate(); } } } }
24.862069
116
0.565881
[ "MIT" ]
Freezer-Games/Frozen-Out
FrozenOut/Assets/Scripts/Level/Dialogue/Acter/Talker/DialogueTalkerDirect.cs
2,163
C#
using System; using System.Collections.Generic; using System.Data; using System.Data.SqlClient; using System.Linq; using JetBrains.Annotations; using Reusable.Extensions; using Reusable.IOnymous; namespace Reusable.Utilities.SqlClient.SqlSchemas { // Based on // https://docs.microsoft.com/en-us/dotnet/framework/data/adonet/sql-server-schema-collections [PublicAPI] public static class SqlSchemaReader { private static readonly string GetIdentityColumnSchemasQuery; static SqlSchemaReader() { var fileProvider = new EmbeddedFileProvider(typeof(SqlSchemaReader).Assembly); GetIdentityColumnSchemasQuery = fileProvider.ReadTextFile($"sql\\{nameof(GetIdentityColumnSchemas)}.sql"); } public static IList<SqlTableSchema> GetTableSchemas(this SqlConnection sqlConnection, SqlTableSchema schemaRestriction) { if (sqlConnection == null) throw new ArgumentNullException(nameof(sqlConnection)); if (schemaRestriction == null) throw new ArgumentNullException(nameof(schemaRestriction)); using (var schema = sqlConnection.GetSchema(SqlSchemaCollection.Tables, schemaRestriction)) { return schema .AsEnumerable() .Select(SqlSchemaFactory.Create<SqlTableSchema>) .ToList(); } } /// <summary> /// Gets column schemas ordered by their ordinal-position. /// </summary> public static IList<SqlColumnSchema> GetColumnSchemas(this SqlConnection sqlConnection, SqlColumnSchema schemaRestriction) { if (sqlConnection == null) throw new ArgumentNullException(nameof(sqlConnection)); if (schemaRestriction == null) throw new ArgumentNullException(nameof(schemaRestriction)); using (var schema = sqlConnection.GetSchema(SqlSchemaCollection.Columns, schemaRestriction)) { return schema .AsEnumerable() .Select(SqlSchemaFactory.Create<SqlColumnSchema>) .OrderBy(x => x.OrdinalPosition) .ToList(); } } public static IList<SqlIdentityColumnSchema> GetIdentityColumnSchemas(this SqlConnection connection, string schema, string table) { using (var cmd = connection.CreateCommand()) { cmd.CommandText = GetIdentityColumnSchemasQuery; cmd.Parameters.AddWithValue("@schema", schema); cmd.Parameters.AddWithValue("@table", table); using (var reader = cmd.ExecuteReader()) { var identityColumns = new DataTable("IdentityColumns"); identityColumns.Load(reader); return identityColumns .AsEnumerable() .Select(SqlSchemaFactory.Create<SqlIdentityColumnSchema>) .ToList(); } } } [NotNull] public static IList<(SoftString Name, Type Type)> GetColumnFrameworkTypes(this SqlConnection connection, [NotNull] string schema, [NotNull] string table) { if (schema == null) throw new ArgumentNullException(nameof(schema)); if (table == null) throw new ArgumentNullException(nameof(table)); return connection.GetColumnSchemas(new SqlColumnSchema { TableSchema = schema, TableName = table }) .Select((column, ordinal) => (column.ColumnName.ToSoftString(), column.FrameworkType)) .ToList(); } } }
40.020833
161
0.597345
[ "MIT" ]
he-dev/DotNetBits
Reusable.Utilities.SqlClient/src/SqlSchemas/SqlSchemaReader.cs
3,842
C#
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.IO; using System.Linq; using System.Net; using System.Net.Sockets; using System.Text; using System.Threading; using System.Threading.Tasks; using System.Windows.Forms; namespace _06Server { public partial class Form1 : Form { public Form1() { InitializeComponent(); } /// <summary> /// 开始监听 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void btnStart_Click(object sender, EventArgs e) { try { //当点击开始监听的时候 在服务器端创建一个负责监IP地址跟端口号的Socket Socket socketWatch = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); IPAddress ip = IPAddress.Any; //创建端口号对象 IPEndPoint point = new IPEndPoint(ip, Convert.ToInt32(txtPort.Text)); //监听 socketWatch.Bind(point); ShowMsg("监听成功"); socketWatch.Listen(10);//挂起队列 Thread th = new Thread(Listen); th.IsBackground = true; th.Start(socketWatch); } catch { } } Socket socketSend; /// <summary> /// 等待客户端的连接 并且创建与之通信的Socket /// </summary> void Listen(object o) { Socket socketWatch = o as Socket; while (true) { try { //等待客户端的连接 并且创建一个负责通信的Socket socketSend = socketWatch.Accept(); //将远程连接的客户端IP地址和Socket存入集合中 dicSocket.Add(socketSend.RemoteEndPoint.ToString(), socketSend); //将远程连接的客户端IP地址和端口号存入下拉框 cboUsers.Items.Add(socketSend.RemoteEndPoint.ToString()); //192.168.11.87:连接成功 ShowMsg(socketSend.RemoteEndPoint.ToString() + ":" + "连接成功"); //开启一个新线程 不停地接受客户端发来的消息 Thread th = new Thread(Recive); th.IsBackground = true; th.Start(socketSend); } catch { } } } //将远程连接的客户端IP地址和Socket存入集合中 Dictionary<string, Socket> dicSocket = new Dictionary<string, Socket>(); /// <summary> /// 服务器端不停地接受客户端发送的消息 /// </summary> /// <param name="o"></param> void Recive(object o) { Socket socketSend = o as Socket; while (true) { try { //客户端连接成功后 服务器应该接受客户端发来的消息 byte[] buffer = new byte[1024 * 1024 * 5]; //实际接收到的有效字节数 int r = socketSend.Receive(buffer); if (r == 0) { break; } string str = Encoding.UTF8.GetString(buffer, 0, r); ShowMsg(socketSend.RemoteEndPoint + ":" + str); } catch { } } } void ShowMsg(string str) { txtLog.AppendText(str + "\t\n"); } private void Form1_Load(object sender, EventArgs e) { Control.CheckForIllegalCrossThreadCalls = false; } /// <summary> /// 服务器给客户端发送消息 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void btnSend_Click(object sender, EventArgs e) { try { string str = txtMsg.Text; byte[] buffer = Encoding.UTF8.GetBytes(str); List<byte> list = new List<byte>(); list.Add(0); list.AddRange(buffer); //将泛型集合转换为数组 byte[] newBuffer = list.ToArray(); //获得用户在下拉框中选中的IP地址 string ip = cboUsers.SelectedItem.ToString(); dicSocket[ip].Send(newBuffer); //socketSend.Send(buffer); } catch { } } /// <summary> /// 选择要发送的文件 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void btnSelect_Click(object sender, EventArgs e) { try { OpenFileDialog ofd = new OpenFileDialog(); ofd.Title = "请选择要发送的文件"; ofd.InitialDirectory = @"C:\Users\PC\Desktop"; ofd.Multiselect = true; ofd.Filter = "所有文件|*.*"; ofd.ShowDialog(); txtPath.Text = ofd.FileName; } catch { } } private void btnSendFile_Click(object sender, EventArgs e) { try { //获得要发送文件的路径 string path = txtPath.Text; using (FileStream fsRead = new FileStream(path, FileMode.OpenOrCreate, FileAccess.Read)) { byte[] buffer = new byte[1024 * 1024 * 5]; List<byte> list = new List<byte>(); list.Add(1); list.AddRange(buffer); byte[] newBuffer = list.ToArray(); int r = fsRead.Read(newBuffer, 0, newBuffer.Length);//这是个问题 dicSocket[cboUsers.SelectedIndex.ToString()].Send(newBuffer, 0, r, SocketFlags.None); } } catch { } } /// <summary> /// 发送震动 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void btnZD_Click(object sender, EventArgs e) { byte[] buffer = new byte[1]; buffer[0] = 2; dicSocket[cboUsers.SelectedIndex.ToString()].Send(buffer); } } }
32.688172
113
0.465132
[ "MIT" ]
yemingxingkong/ymxk
code/CSharp/old/Projects/4.21socket/06Server/Form1.cs
6,670
C#
global using Dapr; global using Dapr.Client; global using Microsoft.AspNetCore.Mvc; global using Serilog; global using Shared.Events; global using System.ComponentModel.DataAnnotations; global using UserService.Models;
31.142857
51
0.844037
[ "MIT" ]
fawohlsc/dapr-microservices
src/UserService/GlobalUsings.cs
218
C#
#region LICENSE //==============================================================================// // Copyright (c) 2014 Daniel Castaño Estrella // // This projected is licensed under the terms of the MIT license. // // See accompanying file LICENSE or copy at http://opensource.org/licenses/MIT // //==============================================================================// #endregion using UnityEngine; using System.Collections; public class xButtons : MonoBehaviour { #region Variables #region Scripts public xLogic my_logic; public xAudio my_audio; #endregion #region Twitter private const string TWITTER_ADDRESS = "http://twitter.com/intent/tweet"; private const string TWEET_LANGUAGE = "en"; public string APP_NAME = "YOUR_APP_NAME"; public string URL = "http://bit.ly/SHORT_CODE"; //I recommend to use a short url, bit.ly or whatever #endregion #region Market //change by yours, set it on Edit/Project Settings/Player > Other Settings > Bundle Identifier public string BUNDLE_ID = "com.Company_name.App_name"; #endregion #region buttons public GameObject button_mute; public GameObject button_unmute; #endregion #endregion void Awake() { //Show the correct Audio Button. if(xPlayerPrefs.GetBool("audio",true)) { button_unmute.SetActive(true); button_mute.SetActive(false); } } public void mute(bool is_muted) { my_audio.Mute (is_muted); } public void Rate() { Application.OpenURL("market://details?id=" + BUNDLE_ID); } public void Twitter_share() { string textToDisplay = string.Format("I've got {0} points on #{1}! Get it on the Google Play! {2}",(int)my_logic.score, APP_NAME, URL); Application.OpenURL(TWITTER_ADDRESS + "?text=" + WWW.EscapeURL(textToDisplay) + "&amp;lang=" + WWW.EscapeURL(TWEET_LANGUAGE)); } public void Home() { Application.LoadLevel(1); } public void Restart() { my_logic.Restart(); } public void Pause() { my_logic.Pause(); } public void Play() { my_logic.Play (); } }
23.340909
137
0.639727
[ "MIT" ]
danielcestrella/x-unity-android-framework
Assets/Scripts/xButtons.cs
2,055
C#
using System.Linq; using Content.Client.HUD.UI; using Content.Client.Inventory; using Content.Client.Preferences; using Content.Shared.CharacterAppearance.Systems; using Content.Shared.GameTicking; using Content.Shared.Inventory; using Content.Shared.Preferences; using Content.Shared.Roles; using Content.Shared.Species; using Robust.Client.GameObjects; using Robust.Client.UserInterface; using Robust.Client.UserInterface.Controls; using Robust.Shared.GameObjects; using Robust.Shared.IoC; using Robust.Shared.Localization; using Robust.Shared.Map; using Robust.Shared.Maths; using Robust.Shared.Prototypes; using static Robust.Client.UserInterface.Controls.BoxContainer; namespace Content.Client.Lobby.UI { public sealed class LobbyCharacterPreviewPanel : Control { private readonly IEntityManager _entMan; private readonly IClientPreferencesManager _preferencesManager; private readonly IPrototypeManager _prototypeManager; private EntityUid? _previewDummy; private readonly Label _summaryLabel; private readonly BoxContainer _loaded; private readonly BoxContainer _viewBox; private readonly Label _unloaded; public LobbyCharacterPreviewPanel(IEntityManager entityManager, IClientPreferencesManager preferencesManager, IPrototypeManager prototypeManager) { _entMan = entityManager; _preferencesManager = preferencesManager; _prototypeManager = prototypeManager; var header = new NanoHeading { Text = Loc.GetString("lobby-character-preview-panel-header") }; CharacterSetupButton = new Button { Text = Loc.GetString("lobby-character-preview-panel-character-setup-button"), HorizontalAlignment = HAlignment.Left }; _summaryLabel = new Label(); var vBox = new BoxContainer { Orientation = LayoutOrientation.Vertical }; vBox.AddChild(header); _unloaded = new Label { Text = Loc.GetString("lobby-character-preview-panel-unloaded-preferences-label") }; _loaded = new BoxContainer { Orientation = LayoutOrientation.Vertical, Visible = false }; _loaded.AddChild(CharacterSetupButton); _loaded.AddChild(_summaryLabel); _viewBox = new BoxContainer { Orientation = LayoutOrientation.Horizontal }; _loaded.AddChild(_viewBox); vBox.AddChild(_loaded); vBox.AddChild(_unloaded); AddChild(vBox); UpdateUI(); _preferencesManager.OnServerDataLoaded += UpdateUI; } public Button CharacterSetupButton { get; } protected override void Dispose(bool disposing) { base.Dispose(disposing); _preferencesManager.OnServerDataLoaded -= UpdateUI; if (!disposing) return; if (_previewDummy != null) _entMan.DeleteEntity(_previewDummy.Value); _previewDummy = default; } private SpriteView MakeSpriteView(EntityUid entity, Direction direction) { return new() { Sprite = _entMan.GetComponent<ISpriteComponent>(entity), OverrideDirection = direction, Scale = (2, 2) }; } public void UpdateUI() { if (!_preferencesManager.ServerDataLoaded) { _loaded.Visible = false; _unloaded.Visible = true; } else { _loaded.Visible = true; _unloaded.Visible = false; if (_preferencesManager.Preferences?.SelectedCharacter is not HumanoidCharacterProfile selectedCharacter) { _summaryLabel.Text = string.Empty; } else { _previewDummy = _entMan.SpawnEntity(_prototypeManager.Index<SpeciesPrototype>(selectedCharacter.Species).DollPrototype, MapCoordinates.Nullspace); var viewSouth = MakeSpriteView(_previewDummy.Value, Direction.South); var viewNorth = MakeSpriteView(_previewDummy.Value, Direction.North); var viewWest = MakeSpriteView(_previewDummy.Value, Direction.West); var viewEast = MakeSpriteView(_previewDummy.Value, Direction.East); _viewBox.DisposeAllChildren(); _viewBox.AddChild(viewSouth); _viewBox.AddChild(viewNorth); _viewBox.AddChild(viewWest); _viewBox.AddChild(viewEast); _summaryLabel.Text = selectedCharacter.Summary; EntitySystem.Get<SharedHumanoidAppearanceSystem>().UpdateFromProfile(_previewDummy.Value, selectedCharacter); GiveDummyJobClothes(_previewDummy.Value, selectedCharacter); } } } public static void GiveDummyJobClothes(EntityUid dummy, HumanoidCharacterProfile profile) { var protoMan = IoCManager.Resolve<IPrototypeManager>(); var entMan = IoCManager.Resolve<IEntityManager>(); var invSystem = EntitySystem.Get<ClientInventorySystem>(); var highPriorityJob = profile.JobPriorities.FirstOrDefault(p => p.Value == JobPriority.High).Key; // ReSharper disable once ConstantNullCoalescingCondition var job = protoMan.Index<JobPrototype>(highPriorityJob ?? SharedGameTicker.FallbackOverflowJob); if (job.StartingGear != null && invSystem.TryGetSlots(dummy, out var slots)) { var gear = protoMan.Index<StartingGearPrototype>(job.StartingGear); foreach (var slot in slots) { var itemType = gear.GetGear(slot.Name, profile); if (invSystem.TryUnequip(dummy, slot.Name, out var unequippedItem, true, true)) { entMan.DeleteEntity(unequippedItem.Value); } if (itemType != string.Empty) { var item = entMan.SpawnEntity(itemType, MapCoordinates.Nullspace); invSystem.TryEquip(dummy, item, slot.Name, true, true); } } } } } }
37.173184
166
0.602344
[ "MIT" ]
Carou02/space-station-14
Content.Client/Lobby/UI/LobbyCharacterPreviewPanel.cs
6,654
C#
using System.Linq; public enum Classification { Perfect, Abundant, Deficient } public static class PerfectNumbers { public static Classification Classify(int number) { var divisors = GetDivisors(number); var sumOfDivisors = divisors.Sum(); if (sumOfDivisors == number) { return Classification.Perfect; } if (sumOfDivisors > number) { return Classification.Abundant; } return Classification.Deficient; } static int[] GetDivisors(int number) => Enumerable.Range(1, number - 1).Where(n => number % n == 0).ToArray(); }
24.346154
81
0.617694
[ "MIT" ]
Sankra/ExercismSolutions
csharp/perfect-numbers/PerfectNumbers.cs
635
C#
using Microsoft.Extensions.Options; using OrchardCore.ResourceManagement; namespace OrchardCore.Spatial { public class ResourceManagementOptionsConfiguration : IConfigureOptions<ResourceManagementOptions> { private static ResourceManifest _manifest; static ResourceManagementOptionsConfiguration() { _manifest = new ResourceManifest(); _manifest .DefineScript("leaflet") .SetUrl("/OrchardCore.Spatial/Scripts/leaflet/leaflet.js", "/OrchardCore.Spatial/Scripts/leaflet/leaflet-src.js") .SetCdn("https://cdnjs.cloudflare.com/ajax/libs/leaflet/1.7.1/leaflet.min.js", "https://cdnjs.cloudflare.com/ajax/libs/leaflet/1.7.1/leaflet-src.js") .SetCdnIntegrity("sha384-vdvDM6Rl/coCrMsKwhal4uc9MUUFNrYa+cxp+nJQHy3TvozEpVKVexz/NTbE5VSO", "sha384-mc6rNK5V0bzWGJ1EUEAR2o+a/oH6qaVl+NCF63Et+mVpGnlSnyVSBhSP/wp4ir+O") .SetVersion("1.7.1"); _manifest .DefineStyle("leaflet") .SetUrl("/OrchardCore.Spatial/Styles/leaflet.min.css", "/OrchardCore.Spatial/Styles/leaflet.css") .SetCdn("https://cdnjs.cloudflare.com/ajax/libs/leaflet/1.7.1/leaflet.min.css", "https://cdnjs.cloudflare.com/ajax/libs/leaflet/1.7.1/leaflet.css") .SetCdnIntegrity("sha384-d7pQbIswLsqVbYoAoHHlzPt+fmjkMwiXW/fvtIgK2r1u1bZXvGzL9HICUg4DKSgO", "sha384-VzLXTJGPSyTLX6d96AxgkKvE/LRb7ECGyTxuwtpjHnVWVZs2gp5RDjeM/tgBnVdM") .SetVersion("1.7.1"); } public void Configure(ResourceManagementOptions options) { options.ResourceManifests.Add(_manifest); } } }
48.085714
182
0.682115
[ "BSD-3-Clause" ]
1051324354/OrchardCore
src/OrchardCore.Modules/OrchardCore.Spatial/ResourceManifestOptionsConfiguration.cs
1,683
C#
using System; using System.Collections.Generic; namespace _08.MatrixPassChecker { internal class Labyrinth { private const char UNPASSABLE = '0'; private bool pathFound = false; private char[,] matrix; private int[,] dir = new int[,] { { 1, 0 }, { 0, 1 }, { -1, 0 }, { 0, -1 } }; List<char> directions = new List<char>(); private char[] charDir = new[] { 'D', 'R', 'U', 'L' }; public Labyrinth(char[,] matrix) { this.matrix = matrix; } public void FindPaths(int row, int col, char direction) { if (pathFound) { return; } if (!InRange(row, col)) { return; } if (matrix[row, col] == '*') { return; } if (matrix[row, col] == 'e') { directions.Add(direction); PrintMatrix(); PrintPath(); pathFound = true; directions.RemoveAt(this.directions.Count - 1); return; } directions.Add(direction); MarkCurrent(row, col, direction); for (int i = 0; i < dir.GetLength(0); i++) { FindPaths(row + dir[i, 0], col + dir[i, 1], charDir[i]); } directions.RemoveAt(this.directions.Count - 1); } private void MarkCurrent(int row, int col, char direction) { this.matrix[row, col] = direction; } private void PrintPath() { Console.Write("Path: "); Console.WriteLine(string.Join(">", directions)); } private void PrintMatrix() { for (int row = 0; row < this.matrix.GetLength(0); row++) { for (int col = 0; col < this.matrix.GetLength(1); col++) { Console.Write("{0,3}", this.matrix[row, col]); } Console.WriteLine(); } } private bool InRange(int row, int col) { bool rowInRange = row >= 0 && row < matrix.GetLength(0); bool colInRange = col >= 0 && col < matrix.GetLength(1); return rowInRange && colInRange; } } }
27.136364
85
0.441374
[ "MIT" ]
Camyul/Modul_2_CSharp
DSA/03.Recursion/08.MatrixPassChecker/Labyrinth.cs
2,390
C#
using MasterDevs.ChromeDevTools; using Newtonsoft.Json; using System.Collections.Generic; namespace MasterDevs.ChromeDevTools.Protocol.Debugger { /// <summary> /// Stops on the next JavaScript statement. /// </summary> [CommandResponse(ProtocolName.Debugger.Pause)] public class PauseCommandResponse { } }
20.933333
53
0.77707
[ "MIT" ]
brewdente/AutoWebPerf
MasterDevs.ChromeDevTools/Protocol/Debugger/PauseCommandResponse.cs
314
C#
using System; namespace Thriot.Client.DotNet.Management { /// <summary> /// This exception will be thrown when the registration is performed on a Thriot installation where activation is needed after registration. /// When this exception is thrown the user was registered successfully by the <see cref="UserManagementClient.Register"/> method but cannot be logged in due to the activation requirement. /// PLease check your email and click the activation link. /// </summary> public class ActivationRequiredException : Exception { /// <summary> /// Initializes a new instance /// </summary> /// <param name="message">Message to be passed to the exception</param> public ActivationRequiredException(string message) : base(message) { } } }
38.181818
191
0.675
[ "MIT" ]
kpocza/thriot
Client/DotNet/Thriot.Client.DotNet/Management/ActivationRequiredException.cs
842
C#
// ----------------------------------------------------------------------- // <copyright file="GossipActor.cs" company="Asynkron AB"> // Copyright (C) 2015-2021 Asynkron AB All rights reserved // </copyright> // ----------------------------------------------------------------------- using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Linq; using System.Threading.Tasks; using Google.Protobuf; using Google.Protobuf.WellKnownTypes; using Microsoft.Extensions.Logging; using Proto.Logging; using Proto.Remote; namespace Proto.Cluster.Gossip { public class GossipActor : IActor { private readonly TimeSpan _gossipRequestTimeout; private static readonly ILogger Logger = Log.CreateLogger<GossipActor>(); private long _localSequenceNo; private GossipState _state = new(); private readonly Random _rnd = new(); private ImmutableDictionary<string, long> _committedOffsets = ImmutableDictionary<string, long>.Empty; private ImmutableHashSet<string> _activeMemberIds = ImmutableHashSet<string>.Empty; private Member[] _otherMembers = Array.Empty<Member>(); private readonly ConsensusChecks _consensusChecks = new(); // lookup from state key -> consensus checks public GossipActor(TimeSpan gossipRequestTimeout) => _gossipRequestTimeout = gossipRequestTimeout; public Task ReceiveAsync(IContext context) => context.Message switch { SetGossipStateKey setState => OnSetGossipStateKey(context, setState), GetGossipStateRequest getState => OnGetGossipStateKey(context, getState), GossipRequest gossipRequest => OnGossipRequest(context, gossipRequest), SendGossipStateRequest => OnSendGossipState(context), AddConsensusCheck request => OnAddConsensusCheck(context, request), RemoveConsensusCheck request => OnRemoveConsensusCheck(request), ClusterTopology clusterTopology => OnClusterTopology(context, clusterTopology), _ => Task.CompletedTask }; private Task OnClusterTopology(IContext context, ClusterTopology clusterTopology) { _otherMembers = clusterTopology.Members.Where(m => m.Id != context.System.Id).ToArray(); _activeMemberIds = clusterTopology.Members.Select(m => m.Id).ToImmutableHashSet(); SetState(context, "topology", clusterTopology); CheckConsensus(context, "topology"); return Task.CompletedTask; } private Task OnAddConsensusCheck(IContext context, AddConsensusCheck msg) { _consensusChecks.Add(msg.Check); // Check when adding, if we are already consistent msg.Check.Check(_state, _activeMemberIds, context); return Task.CompletedTask; } private Task OnRemoveConsensusCheck(RemoveConsensusCheck request) { _consensusChecks.Remove(request.Id); return Task.CompletedTask; } private Task OnGetGossipStateKey(IContext context, GetGossipStateRequest getState) { var entries = ImmutableDictionary<string, Any>.Empty; var key = getState.Key; foreach (var (memberId, memberState) in _state.Members) { if (memberState.Values.TryGetValue(key, out var value)) { entries = entries.SetItem(memberId, value.Value); } } var res = new GetGossipStateResponse(entries); context.Respond(res); return Task.CompletedTask; } private Task OnGossipRequest(IContext context, GossipRequest gossipRequest) { var logger = context.Logger()?.BeginScope<GossipActor>(); logger?.LogDebug("Gossip Request {Sender}", context.Sender!); Logger.LogDebug("Gossip Request {Sender}", context.Sender!); ReceiveState(context, gossipRequest.State); var senderMember = TryGetSenderMember(context); if (senderMember is null || !TryGetStateForMember(senderMember, out var pendingOffsets, out var stateForMember)) { // Nothing to send, do not provide sender or state payload context.Respond(new GossipResponse()); return Task.CompletedTask; } context.RequestReenter<GossipResponseAck>(context.Sender!, new GossipResponse { State = stateForMember }, task => ReenterAfterResponseAck(context, task, pendingOffsets), context.CancellationToken); return Task.CompletedTask; } private Member? TryGetSenderMember(IContext context) { var senderAddress = context.Sender?.Address; if (senderAddress is null) return default; return Array.Find(_otherMembers, member => member.Address.Equals(senderAddress, StringComparison.OrdinalIgnoreCase)); } private void ReceiveState(IContext context, GossipState remoteState) { var updates = GossipStateManagement.MergeState(_state, remoteState, out var newState, out var updatedKeys); if (updates.Count <= 0) return; foreach (var update in updates) { context.System.EventStream.Publish(update); } _state = newState; CheckConsensus(context, updatedKeys); } private void CheckConsensus(IContext context, string updatedKey) { foreach (var consensusCheck in _consensusChecks.GetByUpdatedKey(updatedKey)) { consensusCheck.Check(_state, _activeMemberIds, context); } } private void CheckConsensus(IContext context, IEnumerable<string> updatedKeys) { foreach (var consensusCheck in _consensusChecks.GetByUpdatedKeys(updatedKeys)) { consensusCheck.Check(_state, _activeMemberIds, context); } } private Task OnSetGossipStateKey(IContext context, SetGossipStateKey setStateKey) { var logger = context.Logger()?.BeginMethodScope(); var (key, message) = setStateKey; SetState(context, key, message); logger?.LogDebug("Setting state key {Key} - {Value} - {State}", key, message, _state); Logger.LogDebug("Setting state key {Key} - {Value} - {State}", key, message, _state); if (!_state.Members.ContainsKey(context.System.Id)) { logger?.LogCritical("State corrupt"); } CheckConsensus(context, setStateKey.Key); if (context.Sender is not null) { context.Respond(new SetGossipStateResponse()); } return Task.CompletedTask; } private long SetState(IContext context, string key, IMessage message) => _localSequenceNo = GossipStateManagement.SetKey(_state, key, message, context.System.Id, _localSequenceNo); private Task OnSendGossipState(IContext context) { var logger = context.Logger()?.BeginMethodScope(); PurgeBannedMembers(context); foreach (var member in _otherMembers) { GossipStateManagement.EnsureMemberStateExists(_state, member.Id); } var fanOutMembers = PickRandomFanOutMembers(_otherMembers, context.System.Cluster().Config.GossipFanout); foreach (var member in fanOutMembers) { //fire and forget, we handle results in ReenterAfter SendGossipForMember(context, member, logger); } // CheckConsensus(context); context.Respond(new SendGossipStateResponse()); return Task.CompletedTask; } private void PurgeBannedMembers(IContext context) { var banned = context.Remote().BlockList.BlockedMembers; foreach (var memberId in _state.Members.Keys.ToArray()) { if (banned.Contains(memberId)) { _state.Members.Remove(memberId); } } } private void SendGossipForMember(IContext context, Member member, InstanceLogger? logger) { var pid = PID.FromAddress(member.Address, Gossiper.GossipActorName); if (!TryGetStateForMember(member, out var pendingOffsets, out var stateForMember)) return; logger?.LogInformation("Sending GossipRequest to {MemberId}", member.Id); Logger.LogDebug("Sending GossipRequest to {MemberId}", member.Id); //a short timeout is massively important, we cannot afford hanging around waiting for timeout, blocking other gossips from getting through // This will return a GossipResponse, but since we need could need to get the sender, we do not unpack it from the MessageEnvelope var t = context.RequestAsync<MessageEnvelope>(pid, new GossipRequest { State = stateForMember, }, CancellationTokens.WithTimeout(_gossipRequestTimeout) ); context.ReenterAfter(t, task => GossipReenterAfterSend(context, task, pendingOffsets)); } private bool TryGetStateForMember(Member member, out ImmutableDictionary<string, long> pendingOffsets, out GossipState stateForMember) { (pendingOffsets, stateForMember) = GossipStateManagement.FilterGossipStateForMember(_state, _committedOffsets, member.Id); //if we dont have any state to send, don't send it... return pendingOffsets != _committedOffsets; } private async Task GossipReenterAfterSend(IContext context, Task<MessageEnvelope> task, ImmutableDictionary<string, long> pendingOffsets) { var logger = context.Logger(); try { await task; var envelope = task.Result; if (envelope.Message is GossipResponse response) { CommitPendingOffsets(pendingOffsets); if (response.State is not null) { ReceiveState(context, response.State!); if (envelope.Sender is not null) { context.Send(envelope.Sender, new GossipResponseAck()); } } } } catch (DeadLetterException) { logger?.LogWarning("DeadLetter"); } catch (OperationCanceledException) { logger?.LogWarning("Timeout"); } catch (TimeoutException) { logger?.LogWarning("Timeout"); } catch (Exception x) { logger?.LogError(x, "OnSendGossipState failed"); Logger.LogError(x, "OnSendGossipState failed"); } } private async Task ReenterAfterResponseAck(IContext context, Task<GossipResponseAck> task, ImmutableDictionary<string, long> pendingOffsets) { var logger = context.Logger(); try { await task; CommitPendingOffsets(pendingOffsets); } catch (DeadLetterException) { logger?.LogWarning("DeadLetter"); } catch (OperationCanceledException) { logger?.LogWarning("Timeout"); } catch (TimeoutException) { logger?.LogWarning("Timeout"); } catch (Exception x) { logger?.LogError(x, "OnSendGossipState failed"); Logger.LogError(x, "OnSendGossipState failed"); } } private void CommitPendingOffsets(ImmutableDictionary<string, long> pendingOffsets) { foreach (var (key, sequenceNumber) in pendingOffsets) { //TODO: this needs to be improved with filter state on sender side, and then Ack from here //update our state with the data from the remote node //GossipStateManagement.MergeState(_state, response.State, out var newState); //_state = newState; if (!_committedOffsets.ContainsKey(key) || _committedOffsets[key] < pendingOffsets[key]) { _committedOffsets = _committedOffsets.SetItem(key, sequenceNumber); } } } private List<Member> PickRandomFanOutMembers(Member[] members, int fanOutBy) => members .Select(m => (member: m, index: _rnd.Next())) .OrderBy(m => m.index) .Take(fanOutBy) .Select(m => m.member) .ToList(); } }
39.289941
150
0.587199
[ "Apache-2.0" ]
Damian-P/protoactor-dotnet
src/Proto.Cluster/Gossip/GossipActor.cs
13,280
C#
using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; using TMPro; using Photon.Pun; using Photon.Realtime; using ExitGames.Client.Photon; public class RoomPanel : BasePanel { [SerializeField] private TextMeshProUGUI _roomName = null; [SerializeField] private TextMeshProUGUI _playerCountText = null; [SerializeField] private ScrollRect _playerScroll = null; [SerializeField] private PlayerDisplayWidget _displayWidget; private Dictionary<string, PlayerDisplayWidget> _playerWidgets = new Dictionary<string, PlayerDisplayWidget>(); private string _roomId; private ChatManager _chatManger; private int _playerCount = 0; public void ExtOnBack() { PhotonNetwork.LeaveRoom(); ServiceManager.ViewManager.TransitToMainMenu(); } protected override void OnActivate() { Debug.Log("Room Panel onActive!"); ServiceManager.ChatManager.OnChannelMessageReceived += OnChannelMessageReceived; } protected override void OnDeactivate() { ServiceManager.ChatManager.OnChannelMessageReceived -= OnChannelMessageReceived; } private void Start() { _chatManger = ServiceManager.ChatManager; } private void Update() { if(string.IsNullOrEmpty(_roomId) && PhotonNetwork.InRoom) { _roomId = PhotonNetwork.CurrentRoom.Name; _roomName.SetText(PhotonNetwork.CurrentRoom.CustomProperties[RoomManager.RoomNameKey] as string); _chatManger.Subscribe(_roomId); _chatManger.SendChannelMessage(_roomId, new ChatManager.PlayerInfoMessage() { PlayerName = ServiceManager.PlayerManager.LocalPlayerProfile.PlayerName }); PlayerDisplayWidget newWidget = Instantiate(_displayWidget, _playerScroll.content.transform); newWidget.Initialize(ServiceManager.PlayerManager.LocalPlayerProfile.PlayerName); _playerWidgets.Add(ServiceManager.PlayerManager.LocalPlayerProfile.Uid, newWidget); _playerCount++; _playerCountText.SetText($"{_playerCount}/{PhotonNetwork.CurrentRoom.MaxPlayers}"); } } private void OnChannelMessageReceived(string channelName, string[] senders, object[] messages) { if(channelName != _roomId) return; foreach(string sender in senders) { if(sender == ServiceManager.PlayerManager.LocalPlayerProfile.Uid) continue; ChatManager.PlayerInfoMessage playerInfo = ChatManager.GetLatestMessage<ChatManager.PlayerInfoMessage>(sender, senders, messages); if(playerInfo != null && !_playerWidgets.ContainsKey(sender)) { // Create player item with info PlayerDisplayWidget newWidget = Instantiate(_displayWidget, _playerScroll.content.transform); newWidget.Initialize(playerInfo.PlayerName); _playerWidgets.Add(sender, newWidget); _playerCount++; _playerCountText.SetText($"{_playerCount}/{PhotonNetwork.CurrentRoom.MaxPlayers}"); } } } }
38.385542
142
0.682674
[ "MIT" ]
CheckShumm/QuoteMe
Assets/Assets/Scripts/ViewPanels/RoomPanel.cs
3,188
C#
// *** WARNING: this file was generated by the Pulumi SDK Generator. *** // *** Do not edit by hand unless you're certain you know what you are doing! *** using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Threading.Tasks; using Pulumi.Serialization; namespace Pulumi.AzureNative.RecoveryServices.V20210210.Outputs { /// <summary> /// A resource identity that is managed by the user of the service. /// </summary> [OutputType] public sealed class UserIdentityResponse { /// <summary> /// The client ID of the user-assigned identity. /// </summary> public readonly string ClientId; /// <summary> /// The principal ID of the user-assigned identity. /// </summary> public readonly string PrincipalId; [OutputConstructor] private UserIdentityResponse( string clientId, string principalId) { ClientId = clientId; PrincipalId = principalId; } } }
27.282051
81
0.629699
[ "Apache-2.0" ]
polivbr/pulumi-azure-native
sdk/dotnet/RecoveryServices/V20210210/Outputs/UserIdentityResponse.cs
1,064
C#
using System.Web.Mvc; namespace FluentSecurity.SampleApplication.Controllers { public class ExampleController : Controller { public ActionResult MissingConfiguration() { return View(); } public ActionResult DenyAnonymousAccess() { return View(); } public ActionResult DenyAuthenticatedAccess() { return View(); } public ActionResult RequireAdministratorRole() { return View(); } public ActionResult RequirePublisherRole() { return View(); } } }
17.96875
54
0.612174
[ "MIT" ]
DiogenesPolanco/FluentSecurity
SampleApplication/FluentSecurity.SampleApplication/Controllers/ExampleController.cs
575
C#
using System.Collections; using System.Collections.Generic; using Stranne.BooliLib.Models; namespace Stranne.BooliLib.Tests.Models { public class SoldRoot { public IEnumerable<SoldObject> Sold { get; set; } } }
19.416667
57
0.72103
[ "MIT" ]
stranne/BooliLib
Stranne.BooliLib.Tests/Models/SoldRoot.cs
235
C#
using System; using System.Linq; using FubuCore.Logging; using FubuCore.Reflection; using FubuMVC.Core.ServiceBus; using FubuMVC.Core.ServiceBus.Configuration; using FubuMVC.Core.ServiceBus.Logging; using FubuMVC.Core.ServiceBus.Runtime; using FubuMVC.Core.ServiceBus.Runtime.Headers; using FubuMVC.Core.ServiceBus.Runtime.Routing; using FubuMVC.Core.ServiceBus.Runtime.Serializers; using FubuMVC.Core.ServiceBus.Scheduling; using NUnit.Framework; using Rhino.Mocks; using Shouldly; using TestMessages; using Is = Rhino.Mocks.Constraints.Is; namespace FubuMVC.Tests.ServiceBus.Configuration { [TestFixture] public class ChannelNodeTester { [Test] public void no_publishing_rules_is_always_false() { var node = new ChannelNode(); node.Publishes(typeof(NewUser)).ShouldBeFalse(); } [Test] public void publishes_is_true_if_any_rule_passes() { var node = new ChannelNode(); for (int i = 0; i < 5; i++) { node.Rules.Add(MockRepository.GenerateMock<IRoutingRule>()); } node.Rules[2].Stub(x => x.Matches(typeof (NewUser))).Return(true); node.Publishes(typeof(NewUser)).ShouldBeTrue(); } [Test] public void publishes_is_false_if_no_rules_pass() { var node = new ChannelNode(); for (int i = 0; i < 5; i++) { node.Rules.Add(MockRepository.GenerateMock<IRoutingRule>()); } node.Publishes(typeof(NewUser)).ShouldBeFalse(); } [Test] public void setting_address_has_to_be_a_Uri() { var node = new ChannelNode(); Exception<ArgumentOutOfRangeException>.ShouldBeThrownBy(() => { node.SettingAddress = ReflectionHelper.GetAccessor<FakeThing>(x => x.Name); }); } [Test] public void setting_default_content_type_will_clear_the_serializer() { var node = new ChannelNode(); node.DefaultSerializer = new BinarySerializer(); node.DefaultContentType = "application/xml"; node.DefaultContentType.ShouldBe("application/xml"); node.DefaultSerializer.ShouldBeNull(); } [Test] public void setting_the_default_serializer_will_clear_the_default_content_type() { var node = new ChannelNode { DefaultContentType = "application/xml" }; node.DefaultSerializer = new BinarySerializer(); node.DefaultSerializer.ShouldBeOfType<BinarySerializer>(); node.DefaultContentType.ShouldBeNull(); } public void start_receiving() { if (DateTime.Today > new DateTime(2013, 11, 21)) { Assert.Fail("Jeremy needs to fix the structure so that this is possible"); } // var invoker = MockRepository.GenerateMock<IHandlerPipeline>(); // // var node = new ChannelNode // { // Incoming = true, // Channel = MockRepository.GenerateMock<IChannel>(), // Scheduler = new FakeScheduler() // }; // // var graph = new ChannelGraph(); // // var startingVisitor = new StartingChannelNodeVisitor(new Receiver(invoker, graph, node)); // startingVisitor.Visit(node); // // // // node.Channel.AssertWasCalled(x => x.Receive(new Receiver(invoker, graph, node))); } [Test] public void ReceiveFailed_error_handling() { var node = new ChannelNode { Key = "TestKey", Channel = new FakeChannel { StopAfter = 2 }, Scheduler = new FakeScheduler() }; var logger = new RecordingLogger(); node.StartReceiving(new RecordingReceiver(), logger); logger.ErrorMessages.ShouldHaveCount(1); logger.InfoMessages.ShouldHaveCount(1); var message = logger.InfoMessages.Cast<ReceiveFailed>().Single(); message.ChannelKey.ShouldBe(node.Key); message.Exception.ShouldNotBeNull(); } [Test] public void continuous_receive_errors() { var logger = new RecordingLogger(); var receiver = new RecordingReceiver(); var channel = MockRepository.GenerateMock<IChannel>(); channel.Expect(x => x.Receive(receiver)) .Throw(new Exception("I failed")); var node = new ChannelNode { Channel = channel, Scheduler = new FakeScheduler() }; Exception<ReceiveFailureException>.ShouldBeThrownBy(() => { node.StartReceiving(receiver, logger); }); } [Test] public void doesnt_throw_if_receive_only_fails_intermittently() { var channel = new FakeChannel { StopAfter = 20 }; var node = new ChannelNode { Channel = channel, Scheduler = new FakeScheduler() }; var logger = new RecordingLogger(); var receiver = new RecordingReceiver(); node.StartReceiving(receiver, logger); channel.HitCount.ShouldBe(20); } public class FakeChannel : IChannel { public int HitCount { get; private set; } public int StopAfter { get; set; } public ReceivingState Receive(IReceiver receiver) { if (++HitCount >= StopAfter) return ReceivingState.StopReceiving; // Throw every other time if (HitCount % 2 == 1) throw new Exception("I failed"); return ReceivingState.CanContinueReceiving; } public Uri Address { get; private set; } public void Send(byte[] data, IHeaders headers) { } public void Dispose() { } } } public class FakeScheduler : IScheduler { public void Dispose() { } public void Start(Action action) { action(); } } [TestFixture] public class when_sending_an_envelope { private Envelope theEnvelope; private RecordingChannel theChannel; private ChannelNode theNode; private IEnvelopeSerializer theSerializer; [SetUp] public void SetUp() { theEnvelope = new Envelope() { Data = new byte[]{1,2,3,4}, }; theSerializer = MockRepository.GenerateMock<IEnvelopeSerializer>(); theEnvelope.Headers["A"] = "1"; theEnvelope.Headers["B"] = "2"; theEnvelope.Headers["C"] = "3"; theEnvelope.CorrelationId = Guid.NewGuid().ToString(); theChannel = new RecordingChannel(); theNode = new ChannelNode { Channel = theChannel, Key = "Foo", Uri = "foo://bar".ToUri() }; theNode.Modifiers.Add(new HeaderSetter("D", "4")); theNode.Modifiers.Add(new HeaderSetter("E", "5")); theNode.Send(theEnvelope, theSerializer); } public class HeaderSetter : IEnvelopeModifier { private readonly string _key; private readonly string _value; public HeaderSetter(string key, string value) { _key = key; _value = value; } public void Modify(Envelope envelope) { envelope.Headers[_key] = _value; } } [Test] public void should_serialize_the_envelope() { theSerializer.AssertWasCalled(x => x.Serialize(null, theNode), x => { x.Constraints(Is.Matching<Envelope>(o => { o.CorrelationId.ShouldBe(theEnvelope.CorrelationId); o.ShouldNotBeTheSameAs(theEnvelope); return true; }), Is.Same(theNode)); }); } [Test] public void should_have_applied_the_channel_specific_modifiers() { var sentHeaders = theChannel.Sent.Single().Headers; sentHeaders["D"].ShouldBe("4"); sentHeaders["E"].ShouldBe("5"); } [Test] public void should_have_sent_a_copy_of_the_headers() { var sentHeaders = theChannel.Sent.Single().Headers; sentHeaders.ShouldNotBeTheSameAs(theEnvelope.Headers); sentHeaders["A"].ShouldBe("1"); sentHeaders["B"].ShouldBe("2"); sentHeaders["C"].ShouldBe("3"); } [Test] public void sends_the_channel_key() { var sentHeaders = theChannel.Sent.Single().Headers; sentHeaders[Envelope.ChannelKey].ShouldBe(theNode.Key); } [Test] public void sends_the_destination_as_a_header() { var sentHeaders = theChannel.Sent.Single().Headers; sentHeaders[Envelope.DestinationKey].ToUri().ShouldBe(theNode.Uri); } } public class FakeThing { public string Name { get; set; } } }
29.248485
103
0.54569
[ "Apache-2.0" ]
JohnnyKapps/fubumvc
src/FubuMVC.Tests/ServiceBus/Configuration/ChannelNodeTester.cs
9,654
C#
using System.Threading.Tasks; using Termigram.Bot; using Termigram.Commands; namespace Termigram.ResultProcessors { public abstract class ResultProcessorBase<TResult> : IResultProcessor<TResult> { public virtual async Task<bool> TryProcessResultAsync(IBot bot, ICommand command, TResult result) { try { await ProcessResultAsync(bot, command, result); return true; } catch { return false; } } protected virtual Task ProcessResultAsync(IBot bot, ICommand command, TResult result) => Task.CompletedTask; } }
26.88
116
0.604167
[ "MIT" ]
Kir-Antipov/Termigram
Termigram/ResultProcessors/ResultProcessorBase`1.cs
674
C#
using Codeizi.DI.Helper.Anotations; using Codeizi.Domain.Customers; using Codeizi.Infra.Data.Context; using System; namespace Codeizi.Infra.Data.DAO.Customers { [Injectable(typeof(ICustomerDAO), typeof(CustomerDAO))] public class CustomerDAO : GenericDAO<Customer, Guid>, ICustomerDAO { public CustomerDAO(CodeiziContext context) : base(context) { } } }
24.882353
71
0.669031
[ "MIT" ]
JDouglasMendes/codeizi-architecture
src/Codeizi.Infra.Data/DAO/Customers/CustomerDAO.cs
425
C#
/* * Copyright (c) Contributors, http://opensimulator.org/ * See CONTRIBUTORS.TXT for a full list of copyright holders. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the OpenSim Project nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ using System.IO; using System.Text; using System.Xml; using IOStream = System.IO.Stream; namespace OpenSim.Framework.Communications.XMPP { public class XMPPWriter: XmlTextWriter { public XMPPWriter(TextWriter textWriter) : base(textWriter) { } public XMPPWriter(IOStream stream) : this(stream, Encoding.UTF8) { } public XMPPWriter(IOStream stream, Encoding enc) : base(stream, enc) { } public override void WriteStartDocument() { } public override void WriteStartDocument(bool standalone) { } } }
38.741379
80
0.714731
[ "BSD-3-Clause" ]
WhiteCoreSim/WhiteCore-Merger
OpenSim/Framework/Communications/XMPP/XmppWriter.cs
2,247
C#
using Cirrious.CrossCore; using Cirrious.CrossCore.Plugins; namespace Cheesebaron.MvxPlugins.AppId { public class Plugin : IMvxPlugin { public void Load() { Mvx.RegisterSingleton<IAppIdGenerator>(new AppIdGenerator()); } } }
18.866667
73
0.632509
[ "Apache-2.0" ]
Ideine/Cheesebaron.MvxPlugins
AppId/Touch/Plugin.cs
285
C#
// Copyright (c) Imazen LLC. // No part of this project, including this file, may be copied, modified, // propagated, or distributed except as permitted in COPYRIGHT.txt. // Licensed under the GNU Affero General Public License, Version 3.0. // Commercial licenses available at http://imageresizing.net/ using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using ImageResizer.Util; // So the ImageResizer knows which edition or bundle this assembly belongs to [assembly: Edition("R4Creative")] // 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("ImageResizer.Plugins.AdvancedFilters")] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("5cfe2b47-083e-4684-ab10-b58e18ee8c1f")]
41.043478
84
0.787076
[ "MIT" ]
2sic/resizer
Plugins/AdvancedFilters/AssemblyInfo.cs
946
C#
// Copyright (c) .NET Foundation. All rights reserved. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using System.Linq; using System.Runtime.InteropServices; using BasicTestApp; using BasicTestApp.RouterTest; using Microsoft.AspNetCore.Components.E2ETest.Infrastructure; using Microsoft.AspNetCore.Components.E2ETest.Infrastructure.ServerFixtures; using Microsoft.AspNetCore.E2ETesting; using OpenQA.Selenium; using OpenQA.Selenium.Interactions; using Xunit; using Xunit.Abstractions; namespace Microsoft.AspNetCore.Components.E2ETest.Tests { public class RoutingTest : BasicTestAppTestBase { public RoutingTest( BrowserFixture browserFixture, ToggleExecutionModeServerFixture<Program> serverFixture, ITestOutputHelper output) : base(browserFixture, serverFixture, output) { } protected override void InitializeAsyncCore() { Navigate(ServerPathBase, noReload: false); WaitUntilTestSelectorReady(); } [Fact] public void CanArriveAtDefaultPage() { SetUrlViaPushState("/"); var app = MountTestComponent<TestRouter>(); Assert.Equal("This is the default page.", app.FindElement(By.Id("test-info")).Text); AssertHighlightedLinks("Default (matches all)", "Default with base-relative URL (matches all)"); } [Fact] public void CanArriveAtDefaultPageWithoutTrailingSlash() { // This is a bit of a degenerate case because ideally devs would configure their // servers to enforce a canonical URL (with trailing slash) for the homepage. // But in case they don't want to, we need to handle it the same as if the URL does // have a trailing slash. SetUrlViaPushState(""); var app = MountTestComponent<TestRouter>(); Assert.Equal("This is the default page.", app.FindElement(By.Id("test-info")).Text); AssertHighlightedLinks("Default (matches all)", "Default with base-relative URL (matches all)"); } [Fact] public void CanArriveAtPageWithParameters() { SetUrlViaPushState("/WithParameters/Name/Ghi/LastName/O'Jkl"); var app = MountTestComponent<TestRouter>(); Assert.Equal("Your full name is Ghi O'Jkl.", app.FindElement(By.Id("test-info")).Text); AssertHighlightedLinks(); } [Fact] public void CanArriveAtPageWithNumberParameters() { var testInt = int.MinValue; var testLong = long.MinValue; var testDec = -2.33333m; var testDouble = -1.489d; var testFloat = -2.666f; SetUrlViaPushState($"/WithNumberParameters/{testInt}/{testLong}/{testDouble}/{testFloat}/{testDec}"); var app = MountTestComponent<TestRouter>(); var expected = $"Test parameters: {testInt} {testLong} {testDouble} {testFloat} {testDec}"; Assert.Equal(expected, app.FindElement(By.Id("test-info")).Text); } [Fact] public void CanArriveAtNonDefaultPage() { SetUrlViaPushState("/Other"); var app = MountTestComponent<TestRouter>(); Assert.Equal("This is another page.", app.FindElement(By.Id("test-info")).Text); AssertHighlightedLinks("Other", "Other with base-relative URL (matches all)"); } [Fact] public void CanArriveAtFallbackPageFromBadURI() { SetUrlViaPushState("/Oopsie_Daisies%20%This_Aint_A_Real_Page"); var app = MountTestComponent<TestRouter>(); Assert.Equal("Oops, that component wasn't found!", app.FindElement(By.Id("test-info")).Text); } [Fact] public void CanFollowLinkToOtherPage() { SetUrlViaPushState("/"); var app = MountTestComponent<TestRouter>(); app.FindElement(By.LinkText("Other")).Click(); Browser.Equal("This is another page.", () => app.FindElement(By.Id("test-info")).Text); AssertHighlightedLinks("Other", "Other with base-relative URL (matches all)"); } [Fact] public void CanFollowLinkToOtherPageWithCtrlClick() { // On macOS we need to hold the command key not the control for opening a popup var key = RuntimeInformation.IsOSPlatform(OSPlatform.OSX) ? Keys.Command : Keys.Control; try { SetUrlViaPushState("/"); var app = MountTestComponent<TestRouter>(); var button = app.FindElement(By.LinkText("Other")); new Actions(Browser).KeyDown(key).Click(button).Build().Perform(); Browser.Equal(2, () => Browser.WindowHandles.Count); } finally { // Leaving the ctrl key up new Actions(Browser).KeyUp(key).Build().Perform(); // Closing newly opened windows if a new one was opened while (Browser.WindowHandles.Count > 1) { Browser.SwitchTo().Window(Browser.WindowHandles.Last()); Browser.Close(); } // Needed otherwise Selenium tries to direct subsequent commands // to the tab that has already been closed Browser.SwitchTo().Window(Browser.WindowHandles.First()); } } [Fact] public void CanFollowLinkToTargetBlankClick() { try { SetUrlViaPushState("/"); var app = MountTestComponent<TestRouter>(); app.FindElement(By.LinkText("Target (_blank)")).Click(); Browser.Equal(2, () => Browser.WindowHandles.Count); } finally { // Closing newly opened windows if a new one was opened while (Browser.WindowHandles.Count > 1) { Browser.SwitchTo().Window(Browser.WindowHandles.Last()); Browser.Close(); } // Needed otherwise Selenium tries to direct subsequent commands // to the tab that has already been closed Browser.SwitchTo().Window(Browser.WindowHandles.First()); } } [Fact] public void CanFollowLinkToOtherPageDoesNotOpenNewWindow() { SetUrlViaPushState("/"); var app = MountTestComponent<TestRouter>(); app.FindElement(By.LinkText("Other")).Click(); Assert.Single(Browser.WindowHandles); } [Fact] public void CanFollowLinkToOtherPageWithBaseRelativeUrl() { SetUrlViaPushState("/"); var app = MountTestComponent<TestRouter>(); app.FindElement(By.LinkText("Other with base-relative URL (matches all)")).Click(); Browser.Equal("This is another page.", () => app.FindElement(By.Id("test-info")).Text); AssertHighlightedLinks("Other", "Other with base-relative URL (matches all)"); } [Fact] public void CanFollowLinkToEmptyStringHrefAsBaseRelativeUrl() { SetUrlViaPushState("/Other"); var app = MountTestComponent<TestRouter>(); app.FindElement(By.LinkText("Default with base-relative URL (matches all)")).Click(); Browser.Equal("This is the default page.", () => app.FindElement(By.Id("test-info")).Text); AssertHighlightedLinks("Default (matches all)", "Default with base-relative URL (matches all)"); } [Fact] public void CanFollowLinkToPageWithParameters() { SetUrlViaPushState("/Other"); var app = MountTestComponent<TestRouter>(); app.FindElement(By.LinkText("With parameters")).Click(); Browser.Equal("Your full name is Abc .", () => app.FindElement(By.Id("test-info")).Text); AssertHighlightedLinks("With parameters"); // Can add more parameters while remaining on same page app.FindElement(By.LinkText("With more parameters")).Click(); Browser.Equal("Your full name is Abc McDef.", () => app.FindElement(By.Id("test-info")).Text); AssertHighlightedLinks("With parameters", "With more parameters"); // Can remove parameters while remaining on same page app.FindElement(By.LinkText("With parameters")).Click(); Browser.Equal("Your full name is Abc .", () => app.FindElement(By.Id("test-info")).Text); AssertHighlightedLinks("With parameters"); } [Fact] public void CanFollowLinkToDefaultPage() { SetUrlViaPushState("/Other"); var app = MountTestComponent<TestRouter>(); app.FindElement(By.LinkText("Default (matches all)")).Click(); Browser.Equal("This is the default page.", () => app.FindElement(By.Id("test-info")).Text); AssertHighlightedLinks("Default (matches all)", "Default with base-relative URL (matches all)"); } [Fact] public void CanFollowLinkToOtherPageWithQueryString() { SetUrlViaPushState("/"); var app = MountTestComponent<TestRouter>(); app.FindElement(By.LinkText("Other with query")).Click(); Browser.Equal("This is another page.", () => app.FindElement(By.Id("test-info")).Text); AssertHighlightedLinks("Other", "Other with query"); } [Fact] public void CanFollowLinkToDefaultPageWithQueryString() { SetUrlViaPushState("/Other"); var app = MountTestComponent<TestRouter>(); app.FindElement(By.LinkText("Default with query")).Click(); Browser.Equal("This is the default page.", () => app.FindElement(By.Id("test-info")).Text); AssertHighlightedLinks("Default with query"); } [Fact] public void CanFollowLinkToOtherPageWithHash() { SetUrlViaPushState("/"); var app = MountTestComponent<TestRouter>(); app.FindElement(By.LinkText("Other with hash")).Click(); Browser.Equal("This is another page.", () => app.FindElement(By.Id("test-info")).Text); AssertHighlightedLinks("Other", "Other with hash"); } [Fact] public void CanFollowLinkToDefaultPageWithHash() { SetUrlViaPushState("/Other"); var app = MountTestComponent<TestRouter>(); app.FindElement(By.LinkText("Default with hash")).Click(); Browser.Equal("This is the default page.", () => app.FindElement(By.Id("test-info")).Text); AssertHighlightedLinks("Default with hash"); } [Fact] public void CanFollowLinkToNotAComponent() { SetUrlViaPushState("/"); var app = MountTestComponent<TestRouter>(); app.FindElement(By.LinkText("Not a component")).Click(); Browser.Equal("Not a component!", () => Browser.FindElement(By.Id("test-info")).Text); } [Fact] public void CanGoBackFromNotAComponent() { SetUrlViaPushState("/"); // First go to some URL on the router var app = MountTestComponent<TestRouter>(); app.FindElement(By.LinkText("Other")).Click(); Browser.True(() => Browser.Url.EndsWith("/Other")); // Now follow a link out of the SPA entirely app.FindElement(By.LinkText("Not a component")).Click(); Browser.Equal("Not a component!", () => Browser.FindElement(By.Id("test-info")).Text); Browser.True(() => Browser.Url.EndsWith("/NotAComponent.html")); // Now click back // Because of how the tests are structured with the router not appearing until the router // tests are selected, we can only observe the test selector being there, but this is enough // to show we did go back to the right place and the Blazor app started up Browser.Navigate().Back(); Browser.True(() => Browser.Url.EndsWith("/Other")); WaitUntilTestSelectorReady(); } [Fact] public void CanNavigateProgrammatically() { SetUrlViaPushState("/"); var app = MountTestComponent<TestRouter>(); var testSelector = WaitUntilTestSelectorReady(); app.FindElement(By.Id("do-navigation")).Click(); Browser.True(() => Browser.Url.EndsWith("/Other")); Browser.Equal("This is another page.", () => app.FindElement(By.Id("test-info")).Text); AssertHighlightedLinks("Other", "Other with base-relative URL (matches all)"); // Because this was client-side navigation, we didn't lose the state in the test selector Assert.Equal(typeof(TestRouter).FullName, testSelector.SelectedOption.GetAttribute("value")); } [Fact] public void CanNavigateProgrammaticallyWithForceLoad() { SetUrlViaPushState("/"); var app = MountTestComponent<TestRouter>(); var testSelector = WaitUntilTestSelectorReady(); app.FindElement(By.Id("do-navigation-forced")).Click(); Browser.True(() => Browser.Url.EndsWith("/Other")); // Because this was a full-page load, our element references should no longer be valid Assert.Throws<StaleElementReferenceException>(() => { testSelector.SelectedOption.GetAttribute("value"); }); } [Fact] public void ClickingAnchorWithNoHrefShouldNotNavigate() { SetUrlViaPushState("/"); var initialUrl = Browser.Url; var app = MountTestComponent<TestRouter>(); app.FindElement(By.Id("anchor-with-no-href")).Click(); Assert.Equal(initialUrl, Browser.Url); AssertHighlightedLinks("Default (matches all)", "Default with base-relative URL (matches all)"); } [Fact] public void UsingNavigationManagerWithoutRouterWorks() { var app = MountTestComponent<NavigationManagerComponent>(); var initialUrl = Browser.Url; Browser.Equal(Browser.Url, () => app.FindElement(By.Id("test-info")).Text); var uri = SetUrlViaPushState("/mytestpath"); Browser.Equal(uri, () => app.FindElement(By.Id("test-info")).Text); var jsExecutor = (IJavaScriptExecutor)Browser; jsExecutor.ExecuteScript("history.back()"); Browser.Equal(initialUrl, () => app.FindElement(By.Id("test-info")).Text); } [Fact] public void UriHelperCanReadAbsoluteUriIncludingHash() { var app = MountTestComponent<NavigationManagerComponent>(); Browser.Equal(Browser.Url, () => app.FindElement(By.Id("test-info")).Text); var uri = "/mytestpath?my=query&another#some/hash?tokens"; var expectedAbsoluteUri = $"{_serverFixture.RootUri}subdir{uri}"; SetUrlViaPushState(uri); Browser.Equal(expectedAbsoluteUri, () => app.FindElement(By.Id("test-info")).Text); } [Fact] public void CanArriveAtRouteWithExtension() { // This is an odd test, but it's primarily here to verify routing for routeablecomponentfrompackage isn't available due to // some unknown reason SetUrlViaPushState("/Default.html"); var app = MountTestComponent<TestRouter>(); Assert.Equal("This is the default page.", app.FindElement(By.Id("test-info")).Text); AssertHighlightedLinks("With extension"); } [Fact] public void RoutingToComponentOutsideMainAppDoesNotWork() { SetUrlViaPushState("/routeablecomponentfrompackage.html"); var app = MountTestComponent<TestRouter>(); Assert.Equal("Oops, that component wasn't found!", app.FindElement(By.Id("test-info")).Text); } [Fact] public void RoutingToComponentOutsideMainAppWorksWithAdditionalAssemblySpecified() { SetUrlViaPushState("/routeablecomponentfrompackage.html"); var app = MountTestComponent<TestRouterWithAdditionalAssembly>(); Assert.Contains("This component, including the CSS and image required to produce its", app.FindElement(By.CssSelector("div.special-style")).Text); } [Fact] public void ResetsScrollPositionWhenPerformingInternalNavigation_LinkClick() { SetUrlViaPushState("/LongPage1"); var app = MountTestComponent<TestRouter>(); Browser.Equal("This is a long page you can scroll.", () => app.FindElement(By.Id("test-info")).Text); BrowserScrollY = 500; Browser.True(() => BrowserScrollY > 300); // Exact position doesn't matter app.FindElement(By.LinkText("Long page 2")).Click(); Browser.Equal("This is another long page you can scroll.", () => app.FindElement(By.Id("test-info")).Text); Browser.Equal(0, () => BrowserScrollY); } [Fact] public void ResetsScrollPositionWhenPerformingInternalNavigation_ProgrammaticNavigation() { SetUrlViaPushState("/LongPage1"); var app = MountTestComponent<TestRouter>(); Browser.Equal("This is a long page you can scroll.", () => app.FindElement(By.Id("test-info")).Text); BrowserScrollY = 500; Browser.True(() => BrowserScrollY > 300); // Exact position doesn't matter app.FindElement(By.Id("go-to-longpage2")).Click(); Browser.Equal("This is another long page you can scroll.", () => app.FindElement(By.Id("test-info")).Text); Browser.Equal(0, () => BrowserScrollY); } private long BrowserScrollY { get => (long)((IJavaScriptExecutor)Browser).ExecuteScript("return window.scrollY"); set => ((IJavaScriptExecutor)Browser).ExecuteScript($"window.scrollTo(0, {value})"); } private string SetUrlViaPushState(string relativeUri) { var pathBaseWithoutHash = ServerPathBase.Split('#')[0]; var jsExecutor = (IJavaScriptExecutor)Browser; var absoluteUri = new Uri(_serverFixture.RootUri, $"{pathBaseWithoutHash}{relativeUri}"); jsExecutor.ExecuteScript($"Blazor.navigateTo('{absoluteUri.ToString().Replace("'", "\\'")}')"); return absoluteUri.AbsoluteUri; } private void AssertHighlightedLinks(params string[] linkTexts) { Browser.Equal(linkTexts, () => Browser .FindElements(By.CssSelector("a.active")) .Select(x => x.Text)); } } }
39.995851
158
0.59695
[ "Apache-2.0" ]
7Q2019/AspNetCore
src/Components/test/E2ETest/Tests/RoutingTest.cs
19,278
C#
using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.Extensions.Logging; using MongoDB.Driver; using Quartz; using Turquoise.Common.Mongo; using Turquoise.Common.Scheduler; using Turquoise.Common.Scheduler.HealthCheck; using Turquoise.Models.Scheduler; namespace Turquoise.Worker.Scheduler.QuartzJobSchedules { [DisallowConcurrentExecution] public class HealthCheckSchedulerRepositoryFeeder : IJob { private readonly ILogger<HealthCheckSchedulerRepositoryFeeder> _logger; private readonly MangoBaseRepo<Turquoise.Models.Mongo.ServiceV1> serviceRepo; private readonly HealthCheckSchedulerRepository<Turquoise.Models.Mongo.ServiceV1> healthCheckSchedulerRepository; public HealthCheckSchedulerRepositoryFeeder( ILogger<HealthCheckSchedulerRepositoryFeeder> logger, MangoBaseRepo<Turquoise.Models.Mongo.ServiceV1> serviceRepo, HealthCheckSchedulerRepository<Turquoise.Models.Mongo.ServiceV1> healthCheckSchedulerRepository) { _logger = logger; this.serviceRepo = serviceRepo; this.healthCheckSchedulerRepository = healthCheckSchedulerRepository; } public async Task Execute(IJobExecutionContext context) { var filter = Builders<Turquoise.Models.Mongo.ServiceV1>.Filter.ElemMatch(x => x.Annotations, x => x.Key == "healthcheck/crontab"); var qq = await serviceRepo.Items.FindAsync(filter); var cronitems = qq.ToList(); _logger.LogCritical("HealthCheckSchedulerRepositoryFeeder Started " + cronitems.Count() + " element"); // Add Modify foreach (var item in cronitems) { var repoitem = healthCheckSchedulerRepository.Items.FirstOrDefault(p => p.Uid == item.Uid); if (repoitem != null) { if (item.Annotations.FirstOrDefault(p => p.Key == "healthcheck/crontab")?.Value != null && repoitem.Schedule != item.Annotations.FirstOrDefault(p => p.Key == "healthcheck/crontab")?.Value ) { healthCheckSchedulerRepository.Items.Remove(repoitem); var newitem = new ScheduledTask<Models.Mongo.ServiceV1> { Item = item, Name = item.Name, Namespace = item.Namespace, Uid = item.Uid, Schedule = item.Annotations.FirstOrDefault(p => p.Key == "healthcheck/crontab")?.Value }; healthCheckSchedulerRepository.Items.Add(newitem); } } else { _logger.LogCritical("HealthCheckSchedulerRepositoryFeeder Item Added " + item.Name); var newitem = new ScheduledTask<Models.Mongo.ServiceV1> { Item = item, Name = item.Name, Namespace = item.Namespace, Uid = item.Uid, Schedule = item.Annotations.FirstOrDefault(p => p.Key == "healthcheck/crontab")?.Value }; healthCheckSchedulerRepository.Items.Add(newitem); } } foreach (var item in healthCheckSchedulerRepository.Items) { var cronitem = cronitems.FirstOrDefault(p => p.Uid == item.Uid); if (cronitem == null) { healthCheckSchedulerRepository.Items.Remove(item); } } } } }
41.032258
142
0.57521
[ "Apache-2.0" ]
mmercan/Turquoise.HealthChecks
App/Workers/Turquoise.Worker.Scheduler/QuartzJobSchedules/HealthCheckSchedulerRepositoryFeeder.cs
3,816
C#
// Copyright © Tanner Gooding and Contributors. Licensed under the MIT License (MIT). See License.md in the repository root for more information. // Ported from um/d3d11.h in the Windows SDK for Windows 10.0.19041.0 // Original source is Copyright © Microsoft. All rights reserved. using System; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; namespace TerraFX.Interop { [Guid("38325B96-EFFB-4022-BA02-2E795B70275C")] [NativeTypeName("struct ID3D11GeometryShader : ID3D11DeviceChild")] public unsafe partial struct ID3D11GeometryShader { public void** lpVtbl; [MethodImpl(MethodImplOptions.AggressiveInlining)] [return: NativeTypeName("HRESULT")] public int QueryInterface([NativeTypeName("const IID &")] Guid* riid, [NativeTypeName("void **")] void** ppvObject) { return ((delegate* stdcall<ID3D11GeometryShader*, Guid*, void**, int>)(lpVtbl[0]))((ID3D11GeometryShader*)Unsafe.AsPointer(ref this), riid, ppvObject); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [return: NativeTypeName("ULONG")] public uint AddRef() { return ((delegate* stdcall<ID3D11GeometryShader*, uint>)(lpVtbl[1]))((ID3D11GeometryShader*)Unsafe.AsPointer(ref this)); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [return: NativeTypeName("ULONG")] public uint Release() { return ((delegate* stdcall<ID3D11GeometryShader*, uint>)(lpVtbl[2]))((ID3D11GeometryShader*)Unsafe.AsPointer(ref this)); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public void GetDevice([NativeTypeName("ID3D11Device **")] ID3D11Device** ppDevice) { ((delegate* stdcall<ID3D11GeometryShader*, ID3D11Device**, void>)(lpVtbl[3]))((ID3D11GeometryShader*)Unsafe.AsPointer(ref this), ppDevice); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [return: NativeTypeName("HRESULT")] public int GetPrivateData([NativeTypeName("const GUID &")] Guid* guid, [NativeTypeName("UINT *")] uint* pDataSize, [NativeTypeName("void *")] void* pData) { return ((delegate* stdcall<ID3D11GeometryShader*, Guid*, uint*, void*, int>)(lpVtbl[4]))((ID3D11GeometryShader*)Unsafe.AsPointer(ref this), guid, pDataSize, pData); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [return: NativeTypeName("HRESULT")] public int SetPrivateData([NativeTypeName("const GUID &")] Guid* guid, [NativeTypeName("UINT")] uint DataSize, [NativeTypeName("const void *")] void* pData) { return ((delegate* stdcall<ID3D11GeometryShader*, Guid*, uint, void*, int>)(lpVtbl[5]))((ID3D11GeometryShader*)Unsafe.AsPointer(ref this), guid, DataSize, pData); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [return: NativeTypeName("HRESULT")] public int SetPrivateDataInterface([NativeTypeName("const GUID &")] Guid* guid, [NativeTypeName("const IUnknown *")] IUnknown* pData) { return ((delegate* stdcall<ID3D11GeometryShader*, Guid*, IUnknown*, int>)(lpVtbl[6]))((ID3D11GeometryShader*)Unsafe.AsPointer(ref this), guid, pData); } } }
49.044776
176
0.678028
[ "MIT" ]
Ethereal77/terrafx.interop.windows
sources/Interop/Windows/um/d3d11/ID3D11GeometryShader.cs
3,288
C#
#region License Header /* * QUANTLER.COM - Quant Fund Development Platform * Quantler Core Trading Engine. Copyright 2018 Quantler B.V. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #endregion License Header using Quantler.Account.Cash; using Quantler.Interfaces; namespace Quantler.Messaging.Event { /// <summary> /// Update send outbound for account related information /// </summary> /// <seealso cref="EventMessage" /> public class AccountInfoMessage : EventMessage { #region Public Properties /// <summary> /// Gets or sets the account identifier. /// </summary> public string AccountId { get; set; } /// <summary> /// Gets or sets the fund identifier. /// </summary> public string FundId { get; set; } /// <summary> /// Gets or sets the porfoltio identifier. /// </summary> public string PorfoltioId { get; set; } /// <summary> /// Message type /// </summary> public override EventMessageType Type => EventMessageType.AccountInfo; /// <summary> /// Gets or sets the values. /// </summary> public CalculatedFunds Values { get; set; } #endregion Public Properties #region Public Methods /// <summary> /// Creates the account information message for a portfolio /// </summary> /// <param name="portfolioid">The portfolio id.</param> /// <param name="accountid">The account id.</param> /// <param name="values">The values.</param> /// <param name="currency">The currency.</param> /// <param name="displaycurrency">The display currency.</param> /// <param name="fundid"></param> /// <returns></returns> public static AccountInfoMessage Create(string portfolioid, string accountid, CalculatedFunds values, Currency currency, CurrencyType displaycurrency, string fundid = "") { if(displaycurrency == values.BaseCurrency) //Return generated object return new AccountInfoMessage { PorfoltioId = portfolioid, Values = values, AccountId = accountid, FundId = fundid }; else { //Return currency adjusted values return new AccountInfoMessage { PorfoltioId = portfolioid, Values = values.ConvertCurrency(currency, displaycurrency), AccountId = accountid, FundId = fundid }; } } /// <summary> /// Check if this message is the same as a previous message /// (prevents us from sending messages which have the same information) /// </summary> /// <param name="message"></param> /// <returns></returns> public override bool Equals(EventMessage message) { if (message is AccountInfoMessage) { var instance = message as AccountInfoMessage; return instance.Values.Equity == Values.Equity && instance.Values.FreeMargin == Values.FreeMargin && instance.UniqueId == UniqueId && instance.Values.UnsettledCash == Values.UnsettledCash && instance.Values.BuyingPower == Values.BuyingPower && instance.Values.FloatingPnl == Values.FloatingPnl; } else return false; } #endregion Public Methods #region Protected Methods /// <summary> /// Get unique id for this message type /// </summary> /// <returns></returns> protected override string GetUniqueId() => PorfoltioId + FundId + AccountId; #endregion Protected Methods } }
34.723077
178
0.575764
[ "Apache-2.0" ]
Quantler/Core
Quantler/Messaging/Event/AccountInfoMessage.cs
4,516
C#
//////////////////////////////////////////////////////////////////////////// // <copyright file="Pronunciations.cs" company="Intel Corporation"> // // Copyright (c) 2013-2015 Intel Corporation  // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // // </copyright> //////////////////////////////////////////////////////////////////////////// using System; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.IO; using System.Text; using System.Xml; using ACAT.Lib.Core.Utility; #region SupressStyleCopWarnings [module: SuppressMessage( "StyleCop.CSharp.ReadabilityRules", "SA1126:PrefixCallsCorrectly", Scope = "namespace", Justification = "Not needed. ACAT naming conventions takes care of this")] [module: SuppressMessage( "StyleCop.CSharp.ReadabilityRules", "SA1101:PrefixLocalCallsWithThis", Scope = "namespace", Justification = "Not needed. ACAT naming conventions takes care of this")] [module: SuppressMessage( "StyleCop.CSharp.ReadabilityRules", "SA1121:UseBuiltInTypeAlias", Scope = "namespace", Justification = "Since they are just aliases, it doesn't really matter")] [module: SuppressMessage( "StyleCop.CSharp.DocumentationRules", "SA1200:UsingDirectivesMustBePlacedWithinNamespace", Scope = "namespace", Justification = "ACAT guidelines")] [module: SuppressMessage( "StyleCop.CSharp.NamingRules", "SA1309:FieldNamesMustNotBeginWithUnderscore", Scope = "namespace", Justification = "ACAT guidelines. Private fields begin with an underscore")] [module: SuppressMessage( "StyleCop.CSharp.NamingRules", "SA1300:ElementMustBeginWithUpperCaseLetter", Scope = "namespace", Justification = "ACAT guidelines. Private/Protected methods begin with lowercase")] #endregion SupressStyleCopWarnings namespace ACAT.Lib.Core.TTSManagement { /// <summary> /// Holds a sorted list of pronunciation objects. Raises events when /// it detects a pronunciation has been entered in the text stream /// so the application can handle the expansion suitably. The list of /// pronunciation is created by parsing the xml file that has a list /// of all the pronunciations. /// Pronunciations are useful where the TTS engine may not pronounce /// words correctly (eg proper nouns). This object maps the actual /// spelling with the phonetic spelling. The phonetically spelt word /// is the one sent to the TTS engine to convert to speech. /// </summary> public class Pronunciations : IDisposable { /// <summary> /// xml attribute to get the alternate pronunciation /// </summary> private const String PronunciationAttr = "pronunciation"; /// <summary> /// Xml attribute to get the original word /// </summary> private const String WordAttr = "word"; /// <summary> /// Holds a sorted list of pronunciations /// </summary> private readonly SortedDictionary<String, Pronunciation> _pronunciationList = new SortedDictionary<string, Pronunciation>(); /// <summary> /// Has this object been disposed /// </summary> private bool _disposed; /// <summary> /// Holds a mapping between words and their pronunciations /// </summary> public SortedDictionary<String, Pronunciation> PronunciationList { get { return _pronunciationList; } } /// <summary> /// Adds the pronunciation to the list. If it already exists, /// it is replaced. /// </summary> /// <param name="pronunciation">the pronunciation object</param> /// <returns>true on success</returns> public bool Add(Pronunciation pronunciation) { if (String.IsNullOrEmpty(pronunciation.Word) || String.IsNullOrWhiteSpace(pronunciation.Word) || String.IsNullOrWhiteSpace(pronunciation.AltPronunciation) || String.IsNullOrEmpty(pronunciation.AltPronunciation)) { return false; } _pronunciationList[pronunciation.Word] = pronunciation; return true; } /// <summary> /// Clears all the pronunciations in the list /// </summary> public void Clear() { _pronunciationList.Clear(); } /// <summary> /// Disposes resources /// </summary> public void Dispose() { Dispose(true); // Prevent finalization code for this object // from executing a second time. GC.SuppressFinalize(this); } /// <summary> /// Checks if a word already exists in the lookup table /// </summary> /// <param name="word">pronunciat</param> /// <returns></returns> public bool Exists(String word) { // TODO see if we need to make pronunciations case sensitive or not //return _pronunciationList.ContainsKey(pronunciation.ToUpper()); return _pronunciationList.ContainsKey(word); } /// <summary> /// Loads pronunciation from the specified file. If filename /// is null, loads from the default file. Parses the XML file /// and populates the sorted list /// </summary> /// <param name="pronunciationsFile">Name of the file</param> /// <returns>true on success</returns> public bool Load(String pronunciationsFile) { Log.Debug("Entering..."); bool retVal = true; if (String.IsNullOrEmpty(pronunciationsFile)) { return false; } Log.Debug("pronunciationsFile=" + pronunciationsFile); var doc = new XmlDocument(); try { _pronunciationList.Clear(); if (!File.Exists(pronunciationsFile)) { Log.Debug("Pronunciation file " + pronunciationsFile + " does not exist"); return false; } Log.Debug("found pronuncation file!"); doc.Load(pronunciationsFile); var xmlNodes = doc.SelectNodes("/ACAT/Pronunciations/Pronunciation"); Log.Debug("xmlNodes count=" + xmlNodes.Count); // load all the pronunciations foreach (XmlNode node in xmlNodes) { Log.Debug("adding node:" + node); createAndAddPronunciation(node); } } catch (Exception ex) { Log.Debug("Error processing pronunciation file " + pronunciationsFile + ". Exception: " + ex.ToString()); retVal = false; } return retVal; } /// <summary> /// Looks up the word and returns its pronunciation object. /// </summary> /// <param name="word">word to lookup</param> /// <returns>pronunciation object, null if not found</returns> public Pronunciation Lookup(String word) { var w = word.ToLower(); return Exists(w) ? _pronunciationList[w] : null; } /// <summary> /// Removes the word from the lookup table /// </summary> /// <param name="word">word to lookup</param> /// <returns>true on success</returns> public bool Remove(String word) { bool retVal = true; try { if (Exists(word)) { _pronunciationList.Remove(word); } } catch { retVal = false; } return retVal; } /// <summary> /// Takes in a string of text (a sentence for example), parses it into /// words, looks up each word in the lookup table to see if there is /// an alternate pronunciation and if so, replaces the word with the /// alternate pronunciation. Returns the converted sentence with the /// phonetically spelt words. /// </summary> /// <param name="inputString">input text</param> /// <returns>converted text</returns> public String ReplaceWithAlternatePronunciations(String inputString) { String word; var strOutput = new StringBuilder(); var strWord = new StringBuilder(); Pronunciation pronunciation; foreach (char ch in inputString) { if (Char.IsLetterOrDigit(ch) || ch == '\'' || ch == '’') { strWord.Append(ch); } else { word = strWord.ToString(); strOutput.Append(((pronunciation = Lookup(word)) != null) ? pronunciation.AltPronunciation : word); strWord = new StringBuilder(); strOutput.Append(ch); } } word = strWord.ToString(); strOutput.Append(((pronunciation = Lookup(word)) != null) ? pronunciation.AltPronunciation : word); var retVal = strOutput.ToString(); Log.Debug("replacedString: " + retVal); return retVal; } /// <summary> /// Saves all the pronunciation from the lookup table to the pronunciation file /// </summary> /// <returns>true on success</returns> public bool Save(String pronunciationsFile) { bool retVal = true; try { var xmlTextWriter = createPronunciationsFile(pronunciationsFile); if (xmlTextWriter != null) { foreach (var pronunciationObj in _pronunciationList.Values) { xmlTextWriter.WriteStartElement("Pronunciation"); xmlTextWriter.WriteAttributeString(WordAttr, pronunciationObj.Word); xmlTextWriter.WriteAttributeString(PronunciationAttr, pronunciationObj.AltPronunciation); xmlTextWriter.WriteEndElement(); } closePronunciationFile(xmlTextWriter); } } catch (IOException ex) { Log.Exception(ex); retVal = false; } return retVal; } /// <summary> /// Replaces the old pronunciation with a new one. /// </summary> /// <param name="word">word to look for</param> /// <param name="pronunciation">new pronunciation object</param> /// <returns></returns> public bool Update(String word, Pronunciation pronunciation) { Remove(word); return Add(pronunciation); } /// <summary> /// Disposer. Release resources and cleanup. /// </summary> /// <param name="disposing">true to dispose managed resources</param> protected virtual void Dispose(bool disposing) { // Check to see if Dispose has already been called. if (!_disposed) { Log.Debug(); if (disposing) { foreach (var p in _pronunciationList.Values) { p.Dispose(); } _pronunciationList.Clear(); } // Release unmanaged resources. } _disposed = true; } /// <summary> /// Closes the pronunciation file after writing out the close tag /// </summary> /// <param name="xmlTextWriter">the xml writer object</param> private static void closePronunciationFile(XmlWriter xmlTextWriter) { try { xmlTextWriter.WriteEndDocument(); xmlTextWriter.Flush(); xmlTextWriter.Close(); } catch (Exception ex) { Log.Debug(ex.ToString()); } } /// <summary> /// Creates an empty pronunciation XML file /// </summary> /// <param name="fileName">name of the file to create</param> /// <returns>xml writer</returns> private static XmlTextWriter createPronunciationsFile(String fileName) { XmlTextWriter xmlTextWriter; // overwrite even if it already exists try { xmlTextWriter = new XmlTextWriter(fileName, null) { Formatting = Formatting.Indented }; xmlTextWriter.WriteStartDocument(); xmlTextWriter.WriteStartElement("ACAT"); xmlTextWriter.WriteStartElement("Pronunciations"); } catch (Exception ex) { Log.Debug(ex.ToString()); xmlTextWriter = null; } return xmlTextWriter; } /// <summary> /// Parses the xml node attributes and creates an pronunciation object /// and adds it to the sort list /// </summary> /// <param name="node">xml node to parse</param> private void createAndAddPronunciation(XmlNode node) { var word = XmlUtils.GetXMLAttrString(node, WordAttr).Trim().ToLower(); var pronunciation = XmlUtils.GetXMLAttrString(node, PronunciationAttr); Log.Debug("word=" + word + " pronunciation=" + pronunciation); Add(new Pronunciation(word, pronunciation)); } } }
34.494062
132
0.552403
[ "Apache-2.0" ]
AchilleFoti/acat
src/Libraries/ACATCore/TTSManagement/Pronunciations.cs
14,599
C#
using AutoMapper; using MediatR; using Microsoft.AspNetCore.Authentication.JwtBearer; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc; using NetCoreWebTemplate.Api.Contracts.Version1.Requests; using NetCoreWebTemplate.Api.Routes.Version1; using NetCoreWebTemplate.Application.Clients.Commands.CreateClient; using NetCoreWebTemplate.Application.Clients.Queries.GetClientDetails; using System.Threading.Tasks; namespace NetCoreWebTemplate.Api.Controllers.Version1 { [Authorize(AuthenticationSchemes = JwtBearerDefaults.AuthenticationScheme)] [ApiController] public class ClientController : ControllerBase { private readonly IMediator mediator; private readonly IMapper mapper; public ClientController(IMediator mediator, IMapper mapper) { this.mediator = mediator; this.mapper = mapper; } /// <summary> /// Creates a New Client /// </summary> /// <response code="201">Creates a New Client</response> /// <response code="400">Unable to create Client due to validation error</response> /// <response code="429">Too Many Requests</response> [ProducesResponseType(StatusCodes.Status201Created)] [ProducesResponseType(StatusCodes.Status400BadRequest)] [ProducesResponseType(StatusCodes.Status429TooManyRequests)] [HttpPost(ApiRoutes.Client.Create)] public async Task<IActionResult> Create([FromBody] ClientRequest clientRequest) { var clientViewModel = mapper.Map<ClientViewModel>(clientRequest); var command = new CreateClientCommand(clientViewModel); var result = await mediator.Send(command); return CreatedAtAction("CreateClient", result); } /// <summary> /// Returns a Client specified by an Id /// </summary> /// <response code="200">Returns a Client specified by an Id</response> /// <response code="400">Unable to return Client due to invalid Id</response> /// <response code="429">Too Many Requests</response> /// <returns></returns> [ProducesResponseType(StatusCodes.Status200OK)] [ProducesResponseType(StatusCodes.Status404NotFound)] [ProducesResponseType(StatusCodes.Status429TooManyRequests)] [HttpPost(ApiRoutes.Client.Get)] public async Task<IActionResult> Get(long clientId) { var query = new GetClientByIdQuery(clientId); var result = await mediator.Send(query); return Ok(result); } } }
39.507463
91
0.687571
[ "MIT" ]
marlonajgayle/NetCoreWebTemplate
NetCoreWebTemplate.Api/Controllers/Version1/ClientController.cs
2,649
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("LewisTech.Utils.Tests")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("LewisTech.Utils.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("8275fad2-69a0-402d-9e1a-c5f8ac38d79d")] // 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.243243
84
0.745583
[ "MIT" ]
coolkev/LewisTech.Utils
src/LewisTech.Utils.Tests/Properties/AssemblyInfo.cs
1,418
C#
using System; using System.Data; using System.Text; using System.Data.SqlClient; using MxWeiXinPF.DBUtility; using MxWeiXinPF.Common;//Please add references namespace MxWeiXinPF.DAL { /// <summary> /// 数据访问类:wx_message_blacklist /// </summary> public partial class wx_message_blacklist { public wx_message_blacklist() {} #region BasicMethod /// <summary> /// 得到最大ID /// </summary> public int GetMaxId() { return DbHelperSQL.GetMaxID("id", "wx_message_blacklist"); } /// <summary> /// 是否存在该记录 /// </summary> public bool Exists(int id) { StringBuilder strSql = new StringBuilder(); strSql.Append("select count(1) from wx_message_blacklist"); strSql.Append(" where id=@id"); SqlParameter[] parameters = { new SqlParameter("@id", SqlDbType.Int,8) }; parameters[0].Value = id; return DbHelperSQL.Exists(strSql.ToString(), parameters); } /// <summary> /// 增加一条数据 /// </summary> public int Add(MxWeiXinPF.Model.wx_message_blacklist model) { StringBuilder strSql = new StringBuilder(); strSql.Append("insert into wx_message_blacklist("); strSql.Append("wid,openid,blacktime)"); strSql.Append(" values ("); strSql.Append("@wid,@openid,@blacktime)"); strSql.Append(";select @@IDENTITY"); SqlParameter[] parameters = { new SqlParameter("@wid", SqlDbType.Int,8), new SqlParameter("@openid", SqlDbType.VarChar,500), new SqlParameter("@blacktime", SqlDbType.DateTime)}; parameters[0].Value = model.wid; parameters[1].Value = model.openid; parameters[2].Value = model.blacktime; object obj = DbHelperSQL.GetSingle(strSql.ToString(), parameters); if (obj == null) { return 0; } else { return Convert.ToInt32(obj); } } /// <summary> /// 更新一条数据 /// </summary> public bool Update(MxWeiXinPF.Model.wx_message_blacklist model) { StringBuilder strSql = new StringBuilder(); strSql.Append("update wx_message_blacklist set "); strSql.Append("wid=@wid,"); strSql.Append("openid=@openid,"); strSql.Append("blacktime=@blacktime"); strSql.Append(" where id=@id"); SqlParameter[] parameters = { new SqlParameter("@wid", SqlDbType.Int,8), new SqlParameter("@openid", SqlDbType.VarChar,500), new SqlParameter("@blacktime", SqlDbType.DateTime), new SqlParameter("@id", SqlDbType.Int,8)}; parameters[0].Value = model.wid; parameters[1].Value = model.openid; parameters[2].Value = model.blacktime; parameters[3].Value = model.id; int rows = DbHelperSQL.ExecuteSql(strSql.ToString(), parameters); if (rows > 0) { return true; } else { return false; } } /// <summary> /// 删除一条数据 /// </summary> public bool Delete(int id) { StringBuilder strSql = new StringBuilder(); strSql.Append("delete from wx_message_blacklist "); strSql.Append(" where id=@id"); SqlParameter[] parameters = { new SqlParameter("@id", SqlDbType.Int,8) }; parameters[0].Value = id; int rows = DbHelperSQL.ExecuteSql(strSql.ToString(), parameters); if (rows > 0) { return true; } else { return false; } } /// <summary> /// 批量删除数据 /// </summary> public bool DeleteList(string idlist) { StringBuilder strSql = new StringBuilder(); strSql.Append("delete from wx_message_blacklist "); strSql.Append(" where id in (" + idlist + ") "); int rows = DbHelperSQL.ExecuteSql(strSql.ToString()); if (rows > 0) { return true; } else { return false; } } /// <summary> /// 得到一个对象实体 /// </summary> public MxWeiXinPF.Model.wx_message_blacklist GetModel(int id) { StringBuilder strSql = new StringBuilder(); strSql.Append("select top 1 id,wid,openid,blacktime from wx_message_blacklist "); strSql.Append(" where id=@id"); SqlParameter[] parameters = { new SqlParameter("@id", SqlDbType.Int,8) }; parameters[0].Value = id; MxWeiXinPF.Model.wx_message_blacklist model = new MxWeiXinPF.Model.wx_message_blacklist(); DataSet ds = DbHelperSQL.Query(strSql.ToString(), parameters); if (ds.Tables[0].Rows.Count > 0) { return DataRowToModel(ds.Tables[0].Rows[0]); } else { return null; } } /// <summary> /// 得到一个对象实体 /// </summary> public MxWeiXinPF.Model.wx_message_blacklist DataRowToModel(DataRow row) { MxWeiXinPF.Model.wx_message_blacklist model = new MxWeiXinPF.Model.wx_message_blacklist(); if (row != null) { if (row["id"] != null && row["id"].ToString() != "") { model.id = int.Parse(row["id"].ToString()); } if (row["wid"] != null && row["wid"].ToString() != "") { model.wid = int.Parse(row["wid"].ToString()); } if (row["openid"] != null) { model.openid = row["openid"].ToString(); } if (row["blacktime"] != null && row["blacktime"].ToString() != "") { model.blacktime = DateTime.Parse(row["blacktime"].ToString()); } } return model; } /// <summary> /// 获得数据列表 /// </summary> public DataSet GetList(string strWhere) { StringBuilder strSql = new StringBuilder(); strSql.Append("select id,wid,openid,blacktime "); strSql.Append(" FROM wx_message_blacklist "); if (strWhere.Trim() != "") { strSql.Append(" where " + strWhere); } return DbHelperSQL.Query(strSql.ToString()); } /// <summary> /// 获得前几行数据 /// </summary> public DataSet GetList(int Top, string strWhere, string filedOrder) { StringBuilder strSql = new StringBuilder(); strSql.Append("select "); if (Top > 0) { strSql.Append(" top " + Top.ToString()); } strSql.Append(" id,wid,openid,blacktime "); strSql.Append(" FROM wx_message_blacklist "); if (strWhere.Trim() != "") { strSql.Append(" where " + strWhere); } strSql.Append(" order by " + filedOrder); return DbHelperSQL.Query(strSql.ToString()); } /// <summary> /// 获取记录总数 /// </summary> public int GetRecordCount(string strWhere) { StringBuilder strSql = new StringBuilder(); strSql.Append("select count(1) FROM wx_message_blacklist "); if (strWhere.Trim() != "") { strSql.Append(" where " + strWhere); } object obj = DbHelperSQL.GetSingle(strSql.ToString()); if (obj == null) { return 0; } else { return Convert.ToInt32(obj); } } /// <summary> /// 分页获取数据列表 /// </summary> public DataSet GetListByPage(string strWhere, string orderby, int startIndex, int endIndex) { StringBuilder strSql = new StringBuilder(); strSql.Append("SELECT * FROM ( "); strSql.Append(" SELECT ROW_NUMBER() OVER ("); if (!string.IsNullOrEmpty(orderby.Trim())) { strSql.Append("order by T." + orderby); } else { strSql.Append("order by T.id desc"); } strSql.Append(")AS Row, T.* from wx_message_blacklist T "); if (!string.IsNullOrEmpty(strWhere.Trim())) { strSql.Append(" WHERE " + strWhere); } strSql.Append(" ) TT"); strSql.AppendFormat(" WHERE TT.Row between {0} and {1}", startIndex, endIndex); return DbHelperSQL.Query(strSql.ToString()); } #endregion BasicMethod #region ExtensionMethod /// <summary> /// 获得数据列表 /// </summary> public DataSet GetList(int pageSize, int pageIndex, string strWhere, string filedOrder, out int recordCount) { StringBuilder strSql = new StringBuilder(); strSql.Append("select wid,openid,blacktime "); strSql.Append(" FROM wx_message_blacklist "); if (strWhere.Trim() != "") { strSql.Append(" where " + strWhere); } recordCount = Convert.ToInt32(DbHelperSQL.GetSingle(PagingHelper.CreateCountingSql(strSql.ToString()))); return DbHelperSQL.Query(PagingHelper.CreatePagingSql(recordCount, pageSize, pageIndex, strSql.ToString(), filedOrder)); } /// <summary> /// 删除一条数据 /// </summary> public bool DeleteByOpenid(int openId) { //该表无主键信息,请自定义主键/条件字段 StringBuilder strSql = new StringBuilder(); strSql.Append("delete from wx_message_blacklist "); strSql.Append(" where openId='" + openId + "' "); SqlParameter[] parameters = { new SqlParameter("@openId", SqlDbType.Int,8) }; parameters[0].Value = openId; int rows = DbHelperSQL.ExecuteSql(strSql.ToString(), parameters); if (rows > 0) { return true; } else { return false; } } public bool ExistsByOpenid(string openid) { StringBuilder strSql = new StringBuilder(); strSql.Append("select count(1) from wx_message_blacklist"); strSql.Append(" where openid=@openid"); SqlParameter[] parameters = { new SqlParameter("@openid", SqlDbType.VarChar,500) }; parameters[0].Value = openid; return DbHelperSQL.Exists(strSql.ToString(), parameters); } public bool Deleteblack(int wid, string openId) { //该表无主键信息,请自定义主键/条件字段 StringBuilder strSql = new StringBuilder(); strSql.Append("delete from wx_message_blacklist "); strSql.Append(" where openId='" + openId + "' and wid='" + wid + "' "); SqlParameter[] parameters = { new SqlParameter("@openId", SqlDbType.VarChar,500), new SqlParameter("@wid", SqlDbType.Int,8) }; parameters[0].Value = openId; parameters[1].Value = wid; int rows = DbHelperSQL.ExecuteSql(strSql.ToString(), parameters); if (rows > 0) { return true; } else { return false; } } public bool Deleteopenid(int id) { StringBuilder strSql = new StringBuilder(); strSql.Append("delete from wx_message_list "); strSql.Append(" where openId=@id"); SqlParameter[] parameters = { new SqlParameter("@id", SqlDbType.Int,8) }; parameters[0].Value = id; int rows = DbHelperSQL.ExecuteSql(strSql.ToString(), parameters); if (rows > 0) { return true; } else { return false; } } #endregion ExtensionMethod } }
32.017766
132
0.499723
[ "MIT" ]
herrylau/wwzkushop
MxWeiXinPF.DAL/plugs/wx_message_blacklist.cs
12,879
C#
using Presentation.Common.Domain.StructuralMetadata.Interfaces; namespace Presentation.Common.Domain.StructuralMetadata.Abstracts { public abstract class AbstractDomain : AuditableEntity, IDomain { public long Id { get; set; } } }
25.3
67
0.750988
[ "MIT" ]
parstat/structural-metadata
Parstat.StructuralMetadata/Presentation/Presentation.Common.Domain/StructuralMetadata/Abstracts/AbstractDomain.cs
255
C#
/* The MIT License (MIT) Copyright (c) 2015 Dimitri Slappendel Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ using System; using System.Collections.Generic; using System.Linq; using System.Text; using UnityEngine; namespace AmbientSoundsTuner2.Compatibility { /// <summary> /// This static class contains patches for sirens that maintain compatibility with other mods as much as possible, /// while still patching and improving functionality of those sirens. /// </summary> /// /// <remarks> /// Patches created by Archomeda, released under MIT license. /// /// If you're looking for applying the same patch, please use my methods below. /// This will ensure that you don't break other mods when trying to create your own patch. /// </remarks> public static class SoundDuplicator { public const string EFFECT_POLICE_CAR_SIREN = "Police Car Siren"; public const string EFFECT_SCOOTER_SOUND = "Scooter Sound"; public const string BUILDING_OIL_POWER_PLANT = "Oil Power Plant"; public const string BUILDING_WATER_TREATMENT_PLANT = "Water Treatment Plant"; public const string AUDIOINFO_POLICE_CAR_SIREN = "Siren Police Car"; public const string AUDIOINFO_SCOOTER_ENGINE = "Scooter Engine"; public const string AUDIOINFO_OIL_POWER_PLANT = "Building Oil Power Plant"; public const string AUDIOINFO_WATER_TREATMENT_PLANT = "Building Water Treatment Plant"; public enum PatchResult { Success, AlreadyPatched, NotFound, } /// <summary> /// This method has to be called before changing the police sirens. /// Currently, the game treats the police sirens the same as the ambulance sirens. /// This means that, when the ambulance siren gets changed, the police siren gets changed too, and vice versa. /// Here we patch it so they are both treated differently. /// </summary> public static PatchResult PatchPoliceSiren() { return DuplicateEffectAudioInfo(EFFECT_POLICE_CAR_SIREN, AUDIOINFO_POLICE_CAR_SIREN); } /// <summary> /// This method has to be called before changing the scooter sounds. /// Currently, the game treats the scooter sounds the same as the small car engine sounds. /// This means that, when the small car engine sound gets changed, the scooter sound gets changed too, and vice versa. /// Here we patch it so they are both treated differently. /// </summary> public static PatchResult PatchScooterSound() { return DuplicateEffectAudioInfo(EFFECT_SCOOTER_SOUND, AUDIOINFO_SCOOTER_ENGINE); } /// <summary> /// This method has to be called before changing the oil power plant sounds. /// Currently, the game treats the oil power plant sounds the same as the coal power plant sounds. /// This means that, when the oil power plant sound gets changed, the coal power plant sound gets changed too, and vice versa. /// Here we patch it so they are both treated differently. /// </summary> public static PatchResult PatchOilPowerPlant() { return DuplicateBuildingAudioInfo(BUILDING_OIL_POWER_PLANT, AUDIOINFO_OIL_POWER_PLANT); } /// <summary> /// This method has to be called before changing the water treatment plant sounds. /// Currently, the game treats the water treatment plant sounds the same as the water drain pipe sounds. /// This means that, when the water treatment plant sound gets changed, the water drain pipe sound gets changed too, and vice versa. /// Here we patch it so they are both treated differently. /// </summary> public static PatchResult PatchWaterTreatmentPlant() { return DuplicateBuildingAudioInfo(BUILDING_WATER_TREATMENT_PLANT, AUDIOINFO_WATER_TREATMENT_PLANT); } private static PatchResult DuplicateEffectAudioInfo(string effectId, string audioInfoId, MultiEffect effectContainer = null) { SoundEffect soundEffect = null; if (effectContainer != null) soundEffect = effectContainer.m_effects.FirstOrDefault(e => e.m_effect.name == effectId).m_effect as SoundEffect; else soundEffect = EffectCollection.FindEffect(effectId) as SoundEffect; if (soundEffect == null || soundEffect.m_audioInfo == null) return PatchResult.NotFound; // Check if the AudioInfo object has our name, if not, we have to patch it. if (soundEffect.m_audioInfo.name != audioInfoId) { AudioInfo audioInfo = GameObject.Instantiate(soundEffect.m_audioInfo); audioInfo.name = audioInfoId; soundEffect.m_audioInfo = audioInfo; return PatchResult.Success; } return PatchResult.AlreadyPatched; } private static PatchResult DuplicateBuildingAudioInfo(string buildingId, string audioInfoId) { BuildingInfo building = PrefabCollection<BuildingInfo>.FindLoaded(buildingId); if (building == null || building.m_customLoopSound == null) return PatchResult.NotFound; // Check if the AudioInfo object has our name, if not, we have to patch it. if (building.m_customLoopSound.name != audioInfoId) { AudioInfo audioInfo = GameObject.Instantiate(building.m_customLoopSound); audioInfo.name = audioInfoId; building.m_customLoopSound = audioInfo; return PatchResult.Success; } return PatchResult.AlreadyPatched; } } }
46.236486
140
0.682011
[ "MIT" ]
bloodypenguin/csl-ambient-sounds-tuner
CSL Ambient Sounds Tuner/Compatibility/SoundDuplicator.cs
6,845
C#
//*********************************************************// // Copyright (c) Microsoft. All rights reserved. // // Apache 2.0 License // // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or // implied. See the License for the specific language governing // permissions and limitations under the License. // //*********************************************************// using System; using System.ComponentModel.Composition; using System.Diagnostics; using Microsoft.VisualStudio.Text.BraceCompletion; using Microsoft.VisualStudio.Text.Operations; using PowerShellTools.Repl; namespace PowerShellTools.LanguageService.BraceCompletion { [Export(typeof(IBraceCompletionContext))] internal class BraceCompletionContext : IBraceCompletionContext { private readonly IEditorOperations _editorOperations; private readonly ITextUndoHistory _undoHistory; /// <summary> /// Constructor. /// </summary> /// <param name="editorOperations">Imported MEF component.</param> /// <param name="undoHistory">Imported MEF component.</param> public BraceCompletionContext(IEditorOperations editorOperations, ITextUndoHistory undoHistory) { _editorOperations = editorOperations; _undoHistory = undoHistory; } /// <summary> /// Interface method implementation. Called by the editor when the closing brace character has been typed. /// It does not occur if there is any non-whitespace character between the caret and the closing brace. /// </summary> /// <param name="session">Current brace completion session.</param> /// <returns>Always true.</returns> public bool AllowOverType(IBraceCompletionSession session) { return true; } /// <summary> /// Occurs after the session has been removed from the stack. /// </summary> /// <param name="session"></param> public void Finish(IBraceCompletionSession session) { } /// <summary> /// Called before the session is added to the stack. /// </summary> /// <param name="session"></param> public void Start(IBraceCompletionSession session) { } /// <summary> /// Called by the editor when return is pressed while both braces are on the same line and no typing has occurred in the session. /// </summary> /// <param name="session">Current brace completion session.</param> public void OnReturn(IBraceCompletionSession session) { // Return in Repl window would just execute the current command if (session.SubjectBuffer.ContentType.TypeName.Equals(ReplConstants.ReplContentTypeName, StringComparison.OrdinalIgnoreCase)) { return; } var closingPointPosition = session.ClosingPoint.GetPosition(session.SubjectBuffer.CurrentSnapshot); Debug.Assert( condition: closingPointPosition > 0, message: "The closing point position should always be greater than zero", detailMessage: "The closing point position should always be greater than zero, " + "since there is also an opening point for this brace completion session"); // reshape code from // { // |} // // to // { // | // } // where | indicates caret position. using (var undo = _undoHistory.CreateTransaction("Insert new line.")) { _editorOperations.AddBeforeTextBufferChangePrimitive(); _editorOperations.MoveLineUp(false); _editorOperations.MoveToEndOfLine(false); _editorOperations.InsertNewLine(); _editorOperations.AddAfterTextBufferChangePrimitive(); undo.Complete(); } } } }
40.229358
138
0.596807
[ "Apache-2.0" ]
Bhaskers-Blu-Org2/poshtools
PowerShellTools/LanguageService/BraceCompletion/BraceCompletionContext.cs
4,387
C#
using Dhgms.GripeWithRoslyn.Analyzer.CodeCracker.Extensions; namespace Dhgms.GripeWithRoslyn.Analyzer.Analyzers { using System; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Diagnostics; /// <summary> /// Roslyn Analyzer to check for uses of FluentData's AutoMap method /// </summary> /// <remarks> /// Based upon : https://raw.githubusercontent.com/Wintellect/Wintellect.Analyzers/master/Source/Wintellect.Analyzers/Wintellect.Analyzers/Usage/CallAssertMethodsWithMessageParameterAnalyzer.cs /// </remarks> [DiagnosticAnalyzer(LanguageNames.CSharp, LanguageNames.VisualBasic)] public sealed class FluentDataQueryManyWithNullArgument : BaseInvocationWithArgumentsAnalzyer { private const string Title = "FluentData QueryMany should not be used with a null value for the mapper."; private const string MessageFormat = Title; private const string Category = SupportedCategories.Maintainability; private const string Description = "QueryMany without a mapper produces potential technical debt where if you are preparing the database schema for new content the old POCO objects won't map due to not having the corresponding property. This risks taking down your platform\\service. Please use a mapper."; /// <summary> /// Creates an instance of FluentDataQueryManyWithNullArgument /// </summary> public FluentDataQueryManyWithNullArgument() : base( DiagnosticIdsHelper.FluentDataQueryManyWithNullArgumentAnalyzer, Title, MessageFormat, Category, Description, DiagnosticSeverity.Warning) { } /// <summary> /// The name of the method to check for. /// </summary> protected override string MethodName => "QueryMany"; /// <summary> /// The classes the method may belong to. /// </summary> protected override string[] ContainingTypes => new[] { "FluentData.ISelectBuilder<TEntity>", "FluentData.IStoredProcedureBuilder<T>", "FluentData.IStoredProcedureBuilderDynamic", "FluentData.IDbCommand", "FluentData.IQuery" }; /// <summary> /// Event for validating the arguments passed /// </summary> /// <param name="context">The context for the Roslyn syntax analysis</param> /// <param name="argumentList">Syntax representation of the argument list.</param> protected override void OnValidateArguments(SyntaxNodeAnalysisContext context, ArgumentListSyntax argumentList) { if (argumentList?.Arguments.Count != 1) { return; } // todo: try and remove the tostring call var arg = argumentList.Arguments[0]; if (arg.Expression.ToString().Equals("null", StringComparison.Ordinal)) { var diagnostic = Diagnostic.Create(Rule, arg.Expression.GetLocation()); context.ReportDiagnostic(diagnostic); } } } }
40.987654
283
0.631928
[ "MIT" ]
DHGMS-Solutions/gripewithroslyn
src/Dhgms.GripeWithRoslyn.Analyzer/Analyzers/FluentDataQueryManyWithNullArgumentAnalyzer.cs
3,322
C#
// Copyright (c) 2012, Event Store LLP // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // Neither the name of the Event Store LLP nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // using System.Collections.Generic; using System.Net; using EventStore.Common.Utils; using EventStore.Core.Bus; using EventStore.Core.DataStructures; using EventStore.Core.Messaging; namespace EventStore.Core.Tests.Infrastructure { public class RandomTestRunner { private readonly int _maxIterCnt; private readonly PairingHeap<RandTestQueueItem> _queue; private int _iter; private int _curLogicalTime; private int _globalMsgId; public RandomTestRunner(int maxIterCnt) { _maxIterCnt = maxIterCnt; _queue = new PairingHeap<RandTestQueueItem>(new GlobalQueueItemComparer()); } public bool Run(IRandTestFinishCondition finishCondition, params IRandTestItemProcessor[] processors) { Ensure.NotNull(finishCondition, "finishCondition"); while (++_iter <= _maxIterCnt && _queue.Count > 0) { var item = _queue.DeleteMin(); _curLogicalTime = item.LogicalTime; foreach (var processor in processors) { processor.Process(_iter, item); } finishCondition.Process(_iter, item); if (finishCondition.Done) break; item.Bus.Publish(item.Message); } return finishCondition.Success; } public void Enqueue(IPEndPoint endPoint, Message message, IPublisher bus, int timeDelay = 1) { System.Diagnostics.Debug.Assert(timeDelay >= 1); _queue.Add(new RandTestQueueItem(_curLogicalTime + timeDelay, _globalMsgId++, endPoint, message, bus)); } private class GlobalQueueItemComparer: IComparer<RandTestQueueItem> { public int Compare(RandTestQueueItem x, RandTestQueueItem y) { if (x.LogicalTime == y.LogicalTime) return x.GlobalId - y.GlobalId; return x.LogicalTime - y.LogicalTime; } } } }
40.021978
115
0.676002
[ "BSD-3-Clause" ]
eleks/EventStore
src/EventStore/EventStore.Core.Tests/Infrastructure/RandomTestRunner.cs
3,644
C#
#pragma warning disable 1591 // ------------------------------------------------------------------------------ // <autogenerated> // This code was generated by a tool. // Mono Runtime Version: 4.0.30319.17020 // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // </autogenerated> // ------------------------------------------------------------------------------ [assembly: Android.Runtime.ResourceDesignerAttribute("XamChat.Droid.Resource", IsApplication=true)] namespace XamChat.Droid { [System.CodeDom.Compiler.GeneratedCodeAttribute("Xamarin.Android.Build.Tasks", "1.0.0.0")] public partial class Resource { static Resource() { global::Android.Runtime.ResourceIdManager.UpdateIdValues(); } public static void UpdateIdValues() { } public partial class Attribute { static Attribute() { global::Android.Runtime.ResourceIdManager.UpdateIdValues(); } private Attribute() { } } public partial class Drawable { // aapt resource value: 0x7f020000 public const int Icon = 2130837504; static Drawable() { global::Android.Runtime.ResourceIdManager.UpdateIdValues(); } private Drawable() { } } public partial class Id { // aapt resource value: 0x7f060010 public const int addFriendMenu = 2131099664; // aapt resource value: 0x7f060001 public const int conversationLastMessage = 2131099649; // aapt resource value: 0x7f060000 public const int conversationUsername = 2131099648; // aapt resource value: 0x7f060002 public const int conversationsList = 2131099650; // aapt resource value: 0x7f060003 public const int friendName = 2131099651; // aapt resource value: 0x7f060004 public const int friendsList = 2131099652; // aapt resource value: 0x7f060007 public const int login = 2131099655; // aapt resource value: 0x7f060008 public const int messageList = 2131099656; // aapt resource value: 0x7f06000b public const int messageText = 2131099659; // aapt resource value: 0x7f06000d public const int myMessageDate = 2131099661; // aapt resource value: 0x7f06000c public const int myMessageText = 2131099660; // aapt resource value: 0x7f060006 public const int password = 2131099654; // aapt resource value: 0x7f060009 public const int relativeLayout1 = 2131099657; // aapt resource value: 0x7f06000a public const int sendButton = 2131099658; // aapt resource value: 0x7f06000f public const int theirMessageDate = 2131099663; // aapt resource value: 0x7f06000e public const int theirMessageText = 2131099662; // aapt resource value: 0x7f060005 public const int username = 2131099653; static Id() { global::Android.Runtime.ResourceIdManager.UpdateIdValues(); } private Id() { } } public partial class Layout { // aapt resource value: 0x7f030000 public const int ConversationListItem = 2130903040; // aapt resource value: 0x7f030001 public const int Conversations = 2130903041; // aapt resource value: 0x7f030002 public const int FriendListItem = 2130903042; // aapt resource value: 0x7f030003 public const int Friends = 2130903043; // aapt resource value: 0x7f030004 public const int Login = 2130903044; // aapt resource value: 0x7f030005 public const int Messages = 2130903045; // aapt resource value: 0x7f030006 public const int MyMessageListItem = 2130903046; // aapt resource value: 0x7f030007 public const int TheirMessageListItem = 2130903047; static Layout() { global::Android.Runtime.ResourceIdManager.UpdateIdValues(); } private Layout() { } } public partial class Menu { // aapt resource value: 0x7f050000 public const int ConversationsMenu = 2131034112; static Menu() { global::Android.Runtime.ResourceIdManager.UpdateIdValues(); } private Menu() { } } public partial class String { // aapt resource value: 0x7f040000 public const int ApplicationName = 2130968576; // aapt resource value: 0x7f040001 public const int ErrorTitle = 2130968577; // aapt resource value: 0x7f040002 public const int Loading = 2130968578; static String() { global::Android.Runtime.ResourceIdManager.UpdateIdValues(); } private String() { } } } } #pragma warning restore 1591
22.835821
99
0.655556
[ "MIT" ]
PacktPublishing/Xamarin-Cross-Platform-Mobile-Application-Development
Module 1/Chapter6/XamChat.Droid/Resources/Resource.designer.cs
4,590
C#
using UnityEngine.InputSystem.Layouts; using UnityEngine.InputSystem.LowLevel; namespace UnityEngine.InputSystem.Controls { /// <summary> /// A floating-point 2D vector control composed of two <see cref="AxisControl"/>s. /// </summary> /// <remarks> /// An example is <see cref="Pointer.position"/>. /// /// <example> /// <code> /// Debug.Log(string.Format("Mouse position x={0} y={1}", /// Mouse.current.position.x.ReadValue(), /// Mouse.current.position.y.ReadValue())); /// </code> /// /// Normalization is not implied. The X and Y coordinates can be in any range or units. /// </example> /// </remarks> public class Vector2Control : InputControl<Vector2> { /// <summary> /// Horizontal position of the control. /// </summary> /// <value>Control representing horizontal motion input.</value> [InputControl(offset = 0, displayName = "X")] public AxisControl x { get; set; } /// <summary> /// Vertical position of the control. /// </summary> /// <value>Control representing vertical motion input.</value> [InputControl(offset = 4, displayName = "Y")] public AxisControl y { get; set; } /// <summary> /// Default-initialize the control. /// </summary> public Vector2Control() { m_StateBlock.format = InputStateBlock.FormatVector2; } /// <inheritdoc /> protected override void FinishSetup() { x = GetChildControl<AxisControl>("x"); y = GetChildControl<AxisControl>("y"); base.FinishSetup(); } /// <inheritdoc /> public override unsafe Vector2 ReadUnprocessedValueFromState(void* statePtr) { return new Vector2( x.ReadUnprocessedValueFromState(statePtr), y.ReadUnprocessedValueFromState(statePtr)); } /// <inheritdoc /> public override unsafe void WriteValueIntoState(Vector2 value, void* statePtr) { x.WriteValueIntoState(value.x, statePtr); y.WriteValueIntoState(value.y, statePtr); } /// <inheritdoc /> public override unsafe float EvaluateMagnitude(void* statePtr) { ////REVIEW: this can go beyond 1; that okay? return ReadValueFromState(statePtr).magnitude; } } }
31.679487
91
0.57588
[ "Apache-2.0" ]
AhmadAlrifa1/Shooter-Game
Library/PackageCache/com.unity.inputsystem@1.3.0/InputSystem/Controls/Vector2Control.cs
2,471
C#
using System; using Mirror; using System.Collections.Generic; using UnityEngine.Assertions; namespace Insight { public class InsightMessageBase : MessageBase {} public class InsightMessage : InsightMessageBase { public int callbackId; public CallbackStatus status = CallbackStatus.Default; public InsightMessageBase message; public Type MsgType => message.GetType(); public InsightMessage() { message = new EmptyMessage(); } public InsightMessage(InsightMessage _insightMsg) { status = _insightMsg.status; message = _insightMsg.message; } public InsightMessage(InsightMessageBase _message) { message = _message; } public override void Deserialize(NetworkReader _reader) { base.Deserialize(_reader); callbackId = _reader.ReadInt32(); status = (CallbackStatus) _reader.ReadByte(); var msgType = Type.GetType(_reader.ReadString()); Assert.IsNotNull(msgType); message = (InsightMessageBase) Activator.CreateInstance(msgType); message.Deserialize(_reader); } public override void Serialize(NetworkWriter _writer) { base.Serialize(_writer); _writer.WriteInt32(callbackId); _writer.WriteByte((byte) status); _writer.WriteString(MsgType.FullName); message.Serialize(_writer); } } public class InsightNetworkMessage : InsightMessage { public int connectionId; public InsightNetworkMessage() {} public InsightNetworkMessage(InsightMessageBase _message) : base(_message) {} public InsightNetworkMessage(InsightMessage _insightMsg) : base(_insightMsg) {} } public class EmptyMessage : InsightMessageBase {} #region Spawner public class RegisterSpawnerMsg : InsightMessageBase { public string uniqueId; //Guid public int maxThreads; } public class SpawnerStatusMsg : InsightMessageBase { public string uniqueId; //Guid public int currentThreads; } public abstract class RequestSpawnStartMsg : InsightMessageBase { public string gameUniqueId; //Guid public string networkAddress; public ushort networkPort; public string gameName; public int minPlayers; public int maxPlayers; protected RequestSpawnStartMsg() {} protected RequestSpawnStartMsg(RequestSpawnStartMsg _original) { gameUniqueId = _original.gameUniqueId; networkAddress = _original.networkAddress; networkPort = _original.networkPort; gameName = _original.gameName; minPlayers = _original.minPlayers; maxPlayers = _original.maxPlayers; } } public class RequestSpawnStartToMasterMsg : RequestSpawnStartMsg { public RequestSpawnStartToMasterMsg() {} public RequestSpawnStartToMasterMsg(RequestSpawnStartMsg _original) : base(_original) {} } public class RequestSpawnStartToSpawnerMsg : RequestSpawnStartMsg { public RequestSpawnStartToSpawnerMsg() {} public RequestSpawnStartToSpawnerMsg(RequestSpawnStartMsg _original) : base(_original) {} } public class KillSpawnMsg : InsightMessageBase { public string uniqueId; //Guid } #endregion #region GameManager public class RegisterGameMsg : InsightMessageBase { public string uniqueId; //Guid public string networkAddress; public ushort networkPort; public string gameName; public int minPlayers; public int maxPlayers; public int currentPlayers; } public class RegisterPlayerMsg : InsightMessageBase { public string uniqueId; //Guid } public class ChangeServerMsg : InsightMessageBase { public string uniqueId; public string networkAddress; public ushort networkPort; } public class CreateGameMsg : InsightMessageBase { public string uniqueId; //Guid public string gameName; public int minPlayers; public int maxPlayers; } public class JoinGameMsg : InsightMessageBase { public string uniqueId; //Guid public string gameUniqueId; } public class LeaveGameMsg : InsightMessageBase { public string uniqueId; //Guid } public class GameStatusMsg : InsightMessageBase { public GameContainer game; } public class GameListMsg : InsightMessageBase { public GameContainer[] gamesArray; public void Load(List<GameContainer> _gamesList) { gamesArray = _gamesList.ToArray(); } } public class GameListStatusMsg : InsightMessageBase { public enum Operation { Add, Remove, Update } public Operation operation; public GameContainer game; } #endregion #region Login public class LoginMsg : InsightMessageBase { public string uniqueId; //Guid public string accountName; public string accountPassword; } #endregion #region Chat public class ChatMsg : InsightMessageBase { public string username; public string data; } #endregion #region MatchMaking public class MatchGameMsg : InsightMessageBase { public string uniqueId; //Guid } #endregion }
24.173469
91
0.762769
[ "MIT" ]
PsarTech-Shorii/Insight
Insight/InsightMessage.cs
4,738
C#
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using Microsoft.ML.Data; using Microsoft.ML.Internal.Utilities; using Microsoft.ML.LightGBM; using Microsoft.ML.RunTests; using Microsoft.ML.Trainers.FastTree; using Microsoft.ML.Transforms.Conversions; using Xunit; namespace Microsoft.ML.Tests.TrainerEstimators { public partial class TrainerEstimators : TestDataPipeBase { /// <summary> /// FastTreeBinaryClassification TrainerEstimator test /// </summary> [Fact] public void FastTreeBinaryEstimator() { var (pipe, dataView) = GetBinaryClassificationPipeline(); var trainer = new FastTreeBinaryClassificationTrainer(Env, "Label", "Features", numTrees: 10, numLeaves: 5, advancedSettings: s => { s.NumThreads = 1; }); var pipeWithTrainer = pipe.Append(trainer); TestEstimatorCore(pipeWithTrainer, dataView); var transformedDataView = pipe.Fit(dataView).Transform(dataView); var model = trainer.Train(transformedDataView, transformedDataView); Done(); } [ConditionalFact(typeof(Environment), nameof(Environment.Is64BitProcess))] // LightGBM is 64-bit only public void LightGBMBinaryEstimator() { var (pipe, dataView) = GetBinaryClassificationPipeline(); var trainer = new LightGbmBinaryTrainer(Env, "Label", "Features", advancedSettings: s => { s.NumLeaves = 10; s.NThread = 1; s.MinDataPerLeaf = 2; }); var pipeWithTrainer = pipe.Append(trainer); TestEstimatorCore(pipeWithTrainer, dataView); var transformedDataView = pipe.Fit(dataView).Transform(dataView); var model = trainer.Train(transformedDataView, transformedDataView); Done(); } [Fact] public void GAMClassificationEstimator() { var (pipe, dataView) = GetBinaryClassificationPipeline(); var trainer = new BinaryClassificationGamTrainer(Env, "Label", "Features", advancedSettings: s => { s.GainConfidenceLevel = 0; s.NumIterations = 15; }); var pipeWithTrainer = pipe.Append(trainer); TestEstimatorCore(pipeWithTrainer, dataView); var transformedDataView = pipe.Fit(dataView).Transform(dataView); var model = trainer.Train(transformedDataView, transformedDataView); Done(); } [Fact] public void FastForestClassificationEstimator() { var (pipe, dataView) = GetBinaryClassificationPipeline(); var trainer = new FastForestClassification(Env, "Label", "Features", advancedSettings: s => { s.NumLeaves = 10; s.NumTrees = 20; }); var pipeWithTrainer = pipe.Append(trainer); TestEstimatorCore(pipeWithTrainer, dataView); var transformedDataView = pipe.Fit(dataView).Transform(dataView); var model = trainer.Train(transformedDataView, transformedDataView); Done(); } /// <summary> /// FastTreeRankingTrainer TrainerEstimator test /// </summary> [Fact] public void FastTreeRankerEstimator() { var (pipe, dataView) = GetRankingPipeline(); var trainer = new FastTreeRankingTrainer(Env, "Label0", "NumericFeatures", "Group", advancedSettings: s => { s.NumTrees = 10; }); var pipeWithTrainer = pipe.Append(trainer); TestEstimatorCore(pipeWithTrainer, dataView); var transformedDataView = pipe.Fit(dataView).Transform(dataView); var model = trainer.Train(transformedDataView, transformedDataView); Done(); } /// <summary> /// LightGbmRankingTrainer TrainerEstimator test /// </summary> [ConditionalFact(typeof(Environment), nameof(Environment.Is64BitProcess))] // LightGBM is 64-bit only public void LightGBMRankerEstimator() { var (pipe, dataView) = GetRankingPipeline(); var trainer = new LightGbmRankingTrainer(Env, "Label0", "NumericFeatures", "Group", advancedSettings: s => { s.LearningRate = 0.4; }); var pipeWithTrainer = pipe.Append(trainer); TestEstimatorCore(pipeWithTrainer, dataView); var transformedDataView = pipe.Fit(dataView).Transform(dataView); var model = trainer.Train(transformedDataView, transformedDataView); Done(); } /// <summary> /// FastTreeRegressor TrainerEstimator test /// </summary> [Fact] public void FastTreeRegressorEstimator() { var dataView = GetRegressionPipeline(); var trainer = new FastTreeRegressionTrainer(Env, "Label", "Features", advancedSettings: s => { s.NumTrees = 10; s.NumThreads = 1; s.NumLeaves = 5; }); TestEstimatorCore(trainer, dataView); var model = trainer.Train(dataView, dataView); Done(); } /// <summary> /// LightGbmRegressorTrainer TrainerEstimator test /// </summary> [ConditionalFact(typeof(Environment), nameof(Environment.Is64BitProcess))] // LightGBM is 64-bit only public void LightGBMRegressorEstimator() { var dataView = GetRegressionPipeline(); var trainer = new LightGbmRegressorTrainer(Env, "Label", "Features", advancedSettings: s => { s.NThread = 1; s.NormalizeFeatures = NormalizeOption.Warn; s.CatL2 = 5; }); TestEstimatorCore(trainer, dataView); var model = trainer.Train(dataView, dataView); Done(); } /// <summary> /// RegressionGamTrainer TrainerEstimator test /// </summary> [Fact] public void GAMRegressorEstimator() { var dataView = GetRegressionPipeline(); var trainer = new RegressionGamTrainer(Env, "Label", "Features", advancedSettings: s => { s.EnablePruning = false; s.NumIterations = 15; }); TestEstimatorCore(trainer, dataView); var model = trainer.Train(dataView, dataView); Done(); } /// <summary> /// FastTreeTweedieTrainer TrainerEstimator test /// </summary> [Fact] public void TweedieRegressorEstimator() { var dataView = GetRegressionPipeline(); var trainer = new FastTreeTweedieTrainer(Env, "Label", "Features", advancedSettings: s => { s.EntropyCoefficient = 0.3; s.OptimizationAlgorithm = BoostedTreeArgs.OptimizationAlgorithmType.AcceleratedGradientDescent; }); TestEstimatorCore(trainer, dataView); var model = trainer.Train(dataView, dataView); Done(); } /// <summary> /// FastForestRegression TrainerEstimator test /// </summary> [Fact] public void FastForestRegressorEstimator() { var dataView = GetRegressionPipeline(); var trainer = new FastForestRegression(Env, "Label", "Features", advancedSettings: s => { s.BaggingSize = 2; s.NumTrees = 10; }); TestEstimatorCore(trainer, dataView); var model = trainer.Train(dataView, dataView); Done(); } /// <summary> /// LightGbmMulticlass TrainerEstimator test /// </summary> [ConditionalFact(typeof(Environment), nameof(Environment.Is64BitProcess))] // LightGBM is 64-bit only public void LightGbmMultiClassEstimator() { var (pipeline, dataView) = GetMultiClassPipeline(); var trainer = new LightGbmMulticlassTrainer(Env, "Label", "Features", advancedSettings: s => { s.LearningRate = 0.4; }); var pipe = pipeline.Append(trainer) .Append(new KeyToValueMappingEstimator(Env, "PredictedLabel")); TestEstimatorCore(pipe, dataView); Done(); } // Number of examples private const int _rowNumber = 1000; // Number of features private const int _columnNumber = 5; // Number of classes private const int _classNumber = 3; private class GbmExample { [VectorType(_columnNumber)] public float[] Features; [KeyType(Contiguous = true, Count =_classNumber, Min = 0)] public uint Label; [VectorType(_classNumber)] public float[] Score; } private void LightGbmHelper(bool useSoftmax, out string modelString, out List<GbmExample> mlnetPredictions, out double[] lgbmRawScores, out double[] lgbmProbabilities) { // Prepare data and train LightGBM model via ML.NET // Training matrix. It contains all feature vectors. var dataMatrix = new float[_rowNumber * _columnNumber]; // Labels for multi-class classification var labels = new uint[_rowNumber]; // Training list, which is equivalent to the training matrix above. var dataList = new List<GbmExample>(); for (/*row index*/ int i = 0; i < _rowNumber; ++i) { int featureSum = 0; var featureVector = new float[_columnNumber]; for (/*column index*/ int j = 0; j < _columnNumber; ++j) { int featureValue = (j + i * _columnNumber) % 10; featureSum += featureValue; dataMatrix[j + i * _columnNumber] = featureValue; featureVector[j] = featureValue; } labels[i] = (uint)featureSum % _classNumber; dataList.Add(new GbmExample { Features = featureVector, Label = labels[i], Score = new float[_classNumber] }); } var mlContext = new MLContext(seed: 0, conc: 1); var dataView = ComponentCreation.CreateDataView(mlContext, dataList); int numberOfTrainingIterations = 3; var gbmTrainer = new LightGbmMulticlassTrainer(mlContext, labelColumn: "Label", featureColumn: "Features", numBoostRound: numberOfTrainingIterations, advancedSettings: s => { s.MinDataPerGroup = 1; s.MinDataPerLeaf = 1; s.UseSoftmax = useSoftmax; }); var gbm = gbmTrainer.Fit(dataView); var predicted = gbm.Transform(dataView); mlnetPredictions = new List<GbmExample>(predicted.AsEnumerable<GbmExample>(mlContext, false)); // Convert training to LightGBM's native format and train LightGBM model via its APIs // Convert the whole training matrix to CSC format required by LightGBM interface. Notice that the training matrix // is dense so this conversion is simply a matrix transpose. double[][] sampleValueGroupedByColumn = new double[_columnNumber][]; int[][] sampleIndicesGroupedByColumn = new int[_columnNumber][]; int[] sampleNonZeroCntPerColumn = new int[_columnNumber]; for (int j = 0; j < _columnNumber; ++j) { // Allocate memory for the j-th column in the training matrix sampleValueGroupedByColumn[j] = new double[_rowNumber]; sampleIndicesGroupedByColumn[j] = new int[_rowNumber]; sampleNonZeroCntPerColumn[j] = _rowNumber; // Copy the j-th column in training matrix for (int i = 0; i < _rowNumber; ++i) { // data[j + i * _columnNumber] is the value at the j-th column and the i-th row. sampleValueGroupedByColumn[j][i] = dataMatrix[j + i * _columnNumber]; // Row index of the assigned value. sampleIndicesGroupedByColumn[j][i] = i; } } // LightGBM only accepts float labels. float[] floatLabels = new float[_rowNumber]; for (int i = 0; i < _rowNumber; ++i) floatLabels[i] = labels[i]; // Allocate LightGBM data container (called Dataset in LightGBM world). var gbmDataSet = new Dataset(sampleValueGroupedByColumn, sampleIndicesGroupedByColumn, _columnNumber, sampleNonZeroCntPerColumn, _rowNumber, _rowNumber, "", floatLabels); // Push training examples into LightGBM data container. gbmDataSet.PushRows(dataMatrix, _rowNumber, _columnNumber, 0); // Probability output. lgbmProbabilities = new double[_rowNumber * _classNumber]; // Raw score. lgbmRawScores = new double[_rowNumber * _classNumber]; // Get parameters used in ML.NET's LightGBM var gbmParams = gbmTrainer.GetGbmParameters(); // Call LightGBM C-style APIs to do prediction. modelString = null; using (var ch = (mlContext as IChannelProvider).Start("Training LightGBM...")) using (var pch = (mlContext as IProgressChannelProvider).StartProgressChannel("Training LightGBM...")) { var host = (mlContext as IHostEnvironment).Register("Training LightGBM..."); var gbmNative = WrappedLightGbmTraining.Train(ch, pch, gbmParams, gbmDataSet, numIteration : numberOfTrainingIterations); int nativeLength = 0; unsafe { fixed (float* data = dataMatrix) fixed (double* result0 = lgbmProbabilities) fixed (double* result1 = lgbmRawScores) { WrappedLightGbmInterface.BoosterPredictForMat(gbmNative.Handle, (IntPtr)data, WrappedLightGbmInterface.CApiDType.Float32, _rowNumber, _columnNumber, 1, (int)WrappedLightGbmInterface.CApiPredictType.Normal, numberOfTrainingIterations, "", ref nativeLength, result0); WrappedLightGbmInterface.BoosterPredictForMat(gbmNative.Handle, (IntPtr)data, WrappedLightGbmInterface.CApiDType.Float32, _rowNumber, _columnNumber, 1, (int)WrappedLightGbmInterface.CApiPredictType.Raw, numberOfTrainingIterations, "", ref nativeLength, result1); } modelString = gbmNative.GetModelString(); } } } [ConditionalFact(typeof(Environment), nameof(Environment.Is64BitProcess))] // LightGBM is 64-bit only public void LightGbmMultiClassEstimatorCompareOva() { // Train ML.NET LightGBM and native LightGBM and apply the trained models to the training set. LightGbmHelper(useSoftmax: false, out string modelString, out List<GbmExample> mlnetPredictions, out double[] nativeResult1, out double[] nativeResult0); // The i-th predictor returned by LightGBM produces the raw score, denoted by z_i, of the i-th class. // Assume that we have n classes in total. The i-th class probability can be computed via // p_i = sigmoid(sigmoidScale * z_i) / (sigmoid(sigmoidScale * z_1) + ... + sigmoid(sigmoidScale * z_n)). Assert.True(modelString != null); float sigmoidScale = 0.5f; // Constant used train LightGBM. See gbmParams["sigmoid"] in the helper function. // Compare native LightGBM's and ML.NET's LightGBM results example by example for (int i = 0; i < _rowNumber; ++i) { double sum = 0; for (int j = 0; j < _classNumber; ++j) { Assert.Equal(nativeResult0[j + i * _classNumber], mlnetPredictions[i].Score[j], 6); sum += MathUtils.SigmoidSlow(sigmoidScale* (float)nativeResult1[j + i * _classNumber]); } for (int j = 0; j < _classNumber; ++j) { double prob = MathUtils.SigmoidSlow(sigmoidScale * (float)nativeResult1[j + i * _classNumber]); Assert.Equal(prob / sum, mlnetPredictions[i].Score[j], 6); } } Done(); } [ConditionalFact(typeof(Environment), nameof(Environment.Is64BitProcess))] // LightGBM is 64-bit only public void LightGbmMultiClassEstimatorCompareSoftMax() { // Train ML.NET LightGBM and native LightGBM and apply the trained models to the training set. LightGbmHelper(useSoftmax: true, out string modelString, out List<GbmExample> mlnetPredictions, out double[] nativeResult1, out double[] nativeResult0); // The i-th predictor returned by LightGBM produces the raw score, denoted by z_i, of the i-th class. // Assume that we have n classes in total. The i-th class probability can be computed via // p_i = exp(z_i) / (exp(z_1) + ... + exp(z_n)). Assert.True(modelString != null); // Compare native LightGBM's and ML.NET's LightGBM results example by example for (int i = 0; i < _rowNumber; ++i) { double sum = 0; for (int j = 0; j < _classNumber; ++j) { Assert.Equal(nativeResult0[j + i * _classNumber], mlnetPredictions[i].Score[j], 6); sum += Math.Exp((float)nativeResult1[j + i * _classNumber]); } for (int j = 0; j < _classNumber; ++j) { double prob = Math.Exp(nativeResult1[j + i * _classNumber]); Assert.Equal(prob / sum, mlnetPredictions[i].Score[j], 6); } } Done(); } } }
44.676329
182
0.585262
[ "MIT" ]
mnboos/machinelearning
test/Microsoft.ML.Tests/TrainerEstimators/TreeEstimators.cs
18,496
C#
/* * Copyright (c) Contributors, http://virtual-planets.org/ * See CONTRIBUTORS.TXT for a full list of copyright holders. * For an explanation of the license of each contributor and the content it * covers please see the Licenses directory. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the Virtual Universe Project nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ using System; using System.Collections.Generic; using System.Net; using OpenMetaverse; using Universe.Framework.PresenceInfo; namespace Universe.Framework.SceneInfo { /// <summary> /// Maps from client AgentID and RemoteEndPoint values to IClientAPI /// references for all of the connected clients /// </summary> public class ClientManager { /// <summary> /// A dictionary mapping from <seealso cref="UUID" /> /// to <seealso cref="IClientAPI" /> references /// </summary> readonly Dictionary<UUID, IClientAPI> m_dict1; /// <summary> /// A dictionary mapping from <seealso cref="IPEndPoint" /> /// to <seealso cref="IClientAPI" /> references /// </summary> readonly Dictionary<IPEndPoint, IClientAPI> m_dict2; /// <summary> /// Synchronization object for writing to the collections /// </summary> readonly object m_syncRoot = new object (); /// <summary> /// An immutable collection of <seealso cref="IClientAPI" /> /// references /// </summary> IClientAPI [] m_array; /// <summary> /// Default constructor /// </summary> public ClientManager () { m_dict1 = new Dictionary<UUID, IClientAPI> (); m_dict2 = new Dictionary<IPEndPoint, IClientAPI> (); m_array = new IClientAPI [0]; } /// <summary> /// Number of clients in the collection /// </summary> public int Count { get { return m_dict1.Count; } } /// <summary> /// Add a client reference to the collection if it does not already /// exist /// </summary> /// <param name="value">Reference to the client object</param> /// <returns> /// True if the client reference was successfully added, /// otherwise false if the given key already existed in the collection /// </returns> public bool Add (IClientAPI value) { lock (m_syncRoot) { if (m_dict1.ContainsKey (value.AgentId) || m_dict2.ContainsKey (value.RemoteEndPoint)) return false; m_dict1 [value.AgentId] = value; m_dict2 [value.RemoteEndPoint] = value; IClientAPI [] oldArray = m_array; int oldLength = oldArray.Length; IClientAPI [] newArray = new IClientAPI [oldLength + 1]; for (int i = 0; i < oldLength; i++) newArray [i] = oldArray [i]; newArray [oldLength] = value; m_array = newArray; } return true; } /// <summary> /// Remove a client from the collection /// </summary> /// <param name="key">UUID of the client to remove</param> /// <returns> /// True if a client was removed, or false if the given UUID /// was not present in the collection /// </returns> public bool Remove (UUID key) { lock (m_syncRoot) { IClientAPI value; if (m_dict1.TryGetValue (key, out value)) { m_dict1.Remove (key); m_dict2.Remove (value.RemoteEndPoint); IClientAPI [] oldArray = m_array; int oldLength = oldArray.Length; IClientAPI [] newArray = new IClientAPI [oldLength - 1]; int j = 0; for (int i = 0; i < oldLength; i++) { if (oldArray [i] != value) newArray [j++] = oldArray [i]; } m_array = newArray; return true; } } return false; } /// <summary> /// Resets the client collection /// </summary> public void Clear () { lock (m_syncRoot) { m_dict1.Clear (); m_dict2.Clear (); m_array = new IClientAPI [0]; } } /// <summary> /// Checks if a UUID is in the collection /// </summary> /// <param name="key">UUID to check for</param> /// <returns>True if the UUID was found in the collection, otherwise false</returns> public bool ContainsKey (UUID key) { return m_dict1.ContainsKey (key); } /// <summary> /// Checks if an endpoint is in the collection /// </summary> /// <param name="key">Endpoint to check for</param> /// <returns>True if the endpoint was found in the collection, otherwise false</returns> public bool ContainsKey (IPEndPoint key) { return m_dict2.ContainsKey (key); } /// <summary> /// Attempts to fetch a value out of the collection /// </summary> /// <param name="key">UUID of the client to retrieve</param> /// <param name="value">Retrieved client, or null on lookup failure</param> /// <returns>True if the lookup succeeded, otherwise false</returns> public bool TryGetValue (UUID key, out IClientAPI value) { try { return m_dict1.TryGetValue (key, out value); } catch (Exception) { value = null; return false; } } /// <summary> /// Attempts to fetch a value out of the collection /// </summary> /// <param name="key">Endpoint of the client to retrieve</param> /// <param name="value">Retrieved client, or null on lookup failure</param> /// <returns>True if the lookup succeeded, otherwise false</returns> public bool TryGetValue (IPEndPoint key, out IClientAPI value) { try { return m_dict2.TryGetValue (key, out value); } catch (Exception) { value = null; return false; } } /// <summary> /// Performs a given task in parallel for each of the elements in the /// collection /// </summary> /// <param name="action">Action to perform on each element</param> public void ForEach (Action<IClientAPI> action) { IClientAPI [] localArray; lock (m_syncRoot) localArray = m_array; Parallel.For (0, localArray.Length, i => action (localArray [i])); } /// <summary> /// Performs a given task synchronously for each of the elements in /// the collection /// </summary> /// <param name="action">Action to perform on each element</param> public void ForEachSync (Action<IClientAPI> action) { IClientAPI [] localArray; lock (m_syncRoot) localArray = m_array; foreach (IClientAPI t in localArray) action (t); } } }
38.107438
103
0.543917
[ "MIT" ]
johnfelipe/Virtual-Universe
Universe/Framework/SceneInfo/ClientManager.cs
9,222
C#
namespace Nacos { using System.Threading; public class Listener { public Listener(string name, Timer timer) { this.Name = name; this.Timer = timer; } public string Name { get; private set; } public Timer Timer { get; set; } } }
17.333333
49
0.525641
[ "Apache-2.0" ]
coldhighsun/nacos-sdk-csharp
src/Nacos/Config/Core/Listener.cs
314
C#
using System; using Newtonsoft.Json.Linq; namespace Stripe.Infrastructure { internal static class StringOrObject<T> where T : StripeEntityWithId { public static void Map(object value, Action<string> updateId, Action<T> updateObject) { if (value is JObject) { T item = ((JToken) value).ToObject<T>(); updateId(item.Id); updateObject(item); } else if (value is string) { updateId((string) value); updateObject(null); } } } }
25.541667
93
0.513866
[ "Apache-2.0" ]
TrueNorthIT/stripe-dotnet
src/Stripe.net/Infrastructure/StringOrObject.cs
615
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("CodeCamper.Model")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("CodeCamper.Model")] [assembly: AssemblyCopyright("Copyright © 2012")] [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("d5787f29-17b0-440a-b66e-7b17c4892033")] // 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.916667
85
0.723055
[ "MIT" ]
kushan2018/CodeCamper
CodeCamper.Model/Properties/AssemblyInfo.cs
1,404
C#
using Microsoft.AspNetCore.Mvc; using System.Threading.Tasks; using Vic.Api.Helpers.Mail; using Vic.Api.Models.Contact; namespace Vic.Api.Controllers { /// <summary> /// ContactController class, provides a controller for contact endpoints. /// </summary> [ApiController] [Route("[controller]")] public class ContactController : ControllerBase { #region Variables private readonly IMailHelper _mail; #endregion #region Constructors /// <summary> /// Creates a new instance of a ContactController object, initializes with specified arguments. /// </summary> /// <param name="mail"></param> public ContactController(IMailHelper mail) { _mail = mail; } #endregion #region Endpoints /// <summary> /// Send an email to the contact us address. /// </summary> /// <returns></returns> [HttpPost()] public async Task<IActionResult> SubmitAsync(ContactModel model) { await _mail.SendEmailAsync(_mail.Options.ContactEmail, model.Subject, $"<p>{model.FirstName} {model.LastName} {model.Email}</p><div>{model.Body}</div>"); return new JsonResult(new { Success = true }); } #endregion } }
30.045455
165
0.606657
[ "MIT" ]
FosolSolutions/vic-api
src/Controllers/ContactController.cs
1,324
C#
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Threading.Tasks; using Statiq.Common; namespace Statiq.Common { public static class IDocumentCloneExtensions { /// <summary> /// Clones this document. /// </summary> /// <param name="document">The document.</param> /// <param name="destination">The new destination or <c>null</c> to keep the existing destination.</param> /// <param name="items">New metadata items.</param> /// <param name="contentProvider">The new content provider or <c>null</c> to keep the existing content provider.</param> /// <returns>A new document of the same type as this document.</returns> public static IDocument Clone( this IDocument document, in NormalizedPath destination, IEnumerable<KeyValuePair<string, object>> items, IContentProvider contentProvider = null) => document.Clone(null, destination, items, contentProvider); /// <summary> /// Clones this document. /// </summary> /// <param name="document">The document.</param> /// <param name="source">The new source. If this document already contains a source, then it's used and this is ignored.</param> /// <param name="destination">The new destination or <c>null</c> to keep the existing destination.</param> /// <param name="contentProvider">The new content provider or <c>null</c> to keep the existing content provider.</param> /// <returns>A new document of the same type as this document.</returns> public static IDocument Clone( this IDocument document, in NormalizedPath source, in NormalizedPath destination, IContentProvider contentProvider = null) => document.Clone(source, destination, null, contentProvider); /// <summary> /// Clones this document. /// </summary> /// <param name="document">The document.</param> /// <param name="destination">The new destination or <c>null</c> to keep the existing destination.</param> /// <param name="contentProvider">The new content provider or <c>null</c> to keep the existing content provider.</param> /// <returns>A new document of the same type as this document.</returns> public static IDocument Clone( this IDocument document, in NormalizedPath destination, IContentProvider contentProvider = null) => document.Clone(null, destination, null, contentProvider); /// <summary> /// Clones this document. /// </summary> /// <param name="document">The document.</param> /// <param name="items">New metadata items or <c>null</c> not to add any new metadata.</param> /// <param name="contentProvider">The new content provider or <c>null</c> to keep the existing content provider.</param> /// <returns>A new document of the same type as this document.</returns> public static IDocument Clone( this IDocument document, IEnumerable<KeyValuePair<string, object>> items, IContentProvider contentProvider = null) => document.Clone(null, null, items, contentProvider); /// <summary> /// Clones this document. /// </summary> /// <param name="document">The document.</param> /// <param name="contentProvider">The new content provider or <c>null</c> to keep the existing content provider.</param> /// <returns>A new document of the same type as this document.</returns> public static IDocument Clone( this IDocument document, IContentProvider contentProvider) => document.Clone(null, null, null, contentProvider); // Stream /// <summary> /// Clones this document. /// </summary> /// <param name="document">The document.</param> /// <param name="destination">The new destination or <c>null</c> to keep the existing destination.</param> /// <param name="items">New metadata items.</param> /// <param name="stream">A stream that contains the new content.</param> /// <param name="mediaType">The media type of the content.</param> /// <returns>A new document of the same type as this document.</returns> public static IDocument Clone( this IDocument document, in NormalizedPath destination, IEnumerable<KeyValuePair<string, object>> items, Stream stream, string mediaType = null) => document.Clone(null, destination, items, IExecutionContext.Current.GetContentProvider(stream, mediaType)); /// <summary> /// Clones this document. /// </summary> /// <param name="document">The document.</param> /// <param name="source">The new source. If this document already contains a source, then it's used and this is ignored.</param> /// <param name="destination">The new destination or <c>null</c> to keep the existing destination.</param> /// <param name="stream">A stream that contains the new content.</param> /// <param name="mediaType">The media type of the content.</param> /// <returns>A new document of the same type as this document.</returns> public static IDocument Clone( this IDocument document, in NormalizedPath source, in NormalizedPath destination, Stream stream, string mediaType = null) => document.Clone(source, destination, null, IExecutionContext.Current.GetContentProvider(stream, mediaType)); /// <summary> /// Clones this document. /// </summary> /// <param name="document">The document.</param> /// <param name="destination">The new destination or <c>null</c> to keep the existing destination.</param> /// <param name="stream">A stream that contains the new content.</param> /// <param name="mediaType">The media type of the content.</param> /// <returns>A new document of the same type as this document.</returns> public static IDocument Clone( this IDocument document, in NormalizedPath destination, Stream stream, string mediaType = null) => document.Clone(null, destination, null, IExecutionContext.Current.GetContentProvider(stream, mediaType)); /// <summary> /// Clones this document. /// </summary> /// <param name="document">The document.</param> /// <param name="items">New metadata items or <c>null</c> not to add any new metadata.</param> /// <param name="stream">A stream that contains the new content.</param> /// <param name="mediaType">The media type of the content.</param> /// <returns>A new document of the same type as this document.</returns> public static IDocument Clone( this IDocument document, IEnumerable<KeyValuePair<string, object>> items, Stream stream, string mediaType = null) => document.Clone(null, null, items, IExecutionContext.Current.GetContentProvider(stream, mediaType)); /// <summary> /// Clones this document. /// </summary> /// <param name="document">The document.</param> /// <param name="stream">A stream that contains the new content.</param> /// <param name="mediaType">The media type of the content.</param> /// <returns>A new document of the same type as this document.</returns> public static IDocument Clone( this IDocument document, Stream stream, string mediaType = null) => document.Clone(null, null, null, IExecutionContext.Current.GetContentProvider(stream, mediaType)); // String /// <summary> /// Clones this document. /// </summary> /// <param name="document">The document.</param> /// <param name="destination">The new destination or <c>null</c> to keep the existing destination.</param> /// <param name="items">New metadata items.</param> /// <param name="content">The new content.</param> /// <param name="mediaType">The media type of the content.</param> /// <returns>A new document of the same type as this document.</returns> public static IDocument Clone( this IDocument document, NormalizedPath destination, IEnumerable<KeyValuePair<string, object>> items, string content, string mediaType = null) => document.Clone(null, destination, items, IExecutionContext.Current.GetContentProvider(content, mediaType)); /// <summary> /// Clones this document. /// </summary> /// <param name="document">The document.</param> /// <param name="source">The new source. If this document already contains a source, then it's used and this is ignored.</param> /// <param name="destination">The new destination or <c>null</c> to keep the existing destination.</param> /// <param name="content">The new content.</param> /// <param name="mediaType">The media type of the content.</param> /// <returns>A new document of the same type as this document.</returns> public static IDocument Clone( this IDocument document, NormalizedPath source, NormalizedPath destination, string content, string mediaType = null) => document.Clone(source, destination, null, IExecutionContext.Current.GetContentProvider(content, mediaType)); /// <summary> /// Clones this document. /// </summary> /// <param name="document">The document.</param> /// <param name="destination">The new destination or <c>null</c> to keep the existing destination.</param> /// <param name="content">The new content.</param> /// <param name="mediaType">The media type of the content.</param> /// <returns>A new document of the same type as this document.</returns> public static IDocument Clone( this IDocument document, NormalizedPath destination, string content, string mediaType = null) => document.Clone(null, destination, null, IExecutionContext.Current.GetContentProvider(content, mediaType)); /// <summary> /// Clones this document. /// </summary> /// <param name="document">The document.</param> /// <param name="items">New metadata items or <c>null</c> not to add any new metadata.</param> /// <param name="content">The new content.</param> /// <param name="mediaType">The media type of the content.</param> /// <returns>A new document of the same type as this document.</returns> public static IDocument Clone( this IDocument document, IEnumerable<KeyValuePair<string, object>> items, string content, string mediaType = null) => document.Clone(null, null, items, IExecutionContext.Current.GetContentProvider(content, mediaType)); /// <summary> /// Clones this document. /// </summary> /// <param name="document">The document.</param> /// <param name="content">The new content.</param> /// <param name="mediaType">The media type of the content.</param> /// <returns>A new document of the same type as this document.</returns> public static IDocument Clone( this IDocument document, string content, string mediaType = null) => document.Clone(null, null, null, IExecutionContext.Current.GetContentProvider(content, mediaType)); } }
50.466387
136
0.618017
[ "MIT" ]
JoshClose/Statiq.Framework
src/core/Statiq.Common/Documents/IDocumentCloneExtensions.cs
12,013
C#
#pragma checksum "C:\Users\darko\Desktop\NBPpr\recipe-blog\PronadjiRecept\PronadjiRecept\Views\_ViewStart.cshtml" "{ff1816ec-aa5e-4d10-87f7-6f4963833460}" "a4bc9cb4a1d11f0c28a746ed054b4cb82c25e233" // <auto-generated/> #pragma warning disable 1591 [assembly: global::Microsoft.AspNetCore.Razor.Hosting.RazorCompiledItemAttribute(typeof(AspNetCore.Views__ViewStart), @"mvc.1.0.view", @"/Views/_ViewStart.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; [global::Microsoft.AspNetCore.Razor.Hosting.RazorSourceChecksumAttribute(@"SHA1", @"a4bc9cb4a1d11f0c28a746ed054b4cb82c25e233", @"/Views/_ViewStart.cshtml")] public class Views__ViewStart : global::Microsoft.AspNetCore.Mvc.Razor.RazorPage<dynamic> { #pragma warning disable 1998 public async override global::System.Threading.Tasks.Task ExecuteAsync() { #nullable restore #line 1 "C:\Users\darko\Desktop\NBPpr\recipe-blog\PronadjiRecept\PronadjiRecept\Views\_ViewStart.cshtml" Layout = "~/Views/Shared/_Layout.cshtml"; #line default #line hidden #nullable disable } #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<dynamic> Html { get; private set; } } } #pragma warning restore 1591
52.363636
197
0.760417
[ "MIT" ]
JovanMarkovic99/recipe-blog
PronadjiRecept/PronadjiRecept/obj/Debug/netcoreapp3.1/Razor/Views/_ViewStart.cshtml.g.cs
2,304
C#
#region Copyright(c) Carlos Segura Sanz, All right reserved. // ----------------------------------------------------------------------------- // Copyright(c) 2008-2009 Carlos Segura Sanz, All right reserved. // // csegura@ideseg.com // http://www.ideseg.com // // * Attribution. You must attribute the work in the manner specified by the author or // licensor (but not in any way that suggests that they endorse you or your use of the // work). // // * Noncommercial. You may not use this work for commercial purposes. // // * No Derivative Works. You may not alter, transform, or build upon this work without // author authorization // * For any reuse or distribution, you must make clear to others the license terms of this work. The best way to do this is contact with author. // * Any of the above conditions can be waived if you get permission from the copyright // holder. // * Nothing in this license impairs or restricts the author's moral rights. // // THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED // WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF // MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO // EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF // THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // ----------------------------------------------------------------------------- #endregion namespace IdeSeg.SharePoint.Caml.QueryParser.AST.Base { public class FieldList : ASTNode { public FieldList(FieldNode fieldLeft, FieldList fields) : base(fieldLeft, fields) { } public FieldList(FieldNode fieldLeft) : base(fieldLeft, null) { } } }
45.020408
159
0.641886
[ "MIT" ]
csegura/YACAMLQP
IdeSeg.SharePoint.Caml.QueryParser/AST/Base/FieldList.cs
2,208
C#
using System.ComponentModel.DataAnnotations; using System.Runtime.Serialization; using Lykke.Service.EthereumCore.Core; namespace Lykke.Service.EthereumCore.Models.Models { public class GasPriceModel { [Required] [RegularExpression(Constants.BigIntTemplate)] public string Max { get; set; } [Required] [RegularExpression(Constants.BigIntTemplate)] public string Min { get; set; } } }
26.235294
53
0.697309
[ "MIT" ]
JTOne123/EthereumApiDotNetCore
src/Lykke.Service.EthereumCore..Models/Models/GasPriceModel.cs
448
C#
using System; using System.Collections.Generic; using System.Data.Entity; using System.Linq; using System.Web; using System.Web.Http; using System.Web.Mvc; using System.Web.Optimization; using System.Web.Routing; namespace JiraCloneMVC.Web { public class MvcApplication : System.Web.HttpApplication { protected void Application_Start() { GlobalConfiguration.Configure(WebApiConfig.Register); AreaRegistration.RegisterAllAreas(); FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters); RouteConfig.RegisterRoutes(RouteTable.Routes); BundleConfig.RegisterBundles(BundleTable.Bundles); Database.SetInitializer(new DropCreateDatabaseIfModelChanges<ApplicationDbContext>()); } } }
30.346154
98
0.723701
[ "MIT" ]
CrazyLlama98/JiraCloneMVC
JiraCloneMVC.Web/Global.asax.cs
791
C#
// <auto-generated> // Code generated by Microsoft (R) AutoRest Code Generator. // Changes may cause incorrect behavior and will be lost if the code is // regenerated. // </auto-generated> namespace Kmd.Logic.Cpr.Client.Models { using Newtonsoft.Json; using System.Linq; public partial class ExperianProviderConfigurationResponse { /// <summary> /// Initializes a new instance of the /// ExperianProviderConfigurationResponse class. /// </summary> public ExperianProviderConfigurationResponse() { CustomInit(); } /// <summary> /// Initializes a new instance of the /// ExperianProviderConfigurationResponse class. /// </summary> public ExperianProviderConfigurationResponse(System.Guid? id = default(System.Guid?), System.Guid? subscriptionId = default(System.Guid?), string name = default(string), string environment = default(string), string callbackUrl = default(string), bool? isApproved = default(bool?)) { Id = id; SubscriptionId = subscriptionId; Name = name; Environment = environment; CallbackUrl = callbackUrl; IsApproved = isApproved; CustomInit(); } /// <summary> /// An initialization method that performs custom operations like setting defaults /// </summary> partial void CustomInit(); /// <summary> /// </summary> [JsonProperty(PropertyName = "id")] public System.Guid? Id { get; set; } /// <summary> /// </summary> [JsonProperty(PropertyName = "subscriptionId")] public System.Guid? SubscriptionId { get; set; } /// <summary> /// </summary> [JsonProperty(PropertyName = "name")] public string Name { get; set; } /// <summary> /// </summary> [JsonProperty(PropertyName = "environment")] public string Environment { get; set; } /// <summary> /// </summary> [JsonProperty(PropertyName = "callbackUrl")] public string CallbackUrl { get; set; } /// <summary> /// </summary> [JsonProperty(PropertyName = "isApproved")] public bool? IsApproved { get; set; } } }
31.133333
288
0.585011
[ "MIT" ]
deviprasad-kmd/kmd-logic-cpr-client
src/Kmd.Logic.Cpr.Client/Models/ExperianProviderConfigurationResponse.cs
2,335
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 mediapackage-2017-10-12.normal.json service model. */ using System; using System.Collections.Generic; using System.Xml.Serialization; using System.Text; using System.IO; using System.Net; using Amazon.Runtime; using Amazon.Runtime.Internal; namespace Amazon.MediaPackage.Model { /// <summary> /// This is the response object from the TagResource operation. /// </summary> public partial class TagResourceResponse : AmazonWebServiceResponse { } }
29.605263
110
0.734222
[ "Apache-2.0" ]
DetlefGolze/aws-sdk-net
sdk/src/Services/MediaPackage/Generated/Model/TagResourceResponse.cs
1,125
C#
using System; using System.Collections.Generic; using System.Linq; using System.Windows.Forms; namespace QRCoderDemo { static class Program { /// <summary> /// Der Haupteinstiegspunkt für die Anwendung. /// </summary> [STAThread] static void Main() { Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); //Application.Run(new Form1()); Application.Run(new Form1()); } } }
22.826087
65
0.594286
[ "MIT" ]
0x7d9/QRCoder
QRCoderDemo/Program.cs
528
C#
using UnityEngine; using System.Collections; public class RecordPlayer : MonoBehaviour { //-------------------------------------------------------------------------------------------- //-------------------------------------------------------------------------------------------- //-------------------------------------------------------------------------------------------- public bool recordPlayerActive = false; GameObject disc; GameObject arm; int mode; float armAngle; float discAngle; float discSpeed; //-------------------------------------------------------------------------------------------- //-------------------------------------------------------------------------------------------- //-------------------------------------------------------------------------------------------- void Awake() { disc = gameObject.transform.Find("teller").gameObject; arm = gameObject.transform.Find("arm").gameObject; } //-------------------------------------------------------------------------------------------- //-------------------------------------------------------------------------------------------- //-------------------------------------------------------------------------------------------- void Start() { mode = 0; armAngle = 0.0f; discAngle = 0.0f; discSpeed = 0.0f; } //-------------------------------------------------------------------------------------------- //-------------------------------------------------------------------------------------------- //-------------------------------------------------------------------------------------------- void Update() { //-- Mode 0: player off if(mode == 0) { if(recordPlayerActive == true) mode = 1; } //-- Mode 1: activation else if(mode == 1) { if(recordPlayerActive == true) { armAngle += Time.deltaTime * 30.0f; if(armAngle >= 30.0f) { armAngle = 30.0f; mode = 2; } discAngle += Time.deltaTime * discSpeed; discSpeed += Time.deltaTime * 80.0f; } else mode = 3; } //-- Mode 2: running else if(mode == 2) { if(recordPlayerActive == true) discAngle += Time.deltaTime * discSpeed; else mode = 3; } //-- Mode 3: stopping else { if(recordPlayerActive == false) { armAngle -= Time.deltaTime * 30.0f; if(armAngle <= 0.0f) armAngle = 0.0f; discAngle += Time.deltaTime * discSpeed; discSpeed -= Time.deltaTime * 80.0f; if(discSpeed <= 0.0f) discSpeed = 0.0f; if((discSpeed == 0.0f) && (armAngle == 0.0f)) mode = 0; } else mode = 1; } //-- update objects arm.transform.localEulerAngles = new Vector3(0.0f, armAngle, 0.0f); disc.transform.localEulerAngles = new Vector3(0.0f, discAngle, 0.0f); } //-------------------------------------------------------------------------------------------- //-------------------------------------------------------------------------------------------- //-------------------------------------------------------------------------------------------- }
32.823529
94
0.290621
[ "Apache-2.0" ]
anthonywong555/Vector-Google-Daydream
unity/PersonalProject/Assets/Record_player/Scripts/RecordPlayer.cs
3,348
C#
/* insert license info here */ using System; using System.Collections; namespace Business.Data.Laboratorio { /// <summary> /// Generated by MyGeneration using the NHibernate Object Mapping template /// </summary> [Serializable] public sealed class SectorServicio: Business.BaseDataAccess { #region Private Members private bool m_isChanged; private int m_idsectorservicio; private Efector m_idefector; private string m_prefijo; private string m_nombre; private bool m_baja; private Usuario m_idusuarioregistro; private DateTime m_fecharegistro; #endregion #region Default ( Empty ) Class Constuctor /// <summary> /// default constructor /// </summary> public SectorServicio() { m_idsectorservicio = 0; m_idefector = new Efector(); m_prefijo = String.Empty; m_nombre = String.Empty; m_baja = false; m_idusuarioregistro = new Usuario(); m_fecharegistro = DateTime.MinValue; } #endregion // End of Default ( Empty ) Class Constuctor #region Required Fields Only Constructor /// <summary> /// required (not null) fields only constructor /// </summary> public SectorServicio( Efector idefector, string prefijo, string nombre, bool baja, Usuario idusuarioregistro, DateTime fecharegistro) : this() { m_idefector = idefector; m_prefijo = prefijo; m_nombre = nombre; m_baja = baja; m_idusuarioregistro = idusuarioregistro; m_fecharegistro = fecharegistro; } #endregion // End Required Fields Only Constructor #region Public Properties /// <summary> /// /// </summary> public int IdSectorServicio { get { return m_idsectorservicio; } set { m_isChanged |= ( m_idsectorservicio != value ); m_idsectorservicio = value; } } /// <summary> /// /// </summary> public Efector IdEfector { get { return m_idefector; } set { m_isChanged |= ( m_idefector != value ); m_idefector = value; } } /// <summary> /// /// </summary> public string Prefijo { get { return m_prefijo; } set { if( value == null ) throw new ArgumentOutOfRangeException("Null value not allowed for Prefijo", value, "null"); if( value.Length > 10) throw new ArgumentOutOfRangeException("Invalid value for Prefijo", value, value.ToString()); m_isChanged |= (m_prefijo != value); m_prefijo = value; } } /// <summary> /// /// </summary> public string Nombre { get { return m_nombre; } set { if( value == null ) throw new ArgumentOutOfRangeException("Null value not allowed for Nombre", value, "null"); if( value.Length > 50) throw new ArgumentOutOfRangeException("Invalid value for Nombre", value, value.ToString()); m_isChanged |= (m_nombre != value); m_nombre = value; } } /// <summary> /// /// </summary> //public int NumeroInicial //{ // get { return m_numeroinicial; } // set // { // m_isChanged |= ( m_numeroinicial != value ); // m_numeroinicial = value; // } //} /// <summary> /// /// </summary> public bool Baja { get { return m_baja; } set { m_isChanged |= ( m_baja != value ); m_baja = value; } } /// <summary> /// /// </summary> public Usuario IdUsuarioRegistro { get { return m_idusuarioregistro; } set { m_isChanged |= ( m_idusuarioregistro != value ); m_idusuarioregistro = value; } } /// <summary> /// /// </summary> public DateTime FechaRegistro { get { return m_fecharegistro; } set { m_isChanged |= ( m_fecharegistro != value ); m_fecharegistro = value; } } /// <summary> /// Returns whether or not the object has changed it's values. /// </summary> public bool IsChanged { get { return m_isChanged; } } #endregion } }
20.910448
98
0.578396
[ "MIT" ]
saludnqn/laboratorio
Business/Data/Laboratorio/SectorServicio.cs
4,203
C#
//------------------------------------------------------------------------------ // <auto-generated> // This code was generated by a tool. // Runtime Version:4.0.30319.42000 // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ namespace WindowsFormsApp1.Properties { /// <summary> /// A strongly-typed resource class, for looking up localized strings, etc. /// </summary> // This class was auto-generated by the StronglyTypedResourceBuilder // class via a tool like ResGen or Visual Studio. // To add or remove a member, edit your .ResX file then rerun ResGen // with the /str option, or rebuild your VS project. [global::System.CodeDom.Compiler.GeneratedCodeAttribute( "System.Resources.Tools.StronglyTypedResourceBuilder", "4.0.0.0" )] [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] internal class Resources { private static global::System.Resources.ResourceManager resourceMan; private static global::System.Globalization.CultureInfo resourceCulture; [global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute( "Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode" )] internal Resources() { } /// <summary> /// Returns the cached ResourceManager instance used by this class. /// </summary> [global::System.ComponentModel.EditorBrowsableAttribute( global::System.ComponentModel.EditorBrowsableState.Advanced )] internal static global::System.Resources.ResourceManager ResourceManager { get { if( ( resourceMan == null ) ) { global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager( "WindowsFormsApp1.Properties.Resources", typeof( Resources ).Assembly ); resourceMan = temp; } return resourceMan; } } /// <summary> /// Overrides the current thread's CurrentUICulture property for all /// resource lookups using this strongly typed resource class. /// </summary> [global::System.ComponentModel.EditorBrowsableAttribute( global::System.ComponentModel.EditorBrowsableState.Advanced )] internal static global::System.Globalization.CultureInfo Culture { get { return resourceCulture; } set { resourceCulture = value; } } } }
39.478873
186
0.601498
[ "MIT" ]
hubertfuchs/Components
WindowsFormsApp1/Properties/Resources.Designer.cs
2,805
C#
/* This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0. If a copy of the MPL was not distributed with this file, You can obtain one at http://mozilla.org/MPL/2.0/. Copyright (C) 2012 Prince Samuel <prince.samuel@gmail.com> Copyright (C) 2012-2013 Michael Möller <mmoeller@openhardwaremonitor.org> */ using System; using System.Drawing; using System.Drawing.Imaging; using System.IO; using System.Net; using System.Reflection; using System.Text; using System.Threading; using OpenHardwareMonitor.GUI; using OpenHardwareMonitor.Hardware; namespace OpenHardwareMonitor.Utilities { public class HttpServer { private HttpListener listener; private int listenerPort, nodeCount; private Thread listenerThread; private Node root; public HttpServer(Node node, int port) { root = node; listenerPort = port; //JSON node count. nodeCount = 0; try { listener = new HttpListener(); listener.IgnoreWriteExceptions = true; } catch (PlatformNotSupportedException) { listener = null; } } public bool PlatformNotSupported { get { return listener == null; } } public Boolean StartHTTPListener() { if (PlatformNotSupported) return false; try { if (listener.IsListening) return true; string prefix = "http://+:" + listenerPort + "/"; listener.Prefixes.Clear(); listener.Prefixes.Add(prefix); listener.Start(); if (listenerThread == null) { listenerThread = new Thread(HandleRequests); listenerThread.Start(); } } catch (Exception) { return false; } return true; } public Boolean StopHTTPListener() { if (PlatformNotSupported) return false; try { listenerThread.Abort(); listener.Stop(); listenerThread = null; } catch (HttpListenerException) { } catch (ThreadAbortException) { } catch (NullReferenceException) { } catch (Exception) { } return true; } private void HandleRequests() { while (listener.IsListening) { var context = listener.BeginGetContext( new AsyncCallback(ListenerCallback), listener); context.AsyncWaitHandle.WaitOne(); } } private void ListenerCallback(IAsyncResult result) { HttpListener listener = (HttpListener)result.AsyncState; if (listener == null || !listener.IsListening) return; // Call EndGetContext to complete the asynchronous operation. HttpListenerContext context; try { context = listener.EndGetContext(result); } catch (Exception) { return; } HttpListenerRequest request = context.Request; var requestedFile = request.RawUrl.Substring(1); if (requestedFile == "data.json") { SendJSON(context.Response); return; } if (requestedFile.Contains("images_icon")) { ServeResourceImage(context.Response, requestedFile.Replace("images_icon/", "")); return; } // default file to be served if (string.IsNullOrEmpty(requestedFile)) requestedFile = "index.html"; string[] splits = requestedFile.Split('.'); string ext = splits[splits.Length - 1]; ServeResourceFile(context.Response, "Web." + requestedFile.Replace('/', '.'), ext); } private void ServeResourceFile(HttpListenerResponse response, string name, string ext) { // resource names do not support the hyphen name = "OpenHardwareMonitor.Resources." + name.Replace("custom-theme", "custom_theme"); string[] names = Assembly.GetExecutingAssembly().GetManifestResourceNames(); for (int i = 0; i < names.Length; i++) { if (names[i].Replace('\\', '.') == name) { using (Stream stream = Assembly.GetExecutingAssembly(). GetManifestResourceStream(names[i])) { response.ContentType = GetcontentType("." + ext); response.ContentLength64 = stream.Length; byte[] buffer = new byte[512 * 1024]; int len; try { Stream output = response.OutputStream; while ((len = stream.Read(buffer, 0, buffer.Length)) > 0) { output.Write(buffer, 0, len); } output.Flush(); output.Close(); response.Close(); } catch (HttpListenerException) { } catch (InvalidOperationException) { } return; } } } response.StatusCode = 404; response.Close(); } private void ServeResourceImage(HttpListenerResponse response, string name) { name = "OpenHardwareMonitor.Resources." + name; string[] names = Assembly.GetExecutingAssembly().GetManifestResourceNames(); for (int i = 0; i < names.Length; i++) { if (names[i].Replace('\\', '.') == name) { using (Stream stream = Assembly.GetExecutingAssembly(). GetManifestResourceStream(names[i])) { Image image = Image.FromStream(stream); response.ContentType = "image/png"; try { Stream output = response.OutputStream; using (MemoryStream ms = new MemoryStream()) { image.Save(ms, ImageFormat.Png); ms.WriteTo(output); } output.Close(); } catch (HttpListenerException) { } image.Dispose(); response.Close(); return; } } } response.StatusCode = 404; response.Close(); } private void SendJSON(HttpListenerResponse response) { string JSON = "{\"id\": 0, \"Text\": \"Sensor\", \"Children\": ["; nodeCount = 1; JSON += GenerateJSON(root); JSON += "]"; JSON += ", \"Min\": \"Min\""; JSON += ", \"Value\": \"Value\""; JSON += ", \"Max\": \"Max\""; JSON += ", \"ImageURL\": \"\""; JSON += "}"; var responseContent = JSON; byte[] buffer = Encoding.UTF8.GetBytes(responseContent); response.AddHeader("Cache-Control", "no-cache"); response.ContentLength64 = buffer.Length; response.ContentType = "application/json"; try { Stream output = response.OutputStream; output.Write(buffer, 0, buffer.Length); output.Close(); } catch (HttpListenerException) { } response.Close(); } private string GenerateJSON(Node n) { string JSON = "{\"id\": " + nodeCount + ", \"Text\": \"" + n.Text + "\", \"Children\": ["; nodeCount++; foreach (Node child in n.Nodes) JSON += GenerateJSON(child) + ", "; if (JSON.EndsWith(", ")) JSON = JSON.Remove(JSON.LastIndexOf(",")); JSON += "]"; if (n is SensorNode) { JSON += ", \"Min\": \"" + ((SensorNode)n).Min + "\""; JSON += ", \"Value\": \"" + ((SensorNode)n).Value + "\""; JSON += ", \"Max\": \"" + ((SensorNode)n).Max + "\""; JSON += ", \"ImageURL\": \"images/transparent.png\""; } else if (n is HardwareNode) { JSON += ", \"Min\": \"\""; JSON += ", \"Value\": \"\""; JSON += ", \"Max\": \"\""; JSON += ", \"ImageURL\": \"images_icon/" + GetHardwareImageFile((HardwareNode)n) + "\""; } else if (n is TypeNode) { JSON += ", \"Min\": \"\""; JSON += ", \"Value\": \"\""; JSON += ", \"Max\": \"\""; JSON += ", \"ImageURL\": \"images_icon/" + GetTypeImageFile((TypeNode)n) + "\""; } else { JSON += ", \"Min\": \"\""; JSON += ", \"Value\": \"\""; JSON += ", \"Max\": \"\""; JSON += ", \"ImageURL\": \"images_icon/computer.png\""; } JSON += "}"; return JSON; } private static void ReturnFile(HttpListenerContext context, string filePath) { context.Response.ContentType = GetcontentType(Path.GetExtension(filePath)); const int bufferSize = 1024 * 512; //512KB var buffer = new byte[bufferSize]; using (var fs = File.OpenRead(filePath)) { context.Response.ContentLength64 = fs.Length; int read; while ((read = fs.Read(buffer, 0, buffer.Length)) > 0) context.Response.OutputStream.Write(buffer, 0, read); } context.Response.OutputStream.Close(); } private static string GetcontentType(string extension) { switch (extension) { case ".avi": return "video/x-msvideo"; case ".css": return "text/css"; case ".doc": return "application/msword"; case ".gif": return "image/gif"; case ".htm": case ".html": return "text/html"; case ".jpg": case ".jpeg": return "image/jpeg"; case ".js": return "application/x-javascript"; case ".mp3": return "audio/mpeg"; case ".png": return "image/png"; case ".pdf": return "application/pdf"; case ".ppt": return "application/vnd.ms-powerpoint"; case ".zip": return "application/zip"; case ".txt": return "text/plain"; default: return "application/octet-stream"; } } private static string GetHardwareImageFile(HardwareNode hn) { switch (hn.Hardware.HardwareType) { case HardwareType.CPU: return "cpu.png"; case HardwareType.GpuNvidia: return "nvidia.png"; case HardwareType.GpuAti: return "ati.png"; case HardwareType.HDD: return "hdd.png"; case HardwareType.Heatmaster: return "bigng.png"; case HardwareType.Mainboard: return "mainboard.png"; case HardwareType.SuperIO: return "chip.png"; case HardwareType.TBalancer: return "bigng.png"; case HardwareType.RAM: return "ram.png"; default: return "cpu.png"; } } private static string GetTypeImageFile(TypeNode tn) { switch (tn.SensorType) { case SensorType.Voltage: return "voltage.png"; case SensorType.Clock: return "clock.png"; case SensorType.Load: return "load.png"; case SensorType.Temperature: return "temperature.png"; case SensorType.Fan: return "fan.png"; case SensorType.Flow: return "flow.png"; case SensorType.Control: return "control.png"; case SensorType.Level: return "level.png"; case SensorType.Power: return "power.png"; default: return "power.png"; } } public int ListenerPort { get { return listenerPort; } set { listenerPort = value; } } ~HttpServer() { if (PlatformNotSupported) return; StopHTTPListener(); listener.Abort(); } public void Quit() { if (PlatformNotSupported) return; StopHTTPListener(); listener.Abort(); } } }
28.9
81
0.55523
[ "MPL-2.0", "MPL-2.0-no-copyleft-exception" ]
AlannaMuir/open-hardware-monitor
Utilities/HttpServer.cs
11,274
C#
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ /* * Do not modify this file. This file is generated from the lookoutvision-2020-11-20.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.LookoutforVision.Model; using Amazon.Runtime; using Amazon.Runtime.Internal; using Amazon.Runtime.Internal.Transform; using Amazon.Runtime.Internal.Util; using ThirdParty.Json.LitJson; namespace Amazon.LookoutforVision.Model.Internal.MarshallTransformations { /// <summary> /// UpdateDatasetEntries Request Marshaller /// </summary> public class UpdateDatasetEntriesRequestMarshaller : IMarshaller<IRequest, UpdateDatasetEntriesRequest> , 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((UpdateDatasetEntriesRequest)input); } /// <summary> /// Marshaller the request object to the HTTP request. /// </summary> /// <param name="publicRequest"></param> /// <returns></returns> public IRequest Marshall(UpdateDatasetEntriesRequest publicRequest) { IRequest request = new DefaultRequest(publicRequest, "Amazon.LookoutforVision"); request.Headers["Content-Type"] = "application/json"; request.Headers[Amazon.Util.HeaderKeys.XAmzApiVersion] = "2020-11-20"; request.HttpMethod = "PATCH"; if (!publicRequest.IsSetDatasetType()) throw new AmazonLookoutforVisionException("Request object does not have required field DatasetType set"); request.AddPathResource("{datasetType}", StringUtils.FromString(publicRequest.DatasetType)); if (!publicRequest.IsSetProjectName()) throw new AmazonLookoutforVisionException("Request object does not have required field ProjectName set"); request.AddPathResource("{projectName}", StringUtils.FromString(publicRequest.ProjectName)); request.ResourcePath = "/2020-11-20/projects/{projectName}/datasets/{datasetType}/entries"; request.MarshallerVersion = 2; using (StringWriter stringWriter = new StringWriter(CultureInfo.InvariantCulture)) { JsonWriter writer = new JsonWriter(stringWriter); writer.WriteObjectStart(); var context = new JsonMarshallerContext(request, writer); if(publicRequest.IsSetChanges()) { context.Writer.WritePropertyName("Changes"); context.Writer.Write(StringUtils.FromMemoryStream(publicRequest.Changes)); } writer.WriteObjectEnd(); string snippet = stringWriter.ToString(); request.Content = System.Text.Encoding.UTF8.GetBytes(snippet); } if(publicRequest.IsSetClientToken()) request.Headers["X-Amzn-Client-Token"] = publicRequest.ClientToken; return request; } private static UpdateDatasetEntriesRequestMarshaller _instance = new UpdateDatasetEntriesRequestMarshaller(); internal static UpdateDatasetEntriesRequestMarshaller GetInstance() { return _instance; } /// <summary> /// Gets the singleton. /// </summary> public static UpdateDatasetEntriesRequestMarshaller Instance { get { return _instance; } } } }
40.410714
156
0.634114
[ "Apache-2.0" ]
philasmar/aws-sdk-net
sdk/src/Services/LookoutforVision/Generated/Model/Internal/MarshallTransformations/UpdateDatasetEntriesRequestMarshaller.cs
4,526
C#
using Microsoft.ApplicationInsights.Extensibility; using softaware.UsageAware.ApplicationInsights; using System; using System.Collections.Generic; using System.Configuration; using System.Data; using System.Linq; using System.Threading.Tasks; using System.Windows; namespace softaware.UsageAware.UI.DemoClient { /// <summary> /// Interaction logic for App.xaml /// </summary> public partial class App : Application { public App() { } } }
21.217391
51
0.711066
[ "MIT" ]
softawaregmbh/library-usageaware
src/softaware.UsageAware.UI.DemoClient/App.xaml.cs
490
C#
// Copyright (c) Brock Allen & Dominick Baier. All rights reserved. // Licensed under the Apache License, Version 2.0. See LICENSE in the project root for license information. // Original file: https://github.com/IdentityServer/IdentityServer4.Quickstart.UI // Modified by Jan Škoruba namespace ODMIdentity.STS.Identity.ViewModels.Consent { public class ScopeViewModel { public string Name { get; set; } public string DisplayName { get; set; } public string Description { get; set; } public bool Emphasize { get; set; } public bool Required { get; set; } public bool Checked { get; set; } } }
34.526316
107
0.681402
[ "MIT" ]
omikolaj/IdentityServer4-Admin
ODMIdentity/src/ODMIdentity.STS.Identity/ViewModels/Consent/ScopeViewModel.cs
659
C#
/* * Copyright 2014 Dominick Baier, Brock Allen * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ using BrockAllen.MembershipReboot; using BrockAllen.MembershipReboot.Ef; using BrockAllen.MembershipReboot.Relational; using WebHost.MR; using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Linq; using System.Threading.Tasks; using System.Web; using IdentityManager; using IdentityManager.Configuration; using IdentityManager.MembershipReboot; namespace WebHost.IdMgr { public static class MembershipRebootIdentityManagerServiceExtensions { public static void Configure(this IdentityManagerServiceFactory factory, string connectionString) { factory.IdentityManagerService = new Registration<IIdentityManagerService, CustomIdentityManagerService>(); factory.Register(new Registration<CustomUserAccountService>()); factory.Register(new Registration<CustomGroupService>()); factory.Register(new Registration<CustomUserRepository>()); factory.Register(new Registration<CustomGroupRepository>()); factory.Register(new Registration<CustomDatabase>(resolver => new CustomDatabase(connectionString))); factory.Register(new Registration<CustomConfig>(CustomConfig.Config)); } } }
41.2
119
0.760518
[ "Apache-2.0" ]
AkhilNaidu09/IdentityServer3.Samples
source/MembershipReboot/WebHost/IdMgr/MembershipRebootIdentityManagerServiceExtensions.cs
1,856
C#
using System; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Threading; using System.Threading.Tasks; using Metozis.External.WeightedRandomization; using Metozis.TeTwo.Internal.Entities.Archetypes; using Metozis.TeTwo.Internal.Entities.Factories; using Metozis.TeTwo.Internal.Entities.Meta; using Metozis.TeTwo.Internal.Generation.World.Framework; using Metozis.TeTwo.Internal.Generation.World.Processes; using Metozis.TeTwo.Internal.Generation.World.Rules; using Sirenix.Utilities; using UnityEngine; using Random = UnityEngine.Random; namespace Metozis.TeTwo.Internal.Generation.World { public class WorldGenerator : MonoBehaviour { public Sprite BlockSprite; public bool CustomGeneration; public Action<WorldGenerationMeta> OnWorldGenerated = delegate { }; private readonly HashSet<IGenerationProcess> generationProcessor = new HashSet<IGenerationProcess>(); private void InitializeDefaultGeneration(WorldGenerationSettings settings) { generationProcessor.AddRange(DefaultGeneration.AssembleDefaultProcessor(settings)); } private void Start() { var options = new WorldGenerationSettings { Rules = DefaultGeneration.DefaultRules, ChunkSize = new Vector2(100, 100), Seed = 219 }; Random.InitState(options.Seed); OnWorldGenerated += CreateWorld; GenerateWorld(options); if (false) { //StartCoroutine(CreateWorldAsync(GenerateWorld(options))); } } public void GenerateWorld(WorldGenerationSettings options) { StartCoroutine(GenerationRoutine(options)); } private IEnumerator GenerationRoutine(WorldGenerationSettings options) { var result = new WorldGenerationMeta(); if (!CustomGeneration) { InitializeDefaultGeneration(options); } result.Initialize(); options.DistributeChunks(); foreach (var meta in GenerationPreferences.Instance.BlockMeta) { result.BlocksMeta[meta.Id] = meta; } foreach (var process in generationProcessor.Where(p => p.Type == GenerationProcessType.Preprocess)) { process.Generate(ref result, options.GetDataChunk(process.DataPieceType)); yield return new WaitUntil(() => process.Complete); } options.Rules.Sort((rule, another) => { if (rule.Order > another.Order) return 1; if (rule.Order < another.Order) return -1; return 0; } ); foreach (var rule in options.Rules) { rule.Resolve(ref result); } foreach (var process in generationProcessor.Where(p => p.Type == GenerationProcessType.Postprocess)) { process.Generate(ref result, options.GetDataChunk(process.DataPieceType)); yield return new WaitUntil(() => process.Complete); } OnWorldGenerated.Invoke(result); Debug.Log("World generation complete!"); } public void CreateWorld(WorldGenerationMeta meta) { var world = new GameObject("World Chunk"); var blockFactory = new BlockFactory(Vector3.zero); foreach (var variant in meta.Blocks) { foreach (var pos in variant.Positions) { blockFactory.SetPosition(pos); var block = blockFactory.Create<Block>(variant.Meta); block.transform.parent = world.transform; } } } private IEnumerator CreateWorldAsync(WorldGenerationMeta meta) { yield return new WaitForSeconds(1); var blockFactory = new BlockFactory(Vector3.zero); foreach (var variant in meta.Blocks) { foreach (var pos in variant.Positions) { yield return new WaitForSeconds(Time.deltaTime); UnityMainThreadDispatcher.Instance().Enqueue(() => { blockFactory.SetPosition(pos); blockFactory.Create<Block>(variant.Meta); }); } } } } }
34.522059
112
0.572311
[ "MIT" ]
Donatoz/Terrabound
Internal/Generation/World/WorldGenerator.cs
4,697
C#
using System; using System.ComponentModel; using EfsTools.Attributes; using EfsTools.Utils; using Newtonsoft.Json; namespace EfsTools.Items.Efs { [Serializable] [EfsFile("/nv/item_files/rfnv/00021008", true, 0xE1FF)] [Attributes(9)] public class Bc3PaSmpsPdmLevelTemp { [ElementsCount(8)] [ElementType("uint16")] [Description("")] public ushort[] Value { get; set; } } }
21.761905
60
0.617068
[ "MIT" ]
HomerSp/EfsTools
EfsTools/Items/Efs/Bc3PaSmpsPdmLevelTempI.cs
457
C#
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Drawing; using static Interop; namespace System.Windows.Forms { public partial class DataGridViewCheckBoxCell { protected class DataGridViewCheckBoxCellAccessibleObject : DataGridViewCellAccessibleObject { private int[] runtimeId = null!; // Used by UIAutomation public DataGridViewCheckBoxCellAccessibleObject(DataGridViewCell? owner) : base(owner) { } public override AccessibleStates State { get { if (Owner is null) { throw new InvalidOperationException(SR.DataGridViewCellAccessibleObject_OwnerNotSet); } if (!(Owner is DataGridViewButtonCell dataGridViewCheckBoxCell)) { return base.State; } switch (dataGridViewCheckBoxCell.EditedFormattedValue) { case CheckState state: return state switch { CheckState.Checked => AccessibleStates.Checked | base.State, CheckState.Indeterminate => AccessibleStates.Indeterminate | base.State, _ => base.State }; case bool stateAsBool: return stateAsBool ? AccessibleStates.Checked | base.State : base.State; default: return base.State; } } } public override string DefaultAction { get { if (Owner is null) { throw new InvalidOperationException(SR.DataGridViewCellAccessibleObject_OwnerNotSet); } if (Owner.ReadOnly) { return string.Empty; } bool switchToCheckedState = true; switch (Owner.FormattedValue) { case CheckState checkState: switchToCheckedState = checkState == CheckState.Unchecked; break; case bool boolState: switchToCheckedState = !boolState; break; } return switchToCheckedState ? SR.DataGridView_AccCheckBoxCellDefaultActionCheck : SR.DataGridView_AccCheckBoxCellDefaultActionUncheck; } } public override void DoDefaultAction() { if (Owner is null) { throw new InvalidOperationException(SR.DataGridViewCellAccessibleObject_OwnerNotSet); } if (!(Owner is DataGridViewCheckBoxCell dataGridViewCell)) { return; } if (dataGridViewCell.RowIndex == -1) { throw new InvalidOperationException(SR.DataGridView_InvalidOperationOnSharedCell); } DataGridView? dataGridView = dataGridViewCell.DataGridView; if (dataGridView?.IsHandleCreated != true) { return; } if (!dataGridViewCell.ReadOnly && dataGridViewCell.OwningColumn is not null && dataGridViewCell.OwningRow is not null) { dataGridView.CurrentCell = dataGridViewCell; bool endEditMode = false; if (!dataGridView.IsCurrentCellInEditMode) { endEditMode = true; dataGridView.BeginEdit(selectAll: false); } if (dataGridView.IsCurrentCellInEditMode) { if (dataGridViewCell.SwitchFormattedValue()) { dataGridViewCell.NotifyDataGridViewOfValueChange(); dataGridView.InvalidateCell(dataGridViewCell.ColumnIndex, dataGridViewCell.RowIndex); if (Owner is DataGridViewCheckBoxCell checkBoxCell) { checkBoxCell.NotifyMSAAClient(dataGridViewCell.ColumnIndex, dataGridViewCell.RowIndex); checkBoxCell.NotifyUiaClient(); } } if (endEditMode) { dataGridView.EndEdit(); } } } } public override int GetChildCount() => 0; internal override bool IsIAccessibleExSupported() => true; internal override int[] RuntimeId { get { if (runtimeId is null) { runtimeId = new int[2]; runtimeId[0] = RuntimeIDFirstItem; // first item is static - 0x2a runtimeId[1] = GetHashCode(); } return runtimeId; } } internal override object? GetPropertyValue(UiaCore.UIA propertyID) => propertyID switch { UiaCore.UIA.IsTogglePatternAvailablePropertyId => (object)IsPatternSupported(UiaCore.UIA.TogglePatternId), UiaCore.UIA.ControlTypePropertyId => UiaCore.UIA.CheckBoxControlTypeId, _ => base.GetPropertyValue(propertyID) }; internal override bool IsPatternSupported(UiaCore.UIA patternId) => patternId == UiaCore.UIA.TogglePatternId ? true : base.IsPatternSupported(patternId); internal override void Toggle() => DoDefaultAction(); internal override UiaCore.ToggleState ToggleState { get { if (Owner is null) { throw new InvalidOperationException(SR.DataGridViewCellAccessibleObject_OwnerNotSet); } bool toggledState; switch (Owner.FormattedValue) { case CheckState checkState: toggledState = checkState == CheckState.Unchecked; break; case bool boolState: toggledState = !boolState; break; default: return UiaCore.ToggleState.Indeterminate; } return toggledState ? UiaCore.ToggleState.On : UiaCore.ToggleState.Off; } } } } }
37.907692
165
0.471591
[ "MIT" ]
adamsitnik/winforms
src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewCheckBoxCell.DataGridViewCheckBoxCellAccessibleObject.cs
7,394
C#
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT license. See the License.txt file in the project root for full license information. using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.Collections.Specialized; using System.Configuration; using System.Linq; using System.Linq.Expressions; using System.Text.RegularExpressions; using System.Threading.Tasks; using Azure; using Azure.Data.AppConfiguration; using Azure.Identity; using Azure.Security.KeyVault.Secrets; using Newtonsoft.Json; namespace Microsoft.Configuration.ConfigurationBuilders { /// <summary> /// A ConfigurationProvider that retrieves values from Azure App Configuration stores. /// </summary> public class AzureAppConfigurationBuilder : KeyValueConfigBuilder { private const string KeyVaultContentType = "application/vnd.microsoft.appconfig.keyvaultref+json"; #pragma warning disable CS1591 // No xml comments for tag literals. public const string endpointTag = "endpoint"; public const string connectionStringTag = "connectionString"; public const string keyFilterTag = "keyFilter"; public const string labelFilterTag = "labelFilter"; public const string dateTimeFilterTag = "acceptDateTime"; public const string useKeyVaultTag = "useAzureKeyVault"; #pragma warning restore CS1591 // No xml comments for tag literals. private Uri _endpoint; private string _connectionString; private string _keyFilter; private string _labelFilter; private DateTimeOffset _dateTimeFilter; private bool _useKeyVault = false; private ConcurrentDictionary<Uri, SecretClient> _kvClientCache; private ConfigurationClient _client; /// <summary> /// Initializes the configuration builder lazily. /// </summary> /// <param name="name">The friendly name of the provider.</param> /// <param name="config">A collection of the name/value pairs representing builder-specific attributes specified in the configuration for this provider.</param> protected override void LazyInitialize(string name, NameValueCollection config) { // Default 'Optional' to false. base.LazyInitialize() will override if specified in config. Optional = false; base.LazyInitialize(name, config); // keyFilter _keyFilter = UpdateConfigSettingWithAppSettings(keyFilterTag); if (String.IsNullOrWhiteSpace(_keyFilter)) _keyFilter = null; // labelFilter // Place some restrictions on label filter, similar to the .net core provider. // The idea is to restrict queries to one label, and one label only. Even if that // one label is the "empty" label. Doing so will remove the decision making process // from this builders hands about which key/value/label tuple to choose when there // are multiple. _labelFilter = UpdateConfigSettingWithAppSettings(labelFilterTag); if (String.IsNullOrWhiteSpace(_labelFilter)) { _labelFilter = null; } else if (_labelFilter.Contains('*') || _labelFilter.Contains(',')) { throw new ArgumentException("The characters '*' and ',' are not supported in label filters.", labelFilterTag); } // acceptDateTime _dateTimeFilter = DateTimeOffset.TryParse(UpdateConfigSettingWithAppSettings(dateTimeFilterTag), out _dateTimeFilter) ? _dateTimeFilter : DateTimeOffset.MinValue; // Azure Key Vault Integration _useKeyVault = (UpdateConfigSettingWithAppSettings(useKeyVaultTag) != null) ? Boolean.Parse(config[useKeyVaultTag]) : _useKeyVault; if (_useKeyVault) _kvClientCache = new ConcurrentDictionary<Uri, SecretClient>(EqualityComparer<Uri>.Default); // Always allow 'connectionString' to override black magic. But we expect this to be null most of the time. _connectionString = UpdateConfigSettingWithAppSettings(connectionStringTag); if (String.IsNullOrWhiteSpace(_connectionString)) { _connectionString = null; // Use Endpoint instead string uri = UpdateConfigSettingWithAppSettings(endpointTag); if (!String.IsNullOrWhiteSpace(uri)) { try { _endpoint = new Uri(uri); _client = new ConfigurationClient(_endpoint, new DefaultAzureCredential()); } catch (Exception ex) { if (!Optional) throw new ArgumentException($"Exception encountered while creating connection to Azure App Configuration store.", ex); } } else { throw new ArgumentException($"An endpoint URI or connection string must be provided for connecting to Azure App Configuration service via the '{endpointTag}' or '{connectionStringTag}' attribute."); } } else { // If we get here, then we should try to connect with a connection string. try { _client = new ConfigurationClient(_connectionString); } catch (Exception ex) { if (!Optional) throw new ArgumentException($"Exception encountered while creating connection to Azure App Configuration store.", ex); } } // At this point we've got all our ducks in a row and are ready to go. And we know that // we will be used, because this is the 'lazy' initializer. But let's handle one oddball case // before we go. // If we have a keyFilter set, then we will always query a set of values instead of a single // value, regardless of whether we are in strict/expand/greedy mode. But if we're not in // greedy mode, then the base KeyValueConfigBuilder will still request each key/value it is // interested in one at a time, and only cache that one result. So we will end up querying the // same set of values from the AppConfig service for every value. Let's only do this once and // cache the entire set to make those calls to GetValueInternal read from the cache instead of // hitting the service every time. if (_keyFilter != null && Mode != KeyValueMode.Greedy) EnsureGreedyInitialized(); } /// <summary> /// Makes a determination about whether the input key is valid for this builder and backing store. /// </summary> /// <param name="key">The string to be validated. May be partial.</param> /// <returns>True if the string is valid. False if the string is not a valid key.</returns> public override bool ValidateKey(string key) { // From - https://docs.microsoft.com/en-us/azure/azure-app-configuration/concept-key-value // You can use any unicode character in key names entered into App Configuration except for *, ,, and \. These characters are // reserved.If you need to include a reserved character, you must escape it by using \{ Reserved Character}. if (String.IsNullOrWhiteSpace(key)) return false; if (key.Contains('*') || key.Contains(',')) return false; // We don't want to completely disallow '\' since it is used for escaping. But writing a full parser for someone elses // naming format could be error prone. If we see a '\' followed by a '{', just call it good. Don't bother with the Regex // if there aren't any backslashes though. if (key.Contains('\\')) return !Regex.IsMatch(key, @"\\[^{]"); return true; } /// <summary> /// Looks up a single 'value' for the given 'key.' /// </summary> /// <param name="key">The 'key' for the secret to look up in the configured Key Vault. (Prefix handling is not needed here.)</param> /// <returns>The value corresponding to the given 'key' or null if no value is found.</returns> public override string GetValue(string key) { // Quick shortcut. If we have a keyFilter set, then we've already populated the cache with // all possible values for this builder. If we get here, that means the key was not found in // the cache. Going further will query with just the key name, and no keyFilter applied. This // could result in finding a value... but we shouldn't, because the requested key does not // match the keyFilter - otherwise it would already be in the cache. Avoid the trouble and // shortcut return nothing in this case. if (_keyFilter != null) return null; // Azure Key Vault keys are case-insensitive, so this should be fine. // Also, this is a synchronous method. And in single-threaded contexts like ASP.Net // it can be bad/dangerous to block on async calls. So lets work some TPL voodoo // to avoid potential deadlocks. return Task.Run(async () => { return await GetValueAsync(key); }).Result; } /// <summary> /// Retrieves all known key/value pairs from the Azure App Config store where the key begins with with <paramref name="prefix"/>. /// </summary> /// <param name="prefix">A prefix string to filter the list of potential keys retrieved from the source.</param> /// <returns>A collection of key/value pairs.</returns> public override ICollection<KeyValuePair<string, string>> GetAllValues(string prefix) { // This is also a synchronous method. And in single-threaded contexts like ASP.Net // it can be bad/dangerous to block on async calls. So lets work some TPL voodoo // again to avoid potential deadlocks. return Task.Run(async () => { return await GetAllValuesAsync(prefix); }).Result; } private async Task<string> GetValueAsync(string key) { if (_client == null) return null; SettingSelector selector = new SettingSelector(); selector.KeyFilter = key; if (_labelFilter != null) { selector.LabelFilter = _labelFilter; } if (_dateTimeFilter > DateTimeOffset.MinValue) { selector.AcceptDateTime = _dateTimeFilter; } // TODO: Reduce bandwidth by limiting the fields we retrieve. // Currently, content type doesn't get delivered, even if we add it to the selection. This prevents KeyVault recognition. //selector.Fields = SettingFields.Key | SettingFields.Value | SettingFields.ContentType; try { AsyncPageable<ConfigurationSetting> settings = _client.GetConfigurationSettingsAsync(selector); IAsyncEnumerator<ConfigurationSetting> enumerator = settings.GetAsyncEnumerator(); try { // There should only be one result. If there's more, we're only returning the fisrt. await enumerator.MoveNextAsync(); ConfigurationSetting current = enumerator.Current; if (current == null) return null; if (_useKeyVault && IsKeyVaultReference(current)) { try { return await GetKeyVaultValue(current); } catch (Exception) { // 'Optional' plays a double role with this provider. Being optional means it is // ok for us to fail to resolve a keyvault reference. If we are not optional though, // we want to make some noise when a reference fails to resolve. if (!Optional) throw; } } return current.Value; } finally { await enumerator.DisposeAsync(); } } catch (Exception e) when (Optional && ((e.InnerException is System.Net.Http.HttpRequestException) || (e.InnerException is UnauthorizedAccessException))) { } return null; } private async Task<ICollection<KeyValuePair<string, string>>> GetAllValuesAsync(string prefix) { Dictionary<string, string> data = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase); if (_client == null) return data; SettingSelector selector = new SettingSelector(); if (_keyFilter != null) { selector.KeyFilter = _keyFilter; } if (_labelFilter != null) { selector.LabelFilter = _labelFilter; } if (_dateTimeFilter > DateTimeOffset.MinValue) { selector.AcceptDateTime = _dateTimeFilter; } // TODO: Reduce bandwidth by limiting the fields we retrieve. // Currently, content type doesn't get delivered, even if we add it to the selection. This prevents KeyVault recognition. //selector.Fields = SettingFields.Key | SettingFields.Value | SettingFields.ContentType; // We don't make any guarantees about which kv get precendence when there are multiple of the same key... // But the config service does seem to return kvs in a preferred order - no label first, then alphabetical by label. // Prefer the first kv we encounter from the config service. try { AsyncPageable<ConfigurationSetting> settings = _client.GetConfigurationSettingsAsync(selector); IAsyncEnumerator<ConfigurationSetting> enumerator = settings.GetAsyncEnumerator(); try { while (await enumerator.MoveNextAsync()) { ConfigurationSetting setting = enumerator.Current; string configValue = setting.Value; // If it's a key vault reference, go fetch the value from key vault if (_useKeyVault && IsKeyVaultReference(setting)) { try { configValue = await GetKeyVaultValue(setting); } catch (Exception) { // 'Optional' plays a double role with this provider. Being optional means it is // ok for us to fail to resolve a keyvault reference. If we are not optional though, // we want to make some noise when a reference fails to resolve. if (!Optional) throw; } } if (!data.ContainsKey(setting.Key)) data[setting.Key] = configValue; } } finally { await enumerator.DisposeAsync(); } } catch (Exception e) when (Optional && ((e.InnerException is System.Net.Http.HttpRequestException) || (e.InnerException is UnauthorizedAccessException))) { } return data; } private bool IsKeyVaultReference(ConfigurationSetting setting) { string contentType = setting.ContentType?.Split(';')[0].Trim(); return String.Equals(contentType, KeyVaultContentType); } private async Task<string> GetKeyVaultValue(ConfigurationSetting setting) { // The key vault reference will be in the form of a Uri wrapped in JSON, like so: // {"uri":"https://vaultName.vault.azure.net/secrets/secretName"} // Content validation - will throw JsonReaderException on failure KeyVaultSecretReference secretRef = JsonConvert.DeserializeObject<KeyVaultSecretReference>(setting.Value, KeyVaultSecretReference.s_SerializationSettings); // Uri validation - will throw UriFormatException upon failure Uri secretUri = new Uri(secretRef.Uri); Uri vaultUri = new Uri(secretUri.GetLeftPart(UriPartial.Authority)); // TODO: Check to see if SecretClient can take the full uri instead of requiring us to parse out the secretID. SecretClient kvClient = GetSecretClient(vaultUri); if (kvClient == null && !Optional) throw new ConfigurationErrorsException("Could not connect to Azure Key Vault while retrieving secret. Connection is not optional."); // Retrieve Value KeyVaultSecret kvSecret = await kvClient.GetSecretAsync(secretUri.Segments[2].TrimEnd(new char[] { '/' })); // ['/', 'secrets/', '{secretID}/'] if (kvSecret != null && kvSecret.Properties.Enabled.GetValueOrDefault()) return kvSecret.Value; return null; } private SecretClient GetSecretClient(Uri vaultUri) { return _kvClientCache.GetOrAdd(vaultUri, uri => new SecretClient(uri, new DefaultAzureCredential())); } [JsonObject(MemberSerialization.OptIn)] private class KeyVaultSecretReference { public static JsonSerializerSettings s_SerializationSettings = new JsonSerializerSettings { DateParseHandling = DateParseHandling.None }; [JsonProperty("uri")] public string Uri { get; set; } } } }
49.148148
218
0.592206
[ "MIT" ]
Expecho/MicrosoftConfigurationBuilders
src/AzureAppConfig/AzureAppConfigurationBuilder.cs
18,580
C#
using System.Collections.Generic; using UnityEngine; namespace CXUtils.Common { ///<summary> CX's Helper Mesh Utils and extensions </summary> public static class MeshUtils { #region Script Methods /// <summary> Recalculates all the bounds, normals and tangents of the mesh </summary> public static void RecalculateAll( this Mesh mesh ) { mesh.RecalculateBounds(); mesh.RecalculateNormals(); mesh.RecalculateTangents(); } #endregion #region Mesh Construction /// <summary> /// This will create a connected quad mesh (which uses the mesh to just display one big texture only (not for single /// quad grid uv)) /// </summary> public static void CreateEmptyConnectedQuadMeshArrays( Vector2Int size, out Vector3[] vertices, out int[] triangles, out Vector2[] uvs ) { int totVerticesCount = ( size.x + 1 ) * ( size.y + 1 ); vertices = new Vector3[totVerticesCount]; triangles = new int[size.x * size.y * 2]; uvs = new Vector2[totVerticesCount]; } /// <summary> /// This will create a connected quad mesh but independent with each other quad meshes /// (which u use the mesh to display grid like tiles and other awesome stuff) /// </summary> public static void CreateEmptyQuadMeshArrays( Vector2Int size, out Vector3[] vertices, out int[] triangles, out Vector2[] uvs ) { int totVerticesCount = size.x * size.y * 4; vertices = new Vector3[totVerticesCount]; triangles = new int[size.x * size.y * 2]; uvs = new Vector2[totVerticesCount]; } #endregion #region All Mesh /// <summary> /// Adds a triangle mesh on a mesh /// </summary> public static void AddTriangleMesh( this Mesh mesh, Vector3 PT1, Vector3 PT2, Vector3 PT3, int TriangleSubMeshIndex ) { var vertices = new List<Vector3>(); var triangles = new List<int>(); foreach ( var vert in mesh.vertices ) vertices.Add( vert ); foreach ( int tris in mesh.triangles ) triangles.Add( tris ); mesh.Clear(); vertices.Add( PT1 ); triangles.Add( vertices.Count - 1 ); vertices.Add( PT2 ); triangles.Add( vertices.Count - 1 ); vertices.Add( PT3 ); triangles.Add( vertices.Count - 1 ); mesh.SetVertices( vertices ); mesh.SetTriangles( triangles, TriangleSubMeshIndex ); } /// <summary> Adds a rectangular mesh on (facing on left down , left up , right up || right down, left down, right up)</summary> public static void AddRectangleMesh( this Mesh mesh, Vector3 leftDown, Vector3 leftUp, Vector3 rightUp, Vector3 rightDown, int triangleSubMeshesIndex ) { AddTriangleMesh( mesh, leftDown, leftUp, rightUp, triangleSubMeshesIndex ); AddTriangleMesh( mesh, rightDown, leftDown, rightUp, triangleSubMeshesIndex ); } #endregion #region Add Grid Mesh /// <summary> Adds a rectangular grid mesh (In order [vertices are in 1D array with orders]) </summary> public static void AddGridMeshInOrder( this Mesh mesh, float eachGridSize, Vector2Int wholeGridSize, int triangleSubMesh ) { var vertices = new List<Vector3>(); var triangles = new List<int>(); //vertices for ( float z = 0; z <= wholeGridSize.y; z += eachGridSize ) for ( float x = 0; x <= wholeGridSize.x; x += eachGridSize ) vertices.Add( new Vector3( x, 0, z ) ); //triangles int vert = 0; for ( int z = 0; z < wholeGridSize.y; z++ ) { for ( int x = 0; x < wholeGridSize.x; x++ ) { triangles.Add( vert + 1 ); triangles.Add( vert ); triangles.Add( vert + wholeGridSize.x + 1 ); triangles.Add( vert + 1 ); triangles.Add( vert + wholeGridSize.x + 1 ); triangles.Add( vert + wholeGridSize.x + 2 ); vert++; } vert++; } mesh.SetVertices( vertices ); mesh.SetTriangles( triangles.ToArray(), triangleSubMesh ); //and recalculate mesh.RecalculateAll(); } /// <summary> Adds a rectangular grid mesh (In order [vertices are in 1D array with orders]) Out vertices </summary> public static void AddGridMeshInOrder( this Mesh mesh, float eachGridSize, Vector2Int wholeGridSize, int triangleSubMesh, out List<Vector3> vertices ) { vertices = new List<Vector3>(); var triangles = new List<int>(); //vetrticies for ( float z = 0; z <= wholeGridSize.y; z += eachGridSize ) for ( float x = 0; x <= wholeGridSize.x; x += eachGridSize ) vertices.Add( new Vector3( x, 0, z ) ); //triangles int vert = 0; for ( int z = 0; z < wholeGridSize.y; z++ ) { for ( int x = 0; x < wholeGridSize.x; x++ ) { triangles.Add( vert + 1 ); triangles.Add( vert ); triangles.Add( vert + wholeGridSize.x + 1 ); triangles.Add( vert + 1 ); triangles.Add( vert + wholeGridSize.x + 1 ); triangles.Add( vert + wholeGridSize.x + 2 ); vert++; } vert++; } mesh.SetVertices( vertices ); mesh.SetTriangles( triangles.ToArray(), triangleSubMesh ); //and recalculate RecalculateAll( mesh ); } /// <summary> Adds a rectangular grid mesh (In order [vertices are in 1D array with orders]) Out vertices and triangles </summary> public static void AddGridMeshInOrder( this Mesh mesh, float eachGridSize, Vector2Int wholeGridSize, int triangleSubMesh, out List<Vector3> vertices, out List<int> triangles ) { vertices = new List<Vector3>(); triangles = new List<int>(); //vertices for ( float z = 0; z <= wholeGridSize.y; z += eachGridSize ) for ( float x = 0; x <= wholeGridSize.x; x += eachGridSize ) vertices.Add( new Vector3( x, 0, z ) ); //triangles int vert = 0; for ( int z = 0; z < wholeGridSize.y; z++ ) { for ( int x = 0; x < wholeGridSize.x; x++ ) { triangles.Add( vert + 1 ); triangles.Add( vert ); triangles.Add( vert + wholeGridSize.x + 1 ); triangles.Add( vert + 1 ); triangles.Add( vert + wholeGridSize.x + 1 ); triangles.Add( vert + wholeGridSize.x + 2 ); vert++; } vert += 2; } mesh.SetVertices( vertices ); mesh.SetTriangles( triangles.ToArray(), triangleSubMesh ); //and recalculate mesh.RecalculateAll(); } #endregion } }
37.364532
144
0.524588
[ "MIT" ]
AMAIOLAMO/CXUtilsByCXRedix-UnityUtils
Scripts/Src/Unity/Utilities/Mesh/MeshUtils.cs
7,587
C#
using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Threading; using Octopus.Client.Model; namespace Octopus.Client.Repositories { public interface ITaskRepository : IPaginate<TaskResource>, IGet<TaskResource>, ICreate<TaskResource> { TaskResource ExecuteHealthCheck(string description = null, int timeoutAfterMinutes = 5, int machineTimeoutAfterMinutes = 1, string environmentId = null, string[] machineIds = null); TaskResource ExecuteCalamariUpdate(string description = null, string[] machineIds = null); TaskResource ExecuteBackup(string description = null); TaskResource ExecuteTentacleUpgrade(string description = null, string environmentId = null, string[] machineIds = null); TaskResource ExecuteAdHocScript(string scriptBody, string[] machineIds = null, string[] environmentIds = null, string[] targetRoles = null, string description = null, string syntax = "PowerShell"); TaskResource ExecuteActionTemplate(ActionTemplateResource resource, Dictionary<string, PropertyValueResource> properties, string[] machineIds = null, string[] environmentIds = null, string[] targetRoles = null, string description = null); TaskResource ExecuteCommunityActionTemplatesSynchronisation(string description = null); List<TaskResource> GetAllActive(); TaskDetailsResource GetDetails(TaskResource resource); string GetRawOutputLog(TaskResource resource); void Rerun(TaskResource resource); void Cancel(TaskResource resource); IReadOnlyList<TaskResource> GetQueuedBehindTasks(TaskResource resource); void WaitForCompletion(TaskResource task, int pollIntervalSeconds = 4, int timeoutAfterMinutes = 0, Action<TaskResource[]> interval = null); void WaitForCompletion(TaskResource[] tasks, int pollIntervalSeconds = 4, int timeoutAfterMinutes = 0, Action<TaskResource[]> interval = null); } class TaskRepository : BasicRepository<TaskResource>, ITaskRepository { public TaskRepository(IOctopusClient client) : base(client, "Tasks") { } public TaskResource ExecuteHealthCheck(string description = null, int timeoutAfterMinutes = 5, int machineTimeoutAfterMinutes = 1, string environmentId = null, string[] machineIds = null) { var resource = new TaskResource(); resource.Name = BuiltInTasks.Health.Name; resource.Description = string.IsNullOrWhiteSpace(description) ? "Manual health check" : description; resource.Arguments = new Dictionary<string, object> { {BuiltInTasks.Health.Arguments.Timeout, TimeSpan.FromMinutes(timeoutAfterMinutes)}, {BuiltInTasks.Health.Arguments.MachineTimeout, TimeSpan.FromMinutes(machineTimeoutAfterMinutes)}, {BuiltInTasks.Health.Arguments.EnvironmentId, environmentId}, {BuiltInTasks.Health.Arguments.MachineIds, machineIds} }; return Create(resource); } public TaskResource ExecuteCalamariUpdate(string description = null, string[] machineIds = null) { var resource = new TaskResource(); resource.Name = BuiltInTasks.UpdateCalamari.Name; resource.Description = string.IsNullOrWhiteSpace(description) ? "Manual Calamari update" : description; resource.Arguments = new Dictionary<string, object> { {BuiltInTasks.UpdateCalamari.Arguments.MachineIds, machineIds } }; return Create(resource); } public TaskResource ExecuteBackup(string description = null) { var resource = new TaskResource(); resource.Name = BuiltInTasks.Backup.Name; resource.Description = string.IsNullOrWhiteSpace(description) ? "Manual backup" : description; return Create(resource); } public TaskResource ExecuteTentacleUpgrade(string description = null, string environmentId = null, string[] machineIds = null) { var resource = new TaskResource(); resource.Name = BuiltInTasks.Upgrade.Name; resource.Description = string.IsNullOrWhiteSpace(description) ? "Manual upgrade" : description; resource.Arguments = new Dictionary<string, object> { {BuiltInTasks.Upgrade.Arguments.EnvironmentId, environmentId}, {BuiltInTasks.Upgrade.Arguments.MachineIds, machineIds} }; return Create(resource); } public TaskResource ExecuteAdHocScript(string scriptBody, string[] machineIds = null, string[] environmentIds = null, string[] targetRoles = null, string description = null, string syntax = "PowerShell") { var resource = new TaskResource(); resource.Name = BuiltInTasks.AdHocScript.Name; resource.Description = string.IsNullOrWhiteSpace(description) ? "Run ad-hoc PowerShell script" : description; resource.Arguments = new Dictionary<string, object> { {BuiltInTasks.AdHocScript.Arguments.EnvironmentIds, environmentIds}, {BuiltInTasks.AdHocScript.Arguments.TargetRoles, targetRoles}, {BuiltInTasks.AdHocScript.Arguments.MachineIds, machineIds}, {BuiltInTasks.AdHocScript.Arguments.ScriptBody, scriptBody}, {BuiltInTasks.AdHocScript.Arguments.Syntax, syntax} }; return Create(resource); } public TaskResource ExecuteActionTemplate(ActionTemplateResource template, Dictionary<string, PropertyValueResource> properties, string[] machineIds = null, string[] environmentIds = null, string[] targetRoles = null, string description = null) { if (string.IsNullOrEmpty(template?.Id)) throw new ArgumentException("The step template was either null, or has no ID"); var resource = new TaskResource(); resource.Name = BuiltInTasks.AdHocScript.Name; resource.Description = string.IsNullOrWhiteSpace(description) ? "Run step template: " + template.Name : description; resource.Arguments = new Dictionary<string, object> { {BuiltInTasks.AdHocScript.Arguments.EnvironmentIds, environmentIds}, {BuiltInTasks.AdHocScript.Arguments.TargetRoles, targetRoles}, {BuiltInTasks.AdHocScript.Arguments.MachineIds, machineIds}, {BuiltInTasks.AdHocScript.Arguments.ActionTemplateId, template.Id}, {BuiltInTasks.AdHocScript.Arguments.Properties, properties} }; return Create(resource); } public TaskResource ExecuteCommunityActionTemplatesSynchronisation(string description = null) { var resource = new TaskResource(); resource.Name = BuiltInTasks.SyncCommunityActionTemplates.Name; resource.Description = description ?? "Run " + BuiltInTasks.SyncCommunityActionTemplates.Name; return Create(resource); } public TaskDetailsResource GetDetails(TaskResource resource) { return Client.Get<TaskDetailsResource>(resource.Link("Details")); } public string GetRawOutputLog(TaskResource resource) { return Client.Get<string>(resource.Link("Raw")); } public void Rerun(TaskResource resource) { Client.Post(resource.Link("Rerun"), (TaskResource)null); } public void Cancel(TaskResource resource) { Client.Post(resource.Link("Cancel"), (TaskResource)null); } public IReadOnlyList<TaskResource> GetQueuedBehindTasks(TaskResource resource) { return Client.ListAll<TaskResource>(resource.Link("QueuedBehind")); } public void WaitForCompletion(TaskResource task, int pollIntervalSeconds = 4, int timeoutAfterMinutes = 0, Action<TaskResource[]> interval = null) { WaitForCompletion(new[] { task }, pollIntervalSeconds, timeoutAfterMinutes, interval); } public void WaitForCompletion(TaskResource[] tasks, int pollIntervalSeconds = 4, int timeoutAfterMinutes = 0, Action<TaskResource[]> interval = null) { var start = Stopwatch.StartNew(); if (tasks == null || tasks.Length == 0) return; while (true) { var stillRunning = (from task in tasks let currentStatus = Client.Get<TaskResource>(task.Link("Self")) select currentStatus).ToArray(); if (interval != null) { interval(stillRunning); } if (stillRunning.All(t => t.IsCompleted)) return; if (timeoutAfterMinutes > 0 && start.Elapsed.TotalMinutes > timeoutAfterMinutes) { throw new TimeoutException(string.Format("One or more tasks did not complete before the timeout was reached. We waited {0:n1} minutes for the tasks to complete.", start.Elapsed.TotalMinutes)); } Thread.Sleep(pollIntervalSeconds * 1000); } } public List<TaskResource> GetAllActive() => FindAll(pathParameters: new { active = true }); } }
50.078947
246
0.655176
[ "Apache-2.0" ]
roederja/OctopusClients
source/Octopus.Client/Repositories/TaskRepository.cs
9,515
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.Xml; using System.Text; using Microsoft.Test.ModuleCore; using System.IO; using XmlCoreTest.Common; using Xunit; namespace CoreXml.Test.XLinq { public partial class XNodeReaderFunctionalTests : TestModule { // Type is CoreXml.Test.XLinq.FunctionalTests // Test Module [Fact] [OuterLoop] public static void RunTests() { TestInput.CommandLine = ""; XNodeReaderFunctionalTests module = new XNodeReaderFunctionalTests(); module.Init(); module.AddChild(new XNodeReaderTests() { Attribute = new TestCaseAttribute() { Name = "XNodeReader", Desc = "XLinq XNodeReader Tests" } }); module.Execute(); Assert.False(module.HasFailures, module.GetFailuresInfo()); } #region Class public partial class XNodeReaderTests : XLinqTestCase { // Type is CoreXml.Test.XLinq.FunctionalTests+XNodeReaderTests public override void AddChildren() { this.AddChild(new TCDispose() { Attribute = new TestCaseAttribute() { Name = "Dispose", Desc = "Dispose" } }); this.AddChild(new TCDepth() { Attribute = new TestCaseAttribute() { Name = "Depth", Desc = "Depth" } }); this.AddChild(new TCNamespace() { Attribute = new TestCaseAttribute() { Name = "Namespace", Desc = "Namespace" } }); this.AddChild(new TCLookupNamespace() { Attribute = new TestCaseAttribute() { Name = "LookupNamespace", Desc = "LookupNamespace" } }); this.AddChild(new TCHasValue() { Attribute = new TestCaseAttribute() { Name = "HasValue", Desc = "HasValue" } }); this.AddChild(new TCIsEmptyElement2() { Attribute = new TestCaseAttribute() { Name = "IsEmptyElement", Desc = "IsEmptyElement" } }); this.AddChild(new TCXmlSpace() { Attribute = new TestCaseAttribute() { Name = "XmlSpace", Desc = "XmlSpace" } }); this.AddChild(new TCXmlLang() { Attribute = new TestCaseAttribute() { Name = "XmlLang", Desc = "XmlLang" } }); this.AddChild(new TCSkip() { Attribute = new TestCaseAttribute() { Name = "Skip", Desc = "Skip" } }); this.AddChild(new TCIsDefault() { Attribute = new TestCaseAttribute() { Name = "IsDefault", Desc = "IsDefault" } }); this.AddChild(new TCBaseURI() { Attribute = new TestCaseAttribute() { Name = "BaseUri", Desc = "BaseUri" } }); this.AddChild(new TCAttributeAccess() { Attribute = new TestCaseAttribute() { Name = "AttributeAccess", Desc = "AttributeAccess" } }); this.AddChild(new TCThisName() { Attribute = new TestCaseAttribute() { Name = "ThisName", Desc = "ThisName" } }); this.AddChild(new TCMoveToAttributeReader() { Attribute = new TestCaseAttribute() { Name = "MoveToAttribute", Desc = "MoveToAttribute" } }); this.AddChild(new TCGetAttributeOrdinal() { Attribute = new TestCaseAttribute() { Name = "GetAttributeOrdinal", Desc = "GetAttributeOrdinal" } }); this.AddChild(new TCGetAttributeName() { Attribute = new TestCaseAttribute() { Name = "GetAttributeName", Desc = "GetAttributeName" } }); this.AddChild(new TCThisOrdinal() { Attribute = new TestCaseAttribute() { Name = "ThisOrdinal", Desc = "ThisOrdinal" } }); this.AddChild(new TCMoveToAttributeOrdinal() { Attribute = new TestCaseAttribute() { Name = "MoveToAttributeOrdinal", Desc = "MoveToAttributeOrdinal" } }); this.AddChild(new TCMoveToFirstAttribute() { Attribute = new TestCaseAttribute() { Name = "MoveToFirstAttribute", Desc = "MoveToFirstAttribute" } }); this.AddChild(new TCMoveToNextAttribute() { Attribute = new TestCaseAttribute() { Name = "MoveToNextAttribute", Desc = "MoveToNextAttribute" } }); this.AddChild(new TCAttributeTest() { Attribute = new TestCaseAttribute() { Name = "AttributeTest", Desc = "AttributeTest" } }); this.AddChild(new TCXmlns() { Attribute = new TestCaseAttribute() { Name = "Xlmns", Desc = "Xlmns" } }); this.AddChild(new TCXmlnsPrefix() { Attribute = new TestCaseAttribute() { Name = "XlmnsPrefix", Desc = "XlmnsPrefix" } }); this.AddChild(new TCReadState() { Attribute = new TestCaseAttribute() { Name = "ReadState", Desc = "ReadState" } }); this.AddChild(new TCReadInnerXml() { Attribute = new TestCaseAttribute() { Name = "ReadInnerXml", Desc = "ReadInnerXml" } }); this.AddChild(new TCMoveToContent() { Attribute = new TestCaseAttribute() { Name = "MoveToContent", Desc = "MoveToContent" } }); this.AddChild(new TCIsStartElement() { Attribute = new TestCaseAttribute() { Name = "IsStartElement", Desc = "IsStartElement" } }); this.AddChild(new TCReadStartElement() { Attribute = new TestCaseAttribute() { Name = "ReadStartElement", Desc = "ReadStartElement" } }); this.AddChild(new TCReadEndElement() { Attribute = new TestCaseAttribute() { Name = "ReadEndElement", Desc = "ReadEndElement" } }); this.AddChild(new TCMoveToElement() { Attribute = new TestCaseAttribute() { Name = "MoveToElement", Desc = "MoveToElement" } }); this.AddChild(new ErrorConditions() { Attribute = new TestCaseAttribute() { Name = "ErrorConditions" } }); this.AddChild(new TCXMLIntegrityBase() { Attribute = new TestCaseAttribute() { Name = "XMLIntegrityBase", Desc = "XMLIntegrityBase" } }); this.AddChild(new TCReadContentAsBase64() { Attribute = new TestCaseAttribute() { Name = "ReadContentAsBase64", Desc = "ReadContentAsBase64" } }); this.AddChild(new TCReadElementContentAsBase64() { Attribute = new TestCaseAttribute() { Name = "ReadElementContentAsBase64", Desc = "ReadElementContentAsBase64" } }); this.AddChild(new TCReadContentAsBinHex() { Attribute = new TestCaseAttribute() { Name = "ReadContentAsBinHex", Desc = "ReadContentAsBinHex" } }); this.AddChild(new TCReadElementContentAsBinHex() { Attribute = new TestCaseAttribute() { Name = "ReadElementContentAsBinHex", Desc = "ReadElementContentAsBinHex" } }); this.AddChild(new CReaderTestModule() { Attribute = new TestCaseAttribute() { Name = "ReaderProperty", Desc = "Reader Property" } }); this.AddChild(new TCReadOuterXml() { Attribute = new TestCaseAttribute() { Name = "ReadOuterXml", Desc = "ReadOuterXml" } }); this.AddChild(new TCReadSubtree() { Attribute = new TestCaseAttribute() { Name = "ReadSubtree", Desc = "ReadSubtree" } }); this.AddChild(new TCReadToDescendant() { Attribute = new TestCaseAttribute() { Name = "ReadToDescendant", Desc = "ReadToDescendant" } }); this.AddChild(new TCReadToFollowing() { Attribute = new TestCaseAttribute() { Name = "ReadToFollowing", Desc = "ReadToFollowing" } }); this.AddChild(new TCReadToNextSibling() { Attribute = new TestCaseAttribute() { Name = "ReadToNextSibling", Desc = "ReadToNextSibling" } }); this.AddChild(new TCReadValue() { Attribute = new TestCaseAttribute() { Name = "ReadValue", Desc = "ReadValue" } }); this.AddChild(new XNodeReaderAPI() { Attribute = new TestCaseAttribute() { Name = "API Tests" } }); } public partial class TCDispose : BridgeHelpers { // Type is CoreXml.Test.XLinq.FunctionalTests+XNodeReaderTests+TCDispose // Test Case public override void AddChildren() { this.AddChild(new TestVariation(Variation1) { Attribute = new VariationAttribute("Test Integrity of all values after Dispose") }); this.AddChild(new TestVariation(Variation2) { Attribute = new VariationAttribute("Call Dispose Multiple(3) Times") }); } } public partial class TCDepth : BridgeHelpers { // Type is CoreXml.Test.XLinq.FunctionalTests+XNodeReaderTests+TCDepth // Test Case public override void AddChildren() { this.AddChild(new TestVariation(TestDepth1) { Attribute = new VariationAttribute("XmlReader Depth at the Root") { Priority = 0 } }); this.AddChild(new TestVariation(TestDepth2) { Attribute = new VariationAttribute("XmlReader Depth at Empty Tag") }); this.AddChild(new TestVariation(TestDepth3) { Attribute = new VariationAttribute("XmlReader Depth at Empty Tag with Attributes") }); this.AddChild(new TestVariation(TestDepth4) { Attribute = new VariationAttribute("XmlReader Depth at Non Empty Tag with Text") }); } } public partial class TCNamespace : BridgeHelpers { // Type is CoreXml.Test.XLinq.FunctionalTests+XNodeReaderTests+TCNamespace // Test Case public override void AddChildren() { this.AddChild(new TestVariation(TestNamespace1) { Attribute = new VariationAttribute("Namespace test within a scope (no nested element)") { Priority = 0 } }); this.AddChild(new TestVariation(TestNamespace2) { Attribute = new VariationAttribute("Namespace test within a scope (with nested element)") { Priority = 0 } }); this.AddChild(new TestVariation(TestNamespace3) { Attribute = new VariationAttribute("Namespace test immediately outside the Namespace scope") }); this.AddChild(new TestVariation(TestNamespace4) { Attribute = new VariationAttribute("Namespace test Attribute should has no default namespace") { Priority = 0 } }); this.AddChild(new TestVariation(TestNamespace5) { Attribute = new VariationAttribute("Namespace test with multiple Namespace declaration") { Priority = 0 } }); this.AddChild(new TestVariation(TestNamespace6) { Attribute = new VariationAttribute("Namespace test with multiple Namespace declaration, including default namespace") }); this.AddChild(new TestVariation(TestNamespace7) { Attribute = new VariationAttribute("Namespace URI for xml prefix") { Priority = 0 } }); } } public partial class TCLookupNamespace : BridgeHelpers { // Type is CoreXml.Test.XLinq.FunctionalTests+XNodeReaderTests+TCLookupNamespace // Test Case public override void AddChildren() { this.AddChild(new TestVariation(LookupNamespace1) { Attribute = new VariationAttribute("LookupNamespace test within EmptyTag") }); this.AddChild(new TestVariation(LookupNamespace2) { Attribute = new VariationAttribute("LookupNamespace test with Default namespace within EmptyTag") { Priority = 0 } }); this.AddChild(new TestVariation(LookupNamespace3) { Attribute = new VariationAttribute("LookupNamespace test within a scope (no nested element)") { Priority = 0 } }); this.AddChild(new TestVariation(LookupNamespace4) { Attribute = new VariationAttribute("LookupNamespace test within a scope (with nested element)") { Priority = 0 } }); this.AddChild(new TestVariation(LookupNamespace5) { Attribute = new VariationAttribute("LookupNamespace test immediately outside the Namespace scope") }); this.AddChild(new TestVariation(LookupNamespace6) { Attribute = new VariationAttribute("LookupNamespace test with multiple Namespace declaration") { Priority = 0 } }); this.AddChild(new TestVariation(LookupNamespace7) { Attribute = new VariationAttribute("Namespace test with multiple Namespace declaration, including default namespace") }); this.AddChild(new TestVariation(LookupNamespace8) { Attribute = new VariationAttribute("LookupNamespace on whitespace node PreserveWhitespaces = true") { Priority = 0 } }); this.AddChild(new TestVariation(LookupNamespace9) { Attribute = new VariationAttribute("Different prefix on inner element for the same namespace") { Priority = 0 } }); this.AddChild(new TestVariation(LookupNamespace10) { Attribute = new VariationAttribute("LookupNamespace when Namespaces = false") { Priority = 0 } }); } } public partial class TCHasValue : BridgeHelpers { // Type is CoreXml.Test.XLinq.FunctionalTests+XNodeReaderTests+TCHasValue // Test Case public override void AddChildren() { this.AddChild(new TestVariation(TestHasValueNodeType_None) { Attribute = new VariationAttribute("HasValue On None") }); this.AddChild(new TestVariation(TestHasValueNodeType_Element) { Attribute = new VariationAttribute("HasValue On Element") { Priority = 0 } }); this.AddChild(new TestVariation(TestHasValue1) { Attribute = new VariationAttribute("Get node with a scalar value, verify the value with valid ReadString") }); this.AddChild(new TestVariation(TestHasValueNodeType_Attribute) { Attribute = new VariationAttribute("HasValue On Attribute") { Priority = 0 } }); this.AddChild(new TestVariation(TestHasValueNodeType_Text) { Attribute = new VariationAttribute("HasValue On Text") { Priority = 0 } }); this.AddChild(new TestVariation(TestHasValueNodeType_CDATA) { Attribute = new VariationAttribute("HasValue On CDATA") { Priority = 0 } }); this.AddChild(new TestVariation(TestHasValueNodeType_ProcessingInstruction) { Attribute = new VariationAttribute("HasValue On ProcessingInstruction") { Priority = 0 } }); this.AddChild(new TestVariation(TestHasValueNodeType_Comment) { Attribute = new VariationAttribute("HasValue On Comment") { Priority = 0 } }); this.AddChild(new TestVariation(TestHasValueNodeType_DocumentType) { Attribute = new VariationAttribute("HasValue On DocumentType") { Priority = 0 } }); this.AddChild(new TestVariation(TestHasValueNodeType_Whitespace) { Attribute = new VariationAttribute("HasValue On Whitespace PreserveWhitespaces = true") { Priority = 0 } }); this.AddChild(new TestVariation(TestHasValueNodeType_EndElement) { Attribute = new VariationAttribute("HasValue On EndElement") }); this.AddChild(new TestVariation(TestHasValueNodeType_XmlDeclaration) { Attribute = new VariationAttribute("HasValue On XmlDeclaration") { Priority = 0 } }); this.AddChild(new TestVariation(TestHasValueNodeType_EntityReference) { Attribute = new VariationAttribute("HasValue On EntityReference") }); this.AddChild(new TestVariation(TestHasValueNodeType_EndEntity) { Attribute = new VariationAttribute("HasValue On EndEntity") }); this.AddChild(new TestVariation(v13) { Attribute = new VariationAttribute("PI Value containing surrogates") { Priority = 0 } }); } } public partial class TCIsEmptyElement2 : BridgeHelpers { // Type is CoreXml.Test.XLinq.FunctionalTests+XNodeReaderTests+TCIsEmptyElement2 // Test Case public override void AddChildren() { this.AddChild(new TestVariation(TestEmpty1) { Attribute = new VariationAttribute("Set and Get an element that ends with />") { Priority = 0 } }); this.AddChild(new TestVariation(TestEmpty2) { Attribute = new VariationAttribute("Set and Get an element with an attribute that ends with />") { Priority = 0 } }); this.AddChild(new TestVariation(TestEmpty3) { Attribute = new VariationAttribute("Set and Get an element that ends without />") { Priority = 0 } }); this.AddChild(new TestVariation(TestEmpty4) { Attribute = new VariationAttribute("Set and Get an element with an attribute that ends with />") { Priority = 0 } }); this.AddChild(new TestVariation(TestEmptyNodeType_Element) { Attribute = new VariationAttribute("IsEmptyElement On Element") { Priority = 0 } }); this.AddChild(new TestVariation(TestEmptyNodeType_None) { Attribute = new VariationAttribute("IsEmptyElement On None") }); this.AddChild(new TestVariation(TestEmptyNodeType_Text) { Attribute = new VariationAttribute("IsEmptyElement On Text") }); this.AddChild(new TestVariation(TestEmptyNodeType_CDATA) { Attribute = new VariationAttribute("IsEmptyElement On CDATA") }); this.AddChild(new TestVariation(TestEmptyNodeType_ProcessingInstruction) { Attribute = new VariationAttribute("IsEmptyElement On ProcessingInstruction") }); this.AddChild(new TestVariation(TestEmptyNodeType_Comment) { Attribute = new VariationAttribute("IsEmptyElement On Comment") }); this.AddChild(new TestVariation(TestEmptyNodeType_DocumentType) { Attribute = new VariationAttribute("IsEmptyElement On DocumentType") }); this.AddChild(new TestVariation(TestEmptyNodeType_Whitespace) { Attribute = new VariationAttribute("IsEmptyElement On Whitespace PreserveWhitespaces = true") }); this.AddChild(new TestVariation(TestEmptyNodeType_EndElement) { Attribute = new VariationAttribute("IsEmptyElement On EndElement") }); this.AddChild(new TestVariation(TestEmptyNodeType_EntityReference) { Attribute = new VariationAttribute("IsEmptyElement On EntityReference") }); this.AddChild(new TestVariation(TestEmptyNodeType_EndEntity) { Attribute = new VariationAttribute("IsEmptyElement On EndEntity") }); } } public partial class TCXmlSpace : BridgeHelpers { // Type is CoreXml.Test.XLinq.FunctionalTests+XNodeReaderTests+TCXmlSpace // Test Case public override void AddChildren() { this.AddChild(new TestVariation(TestXmlSpace1) { Attribute = new VariationAttribute("XmlSpace test within EmptyTag") }); this.AddChild(new TestVariation(TestXmlSpace2) { Attribute = new VariationAttribute("Xmlspace test within a scope (no nested element)") { Priority = 0 } }); this.AddChild(new TestVariation(TestXmlSpace3) { Attribute = new VariationAttribute("Xmlspace test within a scope (with nested element)") { Priority = 0 } }); this.AddChild(new TestVariation(TestXmlSpace4) { Attribute = new VariationAttribute("Xmlspace test immediately outside the XmlSpace scope") }); this.AddChild(new TestVariation(TestXmlSpace5) { Attribute = new VariationAttribute("XmlSpace test with multiple XmlSpace declaration") }); } } public partial class TCXmlLang : BridgeHelpers { // Type is CoreXml.Test.XLinq.FunctionalTests+XNodeReaderTests+TCXmlLang // Test Case public override void AddChildren() { this.AddChild(new TestVariation(TestXmlLang1) { Attribute = new VariationAttribute("XmlLang test within EmptyTag") }); this.AddChild(new TestVariation(TestXmlLang2) { Attribute = new VariationAttribute("XmlLang test within a scope (no nested element)") { Priority = 0 } }); this.AddChild(new TestVariation(TestXmlLang3) { Attribute = new VariationAttribute("XmlLang test within a scope (with nested element)") { Priority = 0 } }); this.AddChild(new TestVariation(TestXmlLang4) { Attribute = new VariationAttribute("XmlLang test immediately outside the XmlLang scope") }); this.AddChild(new TestVariation(TestXmlLang5) { Attribute = new VariationAttribute("XmlLang test with multiple XmlLang declaration") }); this.AddChild(new TestVariation(TestXmlLang6) { Attribute = new VariationAttribute("XmlLang valid values") { Priority = 0 } }); this.AddChild(new TestVariation(TestXmlTextReaderLang1) { Attribute = new VariationAttribute("More XmlLang valid values") }); } } public partial class TCSkip : BridgeHelpers { // Type is CoreXml.Test.XLinq.FunctionalTests+XNodeReaderTests+TCSkip // Test Case public override void AddChildren() { this.AddChild(new TestVariation(TestSkip1) { Attribute = new VariationAttribute("Call Skip on empty element") { Priority = 0 } }); this.AddChild(new TestVariation(TestSkip2) { Attribute = new VariationAttribute("Call Skip on element") { Priority = 0 } }); this.AddChild(new TestVariation(TestSkip3) { Attribute = new VariationAttribute("Call Skip on element with content") { Priority = 0 } }); this.AddChild(new TestVariation(TestSkip4) { Attribute = new VariationAttribute("Call Skip on text node (leave node)") { Priority = 0 } }); this.AddChild(new TestVariation(skip307543) { Attribute = new VariationAttribute("Call Skip in while read loop") { Priority = 0 } }); this.AddChild(new TestVariation(TestSkip5) { Attribute = new VariationAttribute("Call Skip on text node with another element: <elem2>text<elem3></elem3></elem2>") }); this.AddChild(new TestVariation(TestSkip6) { Attribute = new VariationAttribute("Call Skip on attribute") { Priority = 0 } }); this.AddChild(new TestVariation(TestSkip7) { Attribute = new VariationAttribute("Call Skip on text node of attribute") }); this.AddChild(new TestVariation(TestSkip8) { Attribute = new VariationAttribute("Call Skip on CDATA") { Priority = 0 } }); this.AddChild(new TestVariation(TestSkip9) { Attribute = new VariationAttribute("Call Skip on Processing Instruction") { Priority = 0 } }); this.AddChild(new TestVariation(TestSkip10) { Attribute = new VariationAttribute("Call Skip on Comment") { Priority = 0 } }); this.AddChild(new TestVariation(TestSkip12) { Attribute = new VariationAttribute("Call Skip on Whitespace") { Priority = 0 } }); this.AddChild(new TestVariation(TestSkip13) { Attribute = new VariationAttribute("Call Skip on EndElement") { Priority = 0 } }); this.AddChild(new TestVariation(TestSkip14) { Attribute = new VariationAttribute("Call Skip on root Element") }); this.AddChild(new TestVariation(XmlTextReaderDoesNotThrowWhenHandlingAmpersands) { Attribute = new VariationAttribute("XmlTextReader ArgumentOutOfRangeException when handling ampersands") }); } } public partial class TCBaseURI : BridgeHelpers { // Type is CoreXml.Test.XLinq.FunctionalTests+XNodeReaderTests+TCBaseURI // Test Case public override void AddChildren() { this.AddChild(new TestVariation(TestBaseURI1) { Attribute = new VariationAttribute("BaseURI for element node") { Priority = 0 } }); this.AddChild(new TestVariation(TestBaseURI2) { Attribute = new VariationAttribute("BaseURI for attribute node") { Priority = 0 } }); this.AddChild(new TestVariation(TestBaseURI3) { Attribute = new VariationAttribute("BaseURI for text node") { Priority = 0 } }); this.AddChild(new TestVariation(TestBaseURI4) { Attribute = new VariationAttribute("BaseURI for CDATA node") }); this.AddChild(new TestVariation(TestBaseURI6) { Attribute = new VariationAttribute("BaseURI for PI node") }); this.AddChild(new TestVariation(TestBaseURI7) { Attribute = new VariationAttribute("BaseURI for Comment node") }); this.AddChild(new TestVariation(TestBaseURI9) { Attribute = new VariationAttribute("BaseURI for Whitespace node PreserveWhitespaces = true") }); this.AddChild(new TestVariation(TestBaseURI10) { Attribute = new VariationAttribute("BaseURI for EndElement node") }); this.AddChild(new TestVariation(TestTextReaderBaseURI4) { Attribute = new VariationAttribute("BaseURI for external General Entity") }); } } public partial class TCAttributeAccess : BridgeHelpers { // Type is CoreXml.Test.XLinq.FunctionalTests+XNodeReaderTests+TCAttributeAccess // Test Case public override void AddChildren() { this.AddChild(new TestVariation(TestAttributeAccess1) { Attribute = new VariationAttribute("Attribute Access test using ordinal (Ascending Order)") { Priority = 0 } }); this.AddChild(new TestVariation(TestAttributeAccess2) { Attribute = new VariationAttribute("Attribute Access test using ordinal (Descending Order)") }); this.AddChild(new TestVariation(TestAttributeAccess3) { Attribute = new VariationAttribute("Attribute Access test using ordinal (Odd number)") { Priority = 0 } }); this.AddChild(new TestVariation(TestAttributeAccess4) { Attribute = new VariationAttribute("Attribute Access test using ordinal (Even number)") }); this.AddChild(new TestVariation(TestAttributeAccess5) { Attribute = new VariationAttribute("Attribute Access with namespace=null") }); } } public partial class TCThisName : BridgeHelpers { // Type is CoreXml.Test.XLinq.FunctionalTests+XNodeReaderTests+TCThisName // Test Case public override void AddChildren() { this.AddChild(new TestVariation(ThisWithName1) { Attribute = new VariationAttribute("This[Name] Verify with GetAttribute(Name)") { Priority = 0 } }); this.AddChild(new TestVariation(ThisWithName2) { Attribute = new VariationAttribute("This[Name, null] Verify with GetAttribute(Name)") }); this.AddChild(new TestVariation(ThisWithName3) { Attribute = new VariationAttribute("This[Name] Verify with GetAttribute(Name,null)") }); this.AddChild(new TestVariation(ThisWithName4) { Attribute = new VariationAttribute("This[Name, NamespaceURI] Verify with GetAttribute(Name, NamespaceURI)") { Priority = 0 } }); this.AddChild(new TestVariation(ThisWithName5) { Attribute = new VariationAttribute("This[Name, null] Verify not the same as GetAttribute(Name, NamespaceURI)") }); this.AddChild(new TestVariation(ThisWithName6) { Attribute = new VariationAttribute("This[Name, NamespaceURI] Verify not the same as GetAttribute(Name, null)") }); this.AddChild(new TestVariation(ThisWithName7) { Attribute = new VariationAttribute("This[Name] Verify with MoveToAttribute(Name)") { Priority = 0 } }); this.AddChild(new TestVariation(ThisWithName8) { Attribute = new VariationAttribute("This[Name, null] Verify with MoveToAttribute(Name)") }); this.AddChild(new TestVariation(ThisWithName9) { Attribute = new VariationAttribute("This[Name] Verify with MoveToAttribute(Name,null)") }); this.AddChild(new TestVariation(ThisWithName10) { Attribute = new VariationAttribute("This[Name, NamespaceURI] Verify not the same as MoveToAttribute(Name, null)") { Priority = 0 } }); this.AddChild(new TestVariation(ThisWithName11) { Attribute = new VariationAttribute("This[Name, null] Verify not the same as MoveToAttribute(Name, NamespaceURI)") }); this.AddChild(new TestVariation(ThisWithName12) { Attribute = new VariationAttribute("This[Name, namespace] Verify not the same as MoveToAttribute(Name, namespace)") }); this.AddChild(new TestVariation(ThisWithName13) { Attribute = new VariationAttribute("This(String.Empty)") }); this.AddChild(new TestVariation(ThisWithName14) { Attribute = new VariationAttribute("This[String.Empty,String.Empty]") }); this.AddChild(new TestVariation(ThisWithName15) { Attribute = new VariationAttribute("This[QName] Verify with GetAttribute(Name, NamespaceURI)") { Priority = 0 } }); this.AddChild(new TestVariation(ThisWithName16) { Attribute = new VariationAttribute("This[QName] invalid Qname") }); } } public partial class TCMoveToAttributeReader : BridgeHelpers { // Type is CoreXml.Test.XLinq.FunctionalTests+XNodeReaderTests+TCMoveToAttributeReader // Test Case public override void AddChildren() { this.AddChild(new TestVariation(MoveToAttributeWithName1) { Attribute = new VariationAttribute("MoveToAttribute(String.Empty)") }); this.AddChild(new TestVariation(MoveToAttributeWithName2) { Attribute = new VariationAttribute("MoveToAttribute(String.Empty,String.Empty)") }); } } public partial class TCGetAttributeOrdinal : BridgeHelpers { // Type is CoreXml.Test.XLinq.FunctionalTests+XNodeReaderTests+TCGetAttributeOrdinal // Test Case public override void AddChildren() { this.AddChild(new TestVariation(GetAttributeWithGetAttrDoubleQ) { Attribute = new VariationAttribute("GetAttribute(i) Verify with This[i] - Double Quote") { Priority = 0 } }); this.AddChild(new TestVariation(OrdinalWithGetAttrSingleQ) { Attribute = new VariationAttribute("GetAttribute[i] Verify with This[i] - Single Quote") }); this.AddChild(new TestVariation(GetAttributeWithMoveAttrDoubleQ) { Attribute = new VariationAttribute("GetAttribute(i) Verify with MoveToAttribute[i] - Double Quote") { Priority = 0 } }); this.AddChild(new TestVariation(GetAttributeWithMoveAttrSingleQ) { Attribute = new VariationAttribute("GetAttribute(i) Verify with MoveToAttribute[i] - Single Quote") }); this.AddChild(new TestVariation(NegativeOneOrdinal) { Attribute = new VariationAttribute("GetAttribute(i) NegativeOneOrdinal") { Priority = 0 } }); this.AddChild(new TestVariation(FieldCountOrdinal) { Attribute = new VariationAttribute("GetAttribute(i) FieldCountOrdinal") }); this.AddChild(new TestVariation(OrdinalPlusOne) { Attribute = new VariationAttribute("GetAttribute(i) OrdinalPlusOne") { Priority = 0 } }); this.AddChild(new TestVariation(OrdinalMinusOne) { Attribute = new VariationAttribute("GetAttribute(i) OrdinalMinusOne") }); } } public partial class TCGetAttributeName : BridgeHelpers { // Type is CoreXml.Test.XLinq.FunctionalTests+XNodeReaderTests+TCGetAttributeName // Test Case public override void AddChildren() { this.AddChild(new TestVariation(GetAttributeWithName1) { Attribute = new VariationAttribute("GetAttribute(Name) Verify with This[Name]") { Priority = 0 } }); this.AddChild(new TestVariation(GetAttributeWithName2) { Attribute = new VariationAttribute("GetAttribute(Name, null) Verify with This[Name]") }); this.AddChild(new TestVariation(GetAttributeWithName3) { Attribute = new VariationAttribute("GetAttribute(Name) Verify with This[Name,null]") }); this.AddChild(new TestVariation(GetAttributeWithName4) { Attribute = new VariationAttribute("GetAttribute(Name, NamespaceURI) Verify with This[Name, NamespaceURI]") { Priority = 0 } }); this.AddChild(new TestVariation(GetAttributeWithName5) { Attribute = new VariationAttribute("GetAttribute(Name, null) Verify not the same as This[Name, NamespaceURI]") }); this.AddChild(new TestVariation(GetAttributeWithName6) { Attribute = new VariationAttribute("GetAttribute(Name, NamespaceURI) Verify not the same as This[Name, null]") }); this.AddChild(new TestVariation(GetAttributeWithName7) { Attribute = new VariationAttribute("GetAttribute(Name) Verify with MoveToAttribute(Name)") }); this.AddChild(new TestVariation(GetAttributeWithName8) { Attribute = new VariationAttribute("GetAttribute(Name,null) Verify with MoveToAttribute(Name)") { Priority = 1 } }); this.AddChild(new TestVariation(GetAttributeWithName9) { Attribute = new VariationAttribute("GetAttribute(Name) Verify with MoveToAttribute(Name,null)") { Priority = 1 } }); this.AddChild(new TestVariation(GetAttributeWithName10) { Attribute = new VariationAttribute("GetAttribute(Name, NamespaceURI) Verify not the same as MoveToAttribute(Name, null)") }); this.AddChild(new TestVariation(GetAttributeWithName11) { Attribute = new VariationAttribute("GetAttribute(Name, null) Verify not the same as MoveToAttribute(Name, NamespaceURI)") }); this.AddChild(new TestVariation(GetAttributeWithName12) { Attribute = new VariationAttribute("GetAttribute(Name, namespace) Verify not the same as MoveToAttribute(Name, namespace)") }); this.AddChild(new TestVariation(GetAttributeWithName13) { Attribute = new VariationAttribute("GetAttribute(String.Empty)") }); this.AddChild(new TestVariation(GetAttributeWithName14) { Attribute = new VariationAttribute("GetAttribute(String.Empty,String.Empty)") }); } } public partial class TCThisOrdinal : BridgeHelpers { // Type is CoreXml.Test.XLinq.FunctionalTests+XNodeReaderTests+TCThisOrdinal // Test Case public override void AddChildren() { this.AddChild(new TestVariation(OrdinalWithGetAttrDoubleQ) { Attribute = new VariationAttribute("This[i] Verify with GetAttribute[i] - Double Quote") { Priority = 0 } }); this.AddChild(new TestVariation(OrdinalWithGetAttrSingleQ) { Attribute = new VariationAttribute("This[i] Verify with GetAttribute[i] - Single Quote") }); this.AddChild(new TestVariation(OrdinalWithMoveAttrSingleQ) { Attribute = new VariationAttribute("This[i] Verify with MoveToAttribute[i] - Single Quote") }); this.AddChild(new TestVariation(OrdinalWithMoveAttrDoubleQ) { Attribute = new VariationAttribute("This[i] Verify with MoveToAttribute[i] - Double Quote") { Priority = 0 } }); this.AddChild(new TestVariation(NegativeOneOrdinal) { Attribute = new VariationAttribute("ThisOrdinal NegativeOneOrdinal") { Priority = 0 } }); this.AddChild(new TestVariation(FieldCountOrdinal) { Attribute = new VariationAttribute("ThisOrdinal FieldCountOrdinal") }); this.AddChild(new TestVariation(OrdinalPlusOne) { Attribute = new VariationAttribute("ThisOrdinal OrdinalPlusOne") { Priority = 0 } }); this.AddChild(new TestVariation(OrdinalMinusOne) { Attribute = new VariationAttribute("ThisOrdinal OrdinalMinusOne") }); } } public partial class TCMoveToAttributeOrdinal : BridgeHelpers { // Type is CoreXml.Test.XLinq.FunctionalTests+XNodeReaderTests+TCMoveToAttributeOrdinal // Test Case public override void AddChildren() { this.AddChild(new TestVariation(MoveToAttributeWithGetAttrDoubleQ) { Attribute = new VariationAttribute("MoveToAttribute(i) Verify with This[i] - Double Quote") { Priority = 0 } }); this.AddChild(new TestVariation(MoveToAttributeWithGetAttrSingleQ) { Attribute = new VariationAttribute("MoveToAttribute(i) Verify with This[i] - Single Quote") }); this.AddChild(new TestVariation(MoveToAttributeWithMoveAttrDoubleQ) { Attribute = new VariationAttribute("MoveToAttribute(i) Verify with GetAttribute(i) - Double Quote") { Priority = 0 } }); this.AddChild(new TestVariation(MoveToAttributeWithMoveAttrSingleQ) { Attribute = new VariationAttribute("MoveToAttribute(i) Verify with GetAttribute[i] - Single Quote") }); this.AddChild(new TestVariation(NegativeOneOrdinal) { Attribute = new VariationAttribute("MoveToAttribute(i) NegativeOneOrdinal") { Priority = 0 } }); this.AddChild(new TestVariation(FieldCountOrdinal) { Attribute = new VariationAttribute("MoveToAttribute(i) FieldCountOrdinal") }); this.AddChild(new TestVariation(OrdinalPlusOne) { Attribute = new VariationAttribute("MoveToAttribute(i) OrdinalPlusOne") { Priority = 0 } }); this.AddChild(new TestVariation(OrdinalMinusOne) { Attribute = new VariationAttribute("MoveToAttribute(i) OrdinalMinusOne") }); } } public partial class TCMoveToFirstAttribute : BridgeHelpers { // Type is CoreXml.Test.XLinq.FunctionalTests+XNodeReaderTests+TCMoveToFirstAttribute // Test Case public override void AddChildren() { this.AddChild(new TestVariation(MoveToFirstAttribute1) { Attribute = new VariationAttribute("MoveToFirstAttribute() When AttributeCount=0, <EMPTY1/> ") { Priority = 0 } }); this.AddChild(new TestVariation(MoveToFirstAttribute2) { Attribute = new VariationAttribute("MoveToFirstAttribute() When AttributeCount=0, <NONEMPTY1>ABCDE</NONEMPTY1> ") }); this.AddChild(new TestVariation(MoveToFirstAttribute3) { Attribute = new VariationAttribute("MoveToFirstAttribute() When iOrdinal=0, with namespace") }); this.AddChild(new TestVariation(MoveToFirstAttribute4) { Attribute = new VariationAttribute("MoveToFirstAttribute() When iOrdinal=0, without namespace") }); this.AddChild(new TestVariation(MoveToFirstAttribute5) { Attribute = new VariationAttribute("MoveToFirstAttribute() When iOrdinal=mIddle, with namespace") }); this.AddChild(new TestVariation(MoveToFirstAttribute6) { Attribute = new VariationAttribute("MoveToFirstAttribute() When iOrdinal=mIddle, without namespace") }); this.AddChild(new TestVariation(MoveToFirstAttribute7) { Attribute = new VariationAttribute("MoveToFirstAttribute() When iOrdinal=end, with namespace") }); this.AddChild(new TestVariation(MoveToFirstAttribute8) { Attribute = new VariationAttribute("MoveToFirstAttribute() When iOrdinal=end, without namespace") }); } } public partial class TCMoveToNextAttribute : BridgeHelpers { // Type is CoreXml.Test.XLinq.FunctionalTests+XNodeReaderTests+TCMoveToNextAttribute // Test Case public override void AddChildren() { this.AddChild(new TestVariation(MoveToNextAttribute1) { Attribute = new VariationAttribute("MoveToNextAttribute() When AttributeCount=0, <EMPTY1/> ") { Priority = 0 } }); this.AddChild(new TestVariation(MoveToNextAttribute2) { Attribute = new VariationAttribute("MoveToNextAttribute() When AttributeCount=0, <NONEMPTY1>ABCDE</NONEMPTY1> ") }); this.AddChild(new TestVariation(MoveToNextAttribute3) { Attribute = new VariationAttribute("MoveToNextAttribute() When iOrdinal=0, with namespace") }); this.AddChild(new TestVariation(MoveToNextAttribute4) { Attribute = new VariationAttribute("MoveToNextAttribute() When iOrdinal=0, without namespace") }); this.AddChild(new TestVariation(MoveToFirstAttribute5) { Attribute = new VariationAttribute("MoveToFirstAttribute() When iOrdinal=mIddle, with namespace") }); this.AddChild(new TestVariation(MoveToFirstAttribute6) { Attribute = new VariationAttribute("MoveToFirstAttribute() When iOrdinal=mIddle, without namespace") }); this.AddChild(new TestVariation(MoveToFirstAttribute7) { Attribute = new VariationAttribute("MoveToFirstAttribute() When iOrdinal=end, with namespace") }); this.AddChild(new TestVariation(MoveToFirstAttribute8) { Attribute = new VariationAttribute("MoveToFirstAttribute() When iOrdinal=end, without namespace") }); } } public partial class TCAttributeTest : BridgeHelpers { // Type is CoreXml.Test.XLinq.FunctionalTests+XNodeReaderTests+TCAttributeTest // Test Case public override void AddChildren() { this.AddChild(new TestVariation(TestAttributeTestNodeType_None) { Attribute = new VariationAttribute("Attribute Test On None") }); this.AddChild(new TestVariation(TestAttributeTestNodeType_Element) { Attribute = new VariationAttribute("Attribute Test On Element") { Priority = 0 } }); this.AddChild(new TestVariation(TestAttributeTestNodeType_Text) { Attribute = new VariationAttribute("Attribute Test On Text") { Priority = 0 } }); this.AddChild(new TestVariation(TestAttributeTestNodeType_CDATA) { Attribute = new VariationAttribute("Attribute Test On CDATA") }); this.AddChild(new TestVariation(TestAttributeTestNodeType_ProcessingInstruction) { Attribute = new VariationAttribute("Attribute Test On ProcessingInstruction") }); this.AddChild(new TestVariation(TestAttributeTestNodeType_Comment) { Attribute = new VariationAttribute("AttributeTest On Comment") }); this.AddChild(new TestVariation(TestAttributeTestNodeType_DocumentType) { Attribute = new VariationAttribute("AttributeTest On DocumentType") { Priority = 0 } }); this.AddChild(new TestVariation(TestAttributeTestNodeType_Whitespace) { Attribute = new VariationAttribute("AttributeTest On Whitespace") }); this.AddChild(new TestVariation(TestAttributeTestNodeType_EndElement) { Attribute = new VariationAttribute("AttributeTest On EndElement") }); this.AddChild(new TestVariation(TestAttributeTestNodeType_XmlDeclaration) { Attribute = new VariationAttribute("AttributeTest On XmlDeclaration") { Priority = 0 } }); this.AddChild(new TestVariation(TestAttributeTestNodeType_EndEntity) { Attribute = new VariationAttribute("AttributeTest On EndEntity") }); } } public partial class TCXmlns : BridgeHelpers { // Type is CoreXml.Test.XLinq.FunctionalTests+XNodeReaderTests+TCXmlns // Test Case public override void AddChildren() { this.AddChild(new TestVariation(TXmlns1) { Attribute = new VariationAttribute("Name, LocalName, Prefix and Value with xmlns=ns attribute") { Priority = 0 } }); this.AddChild(new TestVariation(TXmlns2) { Attribute = new VariationAttribute("Name, LocalName, Prefix and Value with xmlns:p=ns attribute") }); this.AddChild(new TestVariation(TXmlns3) { Attribute = new VariationAttribute("LookupNamespace with xmlns=ns attribute") }); this.AddChild(new TestVariation(TXmlns4) { Attribute = new VariationAttribute("MoveToAttribute access on xmlns attribute") }); this.AddChild(new TestVariation(TXmlns5) { Attribute = new VariationAttribute("GetAttribute access on xmlns attribute") }); this.AddChild(new TestVariation(TXmlns6) { Attribute = new VariationAttribute("this[xmlns] attribute access") }); } } public partial class TCXmlnsPrefix : BridgeHelpers { // Type is CoreXml.Test.XLinq.FunctionalTests+XNodeReaderTests+TCXmlnsPrefix // Test Case public override void AddChildren() { this.AddChild(new TestVariation(TXmlnsPrefix1) { Attribute = new VariationAttribute("NamespaceURI of xmlns:a attribute") { Priority = 0 } }); this.AddChild(new TestVariation(TXmlnsPrefix2) { Attribute = new VariationAttribute("NamespaceURI of element/attribute with xmlns attribute") { Priority = 0 } }); this.AddChild(new TestVariation(TXmlnsPrefix3) { Attribute = new VariationAttribute("LookupNamespace with xmlns prefix") }); this.AddChild(new TestVariation(TXmlnsPrefix4) { Attribute = new VariationAttribute("Define prefix for 'www.w3.org/2000/xmlns'") { Priority = 0 } }); this.AddChild(new TestVariation(TXmlnsPrefix5) { Attribute = new VariationAttribute("Redefine namespace attached to xmlns prefix") }); } } public partial class TCReadState : BridgeHelpers { // Type is CoreXml.Test.XLinq.FunctionalTests+XNodeReaderTests+TCReadState // Test Case public override void AddChildren() { this.AddChild(new TestVariation(ReadState1) { Attribute = new VariationAttribute("XmlReader ReadState Initial") { Priority = 0 } }); this.AddChild(new TestVariation(ReadState2) { Attribute = new VariationAttribute("XmlReader ReadState Interactive") { Priority = 0 } }); this.AddChild(new TestVariation(ReadState3) { Attribute = new VariationAttribute("XmlReader ReadState EndOfFile") { Priority = 0 } }); this.AddChild(new TestVariation(ReadState4) { Attribute = new VariationAttribute("XmlReader ReadState Initial") { Priority = 0 } }); this.AddChild(new TestVariation(ReadState5) { Attribute = new VariationAttribute("XmlReader ReadState EndOfFile") { Priority = 0 } }); } } public partial class TCReadInnerXml : BridgeHelpers { // Type is CoreXml.Test.XLinq.FunctionalTests+XNodeReaderTests+TCReadInnerXml // Test Case public override void AddChildren() { this.AddChild(new TestVariation(TestReadInnerXml1) { Attribute = new VariationAttribute("ReadInnerXml on Empty Tag") { Priority = 0 } }); this.AddChild(new TestVariation(TestReadInnerXml2) { Attribute = new VariationAttribute("ReadInnerXml on non Empty Tag") { Priority = 0 } }); this.AddChild(new TestVariation(TestReadInnerXml3) { Attribute = new VariationAttribute("ReadInnerXml on non Empty Tag with text content") { Priority = 0 } }); this.AddChild(new TestVariation(TestReadInnerXml6) { Attribute = new VariationAttribute("ReadInnerXml with multiple Level of elements") }); this.AddChild(new TestVariation(TestReadInnerXml7) { Attribute = new VariationAttribute("ReadInnerXml with multiple Level of elements, text and attributes") { Priority = 0 } }); this.AddChild(new TestVariation(TestReadInnerXml8) { Attribute = new VariationAttribute("ReadInnerXml with entity references, EntityHandling = ExpandEntities") }); this.AddChild(new TestVariation(TestReadInnerXml9) { Attribute = new VariationAttribute("ReadInnerXml on attribute node") { Priority = 0 } }); this.AddChild(new TestVariation(TestReadInnerXml10) { Attribute = new VariationAttribute("ReadInnerXml on attribute node with entity reference in value") { Priority = 0 } }); this.AddChild(new TestVariation(TestReadInnerXml11) { Attribute = new VariationAttribute("ReadInnerXml on Text") { Priority = 0 } }); this.AddChild(new TestVariation(TestReadInnerXml12) { Attribute = new VariationAttribute("ReadInnerXml on CDATA") }); this.AddChild(new TestVariation(TestReadInnerXml13) { Attribute = new VariationAttribute("ReadInnerXml on ProcessingInstruction") }); this.AddChild(new TestVariation(TestReadInnerXml14) { Attribute = new VariationAttribute("ReadInnerXml on Comment") }); this.AddChild(new TestVariation(TestReadInnerXml16) { Attribute = new VariationAttribute("ReadInnerXml on EndElement") }); this.AddChild(new TestVariation(TestReadInnerXml17) { Attribute = new VariationAttribute("ReadInnerXml on XmlDeclaration") }); this.AddChild(new TestVariation(TestReadInnerXml18) { Attribute = new VariationAttribute("Current node after ReadInnerXml on element") { Priority = 0 } }); this.AddChild(new TestVariation(TestReadInnerXml19) { Attribute = new VariationAttribute("Current node after ReadInnerXml on element") }); this.AddChild(new TestVariation(TestTextReadInnerXml2) { Attribute = new VariationAttribute("ReadInnerXml with entity references, EntityHandling = ExpandCharEntites") }); this.AddChild(new TestVariation(TestTextReadInnerXml4) { Attribute = new VariationAttribute("ReadInnerXml on EntityReference") }); this.AddChild(new TestVariation(TestTextReadInnerXml5) { Attribute = new VariationAttribute("ReadInnerXml on EndEntity") }); this.AddChild(new TestVariation(TestTextReadInnerXml18) { Attribute = new VariationAttribute("One large element") }); } } public partial class TCMoveToContent : BridgeHelpers { // Type is CoreXml.Test.XLinq.FunctionalTests+XNodeReaderTests+TCMoveToContent // Test Case public override void AddChildren() { this.AddChild(new TestVariation(TestMoveToContent1) { Attribute = new VariationAttribute("MoveToContent on Skip XmlDeclaration") { Priority = 0 } }); this.AddChild(new TestVariation(TestMoveToContent2) { Attribute = new VariationAttribute("MoveToContent on Read through All valid Content Node(Element, Text, CDATA, and EndElement)") { Priority = 0 } }); this.AddChild(new TestVariation(TestMoveToContent3) { Attribute = new VariationAttribute("MoveToContent on Read through All invalid Content Node(PI, Comment and whitespace)") { Priority = 0 } }); this.AddChild(new TestVariation(TestMoveToContent4) { Attribute = new VariationAttribute("MoveToContent on Read through Mix valid and Invalid Content Node") }); this.AddChild(new TestVariation(TestMoveToContent5) { Attribute = new VariationAttribute("MoveToContent on Attribute") { Priority = 0 } }); } } public partial class TCIsStartElement : BridgeHelpers { // Type is CoreXml.Test.XLinq.FunctionalTests+XNodeReaderTests+TCIsStartElement // Test Case public override void AddChildren() { this.AddChild(new TestVariation(TestIsStartElement1) { Attribute = new VariationAttribute("IsStartElement on Regular Element, no namespace") { Priority = 0 } }); this.AddChild(new TestVariation(TestIsStartElement2) { Attribute = new VariationAttribute("IsStartElement on Empty Element, no namespace") { Priority = 0 } }); this.AddChild(new TestVariation(TestIsStartElement3) { Attribute = new VariationAttribute("IsStartElement on regular Element, with namespace") { Priority = 0 } }); this.AddChild(new TestVariation(TestIsStartElement4) { Attribute = new VariationAttribute("IsStartElement on Empty Tag, with default namespace") { Priority = 0 } }); this.AddChild(new TestVariation(TestIsStartElement5) { Attribute = new VariationAttribute("IsStartElement with Name=String.Empty") }); this.AddChild(new TestVariation(TestIsStartElement6) { Attribute = new VariationAttribute("IsStartElement on Empty Element with Name and Namespace=String.Empty") }); this.AddChild(new TestVariation(TestIsStartElement7) { Attribute = new VariationAttribute("IsStartElement on CDATA") }); this.AddChild(new TestVariation(TestIsStartElement8) { Attribute = new VariationAttribute("IsStartElement on EndElement, no namespace") }); this.AddChild(new TestVariation(TestIsStartElement9) { Attribute = new VariationAttribute("IsStartElement on EndElement, with namespace") }); this.AddChild(new TestVariation(TestIsStartElement10) { Attribute = new VariationAttribute("IsStartElement on Attribute") }); this.AddChild(new TestVariation(TestIsStartElement11) { Attribute = new VariationAttribute("IsStartElement on Text") }); this.AddChild(new TestVariation(TestIsStartElement12) { Attribute = new VariationAttribute("IsStartElement on ProcessingInstruction") }); this.AddChild(new TestVariation(TestIsStartElement13) { Attribute = new VariationAttribute("IsStartElement on Comment") }); } } public partial class TCReadStartElement : BridgeHelpers { // Type is CoreXml.Test.XLinq.FunctionalTests+XNodeReaderTests+TCReadStartElement // Test Case public override void AddChildren() { this.AddChild(new TestVariation(TestReadStartElement1) { Attribute = new VariationAttribute("ReadStartElement on Regular Element, no namespace") { Priority = 0 } }); this.AddChild(new TestVariation(TestReadStartElement2) { Attribute = new VariationAttribute("ReadStartElement on Empty Element, no namespace") { Priority = 0 } }); this.AddChild(new TestVariation(TestReadStartElement3) { Attribute = new VariationAttribute("ReadStartElement on regular Element, with namespace") { Priority = 0 } }); this.AddChild(new TestVariation(TestReadStartElement4) { Attribute = new VariationAttribute("Passing ns=String.EmptyErrorCase: ReadStartElement on regular Element, with namespace") { Priority = 0 } }); this.AddChild(new TestVariation(TestReadStartElement5) { Attribute = new VariationAttribute("Passing no ns: ReadStartElement on regular Element, with namespace") { Priority = 0 } }); this.AddChild(new TestVariation(TestReadStartElement6) { Attribute = new VariationAttribute("ReadStartElement on Empty Tag, with namespace") }); this.AddChild(new TestVariation(TestReadStartElement7) { Attribute = new VariationAttribute("ErrorCase: ReadStartElement on Empty Tag, with namespace, passing ns=String.Empty") }); this.AddChild(new TestVariation(TestReadStartElement8) { Attribute = new VariationAttribute("ReadStartElement on Empty Tag, with namespace, passing no ns") }); this.AddChild(new TestVariation(TestReadStartElement9) { Attribute = new VariationAttribute("ReadStartElement with Name=String.Empty") }); this.AddChild(new TestVariation(TestReadStartElement10) { Attribute = new VariationAttribute("ReadStartElement on Empty Element with Name and Namespace=String.Empty") }); this.AddChild(new TestVariation(TestReadStartElement11) { Attribute = new VariationAttribute("ReadStartElement on CDATA") }); this.AddChild(new TestVariation(TestReadStartElement12) { Attribute = new VariationAttribute("ReadStartElement() on EndElement, no namespace") }); this.AddChild(new TestVariation(TestReadStartElement13) { Attribute = new VariationAttribute("ReadStartElement(n) on EndElement, no namespace") }); this.AddChild(new TestVariation(TestReadStartElement14) { Attribute = new VariationAttribute("ReadStartElement(n, String.Empty) on EndElement, no namespace") }); this.AddChild(new TestVariation(TestReadStartElement15) { Attribute = new VariationAttribute("ReadStartElement() on EndElement, with namespace") }); this.AddChild(new TestVariation(TestReadStartElement16) { Attribute = new VariationAttribute("ReadStartElement(n,ns) on EndElement, with namespace") }); } } public partial class TCReadEndElement : BridgeHelpers { // Type is CoreXml.Test.XLinq.FunctionalTests+XNodeReaderTests+TCReadEndElement // Test Case public override void AddChildren() { this.AddChild(new TestVariation(TestReadEndElement3) { Attribute = new VariationAttribute("ReadEndElement on Start Element, no namespace") }); this.AddChild(new TestVariation(TestReadEndElement4) { Attribute = new VariationAttribute("ReadEndElement on Empty Element, no namespace") { Priority = 0 } }); this.AddChild(new TestVariation(TestReadEndElement5) { Attribute = new VariationAttribute("ReadEndElement on regular Element, with namespace") { Priority = 0 } }); this.AddChild(new TestVariation(TestReadEndElement6) { Attribute = new VariationAttribute("ReadEndElement on Empty Tag, with namespace") { Priority = 0 } }); this.AddChild(new TestVariation(TestReadEndElement7) { Attribute = new VariationAttribute("ReadEndElement on CDATA") }); this.AddChild(new TestVariation(TestReadEndElement9) { Attribute = new VariationAttribute("ReadEndElement on Text") }); this.AddChild(new TestVariation(TestReadEndElement10) { Attribute = new VariationAttribute("ReadEndElement on ProcessingInstruction") }); this.AddChild(new TestVariation(TestReadEndElement11) { Attribute = new VariationAttribute("ReadEndElement on Comment") }); this.AddChild(new TestVariation(TestReadEndElement13) { Attribute = new VariationAttribute("ReadEndElement on XmlDeclaration") }); this.AddChild(new TestVariation(TestTextReadEndElement1) { Attribute = new VariationAttribute("ReadEndElement on EntityReference") }); this.AddChild(new TestVariation(TestTextReadEndElement2) { Attribute = new VariationAttribute("ReadEndElement on EndEntity") }); } } public partial class TCMoveToElement : BridgeHelpers { // Type is CoreXml.Test.XLinq.FunctionalTests+XNodeReaderTests+TCMoveToElement // Test Case public override void AddChildren() { this.AddChild(new TestVariation(v1) { Attribute = new VariationAttribute("Attribute node") }); this.AddChild(new TestVariation(v2) { Attribute = new VariationAttribute("Element node") }); this.AddChild(new TestVariation(v5) { Attribute = new VariationAttribute("Comment node") }); } } public partial class ErrorConditions : BridgeHelpers { // Type is CoreXml.Test.XLinq.FunctionalTests+XNodeReaderTests+ErrorConditions // Test Case public override void AddChildren() { this.AddChild(new TestVariation(Variation1) { Attribute = new VariationAttribute("Move to Attribute using []") }); this.AddChild(new TestVariation(Variation2) { Attribute = new VariationAttribute("GetAttribute") }); this.AddChild(new TestVariation(Variation3) { Attribute = new VariationAttribute("IsStartElement") }); this.AddChild(new TestVariation(Variation4) { Attribute = new VariationAttribute("LookupNamespace") }); this.AddChild(new TestVariation(Variation5) { Attribute = new VariationAttribute("MoveToAttribute") }); this.AddChild(new TestVariation(Variation6) { Attribute = new VariationAttribute("Other APIs") }); this.AddChild(new TestVariation(Variation7) { Attribute = new VariationAttribute("ReadContentAs(null, null)") }); this.AddChild(new TestVariation(Variation8) { Attribute = new VariationAttribute("ReadContentAsBase64") }); this.AddChild(new TestVariation(Variation9) { Attribute = new VariationAttribute("ReadContentAsBinHex") }); this.AddChild(new TestVariation(Variation10) { Attribute = new VariationAttribute("ReadContentAsBoolean") }); this.AddChild(new TestVariation(Variation11b) { Attribute = new VariationAttribute("ReadContentAsDateTimeOffset") }); this.AddChild(new TestVariation(Variation12) { Attribute = new VariationAttribute("ReadContentAsDecimal") }); this.AddChild(new TestVariation(Variation13) { Attribute = new VariationAttribute("ReadContentAsDouble") }); this.AddChild(new TestVariation(Variation14) { Attribute = new VariationAttribute("ReadContentAsFloat") }); this.AddChild(new TestVariation(Variation15) { Attribute = new VariationAttribute("ReadContentAsInt") }); this.AddChild(new TestVariation(Variation16) { Attribute = new VariationAttribute("ReadContentAsLong") }); this.AddChild(new TestVariation(Variation17) { Attribute = new VariationAttribute("ReadElementContentAs(null, null)") }); this.AddChild(new TestVariation(Variation18) { Attribute = new VariationAttribute("ReadElementContentAsBase64") }); this.AddChild(new TestVariation(Variation19) { Attribute = new VariationAttribute("ReadElementContentAsBinHex") }); this.AddChild(new TestVariation(Variation20) { Attribute = new VariationAttribute("ReadElementContentAsBoolean") }); this.AddChild(new TestVariation(Variation22) { Attribute = new VariationAttribute("ReadElementContentAsDecimal") }); this.AddChild(new TestVariation(Variation23) { Attribute = new VariationAttribute("ReadElementContentAsDouble") }); this.AddChild(new TestVariation(Variation24) { Attribute = new VariationAttribute("ReadElementContentAsFloat") }); this.AddChild(new TestVariation(Variation25) { Attribute = new VariationAttribute("ReadElementContentAsInt") }); this.AddChild(new TestVariation(Variation26) { Attribute = new VariationAttribute("ReadElementContentAsLong") }); this.AddChild(new TestVariation(Variation27) { Attribute = new VariationAttribute("ReadElementContentAsObject") }); this.AddChild(new TestVariation(Variation28) { Attribute = new VariationAttribute("ReadElementContentAsString") }); this.AddChild(new TestVariation(Variation30) { Attribute = new VariationAttribute("ReadStartElement") }); this.AddChild(new TestVariation(Variation31) { Attribute = new VariationAttribute("ReadToDescendant(null)") }); this.AddChild(new TestVariation(Variation32) { Attribute = new VariationAttribute("ReadToDescendant(String.Empty)") }); this.AddChild(new TestVariation(Variation33) { Attribute = new VariationAttribute("ReadToFollowing(null)") }); this.AddChild(new TestVariation(Variation34) { Attribute = new VariationAttribute("ReadToFollowing(String.Empty)") }); this.AddChild(new TestVariation(Variation35) { Attribute = new VariationAttribute("ReadToNextSibling(null)") }); this.AddChild(new TestVariation(Variation36) { Attribute = new VariationAttribute("ReadToNextSibling(String.Empty)") }); this.AddChild(new TestVariation(Variation37) { Attribute = new VariationAttribute("ReadValueChunk") }); this.AddChild(new TestVariation(Variation38) { Attribute = new VariationAttribute("ReadElementContentAsObject") }); this.AddChild(new TestVariation(Variation39) { Attribute = new VariationAttribute("ReadElementContentAsString") }); } } public partial class TCXMLIntegrityBase : BridgeHelpers { // Type is CoreXml.Test.XLinq.FunctionalTests+XNodeReaderTests+TCXMLIntegrityBase // Test Case public override void AddChildren() { this.AddChild(new TestVariation(GetXmlReaderNodeType) { Attribute = new VariationAttribute("NodeType") }); this.AddChild(new TestVariation(GetXmlReaderName) { Attribute = new VariationAttribute("Name") }); this.AddChild(new TestVariation(GetXmlReaderLocalName) { Attribute = new VariationAttribute("LocalName") }); this.AddChild(new TestVariation(Namespace) { Attribute = new VariationAttribute("NamespaceURI") }); this.AddChild(new TestVariation(Prefix) { Attribute = new VariationAttribute("Prefix") }); this.AddChild(new TestVariation(HasValue) { Attribute = new VariationAttribute("HasValue") }); this.AddChild(new TestVariation(GetXmlReaderValue) { Attribute = new VariationAttribute("Value") }); this.AddChild(new TestVariation(GetDepth) { Attribute = new VariationAttribute("Depth") }); this.AddChild(new TestVariation(GetBaseURI) { Attribute = new VariationAttribute("BaseURI") }); this.AddChild(new TestVariation(IsEmptyElement) { Attribute = new VariationAttribute("IsEmptyElement") }); this.AddChild(new TestVariation(IsDefault) { Attribute = new VariationAttribute("IsDefault") }); this.AddChild(new TestVariation(GetXmlSpace) { Attribute = new VariationAttribute("XmlSpace") }); this.AddChild(new TestVariation(GetXmlLang) { Attribute = new VariationAttribute("XmlLang") }); this.AddChild(new TestVariation(AttributeCount) { Attribute = new VariationAttribute("AttributeCount") }); this.AddChild(new TestVariation(HasAttribute) { Attribute = new VariationAttribute("HasAttributes") }); this.AddChild(new TestVariation(GetAttributeName) { Attribute = new VariationAttribute("GetAttributes(name)") }); this.AddChild(new TestVariation(GetAttributeEmptyName) { Attribute = new VariationAttribute("GetAttribute(String.Empty)") }); this.AddChild(new TestVariation(GetAttributeNameNamespace) { Attribute = new VariationAttribute("GetAttribute(name,ns)") }); this.AddChild(new TestVariation(GetAttributeEmptyNameNamespace) { Attribute = new VariationAttribute("GetAttribute(String.Empty, String.Empty)") }); this.AddChild(new TestVariation(GetAttributeOrdinal) { Attribute = new VariationAttribute("GetAttribute(i)") }); this.AddChild(new TestVariation(HelperThisOrdinal) { Attribute = new VariationAttribute("this[i]") }); this.AddChild(new TestVariation(HelperThisName) { Attribute = new VariationAttribute("this[name]") }); this.AddChild(new TestVariation(HelperThisNameNamespace) { Attribute = new VariationAttribute("this[name,namespace]") }); this.AddChild(new TestVariation(MoveToAttributeName) { Attribute = new VariationAttribute("MoveToAttribute(name)") }); this.AddChild(new TestVariation(MoveToAttributeNameNamespace) { Attribute = new VariationAttribute("MoveToAttributeNameNamespace(name,ns)") }); this.AddChild(new TestVariation(MoveToAttributeOrdinal) { Attribute = new VariationAttribute("MoveToAttribute(i)") }); this.AddChild(new TestVariation(MoveToFirstAttribute) { Attribute = new VariationAttribute("MoveToFirstAttribute()") }); this.AddChild(new TestVariation(MoveToNextAttribute) { Attribute = new VariationAttribute("MoveToNextAttribute()") }); this.AddChild(new TestVariation(MoveToElement) { Attribute = new VariationAttribute("MoveToElement()") }); this.AddChild(new TestVariation(ReadTestAfterClose) { Attribute = new VariationAttribute("Read") }); this.AddChild(new TestVariation(GetEOF) { Attribute = new VariationAttribute("GetEOF") }); this.AddChild(new TestVariation(GetReadState) { Attribute = new VariationAttribute("GetReadState") }); this.AddChild(new TestVariation(XMLSkip) { Attribute = new VariationAttribute("Skip") }); this.AddChild(new TestVariation(TestNameTable) { Attribute = new VariationAttribute("NameTable") }); this.AddChild(new TestVariation(ReadInnerXmlTestAfterClose) { Attribute = new VariationAttribute("ReadInnerXml") }); this.AddChild(new TestVariation(TestReadOuterXml) { Attribute = new VariationAttribute("ReadOuterXml") }); this.AddChild(new TestVariation(TestMoveToContent) { Attribute = new VariationAttribute("MoveToContent") }); this.AddChild(new TestVariation(TestIsStartElement) { Attribute = new VariationAttribute("IsStartElement") }); this.AddChild(new TestVariation(TestIsStartElementName) { Attribute = new VariationAttribute("IsStartElement(name)") }); this.AddChild(new TestVariation(TestIsStartElementName2) { Attribute = new VariationAttribute("IsStartElement(String.Empty)") }); this.AddChild(new TestVariation(TestIsStartElementNameNs) { Attribute = new VariationAttribute("IsStartElement(name, ns)") }); this.AddChild(new TestVariation(TestIsStartElementNameNs2) { Attribute = new VariationAttribute("IsStartElement(String.Empty,String.Empty)") }); this.AddChild(new TestVariation(TestReadStartElement) { Attribute = new VariationAttribute("ReadStartElement") }); this.AddChild(new TestVariation(TestReadStartElementName) { Attribute = new VariationAttribute("ReadStartElement(name)") }); this.AddChild(new TestVariation(TestReadStartElementName2) { Attribute = new VariationAttribute("ReadStartElement(String.Empty)") }); this.AddChild(new TestVariation(TestReadStartElementNameNs) { Attribute = new VariationAttribute("ReadStartElement(name, ns)") }); this.AddChild(new TestVariation(TestReadStartElementNameNs2) { Attribute = new VariationAttribute("ReadStartElement(String.Empty,String.Empty)") }); this.AddChild(new TestVariation(TestReadEndElement) { Attribute = new VariationAttribute("ReadEndElement") }); this.AddChild(new TestVariation(LookupNamespace) { Attribute = new VariationAttribute("LookupNamespace") }); this.AddChild(new TestVariation(ReadAttributeValue) { Attribute = new VariationAttribute("ReadAttributeValue") }); this.AddChild(new TestVariation(CloseTest) { Attribute = new VariationAttribute("Close") }); } } public partial class TCReadContentAsBase64 : BridgeHelpers { // Type is CoreXml.Test.XLinq.FunctionalTests+XNodeReaderTests+TCReadContentAsBase64 // Test Case public override void AddChildren() { this.AddChild(new TestVariation(TestReadBase64_1) { Attribute = new VariationAttribute("ReadBase64 Element with all valid value") }); this.AddChild(new TestVariation(TestReadBase64_2) { Attribute = new VariationAttribute("ReadBase64 Element with all valid Num value") { Priority = 0 } }); this.AddChild(new TestVariation(TestReadBase64_3) { Attribute = new VariationAttribute("ReadBase64 Element with all valid Text value") }); this.AddChild(new TestVariation(TestReadBase64_5) { Attribute = new VariationAttribute("ReadBase64 Element with all valid value (from concatenation), Priority=0") }); this.AddChild(new TestVariation(TestReadBase64_6) { Attribute = new VariationAttribute("ReadBase64 Element with Long valid value (from concatenation), Priority=0") }); this.AddChild(new TestVariation(ReadBase64_7) { Attribute = new VariationAttribute("ReadBase64 with count > buffer size") }); this.AddChild(new TestVariation(ReadBase64_8) { Attribute = new VariationAttribute("ReadBase64 with count < 0") }); this.AddChild(new TestVariation(ReadBase64_9) { Attribute = new VariationAttribute("ReadBase64 with index > buffer size") }); this.AddChild(new TestVariation(ReadBase64_10) { Attribute = new VariationAttribute("ReadBase64 with index < 0") }); this.AddChild(new TestVariation(ReadBase64_11) { Attribute = new VariationAttribute("ReadBase64 with index + count exceeds buffer") }); this.AddChild(new TestVariation(ReadBase64_12) { Attribute = new VariationAttribute("ReadBase64 index & count =0") }); this.AddChild(new TestVariation(TestReadBase64_13) { Attribute = new VariationAttribute("ReadBase64 Element multiple into same buffer (using offset), Priority=0") }); this.AddChild(new TestVariation(TestReadBase64_14) { Attribute = new VariationAttribute("ReadBase64 with buffer == null") }); this.AddChild(new TestVariation(TestReadBase64_15) { Attribute = new VariationAttribute("ReadBase64 after failure") }); this.AddChild(new TestVariation(TestReadBase64_16) { Attribute = new VariationAttribute("Read after partial ReadBase64") { Priority = 0 } }); this.AddChild(new TestVariation(TestReadBase64_17) { Attribute = new VariationAttribute("Current node on multiple calls") }); this.AddChild(new TestVariation(TestReadBase64_18) { Attribute = new VariationAttribute("No op node types") }); this.AddChild(new TestVariation(TestTextReadBase64_23) { Attribute = new VariationAttribute("ReadBase64 with incomplete sequence") }); this.AddChild(new TestVariation(TestTextReadBase64_24) { Attribute = new VariationAttribute("ReadBase64 when end tag doesn't exist") }); this.AddChild(new TestVariation(TestTextReadBase64_26) { Attribute = new VariationAttribute("ReadBase64 with whitespace in the mIddle") }); this.AddChild(new TestVariation(TestTextReadBase64_27) { Attribute = new VariationAttribute("ReadBase64 with = in the mIddle") }); this.AddChild(new TestVariation(RunBase64DoesnNotRunIntoOverflow) { Attribute = new VariationAttribute("ReadBase64 runs into an Overflow") { Params = new object[] { "10000000" } } }); this.AddChild(new TestVariation(RunBase64DoesnNotRunIntoOverflow) { Attribute = new VariationAttribute("ReadBase64 runs into an Overflow") { Params = new object[] { "1000000" } } }); this.AddChild(new TestVariation(RunBase64DoesnNotRunIntoOverflow) { Attribute = new VariationAttribute("ReadBase64 runs into an Overflow") { Params = new object[] { "10000" } } }); } } public partial class TCReadElementContentAsBase64 : BridgeHelpers { // Type is CoreXml.Test.XLinq.FunctionalTests+XNodeReaderTests+TCReadElementContentAsBase64 // Test Case public override void AddChildren() { this.AddChild(new TestVariation(TestReadBase64_1) { Attribute = new VariationAttribute("ReadBase64 Element with all valid value") }); this.AddChild(new TestVariation(TestReadBase64_2) { Attribute = new VariationAttribute("ReadBase64 Element with all valid Num value") { Priority = 0 } }); this.AddChild(new TestVariation(TestReadBase64_3) { Attribute = new VariationAttribute("ReadBase64 Element with all valid Text value") }); this.AddChild(new TestVariation(TestReadBase64_5) { Attribute = new VariationAttribute("ReadBase64 Element with all valid value (from concatenation), Priority=0") }); this.AddChild(new TestVariation(TestReadBase64_6) { Attribute = new VariationAttribute("ReadBase64 Element with Long valid value (from concatenation), Priority=0") }); this.AddChild(new TestVariation(ReadBase64_7) { Attribute = new VariationAttribute("ReadBase64 with count > buffer size") }); this.AddChild(new TestVariation(ReadBase64_8) { Attribute = new VariationAttribute("ReadBase64 with count < 0") }); this.AddChild(new TestVariation(ReadBase64_9) { Attribute = new VariationAttribute("ReadBase64 with index > buffer size") }); this.AddChild(new TestVariation(ReadBase64_10) { Attribute = new VariationAttribute("ReadBase64 with index < 0") }); this.AddChild(new TestVariation(ReadBase64_11) { Attribute = new VariationAttribute("ReadBase64 with index + count exceeds buffer") }); this.AddChild(new TestVariation(ReadBase64_12) { Attribute = new VariationAttribute("ReadBase64 index & count =0") }); this.AddChild(new TestVariation(TestReadBase64_13) { Attribute = new VariationAttribute("ReadBase64 Element multiple into same buffer (using offset), Priority=0") }); this.AddChild(new TestVariation(TestReadBase64_14) { Attribute = new VariationAttribute("ReadBase64 with buffer == null") }); this.AddChild(new TestVariation(TestReadBase64_15) { Attribute = new VariationAttribute("ReadBase64 after failure") }); this.AddChild(new TestVariation(TestReadBase64_16) { Attribute = new VariationAttribute("Read after partial ReadBase64") { Priority = 0 } }); this.AddChild(new TestVariation(TestReadBase64_17) { Attribute = new VariationAttribute("Current node on multiple calls") }); this.AddChild(new TestVariation(TestTextReadBase64_23) { Attribute = new VariationAttribute("ReadBase64 with incomplete sequence") }); this.AddChild(new TestVariation(TestTextReadBase64_24) { Attribute = new VariationAttribute("ReadBase64 when end tag doesn't exist") }); this.AddChild(new TestVariation(TestTextReadBase64_26) { Attribute = new VariationAttribute("ReadBase64 with whitespace in the mIddle") }); this.AddChild(new TestVariation(TestTextReadBase64_27) { Attribute = new VariationAttribute("ReadBase64 with = in the mIddle") }); this.AddChild(new TestVariation(ReadBase64DoesNotRunIntoOverflow2) { Attribute = new VariationAttribute("105376: ReadBase64 runs into an Overflow") { Params = new object[] { "10000000" } } }); this.AddChild(new TestVariation(ReadBase64DoesNotRunIntoOverflow2) { Attribute = new VariationAttribute("105376: ReadBase64 runs into an Overflow") { Params = new object[] { "1000000" } } }); this.AddChild(new TestVariation(ReadBase64DoesNotRunIntoOverflow2) { Attribute = new VariationAttribute("105376: ReadBase64 runs into an Overflow") { Params = new object[] { "10000" } } }); this.AddChild(new TestVariation(SubtreeReaderInsertedAttributesWontWorkWithReadContentAsBase64) { Attribute = new VariationAttribute("430329: SubtreeReader inserted attributes don't work with ReadContentAsBase64") }); } } public partial class TCReadContentAsBinHex : BridgeHelpers { // Type is CoreXml.Test.XLinq.FunctionalTests+XNodeReaderTests+TCReadContentAsBinHex // Test Case public override void AddChildren() { this.AddChild(new TestVariation(TestReadBinHex_1) { Attribute = new VariationAttribute("ReadBinHex Element with all valid value") }); this.AddChild(new TestVariation(TestReadBinHex_2) { Attribute = new VariationAttribute("ReadBinHex Element with all valid Num value") { Priority = 0 } }); this.AddChild(new TestVariation(TestReadBinHex_3) { Attribute = new VariationAttribute("ReadBinHex Element with all valid Text value") }); this.AddChild(new TestVariation(TestReadBinHex_4) { Attribute = new VariationAttribute("ReadBinHex Element on CDATA") { Priority = 0 } }); this.AddChild(new TestVariation(TestReadBinHex_5) { Attribute = new VariationAttribute("ReadBinHex Element with all valid value (from concatenation), Priority=0") }); this.AddChild(new TestVariation(TestReadBinHex_6) { Attribute = new VariationAttribute("ReadBinHex Element with all long valid value (from concatenation)") }); this.AddChild(new TestVariation(TestReadBinHex_7) { Attribute = new VariationAttribute("ReadBinHex with count > buffer size") }); this.AddChild(new TestVariation(TestReadBinHex_8) { Attribute = new VariationAttribute("ReadBinHex with count < 0") }); this.AddChild(new TestVariation(vReadBinHex_9) { Attribute = new VariationAttribute("ReadBinHex with index > buffer size") }); this.AddChild(new TestVariation(TestReadBinHex_10) { Attribute = new VariationAttribute("ReadBinHex with index < 0") }); this.AddChild(new TestVariation(TestReadBinHex_11) { Attribute = new VariationAttribute("ReadBinHex with index + count exceeds buffer") }); this.AddChild(new TestVariation(TestReadBinHex_12) { Attribute = new VariationAttribute("ReadBinHex index & count =0") }); this.AddChild(new TestVariation(TestReadBinHex_13) { Attribute = new VariationAttribute("ReadBinHex Element multiple into same buffer (using offset), Priority=0") }); this.AddChild(new TestVariation(TestReadBinHex_14) { Attribute = new VariationAttribute("ReadBinHex with buffer == null") }); this.AddChild(new TestVariation(TestReadBinHex_15) { Attribute = new VariationAttribute("ReadBinHex after failed ReadBinHex") }); this.AddChild(new TestVariation(TestReadBinHex_16) { Attribute = new VariationAttribute("Read after partial ReadBinHex") }); this.AddChild(new TestVariation(TestReadBinHex_17) { Attribute = new VariationAttribute("Current node on multiple calls") }); this.AddChild(new TestVariation(TestTextReadBinHex_21) { Attribute = new VariationAttribute("ReadBinHex with whitespace") }); this.AddChild(new TestVariation(TestTextReadBinHex_22) { Attribute = new VariationAttribute("ReadBinHex with odd number of chars") }); this.AddChild(new TestVariation(TestTextReadBinHex_23) { Attribute = new VariationAttribute("ReadBinHex when end tag doesn't exist") }); this.AddChild(new TestVariation(TestTextReadBinHex_24) { Attribute = new VariationAttribute("WS:WireCompat:hex binary fails to send/return data after 1787 bytes going Whidbey to Everett") }); this.AddChild(new TestVariation(DebugAssertInReadContentAsBinHex) { Attribute = new VariationAttribute("DebugAssert in ReadContentAsBinHex") }); } } public partial class TCReadElementContentAsBinHex : BridgeHelpers { // Type is CoreXml.Test.XLinq.FunctionalTests+XNodeReaderTests+TCReadElementContentAsBinHex // Test Case public override void AddChildren() { this.AddChild(new TestVariation(TestReadBinHex_1) { Attribute = new VariationAttribute("ReadBinHex Element with all valid value") }); this.AddChild(new TestVariation(TestReadBinHex_2) { Attribute = new VariationAttribute("ReadBinHex Element with all valid Num value") { Priority = 0 } }); this.AddChild(new TestVariation(TestReadBinHex_3) { Attribute = new VariationAttribute("ReadBinHex Element with all valid Text value") }); this.AddChild(new TestVariation(TestReadBinHex_4) { Attribute = new VariationAttribute("ReadBinHex Element with Comments and PIs") { Priority = 0 } }); this.AddChild(new TestVariation(TestReadBinHex_5) { Attribute = new VariationAttribute("ReadBinHex Element with all valid value (from concatenation), Priority=0") }); this.AddChild(new TestVariation(TestReadBinHex_6) { Attribute = new VariationAttribute("ReadBinHex Element with all long valid value (from concatenation)") }); this.AddChild(new TestVariation(TestReadBinHex_7) { Attribute = new VariationAttribute("ReadBinHex with count > buffer size") }); this.AddChild(new TestVariation(TestReadBinHex_8) { Attribute = new VariationAttribute("ReadBinHex with count < 0") }); this.AddChild(new TestVariation(vReadBinHex_9) { Attribute = new VariationAttribute("ReadBinHex with index > buffer size") }); this.AddChild(new TestVariation(TestReadBinHex_10) { Attribute = new VariationAttribute("ReadBinHex with index < 0") }); this.AddChild(new TestVariation(TestReadBinHex_11) { Attribute = new VariationAttribute("ReadBinHex with index + count exceeds buffer") }); this.AddChild(new TestVariation(TestReadBinHex_12) { Attribute = new VariationAttribute("ReadBinHex index & count =0") }); this.AddChild(new TestVariation(TestReadBinHex_13) { Attribute = new VariationAttribute("ReadBinHex Element multiple into same buffer (using offset), Priority=0") }); this.AddChild(new TestVariation(TestReadBinHex_14) { Attribute = new VariationAttribute("ReadBinHex with buffer == null") }); this.AddChild(new TestVariation(TestReadBinHex_15) { Attribute = new VariationAttribute("ReadBinHex after failed ReadBinHex") }); this.AddChild(new TestVariation(TestReadBinHex_16) { Attribute = new VariationAttribute("Read after partial ReadBinHex") }); this.AddChild(new TestVariation(TestTextReadBinHex_21) { Attribute = new VariationAttribute("ReadBinHex with whitespace") }); this.AddChild(new TestVariation(TestTextReadBinHex_22) { Attribute = new VariationAttribute("ReadBinHex with odd number of chars") }); this.AddChild(new TestVariation(TestTextReadBinHex_23) { Attribute = new VariationAttribute("ReadBinHex when end tag doesn't exist") }); this.AddChild(new TestVariation(TestTextReadBinHex_24) { Attribute = new VariationAttribute("WS:WireCompat:hex binary fails to send/return data after 1787 bytes going Whidbey to Everett") }); this.AddChild(new TestVariation(TestTextReadBinHex_25) { Attribute = new VariationAttribute("SubtreeReader inserted attributes don't work with ReadContentAsBinHex") }); } } public partial class CReaderTestModule : BridgeHelpers { // Type is CoreXml.Test.XLinq.FunctionalTests+XNodeReaderTests+CReaderTestModule // Test Case public override void AddChildren() { this.AddChild(new TestVariation(v1) { Attribute = new VariationAttribute("Reader Property empty doc") { Priority = 0 } }); this.AddChild(new TestVariation(v2) { Attribute = new VariationAttribute("Reader Property after Read") { Priority = 0 } }); this.AddChild(new TestVariation(v3) { Attribute = new VariationAttribute("Reader Property after EOF") { Priority = 0 } }); this.AddChild(new TestVariation(v4) { Attribute = new VariationAttribute("Default Reader Settings") { Priority = 0 } }); } } public partial class TCReadOuterXml : BridgeHelpers { // Type is CoreXml.Test.XLinq.FunctionalTests+XNodeReaderTests+TCReadOuterXml // Test Case public override void AddChildren() { this.AddChild(new TestVariation(ReadOuterXml1) { Attribute = new VariationAttribute("ReadOuterXml on empty element w/o attributes") { Priority = 0 } }); this.AddChild(new TestVariation(ReadOuterXml2) { Attribute = new VariationAttribute("ReadOuterXml on empty element w/ attributes") { Priority = 0 } }); this.AddChild(new TestVariation(ReadOuterXml3) { Attribute = new VariationAttribute("ReadOuterXml on full empty element w/o attributes") }); this.AddChild(new TestVariation(ReadOuterXml4) { Attribute = new VariationAttribute("ReadOuterXml on full empty element w/ attributes") }); this.AddChild(new TestVariation(ReadOuterXml5) { Attribute = new VariationAttribute("ReadOuterXml on element with text content") { Priority = 0 } }); this.AddChild(new TestVariation(ReadOuterXml6) { Attribute = new VariationAttribute("ReadOuterXml on element with attributes") { Priority = 0 } }); this.AddChild(new TestVariation(ReadOuterXml7) { Attribute = new VariationAttribute("ReadOuterXml on element with text and markup content") }); this.AddChild(new TestVariation(ReadOuterXml8) { Attribute = new VariationAttribute("ReadOuterXml with multiple level of elements") }); this.AddChild(new TestVariation(ReadOuterXml9) { Attribute = new VariationAttribute("ReadOuterXml with multiple level of elements, text and attributes") { Priority = 0 } }); this.AddChild(new TestVariation(ReadOuterXml10) { Attribute = new VariationAttribute("ReadOuterXml on element with complex content (CDATA, PIs, Comments)") { Priority = 0 } }); this.AddChild(new TestVariation(ReadOuterXml12) { Attribute = new VariationAttribute("ReadOuterXml on attribute node of empty element") }); this.AddChild(new TestVariation(ReadOuterXml13) { Attribute = new VariationAttribute("ReadOuterXml on attribute node of full empty element") }); this.AddChild(new TestVariation(ReadOuterXml14) { Attribute = new VariationAttribute("ReadOuterXml on attribute node") { Priority = 0 } }); this.AddChild(new TestVariation(ReadOuterXml15) { Attribute = new VariationAttribute("ReadOuterXml on attribute with entities, EntityHandling = ExpandEntities") { Priority = 0 } }); this.AddChild(new TestVariation(ReadOuterXml17) { Attribute = new VariationAttribute("ReadOuterXml on ProcessingInstruction") }); this.AddChild(new TestVariation(ReadOuterXml24) { Attribute = new VariationAttribute("ReadOuterXml on CDATA") }); this.AddChild(new TestVariation(TRReadOuterXml27) { Attribute = new VariationAttribute("ReadOuterXml on element with entities, EntityHandling = ExpandCharEntities") }); this.AddChild(new TestVariation(TRReadOuterXml28) { Attribute = new VariationAttribute("ReadOuterXml on attribute with entities, EntityHandling = ExpandCharEntites") }); this.AddChild(new TestVariation(TestTextReadOuterXml29) { Attribute = new VariationAttribute("One large element") }); this.AddChild(new TestVariation(ReadOuterXmlWhenNamespacesEqualsToFalseAndHasAnAttributeXmlns) { Attribute = new VariationAttribute("Read OuterXml when Namespaces=false and has an attribute xmlns") }); } } public partial class TCReadSubtree : BridgeHelpers { // Type is CoreXml.Test.XLinq.FunctionalTests+XNodeReaderTests+TCReadSubtree // Test Case public override void AddChildren() { this.AddChild(new TestVariation(ReadSubtreeOnlyWorksOnElementNode) { Attribute = new VariationAttribute("ReadSubtree only works on Element Node") }); this.AddChild(new TestVariation(v2) { Attribute = new VariationAttribute("ReadSubtree Test depth=1") { Params = new object[] { "elem1", "", "ELEMENT", "elem5", "", "ELEMENT" }, Priority = 0 } }); this.AddChild(new TestVariation(v2) { Attribute = new VariationAttribute("ReadSubtree Test depth=2") { Params = new object[] { "elem2", "", "ELEMENT", "elem1", "", "ENDELEMENT" }, Priority = 0 } }); this.AddChild(new TestVariation(v2) { Attribute = new VariationAttribute("ReadSubtree Test empty element") { Params = new object[] { "elem5", "", "ELEMENT", "elem6", "", "ELEMENT" }, Priority = 0 } }); this.AddChild(new TestVariation(v2) { Attribute = new VariationAttribute("ReadSubtree Test on Root") { Params = new object[] { "root", "", "ELEMENT", "", "", "NONE" }, Priority = 0 } }); this.AddChild(new TestVariation(v2) { Attribute = new VariationAttribute("ReadSubtree Test Comment after element") { Params = new object[] { "elem", "", "ELEMENT", "", "Comment", "COMMENT" }, Priority = 0 } }); this.AddChild(new TestVariation(v2) { Attribute = new VariationAttribute("ReadSubtree Test depth=4") { Params = new object[] { "elem4", "", "ELEMENT", "x:elem3", "", "ENDELEMENT" }, Priority = 0 } }); this.AddChild(new TestVariation(v2) { Attribute = new VariationAttribute("ReadSubtree Test depth=3") { Params = new object[] { "x:elem3", "", "ELEMENT", "elem2", "", "ENDELEMENT" }, Priority = 0 } }); this.AddChild(new TestVariation(v2) { Attribute = new VariationAttribute("ReadSubtree Test empty element before root") { Params = new object[] { "elem6", "", "ELEMENT", "root", "", "ENDELEMENT" }, Priority = 0 } }); this.AddChild(new TestVariation(v2) { Attribute = new VariationAttribute("ReadSubtree Test PI after element") { Params = new object[] { "elempi", "", "ELEMENT", "pi", "target", "PROCESSINGINSTRUCTION" }, Priority = 0 } }); this.AddChild(new TestVariation(v3) { Attribute = new VariationAttribute("Read with entities") { Priority = 1 } }); this.AddChild(new TestVariation(v4) { Attribute = new VariationAttribute("Inner XML on Subtree reader") { Priority = 1 } }); this.AddChild(new TestVariation(v5) { Attribute = new VariationAttribute("Outer XML on Subtree reader") { Priority = 1 } }); this.AddChild(new TestVariation(v6) { Attribute = new VariationAttribute("ReadString on Subtree reader") { Priority = 1 } }); this.AddChild(new TestVariation(v7) { Attribute = new VariationAttribute("Close on inner reader with CloseInput should not close the outer reader") { Params = new object[] { "true" }, Priority = 1 } }); this.AddChild(new TestVariation(v7) { Attribute = new VariationAttribute("Close on inner reader with CloseInput should not close the outer reader") { Params = new object[] { "false" }, Priority = 1 } }); this.AddChild(new TestVariation(v8) { Attribute = new VariationAttribute("Nested Subtree reader calls") { Priority = 2 } }); this.AddChild(new TestVariation(v100) { Attribute = new VariationAttribute("ReadSubtree for element depth more than 4K chars") { Priority = 2 } }); this.AddChild(new TestVariation(MultipleNamespacesOnSubtreeReader) { Attribute = new VariationAttribute("Multiple Namespaces on Subtree reader") { Priority = 1 } }); this.AddChild(new TestVariation(SubtreeReaderCachesNodeTypeAndReportsNodeTypeOfAttributeOnSubsequentReads) { Attribute = new VariationAttribute("Subtree Reader caches the NodeType and reports node type of Attribute on subsequent reads.") { Priority = 1 } }); } } public partial class TCReadToDescendant : BridgeHelpers { // Type is CoreXml.Test.XLinq.FunctionalTests+XNodeReaderTests+TCReadToDescendant // Test Case public override void AddChildren() { this.AddChild(new TestVariation(v) { Attribute = new VariationAttribute("Simple positive test") { Params = new object[] { "NNS" }, Priority = 0 } }); this.AddChild(new TestVariation(v) { Attribute = new VariationAttribute("Simple positive test") { Params = new object[] { "DNS" }, Priority = 0 } }); this.AddChild(new TestVariation(v) { Attribute = new VariationAttribute("Simple positive test") { Params = new object[] { "NS" }, Priority = 0 } }); this.AddChild(new TestVariation(v2) { Attribute = new VariationAttribute("Read on a deep tree at least more than 4K boundary") { Priority = 2 } }); this.AddChild(new TestVariation(v3) { Attribute = new VariationAttribute("Read on descendant with same names") { Params = new object[] { "DNS" }, Priority = 1 } }); this.AddChild(new TestVariation(v3) { Attribute = new VariationAttribute("Read on descendant with same names") { Params = new object[] { "NNS" }, Priority = 1 } }); this.AddChild(new TestVariation(v3) { Attribute = new VariationAttribute("Read on descendant with same names") { Params = new object[] { "NS" }, Priority = 1 } }); this.AddChild(new TestVariation(v4) { Attribute = new VariationAttribute("If name not found, stop at end element of the subtree") { Priority = 1 } }); this.AddChild(new TestVariation(v5) { Attribute = new VariationAttribute("Positioning on a level and try to find the name which is on a level higher") { Priority = 1 } }); this.AddChild(new TestVariation(v6) { Attribute = new VariationAttribute("Read to Descendant on one level and again to level below it") { Priority = 1 } }); this.AddChild(new TestVariation(v7) { Attribute = new VariationAttribute("Read to Descendant on one level and again to level below it, with namespace") { Priority = 1 } }); this.AddChild(new TestVariation(v8) { Attribute = new VariationAttribute("Read to Descendant on one level and again to level below it, with prefix") { Priority = 1 } }); this.AddChild(new TestVariation(v9) { Attribute = new VariationAttribute("Multiple Reads to children and then next siblings, NNS") { Priority = 2 } }); this.AddChild(new TestVariation(v10) { Attribute = new VariationAttribute("Multiple Reads to children and then next siblings, DNS") { Priority = 2 } }); this.AddChild(new TestVariation(v11) { Attribute = new VariationAttribute("Multiple Reads to children and then next siblings, NS") { Priority = 2 } }); this.AddChild(new TestVariation(v12) { Attribute = new VariationAttribute("Call from different nodetypes") { Priority = 1 } }); this.AddChild(new TestVariation(v14) { Attribute = new VariationAttribute("Only child has namespaces and read to it") { Priority = 2 } }); this.AddChild(new TestVariation(v15) { Attribute = new VariationAttribute("Pass null to both arguments throws ArgumentException") { Priority = 2 } }); this.AddChild(new TestVariation(v17) { Attribute = new VariationAttribute("Different names, same uri works correctly") { Priority = 2 } }); this.AddChild(new TestVariation(v18) { Attribute = new VariationAttribute("On Root Node") { Params = new object[] { "DNS" }, Priority = 0 } }); this.AddChild(new TestVariation(v18) { Attribute = new VariationAttribute("On Root Node") { Params = new object[] { "NNS" }, Priority = 0 } }); this.AddChild(new TestVariation(v18) { Attribute = new VariationAttribute("On Root Node") { Params = new object[] { "NS" }, Priority = 0 } }); this.AddChild(new TestVariation(v19) { Attribute = new VariationAttribute("427176 Assertion failed when call XmlReader.ReadToDescendant() for non-existing node") { Priority = 1 } }); } } public partial class TCReadToFollowing : BridgeHelpers { // Type is CoreXml.Test.XLinq.FunctionalTests+XNodeReaderTests+TCReadToFollowing // Test Case public override void AddChildren() { this.AddChild(new TestVariation(v1) { Attribute = new VariationAttribute("Simple positive test") { Params = new object[] { "DNS" }, Priority = 0 } }); this.AddChild(new TestVariation(v1) { Attribute = new VariationAttribute("Simple positive test") { Params = new object[] { "NS" }, Priority = 0 } }); this.AddChild(new TestVariation(v1) { Attribute = new VariationAttribute("Simple positive test") { Params = new object[] { "NNS" }, Priority = 0 } }); this.AddChild(new TestVariation(v2) { Attribute = new VariationAttribute("Read on following with same names") { Params = new object[] { "NNS" }, Priority = 1 } }); this.AddChild(new TestVariation(v2) { Attribute = new VariationAttribute("Read on following with same names") { Params = new object[] { "NS" }, Priority = 1 } }); this.AddChild(new TestVariation(v2) { Attribute = new VariationAttribute("Read on following with same names") { Params = new object[] { "DNS" }, Priority = 1 } }); this.AddChild(new TestVariation(v4) { Attribute = new VariationAttribute("If name not found, go to eof") { Priority = 1 } }); this.AddChild(new TestVariation(v5_1) { Attribute = new VariationAttribute("If localname not found go to eof") { Priority = 1 } }); this.AddChild(new TestVariation(v5_2) { Attribute = new VariationAttribute("If uri not found, go to eof") { Priority = 1 } }); this.AddChild(new TestVariation(v6) { Attribute = new VariationAttribute("Read to Following on one level and again to level below it") { Priority = 1 } }); this.AddChild(new TestVariation(v7) { Attribute = new VariationAttribute("Read to Following on one level and again to level below it, with namespace") { Priority = 1 } }); this.AddChild(new TestVariation(v8) { Attribute = new VariationAttribute("Read to Following on one level and again to level below it, with prefix") { Priority = 1 } }); this.AddChild(new TestVariation(v9) { Attribute = new VariationAttribute("Multiple Reads to children and then next siblings, NNS") { Priority = 2 } }); this.AddChild(new TestVariation(v10) { Attribute = new VariationAttribute("Multiple Reads to children and then next siblings, DNS") { Priority = 2 } }); this.AddChild(new TestVariation(v11) { Attribute = new VariationAttribute("Multiple Reads to children and then next siblings, NS") { Priority = 2 } }); this.AddChild(new TestVariation(v14) { Attribute = new VariationAttribute("Only child has namespaces and read to it") { Priority = 2 } }); this.AddChild(new TestVariation(v15) { Attribute = new VariationAttribute("Pass null to both arguments throws ArgumentException") { Priority = 2 } }); this.AddChild(new TestVariation(v17) { Attribute = new VariationAttribute("Different names, same uri works correctly") { Priority = 2 } }); } } public partial class TCReadToNextSibling : BridgeHelpers { // Type is CoreXml.Test.XLinq.FunctionalTests+XNodeReaderTests+TCReadToNextSibling // Test Case public override void AddChildren() { this.AddChild(new TestVariation(v) { Attribute = new VariationAttribute("Simple positive test 2") { Params = new object[] { "DNS" }, Priority = 0 } }); this.AddChild(new TestVariation(v) { Attribute = new VariationAttribute("Simple positive test 3") { Params = new object[] { "NS" }, Priority = 0 } }); this.AddChild(new TestVariation(v) { Attribute = new VariationAttribute("Simple positive test 1") { Params = new object[] { "NNS" }, Priority = 0 } }); this.AddChild(new TestVariation(v2) { Attribute = new VariationAttribute("Read on a deep tree at least more than 4K boundary") { Priority = 2 } }); this.AddChild(new TestVariation(v3) { Attribute = new VariationAttribute("Read to next sibling with same names 1") { Params = new object[] { "NNS", "<root><a att='1'/><a att='2'/><a att='3'/></root>" }, Priority = 1 } }); this.AddChild(new TestVariation(v3) { Attribute = new VariationAttribute("Read on next sibling with same names 2") { Params = new object[] { "DNS", "<root xmlns='a'><a att='1'/><a att='2'/><a att='3'/></root>" }, Priority = 1 } }); this.AddChild(new TestVariation(v3) { Attribute = new VariationAttribute("Read on next sibling with same names 3") { Params = new object[] { "NS", "<root xmlns:a='a'><a:a att='1'/><a:a att='2'/><a:a att='3'/></root>" }, Priority = 1 } }); this.AddChild(new TestVariation(v4) { Attribute = new VariationAttribute("If name not found, stop at end element of the subtree") { Priority = 1 } }); this.AddChild(new TestVariation(v5) { Attribute = new VariationAttribute("Positioning on a level and try to find the name which is on a level higher") { Priority = 1 } }); this.AddChild(new TestVariation(v6) { Attribute = new VariationAttribute("Read to next sibling on one level and again to level below it") { Priority = 1 } }); this.AddChild(new TestVariation(v12) { Attribute = new VariationAttribute("Call from different nodetypes") { Priority = 1 } }); this.AddChild(new TestVariation(v16) { Attribute = new VariationAttribute("Pass null to both arguments throws ArgumentException") { Priority = 2 } }); this.AddChild(new TestVariation(v17) { Attribute = new VariationAttribute("Different names, same uri works correctly") { Priority = 2 } }); } } public partial class TCReadValue : BridgeHelpers { // Type is CoreXml.Test.XLinq.FunctionalTests+XNodeReaderTests+TCReadValue // Test Case public override void AddChildren() { this.AddChild(new TestVariation(TestReadValuePri0) { Attribute = new VariationAttribute("ReadValue") { Priority = 0 } }); this.AddChild(new TestVariation(TestReadValuePri0onElement) { Attribute = new VariationAttribute("ReadValue on Element") { Priority = 0 } }); this.AddChild(new TestVariation(TestReadValueOnAttribute0) { Attribute = new VariationAttribute("ReadValue on Attribute") { Priority = 0 } }); this.AddChild(new TestVariation(TestReadValueOnAttribute1) { Attribute = new VariationAttribute("ReadValue on Attribute after ReadAttributeValue") { Priority = 2 } }); this.AddChild(new TestVariation(TestReadValue2Pri0) { Attribute = new VariationAttribute("ReadValue on empty buffer") { Priority = 0 } }); this.AddChild(new TestVariation(TestReadValue3Pri0) { Attribute = new VariationAttribute("ReadValue on negative count") { Priority = 0 } }); this.AddChild(new TestVariation(TestReadValue4Pri0) { Attribute = new VariationAttribute("ReadValue on negative offset") { Priority = 0 } }); this.AddChild(new TestVariation(TestReadValue1) { Attribute = new VariationAttribute("ReadValue with buffer = element content / 2") { Priority = 0 } }); this.AddChild(new TestVariation(TestReadValue2) { Attribute = new VariationAttribute("ReadValue entire value in one call") { Priority = 0 } }); this.AddChild(new TestVariation(TestReadValue3) { Attribute = new VariationAttribute("ReadValue bit by bit") { Priority = 0 } }); this.AddChild(new TestVariation(TestReadValue4) { Attribute = new VariationAttribute("ReadValue for value more than 4K") { Priority = 0 } }); this.AddChild(new TestVariation(TestReadValue5) { Attribute = new VariationAttribute("ReadValue for value more than 4K and invalid element") { Priority = 1 } }); this.AddChild(new TestVariation(TestReadValue6) { Attribute = new VariationAttribute("ReadValue with Entity Reference, EntityHandling = ExpandEntities") }); this.AddChild(new TestVariation(TestReadValue7) { Attribute = new VariationAttribute("ReadValue with count > buffer size") }); this.AddChild(new TestVariation(TestReadValue8) { Attribute = new VariationAttribute("ReadValue with index > buffer size") }); this.AddChild(new TestVariation(TestReadValue10) { Attribute = new VariationAttribute("ReadValue with index + count exceeds buffer") }); this.AddChild(new TestVariation(TestReadChar11) { Attribute = new VariationAttribute("ReadValue with combination Text, CDATA and Whitespace") }); this.AddChild(new TestVariation(TestReadChar12) { Attribute = new VariationAttribute("ReadValue with combination Text, CDATA and SignificantWhitespace") }); this.AddChild(new TestVariation(TestReadChar13) { Attribute = new VariationAttribute("ReadValue with buffer == null") }); this.AddChild(new TestVariation(TestReadChar14) { Attribute = new VariationAttribute("ReadValue with multiple different inner nodes") }); this.AddChild(new TestVariation(TestReadChar15) { Attribute = new VariationAttribute("ReadValue after failed ReadValue") }); this.AddChild(new TestVariation(TestReadChar16) { Attribute = new VariationAttribute("Read after partial ReadValue") }); this.AddChild(new TestVariation(TestReadChar19) { Attribute = new VariationAttribute("Test error after successful ReadValue") }); this.AddChild(new TestVariation(TestReadChar21) { Attribute = new VariationAttribute("Call on invalid element content after 4k boundary") { Priority = 1 } }); this.AddChild(new TestVariation(TestTextReadValue25) { Attribute = new VariationAttribute("ReadValue with whitespace") }); this.AddChild(new TestVariation(TestTextReadValue26) { Attribute = new VariationAttribute("ReadValue when end tag doesn't exist") }); this.AddChild(new TestVariation(TestCharEntities0) { Attribute = new VariationAttribute("Testing with character entities") }); this.AddChild(new TestVariation(TestCharEntities1) { Attribute = new VariationAttribute("Testing with character entities when value more than 4k") }); this.AddChild(new TestVariation(TestCharEntities2) { Attribute = new VariationAttribute("Testing with character entities with another pattern") }); this.AddChild(new TestVariation(TestReadValueOnBig) { Attribute = new VariationAttribute("Testing a use case pattern with large file") }); this.AddChild(new TestVariation(TestReadValueOnComments0) { Attribute = new VariationAttribute("ReadValue on Comments with IgnoreComments") }); this.AddChild(new TestVariation(TestReadValueOnPIs0) { Attribute = new VariationAttribute("ReadValue on PI with IgnorePI") }); this.AddChild(new TestVariation(bug340158) { Attribute = new VariationAttribute("Skip after ReadAttributeValue/ReadValueChunk") }); } } public partial class XNodeReaderAPI : XLinqTestCase { // Type is CoreXml.Test.XLinq.FunctionalTests+XNodeReaderTests+XNodeReaderAPI // Test Case public override void AddChildren() { this.AddChild(new TestVariation(OpenOnNodeType) { Attribute = new VariationAttribute("Open on node type: Text") { Params = new object[] { XmlNodeType.Text, 1, new string[] { "some_text" }, 1 }, Priority = 1 } }); this.AddChild(new TestVariation(OpenOnNodeType) { Attribute = new VariationAttribute("Open on node type: PI (root level)") { Params = new object[] { XmlNodeType.ProcessingInstruction, 0, new string[] { "PI", "" }, 1 }, Priority = 2 } }); this.AddChild(new TestVariation(OpenOnNodeType) { Attribute = new VariationAttribute("Open on node type: Comment") { Params = new object[] { XmlNodeType.Comment, 1, new string[] { "comm2" }, 1 }, Priority = 2 } }); this.AddChild(new TestVariation(OpenOnNodeType) { Attribute = new VariationAttribute("Open on node type: Text (root level)") { Params = new object[] { XmlNodeType.Text, 0, new string[] { "\t" }, 1 }, Priority = 0 } }); this.AddChild(new TestVariation(OpenOnNodeType) { Attribute = new VariationAttribute("Open on node type: XElement (root)") { Params = new object[] { XmlNodeType.Element, 0, new string[] { "A", "", "" }, 15 }, Priority = 1 } }); this.AddChild(new TestVariation(OpenOnNodeType) { Attribute = new VariationAttribute("Open on node type: PI") { Params = new object[] { XmlNodeType.ProcessingInstruction, 1, new string[] { "PIX", "click" }, 1 }, Priority = 2 } }); this.AddChild(new TestVariation(OpenOnNodeType) { Attribute = new VariationAttribute("Open on node type: Comment (root level)") { Params = new object[] { XmlNodeType.Comment, 0, new string[] { "comment1" }, 1 }, Priority = 2 } }); this.AddChild(new TestVariation(OpenOnNodeType) { Attribute = new VariationAttribute("Open on node type: XElement (in the mIddle)") { Params = new object[] { XmlNodeType.Element, 1, new string[] { "B", "", "x" }, 11 }, Priority = 0 } }); this.AddChild(new TestVariation(OpenOnNodeType) { Attribute = new VariationAttribute("Open on node type: XElement (leaf I.)") { Params = new object[] { XmlNodeType.Element, 3, new string[] { "D", "", "y" }, 2 }, Priority = 0 } }); this.AddChild(new TestVariation(OpenOnNodeType) { Attribute = new VariationAttribute("Open on node type: XElement (leaf II.)") { Params = new object[] { XmlNodeType.Element, 4, new string[] { "E", "p", "nsp" }, 1 }, Priority = 1 } }); this.AddChild(new TestVariation(Namespaces) { Attribute = new VariationAttribute("Namespaces - Comment") { Params = new object[] { XmlNodeType.Comment, 1, new string[] { "", "x" }, new string[] { "p", "nsp" } } } }); this.AddChild(new TestVariation(Namespaces) { Attribute = new VariationAttribute("Namespaces - root element") { Params = new object[] { XmlNodeType.Element, 0, new string[] { "", "" } } } }); this.AddChild(new TestVariation(Namespaces) { Attribute = new VariationAttribute("Namespaces - element") { Params = new object[] { XmlNodeType.Element, 1, new string[] { "", "x" }, new string[] { "p", "nsp" } } } }); this.AddChild(new TestVariation(Namespaces) { Attribute = new VariationAttribute("Namespaces - element, def. ns redef") { Params = new object[] { XmlNodeType.Element, 3, new string[] { "", "y" }, new string[] { "p", "nsp" } } } }); this.AddChild(new TestVariation(ReadSubtreeSanity) { Attribute = new VariationAttribute("ReadSubtree (sanity)") { Priority = 0 } }); this.AddChild(new TestVariation(AdjacentTextNodes1) { Attribute = new VariationAttribute("Adjacent text nodes (sanity I.)") { Priority = 0 } }); this.AddChild(new TestVariation(AdjacentTextNodes2) { Attribute = new VariationAttribute("Adjacent text nodes (sanity II.) : ReadElementContent") { Priority = 0 } }); this.AddChild(new TestVariation(AdjacentTextNodesI) { Attribute = new VariationAttribute("Adjacent text nodes (sanity IV.) : ReadInnerXml") { Priority = 0 } }); this.AddChild(new TestVariation(AdjacentTextNodes3) { Attribute = new VariationAttribute("Adjacent text nodes (sanity III.) : ReadContent") { Priority = 0 } }); } } } #endregion } }
115.26908
278
0.661848
[ "MIT" ]
AndyAyersMS/runtime
src/libraries/System.Private.Xml.Linq/tests/xNodeReader/FunctionalTests.cs
117,805
C#
namespace BaristaLabs.ChromeDevTools.Runtime.DOM { using Newtonsoft.Json; /// <summary> /// Requests that the node is sent to the caller given the JavaScript node object reference. All /// nodes that form the path from the node to the root are also sent to the client as a series of /// `setChildNodes` notifications. /// </summary> public sealed class RequestNodeCommand : ICommand { private const string ChromeRemoteInterface_CommandName = "DOM.requestNode"; [JsonIgnore] public string CommandName { get { return ChromeRemoteInterface_CommandName; } } /// <summary> /// JavaScript object id to convert into node. /// </summary> [JsonProperty("objectId")] public string ObjectId { get; set; } } public sealed class RequestNodeCommandResponse : ICommandResponse<RequestNodeCommand> { /// <summary> /// Node id for given object. ///</summary> [JsonProperty("nodeId")] public long NodeId { get; set; } } }
27.325581
101
0.579574
[ "MIT" ]
BaristaLabs/chrome-dev-tools-runtime
BaristaLabs.ChromeDevTools.Runtime/DOM/RequestNodeCommand.cs
1,175
C#
using CleanArchitecture.Application.Common.Exceptions; using CleanArchitecture.Application.Common.Interfaces; using CleanArchitecture.Domain.Entities; using CleanArchitecture.Domain.Events; using MediatR; using System.Threading; using System.Threading.Tasks; namespace CleanArchitecture.Application.MediatR.TodoItems.Commands.DeleteTodoItem { public class DeleteTodoItemCommand : IRequest { public int Id { get; set; } } public class DeleteTodoItemCommandHandler : IRequestHandler<DeleteTodoItemCommand> { private readonly IApplicationDbContext _context; public DeleteTodoItemCommandHandler(IApplicationDbContext context) { _context = context; } public async Task<Unit> Handle(DeleteTodoItemCommand request, CancellationToken cancellationToken) { var entity = await _context.TodoItems.FindAsync(request.Id); if (entity == null) { throw new NotFoundException(nameof(TodoItem), request.Id); } _context.TodoItems.Remove(entity); entity.DomainEvents.Add(new TodoItemDeletedEvent(entity)); await _context.SaveChangesAsync(cancellationToken); return Unit.Value; } } }
29.181818
106
0.692368
[ "MIT" ]
Ulysses31/Clean-Architecture
src/Application/MediatR/TodoItems/Commands/DeleteTodoItem/DeleteTodoItemCommand.cs
1,286
C#
using System; using System.Collections; using System.Collections.Generic; using TMPro; using UnityEngine; using UnityEngine.EventSystems; using UnityEngine.UI; public class Food : Draggable { public ItemData food; private PlayerAnimationController player; [SerializeField] private TextMeshProUGUI stackUI; public override void OnDrag(PointerEventData eventData) { if (food == null) return; base.OnDrag(eventData); if (!hit & player != null) player.Nam(false); } public override void OnBeginDrag(PointerEventData eventData) { if (food == null) { return; } base.OnBeginDrag(eventData); } public void CheckStack() { if (food == null) { stackUI.gameObject.SetActive(false); return; } if (food.Stack > 0) { stackUI.gameObject.SetActive(true); stackUI.text = "X" + food.Stack; } else stackUI.gameObject.SetActive(false); } private void OnEnable() { base.OnEndDrag(null); } public override void Drag() { var check = hit.collider.gameObject.GetComponent<PlayerAnimationController>(); if (check == null) { return; } if (player == null) player = check; check.Nam(true); } public override void OnEndDrag(PointerEventData eventData) { if (hit) { if (food == null) return; if (Eating.CheckSameFood(food)) Player.EetFoodEvent.Invoke(food.value); else { MenuSystem.OpenWarning.Invoke("DOESNT WANT :/"); GameBase.Dilaver.SoundSystem.PlaySound(Sounds.dontwant); base.OnEndDrag(eventData); return; } hit.collider.GetComponent<PlayerAnimationController>().NamNam(food); GameBase.Dilaver.SoundSystem.PlaySound(Sounds.eat); PlayerInventory.RemoveItemEvent.Invoke(food); player.Nam(false); Kitchen.GetFoodEvent.Invoke(); } if (player != null) { player.Nam(false); player = null; } base.OnEndDrag(eventData); } }
23.762887
86
0.560954
[ "MIT" ]
DilaverSerif/PotatoPET
Assets/Scripts/Food.cs
2,305
C#
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // As informações gerais sobre um assembly são controladas por // conjunto de atributos. Altere estes valores de atributo para modificar as informações // associadas a um assembly. [assembly: AssemblyTitle("ConsoleBank")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("ConsoleBank")] [assembly: AssemblyCopyright("Copyright © 2020")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Definir ComVisible como false torna os tipos neste assembly invisíveis // para componentes COM. Caso precise acessar um tipo neste assembly de // COM, defina o atributo ComVisible como true nesse tipo. [assembly: ComVisible(false)] // O GUID a seguir será destinado à ID de typelib se este projeto for exposto para COM [assembly: Guid("070c195e-6d3f-48f1-b950-eb4255571c32")] // As informações da versão de um assembly consistem nos quatro valores a seguir: // // Versão Principal // Versão Secundária // Número da Versão // Revisão // // É possível especificar todos os valores ou usar como padrão os Números de Build e da Revisão // usando o "*" como mostrado abaixo: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
38.135135
95
0.752658
[ "MIT" ]
Felipe13devmaster/Console-Bank
ConsoleBank/01-ConsoleBank/Properties/AssemblyInfo.cs
1,436
C#
namespace formulate.app.DataValues.Kinds { // Namespaces. using core.Types; using DataInterfaces; using Helpers; using Newtonsoft.Json.Linq; using Suppliers; using System; using System.Collections.Generic; using System.Linq; using Constants = Constants.DataValues.DataValueListFunction; /// <summary> /// A data value kind that calls other functions that supply a list of data. /// </summary> public class DataValueListFunction : IDataValueKind, IGetValueAndLabelCollection { #region Properties /// <summary> /// The kind ID. /// </summary> public Guid Id { get { return GuidHelper.GetGuid(Constants.Id); } } /// <summary> /// The kind name. /// </summary> public string Name { get { return LocalizationHelper.GetDataValueName(Constants.Name); } } /// <summary> /// The kind directive. /// </summary> public string Directive { get { return Constants.Directive; } } #endregion #region Methods /// <summary> /// Extracts the value and label collection from the specified raw data. /// </summary> /// <param name="rawData"> /// The raw data for the list. /// </param> /// <returns> /// The collection of value and label items. /// </returns> public IEnumerable<ValueAndLabel> GetValues(string rawData) { // Variables. var supplierTypes = ReflectionHelper .GetTypesImplementingInterface<ISupplyValueAndLabelCollection>(); // Validate input. if (string.IsNullOrWhiteSpace(rawData)) { return Enumerable.Empty<ValueAndLabel>(); } // Deserialize the raw data. var configData = JsonHelper.Deserialize<JObject>(rawData); var dynamicConfig = configData as dynamic; var properties = configData.Properties().Select(x => x.Name); var propertySet = new HashSet<string>(properties); // Get the values from the supplier. if (propertySet.Contains("supplier")) { var strSupplier = dynamicConfig.supplier.Value as string; var supplierType = supplierTypes .FirstOrDefault(x => x.AssemblyQualifiedName == strSupplier); var supplier = default(ISupplyValueAndLabelCollection); if (supplierType != null) { supplier = Activator.CreateInstance(supplierType) as ISupplyValueAndLabelCollection; } if (supplier != null) { return supplier.GetValues(); } } // Return empty collection. return Enumerable.Empty<ValueAndLabel>(); } #endregion } }
25.983607
104
0.526498
[ "MIT" ]
DKompile/formulate
src/formulate.app/DataValues/Kinds/DataValueListFunction.cs
3,172
C#
using ManageCourse.Core.Data.Common; using System.Collections.Generic; namespace ManageCourse.Core.Data { public class Grade: Audit, IHasId { public int Id { get; set; } public int AssignmentId { get; set; } public int StudentId { get; set; } public string MSSV { get; set; } public string Name { get; set; } public string Description { get; set; } public float GradeAssignment { get; set; } public bool IsFinalized { get; set; } public virtual Assignments Assignments { get; set; } public virtual Student Student { get; set; } public ICollection<GradeReview> GradeReviews { get; set; } } }
31.545455
66
0.628242
[ "MIT" ]
hdh-se/classroom-api
ManageCourse.Core/Data/Grade.cs
696
C#
using Jigsaw_2.Abstracts; using System.Windows.Controls; namespace Jigsaw_2.Games.LetterOnLetter.Commands { internal class SelectCommand : ICommand, IUndoable { private readonly ILoLGameBehavior lolGameBehavior; private readonly Button selecter; public SelectCommand(ILoLGameBehavior lolGameBehavior, Button selecter) { this.lolGameBehavior = lolGameBehavior; this.selecter = selecter; } public void Execute() { lolGameBehavior.Select(selecter); } public void Undo() { lolGameBehavior.Undo(selecter); } } }
22.793103
79
0.627837
[ "MIT" ]
shkemilo/Jigsaw-2
Jigsaw 2/Games/LetterOnLetter/Commands/SelectCommand.cs
663
C#
using System; using Alipay.AopSdk.Domain; using System.Collections.Generic; using Alipay.AopSdk.Response; namespace Alipay.AopSdk.Request { /// <summary> /// AOP API: alipay.marketing.tool.fengdie.space.batchquery /// </summary> public class AlipayMarketingToolFengdieSpaceBatchqueryRequest : IAopRequest<AlipayMarketingToolFengdieSpaceBatchqueryResponse> { /// <summary> /// 查询空间列表 /// </summary> public string BizContent { get; set; } #region IAopRequest Members private bool needEncrypt=false; private string apiVersion = "1.0"; private string terminalType; private string terminalInfo; private string prodCode; private string notifyUrl; private string returnUrl; private AopObject bizModel; public void SetNeedEncrypt(bool needEncrypt){ this.needEncrypt=needEncrypt; } public bool GetNeedEncrypt(){ return this.needEncrypt; } public void SetNotifyUrl(string notifyUrl){ this.notifyUrl = notifyUrl; } public string GetNotifyUrl(){ return this.notifyUrl; } public void SetReturnUrl(string returnUrl){ this.returnUrl = returnUrl; } public string GetReturnUrl(){ return this.returnUrl; } public void SetTerminalType(String terminalType){ this.terminalType=terminalType; } public string GetTerminalType(){ return this.terminalType; } public void SetTerminalInfo(String terminalInfo){ this.terminalInfo=terminalInfo; } public string GetTerminalInfo(){ return this.terminalInfo; } public void SetProdCode(String prodCode){ this.prodCode=prodCode; } public string GetProdCode(){ return this.prodCode; } public string GetApiName() { return "alipay.marketing.tool.fengdie.space.batchquery"; } public void SetApiVersion(string apiVersion){ this.apiVersion=apiVersion; } public string GetApiVersion(){ return this.apiVersion; } public IDictionary<string, string> GetParameters() { AopDictionary parameters = new AopDictionary(); parameters.Add("biz_content", this.BizContent); return parameters; } public AopObject GetBizModel() { return this.bizModel; } public void SetBizModel(AopObject bizModel) { this.bizModel = bizModel; } #endregion } }
24.154545
130
0.614227
[ "MIT" ]
ArcherTrister/LeXun.Alipay.AopSdk
src/Alipay.AopSdk/Request/AlipayMarketingToolFengdieSpaceBatchqueryRequest.cs
2,669
C#
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Common.Contract { public class FileRequest { public string FileFullName { get; set; } } }
17.533333
56
0.695817
[ "Apache-2.0" ]
Theremiracle/FileService
Common/Contract/FileRequest.cs
265
C#
// *** WARNING: this file was generated by the Pulumi SDK Generator. *** // *** Do not edit by hand unless you're certain you know what you are doing! *** using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Threading.Tasks; using Pulumi.Serialization; namespace Pulumi.GoogleNative.Storage.V1.Inputs { /// <summary> /// The owner of the bucket. This is always the project team's owner group. /// </summary> public sealed class BucketOwnerArgs : Pulumi.ResourceArgs { /// <summary> /// The entity, in the form project-owner-projectId. /// </summary> [Input("entity")] public Input<string>? Entity { get; set; } /// <summary> /// The ID for the entity. /// </summary> [Input("entityId")] public Input<string>? EntityId { get; set; } public BucketOwnerArgs() { } } }
26.914286
81
0.611465
[ "Apache-2.0" ]
AaronFriel/pulumi-google-native
sdk/dotnet/Storage/V1/Inputs/BucketOwnerArgs.cs
942
C#
//------------------------------------------------------------------------------ // <auto-generated> // This code was generated by a tool. // Runtime Version:4.0.30319.18444 // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ namespace _01_Start.Properties { using System; /// <summary> /// A strongly-typed resource class, for looking up localized strings, etc. /// </summary> // This class was auto-generated by the StronglyTypedResourceBuilder // class via a tool like ResGen or Visual Studio. // To add or remove a member, edit your .ResX file then rerun ResGen // with the /str option, or rebuild your VS project. [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "4.0.0.0")] [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] internal class Resources { private static global::System.Resources.ResourceManager resourceMan; private static global::System.Globalization.CultureInfo resourceCulture; [global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] internal Resources() { } /// <summary> /// Returns the cached ResourceManager instance used by this class. /// </summary> [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] internal static global::System.Resources.ResourceManager ResourceManager { get { if (object.ReferenceEquals(resourceMan, null)) { global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("_01_Start.Properties.Resources", typeof(Resources).Assembly); resourceMan = temp; } return resourceMan; } } /// <summary> /// Overrides the current thread's CurrentUICulture property for all /// resource lookups using this strongly typed resource class. /// </summary> [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] internal static global::System.Globalization.CultureInfo Culture { get { return resourceCulture; } set { resourceCulture = value; } } } }
44.4375
176
0.599156
[ "Unlicense" ]
Slesa/Poseidon
sketches/wpf/caliburn/01_Start/Properties/Resources.Designer.cs
2,846
C#
//------------------------------------------------------------------------------ // <auto-generated> // This code was generated from a template. // // Manual changes to this file may cause unexpected behavior in your application. // Manual changes to this file will be overwritten if the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ namespace X_SMS_DAL.Database { using System; using System.Collections.Generic; public partial class Game { [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")] public Game() { this.Players = new HashSet<Player>(); } public int GameId { get; set; } public string GameCode { get; set; } public Nullable<System.DateTime> StartTime { get; set; } public Nullable<System.DateTime> EndTime { get; set; } public string CreatedPlayer { get; set; } public int PlayersCount { get; set; } public bool IsPublic { get; set; } public bool IsActive { get; set; } public bool IsStarted { get; set; } public bool IsCanceled { get; set; } public string Winner { get; set; } [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")] public virtual ICollection<Player> Players { get; set; } } }
38.641026
128
0.578633
[ "MIT" ]
imanshu15/x-sms
X-SMS/X-SMS-DAL/Database/Game.cs
1,507
C#
using System.Collections.Generic; using UnityEngine.Serialization; #if ENVIRO_LWRP && ENVIRO_HD namespace UnityEngine.Rendering.LWRP { public class EnviroFogLWRP : UnityEngine.Rendering.Universal.ScriptableRendererFeature { EnviroBlitPass blitPass; private Camera myCam; #region Fog Var public enum FogType { Disabled, Simple, Standard } [HideInInspector] public FogType currentFogType; private Material fogMat; private Texture2D dither; private Texture2D blackTexture; private Texture3D detailNoiseTexture = null; #endregion private void RenderFog() { if (fogMat == null) CreateFogMaterial(); //////////////// FOG float FdotC = myCam.transform.position.y - EnviroSky.instance.fogSettings.height; float paramK = (FdotC <= 0.0f ? 1.0f : 0.0f); var sceneMode = RenderSettings.fogMode; var sceneDensity = RenderSettings.fogDensity; var sceneStart = RenderSettings.fogStartDistance; var sceneEnd = RenderSettings.fogEndDistance; Vector4 sceneParams; bool linear = (sceneMode == FogMode.Linear); float diff = linear ? sceneEnd - sceneStart : 0.0f; float invDiff = Mathf.Abs(diff) > 0.0001f ? 1.0f / diff : 0.0f; sceneParams.x = sceneDensity * 1.2011224087f; // density / sqrt(ln(2)), used by Exp2 fog mode sceneParams.y = sceneDensity * 1.4426950408f; // density / ln(2), used by Exp fog mode sceneParams.z = linear ? -invDiff : 0.0f; sceneParams.w = linear ? sceneEnd * invDiff : 0.0f; ////////////////// if (!EnviroSky.instance.fogSettings.useSimpleFog) { Shader.SetGlobalVector("_FogNoiseVelocity", new Vector4(-EnviroSky.instance.Components.windZone.transform.forward.x * EnviroSky.instance.windIntensity * 5, -EnviroSky.instance.Components.windZone.transform.forward.z * EnviroSky.instance.windIntensity * 5) * EnviroSky.instance.fogSettings.noiseScale); Shader.SetGlobalVector("_FogNoiseData", new Vector4(EnviroSky.instance.fogSettings.noiseScale, EnviroSky.instance.fogSettings.noiseIntensity, EnviroSky.instance.fogSettings.noiseIntensityOffset)); Shader.SetGlobalTexture("_FogNoiseTexture", detailNoiseTexture); } Shader.SetGlobalFloat("_EnviroVolumeDensity", EnviroSky.instance.globalVolumeLightIntensity); Shader.SetGlobalVector("_SceneFogParams", sceneParams); Shader.SetGlobalVector("_SceneFogMode", new Vector4((int)sceneMode, EnviroSky.instance.fogSettings.useRadialDistance ? 1 : 0, 0, Application.isPlaying ? 1f : 0f)); Shader.SetGlobalVector("_HeightParams", new Vector4(EnviroSky.instance.fogSettings.height, FdotC, paramK, EnviroSky.instance.fogSettings.heightDensity * 0.5f)); Shader.SetGlobalVector("_DistanceParams", new Vector4(-Mathf.Max(EnviroSky.instance.fogSettings.startDistance, 0.0f), 0, 0, 0)); fogMat.SetFloat("_DitheringIntensity", EnviroSky.instance.fogSettings.fogDithering); Shader.SetGlobalTexture("_EnviroVolumeLightingTex", blackTexture); } private void CreateFogMaterial() { if (EnviroSky.instance == null) return; if (dither == null) dither = Resources.Load("tex_enviro_dither") as Texture2D; if (detailNoiseTexture == null) detailNoiseTexture = Resources.Load("enviro_clouds_detail_low") as Texture3D; if (blackTexture == null) blackTexture = Resources.Load("tex_enviro_black") as Texture2D; //Cleanup if (fogMat != null) DestroyImmediate(fogMat); if (!EnviroSky.instance.useFog) { Shader shader = Shader.Find("Enviro/Standard/EnviroFogRenderingDisabled"); fogMat = new Material(shader); if (shader == null) currentFogType = FogType.Disabled; } else if (!EnviroSky.instance.fogSettings.useSimpleFog) { Shader shader = Shader.Find("Enviro/Standard/EnviroFogRendering"); fogMat = new Material(shader); if (shader == null) currentFogType = FogType.Standard; } else { Shader shader = Shader.Find("Enviro/Standard/EnviroFogRenderingSimple"); if (shader == null) fogMat = new Material(shader); currentFogType = FogType.Simple; } } private void UpdateMatrix() { ///////////////////Matrix Information if (myCam.stereoEnabled) { // Both stereo eye inverse view matrices Matrix4x4 left_world_from_view = myCam.GetStereoViewMatrix(Camera.StereoscopicEye.Left).inverse; Matrix4x4 right_world_from_view = myCam.GetStereoViewMatrix(Camera.StereoscopicEye.Right).inverse; // Both stereo eye inverse projection matrices, plumbed through GetGPUProjectionMatrix to compensate for render texture Matrix4x4 left_screen_from_view = myCam.GetStereoProjectionMatrix(Camera.StereoscopicEye.Left); Matrix4x4 right_screen_from_view = myCam.GetStereoProjectionMatrix(Camera.StereoscopicEye.Right); Matrix4x4 left_view_from_screen = GL.GetGPUProjectionMatrix(left_screen_from_view, true).inverse; Matrix4x4 right_view_from_screen = GL.GetGPUProjectionMatrix(right_screen_from_view, true).inverse; // Negate [1,1] to reflect Unity's CBuffer state if (SystemInfo.graphicsDeviceType != UnityEngine.Rendering.GraphicsDeviceType.OpenGLCore && SystemInfo.graphicsDeviceType != UnityEngine.Rendering.GraphicsDeviceType.OpenGLES3) { left_view_from_screen[1, 1] *= -1; right_view_from_screen[1, 1] *= -1; } Shader.SetGlobalMatrix("_LeftWorldFromView", left_world_from_view); Shader.SetGlobalMatrix("_RightWorldFromView", right_world_from_view); Shader.SetGlobalMatrix("_LeftViewFromScreen", left_view_from_screen); Shader.SetGlobalMatrix("_RightViewFromScreen", right_view_from_screen); } else { // Main eye inverse view matrix Matrix4x4 left_world_from_view = myCam.cameraToWorldMatrix; // Inverse projection matrices, plumbed through GetGPUProjectionMatrix to compensate for render texture Matrix4x4 screen_from_view = myCam.projectionMatrix; Matrix4x4 left_view_from_screen = GL.GetGPUProjectionMatrix(screen_from_view, true).inverse; // Negate [1,1] to reflect Unity's CBuffer state if (SystemInfo.graphicsDeviceType != UnityEngine.Rendering.GraphicsDeviceType.OpenGLCore && SystemInfo.graphicsDeviceType != UnityEngine.Rendering.GraphicsDeviceType.OpenGLES3) left_view_from_screen[1, 1] *= -1; // Store matrices Shader.SetGlobalMatrix("_LeftWorldFromView", left_world_from_view); Shader.SetGlobalMatrix("_LeftViewFromScreen", left_view_from_screen); } ////////////////////////////// } public override void Create() { if (EnviroSkyMgr.instance == null || EnviroSky.instance == null) return; CreateFogMaterial(); blitPass = new EnviroBlitPass(UnityEngine.Rendering.Universal.RenderPassEvent.BeforeRenderingTransparents, fogMat, 0, name); } public override void AddRenderPasses(UnityEngine.Rendering.Universal.ScriptableRenderer renderer, ref UnityEngine.Rendering.Universal.RenderingData renderingData) { if (renderingData.cameraData.camera.cameraType == CameraType.Preview) return; myCam = renderingData.cameraData.camera; if (EnviroSky.instance != null && EnviroSky.instance.useFog && EnviroSky.instance.PlayerCamera != null) { var src = renderer.cameraColorTarget; var dest = UnityEngine.Rendering.Universal.RenderTargetHandle.CameraTarget; if (renderingData.cameraData.isSceneViewCamera && !EnviroSky.instance.showFogInEditor) return; UpdateMatrix(); RenderFog(); if (blitPass == null) Create(); blitPass.Setup(src, dest); renderer.EnqueuePass(blitPass); } } } } #endif
45.356784
317
0.619433
[ "Unlicense" ]
adityawahyu04/Tugas-Pertemuan-1-Lab-Pemgame
Assets/Enviro - Sky and Weather/Enviro Standard/URP Support/Scripts/EnviroFogLWRP.cs
9,028
C#
using System; using System.Collections.Generic; using System.Linq.Expressions; using ASTRA.EMSG.Business.Entities.Common; using ASTRA.EMSG.Business.Entities.Summarisch; using ASTRA.EMSG.Business.Infrastructure.Transactioning; using ASTRA.EMSG.Business.Models.Summarisch; using ASTRA.EMSG.Business.ReflectionMappingConfiguration; using ASTRA.EMSG.Business.Services.Common; using ASTRA.EMSG.Business.Services.EntityServices.Common; using ASTRA.EMSG.Business.Services.Historization; using ASTRA.EMSG.Business.Services.Security; using System.Linq; using NHibernate.Linq; namespace ASTRA.EMSG.Business.Services.EntityServices.Summarisch { public interface INetzSummarischDetailService : IService { IQueryable<NetzSummarischDetail> GetEntitiesBy(ErfassungsPeriod getErfassungsPeriod); IQueryable<NetzSummarischDetail> GetEntitiesBy(ErfassungsPeriod getErfassungsPeriod, Mandant mandant); NetzSummarischDetailModel GetById(Guid id); NetzSummarischDetailModel UpdateEntity(NetzSummarischDetailModel netzSummarischDetailModel); List<NetzSummarischDetailModel> GetCurrentModels(); IQueryable<NetzSummarischDetail> GetEntites(); } public class NetzSummarischDetailService : MandantAndErfassungsPeriodDependentEntityServiceBase<NetzSummarischDetail, NetzSummarischDetailModel>, INetzSummarischDetailService { private readonly ILocalizationService localizationService; public NetzSummarischDetailService( ITransactionScopeProvider transactionScopeProvider, IEntityServiceMappingEngine entityServiceMappingEngine, ISecurityService securityService, IHistorizationService historizationService, ILocalizationService localizationService) :base(transactionScopeProvider, entityServiceMappingEngine, securityService, historizationService) { this.localizationService = localizationService; } protected override Expression<Func<NetzSummarischDetail, Mandant>> MandantExpression { get { return nsd => nsd.NetzSummarisch.Mandant; } } protected override Expression<Func<NetzSummarischDetail, ErfassungsPeriod>> ErfassungsPeriodExpression { get { return nsd => nsd.NetzSummarisch.ErfassungsPeriod; } } public override List<NetzSummarischDetailModel> GetCurrentModels() { return FilteredEntities.OrderBy(ns => ns.Belastungskategorie.Reihenfolge).Fetch(ns => ns.Belastungskategorie).Select(CreateModel).ToList(); } public IQueryable<NetzSummarischDetail> GetEntites() { return FilteredEntities; } protected override void OnModelCreated(NetzSummarischDetail entity, NetzSummarischDetailModel model) { model.BelastungskategorieTyp = localizationService.GetLocalizedBelastungskategorieTyp(model.BelastungskategorieTyp); } } }
47.786885
178
0.773242
[ "BSD-3-Clause" ]
astra-emsg/ASTRA.EMSG
Master/ASTRA.EMSG.Business/Services/EntityServices/Summarisch/NetzSummarischDetailService.cs
2,915
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Net; using System.Net.Sockets; namespace C1_BT2_Client { class SimpleTcpClient { static void Main(string[] args) { byte[] data = new byte[1024]; string input, stringData; IPEndPoint ipep = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 9050); Socket server = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); try { server.Connect(ipep); } catch (SocketException e) { Console.WriteLine("Unable to connect to server."); Console.WriteLine(e.ToString()); return; } int recv = server.Receive(data); stringData = Encoding.ASCII.GetString(data, 0, recv); Console.WriteLine(stringData); while(true) { input = Console.ReadLine(); if (input == "exit") break; server.Send(Encoding.ASCII.GetBytes(input)); data = new byte[1024]; recv = server.Receive(data); stringData = Encoding.ASCII.GetString(data, 0, recv); Console.WriteLine(stringData); } Console.WriteLine("Disconnecting from server..."); server.Shutdown(SocketShutdown.Both); server.Close(); Console.ReadKey(); } } }
30.588235
104
0.526282
[ "Unlicense" ]
phuccoder/Network-Program
2_1_SimpleTcpClient/SimpleTcpClient.cs
1,562
C#
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; using System.Web.Routing; namespace api { public class RouteConfig { public static void RegisterRoutes(RouteCollection routes) { routes.IgnoreRoute("{resource}.axd/{*pathInfo}"); routes.MapRoute( name: "Default", url: "{controller}/{action}/{id}", defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional } ); } } }
23.791667
99
0.581436
[ "MIT" ]
ShenLx1/WebApi
api/App_Start/RouteConfig.cs
573
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.ComponentModel; using Livet; using Livet.Commands; using Livet.Messaging; using Livet.Messaging.IO; using Livet.EventListeners; using Livet.Messaging.Windows; using ProgressiveTweet.Models; namespace ProgressiveTweet.ViewModels { public class RootThumbViewModel : NavigativeViewModel { private RootMenuViewModel RootMenu { get; set; } public RootThumbViewModel(NavigativeViewModel host) : base(host) { RootMenu = new RootMenuViewModel(this); } #region GoRootMenuCommand private ViewModelCommand _GoRootMenuCommand; public ViewModelCommand GoRootMenuCommand { get { if (_GoRootMenuCommand == null) { _GoRootMenuCommand = new ViewModelCommand(GoRootMenu); } return _GoRootMenuCommand; } } public void GoRootMenu() { this.GoForward(RootMenu); } #endregion } }
22.294118
74
0.614776
[ "MIT" ]
paralleltree/ProgressiveTweet
ProgressiveTweet/ViewModels/Navigative/RootThumbViewModel.cs
1,139
C#
// Copyright (c) .NET Foundation. All rights reserved. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using Microsoft; using NuGet.ProjectManagement; using NuGet.VisualStudio; namespace NuGet.PackageManagement.VisualStudio { /// <summary> /// Represents Visual Studio core project system in the integrated development environment (IDE). /// </summary> internal class VsCoreProjectSystemServices : INuGetProjectServices, IProjectSystemCapabilities { private readonly IVsProjectAdapter _vsProjectAdapter; private readonly IVsProjectThreadingService _threadingService; public bool SupportsPackageReferences => false; public bool NominatesOnSolutionLoad => false; #region INuGetProjectServices public IProjectBuildProperties BuildProperties => _vsProjectAdapter.BuildProperties; public IProjectSystemCapabilities Capabilities => this; public IProjectSystemReferencesReader ReferencesReader { get; } public IProjectSystemReferencesService References => throw new NotSupportedException(); public IProjectSystemService ProjectSystem { get; } public IProjectScriptHostService ScriptService { get; } #endregion INuGetProjectServices public VsCoreProjectSystemServices( IVsProjectAdapter vsProjectAdapter, IVsProjectThreadingService threadingService, Lazy<IScriptExecutor> _scriptExecutor) { Assumes.Present(vsProjectAdapter); Assumes.Present(threadingService); _vsProjectAdapter = vsProjectAdapter; _threadingService = threadingService; ProjectSystem = new VsCoreProjectSystem(_vsProjectAdapter); ReferencesReader = new VsCoreProjectSystemReferenceReader(vsProjectAdapter, threadingService); ScriptService = new VsProjectScriptHostService(vsProjectAdapter, _scriptExecutor); } } }
35.275862
111
0.72825
[ "Apache-2.0" ]
AntonC9018/NuGet.Client
src/NuGet.Clients/NuGet.PackageManagement.VisualStudio/ProjectServices/VsCoreProjectSystemServices.cs
2,046
C#
using Skybrud.Social.Vimeo.Endpoints.Raw; using Skybrud.Social.Vimeo.Responses.Users; namespace Skybrud.Social.Vimeo.Endpoints { /// <summary> /// Class representing the implementation of the me endpoint. /// </summary> /// <see> /// <cref>https://developer.vimeo.com/api/endpoints/me</cref> /// </see> public class VimeoMeEndpoint { #region Properties /// <summary> /// Gets a reference to the Vimeo service. /// </summary> public VimeoService Service { get; } /// <summary> /// Gets a reference to the raw endpoint. /// </summary> public VimeoMeRawEndpoint Raw => Service.Client.Me; #endregion #region Constructors internal VimeoMeEndpoint(VimeoService service) { Service = service; } #endregion #region Member methods /// <summary> /// Gets information about the authenticated user. /// </summary> /// <returns>An instance of <see cref="VimeoUserResponse"/> representing the response.</returns> /// <see> /// <cref>https://developer.vimeo.com/api/endpoints/me#GET/me</cref> /// </see> public VimeoUserResponse GetInfo() { return new VimeoUserResponse(Raw.GetInfo()); } #endregion } }
25.754717
104
0.578755
[ "MIT" ]
jemayn/Skybrud.Social.Vimeo
src/Skybrud.Social.Vimeo/Endpoints/VimeoMeEndpoint.cs
1,367
C#