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 Blamite.Blam.Resources.Models; using Blamite.Serialization; namespace Blamite.Blam.ThirdGen.Resources.Models { public class ThirdGenModelVertexGroup : IModelVertexGroup { public ThirdGenModelVertexGroup(StructureValueCollection values, IModelSubmesh[] submeshes) { Load(values, submeshes); } public int IndexBufferStart { get; private set; } public int IndexBufferCount { get; private set; } public int VertexBufferCount { get; private set; } public IModelSubmesh Submesh { get; private set; } private void Load(StructureValueCollection values, IModelSubmesh[] submeshes) { IndexBufferStart = (int) values.GetInteger("index buffer start"); IndexBufferCount = (int) values.GetInteger("index buffer count"); VertexBufferCount = (int) values.GetInteger("vertex buffer count"); var submeshIndex = (int) values.GetInteger("parent submesh index"); Submesh = submeshes[submeshIndex]; } } }
30.225806
93
0.755603
[ "MIT" ]
Dreamarchs/MCCEditor
Blamite/Blam/ThirdGen/Resources/Models/ThirdGenModelVertexGroup.cs
939
C#
using System.IO; using System.Runtime.Serialization.Formatters.Binary; namespace ObjectCloner { public static class SerializingCloner { public static T Copy<T>(T obj) { using MemoryStream memoryStream = new MemoryStream(); BinaryFormatter binaryFormatter = new BinaryFormatter(); binaryFormatter.Serialize(memoryStream, obj); memoryStream.Position = 0L; return (T)binaryFormatter.Deserialize(memoryStream); } } }
24.333333
59
0.76484
[ "MIT" ]
undancer/oni-data
Managed/firstpass/ObjectCloner/SerializingCloner.cs
438
C#
using System; namespace CS8_Interface { public class FixedBot : IBot { public string Toot() => "これは固定tootです。"; } }
14.6
48
0.568493
[ "CC0-1.0" ]
ytyaru/CSharp.Interface.8.0.20191026095218
src/CS8_Interface/FixedBot.cs
164
C#
namespace CryV.Net.Enums { public enum TextAlignment { Center, Left, Right } }
11.6
29
0.508621
[ "MIT" ]
Cryma/CryV.Net
CryV.Net/src/Enums/TextAlignment.cs
118
C#
using System; using System.Collections.Generic; using FluentAssertions; using Xunit; namespace RecShark.ExpressionEvaluator.Tests { public class ExpressionTests { [Fact] public void Should_evaluate_operation_as_double() { var expression = new Expression(@"x*y^2 + (isOk ? 100 : 50) + (car == ""any"" ? 1000 : 500)"); var parameters = new Dictionary<string, object> { ["x"] = 3, ["y"] = 5, ["isOk"] = true, ["car"] = "any" }; var actual = expression.Evaluate<double>(parameters); actual.Should().Be(75 + 100 + 1000); } [Fact] public void Should_evaluate_condition_as_boolean() { var expression = new Expression(@"x < y && isOk || car == ""any"""); var parameters = new Dictionary<string, object> { ["x"] = 3, ["y"] = 5, ["isOk"] = true, ["car"] = "any" }; var actual = expression.Evaluate<bool>(parameters); actual.Should().BeTrue(); } [Fact] public void Should_evaluate_condition_as_string() { var expression = new Expression(@"x < y ? ""true"" : ""false"""); var parameters = new Dictionary<string, object> {["x"] = 3, ["y"] = 5}; var actual = expression.Evaluate<string>(parameters); actual.Should().Be("true"); parameters["x"] = 5; actual = expression.Evaluate<string>(parameters); actual.Should().Be("false"); } [Theory] [InlineData(5)] [InlineData(true)] [InlineData("ok")] public void Should_evaluate_multiple_parameter_type(object parameter) { const string formula = @"1 < 2 ? x : ""error"""; var parameters = new Dictionary<string, object> {["x"] = parameter}; var expression = new Expression(formula); var actual = expression.Evaluate(parameters); actual.Should().Be(parameter); } [Fact] public void Should_evaluate_parameter_value() { var expression = new Expression("x ^ 2 + y"); var parameters = new Dictionary<string, object> {["x"] = 3, ["y"] = -0.5}; var actual = expression.Evaluate<double>(parameters); actual.Should().Be(8.5); parameters["x"] = 5; actual = expression.Evaluate<double>(parameters); actual.Should().Be(24.5); } [Fact] public void Should_evaluate_empty_string_as_double_0() { var expression = new Expression("x"); var parameters = new Dictionary<string, object> {["x"] = ""}; var actual = expression.Evaluate<double>(parameters); actual.Should().Be(0); } [Fact] public void Should_evaluate_empty_string_as_bool_false() { var expression = new Expression("x"); var parameters = new Dictionary<string, object> {["x"] = ""}; var actual = expression.Evaluate<bool>(parameters); actual.Should().BeFalse(); } [Theory] [InlineData("(2 + 3", "line 1:6 missing ')' at '<EOF>'")] [InlineData("2 + 3)", "line 1:5 extraneous input ')' expecting <EOF>")] [InlineData("1 * 2 3", "line 1:6 extraneous input '3' expecting <EOF>")] [InlineData("1 *", "line 1:3 mismatched input '<EOF>' expecting {PI, '-', '!', TRUE, FALSE, '(', ID, NUMBER, STRING}")] [InlineData("1 && || 0", "line 1:5 extraneous input '||' expecting {PI, '-', '!', TRUE, FALSE, '(', ID, NUMBER, STRING}")] public void Should_throw_exception_When_parse_bad_formula(string expression, string expectedMessage) { Func<Expression> action = () => new Expression(expression); action.Should().Throw<ParsingException>().WithMessage(expectedMessage); } [Fact] public void Should_throw_exception_When_evaluate_as_double_and_result_is_not() { var expression = new Expression("x"); var parameters = new Dictionary<string, object> {["x"] = "a"}; Action action = () => expression.Evaluate<double>(parameters); action.Should().Throw<EvaluationException>().WithMessage("Cannot convert 'a' to double"); } [Fact] public void Should_throw_exception_When_result_is_not_of_requested_type() { var expression = new Expression("x"); var parameters = new Dictionary<string, object> {["x"] = "a"}; Action action = () => expression.Evaluate<DateTime>(parameters); action.Should().Throw<FormatException>().WithMessage("The string 'a' was not recognized as a valid DateTime.*"); } [Fact] public void Should_fill_description() { var expression = new Expression("x + y"); expression.Description.Should().Be("x + y"); } [Fact] public void Should_fill_variables() { var expression = new Expression("x + y"); expression.Variables.Should().ContainInOrder("x", "y"); } [Fact] public void Should_display_tree() { var expression = new Expression("x + 1"); expression.ToStringTree().Should().Be("(safeExpr (expr (expr (atom (var x))) + (expr (atom (num 1)))) <EOF>)"); } } }
33.529762
130
0.536659
[ "Apache-2.0" ]
KevinRecuerda/RecShark
tests/ExpressionEvaluator.Tests/ExpressionTests.cs
5,635
C#
using System; using System.Collections.Generic; using System.Data; using System.Data.SqlClient; using System.Threading.Tasks; using JX.Core; using JX.Core.Entity; using JX.Infrastructure.Common; using MyADO; namespace JX.ADO { /// <summary> /// 数据库表:Advertisement 的仓储实现类. /// </summary> public partial class AdvertisementRepositoryADO : IAdvertisementRepositoryADO { #region 数据上下文 /// <summary> /// 数据上下文 /// </summary> private IDBOperator _DB; /// <summary> /// 构造器注入 /// </summary> /// <param name="DB"></param> public AdvertisementRepositoryADO(IDBOperator DB) { _DB = DB; } #endregion #region 得到第一行第一列的值 /// <summary> /// 得到第一行第一列的值 /// </summary> /// <param name="statistic">要返回的字段(如:count(*) 或者 UserName)</param> /// <param name="strWhere">参数化查询条件(例如: and Name = @Name )</param> /// <param name="dict">参数的名/值集合</param> /// <returns></returns> public virtual string GetScalar(string statistic, string strWhere = "", Dictionary<string, object> dict = null) { string strSQL = "select " + statistic + " from Advertisement where 1=1 "; if (!string.IsNullOrEmpty(strWhere)) { strSQL += strWhere; } return _DB.ExeSQLScalar(strSQL, dict); } /// <summary> /// 得到第一行第一列的值(异步方式) /// </summary> /// <param name="statistic">要返回的字段(如:count(*) 或者 UserName)</param> /// <param name="strWhere">参数化查询条件(例如: and Name = @Name )</param> /// <param name="dict">参数的名/值集合</param> /// <returns></returns> public virtual async Task<string> GetScalarAsync(string statistic, string strWhere = "", Dictionary<string, object> dict = null) { string strSQL = "select " + statistic + " from Advertisement where 1=1 "; if (!string.IsNullOrEmpty(strWhere)) { strSQL += strWhere; } return await Task.Run(() => _DB.ExeSQLScalar(strSQL, dict)); } #endregion #region 得到所有行数 /// <summary> /// 得到所有行数 /// </summary> /// <returns></returns> public virtual int GetCount() { return DataConverter.CLng(GetScalar("count(*)"), 0); } /// <summary> /// 得到所有行数(异步方式) /// </summary> /// <returns></returns> public virtual async Task<int> GetCountAsync() { return DataConverter.CLng(await GetScalarAsync("count(*)"), 0); } /// <summary> /// 得到所有行数 /// </summary> /// <param name="strWhere">参数化查询条件(例如: and Name = @Name )</param> /// <param name="dict">参数的名/值集合</param> /// <returns></returns> public virtual int GetCount(string strWhere, Dictionary<string, object> dict = null) { return DataConverter.CLng(GetScalar("count(*)", strWhere, dict), 0); } /// <summary> /// 得到所有行数(异步方式) /// </summary> /// <param name="strWhere">参数化查询条件(例如: and Name = @Name )</param> /// <param name="dict">参数的名/值集合</param> /// <returns></returns> public virtual async Task<int> GetCountAsync(string strWhere, Dictionary<string, object> dict = null) { return DataConverter.CLng(await GetScalarAsync("count(*)", strWhere, dict), 0); } #endregion #region 得到最大ID、最新ID /// <summary> /// 得到数据表中第一个主键的最大数值 /// </summary> /// <returns></returns> public virtual int GetMaxID() { return _DB.GetMaxID("Advertisement", "ADID"); } /// <summary> /// 得到数据表中第一个主键的最大数值(异步方式) /// </summary> /// <returns></returns> public virtual async Task<int> GetMaxIDAsync() { return await Task.Run(() => _DB.GetMaxID("Advertisement", "ADID")); } /// <summary> /// 得到数据表中第一个主键的最大数值加1 /// </summary> /// <returns></returns> public virtual int GetNewID() { return GetMaxID() + 1; } /// <summary> /// 得到数据表中第一个主键的最大数值加1(异步方式) /// </summary> /// <returns></returns> public virtual async Task<int> GetNewIDAsync() { return await GetMaxIDAsync() + 1; } #endregion #region 验证是否存在 /// <summary> /// 检查数据是否存在 /// </summary> /// <param name="strWhere">参数化查询条件(例如: and Name = @Name )</param> /// <param name="dict">参数的名/值集合</param> /// <returns></returns> public virtual bool IsExist(string strWhere, Dictionary<string, object> dict = null) { if (GetCount(strWhere, dict) == 0) { return false; } return true; } /// <summary> /// 检查数据是否存在(异步方式) /// </summary> /// <param name="strWhere">参数化查询条件(例如: and Name = @Name )</param> /// <param name="dict">参数的名/值集合</param> /// <returns></returns> public virtual async Task<bool> IsExistAsync(string strWhere, Dictionary<string, object> dict = null) { int count = await GetCountAsync(strWhere, dict); if (count == 0) { return false; } return true; } #endregion #region 添加 /// <summary> /// 增加一条记录 /// </summary> /// <param name="entity">实体模型</param> /// <returns></returns> public virtual bool Add(Advertisement entity) { if(entity.ADID <= 0) entity.ADID=GetNewID(); Dictionary<string, object> dict = new Dictionary<string, object>(); GetParameters(entity,dict); string strSQL = "insert into Advertisement ("+ "ADID,"+ "UserID,"+ "ADType,"+ "ADName,"+ "ImgUrl,"+ "ImgWidth,"+ "ImgHeight,"+ "FlashWmode,"+ "ADIntro,"+ "LinkUrl,"+ "LinkTarget,"+ "LinkAlt,"+ "Priority,"+ "Setting,"+ "IsCountView,"+ "Views,"+ "IsCountClick,"+ "Clicks,"+ "IsAbsolutePath,"+ "IsPassed,"+ "OverdueDate) "+ "values("+ "@ADID,"+ "@UserID,"+ "@ADType,"+ "@ADName,"+ "@ImgUrl,"+ "@ImgWidth,"+ "@ImgHeight,"+ "@FlashWmode,"+ "@ADIntro,"+ "@LinkUrl,"+ "@LinkTarget,"+ "@LinkAlt,"+ "@Priority,"+ "@Setting,"+ "@IsCountView,"+ "@Views,"+ "@IsCountClick,"+ "@Clicks,"+ "@IsAbsolutePath,"+ "@IsPassed,"+ "@OverdueDate)"; return _DB.ExeSQLResult(strSQL,dict); } /// <summary> /// 增加一条记录(异步方式) /// </summary> /// <param name="entity">实体模型</param> /// <returns></returns> public virtual async Task<bool> AddAsync(Advertisement entity) { if(entity.ADID <= 0) entity.ADID=GetNewID(); Dictionary<string, object> dict = new Dictionary<string, object>(); GetParameters(entity, dict); string strSQL = "insert into Advertisement ("+ "ADID,"+ "UserID,"+ "ADType,"+ "ADName,"+ "ImgUrl,"+ "ImgWidth,"+ "ImgHeight,"+ "FlashWmode,"+ "ADIntro,"+ "LinkUrl,"+ "LinkTarget,"+ "LinkAlt,"+ "Priority,"+ "Setting,"+ "IsCountView,"+ "Views,"+ "IsCountClick,"+ "Clicks,"+ "IsAbsolutePath,"+ "IsPassed,"+ "OverdueDate) "+ "values("+ "@ADID,"+ "@UserID,"+ "@ADType,"+ "@ADName,"+ "@ImgUrl,"+ "@ImgWidth,"+ "@ImgHeight,"+ "@FlashWmode,"+ "@ADIntro,"+ "@LinkUrl,"+ "@LinkTarget,"+ "@LinkAlt,"+ "@Priority,"+ "@Setting,"+ "@IsCountView,"+ "@Views,"+ "@IsCountClick,"+ "@Clicks,"+ "@IsAbsolutePath,"+ "@IsPassed,"+ "@OverdueDate)"; return await Task.Run(() => _DB.ExeSQLResult(strSQL, dict)); } /// <summary> /// 增加一条记录,返回新的ID号。需要有一个单一主键,并且开启有标识符属性 /// </summary> /// <param name="entity">实体模型</param> /// <returns></returns> public virtual int Insert(Advertisement entity) { if(entity.ADID <= 0) entity.ADID=GetNewID(); Dictionary<string, object> dict = new Dictionary<string, object>(); GetParameters(entity,dict); string strSQL = "insert into Advertisement ("+ "ADID,"+ "UserID,"+ "ADType,"+ "ADName,"+ "ImgUrl,"+ "ImgWidth,"+ "ImgHeight,"+ "FlashWmode,"+ "ADIntro,"+ "LinkUrl,"+ "LinkTarget,"+ "LinkAlt,"+ "Priority,"+ "Setting,"+ "IsCountView,"+ "Views,"+ "IsCountClick,"+ "Clicks,"+ "IsAbsolutePath,"+ "IsPassed,"+ "OverdueDate) "+ "values("+ "@ADID,"+ "@UserID,"+ "@ADType,"+ "@ADName,"+ "@ImgUrl,"+ "@ImgWidth,"+ "@ImgHeight,"+ "@FlashWmode,"+ "@ADIntro,"+ "@LinkUrl,"+ "@LinkTarget,"+ "@LinkAlt,"+ "@Priority,"+ "@Setting,"+ "@IsCountView,"+ "@Views,"+ "@IsCountClick,"+ "@Clicks,"+ "@IsAbsolutePath,"+ "@IsPassed,"+ "@OverdueDate)"; if(_DB.ExeSQLResult(strSQL,dict)) { return DataConverter.CLng(entity.ADID); } return -1; } /// <summary> /// 增加一条记录,返回新的ID号。需要有一个单一主键,并且开启有标识符属性(异步方式) /// </summary> /// <param name="entity">实体模型</param> /// <returns></returns> public virtual async Task<int> InsertAsync(Advertisement entity) { if(entity.ADID <= 0) entity.ADID=GetNewID(); Dictionary<string, object> dict = new Dictionary<string, object>(); GetParameters(entity,dict); string strSQL = "insert into Advertisement ("+ "ADID,"+ "UserID,"+ "ADType,"+ "ADName,"+ "ImgUrl,"+ "ImgWidth,"+ "ImgHeight,"+ "FlashWmode,"+ "ADIntro,"+ "LinkUrl,"+ "LinkTarget,"+ "LinkAlt,"+ "Priority,"+ "Setting,"+ "IsCountView,"+ "Views,"+ "IsCountClick,"+ "Clicks,"+ "IsAbsolutePath,"+ "IsPassed,"+ "OverdueDate) "+ "values("+ "@ADID,"+ "@UserID,"+ "@ADType,"+ "@ADName,"+ "@ImgUrl,"+ "@ImgWidth,"+ "@ImgHeight,"+ "@FlashWmode,"+ "@ADIntro,"+ "@LinkUrl,"+ "@LinkTarget,"+ "@LinkAlt,"+ "@Priority,"+ "@Setting,"+ "@IsCountView,"+ "@Views,"+ "@IsCountClick,"+ "@Clicks,"+ "@IsAbsolutePath,"+ "@IsPassed,"+ "@OverdueDate)"; if(await Task.Run(() => _DB.ExeSQLResult(strSQL, dict))) { return DataConverter.CLng(entity.ADID); } return -1; } /// <summary> /// 增加或更新一条记录 /// </summary> /// <param name="entity">实体模型</param> /// <param name="IsSave">是否增加</param> /// <returns></returns> public virtual bool AddOrUpdate(Advertisement entity, bool IsSave) { return IsSave ? Add(entity) : Update(entity); } /// <summary> /// 增加或更新一条记录(异步方式) /// </summary> /// <param name="entity">实体模型</param> /// <param name="IsSave">是否增加</param> /// <returns></returns> public virtual async Task<bool> AddOrUpdateAsync(Advertisement entity, bool IsSave) { return IsSave ? await AddAsync(entity) : await UpdateAsync(entity); } #endregion #region 删除 /// <summary> /// 通过主键删除 /// </summary> /// <returns></returns> public bool Delete(System.Int32 adid) { string strSQL = "delete from Advertisement where " + "ADID = @ADID"; Dictionary<string, object> dict = new Dictionary<string, object>(); dict.Add("ADID", adid); return _DB.ExeSQLResult(strSQL, dict); } /// <summary> /// 通过主键删除 /// </summary> /// <returns></returns> public async Task<bool> DeleteAsync(System.Int32 adid) { string strSQL = "delete from Advertisement where " + "ADID = @ADID"; Dictionary<string, object> dict = new Dictionary<string, object>(); dict.Add("ADID", adid); return await Task.Run(() => _DB.ExeSQLResult(strSQL, dict)); } /// <summary> /// 删除一条或多条记录 /// </summary> /// <param name="strWhere">参数化删除条件(例如: and Name = @Name )</param> /// <param name="dict">参数的名/值集合</param> /// <returns></returns> public virtual bool Delete(string strWhere, Dictionary<string, object> dict = null) { string strSQL = "delete from Advertisement where 1=1 " + strWhere; return _DB.ExeSQLResult(strSQL, dict); } /// <summary> /// 删除一条或多条记录(异步方式) /// </summary> /// <param name="strWhere">参数化删除条件(例如: and Name = @Name )</param> /// <param name="dict">参数的名/值集合</param> /// <returns></returns> public virtual async Task<bool> DeleteAsync(string strWhere, Dictionary<string, object> dict = null) { string strSQL = "delete from Advertisement where 1=1 " + strWhere; return await Task.Run(() => _DB.ExeSQLResult(strSQL, dict)); } #endregion #region 修改 /// <summary> /// 更新一条记录 /// </summary> /// <param name="entity">实体模型</param> /// <returns></returns> public virtual bool Update(Advertisement entity) { Dictionary<string, object> dict = new Dictionary<string, object>(); GetParameters(entity, dict); string strSQL = "Update Advertisement SET "+ "UserID = @UserID,"+ "ADType = @ADType,"+ "ADName = @ADName,"+ "ImgUrl = @ImgUrl,"+ "ImgWidth = @ImgWidth,"+ "ImgHeight = @ImgHeight,"+ "FlashWmode = @FlashWmode,"+ "ADIntro = @ADIntro,"+ "LinkUrl = @LinkUrl,"+ "LinkTarget = @LinkTarget,"+ "LinkAlt = @LinkAlt,"+ "Priority = @Priority,"+ "Setting = @Setting,"+ "IsCountView = @IsCountView,"+ "Views = @Views,"+ "IsCountClick = @IsCountClick,"+ "Clicks = @Clicks,"+ "IsAbsolutePath = @IsAbsolutePath,"+ "IsPassed = @IsPassed,"+ "OverdueDate = @OverdueDate"+ " WHERE "+ "ADID = @ADID"; return _DB.ExeSQLResult(strSQL, dict); } /// <summary> /// 更新一条记录(异步方式) /// </summary> /// <param name="entity">实体模型</param> /// <returns></returns> public virtual async Task<bool> UpdateAsync(Advertisement entity) { Dictionary<string, object> dict = new Dictionary<string, object>(); GetParameters(entity, dict); string strSQL = "Update Advertisement SET "+ "UserID = @UserID,"+ "ADType = @ADType,"+ "ADName = @ADName,"+ "ImgUrl = @ImgUrl,"+ "ImgWidth = @ImgWidth,"+ "ImgHeight = @ImgHeight,"+ "FlashWmode = @FlashWmode,"+ "ADIntro = @ADIntro,"+ "LinkUrl = @LinkUrl,"+ "LinkTarget = @LinkTarget,"+ "LinkAlt = @LinkAlt,"+ "Priority = @Priority,"+ "Setting = @Setting,"+ "IsCountView = @IsCountView,"+ "Views = @Views,"+ "IsCountClick = @IsCountClick,"+ "Clicks = @Clicks,"+ "IsAbsolutePath = @IsAbsolutePath,"+ "IsPassed = @IsPassed,"+ "OverdueDate = @OverdueDate"+ " WHERE "+ "ADID = @ADID"; return await Task.Run(() => _DB.ExeSQLResult(strSQL, dict)); } /// <summary> /// 修改一条或多条记录 /// </summary> /// <param name="strColumns">参数化要修改的列(如:ID = @ID,Name = @Name)</param> /// <param name="dictColumns">包含要修改的名称和值的集合,对应strColumns参数中要修改列的值</param> /// <param name="strWhere">参数化修改条件(例如: and ID = @ID)</param> /// <param name="dictWhere">包含查询名称和值的集合,对应strWhere参数中的值</param> /// <returns></returns> public virtual bool Update(string strColumns, Dictionary<string, object> dictColumns = null, string strWhere = "", Dictionary<string, object> dictWhere = null) { if (string.IsNullOrEmpty(strColumns)) return false; strColumns = StringHelper.ReplaceIgnoreCase(strColumns, "@", "@UP_"); string strSQL = "Update Advertisement SET " + strColumns + " where 1=1 " + strWhere; Dictionary<string, object> dict = new Dictionary<string, object>(); //生成要修改列的参数 foreach (KeyValuePair<string, object> kvp in dictColumns) { dict.Add("@UP_" + kvp.Key,kvp.Value); } //生成查询条件的参数 foreach (KeyValuePair<string, object> kvp in dictWhere) { dict.Add(kvp.Key, kvp.Value); } return _DB.ExeSQLResult(strSQL, dict); } /// <summary> /// 修改一条或多条记录(异步方式) /// </summary> /// <param name="strColumns">参数化要修改的列(如:ID = @ID,Name = @Name)</param> /// <param name="dictColumns">包含要修改的名称和值的集合,对应strColumns参数中要修改列的值</param> /// <param name="strWhere">参数化修改条件(例如: and ID = @ID)</param> /// <param name="dictWhere">包含查询名称和值的集合,对应strWhere参数中的值</param> /// <returns></returns> public virtual async Task<bool> UpdateAsync(string strColumns, Dictionary<string, object> dictColumns = null, string strWhere = "", Dictionary<string, object> dictWhere = null) { if (string.IsNullOrEmpty(strColumns)) return false; strColumns = StringHelper.ReplaceIgnoreCase(strColumns, "@", "@UP_"); string strSQL = "Update Advertisement SET " + strColumns + " where 1=1 " + strWhere; Dictionary<string, object> dict = new Dictionary<string, object>(); //生成要修改列的参数 foreach (KeyValuePair<string, object> kvp in dictColumns) { dict.Add("@UP_" + kvp.Key, kvp.Value); } //生成查询条件的参数 foreach (KeyValuePair<string, object> kvp in dictWhere) { dict.Add(kvp.Key, kvp.Value); } return await Task.Run(() => _DB.ExeSQLResult(strSQL, dict)); } #endregion #region 得到实体 /// <summary> /// 通过主键返回第一条信息的实体类。 /// </summary> /// <returns></returns> public Advertisement GetEntity(System.Int32 adid) { string strCondition = string.Empty; strCondition += " and ADID = @ADID"; Dictionary<string, object> dict = new Dictionary<string, object>(); dict.Add("ADID", adid); return GetEntity(strCondition,dict); } /// <summary> /// 通过主键返回第一条信息的实体类。 /// </summary> /// <returns></returns> public async Task<Advertisement> GetEntityAsync(System.Int32 adid) { string strCondition = string.Empty; strCondition += " and ADID = @ADID"; Dictionary<string, object> dict = new Dictionary<string, object>(); dict.Add("ADID", adid); return await GetEntityAsync(strCondition,dict); } /// <summary> /// 获取实体 /// </summary> /// <param name="strWhere">参数化查询条件(例如: and Name = @Name )</param> /// <param name="dict">参数的名/值集合</param> /// <returns></returns> public virtual Advertisement GetEntity(string strWhere, Dictionary<string, object> dict = null) { Advertisement obj = null; string strSQL = "select top 1 * from Advertisement where 1=1 " + strWhere; using (NullableDataReader reader = _DB.GetDataReader(strSQL, dict)) { if (reader.Read()) { obj = GetEntityFromrdr(reader); } } return obj; } /// <summary> /// 获取实体(异步方式) /// </summary> /// <param name="strWhere">参数化查询条件(例如: and Name = @Name )</param> /// <param name="dict">参数的名/值集合</param> /// <returns></returns> public virtual async Task<Advertisement> GetEntityAsync(string strWhere, Dictionary<string, object> dict = null) { Advertisement obj = null; string strSQL = "select top 1 * from Advertisement where 1=1 " + strWhere; using (NullableDataReader reader = await Task.Run(() => _DB.GetDataReader(strSQL, dict))) { if (reader.Read()) { obj = GetEntityFromrdr(reader); } } return obj; } #endregion #region 得到实体列表 /// <summary> /// 得到实体列表 /// </summary> /// <param name="strWhere">参数化查询条件(例如: and Name = @Name )</param> /// <param name="dict">参数的名/值集合</param> /// <returns></returns> public virtual IList<Advertisement> GetEntityList(string strWhere="", Dictionary<string, object> dict = null) { IList<Advertisement> list = new List<Advertisement>(); string strSQL = "select * from Advertisement where 1=1 "; if(!string.IsNullOrEmpty(strWhere)) { strSQL += strWhere; } using (NullableDataReader reader = _DB.GetDataReader(strSQL, dict)) { while (reader.Read()) { list.Add(GetEntityFromrdr(reader)); } } return list; } /// <summary> /// 得到实体列表(异步方式) /// </summary> /// <param name="strWhere">参数化查询条件(例如: and Name = @Name )</param> /// <param name="dict">参数的名/值集合</param> /// <returns></returns> public virtual async Task<IList<Advertisement>> GetEntityListAsync(string strWhere = "", Dictionary<string, object> dict = null) { IList<Advertisement> list = new List<Advertisement>(); string strSQL = "select * from Advertisement where 1=1 "; if (!string.IsNullOrEmpty(strWhere)) { strSQL += strWhere; } using (NullableDataReader reader = await Task.Run(() => _DB.GetDataReader(strSQL, dict))) { while (reader.Read()) { list.Add(GetEntityFromrdr(reader)); } } return list; } #endregion #region 得到数据列表 /// <summary> /// 返回所有信息 /// </summary> /// <param name="strWhere">参数化查询条件(例如: and Name = @Name )</param> /// <param name="dict">参数的名/值集合</param> /// <returns></returns> public virtual DataTable GetAllData(string strWhere = "", Dictionary<string, object> dict = null) { string strSQL = "select * from Advertisement where 1=1 "; if(!string.IsNullOrEmpty(strWhere)) { strSQL += strWhere; } return _DB.GetDataTable(strSQL, dict); } /// <summary> /// 返回所有信息(异步方式) /// </summary> /// <param name="strWhere">参数化查询条件(例如: and Name = @Name )</param> /// <param name="dict">参数的名/值集合</param> /// <returns></returns> public virtual async Task<DataTable> GetAllDataAsync(string strWhere = "", Dictionary<string, object> dict = null) { string strSQL = "select * from Advertisement where 1=1 "; if(!string.IsNullOrEmpty(strWhere)) { strSQL += strWhere; } return await Task.Run(() => _DB.GetDataTable(strSQL, dict)); } /// <summary> /// 返回所有信息 /// </summary> /// <param name="strWhere">参数化查询条件(例如: and Name = @Name )</param> /// <param name="dict">参数的名/值集合</param> /// <param name="strExtended">返回的指定列(例如: extended = id + name 或 distinct name)</param> /// <returns></returns> public virtual DataTable GetAllData(string strWhere = "", Dictionary<string, object> dict = null, string strExtended="*") { string strSQL = "select " + strExtended + " from Advertisement where 1=1 "; if(!string.IsNullOrEmpty(strWhere)) { strSQL += strWhere; } return _DB.GetDataTable(strSQL, dict); } /// <summary> /// 返回所有信息(异步方式) /// </summary> /// <param name="strWhere">参数化查询条件(例如: and Name = @Name )</param> /// <param name="dict">参数的名/值集合</param> /// <param name="strExtended">返回的指定列(例如: extended = id + name 或 distinct name)</param> /// <returns></returns> public virtual async Task<DataTable> GetAllDataAsync(string strWhere = "", Dictionary<string, object> dict = null, string strExtended = "*") { string strSQL = "select " + strExtended + " from Advertisement where 1=1 "; if(!string.IsNullOrEmpty(strWhere)) { strSQL += strWhere; } return await Task.Run(() => _DB.GetDataTable(strSQL, dict)); } #endregion #region 分页 /// <summary> /// 通过存储过程"Common_GetList",得到分页后的数据 /// </summary> /// <param name="startRowIndexId">开始行索引</param> /// <param name="maxNumberRows">每页最大显示数量</param> /// <param name="Filter">查询条件(例如: Name = 'name' and id=1 )</param> /// <param name="Total">输出参数:查询总数</param> /// <returns></returns> public IList<Advertisement> GetList(int startRowIndexId, int maxNumberRows,string Filter, out int Total) { Total = 0; return GetList(startRowIndexId,maxNumberRows,"","","",Filter,"",out Total); } /// <summary> /// 通过存储过程“Common_GetList”,得到分页后的数据 /// </summary> /// <param name="startRowIndexId">开始行索引</param> /// <param name="maxNumberRows">每页最大显示数量</param> /// <param name="SortColumn">排序字段名,只能指定一个字段</param> /// <param name="StrColumn">返回列名</param> /// <param name="Sorts">排序方式(DESC,ASC)</param> /// <param name="Filter">查询条件(例如: Name = 'name' and id=1 )</param> /// <param name="TableName">查询表名,可以指定联合查询的SQL语句(例如: Comment LEFT JOIN Users ON Comment.UserName = Users.UserName)</param> /// <param name="Total">输出参数:查询总数</param> /// <returns></returns> public virtual IList<Advertisement> GetList(int startRowIndexId, int maxNumberRows, string SortColumn, string StrColumn, string Sorts, string Filter, string TableName, out int Total) { IList<Advertisement> list = new List<Advertisement>(); if (string.IsNullOrEmpty(SortColumn)) { SortColumn = "ADID"; } if (string.IsNullOrEmpty(StrColumn)) { StrColumn = "*"; } if (string.IsNullOrEmpty(Sorts)) { Sorts = "DESC"; } if (string.IsNullOrEmpty(TableName)) { TableName = "Advertisement"; } string storedProcedureName = "Common_GetList"; SqlParameter parmStartRows = new SqlParameter("StartRows", startRowIndexId); SqlParameter parmPageSize = new SqlParameter("PageSize", maxNumberRows); SqlParameter parmSortColumn = new SqlParameter("SortColumn", SortColumn); SqlParameter parmStrColumn = new SqlParameter("StrColumn", StrColumn); SqlParameter parmSorts = new SqlParameter("Sorts", Sorts); SqlParameter parmTableName = new SqlParameter("TableName", TableName); SqlParameter parmFilter = new SqlParameter("Filter", Filter); SqlParameter parmTotal = new SqlParameter("Total", SqlDbType.Int); parmTotal.Direction = ParameterDirection.Output; IDataParameter[] parameterArray = new IDataParameter[8]; parameterArray[0] = parmStartRows; parameterArray[1] = parmPageSize; parameterArray[2] = parmSortColumn; parameterArray[3] = parmStrColumn; parameterArray[4] = parmSorts; parameterArray[5] = parmTableName; parameterArray[6] = parmFilter; parameterArray[7] = parmTotal; using (NullableDataReader reader = _DB.GetDataReaderByProc(storedProcedureName, parameterArray)) { while (reader.Read()) { list.Add(GetEntityFromrdr(reader)); } } Total = (int)parmTotal.Value; return list; } /// <summary> /// 通过存储过程"Common_GetListBySortColumn",得到分页后的数据 /// </summary> /// <param name="startRowIndexId">开始行索引</param> /// <param name="maxNumberRows">每页最大显示数量</param> /// <param name="Filter">查询条件(例如: Name = 'name' and id=1 )</param> /// <param name="Total">输出参数:查询总数</param> /// <returns></returns> public IList<Advertisement> GetListBySortColumn(int startRowIndexId, int maxNumberRows,string Filter, out int Total) { Total = 0; return GetListBySortColumn(startRowIndexId,maxNumberRows,"","","","","",Filter,"",out Total); } /// <summary> /// 通过存储过程"Common_GetListBySortColumn",得到分页后的数据 /// </summary> /// <param name="startRowIndexId">开始行索引</param> /// <param name="maxNumberRows">每页最大显示数量</param> /// <param name="Sorts">排序方式(DESC,ASC)</param> /// <param name="Filter">查询条件(例如: Name = 'name' and id=1 )</param> /// <param name="Total">输出参数:查询总数</param> /// <returns></returns> public IList<Advertisement> GetListBySortColumn(int startRowIndexId, int maxNumberRows,string Sorts,string Filter, out int Total) { Total = 0; return GetListBySortColumn(startRowIndexId,maxNumberRows,"","","","",Sorts,Filter,"",out Total); } /// <summary> /// 通过存储过程“Common_GetListBySortColumn”,得到分页后的数据 /// </summary> /// <param name="startRowIndexId">开始行索引</param> /// <param name="maxNumberRows">每页最大显示数量</param> /// <param name="PrimaryColumn">主键字段名</param> /// <param name="SortColumnDbType">排序字段的数据类型(如:int)</param> /// <param name="SortColumn">排序字段名,只能指定一个字段</param> /// <param name="StrColumn">返回列名</param> /// <param name="Sorts">排序方式(DESC,ASC)</param> /// <param name="Filter">查询条件(例如: Name = 'name' and id=1 )</param> /// <param name="TableName">查询表名,可以指定联合查询的SQL语句(例如: Comment LEFT JOIN Users ON Comment.UserName = Users.UserName)</param> /// <param name="Total">输出参数:查询总数</param> /// <returns></returns> public virtual IList<Advertisement> GetListBySortColumn(int startRowIndexId, int maxNumberRows, string PrimaryColumn, string SortColumnDbType, string SortColumn, string StrColumn, string Sorts, string Filter, string TableName, out int Total) { IList<Advertisement> list = new List<Advertisement>(); if (string.IsNullOrEmpty(PrimaryColumn)) { PrimaryColumn = "ADID"; } if (string.IsNullOrEmpty(SortColumnDbType)) { SortColumnDbType = "int"; } if (string.IsNullOrEmpty(SortColumn)) { SortColumn = "ADID"; } if (string.IsNullOrEmpty(StrColumn)) { StrColumn = "*"; } if (string.IsNullOrEmpty(Sorts)) { Sorts = "DESC"; } if (string.IsNullOrEmpty(TableName)) { TableName = "Advertisement"; } string storedProcedureName = "Common_GetListBySortColumn"; SqlParameter parmStartRows = new SqlParameter("StartRows", startRowIndexId); SqlParameter parmPageSize = new SqlParameter("PageSize", maxNumberRows); SqlParameter parmPrimaryColumn = new SqlParameter("PrimaryColumn", PrimaryColumn); SqlParameter parmSortColumnDbType = new SqlParameter("SortColumnDbType", SortColumnDbType); SqlParameter parmSortColumn = new SqlParameter("SortColumn", SortColumn); SqlParameter parmStrColumn = new SqlParameter("StrColumn", StrColumn); SqlParameter parmSorts = new SqlParameter("Sorts", Sorts); SqlParameter parmTableName = new SqlParameter("TableName", TableName); SqlParameter parmFilter = new SqlParameter("Filter", Filter); SqlParameter parmTotal = new SqlParameter("Total", SqlDbType.Int); parmTotal.Direction = ParameterDirection.Output; IDataParameter[] parameterArray = new IDataParameter[10]; parameterArray[0] = parmStartRows; parameterArray[1] = parmPageSize; parameterArray[2] = parmPrimaryColumn; parameterArray[3] = parmSortColumnDbType; parameterArray[4] = parmSortColumn; parameterArray[5] = parmStrColumn; parameterArray[6] = parmSorts; parameterArray[7] = parmTableName; parameterArray[8] = parmFilter; parameterArray[9] = parmTotal; using (NullableDataReader reader = _DB.GetDataReaderByProc(storedProcedureName, parameterArray)) { while (reader.Read()) { list.Add(GetEntityFromrdr(reader)); } } Total = (int)parmTotal.Value; return list; } #endregion #region 辅助方法 /// <summary> /// 把实体类转换成键/值对集合 /// </summary> /// <param name="entity"></param> /// <param name="dict"></param> private static void GetParameters(Advertisement entity, Dictionary<string, object> dict) { dict.Add("ADID", entity.ADID); dict.Add("UserID", entity.UserID); dict.Add("ADType", entity.ADType); dict.Add("ADName", entity.ADName); dict.Add("ImgUrl", entity.ImgUrl); dict.Add("ImgWidth", entity.ImgWidth); dict.Add("ImgHeight", entity.ImgHeight); dict.Add("FlashWmode", entity.FlashWmode); dict.Add("ADIntro", entity.ADIntro); dict.Add("LinkUrl", entity.LinkUrl); dict.Add("LinkTarget", entity.LinkTarget); dict.Add("LinkAlt", entity.LinkAlt); dict.Add("Priority", entity.Priority); dict.Add("Setting", entity.Setting); dict.Add("IsCountView", entity.IsCountView); dict.Add("Views", entity.Views); dict.Add("IsCountClick", entity.IsCountClick); dict.Add("Clicks", entity.Clicks); dict.Add("IsAbsolutePath", entity.IsAbsolutePath); dict.Add("IsPassed", entity.IsPassed); dict.Add("OverdueDate", entity.OverdueDate); } /// <summary> /// 通过数据读取器生成实体类 /// </summary> /// <param name="rdr"></param> /// <returns></returns> private static Advertisement GetEntityFromrdr(NullableDataReader rdr) { Advertisement info = new Advertisement(); info.ADID = rdr.GetInt32("ADID"); info.UserID = rdr.GetInt32("UserID"); info.ADType = rdr.GetInt32("ADType"); info.ADName = rdr.GetString("ADName"); info.ImgUrl = rdr.GetString("ImgUrl"); info.ImgWidth = rdr.GetInt32("ImgWidth"); info.ImgHeight = rdr.GetInt32("ImgHeight"); info.FlashWmode = rdr.GetInt32("FlashWmode"); info.ADIntro = rdr.GetString("ADIntro"); info.LinkUrl = rdr.GetString("LinkUrl"); info.LinkTarget = rdr.GetInt32("LinkTarget"); info.LinkAlt = rdr.GetString("LinkAlt"); info.Priority = rdr.GetInt32("Priority"); info.Setting = rdr.GetString("Setting"); info.IsCountView = rdr.GetBoolean("IsCountView"); info.Views = rdr.GetInt32("Views"); info.IsCountClick = rdr.GetBoolean("IsCountClick"); info.Clicks = rdr.GetInt32("Clicks"); info.IsAbsolutePath = rdr.GetBoolean("IsAbsolutePath"); info.IsPassed = rdr.GetBoolean("IsPassed"); info.OverdueDate = rdr.GetNullableDateTime("OverdueDate"); return info; } #endregion } }
30.00473
243
0.625225
[ "Apache-2.0" ]
lixiong24/IPS2.1
CodeSmith/output/RepositoryADO/AdvertisementRepositoryADO.cs
34,489
C#
using FacialStuff.Defs; using JetBrains.Annotations; using RimWorld; using System; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Linq; using UnityEngine; using Verse; using Verse.AI; namespace FacialStuff.AnimatorWindows { public class MainTabWindow_PoseAnimator : MainTabWindow_BaseAnimator { #region Public Fields public static bool Equipment; public static float HorHeadOffset; public static float VerHeadOffset; public static bool IsPosing; #endregion Public Fields #region Private Fields [CanBeNull] public static PoseCycleDef EditorPoseCycle; #endregion Private Fields public static bool IsOpen; #region Public Properties #endregion Private Properties #region Public Methods // public static float horHeadOffset; protected override void DoBasicSettingsMenu(Listing_Standard listing) { base.DoBasicSettingsMenu(listing); GetBodyAnimDef(); // listing_Standard.CheckboxLabeled("Equipment", ref Equipment); // listing_Standard.Label(horHeadOffset.ToString("N2") + " - " + verHeadOffset.ToString("N2")); // horHeadOffset = listing_Standard.Slider(horHeadOffset, -1f, 1f); // verHeadOffset = listing_Standard.Slider(verHeadOffset, -1f, 1f); listing.Label(CompAnim.BodyAnim.offCenterX.ToString("N2")); CompAnim.BodyAnim.offCenterX = listing.Slider(CompAnim.BodyAnim.offCenterX, -0.2f, 0.2f); if (listing.ButtonText(EditorPoseCycle?.LabelCap)) { List<string> exists = new List<string>(); List<FloatMenuOption> list = new List<FloatMenuOption>(); CompAnim.BodyAnim.poseCycles.Clear(); foreach (PoseCycleDef posecycle in (from bsm in DefDatabase<PoseCycleDef>.AllDefs orderby bsm.label select bsm) .TakeWhile(current => CompAnim.BodyAnim.PoseCycleType != "None") .Where(current => current.PoseCycleType == CompAnim.BodyAnim.PoseCycleType)) { list.Add(new FloatMenuOption(posecycle.LabelCap, delegate { EditorPoseCycle = posecycle; })); exists.Add(posecycle.pawnPosture.ToString()); CompAnim.BodyAnim.poseCycles.Add(posecycle); } string[] names = Enum.GetNames(typeof(PawnPosture)); for (int index = 0; index < names.Length; index++) { string name = names[index]; PawnPosture myenum = (PawnPosture)Enum.ToObject(typeof(PawnPosture), index); if (exists.Contains(myenum.ToString())) { continue; } list.Add( new FloatMenuOption( "Add new " + CompAnim.BodyAnim.PoseCycleType + "_" + myenum, delegate { PoseCycleDef newCycle = new PoseCycleDef(); newCycle.defName = newCycle.label = CompAnim.BodyAnim.PoseCycleType + "_" + name; newCycle.pawnPosture = myenum; newCycle.PoseCycleType = CompAnim.BodyAnim.PoseCycleType; GameComponent_FacialStuff.BuildPoseCycles(newCycle); EditorPoseCycle = newCycle; CompAnim.BodyAnim.poseCycles.Add(newCycle); })); } Find.WindowStack.Add(new FloatMenu(list)); } listing.Gap(); string configFolder = DefPath; if (listing.ButtonText("Export BodyDef")) { string filePath = configFolder + "/BodyAnimDefs/" + CompAnim.BodyAnim.defName + ".xml"; Find.WindowStack.Add( Dialog_MessageBox.CreateConfirmation( "Confirm overwriting " + filePath, delegate { ExportAnimDefs.Defs animDef = new ExportAnimDefs.Defs(CompAnim.BodyAnim); DirectXmlSaver.SaveDataObject( animDef, filePath); }, true)); // BodyAnimDef animDef = this.bodyAnimDef; } if (listing.ButtonText("Export PoseCycle")) { string path = configFolder + "/PoseCycleDefs/" + EditorPoseCycle?.defName + ".xml"; Find.WindowStack.Add( Dialog_MessageBox.CreateConfirmation( "Confirm overwriting " + path, delegate { ExportPoseCycleDefs.Defs cycle = new ExportPoseCycleDefs.Defs(EditorPoseCycle); DirectXmlSaver.SaveDataObject( cycle, path); }, true)); } } public override void DoWindowContents(Rect inRect) { base.DoWindowContents(inRect); if (GUI.changed) { GameComponent_FacialStuff.BuildPoseCycles(); } } protected override void BuildEditorCycle() { base.BuildEditorCycle(); GameComponent_FacialStuff.BuildPoseCycles(EditorPoseCycle); } protected override void DrawBodySettingsEditor(Rot4 rotation) { Rect sliderRect = new Rect(0, 0, this.SliderWidth, 40f); // this.DrawBodyStats("legLength", ref bodyAnimDef.legLength, ref sliderRect); // this.DrawBodyStats("hipOffsetVerticalFromCenter", // ref bodyAnimDef.hipOffsetVerticalFromCenter, ref sliderRect); GetBodyAnimDef(); Vector3 shoulderOffset = CompAnim.BodyAnim.shoulderOffsets[rotation.AsInt]; if (shoulderOffset.y == 0f) { if (rotation == Rot4.West) { shoulderOffset.y = -0.025f; } else { shoulderOffset.y = 0.025f; } } bool front = shoulderOffset.y > 0; if (rotation == Rot4.West) { front = shoulderOffset.y < 0; } this.DrawBodyStats("shoulderOffsetX", ref shoulderOffset.x, ref sliderRect); this.DrawBodyStats("shoulderOffsetZ", ref shoulderOffset.z, ref sliderRect); // this.DrawBodyStats("shoulderFront", ref front, ref sliderRect); Vector3 hipOffset = CompAnim.BodyAnim.hipOffsets[rotation.AsInt]; if (hipOffset.y == 0f) { if (rotation == Rot4.West) { hipOffset.y = -0.025f; } else { hipOffset.y = 0.025f; } } bool hipFront = hipOffset.y > 0; if (rotation == Rot4.West) { hipFront = hipOffset.y < 0; } this.DrawBodyStats("hipOffsetX", ref hipOffset.x, ref sliderRect); this.DrawBodyStats("hipOffsetZ", ref hipOffset.z, ref sliderRect); // this.DrawBodyStats("hipFront", ref hipFront, ref sliderRect); if (GUI.changed) { this.SetNewVector(rotation, shoulderOffset, CompAnim.BodyAnim.shoulderOffsets, front); this.SetNewVector(rotation, hipOffset, CompAnim.BodyAnim.hipOffsets, hipFront); } this.DrawBodyStats("armLength", ref CompAnim.BodyAnim.armLength, ref sliderRect); this.DrawBodyStats("extraLegLength", ref CompAnim.BodyAnim.extraLegLength, ref sliderRect); } [SuppressMessage("ReSharper", "PossibleNullReferenceException")] protected override void DrawKeyframeEditor(Rect keyframes, Rot4 rotation) { if (this.CurrentFrame == null) { return; } Rect leftController = keyframes.LeftHalf(); Rect rightController = keyframes.RightHalf(); leftController.xMax -= this.Spacing; rightController.xMin += this.Spacing; { GUI.BeginGroup(leftController); Rect editorRect = new Rect(0f, 0f, leftController.width, 56f); // Dictionary<int, float> keysFloats = new Dictionary<int, float>(); // // Get the next keyframe // for (int i = 0; i < frames.Count; i++) // { // float? footPositionX = frames[i].FootPositionX; // if (!footPositionX.HasValue) // { // continue; // } // keysFloats.Add(frames[i].KeyIndex, footPositionX.Value); // } List<int> framesAt; List<PawnKeyframe> frames = PawnKeyframes; PoseCycleDef cycleDef = EditorPoseCycle; { framesAt = (from keyframe in frames where keyframe.HandPositionX.HasValue select keyframe.KeyIndex) .ToList(); this.SetPosition( ref this.CurrentFrame.HandPositionX, ref editorRect, cycleDef.HandPositionX, "HandPosX", framesAt); framesAt = (from keyframe in frames where keyframe.HandPositionZ.HasValue select keyframe.KeyIndex) .ToList(); this.SetPosition( ref this.CurrentFrame.HandPositionZ, ref editorRect, cycleDef.HandPositionZ, "HandPosZ", framesAt); framesAt = (from keyframe in frames where keyframe.FootPositionX.HasValue select keyframe.KeyIndex) .ToList(); this.SetPosition( ref this.CurrentFrame.FootPositionX, ref editorRect, cycleDef.FootPositionX, "FootPosX", framesAt); framesAt = (from keyframe in frames where keyframe.FootPositionZ.HasValue select keyframe.KeyIndex) .ToList(); this.SetPosition( ref this.CurrentFrame.FootPositionZ, ref editorRect, cycleDef.FootPositionZ, "FootPosZ", framesAt); framesAt = (from keyframe in frames where keyframe.FootAngle.HasValue select keyframe.KeyIndex) .ToList(); this.SetAngle( ref this.CurrentFrame.FootAngle, ref editorRect, cycleDef.FootAngle, "FootAngle", framesAt); framesAt = (from keyframe in frames where keyframe.HipOffsetHorizontalX.HasValue select keyframe.KeyIndex).ToList(); this.SetPosition( ref this.CurrentFrame.HipOffsetHorizontalX, ref editorRect, cycleDef.HipOffsetHorizontalX, "HipOffsetHorizontalX", framesAt); // Quadruped } GUI.EndGroup(); GUI.BeginGroup(rightController); editorRect.x = 0f; editorRect.y = 0f; if (this.CompAnim.Props.bipedWithHands) { this.SetAngleShoulder(ref cycleDef.shoulderAngle, ref editorRect, "ShoulderAngle"); framesAt = (from keyframe in frames where keyframe.HandsSwingAngle.HasValue select keyframe.KeyIndex) .ToList(); this.SetAngle( ref this.CurrentFrame.HandsSwingAngle, ref editorRect, cycleDef.HandsSwingAngle, "HandSwing", framesAt); } if (rotation.IsHorizontal) { if (this.CompAnim.Props.quadruped) { framesAt = (from keyframe in frames where keyframe.FrontPawPositionX.HasValue select keyframe.KeyIndex).ToList(); this.SetPosition( ref this.CurrentFrame.FrontPawPositionX, ref editorRect, cycleDef.FrontPawPositionX, "FrontPawPositionX", framesAt); framesAt = (from keyframe in frames where keyframe.FrontPawPositionZ.HasValue select keyframe.KeyIndex).ToList(); this.SetPosition( ref this.CurrentFrame.FrontPawPositionZ, ref editorRect, cycleDef.FrontPawPositionZ, "FrontPawPositionZ", framesAt); framesAt = (from keyframe in frames where keyframe.FrontPawAngle.HasValue select keyframe.KeyIndex).ToList(); this.SetAngle( ref this.CurrentFrame.FrontPawAngle, ref editorRect, cycleDef.FrontPawAngle, "FrontPawAngle", framesAt); } framesAt = (from keyframe in frames where keyframe.BodyAngle.HasValue select keyframe.KeyIndex) .ToList(); this.SetAngle( ref this.CurrentFrame.BodyAngle, ref editorRect, cycleDef.BodyAngle, "BodyAngle", framesAt); } else { framesAt = (from keyframe in frames where keyframe.BodyAngleVertical.HasValue select keyframe.KeyIndex).ToList(); this.SetAngle( ref this.CurrentFrame.BodyAngleVertical, ref editorRect, cycleDef.BodyAngleVertical, "BodyAngleVertical", framesAt); } framesAt = (from keyframe in frames where keyframe.ShoulderOffsetHorizontalX.HasValue select keyframe.KeyIndex).ToList(); this.SetPosition( ref this.CurrentFrame.ShoulderOffsetHorizontalX, ref editorRect, cycleDef.ShoulderOffsetHorizontalX, "ShoulderOffsetHorizontalX", framesAt); framesAt = (from keyframe in frames where keyframe.BodyOffsetZ.HasValue select keyframe.KeyIndex).ToList(); this.SetPosition( ref this.CurrentFrame.BodyOffsetZ, ref editorRect, cycleDef.BodyOffsetZ, "BodyOffsetZ", framesAt); GUI.EndGroup(); } } protected override void SetCurrentCycle() { BodyAnimDef anim = this.CompAnim.BodyAnim; if (anim != null && anim.poseCycles.Any()) { EditorPoseCycle = anim.poseCycles.FirstOrDefault(); } } protected override void SetKeyframes() { PawnKeyframes = EditorPoseCycle?.keyframes; this.Label = EditorPoseCycle?.LabelCap; } protected override void FindRandomPawn() { base.FindRandomPawn(); BodyAnimDef anim = this.CompAnim.BodyAnim; if (anim != null && anim.poseCycles.Any()) { EditorPoseCycle = anim.poseCycles.FirstOrDefault(); } this.CompAnim.AnimatorPoseOpen = true; } #endregion Public Methods #region Private Methods private void DrawBodyStats(string label, ref float value, ref Rect sliderRect) { float left = -1.5f; float right = 1.5f; value = Widgets.HorizontalSlider( sliderRect, value, left, right, false, label + ": " + value, left.ToString(), right.ToString(), 0.025f); sliderRect.y += sliderRect.height + 8f; } #endregion Private Methods } }
43.049587
124
0.416299
[ "MIT" ]
CaptainMuscles/RW_FacialStuff
Source/RW_FacialStuff/AnimatorWindows/MainTabWindow_PoseAnimator.cs
20,838
C#
using Microsoft.AspNetCore.Hosting; using Microsoft.Extensions.Hosting; using Microsoft.Extensions.Logging; using NLog; using NLog.Extensions.Hosting; using NLog.Extensions.Logging; namespace Chatterbox.Server.DependencyInjection { internal static class HostBuilderExtensions { /// <summary> /// Gets the name of the configuration section for logging. /// </summary> private const string LoggingSectionName = "Logging"; /// <summary> /// Gets the name of the configuration section for NLog. /// </summary> private const string NLogSectionName = LoggingSectionName + ":NLog"; /// <summary> /// Configures all the services of the application on the given <see cref="IHostBuilder"/>. /// </summary> /// <param name="hostBuilder">This <see cref="IHostBuilder"/> will obtain the various service registrations of the application.</param> /// <returns>Returns the given <paramref name="hostBuilder"/> again.</returns> internal static IHostBuilder ConfigureServer(this IHostBuilder hostBuilder) { return hostBuilder .UseNLog() .ConfigureWebHostDefaults(webBuilder => webBuilder.UseStartup<Startup>()) .ConfigureLogging((context, builder) => { builder.AddConfiguration(context.Configuration.GetSection(LoggingSectionName)); LogManager.Configuration = new NLogLoggingConfiguration(context.Configuration.GetSection(NLogSectionName)); }); } } }
40.225
143
0.650093
[ "MIT" ]
doklem/chatterbox
Chatterbox.Server/DependencyInjection/HostBuilderExtensions.cs
1,611
C#
using System.IO; using System.Runtime.Serialization; using GameEstate.Formats.Red.CR2W.Reflection; using FastMember; using static GameEstate.Formats.Red.Records.Enums; namespace GameEstate.Formats.Red.Types { [DataContract(Namespace = "")] [REDMeta] public class CAIQuestNPCReactionsTree : CAINpcReactionsTree { public CAIQuestNPCReactionsTree(CR2WFile cr2w, CVariable parent, string name) : base(cr2w, parent, name){ } public static new CVariable Create(CR2WFile cr2w, CVariable parent, string name) => new CAIQuestNPCReactionsTree(cr2w, parent, name); public override void Read(BinaryReader file, uint size) => base.Read(file, size); public override void Write(BinaryWriter file) => base.Write(file); } }
32.478261
136
0.75502
[ "MIT" ]
smorey2/GameEstate
src/GameEstate.Formats.Red/Formats/Red/W3/RTTIConvert/CAIQuestNPCReactionsTree.cs
747
C#
namespace ErtisAuth.Infrastructure.Configuration { public interface IIp2LocationOptions { #region Properties string LicenseKey { get; set; } string Package { get; set; } #endregion } public class Ip2LocationOptions : IIp2LocationOptions { #region Properties public string LicenseKey { get; set; } public string Package { get; set; } #endregion } }
16.041667
54
0.703896
[ "MIT" ]
ertugrulozcan/ErtisAuth
ErtisAuth.Infrastructure/Configuration/IIp2LocationOptions.cs
385
C#
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Net.Http; using System.Net.Test.Common; using System.Security.Cryptography.X509Certificates; using System.Security.Authentication; using System.Threading.Tasks; using Xunit; namespace System.Net.Security.Tests { using Configuration = System.Net.Test.Common.Configuration; public abstract class SslStreamSystemDefaultTest { protected readonly SslStream _clientStream; protected readonly SslStream _serverStream; public SslStreamSystemDefaultTest() { var network = new VirtualNetwork(); var clientNet = new VirtualNetworkStream(network, isServer:false); var serverNet = new VirtualNetworkStream(network, isServer: true); _clientStream = new SslStream(clientNet, false, ClientCertCallback); _serverStream = new SslStream(serverNet, false, ServerCertCallback); } public static bool IsNotWindows7 => !PlatformDetection.IsWindows7; protected abstract Task AuthenticateClientAsync(string targetHost, X509CertificateCollection clientCertificates, bool checkCertificateRevocation, SslProtocols? protocols = null); protected abstract Task AuthenticateServerAsync(X509Certificate serverCertificate, bool clientCertificateRequired, bool checkCertificateRevocation, SslProtocols? protocols = null); [ConditionalTheory(nameof(IsNotWindows7))] [InlineData(null, null)] [InlineData(SslProtocols.None, null)] [InlineData(null, SslProtocols.None)] [InlineData(SslProtocols.None, SslProtocols.None)] [InlineData(NegotiatedCipherSuiteTest.NonTls13Protocols, SslProtocols.Tls11)] [InlineData(SslProtocols.Tls11, NegotiatedCipherSuiteTest.NonTls13Protocols)] [InlineData(null, SslProtocols.Tls12)] [InlineData(SslProtocols.Tls12, null)] [InlineData(SslProtocols.Tls | SslProtocols.Tls11 | SslProtocols.Tls12, null)] [InlineData(null, SslProtocols.Tls | SslProtocols.Tls11 | SslProtocols.Tls12)] #pragma warning disable 0618 [InlineData(SslProtocols.Default, NegotiatedCipherSuiteTest.NonTls13Protocols)] [InlineData(NegotiatedCipherSuiteTest.NonTls13Protocols, SslProtocols.Default)] #pragma warning restore 0618 public async Task ClientAndServer_OneOrBothUseDefault_Ok(SslProtocols? clientProtocols, SslProtocols? serverProtocols) { using (X509Certificate2 serverCertificate = Configuration.Certificates.GetServerCertificate()) using (X509Certificate2 clientCertificate = Configuration.Certificates.GetClientCertificate()) { string serverHost = serverCertificate.GetNameInfo(X509NameType.SimpleName, false); var clientCertificates = new X509CertificateCollection() { clientCertificate }; await TestConfiguration.WhenAllOrAnyFailedWithTimeout( AuthenticateClientAsync(serverHost, clientCertificates, checkCertificateRevocation: false, protocols: clientProtocols), AuthenticateServerAsync(serverCertificate, clientCertificateRequired: true, checkCertificateRevocation: false, protocols: serverProtocols)); if (PlatformDetection.IsWindows && PlatformDetection.WindowsVersion >= 10 && #pragma warning disable 0618 clientProtocols.GetValueOrDefault() != SslProtocols.Default && serverProtocols.GetValueOrDefault() != SslProtocols.Default) #pragma warning restore 0618 { Assert.True( (_clientStream.SslProtocol == SslProtocols.Tls11 && _clientStream.HashAlgorithm == HashAlgorithmType.Sha1) || _clientStream.HashAlgorithm == HashAlgorithmType.Sha256 || _clientStream.HashAlgorithm == HashAlgorithmType.Sha384 || _clientStream.HashAlgorithm == HashAlgorithmType.Sha512, _clientStream.SslProtocol + " " + _clientStream.HashAlgorithm); } } } [ConditionalTheory(nameof(IsNotWindows7))] #pragma warning disable 0618 [InlineData(null, SslProtocols.Ssl2)] [InlineData(SslProtocols.None, SslProtocols.Ssl2)] [InlineData(SslProtocols.Ssl2, null)] [InlineData(SslProtocols.Ssl2, SslProtocols.None)] #pragma warning restore 0618 public async Task ClientAndServer_OneUsesDefault_OtherUsesLowerProtocol_Fails( SslProtocols? clientProtocols, SslProtocols? serverProtocols) { using (X509Certificate2 serverCertificate = Configuration.Certificates.GetServerCertificate()) using (X509Certificate2 clientCertificate = Configuration.Certificates.GetClientCertificate()) { string serverHost = serverCertificate.GetNameInfo(X509NameType.SimpleName, false); var clientCertificates = new X509CertificateCollection() { clientCertificate }; await Assert.ThrowsAnyAsync<Exception>(() => TestConfiguration.WhenAllOrAnyFailedWithTimeout( AuthenticateClientAsync(serverHost, clientCertificates, checkCertificateRevocation: false, protocols: clientProtocols), AuthenticateServerAsync(serverCertificate, clientCertificateRequired: true, checkCertificateRevocation: false, protocols: serverProtocols))); } } private bool ClientCertCallback(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors) { switch (sslPolicyErrors) { case SslPolicyErrors.None: case SslPolicyErrors.RemoteCertificateChainErrors: case SslPolicyErrors.RemoteCertificateNameMismatch: return true; case SslPolicyErrors.RemoteCertificateNotAvailable: default: return false; } } private bool ServerCertCallback(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors) { switch (sslPolicyErrors) { case SslPolicyErrors.None: case SslPolicyErrors.RemoteCertificateChainErrors: case SslPolicyErrors.RemoteCertificateNameMismatch: return true; case SslPolicyErrors.RemoteCertificateNotAvailable: // https://technet.microsoft.com/en-us/library/hh831771.aspx#BKMK_Changes2012R2 // Starting with Windows 8, the "Management of trusted issuers for client authentication" has changed: // The behavior to send the Trusted Issuers List by default is off. // // In Windows 7 the Trusted Issuers List is sent within the Server Hello TLS record. This list is built // by the server using certificates from the Trusted Root Authorities certificate store. // The client side will use the Trusted Issuers List, if not empty, to filter proposed certificates. return PlatformDetection.IsWindows7 && !Capability.IsTrustedRootCertificateInstalled(); default: return false; } } public void Dispose() { _clientStream?.Dispose(); _serverStream?.Dispose(); } } public sealed class SyncSslStreamSystemDefaultTest : SslStreamSystemDefaultTest { protected override Task AuthenticateClientAsync(string targetHost, X509CertificateCollection clientCertificates, bool checkCertificateRevocation, SslProtocols? protocols) => Task.Run(() => { if (protocols.HasValue) { _clientStream.AuthenticateAsClient(targetHost, clientCertificates, protocols.Value, checkCertificateRevocation); } else { _clientStream.AuthenticateAsClient(targetHost, clientCertificates, checkCertificateRevocation); } }); protected override Task AuthenticateServerAsync(X509Certificate serverCertificate, bool clientCertificateRequired, bool checkCertificateRevocation, SslProtocols? protocols) => Task.Run(() => { if (protocols.HasValue) { _serverStream.AuthenticateAsServer(serverCertificate, clientCertificateRequired, protocols.Value, checkCertificateRevocation); } else { _serverStream.AuthenticateAsServer(serverCertificate, clientCertificateRequired, checkCertificateRevocation); } }); } public sealed class ApmSslStreamSystemDefaultTest : SslStreamSystemDefaultTest { protected override Task AuthenticateClientAsync(string targetHost, X509CertificateCollection clientCertificates, bool checkCertificateRevocation, SslProtocols? protocols) => Task.Factory.FromAsync( (callback, state) => protocols.HasValue ? _clientStream.BeginAuthenticateAsClient(targetHost, clientCertificates, protocols.Value, checkCertificateRevocation, callback, state) : _clientStream.BeginAuthenticateAsClient(targetHost, clientCertificates, checkCertificateRevocation, callback, state), _clientStream.EndAuthenticateAsClient, state: null); protected override Task AuthenticateServerAsync(X509Certificate serverCertificate, bool clientCertificateRequired, bool checkCertificateRevocation, SslProtocols? protocols) => Task.Factory.FromAsync( (callback, state) => protocols.HasValue ? _serverStream.BeginAuthenticateAsServer(serverCertificate, clientCertificateRequired, protocols.Value, checkCertificateRevocation, callback, state) : _serverStream.BeginAuthenticateAsServer(serverCertificate, clientCertificateRequired, checkCertificateRevocation, callback, state), _serverStream.EndAuthenticateAsServer, state: null); } public sealed class AsyncSslStreamSystemDefaultTest : SslStreamSystemDefaultTest { protected override Task AuthenticateClientAsync(string targetHost, X509CertificateCollection clientCertificates, bool checkCertificateRevocation, SslProtocols? protocols) => protocols.HasValue ? _clientStream.AuthenticateAsClientAsync(targetHost, clientCertificates, protocols.Value, checkCertificateRevocation) : _clientStream.AuthenticateAsClientAsync(targetHost, clientCertificates, checkCertificateRevocation); protected override Task AuthenticateServerAsync(X509Certificate serverCertificate, bool clientCertificateRequired, bool checkCertificateRevocation, SslProtocols? protocols) => protocols.HasValue ? _serverStream.AuthenticateAsServerAsync(serverCertificate, clientCertificateRequired, protocols.Value, checkCertificateRevocation) : _serverStream.AuthenticateAsServerAsync(serverCertificate, clientCertificateRequired, checkCertificateRevocation); } }
56.190244
188
0.691466
[ "MIT" ]
1shekhar/runtime
src/libraries/System.Net.Security/tests/FunctionalTests/SslStreamSystemDefaultsTest.cs
11,521
C#
#region File Description //----------------------------------------------------------------------------- // Map.cs // // Microsoft XNA Community Game Platform // Copyright (C) Microsoft Corporation. All rights reserved. //----------------------------------------------------------------------------- #endregion #region Using Statements using System; using System.Collections.Generic; using System.Text; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Graphics; using Microsoft.Xna.Framework.Content; using PathfindingData; #endregion namespace Pathfinding { #region Map Tile Type Enum public enum MapTileType { MapEmpty, MapBarrier, MapStart, MapExit } #endregion public class Map { #region Fields // Draw data private Texture2D tileTexture; private Vector2 tileSquareCenter; private Texture2D dotTexture; private Vector2 dotTextureCenter; private Texture2D barrierTexture; private Color tileColor1 = Color.Navy; private Color tileColor2 = Color.LightBlue; private Color startColor = Color.Green; private Color exitColor = Color.Red; // Map data private List<MapData> maps; private MapTileType[,] mapTiles; private int currentMap; private int numberColumns; private int numberRows; #endregion #region Properties /// <summary> /// The height/width of a tile square /// </summary> public float TileSize { get { return tileSize; } } private float tileSize; /// <summary> /// The Draw scale as a % of TileSize /// </summary> public float Scale { get { return scale; } } private float scale; /// <summary> /// Start positon on the Map /// </summary> public Point StartTile { get { return startTile; } } private Point startTile; /// <summary> /// End position in the Map /// </summary> public Point EndTile { get { return endTile; } } private Point endTile; /// <summary> /// Set: reload Map data, Get: has the Map data changed /// </summary> public bool MapReload { get { return mapReload; } set { mapReload = value; } } private bool mapReload; #endregion #region Initialization /// <summary> /// Load Draw textures and Map data /// </summary> public void LoadContent(ContentManager content) { tileTexture = content.Load<Texture2D>("whiteTile"); barrierTexture = content.Load<Texture2D>("barrier"); dotTexture = content.Load<Texture2D>("dot"); dotTextureCenter = new Vector2(dotTexture.Width / 2, dotTexture.Height / 2); maps = new List<MapData>(); maps.Add(content.Load<MapData>("map1")); maps.Add(content.Load<MapData>("map2")); maps.Add(content.Load<MapData>("map3")); maps.Add(content.Load<MapData>("map4")); ReloadMap(); mapReload = true; } #endregion #region Draw /// <summary> /// Draw the map and all it's elements /// </summary> public void Draw(SpriteBatch spriteBatch) { spriteBatch.Begin(); // These two loops go through each tile in the map, starting at the upper // left and going to the upper right, then repeating for the next row of // tiles until the end for (int i = 0; i < numberRows; i++) { for (int j = 0; j < numberColumns; j++) { // Get the screen coordinates of the tile Vector2 tilePosition = MapToWorld(j, i, false); // Alternate between the 2 tile colors to create a checker pattern Color currentColor = (i+j)%2==1?tileColor1:tileColor2; // Draw the tile spriteBatch.Draw(tileTexture, tilePosition,null,currentColor,0f, Vector2.Zero,scale,SpriteEffects.None,0f); // If the current tile is a type with a special draw element, the //start location, the end location or a barrier, then draw that. switch (mapTiles[j, i]) { case MapTileType.MapBarrier: spriteBatch.Draw( barrierTexture, tilePosition, null, Color.White, 0f, Vector2.Zero, scale, SpriteEffects.None, .25f); break; case MapTileType.MapStart: spriteBatch.Draw( dotTexture, tilePosition + tileSquareCenter, null, startColor, 0f, dotTextureCenter, scale, SpriteEffects.None, .25f); break; case MapTileType.MapExit: spriteBatch.Draw( dotTexture, tilePosition + tileSquareCenter, null, exitColor, 0f, dotTextureCenter, scale, SpriteEffects.None, .25f); break; default: break; } } } spriteBatch.End(); } #endregion #region Methods /// <summary> /// Translates a map tile location into a screen position /// </summary> /// <param name="column">column position(x)</param> /// <param name="row">row position(y)</param> /// <param name="centered">true: return the location of the center of the tile /// false: return the position of the upper-left corner of the tile</param> /// <returns>screen position</returns> public Vector2 MapToWorld(int column, int row, bool centered) { Vector2 screenPosition = new Vector2(); if (InMap(column, row)) { screenPosition.X = column * tileSize; screenPosition.Y = row * tileSize; if (centered) { screenPosition += tileSquareCenter; } } else { screenPosition = Vector2.Zero; } return screenPosition; } /// <summary> /// Translates a map tile location into a screen position /// </summary> /// <param name="location">map location</param> /// <param name="centered">true: return the location of the center of the tile /// false: return the position of the upper-left corner of the tile</param> /// <returns>screen position</returns> public Vector2 MapToWorld(Point location, bool centered) { Vector2 screenPosition = new Vector2(); if (InMap(location.X, location.Y)) { screenPosition.X = location.X * tileSize; screenPosition.Y = location.Y * tileSize; if (centered) { screenPosition += tileSquareCenter; } } else { screenPosition = Vector2.Zero; } return screenPosition; } /// <summary> /// Returns true if the given map location exists /// </summary> /// <param name="column">column position(x)</param> /// <param name="row">row position(y)</param> private bool InMap(int column, int row) { return (row >= 0 && row < numberRows && column >= 0 && column < numberColumns); } /// <summary> /// Returns true if the given map location exists and is not /// blocked by a barrier /// </summary> /// <param name="column">column position(x)</param> /// <param name="row">row position(y)</param> private bool IsOpen(int column, int row) { return InMap(column, row) && mapTiles[column, row] != MapTileType.MapBarrier; } /// <summary> /// Enumerate all the map locations that can be entered from the given /// map location /// </summary> public IEnumerable<Point> OpenMapTiles(Point mapLoc) { if (IsOpen(mapLoc.X, mapLoc.Y + 1)) yield return new Point(mapLoc.X, mapLoc.Y + 1); if (IsOpen(mapLoc.X, mapLoc.Y - 1)) yield return new Point(mapLoc.X, mapLoc.Y - 1); if (IsOpen(mapLoc.X + 1, mapLoc.Y)) yield return new Point(mapLoc.X + 1, mapLoc.Y); if (IsOpen(mapLoc.X - 1, mapLoc.Y)) yield return new Point(mapLoc.X - 1, mapLoc.Y); } /// <summary> /// Create a viewport for the Map based on the passed in viewport and the /// size of the map, scales the graphics to fit. /// </summary> /// <param name="viewport">Screen viewport</param> /// <returns>Map viewport</returns> public void UpdateMapViewport(Rectangle safeViewableArea) { // This finds the largest sized tiles we can draw while still keeping // everything in the given viewable area tileSize = Math.Min(safeViewableArea.Height / (float)numberRows, safeViewableArea.Width / (float)numberColumns); scale = tileSize / (float)tileTexture.Height; tileSquareCenter = new Vector2(tileSize / 2); } /// <summary> /// Finds the minimum number of tiles it takes to move from Point A to /// Point B if there are no barriers in the way /// </summary> /// <param name="pointA">Start position</param> /// <param name="pointB">End position</param> /// <returns>Distance in tiles</returns> public static int StepDistance(Point pointA, Point pointB) { int distanceX = Math.Abs(pointA.X - pointB.X); int distanceY = Math.Abs(pointA.Y - pointB.Y); return distanceX + distanceY; } /// <summary> /// Finds the minimum number of tiles it takes to move from the current /// position to the end location on the Map if there are no barriers in /// the way /// </summary> /// <param name="point">Current position</param> /// <returns>Distance to end in tiles</returns> public int StepDistanceToEnd(Point point) { return StepDistance(point, endTile); } /// <summary> /// Load the next map /// </summary> public void CycleMap() { currentMap = (currentMap + 1) % maps.Count; mapReload = true; } /// <summary> /// Reload map data /// </summary> public void ReloadMap() { // Set the map height and width numberColumns = maps[currentMap].NumberColumns; numberRows = maps[currentMap].NumberRows; // Recreate the tile array mapTiles = new MapTileType[maps[currentMap].NumberColumns, maps[currentMap].NumberRows]; // Set the start startTile = maps[currentMap].Start; mapTiles[startTile.X, startTile.Y] = MapTileType.MapStart; // Set the end endTile = maps[currentMap].End; mapTiles[endTile.X, endTile.Y] = MapTileType.MapExit; int x = 0; int y = 0; // Set the barriers for (int i = 0; i < maps[currentMap].Barriers.Count; i++) { x = maps[currentMap].Barriers[i].X; y = maps[currentMap].Barriers[i].Y; mapTiles[x, y] = MapTileType.MapBarrier; } mapReload = false; } #endregion } }
33.416
100
0.509776
[ "MIT" ]
SimonDarksideJ/XNAGameStudio
Samples/Pathfinding_4_0/Pathfinding/Pathfinding/Map.cs
12,531
C#
using System; using Xamarin.Forms; using Xamarin.Forms.Xaml; namespace SkiaSharpFormsDemos { [XamlCompilation(XamlCompilationOptions.Compile)] public partial class HomePage : HomeBasePage { public HomePage() { InitializeComponent(); } } }
18.3125
53
0.65529
[ "Apache-2.0" ]
sfmoloney/mobile-octo-train
SkiaSharpForms/SkiaSharpFormsDemos/SkiaSharpFormsDemos/SkiaSharpFormsDemos/HomePage.xaml.cs
295
C#
using Antlr4.Runtime.Tree; using MCSharp.Linkage; using MCSharp.Linkage.Minecraft; using System; using System.Collections.Generic; namespace MCSharp.Compilation.Instancing; /// <summary> /// Represents an instance of some type. /// </summary> public interface IInstance { /// <summary> /// The <see cref="IType"/> that defines this instance. /// </summary> public IType Type { get; } /// <summary> /// The local identifier for this instance. /// </summary> public string Identifier { get; } /// <summary> /// <see cref="Exception"/> thrown when <see cref="Type"/> is assigned an invalid value. /// </summary> public class InvalidTypeException : Exception { public InvalidTypeException(IType given, string expected) : base($"Cannot assign '{given.Identifier}' to {nameof(Type)} when '{expected}' was expected.") { } } protected static Exception GenerateInvalidBlockRangeException(int length, int expected) => new InvalidOperationException($"The given range of length {length} does not match the expected range of length {expected}."); /// <summary> /// Assigns the value of this <see cref="IInstance"/> into a new <see cref="IInstance"/>. /// If possible, not of the <see cref="IConstantInstance"/> interface. /// </summary> /// <param name="compile"></param> /// <param name="identifier">The <see cref="Identifier"/> of the new <see cref="IInstance"/>.</param> /// <returns>Returns a new <see cref="IInstance"/>.</returns> public IInstance Copy(Compiler.CompileArguments compile, string identifier); /// <inheritdoc cref="IInstanceExtensions.SaveToBlock(IInstance, Compiler.CompileArguments, string, Objective[])"/> /// <param name="range"></param> /// <seealso cref="IInstanceExtensions.SaveToBlock(IInstance, Compiler.CompileArguments, string, Objective[])"/> public void SaveToBlock(Compiler.CompileArguments location, string selector, Objective[] block, Range range); /// <inheritdoc cref="IInstanceExtensions.LoadFromBlock(IInstance, Compiler.CompileArguments, string, Objective[])"/> /// <param name="range"></param> /// <seealso cref="IInstanceExtensions.LoadFromBlock(IInstance, Compiler.CompileArguments, string, Objective[])"/> public void LoadFromBlock(Compiler.CompileArguments location, string selector, Objective[] block, Range range); } public static class IInstanceExtensions { public static ResultInfo ConvertType(this IInstance instance, Compiler.CompileArguments location, IType toType, out IInstance value) { IType fromType = instance.Type; IDictionary<IType, IConversion> conversions = fromType.Conversions; if(conversions.ContainsKey(toType)) { var conversion = conversions[toType]; ResultInfo conversionResult = conversion.Function.InvokeStatic(location, Array.Empty<IType>(), new IInstance[] { instance }, out value); if(conversionResult.Failure) { value = null; return conversionResult; } return ResultInfo.DefaultSuccess; } else { value = null; return new ResultInfo(false, $"Cannot cast '{fromType.Identifier}' as '{toType.Identifier}'."); } } /// <summary> /// Saves this <see cref="IInstance"/> to the given set of <see cref="Objective"/>s. /// </summary> /// <param name="instance">The <see cref="IInstance"/> to save.</param> /// <param name="location"></param> /// <param name="selector"></param> /// <exception cref="InvalidOperationException">Thrown when the relevant length of <paramref name="block"/> does not match <see cref="ITypeExtensions.GetBlockSize(IType, Compiler)"/>.</exception> /// <seealso cref="IInstance.SaveToBlock(Compiler.CompileArguments, string, Objective[], Range)"/> /// <param name="block">The array of <see cref="Objective"/>s to save to.</param> public static void SaveToBlock(this IInstance instance, Compiler.CompileArguments location, string selector, Objective[] block) { instance.SaveToBlock(location, selector, block, 0..^0); } /// <summary> /// Loads a value for this <see cref="IInstance"/> from the given set of <see cref="Objective"/>s. /// </summary> /// <param name="instance">The <see cref="IInstance"/> to load.</param> /// <param name="location"></param> /// <param name="selector"></param> /// <exception cref="InvalidOperationException">Thrown when the relevant length of <paramref name="block"/> does not match <see cref="ITypeExtensions.GetBlockSize(IType, Compiler)"/>.</exception> /// <seealso cref="IInstance.SaveToBlock(Compiler.CompileArguments, string, Objective[], Range)"/> /// <param name="block">The array of <see cref="Objective"/>s to load from.</param> public static void LoadFromBlock(this IInstance instance, Compiler.CompileArguments location, string selector, Objective[] block) { instance.LoadFromBlock(location, selector, block, 0..^0); } public static ResultInfo InvokeBestMethod( this IInstance instance, Compiler.CompileArguments location, ITerminalNode identifier, GenericArgumentsContext generic_arguments, MethodArgumentsContext method_arguments, out IInstance value ) { // Find the best method. ResultInfo searchResult = instance.Type.FindBestMethodFromContext(location, identifier, generic_arguments, method_arguments, out IMember member, out IType[] genericTypes, out _, out IInstance[] argumentInstances); if(searchResult.Failure) { value = null; return searchResult; } IMethod method = member.Definition as IMethod; // Invoke method. ResultInfo result = method.Invoker.InvokeNonStatic(location, instance, genericTypes, argumentInstances, out value); if(result.Failure) return location.GetLocation(identifier) + result; return ResultInfo.DefaultSuccess; } public static ResultInfo InvokePropertyOrFieldFromContext(this IInstance instance, Compiler.CompileArguments location, ITerminalNode identifier, IMember propertyOrField, out IInstance value) { #region Argument Checks if(instance is null) throw new ArgumentNullException(nameof(instance)); if(identifier is null) throw new ArgumentNullException(nameof(identifier)); if(propertyOrField is null) throw new ArgumentNullException(nameof(propertyOrField)); #endregion IMemberDefinition definition = propertyOrField.Definition; if(definition is IProperty property) { // Get getter. var getter = property.Getter; if(getter == null) { value = null; return new ResultInfo(false, location.GetLocation(identifier) + "This property is not get-able."); } // Invoke 'get' method. ResultInfo result = property.Getter.InvokeNonStatic(location, instance, Array.Empty<IType>(), Array.Empty<IInstance>(), out value); if(result.Failure) return location.GetLocation(identifier) + result; // Return success. return ResultInfo.DefaultSuccess; } else if(definition is IField field) { // Struct, Class, and Predefined all have different ways of storing fields. switch(instance) { // Get IInstance value from struct field dictionary. case StructInstance structInstance: { value = structInstance.FieldInstances[field]; return ResultInfo.DefaultSuccess; } // Create IInstance value from object reference. // Simple objects do not have fields so we can assume it is a class type. case ClassInstance classInstance: { value = location.Compiler.DefinedTypes[propertyOrField.TypeIdentifier].InitializeInstance(location, null); Objective[] block = classInstance.FieldObjectives[field]; string selector = classInstance.GetSelector(location); value.LoadFromBlock(location, selector, block); return ResultInfo.DefaultSuccess; } // PrimitiveInstance case PrimitiveInstance primitiveInstance: { value = null; return new ResultInfo(false, $"{location.GetLocation(identifier)}Accessing fields of primitive types is not supported."); } default: throw new Exception($"Unsupported type of {nameof(IInstance)}: '{instance.GetType().FullName}'."); } } else { throw new InvalidOperationException($"{definition.GetType().Name} is not a property or field."); } } }
40.301508
196
0.735162
[ "MIT" ]
GrantShotwell/MCSharp
Compilation/Instancing/IInstance.cs
8,022
C#
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; using System.Collections.Generic; using System.Diagnostics.ContractsLight; using System.IO; using System.Threading; using System.Threading.Tasks; using BuildXL.Native.IO; using BuildXL.Tracing; using BuildXL.Utilities; using BuildXL.Utilities.Instrumentation.Common; namespace BuildXL.Engine { /// <summary> /// Cleans build outputs independently of executing pips /// </summary> public static class OutputCleaner { private const string Category = "OutputCleaner"; /// <summary> /// Cleans output files and directories. /// </summary> public static bool DeleteOutputs( LoggingContext loggingContext, Func<DirectoryArtifact, bool> isOutputDir, IList<FileOrDirectoryArtifact> filesOrDirectoriesToDelete, PathTable pathTable, ITempDirectoryCleaner tempDirectoryCleaner = null) { int fileFailCount = 0; int fileSuccessCount = 0; int directoryFailCount = 0; int directorySuccessCount = 0; using (PerformanceMeasurement.Start( loggingContext, Category, Tracing.Logger.Log.CleaningStarted, localLoggingContext => { Tracing.Logger.Log.CleaningFinished(loggingContext, fileSuccessCount, fileFailCount); LoggingHelpers.LogCategorizedStatistic(loggingContext, Category, "FilesDeleted", fileSuccessCount); LoggingHelpers.LogCategorizedStatistic(loggingContext, Category, "FilesFailed", fileFailCount); LoggingHelpers.LogCategorizedStatistic(loggingContext, Category, "DirectoriesDeleted", directorySuccessCount); LoggingHelpers.LogCategorizedStatistic(loggingContext, Category, "DirectoriesFailed", directoryFailCount); })) { // Note: filesOrDirectoriesToDelete better be an IList<...> in order to get good Parallel.ForEach performance Parallel.ForEach( filesOrDirectoriesToDelete, fileOrDirectory => { string path = fileOrDirectory.Path.ToString(pathTable); Tracing.Logger.Log.CleaningOutputFile(loggingContext, path); try { if (fileOrDirectory.IsFile) { Contract.Assume(fileOrDirectory.FileArtifact.IsOutputFile, "Encountered non-output file"); if (FileUtilities.FileExistsNoFollow(path)) { FileUtilities.DeleteFile(path, waitUntilDeletionFinished: true, tempDirectoryCleaner: tempDirectoryCleaner); Interlocked.Increment(ref fileSuccessCount); } } else { if (FileUtilities.DirectoryExistsNoFollow(path)) { // TODO:1011977 this is a hacky fix for a bug where we delete SourceSealDirectories in /cleanonly mode // The bug stems from the fact that FilterOutputs() returns SourceSealDirectories, which aren't inputs. // Once properly addressed, this check should remain in here as a safety precaution and turn into // a Contract.Assume() like the check above if (isOutputDir(fileOrDirectory.DirectoryArtifact)) { FileUtilities.DeleteDirectoryContents(path, deleteRootDirectory: false, tempDirectoryCleaner: tempDirectoryCleaner); Interlocked.Increment(ref directorySuccessCount); } } } } catch (BuildXLException ex) { if (fileOrDirectory.IsFile) { Interlocked.Increment(ref fileFailCount); Tracing.Logger.Log.CleaningFileFailed(loggingContext, path, ex.LogEventMessage); } else { Interlocked.Increment(ref directoryFailCount); Tracing.Logger.Log.CleaningDirectoryFailed(loggingContext, path, ex.LogEventMessage); } } }); } return fileFailCount + directoryFailCount == 0; } } }
49.242991
157
0.516607
[ "MIT" ]
MatisseHack/BuildXL
Public/Src/Engine/Dll/OutputCleaner.cs
5,269
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/mfapi.h in the Windows SDK for Windows 10.0.19041.0 // Original source is Copyright © Microsoft. All rights reserved. using NUnit.Framework; using System.Runtime.InteropServices; namespace TerraFX.Interop.UnitTests { /// <summary>Provides validation of the <see cref="FaceRectInfoBlobHeader" /> struct.</summary> public static unsafe class FaceRectInfoBlobHeaderTests { /// <summary>Validates that the <see cref="FaceRectInfoBlobHeader" /> struct is blittable.</summary> [Test] public static void IsBlittableTest() { Assert.That(Marshal.SizeOf<FaceRectInfoBlobHeader>(), Is.EqualTo(sizeof(FaceRectInfoBlobHeader))); } /// <summary>Validates that the <see cref="FaceRectInfoBlobHeader" /> struct has the right <see cref="LayoutKind" />.</summary> [Test] public static void IsLayoutSequentialTest() { Assert.That(typeof(FaceRectInfoBlobHeader).IsLayoutSequential, Is.True); } /// <summary>Validates that the <see cref="FaceRectInfoBlobHeader" /> struct has the correct size.</summary> [Test] public static void SizeOfTest() { Assert.That(sizeof(FaceRectInfoBlobHeader), Is.EqualTo(8)); } } }
39.75
145
0.680643
[ "MIT" ]
Ethereal77/terrafx.interop.windows
tests/Interop/Windows/um/mfapi/FaceRectInfoBlobHeaderTests.cs
1,433
C#
namespace GrobExp.Mutators.MultiLanguages { public abstract class MultiLanguageTextBaseWithPath : MultiLanguageTextBase { public MultiLanguagePathText Path { get; set; } public object Value { get { return value; } set { if (!valueInitialized) { valueInitialized = true; this.value = value; } } } private object value; private bool valueInitialized; } }
23.956522
79
0.499093
[ "MIT" ]
RGleb/GrobExp.Mutators
Mutators/MultiLanguages/MultiLanguageTextBaseWithPath.cs
553
C#
using System.Collections; using System.Collections.Generic; using UnityEngine; public class FanScript : MonoBehaviour { [SerializeField] public bool _powered = false; private void Start() { if (_powered) GetComponent<Animator>().SetTrigger("power"); } public void StartFan() { GetComponent<Animator>().SetTrigger("power"); _powered = true; } }
20
67
0.6575
[ "MIT" ]
metalac190/GhostHouse
Assets/_Game/Environments/GlobalProps/Living Room/Fan/FanScript.cs
402
C#
// Copyright (c) Matt Lacey Ltd. All rights reserved. // Licensed under the MIT license. using RapidXamlToolkit.Resources; namespace RapidXamlToolkit.XamlAnalysis.Tags { public class CheckBoxCheckedAndUncheckedEventsTag : RapidXamlDisplayedTag { // https://docs.microsoft.com/en-us/windows/uwp/design/controls-and-patterns/checkbox#handle-click-and-checked-events public CheckBoxCheckedAndUncheckedEventsTag(TagDependencies tagDeps, string existingName, bool hasChecked) : base(tagDeps, "RXT401", TagErrorType.Warning) { this.ToolTip = StringRes.UI_XamlAnalysisCheckBoxCheckedAndUncheckedEventsToolTip; this.Description = StringRes.UI_XamlAnalysisCheckBoxCheckedAndUncheckedEventsDescription; this.ExtendedMessage = StringRes.UI_XamlAnalysisCheckBoxCheckedAndUncheckedEventsExtendedMessage; this.ExistingIsChecked = hasChecked; this.ExistingName = existingName; } public int InsertPosition { get; set; } public bool ExistingIsChecked { get; set; } public string ExistingName { get; set; } } }
39.310345
125
0.728947
[ "MIT" ]
DhiaaAlshamy/Rapid-XAML-Toolkit
VSIX/RapidXaml.Analysis/XamlAnalysis/Tags/CheckBoxCheckedAndUncheckedEventsTag.cs
1,142
C#
using UniGLTF; using UnityEngine; using VRMShaders; namespace UniVRM10 { public sealed class Vrm10UrpMaterialDescriptorGenerator : IMaterialDescriptorGenerator { public MaterialDescriptor Get(GltfData data, int i) { // unlit if (!GltfUnlitMaterialImporter.TryCreateParam(data, i, out MaterialDescriptor matDesc)) { // pbr if (!GltfPbrUrpMaterialImporter.TryCreateParam(data, i, out matDesc)) { // fallback Debug.LogWarning($"material: {i} out of range. fallback"); return new MaterialDescriptor(GltfMaterialDescriptorGenerator.GetMaterialName(i, null), GltfPbrMaterialImporter.ShaderName); } } return matDesc; } } }
31.074074
144
0.59118
[ "MIT" ]
StrawberryLovah/UniVRM
Assets/VRM10/Runtime/IO/Material/Vrm10UrpMaterialDescriptorGenerator.cs
841
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 backup-2018-11-15.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.Backup.Model; using Amazon.Runtime; using Amazon.Runtime.Internal; using Amazon.Runtime.Internal.Transform; using Amazon.Runtime.Internal.Util; using ThirdParty.Json.LitJson; namespace Amazon.Backup.Model.Internal.MarshallTransformations { /// <summary> /// CreateFramework Request Marshaller /// </summary> public class CreateFrameworkRequestMarshaller : IMarshaller<IRequest, CreateFrameworkRequest> , 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((CreateFrameworkRequest)input); } /// <summary> /// Marshaller the request object to the HTTP request. /// </summary> /// <param name="publicRequest"></param> /// <returns></returns> public IRequest Marshall(CreateFrameworkRequest publicRequest) { IRequest request = new DefaultRequest(publicRequest, "Amazon.Backup"); request.Headers["Content-Type"] = "application/json"; request.Headers[Amazon.Util.HeaderKeys.XAmzApiVersion] = "2018-11-15"; request.HttpMethod = "POST"; request.ResourcePath = "/audit/frameworks"; using (StringWriter stringWriter = new StringWriter(CultureInfo.InvariantCulture)) { JsonWriter writer = new JsonWriter(stringWriter); writer.WriteObjectStart(); var context = new JsonMarshallerContext(request, writer); if(publicRequest.IsSetFrameworkControls()) { context.Writer.WritePropertyName("FrameworkControls"); context.Writer.WriteArrayStart(); foreach(var publicRequestFrameworkControlsListValue in publicRequest.FrameworkControls) { context.Writer.WriteObjectStart(); var marshaller = FrameworkControlMarshaller.Instance; marshaller.Marshall(publicRequestFrameworkControlsListValue, context); context.Writer.WriteObjectEnd(); } context.Writer.WriteArrayEnd(); } if(publicRequest.IsSetFrameworkDescription()) { context.Writer.WritePropertyName("FrameworkDescription"); context.Writer.Write(publicRequest.FrameworkDescription); } if(publicRequest.IsSetFrameworkName()) { context.Writer.WritePropertyName("FrameworkName"); context.Writer.Write(publicRequest.FrameworkName); } if(publicRequest.IsSetFrameworkTags()) { context.Writer.WritePropertyName("FrameworkTags"); context.Writer.WriteObjectStart(); foreach (var publicRequestFrameworkTagsKvp in publicRequest.FrameworkTags) { context.Writer.WritePropertyName(publicRequestFrameworkTagsKvp.Key); var publicRequestFrameworkTagsValue = publicRequestFrameworkTagsKvp.Value; context.Writer.Write(publicRequestFrameworkTagsValue); } context.Writer.WriteObjectEnd(); } if(publicRequest.IsSetIdempotencyToken()) { context.Writer.WritePropertyName("IdempotencyToken"); context.Writer.Write(publicRequest.IdempotencyToken); } else if(!(publicRequest.IsSetIdempotencyToken())) { context.Writer.WritePropertyName("IdempotencyToken"); context.Writer.Write(Guid.NewGuid().ToString()); } writer.WriteObjectEnd(); string snippet = stringWriter.ToString(); request.Content = System.Text.Encoding.UTF8.GetBytes(snippet); } return request; } private static CreateFrameworkRequestMarshaller _instance = new CreateFrameworkRequestMarshaller(); internal static CreateFrameworkRequestMarshaller GetInstance() { return _instance; } /// <summary> /// Gets the singleton. /// </summary> public static CreateFrameworkRequestMarshaller Instance { get { return _instance; } } } }
38.236486
145
0.598869
[ "Apache-2.0" ]
Hazy87/aws-sdk-net
sdk/src/Services/Backup/Generated/Model/Internal/MarshallTransformations/CreateFrameworkRequestMarshaller.cs
5,659
C#
using Duality; using Duality.Components.Renderers; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace FlapOrDie.Components { public class Ticker : TextRenderer, ICmpUpdatable { private float speed; public float Speed { get { return this.speed; } set { this.speed = value; } } private List<string> strings; public List<string> Strings { get { return this.strings; } set { this.strings = value; } } private Vector2 delta; private int index; void ICmpUpdatable.OnUpdate() { delta.X = this.speed * Time.MsPFMult * Time.TimeMult / 1000; this.GameObj.Transform.MoveBy(-delta); if(this.GameObj.Transform.Pos.X + this.Text.TextMetrics.Size.X < -FlapOrDieCorePlugin.HalfWidth) { ShowNextString(); } } private void ShowNextString() { this.Text.SourceText = this.strings[index]; this.GameObj.Transform.RelativePos = new Vector3(FlapOrDieCorePlugin.HalfWidth + this.Text.TextMetrics.Size.X, 0, 0); index = (index + 1) % this.strings.Count; } } }
24.90566
129
0.581818
[ "MIT" ]
LukasPirkl/duality
Samples/FlapOrDie/Components/Ticker.cs
1,322
C#
using UnityEngine; using System.Collections; //To save space so we don't have to send millions of parameters to each method public struct TriangleData { //The corners of this triangle in global coordinates public Vector3 p1; public Vector3 p2; public Vector3 p3; //The center of the triangle public Vector3 center; //The distance to the surface from the center of the triangle public float distanceToSurface; //The normal to the triangle public Vector3 normal; //The area of the triangle public float area; //The velocity of the triangle at the center public Vector3 velocity; //The velocity normalized public Vector3 velocityDir; //The angle between the normal and the velocity //Negative if pointing in the opposite direction //Positive if pointing in the same direction public float cosTheta; public TriangleData(Vector3 p1, Vector3 p2, Vector3 p3, Rigidbody boatRB, float timeSinceStart) { this.p1 = p1; this.p2 = p2; this.p3 = p3; //Center of the triangle this.center = (p1 + p2 + p3) / 3f; //Distance to the surface from the center of the triangle this.distanceToSurface = Mathf.Abs(WaterController.current.DistanceToWater(this.center, timeSinceStart)); //Normal to the triangle this.normal = Vector3.Cross(p2 - p1, p3 - p1).normalized; //Area of the triangle this.area = BoatPhysicsMath.GetTriangleArea(p1, p2, p3); //Celocity vector of the triangle at the center this.velocity = BoatPhysicsMath.GetTriangleVelocity(boatRB, this.center); //Velocity direction this.velocityDir = this.velocity.normalized; //Angle between the normal and the velocity //Negative if pointing in the opposite direction //Positive if pointing in the same direction this.cosTheta = Vector3.Dot(this.velocityDir, this.normal); } }
29.058824
113
0.68168
[ "MIT" ]
Habrador/Unity-Boat-physics-Tutorial
Assets/Scripts/Boat/Physics/TriangleData.cs
1,976
C#
// ----------------------------------------------------------------------- // <copyright file="BloodBowlToolbar.cs" company="Secondnorth, Inc."> // All Rights Reserved. // </copyright> // ----------------------------------------------------------------------- namespace PBEM.BloodBowl { using System; using System.ComponentModel; using System.Windows.Forms; /// <summary> /// The Blood Bowl Toolbar class. /// </summary> public partial class BloodBowlToolbar : UserControl, IMenuItem { #region " Constructor " /// <summary> /// Initializes a new instance of the <see cref="BloodBowlToolbar"/> class. /// </summary> public BloodBowlToolbar() { this.InitializeComponent(); } #endregion #region " Public Event Functions " /// <summary> /// Event that is called when the Main tool strip button is pressed. /// </summary> public event EventHandler<CancelEventArgs> MainStart; /// <summary> /// Event that is called when the Team Manager tool strip button is pressed. /// </summary> public event EventHandler<CancelEventArgs> TeamManagerStart; /// <summary> /// Event that is called when the Game Manager tool strip button is pressed. /// </summary> public event EventHandler<CancelEventArgs> GameManagerStart; #endregion #region " Public Functions " /// <summary> /// Returns all the menu strip items. /// </summary> /// <returns>The menu strip for this game.</returns> public MenuStrip GetMenuStrip() { return this.menuStrip1; } /// <summary> /// Returns all the tool strip items. /// </summary> /// <returns>The menu strip for this game.</returns> public ToolStrip GetToolStrip() { return this.toolStrip1; } #endregion #region " Private Event Functions " /// <summary> /// Fires when the main tool strip button is pressed. Passes on event to handlers. /// </summary> /// <param name="sender">The tool strip button.</param> /// <param name="e">Event arguments.</param> private void ToolStripButtonMain_Click(object sender, EventArgs e) { CancelEventArgs args = new CancelEventArgs(false); this.MainStart?.Invoke(this, args); } /// <summary> /// Fires when the team manager tool strip button is pressed. Passes on event to handlers. /// </summary> /// <param name="sender">The tool strip button.</param> /// <param name="e">Event arguments.</param> private void ToolStripButtonTeamManager_Click_1(object sender, EventArgs e) { CancelEventArgs args = new CancelEventArgs(false); this.TeamManagerStart?.Invoke(this, args); } /// <summary> /// Fires when the game manager tool strip button is pressed. Passes on event to handlers. /// </summary> /// <param name="sender">The tool strip button.</param> /// <param name="e">Event arguments.</param> private void ToolStripButtonGameManger_Click(object sender, EventArgs e) { CancelEventArgs args = new CancelEventArgs(false); this.GameManagerStart?.Invoke(this, args); } #endregion } }
34.60396
99
0.562518
[ "MIT" ]
runmbrun/pbem
BloodBowl/BloodBowlToolbar.cs
3,497
C#
using System.Collections.Generic; using Chinook.Domain.Converters; using Chinook.Domain.Entities; namespace Chinook.Domain.ApiModels { public class PlaylistApiModel : BaseApiModel, IConvertModel<Playlist> { public string Name { get; set; } public IList<TrackApiModel> Tracks { get; set; } public IList<PlaylistTrackApiModel> PlaylistTracks { get; set; } public Playlist Convert() => new() { Id = Id, Name = Name }; } }
24.318182
73
0.598131
[ "MIT" ]
cwoodruff/Chinook5WebAPI
Chinook/Chinook.Domain/ApiModels/PlaylistApiModel.cs
537
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 license-manager-2018-08-01.normal.json service model. */ using System; using System.Collections.Generic; using System.Globalization; using System.IO; using System.Net; using System.Text; using System.Xml.Serialization; using Amazon.LicenseManager.Model; using Amazon.Runtime; using Amazon.Runtime.Internal; using Amazon.Runtime.Internal.Transform; using Amazon.Runtime.Internal.Util; using ThirdParty.Json.LitJson; namespace Amazon.LicenseManager.Model.Internal.MarshallTransformations { /// <summary> /// Response Unmarshaller for ListResourceInventory operation /// </summary> public class ListResourceInventoryResponseUnmarshaller : JsonResponseUnmarshaller { /// <summary> /// Unmarshaller the response from the service to the response class. /// </summary> /// <param name="context"></param> /// <returns></returns> public override AmazonWebServiceResponse Unmarshall(JsonUnmarshallerContext context) { ListResourceInventoryResponse response = new ListResourceInventoryResponse(); context.Read(); int targetDepth = context.CurrentDepth; while (context.ReadAtDepth(targetDepth)) { if (context.TestExpression("NextToken", targetDepth)) { var unmarshaller = StringUnmarshaller.Instance; response.NextToken = unmarshaller.Unmarshall(context); continue; } if (context.TestExpression("ResourceInventoryList", targetDepth)) { var unmarshaller = new ListUnmarshaller<ResourceInventory, ResourceInventoryUnmarshaller>(ResourceInventoryUnmarshaller.Instance); response.ResourceInventoryList = unmarshaller.Unmarshall(context); continue; } } return response; } /// <summary> /// Unmarshaller error response to exception. /// </summary> /// <param name="context"></param> /// <param name="innerException"></param> /// <param name="statusCode"></param> /// <returns></returns> public override AmazonServiceException UnmarshallException(JsonUnmarshallerContext context, Exception innerException, HttpStatusCode statusCode) { ErrorResponse errorResponse = JsonErrorResponseUnmarshaller.GetInstance().Unmarshall(context); if (errorResponse.Code != null && errorResponse.Code.Equals("AccessDeniedException")) { return new AccessDeniedException(errorResponse.Message, innerException, errorResponse.Type, errorResponse.Code, errorResponse.RequestId, statusCode); } if (errorResponse.Code != null && errorResponse.Code.Equals("AuthorizationException")) { return new AuthorizationException(errorResponse.Message, innerException, errorResponse.Type, errorResponse.Code, errorResponse.RequestId, statusCode); } if (errorResponse.Code != null && errorResponse.Code.Equals("FailedDependencyException")) { return new FailedDependencyException(errorResponse.Message, innerException, errorResponse.Type, errorResponse.Code, errorResponse.RequestId, statusCode); } if (errorResponse.Code != null && errorResponse.Code.Equals("FilterLimitExceededException")) { return new FilterLimitExceededException(errorResponse.Message, innerException, errorResponse.Type, errorResponse.Code, errorResponse.RequestId, statusCode); } if (errorResponse.Code != null && errorResponse.Code.Equals("InvalidParameterValueException")) { return new InvalidParameterValueException(errorResponse.Message, innerException, errorResponse.Type, errorResponse.Code, errorResponse.RequestId, statusCode); } if (errorResponse.Code != null && errorResponse.Code.Equals("RateLimitExceededException")) { return new RateLimitExceededException(errorResponse.Message, innerException, errorResponse.Type, errorResponse.Code, errorResponse.RequestId, statusCode); } if (errorResponse.Code != null && errorResponse.Code.Equals("ServerInternalException")) { return new ServerInternalException(errorResponse.Message, innerException, errorResponse.Type, errorResponse.Code, errorResponse.RequestId, statusCode); } return new AmazonLicenseManagerException(errorResponse.Message, innerException, errorResponse.Type, errorResponse.Code, errorResponse.RequestId, statusCode); } private static ListResourceInventoryResponseUnmarshaller _instance = new ListResourceInventoryResponseUnmarshaller(); internal static ListResourceInventoryResponseUnmarshaller GetInstance() { return _instance; } /// <summary> /// Gets the singleton. /// </summary> public static ListResourceInventoryResponseUnmarshaller Instance { get { return _instance; } } } }
45.40458
174
0.666611
[ "Apache-2.0" ]
Bio2hazard/aws-sdk-net
sdk/src/Services/LicenseManager/Generated/Model/Internal/MarshallTransformations/ListResourceInventoryResponseUnmarshaller.cs
5,948
C#
using System; using System.Windows.Input; namespace Mach.Wpf.Mvvm { /// <summary> /// An <see cref="ICommand"/> whose delegates can be attached for <see cref="Execute"/> and <see cref="CanExecute"/>. /// </summary> public class DelegateCommand : ICommand { private readonly Action _action; private readonly ICommandOnCanExecute _canExecute; /// <summary> /// Delegate when CanExecute is called on the command. This can be null. /// </summary> /// <param name="parameter">Data used by the command.</param> /// <returns></returns> public delegate bool ICommandOnCanExecute(object parameter); /// <summary> /// Initializes a new instance of <see cref="DelegateCommand"/> class. /// </summary> /// <param name="action">Delegate to execute when Execute is called on the command.</param> public DelegateCommand(Action action) { _action = action; } /// <summary> /// Initializes a new instance of <see cref="DelegateCommand"/> class. /// </summary> /// <param name="action">Delegate to execute when Execute is called on the command.</param> /// <param name="canExecute">Delegate to execute when CanExecute is called on the command. This can be null.</param> public DelegateCommand(Action action, ICommandOnCanExecute canExecute) { _action = action; _canExecute = canExecute; } /// <summary> /// Defines the method that determines whether the command can execute in its current state. /// </summary> /// <param name="parameter">Data used by the command.</param> /// <returns>true if this command can be executed; otherwise, false.</returns> public bool CanExecute(object parameter) { if (_canExecute == null) { return true; } return _canExecute(parameter); } /// <summary> /// Defines the method to be called when the command is invoked. /// </summary> /// <param name="parameter">Data used by the command.</param> public void Execute(object parameter) { _action(); } /// <summary> /// Occurs when changes occur that affect whether or not the command should execute. /// </summary> //public event EventHandler CanExecuteChanged; public event EventHandler CanExecuteChanged { add { CommandManager.RequerySuggested += value; } remove { CommandManager.RequerySuggested -= value; } } } }
35.592105
124
0.590388
[ "MIT" ]
machv/wpf-mvvm
Mach.Wpf.Mvvm/Commands/DelegateCommand.cs
2,707
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 Shuttle.Esb.Sql.Idempotence { 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", "15.0.0.0")] [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] public 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)] public static global::System.Resources.ResourceManager ResourceManager { get { if (object.ReferenceEquals(resourceMan, null)) { global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("Shuttle.Esb.Sql.Idempotence.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)] public static global::System.Globalization.CultureInfo Culture { get { return resourceCulture; } set { resourceCulture = value; } } /// <summary> /// Looks up a localized string similar to The connection string used by &apos;{0}&apos; is empty.. /// </summary> public static string ConnectionStringEmpty { get { return ResourceManager.GetString("ConnectionStringEmpty", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Could not find a connection string with name &apos;{0}&apos;.. /// </summary> public static string ConnectionStringMissing { get { return ResourceManager.GetString("ConnectionStringMissing", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Could not get count for queue &apos;{0}&apos;. Exception: {1}. Query: {2}. /// </summary> public static string CountError { get { return ResourceManager.GetString("CountError", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Could not create queue &apos;{0}&apos;. Exception: {1}. Query: {2}. /// </summary> public static string CreateError { get { return ResourceManager.GetString("CreateError", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Could not get count for DeferredMessage table. Exception: {0}. Query: {1}. /// </summary> public static string DeferredMessageCountError { get { return ResourceManager.GetString("DeferredMessageCountError", resourceCulture); } } /// <summary> /// Looks up a localized string similar to The database has not been configured for deferred message storage. Please run the DeferredMessageCreate.sql script file against your database.. /// </summary> public static string DeferredMessageDatabaseNotConfigured { get { return ResourceManager.GetString("DeferredMessageDatabaseNotConfigured", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Could not dequeue a deferred message. Exception: {0}. Query: {1}. /// </summary> public static string DeferredMessageDequeueError { get { return ResourceManager.GetString("DeferredMessageDequeueError", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Could not enqueue a deferred message. Exception: {0}. Query: {1}. /// </summary> public static string DeferredMessageEnqueueError { get { return ResourceManager.GetString("DeferredMessageEnqueueError", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Could not purge DeferredMessage table. Exception: {0}. Query: {1}. /// </summary> public static string DeferredMessagePurgeError { get { return ResourceManager.GetString("DeferredMessagePurgeError", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Could not dequeue message from queue &apos;{0}&apos;. Exception: {1}. Query: {2}. /// </summary> public static string DequeueError { get { return ResourceManager.GetString("DequeueError", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Could not dequeue message from queue &apos;{0}&apos;. Exception: {1}. Query: {2}. /// </summary> public static string DequeueIdError { get { return ResourceManager.GetString("DequeueIdError", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Could not drop queue &apos;{0}&apos;. Exception: {1}. Query: {2}. /// </summary> public static string DropError { get { return ResourceManager.GetString("DropError", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Could not find embedded resource script with file name &apos;{0}&apos;.. /// </summary> public static string EmbeddedScriptMissingException { get { return ResourceManager.GetString("EmbeddedScriptMissingException", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Could not enqueue message data with message id &apos;{0}&apos; on queue &apos;{1}&apos;. Exception: {2}. /// </summary> public static string EnqueueDataError { get { return ResourceManager.GetString("EnqueueDataError", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Could not enqueue message id &apos;{0}&apos; on queue &apos;{1}&apos;. Exception: {2}. /// </summary> public static string EnqueueError { get { return ResourceManager.GetString("EnqueueError", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Could not check whether queue &apos;{0}&apos; exists. Exception: {1}. Query: {2}. /// </summary> public static string ExistsError { get { return ResourceManager.GetString("ExistsError", resourceCulture); } } /// <summary> /// Looks up a localized string similar to The database has not been configured for the idempotence service. Please run the IdempotenceServiceCreate.sql script file against your database.. /// </summary> public static string IdempotenceDatabaseNotConfigured { get { return ResourceManager.GetString("IdempotenceDatabaseNotConfigured", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Saga data with id &apos;{0}&apos; for type &apos;{1}&apos; does not implement SagaData.. /// </summary> public static string InvalidSagaData { get { return ResourceManager.GetString("InvalidSagaData", resourceCulture); } } /// <summary> /// Looks up a localized string similar to The idempotence service cannot be used as there is no inbox configured for the service bus.. /// </summary> public static string NoInboxException { get { return ResourceManager.GetString("NoInboxException", resourceCulture); } } /// <summary> /// Looks up a localized string similar to The provider name used by &apos;{0}&apos; is empty.. /// </summary> public static string ProviderNameEmpty { get { return ResourceManager.GetString("ProviderNameEmpty", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Could not purge queue &apos;{0}&apos;. Exception: {1}. Query: {2}. /// </summary> public static string PurgeError { get { return ResourceManager.GetString("PurgeError", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Could not read top {0} messages from queue &apos;{1}&apos;. Exception: {2}. Query: {3}. /// </summary> public static string ReadError { get { return ResourceManager.GetString("ReadError", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Could not remove message from queue &apos;{0}&apos;. Exception: {1}. Query: {2}. /// </summary> public static string RemoveError { get { return ResourceManager.GetString("RemoveError", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Directory &apos;{0}&apos; was searched (recursively) for script file &apos;{1}&apos;. Exactly 1 file must exist in the directory structure but {2} were found.. /// </summary> public static string ScriptCountException { get { return ResourceManager.GetString("ScriptCountException", resourceCulture); } } /// <summary> /// Looks up a localized string similar to The database has not been configured for subscription storage and the creation script could not be executed against your database. The inner exception should provide the reason. Please run the SubscriptionManagerCreate.sql script file against your database.. /// </summary> public static string SubscriptionManagerCreateException { get { return ResourceManager.GetString("SubscriptionManagerCreateException", resourceCulture); } } } }
42.778547
313
0.577772
[ "BSD-3-Clause" ]
Shuttle/Shuttle.Esb.Sql.Idempotence
Shuttle.Esb.Sql.Idempotence/Resources.Designer.cs
12,365
C#
using System; using System.Diagnostics; using System.Threading.Tasks; using AmazonAccess.Misc; using NUnit.Framework; namespace AmazonAccessTests.Tests { internal abstract class ThrottlerTestsBase { private int _callCounter; private Func< int > _callCounterFunc; private Func< Func< int >, int > _throttlerExecute; protected Throttler _throttler; protected ThrottlerAsync _throttlerAsync; [ SetUp ] public virtual void Init() { this._callCounter = 0; this._callCounterFunc = () => this._callCounter++; this._throttlerExecute = x => this._throttler.Execute( x ); //this._throttlerExecute = x => this._throttlerAsync.ExecuteAsync( () => Task.FromResult( x() ) ).GetAwaiter().GetResult(); } protected void MakeRequests( int requestsCount ) { for( var i = 1; i <= requestsCount; i++ ) { Debug.WriteLine( "Request=" + i ); Assert.AreEqual( this._callCounter, this._throttlerExecute( this._callCounterFunc ) ); } } } internal class ThrottlerTests1: ThrottlerTestsBase { [ SetUp ] public override void Init() { this._throttler = new Throttler( 5, 2, 1 ); this._throttlerAsync = new ThrottlerAsync( 5, 2, 1 ); base.Init(); } [ Test ] public void NoDelayUntilLimitHit() { //------------ Arrange var stopwatch = new Stopwatch(); stopwatch.Start(); //------------ Act this.MakeRequests( 5 ); //------------ Assert stopwatch.Stop(); Assert.IsTrue( stopwatch.Elapsed.TotalSeconds < 1f ); } [ Test ] public void DelayWhenLimitHit() { //------------ Arrange var stopwatch = new Stopwatch(); stopwatch.Start(); //------------ Act this.MakeRequests( 6 ); //------------ Assert stopwatch.Stop(); Assert.IsTrue( stopwatch.Elapsed.TotalSeconds >= 2.0 ); Assert.IsTrue( stopwatch.Elapsed.TotalSeconds <= 2.5 ); } [ Test ] public void ReleaseAutomaticallyIfTimePasses() { //------------ Arrange var stopwatch = new Stopwatch(); stopwatch.Start(); Debug.WriteLine( "Not throttlered requests" ); this.MakeRequests( 5 ); //------------ Act Debug.WriteLine( "Throttlered requests" ); this.MakeRequests( 2 ); //------------ Assert stopwatch.Stop(); Debug.WriteLine( "TotalSeconds=" + stopwatch.Elapsed.TotalSeconds ); Assert.IsTrue( stopwatch.Elapsed.TotalSeconds >= 4.0 ); Assert.IsTrue( stopwatch.Elapsed.TotalSeconds <= 4.5 ); } [ Test ] public void ReleaseAutomaticallyIfTimePasses2() { //------------ Arrange var stopwatch = new Stopwatch(); stopwatch.Start(); Debug.WriteLine( "Not throttlered requests" ); this.MakeRequests( 5 ); Task.Delay( 4000 ).Wait(); //------------ Act Debug.WriteLine( "Not throttlered requests" ); this.MakeRequests( 2 ); //------------ Assert stopwatch.Stop(); Debug.WriteLine( "TotalSeconds=" + stopwatch.Elapsed.TotalSeconds ); Assert.IsTrue( stopwatch.Elapsed.TotalSeconds >= 4.0 ); Assert.IsTrue( stopwatch.Elapsed.TotalSeconds <= 4.5 ); } [ Test ] public void ReleaseAutomaticallyIfTimePasses3() { //------------ Arrange var stopwatch = new Stopwatch(); stopwatch.Start(); Debug.WriteLine( "Not throttlered requests" ); this.MakeRequests( 5 ); Task.Delay( 2000 ).Wait(); //------------ Act Debug.WriteLine( "1 not throttlered and 1 throttlered requests" ); this.MakeRequests( 2 ); //------------ Assert stopwatch.Stop(); Debug.WriteLine( "TotalSeconds=" + stopwatch.Elapsed.TotalSeconds ); Assert.IsTrue( stopwatch.Elapsed.TotalSeconds >= 4.0 ); Assert.IsTrue( stopwatch.Elapsed.TotalSeconds <= 4.5 ); } [ Test ] public void ReleaseAutomaticallyIfTimePasses4() { //------------ Arrange var stopwatch = new Stopwatch(); stopwatch.Start(); Debug.WriteLine( "Not throttlered requests" ); this.MakeRequests( 5 ); Task.Delay( 10000 ).Wait(); //------------ Act Debug.WriteLine( "Not throttlered requests" ); this.MakeRequests( 5 ); //------------ Assert stopwatch.Stop(); Debug.WriteLine( "TotalSeconds=" + stopwatch.Elapsed.TotalSeconds ); Assert.IsTrue( stopwatch.Elapsed.TotalSeconds >= 10.0 ); Assert.IsTrue( stopwatch.Elapsed.TotalSeconds <= 10.5 ); } [ Test ] public void ReleaseAutomaticallyIfTimePasses5() { //------------ Arrange var stopwatch = new Stopwatch(); stopwatch.Start(); Debug.WriteLine( "Not throttlered requests" ); this.MakeRequests( 5 ); Task.Delay( 12000 ).Wait(); //------------ Act Debug.WriteLine( "5 not throttlered and 1 throttlered requests" ); this.MakeRequests( 6 ); //------------ Assert stopwatch.Stop(); Debug.WriteLine( "TotalSeconds=" + stopwatch.Elapsed.TotalSeconds ); Assert.IsTrue( stopwatch.Elapsed.TotalSeconds >= 14.0 ); Assert.IsTrue( stopwatch.Elapsed.TotalSeconds <= 14.5 ); } [ Test ] public void ReleaseAutomaticallyIfTimePasses6() { //------------ Arrange var stopwatch = new Stopwatch(); stopwatch.Start(); //------------ Act Debug.WriteLine( "5 not throttlered and 9 throttlered requests" ); this.MakeRequests( 14 ); //------------ Assert stopwatch.Stop(); Debug.WriteLine( "TotalSeconds=" + stopwatch.Elapsed.TotalSeconds ); Assert.IsTrue( stopwatch.Elapsed.TotalSeconds >= 18.0 ); Assert.IsTrue( stopwatch.Elapsed.TotalSeconds <= 18.5 ); } } internal class ThrottlerTests2: ThrottlerTestsBase { [ SetUp ] public override void Init() { this._throttler = new Throttler( 5, 10, 5 ); this._throttlerAsync = new ThrottlerAsync( 5, 10, 5 ); base.Init(); } [ Test ] public void NoDelayUntilLimitHit() { //------------ Arrange var stopwatch = new Stopwatch(); stopwatch.Start(); //------------ Act this.MakeRequests( 5 ); //------------ Assert stopwatch.Stop(); Assert.IsTrue( stopwatch.Elapsed.TotalSeconds < 1f ); } [ Test ] public void DelayWhenLimitHit() { //------------ Arrange var stopwatch = new Stopwatch(); stopwatch.Start(); //------------ Act this.MakeRequests( 6 ); //------------ Assert stopwatch.Stop(); Assert.IsTrue( stopwatch.Elapsed.TotalSeconds >= 10.0 ); Assert.IsTrue( stopwatch.Elapsed.TotalSeconds <= 10.5 ); } [ Test ] public void ReleaseAutomaticallyIfTimePasses() { //------------ Arrange var stopwatch = new Stopwatch(); stopwatch.Start(); Debug.WriteLine( "Not throttlered requests" ); this.MakeRequests( 5 ); //------------ Act Debug.WriteLine( "Throttlered requests" ); this.MakeRequests( 2 ); //------------ Assert stopwatch.Stop(); Debug.WriteLine( "TotalSeconds=" + stopwatch.Elapsed.TotalSeconds ); Assert.IsTrue( stopwatch.Elapsed.TotalSeconds >= 10.0 ); Assert.IsTrue( stopwatch.Elapsed.TotalSeconds <= 10.5 ); } [ Test ] public void ReleaseAutomaticallyIfTimePasses2() { //------------ Arrange var stopwatch = new Stopwatch(); stopwatch.Start(); Debug.WriteLine( "Not throttlered requests" ); this.MakeRequests( 5 ); Task.Delay( 10000 ).Wait(); //------------ Act Debug.WriteLine( "Not throttlered requests" ); this.MakeRequests( 2 ); //------------ Assert stopwatch.Stop(); Debug.WriteLine( "TotalSeconds=" + stopwatch.Elapsed.TotalSeconds ); Assert.IsTrue( stopwatch.Elapsed.TotalSeconds >= 10.0 ); Assert.IsTrue( stopwatch.Elapsed.TotalSeconds <= 10.5 ); } [ Test ] public void ReleaseAutomaticallyIfTimePasses3() { //------------ Arrange var stopwatch = new Stopwatch(); stopwatch.Start(); Debug.WriteLine( "Not throttlered requests" ); this.MakeRequests( 5 ); Task.Delay( 5000 ).Wait(); //------------ Act Debug.WriteLine( "Throttlered requests on remaining 5 sec" ); this.MakeRequests( 2 ); //------------ Assert stopwatch.Stop(); Debug.WriteLine( "TotalSeconds=" + stopwatch.Elapsed.TotalSeconds ); Assert.IsTrue( stopwatch.Elapsed.TotalSeconds >= 10.0 ); Assert.IsTrue( stopwatch.Elapsed.TotalSeconds <= 10.5 ); } [ Test ] public void ReleaseAutomaticallyIfTimePasses4() { //------------ Arrange var stopwatch = new Stopwatch(); stopwatch.Start(); Debug.WriteLine( "Not throttlered requests" ); this.MakeRequests( 5 ); Task.Delay( 10000 ).Wait(); //------------ Act Debug.WriteLine( "Not throttlered requests" ); this.MakeRequests( 5 ); //------------ Assert stopwatch.Stop(); Debug.WriteLine( "TotalSeconds=" + stopwatch.Elapsed.TotalSeconds ); Assert.IsTrue( stopwatch.Elapsed.TotalSeconds >= 10.0 ); Assert.IsTrue( stopwatch.Elapsed.TotalSeconds <= 10.5 ); } [ Test ] public void ReleaseAutomaticallyIfTimePasses5() { //------------ Arrange var stopwatch = new Stopwatch(); stopwatch.Start(); Debug.WriteLine( "Not throttlered requests" ); this.MakeRequests( 5 ); Task.Delay( 12000 ).Wait(); //------------ Act Debug.WriteLine( "5 not throttlered and 1 throttlered requests" ); this.MakeRequests( 6 ); //------------ Assert stopwatch.Stop(); Debug.WriteLine( "TotalSeconds=" + stopwatch.Elapsed.TotalSeconds ); Assert.IsTrue( stopwatch.Elapsed.TotalSeconds >= 22.0 ); Assert.IsTrue( stopwatch.Elapsed.TotalSeconds <= 22.5 ); } [ Test ] public void ReleaseAutomaticallyIfTimePasses6() { //------------ Arrange var stopwatch = new Stopwatch(); stopwatch.Start(); //------------ Act Debug.WriteLine( "5 not throttlered and 9 throttlered requests" ); this.MakeRequests( 14 ); //------------ Assert stopwatch.Stop(); Debug.WriteLine( "TotalSeconds=" + stopwatch.Elapsed.TotalSeconds ); Assert.IsTrue( stopwatch.Elapsed.TotalSeconds >= 20.0 ); Assert.IsTrue( stopwatch.Elapsed.TotalSeconds <= 20.5 ); } } }
26.334232
126
0.629069
[ "BSD-3-Clause" ]
skuvault-integrations/amazonAccess
src/AmazonAccessTests/Tests/ThrottlerTests.cs
9,772
C#
using System.Collections.Generic; using System.Xml.Serialization; namespace dbqf.Serialization.DTO.Parsers { [XmlRoot("ChainedParser")] public class ChainedParserDTO : ParserDTO { public ChainedParserDTO() { Parsers = new List<ParserDTO>(); } [XmlArray] [XmlArrayItem("DelimitedParser", typeof(DelimitedParserDTO))] [XmlArrayItem("ChainedParser", typeof(ChainedParserDTO))] [XmlArrayItem("ConvertParser", typeof(ConvertParserDTO))] [XmlArrayItem("DateParser", typeof(DateParserDTO))] public List<ParserDTO> Parsers { get; set; } } }
28.954545
69
0.657771
[ "MIT" ]
SammyEnigma/dbqf
lib/dbqf.Serialization/DTO/Parsers/ChainedParserDTO.cs
639
C#
// Copyright 2019 Maintainers of NUKE. // Distributed under the MIT License. // https://github.com/nuke-build/nuke/blob/master/LICENSE using System; using System.Linq; using JetBrains.Annotations; namespace Nuke.Common.BuildServers { [PublicAPI] public enum TeamServicesIssueType { Warning, Error } }
18.611111
57
0.707463
[ "MIT" ]
MarkusAmshove/common
source/Nuke.Common/BuildServers/TeamServicesIssueType.cs
335
C#
using Avalonia; using Avalonia.Threading; using ReactiveUI; using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using System.Reactive.Linq; using System.Text; using System.Threading.Tasks; using WalletWasabi.Gui.Tabs.WalletManager; using WalletWasabi.Gui.ViewModels; using WalletWasabi.KeyManagement; namespace WalletWasabi.Gui.Controls.WalletExplorer { public class ReceiveTabViewModel : WalletActionViewModel { private ObservableCollection<AddressViewModel> _addresses; private AddressViewModel _selectedAddress; private string _label; private double _labelRequiredNotificationOpacity; private bool _labelRequiredNotificationVisible; private double _clipboardNotificationOpacity; private bool _clipboardNotificationVisible; private int _caretIndex; private ObservableCollection<SuggestionViewModel> _suggestions; public ReceiveTabViewModel(WalletViewModel walletViewModel) : base("Receive", walletViewModel) { _addresses = new ObservableCollection<AddressViewModel>(); Label = ""; Observable.FromEventPattern(Global.WalletService.Coins, nameof(Global.WalletService.Coins.HashSetChanged)) .ObserveOn(RxApp.MainThreadScheduler) .Subscribe(o => { InitializeAddresses(); }); InitializeAddresses(); GenerateCommand = ReactiveCommand.Create(() => { if (string.IsNullOrWhiteSpace(Label)) { LabelRequiredNotificationVisible = true; LabelRequiredNotificationOpacity = 1; Dispatcher.UIThread.Post(async () => { await Task.Delay(1000); LabelRequiredNotificationOpacity = 0; }); return; } Dispatcher.UIThread.Post(() => { var label = Label.Trim(',', ' ').Trim(); HdPubKey newKey = Global.WalletService.GetReceiveKey(label, Addresses.Select(x => x.Model).Take(7)); // Never touch the first 7 keys. AddressViewModel found = Addresses.FirstOrDefault(x => x.Model == newKey); if (found != default) { Addresses.Remove(found); } var newAddress = new AddressViewModel(newKey); Addresses.Insert(0, newAddress); SelectedAddress = newAddress; Label = ""; }); }); this.WhenAnyValue(x => x.Label).Subscribe(x => UpdateSuggestions(x)); this.WhenAnyValue(x => x.SelectedAddress).Subscribe(address => { if (!(address is null)) { address.CopyToClipboard(); ClipboardNotificationVisible = true; ClipboardNotificationOpacity = 1; Dispatcher.UIThread.Post(async () => { await Task.Delay(1000); ClipboardNotificationOpacity = 0; }); } }); this.WhenAnyValue(x => x.CaretIndex).Subscribe(_ => { if (Label == null) return; if (CaretIndex != Label.Length) { CaretIndex = Label.Length; } }); _suggestions = new ObservableCollection<SuggestionViewModel>(); } private void InitializeAddresses() { _addresses?.Clear(); var keys = Global.WalletService.KeyManager.GetKeys(KeyState.Clean, false); foreach (HdPubKey key in keys.Where(x => x.HasLabel()).Reverse()) { _addresses.Add(new AddressViewModel(key)); } } public ObservableCollection<AddressViewModel> Addresses { get { return _addresses; } set { this.RaiseAndSetIfChanged(ref _addresses, value); } } public AddressViewModel SelectedAddress { get { return _selectedAddress; } set { this.RaiseAndSetIfChanged(ref _selectedAddress, value); } } public string Label { get { return _label; } set { this.RaiseAndSetIfChanged(ref _label, value); } } public double LabelRequiredNotificationOpacity { get { return _labelRequiredNotificationOpacity; } set { this.RaiseAndSetIfChanged(ref _labelRequiredNotificationOpacity, value); } } public bool LabelRequiredNotificationVisible { get { return _labelRequiredNotificationVisible; } set { this.RaiseAndSetIfChanged(ref _labelRequiredNotificationVisible, value); } } public double ClipboardNotificationOpacity { get { return _clipboardNotificationOpacity; } set { this.RaiseAndSetIfChanged(ref _clipboardNotificationOpacity, value); } } public bool ClipboardNotificationVisible { get { return _clipboardNotificationVisible; } set { this.RaiseAndSetIfChanged(ref _clipboardNotificationVisible, value); } } public int CaretIndex { get { return _caretIndex; } set { this.RaiseAndSetIfChanged(ref _caretIndex, value); } } public ObservableCollection<SuggestionViewModel> Suggestions { get { return _suggestions; } set { this.RaiseAndSetIfChanged(ref _suggestions, value); } } private void UpdateSuggestions(string words) { if (string.IsNullOrWhiteSpace(words)) { Suggestions?.Clear(); return; } var enteredWordList = words.Split(',', StringSplitOptions.RemoveEmptyEntries).Select(x => x.Trim()); var lastWorld = enteredWordList.LastOrDefault().Replace("\t", ""); if (lastWorld.Length < 1) { Suggestions.Clear(); return; } string[] nonSpecialLabels = Global.WalletService.GetNonSpecialLabels().ToArray(); IEnumerable<string> suggestedWords = nonSpecialLabels.Where(w => w.StartsWith(lastWorld, StringComparison.InvariantCultureIgnoreCase)) .Union(nonSpecialLabels.Where(w => w.Contains(lastWorld, StringComparison.InvariantCultureIgnoreCase))) .Except(enteredWordList) .Take(3); Suggestions.Clear(); foreach (var suggestion in suggestedWords) { Suggestions.Add(new SuggestionViewModel(suggestion, OnAddWord)); } } public void OnAddWord(string word) { var words = Label.Split(',', StringSplitOptions.RemoveEmptyEntries).Select(x => x.Trim()).ToArray(); if (words.Length == 0) { Label = word + ", "; } else { words[words.Length - 1] = word; Label = string.Join(", ", words) + ", "; } CaretIndex = Label.Length; Suggestions.Clear(); } public ReactiveCommand GenerateCommand { get; } } }
26.542222
138
0.708305
[ "MIT" ]
JuniperTonic/WalletWasabi
WalletWasabi.Gui/Controls/WalletExplorer/ReceiveTabViewModel.cs
5,974
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("Tests")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("Tests")] [assembly: AssemblyCopyright("Copyright © 2014")] [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("24a60d3e-4be1-4890-9f53-84396ed2238e")] // 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")]
34.538462
84
0.737194
[ "Apache-2.0" ]
jayotterbein/MissingLinq
MissingLinqTests/Properties/AssemblyInfo.cs
1,350
C#
// This code is part of the Fungus library (http://fungusgames.com) maintained by Chris Gregan (http://twitter.com/gofungus). // It is released for free under the MIT open source license (https://github.com/snozbot/fungus/blob/master/LICENSE) using System; using System.Collections.Generic; using UnityEngine; namespace Fungus { /// <summary> /// A single line of dialog /// </summary> [Serializable] public class Line { [SerializeField] public string name; [SerializeField] public string text; } /// <summary> /// Serializable object to store Narrative Lines /// </summary> [Serializable] public class NarrativeData { [SerializeField] public List<Line> lines; public NarrativeData() { lines = new List<Line>(); } } /// <summary> /// Controls dialog history /// </summary> public class NarrativeLog : MonoBehaviour { /// <summary> /// NarrativeAdded signal. Sent when a line is added. /// </summary> public static event NarrativeAddedHandler OnNarrativeAdded; public delegate void NarrativeAddedHandler(); public static void DoNarrativeAdded() { if (OnNarrativeAdded != null) OnNarrativeAdded(); } NarrativeData history; protected virtual void Awake() { history = new NarrativeData(); } protected virtual void OnEnable() { WriterSignals.OnWriterState += OnWriterState; } protected virtual void OnDisable() { WriterSignals.OnWriterState -= OnWriterState; } protected virtual void OnWriterState(Writer writer, WriterState writerState) { if (writerState == WriterState.End) { var sd = SayDialog.GetSayDialog(); var from = sd.NameText; var line = sd.StoryText; AddLine(from, line); } } #region Public Methods /// <summary> /// Add a line of dialog to the Narrative Log /// </summary> /// <param name="name">Character Name</param> /// <param name="text">Narrative Text</param> public void AddLine(string name, string text) { Line line = new Line(); line.name = name; line.text = text; history.lines.Add(line); DoNarrativeAdded(); } /// <summary> /// Clear all lines of the narrative log /// Usually used on restart /// </summary> public void Clear() { history.lines.Clear(); } /// <summary> /// Convert history into Json for saving in SaveData /// </summary> /// <returns></returns> public string GetJsonHistory() { string jsonText = JsonUtility.ToJson(history, true); return jsonText; } /// <summary> /// Show previous lines for display purposes /// </summary> /// <returns></returns> public string GetPrettyHistory(bool previousOnly = false) { string output = "\n "; int count; count = previousOnly ? history.lines.Count - 1: history.lines.Count; for (int i = 0; i < count; i++) { output += "<b>" + history.lines[i].name + "</b>\n"; output += history.lines[i].text + "\n\n"; } return output; } /// <summary> /// Load History from Json /// </summary> /// <param name="narrativeData"></param> public void LoadHistory(string narrativeData) { if (narrativeData == null) { Debug.LogError("Failed to decode History save data item"); return; } history = JsonUtility.FromJson<NarrativeData>(narrativeData); } #endregion } }
27.856164
125
0.535038
[ "MIT" ]
ACM-London-Game-Development/MinoTourPublic
Assets/Fungus/Scripts/Components/NarrativeLog.cs
4,067
C#
using ClaimManager.Infrastructure.Identity.Models; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Identity; using Microsoft.AspNetCore.Identity.UI.Services; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.RazorPages; using Microsoft.AspNetCore.WebUtilities; using System.ComponentModel.DataAnnotations; using System.Text; using System.Text.Encodings.Web; using System.Threading.Tasks; namespace ClaimManager.Web.Areas.Identity.Pages.Account { [AllowAnonymous] public class ForgotPasswordModel : PageModel { private readonly UserManager<ApplicationUser> _userManager; private readonly IEmailSender _emailSender; public ForgotPasswordModel(UserManager<ApplicationUser> userManager, IEmailSender emailSender) { _userManager = userManager; _emailSender = emailSender; } [BindProperty] public InputModel Input { get; set; } public class InputModel { [Required] [EmailAddress] public string Email { get; set; } } public async Task<IActionResult> OnPostAsync() { if (ModelState.IsValid) { var user = await _userManager.FindByEmailAsync(Input.Email); if (user == null || !(await _userManager.IsEmailConfirmedAsync(user))) { // Don't reveal that the user does not exist or is not confirmed return RedirectToPage("./ForgotPasswordConfirmation"); } // For more information on how to enable account confirmation and password reset please // visit https://go.microsoft.com/fwlink/?LinkID=532713 var code = await _userManager.GeneratePasswordResetTokenAsync(user); code = WebEncoders.Base64UrlEncode(Encoding.UTF8.GetBytes(code)); var callbackUrl = Url.Page( "/Account/ResetPassword", pageHandler: null, values: new { area = "Identity", code }, protocol: Request.Scheme); await _emailSender.SendEmailAsync( Input.Email, "Reset Password", $"Please reset your password by <a href='{HtmlEncoder.Default.Encode(callbackUrl)}'>clicking here</a>."); return RedirectToPage("./ForgotPasswordConfirmation"); } return Page(); } } }
36.782609
125
0.615839
[ "MIT" ]
seungilpark/ClaimManager
ClaimManager.Web/Areas/Identity/Pages/Account/ForgotPassword.cshtml.cs
2,540
C#
using System; namespace WebApi.HypermediaExtensions.WebApi.AttributedRoutes { public interface IHaveRouteInfo { Type RouteType { get; } Type RouteKeyProducerType { get; } } }
18.545455
61
0.686275
[ "MIT" ]
bluehands/WebApiHypermediaExtensions
Source/WebApi.HypermediaExtensions/WebApi/AttributedRoutes/IHaveRouteInfo.cs
204
C#
using System.Security.Cryptography; using Murmur; namespace DotnetSpider.Infrastructure { public class MurmurHashAlgorithmService : HashAlgorithmService { private readonly HashAlgorithm _hashAlgorithm; public MurmurHashAlgorithmService() { _hashAlgorithm = MurmurHash.Create32(); } protected override HashAlgorithm GetHashAlgorithm() { return _hashAlgorithm; } } }
18.619048
63
0.782609
[ "MIT" ]
Ponderfly/DotnetSpider
src/DotnetSpider/Infrastructure/MurmurHashAlgorithmService.cs
391
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.Compute.V20180401.Outputs { /// <summary> /// The configuration parameters used for performing automatic OS upgrade. /// </summary> [OutputType] public sealed class AutoOSUpgradePolicyResponse { /// <summary> /// Whether OS image rollback feature should be disabled. Default value is false. /// </summary> public readonly bool? DisableAutoRollback; [OutputConstructor] private AutoOSUpgradePolicyResponse(bool? disableAutoRollback) { DisableAutoRollback = disableAutoRollback; } } }
29.580645
89
0.687023
[ "Apache-2.0" ]
polivbr/pulumi-azure-native
sdk/dotnet/Compute/V20180401/Outputs/AutoOSUpgradePolicyResponse.cs
917
C#
using System; using System.ComponentModel.Design; namespace EIDSS.Reports.Barcode.Designer { public class MenuCommandServiceStub : IMenuCommandService { public void AddCommand(MenuCommand command) { } public void AddVerb(DesignerVerb verb) { } private void HandlerStub(object senrer, EventArgs e) { } public MenuCommand FindCommand(CommandID commandID) { return new MenuCommand(HandlerStub, new CommandID(Guid.NewGuid(), -1)); } public bool GlobalInvoke(CommandID commandID) { return true; } public void RemoveCommand(MenuCommand command) { } public void RemoveVerb(DesignerVerb verb) { } public void ShowContextMenu(CommandID menuID, int x, int y) { } public DesignerVerbCollection Verbs { get { return new DesignerVerbCollection(); } } } }
22.574468
84
0.554194
[ "BSD-2-Clause" ]
EIDSS/EIDSS-Legacy
EIDSS v5/vb/EIDSS/EIDSS.Reports/Barcode/Designer/MenuCommandServiceStub.cs
1,063
C#
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ using System; using System.Collections.Generic; using Aliyun.Acs.Core.Transform; using Aliyun.Acs.Cdn.Model.V20141111; namespace Aliyun.Acs.Cdn.Transform.V20141111 { public class AddLiveDomainMappingResponseUnmarshaller { public static AddLiveDomainMappingResponse Unmarshall(UnmarshallerContext context) { AddLiveDomainMappingResponse addLiveDomainMappingResponse = new AddLiveDomainMappingResponse(); addLiveDomainMappingResponse.HttpResponse = context.HttpResponse; addLiveDomainMappingResponse.RequestId = context.StringValue("AddLiveDomainMapping.RequestId"); return addLiveDomainMappingResponse; } } }
37.05
99
0.765857
[ "Apache-2.0" ]
bbs168/aliyun-openapi-net-sdk
aliyun-net-sdk-cdn/Cdn/Transform/V20141111/AddLiveDomainMappingResponseUnmarshaller.cs
1,482
C#
using System; using Microsoft.VisualStudio.TestTools.UnitTesting; namespace IntrepidProducts.ElevatorSystem.Tests { [TestClass] public class FloorTest { [TestMethod] public void ShouldDefaultNameToFloorNumber() { var floor = new Floor(5); Assert.AreEqual("5", floor.Name); } [TestMethod] [ExpectedException(typeof(ArgumentException))] public void ShouldRejectFloorNumbersBelowOne() { var floor = new Floor(0); } [TestMethod] public void ShouldDefaultToUnlocked() { var floor = new Floor(5); Assert.IsFalse(floor.IsLocked); } [TestMethod] public void ShouldConsiderFloorsWithIdenticalNumbersEqual() { var floor1 = new Floor(5) { Name = "XXX" }; var floor2 = new Floor(5) { Name = "YYY" }; var floor3 = new Floor(3) { Name = "ABC" }; Assert.AreEqual(floor1, floor2); Assert.AreNotEqual(floor1, floor3); } [TestMethod] public void ShouldSupportFloorOperatorComparisons() { var floor1 = new Floor(1) { Name = "XXX" }; var floor2 = new Floor(2) { Name = "YYY" }; Assert.IsTrue(floor1 < floor2); Assert.IsTrue(floor2 > floor1); } } }
26.188679
67
0.551873
[ "MIT" ]
EdChaparro/ElevatorSystem.NET
src/Tests/Test.ElevatorSystem/FloorTest.cs
1,388
C#
using System.Collections; using System.Collections.Generic; using UnityEngine; public class InflictDamage : MonoBehaviour { public int DamageAmount = 1; public float TargetDistance; public float AllowedRange = 2.7f; public int DealingDamage; public RaycastHit hit; // Update is called once per frame void Update() { if(Input.GetButtonDown("Fire1") && UiManagerScript.MyInstance.MenuOpen == false) { if(Physics.Raycast (transform.position, transform.TransformDirection (Vector3.forward), out hit)) { TargetDistance = hit.distance; if (TargetDistance <= AllowedRange) { if(DealingDamage == 0){ StartCoroutine (weaponAttack()); } } } } } IEnumerator weaponAttack() { DealingDamage = 2; yield return new WaitForSeconds (0.5f); DamageAmount = PlayerStats.MyInstance.attributes[6].value; hit.transform.SendMessage ("DeductPoints", DamageAmount, SendMessageOptions.DontRequireReceiver); yield return new WaitForSeconds (0.5f); DealingDamage = 0; } }
30.74359
111
0.615513
[ "Unlicense" ]
tjramsey/CSU-Senior-Project
src/Assets/Scripts/AiScripts/EnemyScripts/InflictDamage.cs
1,201
C#
using Cofoundry.Domain; using System; using System.Collections.Generic; using System.Text; namespace Bogevang.Templates.Domain.CustomEntities { public class TemplateCustomEntityDefinition : ICustomEntityDefinition<TemplateDataModel>, ICustomizedTermCustomEntityDefinition { /// <summary> /// This constant is a convention that allows us to reference this definition code /// in other parts of the application (e.g. querying) /// </summary> public const string DefinitionCode = "TMPLAT"; /// <summary> /// Unique 6 letter code representing the module (the convention is to use uppercase) /// </summary> public string CustomEntityDefinitionCode => DefinitionCode; /// <summary> /// Singlar name of the entity /// </summary> public string Name => "Skabelon"; /// <summary> /// Plural name of the entity /// </summary> public string NamePlural => "Skabeloner"; /// <summary> /// A short description that shows up as a tooltip for the admin /// panel. /// </summary> public string Description => "Skabeloner til breve."; /// <summary> /// Indicates whether the UrlSlug property should be treated /// as a unique property and be validated as such. /// </summary> public bool ForceUrlSlugUniqueness => true; /// <summary> /// Indicates whether the url slug should be autogenerated. If this /// is selected then the user will not be shown the UrlSlug property /// and it will be auto-generated based on the title. /// </summary> public bool AutoGenerateUrlSlug => false; /// <summary> /// Indicates whether this custom entity should always be published when /// saved, provided the user has permissions to do so. Useful if this isn't /// the sort of entity that needs a draft state workflow /// </summary> public bool AutoPublish => true; /// <summary> /// Indicates whether the entities are partitioned by locale /// </summary> public bool HasLocale => false; public Dictionary<string, string> CustomTerms => new Dictionary<string, string> { [CustomizableCustomEntityTermKeys.UrlSlug] = "Skabelonnavn" }; } }
32.742857
90
0.650524
[ "MIT" ]
Bogevang-spejderhytte/website
Bogevang.Templates.Domain/CustomEntities/TemplateCustomEntityDefinition.cs
2,294
C#
//---------------------------------------------------------------- // Copyright (c) Yamool Inc. All rights reserved. //---------------------------------------------------------------- namespace Yamool.CWSharp { using System; using System.Collections.Generic; /// <summary> /// The standard unigram tokenizer that converting text into a sequence of tokens. /// </summary> public sealed class UnigramTokenizer : ITokenizer { public UnigramTokenizer() { } public bool OptionOutputOriginalCase { get; set; } public IEnumerable<Token> Traverse(string text) { if (string.IsNullOrEmpty(text)) { yield break; } using (var reader = new RewindStringReader(text, this.OptionOutputOriginalCase)) { var breaker = new UnigramTokenBreaker(reader); var token = breaker.Next(); do { yield return token; } while ((token = breaker.Next()) != null); } } private class UnigramTokenBreaker : WhiteSpaceTokenBreaker { private RewindStringReader _reader; public UnigramTokenBreaker(RewindStringReader reader) : base(reader) { _reader = reader; } public override Token Next() { var code = _reader.Read(); if (code.IsNull()) { return null; } if (code.IsLetterCase() || code.IsNumeralCase()) { _reader.Seek(_reader.Position - 1); return base.Next(); } else if (code.IsCjkCase()) { return new Token(code.ToString(), TokenType.CJK); } return new Token(code.ToString(), TokenType.PUNC); } } } }
29.309859
92
0.440654
[ "MIT" ]
DavidAlphaFox/CWSharp
src/Yamool.CWSharp/UnigramTokenizer.cs
2,083
C#
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Abp.Application.Services.Dto; using Abp.Domain.Repositories; using Abp.Linq.Extensions; using demo.TaskAppService.Dto; using Microsoft.EntityFrameworkCore; namespace demo.TaskAppService { public class TaskAppService : demoAppServiceBase, ITaskAppService { private readonly IRepository<Tasks.Task> _taskRepository; public TaskAppService(IRepository<Tasks.Task> taskRepository) { _taskRepository = taskRepository; } public async Task<ListResultDto<TaskListDto>> GetAll() { var tasks = await _taskRepository.GetAll() //.WhereIf(input.State.HasValue, t => t.State == input.State.Value) .OrderByDescending(t => t.CreationTime) .ToListAsync(); //var newList = new List<TaskListDto>(); return new ListResultDto<TaskListDto>( ObjectMapper.Map<List<TaskListDto>>(tasks) ); } public async Task<Tasks.Task> AddNewTask(RequestDto requestDto) { var newTaskItem = await _taskRepository.InsertAsync( new Tasks.Task( requestDto.Title, requestDto.Description ) ); return newTaskItem; } public async Task<Tasks.Task> UpdateTask(TaskListDto taskListDto) { try { var task = await _taskRepository.SingleAsync(t => t.Id.Equals(taskListDto.Id)); task.Title = taskListDto.Title; task.Description = taskListDto.Description; var update = await _taskRepository.UpdateAsync(task); return task; } catch (Exception exception) { return null; } } public void DeleteTask(int id) { var delete = _taskRepository.DeleteAsync(id); } } }
27.680556
126
0.599097
[ "MIT" ]
ebiggerr/ABP_Training
aspnet-core/src/demo.Application/TaskAppService/TaskAppService.cs
1,995
C#
// //----------------------------------------------------------------------- // // <copyright file="BatchingOracleJournalPerfSpec.cs" company="Akka.NET Project"> // // Copyright (C) 2009-2020 Lightbend Inc. <http://www.lightbend.com> // // Copyright (C) 2013-2020 .NET Foundation <https://github.com/akkadotnet/akka.net> // // </copyright> // //----------------------------------------------------------------------- using System; using Akka.Configuration; using Akka.Persistence.TestKit.Performance; using Xunit; using Xunit.Abstractions; namespace Akka.Persistence.Oracle.Tests.Batching { [Collection("OracleSpec")] public class BatchingOracleJournalPerfSpec : JournalPerfSpec { public static Config SpecConfig => ConfigurationFactory.ParseString(@" akka.persistence { publish-plugin-commands = on journal { plugin = ""akka.persistence.journal.oracle"" oracle { class = ""Akka.Persistence.Oracle.Journal.BatchingOracleJournal, Akka.Persistence.Oracle"" plugin-dispatcher = ""akka.actor.default-dispatcher"" table-name = EVENTJOURNAL schema-name = AKKA_PERSISTENCE_TEST auto-initialize = on connection-string = """ + DbUtils.ConnectionString + @""" } } }"); static BatchingOracleJournalPerfSpec() { DbUtils.Initialize(); } public BatchingOracleJournalPerfSpec(ITestOutputHelper output) : base(SpecConfig, "BatchingOracleJournalPerfSpec", output) { EventsCount = 1000; ExpectDuration = TimeSpan.FromMinutes(10); MeasurementIterations = 1; } protected override void AfterAll() { base.AfterAll(); DbUtils.Clean(); } } }
37.444444
142
0.523244
[ "Apache-2.0" ]
ismaelhamed/akka.persistence.oracle
src/Akka.Persistence.Oracle.Tests/Batching/BatchingOracleJournalPerfSpec.cs
2,022
C#
using System; using System.Collections.Generic; using System.Data; using System.Globalization; using System.IO; using System.IO.Compression; using System.Linq; using System.Text; using System.Xml; //some code from https://github.com/MarkPflug/Sylvan.Data.Excel //some code from https://github.com/ExcelDataReader/ExcelDataReader namespace SpreadSheetTasks { public sealed class XlsxOrXlsbReadOrEdit : ExcelReaderAbstract, IDisposable { private ZipArchive _xlsxArchive; private readonly Dictionary<string, string> _worksheetIdToName = new Dictionary<string, string>(); private readonly Dictionary<string, string> _worksheetNameToId = new Dictionary<string, string>(); private readonly Dictionary<string, string> _worksheetIdToLocation = new Dictionary<string, string>(); private Dictionary<int, string> _pivotCacheIdtoRid; private Dictionary<string, string> _pivotCachRidToLocation; //private Dictionary<int, string> _worksheetSheetIdToId = new Dictionary<int, string>(); private string[] _sharedStringArray; private StyleInfo[] _stylesCellXfsArray; internal readonly static Dictionary<int, Type> _numberFormatsTypeDic = new Dictionary<int, Type>() { // to do {0,typeof(string)}, {1,typeof(decimal?)}, {2,typeof(decimal?)}, {3,typeof(decimal?)}, {4,typeof(decimal?)}, {5,typeof(decimal?)}, {6,typeof(decimal?)}, {7,typeof(decimal?)}, {9, typeof(decimal?)}, // 0% { 14,typeof(DateTime?)}, { 15,typeof(DateTime?)}, { 16,typeof(DateTime?)}, { 17,typeof(DateTime?)}, { 18,typeof(DateTime?)}, { 19,typeof(DateTime?)}, { 20,typeof(DateTime?)}, { 21,typeof(DateTime?)}, { 22,typeof(DateTime?)}, { 44,typeof(decimal?)} }; internal readonly static HashSet<string> _dateExcelMasks = new HashSet<string>() { @"[$-F800]dddd\,\ mmmm\ dd\,\ yyyy", @"d\-mm;@", @"yy\-mm\-dd;@", @"[$-415]d\ mmm;@", @"[$-415]d\ mmm\ yy;@", @"[$-415]dd\ mmm\ yy;@", @"[$-415]mmm\ yy;@", @"[$-415]mmmm\ yy;@", @"[$-415]d\ mmmm\ yyyy;@", @"yyyy\-mm\-dd\ hh:mm", @"yyyy\-mm\-dd\ hh:mm:ss", @"yyyy\-mm\-dd;@", @"[$-409]dd\-mm\-yy\ h:mm\ AM/PM;@", @"dd\-mm\-yy\ h:mm;@", @"[$-415]mmmmm;@", @"[$-415]mmmmm\.yy;@", @"\-m\-yyyy;@", @"[$-415]d\-mmm\-yyyy;@", @"d\-m\-yyyy;@" }; private string _sharedStringsLocation = null; private string _stylesLocation = null; private string _themeLocation = null; private int _uniqueStringCount = -1; private int _stringCount = -1; Modes mode = Modes.xlsx; enum Modes { xlsx, xlsb } private static readonly string _openXmlInfoString = "http://schemas.openxmlformats.org/spreadsheetml/2006/main"; private static readonly XmlReaderSettings _xmlSettings = new XmlReaderSettings { IgnoreComments = true, IgnoreWhitespace = true, }; private static readonly Dictionary<string, int> _letterToColumnNum = new Dictionary<string, int>(); static XlsxOrXlsbReadOrEdit() { for (int i = 0; i < XlsxWriter._letters.Length; i++) { _letterToColumnNum[XlsxWriter._letters[i]] = i; } } public override void Dispose() { if (_xlsxArchive != null) { _xlsxArchive.Dispose(); } } private void OpenXlsx(string path, bool readSharedStrings = true, bool updateMode = false) { mode = Modes.xlsx; if (updateMode) { _xlsxArchive = new ZipArchive(new FileStream(path, FileMode.Open), ZipArchiveMode.Read | ZipArchiveMode.Update); } else { _xlsxArchive = new ZipArchive(new FileStream(path, FileMode.Open), ZipArchiveMode.Read); } var e1 = _xlsxArchive.GetEntry("xl/workbook.xml"); using (var str = e1.Open()) { using var reader = XmlReader.Create(str); while (reader.Read()) { if (reader.NodeType == XmlNodeType.Whitespace) { continue; } if (reader.Name == "sheet") { string name = reader.GetAttribute("name"); string rId = reader.GetAttribute("r:id"); _worksheetIdToName[rId] = name; _worksheetNameToId[name] = rId; //int.TryParse(reader.GetAttribute("sheetId"), out int sheetId); //_worksheetSheetIdToId[sheetId] = rId; } else if (reader.Name == "pivotCache") { if (_pivotCacheIdtoRid == null) { _pivotCacheIdtoRid = new Dictionary<int, string>(); } if (!int.TryParse(reader.GetAttribute("cacheId"), out int cacheId)) { throw new Exception("getting pivot table cache error"); } string rId = reader.GetAttribute("r:id"); _pivotCacheIdtoRid[cacheId] = rId; } } } _resultCount = _worksheetIdToName.Count; FillRels("xml"); if (_stylesLocation != null) { FillStyles(); } if (readSharedStrings && _sharedStringsLocation != null) { FillSharedStrings(); } } private void OpenXlsb(string path, bool readSharedStrings = true) { mode = Modes.xlsb; _xlsxArchive = new ZipArchive(new FileStream(path, FileMode.Open), ZipArchiveMode.Read); var e1 = _xlsxArchive.GetEntry("xl/workbook.bin"); Stream str; if (UseMemoryStreamInXlsb) { str = GetMemoryStream(e1.Open(), e1.Length); } else { str = new BufferedStream(e1.Open()); } try { using var reader = new BiffReaderWriter(str); while (reader.ReadWorkbook()) { if (reader.isSheet == true) { string name = reader.workbookName; string rId = reader.recId; _worksheetIdToName[rId] = name; _worksheetNameToId[name] = rId; } } } finally { str.Dispose(); } _resultCount = _worksheetIdToName.Count; FillRels("bin"); if (_stylesLocation != null) { FillBinStyles(); } if (readSharedStrings && _sharedStringsLocation != null) { FillBinSharedStrings(); } } /// <summary> /// Initialize file to read (detection xlsx/xlsb by extension) /// </summary> /// <param name="path"></param> /// <param name="readSharedStrings"></param> /// <param name="updateMode"></param> public override void Open(string path, bool readSharedStrings = true, bool updateMode = false, Encoding encoding = null) { if (path.EndsWith("xlsb", StringComparison.OrdinalIgnoreCase)) { mode = Modes.xlsb; OpenXlsb(path, readSharedStrings); } else { mode = Modes.xlsx; OpenXlsx(path); } } private void FillRels(string xmlOrBin) { var e2 = _xlsxArchive.GetEntry($"xl/_rels/workbook.{xmlOrBin}.rels"); using var str = e2.Open(); using var reader = XmlReader.Create(str); while (reader.Read()) { if (reader.NodeType == XmlNodeType.Whitespace) { continue; } if (reader.Name == "Relationship") { string target = reader.GetAttribute("Target"); string type = reader.GetAttribute("Type"); string rId = reader.GetAttribute("Id"); if (type == "http://schemas.openxmlformats.org/officeDocument/2006/relationships/worksheet") { _worksheetIdToLocation[rId] = target; } else if (type == "http://schemas.openxmlformats.org/officeDocument/2006/relationships/pivotCacheDefinition") { if (_pivotCachRidToLocation == null) { _pivotCachRidToLocation = new Dictionary<string, string>(); } _pivotCachRidToLocation[rId] = target; } else if (type == "http://schemas.openxmlformats.org/officeDocument/2006/relationships/sharedStrings") { _sharedStringsLocation = target; } else if (type == "http://schemas.openxmlformats.org/officeDocument/2006/relationships/styles") { _stylesLocation = target; } else if (type == "http://schemas.openxmlformats.org/officeDocument/2006/relationships/theme") { _themeLocation = target; } } } } /// <summary> /// xlsb read strategy, true = More RAM needed but faster /// </summary> public bool UseMemoryStreamInXlsb = true; private static MemoryStream GetMemoryStream(Stream streamToRead, long length) { byte[] byteArray = new byte[length]; int pos = 0; int bytesRead = 0; int toRead = 65_536; while (true) { if (length - bytesRead < toRead) { toRead = (int)length - bytesRead; } pos = streamToRead.Read(byteArray, bytesRead, toRead); bytesRead += pos; if (pos == 0) { break; } } return new MemoryStream(byteArray); } public void FillSharedStrings() { if (_sharedStringsLocation == null) { throw new Exception("no shared strings found"); } var sharedstringsEntry = _xlsxArchive.GetEntry($@"xl/{_sharedStringsLocation}"); Stream str = sharedstringsEntry.Open(); //Stream str = getMemoryStream(sharedstringsEntry.Open(), sharedstringsEntry.Length); try { using var reader = XmlReader.Create(str/*, _xmlSettings*/); reader.Read(); if (reader.IsStartElement("sst", _openXmlInfoString)) { string unqCnt = reader.GetAttribute("uniqueCount"); if (unqCnt != null) { int.TryParse(unqCnt, out _uniqueStringCount); } string cnt = reader.GetAttribute("count"); if (cnt != null) { int.TryParse(cnt, out _stringCount); } } else { throw new Exception("not openXml 2006 format!"); } if (_uniqueStringCount !=-1) { _sharedStringArray = new string[_uniqueStringCount]; } else { _sharedStringArray = new string[1024]; } int stringNum = 0; while (reader.Read()) { if (reader.IsStartElement("si")) { reader.Read(); if (reader.IsStartElement("t")) { string vall = reader.ReadElementContentAsString(); // si -> t-> t -> value //string vall = reader.Value; if (stringNum >= _sharedStringArray.Length) { Array.Resize(ref _sharedStringArray, 2 * _sharedStringArray.Length); } _sharedStringArray[stringNum++] = vall; } } } if (stringNum != _sharedStringArray.Length) { Array.Resize(ref _sharedStringArray, stringNum); } } finally { str.Dispose(); } } public void FillBinSharedStrings() { if (_sharedStringsLocation == null) { throw new Exception("no shared strings found"); } var sharedstringsEntry = _xlsxArchive.GetEntry($@"xl/{_sharedStringsLocation}"); Stream str; if (UseMemoryStreamInXlsb) { str = GetMemoryStream(sharedstringsEntry.Open(), sharedstringsEntry.Length); } else { str = new BufferedStream(sharedstringsEntry.Open()); } try { using var reader = new BiffReaderWriter(str); int stringNum = 0; reader.ReadSharedStrings(); if (_sharedStringArray == null && reader.sharedStringUniqueCount != 0) { _sharedStringArray = new string[reader.sharedStringUniqueCount]; } else { _sharedStringArray = new string[1024]; } while (reader.ReadSharedStrings()) { string vall = reader.sharedStringValue; if (vall != null) { //_sharedStringList.Add(vall); if (stringNum >= _sharedStringArray.Length) { Array.Resize(ref _sharedStringArray, 2 * _sharedStringArray.Length); } _sharedStringArray[stringNum++] = vall; } } if (stringNum != _sharedStringArray.Length) { Array.Resize(ref _sharedStringArray, stringNum); } } finally { str.Dispose(); } } private void FillStyles() { var _stylesCellXfs = new List<StyleInfo>(); var e = _xlsxArchive.GetEntry($"xl/{_stylesLocation}"); using (var str = e.Open()) { using var reader = XmlReader.Create(str); reader.Read(); while (!reader.EOF) { if (reader.IsStartElement("cellXfs")) { reader.Read(); while (!reader.EOF) { if (reader.IsStartElement("xf")) { int.TryParse(reader.GetAttribute("xfId"), out var xfId); int.TryParse(reader.GetAttribute("numFmtId"), out var numFmtId); _stylesCellXfs.Add(new StyleInfo() { XfId = xfId, NumFmtId = numFmtId/*, ApplyNumberFormat = applyNumberFormat*/ }); reader.Skip(); } else { break; } } } else if (reader.IsStartElement("numFmts")) { reader.Read(); while (!reader.EOF) { if (reader.IsStartElement("numFmt")) { string formatCode = reader.GetAttribute("formatCode"); int.TryParse(reader.GetAttribute("numFmtId"), out var numFmtId); if (!_numberFormatsTypeDic.TryGetValue(numFmtId, out var type)) { if (_dateExcelMasks.Contains(formatCode)) { type = typeof(DateTime?); } else { type = typeof(string); } _numberFormatsTypeDic[numFmtId] = type; } else { _numberFormatsTypeDic[numFmtId] = type; } reader.Skip(); } else { break; } } } if (reader.Depth > 0) { reader.Skip(); } else { reader.Read(); } } } _stylesCellXfsArray = _stylesCellXfs.ToArray(); } private void FillBinStyles() { var _stylesCellXfs = new List<StyleInfo>(); var e = _xlsxArchive.GetEntry($"xl/{_stylesLocation}"); using (var str = e.Open()) { bool stylesFirstTime = true; bool formatFirstTime = true; using var reader = new BiffReaderWriter(str); while (reader.ReadStyles()) { if (reader._inCellXf) { if (stylesFirstTime) { reader.ReadStyles(); stylesFirstTime = false; } int numFmtId = reader.NumberFormatIndex; int xfId = reader.ParentCellStyleXf; _stylesCellXfs.Add(new StyleInfo() { XfId = xfId, NumFmtId = numFmtId }); //reader.ReadStyles(); } else if (reader._inNumberFormat) { if (formatFirstTime) { reader.ReadStyles(); formatFirstTime = false; } string formatCode = reader.formatString; int numFmtId = reader.format; if (!_numberFormatsTypeDic.TryGetValue(numFmtId, out var type)) { if (_dateExcelMasks.Contains(formatCode)) { type = typeof(DateTime?); } else { type = typeof(string); } _numberFormatsTypeDic[numFmtId] = type; } //reader.ReadStyles(); } } } _stylesCellXfsArray = _stylesCellXfs.ToArray(); } public override string[] GetScheetNames() { return _worksheetIdToName.Values.ToArray(); } private static readonly char[] _digits = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9' }; private string _actualSheetDimensions = null; Stream sheetStream; XmlReader xmlReader; BiffReaderWriter biffReader; ZipArchiveEntry sheetEntry; int prevRowNum = -1; bool isFirstRow = true; int columnsCntFromFirstRow = -1; int minColNum = -1; int maxColNum = -1; int collDif = 0; int colNum = -1; int prevColNum = -1; int howManyEmptyRow = -1; int emptyRowCnt = -1; bool success = false; int len = 0; int rowNum = 0; bool returnValue = true; void sheetPreInitialize() { prevRowNum = -1; //isFirstRow = true; columnsCntFromFirstRow = -1; minColNum = -1; maxColNum = -1; collDif = 0; colNum = -1; prevColNum = -1; howManyEmptyRow = -1; emptyRowCnt = -1; success = false; len = 0; rowNum = 0; returnValue = true; innerRow = new FieldInfo[4096]; sheetEntry = GetArchiverEntry(ActualSheetName); } private void initSheetXlsxReader() { sheetPreInitialize(); //sheetStream = sheetEntry.Open(); sheetStream = new BufferedStream(sheetEntry.Open(), 65_536); xmlReader = XmlReader.Create(sheetStream, _xmlSettings); xmlReader.Read(); while (!xmlReader.EOF) { if (xmlReader.IsStartElement("sheetData")) { prevRowNum = -1; return; } else if (xmlReader.IsStartElement("dimension")) { _actualSheetDimensions = xmlReader.GetAttribute("ref"); xmlReader.Skip(); } else if (xmlReader.Depth == 0) { xmlReader.Read(); } else { xmlReader.Skip(); } } } private bool ReadXlsx() { if (isFirstRow) { initSheetXlsxReader(); } if (emptyRowCnt < howManyEmptyRow) { emptyRowCnt++; prevRowNum++; return true; } if (emptyRowCnt == -1) { if (!xmlReader!.ReadToFollowing("row")) { xmlReader.Dispose(); sheetStream.Dispose(); isFirstRow = true; // RESET return false; } success = xmlReader.MoveToAttribute("r"); len = xmlReader.ReadValueChunk(_buffer, 0, _buffer.Length); rowNum = ParseToUnsignedIntFromBuffer(_buffer, len); } howManyEmptyRow = -1; emptyRowCnt = -1; //empty row/s if (prevRowNum != -1 && rowNum > prevRowNum + 1) { for (int i = 0; i < columnsCntFromFirstRow; i++) { innerRow[i].type = ExcelDataType.Null; } howManyEmptyRow = rowNum - prevRowNum - 1; prevRowNum++; emptyRowCnt = 1; return true; } prevRowNum = rowNum; while (xmlReader.Read() && xmlReader.IsStartElement("c")) { //reader.MoveToAttribute("r"); xmlReader.MoveToNextAttribute(); len = xmlReader.ReadValueChunk(_buffer, 0, _buffer.Length); colNum = -1; //Sylvan for (int j = 0; j < len; j++) { char c = _buffer[j]; if (c < 'A' || c > 'Z') { break; } int v = c - 'A'; if ((uint)v < 26u) { colNum = ((colNum + 1) * 26) + v; } } colNum++; if (isFirstRow && minColNum == -1) { minColNum = colNum; collDif = minColNum - 1; } if (isFirstRow && maxColNum < colNum) { maxColNum = colNum; } ref FieldInfo valueX = ref innerRow[colNum - 1 - collDif]; bool isEmptyElement = xmlReader.IsEmptyElement; if (!isEmptyElement) { char sstMark = '\0'; int sstLen = 0; int styleId = -1; success = xmlReader.MoveToNextAttribute(); if (success && xmlReader.Name == "s") { len = xmlReader.ReadValueChunk(_buffer, 0, _buffer.Length); styleId = ParseToUnsignedIntFromBuffer(_buffer, len); success = xmlReader.MoveToNextAttribute(); } if (success && xmlReader.Name == "t") { sstLen = xmlReader.ReadValueChunk(_buffer, 0, _buffer.Length); sstMark = _buffer[0]; } xmlReader.MoveToElement(); //bool success = false; if (sstMark == 'i' && sstLen == 9) { //success = xmlReader.ReadToDescendant("is"); xmlReader.Read(); xmlReader.Read(); valueX.type = ExcelDataType.String; valueX.strValue = xmlReader.ReadContentAsString(); } else if (xmlReader.ReadToDescendant("v")) { xmlReader.Read(); if (sstMark == 's' && sstLen == 1) // 's' = string/sharedstring'b' = boolean, 'e' = error { len = xmlReader.ReadValueChunk(_buffer, 0, _buffer.Length); valueX.type = ExcelDataType.String; valueX.strValue = _sharedStringArray[ParseToUnsignedIntFromBuffer(_buffer, len)]; } else if (sstMark == 's' || sstMark == 'i' && sstLen == 9) // InlineStr? { if (xmlReader.NodeType != XmlNodeType.EndElement || xmlReader.Name != "c") { //if (xmlReader.NodeType != XmlNodeType.Text) //{ // xmlReader.Read(); //} valueX.type = ExcelDataType.String; valueX.strValue = xmlReader.ReadContentAsString(); } else { valueX.type = ExcelDataType.Null; } //valueX = _buffer.AsSpan(0, len).ToString(); } else { len = xmlReader.ReadValueChunk(_buffer, 0, _buffer.Length); if (sstMark == 'b') // 'b' = boolean, 'e' = error { valueX.type = ExcelDataType.Boolean; valueX.int64Value = (_buffer[0] - '0'); } else if (sstMark == 'e') // 'b' = boolean, 'e' = error { valueX.type = ExcelDataType.String; valueX.strValue = "error in cell"; } else if (styleId != -1) { var s = _stylesCellXfsArray[styleId]; int numFormatId = s.NumFmtId; if (_numberFormatsTypeDic.TryGetValue(numFormatId, out Type type) && type == typeof(DateTime?) && double.TryParse(_buffer.AsSpan(0, len), NumberStyles.Any, provider: invariantCultureInfo, out double doubleDate) ) { valueX.type = ExcelDataType.DateTime; valueX.dtValue = DateTime.FromOADate(doubleDate); } else { if (ContainsDoubleMarks(_buffer, len)) { valueX.type = ExcelDataType.Double; valueX.doubleValue = double.Parse(_buffer.AsSpan(0, len), provider: invariantCultureInfo); } else { valueX.type = ExcelDataType.Int64; valueX.int64Value = ParseToInt64FromBuffer(_buffer, len); } } } else { if (ContainsDoubleMarks(_buffer, len)) { valueX.type = ExcelDataType.Double; valueX.doubleValue = double.Parse(_buffer.AsSpan(0, len), provider: invariantCultureInfo); } else { valueX.type = ExcelDataType.Int64; valueX.int64Value = ParseToInt64FromBuffer(_buffer, len); } } } } else { valueX.type = ExcelDataType.Null; } } if (prevColNum >= colNum && colNum > minColNum) { for (int i = minColNum; i < colNum; i++) { innerRow[i - 1 - collDif].type = ExcelDataType.Null; } } else if (colNum - prevColNum > 1 && prevColNum != -1) { for (int i = 0; i < colNum - prevColNum - collDif - 1; i++) { innerRow[prevColNum - collDif + i].type = ExcelDataType.Null; } } prevColNum = colNum; if (!isEmptyElement) // depth = ... { while (xmlReader.Depth > 3) { //reader.Skip(); xmlReader.Read(); } } } if (isFirstRow) { isFirstRow = false; columnsCntFromFirstRow = maxColNum - minColNum + 1; Array.Resize<FieldInfo>(ref innerRow, columnsCntFromFirstRow); FieldCount = columnsCntFromFirstRow; } if (colNum < maxColNum) { for (int i = colNum; i < maxColNum; i++) { innerRow[i - collDif].type = ExcelDataType.Null; } } return true; } private void initSheetXlsbReader() { sheetPreInitialize(); if (UseMemoryStreamInXlsb) { sheetStream = GetMemoryStream(sheetEntry.Open(), sheetEntry.Length); } else { sheetStream = new BufferedStream(sheetEntry.Open()); } biffReader = new BiffReaderWriter(sheetStream); while (!biffReader.readCell) //read to cell { biffReader.ReadWorksheet(); } //prevColNum = colNum; rowNum = biffReader.rowIndex; colNum = biffReader.columnNum; } private bool ReadXlsb() { //fist time = initialize if (isFirstRow) { initSheetXlsbReader(); } //last row is not complete if (!isFirstRow && colNum > minColNum) { for (int i = minColNum; i < colNum; i++) { innerRow[i - minColNum].type = ExcelDataType.Null; } } //previous read = false if (!returnValue) { biffReader.Dispose(); sheetStream.Dispose(); isFirstRow = true; // RESET return false; } //missing rows if (prevRowNum != -1 && rowNum > prevRowNum + 1) { for (int i = 0; i < columnsCntFromFirstRow; i++) { innerRow[i].type = ExcelDataType.Null; } howManyEmptyRow = rowNum - prevRowNum - 1; prevRowNum++; emptyRowCnt = 1; return true; } prevRowNum = rowNum; while (rowNum == prevRowNum && returnValue) { if (biffReader.readCell) { //determine first row length if (isFirstRow) { if (minColNum == -1) { minColNum = colNum; } maxColNum = colNum; columnsCntFromFirstRow = maxColNum - minColNum + 1; FieldCount = columnsCntFromFirstRow; } ref FieldInfo valueX = ref innerRow[colNum - minColNum]; valueX.type = ExcelDataType.String; switch (biffReader.cellType) { case CellType.sharedString: valueX.type = ExcelDataType.String; valueX.strValue = _sharedStringArray[biffReader.intValue]; break; case CellType.stringVal: valueX.type = ExcelDataType.String; valueX.strValue = biffReader.stringValue; break; case CellType.boolVal: valueX.type = ExcelDataType.Boolean; valueX.int64Value = biffReader.boolValue ? 1 : 0; break; case CellType.doubleVal: { double doubleVal = biffReader.doubleVal; var styleIndex = biffReader.xfIndex; if (styleIndex == 0) // general { SetValueForXlsb(doubleVal, ref valueX); } else { int numFormatId = _stylesCellXfsArray[styleIndex].NumFmtId; if (_numberFormatsTypeDic.TryGetValue(numFormatId, out Type type) && type == typeof(DateTime?)) { valueX.type = ExcelDataType.DateTime; valueX.dtValue = DateTime.FromOADate((double)doubleVal); } else { SetValueForXlsb(doubleVal, ref valueX); } } break; } default: valueX.type = ExcelDataType.Null; break; } } biffReader.ReadWorksheet(); while (returnValue && !biffReader.readCell) { returnValue = biffReader.ReadWorksheet(); } prevColNum = colNum; rowNum = biffReader.rowIndex; colNum = biffReader.columnNum; if (!isFirstRow) { if (colNum > prevColNum + 1 && rowNum == prevRowNum) { for (int i = prevColNum + 1; i < colNum; i++) { innerRow[i - minColNum].type = ExcelDataType.Null; } } else if (rowNum > prevRowNum && prevColNum < maxColNum) { for (int i = 1; i <= maxColNum - prevColNum; i++) { innerRow[prevColNum + i - minColNum].type = ExcelDataType.Null; } } } } if (isFirstRow) { isFirstRow = false; Array.Resize(ref innerRow, columnsCntFromFirstRow); } return true; } public override bool Read() { if (mode == Modes.xlsx) { return ReadXlsx(); } else { return ReadXlsb(); } } //inspired by https://github.com/MarkPflug/Sylvan.Data.Excel private readonly static char[] _buffer = new char[64]; private static int ParseToUnsignedIntFromBuffer(char[] buff, int len) { int res = 0; for (int i = 0; i < len; i++) { res = res * 10 + (buff[i] - '0'); } return res; } private static Int64 ParseToInt64FromBuffer(char[] buff, int len) { Int64 res = 0; int start = buff[0] == '-' ? 1 : 0; for (int i = start; i < len; i++) { res = res * 10 + (buff[i] - '0'); } return start == 1 ? -res : res; } private static bool ContainsDoubleMarks(char[] buff, int len) { for (int i = 0; i < len; i++) { char c = buff[i]; if (c == '.' || c == 'E') { return true; } } return false; } public IEnumerable<object[]> GetRowsOfXlsx(string sheetName) { ActualSheetName = sheetName; Read(); object[] row = new object[FieldCount]; GetValues(row); yield return row; while (ReadXlsx()) { GetValues(row); yield return row; } } public IEnumerable<object[]> GetRowsOfXlsb(string sheetName) { ActualSheetName = sheetName; Read(); object[] row = new object[FieldCount]; GetValues(row); yield return row; while (ReadXlsb()) { GetValues(row); yield return row; } } public IEnumerable<object[]> GetRowsOfSheet(string sheetName) { if (mode == Modes.xlsx) { return GetRowsOfXlsx(sheetName); } else { return GetRowsOfXlsb(sheetName); } } private ZipArchiveEntry GetArchiverEntry(string sheetName) { string id = _worksheetNameToId[sheetName]; string location = _worksheetIdToLocation[id]; return _xlsxArchive.GetEntry($"xl/{location}"); } private static (int row, int column) GetNumbersFromAdress(string startingCellAdress) { int n1 = startingCellAdress.IndexOfAny(_digits); string letters = startingCellAdress.Substring(0, n1); int rowNumFromAdress = int.Parse(startingCellAdress.Substring(n1)); int colNumFromAdress = _letterToColumnNum[letters] + 1; return (rowNumFromAdress - 1, colNumFromAdress - 1); } /// <summary> /// clear and fill existing tab with dataReader /// </summary> /// <param name="sheetName"></param> /// <param name="reader"></param> /// <param name="startingCellAdress"></param> /// <returns></returns> public string ReplaceSheetData(string sheetName, IDataReader reader, string startingCellAdress = "A1") { if (!_worksheetNameToId.TryGetValue(sheetName, out string id)) { throw new Exception($"ReplaceSheetData - {sheetName} not found"); } string location = _worksheetIdToLocation[id]; var sheetEntryToReplace = _xlsxArchive.GetEntry($"xl/{location}"); sheetEntryToReplace.Delete(); (int startingRow, int startingColumn) = GetNumbersFromAdress(startingCellAdress); int _dateStyleNum = 0; for (int i = 0; i < _stylesCellXfsArray.Length; i++) { var item = _stylesCellXfsArray[i]; int numFormatId = item.NumFmtId; if (_numberFormatsTypeDic.TryGetValue(numFormatId, out Type type) && type == typeof(DateTime?)) { _dateStyleNum = i; break; } } string excelRangeString = ""; var newData = _xlsxArchive.CreateEntry($"xl/{location}"); using (StreamWriter sheetData = new FormattingStreamWriter(newData.Open(), Encoding.UTF8, CultureInfo.InvariantCulture.NumberFormat)) { int cnt = XlsxWriter.WriteToExisting(sheetData, reader, dateStyleNum: _dateStyleNum, dateTimeStyleNum: _dateStyleNum, startingRow, startingColumn); string start = XlsxWriter._letters[startingColumn] + (startingRow + 1).ToString(); string end = XlsxWriter._letters[startingColumn + reader.FieldCount - 1] + (startingRow + 1 + cnt).ToString(); excelRangeString = start + ":" + end; } return excelRangeString; } private List<string> GetPivotTableList() { List<string> pivotTableList = new List<string>(); var e = _xlsxArchive.GetEntry("[Content_Types].xml"); using (var str = e.Open()) { using var reader = XmlReader.Create(str); while (reader.Read()) { if (reader.Name == "Override") { string nm = reader.GetAttribute("ContentType"); if (nm == "application/vnd.openxmlformats-officedocument.spreadsheetml.pivotTable+xml") { pivotTableList.Add(reader.GetAttribute("PartName")); } } } } return pivotTableList; } private int GetCacheIdForPivotTable(string pivotTableName, List<string> pivotTableList) { int cacheId = -1; foreach (var pivotTableLocation in pivotTableList) { var e1 = _xlsxArchive.GetEntry(pivotTableLocation[1..]); using var str = e1.Open(); using var reader = XmlReader.Create(str); while (reader.Read()) { if (reader.IsStartElement("pivotTableDefinition")) { string name = reader.GetAttribute("name"); if (name == pivotTableName) { int.TryParse(reader.GetAttribute("cacheId"), out cacheId); break; } } } } return cacheId; } /// <summary> /// changes data reference for pivot table, use with ReplaceSheetData /// </summary> /// <param name="pivotTableName">name of pivot table</param> /// <param name="referention">new reference</param> /// <param name="doRefreshOnLoad">refresh pivot table on open</param> public void ReplacePivotTableDim(string pivotTableName, string referention, bool doRefreshOnLoad = true) { var pivotTableList = GetPivotTableList(); int cacheId = GetCacheIdForPivotTable(pivotTableName, pivotTableList); if (cacheId == -1) { throw new Exception($"{pivotTableName} - not found"); } string rId = _pivotCacheIdtoRid[cacheId]; string tableCacheLocation = _pivotCachRidToLocation[rId]; var pivotCacheEntry = _xlsxArchive.GetEntry("xl/" + tableCacheLocation); bool addRefreshOnLoad = false; bool replaceRefresh = false; string reff = null; string pivotTableXmlAsPlainTxt = null; using (var str = pivotCacheEntry.Open()) { using var reader = XmlReader.Create(str); while (reader.Read()) { if (reader.IsStartElement("pivotCacheDefinition")) { string refreshOnLoad = reader.GetAttribute("refreshOnLoad"); if (refreshOnLoad == null) { addRefreshOnLoad = true; } else if (refreshOnLoad == "0") { replaceRefresh = true; } } else if (reader.IsStartElement("cacheSource")) { do { reader.Read(); } while (!reader.IsStartElement("worksheetSource")); reff = reader.GetAttribute("ref"); break; } } } if (reff != null) { using var str = pivotCacheEntry.Open(); using var reader = new StreamReader(str); pivotTableXmlAsPlainTxt = reader.ReadToEnd(); } pivotCacheEntry.Delete(); int firsPartIndex = pivotTableXmlAsPlainTxt.IndexOf(@"</cacheSource>"); string firsPartTxt = pivotTableXmlAsPlainTxt[0..firsPartIndex]; var ent = _xlsxArchive.CreateEntry("xl/" + tableCacheLocation); using (var str = ent.Open()) { using var sw = new StreamWriter(str); if (doRefreshOnLoad && addRefreshOnLoad) { firsPartTxt = firsPartTxt.Replace(" r:id=", " refreshOnLoad=\"1\" r:id="); } else if (doRefreshOnLoad && replaceRefresh) { firsPartTxt = firsPartTxt.Replace("refreshOnLoad=\"0\" r:id=", "refreshOnLoad=\"1\" r:id="); } firsPartTxt = firsPartTxt.Replace($"ref=\"{reff}\"", $"ref=\"{referention}\""); sw.Write(firsPartTxt); sw.Write(pivotTableXmlAsPlainTxt.AsSpan().Slice(firsPartIndex)); } } private string _actualSheetName; public override string ActualSheetName { get => _actualSheetName; set { _rowCount = -2; _actualSheetName = value; } } private int _resultCount = -1; public override int ResultsCount { get => _resultCount; } private string Name { get => ActualSheetName; } private int _rowCount = -2; /// <summary> /// row count (not always available) /// </summary> public override int RowCount { get => _rowCount != -2 ? _rowCount : PrepareRowCnt(); } private int PrepareRowCnt() { _rowCount = -1; if (_actualSheetDimensions == null) { _rowCount = 123123123; return _rowCount; } int i1 = _actualSheetDimensions.IndexOf(":"); string t1 = _actualSheetDimensions[..i1]; int i2 = t1.IndexOfAny(_digits); int.TryParse(t1[i2..], out int start); t1 = _actualSheetDimensions[(i1 + 1)..]; i2 = t1.IndexOfAny(_digits); int.TryParse(t1[i2..], out int end); _rowCount = end - start; // header is not row !! return _rowCount; } private void SetValueForXlsb(double rawValue, ref FieldInfo fieldInfo) { long l1 = Convert.ToInt64(rawValue); double res = l1 - /*(double)*/rawValue; if (res < 3 * double.Epsilon && res > -3 * double.Epsilon) { fieldInfo.type = ExcelDataType.Int64; fieldInfo.int64Value = l1; } else { fieldInfo.type = ExcelDataType.Double; fieldInfo.doubleValue = rawValue; } } } }
36.233146
163
0.421758
[ "MIT" ]
KrzysztofDusko/SpreadSheetTasks
source/SpreadSheetTasks/XlsxOrXlsbReadOrEdit.cs
51,598
C#
/* ------------------------------------------------------------------------------ This source file is a part of SparqlHelper. Copyright (c) 2015 VIS/University of Stuttgart 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 SparqlHelper.Expressions; namespace SparqlHelper.InlineData { public sealed class ValuesLiteral : ValuesValue { public ValuesLiteral(LiteralExpression literal) { if (literal == null) { throw new ArgumentNullException("literal"); } this.literal = literal; } private readonly LiteralExpression literal; public override string ToSparqlString(SparqlHelper.SparqlConversion.SparqlSettings settings) { return literal.ToSparqlString(settings); } } }
36.078431
95
0.694565
[ "MIT" ]
RDF-Utilities-dotnet/SparqlHelper
src/SparqlHelper/InlineData/ValuesLiteral.cs
1,842
C#
// Copyright © Tanner Gooding and Contributors. Licensed under the MIT License (MIT). See License.md in the repository root for more information. // Ported from shared/Iprtrmib.h in the Windows SDK for Windows 10.0.20348.0 // Original source is Copyright © Microsoft. All rights reserved. namespace TerraFX.Interop { public partial struct MIB_BEST_IF { [NativeTypeName("DWORD")] public uint dwDestAddr; [NativeTypeName("DWORD")] public uint dwIfIndex; } }
29.588235
145
0.705765
[ "MIT" ]
DaZombieKiller/terrafx.interop.windows
sources/Interop/Windows/shared/Iprtrmib/MIB_BEST_IF.cs
505
C#
// Copyright (c) 2015, Outercurve Foundation. // All rights reserved. // // Redistribution and use in source and binary forms, with or without modification, // are permitted provided that the following conditions are met: // // - Redistributions of source code must retain the above copyright notice, this // list of conditions and the following disclaimer. // // - Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // - Neither the name of the Outercurve Foundation nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND // ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED // WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE // DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR // ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES // (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; // LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON // ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS // SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. using System; using System.Diagnostics; using System.IO; using System.Collections.Generic; using System.Text; using System.Reflection; using System.Security.Principal; using Microsoft.Win32; using WebsitePanel.Providers.OS; using WebsitePanel.Providers.Utils; using WebsitePanel.Server.Utils; using Microsoft.SharePoint; using Microsoft.SharePoint.Utilities; using Microsoft.SharePoint.Administration; namespace WebsitePanel.Providers.SharePoint { public class Sps30Remote : MarshalByRefObject { public void ExtendVirtualServer(SharePointSite site, bool exclusiveNTLM) { try { WindowsImpersonationContext wic = WindowsIdentity.GetCurrent().Impersonate(); string siteUrl = "http://" + site.Name; // check input parameters if (String.IsNullOrEmpty(site.RootFolder) || !Directory.Exists(site.RootFolder)) throw new Exception("Could not create SharePoint site, because web site root folder does not exist. Open web site properties and click \"Update\" button to re-create site folder."); SPWebApplication app = SPWebApplication.Lookup(new Uri(siteUrl)); if (app != null) throw new Exception("SharePoint is already installed on this web site."); //SPFarm farm = SPFarm.Local; SPFarm farm = SPFarm.Local; SPWebApplicationBuilder builder = new SPWebApplicationBuilder(farm); builder.ApplicationPoolId = site.ApplicationPool; builder.DatabaseServer = site.DatabaseServer; builder.DatabaseName = site.DatabaseName; builder.DatabaseUsername = site.DatabaseUser; builder.DatabasePassword = site.DatabasePassword; builder.ServerComment = site.Name; builder.HostHeader = site.Name; builder.Port = 80; builder.RootDirectory = new DirectoryInfo(site.RootFolder); builder.DefaultZoneUri = new Uri(siteUrl); builder.UseNTLMExclusively = exclusiveNTLM; app = builder.Create(); app.Name = site.Name; app.Sites.Add(siteUrl, null, null, (uint)site.LocaleID, null, site.OwnerLogin, null, site.OwnerEmail); app.Update(); app.Provision(); wic.Undo(); } catch (Exception ex) { try { // try to delete app if it was created SPWebApplication app = SPWebApplication.Lookup(new Uri("http://" + site.Name)); if (app != null) app.Delete(); } catch { /* nop */ } throw new Exception("Error creating SharePoint site", ex); } } public void UnextendVirtualServer(string url, bool deleteContent) { try { WindowsImpersonationContext wic = WindowsIdentity.GetCurrent().Impersonate(); Uri uri = new Uri("http://" + url); SPWebApplication app = SPWebApplication.Lookup(uri); if (app == null) return; SPGlobalAdmin adm = new SPGlobalAdmin(); adm.UnextendVirtualServer(uri, false); //typeof(SPWebApplication).InvokeMember("UnprovisionIisWebSitesAsAdministrator", // BindingFlags.Static | BindingFlags.NonPublic | BindingFlags.InvokeMethod, // null, null, new object[] { false, new string[] { url }, app.ApplicationPool }); //app.Unprovision(); app.Delete(); wic.Undo(); } catch (Exception ex) { throw new Exception("Could not uninstall SharePoint from the web site", ex); } } public string BackupVirtualServer(string url, string fileName, bool zipBackup) { try { WindowsImpersonationContext wic = WindowsIdentity.GetCurrent().Impersonate(); string tempPath = Path.GetTempPath(); string bakFile = Path.Combine(tempPath, (zipBackup ? StringUtils.CleanIdentifier(url) + ".bsh" : StringUtils.CleanIdentifier(fileName))); SPWebApplication app = SPWebApplication.Lookup(new Uri("http://" + url)); if (app == null) throw new Exception("SharePoint is not installed on the web site"); // backup app.Sites.Backup("http://" + url, bakFile, true); // zip backup file if (zipBackup) { string zipFile = Path.Combine(tempPath, fileName); string zipRoot = Path.GetDirectoryName(bakFile); // zip files FileUtils.ZipFiles(zipFile, zipRoot, new string[] { Path.GetFileName(bakFile) }); // delete data files FileUtils.DeleteFile(bakFile); bakFile = zipFile; } wic.Undo(); return bakFile; } catch (Exception ex) { throw new Exception("Could not backup SharePoint site", ex); } } public void RestoreVirtualServer(string url, string fileName) { try { WindowsImpersonationContext wic = WindowsIdentity.GetCurrent().Impersonate(); SPWebApplication app = SPWebApplication.Lookup(new Uri("http://" + url)); if (app == null) throw new Exception("SharePoint is not installed on the web site"); string tempPath = Path.GetTempPath(); // unzip uploaded files if required string expandedFile = fileName; if (Path.GetExtension(fileName).ToLower() == ".zip") { // unpack file expandedFile = FileUtils.UnzipFiles(fileName, tempPath)[0]; // delete zip archive FileUtils.DeleteFile(fileName); } // delete site SPSiteAdministration site = new SPSiteAdministration("http://" + url); site.Delete(false); // restore from backup app.Sites.Restore("http://" + url, expandedFile, true); // delete expanded file FileUtils.DeleteFile(expandedFile); wic.Undo(); } catch (Exception ex) { throw new Exception("Could not restore SharePoint site", ex); } } public string[] GetInstalledWebParts(string url) { try { WindowsImpersonationContext wic = WindowsIdentity.GetCurrent().Impersonate(); SPGlobalAdmin adm = new SPGlobalAdmin(); string lines = adm.EnumWPPacks(null, "http://" + url, false); List<string> list = new List<string>(); if(!String.IsNullOrEmpty(lines)) { string line = null; StringReader reader = new StringReader(lines); while ((line = reader.ReadLine()) != null) { line = line.Trim(); int commaIdx = line.IndexOf(","); if (!String.IsNullOrEmpty(line) && commaIdx != -1) list.Add(line.Substring(0, commaIdx)); } } wic.Undo(); return list.ToArray(); } catch (Exception ex) { throw new Exception("Error reading web parts packages", ex); } } public void InstallWebPartsPackage(string url, string fileName) { try { WindowsImpersonationContext wic = WindowsIdentity.GetCurrent().Impersonate(); string tempPath = Path.GetTempPath(); // unzip uploaded files if required string expandedFile = fileName; if (Path.GetExtension(fileName).ToLower() == ".zip") { // unpack file expandedFile = FileUtils.UnzipFiles(fileName, tempPath)[0]; // delete zip archive FileUtils.DeleteFile(fileName); } StringWriter errors = new StringWriter(); SPGlobalAdmin adm = new SPGlobalAdmin(); int result = adm.AddWPPack(expandedFile, null, 0, "http://" + url, false, true, errors); if (result > 1) throw new Exception("Error installing web parts package: " + errors.ToString()); // delete expanded file FileUtils.DeleteFile(expandedFile); wic.Undo(); } catch (Exception ex) { throw new Exception("Could not install web parts package", ex); } } public void DeleteWebPartsPackage(string url, string packageName) { try { WindowsImpersonationContext wic = WindowsIdentity.GetCurrent().Impersonate(); StringWriter errors = new StringWriter(); SPGlobalAdmin adm = new SPGlobalAdmin(); int result = adm.RemoveWPPack(packageName, 0, "http://" + url, errors); if (result > 1) throw new Exception("Error uninstalling web parts package: " + errors.ToString()); wic.Undo(); } catch (Exception ex) { throw new Exception("Could not uninstall web parts package", ex); } } } }
31.085714
187
0.664522
[ "BSD-3-Clause" ]
9192939495969798/Websitepanel
WebsitePanel/Sources/WebsitePanel.Providers.SharePoint.Sps30/Sps30Remote.cs
9,792
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.Linq; using Windows.UI.Xaml; using Windows.UI.Xaml.Data; namespace Microsoft.Toolkit.Uwp.SampleApp.Common { public class ThicknessConverter : IValueConverter { public object Convert(object value, Type targetType, object parameter, string language) { if (value is string) { return value; } var thickness = (Thickness)value; return thickness.ToString(); } public object ConvertBack(object value, Type targetType, object parameter, string language) { if (value is string thicknessString) { var thicknessTokens = thicknessString.Split(',') .Where(tkn => !string.IsNullOrWhiteSpace(tkn)) .ToArray(); switch (thicknessTokens.Length) { case 1: var thicknessValue = double.Parse(thicknessString); return new Thickness { Left = thicknessValue, Top = thicknessValue, Right = thicknessValue, Bottom = thicknessValue }; case 2: var thicknessHorizontalValue = double.Parse(thicknessTokens[0]); var thicknessVerticalValue = double.Parse(thicknessTokens[1]); return new Thickness { Left = thicknessHorizontalValue, Top = thicknessVerticalValue, Right = thicknessHorizontalValue, Bottom = thicknessVerticalValue }; case 4: return new Thickness { Left = double.Parse(thicknessTokens[0]), Top = double.Parse(thicknessTokens[1]), Right = double.Parse(thicknessTokens[2]), Bottom = double.Parse(thicknessTokens[3]) }; default: return default(Thickness); } } return value.ToString(); } } }
37.333333
99
0.463914
[ "MIT" ]
14632791/WindowsCommunityToolkit
Microsoft.Toolkit.Uwp.SampleApp/Common/ThicknessConverter.cs
2,688
C#
using System; using System.Collections.Generic; using System.Text; namespace ProjectEvent.Core.Action.Types { public enum IFActionConditionType { /// <summary> /// 等于 /// </summary> Equal = 1, /// <summary> /// 不等于 /// </summary> UnEqual = 2, /// <summary> /// 包含 /// </summary> Has = 3, /// <summary> /// 不包含 /// </summary> Miss = 4, /// <summary> /// 大于 /// </summary> Greater = 5, /// <summary> /// 小于 /// </summary> Less = 6, /// <summary> /// 大于或等于 /// </summary> GreaterOrEqual = 7, /// <summary> /// 小于或等于 /// </summary> LessOrEqual = 8, } }
19.046512
40
0.391941
[ "MIT" ]
Planshit/ProjectEvent
src/ProjectEvent.Core/Action/Types/IFActionConditionType.cs
869
C#
using System; using System.Threading.Tasks; using Windows.Networking; using Windows.Networking.Sockets; using Windows.Storage.Streams; namespace InteropTools.RemoteClasses.Client { internal class RemoteClient { private DataReader _reader; private StreamSocket _socket; private DataWriter _writer; public RemoteClient(string ip, int port) { Ip = ip; Port = port; } private string Ip { get; } private int Port { get; } public async Task<string> GetData(string message) { try { var hostName = new HostName(Ip); _socket = new StreamSocket(); try { await _socket.ConnectAsync(hostName, Port.ToString()); _writer = new DataWriter(_socket.OutputStream); _writer.WriteUInt32(_writer.MeasureString(message)); _writer.WriteString(message); try { await _writer.StoreAsync(); await _writer.FlushAsync(); } catch { return null; } _reader = new DataReader(_socket.InputStream); try { var sizeFieldCount = await _reader.LoadAsync(sizeof(uint)); if (sizeFieldCount != sizeof(uint)) { return null; } var stringLength = _reader.ReadUInt32(); var actualStringLength = await _reader.LoadAsync(stringLength); return stringLength != actualStringLength ? null : _reader.ReadString(actualStringLength); } catch { return null; } } catch { return null; } } catch { return null; } } public void Close() { try { _writer.DetachStream(); _writer.Dispose(); _reader.DetachStream(); _reader.Dispose(); _socket.Dispose(); } catch { // ignored } } } }
17.3
96
0.624855
[ "MIT" ]
mediaexplorer74/InteropTools
UI/InteropTools/RemoteClasses/Client/RemoteClient.cs
1,732
C#
using Dapper; using Discount.Grpc.Entities; using Npgsql; namespace Discount.Grpc.Repositories { public class DiscountRepository : IDiscountRepository { private readonly IConfiguration _configuration; public DiscountRepository(IConfiguration configuration) { _configuration = configuration ?? throw new ArgumentNullException(nameof(configuration)); } public async Task<Coupon> GetDiscount(string productName) { using var connection = new NpgsqlConnection (_configuration.GetValue<string>("DatabaseSettings:ConnectionString")); var coupon = await connection.QueryFirstOrDefaultAsync<Coupon> ("SELECT * FROM Coupon WHERE ProductName = @ProductName", new { ProductName = productName }); if (coupon == null) return new Coupon { ProductName = "No Discount", Amount = 0, Description = "No Discount Desc" }; return coupon; } public async Task<bool> CreateDiscount(Coupon coupon) { using var connection = new NpgsqlConnection (_configuration.GetValue<string>("DatabaseSettings:ConnectionString")); var affected = await connection.ExecuteAsync ("INSERT INTO Coupon (ProductName, Description, Amount) VALUES (@ProductName, @Description, @Amount)", new { ProductName = coupon.ProductName, Description = coupon.Description, Amount = coupon.Amount }); if (affected == 0) return false; return true; } public async Task<bool> UpdateDiscount(Coupon coupon) { using var connection = new NpgsqlConnection(_configuration.GetValue<string>("DatabaseSettings:ConnectionString")); var affected = await connection.ExecuteAsync ("UPDATE Coupon SET ProductName=@ProductName, Description = @Description, Amount = @Amount WHERE Id = @Id", new { ProductName = coupon.ProductName, Description = coupon.Description, Amount = coupon.Amount, Id = coupon.Id }); if (affected == 0) return false; return true; } public async Task<bool> DeleteDiscount(string productName) { using var connection = new NpgsqlConnection(_configuration.GetValue<string>("DatabaseSettings:ConnectionString")); var affected = await connection.ExecuteAsync("DELETE FROM Coupon WHERE ProductName = @ProductName", new { ProductName = productName }); if (affected == 0) return false; return true; } } }
36.786667
144
0.611816
[ "MIT" ]
PrashantMaheshwari-SoftwareEngineer/AspnetMicroservices
src/Services/Discount/Discount.Grpc/Repositories/DiscountRepository.cs
2,761
C#
using System; using System.Collections.Generic; using System.Drawing; using System.Text; using System.Windows.Forms; using System.Reflection; namespace HolidayTest1 { public partial class AboutForm : Form { public AboutForm() { InitializeComponent(); String version = AssemblyVersion; richTextBox1.Rtf = "{\\rtf1\\ansi\\ansicpg1252\\deff0\\deflang3081\\deflangfe3081{\\fonttbl{\\f0\\froman\\fprq2\\fcharset0 Times New Roman;}{\\f1\\fswiss\\fprq2\\fcharset0 Calibri;}}\r\n" + "{\\colortbl ;\\red0\\green0\\blue255;}\r\n" + "{\\*\\generator Msftedit 5.41.21.2510;}\\viewkind4\\uc1\\pard\\qc\\lang9\\f0\\fs22\\par\r\n" + "\\b\\f1 MooresCloud Holiday Test Program\\par\r\n" + "\\b0 Version " + version + " \\par\r\n" + "\\par\r\n" + "Developed for MooresCloud\\par\r\n" + "by Kean Electronics\\par\r\n" + "{\\field{\\*\\fldinst{HYPERLINK \"www.kean.com.au\"}}{\\fldrslt{\\ul\\cf1 www.kean.com.au}}}\\f0\\fs22\\par\r\n" + "\\par\r\n" + "\\f1 (c) MooresCloud Pty Ltd 2013\\f0\\par\r\n" + "}"; } #region Assembly Attribute Accessors public string AssemblyTitle { get { object[] attributes = Assembly.GetExecutingAssembly().GetCustomAttributes(typeof(AssemblyTitleAttribute), false); if (attributes.Length > 0) { AssemblyTitleAttribute titleAttribute = (AssemblyTitleAttribute)attributes[0]; if (titleAttribute.Title != "") { return titleAttribute.Title; } } return System.IO.Path.GetFileNameWithoutExtension(Assembly.GetExecutingAssembly().CodeBase); } } public string AssemblyVersion { get { return Assembly.GetExecutingAssembly().GetName().Version.ToString(); } } public string AssemblyDescription { get { object[] attributes = Assembly.GetExecutingAssembly().GetCustomAttributes(typeof(AssemblyDescriptionAttribute), false); if (attributes.Length == 0) { return ""; } return ((AssemblyDescriptionAttribute)attributes[0]).Description; } } public string AssemblyProduct { get { object[] attributes = Assembly.GetExecutingAssembly().GetCustomAttributes(typeof(AssemblyProductAttribute), false); if (attributes.Length == 0) { return ""; } return ((AssemblyProductAttribute)attributes[0]).Product; } } public string AssemblyCopyright { get { object[] attributes = Assembly.GetExecutingAssembly().GetCustomAttributes(typeof(AssemblyCopyrightAttribute), false); if (attributes.Length == 0) { return ""; } return ((AssemblyCopyrightAttribute)attributes[0]).Copyright; } } public string AssemblyCompany { get { object[] attributes = Assembly.GetExecutingAssembly().GetCustomAttributes(typeof(AssemblyCompanyAttribute), false); if (attributes.Length == 0) { return ""; } return ((AssemblyCompanyAttribute)attributes[0]).Company; } } #endregion } }
32.403509
170
0.531944
[ "MIT" ]
moorescloud/HolidayTest1
AboutForm.cs
3,696
C#
using Microsoft.Extensions.Configuration; using Newtonsoft.Json; using System; using System.Collections.Generic; using System.Net.Http; using System.Text; using System.Threading.Tasks; using webui.Service.Models; namespace webui.Service { public class TodoServiceRestContext : ITodoServiceAsyncContext { private Uri _apiBaseUri; public TodoServiceRestContext(IConfiguration configuration) { _apiBaseUri = new Uri(configuration["TodoApiUrl"]); } // https://www.yogihosting.com/aspnet-core-consume-api/ public async Task<IEnumerable<TodoItemDTO>> TodoItems() { List<TodoItemDTO> todoItems = new List<TodoItemDTO>(); using (var httpClient = new HttpClient()) { httpClient.BaseAddress = _apiBaseUri; using (var response = await httpClient.GetAsync("/api/TodoItems/")) { response.EnsureSuccessStatusCode(); string apiResponse = await response.Content.ReadAsStringAsync(); todoItems = JsonConvert.DeserializeObject<List<TodoItemDTO>>(apiResponse); } } return todoItems; } public async Task Create(TodoItemDTO newItem) { using (var httpClient = new HttpClient()) { httpClient.BaseAddress = _apiBaseUri; var response = await httpClient.PostAsync("/api/TodoItems/", new StringContent(JsonConvert.SerializeObject(newItem), Encoding.UTF8, "application/json")); response.EnsureSuccessStatusCode(); } } public async Task<TodoItemDTO> Get(int todoItemId) { TodoItemDTO todoItem = new TodoItemDTO(); using (var httpClient = new HttpClient()) { httpClient.BaseAddress = _apiBaseUri; using (var response = await httpClient.GetAsync("/api/TodoItems/" + todoItemId)) { response.EnsureSuccessStatusCode(); string apiResponse = await response.Content.ReadAsStringAsync(); todoItem = JsonConvert.DeserializeObject<TodoItemDTO>(apiResponse); } } return todoItem; } public async Task Update(TodoItemDTO editItem) { using (var httpClient = new HttpClient()) { httpClient.BaseAddress = _apiBaseUri; var response = await httpClient.PutAsync("/api/TodoItems/" + editItem.Id, new StringContent(JsonConvert.SerializeObject(editItem), Encoding.UTF8, "application/json")); response.EnsureSuccessStatusCode(); } } public async Task Delete(int todoItemId) { using (var httpClient = new HttpClient()) { httpClient.BaseAddress = _apiBaseUri; var response = await httpClient.DeleteAsync("/api/TodoItems/" + todoItemId); response.EnsureSuccessStatusCode(); } } public async Task<IEnumerable<FeatureFlagDTO>> SupportedFeatureFlags() { List<FeatureFlagDTO> featureFlags = new List<FeatureFlagDTO>(); using (var httpClient = new HttpClient()) { httpClient.BaseAddress = _apiBaseUri; using (var response = await httpClient.GetAsync("/api/TodoFeatureFlags")) { response.EnsureSuccessStatusCode(); string apiResponse = await response.Content.ReadAsStringAsync(); featureFlags = JsonConvert.DeserializeObject<List<FeatureFlagDTO>>(apiResponse); } } return featureFlags; } } }
39.422018
116
0.523388
[ "MIT" ]
jhasslof/todo-frontend
webui/Service/TodoServiceRestContext.cs
4,299
C#
// <copyright file="Sepia.cs" company="James Jackson-South"> // Copyright (c) James Jackson-South and contributors. // Licensed under the Apache License, Version 2.0. // </copyright> namespace ImageSharp { using System; using Processing; using Processing.Processors; /// <summary> /// Extension methods for the <see cref="Image{TColor}"/> type. /// </summary> public static partial class ImageExtensions { /// <summary> /// Applies sepia toning to the image. /// </summary> /// <typeparam name="TColor">The pixel format.</typeparam> /// <param name="source">The image this method extends.</param> /// <returns>The <see cref="Image"/>.</returns> public static Image<TColor> Sepia<TColor>(this Image<TColor> source) where TColor : struct, IPixel<TColor> { return Sepia(source, source.Bounds); } /// <summary> /// Applies sepia toning to the image. /// </summary> /// <typeparam name="TColor">The pixel format.</typeparam> /// <param name="source">The image this method extends.</param> /// <param name="rectangle"> /// The <see cref="Rectangle"/> structure that specifies the portion of the image object to alter. /// </param> /// <returns>The <see cref="Image"/>.</returns> public static Image<TColor> Sepia<TColor>(this Image<TColor> source, Rectangle rectangle) where TColor : struct, IPixel<TColor> { source.ApplyProcessor(new SepiaProcessor<TColor>(), rectangle); return source; } } }
36
106
0.599034
[ "Apache-2.0" ]
ststeiger/ImageSharpTestApplication
src/ImageSharp/Processing/ColorMatrix/Sepia.cs
1,658
C#
using System; using System.Threading.Tasks; using Statiq.Common; using Statiq.Core; namespace Grynwald.Extensions.Statiq.DocsTemplate { internal static class CopyFilesExtensions { internal static CopyFiles To(this CopyFiles copyFiles, Func<NormalizedPath, NormalizedPath> destinationPath) { return copyFiles.To((IFile file) => { var relativeInputPath = file.Path.GetRelativeInputPath(); var result = destinationPath(relativeInputPath); return Task.FromResult(result); }); } } }
28.571429
116
0.643333
[ "MIT" ]
ap0llo/extensions-statiq
src/Extensions.Statiq.DocsTemplate/_Extensions/CopyFilesExtensions.cs
602
C#
using Microsoft.ApplicationInsights.AspNetCore.Extensions; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Cors; using Microsoft.AspNetCore.Mvc; using Microsoft.EntityFrameworkCore; using SAEON.AspNet.Auth; using SAEON.Logs; using SAEON.Observations.Auth; using SAEON.Observations.Core; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace SAEON.Observations.WebAPI.Controllers.Internal { [Route("Internal/[controller]")] [EnableCors(ObsDBAuthenticationDefaults.CorsAllowQuerySitePolicy)] //[Authorize(Policy = ODPAuthenticationDefaults.AllowedClientsPolicy)] [ApiExplorerSettings(IgnoreApi = true)] #if ResponseCaching [ResponseCache(Duration = Defaults.InternalCacheDuration)] //[ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)] #endif public abstract class InternalApiController : BaseApiController { } [Route("Internal/[controller]")] [EnableCors(ObsDBAuthenticationDefaults.CorsAllowQuerySitePolicy)] //[Authorize(Policy = ODPAuthenticationDefaults.AllowedClientsPolicy)] [ApiExplorerSettings(IgnoreApi = true)] #if ResponseCaching [ResponseCache(Duration = Defaults.InternalCacheDuration)] //[ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)] #endif public abstract class InternalListController<TEntity> : BaseListController<TEntity> where TEntity : class { } [Route("Internal/[controller]")] [EnableCors(ObsDBAuthenticationDefaults.CorsAllowQuerySitePolicy)] //[Authorize(Policy = ODPAuthenticationDefaults.AllowedClientsPolicy)] [ApiExplorerSettings(IgnoreApi = true)] #if ResponseCaching [ResponseCache(Duration = Defaults.InternalCacheDuration)] //[ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)] #endif public abstract class InternalReadController<TEntity> : BaseIdedReadController<TEntity> where TEntity : IdedEntity { protected override void UpdateRequest() { EntityConfig.BaseUrl = Request.GetUri().GetLeftPart(UriPartial.Authority) + "/Internal"; } } [Route("Internal/[controller]")] [EnableCors(ObsDBAuthenticationDefaults.CorsAllowQuerySitePolicy)] //[Authorize(Policy = ODPAuthenticationDefaults.AllowedClientsPolicy)] [ApiExplorerSettings(IgnoreApi = true)] [ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)] [Authorize(Policy = ODPAuthenticationDefaults.IdTokenPolicy)] public abstract class InternalWriteController<TEntity, TEntityPatch> : BaseIdedReadController<TEntity> where TEntity : NamedEntity where TEntityPatch : NamedEntity { //protected IMapper Mapper { get; private set; } public InternalWriteController() : base() { TrackChanges = true; } protected override void UpdateRequest() { EntityConfig.BaseUrl = Request.GetUri().GetLeftPart(UriPartial.Authority) + "/Internal"; } protected abstract bool IsEntityOk(TEntity item, bool isPost); protected abstract bool IsEntityPatchOk(TEntityPatch item); protected abstract void SetEntity(ref TEntity item, bool isPost); protected abstract void UpdateEntity(ref TEntity item, TEntity updateItem); protected abstract void PatchEntity(ref TEntity item, TEntityPatch patchItem); public List<string> ModelStateErrors { get { return ModelState.Values.SelectMany(v => v.Errors).Select(v => v.ErrorMessage + " " + v.Exception).ToList(); } } [HttpPost] public async Task<ActionResult<TEntity>> Post([FromBody] TEntity newItem) { using (SAEONLogs.MethodCall<TEntity>(GetType(), new MethodCallParameters { { nameof(newItem), newItem } })) { try { UpdateRequest(); if (newItem is null) { SAEONLogs.Error($"{nameof(newItem)} cannot be null"); return BadRequest($"{nameof(newItem)} cannot be null"); } SAEONLogs.Verbose("Adding {Name} {@item}", newItem.Name, newItem); if (!ModelState.IsValid) { SAEONLogs.Error("ModelState.Invalid {ModelStateErrors}", ModelStateErrors); return BadRequest(ModelState); } if (!IsEntityOk(newItem, true)) { SAEONLogs.Error($"NewItem {newItem.Name} invalid"); return BadRequest($"NewItem {newItem.Name} invalid"); } try { SetEntity(ref newItem, true); SAEONLogs.Verbose("Add {@item}", newItem); DbContext.Set<TEntity>().Add(newItem); await DbContext.SaveChangesAsync(); } catch (DbUpdateException ex) { if (await GetQuery().Where(i => i.Name == newItem.Name).AnyAsync()) { SAEONLogs.Error("{Name} conflict", newItem.Name); return Conflict(); } else { SAEONLogs.Exception(ex, "Unable to add {Name}", newItem.Name); return BadRequest(ex.Message); } } catch (Exception ex) { SAEONLogs.Exception(ex, "Unable to add {Name}", newItem.Name); return BadRequest($"Unable to add {newItem.Name}"); } var location = $"{typeof(TEntity).Name}/{newItem.Id}"; SAEONLogs.Verbose("Location: {location} Id: {Id} Item: {@item}", location, newItem.Id, newItem); return CreatedAtAction(nameof(GetById), new { id = newItem.Id }, newItem); } catch (Exception ex) { SAEONLogs.Exception(ex, "Unable to add {Name}", newItem.Name); throw; } } } [HttpPut("{id:guid}")] public virtual async Task<ActionResult> PutById(Guid id, [FromBody] TEntity updateItem) { using (SAEONLogs.MethodCall<TEntity>(GetType(), new MethodCallParameters { { nameof(id), id }, { nameof(updateItem), updateItem } })) { try { UpdateRequest(); SAEONLogs.Information("Put: {id}", id); if (updateItem is null) { SAEONLogs.Error($"{nameof(updateItem)} cannot be null"); return BadRequest($"{nameof(updateItem)} cannot be null"); } SAEONLogs.Verbose("Updating {id} {@updateItem}", id, updateItem); //if (!ModelState.IsValid) //{ // SAEONLogs.Error("ModelState.Invalid {ModelStateErrors}", ModelStateErrors); // return BadRequest(ModelState); //} if (id != updateItem.Id) { SAEONLogs.Error("{id} Id not same", id); return BadRequest($"{id} Id not same"); } var item = await GetQuery().Where(i => i.Id == id).FirstOrDefaultAsync(); if (item is null) { SAEONLogs.Error("{id} not found", id); return NotFound(); } if (!IsEntityOk(item, false)) { SAEONLogs.Error($"Item {item.Name} invalid"); return BadRequest($"Item {item.Name} invalid"); } if (!IsEntityOk(updateItem, false)) { SAEONLogs.Error($"UpdateItem {updateItem.Name} invalid"); return BadRequest($"UpdateItem {updateItem.Name} invalid"); } try { SAEONLogs.Verbose("Loaded {@item} {@updateItem}", item, updateItem); //Mapper.Map(delta, item); //SAEONLogs.Verbose("Mapped delta {@item}", item); UpdateEntity(ref item, updateItem); SetEntity(ref item, false); SAEONLogs.Verbose("Set {@item}", item); await DbContext.SaveChangesAsync(); } catch (Exception ex) { SAEONLogs.Exception(ex, "Unable to update {id}", id); return BadRequest(ex.Message); } return NoContent(); } catch (Exception ex) { SAEONLogs.Exception(ex, "Unable to update {id}", id); throw; } } } [HttpPatch("{id:guid}")] public virtual async Task<ActionResult> PatchById(Guid id, [FromBody] TEntityPatch patchItem) { using (SAEONLogs.MethodCall<TEntity>(GetType(), new MethodCallParameters { { nameof(id), id }, { nameof(patchItem), patchItem } })) { try { UpdateRequest(); SAEONLogs.Information("Patch: {id}", id); if (patchItem is null) { SAEONLogs.Error($"{nameof(patchItem)} cannot be null"); return BadRequest($"{nameof(patchItem)} cannot be null"); } SAEONLogs.Verbose("Updating {id} {@patchItem}", id, patchItem); if (id != patchItem.Id) { SAEONLogs.Error("{id} Id not same", id); return BadRequest($"{id} Id not same"); } var item = await GetQuery().Where(i => i.Id == id).FirstOrDefaultAsync(); if (item is null) { SAEONLogs.Error("{id} not found", id); return NotFound(); } if (!IsEntityOk(item, false)) { SAEONLogs.Error($"Item {item.Name} invalid"); return BadRequest($"Item {item.Name} invalid"); } if (!IsEntityPatchOk(patchItem)) { SAEONLogs.Error($"PatchItem {patchItem.Name} invalid"); return BadRequest($"PatchItem {patchItem.Name} invalid"); } try { SAEONLogs.Verbose("Loaded {@oldItem} {@patchItem}", item, patchItem); PatchEntity(ref item, patchItem); SetEntity(ref item, false); SAEONLogs.Verbose("Set {@item}", item); await DbContext.SaveChangesAsync(); } catch (Exception ex) { SAEONLogs.Exception(ex, "Unable to patch {id}", id); return BadRequest(ex.Message); } return NoContent(); } catch (Exception ex) { SAEONLogs.Exception(ex, "Unable to patch {id}", id); throw; } } } [HttpDelete("{id:guid}")] public async Task<ActionResult> DeleteById(Guid id) { using (SAEONLogs.MethodCall<TEntity>(GetType(), new MethodCallParameters { { "Id", id } })) { try { UpdateRequest(); SAEONLogs.Verbose("Deleting {id}", id); var item = await GetQuery().Where(i => i.Id == id).FirstOrDefaultAsync(); if (item is null) { SAEONLogs.Error("{id} not found", id); return NotFound(); } try { DbContext.Set<TEntity>().Remove(item); SAEONLogs.Verbose("Delete {@item}", item); await DbContext.SaveChangesAsync(); } catch (Exception ex) { SAEONLogs.Exception(ex, "Unable to delete {id}", id); return BadRequest(ex.Message); } return NoContent(); } catch (Exception ex) { SAEONLogs.Exception(ex, "Unable to delete {id}", id); throw; } } } } }
42.89557
167
0.492586
[ "MIT" ]
NimbusServices/SAEON.ObservationsDatabase
SAEON.Observations.WebAPI/Controllers/Internal/InternalControllers.cs
13,557
C#
//------------------------------------------------------------------------------ // <copyright file="TagMapInfo.cs" company="Microsoft"> // Copyright (c) Microsoft Corporation. All rights reserved. // </copyright> //------------------------------------------------------------------------------ namespace System.Web.Configuration { using System; using System.Xml; using System.Configuration; using System.Collections.Specialized; using System.Collections; using System.IO; using System.Text; using System.Web.Util; using System.Web.UI; using System.Web.Compilation; using System.Threading; using System.Web.Configuration; using System.Security.Permissions; public sealed class TagMapInfo : ConfigurationElement { private static ConfigurationPropertyCollection _properties; private static readonly ConfigurationProperty _propTagTypeName = new ConfigurationProperty("tagType", typeof(string), null, null, StdValidatorsAndConverters.NonEmptyStringValidator, ConfigurationPropertyOptions.IsRequired | ConfigurationPropertyOptions.IsKey); private static readonly ConfigurationProperty _propMappedTagTypeName = new ConfigurationProperty("mappedTagType", typeof(string), null, null, StdValidatorsAndConverters.NonEmptyStringValidator, ConfigurationPropertyOptions.IsRequired); static TagMapInfo() { _properties = new ConfigurationPropertyCollection(); _properties.Add(_propTagTypeName); _properties.Add(_propMappedTagTypeName); } internal TagMapInfo() { } public TagMapInfo(String tagTypeName, String mappedTagTypeName) : this() { TagType = tagTypeName; MappedTagType = mappedTagTypeName; } public override bool Equals(object o) { TagMapInfo tm = o as TagMapInfo; return StringUtil.Equals(TagType, tm.TagType) && StringUtil.Equals(MappedTagType, tm.MappedTagType); } public override int GetHashCode() { return TagType.GetHashCode() ^ MappedTagType.GetHashCode(); } protected override ConfigurationPropertyCollection Properties { get { return _properties; } } [ConfigurationProperty("mappedTagType")] [StringValidator(MinLength = 1)] public string MappedTagType { get { return (string)base[_propMappedTagTypeName]; } set { base[_propMappedTagTypeName] = value; } } [ConfigurationProperty("tagType", IsRequired = true, IsKey = true, DefaultValue = "")] [StringValidator(MinLength = 1)] public string TagType { get { return (string)base[_propTagTypeName]; } set { base[_propTagTypeName] = value; } } void Verify() { if (String.IsNullOrEmpty(TagType)) { throw new ConfigurationErrorsException( SR.GetString(SR.Config_base_required_attribute_missing, "tagType")); } if (String.IsNullOrEmpty(MappedTagType)) { throw new ConfigurationErrorsException( SR.GetString(SR.Config_base_required_attribute_missing, "mappedTagType")); } } protected override bool SerializeElement(XmlWriter writer, bool serializeCollectionKey) { Verify(); return base.SerializeElement(writer, serializeCollectionKey); } } }
36.365217
97
0.529173
[ "Apache-2.0" ]
295007712/295007712.github.io
sourceCode/dotNet4.6/ndp/fx/src/xsp/system/Web/Configuration/TagMapInfo.cs
4,182
C#
using Nest.Resolvers.Converters; using Newtonsoft.Json; using System; using System.Collections.Generic; using System.Linq; namespace Nest.DSL.Query { [JsonObject(MemberSerialization = MemberSerialization.OptIn)] [JsonConverter(typeof(ReadAsTypeConverter<FilterScoreQueryDescriptor<object>>))] public interface IFilterScoreQuery : IQuery { [JsonProperty(PropertyName = "filter")] FilterContainer Filter { get; set; } [JsonProperty(PropertyName = "lang")] string Lang { get; set; } [JsonProperty(PropertyName = "script")] string Script { get; set; } [JsonProperty(PropertyName = "params")] [JsonConverter(typeof(DictionaryKeysAreNotPropertyNamesJsonConverter))] Dictionary<string, object> Params { get; set; } [JsonProperty(PropertyName = "boost")] double? Boost { get; set; } } public class FilterScoreQuery : IFilterScoreQuery { public string Name { get; set; } bool IQuery.IsConditionless { get { return false; } } public FilterContainer Filter { get; set; } public string Lang { get; set; } public string Script { get; set; } public Dictionary<string, object> Params { get; set; } public double? Boost { get; set; } } public class FilterScoreQueryDescriptor<T> : IFilterScoreQuery where T : class { private IFilterScoreQuery Self { get { return this; } } string IQuery.Name { get; set; } bool IQuery.IsConditionless { get { return Self.Filter == null; } } FilterContainer IFilterScoreQuery.Filter { get; set; } string IFilterScoreQuery.Script { get; set; } string IFilterScoreQuery.Lang { get; set; } double? IFilterScoreQuery.Boost { get; set; } Dictionary<string, object> IFilterScoreQuery.Params { get; set; } public FilterScoreQueryDescriptor<T> Name(string name) { Self.Name = name; return this; } public FilterScoreQueryDescriptor<T> Boost(double boost) { Self.Boost = boost; return this; } public FilterScoreQueryDescriptor<T> Script(string script) { Self.Script = script; return this; } public FilterScoreQueryDescriptor<T> Lang(string lang) { Self.Lang = lang; return this; } public FilterScoreQueryDescriptor<T> Lang(ScriptLang lang) { Self.Lang = lang.GetStringValue(); return this; } public FilterScoreQueryDescriptor<T> Params(Func<FluentDictionary<string, object>, FluentDictionary<string, object>> paramDictionary) { paramDictionary.ThrowIfNull("paramDictionary"); Self.Params = paramDictionary(new FluentDictionary<string, object>()); return this; } public FilterScoreQueryDescriptor<T> Filter(Func<FilterDescriptor<T>, FilterContainer> filterSelector) { filterSelector.ThrowIfNull("filterSelector"); var filter = new FilterDescriptor<T>(); Self.Filter = filterSelector(filter); return this; } } }
27.754902
135
0.714235
[ "Apache-2.0" ]
molaxx/elasticsearch-net
src/Nest/DSL/Query/FilterScoreQueryDescriptor.cs
2,833
C#
using System; using System.Linq.Expressions; namespace BalazsArva.RavenDb.Extensions.ConditionalPatch.Utilitites { public interface IPatchScriptBuilder { string CreateConditionalPatchScript<TDocument>(PropertyUpdateDescriptor[] propertyUpdates, Expression<Func<TDocument, bool>> condition, ScriptParameterDictionary parameters); } }
35.4
182
0.80791
[ "MIT" ]
BalazsArva/RavenDbExtensions
src/BalazsArva.RavenDb.Extensions.ConditionalPatch/Utilitites/IPatchScriptBuilder.cs
356
C#
using System; using Legacy.Core.Internationalization; using Legacy.Core.StaticData; namespace Legacy.Core.Spells.MonsterSpells { public class MonsterSpellLightningBolt : MonsterSpell { public MonsterSpellLightningBolt(String p_effectAnimationClip, Int32 p_castProbability) : base(EMonsterSpell.LIGHTNING_BOLT, p_effectAnimationClip, p_castProbability) { } public override String GetDescriptionForCaster(MonsterStaticData p_monster) { SetDescriptionValue(0, GetDamageAsString()); SetDescriptionValue(1, p_monster.SpellRanges); return Localization.Instance.GetText("MONSTER_SPELL_LIGHTNING_BOLT_INFO", m_descriptionValues); } } }
31.190476
168
0.819847
[ "MIT" ]
Albeoris/MMXLegacy
Legacy.Core/Core/Spells/MonsterSpells/MonsterSpellLightningBolt.cs
657
C#
using System; using System.Collections.Generic; using System.ComponentModel; using System.Drawing; using System.Data; using System.Linq; using System.Text; using System.Windows.Forms; namespace SwmSuite.Presentation.Common.TimeTable { public partial class OccupationControl : UserControl { #region -_ Public Properties _- public OccupationSettings Settings { get; set; } public OccupationRenderer Renderer { get; set; } //public OccupationHitTest HitTester { get; set; } [DesignerSerializationVisibility( DesignerSerializationVisibility.Content )] [TypeConverter( typeof( ExpandableObjectConverter ) )] public OccupationScheme Scheme { get; set; } [DesignerSerializationVisibility( DesignerSerializationVisibility.Content )] public TimeTableColumnCollection Columns { get; set; } public DateTime Selection { get; set; } #endregion #region -_ Events _- public event EventHandler<EventArgs> DataNeeded; #endregion #region -_ Construction _- /// <summary> /// Initializes a new instance of the <see cref="OccupationControl"/> class. /// </summary> public OccupationControl() { InitializeComponent(); this.SetStyle( ControlStyles.AllPaintingInWmPaint , true ); this.SetStyle( ControlStyles.OptimizedDoubleBuffer , true ); this.SetStyle( ControlStyles.ResizeRedraw , true ); this.SetStyle( ControlStyles.SupportsTransparentBackColor , true ); this.SetStyle( ControlStyles.UserPaint , true ); this.Settings = new OccupationSettings(); this.Columns = new TimeTableColumnCollection(); this.Selection = DateTime.Today; this.Renderer = new OccupationRenderer(); //this.HitTester = new TimeTableHitTest(); this.Scheme = new OccupationScheme(); } #endregion #region -_ Event Handlers _- /// <summary> /// Handles the Paint event of the OccupationControl control. /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="e">The <see cref="System.Windows.Forms.PaintEventArgs"/> instance containing the event data.</param> private void OccupationControl_Paint( object sender , PaintEventArgs e ) { Rectangle realRectangle = new Rectangle( this.ClientRectangle.Left , this.ClientRectangle.Top , this.ClientRectangle.Width - 1 , this.ClientRectangle.Height - 1 ); this.Renderer.Render( e.Graphics , realRectangle , this.Selection , this.Columns , this.Settings , this.Scheme ); } #endregion #region -_ Public Methods _- public void Move( DateTime dateTime ) { this.Selection = dateTime; if( this.DataNeeded != null ) { DataNeeded( this , EventArgs.Empty ); } this.Invalidate(); } #endregion } }
28.98913
166
0.731159
[ "Unlicense" ]
Djohnnie/SwmSuite-Original
SwmSuite.Presentation.Common/TimeTable/OccupationControl.cs
2,669
C#
using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc; using Microsoft.Azure.Documents.Client; using Microsoft.Azure.Documents.Linq; using Microsoft.Azure.WebJobs; using Microsoft.Azure.WebJobs.Extensions.Http; using Microsoft.Azure.WebJobs.Host; using Microsoft.Extensions.Logging; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace vNAAATS.NET { public static class GetAllFlightData { [FunctionName("GetAllFlightData")] public static async Task<IActionResult> Run( [HttpTrigger(AuthorizationLevel.Anonymous, "get", "post", Route = null)] HttpRequest req, [CosmosDB("vnaaats-net", "flights", ConnectionStringSetting = "DbConnectionString")] DocumentClient client, ILogger log) { try { /// PARAMETERS int sorting = -1; // Sorting -> -1: not found in request, 0: ascending, 1: descending bool relevant = false; // We get all by default // Grab the sort parameter if it exists string queryTerm = req.Query["sort"]; if (!string.IsNullOrWhiteSpace(queryTerm) && int.TryParse(queryTerm, out var res)) { // Parse to sorting if it exists if (res > -1 && res < 2) { sorting = Int32.Parse(queryTerm); } } // Get all only relevant queryTerm = req.Query["relevant"]; if (!string.IsNullOrWhiteSpace(queryTerm)) { if (queryTerm.ToLower() == "true") { relevant = true; } } // URI for flight data collection Uri collectionUri = UriFactory.CreateDocumentCollectionUri("vnaaats-net", "flights"); // LINQ Query IDocumentQuery<FlightData> query = client.CreateDocumentQuery<FlightData>(collectionUri, new FeedOptions { MaxItemCount = 1000 }) .AsDocumentQuery(); // Get results List<FlightData> results = new List<FlightData>(); foreach (FlightData result in await query.ExecuteNextAsync()) { if (relevant && result.relevant) // if relevant then only add if the property is true in the flight object { results.Add(result); continue; } results.Add(result); // add them all } // Sort if needed if (sorting != -1) { if (sorting == 0) // ascending { results.Sort((x, y) => x.assignedLevel.CompareTo(y.assignedLevel)); } else // descending { results.Sort((x, y) => y.assignedLevel.CompareTo(x.assignedLevel)); } } // Return okay if found return new OkObjectResult(results); } catch (Exception ex) { // Catch any errors log.LogError($"Could not retrieve flight data. Exception thrown: {ex.Message}."); return new StatusCodeResult(StatusCodes.Status500InternalServerError); } } } }
38.586957
145
0.512676
[ "Apache-2.0" ]
andrewogden1678/vNAAATS-net
GetAllFlightData.cs
3,550
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Cofoundry.Domain.CQS; using Cofoundry.Domain.Data; using Microsoft.EntityFrameworkCore; using Cofoundry.Core.MessageAggregator; using Cofoundry.Core.Data; using Cofoundry.Core; namespace Cofoundry.Domain.Internal { /// <summary> /// Adds a new block to a template region on a custom entity page. /// </summary> public class AddCustomEntityVersionPageBlockCommandHandler : ICommandHandler<AddCustomEntityVersionPageBlockCommand> , IIgnorePermissionCheckHandler { #region constructor private readonly CofoundryDbContext _dbContext; private readonly ICommandExecutor _commandExecutor; private readonly EntityOrderableHelper _entityOrderableHelper; private readonly ICustomEntityCache _customEntityCache; private readonly IPageBlockCommandHelper _pageBlockCommandHelper; private readonly IMessageAggregator _messageAggregator; private readonly IPermissionValidationService _permissionValidationService; private readonly ITransactionScopeManager _transactionScopeFactory; public AddCustomEntityVersionPageBlockCommandHandler( CofoundryDbContext dbContext, ICommandExecutor commandExecutor, EntityOrderableHelper entityOrderableHelper, ICustomEntityCache customEntityCache, IPageBlockCommandHelper pageBlockCommandHelper, IMessageAggregator messageAggregator, ICustomEntityDefinitionRepository customEntityDefinitionRepository, IPermissionValidationService permissionValidationService, ITransactionScopeManager transactionScopeFactory ) { _dbContext = dbContext; _commandExecutor = commandExecutor; _entityOrderableHelper = entityOrderableHelper; _customEntityCache = customEntityCache; _pageBlockCommandHelper = pageBlockCommandHelper; _messageAggregator = messageAggregator; _permissionValidationService = permissionValidationService; _transactionScopeFactory = transactionScopeFactory; } #endregion #region execution public async Task ExecuteAsync(AddCustomEntityVersionPageBlockCommand command, IExecutionContext executionContext) { var customEntityVersion = _dbContext .CustomEntityVersions .Include(s => s.CustomEntityVersionPageBlocks) .Include(s => s.CustomEntity) .FirstOrDefault(v => v.CustomEntityVersionId == command.CustomEntityVersionId); EntityNotFoundException.ThrowIfNull(customEntityVersion, command.CustomEntityVersionId); _permissionValidationService.EnforceCustomEntityPermission<CustomEntityUpdatePermission>(customEntityVersion.CustomEntity.CustomEntityDefinitionCode, executionContext.UserContext); if (customEntityVersion.WorkFlowStatusId != (int)WorkFlowStatus.Draft) { throw new NotPermittedException("Page blocks cannot be added unless the entity is in draft status"); } var page = await _dbContext .Pages .FilterActive() .FilterById(command.PageId) .SingleOrDefaultAsync(); EntityNotFoundException.ThrowIfNull(page, command.PageId); var templateRegion = await _dbContext .PageTemplateRegions .FirstOrDefaultAsync(l => l.PageTemplateRegionId == command.PageTemplateRegionId); EntityNotFoundException.ThrowIfNull(templateRegion, command.PageTemplateRegionId); await ValidateTemplateUsedByPage(command, templateRegion); var customEntityVersionBlocks = customEntityVersion .CustomEntityVersionPageBlocks .Where(m => m.PageTemplateRegionId == templateRegion.PageTemplateRegionId); CustomEntityVersionPageBlock adjacentItem = null; if (command.AdjacentVersionBlockId.HasValue) { adjacentItem = customEntityVersionBlocks .SingleOrDefault(m => m.CustomEntityVersionPageBlockId == command.AdjacentVersionBlockId); EntityNotFoundException.ThrowIfNull(adjacentItem, command.AdjacentVersionBlockId); if (adjacentItem.PageTemplateRegionId != command.PageTemplateRegionId) { throw new Exception("Error adding custom entity page block: the block specified in AdjacentVersionBlockId is in a different region to the block being added."); } } var newBlock = new CustomEntityVersionPageBlock(); newBlock.PageTemplateRegion = templateRegion; newBlock.Page = page; newBlock.CustomEntityVersion = customEntityVersion; await _pageBlockCommandHelper.UpdateModelAsync(command, newBlock); _entityOrderableHelper.SetOrderingForInsert(customEntityVersionBlocks, newBlock, command.InsertMode, adjacentItem); _dbContext.CustomEntityVersionPageBlocks.Add(newBlock); using (var scope = _transactionScopeFactory.Create(_dbContext)) { await _dbContext.SaveChangesAsync(); var dependencyCommand = new UpdateUnstructuredDataDependenciesCommand( CustomEntityVersionPageBlockEntityDefinition.DefinitionCode, newBlock.CustomEntityVersionPageBlockId, command.DataModel); await _commandExecutor.ExecuteAsync(dependencyCommand, executionContext); scope.QueueCompletionTask(() => OnTransactionComplete(customEntityVersion, newBlock)); await scope.CompleteAsync(); } command.OutputCustomEntityVersionPageBlockId = newBlock.CustomEntityVersionPageBlockId; } private Task OnTransactionComplete(CustomEntityVersion customEntityVersion, CustomEntityVersionPageBlock newBlock) { _customEntityCache.Clear(customEntityVersion.CustomEntity.CustomEntityDefinitionCode, customEntityVersion.CustomEntityId); return _messageAggregator.PublishAsync(new CustomEntityVersionBlockAddedMessage() { CustomEntityId = customEntityVersion.CustomEntityId, CustomEntityVersionPageBlockId = newBlock.CustomEntityVersionPageBlockId, CustomEntityDefinitionCode = customEntityVersion.CustomEntity.CustomEntityDefinitionCode }); } private async Task ValidateTemplateUsedByPage(AddCustomEntityVersionPageBlockCommand command, PageTemplateRegion templateRegion) { var isRegionInTemplate = await _dbContext .PageVersions .FilterActive() .FilterByPageId(command.PageId) .AnyAsync(p => p.PageTemplateId == templateRegion.PageTemplateId); if (!isRegionInTemplate) { throw new Exception($"Error adding custom entity page block. The page template region {command.PageTemplateRegionId} does not belong to a template referenced by the page {command.PageId}"); } } #endregion } }
44.849398
205
0.692142
[ "MIT" ]
BearerPipelineTest/cofoundry
src/Cofoundry.Domain/Domain/CustomEntities/Commands/AddCustomEntityVersionPageBlockCommandHandler.cs
7,447
C#
#region License // Copyright (c) 2009, ClearCanvas Inc. // 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 ClearCanvas Inc. nor the names of its contributors // may be used to endorse or promote products derived from this software without // specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, // THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, // OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE // GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) // HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, // STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN // ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY // OF SUCH DAMAGE. #endregion using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using ClearCanvas.Common; [assembly: Plugin] // 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("ClearCanvas.ImageServer.Enterprise")] [assembly: AssemblyDescription("ImageServer Persistant Store Abstraction Assembly")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("ClearCanvas")] [assembly: AssemblyProduct("ImageServer")] [assembly: AssemblyCopyright("Copyright (c) 2009")] [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("e9bdfb6c-5736-40bb-9e27-50cd3bbbd9d2")] // 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 Revision and Build Numbers // by using the '*' as shown below: [assembly: AssemblyVersion("0.90.0.0")] [assembly: AssemblyFileVersion("0.9.0.0")]
45.528571
87
0.739881
[ "Apache-2.0" ]
econmed/ImageServer20
ImageServer/Enterprise/Properties/AssemblyInfo.cs
3,189
C#
using System; using System.ComponentModel; using EfsTools.Attributes; namespace EfsTools.Items.Nv { [Serializable] [NvItemId(3852)] [Attributes(9)] public class WcdmaEqualizerControl { [ElementsCount(1)] [ElementType("uint8")] [Description("")] public byte Value { get; set; } } }
20.764706
40
0.600567
[ "MIT" ]
HomerSp/EfsTools
EfsTools/Items/Nv/WCDMAEqualizerControl.cs
353
C#
using System.ComponentModel.DataAnnotations; using Abp.Auditing; using Abp.Authorization.Users; using Abp.AutoMapper; using Abp.Runtime.Validation; using CricketApplicationWebPortal.Authorization.Users; namespace CricketApplicationWebPortal.Users.Dto { [AutoMapTo(typeof(User))] public class CreateUserDto : IShouldNormalize { [Required] [StringLength(AbpUserBase.MaxUserNameLength)] public string UserName { get; set; } [Required] [StringLength(AbpUserBase.MaxNameLength)] public string Name { get; set; } [Required] [StringLength(AbpUserBase.MaxSurnameLength)] public string Surname { get; set; } [Required] [EmailAddress] [StringLength(AbpUserBase.MaxEmailAddressLength)] public string EmailAddress { get; set; } public bool IsActive { get; set; } public string[] RoleNames { get; set; } [Required] [StringLength(AbpUserBase.MaxPlainPasswordLength)] [DisableAuditing] public string Password { get; set; } public void Normalize() { if (RoleNames == null) { RoleNames = new string[0]; } } } }
25.958333
58
0.627608
[ "MIT" ]
farazahmed879/CricketApp
aspnet-core/src/CricketApplicationWebPortal.Application/Users/Dto/CreateUserDto.cs
1,246
C#
using System; using System.ComponentModel; using System.Drawing; using System.IO; using System.Web; using System.Windows.Forms; using PluginCore; using PluginCore.Helpers; using PluginCore.Localization; using PluginCore.Managers; using PluginCore.Utilities; using ProjectManager; using StartPage.Controls; using WeifenLuo.WinFormsUI.Docking; namespace StartPage { public class PluginMain : IPlugin { bool justOpened = true; string defaultRssUrl = ""; string defaultStartPageUrl = ""; StartPageWebBrowser startPageWebBrowser; string settingFilename; Settings settingObject; DockContent startPage; Image pluginImage; #region Required Properties /// <summary> /// Api level of the plugin /// </summary> public int Api => 1; /// <summary> /// Name of the plugin /// </summary> public string Name { get; } = nameof(StartPage); /// <summary> /// GUID of the plugin /// </summary> public string Guid { get; } = "e4246322-bc55-4f4a-99c8-aaeeed0a7b9a"; /// <summary> /// Author of the plugin /// </summary> public string Author { get; } = "FlashDevelop Team"; /// <summary> /// Description of the plugin /// </summary> public string Description { get; set; } = "Adds a start page to FlashDevelop."; /// <summary> /// Web address for help /// </summary> public string Help { get; } = "www.flashdevelop.org/community/"; /// <summary> /// Object that contains the settings /// </summary> public object Settings => settingObject; #endregion #region Required Methods /// <summary> /// Initializes the plugin /// </summary> public void Initialize() { InitBasics(); LoadSettings(); AddEventHandlers(); CreateMenuItem(); } /// <summary> /// Disposes the plugin /// </summary> public void Dispose() => SaveSettings(); /// <summary> /// Handles the incoming events /// </summary> public void HandleEvent(object sender, NotifyEvent e, HandlingPriority priority) { switch (e.Type) { case EventType.Command : var de = (DataEvent)e; switch (de.Action) { case ProjectManagerEvents.Project : // Close pluginPanel if the user has the setting checked and a project is opened if (de.Data != null && startPage != null) { if (settingObject.CloseOnProjectOpen) startPage.Close(); // The project manager does not update recent projects until after // it broadcasts this event so we'll wait a little bit before refreshing Timer timer = new Timer(); timer.Interval = 100; timer.Tick += delegate { timer.Stop(); if (!startPageWebBrowser.IsDisposed) startPageWebBrowser.SendProjectInfo(); }; timer.Start(); } break; } break; case EventType.FileEmpty : if ((justOpened & (settingObject.ShowStartPageOnStartup == ShowStartPageOnStartupEnum.Always || settingObject.ShowStartPageOnStartup == ShowStartPageOnStartupEnum.NotRestoringSession)) || settingObject.ShowStartPageInsteadOfUntitled) { ShowStartPage(); justOpened = false; e.Handled = true; } break; case EventType.RestoreSession: var session = (ISession) ((DataEvent)e).Data; if (session.Type != SessionType.Startup) return; // handle only startup sessions if (settingObject.ShowStartPageOnStartup == ShowStartPageOnStartupEnum.Always) e.Handled = true; else if (session.Files.Count > 0) justOpened = false; break; } } #endregion #region Custom Methods string CurrentPageUrl => settingObject.UseCustomStartPage ? settingObject.CustomStartPage : defaultStartPageUrl; string CurrentRssUrl => settingObject.UseCustomRssFeed ? settingObject.CustomRssFeed : defaultRssUrl; /// <summary> /// Initializes important variables /// </summary> public void InitBasics() { int length = DistroConfig.DISTRIBUTION_NAME.Length + 1; string dataDir = Path.Combine(PathHelper.DataDir, "StartPage"); string localeName = PluginBase.Settings.LocaleVersion.ToString(); string version = Application.ProductName.Substring(length, Application.ProductName.IndexOfOrdinal(" for") - length); string fileWithArgs = "index.html?l=" + localeName + "&v=" + HttpUtility.HtmlEncode(version); defaultStartPageUrl = Path.Combine(PathHelper.AppDir, "StartPage", fileWithArgs); defaultRssUrl = DistroConfig.DISTRIBUTION_RSS; // Default feed... if (!Directory.Exists(dataDir)) Directory.CreateDirectory(dataDir); settingFilename = Path.Combine(dataDir, "Settings.fdb"); Description = TextHelper.GetString("Info.Description"); pluginImage = PluginBase.MainForm.FindImage("224"); } /// <summary> /// Adds the required event handlers /// </summary> public void AddEventHandlers() { EventManager.AddEventHandler(this, EventType.Command | EventType.FileEmpty | EventType.RestoreSession); } /// <summary> /// Loads the plugin settings /// </summary> public void LoadSettings() { settingObject = new Settings(); if (!File.Exists(settingFilename)) SaveSettings(); else settingObject = ObjectSerializer.Deserialize(settingFilename, settingObject); } /// <summary> /// Saves the plugin settings /// </summary> public void SaveSettings() => ObjectSerializer.Serialize(settingFilename, settingObject); /// <summary> /// Creates a menu item for the plugin /// </summary> public void CreateMenuItem() { var title = TextHelper.GetString("Label.ViewMenuItem"); var menu = (ToolStripMenuItem)PluginBase.MainForm.FindMenuItem("ViewMenu"); var item = new ToolStripMenuItem(title, pluginImage, ViewMenuClick); PluginBase.MainForm.RegisterShortcutItem("ViewMenu.ShowStartPage", item); menu.DropDownItems.Add(item); } /// <summary> /// Creates the Start Page Tab /// </summary> public void CreateStartPage() { startPageWebBrowser = new StartPageWebBrowser(CurrentPageUrl, CurrentRssUrl); startPage = PluginBase.MainForm.CreateCustomDocument(startPageWebBrowser); startPage.Icon = ImageKonverter.ImageToIcon(pluginImage); startPage.Disposed += PluginPanelDisposed; startPage.Closing += PluginPanelClosing; startPage.Text = TextHelper.GetString("Title.StartPage"); } /// <summary> /// Shows the Start Page Tab and creates if necessary. /// </summary> public void ShowStartPage() { if (startPage is null) CreateStartPage(); else startPage.Show(PluginBase.MainForm.DockPanel); } #endregion #region Event Handlers /// <summary> /// Shows the start page. /// </summary> void ViewMenuClick(object sender, EventArgs e) => ShowStartPage(); /// <summary> /// Some internal event handling for closing. /// </summary> void PluginPanelClosing(object sender, CancelEventArgs e) { if (settingObject.ShowStartPageInsteadOfUntitled && PluginBase.MainForm.Documents.Length == 1) { e.Cancel = true; } } /// <summary> /// Reset the start page reference. /// </summary> void PluginPanelDisposed(object sender, EventArgs e) => startPage = null; #endregion } }
37.356846
254
0.547262
[ "MIT" ]
Acidburn0zzz/flashdevelop
External/Plugins/StartPage/PluginMain.cs
8,763
C#
// MIT License // Copyright (c) 2020 Simon Schulze // 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.Globalization; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Data; namespace iRLeagueManager.Converters { public class MultiValueEqualsConverter : IMultiValueConverter { public object Convert(object[] values, Type targetType, object parameter, CultureInfo culture) { bool result = true; var lastValue = values.FirstOrDefault(); foreach (var value in values) { result &= value.Equals(lastValue); lastValue = value; } return result; } public object[] ConvertBack(object value, Type[] targetTypes, object parameter, CultureInfo culture) { return null; } } }
35.672727
108
0.705403
[ "MIT" ]
SSchulze1989/iRLeagueManager
iRLeagueManager/Converters/MultiValueEqualsConverter.cs
1,964
C#
using System; using System.Collections.Generic; using System.Text; using DotNetty.Transport.Channels; using DotNetty.Handlers.Timeout; using DotNetty.Buffers; namespace Meou.Transport.DotNetty { public class ConnectorIdleStateTrigger : ChannelHandlerAdapter { private static IByteBuffer buffer = Unpooled.WrappedBuffer(Heartbeats.HeartbeatContent()); public override bool IsSharable => true; public override void UserEventTriggered(IChannelHandlerContext context, object evt) { if (evt is IdleStateEvent) { IdleState state = ((IdleStateEvent)evt).State; if (state == IdleState.WriterIdle) { // write heartbeat to server context.WriteAndFlushAsync(buffer); Console.WriteLine("发送心跳"); } } else { base.UserEventTriggered(context, evt); } } } }
31.419355
98
0.610883
[ "MIT" ]
lc8882972/MeouY
src/Meou.Transport.DotNetty/ConnectorIdleStateTrigger.cs
984
C#
/* SPDX-License-Identifier: Apache-2.0 * * The OpenSearch Contributors require contributions made to * this file be licensed under the Apache-2.0 license or a * compatible open source license. * * Modifications Copyright OpenSearch Contributors. See * GitHub history for details. * * Licensed to Elasticsearch B.V. under one or more contributor * license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright * ownership. Elasticsearch B.V. licenses this file to you under * the Apache License, Version 2.0 (the "License"); you may * not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ using System; using System.Linq.Expressions; using System.Runtime.Serialization; using OpenSearch.Net.Utf8Json; namespace OpenSearch.Client { [InterfaceDataContract] [ReadAs(typeof(SpanFieldMaskingQuery))] public interface ISpanFieldMaskingQuery : ISpanSubQuery { [DataMember(Name = "field")] Field Field { get; set; } [DataMember(Name = "query")] ISpanQuery Query { get; set; } } public class SpanFieldMaskingQuery : QueryBase, ISpanFieldMaskingQuery { public Field Field { get; set; } public ISpanQuery Query { get; set; } protected override bool Conditionless => IsConditionless(this); internal override void InternalWrapInContainer(IQueryContainer c) => c.SpanFieldMasking = this; internal static bool IsConditionless(ISpanFieldMaskingQuery q) => q.Field.IsConditionless() || q.Query == null || q.Query.Conditionless; } public class SpanFieldMaskingQueryDescriptor<T> : QueryDescriptorBase<SpanFieldMaskingQueryDescriptor<T>, ISpanFieldMaskingQuery> , ISpanFieldMaskingQuery where T : class { protected override bool Conditionless => SpanFieldMaskingQuery.IsConditionless(this); Field ISpanFieldMaskingQuery.Field { get; set; } ISpanQuery ISpanFieldMaskingQuery.Query { get; set; } public SpanFieldMaskingQueryDescriptor<T> Field(Field field) => Assign(field, (a, v) => a.Field = v); public SpanFieldMaskingQueryDescriptor<T> Field<TValue>(Expression<Func<T, TValue>> objectPath) => Assign(objectPath, (a, v) => a.Field = v); public SpanFieldMaskingQueryDescriptor<T> Query(Func<SpanQueryDescriptor<T>, ISpanQuery> selector) => Assign(selector, (a, v) => a.Query = v?.Invoke(new SpanQueryDescriptor<T>())); } }
36.693333
103
0.759448
[ "Apache-2.0" ]
opensearch-project/opensearch-net
src/OpenSearch.Client/QueryDsl/Span/FieldMasking/SpanFieldMaskingQuery.cs
2,752
C#
using System.Collections.Generic; using System.Collections.Immutable; using DeUrgenta.Domain.Api.Entities; using DeUrgenta.Infra.Models; using Swashbuckle.AspNetCore.Filters; namespace DeUrgenta.User.Api.Swagger { public class GetUserLocationTypesResponseExample : IExamplesProvider<IImmutableList<IndexedItemModel>> { public IImmutableList<IndexedItemModel> GetExamples() { return new List<IndexedItemModel> { new() { Id = (int)UserLocationType.Other, Label = "Altă adresă" }, new() { Id = (int)UserLocationType.Home, Label = "Casă" }, new() { Id = (int)UserLocationType.Work, Label = "Serviciu" }, new() { Id = (int)UserLocationType.School, Label = "Școală" }, new() { Id = (int)UserLocationType.Gym, Label = "Sala de sport" } }.ToImmutableList(); } } }
29.511628
106
0.449961
[ "MPL-2.0", "MPL-2.0-no-copyleft-exception" ]
idormenco/de-urgenta-backend
Src/DeUrgenta.User.Api/Swagger/GetUserLocationTypesResponseExample.cs
1,276
C#
using System; using Slight.Alexa.Framework.Models.Requests.RequestTypes; namespace HoneyBear.Alexa.Kodi.Proxies.Alexa { public class AudioRequestBundle : RequestBundle { public new Type GetRequestType() { switch (Type) { case "IntentRequest": return typeof(IIntentRequest); case "LaunchRequest": return typeof(ILaunchRequest); case "SessionEndedRequest": return typeof(ISessionEndedRequest); case "AudioPlayer.PlaybackStarted": return typeof(IAudioPlayerPlaybackStartedRequest); case "AudioPlayer.PlaybackFinished": return typeof(IAudioPlayerPlaybackFinishedRequest); case "AudioPlayer.PlaybackStopped": return typeof(IAudioPlayerPlaybackStoppedRequest); case "AudioPlayer.PlaybackNearlyFinished": return typeof(IAudioPlayerPlaybackNearlyFinishedRequest); case "AudioPlayer.PlaybackFailed": return typeof(IAudioPlayerPlaybackFailedRequest); default: return typeof(IUnknownRequest); } } public string Token { get; set; } public int OffsetInMilliseconds { get; set; } public Error Error { get; set; } public override string ToString() => $"Type={Type}|Reason={Reason}|(Error={Error})"; } }
36.238095
92
0.582786
[ "MIT" ]
eoin55/HoneyBear.Alexa
Src/HoneyBear.Alexa.Kodi/Proxies/Alexa/AudioRequestBundle.cs
1,524
C#
using System; class Program { static void Main() { string first = Console.ReadLine(); string secound = Console.ReadLine(); int age = int.Parse(Console.ReadLine()); Console.WriteLine($"Hello, {first} {secound}.\nYou are {age} years old."); } }
24
82
0.59375
[ "MIT" ]
GabrielRezendi/Programming-Fundamentals-2017
01.Short Fundamentals/10.DATA TYPES AND VARIABLES/07. Greeting/Program.cs
290
C#
namespace Panama.Core.Jobs { public interface IScheduler { void Start(); void Stop(); void Queue<T>(T job); void Queue<T>(T job, int minutes); int Count(); } }
17.75
42
0.521127
[ "MIT" ]
mrogunlana/Panama.Core
Panama/Jobs/IScheduler.cs
215
C#
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. using Azure.Core.Testing; using Azure.Identity; using Azure.Security.KeyVault.Keys.Cryptography; using NUnit.Framework; using System; using System.IO; using System.Security.Cryptography; using System.Threading.Tasks; namespace Azure.Security.KeyVault.Keys.Tests { public class CryptographyClientLiveTests : KeysTestBase { public CryptographyClientLiveTests(bool isAsync) : base(isAsync) { } [SetUp] public void ClearChallengeCacheforRecord() { // in record mode we reset the challenge cache before each test so that the challenge call // is always made. This allows tests to be replayed independently and in any order if (Mode == RecordedTestMode.Record || Mode == RecordedTestMode.Playback) { Client = GetClient(); ChallengeBasedAuthenticationPolicy.AuthenticationChallenge.ClearCache(); } } [Test] public async Task EncryptDecryptRoundTrip([Fields]EncryptionAlgorithm algorithm) { KeyVaultKey key = await CreateTestKey(algorithm); RegisterForCleanup(key.Name); CryptographyClient cryptoClient = GetCryptoClient(key.Id, forceRemote: true); byte[] data = new byte[32]; Recording.Random.NextBytes(data); EncryptResult encResult = await cryptoClient.EncryptAsync(algorithm, data); Assert.AreEqual(algorithm, encResult.Algorithm); Assert.AreEqual(key.Id, encResult.KeyId); Assert.IsNotNull(encResult.Ciphertext); DecryptResult decResult = await cryptoClient.DecryptAsync(algorithm, encResult.Ciphertext); Assert.AreEqual(algorithm, decResult.Algorithm); Assert.AreEqual(key.Id, decResult.KeyId); Assert.IsNotNull(decResult.Plaintext); CollectionAssert.AreEqual(data, decResult.Plaintext); } [Test] public async Task WrapUnwrapRoundTrip([Fields(Exclude = new[] { nameof(KeyWrapAlgorithm.A128KW), nameof(KeyWrapAlgorithm.A192KW), nameof(KeyWrapAlgorithm.A256KW) })]KeyWrapAlgorithm algorithm) { KeyVaultKey key = await CreateTestKey(algorithm); RegisterForCleanup(key.Name); CryptographyClient cryptoClient = GetCryptoClient(key.Id, forceRemote: true); byte[] data = new byte[32]; Recording.Random.NextBytes(data); WrapResult encResult = await cryptoClient.WrapKeyAsync(algorithm, data); Assert.AreEqual(algorithm, encResult.Algorithm); Assert.AreEqual(key.Id, encResult.KeyId); Assert.IsNotNull(encResult.EncryptedKey); UnwrapResult decResult = await cryptoClient.UnwrapKeyAsync(algorithm, encResult.EncryptedKey); Assert.AreEqual(algorithm, decResult.Algorithm); Assert.AreEqual(key.Id, decResult.KeyId); Assert.IsNotNull(decResult.Key); CollectionAssert.AreEqual(data, decResult.Key); } [Test] public async Task SignVerifyDataRoundTrip([Fields]SignatureAlgorithm algorithm) { KeyVaultKey key = await CreateTestKey(algorithm); RegisterForCleanup(key.Name); CryptographyClient cryptoClient = GetCryptoClient(key.Id, forceRemote: true); byte[] data = new byte[32]; Recording.Random.NextBytes(data); using HashAlgorithm hashAlgo = algorithm.GetHashAlgorithm(); byte[] digest = hashAlgo.ComputeHash(data); SignResult signResult = await cryptoClient.SignAsync(algorithm, digest); SignResult signDataResult = await cryptoClient.SignDataAsync(algorithm, data); Assert.AreEqual(algorithm, signResult.Algorithm); Assert.AreEqual(algorithm, signDataResult.Algorithm); Assert.AreEqual(key.Id, signResult.KeyId); Assert.AreEqual(key.Id, signDataResult.KeyId); Assert.NotNull(signResult.Signature); Assert.NotNull(signDataResult.Signature); VerifyResult verifyResult = await cryptoClient.VerifyAsync(algorithm, digest, signDataResult.Signature); VerifyResult verifyDataResult = await cryptoClient.VerifyDataAsync(algorithm, data, signResult.Signature); Assert.AreEqual(algorithm, verifyResult.Algorithm); Assert.AreEqual(algorithm, verifyDataResult.Algorithm); Assert.AreEqual(key.Id, verifyResult.KeyId); Assert.AreEqual(key.Id, verifyDataResult.KeyId); Assert.True(verifyResult.IsValid); Assert.True(verifyResult.IsValid); } [Test] public async Task SignVerifyDataStreamRoundTrip([Fields]SignatureAlgorithm algorithm) { KeyVaultKey key = await CreateTestKey(algorithm); RegisterForCleanup(key.Name); CryptographyClient cryptoClient = GetCryptoClient(key.Id, forceRemote: true); byte[] data = new byte[8000]; Recording.Random.NextBytes(data); using MemoryStream dataStream = new MemoryStream(data); using HashAlgorithm hashAlgo = algorithm.GetHashAlgorithm(); byte[] digest = hashAlgo.ComputeHash(dataStream); dataStream.Seek(0, SeekOrigin.Begin); SignResult signResult = await cryptoClient.SignAsync(algorithm, digest); SignResult signDataResult = await cryptoClient.SignDataAsync(algorithm, dataStream); Assert.AreEqual(algorithm, signResult.Algorithm); Assert.AreEqual(algorithm, signDataResult.Algorithm); Assert.AreEqual(key.Id, signResult.KeyId); Assert.AreEqual(key.Id, signDataResult.KeyId); Assert.NotNull(signResult.Signature); Assert.NotNull(signDataResult.Signature); dataStream.Seek(0, SeekOrigin.Begin); VerifyResult verifyResult = await cryptoClient.VerifyAsync(algorithm, digest, signDataResult.Signature); VerifyResult verifyDataResult = await cryptoClient.VerifyDataAsync(algorithm, dataStream, signResult.Signature); Assert.AreEqual(algorithm, verifyResult.Algorithm); Assert.AreEqual(algorithm, verifyDataResult.Algorithm); Assert.AreEqual(key.Id, verifyResult.KeyId); Assert.AreEqual(key.Id, verifyDataResult.KeyId); Assert.True(verifyResult.IsValid); Assert.True(verifyResult.IsValid); } // We do not test using ES256K below since macOS doesn't support it; various ideas to work around that adversely affect runtime code too much. [Test] public async Task LocalSignVerifyRoundTrip([Fields(Exclude = new[] { nameof(SignatureAlgorithm.ES256K) })]SignatureAlgorithm algorithm) { #if NET461 if (algorithm.GetEcKeyCurveName() != default) { Assert.Ignore("Creating JsonWebKey with ECDsa is not supported on net461."); } #endif #if NETFRAMEWORK if (algorithm.GetRsaSignaturePadding() == RSASignaturePadding.Pss) { Assert.Ignore("RSA-PSS signature padding is not supported on .NET Framework."); } #endif KeyVaultKey key = await CreateTestKeyWithKeyMaterial(algorithm); RegisterForCleanup(key.Name); (CryptographyClient client, ICryptographyProvider remoteClient) = GetCryptoClient(key); byte[] data = new byte[32]; Recording.Random.NextBytes(data); using HashAlgorithm hashAlgo = algorithm.GetHashAlgorithm(); byte[] digest = hashAlgo.ComputeHash(data); // Sign locally... SignResult signResult = await client.SignAsync(algorithm, digest); Assert.AreEqual(algorithm, signResult.Algorithm); Assert.AreEqual(key.Key.Id, signResult.KeyId); Assert.NotNull(signResult.Signature); // ...and verify remotely. VerifyResult verifyResult = await remoteClient.VerifyAsync(algorithm, digest, signResult.Signature); Assert.AreEqual(algorithm, verifyResult.Algorithm); Assert.AreEqual(key.Key.Id, verifyResult.KeyId); Assert.IsTrue(verifyResult.IsValid); } [Test] public async Task LocalSignVerifyRoundTripOnFramework([Fields(nameof(SignatureAlgorithm.PS256), nameof(SignatureAlgorithm.PS384), nameof(SignatureAlgorithm.PS512))]SignatureAlgorithm algorithm) { #if !NETFRAMEWORK // RSA-PSS is not supported on .NET Framework so recorded tests will fall back to the remote client. Assert.Ignore("RSA-PSS is supported on .NET Core so local tests will pass. This test method is to test that on .NET Framework RSA-PSS sign/verify attempts fall back to the remote client."); #endif KeyVaultKey key = await CreateTestKeyWithKeyMaterial(algorithm); RegisterForCleanup(key.Name); (CryptographyClient client, ICryptographyProvider remoteClient) = GetCryptoClient(key); byte[] data = new byte[32]; Recording.Random.NextBytes(data); using HashAlgorithm hashAlgo = algorithm.GetHashAlgorithm(); byte[] digest = hashAlgo.ComputeHash(data); // Sign locally... SignResult signResult = await client.SignAsync(algorithm, digest); Assert.AreEqual(algorithm, signResult.Algorithm); Assert.AreEqual(key.Key.Id, signResult.KeyId); Assert.NotNull(signResult.Signature); // ...and verify remotely. VerifyResult verifyResult = await remoteClient.VerifyAsync(algorithm, digest, signResult.Signature); Assert.AreEqual(algorithm, verifyResult.Algorithm); Assert.AreEqual(key.Key.Id, verifyResult.KeyId); Assert.IsTrue(verifyResult.IsValid); } [Test] public async Task SignLocalVerifyRoundTrip([Fields(Exclude = new[] { nameof(SignatureAlgorithm.ES256K) })]SignatureAlgorithm algorithm) { #if NET461 if (algorithm.GetEcKeyCurveName() != default) { Assert.Ignore("Creating JsonWebKey with ECDsa is not supported on net461."); } #endif #if NETFRAMEWORK if (algorithm.GetRsaSignaturePadding() == RSASignaturePadding.Pss) { Assert.Ignore("RSA-PSS signature padding is not supported on .NET Framework."); } #endif KeyVaultKey key = await CreateTestKey(algorithm); RegisterForCleanup(key.Name); CryptographyClient client = GetCryptoClient(key.Id); byte[] data = new byte[32]; Recording.Random.NextBytes(data); using HashAlgorithm hashAlgo = algorithm.GetHashAlgorithm(); byte[] digest = hashAlgo.ComputeHash(data); // Should sign remotely... SignResult signResult = await client.SignAsync(algorithm, digest); Assert.AreEqual(algorithm, signResult.Algorithm); Assert.AreEqual(key.Key.Id, signResult.KeyId); Assert.NotNull(signResult.Signature); // ...and verify locally. VerifyResult verifyResult = await client.VerifyAsync(algorithm, digest, signResult.Signature); Assert.AreEqual(algorithm, verifyResult.Algorithm); Assert.AreEqual(key.Key.Id, verifyResult.KeyId); Assert.IsTrue(verifyResult.IsValid); } [Test] public async Task SignLocalVerifyRoundTripFramework([Fields(nameof(SignatureAlgorithm.PS256), nameof(SignatureAlgorithm.PS384), nameof(SignatureAlgorithm.PS512))]SignatureAlgorithm algorithm) { #if !NETFRAMEWORK // RSA-PSS is not supported on .NET Framework so recorded tests will fall back to the remote client. Assert.Ignore("RSA-PSS is supported on .NET Core so local tests will pass. This test method is to test that on .NET Framework RSA-PSS sign/verify attempts fall back to the remote client."); #endif KeyVaultKey key = await CreateTestKey(algorithm); RegisterForCleanup(key.Name); CryptographyClient client = GetCryptoClient(key.Properties.Id); byte[] data = new byte[32]; Recording.Random.NextBytes(data); using HashAlgorithm hashAlgo = algorithm.GetHashAlgorithm(); byte[] digest = hashAlgo.ComputeHash(data); // Should sign remotely... SignResult signResult = await client.SignAsync(algorithm, digest); Assert.AreEqual(algorithm, signResult.Algorithm); Assert.AreEqual(key.Key.Id, signResult.KeyId); Assert.NotNull(signResult.Signature); // ...and verify locally. VerifyResult verifyResult = await client.VerifyAsync(algorithm, digest, signResult.Signature); Assert.AreEqual(algorithm, verifyResult.Algorithm); Assert.AreEqual(key.Key.Id, verifyResult.KeyId); Assert.IsTrue(verifyResult.IsValid); } private async Task<KeyVaultKey> CreateTestKey(EncryptionAlgorithm algorithm) { string keyName = Recording.GenerateId(); switch (algorithm.ToString()) { case EncryptionAlgorithm.Rsa15Value: case EncryptionAlgorithm.RsaOaepValue: case EncryptionAlgorithm.RsaOaep256Value: return await Client.CreateKeyAsync(keyName, KeyType.Rsa); default: throw new ArgumentException("Invalid Algorithm", nameof(algorithm)); } } private async Task<KeyVaultKey> CreateTestKey(KeyWrapAlgorithm algorithm) { string keyName = Recording.GenerateId(); switch (algorithm.ToString()) { case KeyWrapAlgorithm.Rsa15Value: case KeyWrapAlgorithm.RsaOaepValue: case KeyWrapAlgorithm.RsaOaep256Value: return await Client.CreateKeyAsync(keyName, KeyType.Rsa); default: throw new ArgumentException("Invalid Algorithm", nameof(algorithm)); } } private CryptographyClient GetCryptoClient(Uri keyId, bool forceRemote = false, TestRecording recording = null) { recording ??= Recording; CryptographyClient client = new CryptographyClient(keyId, recording.GetCredential(new DefaultAzureCredential()), recording.InstrumentClientOptions(new CryptographyClientOptions()), forceRemote); return InstrumentClient(client); } private (CryptographyClient, ICryptographyProvider) GetCryptoClient(KeyVaultKey key, TestRecording recording = null) { recording ??= Recording; CryptographyClient client = new CryptographyClient(key, recording.GetCredential(new DefaultAzureCredential()), recording.InstrumentClientOptions(new CryptographyClientOptions())); CryptographyClient clientProxy = InstrumentClient(client); ICryptographyProvider remoteClientProxy = null; if (client.RemoteClient is RemoteCryptographyClient remoteClient) { remoteClientProxy = InstrumentClient(remoteClient); } return (clientProxy, remoteClientProxy); } private async Task<KeyVaultKey> CreateTestKey(SignatureAlgorithm algorithm) { string keyName = Recording.GenerateId(); switch (algorithm.ToString()) { case SignatureAlgorithm.RS256Value: case SignatureAlgorithm.RS384Value: case SignatureAlgorithm.RS512Value: case SignatureAlgorithm.PS256Value: case SignatureAlgorithm.PS384Value: case SignatureAlgorithm.PS512Value: return await Client.CreateKeyAsync(keyName, KeyType.Rsa); case SignatureAlgorithm.ES256Value: return await Client.CreateEcKeyAsync(new CreateEcKeyOptions(keyName, false) { CurveName = KeyCurveName.P256 }); case SignatureAlgorithm.ES256KValue: return await Client.CreateEcKeyAsync(new CreateEcKeyOptions(keyName, false) { CurveName = KeyCurveName.P256K }); case SignatureAlgorithm.ES384Value: return await Client.CreateEcKeyAsync(new CreateEcKeyOptions(keyName, false) { CurveName = KeyCurveName.P384 }); case SignatureAlgorithm.ES512Value: return await Client.CreateEcKeyAsync(new CreateEcKeyOptions(keyName, false) { CurveName = KeyCurveName.P521 }); default: throw new ArgumentException("Invalid Algorithm", nameof(algorithm)); } } private async Task<KeyVaultKey> CreateTestKeyWithKeyMaterial(SignatureAlgorithm algorithm) { string keyName = Recording.GenerateId(); JsonWebKey keyMaterial = null; switch (algorithm.ToString()) { case SignatureAlgorithm.PS256Value: case SignatureAlgorithm.PS384Value: case SignatureAlgorithm.PS512Value: case SignatureAlgorithm.RS256Value: case SignatureAlgorithm.RS384Value: case SignatureAlgorithm.RS512Value: using (RSA rsa = RSA.Create()) { RSAParameters rsaParameters = new RSAParameters { D = new byte[] { 0x8a, 0x5a, 0x7f, 0x16, 0x29, 0x95, 0x8b, 0x84, 0xeb, 0x8c, 0xba, 0x93, 0xad, 0xbf, 0x40, 0xa2, 0xcc, 0xb9, 0xe9, 0xf8, 0xaa, 0x42, 0x78, 0x24, 0x5d, 0xdf, 0x99, 0xa1, 0x51, 0xd5, 0x1b, 0xaa, 0xfe, 0x0a, 0xa2, 0x82, 0x49, 0xd3, 0x19, 0x9c, 0xfd, 0x48, 0x92, 0xcc, 0x44, 0x98, 0xaf, 0xbf, 0x09, 0xf9, 0x4f, 0xff, 0xcc, 0x49, 0x75, 0x71, 0x27, 0xe1, 0xd8, 0xe2, 0xf2, 0xb7, 0x75, 0x5f, 0x5b, 0x75, 0x75, 0xff, 0x9f, 0xaa, 0x0d, 0xb5, 0x9a, 0x49, 0xff, 0x0b, 0x85, 0xb7, 0x05, 0xb6, 0x8b, 0xfb, 0x1c, 0x7b, 0x2b, 0xf8, 0xf7, 0x9d, 0xad, 0x4b, 0xe7, 0x30, 0x89, 0x13, 0x9d, 0x2b, 0x7f, 0x40, 0x34, 0x3d, 0x8e, 0x38, 0x43, 0x84, 0x19, 0x67, 0xae, 0xab, 0x65, 0xa3, 0xfd, 0x01, 0xcd, 0x2d, 0x5c, 0x87, 0x9f, 0xb7, 0x07, 0x98, 0x82, 0x74, 0x13, 0x69, 0xd1, 0xba, 0x6c, 0xea, 0xf9, 0x54, 0x59, 0xa1, 0x3d, 0x8a, 0xaf, 0x4c, 0xa6, 0x22, 0xde, 0x2a, 0xe3, 0xc1, 0x68, 0x4e, 0xc4, 0x5f, 0x49, 0xe6, 0x78, 0xb6, 0x7c, 0xa7, 0x90, 0xeb, 0xa2, 0x78, 0x93, 0xb4, 0xbb, 0xd2, 0x59, 0x13, 0xe9, 0x20, 0xf5, 0x1a, 0xe5, 0x27, 0x27, 0x6c, 0x98, 0x9e, 0x20, 0x73, 0xc6, 0x61, 0x4f, 0x01, 0x10, 0xf7, 0xb7, 0xe8, 0x17, 0x5f, 0x0e, 0x6b, 0x2b, 0x02, 0xf5, 0xe7, 0x4e, 0x16, 0xcb, 0xd7, 0x6d, 0xb3, 0x80, 0x17, 0xac, 0xad, 0x5c, 0x48, 0x16, 0xf1, 0x2a, 0xf2, 0xde, 0x14, 0xb4, 0x1b, 0x1a, 0x52, 0x11, 0x75, 0x05, 0xd8, 0x2e, 0x37, 0xe3, 0x31, 0xa5, 0x81, 0xa3, 0x29, 0x20, 0xae, 0x6f, 0x52, 0xf6, 0xe4, 0xd1, 0xc2, 0x73, 0x3f, 0x2e, 0x56, 0x8a, 0xa1, 0xc3, 0x0c, 0x4c, 0x1d, 0xb4, 0x77, 0xb9, 0x2a, 0xd4, 0x88, 0xc1, 0xb3, 0x3e, 0x2b, 0xd1, 0x98, 0x49, 0x8d }, DP = new byte[] { 0x05, 0x0c, 0x0c, 0xe9, 0x95, 0x77, 0x4d, 0x0f, 0x1e, 0x4a, 0x95, 0xbf, 0xcb, 0x0e, 0x03, 0x89, 0x6f, 0xe6, 0x56, 0x54, 0xb6, 0x5a, 0x19, 0xdd, 0x7e, 0xde, 0x06, 0xce, 0xdc, 0x1b, 0x76, 0xa1, 0xaa, 0x02, 0xa6, 0x77, 0x52, 0xa4, 0xbf, 0x4b, 0x18, 0x9a, 0x91, 0xc5, 0x86, 0x4a, 0xa2, 0x5f, 0xcc, 0x2c, 0x3e, 0x18, 0x75, 0x75, 0xb3, 0xb4, 0x85, 0xbd, 0x6a, 0x75, 0x01, 0x88, 0xd7, 0xb6, 0x63, 0xb8, 0x4e, 0xed, 0x69, 0x53, 0xb2, 0xb3, 0x80, 0xf3, 0x24, 0x4c, 0x18, 0x21, 0x18, 0xf5, 0xd0, 0xea, 0xf3, 0x53, 0x49, 0x74, 0x5a, 0xc5, 0x07, 0xe6, 0xbc, 0xe0, 0x48, 0x6b, 0xa0, 0xcf, 0x0e, 0x27, 0x80, 0xde, 0x3e, 0x65, 0x30, 0x1e, 0x8a, 0xcb, 0x7b, 0x55, 0xb1, 0xd4, 0x3e, 0xe8, 0x3d, 0xb0, 0xf1, 0x2a, 0x5d, 0x63, 0x33, 0x05, 0x04, 0xc0, 0x52, 0x4d, 0x68, 0xff, 0x28, 0xf9, }, DQ = new byte[] { 0xcc, 0xf9, 0x20, 0x49, 0xfd, 0x71, 0x7b, 0x95, 0xb4, 0x6e, 0xb6, 0xdb, 0x3f, 0x99, 0x5c, 0x2a, 0xf1, 0xf7, 0x17, 0x35, 0x29, 0xc7, 0x2a, 0x87, 0x6b, 0x0c, 0x8b, 0xad, 0x35, 0x00, 0xff, 0xa2, 0xd8, 0x22, 0x75, 0x35, 0x3e, 0x6d, 0xd9, 0x3d, 0x39, 0x1d, 0x06, 0x65, 0x26, 0x08, 0x19, 0xb0, 0xe7, 0xd7, 0x6d, 0xd0, 0xec, 0xc4, 0xe7, 0xcb, 0x2a, 0xe4, 0x2d, 0x78, 0x09, 0x9e, 0x5d, 0x86, 0x8c, 0x85, 0x27, 0xb7, 0x4f, 0xed, 0x22, 0xe3, 0xe5, 0x7a, 0x0a, 0xc0, 0xe0, 0x6d, 0xe7, 0x6a, 0x5c, 0x8c, 0xb6, 0x6a, 0x79, 0x72, 0x6d, 0x12, 0xa4, 0x65, 0x5b, 0xa0, 0xa9, 0xcb, 0x8d, 0x2b, 0xeb, 0x1b, 0x81, 0x84, 0x26, 0xf7, 0x00, 0x49, 0x25, 0x4a, 0xc9, 0xda, 0x43, 0x60, 0x15, 0x47, 0x65, 0x94, 0xe3, 0xb9, 0x0b, 0x00, 0xcb, 0x07, 0x3f, 0x5d, 0xdf, 0x19, 0x4b, 0x0f, 0x84, 0x17, }, Exponent = new byte[] { 0x01, 0x00, 0x01, }, InverseQ = new byte[] { 0xc2, 0xb4, 0x1c, 0x29, 0x19, 0x9e, 0x24, 0xe3, 0x38, 0xe0, 0x9b, 0x25, 0x12, 0x25, 0x5b, 0x5f, 0xdb, 0x45, 0x72, 0xe8, 0xbe, 0x25, 0x4e, 0xc7, 0x0d, 0x15, 0x05, 0x18, 0xa8, 0x47, 0xf7, 0x87, 0xa4, 0xa5, 0x02, 0xa5, 0xa0, 0x00, 0xd9, 0x98, 0xf2, 0xf4, 0x33, 0x64, 0x80, 0x30, 0xb9, 0x6c, 0xcc, 0x83, 0xc0, 0x7a, 0xf3, 0x32, 0xfd, 0x60, 0x91, 0x02, 0x61, 0x9e, 0x79, 0x68, 0xcd, 0x84, 0x6c, 0x39, 0x1e, 0x47, 0xb1, 0x13, 0xf9, 0xea, 0x2b, 0xc9, 0x65, 0xd5, 0x1d, 0x8a, 0x47, 0xf4, 0xa3, 0xf2, 0x01, 0x50, 0x0a, 0xad, 0x72, 0xcd, 0xe3, 0x19, 0x67, 0x3e, 0x15, 0x8d, 0x40, 0x7c, 0x8f, 0x30, 0xa0, 0xc9, 0x3b, 0xf9, 0x96, 0xba, 0x58, 0xae, 0xd6, 0xc8, 0x26, 0xa6, 0xa2, 0xa8, 0x0f, 0x96, 0x2b, 0x28, 0xf8, 0x39, 0x11, 0xa1, 0xf0, 0x6a, 0xc5, 0xdd, 0x99, 0x5b, 0x18, 0x1a, }, Modulus = new byte[] { 0xc7, 0x61, 0xab, 0x5f, 0xc0, 0x4c, 0x50, 0xdf, 0x3a, 0x21, 0x87, 0x41, 0x6b, 0x42, 0x3d, 0xbd, 0xd7, 0x81, 0xe5, 0xed, 0xc0, 0x59, 0xe6, 0xa0, 0xd0, 0xcc, 0x7e, 0xd7, 0xbe, 0x0f, 0xcd, 0xd5, 0x3d, 0x23, 0x08, 0xa2, 0x81, 0x94, 0xc8, 0x60, 0xd0, 0xfc, 0xe8, 0xf6, 0xdf, 0x22, 0xe8, 0xa1, 0xae, 0x4c, 0xab, 0x78, 0xe6, 0x7d, 0x65, 0x1c, 0x20, 0x1a, 0x7b, 0xf2, 0xd9, 0x10, 0xa2, 0x85, 0x28, 0x81, 0xc0, 0x1d, 0x4d, 0xc6, 0xf0, 0x4f, 0x36, 0xe0, 0x83, 0x14, 0x4c, 0x30, 0x5c, 0xef, 0x9c, 0x93, 0x26, 0x7f, 0xf4, 0x67, 0x93, 0x47, 0xe8, 0x3b, 0x27, 0x91, 0xfb, 0xe9, 0xfd, 0xbb, 0x67, 0x9a, 0xa6, 0x0f, 0x84, 0x47, 0xae, 0x55, 0x55, 0x38, 0x32, 0x68, 0xfc, 0x97, 0x42, 0xc1, 0x77, 0x4e, 0x7c, 0x8e, 0xc2, 0x24, 0xe9, 0x9c, 0x29, 0x12, 0xf6, 0xce, 0x90, 0xa3, 0x77, 0x05, 0xaa, 0xc7, 0x63, 0x62, 0x3b, 0x38, 0xf6, 0xee, 0x77, 0x46, 0x0b, 0xed, 0xca, 0xca, 0x6e, 0x6e, 0x08, 0xd1, 0x5e, 0xa9, 0xd1, 0x86, 0xea, 0xdf, 0xcc, 0x7c, 0x17, 0x9c, 0xf2, 0xae, 0x4c, 0x02, 0xe8, 0x47, 0xcf, 0x95, 0xf0, 0x7c, 0x2f, 0x6f, 0x9b, 0x97, 0x87, 0xe7, 0x98, 0xf4, 0x07, 0x4d, 0xd5, 0x2d, 0xf3, 0x5e, 0x91, 0x52, 0x57, 0x99, 0xbd, 0x54, 0xb5, 0x04, 0xef, 0xc8, 0x14, 0x0b, 0xe0, 0xb3, 0x0b, 0x72, 0xb8, 0x43, 0x0e, 0x1f, 0x13, 0x79, 0xa1, 0x88, 0xc9, 0x96, 0x39, 0x68, 0xcb, 0x16, 0x2c, 0xfd, 0xa4, 0x5f, 0x3a, 0x0d, 0x31, 0xd8, 0xc1, 0x12, 0x02, 0xf7, 0x3b, 0x6c, 0xa1, 0x30, 0xad, 0x6d, 0xa4, 0xcf, 0x42, 0xe2, 0xb6, 0x5c, 0xdc, 0x33, 0xf5, 0x17, 0xda, 0x3a, 0x66, 0xdf, 0xdf, 0x6a, 0x04, 0x51, 0x84, 0x8b, 0x3d, 0x8b, 0x7b, 0x9f, 0x7a, 0xd7, 0xdf, 0xad, }, P = new byte[] { 0xca, 0x2e, 0x9f, 0xdd, 0x52, 0x22, 0x31, 0xd3, 0x75, 0x50, 0x1f, 0xab, 0x00, 0x48, 0x62, 0xcf, 0x17, 0x1f, 0xa5, 0x17, 0xe4, 0x46, 0x22, 0xfc, 0xfc, 0x2b, 0x73, 0x4e, 0xb2, 0x1f, 0xb9, 0x72, 0xa4, 0xaa, 0x52, 0xee, 0x05, 0xa4, 0xeb, 0x51, 0xfa, 0xa0, 0x9b, 0x3d, 0xf9, 0xc4, 0x04, 0x22, 0xd2, 0xf0, 0xb4, 0xff, 0xee, 0x2f, 0xc0, 0x81, 0x2a, 0x3d, 0x5e, 0xe4, 0x75, 0x55, 0xf2, 0x1c, 0x13, 0xd3, 0x59, 0x26, 0x38, 0x81, 0x91, 0xb6, 0xb6, 0x8e, 0x47, 0x3c, 0x27, 0x9e, 0x87, 0x07, 0x2d, 0xcf, 0xd7, 0xaa, 0x5f, 0x15, 0x50, 0xf5, 0xc7, 0x01, 0x5f, 0x9c, 0xae, 0x9d, 0xec, 0x63, 0xfc, 0x04, 0xda, 0xb7, 0xe7, 0x80, 0x14, 0x9c, 0xef, 0x6a, 0xbd, 0x36, 0x02, 0xce, 0xaa, 0xf3, 0x93, 0x46, 0x8c, 0xb9, 0x0b, 0x82, 0xe1, 0x5d, 0x39, 0xcb, 0x46, 0x5f, 0xa7, 0xd5, 0xbe, 0xef, }, Q = new byte[] { 0xfc, 0x74, 0x33, 0xc3, 0x32, 0x64, 0x9f, 0x78, 0xe7, 0xfd, 0x79, 0xc0, 0xb0, 0x60, 0x1f, 0x94, 0xc3, 0x3d, 0xd9, 0xfc, 0x02, 0xf7, 0x16, 0x2d, 0x47, 0x88, 0xfc, 0xf4, 0x13, 0xa3, 0xbf, 0x25, 0x80, 0x3c, 0x1b, 0x1d, 0x12, 0x43, 0x5c, 0xce, 0x22, 0xa4, 0x01, 0x7e, 0x04, 0x7a, 0xf3, 0x11, 0x66, 0x36, 0x49, 0x3c, 0x3b, 0x6f, 0x49, 0x69, 0x74, 0xd5, 0x35, 0x23, 0x90, 0x47, 0xb3, 0x15, 0xe7, 0xa5, 0x26, 0x48, 0x9d, 0xb5, 0x38, 0xa0, 0x44, 0x58, 0x63, 0xb2, 0xdd, 0x94, 0xaf, 0x2e, 0x42, 0x08, 0x25, 0x19, 0x4a, 0x7b, 0xe5, 0x72, 0xbe, 0xd5, 0xa3, 0x92, 0x0b, 0xba, 0xf7, 0x5f, 0x0b, 0x18, 0xa6, 0x62, 0x19, 0x6d, 0x53, 0xc1, 0x8a, 0x86, 0x19, 0x43, 0x53, 0xa4, 0x3a, 0x53, 0x94, 0xd9, 0x99, 0x8b, 0x3a, 0xe4, 0x1e, 0xc5, 0x86, 0x15, 0x89, 0x53, 0xb5, 0x3d, 0x8b, 0x23, }, }; rsa.ImportParameters(rsaParameters); keyMaterial = new JsonWebKey(rsa, includePrivateParameters: true); } break; case SignatureAlgorithm.ES256Value: case SignatureAlgorithm.ES256KValue: case SignatureAlgorithm.ES384Value: case SignatureAlgorithm.ES512Value: #if NET461 Assert.Ignore("Creating JsonWebKey with ECDsa is not supported on net461."); #else KeyCurveName curveName = algorithm.GetEcKeyCurveName(); ECCurve curve = ECCurve.CreateFromOid(curveName.Oid); using (ECDsa ecdsa = ECDsa.Create()) { try { ecdsa.GenerateKey(curve); keyMaterial = new JsonWebKey(ecdsa, includePrivateParameters: true); } catch (NotSupportedException) { Assert.Inconclusive("This platform does not support OID {0}", curveName.Oid); } } #endif break; default: throw new ArgumentException("Invalid Algorithm", nameof(algorithm)); } KeyVaultKey key = await Client.ImportKeyAsync(keyName, keyMaterial); keyMaterial.Id = key.Key.Id; key.Key = keyMaterial; return key; } } }
53.445438
206
0.569454
[ "MIT" ]
LingyunSu/azure-sdk-for-net
sdk/keyvault/Azure.Security.KeyVault.Keys/tests/CryptographyClientLiveTests.cs
29,878
C#
// *** WARNING: this file was generated by the Pulumi Terraform Bridge (tfgen) Tool. *** // *** Do not edit by hand unless you're certain you know what you are doing! *** using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Threading.Tasks; using Pulumi.Serialization; namespace Pulumi.Nsxt.Inputs { public sealed class LBHTTPForwardingRuleMethodConditionGetArgs : Pulumi.ResourceArgs { [Input("inverse")] public Input<bool>? Inverse { get; set; } [Input("method", required: true)] public Input<string> Method { get; set; } = null!; public LBHTTPForwardingRuleMethodConditionGetArgs() { } } }
27.307692
88
0.680282
[ "ECL-2.0", "Apache-2.0" ]
nvpnathan/pulumi-nsxt
sdk/dotnet/Inputs/LBHTTPForwardingRuleMethodConditionGetArgs.cs
710
C#
//Problem 8. Isosceles Triangle //Write a program that prints an isosceles triangle of 9 copyright symbols ©, something like this: // © // © © // © © //© © © © //Note: The © symbol may be displayed incorrectly at the console so you may need to change the console character encoding to UTF-8 and assign a Unicode-friendly font in the console. //Note: Under old versions of Windows the © symbol may still be displayed incorrectly, regardless of how much effort you put to fix it. using System; class TriangleWith9CopyrightSymbols { static void Main() { // change the console character encoding to UTF-8 with System.Console.OutputEncoding = System.Text.Encoding.UTF8; Console.OutputEncoding = System.Text.Encoding.UTF8; char symbol = (char)0xA9; //// other way //char symbol = '\u00A9'; Console.WriteLine(" " + symbol + " "); Console.WriteLine(" " + symbol + " " + symbol + " "); Console.WriteLine(" " + symbol + " " + symbol + " "); Console.WriteLine(symbol + " " + symbol + " " + symbol + " " + symbol); // You may need to change the font of your console to some font that supports the “©” symbol, e.g. “Consolas” or “Lucida Console” to display it right. } }
37.705882
181
0.636505
[ "MIT" ]
petyakostova/Telerik-Academy
C#/C# 1/2. PrimitiveDataTypesVariables-Homework/Isosceles-Triangle/TriangleWith9CopyrightSymbols.cs
1,309
C#
/* * author:symbolspace * e-mail:symbolspace@outlook.com */ using System; using System.Drawing; namespace Symbol.Drawing { /// <summary> /// 水印上下文类 /// </summary> public class ImageWaterMarkContext { /// <summary> /// 默认边缘距离(5像素) /// </summary> public static readonly Padding DefaultMargin = new Padding(5); /// <summary> /// 默认文本字体(Arial,18号,粗体) /// </summary> public static readonly Font DefaultTextFont = new Font("楷体", 18F, FontStyle.Regular, GraphicsUnit.Pixel); /// <summary> /// 默认文本背景颜色(Color.WhiteSmoke,雾白色) /// </summary> public static readonly Color DefaultTextBackColor = Color.WhiteSmoke; /// <summary> /// 默认文本前景颜色(Color.Black,黑色) /// </summary> public static readonly Color DefaultTextForeColor = Color.Black; /// <summary> /// 默认文本边框颜色(Color.DimGray,暗灰色) /// </summary> public static readonly Color DefaultBorderColor = Color.DimGray; /// <summary> /// 水印位置 /// </summary> public ImageWaterMarkLocation Location { get; set; } /// <summary> /// 边缘距离(单位:像素) /// </summary> public Padding Margin { get; set; } /// <summary> /// 文本水印 /// </summary> public string Text { get; private set; } /// <summary> /// 文本字体 /// </summary> public Font TextFont { get; set; } /// <summary> /// 文本背景颜色 /// </summary> public Color TextBackColor { get; set; } /// <summary> /// 文本前景颜色 /// </summary> public Color TextForeColor { get; set; } /// <summary> /// 文本边框颜色 /// </summary> public Color TextBorderColor { get; set; } /// <summary> /// 透明度,默认是 0.51,即51的透明度,有效值0.00F-1.00F,值越大越不透明。 /// </summary> public float Opacity { get; set; } /// <summary> /// 图像水印 /// </summary> public Bitmap Image { get; private set; } /// <summary> /// 创建水印上下文实例(文本水印) /// </summary> /// <param name="text">文本水印</param> /// <param name="location">水印位置,默认为下-右</param> public ImageWaterMarkContext(string text, ImageWaterMarkLocation location = ImageWaterMarkLocation.BottomRight) : this(location) { if (string.IsNullOrEmpty(text)) throw new ArgumentNullException("text", "文本水印内容不能为null或“”。"); Text = text; } /// <summary> /// 创建水印上下文实例(图像水印) /// </summary> /// <param name="image">图像水印</param> /// <param name="location">水印位置,默认为下-右</param> public ImageWaterMarkContext(Bitmap image, ImageWaterMarkLocation location = ImageWaterMarkLocation.BottomRight) : this(location) { if (image == null) throw new ArgumentNullException("image", "图像水印不能为null。"); Image = image; } private ImageWaterMarkContext(ImageWaterMarkLocation location) { Location = location; Margin = DefaultMargin; TextFont = DefaultTextFont; TextBackColor = TextBackColor; TextForeColor = DefaultTextForeColor; TextBorderColor = DefaultBorderColor; Opacity = 0.51F; } } }
31.850467
120
0.538146
[ "MIT" ]
symbolspace/Symbol.Drawing
src/Symbol.Drawing/ImageWaterMarkContext.cs
3,856
C#
using Verse; namespace BetterPawnControl { [StaticConstructorOnStartup] class RestrictManager : Manager<RestrictLink> { internal static void DeletePolicy(Policy policy) { //delete if not default AssignPolicy if (policy != null && policy.id > 0) { links.RemoveAll(x => x.zone == policy.id); policies.Remove(policy); int mapId = Find.CurrentMap.uniqueID; foreach (MapActivePolicy m in activePolicies) { if (m.activePolicy.id == policy.id) { m.activePolicy = policies[0]; DirtyPolicy = true; } } } } internal static void DeleteLinksInMap(int mapId) { links.RemoveAll(x => x.mapId == mapId); } internal static void DeleteMap(MapActivePolicy map) { activePolicies.Remove(map); } } }
27.526316
61
0.486616
[ "MIT" ]
Dango998/BetterPawnControl
Source/Managers/RestrictManager.cs
1,048
C#
// This source code is dual-licensed under the Apache License, version // 2.0, and the Mozilla Public License, version 2.0. // // The APL v2.0: // //--------------------------------------------------------------------------- // Copyright (c) 2007-2020 VMware, 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 // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. //--------------------------------------------------------------------------- // // The MPL v2.0: // //--------------------------------------------------------------------------- // 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 https://mozilla.org/MPL/2.0/. // // Copyright (c) 2007-2020 VMware, Inc. All rights reserved. //--------------------------------------------------------------------------- using System; using RabbitMQ.Client.client.framing; using RabbitMQ.Client.Impl; namespace RabbitMQ.Client.Framing.Impl { internal readonly struct ExchangeDelete : IOutgoingAmqpMethod { // deprecated // ushort _reserved1 public readonly string _exchange; public readonly bool _ifUnused; public readonly bool _nowait; public ExchangeDelete(string Exchange, bool IfUnused, bool Nowait) { _exchange = Exchange; _ifUnused = IfUnused; _nowait = Nowait; } public ProtocolCommandId ProtocolCommandId => ProtocolCommandId.ExchangeDelete; public int WriteTo(Span<byte> span) { int offset = WireFormatting.WriteShort(ref span.GetStart(), default); offset += WireFormatting.WriteShortstr(ref span.GetOffset(offset), _exchange); return offset + WireFormatting.WriteBits(ref span.GetOffset(offset), _ifUnused, _nowait); } public int GetRequiredBufferSize() { int bufferSize = 2 + 1 + 1; // bytes for _reserved1, length of _exchange, bit fields bufferSize += WireFormatting.GetByteCount(_exchange); // _exchange in bytes return bufferSize; } } }
37.295775
101
0.592145
[ "MPL-2.0-no-copyleft-exception", "MPL-2.0", "Apache-2.0" ]
10088/rabbitmq-dotnet-client
projects/RabbitMQ.Client/client/framing/ExchangeDelete.cs
2,648
C#
namespace BusinessLogic { public interface IAuditable { } }
13.2
33
0.712121
[ "MIT" ]
PacktPublishing/Entity-Framework-Core-Cookbook
Chapter02/BusinessLogic/IAuditable.cs
68
C#
using System.IO; using System.Runtime.Serialization; using WolvenKit.CR2W.Reflection; using FastMember; using static WolvenKit.CR2W.Types.Enums; namespace WolvenKit.CR2W.Types { [DataContract(Namespace = "")] [REDMeta] public class CBehTreeNodeRiderIdleDynamicRootDefinition : CBehTreeNodeBaseIdleDynamicRootDefinition { public CBehTreeNodeRiderIdleDynamicRootDefinition(CR2WFile cr2w, CVariable parent, string name) : base(cr2w, parent, name){ } public static new CVariable Create(CR2WFile cr2w, CVariable parent, string name) => new CBehTreeNodeRiderIdleDynamicRootDefinition(cr2w, parent, name); public override void Read(BinaryReader file, uint size) => base.Read(file, size); public override void Write(BinaryWriter file) => base.Write(file); } }
34.434783
154
0.77399
[ "MIT" ]
DerinHalil/CP77Tools
CP77.CR2W/Types/W3/RTTIConvert/CBehTreeNodeRiderIdleDynamicRootDefinition.cs
770
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 wafv2-2019-07-29.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.WAFV2.Model { /// <summary> /// Container for the parameters to the DeleteRegexPatternSet operation. /// <note> /// <para> /// This is the latest version of <b>AWS WAF</b>, named AWS WAFV2, released in November, /// 2019. For information, including how to migrate your AWS WAF resources from the prior /// release, see the <a href="https://docs.aws.amazon.com/waf/latest/developerguide/waf-chapter.html">AWS /// WAF Developer Guide</a>. /// </para> /// </note> /// <para> /// Deletes the specified <a>RegexPatternSet</a>. /// </para> /// </summary> public partial class DeleteRegexPatternSetRequest : AmazonWAFV2Request { private string _id; private string _lockToken; private string _name; private Scope _scope; /// <summary> /// Gets and sets the property Id. /// <para> /// A unique identifier for the set. This ID is returned in the responses to create and /// list commands. You provide it to operations like update and delete. /// </para> /// </summary> [AWSProperty(Required=true, Min=1, Max=36)] public string Id { get { return this._id; } set { this._id = value; } } // Check to see if Id property is set internal bool IsSetId() { return this._id != null; } /// <summary> /// Gets and sets the property LockToken. /// <para> /// A token used for optimistic locking. AWS WAF returns a token to your get and list /// requests, to mark the state of the entity at the time of the request. To make changes /// to the entity associated with the token, you provide the token to operations like /// update and delete. AWS WAF uses the token to ensure that no changes have been made /// to the entity since you last retrieved it. If a change has been made, the update fails /// with a <code>WAFOptimisticLockException</code>. If this happens, perform another get, /// and use the new token returned by that operation. /// </para> /// </summary> [AWSProperty(Required=true, Min=1, Max=36)] public string LockToken { get { return this._lockToken; } set { this._lockToken = value; } } // Check to see if LockToken property is set internal bool IsSetLockToken() { return this._lockToken != null; } /// <summary> /// Gets and sets the property Name. /// <para> /// The name of the set. You cannot change the name after you create the set. /// </para> /// </summary> [AWSProperty(Required=true, Min=1, Max=128)] public string Name { get { return this._name; } set { this._name = value; } } // Check to see if Name property is set internal bool IsSetName() { return this._name != null; } /// <summary> /// Gets and sets the property Scope. /// <para> /// Specifies whether this is for an AWS CloudFront distribution or for a regional application. /// A regional application can be an Application Load Balancer (ALB), an API Gateway REST /// API, or an AppSync GraphQL API. /// </para> /// /// <para> /// To work with CloudFront, you must also specify the Region US East (N. Virginia) as /// follows: /// </para> /// <ul> <li> /// <para> /// CLI - Specify the Region when you use the CloudFront scope: <code>--scope=CLOUDFRONT /// --region=us-east-1</code>. /// </para> /// </li> <li> /// <para> /// API and SDKs - For all calls, use the Region endpoint us-east-1. /// </para> /// </li> </ul> /// </summary> [AWSProperty(Required=true)] public Scope Scope { get { return this._scope; } set { this._scope = value; } } // Check to see if Scope property is set internal bool IsSetScope() { return this._scope != null; } } }
34.124183
109
0.580349
[ "Apache-2.0" ]
PureKrome/aws-sdk-net
sdk/src/Services/WAFV2/Generated/Model/DeleteRegexPatternSetRequest.cs
5,221
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 CapModel { using System; using System.Collections.Generic; public partial class User { public int UserId { get; set; } public string UserName { get; set; } public string FirstName { get; set; } public string LastName { get; set; } public string Email { get; set; } public string VerCode { get; set; } public string isVerified { get; set; } public string Password { get; set; } public string UserType { get; set; } public virtual Recruiter Recruiter { get; set; } public virtual JobSeeker JobSeeker { get; set; } public virtual Company Company { get; set; } public virtual UserProfile UserProfile { get; set; } } }
35.818182
85
0.543147
[ "MIT" ]
kaukulpr/nsdk
CapModel/User.cs
1,182
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 ds-2015-04-16.normal.json service model. */ using System; using System.Collections.Generic; using System.Xml.Serialization; using System.Text; using System.IO; using Amazon.Runtime; using Amazon.Runtime.Internal; namespace Amazon.DirectoryService.Model { /// <summary> /// Container for the parameters to the EnableSso operation. /// Enables single sign-on for a directory. /// </summary> public partial class EnableSsoRequest : AmazonDirectoryServiceRequest { private string _directoryId; private string _password; private string _userName; /// <summary> /// Gets and sets the property DirectoryId. /// <para> /// The identifier of the directory for which to enable single-sign on. /// </para> /// </summary> public string DirectoryId { get { return this._directoryId; } set { this._directoryId = value; } } // Check to see if DirectoryId property is set internal bool IsSetDirectoryId() { return this._directoryId != null; } /// <summary> /// Gets and sets the property Password. /// <para> /// The password of an alternate account to use to enable single-sign on. This is only /// used for AD Connector directories. For more information, see the <i>UserName</i> parameter. /// </para> /// </summary> public string Password { get { return this._password; } set { this._password = value; } } // Check to see if Password property is set internal bool IsSetPassword() { return this._password != null; } /// <summary> /// Gets and sets the property UserName. /// <para> /// The username of an alternate account to use to enable single-sign on. This is only /// used for AD Connector directories. This account must have privileges to add a service /// principal name. /// </para> /// /// <para> /// If the AD Connector service account does not have privileges to add a service principal /// name, you can specify an alternate account with the <i>UserName</i> and <i>Password</i> /// parameters. These credentials are only used to enable single sign-on and are not stored /// by the service. The AD Connector service account is not changed. /// </para> /// </summary> public string UserName { get { return this._userName; } set { this._userName = value; } } // Check to see if UserName property is set internal bool IsSetUserName() { return this._userName != null; } } }
33.190476
103
0.610904
[ "Apache-2.0" ]
Bio2hazard/aws-sdk-net
sdk/src/Services/DirectoryService/Generated/Model/EnableSsoRequest.cs
3,485
C#
// This file is part of Core WF which is licensed under the MIT license. // See LICENSE file in the project root for full license information. namespace CoreWf.Hosting { using System.Collections.Generic; // overriden by extensions that want to contribute additional // extensions and/or get notified when they are being used with a WorkflowInstance public interface IWorkflowInstanceExtension { IEnumerable<object> GetAdditionalExtensions(); // called with the targe instance under WorkflowInstance.Initialize void SetInstance(WorkflowInstanceProxy instance); } }
34.166667
86
0.749593
[ "MIT" ]
OIgnat/corewf
src/CoreWf/Hosting/IWorkflowInstanceExtension.cs
615
C#
using buildeR.BLL.Interfaces; using buildeR.Common.DTO.Webhooks.Github.PayloadDTO; using System; using System.Linq; using System.Collections.Generic; using System.Text; using System.Threading.Tasks; namespace buildeR.BLL.Services { public class WebhooksHandler : IWebhooksHandler { private readonly IBuildOperationsService _builder; public WebhooksHandler(IBuildOperationsService builder) { _builder = builder; } public async Task HandleGithubPushEvent(int projectId, PushGithubPayloadDTO payload) { //When commit is pushed to branch github send payload object with property //"refs": "refs/heads/*name of branch*" if (!payload.Ref.StartsWith("refs/heads/")) return; //I parse this property in branch name in the next line: var updatedBranch = payload.Ref.Substring(11); // TODO: replace fake build history id await _builder.StartBuild(projectId, 1); } } }
30.647059
92
0.658349
[ "MIT" ]
yermolenko-d/bsa-2020-buildeR
backend/buildeR.BLL/Services/WebhooksHandler.cs
1,044
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 medialive-2017-10-14.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.MediaLive.Model; using Amazon.Runtime; using Amazon.Runtime.Internal; using Amazon.Runtime.Internal.Transform; using Amazon.Runtime.Internal.Util; using ThirdParty.Json.LitJson; namespace Amazon.MediaLive.Model.Internal.MarshallTransformations { /// <summary> /// DvbTdtSettings Marshaller /// </summary> public class DvbTdtSettingsMarshaller : IRequestMarshaller<DvbTdtSettings, JsonMarshallerContext> { /// <summary> /// Unmarshaller the response from the service to the response class. /// </summary> /// <param name="requestObject"></param> /// <param name="context"></param> /// <returns></returns> public void Marshall(DvbTdtSettings requestObject, JsonMarshallerContext context) { if(requestObject.IsSetRepInterval()) { context.Writer.WritePropertyName("repInterval"); context.Writer.Write(requestObject.RepInterval); } } /// <summary> /// Singleton Marshaller. /// </summary> public readonly static DvbTdtSettingsMarshaller Instance = new DvbTdtSettingsMarshaller(); } }
32.790323
107
0.688637
[ "Apache-2.0" ]
Hazy87/aws-sdk-net
sdk/src/Services/MediaLive/Generated/Model/Internal/MarshallTransformations/DvbTdtSettingsMarshaller.cs
2,033
C#
namespace ishtar.emit { public enum FlowControl { None, Branch, Break, Call, Return, Throw } }
11.923077
27
0.451613
[ "MIT" ]
0xF6/mana_lang
runtime/ishtar.base/emit/FlowControl.cs
155
C#
using DadStormServices; using System; using System.Collections.Generic; namespace PuppetMaster.Command { public class ExitCommand : PuppetCommand { public ExitCommand(PuppetShell shell) : base(shell, "Exit", "Exit: Exites the application") { } public override void execute(string[] args) { if (args.Length != 0) { printMissUsage(args); return; } // Kill all programs foreach (KeyValuePair<string, List<IOperatorProcess>> entry in shell.operatorProxies) { foreach (IOperatorProcess opProxy in entry.Value) { try { opProxy.crash(); } catch (Exception e) { Console.WriteLine("[ExitCommand] Unable to call crash. Cause: {0}.", e.Message); } } } System.Environment.Exit(1); } } }
31.483871
104
0.517418
[ "MIT" ]
Vasco-jofra/dadstorm
PuppetMaster/Command/ExitCommand.cs
978
C#
#region Apache License Version 2.0 /*---------------------------------------------------------------- Copyright 2018 Jeffrey Su & Suzhou Senparc Network Technology Co.,Ltd. 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. Detail: https://github.com/JeffreySu/WeiXinMPSDK/blob/master/license.md ----------------------------------------------------------------*/ #endregion Apache License Version 2.0 /*---------------------------------------------------------------- Copyright (C) 2018 Senparc 文件名:IJsonResult.cs 文件功能描述:所有JSON返回结果基类 创建标识:Senparc - 20150211 修改标识:Senparc - 20170702 修改描述:v4.13.0 1、将 IWxJsonResult 定义移入到 WxResult.cs 文件 2、添加 ErrorCodeValue 只读属性 ----------------------------------------------------------------*/ using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Senparc.Weixin.Entities { /// <summary> /// 所有 JSON 格式返回值的API返回结果接口 /// </summary> public interface IJsonResult// : IJsonResultCallback { /// <summary> /// 返回结果信息 /// </summary> string errmsg { get; set; } /// <summary> /// errcode的 /// </summary> int ErrorCodeValue { get; } object P2PData { get; set; } } }
28.435484
90
0.581395
[ "Apache-2.0" ]
007008aabb/WeiXinMPSDK
src/Senparc.Weixin/Senparc.Weixin/Entities/JsonResult/Interface/IJsonResult.cs
1,907
C#
using System.Threading.Tasks; namespace Confab.Shared.Abstractions.Events { public interface IEventHandler<in TEvent> where TEvent : class, IEvent { Task HandleAsync(TEvent @event); } }
23
74
0.714976
[ "MIT" ]
ArturWincenciak/confab
src/Shared/Confab.Shared.Abstractions/Events/IEventHandler.cs
209
C#
using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Windows; using System.Windows.Controls; using System.Windows.Documents; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Animation; using System.Windows.Shapes; using Microsoft.Phone.Controls; using Microsoft.Phone.Tasks; namespace Launchers { public partial class MediaPlayer : PhoneApplicationPage { public MediaPlayer() { InitializeComponent(); } private void btnLaunch_Click(object sender, RoutedEventArgs e) { MediaPlayerLauncher mediaPlayerLauncher = new MediaPlayerLauncher(); mediaPlayerLauncher.Media = new Uri(txtMediaURL.Text, UriKind.Absolute); mediaPlayerLauncher.Location = MediaLocationType.Data; mediaPlayerLauncher.Controls = MediaPlaybackControls.Pause | MediaPlaybackControls.Stop; mediaPlayerLauncher.Show(); } } }
29.470588
100
0.717565
[ "MIT" ]
noenemy/Book-Windows-Phone-Programming-Bible
Chapter 14/Launchers/Launchers/MediaPlayer.xaml.cs
1,004
C#
// Copyright (c) Xenko contributors (https://xenko.com) and Silicon Studio Corp. (https://www.siliconstudio.co.jp) // Distributed under the MIT license. See the LICENSE.md file in the project root for more information. using System; namespace Xenko.Core.MicroThreading { [AttributeUsage(AttributeTargets.Method | AttributeTargets.Class)] public class XenkoScriptAttribute : Attribute { public XenkoScriptAttribute(ScriptFlags flags = ScriptFlags.None) { this.Flags = flags; } public ScriptFlags Flags { get; set; } } }
32.277778
114
0.698795
[ "MIT" ]
Aminator/xenko
sources/core/Xenko.Core.MicroThreading/XenkoScriptAttribute.cs
581
C#
// Copyright 2021 Google LLC // // 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 // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // Generated code. DO NOT EDIT! namespace Google.Cloud.PubSubLite.V1.Snippets { using Google.Api.Gax.ResourceNames; using Google.Cloud.PubSubLite.V1; using System.Threading.Tasks; public sealed partial class GeneratedAdminServiceClientStandaloneSnippets { /// <summary>Snippet for CreateSubscriptionAsync</summary> /// <remarks> /// This snippet has been automatically generated for illustrative purposes only. /// It may require modifications to work in your environment. /// </remarks> public async Task CreateSubscriptionRequestObjectAsync() { // Create client AdminServiceClient adminServiceClient = await AdminServiceClient.CreateAsync(); // Initialize request argument(s) CreateSubscriptionRequest request = new CreateSubscriptionRequest { ParentAsLocationName = LocationName.FromProjectLocation("[PROJECT]", "[LOCATION]"), Subscription = new Subscription(), SubscriptionId = "", SkipBacklog = false, }; // Make the request Subscription response = await adminServiceClient.CreateSubscriptionAsync(request); } } }
39.531915
99
0.677072
[ "Apache-2.0" ]
googleapis/googleapis-gen
google/cloud/pubsublite/v1/google-cloud-pubsublite-v1-csharp/Google.Cloud.PubSubLite.V1.StandaloneSnippets/AdminServiceClient.CreateSubscriptionRequestObjectAsyncSnippet.g.cs
1,858
C#
using D_API.Lib.Models.Responses; using System; using System.Collections.Generic; using System.IO; using System.Text; namespace D_API.Lib.Exceptions { [Serializable] public abstract class APIException : Exception { public APIResponse Response { get; set; } public APIException(APIResponse response) : base($"{(int)response.APIResponseCode}::{response.Title}\n{response.Serialize()}") => Response = response; public static APIException GetException(string jsonString) => APIResponse.GetResponseCode(jsonString) switch { APIResponseCode.BadDataKey => new BadDataKeyException(APIResponse.GetResponse<BadDataKeyResponse>(jsonString)), APIResponseCode.TooManyRequests => new TooManyRequestsException(APIResponse.GetResponse<TooManyRequestsResponse>(jsonString)), APIResponseCode.BadUserKey => new BadUserKeyException(APIResponse.GetResponse<BadUserKeyResponse>(jsonString)), APIResponseCode.NewSessionFailure => new NewSessionFailureException(APIResponse.GetResponse<NewSessionFailureResponse>(jsonString)), APIResponseCode.NewSessionBadRequest => new NewSessionBadRequestException(APIResponse.GetResponse<NewSessionBadRequestResponse>(jsonString)), APIResponseCode.RenewSessionFailure => new RenewSessionFailureException(APIResponse.GetResponse<RenewSessionFailureResponse>(jsonString)), APIResponseCode.DataUploadFailure => new DataUploadFailureException(APIResponse.GetResponse<DataUploadFailureResponse>(jsonString)), APIResponseCode.DataDownloadFailure => new DataDownloadFailureException(APIResponse.GetResponse<DataDownloadFailureResponse>(jsonString)), APIResponseCode.DataQuotaExceeded => new DataQuotaExceededException(APIResponse.GetResponse<DataQuotaExceededResponse>(jsonString)), APIResponseCode.NewUserFailure => new NewUserFailureException(APIResponse.GetResponse<NewUserFailureResponse>(jsonString)), APIResponseCode.NotInSession => new NotInSessionException(APIResponse.GetResponse<NotInSessionResponse>(jsonString)), APIResponseCode.UnspecifiedError => new UnspecifiedErrorException(APIResponse.GetResponse<UnspecifiedErrorResponse>(jsonString)), _ => throw new InvalidDataException("The given APIResponseCode is not supported as an Exception"), }; public static APIException GetException(APIResponse response) => response.APIResponseCode switch { APIResponseCode.BadDataKey => new BadDataKeyException((BadDataKeyResponse)response), APIResponseCode.TooManyRequests => new TooManyRequestsException((TooManyRequestsResponse)response), APIResponseCode.BadUserKey => new BadUserKeyException((BadUserKeyResponse)response), APIResponseCode.NewSessionFailure => new NewSessionFailureException((NewSessionFailureResponse)response), APIResponseCode.NewSessionBadRequest => new NewSessionBadRequestException((NewSessionBadRequestResponse)response), APIResponseCode.RenewSessionFailure => new RenewSessionFailureException((RenewSessionFailureResponse)response), APIResponseCode.DataUploadFailure => new DataUploadFailureException((DataUploadFailureResponse)response), APIResponseCode.DataDownloadFailure => new DataDownloadFailureException((DataDownloadFailureResponse)response), APIResponseCode.DataQuotaExceeded => new DataQuotaExceededException((DataQuotaExceededResponse)response), APIResponseCode.NewUserFailure => new NewUserFailureException((NewUserFailureResponse)response), APIResponseCode.NotInSession => new NotInSessionException((NotInSessionResponse)response), APIResponseCode.UnspecifiedError => new UnspecifiedErrorException((UnspecifiedErrorResponse)response), _ => throw new InvalidDataException("The given APIResponseCode is not supported as an Exception"), }; } [Serializable] public class NotInSessionException : APIException { public NotInSessionException(NotInSessionResponse response) : base(response) { } } [Serializable] public class TooManyRequestsException : APIException { public TooManyRequestsException(TooManyRequestsResponse response) : base(response) { } } [Serializable] public class NewSessionFailureException : APIException { public NewSessionFailureException(NewSessionFailureResponse response) : base(response) { } } [Serializable] public class RenewSessionFailureException : APIException { public RenewSessionFailureException(RenewSessionFailureResponse response) : base(response) { } } [Serializable] public class NewSessionBadRequestException : APIException { public NewSessionBadRequestException(NewSessionBadRequestResponse response) : base(response) { } } [Serializable] public class UnspecifiedErrorException : APIException { public UnspecifiedErrorException(UnspecifiedErrorResponse response) : base(response) { } } [Serializable] public class DataUploadFailureException : APIException { public DataUploadFailureException(DataUploadFailureResponse response) : base(response) { } } [Serializable] public class DataDownloadFailureException : APIException { public DataDownloadFailureException(DataDownloadFailureResponse response) : base(response) { } } [Serializable] public class DataQuotaExceededException : APIException { public DataQuotaExceededException(DataQuotaExceededResponse response) : base(response) { } } [Serializable] public class BadUserKeyException : APIException { public BadUserKeyException(BadUserKeyResponse response) : base(response) { } } [Serializable] public class BadDataKeyException : APIException { public BadDataKeyException(BadDataKeyResponse response) : base(response) { } } [Serializable] public class NewUserFailureException : APIException { public NewUserFailureException(NewUserFailureResponse response) : base(response) { } } }
51.225806
158
0.73898
[ "MIT" ]
DiegoG1019/D_API
D_API.Lib/Exceptions/APIException.cs
6,354
C#
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; using System.Web.Routing; namespace SozlukSitesi.Service { public class MvcApplication : System.Web.HttpApplication { protected void Application_Start() { AreaRegistration.RegisterAllAreas(); RouteConfig.RegisterRoutes(RouteTable.Routes); } } }
21.789474
60
0.693237
[ "MIT" ]
enesozer/sozlukproject
SozlukSitesi.Service/Global.asax.cs
416
C#