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 |
---|---|---|---|---|---|---|---|---|
//
// Unit tests for DoNotRecurseInEqualityRule
//
// Authors:
// Jesse Jones <[email protected]>
//
// Copyright (C) 2008 Jesse Jones
//
// 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.Runtime.Serialization;
using System.Security;
using System.Security.Permissions;
using Gendarme.Rules.Correctness;
using Mono.Cecil;
using NUnit.Framework;
using Test.Rules.Definitions;
using Test.Rules.Helpers;
using Test.Rules.Fixtures;
namespace Test.Rules.Correctness {
[TestFixture]
public class DoNotRecurseInEqualityTest : MethodRuleTestFixture<DoNotRecurseInEqualityRule> {
private sealed class GoodCase {
public static bool operator== (GoodCase lhs, GoodCase rhs)
{
if (object.ReferenceEquals (lhs, rhs))
return true;
if ((object) lhs == null || (object) rhs == null)
return false;
return lhs.Name == rhs.Name && lhs.Address == rhs.Address;
}
public static bool operator!= (GoodCase lhs, GoodCase rhs)
{
return !(lhs == rhs);
}
public void Recurses ()
{
Recurses(); // this belongs to BadRecursiveInvocationRule, not DoNotRecurseInEqualityRule
}
public string Name {get; set;}
public string Address {get; set;}
}
private sealed class BadEquality {
public static bool operator== (BadEquality lhs, BadEquality rhs)
{
if (object.ReferenceEquals (lhs, rhs))
return true;
if (lhs == null || rhs == null)
return false;
return lhs.Name == rhs.Name && lhs.Address == rhs.Address;
}
public static bool operator!= (BadEquality lhs, BadEquality rhs)
{
return !(lhs == rhs);
}
public string Name {get; set;}
public string Address {get; set;}
}
private sealed class BadInequality {
public static bool operator== (BadInequality lhs, BadInequality rhs)
{
if (object.ReferenceEquals (lhs, rhs))
return true;
if ((object) lhs == null || (object) rhs == null)
return false;
return lhs.Name == rhs.Name && lhs.Address == rhs.Address;
}
public static bool operator!= (BadInequality lhs, BadInequality rhs)
{
if (object.ReferenceEquals (lhs, rhs))
return false;
if (lhs != null && rhs != null)
return true;
return lhs.Name != rhs.Name || lhs.Address != rhs.Address;
}
public string Name {get; set;}
public string Address {get; set;}
}
private sealed class BadGenericEquality<T> {
public static bool operator== (BadGenericEquality<T> lhs, BadGenericEquality<T> rhs)
{
if (object.ReferenceEquals (lhs, rhs))
return true;
if (lhs == null || rhs == null)
return false;
return lhs.Name.Equals(rhs.Name) && lhs.Address.Equals(rhs.Address);
}
public static bool operator!= (BadGenericEquality<T> lhs, BadGenericEquality<T> rhs)
{
return !(lhs == rhs);
}
public T Name {get; set;}
public T Address {get; set;}
}
[Test]
public void DoesNotApply ()
{
AssertRuleDoesNotApply (SimpleMethods.ExternalMethod);
AssertRuleDoesNotApply (SimpleMethods.EmptyMethod);
AssertRuleDoesNotApply<GoodCase> ("Recurses");
}
[Test]
public void Test ()
{
AssertRuleSuccess<GoodCase> ("op_Equality");
AssertRuleSuccess<GoodCase> ("op_Inequality");
AssertRuleFailure<BadEquality> ("op_Equality", 2);
AssertRuleSuccess<BadEquality> ("op_Inequality");
AssertRuleSuccess<BadInequality> ("op_Equality");
AssertRuleFailure<BadInequality> ("op_Inequality", 2);
}
[Test]
public void GenericsTest ()
{
Type type = typeof (BadGenericEquality<>);
TypeDefinition td = DefinitionLoader.GetTypeDefinition (type);
MethodDefinition md = DefinitionLoader.GetMethodDefinition (td, "op_Equality", null);
AssertRuleFailure (md, 2);
md = DefinitionLoader.GetMethodDefinition (td, "op_Inequality", null);
AssertRuleSuccess (md);
}
}
}
| 27.903955 | 95 | 0.689411 |
[
"MIT"
] |
JAD-SVK/Gendarme
|
rules/Gendarme.Rules.Correctness/Test/DoNotRecurseInEqualityTest.cs
| 4,939 |
C#
|
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.ML.Internal.Utilities;
namespace Microsoft.ML.Data
{
/// <summary>
/// This is a data view that is a 'zip' of several data views.
/// The length of the zipped data view is equal to the shortest of the lengths of the components.
/// </summary>
public sealed class ZipDataView : IDataView
{
// REVIEW: there are other potential 'zip modes' that can be implemented:
// * 'zip longest', iterate until all sources finish, and return the 'sensible missing values' for sources that ended
// too early.
// * 'zip longest with loop', iterate until the longest source finishes, and for those that finish earlier, restart from
// the beginning.
public const string RegistrationName = "ZipDataView";
private readonly IHost _host;
private readonly IDataView[] _sources;
private readonly ZipBinding _zipBinding;
public static IDataView Create(IHostEnvironment env, IEnumerable<IDataView> sources)
{
Contracts.CheckValue(env, nameof(env));
var host = env.Register(RegistrationName);
host.CheckValue(sources, nameof(sources));
var srcArray = sources.ToArray();
host.CheckNonEmpty(srcArray, nameof(sources));
if (srcArray.Length == 1)
return srcArray[0];
return new ZipDataView(host, srcArray);
}
private ZipDataView(IHost host, IDataView[] sources)
{
Contracts.AssertValue(host);
_host = host;
_host.Assert(Utils.Size(sources) > 1);
_sources = sources;
_zipBinding = new ZipBinding(_sources.Select(x => x.Schema).ToArray());
}
public bool CanShuffle { get { return false; } }
public Schema Schema => _zipBinding.OutputSchema;
public long? GetRowCount()
{
long min = -1;
foreach (var source in _sources)
{
var cur = source.GetRowCount();
if (cur == null)
return null;
_host.Check(cur.Value >= 0, "One of the sources returned a negative row count");
if (min < 0 || min > cur.Value)
min = cur.Value;
}
return min;
}
public RowCursor GetRowCursor(IEnumerable<Schema.Column> columnsNeeded, Random rand = null)
{
var predicate = RowCursorUtils.FromColumnsToPredicate(columnsNeeded, Schema);
_host.CheckValueOrNull(rand);
var srcPredicates = _zipBinding.GetInputPredicates(predicate);
// REVIEW: if we know the row counts, we could only open cursor if it has needed columns, and have the
// outer cursor handle the early stopping. If we don't know row counts, we need to open all the cursors because
// we don't know which one will be the shortest.
// One reason this is not done currently is because the API has 'somewhat mutable' data views, so potentially this
// optimization might backfire.
var srcCursors = _sources
.Select((dv, i) => srcPredicates[i] == null ? GetMinimumCursor(dv) : dv.GetRowCursor(dv.Schema.Where(x => srcPredicates[i](x.Index)), null)).ToArray();
return new Cursor(this, srcCursors, predicate);
}
/// <summary>
/// Create an <see cref="RowCursor"/> with no requested columns on a data view.
/// Potentially, this can be optimized by calling GetRowCount(lazy:true) first, and if the count is not known,
/// wrapping around GetCursor().
/// </summary>
private RowCursor GetMinimumCursor(IDataView dv)
{
_host.AssertValue(dv);
return dv.GetRowCursor();
}
public RowCursor[] GetRowCursorSet(IEnumerable<Schema.Column> columnsNeeded, int n, Random rand = null)
{
return new RowCursor[] { GetRowCursor(columnsNeeded, rand) };
}
private sealed class Cursor : RootCursorBase
{
private readonly RowCursor[] _cursors;
private readonly ZipBinding _zipBinding;
private readonly bool[] _isColumnActive;
private bool _disposed;
public override long Batch { get { return 0; } }
public Cursor(ZipDataView parent, RowCursor[] srcCursors, Func<int, bool> predicate)
: base(parent._host)
{
Ch.AssertNonEmpty(srcCursors);
Ch.AssertValue(predicate);
_cursors = srcCursors;
_zipBinding = parent._zipBinding;
_isColumnActive = Utils.BuildArray(_zipBinding.ColumnCount, predicate);
}
protected override void Dispose(bool disposing)
{
if (_disposed)
return;
if (disposing)
{
for (int i = _cursors.Length - 1; i >= 0; i--)
_cursors[i].Dispose();
}
_disposed = true;
base.Dispose(disposing);
}
public override ValueGetter<RowId> GetIdGetter()
{
return
(ref RowId val) =>
{
Ch.Check(IsGood, RowCursorUtils.FetchValueStateError);
val = new RowId((ulong)Position, 0);
};
}
protected override bool MoveNextCore()
{
foreach (var cursor in _cursors)
{
if (!cursor.MoveNext())
return false;
}
return true;
}
public override Schema Schema => _zipBinding.OutputSchema;
public override bool IsColumnActive(int col)
{
_zipBinding.CheckColumnInRange(col);
return _isColumnActive[col];
}
public override ValueGetter<TValue> GetGetter<TValue>(int col)
{
int dv;
int srcCol;
_zipBinding.GetColumnSource(col, out dv, out srcCol);
return _cursors[dv].GetGetter<TValue>(srcCol);
}
}
}
}
| 37.376404 | 167 | 0.563806 |
[
"MIT"
] |
cluesblues/machinelearning
|
src/Microsoft.ML.Data/DataView/ZipDataView.cs
| 6,655 |
C#
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.AI;
public enum EnemyState {
PATROL,
CHASE,
ATTACK
}
public class EnemyController : MonoBehaviour {
private EnemyAnimator enemy_Anim;
private NavMeshAgent navAgent;
private EnemyState enemy_State;
public float walk_Speed = 0.5f;
public float run_Speed = 4f;
public float chase_Distance = 7f;
private float current_Chase_Distance;
public float attack_Distance = 1.8f;
public float chase_After_Attack_Distance = 2f;
public float patrol_Radius_Min = 20f, patrol_Radius_Max = 60f;
public float patrol_For_This_Time = 15f;
private float patrol_Timer;
public float wait_Before_Attack = 2f;
private float attack_Timer;
private Transform target;
public GameObject attack_Point;
private EnemyAudio enemy_Audio;
void Awake() {
enemy_Anim = GetComponent<EnemyAnimator>();
navAgent = GetComponent<NavMeshAgent>();
target = GameObject.FindWithTag(Tags.PLAYER_TAG).transform;
enemy_Audio = GetComponentInChildren<EnemyAudio>();
}
// Use this for initialization
void Start () {
enemy_State = EnemyState.PATROL;
patrol_Timer = patrol_For_This_Time;
// when the enemy first gets to the player
// attack right away
attack_Timer = wait_Before_Attack;
// memorize the value of chase distance
// so that we can put it back
current_Chase_Distance = chase_Distance;
}
// Update is called once per frame
void Update () {
if(enemy_State == EnemyState.PATROL) {
Patrol();
}
if(enemy_State == EnemyState.CHASE) {
Chase();
}
if (enemy_State == EnemyState.ATTACK) {
Attack();
}
}
void Patrol() {
// tell nav agent that he can move
navAgent.isStopped = false;
navAgent.speed = walk_Speed;
// add to the patrol timer
patrol_Timer += Time.deltaTime;
if(patrol_Timer > patrol_For_This_Time) {
SetNewRandomDestination();
patrol_Timer = 0f;
}
if(navAgent.velocity.sqrMagnitude > 0) {
enemy_Anim.Walk(true);
} else {
enemy_Anim.Walk(false);
}
// test the distance between the player and the enemy
if(Vector3.Distance(transform.position, target.position) <= chase_Distance) {
enemy_Anim.Walk(false);
enemy_State = EnemyState.CHASE;
// play spotted audio
enemy_Audio.Play_ScreamSound();
}
} // patrol
void Chase() {
// enable the agent to move again
navAgent.isStopped = false;
navAgent.speed = run_Speed;
// set the player's position as the destination
// because we are chasing(running towards) the player
navAgent.SetDestination(target.position);
if (navAgent.velocity.sqrMagnitude > 0) {
enemy_Anim.Run(true);
} else {
enemy_Anim.Run(false);
}
// if the distance between enemy and player is less than attack distance
if(Vector3.Distance(transform.position, target.position) <= attack_Distance) {
// stop the animations
enemy_Anim.Run(false);
enemy_Anim.Walk(false);
enemy_State = EnemyState.ATTACK;
// reset the chase distance to previous
if(chase_Distance != current_Chase_Distance) {
chase_Distance = current_Chase_Distance;
}
} else if(Vector3.Distance(transform.position, target.position) > chase_Distance) {
// player run away from enemy
// stop running
enemy_Anim.Run(false);
enemy_State = EnemyState.PATROL;
// reset the patrol timer so that the function
// can calculate the new patrol destination right away
patrol_Timer = patrol_For_This_Time;
// reset the chase distance to previous
if (chase_Distance != current_Chase_Distance) {
chase_Distance = current_Chase_Distance;
}
} // else
} // chase
void Attack() {
navAgent.velocity = Vector3.zero;
navAgent.isStopped = true;
attack_Timer += Time.deltaTime;
if(attack_Timer > wait_Before_Attack) {
enemy_Anim.Attack();
attack_Timer = 0f;
// play attack sound
enemy_Audio.Play_AttackSound();
}
if(Vector3.Distance(transform.position, target.position) >
attack_Distance + chase_After_Attack_Distance) {
enemy_State = EnemyState.CHASE;
}
} // attack
void SetNewRandomDestination() {
float rand_Radius = Random.Range(patrol_Radius_Min, patrol_Radius_Max);
Vector3 randDir = Random.insideUnitSphere * rand_Radius;
randDir += transform.position;
NavMeshHit navHit;
NavMesh.SamplePosition(randDir, out navHit, rand_Radius, -1);
navAgent.SetDestination(navHit.position);
}
void Turn_On_AttackPoint() {
attack_Point.SetActive(true);
}
void Turn_Off_AttackPoint() {
if (attack_Point.activeInHierarchy) {
attack_Point.SetActive(false);
}
}
public EnemyState Enemy_State {
get; set;
}
}
| 23.210084 | 91 | 0.608979 |
[
"MIT"
] |
Youngermaster/Unity-FPS
|
Assets/Scripts/Enemy Scripts/EnemyController.cs
| 5,526 |
C#
|
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using AryuwatSystem.DerClass;
using Entity;
using WeifenLuo.WinFormsUI.Docking;
namespace AryuwatSystem.Forms
{
public partial class FrmDoctorSchedule : DockContent
{
DataSet ds=new DataSet();
private string EMPName
{
get { return lblEmployeeName.Text; }
set { lblEmployeeName.Text = value; }
}
private string EMPID
{
get { return lblEN.Text; }
set { lblEN.Text = value; }
}
private bool firstLoad=true;
private Dictionary<double, double> DicComRate;
double Sales = 0;
double Commission = 0;
private string EMPTypID = "";
public bool SurgiFeeTYP = true;
public FrmDoctorSchedule()
{
InitializeComponent();
}
private void buttonFind_BtnClick()
{
BindDataSchedule(1);
}
private void setColumn()
{
if (EMPTypID == "17")//Sale Comission
{
dgvData.Columns["CourseUse"].HeaderText = "Amount";
dgvData.Columns["StartTime"].Visible = false;
dgvData.Columns["EndTime"].Visible = false;
}
else//Surgical Fee
{
}
}
public void BindDataSchedule(int _pIntseq)
{
try
{
firstLoad = false;
Sales = 0;
// setColumn();
if (dgvData.Rows.Count>0)dgvData.Rows.RemoveAt(0);
//dgvData.Rows.Clear();
dgvData.DataSource = null;
//int pIntseq = _pIntseq;
ItemInfo info = new ItemInfo();
string Cmndate = "DateShowStart";
//if (dtpDateStart.Checked)
//{
// info.whereDate = Cmndate + " >='" + dtpDateStart.Value.ToString("yyyy-MM-dd 00:00:00") + "'";
// //mydate between ('3/01/2013 12:00:00') and ('3/30/2013 12:00:00')
//}
//if (dtpDateEnd.Checked)
//{
// info.whereDate = Cmndate + " <='" + dtpDateEnd.Value.ToString("yyyy-MM-dd 23:59:59") + "'";
// //mydate between ('3/01/2013 12:00:00') and ('3/30/2013 12:00:00')
//}
//if (dtpDateStart.Checked && dtpDateEnd.Checked)
//{
// info.whereDate = Cmndate + " between ('" + dtpDateStart.Value.ToString("yyyy-MM-dd 00:00:00") + "') and ('" + dtpDateEnd.Value.ToString("yyyy-MM-dd 23:59:59") + "')";
//}
//if (!dtpDateStart.Checked && !dtpDateEnd.Checked)
//{
// info.whereDate = " 1=1 ";
//}
info.DateShowStart = Convert.ToDateTime(AryuwatSystem.DerClass.DerUtility.ToFormatDateyyyyMMdd(txtStartdate.Text)).AddHours(8).AddMinutes(30);// Convert.ToDateTime(txtStartdate.Text).ToString("yyyy-MM-dd");// StartDate.ToString();
info.DateShowEnd = Convert.ToDateTime(AryuwatSystem.DerClass.DerUtility.ToFormatDateyyyyMMdd(txtEnddate.Text)).AddDays(1);
//info.DateShowStart = dtpDateStart.Value;
//info.DateShowEnd = dtpDateEnd.Value;
//if (cboDoctor.SelectedIndex<=0)return;
info.DrID = cboDoctor.SelectedValue+"";
ds = new Business.BookingRoom().SelectDoctorSchedule(info);
long lngTotalPage = 0;
long lngTotalRecord = 0;
if (ds.Tables.Count <= 0)
{
if (ds.Tables[0].Rows.Count <= 0)
{
DerUtility.PopMsg(DerUtility.EnuMsgType.MsgTypeInformation, "ไม่พบข้อมูลในระบบ");
return;
}
}
//if (ds.Tables[0].Columns.Count < 2) return;
//foreach (DataRowView item in ds.Tables[0].DefaultView)
//{
// //this.VN,this.MS_Name,this.CourseUse,this.ProcedureDate,this.StartTime,this.EndTime,this.Money});
// //double m = string.IsNullOrEmpty(item["Com_Bath"] + "") ? 0 : Convert.ToDouble(item["Com_Bath"] + "");
// DateTime dateTimeStart = Convert.ToDateTime(item["DateShowStart"] + "");
// DateTime dateTimeEnd = Convert.ToDateTime(item["DateShowEnd"] + "");
// var myItems = new IComparable[]
// {
// item["CustName"] + "",
// item["Treadment"] + "",
// String.Format("{0:yyyy/MM/dd}", dateTimeStart),
// dateTimeStart.ToString("HH:mm")+"",
// dateTimeEnd.ToString("HH:mm")+"",
// item["RoomName"] + ""
// };
// dgvData.Rows.Add(myItems);
// }
dgvData.DataSource=null;
dgvData.DataSource = ds.Tables[0];
lbCount.Text = "";
lbCount.Text = string.Format("Count {0}", dgvData.RowCount.ToString("###,###,###"));
}
catch (Exception ex)
{
DerUtility.PopMsg(DerUtility.EnuMsgType.MsgTypeError, ex.Message);
return;
}
finally
{
}
}
private void CalCommission()
{
foreach (KeyValuePair<double,double> valuePair in DicComRate)
{
if (Sales > valuePair.Key) continue;
Commission = Sales*valuePair.Value;
break;
}
}
private void btnFindEMP_Click(object sender, EventArgs e)
{
PopEMP();
}
private void PopEMP()
{
try
{
PopEmpSearch obj = new PopEmpSearch();
obj.StartPosition = FormStartPosition.CenterScreen;
obj.WindowState = FormWindowState.Normal;
obj.BackColor = Color.FromArgb(255, 230, 217);
obj.multiSelect = false;
obj._queryType = "LISTNAMECOMMISSION";
obj.ShowDialog();
if (!string.IsNullOrEmpty(obj.StaffsName))
EMPName = obj.StaffsName.Replace(',',' ').Trim();
if (!string.IsNullOrEmpty(obj.EmployeeId))
EMPID = obj.EmployeeId.Replace(',', ' ').Trim();
EMPTypID=obj.EmployeeTypeId;
// BindDataCommission(1);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
private void FrmCommissionCheck_Load(object sender, EventArgs e)
{
lblEN.Text = "";
lblEmployeeName.Text = "";
BindDoctor();
txtEnddate.Text = DateTime.Now.ToString("dd/MM/yyyy");
txtStartdate.Text = DateTime.Now.ToString("dd/MM/yyyy");
//PopEMP();
// BindDataCommission(1);
}
private void BindDoctor()
{
try
{
var info = new Entity.Personnel();
info.QueryType = "LISTDOCTOR";
DataTable dt = new Business.Personnel().SelectCustomerPaging(info).Tables[0];
var dr = dt.NewRow();
dr["EN"] = "";
dr["FullNameThai"] = Statics.StrEmpty;
dt.Rows.InsertAt(dr, 0);
cboDoctor.Items.Clear();
cboDoctor.DataSource = dt.DefaultView;
cboDoctor.ValueMember = "EN";
cboDoctor.DisplayMember = "FullNameThai";
// if (comboBoxCommission.Items.Contains(Entity.Userinfo.EN))
cboDoctor.SelectedIndex = 0;
//else
// comboBoxCommission.SelectedValue = -1;
}
catch (Exception ex)
{
DerUtility.PopMsg(DerUtility.EnuMsgType.MsgTypeError, ex.Message);
DerUtility.MouseOff(this);
return;
}
}
private void FrmCommissionCheck_FormClosing(object sender, FormClosingEventArgs e)
{
Statics.frmCommissionCheck = null;
}
private void cboDoctor_SelectedIndexChanged(object sender, EventArgs e)
{
if (firstLoad)return;
BindDataSchedule(1);
}
private void pictureBoxExport_Click(object sender, EventArgs e)
{
try
{
ExportFile exp = new ExportFile();
//DataSet ds=new DataSet();
//ds.Tables.Add();
SaveFileDialog saveDlg = new SaveFileDialog();
//saveDlg.Filter = "Excel File (*.xls)|*.xls";
saveDlg.Filter = "Excel(xlsx)|*.xlsx";
if (saveDlg.ShowDialog() == DialogResult.OK)
{
DataSet dataSet=new DataSet();
dataSet.Tables.Add(exp.GetDataTableFromDGV(dgvData,"Result"));
//exp.Export(dataSet, saveDlg.FileName);
//exp.ExportUseCloseXML(dataSet, saveDlg.FileName);
//exp.ExportMultipleGridToOneExcel(exp.GetDataTableFromDGV(dgvData));
AryuwatSystem.Forms.ExcelHelper.ExportToExcel(dataSet, saveDlg.FileName,"");
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
private void dgvData_RowPostPaint(object sender, DataGridViewRowPostPaintEventArgs e)
{
try
{
var b = new SolidBrush(((DataGridView)sender).RowHeadersDefaultCellStyle.ForeColor);
e.Graphics.DrawString(Convert.ToString(e.RowIndex + 1), ((DataGridView)sender).DefaultCellStyle.Font, b,
e.RowBounds.Location.X + 15, e.RowBounds.Location.Y + 4);
}
catch (Exception)
{
}
}
}
}
| 38.067138 | 246 | 0.482688 |
[
"Unlicense"
] |
Krailit/Aryuwat_Nurse
|
AryuwatSystem/Forms/FrmDoctorSchedule.cs
| 10,809 |
C#
|
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// Le informazioni generali relative a un assembly sono controllate dal seguente
// set di attributi. Per modificare le informazioni associate a un assembly
// occorre quindi modificare i valori di questi attributi.
[assembly: AssemblyTitle("CompressingWebPages")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("CompressingWebPages")]
[assembly: AssemblyCopyright("Copyright © 2015")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Se si imposta ComVisible su false, i tipi in questo assembly non saranno visibili
// ai componenti COM. Se è necessario accedere a un tipo in questo assembly da
// COM, impostare su true l'attributo ComVisible per tale tipo.
[assembly: ComVisible(false)]
// Se il progetto viene esposto a COM, il GUID che segue verrà utilizzato per creare l'ID della libreria dei tipi
[assembly: Guid("2160e1a3-8415-4f81-98df-dee53eff7e4d")]
// Le informazioni sulla versione di un assembly sono costituite dai seguenti quattro valori:
//
// Numero di versione principale
// Numero di versione secondario
// Numero build
// Revisione
//
// È possibile specificare tutti i valori oppure impostare valori predefiniti per i numeri relativi alla revisione e alla build
// utilizzando l'asterisco (*) come descritto di seguito:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| 43.324324 | 128 | 0.763568 |
[
"MIT"
] |
Draxent/CompressingWebPages
|
CompressingWebPages/Properties/AssemblyInfo.cs
| 1,609 |
C#
|
using BenchmarkDotNet.Attributes;
using LibraryTests.Tests.BaseClasses;
namespace LibraryTests.Tests
{
public class StackAllocVsNew : TestBaseClass
{
[Benchmark(Description = "New")]
public unsafe void NewTest()
{
int[] Data = new int[Count];
fixed (int* Fib = &Data[0])
{
int* Pointer = Fib;
*Pointer++ = *Pointer++ = 1;
for (int x = 2; x < Count; ++x, ++Pointer)
{
*Pointer = Pointer[-1] + Pointer[-2];
}
}
}
[Benchmark(Description = "Stackalloc struct")]
public unsafe void StackAllocClassTest()
{
TempClass* Fib = stackalloc TempClass[Count];
TempClass* Pointer = Fib;
(*Pointer++).Data = 1;
(*Pointer++).Data = 1;
for (int x = 2; x < Count; ++x, ++Pointer)
{
(*Pointer).Data = Pointer[-1].Data + Pointer[-2].Data;
}
}
[Benchmark(Baseline = true, Description = "Stackalloc")]
public unsafe void StackAllocTest()
{
int* Fib = stackalloc int[Count];
int* Pointer = Fib;
*Pointer++ = *Pointer++ = 1;
for (int x = 2; x < Count; ++x, ++Pointer)
{
*Pointer = Pointer[-1] + Pointer[-2];
}
}
public struct TempClass
{
public int Data;
}
}
}
| 29.679245 | 71 | 0.439288 |
[
"Apache-2.0"
] |
JaCraig/I-Got-Bored
|
LibraryTests/Tests/StackAllocVsNew.cs
| 1,575 |
C#
|
using Solnet.KeyStore.Model;
namespace Solnet.KeyStore.Serialization
{
public static class JsonKeyStoreScryptSerializer
{
public static string SerializeScrypt(KeyStore<ScryptParams> scryptKeyStore)
{
return System.Text.Json.JsonSerializer.Serialize(scryptKeyStore);
}
public static KeyStore<ScryptParams> DeserializeScrypt(string json)
{
return System.Text.Json.JsonSerializer.Deserialize<KeyStore<ScryptParams>>(json);
}
}
}
| 30.058824 | 93 | 0.69863 |
[
"MIT"
] |
BAISGame/Solnet-lib-for-BAIS
|
src/Solnet.KeyStore/Serialization/JsonKeyStoreScryptSerializer.cs
| 511 |
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 fms-2018-01-01.normal.json service model.
*/
using System;
using Amazon.Runtime;
namespace Amazon.FMS
{
/// <summary>
/// Constants used for properties of type AccountRoleStatus.
/// </summary>
public class AccountRoleStatus : ConstantClass
{
/// <summary>
/// Constant CREATING for AccountRoleStatus
/// </summary>
public static readonly AccountRoleStatus CREATING = new AccountRoleStatus("CREATING");
/// <summary>
/// Constant DELETED for AccountRoleStatus
/// </summary>
public static readonly AccountRoleStatus DELETED = new AccountRoleStatus("DELETED");
/// <summary>
/// Constant DELETING for AccountRoleStatus
/// </summary>
public static readonly AccountRoleStatus DELETING = new AccountRoleStatus("DELETING");
/// <summary>
/// Constant PENDING_DELETION for AccountRoleStatus
/// </summary>
public static readonly AccountRoleStatus PENDING_DELETION = new AccountRoleStatus("PENDING_DELETION");
/// <summary>
/// Constant READY for AccountRoleStatus
/// </summary>
public static readonly AccountRoleStatus READY = new AccountRoleStatus("READY");
/// <summary>
/// This constant constructor does not need to be called if the constant
/// you are attempting to use is already defined as a static instance of
/// this class.
/// This constructor should be used to construct constants that are not
/// defined as statics, for instance if attempting to use a feature that is
/// newer than the current version of the SDK.
/// </summary>
public AccountRoleStatus(string value)
: base(value)
{
}
/// <summary>
/// Finds the constant for the unique value.
/// </summary>
/// <param name="value">The unique value for the constant</param>
/// <returns>The constant for the unique value</returns>
public static AccountRoleStatus FindValue(string value)
{
return FindValue<AccountRoleStatus>(value);
}
/// <summary>
/// Utility method to convert strings to the constant class.
/// </summary>
/// <param name="value">The string value to convert to the constant class.</param>
/// <returns></returns>
public static implicit operator AccountRoleStatus(string value)
{
return FindValue(value);
}
}
/// <summary>
/// Constants used for properties of type CustomerPolicyScopeIdType.
/// </summary>
public class CustomerPolicyScopeIdType : ConstantClass
{
/// <summary>
/// Constant ACCOUNT for CustomerPolicyScopeIdType
/// </summary>
public static readonly CustomerPolicyScopeIdType ACCOUNT = new CustomerPolicyScopeIdType("ACCOUNT");
/// <summary>
/// Constant ORG_UNIT for CustomerPolicyScopeIdType
/// </summary>
public static readonly CustomerPolicyScopeIdType ORG_UNIT = new CustomerPolicyScopeIdType("ORG_UNIT");
/// <summary>
/// This constant constructor does not need to be called if the constant
/// you are attempting to use is already defined as a static instance of
/// this class.
/// This constructor should be used to construct constants that are not
/// defined as statics, for instance if attempting to use a feature that is
/// newer than the current version of the SDK.
/// </summary>
public CustomerPolicyScopeIdType(string value)
: base(value)
{
}
/// <summary>
/// Finds the constant for the unique value.
/// </summary>
/// <param name="value">The unique value for the constant</param>
/// <returns>The constant for the unique value</returns>
public static CustomerPolicyScopeIdType FindValue(string value)
{
return FindValue<CustomerPolicyScopeIdType>(value);
}
/// <summary>
/// Utility method to convert strings to the constant class.
/// </summary>
/// <param name="value">The string value to convert to the constant class.</param>
/// <returns></returns>
public static implicit operator CustomerPolicyScopeIdType(string value)
{
return FindValue(value);
}
}
/// <summary>
/// Constants used for properties of type DependentServiceName.
/// </summary>
public class DependentServiceName : ConstantClass
{
/// <summary>
/// Constant AWSCONFIG for DependentServiceName
/// </summary>
public static readonly DependentServiceName AWSCONFIG = new DependentServiceName("AWSCONFIG");
/// <summary>
/// Constant AWSSHIELD_ADVANCED for DependentServiceName
/// </summary>
public static readonly DependentServiceName AWSSHIELD_ADVANCED = new DependentServiceName("AWSSHIELD_ADVANCED");
/// <summary>
/// Constant AWSVPC for DependentServiceName
/// </summary>
public static readonly DependentServiceName AWSVPC = new DependentServiceName("AWSVPC");
/// <summary>
/// Constant AWSWAF for DependentServiceName
/// </summary>
public static readonly DependentServiceName AWSWAF = new DependentServiceName("AWSWAF");
/// <summary>
/// This constant constructor does not need to be called if the constant
/// you are attempting to use is already defined as a static instance of
/// this class.
/// This constructor should be used to construct constants that are not
/// defined as statics, for instance if attempting to use a feature that is
/// newer than the current version of the SDK.
/// </summary>
public DependentServiceName(string value)
: base(value)
{
}
/// <summary>
/// Finds the constant for the unique value.
/// </summary>
/// <param name="value">The unique value for the constant</param>
/// <returns>The constant for the unique value</returns>
public static DependentServiceName FindValue(string value)
{
return FindValue<DependentServiceName>(value);
}
/// <summary>
/// Utility method to convert strings to the constant class.
/// </summary>
/// <param name="value">The string value to convert to the constant class.</param>
/// <returns></returns>
public static implicit operator DependentServiceName(string value)
{
return FindValue(value);
}
}
/// <summary>
/// Constants used for properties of type DestinationType.
/// </summary>
public class DestinationType : ConstantClass
{
/// <summary>
/// Constant IPV4 for DestinationType
/// </summary>
public static readonly DestinationType IPV4 = new DestinationType("IPV4");
/// <summary>
/// Constant IPV6 for DestinationType
/// </summary>
public static readonly DestinationType IPV6 = new DestinationType("IPV6");
/// <summary>
/// Constant PREFIX_LIST for DestinationType
/// </summary>
public static readonly DestinationType PREFIX_LIST = new DestinationType("PREFIX_LIST");
/// <summary>
/// This constant constructor does not need to be called if the constant
/// you are attempting to use is already defined as a static instance of
/// this class.
/// This constructor should be used to construct constants that are not
/// defined as statics, for instance if attempting to use a feature that is
/// newer than the current version of the SDK.
/// </summary>
public DestinationType(string value)
: base(value)
{
}
/// <summary>
/// Finds the constant for the unique value.
/// </summary>
/// <param name="value">The unique value for the constant</param>
/// <returns>The constant for the unique value</returns>
public static DestinationType FindValue(string value)
{
return FindValue<DestinationType>(value);
}
/// <summary>
/// Utility method to convert strings to the constant class.
/// </summary>
/// <param name="value">The string value to convert to the constant class.</param>
/// <returns></returns>
public static implicit operator DestinationType(string value)
{
return FindValue(value);
}
}
/// <summary>
/// Constants used for properties of type PolicyComplianceStatusType.
/// </summary>
public class PolicyComplianceStatusType : ConstantClass
{
/// <summary>
/// Constant COMPLIANT for PolicyComplianceStatusType
/// </summary>
public static readonly PolicyComplianceStatusType COMPLIANT = new PolicyComplianceStatusType("COMPLIANT");
/// <summary>
/// Constant NON_COMPLIANT for PolicyComplianceStatusType
/// </summary>
public static readonly PolicyComplianceStatusType NON_COMPLIANT = new PolicyComplianceStatusType("NON_COMPLIANT");
/// <summary>
/// This constant constructor does not need to be called if the constant
/// you are attempting to use is already defined as a static instance of
/// this class.
/// This constructor should be used to construct constants that are not
/// defined as statics, for instance if attempting to use a feature that is
/// newer than the current version of the SDK.
/// </summary>
public PolicyComplianceStatusType(string value)
: base(value)
{
}
/// <summary>
/// Finds the constant for the unique value.
/// </summary>
/// <param name="value">The unique value for the constant</param>
/// <returns>The constant for the unique value</returns>
public static PolicyComplianceStatusType FindValue(string value)
{
return FindValue<PolicyComplianceStatusType>(value);
}
/// <summary>
/// Utility method to convert strings to the constant class.
/// </summary>
/// <param name="value">The string value to convert to the constant class.</param>
/// <returns></returns>
public static implicit operator PolicyComplianceStatusType(string value)
{
return FindValue(value);
}
}
/// <summary>
/// Constants used for properties of type RemediationActionType.
/// </summary>
public class RemediationActionType : ConstantClass
{
/// <summary>
/// Constant MODIFY for RemediationActionType
/// </summary>
public static readonly RemediationActionType MODIFY = new RemediationActionType("MODIFY");
/// <summary>
/// Constant REMOVE for RemediationActionType
/// </summary>
public static readonly RemediationActionType REMOVE = new RemediationActionType("REMOVE");
/// <summary>
/// This constant constructor does not need to be called if the constant
/// you are attempting to use is already defined as a static instance of
/// this class.
/// This constructor should be used to construct constants that are not
/// defined as statics, for instance if attempting to use a feature that is
/// newer than the current version of the SDK.
/// </summary>
public RemediationActionType(string value)
: base(value)
{
}
/// <summary>
/// Finds the constant for the unique value.
/// </summary>
/// <param name="value">The unique value for the constant</param>
/// <returns>The constant for the unique value</returns>
public static RemediationActionType FindValue(string value)
{
return FindValue<RemediationActionType>(value);
}
/// <summary>
/// Utility method to convert strings to the constant class.
/// </summary>
/// <param name="value">The string value to convert to the constant class.</param>
/// <returns></returns>
public static implicit operator RemediationActionType(string value)
{
return FindValue(value);
}
}
/// <summary>
/// Constants used for properties of type SecurityServiceType.
/// </summary>
public class SecurityServiceType : ConstantClass
{
/// <summary>
/// Constant DNS_FIREWALL for SecurityServiceType
/// </summary>
public static readonly SecurityServiceType DNS_FIREWALL = new SecurityServiceType("DNS_FIREWALL");
/// <summary>
/// Constant NETWORK_FIREWALL for SecurityServiceType
/// </summary>
public static readonly SecurityServiceType NETWORK_FIREWALL = new SecurityServiceType("NETWORK_FIREWALL");
/// <summary>
/// Constant SECURITY_GROUPS_COMMON for SecurityServiceType
/// </summary>
public static readonly SecurityServiceType SECURITY_GROUPS_COMMON = new SecurityServiceType("SECURITY_GROUPS_COMMON");
/// <summary>
/// Constant SECURITY_GROUPS_CONTENT_AUDIT for SecurityServiceType
/// </summary>
public static readonly SecurityServiceType SECURITY_GROUPS_CONTENT_AUDIT = new SecurityServiceType("SECURITY_GROUPS_CONTENT_AUDIT");
/// <summary>
/// Constant SECURITY_GROUPS_USAGE_AUDIT for SecurityServiceType
/// </summary>
public static readonly SecurityServiceType SECURITY_GROUPS_USAGE_AUDIT = new SecurityServiceType("SECURITY_GROUPS_USAGE_AUDIT");
/// <summary>
/// Constant SHIELD_ADVANCED for SecurityServiceType
/// </summary>
public static readonly SecurityServiceType SHIELD_ADVANCED = new SecurityServiceType("SHIELD_ADVANCED");
/// <summary>
/// Constant WAF for SecurityServiceType
/// </summary>
public static readonly SecurityServiceType WAF = new SecurityServiceType("WAF");
/// <summary>
/// Constant WAFV2 for SecurityServiceType
/// </summary>
public static readonly SecurityServiceType WAFV2 = new SecurityServiceType("WAFV2");
/// <summary>
/// This constant constructor does not need to be called if the constant
/// you are attempting to use is already defined as a static instance of
/// this class.
/// This constructor should be used to construct constants that are not
/// defined as statics, for instance if attempting to use a feature that is
/// newer than the current version of the SDK.
/// </summary>
public SecurityServiceType(string value)
: base(value)
{
}
/// <summary>
/// Finds the constant for the unique value.
/// </summary>
/// <param name="value">The unique value for the constant</param>
/// <returns>The constant for the unique value</returns>
public static SecurityServiceType FindValue(string value)
{
return FindValue<SecurityServiceType>(value);
}
/// <summary>
/// Utility method to convert strings to the constant class.
/// </summary>
/// <param name="value">The string value to convert to the constant class.</param>
/// <returns></returns>
public static implicit operator SecurityServiceType(string value)
{
return FindValue(value);
}
}
/// <summary>
/// Constants used for properties of type TargetType.
/// </summary>
public class TargetType : ConstantClass
{
/// <summary>
/// Constant CARRIER_GATEWAY for TargetType
/// </summary>
public static readonly TargetType CARRIER_GATEWAY = new TargetType("CARRIER_GATEWAY");
/// <summary>
/// Constant EGRESS_ONLY_INTERNET_GATEWAY for TargetType
/// </summary>
public static readonly TargetType EGRESS_ONLY_INTERNET_GATEWAY = new TargetType("EGRESS_ONLY_INTERNET_GATEWAY");
/// <summary>
/// Constant GATEWAY for TargetType
/// </summary>
public static readonly TargetType GATEWAY = new TargetType("GATEWAY");
/// <summary>
/// Constant INSTANCE for TargetType
/// </summary>
public static readonly TargetType INSTANCE = new TargetType("INSTANCE");
/// <summary>
/// Constant LOCAL_GATEWAY for TargetType
/// </summary>
public static readonly TargetType LOCAL_GATEWAY = new TargetType("LOCAL_GATEWAY");
/// <summary>
/// Constant NAT_GATEWAY for TargetType
/// </summary>
public static readonly TargetType NAT_GATEWAY = new TargetType("NAT_GATEWAY");
/// <summary>
/// Constant NETWORK_INTERFACE for TargetType
/// </summary>
public static readonly TargetType NETWORK_INTERFACE = new TargetType("NETWORK_INTERFACE");
/// <summary>
/// Constant TRANSIT_GATEWAY for TargetType
/// </summary>
public static readonly TargetType TRANSIT_GATEWAY = new TargetType("TRANSIT_GATEWAY");
/// <summary>
/// Constant VPC_ENDPOINT for TargetType
/// </summary>
public static readonly TargetType VPC_ENDPOINT = new TargetType("VPC_ENDPOINT");
/// <summary>
/// Constant VPC_PEERING_CONNECTION for TargetType
/// </summary>
public static readonly TargetType VPC_PEERING_CONNECTION = new TargetType("VPC_PEERING_CONNECTION");
/// <summary>
/// This constant constructor does not need to be called if the constant
/// you are attempting to use is already defined as a static instance of
/// this class.
/// This constructor should be used to construct constants that are not
/// defined as statics, for instance if attempting to use a feature that is
/// newer than the current version of the SDK.
/// </summary>
public TargetType(string value)
: base(value)
{
}
/// <summary>
/// Finds the constant for the unique value.
/// </summary>
/// <param name="value">The unique value for the constant</param>
/// <returns>The constant for the unique value</returns>
public static TargetType FindValue(string value)
{
return FindValue<TargetType>(value);
}
/// <summary>
/// Utility method to convert strings to the constant class.
/// </summary>
/// <param name="value">The string value to convert to the constant class.</param>
/// <returns></returns>
public static implicit operator TargetType(string value)
{
return FindValue(value);
}
}
/// <summary>
/// Constants used for properties of type ViolationReason.
/// </summary>
public class ViolationReason : ConstantClass
{
/// <summary>
/// Constant BLACK_HOLE_ROUTE_DETECTED for ViolationReason
/// </summary>
public static readonly ViolationReason BLACK_HOLE_ROUTE_DETECTED = new ViolationReason("BLACK_HOLE_ROUTE_DETECTED");
/// <summary>
/// Constant BLACK_HOLE_ROUTE_DETECTED_IN_FIREWALL_SUBNET for ViolationReason
/// </summary>
public static readonly ViolationReason BLACK_HOLE_ROUTE_DETECTED_IN_FIREWALL_SUBNET = new ViolationReason("BLACK_HOLE_ROUTE_DETECTED_IN_FIREWALL_SUBNET");
/// <summary>
/// Constant FIREWALL_SUBNET_MISSING_EXPECTED_ROUTE for ViolationReason
/// </summary>
public static readonly ViolationReason FIREWALL_SUBNET_MISSING_EXPECTED_ROUTE = new ViolationReason("FIREWALL_SUBNET_MISSING_EXPECTED_ROUTE");
/// <summary>
/// Constant FMS_CREATED_SECURITY_GROUP_EDITED for ViolationReason
/// </summary>
public static readonly ViolationReason FMS_CREATED_SECURITY_GROUP_EDITED = new ViolationReason("FMS_CREATED_SECURITY_GROUP_EDITED");
/// <summary>
/// Constant INTERNET_GATEWAY_MISSING_EXPECTED_ROUTE for ViolationReason
/// </summary>
public static readonly ViolationReason INTERNET_GATEWAY_MISSING_EXPECTED_ROUTE = new ViolationReason("INTERNET_GATEWAY_MISSING_EXPECTED_ROUTE");
/// <summary>
/// Constant INTERNET_TRAFFIC_NOT_INSPECTED for ViolationReason
/// </summary>
public static readonly ViolationReason INTERNET_TRAFFIC_NOT_INSPECTED = new ViolationReason("INTERNET_TRAFFIC_NOT_INSPECTED");
/// <summary>
/// Constant INVALID_ROUTE_CONFIGURATION for ViolationReason
/// </summary>
public static readonly ViolationReason INVALID_ROUTE_CONFIGURATION = new ViolationReason("INVALID_ROUTE_CONFIGURATION");
/// <summary>
/// Constant MISSING_EXPECTED_ROUTE_TABLE for ViolationReason
/// </summary>
public static readonly ViolationReason MISSING_EXPECTED_ROUTE_TABLE = new ViolationReason("MISSING_EXPECTED_ROUTE_TABLE");
/// <summary>
/// Constant MISSING_FIREWALL for ViolationReason
/// </summary>
public static readonly ViolationReason MISSING_FIREWALL = new ViolationReason("MISSING_FIREWALL");
/// <summary>
/// Constant MISSING_FIREWALL_SUBNET_IN_AZ for ViolationReason
/// </summary>
public static readonly ViolationReason MISSING_FIREWALL_SUBNET_IN_AZ = new ViolationReason("MISSING_FIREWALL_SUBNET_IN_AZ");
/// <summary>
/// Constant MISSING_TARGET_GATEWAY for ViolationReason
/// </summary>
public static readonly ViolationReason MISSING_TARGET_GATEWAY = new ViolationReason("MISSING_TARGET_GATEWAY");
/// <summary>
/// Constant NETWORK_FIREWALL_POLICY_MODIFIED for ViolationReason
/// </summary>
public static readonly ViolationReason NETWORK_FIREWALL_POLICY_MODIFIED = new ViolationReason("NETWORK_FIREWALL_POLICY_MODIFIED");
/// <summary>
/// Constant RESOURCE_INCORRECT_WEB_ACL for ViolationReason
/// </summary>
public static readonly ViolationReason RESOURCE_INCORRECT_WEB_ACL = new ViolationReason("RESOURCE_INCORRECT_WEB_ACL");
/// <summary>
/// Constant RESOURCE_MISSING_DNS_FIREWALL for ViolationReason
/// </summary>
public static readonly ViolationReason RESOURCE_MISSING_DNS_FIREWALL = new ViolationReason("RESOURCE_MISSING_DNS_FIREWALL");
/// <summary>
/// Constant RESOURCE_MISSING_SECURITY_GROUP for ViolationReason
/// </summary>
public static readonly ViolationReason RESOURCE_MISSING_SECURITY_GROUP = new ViolationReason("RESOURCE_MISSING_SECURITY_GROUP");
/// <summary>
/// Constant RESOURCE_MISSING_SHIELD_PROTECTION for ViolationReason
/// </summary>
public static readonly ViolationReason RESOURCE_MISSING_SHIELD_PROTECTION = new ViolationReason("RESOURCE_MISSING_SHIELD_PROTECTION");
/// <summary>
/// Constant RESOURCE_MISSING_WEB_ACL for ViolationReason
/// </summary>
public static readonly ViolationReason RESOURCE_MISSING_WEB_ACL = new ViolationReason("RESOURCE_MISSING_WEB_ACL");
/// <summary>
/// Constant RESOURCE_MISSING_WEB_ACL_OR_SHIELD_PROTECTION for ViolationReason
/// </summary>
public static readonly ViolationReason RESOURCE_MISSING_WEB_ACL_OR_SHIELD_PROTECTION = new ViolationReason("RESOURCE_MISSING_WEB_ACL_OR_SHIELD_PROTECTION");
/// <summary>
/// Constant RESOURCE_VIOLATES_AUDIT_SECURITY_GROUP for ViolationReason
/// </summary>
public static readonly ViolationReason RESOURCE_VIOLATES_AUDIT_SECURITY_GROUP = new ViolationReason("RESOURCE_VIOLATES_AUDIT_SECURITY_GROUP");
/// <summary>
/// Constant SECURITY_GROUP_REDUNDANT for ViolationReason
/// </summary>
public static readonly ViolationReason SECURITY_GROUP_REDUNDANT = new ViolationReason("SECURITY_GROUP_REDUNDANT");
/// <summary>
/// Constant SECURITY_GROUP_UNUSED for ViolationReason
/// </summary>
public static readonly ViolationReason SECURITY_GROUP_UNUSED = new ViolationReason("SECURITY_GROUP_UNUSED");
/// <summary>
/// Constant TRAFFIC_INSPECTION_CROSSES_AZ_BOUNDARY for ViolationReason
/// </summary>
public static readonly ViolationReason TRAFFIC_INSPECTION_CROSSES_AZ_BOUNDARY = new ViolationReason("TRAFFIC_INSPECTION_CROSSES_AZ_BOUNDARY");
/// <summary>
/// Constant UNEXPECTED_FIREWALL_ROUTES for ViolationReason
/// </summary>
public static readonly ViolationReason UNEXPECTED_FIREWALL_ROUTES = new ViolationReason("UNEXPECTED_FIREWALL_ROUTES");
/// <summary>
/// Constant UNEXPECTED_TARGET_GATEWAY_ROUTES for ViolationReason
/// </summary>
public static readonly ViolationReason UNEXPECTED_TARGET_GATEWAY_ROUTES = new ViolationReason("UNEXPECTED_TARGET_GATEWAY_ROUTES");
/// <summary>
/// Constant WEB_ACL_MISSING_RULE_GROUP for ViolationReason
/// </summary>
public static readonly ViolationReason WEB_ACL_MISSING_RULE_GROUP = new ViolationReason("WEB_ACL_MISSING_RULE_GROUP");
/// <summary>
/// This constant constructor does not need to be called if the constant
/// you are attempting to use is already defined as a static instance of
/// this class.
/// This constructor should be used to construct constants that are not
/// defined as statics, for instance if attempting to use a feature that is
/// newer than the current version of the SDK.
/// </summary>
public ViolationReason(string value)
: base(value)
{
}
/// <summary>
/// Finds the constant for the unique value.
/// </summary>
/// <param name="value">The unique value for the constant</param>
/// <returns>The constant for the unique value</returns>
public static ViolationReason FindValue(string value)
{
return FindValue<ViolationReason>(value);
}
/// <summary>
/// Utility method to convert strings to the constant class.
/// </summary>
/// <param name="value">The string value to convert to the constant class.</param>
/// <returns></returns>
public static implicit operator ViolationReason(string value)
{
return FindValue(value);
}
}
}
| 42.589506 | 164 | 0.646677 |
[
"Apache-2.0"
] |
ChristopherButtars/aws-sdk-net
|
sdk/src/Services/FMS/Generated/ServiceEnumerations.cs
| 27,598 |
C#
|
//----------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
//----------------------------------------------------------------
namespace System.Activities.Expressions
{
using System.Activities;
using System.Activities.Statements;
using System.Linq.Expressions;
using System.Activities.Validation;
using System.Collections.Generic;
using System.ComponentModel;
using System.Runtime;
public sealed class Subtract<TLeft, TRight, TResult> : CodeActivity<TResult>
{
//Lock is not needed for operationFunction here. The reason is that delegates for a given Subtract<TLeft, TRight, TResult> are the same.
//It's possible that 2 threads are assigning the operationFucntion at the same time. But it's okay because the compiled codes are the same.
static Func<TLeft, TRight, TResult> checkedOperationFunction;
static Func<TLeft, TRight, TResult> uncheckedOperationFunction;
bool checkedOperation = true;
[RequiredArgument]
[DefaultValue(null)]
public InArgument<TLeft> Left
{
get;
set;
}
[RequiredArgument]
[DefaultValue(null)]
public InArgument<TRight> Right
{
get;
set;
}
[DefaultValue(true)]
public bool Checked
{
get { return this.checkedOperation; }
set { this.checkedOperation = value; }
}
protected override void CacheMetadata(CodeActivityMetadata metadata)
{
BinaryExpressionHelper.OnGetArguments(metadata, this.Left, this.Right);
if (this.checkedOperation)
{
EnsureOperationFunction(metadata, ref checkedOperationFunction, ExpressionType.SubtractChecked);
}
else
{
EnsureOperationFunction(metadata, ref uncheckedOperationFunction, ExpressionType.Subtract);
}
}
void EnsureOperationFunction(CodeActivityMetadata metadata,
ref Func<TLeft, TRight, TResult> operationFunction,
ExpressionType operatorType)
{
if (operationFunction == null)
{
ValidationError validationError;
if (!BinaryExpressionHelper.TryGenerateLinqDelegate(
operatorType,
out operationFunction,
out validationError))
{
metadata.AddValidationError(validationError);
}
}
}
protected override TResult Execute(CodeActivityContext context)
{
TLeft leftValue = this.Left.Get(context);
TRight rightValue = this.Right.Get(context);
//if user changed Checked flag between Open and Execution,
//a NRE may be thrown and that's by design
if (this.checkedOperation)
{
return checkedOperationFunction(leftValue, rightValue);
}
else
{
return uncheckedOperationFunction(leftValue, rightValue);
}
}
}
}
| 34.347368 | 147 | 0.567882 |
[
"Apache-2.0"
] |
295007712/295007712.github.io
|
sourceCode/dotNet4.6/ndp/cdf/src/NetFx40/System.Activities/System/Activities/Expressions/Subtract.cs
| 3,265 |
C#
|
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System;
using System.Diagnostics;
using System.Runtime.CompilerServices;
namespace Iot.Device
{
/// <summary>
/// Common code for Sensirion devices.
/// </summary>
internal static class Sensirion
{
/// <returns>If the CRC8 matched the data, a <see cref="ushort"/> of data. Otherwise, <see langword="null"/>.</returns>
public static ushort? ReadUInt16BigEndianAndCRC8(ReadOnlySpan<byte> bytes)
{
Debug.Assert(bytes.Length >= 3, $"{nameof(bytes)} must contain at least 3 bytes.");
_ = bytes[2];
byte hi = bytes[0];
byte lo = bytes[1];
byte crc = bytes[2];
return CRC8(hi, lo) == crc
? (ushort)((hi << 8) | lo)
: null;
}
public static void WriteUInt16BigEndianAndCRC8(Span<byte> bytes, ushort value)
{
Debug.Assert(bytes.Length >= 3, $"{nameof(bytes)} must contain at least 3 bytes.");
byte hi = (byte)((uint)value >> 8);
byte lo = (byte)value;
_ = bytes[2];
bytes[0] = hi;
bytes[1] = lo;
bytes[2] = CRC8(hi, lo);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private static byte CRC8(byte byteA, byte byteB) =>
CrcLookup[CrcLookup[0xFF ^ byteA] ^ byteB];
private static ReadOnlySpan<byte> CrcLookup => new byte[]
{
0x00, 0x31, 0x62, 0x53, 0xC4, 0xF5, 0xA6, 0x97, 0xB9, 0x88, 0xDB, 0xEA, 0x7D, 0x4C, 0x1F, 0x2E,
0x43, 0x72, 0x21, 0x10, 0x87, 0xB6, 0xE5, 0xD4, 0xFA, 0xCB, 0x98, 0xA9, 0x3E, 0x0F, 0x5C, 0x6D,
0x86, 0xB7, 0xE4, 0xD5, 0x42, 0x73, 0x20, 0x11, 0x3F, 0x0E, 0x5D, 0x6C, 0xFB, 0xCA, 0x99, 0xA8,
0xC5, 0xF4, 0xA7, 0x96, 0x01, 0x30, 0x63, 0x52, 0x7C, 0x4D, 0x1E, 0x2F, 0xB8, 0x89, 0xDA, 0xEB,
0x3D, 0x0C, 0x5F, 0x6E, 0xF9, 0xC8, 0x9B, 0xAA, 0x84, 0xB5, 0xE6, 0xD7, 0x40, 0x71, 0x22, 0x13,
0x7E, 0x4F, 0x1C, 0x2D, 0xBA, 0x8B, 0xD8, 0xE9, 0xC7, 0xF6, 0xA5, 0x94, 0x03, 0x32, 0x61, 0x50,
0xBB, 0x8A, 0xD9, 0xE8, 0x7F, 0x4E, 0x1D, 0x2C, 0x02, 0x33, 0x60, 0x51, 0xC6, 0xF7, 0xA4, 0x95,
0xF8, 0xC9, 0x9A, 0xAB, 0x3C, 0x0D, 0x5E, 0x6F, 0x41, 0x70, 0x23, 0x12, 0x85, 0xB4, 0xE7, 0xD6,
0x7A, 0x4B, 0x18, 0x29, 0xBE, 0x8F, 0xDC, 0xED, 0xC3, 0xF2, 0xA1, 0x90, 0x07, 0x36, 0x65, 0x54,
0x39, 0x08, 0x5B, 0x6A, 0xFD, 0xCC, 0x9F, 0xAE, 0x80, 0xB1, 0xE2, 0xD3, 0x44, 0x75, 0x26, 0x17,
0xFC, 0xCD, 0x9E, 0xAF, 0x38, 0x09, 0x5A, 0x6B, 0x45, 0x74, 0x27, 0x16, 0x81, 0xB0, 0xE3, 0xD2,
0xBF, 0x8E, 0xDD, 0xEC, 0x7B, 0x4A, 0x19, 0x28, 0x06, 0x37, 0x64, 0x55, 0xC2, 0xF3, 0xA0, 0x91,
0x47, 0x76, 0x25, 0x14, 0x83, 0xB2, 0xE1, 0xD0, 0xFE, 0xCF, 0x9C, 0xAD, 0x3A, 0x0B, 0x58, 0x69,
0x04, 0x35, 0x66, 0x57, 0xC0, 0xF1, 0xA2, 0x93, 0xBD, 0x8C, 0xDF, 0xEE, 0x79, 0x48, 0x1B, 0x2A,
0xC1, 0xF0, 0xA3, 0x92, 0x05, 0x34, 0x67, 0x56, 0x78, 0x49, 0x1A, 0x2B, 0xBC, 0x8D, 0xDE, 0xEF,
0x82, 0xB3, 0xE0, 0xD1, 0x46, 0x77, 0x24, 0x15, 0x3B, 0x0A, 0x59, 0x68, 0xFF, 0xCE, 0x9D, 0xAC
};
}
}
| 46.901408 | 127 | 0.577477 |
[
"MIT"
] |
CodedBeard/iot
|
src/devices/Shared/Sensirion.cs
| 3,332 |
C#
|
using Cdy.Spider;
using System;
namespace Cdy.Api.SpiderTcp.Develop
{
public class SpiderTcpDevelop : Cdy.Spider.ApiDevelopBase
{
#region ... Variables ...
private TcpApiData mData;
#endregion ...Variables...
#region ... Events ...
#endregion ...Events...
#region ... Constructor...
#endregion ...Constructor...
#region ... Properties ...
/// <summary>
///
/// </summary>
public override ApiData Data { get => mData; set { mData = value as TcpApiData; } }
/// <summary>
///
/// </summary>
public override string TypeName => "SpiderTcpApi";
#endregion ...Properties...
#region ... Methods ...
/// <summary>
///
/// </summary>
/// <returns></returns>
public override object Config()
{
if(mData==null) mData = new TcpApiData() { Port = 10000, UserName = "Admin", Password = "Admin", ServerIp = "127.0.0.1", Type = ApiData.TransType.Timer, Circle = 2000 };
return new ApiConfigViewModel() { Model = mData };
}
/// <summary>
///
/// </summary>
/// <returns></returns>
protected override ApiData CreatNewData()
{
return new TcpApiData() { Port = 10000,UserName= "Admin", Password="Admin",ServerIp="127.0.0.1",Type = ApiData.TransType.Timer,Circle=2000 };
}
public override IApiDevelop NewApi()
{
return new SpiderTcpDevelop();
}
#endregion ...Methods...
#region ... Interfaces ...
#endregion ...Interfaces...
}
}
| 23.666667 | 181 | 0.514671 |
[
"Apache-2.0"
] |
bingwang12/Spider
|
Develop/Api/Cdy.Api.SpiderTcp.Develop/SpiderTcpDevelop.cs
| 1,704 |
C#
|
namespace Ryujinx.Graphics.Gpu.State
{
/// <summary>
/// Stencil test masks for back tests.
/// </summary>
struct StencilBackMasks
{
#pragma warning disable CS0649
public int FuncRef;
public int Mask;
public int FuncMask;
#pragma warning restore CS0649
}
}
| 20.333333 | 42 | 0.636066 |
[
"MIT"
] |
0MrDarn0/Ryujinx
|
Ryujinx.Graphics.Gpu/State/StencilBackMasks.cs
| 305 |
C#
|
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT license.
//--------------------------------------------------------------------------------------
// QueryEvent.cs
//
// Event structure returned from queries
//
// Advanced Technology Group (ATG)
// Copyright (C) Microsoft Corporation. All rights reserved.
//--------------------------------------------------------------------------------------
using System;
using System.Collections.Generic;
using UnityEngine;
namespace GameTelemetry
{
public static class QueryIds
{
public const string PlayerPos = "pos";
public const string PlayerDir = "dir";
public const string CamPos = "cam_pos";
public const string CamDir = "cam_dir";
public const string Id = "id";
public const string ClientId = "client_id";
public const string SessionId = "session_id";
public const string Sequence = "seq";
public const string EventName = "name";
public const string EventAction = "action";
public const string ClientTimestamp = "client_ts";
public const string EventVersion = "e_ver";
public const string BuildType = "build_type";
public const string BuildId = "build_id";
public const string ProcessId = "process_id";
public const string Platform = "platform";
public const string Category = "cat";
}
//Wrapper for each event
public class QueryEvent
{
Dictionary<string, JSONObj> Attributes = new Dictionary<string, JSONObj>();
public QueryEvent() { }
public QueryEvent(JSONObj jObj)
{
Debug.Assert(jObj.IsObject);
for (int i = 0; i < jObj.keys.Count; i++)
{
this.Attributes.Add(jObj.keys[i], jObj.list[i]);
}
}
public string Id
{
get
{
return GetString(QueryIds.Id);
}
}
public string ClientId
{
get
{
return GetString(QueryIds.ClientId);
}
}
public string SessionId
{
get
{
return GetString(QueryIds.SessionId);
}
}
public string Name
{
get
{
return GetString(QueryIds.EventName);
}
}
public string BuildType
{
get
{
return GetString(QueryIds.BuildType);
}
}
public string BuildId
{
get
{
return GetString(QueryIds.BuildId);
}
}
public string Platform
{
get
{
return GetString(QueryIds.Platform);
}
}
public string Category
{
get
{
return GetString(QueryIds.Category);
}
}
UInt32 Sequence
{
get
{
return (UInt32)GetNumber(QueryIds.Sequence);
}
}
public DateTime Time
{
get
{
return DateTime.Parse(GetString(QueryIds.ClientTimestamp));
}
}
public Vector3 PlayerPosition
{
get
{
return GetVector(QueryIds.PlayerPos);
}
}
public Vector3 PlayerDirection
{
get
{
return GetVector(QueryIds.PlayerDir);
}
}
public Vector3 CameraPosition
{
get
{
return GetVector(QueryIds.CamPos);
}
}
public Vector3 CameraDirection
{
get
{
return GetVector(QueryIds.CamDir);
}
}
public QueryEvent Parse(JSONObj jObj)
{
Debug.Assert(jObj.IsObject);
QueryEvent ev = new QueryEvent();
for (int i = 0; i < jObj.keys.Count; i++)
{
ev.Attributes.Add(jObj.keys[i], jObj.list[i]);
}
return ev;
}
public void GetAttributes(ref Dictionary<string, JSONObj> inMap)
{
foreach (var attr in Attributes)
{
if (attr.Key.StartsWith("pct_") || attr.Key.StartsWith("val_"))
{
inMap.Add(attr.Key, attr.Value);
}
}
}
public bool TryGetString(string name, out string outString)
{
if(Attributes.ContainsKey(name))
{
JSONObj Value = Attributes[name];
if (Value != null && Value.IsString)
{
string newString = Value.ToString();
outString = newString.Substring(1, newString.Length - 2);
return true;
}
}
outString = "";
return false;
}
public string GetString(string name)
{
string value;
TryGetString(name, out value);
return value;
}
public bool TryGetNumber(string name, out double number)
{
if (Attributes.ContainsKey(name))
{
JSONObj Value = Attributes[name];
if (Value != null && Value.IsNumber)
{
number = Value.n;
return true;
}
}
number = 0;
return false;
}
public double GetNumber(string name)
{
double Value;
TryGetNumber(name, out Value);
return Value;
}
public bool TryGetVector(string baseName, out Vector3 vector)
{
vector = new Vector3();
if (Attributes.ContainsKey(baseName))
{
JSONObj Value = Attributes[baseName];
if (Value != null && Value.IsObject)
{
for(int i = 0; i < Value.list.Count; i++)
{
if(Value.list[i].IsNumber)
{
if (Value.keys[i] == "x")
{
vector.x = Value.list[i].f;
}
else if (Value.keys[i] == "y")
{
vector.y = Value.list[i].f;
}
else if (Value.keys[i] == "z")
{
vector.z = Value.list[i].f;
}
}
}
return true;
}
}
return false;
}
public Vector3 GetVector(string baseName)
{
Vector3 vector;
TryGetVector(baseName, out vector);
return vector;
}
public bool TryGetBool(string Name, out bool outBool)
{
if(Attributes.ContainsKey(Name))
{
JSONObj Value = Attributes[Name];
if (Value != null && Value.IsBool)
{
outBool = Value.b;
return true;
}
}
outBool = false;
return false;
}
public bool GetBool(string Name)
{
bool value;
TryGetBool(Name, out value);
return value;
}
}
}
| 26.544262 | 89 | 0.409091 |
[
"MIT"
] |
Bhaskers-Blu-Org2/UnityTelemetryVisualizer
|
Plugins/GameTelemetry/QueryEvents.cs
| 8,096 |
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.Media.V20200501.Inputs
{
/// <summary>
/// Describes the properties for producing a collection of GOP aligned multi-bitrate files. The default behavior is to produce one output file for each video layer which is muxed together with all the audios. The exact output files produced can be controlled by specifying the outputFiles collection.
/// </summary>
public sealed class MultiBitrateFormatArgs : Pulumi.ResourceArgs
{
/// <summary>
/// The pattern of the file names for the generated output files. The following macros are supported in the file name: {Basename} - An expansion macro that will use the name of the input video file. If the base name(the file suffix is not included) of the input video file is less than 32 characters long, the base name of input video files will be used. If the length of base name of the input video file exceeds 32 characters, the base name is truncated to the first 32 characters in total length. {Extension} - The appropriate extension for this format. {Label} - The label assigned to the codec/layer. {Index} - A unique index for thumbnails. Only applicable to thumbnails. {Bitrate} - The audio/video bitrate. Not applicable to thumbnails. {Codec} - The type of the audio/video codec. {Resolution} - The video resolution. Any unsubstituted macros will be collapsed and removed from the filename.
/// </summary>
[Input("filenamePattern", required: true)]
public Input<string> FilenamePattern { get; set; } = null!;
/// <summary>
/// The discriminator for derived types.
/// Expected value is '#Microsoft.Media.MultiBitrateFormat'.
/// </summary>
[Input("odataType", required: true)]
public Input<string> OdataType { get; set; } = null!;
[Input("outputFiles")]
private InputList<Inputs.OutputFileArgs>? _outputFiles;
/// <summary>
/// The list of output files to produce. Each entry in the list is a set of audio and video layer labels to be muxed together .
/// </summary>
public InputList<Inputs.OutputFileArgs> OutputFiles
{
get => _outputFiles ?? (_outputFiles = new InputList<Inputs.OutputFileArgs>());
set => _outputFiles = value;
}
public MultiBitrateFormatArgs()
{
}
}
}
| 55.75 | 908 | 0.695441 |
[
"Apache-2.0"
] |
polivbr/pulumi-azure-native
|
sdk/dotnet/Media/V20200501/Inputs/MultiBitrateFormatArgs.cs
| 2,676 |
C#
|
/*
Copyright 2007-2017 The NGenerics Team
(https://github.com/ngenerics/ngenerics/wiki/Team)
This program is licensed under the MIT License. You should
have received a copy of the license along with the source code. If not, an online copy
of the license can be found at https://opensource.org/licenses/MIT.
*/
using System;
using System.Diagnostics;
using NGenerics.DataStructures.General;
using NGenerics.Extensions;
using NGenerics.Patterns.Visitor;
using NUnit.Framework;
namespace NGenerics.Examples.DataStructures.General
{
[TestFixture]
public class SortedListExamples
{
#region Accept
[Test]
public void AcceptVisitorExample()
{
var sortedList = new SortedList<string> {"cat", "dog", "canary"};
// There should be 3 items in the sortedList.
Assert.AreEqual(3, sortedList.Count);
// Create a visitor that will simply count the items in the sortedList.
var visitor =new CountingVisitor<string>();
// Make sortedList tree call IVisitor<T>.Visit on all items contained.
sortedList.AcceptVisitor(visitor);
// The counting visitor would have visited 3 items.
Assert.AreEqual(3, visitor.Count);
}
#endregion
#region Add
[Test]
public void AddExample()
{
var sortedList = new SortedList<string>();
sortedList.Add("cat");
sortedList.Add("dog");
sortedList.Add("canary");
// There should be 3 items in the sortedList.
Assert.AreEqual(3, sortedList.Count);
}
#endregion
#region Clear
[Test]
public void ClearExample()
{
var sortedList = new SortedList<string> {"cat", "dog", "canary"};
// There should be 3 items in the sortedList.
Assert.AreEqual(3, sortedList.Count);
// Clear the tree
sortedList.Clear();
// The sortedList should be empty.
Assert.AreEqual(0, sortedList.Count);
// No cat here..
Assert.IsFalse(sortedList.Contains("cat"));
}
#endregion
#region Constructor
[Test]
public void ConstructorExample()
{
new SortedList<string> {"cat", "dog", "canary"};
}
#endregion
#region ConstructorCapacity
[Test]
public void ConstructorCapacityExample()
{
// If you know how many items will initially be in the list it is
// more efficient to set the initial capacity
new SortedList<string>(3) {"cat", "dog", "canary"};
}
#endregion
#region ConstructorCollection
[Test]
public void ConstructorCollectionExample()
{
var array = new[] {"cat", "dog", "canary"};
var sortedList = new SortedList<string>(array);
// sortedList contains all the elements of the array
Assert.IsTrue(sortedList.Contains("cat"));
Assert.IsTrue(sortedList.Contains("canary"));
Assert.IsTrue(sortedList.Contains("dog"));
}
#endregion
#region ConstructorComparer
[Test]
public void ConstructorComparerExample()
{
var sortedListIgnoreCase = new SortedList<string>(StringComparer.OrdinalIgnoreCase)
{
"cat",
"dog",
"CAT"
};
//"CAT" will be at the start because case is ignored
Assert.AreEqual(0, sortedListIgnoreCase.IndexOf("CAT"));
var sortedListUseCase = new SortedList<string>
{
"cat",
"dog",
"CAT"
};
//"CAT" will in the second position because case is not ignored
Assert.AreEqual(1, sortedListUseCase.IndexOf("CAT"));
}
#endregion
#region Contains
[Test]
public void ContainsExample()
{
var sortedList = new SortedList<string> {"cat", "dog", "canary"};
// sortedList does contain cat, dog and canary
Assert.IsTrue(sortedList.Contains("cat"));
Assert.IsTrue(sortedList.Contains("dog"));
Assert.IsTrue(sortedList.Contains("canary"));
// but not frog
Assert.IsFalse(sortedList.Contains("frog"));
}
#endregion
#region CopyTo
[Test]
public void CopyToExample()
{
var sortedList = new SortedList<string> {"cat", "dog", "canary"};
// create new string array with the same length
var stringArray = new string[sortedList.Count];
sortedList.CopyTo(stringArray, 0);
// stringArray contains cat, dog and canary (note canary is in the 0 position)
Assert.AreEqual("canary", stringArray[0]);
Assert.AreEqual("cat", stringArray[1]);
Assert.AreEqual("dog", stringArray[2]);
}
#endregion
#region Count
[Test]
public void CountExample()
{
var sortedList = new SortedList<string> {"cat", "dog", "canary"};
// Count is 3
Assert.AreEqual(3, sortedList.Count);
}
#endregion
#region GetEnumerator
[Test]
public void GetEnumeratorExample()
{
var sortedList = new SortedList<string> {"cat", "dog", "canary"};
// Get the enumerator and iterate through it.
var enumerator = sortedList.GetEnumerator();
while (enumerator.MoveNext())
{
Debug.WriteLine(enumerator.Current);
}
}
#endregion
#region IndexOf
[Test]
public void IndexOfExample()
{
var sortedList = new SortedList<string> {"canary", "cat", "dog"};
// "dog" is in position 2
Assert.AreEqual(2, sortedList.IndexOf("dog"));
}
#endregion
#region IsReadOnly
[Test]
public void IsReadOnlyExample()
{
var sortedList = new SortedList<string>();
// IsReadOnly is always false for a SortedList
Assert.IsFalse(sortedList.IsReadOnly);
sortedList.Add("cat");
sortedList.Add("dog");
sortedList.Add("canary");
Assert.IsFalse(sortedList.IsReadOnly);
}
#endregion
#region Remove
[Test]
public void RemoveExample()
{
var sortedList = new SortedList<string> {"cat", "dog", "canary"};
// SortedList Contains "dog"
Assert.IsTrue(sortedList.Contains("dog"));
// Remove "dog"
sortedList.Remove("dog");
// SortedList does not contains "dog"
Assert.IsFalse(sortedList.Contains("dog"));
}
#endregion
#region RemoveAt
[Test]
public void RemoveAtExample()
{
var sortedList = new SortedList<string> {"canary", "cat", "dog"};
// SortedList Contains "dog"
Assert.IsTrue(sortedList.Contains("dog"));
// "dog" is in position 2
Assert.AreEqual(2, sortedList.IndexOf("dog"));
// Remove "dog"
sortedList.RemoveAt(2);
// SortedList does not contains "dog"
Assert.IsFalse(sortedList.Contains("dog"));
}
#endregion
}
}
| 26.341137 | 92 | 0.530853 |
[
"MIT"
] |
ngenerics/ngenerics
|
src/NGenerics.Examples/DataStructures/General/SortedListExamples.cs
| 7,876 |
C#
|
/**
* Copyright (c) Microsoft Corporation.
* Licensed under the MIT License.
*/
using TeamCloud.Model.Commands.Core;
using TeamCloud.Model.Data;
namespace TeamCloud.Model.Commands
{
public sealed class OrganizationDeployCommandResult : CommandResult<Organization>
{
}
}
| 19.333333 | 85 | 0.737931 |
[
"MIT"
] |
Chongruiyuan893/TeamCloud
|
src/TeamCloud.Model/Commands/OrganizationDeployCommandResult.cs
| 292 |
C#
|
using Entitas;
public class MoveSystem : ISystem {
}
| 9.333333 | 35 | 0.714286 |
[
"MIT"
] |
Mwimwii/Entitas-CSharp
|
Tests/Tests/Entitas.Migration/Fixtures/M0180/SubFolder/MoveSystem.cs
| 58 |
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.CustomerInsights.Latest.Inputs
{
/// <summary>
/// Map a field of profile to its corresponding StrongId in Related Profile.
/// </summary>
public sealed class RelationshipTypeFieldMappingArgs : Pulumi.ResourceArgs
{
/// <summary>
/// Specifies the fieldName in profile.
/// </summary>
[Input("profileFieldName", required: true)]
public Input<string> ProfileFieldName { get; set; } = null!;
/// <summary>
/// Specifies the KeyProperty (from StrongId) of the related profile.
/// </summary>
[Input("relatedProfileKeyProperty", required: true)]
public Input<string> RelatedProfileKeyProperty { get; set; } = null!;
public RelationshipTypeFieldMappingArgs()
{
}
}
}
| 32.028571 | 81 | 0.660125 |
[
"Apache-2.0"
] |
pulumi-bot/pulumi-azure-native
|
sdk/dotnet/CustomerInsights/Latest/Inputs/RelationshipTypeFieldMappingArgs.cs
| 1,121 |
C#
|
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEditor.Experimental.U2D.Layout;
namespace UnityEditor.Experimental.U2D.Animation
{
internal class SkeletonToolWrapper : BaseTool
{
private SkeletonTool m_SkeletonTool;
private SkeletonMode m_Mode;
public SkeletonTool skeletonTool
{
get { return m_SkeletonTool; }
set { m_SkeletonTool = value; }
}
public SkeletonMode mode
{
get { return m_Mode; }
set { m_Mode = value; }
}
public bool editBindPose { get; set; }
public override int defaultControlID
{
get
{
Debug.Assert(skeletonTool != null);
return skeletonTool.defaultControlID;
}
}
protected override void OnActivate()
{
Debug.Assert(skeletonTool != null);
skeletonTool.enableBoneInspector = true;
skeletonTool.Activate();
}
protected override void OnDeactivate()
{
skeletonTool.enableBoneInspector = false;
skeletonTool.Deactivate();
}
private SkeletonMode OverrideMode()
{
var modeOverride = mode;
//Disable SkeletonManipulation if character exists and we are in SpriteSheet mode
if (skinningCache.mode == SkinningMode.SpriteSheet && skinningCache.hasCharacter && editBindPose)
modeOverride = SkeletonMode.Selection;
return modeOverride;
}
protected override void OnGUI()
{
Debug.Assert(skeletonTool != null);
skeletonTool.mode = OverrideMode();
skeletonTool.editBindPose = editBindPose;
skeletonTool.DoGUI();
}
}
}
| 27.097222 | 110 | 0.561251 |
[
"MIT"
] |
MandyMY/HalloweenCandies
|
Code/Library/PackageCache/[email protected]/Editor/SkinningModule/SkeletonTool/SkeletonToolWrapper.cs
| 1,951 |
C#
|
using Microsoft.EntityFrameworkCore;
using PatientRecordSystem.Domain.Models;
using PatientRecordSystem.Domain.Repositories;
using PatientRecordSystem.Extensions;
using PatientRecordSystem.Helpers;
using PatientRecordSystem.Persistence.Contexts;
using PatientRecordSystem.Resources;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Threading.Tasks;
namespace PatientRecordSystem.Persistence.Repositories
{
public class PatientRepository : BaseRepository<Patient>, IPatientRepository
{
public PatientRepository(ApplicationDbContext context) : base(context)
{
}
public override async Task<Patient> GetById(int id)
{
return await _context.Patients.Include(x => x.MetaData).SingleOrDefaultAsync(x => x.Id == id);
}
public async Task<IEnumerable<Patient>> Search(string prfix, int size)
{
return await _context.Patients.Where(x => x.PatientName.StartsWith(prfix)).OrderBy(x => x.PatientName).Take(size).ToListAsync();
}
public async Task<PatientReportResource> GetPatientReport(int id)
{
var PatientDiseaseList = new List<PatientDiseasesResource>();
var res = await _context.Patients.Select(x => new
{
x.Id,
x.PatientName,
Diseases = x.Records.Select(r => r.DiseaseName).Distinct()
}).ToListAsync();
var Patient = res.FirstOrDefault(x => x.Id == id);
if (Patient.Diseases.Count() > 1)
{
foreach (var item in res.Where(x => x.Id != id).ToList())
{
if (item.Diseases.Count() < 2)
continue;
var commonDiseases = Patient.Diseases.Intersect(item.Diseases).ToList();
if (commonDiseases.Count() < 2)
continue;
PatientDiseaseList.Add(new PatientDiseasesResource
{
PatientName = item.PatientName,
DiseaseList = commonDiseases
});
}
}
PatientDiseaseList = PatientDiseaseList.OrderBy(x => x.PatientName).ToList();
var list = await _context.PatientReport.Select(x => new PatientReportResource
{
Id = x.Id,
PatientName = x.PatientName,
Age = x.Age,
Avg = x.Avg,
AvgW = x.AvgW,
MostVisitMounth = x.MostVisitMounth,
PatientDiseases = PatientDiseaseList,
record = _context.Records.Where(x => x.PatientId == id).OrderBy(x => x.TimeOfEntry).Skip(4).Take(1).Select(x => new RecordResource
{
Id = x.Id,
PatientName = x.Patient.PatientName,
DiseaseName = x.DiseaseName,
TimeOfEntry = x.TimeOfEntry
}).FirstOrDefault()
}).SingleOrDefaultAsync(x => x.Id == id);
return list;
}
public async Task<PagedList<PatientResource>> ListAsync(QueryStringParameters queryString, Dictionary<string, Expression<Func<PatientResource, object>>> columnsMap)
{
var query = _context.Patients.Select(x => new PatientResource
{
Id = x.Id,
PatientName = x.PatientName,
DateOfBirth = x.DateOfBirth,
MetaDataCount = x.MetaData.Count(),
LastEntry = x.Records.Select(x => x.TimeOfEntry).OrderByDescending(x => x).FirstOrDefault()
}).Sort<PatientResource>(queryString.SortBy, columnsMap, queryString.IsSortAscending);
return await PagedList<PatientResource>.ToPagedListAsync(query, queryString.PageNumber, queryString.PageSize);
}
public async Task<bool> IsExist(int Oid, int? id)
{
var query = id.HasValue ? _context.Patients.Where(x => x.Id != id) : _context.Patients;
return await query.AnyAsync(e => e.OffcialId == Oid);
}
}
}
| 41.87 | 172 | 0.580845 |
[
"MIT"
] |
amiqat/Patient-Record-System
|
PatientRecordSystem/Persistence/Repositories/PatientRepository.cs
| 4,189 |
C#
|
#region BSD License
/*
BSD License
Copyright (c) 2002, Randy Ridge, The CsGL Development Team
http://csgl.sourceforge.net/
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
1. Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
2. 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.
3. Neither the name of The CsGL Development Team 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 BSD License
#region Original Credits / License
/* Copyright (c) Mark J. Kilgard, 1994. */
/*
* (c) Copyright 1993, Silicon Graphics, Inc.
* ALL RIGHTS RESERVED
* Permission to use, copy, modify, and distribute this software for
* any purpose and without fee is hereby granted, provided that the above
* copyright notice appear in all copies and that both the copyright notice
* and this permission notice appear in supporting documentation, and that
* the name of Silicon Graphics, Inc. not be used in advertising
* or publicity pertaining to distribution of the software without specific,
* written prior permission.
*
* THE MATERIAL EMBODIED ON THIS SOFTWARE IS PROVIDED TO YOU "AS-IS"
* AND WITHOUT WARRANTY OF ANY KIND, EXPRESS, IMPLIED OR OTHERWISE,
* INCLUDING WITHOUT LIMITATION, ANY WARRANTY OF MERCHANTABILITY OR
* FITNESS FOR A PARTICULAR PURPOSE. IN NO EVENT SHALL SILICON
* GRAPHICS, INC. BE LIABLE TO YOU OR ANYONE ELSE FOR ANY DIRECT,
* SPECIAL, INCIDENTAL, INDIRECT OR CONSEQUENTIAL DAMAGES OF ANY
* KIND, OR ANY DAMAGES WHATSOEVER, INCLUDING WITHOUT LIMITATION,
* LOSS OF PROFIT, LOSS OF USE, SAVINGS OR REVENUE, OR THE CLAIMS OF
* THIRD PARTIES, WHETHER OR NOT SILICON GRAPHICS, INC. HAS BEEN
* ADVISED OF THE POSSIBILITY OF SUCH LOSS, HOWEVER CAUSED AND ON
* ANY THEORY OF LIABILITY, ARISING OUT OF OR IN CONNECTION WITH THE
* POSSESSION, USE OR PERFORMANCE OF THIS SOFTWARE.
*
* US Government Users Restricted Rights
* Use, duplication, or disclosure by the Government is subject to
* restrictions set forth in FAR 52.227.19(c)(2) or subparagraph
* (c)(1)(ii) of the Rights in Technical Data and Computer Software
* clause at DFARS 252.227-7013 and/or in similar or successor
* clauses in the FAR or the DOD or NASA FAR Supplement.
* Unpublished-- rights reserved under the copyright laws of the
* United States. Contractor/manufacturer is Silicon Graphics,
* Inc., 2011 N. Shoreline Blvd., Mountain View, CA 94039-7311.
*
* OpenGL(TM) is a trademark of Silicon Graphics, Inc.
*/
#endregion Original Credits / License
using CsGL.Basecode;
using System.Reflection;
#region AssemblyInfo
[assembly: AssemblyCompany("The CsGL Development Team (http://csgl.sourceforge.net)")]
[assembly: AssemblyCopyright("2002 The CsGL Development Team (http://csgl.sourceforge.net)")]
[assembly: AssemblyDescription("Redbook Scenebamb")]
[assembly: AssemblyProduct("Redbook Scenebamb")]
[assembly: AssemblyTitle("Redbook Scenebamb")]
[assembly: AssemblyVersion("1.0.0.0")]
#endregion AssemblyInfo
namespace RedbookExamples {
/// <summary>
/// Redbook Scenebamb -- Ambient Lighting (http://www.opengl.org/developers/code/examples/redbook/redbook.html)
/// Implemented In C# By The CsGL Development Team (http://csgl.sourceforge.net)
/// </summary>
public sealed class RedbookScenebamb : Model {
// --- Fields ---
#region Public Properties
/// <summary>
/// Example title.
/// </summary>
public override string Title {
get {
return "Redbook Scenebamb -- Ambient Lighting";
}
}
/// <summary>
/// Example description.
/// </summary>
public override string Description {
get {
return "This program demonstrates use of a blue ambient light source.";
}
}
/// <summary>
/// Example URL.
/// </summary>
public override string Url {
get {
return "http://www.opengl.org/developers/code/examples/redbook/redbook.html";
}
}
#endregion Public Properties
// --- Entry Point ---
#region Main()
/// <summary>
/// Application's entry point, runs this Redbook example.
/// </summary>
public static void Main() { // Entry Point
App.Run(new RedbookScenebamb()); // Run Our Example As A Windows Forms Application
}
#endregion Main()
// --- Basecode Methods ---
#region Initialize()
/// <summary>
/// Overrides OpenGL's initialization.
/// </summary>
public override void Initialize() {
// Initialize material property and light source
float[] light_ambient = {0.0f, 0.0f, 1.0f, 1.0f};
float[] light_diffuse = {1.0f, 1.0f, 1.0f, 1.0f};
float[] light_specular = {1.0f, 1.0f, 1.0f, 1.0f};
// light_position is NOT default value
float[] light_position = {1.0f, 1.0f, 1.0f, 0.0f};
glLightfv(GL_LIGHT0, GL_AMBIENT, light_ambient);
glLightfv(GL_LIGHT0, GL_DIFFUSE, light_diffuse);
glLightfv(GL_LIGHT0, GL_SPECULAR, light_specular);
glLightfv(GL_LIGHT0, GL_POSITION, light_position);
glEnable(GL_LIGHTING);
glEnable(GL_LIGHT0);
glDepthFunc(GL_LESS);
glEnable(GL_DEPTH_TEST);
}
#endregion Initialize()
#region Draw()
/// <summary>
/// Draws Redbook Scenebamb scene.
/// </summary>
public override void Draw() { // Here's Where We Do All The Drawing
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glPushMatrix();
glRotatef(20.0f, 1.0f, 0.0f, 0.0f);
glPushMatrix();
glTranslatef(-0.75f, 0.5f, 0.0f);
glRotatef(90.0f, 1.0f, 0.0f, 0.0f);
glutSolidTorus(0.275f, 0.85f, 15, 15);
glPopMatrix();
glPushMatrix();
glTranslatef(-0.75f, -0.5f, 0.0f);
glRotatef(270.0f, 1.0f, 0.0f, 0.0f);
glutSolidCone(1.0f, 2.0f, 15, 15);
glPopMatrix();
glPushMatrix();
glTranslatef(0.75f, 0.0f, -1.0f);
glutSolidSphere(1.0f, 15, 15);
glPopMatrix();
glPopMatrix();
glFlush();
}
#endregion Draw()
#region Reshape(int width, int height)
/// <summary>
/// Overrides OpenGL reshaping.
/// </summary>
/// <param name="width">New width.</param>
/// <param name="height">New height.</param>
public override void Reshape(int width, int height) { // Resize And Initialize The GL Window
glViewport(0, 0, width, height);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
if(width <= height) {
glOrtho(-2.5f, 2.5f, -2.5f * (float) height / (float) width, 2.5f * (float) height / (float) width, -10.0f, 10.0f);
}
else {
glOrtho(-2.5f * (float) width / (float) height, 2.5f * (float) width / (float) height, -2.5f, 2.5f, -10.0f, 10.0f);
}
glMatrixMode(GL_MODELVIEW);
}
#endregion Reshape(int width, int height)
}
}
| 36.85782 | 119 | 0.707856 |
[
"MIT"
] |
lvendrame/p-atack
|
Usings/CsGLExamples/src/RedbookExamples/src/RedbookScenebamb.cs
| 7,777 |
C#
|
using Avalonia;
using Avalonia.Controls;
using Avalonia.Markup.Xaml;
using Avalonia.Threading;
using System;
namespace roxy_tool.UserControls
{
public class DeviceControl : UserControl
{
ConfigOption flagsCheck;
ConfigOption svre9Left;
ConfigOption svre9Right;
byte[] mapping = new byte[5];
public EventHandler OnClosed;
public DeviceControl()
{
this.InitializeComponent();
}
private void InitializeComponent()
{
AvaloniaXamlLoader.Load(this);
flagsCheck = this.FindControl<ConfigOption>("flagsCheck");
svre9Left = this.FindControl<ConfigOption>("svre9Left");
svre9Right = this.FindControl<ConfigOption>("svre9Right");
var okButton = this.FindControl<Button>("okButton");
okButton.Click += OkButton_Click;
var cancelButton = this.FindControl<Button>("cancelButton");
cancelButton.Click += CancelButton_Click;
}
private void OkButton_Click(object sender, Avalonia.Interactivity.RoutedEventArgs e)
{
mapping = GetMapping();
Dispatcher.UIThread.InvokeAsync(new Action(() =>
{ this.Parent.IsVisible = false; }));
OnClosed?.Invoke(this, new EventArgs());
}
private void CancelButton_Click(object sender, Avalonia.Interactivity.RoutedEventArgs e)
{
SetMapping(mapping);
Dispatcher.UIThread.InvokeAsync(new Action(() =>
{ this.Parent.IsVisible = false; }));
OnClosed?.Invoke(this, new EventArgs());
}
public void SetMapping(byte[] map)
{
flagsCheck.SetCheck(BitConverter.ToUInt32(map, 0));
svre9Left.SetCombo(map[4] & 0xF);
svre9Right.SetCombo((map[4] >> 4) & 0xF);
Array.Copy(map, mapping, 5);
}
public byte[] GetMapping()
{
byte[] bytes = new byte[5];
var flags = flagsCheck.GetCheck();
Array.Copy(BitConverter.GetBytes(flags), bytes, 4);
bytes[4] = (byte)((svre9Left.GetCombo() & 0xF) | ((svre9Right.GetCombo() << 4) & 0xF0));
return bytes;
}
}
}
| 31.013699 | 100 | 0.586572 |
[
"BSD-2-Clause"
] |
veroxzik/roxy-tool
|
roxy-tool/UserControls/DeviceControl.axaml.cs
| 2,266 |
C#
|
// Copyright (c) MOSA Project. Licensed under the New BSD License.
// This code was generated by an automated template.
using Mosa.Compiler.Framework;
namespace Mosa.Platform.x64.Instructions
{
/// <summary>
/// BranchLessThan
/// </summary>
/// <seealso cref="Mosa.Platform.x64.X64Instruction" />
public sealed class BranchLessThan : X64Instruction
{
public override int ID { get { return 554; } }
internal BranchLessThan()
: base(0, 0)
{
}
public override string AlternativeName { get { return "JL"; } }
public override FlowControl FlowControl { get { return FlowControl.ConditionalBranch; } }
public override bool IsSignFlagUsed { get { return true; } }
public override bool IsOverflowFlagUsed { get { return true; } }
public override BaseInstruction GetOpposite()
{
return X64.BranchGreaterOrEqual;
}
public override void Emit(InstructionNode node, BaseCodeEmitter emitter)
{
System.Diagnostics.Debug.Assert(node.ResultCount == 0);
System.Diagnostics.Debug.Assert(node.OperandCount == 0);
emitter.OpcodeEncoder.AppendByte(0x0F);
emitter.OpcodeEncoder.AppendByte(0x8C);
emitter.OpcodeEncoder.EmitRelative32(node.BranchTargets[0].Label);
}
}
}
| 26.369565 | 91 | 0.728772 |
[
"BSD-3-Clause"
] |
kthompson/MOSA-Project
|
Source/Mosa.Platform.x64/Instructions/BranchLessThan.cs
| 1,213 |
C#
|
using System.Runtime.CompilerServices;
[assembly: InternalsVisibleTo("Resony.Server")]
| 29 | 47 | 0.827586 |
[
"MIT"
] |
ikebig/auralsys-audio
|
src/Resony.Server.Abstractions/AssemblyInfo.cs
| 87 |
C#
|
using System;
using System.Collections.Generic;
using System.Collections;
using System.Linq;
using System.Text;
using System.Diagnostics.Contracts;
namespace Exolutio.CodeContracts.Support
{
/// <summary>
/// OCL Bag implementation. Collection with unordered, not unique elements.
///
/// </summary>
public class OclBag : OclCollection
{
internal readonly Dictionary<OclAny, int> map;
#region Constructors
/// <summary>
/// Construct empty bag of the specified element type
/// </summary>
/// <param name="type"></param>
public OclBag(OclClassifier type):
base(type)
{
map = new Dictionary<OclAny, int>();
}
/// <summary>
/// Construct new bag with the specified element type and copy the contents of element dictionary.
/// </summary>
private OclBag(OclClassifier elementType, Dictionary<OclAny, int> elements):
base(elementType)
{
map = new Dictionary<OclAny, int>(elements);
}
/// <summary>
/// Construct a new bag containing elements from the specified collection
/// </summary>
/// <param name="type">Element type</param>
/// <param name="elements">Collection of values</param>
public OclBag(OclClassifier type, IEnumerable<OclAny> elements):
base(type)
{
map = new Dictionary<OclAny, int>();
AddRange(elements);
}
public OclBag(OclClassifier type, params OclAny[] elements):
this(type, (IEnumerable<OclAny>)elements)
{
}
public OclBag(OclClassifier type, params OclCollectionLiteralPart[] items):
base(type)
{
this.map = new Dictionary<OclAny, int>();
foreach(OclCollectionLiteralPart item in items)
AddRange(item);
}
#endregion
#region Equality
public override bool Equals(object obj)
{
if (!(obj is OclBag))
return false;
OclBag bag = (OclBag)obj;
foreach (KeyValuePair<OclAny,int> t in map)
{
int i;
if (!bag.map.TryGetValue(t.Key, out i) || i != t.Value)
return false;
}
foreach (KeyValuePair<OclAny, int> t in bag.map)
{
int i;
if (!map.TryGetValue(t.Key, out i) || i != t.Value)
return false;
}
return true;
}
public override int GetHashCode()
{
unchecked
{
int hash = 21;
foreach (KeyValuePair<OclAny, int> pair in map)
{
OclAny item = pair.Key;
hash += pair.Value * (IsNull(item) ? 0 : item.GetHashCode());
}
return hash;
}
}
#endregion
#region IEnumerable<OclAny> implementation
[Pure]
public override IEnumerator<OclAny> GetEnumerator()
{
foreach (KeyValuePair<OclAny, int> kv in map)
{
for (int i = 0; i < kv.Value; ++i)
yield return kv.Key;
}
}
#endregion
#region Helper methods
private int Count
{
get { return map.Sum(kv => kv.Value); }
}
private void AddRange(IEnumerable<OclAny> c)
{
foreach (OclAny t in c)
Add(t);
}
private void Add(OclAny item)
{
int count;
map.TryGetValue(item, out count);
map[item] = count + 1;
}
private void Clear()
{
map.Clear();
}
[Pure]
private bool Contains(OclAny item)
{
return map.ContainsKey(item);
}
#endregion
#region OCL Operations from Collection
/// <summary>
/// Count elements.
/// </summary>
/// <returns>Number of elements.</returns>
public override OclInteger size()
{
int sum = 0;
foreach (KeyValuePair<OclAny, int> kv in map)
{
sum += kv.Value;
}
return (OclInteger)sum;
}
public override OclBoolean includes<T>(T obj)
{
return (OclBoolean)map.ContainsKey(obj);
}
public override OclBoolean excludes<T>(T obj)
{
return (OclBoolean)!map.ContainsKey(obj);
}
public override OclInteger count<T>(T obj)
{
int cnt;
if (map.TryGetValue(obj, out cnt))
return (OclInteger)cnt;
return (OclInteger)0;
}
public override OclBoolean isEmpty()
{
return (OclBoolean)(map.Count == 0);
}
public override OclBoolean notEmpty()
{
return (OclBoolean)(map.Count != 0);
}
public override OclBag asBag()
{
return this;
}
public override OclCollection flatten()
{
return flattenToBag();
}
#endregion
#region OCL Operations
[Pure]
public OclBag union(OclClassifier newElementType, OclBag bag)
{
if (IsNull(bag))
throw new ArgumentNullException();
OclBag bg = new OclBag(newElementType, map);
bg.AddRange(bag);
return bg;
}
[Pure]
public OclBag union(OclClassifier newElementType,OclSet set)
{
if (IsNull(set))
throw new ArgumentNullException();
OclBag bg = new OclBag(newElementType, map);
bg.AddRange(set);
return bg;
}
/// <summary>
/// Intersect with another bag. The result contains elements that are in both bags and the count is minimum of counts in the bags.
/// </summary>
/// <param name="bag">The bag to intersect with</param>
/// <returns>Bag intersection</returns>
[Pure]
public OclBag intersection(OclBag bag)
{
if (IsNull(bag))
throw new ArgumentNullException();
OclBag bg = new OclBag(elementType);
foreach (KeyValuePair<OclAny, int> pair in map)
{
int count;
if (bag.map.TryGetValue(pair.Key, out count))
bg.map.Add(pair.Key, Math.Min(count, pair.Value));
}
return bg;
}
/// <summary>
/// Intersect with a set. The result contains elements that are in both bags and the count is minimum of counts in the bags.
/// </summary>
/// <param name="bag">The set to intersect with</param>
/// <returns>Set intersection</returns>
[Pure]
public OclSet intersection(OclSet set)
{
if (IsNull(set))
throw new ArgumentNullException();
//Use Set implementation
return set.intersection(this);
}
[Pure]
public OclBag including<T>(OclClassifier newElementType, T item) where T : OclAny
{
OclBag bg = new OclBag(newElementType, map);
bg.Add(item);
return bg;
}
[Pure]
public OclBag excluding<T>(OclClassifier newElementType, T item) where T : OclAny
{
OclBag bg = new OclBag(newElementType, map);
bg.map.Remove(item);
return bg;
}
[Pure]
public OclBag flattenToBag()
{
List<OclAny> list = new List<OclAny>();
FlattenToList(list, OclCollectionType.Depth(elementType));
return new OclBag(OclCollectionType.BasicElementType(elementType), list);
}
#endregion
#region OCL Iterations from Collection
public override OclCollection closure<T>(OclClassifier newElementType, Func<T, OclAny> body)
{
return closureToSet(newElementType, body);
}
[Pure]
public OclSet closureToSet<T>(OclClassifier newElementType, Func<T, OclAny> body) where T : OclAny
{
return ClosureToSet<T>(newElementType, body);
}
public override OclCollection collect<T>(OclClassifier newElementType, Func<T, OclAny> f)
{
return collectToBag<T>(newElementType, f);
}
[Pure]
public OclBag collectToBag<T>(OclClassifier newElementType, Func<T, OclAny> f)
where T : OclAny
{
return collectNested(newElementType, f).flattenToBag();
}
#endregion
#region OCL iterations
[Pure]
public OclSequence sortedBy<T, K>(Func<T, K> f) where T: OclAny where K: OclAny
{
return new OclSequence(elementType, this.OrderBy(x => f((T)x)));
}
[Pure]
public OclBag collectNested<T, K>(OclClassifier newElementType, Func<T, K> f)
where T : OclAny
where K : OclAny
{
return new OclBag(newElementType, this.Select(x => f((T)x)));
}
[Pure]
public OclBag select<T>(Func<T, OclBoolean> predicate) where T: OclAny
{
return new OclBag(elementType, this.Where(x => (bool)predicate((T)x)));
}
[Pure]
public OclBag reject<T>(Func<T, OclBoolean> f) where T : OclAny
{
return new OclBag(elementType, this.Where(item => !(bool)f((T)item)));
}
#endregion
#region OCL Type
public override OclClassifier oclType()
{
return OclCollectionType.Collection(OclCollectionKind.Bag, elementType);
}
#endregion
}
}
| 30.750742 | 139 | 0.503619 |
[
"BSD-2-Clause"
] |
mff-uk/exolutio
|
CodeContractsSupport/OclBag.cs
| 10,365 |
C#
|
// *****************************************************************************
// BSD 3-Clause License (https://github.com/ComponentFactory/Krypton/blob/master/LICENSE)
// © Component Factory Pty Ltd, 2006 - 2016, All rights reserved.
// The software and associated documentation supplied hereunder are the
// proprietary information of Component Factory Pty Ltd, 13 Swallows Close,
// Mornington, Vic 3931, Australia and are supplied subject to license terms.
//
// Modifications by Peter Wagner(aka Wagnerp) & Simon Coghlan(aka Smurf-IV) 2017 - 2020. All rights reserved. (https://github.com/Wagnerp/Krypton-NET-5.451)
// Version 5.451.0.0 www.ComponentFactory.com
// *****************************************************************************
using System;
using System.Drawing;
using System.ComponentModel;
using System.Windows.Forms;
using System.Diagnostics;
using ComponentFactory.Krypton.Toolkit;
namespace ComponentFactory.Krypton.Ribbon
{
/// <summary>
/// Draws a ribbon group textbox.
/// </summary>
internal class ViewDrawRibbonGroupTextBox : ViewComposite,
IRibbonViewGroupItemView
{
#region Static Fields
private const int NULL_CONTROL_WIDTH = 50;
#endregion
#region Instance Fields
private readonly KryptonRibbon _ribbon;
private ViewDrawRibbonGroup _activeGroup;
private readonly TextBoxController _controller;
private readonly NeedPaintHandler _needPaint;
private GroupItemSize _currentSize;
#endregion
#region Identity
/// <summary>
/// Initialize a new instance of the ViewDrawRibbonGroupTextBox class.
/// </summary>
/// <param name="ribbon">Reference to owning ribbon control.</param>
/// <param name="ribbonTextBox">Reference to source textbox.</param>
/// <param name="needPaint">Delegate for notifying paint requests.</param>
public ViewDrawRibbonGroupTextBox(KryptonRibbon ribbon,
KryptonRibbonGroupTextBox ribbonTextBox,
NeedPaintHandler needPaint)
{
Debug.Assert(ribbon != null);
Debug.Assert(ribbonTextBox != null);
Debug.Assert(needPaint != null);
// Remember incoming references
_ribbon = ribbon;
GroupTextBox = ribbonTextBox;
_needPaint = needPaint;
_currentSize = GroupTextBox.ItemSizeCurrent;
// Hook into the textbox events
GroupTextBox.MouseEnterControl += OnMouseEnterControl;
GroupTextBox.MouseLeaveControl += OnMouseLeaveControl;
// Associate this view with the source component (required for design time selection)
Component = GroupTextBox;
if (_ribbon.InDesignMode)
{
// At design time we need to know when the user right clicks the textbox
ContextClickController controller = new ContextClickController();
controller.ContextClick += OnContextClick;
MouseController = controller;
}
// Create controller needed for handling focus and key tip actions
_controller = new TextBoxController(_ribbon, GroupTextBox, this);
SourceController = _controller;
KeyController = _controller;
// We need to rest visibility of the textbox for each layout cycle
_ribbon.ViewRibbonManager.LayoutBefore += OnLayoutAction;
_ribbon.ViewRibbonManager.LayoutAfter += OnLayoutAction;
// Define back reference to view for the text box definition
GroupTextBox.TextBoxView = this;
// Give paint delegate to textbox so its palette changes are redrawn
GroupTextBox.ViewPaintDelegate = needPaint;
// Hook into changes in the ribbon custom definition
GroupTextBox.PropertyChanged += OnTextBoxPropertyChanged;
}
/// <summary>
/// Obtains the String representation of this instance.
/// </summary>
/// <returns>User readable name of the instance.</returns>
public override string ToString()
{
// Return the class name and instance identifier
return "ViewDrawRibbonGroupTextBox:" + Id;
}
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing)
{
if (GroupTextBox != null)
{
// Must unhook to prevent memory leaks
GroupTextBox.MouseEnterControl -= OnMouseEnterControl;
GroupTextBox.MouseLeaveControl -= OnMouseLeaveControl;
GroupTextBox.ViewPaintDelegate = null;
GroupTextBox.PropertyChanged -= OnTextBoxPropertyChanged;
_ribbon.ViewRibbonManager.LayoutAfter -= OnLayoutAction;
_ribbon.ViewRibbonManager.LayoutBefore -= OnLayoutAction;
// Remove association with definition
GroupTextBox.TextBoxView = null;
GroupTextBox = null;
}
}
base.Dispose(disposing);
}
#endregion
#region GroupTextBox
/// <summary>
/// Gets access to the owning group textbox instance.
/// </summary>
public KryptonRibbonGroupTextBox GroupTextBox { get; private set; }
#endregion
#region LostFocus
/// <summary>
/// Source control has lost the focus.
/// </summary>
/// <param name="c">Reference to the source control instance.</param>
public override void LostFocus(Control c)
{
// Ask ribbon to shift focus to the hidden control
_ribbon.HideFocus(GroupTextBox.TextBox);
base.LostFocus(c);
}
#endregion
#region GetFirstFocusItem
/// <summary>
/// Gets the first focus item from the container.
/// </summary>
/// <returns>ViewBase of item; otherwise false.</returns>
public ViewBase GetFirstFocusItem()
{
if ((GroupTextBox.Visible) && (GroupTextBox.LastTextBox?.TextBox != null) && (GroupTextBox.LastTextBox.TextBox.CanSelect))
{
return this;
}
else
{
return null;
}
}
#endregion
#region GetLastFocusItem
/// <summary>
/// Gets the last focus item from the item.
/// </summary>
/// <returns>ViewBase of item; otherwise false.</returns>
public ViewBase GetLastFocusItem()
{
if ((GroupTextBox.Visible) && (GroupTextBox.LastTextBox?.TextBox != null) && (GroupTextBox.LastTextBox.TextBox.CanSelect))
{
return this;
}
else
{
return null;
}
}
#endregion
#region GetNextFocusItem
/// <summary>
/// Gets the next focus item based on the current item as provided.
/// </summary>
/// <param name="current">The view that is currently focused.</param>
/// <param name="matched">Has the current focus item been matched yet.</param>
/// <returns>ViewBase of item; otherwise false.</returns>
public ViewBase GetNextFocusItem(ViewBase current, ref bool matched)
{
// Do we match the current item?
matched = (current == this);
return null;
}
#endregion
#region GetPreviousFocusItem
/// <summary>
/// Gets the previous focus item based on the current item as provided.
/// </summary>
/// <param name="current">The view that is currently focused.</param>
/// <param name="matched">Has the current focus item been matched yet.</param>
/// <returns>ViewBase of item; otherwise false.</returns>
public ViewBase GetPreviousFocusItem(ViewBase current, ref bool matched)
{
// Do we match the current item?
matched = (current == this);
return null;
}
#endregion
#region GetGroupKeyTips
/// <summary>
/// Gets the array of group level key tips.
/// </summary>
/// <param name="keyTipList">List to add new entries into.</param>
/// <param name="lineHint">Provide hint to item about its location.</param>
public void GetGroupKeyTips(KeyTipInfoList keyTipList, int lineHint)
{
// Only provide a key tip if we are visible and the target control can accept focus
if (Visible && LastTextBox.CanFocus)
{
// Get the screen location of the button
Rectangle viewRect = _ribbon.KeyTipToScreen(this);
// Determine the screen position of the key tip
Point screenPt = Point.Empty;
// Determine the screen position of the key tip dependant on item location/size
switch (_currentSize)
{
case GroupItemSize.Large:
screenPt = new Point(viewRect.Left + (viewRect.Width / 2), viewRect.Bottom);
break;
case GroupItemSize.Medium:
case GroupItemSize.Small:
screenPt = _ribbon.CalculatedValues.KeyTipRectToPoint(viewRect, lineHint);
break;
}
keyTipList.Add(new KeyTipInfo(GroupTextBox.Enabled,
GroupTextBox.KeyTip,
screenPt,
ClientRectangle,
_controller));
}
}
#endregion
#region Layout
/// <summary>
/// Override the group item size if possible.
/// </summary>
/// <param name="size">New size to use.</param>
public void SetGroupItemSize(GroupItemSize size)
{
_currentSize = size;
}
/// <summary>
/// Reset the group item size to the item definition.
/// </summary>
public void ResetGroupItemSize()
{
_currentSize = GroupTextBox.ItemSizeCurrent;
}
/// <summary>
/// Discover the preferred size of the element.
/// </summary>
/// <param name="context">Layout context.</param>
public override Size GetPreferredSize(ViewLayoutContext context)
{
Size preferredSize = Size.Empty;
// Ensure the control has the correct parent
UpdateParent(context.Control);
// If there is a textbox associated then ask for its requested size
if (LastTextBox != null)
{
if (ActualVisible(LastTextBox))
{
preferredSize = LastTextBox.GetPreferredSize(context.DisplayRectangle.Size);
// Add two pixels, one for the left and right edges that will be padded
preferredSize.Width += 2;
}
}
else
{
preferredSize.Width = NULL_CONTROL_WIDTH;
}
preferredSize.Height = _currentSize == GroupItemSize.Large
? _ribbon.CalculatedValues.GroupTripleHeight
: _ribbon.CalculatedValues.GroupLineHeight;
return preferredSize;
}
/// <summary>
/// Perform a layout of the elements.
/// </summary>
/// <param name="context">Layout context.</param>
public override void Layout(ViewLayoutContext context)
{
Debug.Assert(context != null);
// We take on all the available display area
ClientRectangle = context.DisplayRectangle;
// Are we allowed to change the layout of controls?
if (!context.ViewManager.DoNotLayoutControls)
{
// If we have an actual control, position it with a pixel padding all around
LastTextBox?.SetBounds(ClientLocation.X + 1,
ClientLocation.Y + 1,
ClientWidth - 2,
ClientHeight - 2);
}
// Let child elements layout in given space
base.Layout(context);
}
#endregion
#region Paint
/// <summary>
/// Perform a render of the elements.
/// </summary>
/// <param name="context">Rendering context.</param>
public override void Render(RenderContext context)
{
Debug.Assert(context != null);
// If we do not have a textbox
if (GroupTextBox.TextBox == null)
{
// And we are in design time
if (_ribbon.InDesignMode)
{
// Draw rectangle is 1 pixel less per edge
Rectangle drawRect = ClientRectangle;
drawRect.Inflate(-1, -1);
drawRect.Height--;
// Draw an indication of where the textbox will be
context.Graphics.FillRectangle(Brushes.Goldenrod, drawRect);
context.Graphics.DrawRectangle(Pens.Gold, drawRect);
}
}
}
#endregion
#region Protected
/// <summary>
/// Raises the NeedPaint event.
/// </summary>
/// <param name="needLayout">Does the palette change require a layout.</param>
protected virtual void OnNeedPaint(bool needLayout)
{
OnNeedPaint(needLayout, Rectangle.Empty);
}
/// <summary>
/// Raises the NeedPaint event.
/// </summary>
/// <param name="needLayout">Does the palette change require a layout.</param>
/// <param name="invalidRect">Rectangle to invalidate.</param>
protected virtual void OnNeedPaint(bool needLayout, Rectangle invalidRect)
{
if (_needPaint != null)
{
_needPaint(this, new NeedLayoutEventArgs(needLayout));
if (needLayout)
{
_ribbon.PerformLayout();
}
}
}
#endregion
#region Implementation
private void OnContextClick(object sender, MouseEventArgs e)
{
GroupTextBox.OnDesignTimeContextMenu(e);
}
private void OnTextBoxPropertyChanged(object sender, PropertyChangedEventArgs e)
{
bool updateLayout = false;
const bool UPDATE_PAINT = false;
switch (e.PropertyName)
{
case "Enabled":
UpdateEnabled(LastTextBox);
break;
case "Visible":
UpdateVisible(LastTextBox);
updateLayout = true;
break;
case "CustomControl":
updateLayout = true;
break;
}
if (updateLayout)
{
// If we are on the currently selected tab then...
if ((GroupTextBox.RibbonTab != null) &&
(_ribbon.SelectedTab == GroupTextBox.RibbonTab))
{
// ...layout so the visible change is made
OnNeedPaint(true);
}
}
if (UPDATE_PAINT)
#pragma warning disable 162
{
// If this button is actually defined as visible...
if (GroupTextBox.Visible || _ribbon.InDesignMode)
{
// ...and on the currently selected tab then...
if ((GroupTextBox.RibbonTab != null) &&
(_ribbon.SelectedTab == GroupTextBox.RibbonTab))
{
// ...repaint it right now
OnNeedPaint(false, ClientRectangle);
}
}
}
#pragma warning restore 162
}
private Control LastParentControl
{
get => GroupTextBox.LastParentControl;
set => GroupTextBox.LastParentControl = value;
}
private KryptonTextBox LastTextBox
{
get => GroupTextBox.LastTextBox;
set => GroupTextBox.LastTextBox = value;
}
private void UpdateParent(Control parentControl)
{
// Is there a change in the textbox or a change in
// the parent control that is hosting the control...
if ((parentControl != LastParentControl) ||
(LastTextBox != GroupTextBox.TextBox))
{
// We only modify the parent and visible state if processing for correct container
if ((GroupTextBox.RibbonContainer.RibbonGroup.ShowingAsPopup && (parentControl is VisualPopupGroup)) ||
(!GroupTextBox.RibbonContainer.RibbonGroup.ShowingAsPopup && !(parentControl is VisualPopupGroup)))
{
// If we have added the custrom control to a parent before
if ((LastTextBox != null) && (LastParentControl != null))
{
// If that control is still a child of the old parent
if (LastParentControl.Controls.Contains(LastTextBox))
{
// Check for a collection that is based on the read only class
LastParentControl.Controls.Remove(LastTextBox);
}
}
// Remember the current control and new parent
LastTextBox = GroupTextBox.TextBox;
LastParentControl = parentControl;
// If we have a new textbox and parent
if ((LastTextBox != null) && (LastParentControl != null))
{
// Ensure the control is not in the display area when first added
LastTextBox.Location = new Point(-LastTextBox.Width, -LastTextBox.Height);
// Check for the correct visible state of the textbox
UpdateVisible(LastTextBox);
// Check for a collection that is based on the read only class
LastParentControl.Controls.Add(LastTextBox);
}
}
}
}
private void UpdateEnabled(Control c)
{
if (c != null)
{
// Start with the enabled state of the group element
bool enabled = GroupTextBox.Enabled;
// If we have an associated designer setup...
if (!_ribbon.InDesignHelperMode && (GroupTextBox.TextBoxDesigner != null))
{
// And we are not using the design helpers, then use the design specified value
enabled = GroupTextBox.TextBoxDesigner.DesignEnabled;
}
c.Enabled = enabled;
}
}
private bool ActualVisible(Control c)
{
if (c != null)
{
// Start with the visible state of the group element
bool visible = GroupTextBox.Visible;
// If we have an associated designer setup...
if (!_ribbon.InDesignHelperMode && (GroupTextBox.TextBoxDesigner != null))
{
// And we are not using the design helpers, then use the design specified value
visible = GroupTextBox.TextBoxDesigner.DesignVisible;
}
return visible;
}
return false;
}
private void UpdateVisible(Control c)
{
if (c != null)
{
// Start with the visible state of the group element
bool visible = GroupTextBox.Visible;
// If we have an associated designer setup...
if (!_ribbon.InDesignHelperMode && (GroupTextBox.TextBoxDesigner != null))
{
// And we are not using the design helpers, then use the design specified value
visible = GroupTextBox.TextBoxDesigner.DesignVisible;
}
if (visible)
{
// Only visible if on the currently selected page
if ((GroupTextBox.RibbonTab == null) ||
(_ribbon.SelectedTab != GroupTextBox.RibbonTab))
{
visible = false;
}
else
{
// Check the owning group is visible
if ((GroupTextBox.RibbonContainer?.RibbonGroup != null)
&& !GroupTextBox.RibbonContainer.RibbonGroup.Visible
&& !_ribbon.InDesignMode
)
{
visible = false;
}
else
{
// Check that the group is not collapsed
if ((GroupTextBox.RibbonContainer.RibbonGroup.IsCollapsed) &&
((_ribbon.GetControllerControl(GroupTextBox.TextBox) is KryptonRibbon) ||
(_ribbon.GetControllerControl(GroupTextBox.TextBox) is VisualPopupMinimized))
)
{
visible = false;
}
else
{
// Check that the hierarchy of containers are all visible
KryptonRibbonGroupContainer container = GroupTextBox.RibbonContainer;
// Keep going until we have searched the entire parent chain of containers
while (container != null)
{
// If any parent container is not visible, then we are not visible
if (!container.Visible)
{
visible = false;
break;
}
// Move up a level
container = container.RibbonContainer;
}
}
}
}
}
c.Visible = visible;
}
}
private void OnLayoutAction(object sender, EventArgs e)
{
// If not disposed then we still have a element reference
if (GroupTextBox != null)
{
// Change in selected tab requires a retest of the control visibility
UpdateVisible(LastTextBox);
}
}
private void OnMouseEnterControl(object sender, EventArgs e)
{
// Reset the active group setting
_activeGroup = null;
// Find the parent group instance
ViewBase parent = Parent;
// Keep going till we get to the top or find a group
while (parent != null)
{
if (parent is ViewDrawRibbonGroup ribGroup)
{
_activeGroup = ribGroup;
break;
}
// Move up a level
parent = parent.Parent;
}
// If we found a group we are inside
if (_activeGroup != null)
{
_activeGroup.Tracking = true;
_needPaint(this, new NeedLayoutEventArgs(false, _activeGroup.ClientRectangle));
}
}
private void OnMouseLeaveControl(object sender, EventArgs e)
{
// If we have a cached group we made active
if (_activeGroup != null)
{
_activeGroup.Tracking = false;
_needPaint(this, new NeedLayoutEventArgs(false, _activeGroup.ClientRectangle));
_activeGroup = null;
}
}
#endregion
}
}
| 38.055976 | 157 | 0.515842 |
[
"BSD-3-Clause"
] |
Krypton-Suite-Legacy/Krypton-NET-5.451
|
Source/Krypton Components/ComponentFactory.Krypton.Ribbon/View Draw/ViewDrawRibbonGroupTextBox.cs
| 25,158 |
C#
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using mtgdm.Data;
namespace mtgdm.Pages.Admin.User
{
[Authorize(Roles = "Admin")]
public class DeleteModel : PageModel
{
private readonly ApplicationDbContext _context;
private readonly IConfiguration _config;
private readonly UserManager<IdentityUser> _userManager;
private readonly RoleManager<IdentityRole> _roleManager;
public DeleteModel(ApplicationDbContext context,
IConfiguration config,
UserManager<IdentityUser> userManager,
RoleManager<IdentityRole> roleManager)
{
_context = context;
_config = config;
_userManager = userManager;
_roleManager = roleManager;
}
[BindProperty(SupportsGet = true)]
public string UserID { get; set; }
[BindProperty]
public IdentityUser UserDelete { get; set; }
public async Task<IActionResult> OnGetAsync()
{
if (string.IsNullOrEmpty(UserID) || !Guid.TryParse(UserID, out Guid userID))
{
return new RedirectToPageResult("/Admin/User/List");
}
UserDelete = await _userManager.FindByIdAsync(UserID);
return Page();
}
public async Task<IActionResult> OnPostAsync()
{
if (string.IsNullOrEmpty(UserID) || !Guid.TryParse(UserID, out Guid userID))
{
return new RedirectToPageResult("/Admin/User/List");
}
var user = await _userManager.FindByIdAsync(UserDelete.Id);
var userRoles = await _userManager.GetRolesAsync(user);
var remove = await _userManager.RemoveFromRolesAsync(user, userRoles);
//Remove showpieces
var ratings = await _context.ShowpieceRating.Where(w => w.UserID == userID).ToListAsync();
var comments = await _context.Comment.Where(w => w.UserID == userID).ToListAsync();
_context.ShowpieceRating.RemoveRange(ratings);
_context.Comment.RemoveRange(comments);
await _userManager.DeleteAsync(user);
await _context.SaveChangesAsync();
return new RedirectToPageResult("/Admin/User/List");
}
}
}
| 35.337838 | 102 | 0.637476 |
[
"MIT"
] |
ZombieFleshEaters/mtgdm
|
mtgdm/Pages/Admin/User/Delete.cshtml.cs
| 2,615 |
C#
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml.Linq;
namespace InnovatorAdmin.Documentation
{
public class List : IElement
{
public ListType Type { get; set; }
public ListItem Header { get; set; }
public List<ListItem> Children { get; } = new List<ListItem>();
internal static List Parse(XElement element)
{
var result = new List();
if (Enum.TryParse<ListType>((string)element.Attribute("type") ?? "bullet", true, out var listType))
result.Type = listType;
var header = element.Element("listheader");
if (header != null)
result.Header = ListItem.Parse(header);
result.Children.AddRange(element.Elements("item").Select(ListItem.Parse));
return result;
}
public T Visit<T>(IElementVisitor<T> visitor)
{
return visitor.Visit(this);
}
}
}
| 26.457143 | 105 | 0.665227 |
[
"MIT"
] |
GCAE/InnovatorAdmin
|
InnovatorAdmin.Api/Documentation/List.cs
| 928 |
C#
|
// <auto-generated />
using System;
using Core;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Metadata;
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
namespace Core.Migrations
{
[DbContext(typeof(AppDbContext))]
partial class AppDbContextModelSnapshot : ModelSnapshot
{
protected override void BuildModel(ModelBuilder modelBuilder)
{
#pragma warning disable 612, 618
modelBuilder
.HasAnnotation("ProductVersion", "2.1.2-rtm-30932")
.HasAnnotation("Relational:MaxIdentifierLength", 128)
.HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn);
modelBuilder.Entity("Core.DynamicForm.FormAttribute", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn);
b.Property<int>("ControlType");
b.Property<int>("DisplayOrder");
b.Property<string>("Name");
b.Property<bool>("Required");
b.Property<int>("TenantId");
b.HasKey("Id");
b.HasIndex("TenantId");
b.ToTable("FormAttributes");
});
modelBuilder.Entity("Core.DynamicForm.FormAttributeValue", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn);
b.Property<int>("DisplayOrder");
b.Property<int?>("FormAttributeId");
b.Property<string>("Name");
b.HasKey("Id");
b.HasIndex("FormAttributeId");
b.ToTable("FormAttributeValues");
});
modelBuilder.Entity("Core.DynamicForm.GenericAttribute", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn);
b.Property<int>("EntityId");
b.Property<int?>("FormAttributeId");
b.Property<string>("Value");
b.HasKey("Id");
b.HasIndex("FormAttributeId");
b.ToTable("GenericAttributes");
});
modelBuilder.Entity("Core.DynamicForm.Order", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn);
b.Property<DateTime>("InsertTime");
b.Property<int>("TenantId");
b.HasKey("Id");
b.HasIndex("TenantId");
b.ToTable("Orders");
});
modelBuilder.Entity("Core.MultiTenant.Tenant", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn);
b.Property<string>("Name");
b.HasKey("Id");
b.ToTable("Tenants");
});
modelBuilder.Entity("Core.DynamicForm.FormAttribute", b =>
{
b.HasOne("Core.MultiTenant.Tenant", "Tenant")
.WithMany()
.HasForeignKey("TenantId")
.OnDelete(DeleteBehavior.Cascade);
});
modelBuilder.Entity("Core.DynamicForm.FormAttributeValue", b =>
{
b.HasOne("Core.DynamicForm.FormAttribute", "FormAttribute")
.WithMany("FormAttributeValues")
.HasForeignKey("FormAttributeId");
});
modelBuilder.Entity("Core.DynamicForm.GenericAttribute", b =>
{
b.HasOne("Core.DynamicForm.FormAttribute", "FormAttribute")
.WithMany()
.HasForeignKey("FormAttributeId");
});
modelBuilder.Entity("Core.DynamicForm.Order", b =>
{
b.HasOne("Core.MultiTenant.Tenant", "Tenant")
.WithMany()
.HasForeignKey("TenantId")
.OnDelete(DeleteBehavior.Cascade);
});
#pragma warning restore 612, 618
}
}
}
| 35.445205 | 126 | 0.49256 |
[
"MIT"
] |
github-123456/DynamicForm
|
src/Core/Migrations/AppDbContextModelSnapshot.cs
| 5,177 |
C#
|
using System;
using NetRuntimeSystem = System;
using System.ComponentModel;
using NetOffice.Attributes;
namespace NetOffice.AccessApi
{
#region Delegates
#pragma warning disable
public delegate void SubReport_EnterEventHandler();
public delegate void SubReport_ExitEventHandler(ref Int16 cancel);
#pragma warning restore
#endregion
/// <summary>
/// CoClass SubReport
/// SupportByVersion Access, 9,10,11,12,14,15,16
/// </summary>
[SupportByVersion("Access", 9,10,11,12,14,15,16)]
[EntityType(EntityType.IsCoClass)]
[ComEventContract(typeof(EventContracts._SubReportEvents), typeof(EventContracts.DispSubReportEvents))]
[TypeId("3B06E965-E47C-11CD-8701-00AA003F0F07")]
public interface SubReport : _SubReport, IEventBinding
{
#region Events
/// <summary>
/// SupportByVersion Access 9 10 11 12 14 15,16
/// </summary>
[SupportByVersion("Access", 9,10,11,12,14,15,16)]
event SubReport_EnterEventHandler EnterEvent;
/// <summary>
/// SupportByVersion Access 9 10 11 12 14 15,16
/// </summary>
[SupportByVersion("Access", 9,10,11,12,14,15,16)]
event SubReport_ExitEventHandler ExitEvent;
#endregion
}
}
| 26.295455 | 107 | 0.740709 |
[
"MIT"
] |
igoreksiz/NetOffice
|
Source/Access/Classes/SubReport.cs
| 1,159 |
C#
|
#Tue Nov 30 21:55:21 EST 2021
lib/com.ibm.ws.cdi.web_1.0.59.jar=2a3b1d88da836f2e16f16ed66e39ec63
dev/api/spec/com.ibm.websphere.javaee.jsp.2.3_1.0.59.jar=1986d83a3a75ecc98c30d075e80e25bd
lib/com.ibm.ws.cdi.1.2.web_1.0.59.jar=57b210267d5ef6abc7d552b58d15b96e
lib/features/com.ibm.websphere.appserver.cdi1.2-servlet3.1.mf=f33ff482f26fd824a510b897b95f2e45
| 58.833333 | 94 | 0.838527 |
[
"MIT"
] |
johnojacob99/CSC480-21F
|
frontend/target/liberty/wlp/lib/features/checksums/com.ibm.websphere.appserver.cdi1.2-servlet3.1.cs
| 353 |
C#
|
using Cemig.Gecipa.CoreBusiness.Domain.Models.ReuniaoAggregate;
using MediatR;
using System;
namespace Cemig.Gecipa.CoreBusiness.Domain.Commands.ReuniaoCommands
{
public class AtualizarAtaDeReuniaoCommand : IRequest
{
public Reuniao Reuniao { get; set; }
public Guid AtaId { get; set; }
public string Local { get; set; }
public DateTime Inicio { get; set; }
public DateTime Termino { get; set; }
}
}
| 30.2 | 67 | 0.684327 |
[
"MIT"
] |
tonihenriques/cemig-gecipa
|
src/Cemig.Gecipa.CoreBusiness.Domain/Commands/ReuniaoCommands/AtualizarAtaDeReuniaoCommand.cs
| 455 |
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.Gcp.AccessContextManager.Outputs
{
[OutputType]
public sealed class ServicePerimetersServicePerimeterStatusEgressPolicyEgressTo
{
/// <summary>
/// A list of `ApiOperations` that this egress rule applies to. A request matches
/// if it contains an operation/service in this list.
/// Structure is documented below.
/// </summary>
public readonly ImmutableArray<Outputs.ServicePerimetersServicePerimeterStatusEgressPolicyEgressToOperation> Operations;
/// <summary>
/// A list of resources, currently only projects in the form
/// `projects/<projectnumber>`, that match this to stanza. A request matches
/// if it contains a resource in this list. If * is specified for resources,
/// then this `EgressTo` rule will authorize access to all resources outside
/// the perimeter.
/// </summary>
public readonly ImmutableArray<string> Resources;
[OutputConstructor]
private ServicePerimetersServicePerimeterStatusEgressPolicyEgressTo(
ImmutableArray<Outputs.ServicePerimetersServicePerimeterStatusEgressPolicyEgressToOperation> operations,
ImmutableArray<string> resources)
{
Operations = operations;
Resources = resources;
}
}
}
| 39.857143 | 128 | 0.695341 |
[
"ECL-2.0",
"Apache-2.0"
] |
la3mmchen/pulumi-gcp
|
sdk/dotnet/AccessContextManager/Outputs/ServicePerimetersServicePerimeterStatusEgressPolicyEgressTo.cs
| 1,674 |
C#
|
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System.Collections.Immutable;
using System.Composition;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.CodeActions;
using Microsoft.CodeAnalysis.CodeFixes;
using Microsoft.CodeAnalysis.CodeFixes.GenerateMember;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.GenerateMember.GenerateVariable;
using Microsoft.CodeAnalysis.Shared.Extensions;
namespace Microsoft.CodeAnalysis.CSharp.GenerateVariable
{
[ExportCodeFixProvider(LanguageNames.CSharp, Name = PredefinedCodeFixProviderNames.GenerateVariable), Shared]
[ExtensionOrder(After = PredefinedCodeFixProviderNames.GenerateMethod)]
internal class CSharpGenerateVariableCodeFixProvider : AbstractGenerateMemberCodeFixProvider
{
private const string CS1061 = nameof(CS1061); // error CS1061: 'C' does not contain a definition for 'Goo' and no extension method 'Goo' accepting a first argument of type 'C' could be found
private const string CS0103 = nameof(CS0103); // error CS0103: The name 'Goo' does not exist in the current context
private const string CS0117 = nameof(CS0117); // error CS0117: 'TestNs.Program' does not contain a definition for 'blah'
private const string CS0539 = nameof(CS0539); // error CS0539: 'Class.SomeProp' in explicit interface declaration is not a member of interface
private const string CS0246 = nameof(CS0246); // error CS0246: The type or namespace name 'Version' could not be found
private const string CS0120 = nameof(CS0120); // error CS0120: An object reference is required for the non-static field, method, or property 'A'
private const string CS0118 = nameof(CS0118); // error CS0118: 'C' is a type but is used like a variable
[ImportingConstructor]
[SuppressMessage("RoslynDiagnosticsReliability", "RS0033:Importing constructor should be [Obsolete]", Justification = "Used in test code: https://github.com/dotnet/roslyn/issues/42814")]
public CSharpGenerateVariableCodeFixProvider()
{
}
public override ImmutableArray<string> FixableDiagnosticIds =>
ImmutableArray.Create(CS1061, CS0103, CS0117, CS0539, CS0246, CS0120, CS0118);
protected override bool IsCandidate(SyntaxNode node, SyntaxToken token, Diagnostic diagnostic)
=> node is SimpleNameSyntax or PropertyDeclarationSyntax or MemberBindingExpressionSyntax;
protected override SyntaxNode GetTargetNode(SyntaxNode node)
{
if (node.IsKind(SyntaxKind.MemberBindingExpression))
{
var nameNode = node.ChildNodes().FirstOrDefault(n => n.IsKind(SyntaxKind.IdentifierName));
if (nameNode != null)
{
return nameNode;
}
}
return base.GetTargetNode(node);
}
protected override Task<ImmutableArray<CodeAction>> GetCodeActionsAsync(
Document document, SyntaxNode node, CancellationToken cancellationToken)
{
var service = document.GetLanguageService<IGenerateVariableService>();
return service.GenerateVariableAsync(document, node, cancellationToken);
}
}
}
| 51.764706 | 198 | 0.725852 |
[
"MIT"
] |
AlexanderSemenyak/roslyn
|
src/Features/CSharp/Portable/GenerateVariable/CSharpGenerateVariableCodeFixProvider.cs
| 3,522 |
C#
|
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Linq;
using System.Reflection;
using Microsoft.AspNet.Mvc.Razor;
using Microsoft.AspNet.Mvc.Razor.Compilation;
using Microsoft.AspNet.Mvc.Rendering;
using Microsoft.AspNet.Razor.TagHelpers;
using Microsoft.Extensions.DependencyInjection.Extensions;
namespace Microsoft.Extensions.DependencyInjection
{
/// <summary>
/// Extensions methods for configuring MVC via an <see cref="IMvcBuilder"/>.
/// </summary>
public static class MvcRazorMvcBuilderExtensions
{
/// <summary>
/// Configures a set of <see cref="RazorViewEngineOptions"/> for the application.
/// </summary>
/// <param name="builder">The <see cref="IMvcBuilder"/>.</param>
/// <param name="setupAction">An action to configure the <see cref="RazorViewEngineOptions"/>.</param>
/// <returns>The <see cref="IMvcBuilder"/>.</returns>
public static IMvcBuilder AddRazorOptions(
this IMvcBuilder builder,
Action<RazorViewEngineOptions> setupAction)
{
if (builder == null)
{
throw new ArgumentNullException(nameof(builder));
}
if (setupAction == null)
{
throw new ArgumentNullException(nameof(setupAction));
}
builder.Services.Configure(setupAction);
return builder;
}
/// <summary>
/// Adds an initialization callback for a given <typeparamref name="TTagHelper"/>.
/// </summary>
/// <remarks>
/// The callback will be invoked on any <typeparamref name="TTagHelper"/> instance before the
/// <see cref="ITagHelper.ProcessAsync(TagHelperContext, TagHelperOutput)"/> method is called.
/// </remarks>
/// <typeparam name="TTagHelper">The type of <see cref="ITagHelper"/> being initialized.</typeparam>
/// <param name="builder">The <see cref="IMvcBuilder"/> instance this method extends.</param>
/// <param name="initialize">An action to initialize the <typeparamref name="TTagHelper"/>.</param>
/// <returns>The <see cref="IMvcBuilder"/> instance this method extends.</returns>
public static IMvcBuilder InitializeTagHelper<TTagHelper>(
this IMvcBuilder builder,
Action<TTagHelper, ViewContext> initialize)
where TTagHelper : ITagHelper
{
if (builder == null)
{
throw new ArgumentNullException(nameof(builder));
}
if (initialize == null)
{
throw new ArgumentNullException(nameof(initialize));
}
var initializer = new TagHelperInitializer<TTagHelper>(initialize);
builder.Services.AddInstance(typeof(ITagHelperInitializer<TTagHelper>), initializer);
return builder;
}
public static IMvcBuilder AddPrecompiledRazorViews(
this IMvcBuilder builder,
params Assembly[] assemblies)
{
if (builder == null)
{
throw new ArgumentNullException(nameof(builder));
}
if (assemblies == null)
{
throw new ArgumentNullException(nameof(assemblies));
}
builder.Services.Replace(
ServiceDescriptor.Singleton<ICompilerCacheProvider>(serviceProvider =>
ActivatorUtilities.CreateInstance<PrecompiledViewsCompilerCacheProvider>(
serviceProvider,
assemblies.AsEnumerable())));
return builder;
}
}
}
| 37.920792 | 111 | 0.610705 |
[
"Apache-2.0"
] |
VGGeorgiev/Mvc
|
src/Microsoft.AspNet.Mvc.Razor/DependencyInjection/MvcRazorMvcBuilderExtensions.cs
| 3,830 |
C#
|
using System;
using SLua;
using System.Collections.Generic;
[UnityEngine.Scripting.Preserve]
public class Lua_UnityEngine_RenderBuffer : LuaObject {
[SLua.MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))]
[UnityEngine.Scripting.Preserve]
static public int constructor(IntPtr l) {
try {
UnityEngine.RenderBuffer o;
o=new UnityEngine.RenderBuffer();
pushValue(l,true);
pushValue(l,o);
return 2;
}
catch(Exception e) {
return error(l,e);
}
}
[SLua.MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))]
[UnityEngine.Scripting.Preserve]
static public int GetNativeRenderBufferPtr(IntPtr l) {
try {
UnityEngine.RenderBuffer self;
checkValueType(l,1,out self);
var ret=self.GetNativeRenderBufferPtr();
pushValue(l,true);
pushValue(l,ret);
return 2;
}
catch(Exception e) {
return error(l,e);
}
}
[UnityEngine.Scripting.Preserve]
static public void reg(IntPtr l) {
getTypeTable(l,"UnityEngine.RenderBuffer");
addMember(l,GetNativeRenderBufferPtr);
createTypeMetatable(l,constructor, typeof(UnityEngine.RenderBuffer),typeof(System.ValueType));
}
}
| 26.5 | 96 | 0.745732 |
[
"MIT"
] |
MonkeyKingMKY/luaide-lite
|
test/slua/Assets/Slua/LuaObject/Unity/Lua_UnityEngine_RenderBuffer.cs
| 1,115 |
C#
|
using Blockcore.Explorer.Models.ApiModels;
using Blockcore.Explorer.Settings;
using Microsoft.Extensions.Options;
namespace Blockcore.Explorer.Services
{
public class BlockIndexService : ServiceBase
{
private readonly ExplorerSettings settings;
public BlockIndexService() : base(string.Empty)
{
}
public BlockIndexService(IOptions<ExplorerSettings> settings) : base(settings.Value.Indexer?.ApiUrl)
{
this.settings = settings.Value;
}
public BlockModel GetBlockByHeight(long blockHeight)
{
return Execute<BlockModel>(GetRequest($"/query/block/index/{blockHeight}/transactions"));
}
public BlockModel GetBlockByHash(string blockHash)
{
return Execute<BlockModel>(GetRequest($"/query/block/{blockHash}/transactions"));
}
public BlockModel GetLatestBlock()
{
return Execute<BlockModel>(GetRequest("/query/block/Latest/transactions"));
}
public AddressModel GetTransactionsByAddress(string adddress)
{
return Execute<AddressModel>(GetRequest($"/query/address/{adddress}/transactions"));
}
public TransactionDetailsModel GetTransaction(string transactionId)
{
return Execute<TransactionDetailsModel>(GetRequest($"/query/transaction/{transactionId}"));
}
public string GetStatistics()
{
string result = Execute(GetRequest("/stats"));
return result;
}
}
}
| 28.09434 | 106 | 0.676293 |
[
"MIT"
] |
block-core/blockcore-explorer-legacy
|
src/Blockcore.Explorer/Services/BlockIndexService.cs
| 1,489 |
C#
|
using System;
namespace ToroChallenge.Application.Interfaces
{
public interface ISensibilizaContaCorrenteApp
{
}
}
| 14.333333 | 49 | 0.751938 |
[
"MIT"
] |
nelson1987/ToroChallenge
|
src/ToroChallenge.Application.Interfaces/ISensibilizaContaCorrente.cs
| 131 |
C#
|
namespace RecepiesProject.Data.Common.Models
{
using System;
using System.ComponentModel.DataAnnotations;
public abstract class BaseModel<TKey> : IAuditInfo
{
[Key]
public TKey Id { get; set; }
public DateTime CreatedOn { get; set; }
public DateTime? ModifiedOn { get; set; }
}
}
| 21 | 54 | 0.633929 |
[
"Apache-2.0"
] |
AKermanov/recipes-project
|
src/Data/RecepiesProject.Data.Common/Models/BaseModel.cs
| 338 |
C#
|
using System;
using System.Runtime.CompilerServices;
namespace YAF.Lucene.Net.Store
{
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/// <summary>
/// Abstract base class for output to a file in a <see cref="Directory"/>. A random-access
/// output stream. Used for all Lucene index output operations.
///
/// <para/><see cref="IndexOutput"/> may only be used from one thread, because it is not
/// thread safe (it keeps internal state like file position).
/// </summary>
/// <seealso cref="Directory"/>
/// <seealso cref="IndexInput"/>
public abstract class IndexOutput : DataOutput, IDisposable
{
/// <summary>
/// Forces any buffered output to be written. </summary>
[MethodImpl(MethodImplOptions.NoInlining)]
public abstract void Flush();
/// <summary>
/// Closes this stream to further operations. </summary>
// LUCENENET specific - implementing proper dispose pattern
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
/// <summary>
/// Closes this stream to further operations. </summary>
protected abstract void Dispose(bool disposing);
/// <summary>
/// Returns the current position in this file, where the next write will
/// occur. </summary>
/// <seealso cref="Seek(long)"/>
public abstract long GetFilePointer();
/// <summary>
/// Sets current position in this file, where the next write will occur. </summary>
/// <seealso cref="GetFilePointer()"/>
[Obsolete("(4.1) this method will be removed in Lucene 5.0")]
public abstract void Seek(long pos);
/// <summary>
/// Returns the current checksum of bytes written so far </summary>
public abstract long Checksum { get; }
/// <summary>
/// Gets or Sets the file length. By default, this property's setter does
/// nothing (it's optional for a <see cref="Directory"/> to implement
/// it). But, certain <see cref="Directory"/> implementations (for
/// example <see cref="FSDirectory"/>) can use this to inform the
/// underlying IO system to pre-allocate the file to the
/// specified size. If the length is longer than the
/// current file length, the bytes added to the file are
/// undefined. Otherwise the file is truncated.</summary>
public virtual long Length { get; set; }
}
}
| 43.43038 | 96 | 0.62081 |
[
"Apache-2.0"
] |
AlbertoP57/YAFNET
|
yafsrc/Lucene.Net/Lucene.Net/Store/IndexOutput.cs
| 3,353 |
C#
|
using System;
using System.Collections.Generic;
using System.Linq;
using Toe.SPIRV.Instructions;
using Toe.SPIRV.Reflection.Types;
using Toe.SPIRV.Spv;
namespace Toe.SPIRV.Reflection.Nodes
{
public partial class String : Node
{
public String()
{
}
public String(string value, string debugName = null)
{
this.Value = value;
DebugName = debugName;
}
public override Op OpCode => Op.OpString;
public string Value { get; set; }
public String WithDecoration(Spv.Decoration decoration)
{
AddDecoration(decoration);
return this;
}
public override void SetUp(Instruction op, SpirvInstructionTreeBuilder treeBuilder)
{
base.SetUp(op, treeBuilder);
SetUp((OpString)op, treeBuilder);
}
public String SetUp(Action<String> setup)
{
setup(this);
return this;
}
private void SetUp(OpString op, SpirvInstructionTreeBuilder treeBuilder)
{
Value = op.Value;
SetUpDecorations(op, treeBuilder);
}
/// <summary>Returns a string that represents the String object.</summary>
/// <returns>A string that represents the String object.</returns>
/// <filterpriority>2</filterpriority>
public override string ToString()
{
return $"String({Value}, {DebugName})";
}
}
}
| 25.862069 | 91 | 0.584667 |
[
"MIT"
] |
gleblebedev/Toe.SPIRV
|
src/Toe.SPIRV/Reflection/Nodes/String.cs
| 1,500 |
C#
|
using BlogService.Features.Core;
using MediatR;
using System.Threading.Tasks;
using System.Web.Http;
using System.Web.Http.Description;
namespace BlogService.Features.Authors
{
[Authorize]
[RoutePrefix("api/author")]
public class AuthorController : ApiController
{
public AuthorController(IMediator mediator)
{
_mediator = mediator;
}
[Route("add")]
[HttpPost]
[ResponseType(typeof(AddOrUpdateAuthorCommand.AddOrUpdateAuthorResponse))]
public async Task<IHttpActionResult> Add(AddOrUpdateAuthorCommand.AddOrUpdateAuthorRequest request)
{
request.TenantUniqueId = Request.GetTenantUniqueId();
return Ok(await _mediator.Send(request));
}
[Route("update")]
[HttpPut]
[ResponseType(typeof(AddOrUpdateAuthorCommand.AddOrUpdateAuthorResponse))]
public async Task<IHttpActionResult> Update(AddOrUpdateAuthorCommand.AddOrUpdateAuthorRequest request)
{
request.TenantUniqueId = Request.GetTenantUniqueId();
return Ok(await _mediator.Send(request));
}
[Route("get")]
[AllowAnonymous]
[HttpGet]
[ResponseType(typeof(GetAuthorsQuery.GetAuthorsResponse))]
public async Task<IHttpActionResult> Get()
{
var request = new GetAuthorsQuery.GetAuthorsRequest();
request.TenantUniqueId = Request.GetTenantUniqueId();
return Ok(await _mediator.Send(request));
}
[Route("getById")]
[HttpGet]
[ResponseType(typeof(GetAuthorByIdQuery.GetAuthorByIdResponse))]
public async Task<IHttpActionResult> GetById([FromUri]GetAuthorByIdQuery.GetAuthorByIdRequest request)
=> Ok(await _mediator.Send(request));
[Route("remove")]
[HttpDelete]
[ResponseType(typeof(RemoveAuthorCommand.RemoveAuthorResponse))]
public async Task<IHttpActionResult> Remove([FromUri]RemoveAuthorCommand.RemoveAuthorRequest request)
{
request.TenantUniqueId = Request.GetTenantUniqueId();
return Ok(await _mediator.Send(request));
}
protected readonly IMediator _mediator;
}
}
| 34.615385 | 110 | 0.663111 |
[
"MIT"
] |
QuinntyneBrown/BlogService
|
src/BlogService/Features/Authors/AuthorController.cs
| 2,250 |
C#
|
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for license information.
namespace ODataValidator.Rule
{
#region Namespace.
using System;
using System.ComponentModel.Composition;
using System.Linq;
using System.Net;
using Newtonsoft.Json.Linq;
using ODataValidator.Rule.Helper;
using ODataValidator.RuleEngine;
using ODataValidator.RuleEngine.Common;
#endregion
/// <summary>
/// Class of service implemenation feature to verify .
/// </summary>
[Export(typeof(ExtensionRule))]
public class ServiceImpl_SystemQueryOptionFilter_Maxdatetime : ServiceImplExtensionRule
{
/// <summary>
/// Gets the service implementation feature name
/// </summary>
public override string Name
{
get
{
return "ServiceImpl_SystemQueryOptionFilter_Maxdatetime";
}
}
/// <summary>
/// Gets the service implementation feature description
/// </summary>
public override string Description
{
get
{
return this.CategoryInfo.CategoryFullName + ",$filter(maxdatetime)";
}
}
/// <summary>
/// Gets the service implementation feature specification in OData document
/// </summary>
public override string V4SpecificationSection
{
get
{
return "";
}
}
/// <summary>
/// Gets the service implementation feature level.
/// </summary>
public override RequirementLevel RequirementLevel
{
get
{
return RequirementLevel.Must;
}
}
/// <summary>
/// Gets the service implementation category.
/// </summary>
public override ServiceImplCategory CategoryInfo
{
get
{
var parent = new ServiceImplCategory(ServiceImplCategoryName.RequestingData);
parent = new ServiceImplCategory(ServiceImplCategoryName.SystemQueryOption, parent);
return new ServiceImplCategory(ServiceImplCategoryName.ArithmeticOperators, parent);
}
}
/// <summary>
/// Verifies the service implementation feature.
/// </summary>
/// <param name="context">The Interop service context</param>
/// <param name="info">out parameter to return violation information when rule does not pass</param>
/// <returns>true if the service implementation feature passes; false otherwise</returns>
public override bool? Verify(ServiceContext context, out ExtensionRuleViolationInfo info)
{
if (context == null)
{
throw new ArgumentNullException("context");
}
bool? passed = null;
info = null;
var svcStatus = ServiceStatus.GetInstance();
string entityTypeShortName;
var propTypes = new string[1] { "Edm.DateTimeOffset" };
var propNames = MetadataHelper.GetPropertyNames(propTypes, out entityTypeShortName);
if (null == propNames || !propNames.Any())
{
return passed;
}
string propName = propNames[0];
var entitySetUrl = entityTypeShortName.GetAccessEntitySetURL();
if (string.IsNullOrEmpty(entitySetUrl))
{
return passed;
}
string url = svcStatus.RootURL.TrimEnd('/') + "/" + entitySetUrl;
var resp = WebHelper.Get(new Uri(url), string.Empty, RuleEngineSetting.Instance().DefaultMaximumPayloadSize, svcStatus.DefaultHeaders);
if (null != resp && HttpStatusCode.OK == resp.StatusCode)
{
url = string.Format("{0}?$filter={1} le maxdatetime()", url, propName);
resp = WebHelper.Get(new Uri(url), string.Empty, RuleEngineSetting.Instance().DefaultMaximumPayloadSize, svcStatus.DefaultHeaders);
var detail = new ExtensionRuleResultDetail(this.Name, url, HttpMethod.Get, string.Empty);
info = new ExtensionRuleViolationInfo(new Uri(url), string.Empty, detail);
if (null != resp && HttpStatusCode.OK == resp.StatusCode)
{
passed = true;
}
else
{
passed = false;
}
}
return passed;
}
}
}
| 34.932836 | 147 | 0.571459 |
[
"MIT"
] |
OData/ValidationTool
|
src/CodeRules/ServiceImplementation/ServiceImpl_SystemQueryOptionFilter_Maxdatetime.cs
| 4,683 |
C#
|
using PlatinDashboard.Domain.Farmacia.Entities;
using PlatinDashboard.Domain.Farmacia.Interfaces.Repositories;
using PlatinDashboard.Infra.Data.Farmacia.Context;
using System.Collections.Generic;
using System.Data.Common;
using System.Linq;
namespace PlatinDashboard.Infra.Data.Farmacia.Repositories
{
public class VendaLojaPorHoraRepository : RepositoryBase<VendaLojaPorHora>, IVendaLojaPorHoraRepository
{
public List<VendaLojaPorHora> BuscarPorLoja(int lojaId, DbConnection connection)
{
//Método para buscar as vendas por loja separado por horas
if (connection.ToString() == "MySql.Data.MySqlClient.MySqlConnection")
{
var db = new MySqlContext(connection);
return db.VendasLojaPorHora.Where(v => v.Loja == lojaId).ToList();
}
else
{
var db = new PostgreContext(connection);
return db.VendasLojaPorHora.Where(v => v.Loja == lojaId).ToList();
}
}
}
}
| 37.142857 | 107 | 0.661538 |
[
"Apache-2.0"
] |
TcavalcantiDesenv/RepasseApcd
|
src/APCD/src/PlatinDashboard.Infra.Data.Farmacia/Repositories/VendaLojaPorHoraRepository.cs
| 1,043 |
C#
|
using System;
using UnityEngine;
using UnityEngine.Advertisements;
namespace Controller
{
public class Advertising : MonoBehaviour
{
public void ShowAd()
{
#if UNITY_IOS || UNITY_ANDROID
if (!Advertisement.IsReady()) return;
var options = new ShowOptions {resultCallback = HandleShowResult};
Advertisement.Show(options);
#endif
}
#if UNITY_IOS || UNITY_ANDROID
private void HandleShowResult(ShowResult result)
{
switch (result)
{
case ShowResult.Finished:
case ShowResult.Skipped:
StartCoroutine(AnimationManager.Instance.ContinueButtonPressed(true));
break;
case ShowResult.Failed:
StartCoroutine(AnimationManager.Instance.ContinueButtonPressed(false));
break;
default:
throw new ArgumentOutOfRangeException("result", result, null);
}
}
#endif
private void Awake()
{
Advertisement.Initialize(Advertisement.gameId);
Manager.Instance.adverts = this;
}
}
}
| 28.619048 | 91 | 0.572379 |
[
"MIT"
] |
tvhees/NumberPanic
|
Assets/_scripts/Controller/Advertising.cs
| 1,204 |
C#
|
using System;
using Xamarin.Forms;
using Xamarin.Forms.Xaml;
namespace XamEasyControl
{
public partial class App : Application
{
public App()
{
InitializeComponent();
MainPage = new MainPage();
}
protected override void OnStart()
{
}
protected override void OnSleep()
{
}
protected override void OnResume()
{
}
}
}
| 12.241379 | 42 | 0.664789 |
[
"MIT"
] |
tannlee/XamEasyControl
|
XamEasyControl/XamEasyControl/XamEasyControl/App.xaml.cs
| 357 |
C#
|
// -----------------------------------------------------------------------------------------
// <copyright file="CloudBlobClientTest.cs" company="Microsoft">
// Copyright 2013 Microsoft Corporation
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// </copyright>
// -----------------------------------------------------------------------------------------
using Microsoft.VisualStudio.TestPlatform.UnitTestFramework;
using Microsoft.WindowsAzure.Storage.Auth;
using Microsoft.WindowsAzure.Storage.Core.Util;
using Microsoft.WindowsAzure.Storage.RetryPolicies;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices.WindowsRuntime;
using System.Threading.Tasks;
namespace Microsoft.WindowsAzure.Storage.Blob
{
[TestClass]
public class CloudBlobClientTest : BlobTestBase
{
//
// Use TestInitialize to run code before running each test
[TestInitialize()]
public void MyTestInitialize()
{
if (TestBase.BlobBufferManager != null)
{
TestBase.BlobBufferManager.OutstandingBufferCount = 0;
}
}
//
// Use TestCleanup to run code after each test has run
[TestCleanup()]
public void MyTestCleanup()
{
if (TestBase.BlobBufferManager != null)
{
Assert.AreEqual(0, TestBase.BlobBufferManager.OutstandingBufferCount);
}
}
[TestMethod]
[Description("Create a service client with URI and credentials")]
[TestCategory(ComponentCategory.Blob)]
[TestCategory(TestTypeCategory.UnitTest)]
[TestCategory(SmokeTestCategory.NonSmoke)]
[TestCategory(TenantTypeCategory.DevStore), TestCategory(TenantTypeCategory.DevFabric), TestCategory(TenantTypeCategory.Cloud)]
public void CloudBlobClientConstructor()
{
CloudBlobClient blobClient = GenerateCloudBlobClient();
Assert.IsTrue(blobClient.BaseUri.ToString().Contains(TestBase.TargetTenantConfig.BlobServiceEndpoint));
Assert.AreEqual(TestBase.StorageCredentials, blobClient.Credentials);
Assert.AreEqual(AuthenticationScheme.SharedKey, blobClient.AuthenticationScheme);
}
[TestMethod]
[Description("Create a service client with uppercase account name")]
[TestCategory(ComponentCategory.Blob)]
[TestCategory(TestTypeCategory.UnitTest)]
[TestCategory(SmokeTestCategory.NonSmoke)]
[TestCategory(TenantTypeCategory.DevStore), TestCategory(TenantTypeCategory.DevFabric), TestCategory(TenantTypeCategory.Cloud)]
public async Task CloudBlobClientWithUppercaseAccountNameAsync()
{
StorageCredentials credentials = new StorageCredentials(TestBase.StorageCredentials.AccountName.ToUpper(), Convert.ToBase64String(TestBase.StorageCredentials.ExportKey()));
Uri baseAddressUri = new Uri(TestBase.TargetTenantConfig.BlobServiceEndpoint);
CloudBlobClient blobClient = new CloudBlobClient(baseAddressUri, TestBase.StorageCredentials);
CloudBlobContainer container = blobClient.GetContainerReference("container");
await container.ExistsAsync();
}
[TestMethod]
[Description("Compare service client properties of blob objects")]
[TestCategory(ComponentCategory.Blob)]
[TestCategory(TestTypeCategory.UnitTest)]
[TestCategory(SmokeTestCategory.NonSmoke)]
[TestCategory(TenantTypeCategory.DevStore), TestCategory(TenantTypeCategory.DevFabric), TestCategory(TenantTypeCategory.Cloud)]
public void CloudBlobClientObjects()
{
CloudBlobClient blobClient = GenerateCloudBlobClient();
CloudBlobContainer container = blobClient.GetContainerReference("container");
Assert.AreEqual(blobClient, container.ServiceClient);
CloudBlockBlob blockBlob = container.GetBlockBlobReference("blockblob");
Assert.AreEqual(blobClient, blockBlob.ServiceClient);
CloudPageBlob pageBlob = container.GetPageBlobReference("pageblob");
Assert.AreEqual(blobClient, pageBlob.ServiceClient);
CloudBlobContainer container2 = GetRandomContainerReference();
Assert.AreNotEqual(blobClient, container2.ServiceClient);
CloudBlockBlob blockBlob2 = container2.GetBlockBlobReference("blockblob");
Assert.AreEqual(container2.ServiceClient, blockBlob2.ServiceClient);
CloudPageBlob pageBlob2 = container2.GetPageBlobReference("pageblob");
Assert.AreEqual(container2.ServiceClient, pageBlob2.ServiceClient);
}
[TestMethod]
[Description("List blobs with prefix")]
[TestCategory(ComponentCategory.Blob)]
[TestCategory(TestTypeCategory.UnitTest)]
[TestCategory(SmokeTestCategory.NonSmoke)]
[TestCategory(TenantTypeCategory.DevStore), TestCategory(TenantTypeCategory.DevFabric), TestCategory(TenantTypeCategory.Cloud)]
public async Task CloudBlobClientListBlobsSegmentedWithPrefixAsync()
{
string name = "bb" + GetRandomContainerName();
CloudBlobClient blobClient = GenerateCloudBlobClient();
CloudBlobContainer rootContainer = blobClient.GetRootContainerReference();
CloudBlobContainer container = blobClient.GetContainerReference(name);
try
{
await rootContainer.CreateIfNotExistsAsync();
await container.CreateAsync();
List<string> blobNames = await CreateBlobsAsync(container, 3, BlobType.BlockBlob);
List<string> rootBlobNames = await CreateBlobsAsync(rootContainer, 2, BlobType.BlockBlob);
BlobResultSegment results;
BlobContinuationToken token = null;
do
{
results = await blobClient.ListBlobsSegmentedAsync("bb", token);
token = results.ContinuationToken;
foreach (CloudBlockBlob blob in results.Results)
{
await blob.DeleteAsync();
rootBlobNames.Remove(blob.Name);
}
}
while (token != null);
Assert.AreEqual(0, rootBlobNames.Count);
results = await blobClient.ListBlobsSegmentedAsync("bb", token);
Assert.AreEqual(0, results.Results.Count());
Assert.IsNull(results.ContinuationToken);
results = await blobClient.ListBlobsSegmentedAsync(name, token);
Assert.AreEqual(0, results.Results.Count());
Assert.IsNull(results.ContinuationToken);
token = null;
do
{
results = await blobClient.ListBlobsSegmentedAsync(name + "/", token);
token = results.ContinuationToken;
foreach (CloudBlockBlob blob in results.Results)
{
Assert.IsTrue(blobNames.Remove(blob.Name));
}
}
while (token != null);
Assert.AreEqual(0, blobNames.Count);
}
finally
{
container.DeleteIfExistsAsync().AsTask().Wait();
}
}
[TestMethod]
[Description("List containers")]
[TestCategory(ComponentCategory.Blob)]
[TestCategory(TestTypeCategory.UnitTest)]
[TestCategory(SmokeTestCategory.NonSmoke)]
[TestCategory(TenantTypeCategory.DevStore), TestCategory(TenantTypeCategory.DevFabric), TestCategory(TenantTypeCategory.Cloud)]
public async Task CloudBlobClientListContainersSegmentedAsync()
{
AssertSecondaryEndpoint();
string name = GetRandomContainerName();
List<string> containerNames = new List<string>();
CloudBlobClient blobClient = GenerateCloudBlobClient();
for (int i = 0; i < 3; i++)
{
string containerName = name + i.ToString();
containerNames.Add(containerName);
await blobClient.GetContainerReference(containerName).CreateAsync();
}
List<string> listedContainerNames = new List<string>();
BlobContinuationToken token = null;
do
{
ContainerResultSegment resultSegment = await blobClient.ListContainersSegmentedAsync(token);
token = resultSegment.ContinuationToken;
foreach (CloudBlobContainer container in resultSegment.Results)
{
Assert.IsTrue(blobClient.GetContainerReference(container.Name).StorageUri.Equals(container.StorageUri));
listedContainerNames.Add(container.Name);
}
}
while (token != null);
foreach (string containerName in listedContainerNames)
{
if (containerNames.Remove(containerName))
{
await blobClient.GetContainerReference(containerName).DeleteAsync();
}
}
Assert.AreEqual(0, containerNames.Count);
}
[TestMethod]
[Description("List containers with prefix using segmented listing")]
[TestCategory(ComponentCategory.Blob)]
[TestCategory(TestTypeCategory.UnitTest)]
[TestCategory(SmokeTestCategory.NonSmoke)]
[TestCategory(TenantTypeCategory.DevStore), TestCategory(TenantTypeCategory.DevFabric), TestCategory(TenantTypeCategory.Cloud)]
public async Task CloudBlobClientListContainersSegmentedWithPrefixAsync()
{
string name = GetRandomContainerName();
List<string> containerNames = new List<string>();
CloudBlobClient blobClient = GenerateCloudBlobClient();
for (int i = 0; i < 3; i++)
{
string containerName = name + i.ToString();
containerNames.Add(containerName);
await blobClient.GetContainerReference(containerName).CreateAsync();
}
List<string> listedContainerNames = new List<string>();
BlobContinuationToken token = null;
do
{
ContainerResultSegment resultSegment = await blobClient.ListContainersSegmentedAsync(name, ContainerListingDetails.None, 1, token, null, null);
token = resultSegment.ContinuationToken;
int count = 0;
foreach (CloudBlobContainer container in resultSegment.Results)
{
count++;
listedContainerNames.Add(container.Name);
}
Assert.IsTrue(count <= 1);
}
while (token != null);
Assert.AreEqual(containerNames.Count, listedContainerNames.Count);
foreach (string containerName in listedContainerNames)
{
Assert.IsTrue(containerNames.Remove(containerName));
await blobClient.GetContainerReference(containerName).DeleteAsync();
}
}
[TestMethod]
[Description("Test Create Container with Shared Key Lite")]
[TestCategory(ComponentCategory.Blob)]
[TestCategory(TestTypeCategory.UnitTest)]
[TestCategory(SmokeTestCategory.NonSmoke)]
[TestCategory(TenantTypeCategory.DevStore), TestCategory(TenantTypeCategory.DevFabric), TestCategory(TenantTypeCategory.Cloud)]
public async Task CloudBlobClientCreateContainerSharedKeyLiteAsync()
{
CloudBlobClient blobClient = GenerateCloudBlobClient();
blobClient.AuthenticationScheme = AuthenticationScheme.SharedKeyLite;
string containerName = GetRandomContainerName();
CloudBlobContainer blobContainer = blobClient.GetContainerReference(containerName);
await blobContainer.CreateAsync();
bool exists = await blobContainer.ExistsAsync();
Assert.IsTrue(exists);
await blobContainer.DeleteAsync();
}
[TestMethod]
[Description("Upload a blob with a small maximum execution time")]
[TestCategory(ComponentCategory.Blob)]
[TestCategory(TestTypeCategory.UnitTest)]
[TestCategory(SmokeTestCategory.NonSmoke)]
[TestCategory(TenantTypeCategory.Cloud)]
public async Task CloudBlobClientMaximumExecutionTimeoutAsync()
{
CloudBlobClient blobClient = GenerateCloudBlobClient();
CloudBlobContainer container = blobClient.GetContainerReference(Guid.NewGuid().ToString("N"));
byte[] buffer = BlobTestBase.GetRandomBuffer(80 * 1024 * 1024);
try
{
await container.CreateAsync();
blobClient.DefaultRequestOptions.MaximumExecutionTime = TimeSpan.FromSeconds(5);
CloudBlockBlob blockBlob = container.GetBlockBlobReference("blob1");
blockBlob.StreamWriteSizeInBytes = 1 * 1024 * 1024;
using (MemoryStream ms = new MemoryStream(buffer))
{
try
{
await blockBlob.UploadFromStreamAsync(ms.AsInputStream());
Assert.Fail();
}
catch (AggregateException ex)
{
Assert.AreEqual("The client could not finish the operation within specified timeout.", RequestResult.TranslateFromExceptionMessage(ex.InnerException.InnerException.Message).ExceptionInfo.Message);
}
catch (TaskCanceledException)
{
}
}
CloudPageBlob pageBlob = container.GetPageBlobReference("blob2");
pageBlob.StreamWriteSizeInBytes = 1 * 1024 * 1024;
using (MemoryStream ms = new MemoryStream(buffer))
{
try
{
await pageBlob.UploadFromStreamAsync(ms.AsInputStream());
Assert.Fail();
}
catch (AggregateException ex)
{
Assert.AreEqual("The client could not finish the operation within specified timeout.", RequestResult.TranslateFromExceptionMessage(ex.InnerException.InnerException.Message).ExceptionInfo.Message);
}
catch (TaskCanceledException)
{
}
}
}
finally
{
blobClient.DefaultRequestOptions.MaximumExecutionTime = null;
container.DeleteIfExistsAsync().AsTask().Wait();
}
}
[TestMethod]
[Description("Make sure MaxExecutionTime is not enforced when using streams")]
[TestCategory(ComponentCategory.Blob)]
[TestCategory(TestTypeCategory.UnitTest)]
[TestCategory(SmokeTestCategory.NonSmoke)]
[TestCategory(TenantTypeCategory.Cloud)]
public async Task CloudBlobClientMaximumExecutionTimeoutShouldNotBeHonoredForStreamsAsync()
{
CloudBlobClient blobClient = GenerateCloudBlobClient();
CloudBlobContainer container = blobClient.GetContainerReference(Guid.NewGuid().ToString("N"));
byte[] buffer = BlobTestBase.GetRandomBuffer(1024 * 1024);
try
{
await container.CreateAsync();
blobClient.DefaultRequestOptions.MaximumExecutionTime = TimeSpan.FromSeconds(30);
CloudBlockBlob blockBlob = container.GetBlockBlobReference("blob1");
CloudPageBlob pageBlob = container.GetPageBlobReference("blob2");
blockBlob.StreamWriteSizeInBytes = 1024 * 1024;
blockBlob.StreamMinimumReadSizeInBytes = 1024 * 1024;
pageBlob.StreamWriteSizeInBytes = 1024 * 1024;
pageBlob.StreamMinimumReadSizeInBytes = 1024 * 1024;
using (ICloudBlobStream bos = await blockBlob.OpenWriteAsync())
{
DateTime start = DateTime.Now;
for (int i = 0; i < 7; i++)
{
await bos.WriteAsync(buffer.AsBuffer());
}
// Sleep to ensure we are over the Max execution time when we do the last write
int msRemaining = (int)(blobClient.DefaultRequestOptions.MaximumExecutionTime.Value - (DateTime.Now - start)).TotalMilliseconds;
if (msRemaining > 0)
{
await Task.Delay(msRemaining);
}
await bos.WriteAsync(buffer.AsBuffer());
await bos.CommitAsync();
}
using (Stream bis = (await blockBlob.OpenReadAsync()).AsStreamForRead())
{
DateTime start = DateTime.Now;
int total = 0;
while (total < 7 * 1024 * 1024)
{
total += await bis.ReadAsync(buffer, 0, buffer.Length);
}
// Sleep to ensure we are over the Max execution time when we do the last read
int msRemaining = (int)(blobClient.DefaultRequestOptions.MaximumExecutionTime.Value - (DateTime.Now - start)).TotalMilliseconds;
if (msRemaining > 0)
{
await Task.Delay(msRemaining);
}
while (true)
{
int count = await bis.ReadAsync(buffer, 0, buffer.Length);
total += count;
if (count == 0)
break;
}
}
using (ICloudBlobStream bos = await pageBlob.OpenWriteAsync(8 * 1024 * 1024))
{
DateTime start = DateTime.Now;
for (int i = 0; i < 7; i++)
{
await bos.WriteAsync(buffer.AsBuffer());
}
// Sleep to ensure we are over the Max execution time when we do the last write
int msRemaining = (int)(blobClient.DefaultRequestOptions.MaximumExecutionTime.Value - (DateTime.Now - start)).TotalMilliseconds;
if (msRemaining > 0)
{
await Task.Delay(msRemaining);
}
await bos.WriteAsync(buffer.AsBuffer());
await bos.CommitAsync();
}
using (Stream bis = (await pageBlob.OpenReadAsync()).AsStreamForRead())
{
DateTime start = DateTime.Now;
int total = 0;
while (total < 7 * 1024 * 1024)
{
total += await bis.ReadAsync(buffer, 0, buffer.Length);
}
// Sleep to ensure we are over the Max execution time when we do the last read
int msRemaining = (int)(blobClient.DefaultRequestOptions.MaximumExecutionTime.Value - (DateTime.Now - start)).TotalMilliseconds;
if (msRemaining > 0)
{
await Task.Delay(msRemaining);
}
while (true)
{
int count = await bis.ReadAsync(buffer, 0, buffer.Length);
total += count;
if (count == 0)
break;
}
}
}
finally
{
blobClient.DefaultRequestOptions.MaximumExecutionTime = null;
container.DeleteIfExistsAsync().AsTask().Wait();
}
}
[TestMethod]
[Description("Get service stats")]
[TestCategory(ComponentCategory.Blob)]
[TestCategory(TestTypeCategory.UnitTest)]
[TestCategory(SmokeTestCategory.NonSmoke)]
[TestCategory(TenantTypeCategory.DevStore), TestCategory(TenantTypeCategory.DevFabric), TestCategory(TenantTypeCategory.Cloud)]
public async Task CloudBlobClientGetServiceStatsAsync()
{
AssertSecondaryEndpoint();
CloudBlobClient client = GenerateCloudBlobClient();
client.DefaultRequestOptions.LocationMode = LocationMode.SecondaryOnly;
TestHelper.VerifyServiceStats(await client.GetServiceStatsAsync());
}
[TestMethod]
[Description("Server timeout query parameter")]
[TestCategory(ComponentCategory.Blob)]
[TestCategory(TestTypeCategory.UnitTest)]
[TestCategory(SmokeTestCategory.NonSmoke)]
[TestCategory(TenantTypeCategory.DevStore), TestCategory(TenantTypeCategory.DevFabric), TestCategory(TenantTypeCategory.Cloud)]
public async Task CloudBlobClientServerTimeoutAsync()
{
CloudBlobClient client = GenerateCloudBlobClient();
string timeout = null;
OperationContext context = new OperationContext();
context.SendingRequest += (sender, e) =>
{
IDictionary<string, string> query = HttpWebUtility.ParseQueryString(e.RequestUri.Query);
if (!query.TryGetValue("timeout", out timeout))
{
timeout = null;
}
};
BlobRequestOptions options = new BlobRequestOptions();
await client.GetServicePropertiesAsync(null, context);
Assert.IsNull(timeout);
await client.GetServicePropertiesAsync(options, context);
Assert.IsNull(timeout);
options.ServerTimeout = TimeSpan.FromSeconds(100);
await client.GetServicePropertiesAsync(options, context);
Assert.AreEqual("100", timeout);
client.DefaultRequestOptions.ServerTimeout = TimeSpan.FromSeconds(90);
await client.GetServicePropertiesAsync(null, context);
Assert.AreEqual("90", timeout);
await client.GetServicePropertiesAsync(options, context);
Assert.AreEqual("100", timeout);
options.ServerTimeout = null;
await client.GetServicePropertiesAsync(options, context);
Assert.AreEqual("90", timeout);
options.ServerTimeout = TimeSpan.Zero;
await client.GetServicePropertiesAsync(options, context);
Assert.IsNull(timeout);
}
}
}
| 44.365348 | 220 | 0.591901 |
[
"Apache-2.0"
] |
SaschaDittmann/azure-storage-net
|
Test/WindowsRuntime/Blob/CloudBlobClientTest.cs
| 23,560 |
C#
|
#if UNITY_EDITOR
using System.Collections;
using ModestTree;
using UnityEngine.TestTools;
#pragma warning disable 219
namespace Zenject.Tests.Bindings
{
public class TestMemoryPool1 : ZenjectIntegrationTestFixture
{
[UnityTest]
public IEnumerator TestFactoryProperties()
{
PreInstall();
Container.BindMemoryPool<Foo, Foo.Pool>();
PostInstall();
var pool = Container.Resolve<Foo.Pool>();
Assert.IsEqual(pool.NumActive, 0);
Assert.IsEqual(pool.NumTotal, 0);
Assert.IsEqual(pool.NumInactive, 0);
var foo = pool.Spawn("asdf");
Assert.IsEqual(pool.NumActive, 1);
Assert.IsEqual(pool.NumTotal, 1);
Assert.IsEqual(pool.NumInactive, 0);
Assert.IsEqual(foo.ResetCount, 1);
Assert.IsEqual(foo.Value, "asdf");
pool.Despawn(foo);
Assert.IsEqual(pool.NumActive, 0);
Assert.IsEqual(pool.NumTotal, 1);
Assert.IsEqual(pool.NumInactive, 1);
Assert.IsEqual(foo.ResetCount, 1);
foo = pool.Spawn("zxcv");
Assert.IsEqual(pool.NumActive, 1);
Assert.IsEqual(pool.NumTotal, 1);
Assert.IsEqual(pool.NumInactive, 0);
Assert.IsEqual(foo.ResetCount, 2);
Assert.IsEqual(foo.Value, "zxcv");
var foo2 = pool.Spawn("qwer");
Assert.IsEqual(pool.NumActive, 2);
Assert.IsEqual(pool.NumTotal, 2);
Assert.IsEqual(pool.NumInactive, 0);
Assert.IsEqual(foo2.ResetCount, 1);
Assert.IsEqual(foo2.Value, "qwer");
pool.Despawn(foo);
Assert.IsEqual(pool.NumActive, 1);
Assert.IsEqual(pool.NumTotal, 2);
Assert.IsEqual(pool.NumInactive, 1);
Assert.IsEqual(foo.ResetCount, 2);
pool.Despawn(foo2);
Assert.IsEqual(pool.NumActive, 0);
Assert.IsEqual(pool.NumTotal, 2);
Assert.IsEqual(pool.NumInactive, 2);
pool.Spawn("zxcv");
pool.Spawn("bxzc");
pool.Spawn("bxzc");
Assert.IsEqual(pool.NumActive, 3);
Assert.IsEqual(pool.NumTotal, 3);
Assert.IsEqual(pool.NumInactive, 0);
yield break;
}
class Foo
{
public string Value
{
get;
private set;
}
public int ResetCount
{
get; private set;
}
public class Pool : MemoryPool<string, Foo>
{
protected override void Reinitialize(string value, Foo foo)
{
foo.Value = value;
foo.ResetCount++;
}
}
}
[UnityTest]
public IEnumerator TestAbstractMemoryPoolValidate()
{
TestAbstractMemoryPoolInternal();
yield break;
}
[UnityTest]
public IEnumerator TestAbstractMemoryPool()
{
TestAbstractMemoryPoolInternal();
var pool = Container.Resolve<BarPool>();
var foo = pool.Spawn(5);
Assert.IsEqual(foo.GetType(), typeof(Bar));
yield break;
}
void TestAbstractMemoryPoolInternal()
{
PreInstall();
Container.BindMemoryPool<IBar, BarPool>()
.WithInitialSize(3).To<Bar>().NonLazy();
PostInstall();
}
public interface IBar
{
}
public class Bar : IBar
{
}
public class BarPool : MemoryPool<int, IBar>
{
}
}
}
#endif
| 25.540541 | 75 | 0.519841 |
[
"MIT"
] |
NRatel/Zenject
|
UnityProject/Assets/Plugins/Zenject/OptionalExtras/IntegrationTests/Tests/Factories/TestMemoryPools/TestMemoryPool1.cs
| 3,780 |
C#
|
/*
* Copyright (c) 2021 Samsung Electronics Co., Ltd. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using System;
using System.Globalization;
namespace Weather.Utils
{
/// <summary>
/// Class that provide custom formatter for string.
/// </summary>
public class UnitFormatter : IFormatProvider, ICustomFormatter
{
#region methods
/// <summary>
/// Gets an object that provides formatting services for the specified type.
/// </summary>
/// <param name="formatType">An object that specifies the type of format object to return.</param>
/// <returns>An instance of the object specified by formatType.</returns>
public object GetFormat(Type formatType)
{
return formatType == typeof(ICustomFormatter) ? this : null;
}
/// <summary>
/// Converts the value of a specified object to an equivalent string representation.
/// </summary>
/// <param name="fmt">A format string containing formatting specifications.</param>
/// <param name="arg">An object to format.</param>
/// <param name="formatProvider">An object that supplies format information about the current instance.</param>
/// <returns>
/// The string representation of the arg, formatted as specified by format and formatProvider.
/// </returns>
public string Format(string fmt, object arg, IFormatProvider formatProvider)
{
if (arg == null)
{
return string.Empty;
}
switch (fmt)
{
case "temp":
{
var sign = RegionInfo.CurrentRegion.IsMetric ? "°C" : "°F";
return $"{arg:0.0}{sign}";
}
case "speed":
{
var sign = RegionInfo.CurrentRegion.IsMetric ? " m/s" : " mph";
return $"{arg:0.00}{sign}";
}
default:
{
return arg.ToString();
}
}
}
#endregion
}
}
| 34.5 | 119 | 0.577852 |
[
"Apache-2.0"
] |
abhimanyu1dots/Tizen-CSharp-Samples
|
Mobile/Xamarin.Forms/Weather/Weather/Weather/Utils/UnitFormatter.cs
| 2,695 |
C#
|
namespace PublicApi.Areas.HelpPage.ModelDescriptions
{
public class KeyValuePairModelDescription : ModelDescription
{
public ModelDescription KeyModelDescription { get; set; }
public ModelDescription ValueModelDescription { get; set; }
}
}
| 29.777778 | 67 | 0.742537 |
[
"Apache-2.0"
] |
AnalogIO/Analog-ShiftPlanner
|
API/PublicApi/Areas/HelpPage/ModelDescriptions/KeyValuePairModelDescription.cs
| 268 |
C#
|
using System;
namespace cs_smallpt {
static class SmallPT {
static void Main(string[] args) {
RNG rng = new RNG();
int nb_samples = (args.Length > 0) ? int.Parse(args[0]) / 4 : 1;
const int w = 1024;
const int h = 768;
Vector3 eye = new Vector3(50, 52, 295.6);
Vector3 gaze = new Vector3(0, -0.042612, -1).Normalize();
const double fov = 0.5135;
Vector3 cx = new Vector3(w * fov / h, 0.0, 0.0);
Vector3 cy = (cx.Cross(gaze)).Normalize() * fov;
Vector3[] Ls = new Vector3[w * h];
for (int i = 0; i < w * h; ++i) {
Ls[i] = new Vector3();
}
for (int y = 0; y < h; ++y) {
// pixel row
Console.Write("\rRendering ({0} spp) {1:0.00}%", nb_samples * 4, 100.0 * y / (h - 1));
for (int x = 0; x < w; ++x) {
// pixel column
for (int sy = 0, i = (h - 1 - y) * w + x; sy < 2; ++sy) {
// 2 subpixel row
for (int sx = 0; sx < 2; ++sx) {
// 2 subpixel column
Vector3 L = new Vector3();
for (int s = 0; s < nb_samples; ++s) {
// samples per subpixel
double u1 = 2.0 * rng.UniformFloat();
double u2 = 2.0 * rng.UniformFloat();
double dx = u1 < 1 ? Math.Sqrt(u1) - 1.0 : 1.0 - Math.Sqrt(2.0 - u1);
double dy = u2 < 1 ? Math.Sqrt(u2) - 1.0 : 1.0 - Math.Sqrt(2.0 - u2);
Vector3 d = cx * (((sx + 0.5 + dx) / 2 + x) / w - 0.5) +
cy * (((sy + 0.5 + dy) / 2 + y) / h - 0.5) + gaze;
L += Radiance(new Ray(eye + d * 130, d.Normalize(), Sphere.EPSILON_SPHERE), rng) * (1.0 / nb_samples);
}
Ls[i] += 0.25 * Vector3.Clamp(L);
}
}
}
}
ImageIO.WritePPM(w, h, Ls);
}
// Scene
public const double REFRACTIVE_INDEX_OUT = 1.0;
public const double REFRACTIVE_INDEX_IN = 1.5;
public static readonly Sphere[] spheres =
{
new Sphere(1e5, new Vector3(1e5 + 1, 40.8, 81.6), new Vector3(), new Vector3(0.75,0.25,0.25), Sphere.Reflection_t.DIFFUSE), //Left
new Sphere(1e5, new Vector3(-1e5 + 99, 40.8, 81.6), new Vector3(), new Vector3(0.25,0.25,0.75), Sphere.Reflection_t.DIFFUSE), //Right
new Sphere(1e5, new Vector3(50, 40.8, 1e5), new Vector3(), new Vector3(0.75), Sphere.Reflection_t.DIFFUSE), //Back
new Sphere(1e5, new Vector3(50, 40.8, -1e5 + 170), new Vector3(), new Vector3(), Sphere.Reflection_t.DIFFUSE), //Front
new Sphere(1e5, new Vector3(50, 1e5, 81.6), new Vector3(), new Vector3(0.75), Sphere.Reflection_t.DIFFUSE), //Bottom
new Sphere(1e5, new Vector3(50, -1e5 + 81.6, 81.6), new Vector3(), new Vector3(0.75), Sphere.Reflection_t.DIFFUSE), //Top
new Sphere(16.5, new Vector3(27, 16.5, 47), new Vector3(), new Vector3(0.999), Sphere.Reflection_t.SPECULAR), //Mirror
new Sphere(16.5, new Vector3(73, 16.5, 78), new Vector3(), new Vector3(0.999), Sphere.Reflection_t.REFRACTIVE), //Glass
new Sphere(600, new Vector3(50, 681.6 - .27, 81.6), new Vector3(12), new Vector3(), Sphere.Reflection_t.DIFFUSE) //Light
};
public static bool Intersect(Ray ray, out int id) {
id = 0;
bool hit = false;
for (int i = 0; i < spheres.Length; ++i) {
if (spheres[i].Intersect(ray)) {
hit = true;
id = i;
}
}
return hit;
}
public static bool Intersect(Ray ray) {
for (int i = 0; i < spheres.Length; ++i) {
if (spheres[i].Intersect(ray)) {
return true;
}
}
return false;
}
public static Vector3 Radiance(Ray ray, RNG rng) {
Ray r = ray;
Vector3 L = new Vector3();
Vector3 F = new Vector3(1.0);
while (true) {
if (!Intersect(r, out int id)) {
return L;
}
Sphere shape = spheres[id];
Vector3 p = r.Eval(r.tmax);
Vector3 n = (p - shape.p).Normalize();
L += F * shape.e;
F *= shape.f;
// Russian roulette
if (r.depth > 4) {
double continue_probability = shape.f.Max();
if (rng.UniformFloat() >= continue_probability) {
return L;
}
F /= continue_probability;
}
// Next path segment
switch (shape.reflection_t) {
case Sphere.Reflection_t.SPECULAR: {
Vector3 d = Specular.IdealSpecularReflect(r.d, n);
r = new Ray(p, d, Sphere.EPSILON_SPHERE, double.PositiveInfinity, r.depth + 1);
break;
}
case Sphere.Reflection_t.REFRACTIVE: {
Vector3 d = Specular.IdealSpecularTransmit(r.d, n, REFRACTIVE_INDEX_OUT, REFRACTIVE_INDEX_IN, out double pr, rng);
F *= pr;
r = new Ray(p, d, Sphere.EPSILON_SPHERE, double.PositiveInfinity, r.depth + 1);
break;
}
default: {
Vector3 w = n.Dot(r.d) < 0 ? n : -n;
Vector3 u = ((Math.Abs(w.x) > 0.1 ? new Vector3(0.0, 1.0, 0.0) : new Vector3(1.0, 0.0, 0.0)).Cross(w)).Normalize();
Vector3 v = w.Cross(u);
Vector3 sample_d = Sampling.CosineWeightedSampleOnHemisphere(rng.UniformFloat(), rng.UniformFloat());
Vector3 d = (sample_d.x * u + sample_d.y * v + sample_d.z * w).Normalize();
r = new Ray(p, d, Sphere.EPSILON_SPHERE, double.PositiveInfinity, r.depth + 1);
break;
}
}
}
}
}
}
| 35.321918 | 143 | 0.561567 |
[
"MIT"
] |
matt77hias/cs-smallpt
|
cs-smallpt/core/SmallPT.cs
| 5,157 |
C#
|
using OpenParser.Enums;
namespace OpenParser.EventResults.Chat
{
public class Say : ChatMessage
{
public Say(LogEntry entry, SayOrigins origin, string from, string message) : base(entry, from, message)
{
Origin = origin;
}
public SayOrigins Origin { get; }
}
}
| 22.785714 | 111 | 0.62069 |
[
"MIT"
] |
thesmallbang/EverquestOpenParser
|
OpenParser/EventResults/Chat/Say.cs
| 321 |
C#
|
namespace Merchello.Web.Models.ContentEditing
{
using System;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using Merchello.Core;
using Merchello.Core.Configuration;
using Merchello.Core.Models;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
/// <summary>
/// The address display.
/// </summary>
public class AddressDisplay
{
/// <summary>
/// Gets or sets the name.
/// </summary>
public string Name { get; set; }
/// <summary>
/// Gets or sets the address 1.
/// </summary>
public string Address1 { get; set; }
/// <summary>
/// Gets or sets the address 2.
/// </summary>
public string Address2 { get; set; }
/// <summary>
/// Gets or sets the locality.
/// </summary>
public string Locality { get; set; }
/// <summary>
/// Gets or sets the region.
/// </summary>
public string Region { get; set; }
/// <summary>
/// Gets or sets the postal code.
/// </summary>
public string PostalCode { get; set; }
/// <summary>
/// Gets or sets the country code.
/// </summary>
public string CountryCode { get; set; }
/// <summary>
/// Gets or sets the country name
/// </summary>
public string CountryName { get; set; }
/// <summary>
/// Gets or sets the phone.
/// </summary>
public string Phone { get; set; }
/// <summary>
/// Gets or sets the email.
/// </summary>
public string Email { get; set; }
/// <summary>
/// Gets or sets the organization.
/// </summary>
public string Organization { get; set; }
/// <summary>
/// Gets or sets a value indicating whether the address is a commercial address.
/// </summary>
public bool IsCommercial { get; set; }
/// <summary>
/// Gets or sets the address type.
/// </summary>
[JsonConverter(typeof(StringEnumConverter))]
public AddressType AddressType { get; set; }
}
/// <summary>
/// Mapping extensions for <see cref="AddressDisplay"/>
/// </summary>
[SuppressMessage("StyleCop.CSharp.MaintainabilityRules", "SA1402:FileMayOnlyContainASingleClass", Justification = "Reviewed. Suppression is OK here.")]
internal static class AddressDetailsMappingExtensions
{
/// <summary>
/// Maps <see cref="IAddress"/> to <see cref="AddressDisplay"/>
/// </summary>
/// <param name="address">
/// The address.
/// </param>
/// <returns>
/// The <see cref="AddressDisplay"/>.
/// </returns>
internal static AddressDisplay ToAddressDisplay(this IAddress address)
{
var mappedAddress = AutoMapper.Mapper.Map<AddressDisplay>(address);
var country = MerchelloConfiguration.Current.MerchelloCountries().Countries.FirstOrDefault(x => x.CountryCode.Equals(mappedAddress.CountryCode, StringComparison.InvariantCultureIgnoreCase));
if (country != null)
{
mappedAddress.CountryName = country.Name;
}
return mappedAddress;
}
/// <summary>
/// Maps <see cref="AddressDisplay"/> to <see cref="IAddress"/>
/// </summary>
/// <param name="addressDisplay">
/// The address display.
/// </param>
/// <returns>
/// The <see cref="IAddress"/>.
/// </returns>
internal static IAddress ToAddress(this AddressDisplay addressDisplay)
{
return AutoMapper.Mapper.Map<Address>(addressDisplay);
}
}
}
| 30.664 | 202 | 0.551004 |
[
"MIT"
] |
HiteshMah-Jan/Merchello
|
src/Merchello.Web/Models/ContentEditing/AddressDisplay.cs
| 3,835 |
C#
|
#pragma checksum "C:\Users\Rolando\Desktop\BTCPAY\banexcoinpay-master-github\banexcoinpay\BTCPayServer\Views\PaymentRequest\MinimalPaymentRequest.cshtml" "{ff1816ec-aa5e-4d10-87f7-6f4963833460}" "cdc7b697e4134cfd8799dac319b13b54d2dde5b1"
// <auto-generated/>
#pragma warning disable 1591
[assembly: global::Microsoft.AspNetCore.Razor.Hosting.RazorCompiledItemAttribute(typeof(AspNetCore.Views_PaymentRequest_MinimalPaymentRequest), @"mvc.1.0.view", @"/Views/PaymentRequest/MinimalPaymentRequest.cshtml")]
[assembly:global::Microsoft.AspNetCore.Mvc.Razor.Compilation.RazorViewAttribute(@"/Views/PaymentRequest/MinimalPaymentRequest.cshtml", typeof(AspNetCore.Views_PaymentRequest_MinimalPaymentRequest))]
namespace AspNetCore
{
#line hidden
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Rendering;
using Microsoft.AspNetCore.Mvc.ViewFeatures;
#line 1 "C:\Users\Rolando\Desktop\BTCPAY\banexcoinpay-master-github\banexcoinpay\BTCPayServer\Views\_ViewImports.cshtml"
using Microsoft.AspNetCore.Identity;
#line default
#line hidden
#line 2 "C:\Users\Rolando\Desktop\BTCPAY\banexcoinpay-master-github\banexcoinpay\BTCPayServer\Views\_ViewImports.cshtml"
using BTCPayServer;
#line default
#line hidden
#line 3 "C:\Users\Rolando\Desktop\BTCPAY\banexcoinpay-master-github\banexcoinpay\BTCPayServer\Views\_ViewImports.cshtml"
using BTCPayServer.Views;
#line default
#line hidden
#line 4 "C:\Users\Rolando\Desktop\BTCPAY\banexcoinpay-master-github\banexcoinpay\BTCPayServer\Views\_ViewImports.cshtml"
using BTCPayServer.Models;
#line default
#line hidden
#line 5 "C:\Users\Rolando\Desktop\BTCPAY\banexcoinpay-master-github\banexcoinpay\BTCPayServer\Views\_ViewImports.cshtml"
using BTCPayServer.Models.AccountViewModels;
#line default
#line hidden
#line 6 "C:\Users\Rolando\Desktop\BTCPAY\banexcoinpay-master-github\banexcoinpay\BTCPayServer\Views\_ViewImports.cshtml"
using BTCPayServer.Models.InvoicingModels;
#line default
#line hidden
#line 7 "C:\Users\Rolando\Desktop\BTCPAY\banexcoinpay-master-github\banexcoinpay\BTCPayServer\Views\_ViewImports.cshtml"
using BTCPayServer.Models.ManageViewModels;
#line default
#line hidden
#line 8 "C:\Users\Rolando\Desktop\BTCPAY\banexcoinpay-master-github\banexcoinpay\BTCPayServer\Views\_ViewImports.cshtml"
using BTCPayServer.Models.StoreViewModels;
#line default
#line hidden
[global::Microsoft.AspNetCore.Razor.Hosting.RazorSourceChecksumAttribute(@"SHA1", @"cdc7b697e4134cfd8799dac319b13b54d2dde5b1", @"/Views/PaymentRequest/MinimalPaymentRequest.cshtml")]
[global::Microsoft.AspNetCore.Razor.Hosting.RazorSourceChecksumAttribute(@"SHA1", @"ded28c9c4aa4680a79c38bc0250cd2d03019ed1b", @"/Views/_ViewImports.cshtml")]
public class Views_PaymentRequest_MinimalPaymentRequest : global::Microsoft.AspNetCore.Mvc.Razor.RazorPage<BTCPayServer.Models.PaymentRequestViewModels.ViewPaymentRequestViewModel>
{
private static readonly global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute __tagHelperAttribute_0 = new global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute("method", "get", global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes);
private static readonly global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute __tagHelperAttribute_1 = new global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute("asp-action", "PayPaymentRequest", global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes);
private static readonly global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute __tagHelperAttribute_2 = new global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute("class", new global::Microsoft.AspNetCore.Html.HtmlString("btn btn-primary btn-lg d-print-none mt-1"), global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes);
private static readonly global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute __tagHelperAttribute_3 = new global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute("asp-action", "CancelUnpaidPendingInvoice", global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes);
#line hidden
#pragma warning disable 0169
private string __tagHelperStringValueBuffer;
#pragma warning restore 0169
private global::Microsoft.AspNetCore.Razor.Runtime.TagHelpers.TagHelperExecutionContext __tagHelperExecutionContext;
private global::Microsoft.AspNetCore.Razor.Runtime.TagHelpers.TagHelperRunner __tagHelperRunner = new global::Microsoft.AspNetCore.Razor.Runtime.TagHelpers.TagHelperRunner();
private global::Microsoft.AspNetCore.Razor.Runtime.TagHelpers.TagHelperScopeManager __backed__tagHelperScopeManager = null;
private global::Microsoft.AspNetCore.Razor.Runtime.TagHelpers.TagHelperScopeManager __tagHelperScopeManager
{
get
{
if (__backed__tagHelperScopeManager == null)
{
__backed__tagHelperScopeManager = new global::Microsoft.AspNetCore.Razor.Runtime.TagHelpers.TagHelperScopeManager(StartTagHelperWritingScope, EndTagHelperWritingScope);
}
return __backed__tagHelperScopeManager;
}
}
private global::Microsoft.AspNetCore.Mvc.TagHelpers.FormTagHelper __Microsoft_AspNetCore_Mvc_TagHelpers_FormTagHelper;
private global::Microsoft.AspNetCore.Mvc.TagHelpers.RenderAtEndOfFormTagHelper __Microsoft_AspNetCore_Mvc_TagHelpers_RenderAtEndOfFormTagHelper;
private global::Microsoft.AspNetCore.Mvc.TagHelpers.AnchorTagHelper __Microsoft_AspNetCore_Mvc_TagHelpers_AnchorTagHelper;
#pragma warning disable 1998
public async override global::System.Threading.Tasks.Task ExecuteAsync()
{
BeginContext(81, 225, true);
WriteLiteral("\r\n<div class=\"container\">\r\n <div class=\"row w-100 p-0 m-0\" style=\"height: 100vh\">\r\n <div class=\"mx-auto my-auto w-100\">\r\n <div class=\"card\">\r\n <h1 class=\"card-header\">\r\n ");
EndContext();
BeginContext(307, 11, false);
#line 8 "C:\Users\Rolando\Desktop\BTCPAY\banexcoinpay-master-github\banexcoinpay\BTCPayServer\Views\PaymentRequest\MinimalPaymentRequest.cshtml"
Write(Model.Title);
#line default
#line hidden
EndContext();
BeginContext(318, 71, true);
WriteLiteral("\r\n <span class=\"text-muted float-right text-center\">");
EndContext();
BeginContext(390, 12, false);
#line 9 "C:\Users\Rolando\Desktop\BTCPAY\banexcoinpay-master-github\banexcoinpay\BTCPayServer\Views\PaymentRequest\MinimalPaymentRequest.cshtml"
Write(Model.Status);
#line default
#line hidden
EndContext();
BeginContext(402, 575, true);
WriteLiteral(@"</span>
</h1>
<div class=""card-body px-0 pt-0"">
<div class=""row mb-4"">
<div class=""col-sm-12 col-md-12 col-lg-6 "">
<ul class=""w-100 list-group list-group-flush"">
<li class=""list-group-item"">
<div class=""d-flex justify-content-between"">
<span class=""h2 text-muted"">Cantidad de la solicitud:</span>
<span class=""h2"">");
EndContext();
BeginContext(978, 21, false);
#line 18 "C:\Users\Rolando\Desktop\BTCPAY\banexcoinpay-master-github\banexcoinpay\BTCPayServer\Views\PaymentRequest\MinimalPaymentRequest.cshtml"
Write(Model.AmountFormatted);
#line default
#line hidden
EndContext();
BeginContext(999, 389, true);
WriteLiteral(@"</span>
</div>
</li>
<li class=""list-group-item"">
<div class=""d-flex justify-content-between"">
<span class=""h2 text-muted"">Pagado hasta ahora:</span>
<span class=""h2"">");
EndContext();
BeginContext(1389, 30, false);
#line 24 "C:\Users\Rolando\Desktop\BTCPAY\banexcoinpay-master-github\banexcoinpay\BTCPayServer\Views\PaymentRequest\MinimalPaymentRequest.cshtml"
Write(Model.AmountCollectedFormatted);
#line default
#line hidden
EndContext();
BeginContext(1419, 386, true);
WriteLiteral(@"</span>
</div>
</li>
<li class=""list-group-item"">
<div class=""d-flex justify-content-between"">
<span class=""h2 text-muted"">Cantidad debida:</span>
<span class=""h2"">");
EndContext();
BeginContext(1806, 24, false);
#line 30 "C:\Users\Rolando\Desktop\BTCPAY\banexcoinpay-master-github\banexcoinpay\BTCPayServer\Views\PaymentRequest\MinimalPaymentRequest.cshtml"
Write(Model.AmountDueFormatted);
#line default
#line hidden
EndContext();
BeginContext(1830, 178, true);
WriteLiteral("</span>\r\n </div>\r\n </li>\r\n </ul>\r\n <div class=\"w-100 p-2\">");
EndContext();
BeginContext(2009, 27, false);
#line 34 "C:\Users\Rolando\Desktop\BTCPAY\banexcoinpay-master-github\banexcoinpay\BTCPayServer\Views\PaymentRequest\MinimalPaymentRequest.cshtml"
Write(Html.Raw(Model.Description));
#line default
#line hidden
EndContext();
BeginContext(2036, 796, true);
WriteLiteral(@"</div>
</div>
<div class=""col-sm-12 col-md-12 col-lg-6"">
<div class=""table-responsive"">
<table class=""table border-top-0 "">
<thead>
<tr>
<th class="" border-top-0"" scope=""col"">Factura #</th>
<th class="" border-top-0"">Precio</th>
<th class="" border-top-0"">Expiración</th>
<th class="" border-top-0"">Estado</th>
</tr>
</thead>
<tbody>
");
EndContext();
#line 49 "C:\Users\Rolando\Desktop\BTCPAY\banexcoinpay-master-github\banexcoinpay\BTCPayServer\Views\PaymentRequest\MinimalPaymentRequest.cshtml"
if (Model.Invoices == null && !Model.Invoices.Any())
{
#line default
#line hidden
BeginContext(2962, 210, true);
WriteLiteral(" <tr>\r\n <td colspan=\"4\" class=\"text-center\">Aún no se han efectuado pagos.</td>\r\n </tr>\r\n");
EndContext();
#line 54 "C:\Users\Rolando\Desktop\BTCPAY\banexcoinpay-master-github\banexcoinpay\BTCPayServer\Views\PaymentRequest\MinimalPaymentRequest.cshtml"
}
else
{
foreach (var invoice in Model.Invoices)
{
#line default
#line hidden
BeginContext(3416, 131, true);
WriteLiteral(" <tr class=\"bg-light\">\r\n <td scope=\"row\">");
EndContext();
BeginContext(3548, 10, false);
#line 60 "C:\Users\Rolando\Desktop\BTCPAY\banexcoinpay-master-github\banexcoinpay\BTCPayServer\Views\PaymentRequest\MinimalPaymentRequest.cshtml"
Write(invoice.Id);
#line default
#line hidden
EndContext();
BeginContext(3558, 59, true);
WriteLiteral("</td>\r\n <td>");
EndContext();
BeginContext(3618, 14, false);
#line 61 "C:\Users\Rolando\Desktop\BTCPAY\banexcoinpay-master-github\banexcoinpay\BTCPayServer\Views\PaymentRequest\MinimalPaymentRequest.cshtml"
Write(invoice.Amount);
#line default
#line hidden
EndContext();
BeginContext(3632, 1, true);
WriteLiteral(" ");
EndContext();
BeginContext(3634, 16, false);
#line 61 "C:\Users\Rolando\Desktop\BTCPAY\banexcoinpay-master-github\banexcoinpay\BTCPayServer\Views\PaymentRequest\MinimalPaymentRequest.cshtml"
Write(invoice.Currency);
#line default
#line hidden
EndContext();
BeginContext(3650, 59, true);
WriteLiteral("</td>\r\n <td>");
EndContext();
BeginContext(3710, 32, false);
#line 62 "C:\Users\Rolando\Desktop\BTCPAY\banexcoinpay-master-github\banexcoinpay\BTCPayServer\Views\PaymentRequest\MinimalPaymentRequest.cshtml"
Write(invoice.ExpiryDate.ToString("g"));
#line default
#line hidden
EndContext();
BeginContext(3742, 59, true);
WriteLiteral("</td>\r\n <td>");
EndContext();
BeginContext(3802, 14, false);
#line 63 "C:\Users\Rolando\Desktop\BTCPAY\banexcoinpay-master-github\banexcoinpay\BTCPayServer\Views\PaymentRequest\MinimalPaymentRequest.cshtml"
Write(invoice.Status);
#line default
#line hidden
EndContext();
BeginContext(3816, 58, true);
WriteLiteral("</td>\r\n </tr>\r\n");
EndContext();
#line 65 "C:\Users\Rolando\Desktop\BTCPAY\banexcoinpay-master-github\banexcoinpay\BTCPayServer\Views\PaymentRequest\MinimalPaymentRequest.cshtml"
if (invoice.Payments != null && invoice.Payments.Any())
{
#line default
#line hidden
BeginContext(4022, 922, true);
WriteLiteral(@" <tr class=""bg-light"">
<td colspan=""4"" class="" px-2 py-1 border-top-0"">
<div class=""table-responsive"">
<table class=""table table-bordered"">
<tr>
<th class=""p-1"" style=""max-width: 300px"">Tx Id</th>
<th class=""p-1"">Método de pago</th>
<th class=""p-1"">Cantidad</th>
<th class=""p-1"">Link</th>
</tr>
");
EndContext();
#line 78 "C:\Users\Rolando\Desktop\BTCPAY\banexcoinpay-master-github\banexcoinpay\BTCPayServer\Views\PaymentRequest\MinimalPaymentRequest.cshtml"
foreach (var payment in invoice.Payments)
{
#line default
#line hidden
BeginContext(5119, 373, true);
WriteLiteral(@" <tr class=""d-flex"">
<td class=""p-1 m-0 d-print-none d-block"" style=""max-width: 300px"">
<div style=""width: 100%; overflow-x: auto; overflow-wrap: initial;"">");
EndContext();
BeginContext(5493, 10, false);
#line 82 "C:\Users\Rolando\Desktop\BTCPAY\banexcoinpay-master-github\banexcoinpay\BTCPayServer\Views\PaymentRequest\MinimalPaymentRequest.cshtml"
Write(payment.Id);
#line default
#line hidden
EndContext();
BeginContext(5503, 309, true);
WriteLiteral(@"</div>
</td>
<td class=""p-1 m-0 d-none d-print-table-cell"" style=""max-width: 150px;"">
");
EndContext();
BeginContext(5813, 10, false);
#line 85 "C:\Users\Rolando\Desktop\BTCPAY\banexcoinpay-master-github\banexcoinpay\BTCPayServer\Views\PaymentRequest\MinimalPaymentRequest.cshtml"
Write(payment.Id);
#line default
#line hidden
EndContext();
BeginContext(5823, 169, true);
WriteLiteral("\r\n </td>\r\n <td class=\"p-1\">");
EndContext();
BeginContext(5993, 21, false);
#line 87 "C:\Users\Rolando\Desktop\BTCPAY\banexcoinpay-master-github\banexcoinpay\BTCPayServer\Views\PaymentRequest\MinimalPaymentRequest.cshtml"
Write(payment.PaymentMethod);
#line default
#line hidden
EndContext();
BeginContext(6014, 95, true);
WriteLiteral("</td>\r\n <td class=\"p-1\">");
EndContext();
BeginContext(6110, 14, false);
#line 88 "C:\Users\Rolando\Desktop\BTCPAY\banexcoinpay-master-github\banexcoinpay\BTCPayServer\Views\PaymentRequest\MinimalPaymentRequest.cshtml"
Write(payment.Amount);
#line default
#line hidden
EndContext();
BeginContext(6124, 110, true);
WriteLiteral("</td>\r\n <td class=\"p-1 d-print-none\">\r\n");
EndContext();
#line 90 "C:\Users\Rolando\Desktop\BTCPAY\banexcoinpay-master-github\banexcoinpay\BTCPayServer\Views\PaymentRequest\MinimalPaymentRequest.cshtml"
if (!string.IsNullOrEmpty(payment.Link))
{
#line default
#line hidden
BeginContext(6432, 82, true);
WriteLiteral(" <a");
EndContext();
BeginWriteAttribute(":href", " :href=\"", 6514, "\"", 6535, 1);
#line 92 "C:\Users\Rolando\Desktop\BTCPAY\banexcoinpay-master-github\banexcoinpay\BTCPayServer\Views\PaymentRequest\MinimalPaymentRequest.cshtml"
WriteAttributeValue("", 6522, payment.Link, 6522, 13, false);
#line default
#line hidden
EndWriteAttribute();
BeginContext(6536, 27, true);
WriteLiteral(" target=\"_blank\">Link</a>\r\n");
EndContext();
#line 93 "C:\Users\Rolando\Desktop\BTCPAY\banexcoinpay-master-github\banexcoinpay\BTCPayServer\Views\PaymentRequest\MinimalPaymentRequest.cshtml"
}
#line default
#line hidden
BeginContext(6642, 297, true);
WriteLiteral(@" </td>
<td class=""p-1 d-none d-print-table-cell"" style=""max-width: 150px;"">
");
EndContext();
BeginContext(6940, 12, false);
#line 96 "C:\Users\Rolando\Desktop\BTCPAY\banexcoinpay-master-github\banexcoinpay\BTCPayServer\Views\PaymentRequest\MinimalPaymentRequest.cshtml"
Write(payment.Link);
#line default
#line hidden
EndContext();
BeginContext(6952, 156, true);
WriteLiteral("\r\n </td>\r\n </tr>\r\n");
EndContext();
#line 99 "C:\Users\Rolando\Desktop\BTCPAY\banexcoinpay-master-github\banexcoinpay\BTCPayServer\Views\PaymentRequest\MinimalPaymentRequest.cshtml"
}
#line default
#line hidden
BeginContext(7175, 248, true);
WriteLiteral(" </table>\r\n </div>\r\n </td>\r\n </tr>\r\n");
EndContext();
#line 104 "C:\Users\Rolando\Desktop\BTCPAY\banexcoinpay-master-github\banexcoinpay\BTCPayServer\Views\PaymentRequest\MinimalPaymentRequest.cshtml"
}
}
}
#line default
#line hidden
BeginContext(7552, 36, true);
WriteLiteral(" ");
EndContext();
#line 107 "C:\Users\Rolando\Desktop\BTCPAY\banexcoinpay-master-github\banexcoinpay\BTCPayServer\Views\PaymentRequest\MinimalPaymentRequest.cshtml"
if (Model.IsPending)
{
#line default
#line hidden
BeginContext(7650, 128, true);
WriteLiteral(" <tr>\r\n <td colspan=\"4\" class=\"text-center\">\r\n");
EndContext();
#line 111 "C:\Users\Rolando\Desktop\BTCPAY\banexcoinpay-master-github\banexcoinpay\BTCPayServer\Views\PaymentRequest\MinimalPaymentRequest.cshtml"
if (Model.AllowCustomPaymentAmounts && !Model.AnyPendingInvoice)
{
#line default
#line hidden
BeginContext(7944, 52, true);
WriteLiteral(" ");
EndContext();
BeginContext(7996, 1720, false);
__tagHelperExecutionContext = __tagHelperScopeManager.Begin("form", global::Microsoft.AspNetCore.Razor.TagHelpers.TagMode.StartTagAndEndTag, "ebdcb0d669fc47bcb62dd4560c463fb4", async() => {
BeginContext(8046, 429, true);
WriteLiteral(@"
<div class=""input-group m-auto"" style=""max-width: 250px"">
<input
class=""form-control""
type=""number""
name=""amount""");
EndContext();
BeginWriteAttribute("value", "\r\n\r\n value=\"", 8475, "\"", 8566, 1);
#line 121 "C:\Users\Rolando\Desktop\BTCPAY\banexcoinpay-master-github\banexcoinpay\BTCPayServer\Views\PaymentRequest\MinimalPaymentRequest.cshtml"
WriteAttributeValue("", 8550, Model.AmountDue, 8550, 16, false);
#line default
#line hidden
EndWriteAttribute();
BeginWriteAttribute("max", "\r\n max=\"", 8567, "\"", 8654, 1);
#line 122 "C:\Users\Rolando\Desktop\BTCPAY\banexcoinpay-master-github\banexcoinpay\BTCPayServer\Views\PaymentRequest\MinimalPaymentRequest.cshtml"
WriteAttributeValue("", 8638, Model.AmountDue, 8638, 16, false);
#line default
#line hidden
EndWriteAttribute();
BeginContext(8655, 430, true);
WriteLiteral(@"
step=""any""
placeholder=""Cantidad""
required>
<div class=""input-group-append"">
<span class='input-group-text'>");
EndContext();
BeginContext(9086, 24, false);
#line 127 "C:\Users\Rolando\Desktop\BTCPAY\banexcoinpay-master-github\banexcoinpay\BTCPayServer\Views\PaymentRequest\MinimalPaymentRequest.cshtml"
Write(Model.Currency.ToUpper());
#line default
#line hidden
EndContext();
BeginContext(9110, 599, true);
WriteLiteral(@"</span>
<button
class=""btn btn-primary""
type=""submit"">
Pague ahora
</button>
</div>
</div>
");
EndContext();
}
);
__Microsoft_AspNetCore_Mvc_TagHelpers_FormTagHelper = CreateTagHelper<global::Microsoft.AspNetCore.Mvc.TagHelpers.FormTagHelper>();
__tagHelperExecutionContext.Add(__Microsoft_AspNetCore_Mvc_TagHelpers_FormTagHelper);
__Microsoft_AspNetCore_Mvc_TagHelpers_RenderAtEndOfFormTagHelper = CreateTagHelper<global::Microsoft.AspNetCore.Mvc.TagHelpers.RenderAtEndOfFormTagHelper>();
__tagHelperExecutionContext.Add(__Microsoft_AspNetCore_Mvc_TagHelpers_RenderAtEndOfFormTagHelper);
__Microsoft_AspNetCore_Mvc_TagHelpers_FormTagHelper.Method = (string)__tagHelperAttribute_0.Value;
__tagHelperExecutionContext.AddTagHelperAttribute(__tagHelperAttribute_0);
__Microsoft_AspNetCore_Mvc_TagHelpers_FormTagHelper.Action = (string)__tagHelperAttribute_1.Value;
__tagHelperExecutionContext.AddTagHelperAttribute(__tagHelperAttribute_1);
await __tagHelperRunner.RunAsync(__tagHelperExecutionContext);
if (!__tagHelperExecutionContext.Output.IsContentModified)
{
await __tagHelperExecutionContext.SetOutputContentAsync();
}
Write(__tagHelperExecutionContext.Output);
__tagHelperExecutionContext = __tagHelperScopeManager.End();
EndContext();
BeginContext(9716, 2, true);
WriteLiteral("\r\n");
EndContext();
#line 136 "C:\Users\Rolando\Desktop\BTCPAY\banexcoinpay-master-github\banexcoinpay\BTCPayServer\Views\PaymentRequest\MinimalPaymentRequest.cshtml"
}
else
{
#line default
#line hidden
BeginContext(9874, 52, true);
WriteLiteral(" ");
EndContext();
BeginContext(9926, 210, false);
__tagHelperExecutionContext = __tagHelperScopeManager.Begin("a", global::Microsoft.AspNetCore.Razor.TagHelpers.TagMode.StartTagAndEndTag, "bbf90fc60e5741b7b5933c9d7dbcd56d", async() => {
BeginContext(10009, 123, true);
WriteLiteral("\r\n Pague ahora\r\n ");
EndContext();
}
);
__Microsoft_AspNetCore_Mvc_TagHelpers_AnchorTagHelper = CreateTagHelper<global::Microsoft.AspNetCore.Mvc.TagHelpers.AnchorTagHelper>();
__tagHelperExecutionContext.Add(__Microsoft_AspNetCore_Mvc_TagHelpers_AnchorTagHelper);
__tagHelperExecutionContext.AddHtmlAttribute(__tagHelperAttribute_2);
__Microsoft_AspNetCore_Mvc_TagHelpers_AnchorTagHelper.Action = (string)__tagHelperAttribute_1.Value;
__tagHelperExecutionContext.AddTagHelperAttribute(__tagHelperAttribute_1);
await __tagHelperRunner.RunAsync(__tagHelperExecutionContext);
if (!__tagHelperExecutionContext.Output.IsContentModified)
{
await __tagHelperExecutionContext.SetOutputContentAsync();
}
Write(__tagHelperExecutionContext.Output);
__tagHelperExecutionContext = __tagHelperScopeManager.End();
EndContext();
BeginContext(10136, 2, true);
WriteLiteral("\r\n");
EndContext();
#line 142 "C:\Users\Rolando\Desktop\BTCPAY\banexcoinpay-master-github\banexcoinpay\BTCPayServer\Views\PaymentRequest\MinimalPaymentRequest.cshtml"
if (Model.AnyPendingInvoice && !Model.PendingInvoiceHasPayments)
{
#line default
#line hidden
BeginContext(10311, 56, true);
WriteLiteral(" ");
EndContext();
BeginContext(10367, 347, false);
__tagHelperExecutionContext = __tagHelperScopeManager.Begin("form", global::Microsoft.AspNetCore.Razor.TagHelpers.TagMode.StartTagAndEndTag, "e835204623b74eb996cd79c7f73ab8e6", async() => {
BeginContext(10426, 281, true);
WriteLiteral(@"
<button class=""btn btn-secondary btn-lg mt-1"" type=""submit"">
Cancelar factura actual</button>
");
EndContext();
}
);
__Microsoft_AspNetCore_Mvc_TagHelpers_FormTagHelper = CreateTagHelper<global::Microsoft.AspNetCore.Mvc.TagHelpers.FormTagHelper>();
__tagHelperExecutionContext.Add(__Microsoft_AspNetCore_Mvc_TagHelpers_FormTagHelper);
__Microsoft_AspNetCore_Mvc_TagHelpers_RenderAtEndOfFormTagHelper = CreateTagHelper<global::Microsoft.AspNetCore.Mvc.TagHelpers.RenderAtEndOfFormTagHelper>();
__tagHelperExecutionContext.Add(__Microsoft_AspNetCore_Mvc_TagHelpers_RenderAtEndOfFormTagHelper);
__Microsoft_AspNetCore_Mvc_TagHelpers_FormTagHelper.Method = (string)__tagHelperAttribute_0.Value;
__tagHelperExecutionContext.AddTagHelperAttribute(__tagHelperAttribute_0);
__Microsoft_AspNetCore_Mvc_TagHelpers_FormTagHelper.Action = (string)__tagHelperAttribute_3.Value;
__tagHelperExecutionContext.AddTagHelperAttribute(__tagHelperAttribute_3);
await __tagHelperRunner.RunAsync(__tagHelperExecutionContext);
if (!__tagHelperExecutionContext.Output.IsContentModified)
{
await __tagHelperExecutionContext.SetOutputContentAsync();
}
Write(__tagHelperExecutionContext.Output);
__tagHelperExecutionContext = __tagHelperScopeManager.End();
EndContext();
BeginContext(10714, 2, true);
WriteLiteral("\r\n");
EndContext();
#line 148 "C:\Users\Rolando\Desktop\BTCPAY\banexcoinpay-master-github\banexcoinpay\BTCPayServer\Views\PaymentRequest\MinimalPaymentRequest.cshtml"
}
}
#line default
#line hidden
BeginContext(10822, 98, true);
WriteLiteral(" </td>\r\n </tr>\r\n");
EndContext();
#line 152 "C:\Users\Rolando\Desktop\BTCPAY\banexcoinpay-master-github\banexcoinpay\BTCPayServer\Views\PaymentRequest\MinimalPaymentRequest.cshtml"
}
#line default
#line hidden
BeginContext(10959, 335, true);
WriteLiteral(@" </tbody>
</table>
</div>
</div>
</div>
</div>
<div class=""card-footer text-muted d-flex justify-content-between"">
<div >Actualizado ");
EndContext();
BeginContext(11295, 31, false);
#line 162 "C:\Users\Rolando\Desktop\BTCPAY\banexcoinpay-master-github\banexcoinpay\BTCPayServer\Views\PaymentRequest\MinimalPaymentRequest.cshtml"
Write(Model.LastUpdated.ToString("g"));
#line default
#line hidden
EndContext();
BeginContext(11326, 290, true);
WriteLiteral(@"</div>
<div >
<span class=""text-muted"">Impulsado por </span><a href=""https://btcpayserver.org"" target=""_blank"">BANEXCOINPAY Server</a>
</div>
</div>
</div>
</div>
</div>
</div>
");
EndContext();
}
#pragma warning restore 1998
[global::Microsoft.AspNetCore.Mvc.Razor.Internal.RazorInjectAttribute]
public global::Microsoft.AspNetCore.Mvc.ViewFeatures.IModelExpressionProvider ModelExpressionProvider { get; private set; }
[global::Microsoft.AspNetCore.Mvc.Razor.Internal.RazorInjectAttribute]
public global::Microsoft.AspNetCore.Mvc.IUrlHelper Url { get; private set; }
[global::Microsoft.AspNetCore.Mvc.Razor.Internal.RazorInjectAttribute]
public global::Microsoft.AspNetCore.Mvc.IViewComponentHelper Component { get; private set; }
[global::Microsoft.AspNetCore.Mvc.Razor.Internal.RazorInjectAttribute]
public global::Microsoft.AspNetCore.Mvc.Rendering.IJsonHelper Json { get; private set; }
[global::Microsoft.AspNetCore.Mvc.Razor.Internal.RazorInjectAttribute]
public global::Microsoft.AspNetCore.Mvc.Rendering.IHtmlHelper<BTCPayServer.Models.PaymentRequestViewModels.ViewPaymentRequestViewModel> Html { get; private set; }
}
}
#pragma warning restore 1591
| 59.154098 | 378 | 0.540406 |
[
"MIT"
] |
CristianBanexcoin/banexcoinpay
|
BTCPayServer/obj/Release/netcoreapp2.1/Razor/Views/PaymentRequest/MinimalPaymentRequest.g.cshtml.cs
| 36,087 |
C#
|
using System;
using System.Windows.Media.Media3D;
using System.Windows.Media;
using System.Collections.Generic;
using System.Collections;
using System.Linq;
using System.Dynamic;
using ESAPIX.Extensions;
using VMS.TPS.Common.Model.Types;
using XC = ESAPIX.Common.AppComThread;
using V = VMS.TPS.Common.Model.API;
using Types = VMS.TPS.Common.Model.Types;
namespace ESAPIX.Facade.API
{
public class StructureSet : ESAPIX.Facade.API.ApiDataObject, System.Xml.Serialization.IXmlSerializable
{
public System.String UID
{
get
{
if ((_client) is System.Dynamic.ExpandoObject)
{
if (((ExpandoObject)(_client)).HasProperty("UID"))
{
return _client.UID;
}
else
{
return default (System.String);
}
}
else if ((XC.Instance) != (null))
{
return XC.Instance.GetValue(sc =>
{
return _client.UID;
}
);
}
else
{
return default (System.String);
}
}
set
{
if ((_client) is System.Dynamic.ExpandoObject)
{
_client.UID = (value);
}
else
{
}
}
}
public ESAPIX.Facade.API.Image Image
{
get
{
if ((_client) is System.Dynamic.ExpandoObject)
{
if (((ExpandoObject)(_client)).HasProperty("Image"))
{
return _client.Image;
}
else
{
return default (ESAPIX.Facade.API.Image);
}
}
else if ((XC.Instance) != (null))
{
return XC.Instance.GetValue(sc =>
{
if ((_client.Image) != (null))
{
return new ESAPIX.Facade.API.Image(_client.Image);
}
else
{
return null;
}
}
);
}
else
{
return default (ESAPIX.Facade.API.Image);
}
}
set
{
if ((_client) is System.Dynamic.ExpandoObject)
{
_client.Image = (value);
}
else
{
}
}
}
public IEnumerable<ESAPIX.Facade.API.Structure> Structures
{
get
{
if (_client is ExpandoObject)
{
if ((_client as ExpandoObject).HasProperty("Structures"))
{
foreach (var item in _client.Structures)
{
yield return item;
}
}
else
{
yield break;
}
}
else
{
IEnumerator enumerator = null;
XC.Instance.Invoke(() =>
{
var asEnum = (IEnumerable)_client.Structures;
if ((asEnum) != null)
{
enumerator = asEnum.GetEnumerator();
}
}
);
if (enumerator == null)
{
yield break;
}
while (XC.Instance.GetValue<bool>(sc => enumerator.MoveNext()))
{
var facade = new ESAPIX.Facade.API.Structure();
XC.Instance.Invoke(() =>
{
var vms = enumerator.Current;
if (vms != null)
{
facade._client = vms;
}
}
);
if (facade._client != null)
{
yield return facade;
}
}
}
}
set
{
if (_client is ExpandoObject)
_client.Structures = value;
}
}
public StructureSet()
{
_client = (new ExpandoObject());
}
public StructureSet(dynamic client)
{
_client = (client);
}
}
}
| 28.393443 | 106 | 0.331409 |
[
"MIT"
] |
avalgoma/ESAPIX
|
ESAPIX/Facade/API11.0/StructureSet.cs
| 5,196 |
C#
|
// Copyright (c) Microsoft Open Technologies, Inc. All rights reserved. See License.txt in the project root for license information.
using System.Web.Http.Controllers;
namespace System.Web.Http.Description
{
/// <summary>
/// Describes a parameter on the API defined by relative URI path and HTTP method.
/// </summary>
public class ApiParameterDescription
{
/// <summary>
/// Gets or sets the name.
/// </summary>
/// <value>
/// The name.
/// </value>
public string Name { get; set; }
/// <summary>
/// Gets or sets the documentation.
/// </summary>
/// <value>
/// The documentation.
/// </value>
public string Documentation { get; set; }
/// <summary>
/// Gets or sets the source of the parameter. It may come from the request URI, request body or other places.
/// </summary>
/// <value>
/// The source.
/// </value>
public ApiParameterSource Source { get; set; }
/// <summary>
/// Gets or sets the parameter descriptor.
/// </summary>
/// <value>
/// The parameter descriptor.
/// </value>
public HttpParameterDescriptor ParameterDescriptor { get; set; }
}
}
| 29.311111 | 133 | 0.55345 |
[
"Apache-2.0"
] |
Icenium/aspnetwebstack
|
src/System.Web.Http/Description/ApiParameterDescription.cs
| 1,321 |
C#
|
namespace GildedRose.InventoryManagement.QualityCalculators
{
public class IncreasingQualityCalculator : QualityCalculatorBase
{
public override bool CanDegrade => false;
public override uint CalculateQuality(int sellInValue, uint quality)
{
return ++quality;
}
}
}
| 21.692308 | 70 | 0.780142 |
[
"MIT"
] |
scousedave/GildedRoseKata
|
InventoryManagement/QualityCalculators/IncreasingQualityCalculator.cs
| 284 |
C#
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
namespace HELLDIVERS.UI
{
[RequireComponent(typeof(UITweenCanvasAlpha))]
public class UIMissionTitle : MonoBehaviour
{
public UITweenCanvasAlpha CanavasTween { get { return m_CanvasTween; } }
[SerializeField] private Text m_Title;
private UITweenCanvasAlpha m_CanvasTween;
private void Awake()
{
m_CanvasTween = this.GetComponent<UITweenCanvasAlpha>();
}
public void Initialize(bool success)
{
if (success)
{
m_Title.text = "MISSION COMPLETE";
}
else
{
m_Title.text = "MISSION FAILED";
}
}
}
}
| 24.333333 | 80 | 0.58406 |
[
"MIT"
] |
IvanCKP/HELLDIVERS_Like
|
HellDivers_UnityProject/Assets/Scripts/UI/Reward/UIMissionTitle.cs
| 805 |
C#
|
using System;
using System.Collections.Generic;
using System.IO;
using System.Runtime.CompilerServices;
using Newtonsoft.Json;
using SmartTaskbar.Core.Helpers;
using static SmartTaskbar.Core.InvokeMethods;
namespace SmartTaskbar.Core.UserConfig
{
public static class SettingsHelper
{
private static readonly string SettingPath =
Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments), "SmartTaskbar",
"SmartTaskbar.json");
private static readonly JsonSerializer Serializer = new JsonSerializer();
[MethodImpl(MethodImplOptions.AggressiveInlining)]
internal static void SaveSettings()
{
DirectoryBuilder();
using (FileStream fs = new FileStream(SettingPath, FileMode.Create))
{
using (StreamWriter sw = new StreamWriter(fs))
{
Serializer.Serialize(sw, Settings);
}
}
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
internal static void ReadSettings()
{
DirectoryBuilder();
using (var fs = new FileStream(SettingPath, FileMode.OpenOrCreate))
{
using (var sr = new StreamReader(fs))
{
using (var jr = new JsonTextReader(sr))
{
GetSettings(Serializer.Deserialize<UserSettings>(jr));
}
}
}
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private static void DirectoryBuilder() =>
Directory.CreateDirectory(Path.GetDirectoryName(SettingPath) ?? throw new InvalidOperationException());
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private static void GetSettings(UserSettings settings)
{
if (settings is null)
{
Settings.DefaultState = BarState.GetDefault();
Settings.ModeType = AutoModeType.ForegroundMode;
Settings.Blacklist = new HashSet<string>(16);
Settings.BlistDefaultState = BarState.GetDefault();
Settings.BlistTargetState = BarState.GetDefault();
Settings.Whitelist = new HashSet<string>(16);
Settings.WlistDefaultState = BarState.GetDefault();
Settings.WlistTargetState = BarState.GetDefault();
Settings.TransparentType = TransparentModeType.Disabled;
Settings.HideTaskbarCompletely = false;
Settings.DisabledOnTabletMode = false;
}
else
{
Settings.DefaultState = settings.DefaultState ?? BarState.GetDefault();
Settings.ModeType = settings.ModeType;
Settings.Blacklist = settings.Blacklist ?? new HashSet<string>(16);
Settings.BlistTargetState = settings.BlistTargetState ?? BarState.GetDefault();
Settings.BlistDefaultState = settings.WlistDefaultState ?? BarState.GetDefault();
Settings.Whitelist = settings.Whitelist ?? new HashSet<string>(16);
Settings.WlistDefaultState = settings.WlistDefaultState ?? BarState.GetDefault();
Settings.WlistTargetState = settings.WlistTargetState ?? BarState.GetDefault();
Settings.TransparentType = settings.TransparentType;
Settings.HideTaskbarCompletely = settings.HideTaskbarCompletely;
Settings.Language = settings.Language;
Settings.DisabledOnTabletMode = settings.DisabledOnTabletMode;
}
}
}
}
| 43.069767 | 115 | 0.611771 |
[
"MIT"
] |
F8889212/SmartTaskbar
|
SmartTaskbar.Core/UserConfig/SettingsHelper.cs
| 3,706 |
C#
|
using Model.Dao;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using TDMU.Common;
namespace TDMU.Controllers
{
public class SearchController : Controller
{
// GET: Search
[HttpGet]
[CompressContent]
public ActionResult Index()
{
return View();
}
[HttpPost]
[CompressContent]
public ActionResult Index(string key)
{
var model = new NewsDao().GetByKey(key);
return View(model);
}
[OutputCache(Duration = int.MaxValue, Location = System.Web.UI.OutputCacheLocation.Client, VaryByParam = "url")]
[CompressContent]
public ActionResult Detail(string url)
{
var model = new NewsDao().GetByUrl(url);
return View(model);
}
}
}
| 23.810811 | 120 | 0.587968 |
[
"Apache-2.0"
] |
huydoan95/aspnet_mvc5_tdmu
|
TDMU/TDMU/Controllers/SearchController.cs
| 883 |
C#
|
namespace Flyweight.Tea
{
public class TeaMaker
{
private Dictionary<string, KarakTea> mAvailableTea = new Dictionary<string, KarakTea>();
public KarakTea Make(string preference)
{
if (!mAvailableTea.ContainsKey(preference))
{
mAvailableTea[preference] = new KarakTea();
}
return mAvailableTea[preference];
}
}
}
| 23.555556 | 96 | 0.575472 |
[
"MIT"
] |
sebash1992/DesignPatterns
|
Structural/Flyweight/Tea/TeaMaker.cs
| 426 |
C#
|
using System.ComponentModel.DataAnnotations;
namespace Phonebook.Data.Models
{
public class Contact
{
[Required]
public string Name { get; set; }
[Required]
public string Number { get; set; }
}
}
| 17.928571 | 45 | 0.589641 |
[
"Apache-2.0"
] |
vencislav-viktorov/VS-Console-App
|
Tech Module New one/27.Basic Web C# ASP.NET Core-Lab/Phonebook/Data/Models/Contact.cs
| 253 |
C#
|
using System;
using System.ComponentModel;
using EfsTools.Attributes;
using EfsTools.Utils;
using Newtonsoft.Json;
namespace EfsTools.Items.Nv
{
[Serializable]
[NvItemId(772)]
[Attributes(9)]
public class DcsTxBurstRampUpIndex02
{
[ElementsCount(30)]
[ElementType("uint16")]
[Description("")]
public ushort[] Value { get; set; }
}
}
| 19.952381 | 44 | 0.606205 |
[
"MIT"
] |
HomerSp/EfsTools
|
EfsTools/Items/Nv/DcsTxBurstRampUpIndex02I.cs
| 419 |
C#
|
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System.Text;
using Microsoft.TemplateEngine.Abstractions;
using Microsoft.TemplateEngine.Abstractions.TemplatePackage;
using Microsoft.TemplateEngine.Cli.Commands;
using Microsoft.TemplateEngine.Cli.TabularOutput;
using Microsoft.TemplateEngine.Edge.Settings;
using Microsoft.TemplateSearch.Common;
using Microsoft.TemplateSearch.Common.Abstractions;
namespace Microsoft.TemplateEngine.Cli.TemplateSearch
{
internal static class CliTemplateSearchCoordinator
{
/// <summary>
/// Executes searching for the templates in configured remote sources.
/// Performs validation for the commands, search for the templates in configured remote source, displays the results in table format.
/// </summary>
/// <param name="environmentSettings">environment settings.</param>
/// <param name="templatePackageManager"></param>
/// <param name="commandArgs">new command data.</param>
/// <param name="defaultLanguage">default language for the host.</param>
/// <param name="cancellationToken"></param>
/// <returns><see cref="NewCommandStatus.Success"/> when the templates were found and displayed;
/// <see cref="NewCommandStatus.Cancelled"/> when the command validation fails;
/// <see cref="NewCommandStatus.NotFound"/> when no templates found based on the filter criteria.
/// </returns>
internal static async Task<NewCommandStatus> SearchForTemplateMatchesAsync(
IEngineEnvironmentSettings environmentSettings,
TemplatePackageManager templatePackageManager,
SearchCommandArgs commandArgs,
string? defaultLanguage,
CancellationToken cancellationToken)
{
if (!ValidateCommandInput(commandArgs))
{
return NewCommandStatus.InvalidParamValues;
}
Reporter.Output.WriteLine(LocalizableStrings.CliTemplateSearchCoordinator_Info_SearchInProgress);
IReadOnlyList<IManagedTemplatePackage> templatePackages =
await templatePackageManager.GetManagedTemplatePackagesAsync(force: false, cancellationToken: cancellationToken).ConfigureAwait(false);
TemplateSearchCoordinator searchCoordinator = CliTemplateSearchCoordinatorFactory.CreateCliTemplateSearchCoordinator(environmentSettings);
CliSearchFiltersFactory searchFiltersFactory = new CliSearchFiltersFactory(templatePackages);
IReadOnlyList<SearchResult>? searchResults = await searchCoordinator.SearchAsync(
searchFiltersFactory.GetPackFilter(commandArgs),
CliSearchFiltersFactory.GetMatchingTemplatesFilter(commandArgs),
cancellationToken).ConfigureAwait(false);
if (!searchResults.Any())
{
Reporter.Error.WriteLine(LocalizableStrings.CliTemplateSearchCoordinator_Error_NoSources.Bold().Red());
return NewCommandStatus.NotFound;
}
foreach (SearchResult result in searchResults)
{
if (!result.Success)
{
Reporter.Error.WriteLine(string.Format(LocalizableStrings.CliTemplateSearchCoordinator_Info_MatchesFromSource, result.Provider.Factory.DisplayName));
Reporter.Error.WriteLine(string.Format(LocalizableStrings.CliTemplateSearchCoordinator_Error_SearchFailure, result.ErrorMessage).Red().Bold());
continue;
}
Reporter.Output.WriteLine(string.Format(LocalizableStrings.CliTemplateSearchCoordinator_Info_MatchesFromSource, result.Provider.Factory.DisplayName));
if (result.SearchHits.Any())
{
DisplayResultsForPack(result.SearchHits, environmentSettings, commandArgs, defaultLanguage);
}
else
{
//TODO: implement it for template options matching
//IReadOnlyDictionary<string, string?>? appliedParameterMatches = TemplateCommandInput.GetTemplateParametersFromCommand(commandArgs);
// No templates found matching the following input parameter(s): {0}.
Reporter.Error.WriteLine(
string.Format(
LocalizableStrings.NoTemplatesMatchingInputParameters,
GetInputParametersString(commandArgs))
.Bold().Red());
}
}
Reporter.Output.WriteLine();
if (searchResults.Where(r => r.Success).SelectMany(r => r.SearchHits).Any())
{
string packageIdToShow = EvaluatePackageToShow(searchResults);
Reporter.Output.WriteLine(LocalizableStrings.CliTemplateSearchCoordinator_Info_InstallHelp);
Reporter.Output.WriteCommand(
Example
.For<NewCommand>(commandArgs.ParseResult)
.WithSubcommand<InstallCommand>()
.WithArgument(InstallCommand.NameArgument));
Reporter.Output.WriteLine(LocalizableStrings.Generic_ExampleHeader);
Reporter.Output.WriteCommand(
Example
.For<NewCommand>(commandArgs.ParseResult)
.WithSubcommand<InstallCommand>()
.WithArgument(InstallCommand.NameArgument, packageIdToShow));
return NewCommandStatus.Success;
}
return NewCommandStatus.NotFound;
}
private static string EvaluatePackageToShow(IReadOnlyList<SearchResult> searchResults)
{
var microsoftAuthoredPackages = searchResults
.SelectMany(r => r.SearchHits)
.Where(hit => hit.PackageInfo.Name.StartsWith("Microsoft", StringComparison.OrdinalIgnoreCase)
&& hit.MatchedTemplates.Any(t => t.Author == "Microsoft"))
.OrderByDescending(hit => hit.PackageInfo.TotalDownloads);
if (microsoftAuthoredPackages.Any())
{
return microsoftAuthoredPackages.First().PackageInfo.Name;
}
else
{
return searchResults
.SelectMany(r => r.SearchHits)
.OrderByDescending(hit => hit.PackageInfo.TotalDownloads)
.First().PackageInfo.Name;
}
}
private static void DisplayResultsForPack(
IReadOnlyList<(ITemplatePackageInfo PackageInfo, IReadOnlyList<ITemplateInfo> MatchedTemplates)> results,
IEngineEnvironmentSettings environmentSettings,
SearchCommandArgs commandArgs,
string? defaultLanguage)
{
//TODO: implement it for template options matching
//IReadOnlyDictionary<string, string?>? appliedParameterMatches = TemplateCommandInput.GetTemplateParametersFromCommand(commandArgs);
Reporter.Output.WriteLine(
string.Format(
LocalizableStrings.TemplatesFoundMatchingInputParameters,
GetInputParametersString(commandArgs)));
Reporter.Output.WriteLine();
IReadOnlyCollection<SearchResultTableRow> data = GetSearchResultsForDisplay(results, commandArgs.Language, defaultLanguage, environmentSettings.Environment);
TabularOutput<SearchResultTableRow> formatter =
TabularOutput.TabularOutput
.For(
new TabularOutputSettings(environmentSettings.Environment, commandArgs),
data
.OrderByDescending(d => d.TotalDownloads, SearchResultTableRow.TotalDownloadsComparer)
.ThenBy(d => d.TemplateGroupInfo.Name, StringComparer.CurrentCultureIgnoreCase))
.DefineColumn(r => r.TemplateGroupInfo.Name, out object? nameColumn, LocalizableStrings.ColumnNameTemplateName, showAlways: true, shrinkIfNeeded: true, minWidth: 15)
.DefineColumn(r => r.TemplateGroupInfo.ShortNames, LocalizableStrings.ColumnNameShortName, showAlways: true)
.DefineColumn(r => r.TemplateGroupInfo.Author, LocalizableStrings.ColumnNameAuthor, TabularOutputSettings.ColumnNames.Author, defaultColumn: true, shrinkIfNeeded: true, minWidth: 10)
.DefineColumn(r => r.TemplateGroupInfo.Languages, LocalizableStrings.ColumnNameLanguage, TabularOutputSettings.ColumnNames.Language, defaultColumn: true)
.DefineColumn(r => r.TemplateGroupInfo.Type, LocalizableStrings.ColumnNameType, TabularOutputSettings.ColumnNames.Type, defaultColumn: false)
.DefineColumn(r => r.TemplateGroupInfo.Classifications, LocalizableStrings.ColumnNameTags, TabularOutputSettings.ColumnNames.Tags, defaultColumn: false, shrinkIfNeeded: true, minWidth: 10)
.DefineColumn(r => r.PackageName, out object? packageColumn, LocalizableStrings.ColumnNamePackage, showAlways: true)
.DefineColumn(r => r.PrintableTotalDownloads, out object? downloadsColumn, LocalizableStrings.ColumnNameTotalDownloads, showAlways: true, rightAlign: true);
Reporter.Output.WriteLine(formatter.Layout());
}
private static IReadOnlyCollection<SearchResultTableRow> GetSearchResultsForDisplay(
IReadOnlyList<(ITemplatePackageInfo PackageInfo, IReadOnlyList<ITemplateInfo> MatchedTemplates)> results,
string? language,
string? defaultLanguage,
IEnvironment environment)
{
List<SearchResultTableRow> templateGroupsForDisplay = new List<SearchResultTableRow>();
foreach (var packSearchResult in results)
{
var templateGroupsForPack = TemplateGroupDisplay.GetTemplateGroupsForListDisplay(packSearchResult.MatchedTemplates, language, defaultLanguage, environment);
templateGroupsForDisplay.AddRange(templateGroupsForPack.Select(t => new SearchResultTableRow(t, packSearchResult.PackageInfo.Name, packSearchResult.PackageInfo.TotalDownloads)));
}
return templateGroupsForDisplay;
}
private static bool ValidateCommandInput(SearchCommandArgs commandArgs)
{
if (string.IsNullOrWhiteSpace(commandArgs.SearchNameCriteria) && !commandArgs.AppliedFilters.Any())
//TODO: implement it for template options matching
// && !commandInput.RemainingParameters.Any())
{
Reporter.Error.WriteLine(LocalizableStrings.CliTemplateSearchCoordinator_Error_NoTemplateName.Red().Bold());
Reporter.Error.WriteLine(string.Format(LocalizableStrings.CliTemplateSearchCoordinator_Info_SearchHelp, string.Join(", ", SearchCommand.SupportedFilters.Select(f => $"'{f.OptionFactory().Aliases.First()}'"))));
Reporter.Error.WriteLine(LocalizableStrings.Generic_ExamplesHeader);
Reporter.Error.WriteCommand(
Example
.For<NewCommand>(commandArgs.ParseResult)
.WithSubcommand<SearchCommand>()
.WithArgument(SearchCommand.NameArgument, "web"));
Reporter.Error.WriteCommand(
Example
.For<NewCommand>(commandArgs.ParseResult)
.WithSubcommand<SearchCommand>()
.WithOption(SharedOptionsFactory.CreateAuthorOption(), "Microsoft"));
Reporter.Error.WriteCommand(
Example
.For<NewCommand>(commandArgs.ParseResult)
.WithSubcommand<SearchCommand>()
.WithArgument(SearchCommand.NameArgument, "web")
.WithOption(SharedOptionsFactory.CreateLanguageOption(), "C#"));
return false;
}
if (!string.IsNullOrWhiteSpace(commandArgs.SearchNameCriteria) && commandArgs.SearchNameCriteria.Length < 2)
{
Reporter.Error.WriteLine(LocalizableStrings.CliTemplateSearchCoordinator_Error_TemplateNameIsTooShort.Bold().Red());
return false;
}
return true;
}
private static string GetInputParametersString(SearchCommandArgs commandArgs/*, IReadOnlyDictionary<string, string?>? templateParameters = null*/)
{
string separator = ", ";
IEnumerable<string> appliedFilters = commandArgs.AppliedFilters
.Select(filter => $"{commandArgs.GetFilterToken(filter)}='{commandArgs.GetFilterValue(filter)}'");
//TODO: implement it for template options matching
//IEnumerable<string> appliedTemplateParameters = templateParameters?
// .Select(param => string.IsNullOrWhiteSpace(param.Value) ? param.Key : $"{param.Key}='{param.Value}'") ?? Array.Empty<string>();
StringBuilder inputParameters = new StringBuilder();
string? mainCriteria = commandArgs.SearchNameCriteria;
if (!string.IsNullOrWhiteSpace(mainCriteria))
{
inputParameters.Append($"'{mainCriteria}'");
if (appliedFilters.Any()/* || appliedTemplateParameters.Any()*/)
{
inputParameters.Append(separator);
}
}
if (appliedFilters/*.Concat(appliedTemplateParameters)*/.Any())
{
inputParameters.Append(string.Join(separator, appliedFilters/*.Concat(appliedTemplateParameters)*/));
}
return inputParameters.ToString();
}
/// <summary>
/// Represents a table row for the template with the package information.
/// </summary>
internal class SearchResultTableRow
{
private const string MinimumDownloadCount = "<1k";
private const char ThousandsChar = 'k';
internal SearchResultTableRow(TemplateGroupTableRow templateGroupTableRow, string packageName, long downloads = 0)
{
TemplateGroupInfo = templateGroupTableRow;
PackageName = packageName;
TotalDownloads = downloads;
}
internal static IComparer<long> TotalDownloadsComparer { get; } = new ThousandComparer();
internal string PackageName { get; private set; }
internal string PrintableTotalDownloads
{
get
{
if (TotalDownloads < 1)
{
return string.Empty;
}
else if (TotalDownloads < 1000)
{
return MinimumDownloadCount;
}
else
{
return $"{(TotalDownloads / 1000):N0}{ThousandsChar}";
}
}
}
internal TemplateGroupTableRow TemplateGroupInfo { get; private set; }
internal long TotalDownloads { get; private set; }
private class ThousandComparer : IComparer<long>
{
public int Compare(long x, long y)
{
if (x == y || x < 1 && y < 1)
{
return 0;
}
if (x < 1)
{
return -1;
}
if (y < 1)
{
return 1;
}
return (x / 1000).CompareTo(y / 1000);
}
}
}
}
}
| 51.445513 | 226 | 0.619151 |
[
"MIT"
] |
Lucifer990046/templating
|
src/Microsoft.TemplateEngine.Cli/TemplateSearch/CliTemplateSearchCoordinator.cs
| 16,051 |
C#
|
using HL7Data.Contracts.Segments.Provider.Facility;
using HL7Data.Models.Base;
using HL7Data.Models.Types;
namespace HL7Data.Models.Segments.Provider.Facility
{
public class LocationCharacteristicSegment : BaseSegment, ILocationCharacteristicSegment
{
public override SegmentTypes SegmentType => SegmentTypes.LCH;
}
}
| 30.727273 | 92 | 0.795858 |
[
"MIT"
] |
amenkes/HL7Parser
|
Models/Segments/Provider/Facility/LocationCharacteristicSegment.cs
| 338 |
C#
|
// Copyright (C) 2012 Winterleaf Entertainment L,L,C.
//
// THE SOFTW ARE IS PROVIDED ON AN “ AS IS” BASIS, WITHOUT W ARRANTY OF ANY KIND,
// INCLUDING WITHOUT LIMIT ATION THE W ARRANTIES OF MERCHANT ABILITY, FITNESS
// FOR A PARTICULAR PURPOSE OR NON-INFRINGEMENT . THE ENTIRE RISK AS TO THE
// QUALITY AND PERFORMANCE OF THE SOFTW ARE IS THE RESPONSIBILITY OF LICENSEE.
// SHOULD THE SOFTW ARE PROVE DEFECTIVE IN ANY RESPECT , LICENSEE AND NOT LICEN -
// SOR OR ITS SUPPLIERS OR RESELLERS ASSUMES THE ENTIRE COST OF AN Y SERVICE AND
// REPAIR. THIS DISCLAIMER OF W ARRANTY CONSTITUTES AN ESSENTIAL PART OF THIS
// AGREEMENT. NO USE OF THE SOFTW ARE IS AUTHORIZED HEREUNDER EXCEPT UNDER
// THIS DISCLAIMER.
//
// The use of the WinterLeaf Entertainment LLC DotNetT orque (“DNT ”) and DotNetT orque
// Customizer (“DNTC”)is governed by this license agreement (“ Agreement”).
//
// R E S T R I C T I O N S
//
// (a) Licensee may not: (i) create any derivative works of DNTC, including but not
// limited to translations, localizations, technology add-ons, or game making software
// other than Games; (ii) reverse engineer , or otherwise attempt to derive the algorithms
// for DNT or DNTC (iii) redistribute, encumber , sell, rent, lease, sublicense, or otherwise
// transfer rights to DNTC; or (iv) remove or alter any tra demark, logo, copyright
// or other proprietary notices, legends, symbols or labels in DNT or DNTC; or (iiv) use
// the Software to develop or distribute any software that compete s with the Software
// without WinterLeaf Entertainment’s prior written consent; or (i iiv) use the Software for
// any illegal purpose.
// (b) Licensee may not distribute the DNTC in any manner.
//
// LI C E N S E G R A N T .
// This license allows companies of any size, government entities or individuals to cre -
// ate, sell, rent, lease, or otherwise profit commercially from, games using executables
// created from the source code of DNT
//
// **********************************************************************************
// **********************************************************************************
// **********************************************************************************
// THE SOURCE CODE GENERATED BY DNTC CAN BE DISTRIBUTED PUBLICLY PROVIDED THAT THE
// DISTRIBUTOR PROVIDES THE GENERATE SOURCE CODE FREE OF CHARGE.
//
// THIS SOURCE CODE (DNT) CAN BE DISTRIBUTED PUBLICLY PROVIDED THAT THE DISTRIBUTOR
// PROVIDES THE SOURCE CODE (DNT) FREE OF CHARGE.
// **********************************************************************************
// **********************************************************************************
// **********************************************************************************
//
// Please visit http://www.winterleafentertainment.com for more information about the project and latest updates.
#region
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using WinterLeaf.Classes;
using WinterLeaf.Containers;
using WinterLeaf.Enums;
using System.ComponentModel;
using System.Threading;
#endregion
namespace WinterLeaf.tsObjects
{
/// <summary>
///
/// </summary>
internal class tsObjectConvertercoGuiConsole : TypeConverter
{
/// <summary>
///
/// </summary>
/// <param name="context"></param>
/// <param name="sourceType"></param>
/// <returns></returns>
public override bool CanConvertFrom(ITypeDescriptorContext context, Type sourceType)
{
return (typeof(string) == sourceType);
}
/// <summary>
///
/// </summary>
/// <param name="context"></param>
/// <param name="culture"></param>
/// <param name="value"></param>
/// <returns></returns>
public override object ConvertFrom(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value)
{
if (value is string)
{
return new coGuiConsole(value as string);
}
return null;
}
}
/// <summary>
///
/// </summary>
[TypeConverter(typeof(tsObjectConvertercoGuiConsole))]
public class coGuiConsole: coGuiArrayCtrl
{
/// <summary>
///
/// </summary>
/// <param name="simobjectid"></param>
internal coGuiConsole(string simobjectid) : base(simobjectid){ }
/// <summary>
///
/// </summary>
/// <param name="simobjectid"></param>
internal coGuiConsole(uint simobjectid): base(simobjectid){ }
/// <summary>
///
/// </summary>
/// <param name="simobjectid"></param>
internal coGuiConsole(int simobjectid): base(simobjectid){ }
/// <summary>
///
/// </summary>
/// <param name="ts"></param>
/// <param name="simobjectid"></param>
/// <returns></returns>
public static bool operator ==(coGuiConsole ts, string simobjectid)
{
if (object.ReferenceEquals(ts, null))
return object.ReferenceEquals(simobjectid, null);
return ts.Equals(simobjectid);
}
/// <summary>
///
/// </summary>
/// <returns></returns>
public override int GetHashCode()
{
throw new NotImplementedException();
}
/// <summary>
///
/// </summary>
/// <param name="obj"></param>
/// <returns></returns>
public override bool Equals(object obj)
{
return (this._mSimObjectId ==(string)myReflections.ChangeType( obj,typeof(string)));
}
/// <summary>
///
/// </summary>
/// <param name="ts"></param>
/// <param name="simobjectid"></param>
/// <returns></returns>
public static bool operator !=(coGuiConsole ts, string simobjectid)
{
if (object.ReferenceEquals(ts, null))
return !object.ReferenceEquals(simobjectid, null);
return !ts.Equals(simobjectid);
}
/// <summary>
///
/// </summary>
/// <param name="ts"></param>
/// <returns></returns>
public static implicit operator string( coGuiConsole ts)
{
if (object.ReferenceEquals(ts, null))
return "0";
return ts._mSimObjectId;
}
/// <summary>
///
/// </summary>
/// <param name="ts"></param>
/// <returns></returns>
public static implicit operator coGuiConsole(string ts)
{
return new coGuiConsole(ts);
}
/// <summary>
///
/// </summary>
/// <param name="ts"></param>
/// <returns></returns>
public static implicit operator int( coGuiConsole ts)
{
if (object.ReferenceEquals(ts, null))
return 0;
int i;
return int.TryParse(ts._mSimObjectId, out i) ? i : 0;
}
/// <summary>
///
/// </summary>
/// <param name="ts"></param>
/// <returns></returns>
public static implicit operator coGuiConsole(int ts)
{
return new coGuiConsole(ts);
}
/// <summary>
///
/// </summary>
/// <param name="ts"></param>
/// <returns></returns>
public static implicit operator uint( coGuiConsole ts)
{
if (object.ReferenceEquals(ts, null))
return 0;
uint i;
return uint.TryParse(ts._mSimObjectId, out i) ? i : 0;
}
/// <summary>
///
/// </summary>
/// <param name="ts"></param>
/// <returns></returns>
public static implicit operator coGuiConsole(uint ts)
{
return new coGuiConsole(ts);
}
}}
| 35.423729 | 131 | 0.522129 |
[
"Unlicense"
] |
Winterleaf/DNT-Torque3D-V1.1-MIT-3.0
|
Engine/lib/DNT/tsObjects/coGuiConsole.cs
| 8,143 |
C#
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Model.DataEntity;
using Model.Locale;
using System.Linq.Expressions;
namespace eIVOGo.Module.UI
{
public partial class GovPlatformNotification : System.Web.UI.UserControl
{
protected void Page_Load(object sender, EventArgs e)
{
}
public Expression<Func<DocumentReplication, bool>> QueryExpr
{
get;
set;
}
protected override void OnInit(EventArgs e)
{
base.OnInit(e);
this.PreRender += new EventHandler(GovPlatformNotification_PreRender);
}
void GovPlatformNotification_PreRender(object sender, EventArgs e)
{
var mgr = dsEntity.CreateDataManager();
IQueryable<DocumentReplication> replication = QueryExpr != null ? mgr.GetTable<DocumentReplication>().Where(QueryExpr) : mgr.GetTable<DocumentReplication>();
var invItems = replication.Where(r => r.TypeID == (int)Naming.DocumentTypeDefinition.E_Invoice);
gvInvoice.DataSource = invItems;
gvInvoice.DataBind();
var cancelItems = replication.Where(r => r.TypeID == (int)Naming.DocumentTypeDefinition.E_InvoiceCancellation);
gvCancel.DataSource = cancelItems;
gvCancel.DataBind();
}
}
}
| 31.911111 | 169 | 0.655989 |
[
"MIT"
] |
uxb2bralph/IFS-EIVO03
|
eIVOGo/Module/UI/GovPlatformNotification.ascx.cs
| 1,438 |
C#
|
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// 有关程序集的常规信息通过以下
// 特性集控制。更改这些特性值可修改
// 与程序集关联的信息。
[assembly: AssemblyTitle("Scree.Syn.Client")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Microsoft")]
[assembly: AssemblyProduct("Scree.Syn.Client")]
[assembly: AssemblyCopyright("Copyright © Microsoft 2012")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// 将 ComVisible 设置为 false 使此程序集中的类型
// 对 COM 组件不可见。如果需要从 COM 访问此程序集中的类型,
// 则将该类型上的 ComVisible 特性设置为 true。
[assembly: ComVisible(false)]
// 如果此项目向 COM 公开,则下列 GUID 用于类型库的 ID
[assembly: Guid("5cf8a677-4f8e-4b9f-852f-ba75131995a8")]
// 程序集的版本信息由下面四个值组成:
//
// 主版本
// 次版本
// 内部版本号
// 修订号
//
// 可以指定所有这些值,也可以使用“内部版本号”和“修订号”的默认值,
// 方法是按如下所示使用“*”:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| 26.459459 | 59 | 0.720123 |
[
"Apache-2.0"
] |
winal/Scree
|
Src/Scree.Syn.Client/Properties/AssemblyInfo.cs
| 1,346 |
C#
|
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Azure.Core;
using Azure.Core.Pipeline;
namespace Azure.AI.FormRecognizer.Models
{
/// <summary>
/// Tracks the status of a long-running operation for recognizing layout elements from forms.
/// </summary>
public class RecognizeContentOperation : Operation<FormPageCollection>
{
/// <summary>Provides communication with the Form Recognizer Azure Cognitive Service through its REST API.</summary>
private readonly ServiceClient _serviceClient;
/// <summary>The last HTTP response received from the server. <c>null</c> until the first response is received.</summary>
private Response _response;
/// <summary>The result of the long-running operation. <c>null</c> until result is received on status update.</summary>
private FormPageCollection _value;
/// <summary><c>true</c> if the long-running operation has completed. Otherwise, <c>false</c>.</summary>
private bool _hasCompleted;
/// <inheritdoc/>
public override string Id { get; }
/// <inheritdoc/>
public override FormPageCollection Value => OperationHelpers.GetValue(ref _value);
/// <inheritdoc/>
public override bool HasCompleted => _hasCompleted;
/// <inheritdoc/>
public override bool HasValue => _value != null;
/// <summary>
/// Initializes a new instance of the <see cref="RecognizeContentOperation"/> class.
/// </summary>
/// <param name="operationId">The ID of this operation.</param>
/// <param name="client">The client used to check for completion.</param>
public RecognizeContentOperation(string operationId, FormRecognizerClient client)
{
// TODO: Add argument validation here.
Id = operationId;
_serviceClient = client.ServiceClient;
}
/// <summary>
/// Initializes a new instance of the <see cref="RecognizeContentOperation"/> class.
/// </summary>
/// <param name="serviceClient">The client for communicating with the Form Recognizer Azure Cognitive Service through its REST API.</param>
/// <param name="operationLocation">The address of the long-running operation. It can be obtained from the response headers upon starting the operation.</param>
internal RecognizeContentOperation(ServiceClient serviceClient, string operationLocation)
{
_serviceClient = serviceClient;
// TODO: Add validation here
// https://github.com/Azure/azure-sdk-for-net/issues/10385
Id = operationLocation.Split('/').Last();
}
/// <summary>
/// Initializes a new instance of the <see cref="RecognizeContentOperation"/> class.
/// </summary>
protected RecognizeContentOperation()
{
}
/// <inheritdoc/>
public override Response GetRawResponse() => _response;
/// <inheritdoc/>
public override ValueTask<Response<FormPageCollection>> WaitForCompletionAsync(CancellationToken cancellationToken = default) =>
this.DefaultWaitForCompletionAsync(cancellationToken);
/// <inheritdoc/>
public override ValueTask<Response<FormPageCollection>> WaitForCompletionAsync(TimeSpan pollingInterval, CancellationToken cancellationToken = default) =>
this.DefaultWaitForCompletionAsync(pollingInterval, cancellationToken);
/// <inheritdoc/>
public override Response UpdateStatus(CancellationToken cancellationToken = default) =>
UpdateStatusAsync(false, cancellationToken).EnsureCompleted();
/// <inheritdoc/>
public override async ValueTask<Response> UpdateStatusAsync(CancellationToken cancellationToken = default) =>
await UpdateStatusAsync(true, cancellationToken).ConfigureAwait(false);
/// <summary>
/// Calls the server to get updated status of the long-running operation.
/// </summary>
/// <param name="async">When <c>true</c>, the method will be executed asynchronously; otherwise, it will execute synchronously.</param>
/// <param name="cancellationToken">A <see cref="CancellationToken"/> controlling the request lifetime.</param>
/// <returns>The HTTP response from the service.</returns>
private async ValueTask<Response> UpdateStatusAsync(bool async, CancellationToken cancellationToken)
{
if (!_hasCompleted)
{
Response<AnalyzeOperationResult_internal> update = async
? await _serviceClient.GetAnalyzeLayoutResultAsync(new Guid(Id), cancellationToken).ConfigureAwait(false)
: _serviceClient.GetAnalyzeLayoutResult(new Guid(Id), cancellationToken);
if (update.Value.Status == OperationStatus.Succeeded || update.Value.Status == OperationStatus.Failed)
{
_hasCompleted = true;
_value = ConvertValue(update.Value.AnalyzeResult.PageResults, update.Value.AnalyzeResult.ReadResults);
}
_response = update.GetRawResponse();
}
return GetRawResponse();
}
private static FormPageCollection ConvertValue(IReadOnlyList<PageResult_internal> pageResults, IReadOnlyList<ReadResult_internal> readResults)
{
Debug.Assert(pageResults.Count == readResults.Count);
List<FormPage> pages = new List<FormPage>();
List<ReadResult_internal> rawPages = readResults.ToList();
for (var pageIndex = 0; pageIndex < pageResults.Count; pageIndex++)
{
pages.Add(new FormPage(pageResults[pageIndex], rawPages, pageIndex));
}
return new FormPageCollection(pages);
}
}
}
| 43.592857 | 168 | 0.660823 |
[
"MIT"
] |
XiangyuL-Microsoft/azure-sdk-for-net
|
sdk/formrecognizer/Azure.AI.FormRecognizer/src/RecognizeContentOperation.cs
| 6,105 |
C#
|
using System;
using System.Collections.Generic;
using System.Text;
namespace TimeSpanParserUtil
{
class TimeSpanToken : ParserToken {
public TimeSpan? timespan;
public Units smallest = Units.None;
public bool initialNegative = false;
public override bool IsInitialNegative() {
//return timespan < TimeSpan.Zero;
return initialNegative;
}
public override bool IsNull() {
return !timespan.HasValue;
}
public override bool IsZero() {
return timespan == TimeSpan.Zero;
}
public override TimeSpan? ToTimeSpan() {
return timespan;
}
public override bool UsesColonedDefault() {
return false;
}
protected override Units SmallestUnit() {
return smallest;
}
//delete me
protected Units SmallestUnitv2() {
if (!timespan.HasValue)
return Units.None;
TimeSpan t = (TimeSpan) timespan.Value;
if (t.Ticks != 0 || t.Milliseconds != 0)
return Units.Milliseconds;
if (t.Seconds != 0)
return Units.Seconds;
if (t.Minutes != 0)
return Units.Minutes;
if (t.Hours != 0)
return Units.Hours;
if (t.Days != 0)
return Units.Days;
return Units.Years; // uh not quite right
}
}
}
| 23.746032 | 53 | 0.529412 |
[
"MIT"
] |
floydpink/TimeSpanParser
|
TimeParser/TimeParser/Tokens/TimeSpanToken.cs
| 1,498 |
C#
|
using System;
using DDD.SimpleExample.Common.Events;
using NEventStore;
using NEventStore.Dispatcher;
namespace DDD.SimpleExample.WriteSide
{
public class InternalDispatcher : IDispatchCommits
{
private readonly IEventPublisher _publisher;
public InternalDispatcher(IEventPublisher publisher)
{
_publisher = publisher;
}
public void Dispose()
{
GC.SuppressFinalize(this);
}
public void Dispatch(ICommit commit)
{
foreach (var e in commit.Events)
{
//var messageType = e.Body.GetType();
_publisher.PublishAsync(e.Body);
}
}
}
}
| 23.064516 | 60 | 0.587413 |
[
"MIT"
] |
Szer/DDD.SimpleExample
|
DDD.SimpleExample.WriteSide/InternalDispatcher.cs
| 717 |
C#
|
//Copyright (c) Microsoft Corporation. All rights reserved.
using System;
using System.Diagnostics;
using System.Runtime.InteropServices;
namespace Microsoft.WindowsAPI.Shell
{
/// <summary>
/// Represents a registered non file system Known Folder
/// </summary>
public class NonFileSystemKnownFolder : ShellNonFileSystemFolder, IKnownFolder, IDisposable
{
#region Private Fields
private IKnownFolderNative knownFolderNative;
private KnownFolderSettings knownFolderSettings;
#endregion
#region Internal Constructors
internal NonFileSystemKnownFolder(IShellItem2 shellItem) : base(shellItem) { }
internal NonFileSystemKnownFolder(IKnownFolderNative kf)
{
Debug.Assert(kf != null);
knownFolderNative = kf;
// Set the native shell item
// and set it on the base class (ShellObject)
Guid guid = new Guid(ShellIIDGuid.IShellItem2);
knownFolderNative.GetShellItem(0, ref guid, out nativeShellItem);
}
#endregion
#region Private Members
private KnownFolderSettings KnownFolderSettings
{
get
{
if (knownFolderNative == null)
{
// We need to get the PIDL either from the NativeShellItem,
// or from base class's property (if someone already set it on us).
// Need to use the PIDL to get the native IKnownFolder interface.
// Get teh PIDL for the ShellItem
if (nativeShellItem != null && base.PIDL == IntPtr.Zero)
{
base.PIDL = ShellHelper.PidlFromShellItem(nativeShellItem);
}
// If we have a valid PIDL, get the native IKnownFolder
if (base.PIDL != IntPtr.Zero)
{
knownFolderNative = KnownFolderHelper.FromPIDL(base.PIDL);
}
Debug.Assert(knownFolderNative != null);
}
// If this is the first time this property is being called,
// get the native Folder Defination (KnownFolder properties)
if (knownFolderSettings == null)
{
knownFolderSettings = new KnownFolderSettings(knownFolderNative);
}
return knownFolderSettings;
}
}
#endregion
#region IKnownFolder Members
/// <summary>
/// Gets the path for this known folder.
/// </summary>
/// <value>A <see cref="System.String"/> object.</value>
public string Path
{
get { return KnownFolderSettings.Path; }
}
/// <summary>
/// Gets the category designation for this known folder.
/// </summary>
/// <value>A <see cref="FolderCategory"/> value.</value>
public FolderCategory Category
{
get { return KnownFolderSettings.Category; }
}
/// <summary>
/// Gets this known folder's canonical name.
/// </summary>
/// <value>A <see cref="System.String"/> object.</value>
public string CanonicalName
{
get { return KnownFolderSettings.CanonicalName; }
}
/// <summary>
/// Gets this known folder's description.
/// </summary>
/// <value>A <see cref="System.String"/> object.</value>
public string Description
{
get { return KnownFolderSettings.Description; }
}
/// <summary>
/// Gets the unique identifier for this known folder's parent folder.
/// </summary>
/// <value>A <see cref="System.Guid"/> value.</value>
public Guid ParentId
{
get { return KnownFolderSettings.ParentId; }
}
/// <summary>
/// Gets this known folder's relative path.
/// </summary>
/// <value>A <see cref="System.String"/> object.</value>
public string RelativePath
{
get { return KnownFolderSettings.RelativePath; }
}
/// <summary>
/// Gets this known folder's parsing name.
/// </summary>
/// <value>A <see cref="System.String"/> object.</value>
public override string ParsingName
{
get { return base.ParsingName; }
}
/// <summary>
/// Gets this known folder's tool tip text.
/// </summary>
/// <value>A <see cref="System.String"/> object.</value>
public string Tooltip
{
get { return KnownFolderSettings.Tooltip; }
}
/// <summary>
/// Gets the resource identifier for this
/// known folder's tool tip text.
/// </summary>
/// <value>A <see cref="System.String"/> object.</value>
public string TooltipResourceId
{
get { return KnownFolderSettings.TooltipResourceId; }
}
/// <summary>
/// Gets this known folder's localized name.
/// </summary>
/// <value>A <see cref="System.String"/> object.</value>
public string LocalizedName
{
get { return KnownFolderSettings.LocalizedName; }
}
/// <summary>
/// Gets the resource identifier for this
/// known folder's localized name.
/// </summary>
/// <value>A <see cref="System.String"/> object.</value>
public string LocalizedNameResourceId
{
get { return KnownFolderSettings.LocalizedNameResourceId; }
}
/// <summary>
/// Gets this known folder's security attributes.
/// </summary>
/// <value>A <see cref="System.String"/> object.</value>
public string Security
{
get { return KnownFolderSettings.Security; }
}
/// <summary>
/// Gets this known folder's file attributes,
/// such as "read-only".
/// </summary>
/// <value>A <see cref="System.IO.FileAttributes"/> value.</value>
public System.IO.FileAttributes FileAttributes
{
get { return KnownFolderSettings.FileAttributes; }
}
/// <summary>
/// Gets an value that describes this known folder's behaviors.
/// </summary>
/// <value>A <see cref="DefinitionOptions"/> value.</value>
public DefinitionOptions DefinitionOptions
{
get { return KnownFolderSettings.DefinitionOptions; }
}
/// <summary>
/// Gets the unique identifier for this known folder's type.
/// </summary>
/// <value>A <see cref="System.Guid"/> value.</value>
public Guid FolderTypeId
{
get { return KnownFolderSettings.FolderTypeId; }
}
/// <summary>
/// Gets a string representation of this known folder's type.
/// </summary>
/// <value>A <see cref="System.String"/> object.</value>
public string FolderType
{
get { return KnownFolderSettings.FolderType; }
}
/// <summary>
/// Gets the unique identifier for this known folder.
/// </summary>
/// <value>A <see cref="System.Guid"/> value.</value>
public Guid FolderId
{
get { return KnownFolderSettings.FolderId; }
}
/// <summary>
/// Gets a value that indicates whether this known folder's path exists on the computer.
/// </summary>
/// <value>A bool<see cref="System.Boolean"/> value.</value>
/// <remarks>If this property value is <b>false</b>,
/// the folder might be a virtual folder (<see cref="Category"/> property will
/// be <see cref="FolderCategory.Virtual"/> for virtual folders)</remarks>
public bool PathExists
{
get { return KnownFolderSettings.PathExists; }
}
/// <summary>
/// Gets a value that states whether this known folder
/// can have its path set to a new value,
/// including any restrictions on the redirection.
/// </summary>
/// <value>A <see cref="RedirectionCapability"/> value.</value>
public RedirectionCapability Redirection
{
get { return KnownFolderSettings.Redirection; }
}
#endregion
#region IDisposable Members
/// <summary>
/// Release resources
/// </summary>
/// <param name="disposing">Indicates that this mothod is being called from Dispose() rather than the finalizer.</param>
protected override void Dispose(bool disposing)
{
if (disposing)
{
knownFolderSettings = null;
}
if (knownFolderNative != null)
{
Marshal.ReleaseComObject(knownFolderNative);
knownFolderNative = null;
}
base.Dispose(disposing);
}
#endregion
}
}
| 32.565371 | 128 | 0.546007 |
[
"MIT"
] |
shellscape/Shellscape.Common
|
Microsoft/Windows API/Shell/KnownFolders/NonFileSystemKnownFolder.cs
| 9,218 |
C#
|
namespace AndroMDA.VS80AddIn.Dialogs
{
partial class AboutOptionsPage
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Component Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.components = new System.ComponentModel.Container();
System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(AboutOptionsPage));
System.Windows.Forms.ListViewGroup listViewGroup1 = new System.Windows.Forms.ListViewGroup("Code Statistics", System.Windows.Forms.HorizontalAlignment.Left);
System.Windows.Forms.ListViewGroup listViewGroup2 = new System.Windows.Forms.ListViewGroup("File Statistics", System.Windows.Forms.HorizontalAlignment.Left);
this.label1 = new System.Windows.Forms.Label();
this.pictureBox1 = new System.Windows.Forms.PictureBox();
this.lblVersion = new System.Windows.Forms.Label();
this.tabControl1 = new System.Windows.Forms.TabControl();
this.tabPage1 = new System.Windows.Forms.TabPage();
this.listViewStatus = new System.Windows.Forms.ListView();
this.columnHeader3 = new System.Windows.Forms.ColumnHeader();
this.columnHeader4 = new System.Windows.Forms.ColumnHeader();
this.tabPage3 = new System.Windows.Forms.TabPage();
this.pnlGenerating = new System.Windows.Forms.Panel();
this.label3 = new System.Windows.Forms.Label();
this.pictureBox2 = new System.Windows.Forms.PictureBox();
this.listViewStatistics = new System.Windows.Forms.ListView();
this.columnHeader1 = new System.Windows.Forms.ColumnHeader();
this.columnHeader2 = new System.Windows.Forms.ColumnHeader();
this.tabPage2 = new System.Windows.Forms.TabPage();
this.richTextBox1 = new System.Windows.Forms.RichTextBox();
this.imageList1 = new System.Windows.Forms.ImageList(this.components);
((System.ComponentModel.ISupportInitialize)(this.pictureBox1)).BeginInit();
this.tabControl1.SuspendLayout();
this.tabPage1.SuspendLayout();
this.tabPage3.SuspendLayout();
this.pnlGenerating.SuspendLayout();
((System.ComponentModel.ISupportInitialize)(this.pictureBox2)).BeginInit();
this.tabPage2.SuspendLayout();
this.SuspendLayout();
//
// label1
//
this.label1.AutoSize = true;
this.label1.BackColor = System.Drawing.Color.Black;
this.label1.Font = new System.Drawing.Font("Microsoft Sans Serif", 8.25F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.label1.ForeColor = System.Drawing.Color.LightGray;
this.label1.Location = new System.Drawing.Point(113, 55);
this.label1.Name = "label1";
this.label1.Size = new System.Drawing.Size(260, 13);
this.label1.TabIndex = 0;
this.label1.Text = "Visual Studio 2005 integration for AndroMDA";
//
// pictureBox1
//
this.pictureBox1.BackColor = System.Drawing.Color.Black;
this.pictureBox1.Dock = System.Windows.Forms.DockStyle.Top;
this.pictureBox1.Image = ((System.Drawing.Image)(resources.GetObject("pictureBox1.Image")));
this.pictureBox1.Location = new System.Drawing.Point(0, 0);
this.pictureBox1.Name = "pictureBox1";
this.pictureBox1.Size = new System.Drawing.Size(395, 95);
this.pictureBox1.SizeMode = System.Windows.Forms.PictureBoxSizeMode.AutoSize;
this.pictureBox1.TabIndex = 4;
this.pictureBox1.TabStop = false;
//
// lblVersion
//
this.lblVersion.BackColor = System.Drawing.Color.Black;
this.lblVersion.Font = new System.Drawing.Font("Microsoft Sans Serif", 8.25F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.lblVersion.ForeColor = System.Drawing.Color.Gray;
this.lblVersion.Location = new System.Drawing.Point(300, 68);
this.lblVersion.Name = "lblVersion";
this.lblVersion.Size = new System.Drawing.Size(73, 13);
this.lblVersion.TabIndex = 0;
this.lblVersion.Text = "version";
this.lblVersion.TextAlign = System.Drawing.ContentAlignment.MiddleRight;
//
// tabControl1
//
this.tabControl1.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom)
| System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.tabControl1.Appearance = System.Windows.Forms.TabAppearance.FlatButtons;
this.tabControl1.Controls.Add(this.tabPage1);
this.tabControl1.Controls.Add(this.tabPage3);
this.tabControl1.Controls.Add(this.tabPage2);
this.tabControl1.ImageList = this.imageList1;
this.tabControl1.Location = new System.Drawing.Point(0, 101);
this.tabControl1.Name = "tabControl1";
this.tabControl1.SelectedIndex = 0;
this.tabControl1.Size = new System.Drawing.Size(395, 239);
this.tabControl1.TabIndex = 5;
this.tabControl1.SelectedIndexChanged += new System.EventHandler(this.tabControl1_SelectedIndexChanged);
//
// tabPage1
//
this.tabPage1.Controls.Add(this.listViewStatus);
this.tabPage1.ImageIndex = 2;
this.tabPage1.Location = new System.Drawing.Point(4, 26);
this.tabPage1.Name = "tabPage1";
this.tabPage1.Padding = new System.Windows.Forms.Padding(3);
this.tabPage1.Size = new System.Drawing.Size(387, 209);
this.tabPage1.TabIndex = 0;
this.tabPage1.Text = "Status";
this.tabPage1.UseVisualStyleBackColor = true;
//
// listViewStatus
//
this.listViewStatus.Columns.AddRange(new System.Windows.Forms.ColumnHeader[] {
this.columnHeader3,
this.columnHeader4});
this.listViewStatus.Dock = System.Windows.Forms.DockStyle.Fill;
this.listViewStatus.FullRowSelect = true;
this.listViewStatus.GridLines = true;
this.listViewStatus.HeaderStyle = System.Windows.Forms.ColumnHeaderStyle.None;
this.listViewStatus.Location = new System.Drawing.Point(3, 3);
this.listViewStatus.MultiSelect = false;
this.listViewStatus.Name = "listViewStatus";
this.listViewStatus.Size = new System.Drawing.Size(381, 203);
this.listViewStatus.TabIndex = 7;
this.listViewStatus.UseCompatibleStateImageBehavior = false;
this.listViewStatus.View = System.Windows.Forms.View.Details;
//
// columnHeader3
//
this.columnHeader3.Text = "Stat";
this.columnHeader3.Width = 153;
//
// columnHeader4
//
this.columnHeader4.Text = "Value";
this.columnHeader4.Width = 199;
//
// tabPage3
//
this.tabPage3.Controls.Add(this.pnlGenerating);
this.tabPage3.Controls.Add(this.listViewStatistics);
this.tabPage3.ImageIndex = 0;
this.tabPage3.Location = new System.Drawing.Point(4, 26);
this.tabPage3.Name = "tabPage3";
this.tabPage3.Padding = new System.Windows.Forms.Padding(3);
this.tabPage3.Size = new System.Drawing.Size(387, 209);
this.tabPage3.TabIndex = 2;
this.tabPage3.Text = "Statistics";
this.tabPage3.UseVisualStyleBackColor = true;
//
// pnlGenerating
//
this.pnlGenerating.BackColor = System.Drawing.Color.White;
this.pnlGenerating.BorderStyle = System.Windows.Forms.BorderStyle.Fixed3D;
this.pnlGenerating.Controls.Add(this.label3);
this.pnlGenerating.Controls.Add(this.pictureBox2);
this.pnlGenerating.Dock = System.Windows.Forms.DockStyle.Fill;
this.pnlGenerating.Location = new System.Drawing.Point(3, 3);
this.pnlGenerating.Name = "pnlGenerating";
this.pnlGenerating.Size = new System.Drawing.Size(381, 203);
this.pnlGenerating.TabIndex = 7;
//
// label3
//
this.label3.Anchor = System.Windows.Forms.AnchorStyles.Top;
this.label3.AutoSize = true;
this.label3.Font = new System.Drawing.Font("Microsoft Sans Serif", 8.25F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.label3.Location = new System.Drawing.Point(121, 127);
this.label3.Name = "label3";
this.label3.Size = new System.Drawing.Size(135, 13);
this.label3.TabIndex = 9;
this.label3.Text = "Generating statistics...";
//
// pictureBox2
//
this.pictureBox2.Anchor = System.Windows.Forms.AnchorStyles.Top;
this.pictureBox2.BackColor = System.Drawing.Color.White;
this.pictureBox2.Image = global::AndroMDA.VS80AddIn.Resource1.indicator_waitanim;
this.pictureBox2.Location = new System.Drawing.Point(147, 41);
this.pictureBox2.Name = "pictureBox2";
this.pictureBox2.Size = new System.Drawing.Size(83, 76);
this.pictureBox2.TabIndex = 8;
this.pictureBox2.TabStop = false;
//
// listViewStatistics
//
this.listViewStatistics.Columns.AddRange(new System.Windows.Forms.ColumnHeader[] {
this.columnHeader1,
this.columnHeader2});
this.listViewStatistics.Dock = System.Windows.Forms.DockStyle.Fill;
this.listViewStatistics.FullRowSelect = true;
this.listViewStatistics.GridLines = true;
listViewGroup1.Header = "Code Statistics";
listViewGroup1.Name = "listViewGroup1";
listViewGroup2.Header = "File Statistics";
listViewGroup2.Name = "listViewGroup2";
this.listViewStatistics.Groups.AddRange(new System.Windows.Forms.ListViewGroup[] {
listViewGroup1,
listViewGroup2});
this.listViewStatistics.HeaderStyle = System.Windows.Forms.ColumnHeaderStyle.None;
this.listViewStatistics.Location = new System.Drawing.Point(3, 3);
this.listViewStatistics.MultiSelect = false;
this.listViewStatistics.Name = "listViewStatistics";
this.listViewStatistics.Size = new System.Drawing.Size(381, 203);
this.listViewStatistics.TabIndex = 6;
this.listViewStatistics.UseCompatibleStateImageBehavior = false;
this.listViewStatistics.View = System.Windows.Forms.View.Details;
//
// columnHeader1
//
this.columnHeader1.Text = "Stat";
this.columnHeader1.Width = 219;
//
// columnHeader2
//
this.columnHeader2.Text = "Value";
this.columnHeader2.Width = 127;
//
// tabPage2
//
this.tabPage2.Controls.Add(this.richTextBox1);
this.tabPage2.ImageIndex = 1;
this.tabPage2.Location = new System.Drawing.Point(4, 26);
this.tabPage2.Name = "tabPage2";
this.tabPage2.Padding = new System.Windows.Forms.Padding(3);
this.tabPage2.Size = new System.Drawing.Size(387, 209);
this.tabPage2.TabIndex = 1;
this.tabPage2.Text = "About";
this.tabPage2.UseVisualStyleBackColor = true;
//
// richTextBox1
//
this.richTextBox1.BackColor = System.Drawing.Color.White;
this.richTextBox1.Cursor = System.Windows.Forms.Cursors.Arrow;
this.richTextBox1.Dock = System.Windows.Forms.DockStyle.Fill;
this.richTextBox1.Location = new System.Drawing.Point(3, 3);
this.richTextBox1.Name = "richTextBox1";
this.richTextBox1.ReadOnly = true;
this.richTextBox1.Size = new System.Drawing.Size(381, 203);
this.richTextBox1.TabIndex = 0;
this.richTextBox1.Text = "";
this.richTextBox1.LinkClicked += new System.Windows.Forms.LinkClickedEventHandler(this.richTextBox1_LinkClicked);
//
// imageList1
//
this.imageList1.ImageStream = ((System.Windows.Forms.ImageListStreamer)(resources.GetObject("imageList1.ImageStream")));
this.imageList1.TransparentColor = System.Drawing.Color.Transparent;
this.imageList1.Images.SetKeyName(0, "propertiesORoptions.ico");
this.imageList1.Images.SetKeyName(1, "help.ico");
this.imageList1.Images.SetKeyName(2, "install.ico");
//
// AboutOptionsPage
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.Controls.Add(this.tabControl1);
this.Controls.Add(this.lblVersion);
this.Controls.Add(this.label1);
this.Controls.Add(this.pictureBox1);
this.Name = "AboutOptionsPage";
this.Size = new System.Drawing.Size(395, 340);
((System.ComponentModel.ISupportInitialize)(this.pictureBox1)).EndInit();
this.tabControl1.ResumeLayout(false);
this.tabPage1.ResumeLayout(false);
this.tabPage3.ResumeLayout(false);
this.pnlGenerating.ResumeLayout(false);
this.pnlGenerating.PerformLayout();
((System.ComponentModel.ISupportInitialize)(this.pictureBox2)).EndInit();
this.tabPage2.ResumeLayout(false);
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
private System.Windows.Forms.PictureBox pictureBox1;
private System.Windows.Forms.Label label1;
private System.Windows.Forms.Label lblVersion;
private System.Windows.Forms.TabPage tabPage1;
private System.Windows.Forms.TabPage tabPage2;
private System.Windows.Forms.ImageList imageList1;
private System.Windows.Forms.TabPage tabPage3;
private System.Windows.Forms.ListView listViewStatus;
private System.Windows.Forms.ColumnHeader columnHeader3;
private System.Windows.Forms.ColumnHeader columnHeader4;
private System.Windows.Forms.ListView listViewStatistics;
private System.Windows.Forms.ColumnHeader columnHeader1;
private System.Windows.Forms.ColumnHeader columnHeader2;
private System.Windows.Forms.Panel pnlGenerating;
private System.Windows.Forms.Label label3;
private System.Windows.Forms.PictureBox pictureBox2;
private System.Windows.Forms.TabControl tabControl1;
private System.Windows.Forms.RichTextBox richTextBox1;
}
}
| 51.527157 | 169 | 0.62407 |
[
"BSD-3-Clause"
] |
ojmakhura/andromda
|
andromda-etc/andromda-dotnet/AndroMDA.VS80AddIn/AndroMDA.VS80AddIn/OptionsPages/AboutOptionsPage.designer.cs
| 16,128 |
C#
|
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.HttpsPolicy;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace MySql.Tutorial.Mvc
{
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
services.AddControllersWithViews();
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
app.UseExceptionHandler("/Home/Error");
// The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
app.UseHsts();
}
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseRouting();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllerRoute(
name: "default",
pattern: "{controller=Home}/{action=Index}/{id?}");
});
}
}
}
| 30.689655 | 143 | 0.610112 |
[
"MIT"
] |
ellorenz2/MySql.Tutorial
|
MySql.Tutorial.Mvc/Startup.cs
| 1,780 |
C#
|
using Jamiras.Components;
using NUnit.Framework;
using RATools.Parser.Internal;
using RATools.Test.Data;
using System.Text;
namespace RATools.Test.Parser.Internal
{
[TestFixture]
class FloatConstantExpressionTests
{
[Test]
[TestCase("2.0", 2.0f)]
[TestCase("3.14", 3.14f)]
[TestCase("-6.12345", -6.12345f)]
public void TestParseExpression(string input, float expected)
{
var expr = ExpressionBase.Parse(new PositionalTokenizer(Tokenizer.CreateTokenizer(input)));
Assert.That(expr, Is.InstanceOf<FloatConstantExpression>());
Assert.That(((FloatConstantExpression)expr).Value, Is.EqualTo(expected));
}
[Test]
[TestCase("2.0", 2.0f)]
[TestCase("3.14", 3.14f)]
[TestCase("-6.12345", -6.12345f)]
public void TestParseExpressionCulture(string input, float expected)
{
using (var cultureOverride = new CultureOverride("fr-FR"))
{
var expr = ExpressionBase.Parse(new PositionalTokenizer(Tokenizer.CreateTokenizer(input)));
Assert.That(expr, Is.InstanceOf<FloatConstantExpression>());
Assert.That(((FloatConstantExpression)expr).Value, Is.EqualTo(expected));
}
}
[Test]
[TestCase(2.0, "2.0")]
[TestCase(3.14, "3.14")]
[TestCase(-6.12345, "-6.12345")]
public void TestAppendString(double value, string expected)
{
var expr = new FloatConstantExpression((float)value);
var builder = new StringBuilder();
expr.AppendString(builder);
Assert.That(builder.ToString(), Is.EqualTo(expected));
}
[Test]
[TestCase(2.0, "2.0")]
[TestCase(3.14, "3.14")]
[TestCase(-6.12345, "-6.12345")]
public void TestAppendStringCulture(double value, string expected)
{
using (var cultureOverride = new CultureOverride("fr-FR"))
{
var expr = new FloatConstantExpression((float)value);
var builder = new StringBuilder();
expr.AppendString(builder);
Assert.That(builder.ToString(), Is.EqualTo(expected));
}
}
}
}
| 34.19403 | 107 | 0.583151 |
[
"MIT"
] |
soopercool101/RATools
|
Tests/Parser/Internal/FloatConstantExpressionTests.cs
| 2,293 |
C#
|
using CupCake.Command;
using CupCake.Command.Source;
using CupCake.Messages.Blocks;
using CupCake.Permissions;
namespace CupCake.DefaultCommands.Commands.Utility
{
public class BlueCommand : UtilityCommandBase
{
[MinGroup(Group.Moderator)]
[Label("blue")]
[CorrectUsage("")]
protected override void Run(IInvokeSource source, ParsedCommand message)
{
this.KeyService.PressKey(Key.Blue);
source.Reply("Pressed blue key.");
}
}
}
| 26.947368 | 80 | 0.662109 |
[
"MIT"
] |
KylerM/CupCake
|
CupCake.DefaultCommands/Commands/Utility/BlueCommand.cs
| 514 |
C#
|
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
// Runtime Version:4.0.30319.42000
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
using System;
using System.Reflection;
[assembly: System.Reflection.AssemblyCompanyAttribute("ImplementingCustomStack")]
[assembly: System.Reflection.AssemblyConfigurationAttribute("Release")]
[assembly: System.Reflection.AssemblyFileVersionAttribute("1.0.0.0")]
[assembly: System.Reflection.AssemblyInformationalVersionAttribute("1.0.0")]
[assembly: System.Reflection.AssemblyProductAttribute("ImplementingCustomStack")]
[assembly: System.Reflection.AssemblyTitleAttribute("ImplementingCustomStack")]
[assembly: System.Reflection.AssemblyVersionAttribute("1.0.0.0")]
// Generated by the MSBuild WriteCodeFragment class.
| 42.541667 | 81 | 0.661117 |
[
"MIT"
] |
wuweisage/Softuni-Svetlina-Projects-and-Code
|
C#/OOP/06.Implementing-Stack-Exercises/Lab_ImplementingStack/ImplementingCustomStack/obj/Release/netcoreapp3.1/ImplementingCustomStack.AssemblyInfo.cs
| 1,021 |
C#
|
using System.Reflection;
using System.Runtime.InteropServices;
// Les informations générales relatives à un assembly dépendent de
// l'ensemble d'attributs suivant. Changez les valeurs de ces attributs pour modifier les informations
// associées à un assembly.
[assembly: AssemblyTitle("Wexflow.Tasks.MailsSender")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Wexflow")]
[assembly: AssemblyProduct("Wexflow.Tasks.MailsSender")]
[assembly: AssemblyCopyright("Copyright © Akram El Assas 2016")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// L'affectation de la valeur false à ComVisible rend les types invisibles dans cet assembly
// aux composants COM. Si vous devez accéder à un type dans cet assembly à partir de
// COM, affectez la valeur true à l'attribut ComVisible sur ce type.
[assembly: ComVisible(false)]
// Le GUID suivant est pour l'ID de la typelib si ce projet est exposé à COM
[assembly: Guid("65569157-d05f-4f9a-9b64-68a0ae21beee")]
// Les informations de version pour un assembly se composent des quatre valeurs suivantes :
//
// Version principale
// Version secondaire
// Numéro de build
// Révision
//
// Vous pouvez spécifier toutes les valeurs ou indiquer les numéros de build et de révision par défaut
// en utilisant '*', comme indiqué ci-dessous :
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("5.6.0.0")]
[assembly: AssemblyFileVersion("5.6.0.0")]
| 41.777778 | 103 | 0.75133 |
[
"MIT"
] |
weirdyang/Wexflow
|
src/net/Wexflow.Tasks.MailsSender/Properties/AssemblyInfo.cs
| 1,529 |
C#
|
//--------------------------------------------------------------------------------------------
// Copyright 2015 Sitecore Corporation A/S
// Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file
// except in compliance with the License. You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software distributed under the
// License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
// either express or implied. See the License for the specific language governing permissions
// and limitations under the License.
// -------------------------------------------------------------------------------------------
using System;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Web.Http;
using ExperienceExtractor.Api.Jobs;
namespace ExperienceExtractor.Api.Http.Controllers
{
[RequireSitecoreLogin]
public class ExperienceExtractorJobResultsController : ApiController
{
private readonly IJobRepository _repository;
public ExperienceExtractorJobResultsController()
: this(ExperienceExtractorApiContainer.JobRepository)
{
}
public ExperienceExtractorJobResultsController(IJobRepository repository)
{
_repository = repository;
}
// GET api/jobs/{id}/result
public HttpResponseMessage Get(Guid id)
{
var stream = _repository.GetZippedResult(id);
if (stream == null)
{
return new HttpResponseMessage(HttpStatusCode.NotFound);
}
var result = new HttpResponseMessage(HttpStatusCode.OK) {Content = new StreamContent(stream)};
result.Content.Headers.ContentType =
new MediaTypeHeaderValue("application/zip");
result.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment")
{
FileName = id.ToString("d") + ".zip"
};
return result;
}
}
}
| 35.540984 | 106 | 0.612546 |
[
"Apache-2.0"
] |
STDGA/experience-extractor
|
src/ExperienceExtractor/Api/Http/Controllers/ExperienceExtractorJobResultsController.cs
| 2,170 |
C#
|
// The MIT License (MIT)
//
// Copyright (c) 2014-2017, Institute for Software & Systems Engineering
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
namespace ISSE.SafetyChecking.StateGraphModel
{
using System;
using System.Linq;
using ExecutableModel;
using Modeling;
using AnalysisModel;
using AnalysisModelTraverser;
using ExecutedModel;
using FaultMinimalKripkeStructure;
using Formula;
using MinimalCriticalSetAnalysis;
/// <summary>
/// Pre-builts the model's entire state graph, subsequently taking advantage of the fault-removal optimization.
/// </summary>
internal class StateGraphBackend<TExecutableModel> : AnalysisBackend<TExecutableModel> where TExecutableModel : ExecutableModel<TExecutableModel>
{
private InvariantChecker _checker;
/// <summary>
/// Initializes the model that should be analyzed.
/// </summary>
/// <param name="configuration">The configuration that should be used for the analyses.</param>
/// <param name="hazard">The hazard that should be analyzed.</param>
protected override void InitializeModel(AnalysisConfiguration configuration, Formula hazard)
{
var invariant = new UnaryFormula(hazard, UnaryOperator.Not);
var checker = new QualitativeChecker<TExecutableModel>(RuntimeModelCreator) { Configuration = configuration };
checker.Configuration.ProgressReportsOnly = false;
var stateGraph = checker.GenerateStateGraph();
var stateCapacity = Math.Max(1024, (int)(stateGraph.StateCount * 1.5));
var newModelCapacity = new ModelCapacityByModelDensity(stateCapacity, ModelDensityLimit.High);
configuration.ModelCapacity=newModelCapacity;
Func<AnalysisModel> createAnalysisModelFunc = () => new StateGraphModel<TExecutableModel>(stateGraph, configuration.SuccessorCapacity);
var createAnalysisModel = new AnalysisModelCreator(createAnalysisModelFunc);
_checker = new InvariantChecker(createAnalysisModel, configuration, invariant);
}
/// <summary>
/// Checks the <see cref="faults" /> for criticality using the <see cref="activation" /> mode.
/// </summary>
/// <param name="faults">The fault set that should be checked for criticality.</param>
/// <param name="activation">The activation mode of the fault set.</param>
internal override InvariantAnalysisResult CheckCriticality(FaultSet faults, Activation activation)
{
var suppressedFaults = new FaultSet();
foreach (var fault in RuntimeModelCreator.FaultsInBaseModel)
{
if (GetEffectiveActivation(fault, faults, activation) == Activation.Suppressed)
suppressedFaults = suppressedFaults.Add(fault);
}
_checker.ModelTraverser.Context.TraversalParameters.TransitionModifiers.Clear();
_checker.ModelTraverser.Context.TraversalParameters.TransitionModifiers.Add(() => new FaultSuppressionModifier(suppressedFaults));
return _checker.Check();
}
/// <summary>
/// Checks the order of <see cref="firstFault" /> and <see cref="secondFault" /> for the
/// <see cref="minimalCriticalFaultSet" /> using the <see cref="activation" /> mode.
/// </summary>
/// <param name="firstFault">The first fault that should be checked.</param>
/// <param name="secondFault">The second fault that should be checked.</param>
/// <param name="minimalCriticalFaultSet">The minimal critical fault set that should be checked.</param>
/// <param name="activation">The activation mode of the fault set.</param>
/// <param name="forceSimultaneous">Indicates whether both faults must occur simultaneously.</param>
internal override InvariantAnalysisResult CheckOrder(Fault firstFault, Fault secondFault, FaultSet minimalCriticalFaultSet,
Activation activation, bool forceSimultaneous)
{
throw new NotImplementedException();
}
}
}
| 46.504854 | 146 | 0.758455 |
[
"MIT"
] |
isse-augsburg/ssharp
|
Source/SafetyChecking/StateGraphModel/StateGraphBackend.cs
| 4,790 |
C#
|
using System;
using System.Collections.Generic;
using System.Text;
namespace NCsvLib
{
public class SchemaOptions
{
public string FieldSeparator;
public bool LastFieldSeparator;
private string _Eol;
public string Eol
{
get { return _Eol; }
set
{
string v = value.ToLower();
if (v == "cr")
_Eol = Encoding.ASCII.GetString(new byte[] { 13 });
else if (v == "lf")
_Eol = Encoding.ASCII.GetString(new byte[] { 10 });
else if (v == "crlf")
_Eol = Encoding.ASCII.GetString(new byte[] { 13, 10 });
else
_Eol = value;
}
}
public string Quotes;
public Encoding Enc;
public SchemaOptions()
{
//Default values for options
Eol = Environment.NewLine;
FieldSeparator = string.Empty;
LastFieldSeparator = true;
Quotes = "\"";
Enc = Encoding.Default;
}
/// <summary>
/// If Enc is one of the common encodings (ie utf8) sets the encoding so
/// that the byte order mark is not emitted
/// </summary>
/// <param name="noBom"></param>
public void SetNoBomEncoding(bool noBom)
{
if (Enc == null)
return;
if (Enc.CodePage == Encoding.UTF8.CodePage)
{
if (noBom)
Enc = new UTF8Encoding(false);
else
Enc = Encoding.UTF8;
}
else if (Enc.CodePage == Encoding.Unicode.CodePage)
{
if (noBom)
Enc = new UnicodeEncoding(false, false);
else
Enc = Encoding.Unicode;
}
else if (Enc.CodePage == Encoding.BigEndianUnicode.CodePage)
{
if (noBom)
Enc = new UnicodeEncoding(true, false);
else
Enc = Encoding.BigEndianUnicode;
}
else if (Enc.CodePage == Encoding.UTF32.CodePage)
{
if (noBom)
Enc = new UTF32Encoding(false, false);
else
Enc = Encoding.UTF32;
}
}
}
}
| 31.049383 | 81 | 0.433797 |
[
"MIT"
] |
franksl/ncsvlib
|
NCsvLib/schema/SchemaOptions.cs
| 2,515 |
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.DataFactory.Outputs
{
[OutputType]
public sealed class ExecutePipelineActivityResponse
{
/// <summary>
/// Activity depends on condition.
/// </summary>
public readonly ImmutableArray<Outputs.ActivityDependencyResponse> DependsOn;
/// <summary>
/// Activity description.
/// </summary>
public readonly string? Description;
/// <summary>
/// Activity name.
/// </summary>
public readonly string Name;
/// <summary>
/// Pipeline parameters.
/// </summary>
public readonly ImmutableDictionary<string, object>? Parameters;
/// <summary>
/// Pipeline reference.
/// </summary>
public readonly Outputs.PipelineReferenceResponse Pipeline;
/// <summary>
/// Type of activity.
/// Expected value is 'Container'.
/// </summary>
public readonly string Type;
/// <summary>
/// Activity user properties.
/// </summary>
public readonly ImmutableArray<Outputs.UserPropertyResponse> UserProperties;
/// <summary>
/// Defines whether activity execution will wait for the dependent pipeline execution to finish. Default is false.
/// </summary>
public readonly bool? WaitOnCompletion;
[OutputConstructor]
private ExecutePipelineActivityResponse(
ImmutableArray<Outputs.ActivityDependencyResponse> dependsOn,
string? description,
string name,
ImmutableDictionary<string, object>? parameters,
Outputs.PipelineReferenceResponse pipeline,
string type,
ImmutableArray<Outputs.UserPropertyResponse> userProperties,
bool? waitOnCompletion)
{
DependsOn = dependsOn;
Description = description;
Name = name;
Parameters = parameters;
Pipeline = pipeline;
Type = type;
UserProperties = userProperties;
WaitOnCompletion = waitOnCompletion;
}
}
}
| 31.088608 | 122 | 0.611156 |
[
"Apache-2.0"
] |
pulumi-bot/pulumi-azure-native
|
sdk/dotnet/DataFactory/Outputs/ExecutePipelineActivityResponse.cs
| 2,456 |
C#
|
// Copyright (c) 2001-2021 Aspose Pty Ltd. All Rights Reserved.
//
// This file is part of Aspose.Words. The source code in this file
// is only intended as a supplement to the documentation, and is provided
// "as is", without warranty of any kind, either expressed or implied.
//////////////////////////////////////////////////////////////////////////
#if NET48 || NET5_0 || JAVA
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text.RegularExpressions;
using System.Xml;
using Aspose.Words;
using Aspose.Words.Fonts;
using Aspose.Words.Loading;
using NUnit.Framework;
namespace ApiExamples
{
[TestFixture]
class ExFontSettings : ApiExampleBase
{
[Test]
public void DefaultFontInstance()
{
//ExStart
//ExFor:Fonts.FontSettings.DefaultInstance
//ExSummary:Shows how to configure the default font settings instance.
// Configure the default font settings instance to use the "Courier New" font
// as a backup substitute when we attempt to use an unknown font.
FontSettings.DefaultInstance.SubstitutionSettings.DefaultFontSubstitution.DefaultFontName = "Courier New";
Assert.True(FontSettings.DefaultInstance.SubstitutionSettings.DefaultFontSubstitution.Enabled);
Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);
builder.Font.Name = "Non-existent font";
builder.Write("Hello world!");
// This document does not have a FontSettings configuration. When we render the document,
// the default FontSettings instance will resolve the missing font.
// Aspose.Words will use "Courier New" to render text that uses the unknown font.
Assert.Null(doc.FontSettings);
doc.Save(ArtifactsDir + "FontSettings.DefaultFontInstance.pdf");
//ExEnd
}
[Test]
public void DefaultFontName()
{
//ExStart
//ExFor:DefaultFontSubstitutionRule.DefaultFontName
//ExSummary:Shows how to specify a default font.
Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);
builder.Font.Name = "Arial";
builder.Writeln("Hello world!");
builder.Font.Name = "Arvo";
builder.Writeln("The quick brown fox jumps over the lazy dog.");
FontSourceBase[] fontSources = FontSettings.DefaultInstance.GetFontsSources();
// The font sources that the document uses contain the font "Arial", but not "Arvo".
Assert.AreEqual(1, fontSources.Length);
Assert.True(fontSources[0].GetAvailableFonts().Any(f => f.FullFontName == "Arial"));
Assert.False(fontSources[0].GetAvailableFonts().Any(f => f.FullFontName == "Arvo"));
// Set the "DefaultFontName" property to "Courier New" to,
// while rendering the document, apply that font in all cases when another font is not available.
FontSettings.DefaultInstance.SubstitutionSettings.DefaultFontSubstitution.DefaultFontName = "Courier New";
Assert.True(fontSources[0].GetAvailableFonts().Any(f => f.FullFontName == "Courier New"));
// Aspose.Words will now use the default font in place of any missing fonts during any rendering calls.
doc.Save(ArtifactsDir + "FontSettings.DefaultFontName.pdf");
//ExEnd
}
[Test]
public void UpdatePageLayoutWarnings()
{
// Store the font sources currently used so we can restore them later
FontSourceBase[] originalFontSources = FontSettings.DefaultInstance.GetFontsSources();
// Load the document to render
Document doc = new Document(MyDir + "Document.docx");
// Create a new class implementing IWarningCallback and assign it to the PdfSaveOptions class
HandleDocumentWarnings callback = new HandleDocumentWarnings();
doc.WarningCallback = callback;
// We can choose the default font to use in the case of any missing fonts
FontSettings.DefaultInstance.SubstitutionSettings.DefaultFontSubstitution.DefaultFontName = "Arial";
// For testing we will set Aspose.Words to look for fonts only in a folder which does not exist. Since Aspose.Words won't
// find any fonts in the specified directory, then during rendering the fonts in the document will be substituted with the default
// font specified under FontSettings.DefaultFontName. We can pick up on this substitution using our callback
FontSettings.DefaultInstance.SetFontsFolder(string.Empty, false);
// When you call UpdatePageLayout the document is rendered in memory. Any warnings that occurred during rendering
// are stored until the document save and then sent to the appropriate WarningCallback
doc.UpdatePageLayout();
// Even though the document was rendered previously, any save warnings are notified to the user during document save
doc.Save(ArtifactsDir + "FontSettings.UpdatePageLayoutWarnings.pdf");
Assert.That(callback.FontWarnings.Count, Is.GreaterThan(0));
Assert.True(callback.FontWarnings[0].WarningType == WarningType.FontSubstitution);
Assert.True(callback.FontWarnings[0].Description.Contains("has not been found"));
// Restore default fonts
FontSettings.DefaultInstance.SetFontsSources(originalFontSources);
}
public class HandleDocumentWarnings : IWarningCallback
{
/// <summary>
/// Our callback only needs to implement the "Warning" method. This method is called whenever there is a
/// potential issue during document processing. The callback can be set to listen for warnings generated during document
/// load and/or document save.
/// </summary>
public void Warning(WarningInfo info)
{
// We are only interested in fonts being substituted
if (info.WarningType == WarningType.FontSubstitution)
{
Console.WriteLine("Font substitution: " + info.Description);
FontWarnings.Warning(info);
}
}
public WarningInfoCollection FontWarnings = new WarningInfoCollection();
}
//ExStart
//ExFor:IWarningCallback
//ExFor:DocumentBase.WarningCallback
//ExFor:Fonts.FontSettings.DefaultInstance
//ExSummary:Shows how to use the IWarningCallback interface to monitor font substitution warnings.
[Test] //ExSkip
public void SubstitutionWarning()
{
Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);
builder.Font.Name = "Times New Roman";
builder.Writeln("Hello world!");
FontSubstitutionWarningCollector callback = new FontSubstitutionWarningCollector();
doc.WarningCallback = callback;
// Store the current collection of font sources, which will be the default font source for every document
// for which we do not specify a different font source.
FontSourceBase[] originalFontSources = FontSettings.DefaultInstance.GetFontsSources();
// For testing purposes, we will set Aspose.Words to look for fonts only in a folder that does not exist.
FontSettings.DefaultInstance.SetFontsFolder(string.Empty, false);
// When rendering the document, there will be no place to find the "Times New Roman" font.
// This will cause a font substitution warning, which our callback will detect.
doc.Save(ArtifactsDir + "FontSettings.SubstitutionWarning.pdf");
FontSettings.DefaultInstance.SetFontsSources(originalFontSources);
Assert.AreEqual(1, callback.FontSubstitutionWarnings.Count); //ExSkip
Assert.True(callback.FontSubstitutionWarnings[0].WarningType == WarningType.FontSubstitution);
Assert.True(callback.FontSubstitutionWarnings[0].Description
.Equals("Font 'Times New Roman' has not been found. Using 'Fanwood' font instead. Reason: first available font."));
}
private class FontSubstitutionWarningCollector : IWarningCallback
{
/// <summary>
/// Called every time a warning occurs during loading/saving.
/// </summary>
public void Warning(WarningInfo info)
{
if (info.WarningType == WarningType.FontSubstitution)
FontSubstitutionWarnings.Warning(info);
}
public WarningInfoCollection FontSubstitutionWarnings = new WarningInfoCollection();
}
//ExEnd
//ExStart
//ExFor:FontSourceBase.WarningCallback
//ExSummary:Shows how to call warning callback when the font sources working with.
[Test]
public void FontSourceWarning()
{
FontSettings settings = new FontSettings();
settings.SetFontsFolder("bad folder?", false);
FontSourceBase source = settings.GetFontsSources()[0];
FontSourceWarningCollector callback = new FontSourceWarningCollector();
source.WarningCallback = callback;
// Get the list of fonts to call warning callback.
IList<PhysicalFontInfo> fontInfos = source.GetAvailableFonts();
Assert.True(callback.FontSubstitutionWarnings[0].Description.Contains("Error loading font from the folder \"bad folder?\""));
}
private class FontSourceWarningCollector : IWarningCallback
{
/// <summary>
/// Called every time a warning occurs during processing of font source.
/// </summary>
public void Warning(WarningInfo info)
{
FontSubstitutionWarnings.Warning(info);
}
public readonly WarningInfoCollection FontSubstitutionWarnings = new WarningInfoCollection();
}
//ExEnd
//ExStart
//ExFor:Fonts.FontInfoSubstitutionRule
//ExFor:Fonts.FontSubstitutionSettings.FontInfoSubstitution
//ExFor:IWarningCallback
//ExFor:IWarningCallback.Warning(WarningInfo)
//ExFor:WarningInfo
//ExFor:WarningInfo.Description
//ExFor:WarningInfo.WarningType
//ExFor:WarningInfoCollection
//ExFor:WarningInfoCollection.Warning(WarningInfo)
//ExFor:WarningInfoCollection.GetEnumerator
//ExFor:WarningInfoCollection.Clear
//ExFor:WarningType
//ExFor:DocumentBase.WarningCallback
//ExSummary:Shows how to set the property for finding the closest match for a missing font from the available font sources.
[Test]
public void EnableFontSubstitution()
{
// Open a document that contains text formatted with a font that does not exist in any of our font sources.
Document doc = new Document(MyDir + "Missing font.docx");
// Assign a callback for handling font substitution warnings.
HandleDocumentSubstitutionWarnings substitutionWarningHandler = new HandleDocumentSubstitutionWarnings();
doc.WarningCallback = substitutionWarningHandler;
// Set a default font name and enable font substitution.
FontSettings fontSettings = new FontSettings();
fontSettings.SubstitutionSettings.DefaultFontSubstitution.DefaultFontName = "Arial"; ;
fontSettings.SubstitutionSettings.FontInfoSubstitution.Enabled = true;
// We will get a font substitution warning if we save a document with a missing font.
doc.FontSettings = fontSettings;
doc.Save(ArtifactsDir + "FontSettings.EnableFontSubstitution.pdf");
using (IEnumerator<WarningInfo> warnings = substitutionWarningHandler.FontWarnings.GetEnumerator())
while (warnings.MoveNext())
Console.WriteLine(warnings.Current.Description);
// We can also verify warnings in the collection and clear them.
Assert.AreEqual(WarningSource.Layout, substitutionWarningHandler.FontWarnings[0].Source);
Assert.AreEqual("Font '28 Days Later' has not been found. Using 'Calibri' font instead. Reason: alternative name from document.",
substitutionWarningHandler.FontWarnings[0].Description);
substitutionWarningHandler.FontWarnings.Clear();
Assert.That(substitutionWarningHandler.FontWarnings, Is.Empty);
}
public class HandleDocumentSubstitutionWarnings : IWarningCallback
{
/// <summary>
/// Called every time a warning occurs during loading/saving.
/// </summary>
public void Warning(WarningInfo info)
{
if (info.WarningType == WarningType.FontSubstitution)
FontWarnings.Warning(info);
}
public WarningInfoCollection FontWarnings = new WarningInfoCollection();
}
//ExEnd
[Test]
public void SubstitutionWarningsClosestMatch()
{
Document doc = new Document(MyDir + "Bullet points with alternative font.docx");
HandleDocumentSubstitutionWarnings callback = new HandleDocumentSubstitutionWarnings();
doc.WarningCallback = callback;
doc.Save(ArtifactsDir + "FontSettings.SubstitutionWarningsClosestMatch.pdf");
Assert.True(callback.FontWarnings[0].Description
.Equals("Font \'SymbolPS\' has not been found. Using \'Wingdings\' font instead. Reason: font info substitution."));
}
[Test]
public void DisableFontSubstitution()
{
Document doc = new Document(MyDir + "Missing font.docx");
HandleDocumentSubstitutionWarnings callback = new HandleDocumentSubstitutionWarnings();
doc.WarningCallback = callback;
FontSettings fontSettings = new FontSettings();
fontSettings.SubstitutionSettings.DefaultFontSubstitution.DefaultFontName = "Arial";
fontSettings.SubstitutionSettings.FontInfoSubstitution.Enabled = false;
doc.FontSettings = fontSettings;
doc.Save(ArtifactsDir + "FontSettings.DisableFontSubstitution.pdf");
Regex reg = new Regex("Font '28 Days Later' has not been found. Using (.*) font instead. Reason: default font setting.");
foreach (WarningInfo fontWarning in callback.FontWarnings)
{
Match match = reg.Match(fontWarning.Description);
if (match.Success)
{
Assert.Pass();
break;
}
}
}
[Test]
[Category("SkipMono")]
public void SubstitutionWarnings()
{
Document doc = new Document(MyDir + "Rendering.docx");
HandleDocumentSubstitutionWarnings callback = new HandleDocumentSubstitutionWarnings();
doc.WarningCallback = callback;
FontSettings fontSettings = new FontSettings();
fontSettings.SubstitutionSettings.DefaultFontSubstitution.DefaultFontName = "Arial";
fontSettings.SetFontsFolder(FontsDir, false);
fontSettings.SubstitutionSettings.TableSubstitution.AddSubstitutes("Arial", "Arvo", "Slab");
doc.FontSettings = fontSettings;
doc.Save(ArtifactsDir + "FontSettings.SubstitutionWarnings.pdf");
Assert.AreEqual("Font \'Arial\' has not been found. Using \'Arvo\' font instead. Reason: table substitution.",
callback.FontWarnings[0].Description);
Assert.AreEqual("Font \'Times New Roman\' has not been found. Using \'M+ 2m\' font instead. Reason: font info substitution.",
callback.FontWarnings[1].Description);
}
[Test]
public void GetSubstitutionWithoutSuffixes()
{
Document doc = new Document(MyDir + "Get substitution without suffixes.docx");
FontSourceBase[] originalFontSources = FontSettings.DefaultInstance.GetFontsSources();
HandleDocumentSubstitutionWarnings substitutionWarningHandler = new HandleDocumentSubstitutionWarnings();
doc.WarningCallback = substitutionWarningHandler;
List<FontSourceBase> fontSources = new List<FontSourceBase>(FontSettings.DefaultInstance.GetFontsSources());
FolderFontSource folderFontSource = new FolderFontSource(FontsDir, true);
fontSources.Add(folderFontSource);
FontSourceBase[] updatedFontSources = fontSources.ToArray();
FontSettings.DefaultInstance.SetFontsSources(updatedFontSources);
doc.Save(ArtifactsDir + "Font.GetSubstitutionWithoutSuffixes.pdf");
Assert.AreEqual(
"Font 'DINOT-Regular' has not been found. Using 'DINOT' font instead. Reason: font name substitution.",
substitutionWarningHandler.FontWarnings[0].Description);
FontSettings.DefaultInstance.SetFontsSources(originalFontSources);
}
[Test]
public void FontSourceFile()
{
//ExStart
//ExFor:Fonts.FileFontSource
//ExFor:Fonts.FileFontSource.#ctor(String)
//ExFor:Fonts.FileFontSource.#ctor(String, Int32)
//ExFor:Fonts.FileFontSource.FilePath
//ExFor:Fonts.FileFontSource.Type
//ExFor:Fonts.FontSourceBase
//ExFor:Fonts.FontSourceBase.Priority
//ExFor:Fonts.FontSourceBase.Type
//ExFor:Fonts.FontSourceType
//ExSummary:Shows how to use a font file in the local file system as a font source.
FileFontSource fileFontSource = new FileFontSource(MyDir + "Alte DIN 1451 Mittelschrift.ttf", 0);
Document doc = new Document();
doc.FontSettings = new FontSettings();
doc.FontSettings.SetFontsSources(new FontSourceBase[] { fileFontSource });
Assert.AreEqual(MyDir + "Alte DIN 1451 Mittelschrift.ttf", fileFontSource.FilePath);
Assert.AreEqual(FontSourceType.FontFile, fileFontSource.Type);
Assert.AreEqual(0, fileFontSource.Priority);
//ExEnd
}
[Test]
public void FontSourceFolder()
{
//ExStart
//ExFor:Fonts.FolderFontSource
//ExFor:Fonts.FolderFontSource.#ctor(String, Boolean)
//ExFor:Fonts.FolderFontSource.#ctor(String, Boolean, Int32)
//ExFor:Fonts.FolderFontSource.FolderPath
//ExFor:Fonts.FolderFontSource.ScanSubfolders
//ExFor:Fonts.FolderFontSource.Type
//ExSummary:Shows how to use a local system folder which contains fonts as a font source.
// Create a font source from a folder that contains font files.
FolderFontSource folderFontSource = new FolderFontSource(FontsDir, false, 1);
Document doc = new Document();
doc.FontSettings = new FontSettings();
doc.FontSettings.SetFontsSources(new FontSourceBase[] { folderFontSource });
Assert.AreEqual(FontsDir, folderFontSource.FolderPath);
Assert.AreEqual(false, folderFontSource.ScanSubfolders);
Assert.AreEqual(FontSourceType.FontsFolder, folderFontSource.Type);
Assert.AreEqual(1, folderFontSource.Priority);
//ExEnd
}
[TestCase(false)]
[TestCase(true)]
public void SetFontsFolder(bool recursive)
{
//ExStart
//ExFor:FontSettings
//ExFor:FontSettings.SetFontsFolder(String, Boolean)
//ExSummary:Shows how to set a font source directory.
Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);
builder.Font.Name = "Arvo";
builder.Writeln("Hello world!");
builder.Font.Name = "Amethysta";
builder.Writeln("The quick brown fox jumps over the lazy dog.");
// Our font sources do not contain the font that we have used for text in this document.
// If we use these font settings while rendering this document,
// Aspose.Words will apply a fallback font to text which has a font that Aspose.Words cannot locate.
FontSourceBase[] originalFontSources = FontSettings.DefaultInstance.GetFontsSources();
Assert.AreEqual(1, originalFontSources.Length);
Assert.True(originalFontSources[0].GetAvailableFonts().Any(f => f.FullFontName == "Arial"));
// The default font sources are missing the two fonts that we are using in this document.
Assert.False(originalFontSources[0].GetAvailableFonts().Any(f => f.FullFontName == "Arvo"));
Assert.False(originalFontSources[0].GetAvailableFonts().Any(f => f.FullFontName == "Amethysta"));
// Use the "SetFontsFolder" method to set a directory which will act as a new font source.
// Pass "false" as the "recursive" argument to include fonts from all the font files that are in the directory
// that we are passing in the first argument, but not include any fonts in any of that directory's subfolders.
// Pass "true" as the "recursive" argument to include all font files in the directory that we are passing
// in the first argument, as well as all the fonts in its subdirectories.
FontSettings.DefaultInstance.SetFontsFolder(FontsDir, recursive);
FontSourceBase[] newFontSources = FontSettings.DefaultInstance.GetFontsSources();
Assert.AreEqual(1, newFontSources.Length);
Assert.False(newFontSources[0].GetAvailableFonts().Any(f => f.FullFontName == "Arial"));
Assert.True(newFontSources[0].GetAvailableFonts().Any(f => f.FullFontName == "Arvo"));
// The "Amethysta" font is in a subfolder of the font directory.
if (recursive)
{
Assert.AreEqual(25, newFontSources[0].GetAvailableFonts().Count);
Assert.True(newFontSources[0].GetAvailableFonts().Any(f => f.FullFontName == "Amethysta"));
}
else
{
Assert.AreEqual(18, newFontSources[0].GetAvailableFonts().Count);
Assert.False(newFontSources[0].GetAvailableFonts().Any(f => f.FullFontName == "Amethysta"));
}
doc.Save(ArtifactsDir + "FontSettings.SetFontsFolder.pdf");
// Restore the original font sources.
FontSettings.DefaultInstance.SetFontsSources(originalFontSources);
//ExEnd
}
[TestCase(false)]
[TestCase(true)]
public void SetFontsFolders(bool recursive)
{
//ExStart
//ExFor:FontSettings
//ExFor:FontSettings.SetFontsFolders(String[], Boolean)
//ExSummary:Shows how to set multiple font source directories.
Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);
builder.Font.Name = "Amethysta";
builder.Writeln("The quick brown fox jumps over the lazy dog.");
builder.Font.Name = "Junction Light";
builder.Writeln("The quick brown fox jumps over the lazy dog.");
// Our font sources do not contain the font that we have used for text in this document.
// If we use these font settings while rendering this document,
// Aspose.Words will apply a fallback font to text which has a font that Aspose.Words cannot locate.
FontSourceBase[] originalFontSources = FontSettings.DefaultInstance.GetFontsSources();
Assert.AreEqual(1, originalFontSources.Length);
Assert.True(originalFontSources[0].GetAvailableFonts().Any(f => f.FullFontName == "Arial"));
// The default font sources are missing the two fonts that we are using in this document.
Assert.False(originalFontSources[0].GetAvailableFonts().Any(f => f.FullFontName == "Amethysta"));
Assert.False(originalFontSources[0].GetAvailableFonts().Any(f => f.FullFontName == "Junction Light"));
// Use the "SetFontsFolders" method to create a font source from each font directory that we pass as the first argument.
// Pass "false" as the "recursive" argument to include fonts from all the font files that are in the directories
// that we are passing in the first argument, but not include any fonts from any of the directories' subfolders.
// Pass "true" as the "recursive" argument to include all font files in the directories that we are passing
// in the first argument, as well as all the fonts in their subdirectories.
FontSettings.DefaultInstance.SetFontsFolders(new[] { FontsDir + "/Amethysta", FontsDir + "/Junction" }, recursive);
FontSourceBase[] newFontSources = FontSettings.DefaultInstance.GetFontsSources();
Assert.AreEqual(2, newFontSources.Length);
Assert.False(newFontSources[0].GetAvailableFonts().Any(f => f.FullFontName == "Arial"));
Assert.AreEqual(1, newFontSources[0].GetAvailableFonts().Count);
Assert.True(newFontSources[0].GetAvailableFonts().Any(f => f.FullFontName == "Amethysta"));
// The "Junction" folder itself contains no font files, but has subfolders that do.
if (recursive)
{
Assert.AreEqual(6, newFontSources[1].GetAvailableFonts().Count);
Assert.True(newFontSources[1].GetAvailableFonts().Any(f => f.FullFontName == "Junction Light"));
}
else
{
Assert.AreEqual(0, newFontSources[1].GetAvailableFonts().Count);
}
doc.Save(ArtifactsDir + "FontSettings.SetFontsFolders.pdf");
// Restore the original font sources.
FontSettings.DefaultInstance.SetFontsSources(originalFontSources);
//ExEnd
}
[Test]
public void AddFontSource()
{
//ExStart
//ExFor:FontSettings
//ExFor:FontSettings.GetFontsSources()
//ExFor:FontSettings.SetFontsSources(FontSourceBase[])
//ExSummary:Shows how to add a font source to our existing font sources.
Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);
builder.Font.Name = "Arial";
builder.Writeln("Hello world!");
builder.Font.Name = "Amethysta";
builder.Writeln("The quick brown fox jumps over the lazy dog.");
builder.Font.Name = "Junction Light";
builder.Writeln("The quick brown fox jumps over the lazy dog.");
FontSourceBase[] originalFontSources = FontSettings.DefaultInstance.GetFontsSources();
Assert.AreEqual(1, originalFontSources.Length);
Assert.True(originalFontSources[0].GetAvailableFonts().Any(f => f.FullFontName == "Arial"));
// The default font source is missing two of the fonts that we are using in our document.
// When we save this document, Aspose.Words will apply fallback fonts to all text formatted with inaccessible fonts.
Assert.False(originalFontSources[0].GetAvailableFonts().Any(f => f.FullFontName == "Amethysta"));
Assert.False(originalFontSources[0].GetAvailableFonts().Any(f => f.FullFontName == "Junction Light"));
// Create a font source from a folder that contains fonts.
FolderFontSource folderFontSource = new FolderFontSource(FontsDir, true);
// Apply a new array of font sources that contains the original font sources, as well as our custom fonts.
FontSourceBase[] updatedFontSources = { originalFontSources[0], folderFontSource };
FontSettings.DefaultInstance.SetFontsSources(updatedFontSources);
// Verify that Aspose.Words has access to all required fonts before we render the document to PDF.
updatedFontSources = FontSettings.DefaultInstance.GetFontsSources();
Assert.True(updatedFontSources[0].GetAvailableFonts().Any(f => f.FullFontName == "Arial"));
Assert.True(updatedFontSources[1].GetAvailableFonts().Any(f => f.FullFontName == "Amethysta"));
Assert.True(updatedFontSources[1].GetAvailableFonts().Any(f => f.FullFontName == "Junction Light"));
doc.Save(ArtifactsDir + "FontSettings.AddFontSource.pdf");
// Restore the original font sources.
FontSettings.DefaultInstance.SetFontsSources(originalFontSources);
//ExEnd
}
[Test]
public void SetSpecifyFontFolder()
{
FontSettings fontSettings = new FontSettings();
fontSettings.SetFontsFolder(FontsDir, false);
// Using load options
LoadOptions loadOptions = new LoadOptions();
loadOptions.FontSettings = fontSettings;
Document doc = new Document(MyDir + "Rendering.docx", loadOptions);
FolderFontSource folderSource = ((FolderFontSource)doc.FontSettings.GetFontsSources()[0]);
Assert.AreEqual(FontsDir, folderSource.FolderPath);
Assert.False(folderSource.ScanSubfolders);
}
[Test]
public void TableSubstitution()
{
//ExStart
//ExFor:Document.FontSettings
//ExFor:TableSubstitutionRule.SetSubstitutes(String, String[])
//ExSummary:Shows how set font substitution rules.
Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);
builder.Font.Name = "Arial";
builder.Writeln("Hello world!");
builder.Font.Name = "Amethysta";
builder.Writeln("The quick brown fox jumps over the lazy dog.");
FontSourceBase[] fontSources = FontSettings.DefaultInstance.GetFontsSources();
// The default font sources contain the first font that the document uses.
Assert.AreEqual(1, fontSources.Length);
Assert.True(fontSources[0].GetAvailableFonts().Any(f => f.FullFontName == "Arial"));
// The second font, "Amethysta", is unavailable.
Assert.False(fontSources[0].GetAvailableFonts().Any(f => f.FullFontName == "Amethysta"));
// We can configure a font substitution table which determines
// which fonts Aspose.Words will use as substitutes for unavailable fonts.
// Set two substitution fonts for "Amethysta": "Arvo", and "Courier New".
// If the first substitute is unavailable, Aspose.Words attempts to use the second substitute, and so on.
doc.FontSettings = new FontSettings();
doc.FontSettings.SubstitutionSettings.TableSubstitution.SetSubstitutes(
"Amethysta", new[] { "Arvo", "Courier New" });
// "Amethysta" is unavailable, and the substitution rule states that the first font to use as a substitute is "Arvo".
Assert.False(fontSources[0].GetAvailableFonts().Any(f => f.FullFontName == "Arvo"));
// "Arvo" is also unavailable, but "Courier New" is.
Assert.True(fontSources[0].GetAvailableFonts().Any(f => f.FullFontName == "Courier New"));
// The output document will display the text that uses the "Amethysta" font formatted with "Courier New".
doc.Save(ArtifactsDir + "FontSettings.TableSubstitution.pdf");
//ExEnd
}
[Test]
public void SetSpecifyFontFolders()
{
FontSettings fontSettings = new FontSettings();
fontSettings.SetFontsFolders(new string[] { FontsDir, @"C:\Windows\Fonts\" }, true);
// Using load options
LoadOptions loadOptions = new LoadOptions();
loadOptions.FontSettings = fontSettings;
Document doc = new Document(MyDir + "Rendering.docx", loadOptions);
FolderFontSource folderSource = ((FolderFontSource)doc.FontSettings.GetFontsSources()[0]);
Assert.AreEqual(FontsDir, folderSource.FolderPath);
Assert.True(folderSource.ScanSubfolders);
folderSource = ((FolderFontSource)doc.FontSettings.GetFontsSources()[1]);
Assert.AreEqual(@"C:\Windows\Fonts\", folderSource.FolderPath);
Assert.True(folderSource.ScanSubfolders);
}
[Test]
public void AddFontSubstitutes()
{
FontSettings fontSettings = new FontSettings();
fontSettings.SubstitutionSettings.TableSubstitution.SetSubstitutes("Slab", new string[] { "Times New Roman", "Arial" });
fontSettings.SubstitutionSettings.TableSubstitution.AddSubstitutes("Arvo", new string[] { "Open Sans", "Arial" });
Document doc = new Document(MyDir + "Rendering.docx");
doc.FontSettings = fontSettings;
string[] alternativeFonts = doc.FontSettings.SubstitutionSettings.TableSubstitution.GetSubstitutes("Slab").ToArray();
Assert.AreEqual(new string[] { "Times New Roman", "Arial" }, alternativeFonts);
alternativeFonts = doc.FontSettings.SubstitutionSettings.TableSubstitution.GetSubstitutes("Arvo").ToArray();
Assert.AreEqual(new string[] { "Open Sans", "Arial" }, alternativeFonts);
}
[Test]
public void FontSourceMemory()
{
//ExStart
//ExFor:Fonts.MemoryFontSource
//ExFor:Fonts.MemoryFontSource.#ctor(Byte[])
//ExFor:Fonts.MemoryFontSource.#ctor(Byte[], Int32)
//ExFor:Fonts.MemoryFontSource.FontData
//ExFor:Fonts.MemoryFontSource.Type
//ExSummary:Shows how to use a byte array with data from a font file as a font source.
byte[] fontBytes = File.ReadAllBytes(MyDir + "Alte DIN 1451 Mittelschrift.ttf");
MemoryFontSource memoryFontSource = new MemoryFontSource(fontBytes, 0);
Document doc = new Document();
doc.FontSettings = new FontSettings();
doc.FontSettings.SetFontsSources(new FontSourceBase[] { memoryFontSource });
Assert.AreEqual(FontSourceType.MemoryFont, memoryFontSource.Type);
Assert.AreEqual(0, memoryFontSource.Priority);
//ExEnd
}
[Test]
public void FontSourceSystem()
{
//ExStart
//ExFor:TableSubstitutionRule.AddSubstitutes(String, String[])
//ExFor:FontSubstitutionRule.Enabled
//ExFor:TableSubstitutionRule.GetSubstitutes(String)
//ExFor:Fonts.FontSettings.ResetFontSources
//ExFor:Fonts.FontSettings.SubstitutionSettings
//ExFor:Fonts.FontSubstitutionSettings
//ExFor:Fonts.SystemFontSource
//ExFor:Fonts.SystemFontSource.#ctor
//ExFor:Fonts.SystemFontSource.#ctor(Int32)
//ExFor:Fonts.SystemFontSource.GetSystemFontFolders
//ExFor:Fonts.SystemFontSource.Type
//ExSummary:Shows how to access a document's system font source and set font substitutes.
Document doc = new Document();
doc.FontSettings = new FontSettings();
// By default, a blank document always contains a system font source.
Assert.AreEqual(1, doc.FontSettings.GetFontsSources().Length);
SystemFontSource systemFontSource = (SystemFontSource)doc.FontSettings.GetFontsSources()[0];
Assert.AreEqual(FontSourceType.SystemFonts, systemFontSource.Type);
Assert.AreEqual(0, systemFontSource.Priority);
PlatformID pid = Environment.OSVersion.Platform;
bool isWindows = (pid == PlatformID.Win32NT) || (pid == PlatformID.Win32S) || (pid == PlatformID.Win32Windows) || (pid == PlatformID.WinCE);
if (isWindows)
{
const string fontsPath = @"C:\WINDOWS\Fonts";
Assert.AreEqual(fontsPath.ToLower(), SystemFontSource.GetSystemFontFolders().FirstOrDefault()?.ToLower());
}
foreach (string systemFontFolder in SystemFontSource.GetSystemFontFolders())
{
Console.WriteLine(systemFontFolder);
}
// Set a font that exists in the Windows Fonts directory as a substitute for one that does not.
doc.FontSettings.SubstitutionSettings.FontInfoSubstitution.Enabled = true;
doc.FontSettings.SubstitutionSettings.TableSubstitution.AddSubstitutes("Kreon-Regular", new[] { "Calibri" });
Assert.AreEqual(1, doc.FontSettings.SubstitutionSettings.TableSubstitution.GetSubstitutes("Kreon-Regular").Count());
Assert.Contains("Calibri", doc.FontSettings.SubstitutionSettings.TableSubstitution.GetSubstitutes("Kreon-Regular").ToArray());
// Alternatively, we could add a folder font source in which the corresponding folder contains the font.
FolderFontSource folderFontSource = new FolderFontSource(FontsDir, false);
doc.FontSettings.SetFontsSources(new FontSourceBase[] { systemFontSource, folderFontSource });
Assert.AreEqual(2, doc.FontSettings.GetFontsSources().Length);
// Resetting the font sources still leaves us with the system font source as well as our substitutes.
doc.FontSettings.ResetFontSources();
Assert.AreEqual(1, doc.FontSettings.GetFontsSources().Length);
Assert.AreEqual(FontSourceType.SystemFonts, doc.FontSettings.GetFontsSources()[0].Type);
Assert.AreEqual(1, doc.FontSettings.SubstitutionSettings.TableSubstitution.GetSubstitutes("Kreon-Regular").Count());
//ExEnd
}
[Test]
public void LoadFontFallbackSettingsFromFile()
{
//ExStart
//ExFor:FontFallbackSettings.Load(String)
//ExFor:FontFallbackSettings.Save(String)
//ExSummary:Shows how to load and save font fallback settings to/from an XML document in the local file system.
Document doc = new Document(MyDir + "Rendering.docx");
// Load an XML document that defines a set of font fallback settings.
FontSettings fontSettings = new FontSettings();
fontSettings.FallbackSettings.Load(MyDir + "Font fallback rules.xml");
doc.FontSettings = fontSettings;
doc.Save(ArtifactsDir + "FontSettings.LoadFontFallbackSettingsFromFile.pdf");
// Save our document's current font fallback settings as an XML document.
doc.FontSettings.FallbackSettings.Save(ArtifactsDir + "FallbackSettings.xml");
//ExEnd
}
[Test]
public void LoadFontFallbackSettingsFromStream()
{
//ExStart
//ExFor:FontFallbackSettings.Load(Stream)
//ExFor:FontFallbackSettings.Save(Stream)
//ExSummary:Shows how to load and save font fallback settings to/from a stream.
Document doc = new Document(MyDir + "Rendering.docx");
// Load an XML document that defines a set of font fallback settings.
using (FileStream fontFallbackStream = new FileStream(MyDir + "Font fallback rules.xml", FileMode.Open))
{
FontSettings fontSettings = new FontSettings();
fontSettings.FallbackSettings.Load(fontFallbackStream);
doc.FontSettings = fontSettings;
}
doc.Save(ArtifactsDir + "FontSettings.LoadFontFallbackSettingsFromStream.pdf");
// Use a stream to save our document's current font fallback settings as an XML document.
using (FileStream fontFallbackStream =
new FileStream(ArtifactsDir + "FallbackSettings.xml", FileMode.Create))
{
doc.FontSettings.FallbackSettings.Save(fontFallbackStream);
}
//ExEnd
XmlDocument fallbackSettingsDoc = new XmlDocument();
fallbackSettingsDoc.LoadXml(File.ReadAllText(ArtifactsDir + "FallbackSettings.xml"));
XmlNamespaceManager manager = new XmlNamespaceManager(fallbackSettingsDoc.NameTable);
manager.AddNamespace("aw", "Aspose.Words");
XmlNodeList rules = fallbackSettingsDoc.SelectNodes("//aw:FontFallbackSettings/aw:FallbackTable/aw:Rule", manager);
Assert.AreEqual("0B80-0BFF", rules[0].Attributes["Ranges"].Value);
Assert.AreEqual("Vijaya", rules[0].Attributes["FallbackFonts"].Value);
Assert.AreEqual("1F300-1F64F", rules[1].Attributes["Ranges"].Value);
Assert.AreEqual("Segoe UI Emoji, Segoe UI Symbol", rules[1].Attributes["FallbackFonts"].Value);
Assert.AreEqual("2000-206F, 2070-209F, 20B9", rules[2].Attributes["Ranges"].Value);
Assert.AreEqual("Arial", rules[2].Attributes["FallbackFonts"].Value);
Assert.AreEqual("3040-309F", rules[3].Attributes["Ranges"].Value);
Assert.AreEqual("MS Gothic", rules[3].Attributes["FallbackFonts"].Value);
Assert.AreEqual("Times New Roman", rules[3].Attributes["BaseFonts"].Value);
Assert.AreEqual("3040-309F", rules[4].Attributes["Ranges"].Value);
Assert.AreEqual("MS Mincho", rules[4].Attributes["FallbackFonts"].Value);
Assert.AreEqual("Arial Unicode MS", rules[5].Attributes["FallbackFonts"].Value);
}
[Test]
public void LoadNotoFontsFallbackSettings()
{
//ExStart
//ExFor:FontFallbackSettings.LoadNotoFallbackSettings
//ExSummary:Shows how to add predefined font fallback settings for Google Noto fonts.
FontSettings fontSettings = new FontSettings();
// These are free fonts licensed under the SIL Open Font License.
// We can download the fonts here:
// https://www.google.com/get/noto/#sans-lgc
fontSettings.SetFontsFolder(FontsDir + "Noto", false);
// Note that the predefined settings only use Sans-style Noto fonts with regular weight.
// Some of the Noto fonts use advanced typography features.
// Fonts featuring advanced typography may not be rendered correctly as Aspose.Words currently do not support them.
fontSettings.FallbackSettings.LoadNotoFallbackSettings();
fontSettings.SubstitutionSettings.FontInfoSubstitution.Enabled = false;
fontSettings.SubstitutionSettings.DefaultFontSubstitution.DefaultFontName = "Noto Sans";
Document doc = new Document();
doc.FontSettings = fontSettings;
//ExEnd
TestUtil.VerifyWebResponseStatusCode(HttpStatusCode.OK, "https://www.google.com/get/noto/#sans-lgc");
}
[Test]
public void DefaultFontSubstitutionRule()
{
//ExStart
//ExFor:Fonts.DefaultFontSubstitutionRule
//ExFor:Fonts.DefaultFontSubstitutionRule.DefaultFontName
//ExFor:Fonts.FontSubstitutionSettings.DefaultFontSubstitution
//ExSummary:Shows how to set the default font substitution rule.
Document doc = new Document();
FontSettings fontSettings = new FontSettings();
doc.FontSettings = fontSettings;
// Get the default substitution rule within FontSettings.
// This rule will substitute all missing fonts with "Times New Roman".
DefaultFontSubstitutionRule defaultFontSubstitutionRule = fontSettings.SubstitutionSettings.DefaultFontSubstitution;
Assert.True(defaultFontSubstitutionRule.Enabled);
Assert.AreEqual("Times New Roman", defaultFontSubstitutionRule.DefaultFontName);
// Set the default font substitute to "Courier New".
defaultFontSubstitutionRule.DefaultFontName = "Courier New";
// Using a document builder, add some text in a font that we do not have to see the substitution take place,
// and then render the result in a PDF.
DocumentBuilder builder = new DocumentBuilder(doc);
builder.Font.Name = "Missing Font";
builder.Writeln("Line written in a missing font, which will be substituted with Courier New.");
doc.Save(ArtifactsDir + "FontSettings.DefaultFontSubstitutionRule.pdf");
//ExEnd
Assert.AreEqual("Courier New", defaultFontSubstitutionRule.DefaultFontName);
}
[Test]
public void FontConfigSubstitution()
{
//ExStart
//ExFor:Fonts.FontConfigSubstitutionRule
//ExFor:Fonts.FontConfigSubstitutionRule.Enabled
//ExFor:Fonts.FontConfigSubstitutionRule.IsFontConfigAvailable
//ExFor:Fonts.FontConfigSubstitutionRule.ResetCache
//ExFor:Fonts.FontSubstitutionRule
//ExFor:Fonts.FontSubstitutionRule.Enabled
//ExFor:Fonts.FontSubstitutionSettings.FontConfigSubstitution
//ExSummary:Shows operating system-dependent font config substitution.
FontSettings fontSettings = new FontSettings();
FontConfigSubstitutionRule fontConfigSubstitution = fontSettings.SubstitutionSettings.FontConfigSubstitution;
bool isWindows = new[] { PlatformID.Win32NT, PlatformID.Win32S, PlatformID.Win32Windows, PlatformID.WinCE }
.Any(p => Environment.OSVersion.Platform == p);
// The FontConfigSubstitutionRule object works differently on Windows/non-Windows platforms.
// On Windows, it is unavailable.
if (isWindows)
{
Assert.False(fontConfigSubstitution.Enabled);
Assert.False(fontConfigSubstitution.IsFontConfigAvailable());
}
bool isLinuxOrMac = new[] { PlatformID.Unix, PlatformID.MacOSX }.Any(p => Environment.OSVersion.Platform == p);
// On Linux/Mac, we will have access to it, and will be able to perform operations.
if (isLinuxOrMac)
{
Assert.True(fontConfigSubstitution.Enabled);
Assert.True(fontConfigSubstitution.IsFontConfigAvailable());
fontConfigSubstitution.ResetCache();
}
//ExEnd
}
[Test]
public void FallbackSettings()
{
//ExStart
//ExFor:Fonts.FontFallbackSettings.LoadMsOfficeFallbackSettings
//ExFor:Fonts.FontFallbackSettings.LoadNotoFallbackSettings
//ExSummary:Shows how to load pre-defined fallback font settings.
Document doc = new Document();
FontSettings fontSettings = new FontSettings();
doc.FontSettings = fontSettings;
FontFallbackSettings fontFallbackSettings = fontSettings.FallbackSettings;
// Save the default fallback font scheme to an XML document.
// For example, one of the elements has a value of "0C00-0C7F" for Range and a corresponding "Vani" value for FallbackFonts.
// This means that if the font some text is using does not have symbols for the 0x0C00-0x0C7F Unicode block,
// the fallback scheme will use symbols from the "Vani" font substitute.
fontFallbackSettings.Save(ArtifactsDir + "FontSettings.FallbackSettings.Default.xml");
// Below are two pre-defined font fallback schemes we can choose from.
// 1 - Use the default Microsoft Office scheme, which is the same one as the default:
fontFallbackSettings.LoadMsOfficeFallbackSettings();
fontFallbackSettings.Save(ArtifactsDir + "FontSettings.FallbackSettings.LoadMsOfficeFallbackSettings.xml");
// 2 - Use the scheme built from Google Noto fonts:
fontFallbackSettings.LoadNotoFallbackSettings();
fontFallbackSettings.Save(ArtifactsDir + "FontSettings.FallbackSettings.LoadNotoFallbackSettings.xml");
//ExEnd
XmlDocument fallbackSettingsDoc = new XmlDocument();
fallbackSettingsDoc.LoadXml(File.ReadAllText(ArtifactsDir + "FontSettings.FallbackSettings.Default.xml"));
XmlNamespaceManager manager = new XmlNamespaceManager(fallbackSettingsDoc.NameTable);
manager.AddNamespace("aw", "Aspose.Words");
XmlNodeList rules = fallbackSettingsDoc.SelectNodes("//aw:FontFallbackSettings/aw:FallbackTable/aw:Rule", manager);
Assert.AreEqual("0C00-0C7F", rules[8].Attributes["Ranges"].Value);
Assert.AreEqual("Vani", rules[8].Attributes["FallbackFonts"].Value);
}
[Test]
public void FallbackSettingsCustom()
{
//ExStart
//ExFor:Fonts.FontSettings.FallbackSettings
//ExFor:Fonts.FontFallbackSettings
//ExFor:Fonts.FontFallbackSettings.BuildAutomatic
//ExSummary:Shows how to distribute fallback fonts across Unicode character code ranges.
Document doc = new Document();
FontSettings fontSettings = new FontSettings();
doc.FontSettings = fontSettings;
FontFallbackSettings fontFallbackSettings = fontSettings.FallbackSettings;
// Configure our font settings to source fonts only from the "MyFonts" folder.
FolderFontSource folderFontSource = new FolderFontSource(FontsDir, false);
fontSettings.SetFontsSources(new FontSourceBase[] { folderFontSource });
// Calling the "BuildAutomatic" method will generate a fallback scheme that
// distributes accessible fonts across as many Unicode character codes as possible.
// In our case, it only has access to the handful of fonts inside the "MyFonts" folder.
fontFallbackSettings.BuildAutomatic();
fontFallbackSettings.Save(ArtifactsDir + "FontSettings.FallbackSettingsCustom.BuildAutomatic.xml");
// We can also load a custom substitution scheme from a file like this.
// This scheme applies the "AllegroOpen" font across the "0000-00ff" Unicode blocks, the "AllegroOpen" font across "0100-024f",
// and the "M+ 2m" font in all other ranges that other fonts in the scheme do not cover.
fontFallbackSettings.Load(MyDir + "Custom font fallback settings.xml");
// Create a document builder and set its font to one that does not exist in any of our sources.
// Our font settings will invoke the fallback scheme for characters that we type using the unavailable font.
DocumentBuilder builder = new DocumentBuilder(doc);
builder.Font.Name = "Missing Font";
// Use the builder to print every Unicode character from 0x0021 to 0x052F,
// with descriptive lines dividing Unicode blocks we defined in our custom font fallback scheme.
for (int i = 0x0021; i < 0x0530; i++)
{
switch (i)
{
case 0x0021:
builder.Writeln("\n\n0x0021 - 0x00FF: \nBasic Latin/Latin-1 Supplement Unicode blocks in \"AllegroOpen\" font:");
break;
case 0x0100:
builder.Writeln("\n\n0x0100 - 0x024F: \nLatin Extended A/B blocks, mostly in \"AllegroOpen\" font:");
break;
case 0x0250:
builder.Writeln("\n\n0x0250 - 0x052F: \nIPA/Greek/Cyrillic blocks in \"M+ 2m\" font:");
break;
}
builder.Write($"{Convert.ToChar(i)}");
}
doc.Save(ArtifactsDir + "FontSettings.FallbackSettingsCustom.pdf");
//ExEnd
XmlDocument fallbackSettingsDoc = new XmlDocument();
fallbackSettingsDoc.LoadXml(File.ReadAllText(ArtifactsDir + "FontSettings.FallbackSettingsCustom.BuildAutomatic.xml"));
XmlNamespaceManager manager = new XmlNamespaceManager(fallbackSettingsDoc.NameTable);
manager.AddNamespace("aw", "Aspose.Words");
XmlNodeList rules = fallbackSettingsDoc.SelectNodes("//aw:FontFallbackSettings/aw:FallbackTable/aw:Rule", manager);
Assert.AreEqual("0000-007F", rules[0].Attributes["Ranges"].Value);
Assert.AreEqual("AllegroOpen", rules[0].Attributes["FallbackFonts"].Value);
Assert.AreEqual("0100-017F", rules[2].Attributes["Ranges"].Value);
Assert.AreEqual("AllegroOpen", rules[2].Attributes["FallbackFonts"].Value);
Assert.AreEqual("0250-02AF", rules[4].Attributes["Ranges"].Value);
Assert.AreEqual("M+ 2m", rules[4].Attributes["FallbackFonts"].Value);
Assert.AreEqual("0370-03FF", rules[7].Attributes["Ranges"].Value);
Assert.AreEqual("Arvo", rules[7].Attributes["FallbackFonts"].Value);
}
[Test]
public void TableSubstitutionRule()
{
//ExStart
//ExFor:Fonts.TableSubstitutionRule
//ExFor:Fonts.TableSubstitutionRule.LoadLinuxSettings
//ExFor:Fonts.TableSubstitutionRule.LoadWindowsSettings
//ExFor:Fonts.TableSubstitutionRule.Save(System.IO.Stream)
//ExFor:Fonts.TableSubstitutionRule.Save(System.String)
//ExSummary:Shows how to access font substitution tables for Windows and Linux.
Document doc = new Document();
FontSettings fontSettings = new FontSettings();
doc.FontSettings = fontSettings;
// Create a new table substitution rule and load the default Microsoft Windows font substitution table.
TableSubstitutionRule tableSubstitutionRule = fontSettings.SubstitutionSettings.TableSubstitution;
tableSubstitutionRule.LoadWindowsSettings();
// In Windows, the default substitute for the "Times New Roman CE" font is "Times New Roman".
Assert.AreEqual(new[] { "Times New Roman" },
tableSubstitutionRule.GetSubstitutes("Times New Roman CE").ToArray());
// We can save the table in the form of an XML document.
tableSubstitutionRule.Save(ArtifactsDir + "FontSettings.TableSubstitutionRule.Windows.xml");
// Linux has its own substitution table.
// There are multiple substitute fonts for "Times New Roman CE".
// If the first substitute, "FreeSerif" is also unavailable,
// this rule will cycle through the others in the array until it finds an available one.
tableSubstitutionRule.LoadLinuxSettings();
Assert.AreEqual(new[] { "FreeSerif", "Liberation Serif", "DejaVu Serif" },
tableSubstitutionRule.GetSubstitutes("Times New Roman CE").ToArray());
// Save the Linux substitution table in the form of an XML document using a stream.
using (FileStream fileStream = new FileStream(ArtifactsDir + "FontSettings.TableSubstitutionRule.Linux.xml", FileMode.Create))
{
tableSubstitutionRule.Save(fileStream);
}
//ExEnd
XmlDocument fallbackSettingsDoc = new XmlDocument();
fallbackSettingsDoc.LoadXml(File.ReadAllText(ArtifactsDir + "FontSettings.TableSubstitutionRule.Windows.xml"));
XmlNamespaceManager manager = new XmlNamespaceManager(fallbackSettingsDoc.NameTable);
manager.AddNamespace("aw", "Aspose.Words");
XmlNodeList rules = fallbackSettingsDoc.SelectNodes("//aw:TableSubstitutionSettings/aw:SubstitutesTable/aw:Item", manager);
Assert.AreEqual("Times New Roman CE", rules[16].Attributes["OriginalFont"].Value);
Assert.AreEqual("Times New Roman", rules[16].Attributes["SubstituteFonts"].Value);
fallbackSettingsDoc.LoadXml(File.ReadAllText(ArtifactsDir + "FontSettings.TableSubstitutionRule.Linux.xml"));
rules = fallbackSettingsDoc.SelectNodes("//aw:TableSubstitutionSettings/aw:SubstitutesTable/aw:Item", manager);
Assert.AreEqual("Times New Roman CE", rules[31].Attributes["OriginalFont"].Value);
Assert.AreEqual("FreeSerif, Liberation Serif, DejaVu Serif", rules[31].Attributes["SubstituteFonts"].Value);
}
[Test]
public void TableSubstitutionRuleCustom()
{
//ExStart
//ExFor:Fonts.FontSubstitutionSettings.TableSubstitution
//ExFor:Fonts.TableSubstitutionRule.AddSubstitutes(System.String,System.String[])
//ExFor:Fonts.TableSubstitutionRule.GetSubstitutes(System.String)
//ExFor:Fonts.TableSubstitutionRule.Load(System.IO.Stream)
//ExFor:Fonts.TableSubstitutionRule.Load(System.String)
//ExFor:Fonts.TableSubstitutionRule.SetSubstitutes(System.String,System.String[])
//ExSummary:Shows how to work with custom font substitution tables.
Document doc = new Document();
FontSettings fontSettings = new FontSettings();
doc.FontSettings = fontSettings;
// Create a new table substitution rule and load the default Windows font substitution table.
TableSubstitutionRule tableSubstitutionRule = fontSettings.SubstitutionSettings.TableSubstitution;
// If we select fonts exclusively from our folder, we will need a custom substitution table.
// We will no longer have access to the Microsoft Windows fonts,
// such as "Arial" or "Times New Roman" since they do not exist in our new font folder.
FolderFontSource folderFontSource = new FolderFontSource(FontsDir, false);
fontSettings.SetFontsSources(new FontSourceBase[] { folderFontSource });
// Below are two ways of loading a substitution table from a file in the local file system.
// 1 - From a stream:
using (FileStream fileStream = new FileStream(MyDir + "Font substitution rules.xml", FileMode.Open))
{
tableSubstitutionRule.Load(fileStream);
}
// 2 - Directly from a file:
tableSubstitutionRule.Load(MyDir + "Font substitution rules.xml");
// Since we no longer have access to "Arial", our font table will first try substitute it with "Nonexistent Font".
// We do not have this font so that it will move onto the next substitute, "Kreon", found in the "MyFonts" folder.
Assert.AreEqual(new[] { "Missing Font", "Kreon" }, tableSubstitutionRule.GetSubstitutes("Arial").ToArray());
// We can expand this table programmatically. We will add an entry that substitutes "Times New Roman" with "Arvo"
Assert.Null(tableSubstitutionRule.GetSubstitutes("Times New Roman"));
tableSubstitutionRule.AddSubstitutes("Times New Roman", "Arvo");
Assert.AreEqual(new[] { "Arvo" }, tableSubstitutionRule.GetSubstitutes("Times New Roman").ToArray());
// We can add a secondary fallback substitute for an existing font entry with AddSubstitutes().
// In case "Arvo" is unavailable, our table will look for "M+ 2m" as a second substitute option.
tableSubstitutionRule.AddSubstitutes("Times New Roman", "M+ 2m");
Assert.AreEqual(new[] { "Arvo", "M+ 2m" }, tableSubstitutionRule.GetSubstitutes("Times New Roman").ToArray());
// SetSubstitutes() can set a new list of substitute fonts for a font.
tableSubstitutionRule.SetSubstitutes("Times New Roman", new[] { "Squarish Sans CT", "M+ 2m" });
Assert.AreEqual(new[] { "Squarish Sans CT", "M+ 2m" }, tableSubstitutionRule.GetSubstitutes("Times New Roman").ToArray());
// Writing text in fonts that we do not have access to will invoke our substitution rules.
DocumentBuilder builder = new DocumentBuilder(doc);
builder.Font.Name = "Arial";
builder.Writeln("Text written in Arial, to be substituted by Kreon.");
builder.Font.Name = "Times New Roman";
builder.Writeln("Text written in Times New Roman, to be substituted by Squarish Sans CT.");
doc.Save(ArtifactsDir + "FontSettings.TableSubstitutionRule.Custom.pdf");
//ExEnd
}
[Test]
public void ResolveFontsBeforeLoadingDocument()
{
//ExStart
//ExFor:LoadOptions.FontSettings
//ExSummary:Shows how to designate font substitutes during loading.
LoadOptions loadOptions = new LoadOptions();
loadOptions.FontSettings = new FontSettings();
// Set a font substitution rule for a LoadOptions object.
// If the document we are loading uses a font which we do not have,
// this rule will substitute the unavailable font with one that does exist.
// In this case, all uses of the "MissingFont" will convert to "Comic Sans MS".
TableSubstitutionRule substitutionRule = loadOptions.FontSettings.SubstitutionSettings.TableSubstitution;
substitutionRule.AddSubstitutes("MissingFont", new[] { "Comic Sans MS" });
Document doc = new Document(MyDir + "Missing font.html", loadOptions);
// At this point such text will still be in "MissingFont".
// Font substitution will take place when we render the document.
Assert.AreEqual("MissingFont", doc.FirstSection.Body.FirstParagraph.Runs[0].Font.Name);
doc.Save(ArtifactsDir + "FontSettings.ResolveFontsBeforeLoadingDocument.pdf");
//ExEnd
}
//ExStart
//ExFor:StreamFontSource
//ExFor:StreamFontSource.OpenFontDataStream
//ExSummary:Shows how to load fonts from stream.
[Test] //ExSkip
public void StreamFontSourceFileRendering()
{
FontSettings fontSettings = new FontSettings();
fontSettings.SetFontsSources(new FontSourceBase[] { new StreamFontSourceFile() });
DocumentBuilder builder = new DocumentBuilder();
builder.Document.FontSettings = fontSettings;
builder.Font.Name = "Kreon-Regular";
builder.Writeln("Test aspose text when saving to PDF.");
builder.Document.Save(ArtifactsDir + "FontSettings.StreamFontSourceFileRendering.pdf");
}
/// <summary>
/// Load the font data only when required instead of storing it in the memory for the entire lifetime of the "FontSettings" object.
/// </summary>
private class StreamFontSourceFile : StreamFontSource
{
public override Stream OpenFontDataStream()
{
return File.OpenRead(FontsDir + "Kreon-Regular.ttf");
}
}
//ExEnd
}
}
#endif
| 50.735247 | 152 | 0.648266 |
[
"MIT"
] |
aspose-words/Aspose.Words-for-.NET
|
Examples/ApiExamples/ApiExamples/ExFontSettings.cs
| 63,624 |
C#
|
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using Android.App;
// 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("SamsungAdHub")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("SamsungAdHub")]
[assembly: AssemblyCopyright("Copyright © 2013")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
[assembly: ComVisible(false)]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
// Add some common permissions, these can be removed if not needed
[assembly: UsesPermission(Android.Manifest.Permission.Internet)]
[assembly: UsesPermission(Android.Manifest.Permission.WriteExternalStorage)]
| 36.314286 | 84 | 0.756098 |
[
"Apache-2.0"
] |
Hitcents/monodroid-bindings
|
SamsungAdHub/Properties/AssemblyInfo.cs
| 1,274 |
C#
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Player : MonoBehaviour
{
public Rigidbody rb;
public Transform cameraTransform;
public GameManager gameManager;
void Update()
{
float moveHorizontal = Input.GetAxis("Horizontal");
float moveVertical = Input.GetAxis("Vertical");
Vector3 forward = cameraTransform.forward;
Vector3 right = cameraTransform.right;
forward.y = 0;
right.y = 0;
forward.Normalize();
right.Normalize();
Vector3 direction = forward * moveVertical + right * moveHorizontal;
rb.AddForce(direction * 5);
}
}
| 27.076923 | 77 | 0.636364 |
[
"MIT"
] |
JayFiraja/JayShaders
|
LearningShaders/LearningShaders/Assets/BunnyBallAssets/Scripts/Player.cs
| 706 |
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 swf-2012-01-25.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.SimpleWorkflow.Model;
using Amazon.Runtime;
using Amazon.Runtime.Internal;
using Amazon.Runtime.Internal.Transform;
using Amazon.Runtime.Internal.Util;
using ThirdParty.Json.LitJson;
namespace Amazon.SimpleWorkflow.Model.Internal.MarshallTransformations
{
/// <summary>
/// Response Unmarshaller for WorkflowExecutionStartedEventAttributes Object
/// </summary>
public class WorkflowExecutionStartedEventAttributesUnmarshaller : IUnmarshaller<WorkflowExecutionStartedEventAttributes, XmlUnmarshallerContext>, IUnmarshaller<WorkflowExecutionStartedEventAttributes, JsonUnmarshallerContext>
{
WorkflowExecutionStartedEventAttributes IUnmarshaller<WorkflowExecutionStartedEventAttributes, XmlUnmarshallerContext>.Unmarshall(XmlUnmarshallerContext context)
{
throw new NotImplementedException();
}
public WorkflowExecutionStartedEventAttributes Unmarshall(JsonUnmarshallerContext context)
{
context.Read();
if (context.CurrentTokenType == JsonToken.Null)
return null;
WorkflowExecutionStartedEventAttributes unmarshalledObject = new WorkflowExecutionStartedEventAttributes();
int targetDepth = context.CurrentDepth;
while (context.ReadAtDepth(targetDepth))
{
if (context.TestExpression("childPolicy", targetDepth))
{
var unmarshaller = StringUnmarshaller.Instance;
unmarshalledObject.ChildPolicy = unmarshaller.Unmarshall(context);
continue;
}
if (context.TestExpression("continuedExecutionRunId", targetDepth))
{
var unmarshaller = StringUnmarshaller.Instance;
unmarshalledObject.ContinuedExecutionRunId = unmarshaller.Unmarshall(context);
continue;
}
if (context.TestExpression("executionStartToCloseTimeout", targetDepth))
{
var unmarshaller = StringUnmarshaller.Instance;
unmarshalledObject.ExecutionStartToCloseTimeout = unmarshaller.Unmarshall(context);
continue;
}
if (context.TestExpression("input", targetDepth))
{
var unmarshaller = StringUnmarshaller.Instance;
unmarshalledObject.Input = unmarshaller.Unmarshall(context);
continue;
}
if (context.TestExpression("parentInitiatedEventId", targetDepth))
{
var unmarshaller = LongUnmarshaller.Instance;
unmarshalledObject.ParentInitiatedEventId = unmarshaller.Unmarshall(context);
continue;
}
if (context.TestExpression("parentWorkflowExecution", targetDepth))
{
var unmarshaller = WorkflowExecutionUnmarshaller.Instance;
unmarshalledObject.ParentWorkflowExecution = unmarshaller.Unmarshall(context);
continue;
}
if (context.TestExpression("tagList", targetDepth))
{
var unmarshaller = new ListUnmarshaller<string, StringUnmarshaller>(StringUnmarshaller.Instance);
unmarshalledObject.TagList = unmarshaller.Unmarshall(context);
continue;
}
if (context.TestExpression("taskList", targetDepth))
{
var unmarshaller = TaskListUnmarshaller.Instance;
unmarshalledObject.TaskList = unmarshaller.Unmarshall(context);
continue;
}
if (context.TestExpression("taskStartToCloseTimeout", targetDepth))
{
var unmarshaller = StringUnmarshaller.Instance;
unmarshalledObject.TaskStartToCloseTimeout = unmarshaller.Unmarshall(context);
continue;
}
if (context.TestExpression("workflowType", targetDepth))
{
var unmarshaller = WorkflowTypeUnmarshaller.Instance;
unmarshalledObject.WorkflowType = unmarshaller.Unmarshall(context);
continue;
}
}
return unmarshalledObject;
}
private static WorkflowExecutionStartedEventAttributesUnmarshaller _instance = new WorkflowExecutionStartedEventAttributesUnmarshaller();
public static WorkflowExecutionStartedEventAttributesUnmarshaller Instance
{
get
{
return _instance;
}
}
}
}
| 43.037594 | 230 | 0.625437 |
[
"Apache-2.0"
] |
ermshiperete/aws-sdk-net
|
AWSSDK_DotNet35/Amazon.SimpleWorkflow/Model/Internal/MarshallTransformations/WorkflowExecutionStartedEventAttributesUnmarshaller.cs
| 5,724 |
C#
|
// -------------------------------------------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License (MIT). See LICENSE in the repo root for license information.
// -------------------------------------------------------------------------------------------------
using System;
using System.Collections.Generic;
using System.Net;
using System.Net.Http;
using Hl7.Fhir.Rest;
using Microsoft.Health.Common.Telemetry;
using Microsoft.Health.Extensions.Fhir.Telemetry.Exceptions;
using Microsoft.Health.Logging.Telemetry;
using Microsoft.Identity.Client;
using NSubstitute;
using Xunit;
namespace Microsoft.Health.Extensions.Fhir.R4.UnitTests
{
public class FhirServiceExceptionProcessorTests
{
private static readonly Exception _fhirForbiddenEx = new FhirOperationException("test", HttpStatusCode.Forbidden);
private static readonly Exception _fhirNotFoundEx = new FhirOperationException("test", HttpStatusCode.NotFound);
private static readonly Exception _fhirBadRequestEx = new FhirOperationException("test", HttpStatusCode.BadRequest);
private static readonly Exception _argEndpointNullEx = new ArgumentNullException("endpoint");
private static readonly Exception _argEndpointEx = new ArgumentException("endpoint", "Endpoint must be absolute");
private static readonly Exception _argEx = new ArgumentException("test_message", "test_param");
private static readonly Exception _uriEx = new UriFormatException();
private static readonly Exception _httpNotKnownEx = new HttpRequestException("Name or service not known");
private static readonly Exception _httpEx = new HttpRequestException();
private static readonly Exception _msalInvalidResourceEx = new MsalServiceException("invalid_resource", "test_message");
private static readonly Exception _msalInvalidScopeEx = new MsalServiceException("invalid_scope", "test_message");
private static readonly Exception _msalEx = new MsalServiceException("test_code", "test_message");
private static readonly Exception _ex = new Exception();
public static IEnumerable<object[]> ProcessExceptionData =>
new List<object[]>
{
new object[] { _fhirForbiddenEx, "FHIRServiceErrorAuthorizationError", nameof(ErrorSource.User) },
new object[] { _fhirNotFoundEx, "FHIRServiceErrorConfigurationError", nameof(ErrorSource.User) },
new object[] { _fhirBadRequestEx, "FHIRServiceErrorBadRequest" },
new object[] { _argEndpointNullEx, "FHIRServiceErrorConfigurationError", nameof(ErrorSource.User) },
new object[] { _argEndpointEx, "FHIRServiceErrorConfigurationError", nameof(ErrorSource.User) },
new object[] { _argEx, "FHIRServiceErrorArgumentErrortest_param" },
new object[] { _uriEx, "FHIRServiceErrorConfigurationError", nameof(ErrorSource.User) },
new object[] { _httpNotKnownEx, "FHIRServiceErrorConfigurationError", nameof(ErrorSource.User) },
new object[] { _httpEx, "FHIRServiceErrorHttpRequestError" },
new object[] { _msalInvalidResourceEx, "FHIRServiceErrorConfigurationError", nameof(ErrorSource.User) },
new object[] { _msalInvalidScopeEx, "FHIRServiceErrorConfigurationError", nameof(ErrorSource.User) },
new object[] { _msalEx, "FHIRServiceErrorMsalServiceErrortest_code" },
new object[] { _ex, "FHIRServiceErrorGeneralError" },
};
public static IEnumerable<object[]> CustomizeExceptionData =>
new List<object[]>
{
new object[] { _fhirForbiddenEx, typeof(UnauthorizedAccessFhirServiceException) },
new object[] { _fhirNotFoundEx, typeof(InvalidFhirServiceException) },
new object[] { _fhirBadRequestEx, typeof(FhirOperationException) },
new object[] { _argEndpointNullEx, typeof(InvalidFhirServiceException) },
new object[] { _argEndpointEx, typeof(InvalidFhirServiceException) },
new object[] { _argEx, typeof(ArgumentException) },
new object[] { _uriEx, typeof(InvalidFhirServiceException) },
new object[] { _httpNotKnownEx, typeof(InvalidFhirServiceException) },
new object[] { _httpEx, typeof(HttpRequestException) },
new object[] { _msalInvalidResourceEx, typeof(InvalidFhirServiceException) },
new object[] { _msalInvalidScopeEx, typeof(InvalidFhirServiceException) },
new object[] { _msalEx, typeof(MsalServiceException) },
new object[] { _ex, typeof(Exception) },
};
[Theory]
[MemberData(nameof(ProcessExceptionData))]
public void GivenExceptionType_WhenProcessException_ThenExceptionLoggedAndErrorMetricLogged_Test(Exception ex, string expectedErrorMetricName, string expectedErrorSource = null)
{
var logger = Substitute.For<ITelemetryLogger>();
FhirServiceExceptionProcessor.ProcessException(ex, logger);
logger.ReceivedWithAnyArgs(1).LogError(ex);
logger.Received(1).LogMetric(
Arg.Is<Metric>(m => ValidateFhirServiceErrorMetricProperties(m, expectedErrorMetricName, expectedErrorSource)),
1);
}
[Theory]
[MemberData(nameof(CustomizeExceptionData))]
public void GivenExceptionType_WhenCustomizeException_ThenCustomExceptionTypeReturned_Test(Exception ex, Type customExType)
{
var (customEx, errName) = FhirServiceExceptionProcessor.CustomizeException(ex);
Assert.IsType(customExType, customEx);
}
private bool ValidateFhirServiceErrorMetricProperties(Metric metric, string expectedErrorMetricName, string expectedErrorSource)
{
return metric.Name.Equals(expectedErrorMetricName) &&
metric.Dimensions[DimensionNames.Name].Equals(expectedErrorMetricName) &&
metric.Dimensions[DimensionNames.Operation].Equals(ConnectorOperation.FHIRConversion) &&
metric.Dimensions[DimensionNames.Category].Equals(Category.Errors) &&
metric.Dimensions[DimensionNames.ErrorType].Equals(ErrorType.FHIRServiceError) &&
metric.Dimensions[DimensionNames.ErrorSeverity].Equals(ErrorSeverity.Critical) &&
(string.IsNullOrWhiteSpace(expectedErrorSource) ? !metric.Dimensions.ContainsKey(DimensionNames.ErrorSource) : metric.Dimensions[DimensionNames.ErrorSource].Equals(expectedErrorSource));
}
}
}
| 63.252336 | 202 | 0.682329 |
[
"MIT"
] |
msebragge/iomt-fhir
|
test/Microsoft.Health.Extensions.Fhir.R4.UnitTests/FhirServiceExceptionProcessorTests.cs
| 6,770 |
C#
|
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.EntityFrameworkCore.Metadata.Internal;
using Microsoft.EntityFrameworkCore.Storage;
using Microsoft.EntityFrameworkCore.Storage.Internal;
using Microsoft.EntityFrameworkCore.TestUtilities;
using Microsoft.EntityFrameworkCore.Update;
using Microsoft.EntityFrameworkCore.Update.Internal;
using Microsoft.EntityFrameworkCore.ValueGeneration.Internal;
using Microsoft.Extensions.DependencyInjection;
using Xunit;
// ReSharper disable InconsistentNaming
namespace Microsoft.EntityFrameworkCore
{
public class SqlServerSequenceValueGeneratorTest
{
[Theory]
[InlineData(false)]
[InlineData(true)]
public async Task Generates_sequential_int_values(bool async) => await Generates_sequential_values<int>(async);
[Theory]
[InlineData(false)]
[InlineData(true)]
public async Task Generates_sequential_long_values(bool async) => await Generates_sequential_values<long>(async);
[Theory]
[InlineData(false)]
[InlineData(true)]
public async Task Generates_sequential_short_values(bool async) => await Generates_sequential_values<short>(async);
[Theory]
[InlineData(false)]
[InlineData(true)]
public async Task Generates_sequential_byte_values(bool async) => await Generates_sequential_values<byte>(async);
[Theory]
[InlineData(false)]
[InlineData(true)]
public async Task Generates_sequential_uint_values(bool async) => await Generates_sequential_values<uint>(async);
[Theory]
[InlineData(false)]
[InlineData(true)]
public async Task Generates_sequential_ulong_values(bool async) => await Generates_sequential_values<ulong>(async);
[Theory]
[InlineData(false)]
[InlineData(true)]
public async Task Generates_sequential_ushort_values(bool async) => await Generates_sequential_values<ushort>(async);
[Theory]
[InlineData(false)]
[InlineData(true)]
public async Task Generates_sequential_sbyte_values(bool async) => await Generates_sequential_values<sbyte>(async);
public async Task Generates_sequential_values<TValue>(bool async)
{
const int blockSize = 4;
var sequence = new Model().SqlServer().GetOrAddSequence("Foo");
sequence.IncrementBy = blockSize;
var state = new SqlServerSequenceValueGeneratorState(sequence);
var generator = new SqlServerSequenceHiLoValueGenerator<TValue>(
new FakeRawSqlCommandBuilder(blockSize),
new SqlServerUpdateSqlGenerator(
new UpdateSqlGeneratorDependencies(
new SqlServerSqlGenerationHelper(
new RelationalSqlGenerationHelperDependencies()),
new SqlServerTypeMapper(
new RelationalTypeMapperDependencies()))),
state,
CreateConnection());
for (var i = 1; i <= 27; i++)
{
var value = async
? await generator.NextAsync(null)
: generator.Next(null);
Assert.Equal(i, (int)Convert.ChangeType(value, typeof(int), CultureInfo.InvariantCulture));
}
}
[Fact]
public async Task Multiple_threads_can_use_the_same_generator_state()
{
const int threadCount = 50;
const int valueCount = 35;
var generatedValues = await GenerateValuesInMultipleThreads(threadCount, valueCount);
// Check that each value was generated once and only once
var checks = new bool[threadCount * valueCount];
foreach (var values in generatedValues)
{
Assert.Equal(valueCount, values.Count);
foreach (var value in values)
{
checks[value - 1] = true;
}
}
Assert.True(checks.All(c => c));
}
private async Task<IEnumerable<List<long>>> GenerateValuesInMultipleThreads(int threadCount, int valueCount)
{
const int blockSize = 10;
var serviceProvider = SqlServerTestHelpers.Instance.CreateServiceProvider();
var sequence = new Model().SqlServer().GetOrAddSequence("Foo");
sequence.IncrementBy = blockSize;
var state = new SqlServerSequenceValueGeneratorState(sequence);
var executor = new FakeRawSqlCommandBuilder(blockSize);
var sqlGenerator = new SqlServerUpdateSqlGenerator(
new UpdateSqlGeneratorDependencies(
new SqlServerSqlGenerationHelper(
new RelationalSqlGenerationHelperDependencies()),
new SqlServerTypeMapper(
new RelationalTypeMapperDependencies())));
var tests = new Func<Task>[threadCount];
var generatedValues = new List<long>[threadCount];
for (var i = 0; i < tests.Length; i++)
{
var testNumber = i;
generatedValues[testNumber] = new List<long>();
tests[testNumber] = async () =>
{
for (var j = 0; j < valueCount; j++)
{
var connection = CreateConnection(serviceProvider);
var generator = new SqlServerSequenceHiLoValueGenerator<long>(executor, sqlGenerator, state, connection);
var value = j % 2 == 0
? await generator.NextAsync(null)
: generator.Next(null);
generatedValues[testNumber].Add(value);
}
};
}
var tasks = tests.Select(Task.Run).ToArray();
foreach (var t in tasks)
{
await t;
}
return generatedValues;
}
[Fact]
public void Does_not_generate_temp_values()
{
var sequence = new Model().SqlServer().GetOrAddSequence("Foo");
sequence.IncrementBy = 4;
var state = new SqlServerSequenceValueGeneratorState(sequence);
var generator = new SqlServerSequenceHiLoValueGenerator<int>(
new FakeRawSqlCommandBuilder(4),
new SqlServerUpdateSqlGenerator(
new UpdateSqlGeneratorDependencies(
new SqlServerSqlGenerationHelper(
new RelationalSqlGenerationHelperDependencies()),
new SqlServerTypeMapper(
new RelationalTypeMapperDependencies()))),
state,
CreateConnection());
Assert.False(generator.GeneratesTemporaryValues);
}
private static ISqlServerConnection CreateConnection(IServiceProvider serviceProvider = null)
{
serviceProvider = serviceProvider ?? SqlServerTestHelpers.Instance.CreateServiceProvider();
return SqlServerTestHelpers.Instance.CreateContextServices(serviceProvider).GetRequiredService<ISqlServerConnection>();
}
private class FakeRawSqlCommandBuilder : IRawSqlCommandBuilder
{
private readonly int _blockSize;
private long _current;
public FakeRawSqlCommandBuilder(int blockSize)
{
_blockSize = blockSize;
_current = -blockSize + 1;
}
public IRelationalCommand Build(string sql) => new FakeRelationalCommand(this);
public RawSqlCommand Build(string sql, IEnumerable<object> parameters)
=> new RawSqlCommand(
new FakeRelationalCommand(this),
new Dictionary<string, object>());
private class FakeRelationalCommand : IRelationalCommand
{
private readonly FakeRawSqlCommandBuilder _commandBuilder;
public FakeRelationalCommand(FakeRawSqlCommandBuilder commandBuilder)
{
_commandBuilder = commandBuilder;
}
public string CommandText
{
get { throw new NotImplementedException(); }
}
public IReadOnlyList<IRelationalParameter> Parameters
{
get { throw new NotImplementedException(); }
}
public IReadOnlyDictionary<string, object> ParameterValues
{
get { throw new NotImplementedException(); }
}
public int ExecuteNonQuery(IRelationalConnection connection, IReadOnlyDictionary<string, object> parameterValues)
{
throw new NotImplementedException();
}
public Task<int> ExecuteNonQueryAsync(IRelationalConnection connection, IReadOnlyDictionary<string, object> parameterValues, CancellationToken cancellationToken = default(CancellationToken))
{
throw new NotImplementedException();
}
public object ExecuteScalar(IRelationalConnection connection, IReadOnlyDictionary<string, object> parameterValues)
=> Interlocked.Add(ref _commandBuilder._current, _commandBuilder._blockSize);
public Task<object> ExecuteScalarAsync(IRelationalConnection connection, IReadOnlyDictionary<string, object> parameterValues, CancellationToken cancellationToken = default(CancellationToken))
=> Task.FromResult<object>(Interlocked.Add(ref _commandBuilder._current, _commandBuilder._blockSize));
public RelationalDataReader ExecuteReader(IRelationalConnection connection, IReadOnlyDictionary<string, object> parameterValues)
{
throw new NotImplementedException();
}
public Task<RelationalDataReader> ExecuteReaderAsync(IRelationalConnection connection, IReadOnlyDictionary<string, object> parameterValues, CancellationToken cancellationToken = default(CancellationToken))
{
throw new NotImplementedException();
}
}
}
}
}
| 40.849057 | 221 | 0.60933 |
[
"Apache-2.0"
] |
h0wXD/EntityFrameworkCore
|
test/EFCore.SqlServer.Tests/SqlServerSequenceValueGeneratorTest.cs
| 10,825 |
C#
|
using System;
using System.Linq;
using Microsoft.Maui.Controls.CustomAttributes;
using Microsoft.Maui.Controls.Internals;
#if UITEST
using Xamarin.UITest;
using NUnit.Framework;
using Microsoft.Maui.Controls.Compatibility.UITests;
#endif
namespace Microsoft.Maui.Controls.Compatibility.ControlGallery.Issues
{
#if UITEST
[Category(UITestCategories.ListView)]
[NUnit.Framework.Category(Compatibility.UITests.UITestCategories.Bugzilla)]
#endif
[Preserve(AllMembers = true)]
[Issue(IssueTracker.Bugzilla, 39668, "Overriding ListView.CreateDefault Does Not Work on Windows", PlatformAffected.WinRT)]
public class Bugzilla39668 : TestContentPage
{
[Preserve(AllMembers = true)]
public class CustomListView : ListView
{
protected override Cell CreateDefault(object item)
{
var cell = new ViewCell();
cell.View = new StackLayout
{
BackgroundColor = Color.Green,
Children = {
new Label { Text = "Success" }
}
};
return cell;
}
}
protected override void Init()
{
CustomListView lv = new CustomListView()
{
ItemsSource = Enumerable.Range(0, 10)
};
Content = new StackLayout { Children = { new Label { Text = "If the ListView does not have green Cells, this test has failed." }, lv } };
}
#if UITEST
[Test]
public void Bugzilla39668Test ()
{
RunningApp.WaitForElement (q => q.Marked ("Success"));
}
#endif
}
}
| 23.79661 | 140 | 0.712963 |
[
"MIT"
] |
Eilon/maui
|
src/Compatibility/ControlGallery/src/Issues.Shared/Bugzilla39668.cs
| 1,406 |
C#
|
using BusterWood.Linq;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace BusterWood.Goodies
{
public static class TextExtensions
{
public static bool IsLetter(this char c) => char.IsLetter(c);
public static bool IsWhiteSpace(this char c) => char.IsWhiteSpace(c);
public static bool IsUpper(this char c) => char.IsUpper(c);
public static bool IsLower(this char c) => char.IsLower(c);
public static char ToUpper(this char c) => char.ToUpper(c);
public static char ToLower(this char c) => char.ToLower(c);
public static IEnumerable<char> ToUpper(this IEnumerable<char> chars) => chars.Select(c => c.ToUpper());
public static IEnumerable<char> ToLower(this IEnumerable<char> chars) => chars.Select(c => c.ToLower());
/// <summary>Turns a sequence of characters into a string</summary>
public static string String(this IEnumerable<char> items) => items is string ? (string)items : new string(items.ToArray());
/// <summary>Turns a sequence of objects into a string with a <paramref name="separator"/> between each</summary>
public static string String(this IEnumerable items, string separator = " ") => string.Join(separator, items.Cast<object>().Select(i => i?.ToString()));
/// <summary>Turns a sequence of strings into a big string with a <paramref name="separator"/> between each</summary>
public static string String(this IEnumerable<string> items, string separator = " ") => string.Join(separator, items);
/// <summary>Separate "TitleCase" text into "Title Case"</summary>
public static string ToWords(this string text) => text?.SplitOn(c => char.IsUpper(c)).Select(String).String();
/// <summary>Formats "title case" text into "TitleCase"</summary>
public static string ToTitleCase(this string text) => text
.SplitOn(c => !c.IsLetter())
.Select(word => word.First().ToUpper().Concat(word.Rest().ToLower()).String())
.String("");
public static StringBuilder ToBuilder(this string text) => new StringBuilder(text);
public static StringBuilder ToBuilder(this IEnumerable items, string separator = null) => new StringBuilder().Append(separator, items);
public static StringBuilder Append(this StringBuilder sb, string separator, params object[] items) => Append(sb, separator, ((IEnumerable)items));
public static StringBuilder Append(this StringBuilder sb, string separator, IEnumerable items)
{
var startLen = sb.Length;
foreach (var i in items)
sb.Append(i).Append(separator);
if (sb.Length > startLen)
sb.Length -= separator.Length; // remove last separator
return sb;
}
}
}
| 52.109091 | 159 | 0.664689 |
[
"Apache-2.0"
] |
SammyEnigma/Goodies
|
Goodies/Goodies/TextExtensions.cs
| 2,868 |
C#
|
using APM.WebApi.Models;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.Hosting;
namespace APM.WebAPI.Models
{
/// <summary>
/// Stores the data in a json file so that no database is required for this
/// sample application
/// </summary>
public class ProductRepository
{
/// <summary>
/// Creates a new product with default values
/// </summary>
/// <returns></returns>
internal Product Create()
{
Product product = new Product
{
ReleaseDate = DateTime.Now
};
return product;
}
/// <summary>
/// Retrieves the list of products.
/// </summary>
/// <returns></returns>
internal List<Product> Retrieve()
{
var filePath = HostingEnvironment.MapPath(@"~/App_Data/product.json");
var json = System.IO.File.ReadAllText(filePath);
var products = JsonConvert.DeserializeObject<List<Product>>(json);
return products;
}
/// <summary>
/// Saves a new product.
/// </summary>
/// <param name="product"></param>
/// <returns></returns>
internal Product Save(Product product)
{
// Read in the existing products
var products = this.Retrieve();
// Assign a new Id
var maxId = products.Max(p => p.ProductId);
product.ProductId = maxId + 1;
products.Add(product);
WriteData(products);
return product;
}
/// <summary>
/// Updates an existing product
/// </summary>
/// <param name="id"></param>
/// <param name="product"></param>
/// <returns></returns>
internal Product Save(int id, Product product)
{
// Read in the existing products
var products = this.Retrieve();
// Locate and replace the item
var itemIndex = products.FindIndex(p => p.ProductId == product.ProductId);
if (itemIndex > 0)
{
products[itemIndex] = product;
}
else
{
return null;
}
WriteData(products);
return product;
}
private bool WriteData(List<Product> products)
{
// Write out the Json
var filePath = HostingEnvironment.MapPath(@"~/App_Data/product.json");
var json = JsonConvert.SerializeObject(products, Formatting.Indented);
System.IO.File.WriteAllText(filePath, json);
return true;
}
}
}
| 27.127451 | 86 | 0.522588 |
[
"MIT"
] |
supercoja/angularJS-Sandbox
|
APM/APM.WebApi/Models/ProductRepository.cs
| 2,769 |
C#
|
using Nfantom.JsonRpc.Client;
using Nfantom.RPC.Infrastructure;
namespace Nfantom.RPC.Net
{
/// <Summary>
/// net_version
/// Returns the current network protocol version.
/// Parameters
/// none
/// Returns
/// String - The current network protocol version
/// Example
/// Request
/// curl -X POST --data '{"jsonrpc":"2.0","method":"net_version","params":[],"id":67}'
/// Result
/// {
/// "id":67,
/// "jsonrpc": "2.0",
/// "result": "59"
/// }
/// </Summary>
public class NetVersion : GenericRpcRequestResponseHandlerNoParam<string>, INetVersion
{
public NetVersion(IClient client) : base(client, ApiMethods.net_version.ToString())
{
}
}
}
| 27.793103 | 94 | 0.538462 |
[
"MIT"
] |
PeaStew/Nfantom
|
Nfantom.RPC/Net/NetVersion.cs
| 806 |
C#
|
using System.Web.Mvc;
using Alloy.Sample.Models.Media;
using Alloy.Sample.Models.ViewModels;
using EPiServer.Web.Mvc;
using EPiServer.Web.Routing;
using System;
using EPiServer.Core;
namespace Alloy.Sample.Controllers
{
/// <summary>
/// Controller for the video file.
/// </summary>
public class VideoFileController : PartialContentController<VideoFile>
{
private readonly UrlResolver _urlResolver;
public VideoFileController(UrlResolver urlResolver)
{
_urlResolver = urlResolver;
}
/// <summary>
/// The index action for the video file. Creates the view model and renders the view.
/// </summary>
/// <param name="currentContent">The current video file.</param>
public override ActionResult Index(VideoFile currentContent)
{
var model = new VideoViewModel
{
Url = _urlResolver.GetUrl(currentContent.ContentLink),
PreviewImageUrl = ContentReference.IsNullOrEmpty(currentContent.PreviewImage) ? String.Empty : _urlResolver.GetUrl(currentContent.PreviewImage),
};
return PartialView(model);
}
}
}
| 30.871795 | 160 | 0.654485 |
[
"Apache-2.0"
] |
advanced-cms/assets-download
|
src/Alloy.Sample/Controllers/VideoFileController.cs
| 1,204 |
C#
|
using System;
using System.Collections.Generic;
using System.Text;
namespace ItsEarth.Models
{
public class Disasters
{
public string Id { get; set; }
public string Name { get; set; }
public string Description { get; set; }
public Bag BagPattern { get; set; }
public List<string> midia { get; set; }
public string logo { get; set; }
}
}
| 23.529412 | 47 | 0.6075 |
[
"MIT"
] |
ItsEarth/ItsEarth
|
ItsEarth/ItsEarth/ItsEarth/Models/Disasters.cs
| 402 |
C#
|
using System;
using System.Runtime.Serialization;
namespace ImportOMatic3000
{
class OutputFieldException : RowException
{
private string OutputFieldName;
public OutputFieldException(string name, IRow row, string message) : base(message, row)
{
}
public OutputFieldException(string outputFieldName, IRow row, Exception ex)
: base($"Error ({row.GetSourceRow()}) writing output field {outputFieldName}: {ex.Message}", row, ex)
{
this.OutputFieldName = outputFieldName;
}
}
}
| 27.095238 | 113 | 0.653779 |
[
"MIT"
] |
rottedfrog/importomatic
|
ImportOMatic3000/OutputFieldException.cs
| 571 |
C#
|
using Microsoft.CodeAnalysis;
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Linq;
namespace NetFabric.Hyperlinq.SourceGenerator
{
static class TypeSymbolExtensions
{
public static bool IsInterface(this ITypeSymbol typeSymbol)
=> typeSymbol.TypeKind == TypeKind.Interface;
public static IEnumerable<INamedTypeSymbol> GetAllInterfaces(this ITypeSymbol typeSymbol, bool includeCurrent = true)
{
if (includeCurrent && typeSymbol.IsInterface())
yield return (INamedTypeSymbol)typeSymbol;
#pragma warning disable IDE0007 // Use implicit type
ITypeSymbol? currentTypeSymbol = typeSymbol;
#pragma warning restore IDE0007 // Use implicit type
do
{
var interfaces = currentTypeSymbol.Interfaces;
for (var index = 0; index < interfaces.Length; index++)
{
var @interface = interfaces[index];
yield return @interface;
foreach (var innerInterface in @interface.GetAllInterfaces())
yield return innerInterface;
}
currentTypeSymbol = currentTypeSymbol.BaseType;
} while (currentTypeSymbol is not null && currentTypeSymbol.SpecialType != SpecialType.System_Object);
}
public static ImmutableArray<(string, string, bool)> GetGenericsMappings(this ISymbol type, Compilation compilation)
{
var mappingAttributeSymbol = compilation.GetTypeByMetadataName("NetFabric.Hyperlinq.GeneratorMappingAttribute");
var mappings = type.GetAttributes()
.Where(attribute => SymbolEqualityComparer.Default.Equals(attribute.AttributeClass, mappingAttributeSymbol))
.Select(attribute => (
(string)attribute.ConstructorArguments[0].Value!,
(string)attribute.ConstructorArguments[1].Value!,
(bool)attribute.ConstructorArguments[2].Value!));
return ImmutableArray.CreateRange(mappings);
}
public static string ToDisplayString(this ITypeSymbol type, ImmutableArray<(string, string, bool)> genericsMapping)
=> type.ToDisplayString().ApplyMappings(genericsMapping, out _);
static IEnumerable<ITypeParameterSymbol> GetTypeArguments(ITypeSymbol typeSymbol)
{
if (typeSymbol is INamedTypeSymbol namedType && namedType.IsGenericType)
{
var typeArguments = namedType.TypeArguments;
for (var index = 0; index < typeArguments.Length; index++)
{
var typeArgument = typeArguments[index];
if (typeArgument is ITypeParameterSymbol typeParameter)
yield return typeParameter;
}
}
}
static IEnumerable<(string Name, ITypeParameterSymbol TypeParameter)> MapTypeParameters(IEnumerable<ITypeParameterSymbol> typeParameters, ImmutableArray<(string, string, bool)> genericsMapping)
{
var set = new HashSet<string>();
foreach (var typeParameter in typeParameters)
{
var (isMapped, mappedTo, _) = typeParameter.IsMapped(genericsMapping);
if (isMapped)
{
if (set.Add(mappedTo))
yield return (mappedTo, typeParameter);
}
else
{
var displayString = typeParameter.ToDisplayString();
if (set.Add(displayString))
{
yield return (displayString, typeParameter);
}
}
}
}
public static IEnumerable<(string Name, string Constraints)> MappedTypeArguments(this ITypeSymbol type, ImmutableArray<(string, string, bool)> genericsMapping)
{
var methodParameters = GetTypeArguments(type);
return MapTypeParameters(methodParameters, genericsMapping)
.Select(typeArgument => (typeArgument.Name, typeArgument.TypeParameter.AsConstraintsStrings(genericsMapping).ToCommaSeparated()));
}
static (bool, string, bool) IsMapped(this ITypeSymbol type, ImmutableArray<(string, string, bool)> genericsMapping)
{
foreach (var (from, to, isConcreteType) in genericsMapping)
{
if (type.Name == from)
return (true, to, isConcreteType);
}
return default;
}
}
}
| 42.351351 | 201 | 0.603489 |
[
"MIT"
] |
ualehosaini/NetFabric.Hyperlinq
|
NetFabric.Hyperlinq.SourceGenerator/Utils/TypeSymbolExtensions.cs
| 4,703 |
C#
|
// Copyright 1998-2015 Epic Games, Inc. All Rights Reserved.
using UnrealBuildTool;
using System.Collections.Generic;
public class DoomVRTarget : TargetRules
{
public DoomVRTarget(TargetInfo Target)
{
Type = TargetType.Game;
}
//
// TargetRules interface.
//
public override void SetupBinaries(
TargetInfo Target,
ref List<UEBuildBinaryConfiguration> OutBuildBinaryConfigurations,
ref List<string> OutExtraModuleNames
)
{
OutExtraModuleNames.Add("DoomVR");
}
}
| 18.692308 | 68 | 0.759259 |
[
"MIT"
] |
EvanJuV/DoomVR
|
Source/DoomVR.Target.cs
| 486 |
C#
|
using Guppy.DependencyInjection;
using Guppy.Events.Delegates;
using Guppy.Extensions.System.Collections;
using Guppy.Extensions.DependencyInjection;
using Guppy.Interfaces;
using Guppy.Lists;
using Guppy.Lists.Interfaces;
using Guppy.UI.Enums;
using Guppy.UI.Interfaces;
using Guppy.UI.Lists;
using Guppy.UI.Utilities;
using Guppy.UI.Utilities.Units;
using Microsoft.Xna.Framework;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Guppy.UI.Elements
{
public class Container<TChildren> : Element, IContainer<TChildren>
where TChildren : class, IElement
{
#region Public Properties
public ElementList<TChildren> Children { get; private set; }
public InlineType Inline { get; set; }
#endregion
#region Events
private event OnEventDelegate<IElement, GameTime> OnUpdateChild;
#endregion
#region Lifecycle Methods
protected override void Create(ServiceProvider provider)
{
base.Create(provider);
this.OnBoundsCleaned += this.HandleBoundsCleaned;
}
protected override void PreInitialize(ServiceProvider provider)
{
base.PreInitialize(provider);
// Create & setup a new children list.
this.Children = provider.GetService<ElementList<TChildren>>();
this.Children.OnAdded += this.HandleChildAdded;
this.Children.OnRemoved += this.HandleChildRemoved;
this.Children.OnCreated += this.HandleChildCreated;
this.OnUpdateChild += this.UpdateChild;
this.OnState[ElementState.Hovered] += this.HandleHoveredStateChanged;
}
protected override void PostInitialize(ServiceProvider provider)
{
base.PostInitialize(provider);
}
protected override void Release()
{
base.Release();
// Release all internal children.
while (this.Children.Any())
this.Children.First().TryRelease();
this.Children.OnAdded -= this.HandleChildAdded;
this.Children.OnRemoved -= this.HandleChildRemoved;
this.Children.OnCreated -= this.HandleChildCreated;
this.Children.TryRelease();
this.OnUpdateChild -= this.UpdateChild;
this.OnState[ElementState.Hovered] -= this.HandleHoveredStateChanged;
}
protected override void Dispose()
{
base.Dispose();
this.OnBoundsCleaned -= this.HandleBoundsCleaned;
}
#endregion
#region Frame Methods
protected override void Draw(GameTime gameTime)
{
base.Draw(gameTime);
this.GetActiveChildren().TryDrawAll(gameTime);
}
protected override void Update(GameTime gameTime)
{
base.Update(gameTime);
foreach (TChildren child in this.GetActiveChildren())
this.OnUpdateChild.Invoke(child, gameTime);
}
#endregion
#region Methods
protected override bool TryCleanInnerBounds()
{
if(base.TryCleanInnerBounds() || this.Inline != InlineType.None)
{
// Recursively clean all children.
foreach (TChildren child in this.GetActiveChildren())
child.TryCleanBounds();
return true;
}
return false;
}
/// <inheritdoc />
Rectangle IContainer.GetInnerBoundsForChildren()
=> this.GetInnerBoundsForChildren();
/// <summary>
/// Retrieve the bounds to pass into the current containers
/// children when recalculating child bounds.
/// </summary>
/// <returns></returns>
protected virtual Rectangle GetInnerBoundsForChildren()
{
if(this.Inline != 0)
{ // Calculate bounds based on padding...
var container = this.Container?.GetInnerBoundsForChildren() ?? new Rectangle();
var width = ((this.Inline & InlineType.Horizontal) == 0) ? this.InnerBounds.Width : container.Width - this.Padding.Left.ToPixel(container.Width) - this.Padding.Right.ToPixel(container.Width);
var height = ((this.Inline & InlineType.Vertical) == 0) ? this.InnerBounds.Width : container.Height - this.Padding.Top.ToPixel(container.Height) - this.Padding.Bottom.ToPixel(container.Height);
return new Rectangle(
x: this.InnerBounds.X,
y: this.InnerBounds.Y,
width: width,
height: height);
}
else
{
return this.InnerBounds;
}
}
/// <summary>
/// If <see cref="Inline"/> is true, this will resize the
/// current element based on the size of the contained
/// children.
/// </summary>
protected void TryCleanInline()
{
if ((this.Inline & InlineType.Vertical) != 0 && this.Children.Any())
this.Bounds.Height = new PixelUnit(this.Children.Max(c => c.OuterBounds.Bottom) - this.Children.Min(c => c.OuterBounds.Top), this.Padding.Top, this.Padding.Bottom);
if((this.Inline & InlineType.Horizontal) != 0 && this.Children.Any())
this.Bounds.Width = new PixelUnit(this.Children.Max(c => c.OuterBounds.Right) - this.Children.Min(c => c.OuterBounds.Left), this.Padding.Left, this.Padding.Right);
}
/// <summary>
/// Return an IEnumerable of <see cref="TChildren"/> that are currently
/// active. This is used when updating, drawing, or resizing embedded children.
/// </summary>
/// <returns></returns>
protected virtual IEnumerable<TChildren> GetActiveChildren()
=> this.Children;
/// <inheritdoc />
protected override void Refresh()
{
base.Refresh();
this.Children.ForEach(c => c.Refresh());
this.TryCleanInline();
}
#endregion
#region Child Update Methods
private void UpdateChild(IElement sender, GameTime arg)
=> sender.TryUpdate(arg);
private void TryCleanChildHovered(IElement sender, GameTime arg)
=> sender.TryCleanHovered();
#endregion
#region Event Handlers
private void HandleChildCreated(TChildren child)
{
child.Container = this;
}
private void HandleChildAdded(IServiceList<TChildren> sender, TChildren child)
{
if (child.Container != null && child.Container != this)
throw new Exception($"Unable to add child, already resides within another container.");
child.Container = this;
child.TryCleanBounds();
child.Bounds.OnChanged += this.HandleChildBoundsChanged;
this.TryCleanInline();
}
private void HandleChildRemoved(IServiceList<TChildren> sender, TChildren child)
{
child.Container = null;
child.Bounds.OnChanged -= this.HandleChildBoundsChanged;
this.TryCleanInline();
}
private void HandleChildBoundsChanged(IElement child, Bounds bounds)
{
child.TryCleanBounds();
this.TryCleanInline();
}
private void HandleHoveredStateChanged(IElement sender, ElementState which, bool value)
{
if (value)
this.OnUpdateChild += this.TryCleanChildHovered;
else
{
// Update all children hovered states one last time.
foreach (TChildren child in this.Children)
child.TryCleanHovered();
this.OnUpdateChild -= this.TryCleanChildHovered;
}
}
/// <summary>
/// Primary event to resize the element when size is inline.
/// </summary>
/// <param name="sender"></param>
private void HandleBoundsCleaned(Element sender)
=> this.TryCleanInline();
#endregion
}
public class Container : Container<IElement>
{
}
}
| 33.857143 | 209 | 0.596022 |
[
"MIT"
] |
rettoph/Guppy
|
src/Guppy.UI/Elements/Container.cs
| 8,297 |
C#
|
// Copyright (c) Microsoft Open Technologies, Inc. All rights reserved. See License.txt in the project root for license information.
using System.Collections.Generic;
using System.Linq;
using System.Web.OData.Builder;
using System.Web.OData.Builder.TestModels;
using System.Web.OData.Query.Validators;
using System.Web.OData.TestCommon;
using Microsoft.OData.Core;
using Microsoft.OData.Core.UriParser;
using Microsoft.OData.Edm;
using Microsoft.OData.Edm.Library;
using Microsoft.TestCommon;
using Moq;
namespace System.Web.OData.Query
{
public class OrderByQueryOptionTest
{
[Fact]
public void ConstructorNullContextThrows()
{
Assert.Throws<ArgumentNullException>(() =>
new OrderByQueryOption("Name", null));
}
[Fact]
public void ConstructorNullRawValueThrows()
{
// Arrange
var model = new ODataModelBuilder().Add_Customer_EntityType().Add_Customers_EntitySet().GetEdmModel();
// Act & Assert
Assert.Throws<ArgumentException>(() =>
new OrderByQueryOption(null, new ODataQueryContext(model, typeof(Customer))));
}
[Fact]
public void ConstructorEmptyRawValueThrows()
{
// Arrange
var model = new ODataModelBuilder().Add_Customer_EntityType().Add_Customers_EntitySet().GetEdmModel();
// Act & Assert
Assert.Throws<ArgumentException>(() =>
new OrderByQueryOption(string.Empty, new ODataQueryContext(model, typeof(Customer))));
}
[Fact]
public void ConstructorNullQueryOptionParserThrows()
{
// Arrange
var model = new ODataModelBuilder().Add_Customer_EntityType().Add_Customers_EntitySet().GetEdmModel();
// Act & Assert
Assert.ThrowsArgumentNull(() =>
new OrderByQueryOption("test", new ODataQueryContext(model, typeof(Customer)), queryOptionParser: null),
"queryOptionParser");
}
[Theory]
[InlineData("Name")]
[InlineData("''")]
public void CanConstructValidFilterQuery(string orderbyValue)
{
var model = new ODataModelBuilder().Add_Customer_EntityType().Add_Customers_EntitySet().GetEdmModel();
var context = new ODataQueryContext(model, typeof(Customer));
var orderby = new OrderByQueryOption(orderbyValue, context);
Assert.Same(context, orderby.Context);
Assert.Equal(orderbyValue, orderby.RawValue);
}
[Fact]
public void PropertyNodes_Getter_Parses_Query()
{
// Arrange
var model = new ODataModelBuilder().Add_Customer_EntityType().Add_Customers_EntitySet().GetEdmModel();
var context = new ODataQueryContext(model, typeof(Customer));
var orderby = new OrderByQueryOption("Name,Website", context);
ICollection<OrderByNode> nodes = orderby.OrderByNodes;
// Assert
Assert.False(nodes.OfType<OrderByItNode>().Any());
IEnumerable<OrderByPropertyNode> propertyNodes = nodes.OfType<OrderByPropertyNode>();
Assert.NotNull(propertyNodes);
Assert.Equal(2, propertyNodes.Count());
Assert.Equal("Name", propertyNodes.First().Property.Name);
Assert.Equal("Website", propertyNodes.Last().Property.Name);
}
[Theory]
[InlineData("BadPropertyName")]
[InlineData("''")]
[InlineData(" ")]
[InlineData("customerid")]
[InlineData("CustomerId,CustomerId")]
[InlineData("CustomerId,Name,CustomerId")]
public void ApplyInValidOrderbyQueryThrows(string orderbyValue)
{
var model = new ODataModelBuilder().Add_Customer_EntityType().Add_Customers_EntitySet().GetEdmModel();
var context = new ODataQueryContext(model, typeof(Customer));
var orderby = new OrderByQueryOption(orderbyValue, context);
Assert.Throws<ODataException>(() =>
orderby.ApplyTo(ODataQueryOptionTest.Customers));
}
[Fact]
[Trait("Description", "Can apply an orderby")]
public void CanApplyOrderBy()
{
var model = new ODataModelBuilder().Add_Customer_EntityType().Add_Customers_EntitySet().GetServiceModel();
var orderByOption = new OrderByQueryOption("Name", new ODataQueryContext(model, typeof(Customer)));
var customers = (new List<Customer>{
new Customer { CustomerId = 1, Name = "Andy" },
new Customer { CustomerId = 2, Name = "Aaron" },
new Customer { CustomerId = 3, Name = "Alex" }
}).AsQueryable();
var results = orderByOption.ApplyTo(customers).ToArray();
Assert.Equal(2, results[0].CustomerId);
Assert.Equal(3, results[1].CustomerId);
Assert.Equal(1, results[2].CustomerId);
}
[Fact]
[Trait("Description", "Can apply an orderby")]
public void CanApplyOrderByAsc()
{
var model = new ODataModelBuilder().Add_Customer_EntityType().Add_Customers_EntitySet().GetServiceModel();
var orderByOption = new OrderByQueryOption("Name asc", new ODataQueryContext(model, typeof(Customer)));
var customers = (new List<Customer>{
new Customer { CustomerId = 1, Name = "Andy" },
new Customer { CustomerId = 2, Name = "Aaron" },
new Customer { CustomerId = 3, Name = "Alex" }
}).AsQueryable();
var results = orderByOption.ApplyTo(customers).ToArray();
Assert.Equal(2, results[0].CustomerId);
Assert.Equal(3, results[1].CustomerId);
Assert.Equal(1, results[2].CustomerId);
}
[Fact]
[Trait("Description", "Can apply an orderby descending")]
public void CanApplyOrderByDescending()
{
var model = new ODataModelBuilder().Add_Customer_EntityType().Add_Customers_EntitySet().GetServiceModel();
var orderByOption = new OrderByQueryOption("Name desc", new ODataQueryContext(model, typeof(Customer)));
var customers = (new List<Customer>{
new Customer { CustomerId = 1, Name = "Andy" },
new Customer { CustomerId = 2, Name = "Aaron" },
new Customer { CustomerId = 3, Name = "Alex" }
}).AsQueryable();
var results = orderByOption.ApplyTo(customers).ToArray();
Assert.Equal(1, results[0].CustomerId);
Assert.Equal(3, results[1].CustomerId);
Assert.Equal(2, results[2].CustomerId);
}
[Fact]
[Trait("Description", "Can apply a compound orderby")]
public void CanApplyOrderByThenBy()
{
var model = new ODataModelBuilder().Add_Customer_EntityType().Add_Customers_EntitySet().GetServiceModel();
var orderByOption = new OrderByQueryOption("Name,Website", new ODataQueryContext(model, typeof(Customer)));
var customers = (new List<Customer>{
new Customer { CustomerId = 1, Name = "ACME", Website = "http://www.acme.net" },
new Customer { CustomerId = 2, Name = "AAAA", Website = "http://www.aaaa.com" },
new Customer { CustomerId = 3, Name = "ACME", Website = "http://www.acme.com" }
}).AsQueryable();
var results = orderByOption.ApplyTo(customers).ToArray();
Assert.Equal(2, results[0].CustomerId);
Assert.Equal(3, results[1].CustomerId);
Assert.Equal(1, results[2].CustomerId);
}
[Fact]
[Trait("Description", "Can apply a OrderByDescending followed by ThenBy")]
public void CanApplyOrderByDescThenBy()
{
var model = new ODataModelBuilder().Add_Customer_EntityType().Add_Customers_EntitySet().GetServiceModel();
var orderByOption = new OrderByQueryOption("Name desc,Website", new ODataQueryContext(model, typeof(Customer)));
var customers = (new List<Customer>{
new Customer { CustomerId = 1, Name = "ACME", Website = "http://www.acme.net" },
new Customer { CustomerId = 2, Name = "AAAA", Website = "http://www.aaaa.com" },
new Customer { CustomerId = 3, Name = "ACME", Website = "http://www.acme.com" }
}).AsQueryable();
var results = orderByOption.ApplyTo(customers).ToArray();
Assert.Equal(3, results[0].CustomerId);
Assert.Equal(1, results[1].CustomerId);
Assert.Equal(2, results[2].CustomerId);
}
[Fact]
[Trait("Description", "Can apply a OrderByDescending followed by ThenBy")]
public void CanApplyOrderByDescThenByDesc()
{
var model = new ODataModelBuilder().Add_Customer_EntityType().Add_Customers_EntitySet().GetServiceModel();
var orderByOption = new OrderByQueryOption("Name desc,Website desc", new ODataQueryContext(model, typeof(Customer)));
var customers = (new List<Customer>{
new Customer { CustomerId = 1, Name = "ACME", Website = "http://www.acme.net" },
new Customer { CustomerId = 2, Name = "AAAA", Website = "http://www.aaaa.com" },
new Customer { CustomerId = 3, Name = "ACME", Website = "http://www.acme.com" }
}).AsQueryable();
var results = orderByOption.ApplyTo(customers).ToArray();
Assert.Equal(1, results[0].CustomerId);
Assert.Equal(3, results[1].CustomerId);
Assert.Equal(2, results[2].CustomerId);
}
[Fact]
public void ApplyToEnums_ReturnsCorrectQueryable()
{
// Arrange
var builder = new ODataConventionModelBuilder();
builder.EntitySet<EnumModel>("EnumModels");
var model = builder.GetEdmModel();
var context = new ODataQueryContext(model, typeof(EnumModel));
var orderbyOption = new OrderByQueryOption("Flag", context);
IEnumerable<EnumModel> enumModels = FilterQueryOptionTest.EnumModelTestData;
// Act
IQueryable queryable = orderbyOption.ApplyTo(enumModels.AsQueryable());
// Assert
Assert.NotNull(queryable);
IEnumerable<EnumModel> actualCustomers = Assert.IsAssignableFrom<IEnumerable<EnumModel>>(queryable);
Assert.Equal(
new int[] { 5, 2, 1, 3, 6 },
actualCustomers.Select(enumModel => enumModel.Id));
}
[Theory]
[InlineData(true, "FirstNameAlias")]
[InlineData(false, "FirstName")]
public void ApplyTo_PropertyAliased_IfEnabled(bool modelAliasing, string propertyName)
{
// Arrange
var builder = new ODataConventionModelBuilder { ModelAliasingEnabled = modelAliasing };
builder.EntitySet<PropertyAlias>("PropertyAliases");
var model = builder.GetEdmModel();
var context = new ODataQueryContext(model, typeof(PropertyAlias));
var orderByOption = new OrderByQueryOption(propertyName, context);
IEnumerable<PropertyAlias> propertyAliases = FilterQueryOptionTest.PropertyAliasTestData;
// Act
IQueryable queryable = orderByOption.ApplyTo(propertyAliases.AsQueryable());
// Assert
Assert.NotNull(queryable);
IEnumerable<PropertyAlias> actualCustomers = Assert.IsAssignableFrom<IEnumerable<PropertyAlias>>(queryable);
Assert.Equal(
new[] { "abc", "def", "xyz" },
actualCustomers.Select(propertyAlias => propertyAlias.FirstName));
}
[Theory]
[InlineData("SharePrice add 1")]
public void OrderBy_Throws_For_Expressions(string orderByQuery)
{
var model = new ODataModelBuilder().Add_Customer_EntityType_With_Address().Add_Customers_EntitySet().GetServiceModel();
var orderByOption = new OrderByQueryOption(orderByQuery, new ODataQueryContext(model, typeof(Customer)));
Assert.Throws<ODataException>(
() => orderByOption.OrderByNodes.Count(),
"Only ordering by properties is supported for non-primitive collections. Expressions are not supported.");
}
[Fact]
public void CanTurnOffValidationForOrderBy()
{
// Arrange
ODataQueryContext context = ValidationTestHelper.CreateCustomerContext();
OrderByQueryOption option = new OrderByQueryOption("Name", context);
ODataValidationSettings settings = new ODataValidationSettings();
settings.AllowedOrderByProperties.Add("Id");
// Act & Assert
Assert.Throws<ODataException>(() => option.Validate(settings),
"Order by 'Name' is not allowed. To allow it, set the 'AllowedOrderByProperties' property on EnableQueryAttribute or QueryValidationSettings.");
option.Validator = null;
Assert.DoesNotThrow(() => option.Validate(settings));
}
[Fact]
public void OrderByDuplicatePropertyThrows()
{
// Arrange
var model = new ODataModelBuilder().Add_Customer_EntityType().Add_Customers_EntitySet().GetServiceModel();
var context = new ODataQueryContext(model, typeof(Customer));
var orderbyOption = new OrderByQueryOption("Name, Name", context);
// Act
Assert.Throws<ODataException>(
() => orderbyOption.ApplyTo(Enumerable.Empty<Customer>().AsQueryable()),
"Duplicate property named 'Name' is not supported in '$orderby'.");
}
[Fact]
public void OrderByDuplicateItThrows()
{
// Arrange
var context = new ODataQueryContext(EdmCoreModel.Instance, typeof(int));
var orderbyOption = new OrderByQueryOption("$it, $it", context);
// Act
Assert.Throws<ODataException>(
() => orderbyOption.ApplyTo(Enumerable.Empty<int>().AsQueryable()),
"Multiple '$it' nodes are not supported in '$orderby'.");
}
[Fact]
public void ApplyTo_NestedProperties_Succeeds()
{
// Arrange
var model = new ODataModelBuilder().Add_Customer_EntityType_With_Address().Add_Customers_EntitySet().GetServiceModel();
var orderByOption = new OrderByQueryOption("Address/City asc", new ODataQueryContext(model, typeof(Customer)));
var customers = (new List<Customer>{
new Customer { CustomerId = 1, Address = new Address { City = "C" } },
new Customer { CustomerId = 2, Address = new Address { City = "B" } },
new Customer { CustomerId = 3, Address = new Address { City = "A" } }
}).AsQueryable();
// Act
var results = orderByOption.ApplyTo(customers).ToArray();
// Assert
Assert.Equal(3, results[0].CustomerId);
Assert.Equal(2, results[1].CustomerId);
Assert.Equal(1, results[2].CustomerId);
}
[Fact]
public void ApplyTo_NestedProperties_HandlesNullPropagation_Succeeds()
{
// Arrange
var model = new ODataModelBuilder().Add_Customer_EntityType_With_Address().Add_Customers_EntitySet().GetServiceModel();
var orderByOption = new OrderByQueryOption("Address/City asc", new ODataQueryContext(model, typeof(Customer)));
var customers = (new List<Customer>{
new Customer { CustomerId = 1, Address = null },
new Customer { CustomerId = 2, Address = new Address { City = "B" } },
new Customer { CustomerId = 3, Address = new Address { City = "A" } }
}).AsQueryable();
// Act
var results = orderByOption.ApplyTo(customers).ToArray();
// Assert
Assert.Equal(1, results[0].CustomerId);
Assert.Equal(3, results[1].CustomerId);
Assert.Equal(2, results[2].CustomerId);
}
[Fact]
public void ApplyTo_NestedProperties_DoesNotHandleNullPropagation_IfExplicitInSettings()
{
// Arrange
var model = new ODataModelBuilder().Add_Customer_EntityType_With_Address().Add_Customers_EntitySet().GetServiceModel();
var orderByOption = new OrderByQueryOption("Address/City asc", new ODataQueryContext(model, typeof(Customer)));
var customers = (new List<Customer>{
new Customer { CustomerId = 1, Address = null },
new Customer { CustomerId = 2, Address = new Address { City = "B" } },
new Customer { CustomerId = 3, Address = new Address { City = "A" } }
}).AsQueryable();
ODataQuerySettings settings = new ODataQuerySettings { HandleNullPropagation = HandleNullPropagationOption.False };
// Act & Assert
Assert.Throws<NullReferenceException>(() => orderByOption.ApplyTo(customers, settings).ToArray());
}
[Fact]
public void Property_OrderByNodes_WorksWithUnTypedContext()
{
// Arrange
CustomersModelWithInheritance model = new CustomersModelWithInheritance();
ODataQueryContext context = new ODataQueryContext(model.Model, model.Customer);
OrderByQueryOption orderBy = new OrderByQueryOption("ID desc", context);
// Act & Assert
Assert.NotNull(orderBy.OrderByNodes);
}
[Fact]
public void ApplyTo_WithUnTypedContext_Throws_InvalidOperation()
{
// Arrange
CustomersModelWithInheritance model = new CustomersModelWithInheritance();
ODataQueryContext context = new ODataQueryContext(model.Model, model.Customer);
OrderByQueryOption orderBy = new OrderByQueryOption("ID desc", context);
IQueryable queryable = new Mock<IQueryable>().Object;
// Act & Assert
Assert.Throws<NotSupportedException>(() => orderBy.ApplyTo(queryable),
"The query option is not bound to any CLR type. 'ApplyTo' is only supported with a query option bound to a CLR type.");
}
[Fact]
public void CanApplyOrderBy_WithParameterAlias()
{
// Arrange
var model = new ODataModelBuilder().Add_Customer_EntityType_With_Address().Add_Address_ComplexType().GetServiceModel();
var parser = new ODataQueryOptionParser(
model,
model.FindType("System.Web.OData.Builder.TestModels.Customer"),
model.FindDeclaredNavigationSource("Default.Container.Customers"),
new Dictionary<string, string> { { "$orderby", "@q desc,@p asc" }, { "@q", "Address/HouseNumber" }, { "@p", "CustomerId" } });
var orderByOption = new OrderByQueryOption("@q desc,@p asc", new ODataQueryContext(model, typeof(Customer)), parser);
var customers = (new List<Customer>{
new Customer { CustomerId = 1, Address = new Address{HouseNumber = 2}},
new Customer { CustomerId = 2, Address = new Address{HouseNumber = 1}},
new Customer { CustomerId = 3, Address = new Address{HouseNumber = 3}},
new Customer { CustomerId = 4, Address = new Address{HouseNumber = 2}},
new Customer { CustomerId = 5, Address = new Address{HouseNumber = 1}},
}).AsQueryable();
// Act
var results = orderByOption.ApplyTo(customers).ToArray();
// Assert
Assert.Equal(3, results[0].CustomerId);
Assert.Equal(1, results[1].CustomerId);
Assert.Equal(4, results[2].CustomerId);
Assert.Equal(2, results[3].CustomerId);
Assert.Equal(5, results[4].CustomerId);
}
[Fact]
public void CanApplyOrderBy_WithNestedParameterAlias()
{
// Arrange
var model = new ODataModelBuilder().Add_Customer_EntityType().Add_Customers_EntitySet().GetServiceModel();
var parser = new ODataQueryOptionParser(
model,
model.FindType("System.Web.OData.Builder.TestModels.Customer"),
model.FindDeclaredNavigationSource("Default.Container.Customers"),
new Dictionary<string, string> { { "$orderby", "@p1" }, { "@p2", "Name" }, { "@p1", "@p2" } });
var orderByOption = new OrderByQueryOption("@p1", new ODataQueryContext(model, typeof(Customer)), parser);
var customers = (new List<Customer>{
new Customer { CustomerId = 1, Name = "Andy" },
new Customer { CustomerId = 2, Name = "Aaron" },
new Customer { CustomerId = 3, Name = "Alex" }
}).AsQueryable();
// Act
var results = orderByOption.ApplyTo(customers).ToArray();
// Assert
Assert.Equal(2, results[0].CustomerId);
Assert.Equal(3, results[1].CustomerId);
Assert.Equal(1, results[2].CustomerId);
}
[Fact]
public void OrderBy_Throws_ParameterAliasNotFound()
{
// Arrange
var model = new ODataModelBuilder().Add_Customer_EntityType().Add_Customers_EntitySet().GetServiceModel();
var orderByOption = new OrderByQueryOption("@p", new ODataQueryContext(model, typeof(Customer)));
// Act & Assert
Assert.Throws<ODataException>(
() => orderByOption.OrderByNodes,
"Only ordering by properties is supported for non-primitive collections. Expressions are not supported.");
}
}
}
| 44.663968 | 160 | 0.60814 |
[
"Apache-2.0"
] |
Darth-Fx/AspNetMvcStack
|
OData/test/System.Web.OData.Test/OData/Query/OrderByQueryOptionTest.cs
| 22,066 |
C#
|
using BlogPessoal.Web.Models;
using System.Data.Entity.ModelConfiguration;
namespace BlogPessoal.Web.Data.Mapeamento
{
public class AutorMap : EntityTypeConfiguration<Autor>
{
public AutorMap()
{
ToTable("autor");
HasKey(t => t.Id);
Property(x => x.Nome).IsRequired().HasMaxLength(150).HasColumnName("nome");
Property(x => x.Email).IsOptional().HasMaxLength(150).HasColumnName("email");
Property(x => x.Senha).IsRequired().HasMaxLength(50).HasColumnName("senha");
Property(x => x.Administrador).IsRequired().HasColumnName("administrador");
Property(x => x.DataCadastro).IsRequired().HasColumnName("data_cadastro");
}
}
}
| 35.428571 | 89 | 0.634409 |
[
"MIT"
] |
fgarcia-fg/asp.net-mvc-blog-pessoal-2
|
BlogPessoal/BlogPessoal.Web/Data/Mapeamento/AutorMap.cs
| 746 |
C#
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.